Update OOUI to v0.31.0
[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-14T00:52:20Z
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 };
7474
7475 /* Setup */
7476
7477 OO.inheritClass( OO.ui.MenuSectionOptionWidget, OO.ui.DecoratedOptionWidget );
7478
7479 /* Static Properties */
7480
7481 /**
7482 * @static
7483 * @inheritdoc
7484 */
7485 OO.ui.MenuSectionOptionWidget.static.selectable = false;
7486
7487 /**
7488 * @static
7489 * @inheritdoc
7490 */
7491 OO.ui.MenuSectionOptionWidget.static.highlightable = false;
7492
7493 /**
7494 * MenuSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains options and
7495 * is used together with OO.ui.MenuOptionWidget. It is designed be used as part of another widget.
7496 * See {@link OO.ui.DropdownWidget DropdownWidget},
7497 * {@link OO.ui.ComboBoxInputWidget ComboBoxInputWidget}, and
7498 * {@link OO.ui.mixin.LookupElement LookupElement} for examples of widgets that contain menus.
7499 * MenuSelectWidgets themselves are not instantiated directly, rather subclassed
7500 * and customized to be opened, closed, and displayed as needed.
7501 *
7502 * By default, menus are clipped to the visible viewport and are not visible when a user presses the
7503 * mouse outside the menu.
7504 *
7505 * Menus also have support for keyboard interaction:
7506 *
7507 * - Enter/Return key: choose and select a menu option
7508 * - Up-arrow key: highlight the previous menu option
7509 * - Down-arrow key: highlight the next menu option
7510 * - Escape key: hide the menu
7511 *
7512 * Unlike most widgets, MenuSelectWidget is initially hidden and must be shown by calling #toggle.
7513 *
7514 * Please see the [OOUI documentation on MediaWiki][1] for more information.
7515 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options
7516 *
7517 * @class
7518 * @extends OO.ui.SelectWidget
7519 * @mixins OO.ui.mixin.ClippableElement
7520 * @mixins OO.ui.mixin.FloatableElement
7521 *
7522 * @constructor
7523 * @param {Object} [config] Configuration options
7524 * @cfg {OO.ui.TextInputWidget} [input] Text input used to implement option highlighting for menu
7525 * items that match the text the user types. This config is used by
7526 * {@link OO.ui.ComboBoxInputWidget ComboBoxInputWidget} and
7527 * {@link OO.ui.mixin.LookupElement LookupElement}
7528 * @cfg {jQuery} [$input] Text input used to implement option highlighting for menu items that match
7529 * the text the user types. This config is used by
7530 * {@link OO.ui.TagMultiselectWidget TagMultiselectWidget}
7531 * @cfg {OO.ui.Widget} [widget] Widget associated with the menu's active state. If the user clicks
7532 * the mouse anywhere on the page outside of this widget, the menu is hidden. For example, if
7533 * there is a button that toggles the menu's visibility on click, the menu will be hidden then
7534 * re-shown when the user clicks that button, unless the button (or its parent widget) is passed
7535 * in here.
7536 * @cfg {boolean} [autoHide=true] Hide the menu when the mouse is pressed outside the menu.
7537 * @cfg {jQuery} [$autoCloseIgnore] If these elements are clicked, don't auto-hide the menu.
7538 * @cfg {boolean} [hideOnChoose=true] Hide the menu when the user chooses an option.
7539 * @cfg {boolean} [filterFromInput=false] Filter the displayed options from the input
7540 * @cfg {boolean} [highlightOnFilter] Highlight the first result when filtering
7541 * @cfg {string} [filterMode='prefix'] The mode by which the menu filters the results.
7542 * Options are 'exact', 'prefix' or 'substring'. See `OO.ui.SelectWidget#getItemMatcher`
7543 * @param {number|string} [width] Width of the menu as a number of pixels or CSS string with unit
7544 * suffix, used by {@link OO.ui.mixin.ClippableElement ClippableElement}
7545 */
7546 OO.ui.MenuSelectWidget = function OoUiMenuSelectWidget( config ) {
7547 // Configuration initialization
7548 config = config || {};
7549
7550 // Parent constructor
7551 OO.ui.MenuSelectWidget.parent.call( this, config );
7552
7553 // Mixin constructors
7554 OO.ui.mixin.ClippableElement.call( this, $.extend( { $clippable: this.$group }, config ) );
7555 OO.ui.mixin.FloatableElement.call( this, config );
7556
7557 // Initial vertical positions other than 'center' will result in
7558 // the menu being flipped if there is not enough space in the container.
7559 // Store the original position so we know what to reset to.
7560 this.originalVerticalPosition = this.verticalPosition;
7561
7562 // Properties
7563 this.autoHide = config.autoHide === undefined || !!config.autoHide;
7564 this.hideOnChoose = config.hideOnChoose === undefined || !!config.hideOnChoose;
7565 this.filterFromInput = !!config.filterFromInput;
7566 this.$input = config.$input ? config.$input : config.input ? config.input.$input : null;
7567 this.$widget = config.widget ? config.widget.$element : null;
7568 this.$autoCloseIgnore = config.$autoCloseIgnore || $( [] );
7569 this.onDocumentMouseDownHandler = this.onDocumentMouseDown.bind( this );
7570 this.onInputEditHandler = OO.ui.debounce( this.updateItemVisibility.bind( this ), 100 );
7571 this.highlightOnFilter = !!config.highlightOnFilter;
7572 this.lastHighlightedItem = null;
7573 this.width = config.width;
7574 this.filterMode = config.filterMode;
7575
7576 // Initialization
7577 this.$element.addClass( 'oo-ui-menuSelectWidget' );
7578 if ( config.widget ) {
7579 this.setFocusOwner( config.widget.$tabIndexed );
7580 }
7581
7582 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
7583 // that reference properties not initialized at that time of parent class construction
7584 // TODO: Find a better way to handle post-constructor setup
7585 this.visible = false;
7586 this.$element.addClass( 'oo-ui-element-hidden' );
7587 this.$focusOwner.attr( 'aria-expanded', 'false' );
7588 };
7589
7590 /* Setup */
7591
7592 OO.inheritClass( OO.ui.MenuSelectWidget, OO.ui.SelectWidget );
7593 OO.mixinClass( OO.ui.MenuSelectWidget, OO.ui.mixin.ClippableElement );
7594 OO.mixinClass( OO.ui.MenuSelectWidget, OO.ui.mixin.FloatableElement );
7595
7596 /* Events */
7597
7598 /**
7599 * @event ready
7600 *
7601 * The menu is ready: it is visible and has been positioned and clipped.
7602 */
7603
7604 /* Static properties */
7605
7606 /**
7607 * Positions to flip to if there isn't room in the container for the
7608 * menu in a specific direction.
7609 *
7610 * @property {Object.<string,string>}
7611 */
7612 OO.ui.MenuSelectWidget.static.flippedPositions = {
7613 below: 'above',
7614 above: 'below',
7615 top: 'bottom',
7616 bottom: 'top'
7617 };
7618
7619 /* Methods */
7620
7621 /**
7622 * Handles document mouse down events.
7623 *
7624 * @protected
7625 * @param {MouseEvent} e Mouse down event
7626 */
7627 OO.ui.MenuSelectWidget.prototype.onDocumentMouseDown = function ( e ) {
7628 if (
7629 this.isVisible() &&
7630 !OO.ui.contains(
7631 this.$element.add( this.$widget ).add( this.$autoCloseIgnore ).get(),
7632 e.target,
7633 true
7634 )
7635 ) {
7636 this.toggle( false );
7637 }
7638 };
7639
7640 /**
7641 * @inheritdoc
7642 */
7643 OO.ui.MenuSelectWidget.prototype.onDocumentKeyDown = function ( e ) {
7644 var currentItem = this.findHighlightedItem() || this.findSelectedItem();
7645
7646 if ( !this.isDisabled() && this.isVisible() ) {
7647 switch ( e.keyCode ) {
7648 case OO.ui.Keys.LEFT:
7649 case OO.ui.Keys.RIGHT:
7650 // Do nothing if a text field is associated, arrow keys will be handled natively
7651 if ( !this.$input ) {
7652 OO.ui.MenuSelectWidget.parent.prototype.onDocumentKeyDown.call( this, e );
7653 }
7654 break;
7655 case OO.ui.Keys.ESCAPE:
7656 case OO.ui.Keys.TAB:
7657 if ( currentItem ) {
7658 currentItem.setHighlighted( false );
7659 }
7660 this.toggle( false );
7661 // Don't prevent tabbing away, prevent defocusing
7662 if ( e.keyCode === OO.ui.Keys.ESCAPE ) {
7663 e.preventDefault();
7664 e.stopPropagation();
7665 }
7666 break;
7667 default:
7668 OO.ui.MenuSelectWidget.parent.prototype.onDocumentKeyDown.call( this, e );
7669 return;
7670 }
7671 }
7672 };
7673
7674 /**
7675 * Update menu item visibility and clipping after input changes (if filterFromInput is enabled)
7676 * or after items were added/removed (always).
7677 *
7678 * @protected
7679 */
7680 OO.ui.MenuSelectWidget.prototype.updateItemVisibility = function () {
7681 var i, item, items, visible, section, sectionEmpty, filter, exactFilter,
7682 anyVisible = false,
7683 len = this.items.length,
7684 showAll = !this.isVisible(),
7685 exactMatch = false;
7686
7687 if ( this.$input && this.filterFromInput ) {
7688 filter = showAll ? null : this.getItemMatcher( this.$input.val(), this.filterMode );
7689 exactFilter = this.getItemMatcher( this.$input.val(), 'exact' );
7690 // Hide non-matching options, and also hide section headers if all options
7691 // in their section are hidden.
7692 for ( i = 0; i < len; i++ ) {
7693 item = this.items[ i ];
7694 if ( item instanceof OO.ui.MenuSectionOptionWidget ) {
7695 if ( section ) {
7696 // If the previous section was empty, hide its header
7697 section.toggle( showAll || !sectionEmpty );
7698 }
7699 section = item;
7700 sectionEmpty = true;
7701 } else if ( item instanceof OO.ui.OptionWidget ) {
7702 visible = showAll || filter( item );
7703 exactMatch = exactMatch || exactFilter( item );
7704 anyVisible = anyVisible || visible;
7705 sectionEmpty = sectionEmpty && !visible;
7706 item.toggle( visible );
7707 }
7708 }
7709 // Process the final section
7710 if ( section ) {
7711 section.toggle( showAll || !sectionEmpty );
7712 }
7713
7714 if ( anyVisible && this.items.length && !exactMatch ) {
7715 this.scrollItemIntoView( this.items[ 0 ] );
7716 }
7717
7718 if ( !anyVisible ) {
7719 this.highlightItem( null );
7720 }
7721
7722 this.$element.toggleClass( 'oo-ui-menuSelectWidget-invisible', !anyVisible );
7723
7724 if (
7725 this.highlightOnFilter &&
7726 !( this.lastHighlightedItem && this.lastHighlightedItem.isVisible() )
7727 ) {
7728 // Highlight the first item on the list
7729 item = null;
7730 items = this.getItems();
7731 for ( i = 0; i < items.length; i++ ) {
7732 if ( items[ i ].isVisible() ) {
7733 item = items[ i ];
7734 break;
7735 }
7736 }
7737 this.highlightItem( item );
7738 this.lastHighlightedItem = item;
7739 }
7740
7741 }
7742
7743 // Reevaluate clipping
7744 this.clip();
7745 };
7746
7747 /**
7748 * @inheritdoc
7749 */
7750 OO.ui.MenuSelectWidget.prototype.bindDocumentKeyDownListener = function () {
7751 if ( this.$input ) {
7752 this.$input.on( 'keydown', this.onDocumentKeyDownHandler );
7753 } else {
7754 OO.ui.MenuSelectWidget.parent.prototype.bindDocumentKeyDownListener.call( this );
7755 }
7756 };
7757
7758 /**
7759 * @inheritdoc
7760 */
7761 OO.ui.MenuSelectWidget.prototype.unbindDocumentKeyDownListener = function () {
7762 if ( this.$input ) {
7763 this.$input.off( 'keydown', this.onDocumentKeyDownHandler );
7764 } else {
7765 OO.ui.MenuSelectWidget.parent.prototype.unbindDocumentKeyDownListener.call( this );
7766 }
7767 };
7768
7769 /**
7770 * @inheritdoc
7771 */
7772 OO.ui.MenuSelectWidget.prototype.bindDocumentKeyPressListener = function () {
7773 if ( this.$input ) {
7774 if ( this.filterFromInput ) {
7775 this.$input.on(
7776 'keydown mouseup cut paste change input select',
7777 this.onInputEditHandler
7778 );
7779 this.updateItemVisibility();
7780 }
7781 } else {
7782 OO.ui.MenuSelectWidget.parent.prototype.bindDocumentKeyPressListener.call( this );
7783 }
7784 };
7785
7786 /**
7787 * @inheritdoc
7788 */
7789 OO.ui.MenuSelectWidget.prototype.unbindDocumentKeyPressListener = function () {
7790 if ( this.$input ) {
7791 if ( this.filterFromInput ) {
7792 this.$input.off(
7793 'keydown mouseup cut paste change input select',
7794 this.onInputEditHandler
7795 );
7796 this.updateItemVisibility();
7797 }
7798 } else {
7799 OO.ui.MenuSelectWidget.parent.prototype.unbindDocumentKeyPressListener.call( this );
7800 }
7801 };
7802
7803 /**
7804 * Choose an item.
7805 *
7806 * When a user chooses an item, the menu is closed, unless the hideOnChoose config option is
7807 * set to false.
7808 *
7809 * Note that ‘choose’ should never be modified programmatically. A user can choose an option with
7810 * the keyboard or mouse and it becomes selected. To select an item programmatically,
7811 * use the #selectItem method.
7812 *
7813 * @param {OO.ui.OptionWidget} item Item to choose
7814 * @chainable
7815 * @return {OO.ui.Widget} The widget, for chaining
7816 */
7817 OO.ui.MenuSelectWidget.prototype.chooseItem = function ( item ) {
7818 OO.ui.MenuSelectWidget.parent.prototype.chooseItem.call( this, item );
7819 if ( this.hideOnChoose ) {
7820 this.toggle( false );
7821 }
7822 return this;
7823 };
7824
7825 /**
7826 * @inheritdoc
7827 */
7828 OO.ui.MenuSelectWidget.prototype.addItems = function ( items, index ) {
7829 // Parent method
7830 OO.ui.MenuSelectWidget.parent.prototype.addItems.call( this, items, index );
7831
7832 this.updateItemVisibility();
7833
7834 return this;
7835 };
7836
7837 /**
7838 * @inheritdoc
7839 */
7840 OO.ui.MenuSelectWidget.prototype.removeItems = function ( items ) {
7841 // Parent method
7842 OO.ui.MenuSelectWidget.parent.prototype.removeItems.call( this, items );
7843
7844 this.updateItemVisibility();
7845
7846 return this;
7847 };
7848
7849 /**
7850 * @inheritdoc
7851 */
7852 OO.ui.MenuSelectWidget.prototype.clearItems = function () {
7853 // Parent method
7854 OO.ui.MenuSelectWidget.parent.prototype.clearItems.call( this );
7855
7856 this.updateItemVisibility();
7857
7858 return this;
7859 };
7860
7861 /**
7862 * Toggle visibility of the menu. The menu is initially hidden and must be shown by calling
7863 * `.toggle( true )` after its #$element is attached to the DOM.
7864 *
7865 * Do not show the menu while it is not attached to the DOM. The calculations required to display
7866 * it in the right place and with the right dimensions only work correctly while it is attached.
7867 * Side-effects may include broken interface and exceptions being thrown. This wasn't always
7868 * strictly enforced, so currently it only generates a warning in the browser console.
7869 *
7870 * @fires ready
7871 * @inheritdoc
7872 */
7873 OO.ui.MenuSelectWidget.prototype.toggle = function ( visible ) {
7874 var change, originalHeight, flippedHeight;
7875
7876 visible = ( visible === undefined ? !this.visible : !!visible ) && !!this.items.length;
7877 change = visible !== this.isVisible();
7878
7879 if ( visible && !this.warnedUnattached && !this.isElementAttached() ) {
7880 OO.ui.warnDeprecation( 'MenuSelectWidget#toggle: Before calling this method, the menu must be attached to the DOM.' );
7881 this.warnedUnattached = true;
7882 }
7883
7884 if ( change && visible ) {
7885 // Reset position before showing the popup again. It's possible we no longer need to flip
7886 // (e.g. if the user scrolled).
7887 this.setVerticalPosition( this.originalVerticalPosition );
7888 }
7889
7890 // Parent method
7891 OO.ui.MenuSelectWidget.parent.prototype.toggle.call( this, visible );
7892
7893 if ( change ) {
7894 if ( visible ) {
7895
7896 if ( this.width ) {
7897 this.setIdealSize( this.width );
7898 } else if ( this.$floatableContainer ) {
7899 this.$clippable.css( 'width', 'auto' );
7900 this.setIdealSize(
7901 this.$floatableContainer[ 0 ].offsetWidth > this.$clippable[ 0 ].offsetWidth ?
7902 // Dropdown is smaller than handle so expand to width
7903 this.$floatableContainer[ 0 ].offsetWidth :
7904 // Dropdown is larger than handle so auto size
7905 'auto'
7906 );
7907 this.$clippable.css( 'width', '' );
7908 }
7909
7910 this.togglePositioning( !!this.$floatableContainer );
7911 this.toggleClipping( true );
7912
7913 this.bindDocumentKeyDownListener();
7914 this.bindDocumentKeyPressListener();
7915
7916 if (
7917 ( this.isClippedVertically() || this.isFloatableOutOfView() ) &&
7918 this.originalVerticalPosition !== 'center'
7919 ) {
7920 // If opening the menu in one direction causes it to be clipped, flip it
7921 originalHeight = this.$element.height();
7922 this.setVerticalPosition(
7923 this.constructor.static.flippedPositions[ this.originalVerticalPosition ]
7924 );
7925 if ( this.isClippedVertically() || this.isFloatableOutOfView() ) {
7926 // If flipping also causes it to be clipped, open in whichever direction
7927 // we have more space
7928 flippedHeight = this.$element.height();
7929 if ( originalHeight > flippedHeight ) {
7930 this.setVerticalPosition( this.originalVerticalPosition );
7931 }
7932 }
7933 }
7934 // Note that we do not flip the menu's opening direction if the clipping changes
7935 // later (e.g. after the user scrolls), that seems like it would be annoying
7936
7937 this.$focusOwner.attr( 'aria-expanded', 'true' );
7938
7939 if ( this.findSelectedItem() ) {
7940 this.$focusOwner.attr( 'aria-activedescendant', this.findSelectedItem().getElementId() );
7941 this.findSelectedItem().scrollElementIntoView( { duration: 0 } );
7942 }
7943
7944 // Auto-hide
7945 if ( this.autoHide ) {
7946 this.getElementDocument().addEventListener( 'mousedown', this.onDocumentMouseDownHandler, true );
7947 }
7948
7949 this.emit( 'ready' );
7950 } else {
7951 this.$focusOwner.removeAttr( 'aria-activedescendant' );
7952 this.unbindDocumentKeyDownListener();
7953 this.unbindDocumentKeyPressListener();
7954 this.$focusOwner.attr( 'aria-expanded', 'false' );
7955 this.getElementDocument().removeEventListener( 'mousedown', this.onDocumentMouseDownHandler, true );
7956 this.togglePositioning( false );
7957 this.toggleClipping( false );
7958 }
7959 }
7960
7961 return this;
7962 };
7963
7964 /**
7965 * DropdownWidgets are not menus themselves, rather they contain a menu of options created with
7966 * OO.ui.MenuOptionWidget. The DropdownWidget takes care of opening and displaying the menu so that
7967 * users can interact with it.
7968 *
7969 * If you want to use this within an HTML form, such as a OO.ui.FormLayout, use
7970 * OO.ui.DropdownInputWidget instead.
7971 *
7972 * @example
7973 * // A DropdownWidget with a menu that contains three options.
7974 * var dropDown = new OO.ui.DropdownWidget( {
7975 * label: 'Dropdown menu: Select a menu option',
7976 * menu: {
7977 * items: [
7978 * new OO.ui.MenuOptionWidget( {
7979 * data: 'a',
7980 * label: 'First'
7981 * } ),
7982 * new OO.ui.MenuOptionWidget( {
7983 * data: 'b',
7984 * label: 'Second'
7985 * } ),
7986 * new OO.ui.MenuOptionWidget( {
7987 * data: 'c',
7988 * label: 'Third'
7989 * } )
7990 * ]
7991 * }
7992 * } );
7993 *
7994 * $( document.body ).append( dropDown.$element );
7995 *
7996 * dropDown.getMenu().selectItemByData( 'b' );
7997 *
7998 * dropDown.getMenu().findSelectedItem().getData(); // Returns 'b'.
7999 *
8000 * For more information, please see the [OOUI documentation on MediaWiki] [1].
8001 *
8002 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options#Menu_selects_and_options
8003 *
8004 * @class
8005 * @extends OO.ui.Widget
8006 * @mixins OO.ui.mixin.IconElement
8007 * @mixins OO.ui.mixin.IndicatorElement
8008 * @mixins OO.ui.mixin.LabelElement
8009 * @mixins OO.ui.mixin.TitledElement
8010 * @mixins OO.ui.mixin.TabIndexedElement
8011 *
8012 * @constructor
8013 * @param {Object} [config] Configuration options
8014 * @cfg {Object} [menu] Configuration options to pass to
8015 * {@link OO.ui.MenuSelectWidget menu select widget}.
8016 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful
8017 * in cases where the expanded menu is larger than its containing `<div>`. The specified overlay
8018 * layer is usually on top of the containing `<div>` and has a larger area. By default, the menu
8019 * uses relative positioning.
8020 * See <https://www.mediawiki.org/wiki/OOUI/Concepts#Overlays>.
8021 */
8022 OO.ui.DropdownWidget = function OoUiDropdownWidget( config ) {
8023 // Configuration initialization
8024 config = $.extend( { indicator: 'down' }, config );
8025
8026 // Parent constructor
8027 OO.ui.DropdownWidget.parent.call( this, config );
8028
8029 // Properties (must be set before TabIndexedElement constructor call)
8030 this.$handle = $( '<button>' );
8031 this.$overlay = ( config.$overlay === true ?
8032 OO.ui.getDefaultOverlay() : config.$overlay ) || this.$element;
8033
8034 // Mixin constructors
8035 OO.ui.mixin.IconElement.call( this, config );
8036 OO.ui.mixin.IndicatorElement.call( this, config );
8037 OO.ui.mixin.LabelElement.call( this, config );
8038 OO.ui.mixin.TitledElement.call( this, $.extend( {
8039 $titled: this.$label
8040 }, config ) );
8041 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {
8042 $tabIndexed: this.$handle
8043 }, config ) );
8044
8045 // Properties
8046 this.menu = new OO.ui.MenuSelectWidget( $.extend( {
8047 widget: this,
8048 $floatableContainer: this.$element
8049 }, config.menu ) );
8050
8051 // Events
8052 this.$handle.on( {
8053 click: this.onClick.bind( this ),
8054 keydown: this.onKeyDown.bind( this ),
8055 // Hack? Handle type-to-search when menu is not expanded and not handling its own events.
8056 keypress: this.menu.onDocumentKeyPressHandler,
8057 blur: this.menu.clearKeyPressBuffer.bind( this.menu )
8058 } );
8059 this.menu.connect( this, {
8060 select: 'onMenuSelect',
8061 toggle: 'onMenuToggle'
8062 } );
8063
8064 // Initialization
8065 this.$handle
8066 .addClass( 'oo-ui-dropdownWidget-handle' )
8067 .attr( {
8068 type: 'button',
8069 'aria-owns': this.menu.getElementId(),
8070 'aria-haspopup': 'listbox'
8071 } )
8072 .append( this.$icon, this.$label, this.$indicator );
8073 this.$element
8074 .addClass( 'oo-ui-dropdownWidget' )
8075 .append( this.$handle );
8076 this.$overlay.append( this.menu.$element );
8077 };
8078
8079 /* Setup */
8080
8081 OO.inheritClass( OO.ui.DropdownWidget, OO.ui.Widget );
8082 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.IconElement );
8083 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.IndicatorElement );
8084 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.LabelElement );
8085 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.TitledElement );
8086 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.TabIndexedElement );
8087
8088 /* Methods */
8089
8090 /**
8091 * Get the menu.
8092 *
8093 * @return {OO.ui.MenuSelectWidget} Menu of widget
8094 */
8095 OO.ui.DropdownWidget.prototype.getMenu = function () {
8096 return this.menu;
8097 };
8098
8099 /**
8100 * Handles menu select events.
8101 *
8102 * @private
8103 * @param {OO.ui.MenuOptionWidget} item Selected menu item
8104 */
8105 OO.ui.DropdownWidget.prototype.onMenuSelect = function ( item ) {
8106 var selectedLabel;
8107
8108 if ( !item ) {
8109 this.setLabel( null );
8110 return;
8111 }
8112
8113 selectedLabel = item.getLabel();
8114
8115 // If the label is a DOM element, clone it, because setLabel will append() it
8116 if ( selectedLabel instanceof $ ) {
8117 selectedLabel = selectedLabel.clone();
8118 }
8119
8120 this.setLabel( selectedLabel );
8121 };
8122
8123 /**
8124 * Handle menu toggle events.
8125 *
8126 * @private
8127 * @param {boolean} isVisible Open state of the menu
8128 */
8129 OO.ui.DropdownWidget.prototype.onMenuToggle = function ( isVisible ) {
8130 this.$element.toggleClass( 'oo-ui-dropdownWidget-open', isVisible );
8131 };
8132
8133 /**
8134 * Handle mouse click events.
8135 *
8136 * @private
8137 * @param {jQuery.Event} e Mouse click event
8138 * @return {undefined/boolean} False to prevent default if event is handled
8139 */
8140 OO.ui.DropdownWidget.prototype.onClick = function ( e ) {
8141 if ( !this.isDisabled() && e.which === OO.ui.MouseButtons.LEFT ) {
8142 this.menu.toggle();
8143 }
8144 return false;
8145 };
8146
8147 /**
8148 * Handle key down events.
8149 *
8150 * @private
8151 * @param {jQuery.Event} e Key down event
8152 * @return {undefined/boolean} False to prevent default if event is handled
8153 */
8154 OO.ui.DropdownWidget.prototype.onKeyDown = function ( e ) {
8155 if (
8156 !this.isDisabled() &&
8157 (
8158 e.which === OO.ui.Keys.ENTER ||
8159 (
8160 e.which === OO.ui.Keys.SPACE &&
8161 // Avoid conflicts with type-to-search, see SelectWidget#onKeyPress.
8162 // Space only closes the menu is the user is not typing to search.
8163 this.menu.keyPressBuffer === ''
8164 ) ||
8165 (
8166 !this.menu.isVisible() &&
8167 (
8168 e.which === OO.ui.Keys.UP ||
8169 e.which === OO.ui.Keys.DOWN
8170 )
8171 )
8172 )
8173 ) {
8174 this.menu.toggle();
8175 return false;
8176 }
8177 };
8178
8179 /**
8180 * RadioOptionWidget is an option widget that looks like a radio button.
8181 * The class is used with OO.ui.RadioSelectWidget to create a selection of radio options.
8182 * Please see the [OOUI documentation on MediaWiki] [1] for more information.
8183 *
8184 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options#Button_selects_and_option
8185 *
8186 * @class
8187 * @extends OO.ui.OptionWidget
8188 *
8189 * @constructor
8190 * @param {Object} [config] Configuration options
8191 */
8192 OO.ui.RadioOptionWidget = function OoUiRadioOptionWidget( config ) {
8193 // Configuration initialization
8194 config = config || {};
8195
8196 // Properties (must be done before parent constructor which calls #setDisabled)
8197 this.radio = new OO.ui.RadioInputWidget( { value: config.data, tabIndex: -1 } );
8198
8199 // Parent constructor
8200 OO.ui.RadioOptionWidget.parent.call( this, config );
8201
8202 // Initialization
8203 // Remove implicit role, we're handling it ourselves
8204 this.radio.$input.attr( 'role', 'presentation' );
8205 this.$element
8206 .addClass( 'oo-ui-radioOptionWidget' )
8207 .attr( 'role', 'radio' )
8208 .attr( 'aria-checked', 'false' )
8209 .removeAttr( 'aria-selected' )
8210 .prepend( this.radio.$element );
8211 };
8212
8213 /* Setup */
8214
8215 OO.inheritClass( OO.ui.RadioOptionWidget, OO.ui.OptionWidget );
8216
8217 /* Static Properties */
8218
8219 /**
8220 * @static
8221 * @inheritdoc
8222 */
8223 OO.ui.RadioOptionWidget.static.highlightable = false;
8224
8225 /**
8226 * @static
8227 * @inheritdoc
8228 */
8229 OO.ui.RadioOptionWidget.static.scrollIntoViewOnSelect = true;
8230
8231 /**
8232 * @static
8233 * @inheritdoc
8234 */
8235 OO.ui.RadioOptionWidget.static.pressable = false;
8236
8237 /**
8238 * @static
8239 * @inheritdoc
8240 */
8241 OO.ui.RadioOptionWidget.static.tagName = 'label';
8242
8243 /* Methods */
8244
8245 /**
8246 * @inheritdoc
8247 */
8248 OO.ui.RadioOptionWidget.prototype.setSelected = function ( state ) {
8249 OO.ui.RadioOptionWidget.parent.prototype.setSelected.call( this, state );
8250
8251 this.radio.setSelected( state );
8252 this.$element
8253 .attr( 'aria-checked', state.toString() )
8254 .removeAttr( 'aria-selected' );
8255
8256 return this;
8257 };
8258
8259 /**
8260 * @inheritdoc
8261 */
8262 OO.ui.RadioOptionWidget.prototype.setDisabled = function ( disabled ) {
8263 OO.ui.RadioOptionWidget.parent.prototype.setDisabled.call( this, disabled );
8264
8265 this.radio.setDisabled( this.isDisabled() );
8266
8267 return this;
8268 };
8269
8270 /**
8271 * RadioSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains radio
8272 * options and is used together with OO.ui.RadioOptionWidget. The RadioSelectWidget provides
8273 * an interface for adding, removing and selecting options.
8274 * Please see the [OOUI documentation on MediaWiki][1] for more information.
8275 *
8276 * If you want to use this within an HTML form, such as a OO.ui.FormLayout, use
8277 * OO.ui.RadioSelectInputWidget instead.
8278 *
8279 * @example
8280 * // A RadioSelectWidget with RadioOptions.
8281 * var option1 = new OO.ui.RadioOptionWidget( {
8282 * data: 'a',
8283 * label: 'Selected radio option'
8284 * } ),
8285 * option2 = new OO.ui.RadioOptionWidget( {
8286 * data: 'b',
8287 * label: 'Unselected radio option'
8288 * } );
8289 * radioSelect = new OO.ui.RadioSelectWidget( {
8290 * items: [ option1, option2 ]
8291 * } );
8292 *
8293 * // Select 'option 1' using the RadioSelectWidget's selectItem() method.
8294 * radioSelect.selectItem( option1 );
8295 *
8296 * $( document.body ).append( radioSelect.$element );
8297 *
8298 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options
8299
8300 *
8301 * @class
8302 * @extends OO.ui.SelectWidget
8303 * @mixins OO.ui.mixin.TabIndexedElement
8304 *
8305 * @constructor
8306 * @param {Object} [config] Configuration options
8307 */
8308 OO.ui.RadioSelectWidget = function OoUiRadioSelectWidget( config ) {
8309 // Parent constructor
8310 OO.ui.RadioSelectWidget.parent.call( this, config );
8311
8312 // Mixin constructors
8313 OO.ui.mixin.TabIndexedElement.call( this, config );
8314
8315 // Events
8316 this.$element.on( {
8317 focus: this.bindDocumentKeyDownListener.bind( this ),
8318 blur: this.unbindDocumentKeyDownListener.bind( this )
8319 } );
8320
8321 // Initialization
8322 this.$element
8323 .addClass( 'oo-ui-radioSelectWidget' )
8324 .attr( 'role', 'radiogroup' );
8325 };
8326
8327 /* Setup */
8328
8329 OO.inheritClass( OO.ui.RadioSelectWidget, OO.ui.SelectWidget );
8330 OO.mixinClass( OO.ui.RadioSelectWidget, OO.ui.mixin.TabIndexedElement );
8331
8332 /**
8333 * MultioptionWidgets are special elements that can be selected and configured with data. The
8334 * data is often unique for each option, but it does not have to be. MultioptionWidgets are used
8335 * with OO.ui.SelectWidget to create a selection of mutually exclusive options. For more information
8336 * and examples, please see the [OOUI documentation on MediaWiki][1].
8337 *
8338 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options
8339 *
8340 * @class
8341 * @extends OO.ui.Widget
8342 * @mixins OO.ui.mixin.ItemWidget
8343 * @mixins OO.ui.mixin.LabelElement
8344 * @mixins OO.ui.mixin.TitledElement
8345 *
8346 * @constructor
8347 * @param {Object} [config] Configuration options
8348 * @cfg {boolean} [selected=false] Whether the option is initially selected
8349 */
8350 OO.ui.MultioptionWidget = function OoUiMultioptionWidget( config ) {
8351 // Configuration initialization
8352 config = config || {};
8353
8354 // Parent constructor
8355 OO.ui.MultioptionWidget.parent.call( this, config );
8356
8357 // Mixin constructors
8358 OO.ui.mixin.ItemWidget.call( this );
8359 OO.ui.mixin.LabelElement.call( this, config );
8360 OO.ui.mixin.TitledElement.call( this, config );
8361
8362 // Properties
8363 this.selected = null;
8364
8365 // Initialization
8366 this.$element
8367 .addClass( 'oo-ui-multioptionWidget' )
8368 .append( this.$label );
8369 this.setSelected( config.selected );
8370 };
8371
8372 /* Setup */
8373
8374 OO.inheritClass( OO.ui.MultioptionWidget, OO.ui.Widget );
8375 OO.mixinClass( OO.ui.MultioptionWidget, OO.ui.mixin.ItemWidget );
8376 OO.mixinClass( OO.ui.MultioptionWidget, OO.ui.mixin.LabelElement );
8377 OO.mixinClass( OO.ui.MultioptionWidget, OO.ui.mixin.TitledElement );
8378
8379 /* Events */
8380
8381 /**
8382 * @event change
8383 *
8384 * A change event is emitted when the selected state of the option changes.
8385 *
8386 * @param {boolean} selected Whether the option is now selected
8387 */
8388
8389 /* Methods */
8390
8391 /**
8392 * Check if the option is selected.
8393 *
8394 * @return {boolean} Item is selected
8395 */
8396 OO.ui.MultioptionWidget.prototype.isSelected = function () {
8397 return this.selected;
8398 };
8399
8400 /**
8401 * Set the option’s selected state. In general, all modifications to the selection
8402 * should be handled by the SelectWidget’s
8403 * {@link OO.ui.SelectWidget#selectItem selectItem( [item] )} method instead of this method.
8404 *
8405 * @param {boolean} [state=false] Select option
8406 * @chainable
8407 * @return {OO.ui.Widget} The widget, for chaining
8408 */
8409 OO.ui.MultioptionWidget.prototype.setSelected = function ( state ) {
8410 state = !!state;
8411 if ( this.selected !== state ) {
8412 this.selected = state;
8413 this.emit( 'change', state );
8414 this.$element.toggleClass( 'oo-ui-multioptionWidget-selected', state );
8415 }
8416 return this;
8417 };
8418
8419 /**
8420 * MultiselectWidget allows selecting multiple options from a list.
8421 *
8422 * For more information about menus and options, please see the [OOUI documentation
8423 * on MediaWiki][1].
8424 *
8425 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options#Menu_selects_and_options
8426 *
8427 * @class
8428 * @abstract
8429 * @extends OO.ui.Widget
8430 * @mixins OO.ui.mixin.GroupWidget
8431 * @mixins OO.ui.mixin.TitledElement
8432 *
8433 * @constructor
8434 * @param {Object} [config] Configuration options
8435 * @cfg {OO.ui.MultioptionWidget[]} [items] An array of options to add to the multiselect.
8436 */
8437 OO.ui.MultiselectWidget = function OoUiMultiselectWidget( config ) {
8438 // Parent constructor
8439 OO.ui.MultiselectWidget.parent.call( this, config );
8440
8441 // Configuration initialization
8442 config = config || {};
8443
8444 // Mixin constructors
8445 OO.ui.mixin.GroupWidget.call( this, config );
8446 OO.ui.mixin.TitledElement.call( this, config );
8447
8448 // Events
8449 this.aggregate( {
8450 change: 'select'
8451 } );
8452 // This is mostly for compatibility with TagMultiselectWidget... normally, 'change' is emitted
8453 // by GroupElement only when items are added/removed
8454 this.connect( this, {
8455 select: [ 'emit', 'change' ]
8456 } );
8457
8458 // Initialization
8459 if ( config.items ) {
8460 this.addItems( config.items );
8461 }
8462 this.$group.addClass( 'oo-ui-multiselectWidget-group' );
8463 this.$element.addClass( 'oo-ui-multiselectWidget' )
8464 .append( this.$group );
8465 };
8466
8467 /* Setup */
8468
8469 OO.inheritClass( OO.ui.MultiselectWidget, OO.ui.Widget );
8470 OO.mixinClass( OO.ui.MultiselectWidget, OO.ui.mixin.GroupWidget );
8471 OO.mixinClass( OO.ui.MultiselectWidget, OO.ui.mixin.TitledElement );
8472
8473 /* Events */
8474
8475 /**
8476 * @event change
8477 *
8478 * A change event is emitted when the set of items changes, or an item is selected or deselected.
8479 */
8480
8481 /**
8482 * @event select
8483 *
8484 * A select event is emitted when an item is selected or deselected.
8485 */
8486
8487 /* Methods */
8488
8489 /**
8490 * Find options that are selected.
8491 *
8492 * @return {OO.ui.MultioptionWidget[]} Selected options
8493 */
8494 OO.ui.MultiselectWidget.prototype.findSelectedItems = function () {
8495 return this.items.filter( function ( item ) {
8496 return item.isSelected();
8497 } );
8498 };
8499
8500 /**
8501 * Find the data of options that are selected.
8502 *
8503 * @return {Object[]|string[]} Values of selected options
8504 */
8505 OO.ui.MultiselectWidget.prototype.findSelectedItemsData = function () {
8506 return this.findSelectedItems().map( function ( item ) {
8507 return item.data;
8508 } );
8509 };
8510
8511 /**
8512 * Select options by reference. Options not mentioned in the `items` array will be deselected.
8513 *
8514 * @param {OO.ui.MultioptionWidget[]} items Items to select
8515 * @chainable
8516 * @return {OO.ui.Widget} The widget, for chaining
8517 */
8518 OO.ui.MultiselectWidget.prototype.selectItems = function ( items ) {
8519 this.items.forEach( function ( item ) {
8520 var selected = items.indexOf( item ) !== -1;
8521 item.setSelected( selected );
8522 } );
8523 return this;
8524 };
8525
8526 /**
8527 * Select items by their data. Options not mentioned in the `datas` array will be deselected.
8528 *
8529 * @param {Object[]|string[]} datas Values of items to select
8530 * @chainable
8531 * @return {OO.ui.Widget} The widget, for chaining
8532 */
8533 OO.ui.MultiselectWidget.prototype.selectItemsByData = function ( datas ) {
8534 var items,
8535 widget = this;
8536 items = datas.map( function ( data ) {
8537 return widget.findItemFromData( data );
8538 } );
8539 this.selectItems( items );
8540 return this;
8541 };
8542
8543 /**
8544 * CheckboxMultioptionWidget is an option widget that looks like a checkbox.
8545 * The class is used with OO.ui.CheckboxMultiselectWidget to create a selection of checkbox options.
8546 * Please see the [OOUI documentation on MediaWiki] [1] for more information.
8547 *
8548 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options#Button_selects_and_option
8549 *
8550 * @class
8551 * @extends OO.ui.MultioptionWidget
8552 *
8553 * @constructor
8554 * @param {Object} [config] Configuration options
8555 */
8556 OO.ui.CheckboxMultioptionWidget = function OoUiCheckboxMultioptionWidget( config ) {
8557 // Configuration initialization
8558 config = config || {};
8559
8560 // Properties (must be done before parent constructor which calls #setDisabled)
8561 this.checkbox = new OO.ui.CheckboxInputWidget();
8562
8563 // Parent constructor
8564 OO.ui.CheckboxMultioptionWidget.parent.call( this, config );
8565
8566 // Events
8567 this.checkbox.on( 'change', this.onCheckboxChange.bind( this ) );
8568 this.$element.on( 'keydown', this.onKeyDown.bind( this ) );
8569
8570 // Initialization
8571 this.$element
8572 .addClass( 'oo-ui-checkboxMultioptionWidget' )
8573 .prepend( this.checkbox.$element );
8574 };
8575
8576 /* Setup */
8577
8578 OO.inheritClass( OO.ui.CheckboxMultioptionWidget, OO.ui.MultioptionWidget );
8579
8580 /* Static Properties */
8581
8582 /**
8583 * @static
8584 * @inheritdoc
8585 */
8586 OO.ui.CheckboxMultioptionWidget.static.tagName = 'label';
8587
8588 /* Methods */
8589
8590 /**
8591 * Handle checkbox selected state change.
8592 *
8593 * @private
8594 */
8595 OO.ui.CheckboxMultioptionWidget.prototype.onCheckboxChange = function () {
8596 this.setSelected( this.checkbox.isSelected() );
8597 };
8598
8599 /**
8600 * @inheritdoc
8601 */
8602 OO.ui.CheckboxMultioptionWidget.prototype.setSelected = function ( state ) {
8603 OO.ui.CheckboxMultioptionWidget.parent.prototype.setSelected.call( this, state );
8604 this.checkbox.setSelected( state );
8605 return this;
8606 };
8607
8608 /**
8609 * @inheritdoc
8610 */
8611 OO.ui.CheckboxMultioptionWidget.prototype.setDisabled = function ( disabled ) {
8612 OO.ui.CheckboxMultioptionWidget.parent.prototype.setDisabled.call( this, disabled );
8613 this.checkbox.setDisabled( this.isDisabled() );
8614 return this;
8615 };
8616
8617 /**
8618 * Focus the widget.
8619 */
8620 OO.ui.CheckboxMultioptionWidget.prototype.focus = function () {
8621 this.checkbox.focus();
8622 };
8623
8624 /**
8625 * Handle key down events.
8626 *
8627 * @protected
8628 * @param {jQuery.Event} e
8629 */
8630 OO.ui.CheckboxMultioptionWidget.prototype.onKeyDown = function ( e ) {
8631 var
8632 element = this.getElementGroup(),
8633 nextItem;
8634
8635 if ( e.keyCode === OO.ui.Keys.LEFT || e.keyCode === OO.ui.Keys.UP ) {
8636 nextItem = element.getRelativeFocusableItem( this, -1 );
8637 } else if ( e.keyCode === OO.ui.Keys.RIGHT || e.keyCode === OO.ui.Keys.DOWN ) {
8638 nextItem = element.getRelativeFocusableItem( this, 1 );
8639 }
8640
8641 if ( nextItem ) {
8642 e.preventDefault();
8643 nextItem.focus();
8644 }
8645 };
8646
8647 /**
8648 * CheckboxMultiselectWidget is a {@link OO.ui.MultiselectWidget multiselect widget} that contains
8649 * checkboxes and is used together with OO.ui.CheckboxMultioptionWidget. The
8650 * CheckboxMultiselectWidget provides an interface for adding, removing and selecting options.
8651 * Please see the [OOUI documentation on MediaWiki][1] for more information.
8652 *
8653 * If you want to use this within an HTML form, such as a OO.ui.FormLayout, use
8654 * OO.ui.CheckboxMultiselectInputWidget instead.
8655 *
8656 * @example
8657 * // A CheckboxMultiselectWidget with CheckboxMultioptions.
8658 * var option1 = new OO.ui.CheckboxMultioptionWidget( {
8659 * data: 'a',
8660 * selected: true,
8661 * label: 'Selected checkbox'
8662 * } ),
8663 * option2 = new OO.ui.CheckboxMultioptionWidget( {
8664 * data: 'b',
8665 * label: 'Unselected checkbox'
8666 * } ),
8667 * multiselect = new OO.ui.CheckboxMultiselectWidget( {
8668 * items: [ option1, option2 ]
8669 * } );
8670 * $( document.body ).append( multiselect.$element );
8671 *
8672 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options
8673 *
8674 * @class
8675 * @extends OO.ui.MultiselectWidget
8676 *
8677 * @constructor
8678 * @param {Object} [config] Configuration options
8679 */
8680 OO.ui.CheckboxMultiselectWidget = function OoUiCheckboxMultiselectWidget( config ) {
8681 // Parent constructor
8682 OO.ui.CheckboxMultiselectWidget.parent.call( this, config );
8683
8684 // Properties
8685 this.$lastClicked = null;
8686
8687 // Events
8688 this.$group.on( 'click', this.onClick.bind( this ) );
8689
8690 // Initialization
8691 this.$element.addClass( 'oo-ui-checkboxMultiselectWidget' );
8692 };
8693
8694 /* Setup */
8695
8696 OO.inheritClass( OO.ui.CheckboxMultiselectWidget, OO.ui.MultiselectWidget );
8697
8698 /* Methods */
8699
8700 /**
8701 * Get an option by its position relative to the specified item (or to the start of the
8702 * option array, if item is `null`). The direction in which to search through the option array
8703 * is specified with a number: -1 for reverse (the default) or 1 for forward. The method will
8704 * return an option, or `null` if there are no options in the array.
8705 *
8706 * @param {OO.ui.CheckboxMultioptionWidget|null} item Item to describe the start position, or
8707 * `null` to start at the beginning of the array.
8708 * @param {number} direction Direction to move in: -1 to move backward, 1 to move forward
8709 * @return {OO.ui.CheckboxMultioptionWidget|null} Item at position, `null` if there are no items
8710 * in the select.
8711 */
8712 OO.ui.CheckboxMultiselectWidget.prototype.getRelativeFocusableItem = function ( item, direction ) {
8713 var currentIndex, nextIndex, i,
8714 increase = direction > 0 ? 1 : -1,
8715 len = this.items.length;
8716
8717 if ( item ) {
8718 currentIndex = this.items.indexOf( item );
8719 nextIndex = ( currentIndex + increase + len ) % len;
8720 } else {
8721 // If no item is selected and moving forward, start at the beginning.
8722 // If moving backward, start at the end.
8723 nextIndex = direction > 0 ? 0 : len - 1;
8724 }
8725
8726 for ( i = 0; i < len; i++ ) {
8727 item = this.items[ nextIndex ];
8728 if ( item && !item.isDisabled() ) {
8729 return item;
8730 }
8731 nextIndex = ( nextIndex + increase + len ) % len;
8732 }
8733 return null;
8734 };
8735
8736 /**
8737 * Handle click events on checkboxes.
8738 *
8739 * @param {jQuery.Event} e
8740 */
8741 OO.ui.CheckboxMultiselectWidget.prototype.onClick = function ( e ) {
8742 var $options, lastClickedIndex, nowClickedIndex, i, direction, wasSelected, items,
8743 $lastClicked = this.$lastClicked,
8744 $nowClicked = $( e.target ).closest( '.oo-ui-checkboxMultioptionWidget' )
8745 .not( '.oo-ui-widget-disabled' );
8746
8747 // Allow selecting multiple options at once by Shift-clicking them
8748 if ( $lastClicked && $nowClicked.length && e.shiftKey ) {
8749 $options = this.$group.find( '.oo-ui-checkboxMultioptionWidget' );
8750 lastClickedIndex = $options.index( $lastClicked );
8751 nowClickedIndex = $options.index( $nowClicked );
8752 // If it's the same item, either the user is being silly, or it's a fake event generated
8753 // by the browser. In either case we don't need custom handling.
8754 if ( nowClickedIndex !== lastClickedIndex ) {
8755 items = this.items;
8756 wasSelected = items[ nowClickedIndex ].isSelected();
8757 direction = nowClickedIndex > lastClickedIndex ? 1 : -1;
8758
8759 // This depends on the DOM order of the items and the order of the .items array being
8760 // the same.
8761 for ( i = lastClickedIndex; i !== nowClickedIndex; i += direction ) {
8762 if ( !items[ i ].isDisabled() ) {
8763 items[ i ].setSelected( !wasSelected );
8764 }
8765 }
8766 // For the now-clicked element, use immediate timeout to allow the browser to do its own
8767 // handling first, then set our value. The order in which events happen is different for
8768 // clicks on the <input> and on the <label> and there are additional fake clicks fired
8769 // for non-click actions that change the checkboxes.
8770 e.preventDefault();
8771 setTimeout( function () {
8772 if ( !items[ nowClickedIndex ].isDisabled() ) {
8773 items[ nowClickedIndex ].setSelected( !wasSelected );
8774 }
8775 } );
8776 }
8777 }
8778
8779 if ( $nowClicked.length ) {
8780 this.$lastClicked = $nowClicked;
8781 }
8782 };
8783
8784 /**
8785 * Focus the widget
8786 *
8787 * @chainable
8788 * @return {OO.ui.Widget} The widget, for chaining
8789 */
8790 OO.ui.CheckboxMultiselectWidget.prototype.focus = function () {
8791 var item;
8792 if ( !this.isDisabled() ) {
8793 item = this.getRelativeFocusableItem( null, 1 );
8794 if ( item ) {
8795 item.focus();
8796 }
8797 }
8798 return this;
8799 };
8800
8801 /**
8802 * @inheritdoc
8803 */
8804 OO.ui.CheckboxMultiselectWidget.prototype.simulateLabelClick = function () {
8805 this.focus();
8806 };
8807
8808 /**
8809 * Progress bars visually display the status of an operation, such as a download,
8810 * and can be either determinate or indeterminate:
8811 *
8812 * - **determinate** process bars show the percent of an operation that is complete.
8813 *
8814 * - **indeterminate** process bars use a visual display of motion to indicate that an operation
8815 * is taking place. Because the extent of an indeterminate operation is unknown, the bar does
8816 * not use percentages.
8817 *
8818 * The value of the `progress` configuration determines whether the bar is determinate
8819 * or indeterminate.
8820 *
8821 * @example
8822 * // Examples of determinate and indeterminate progress bars.
8823 * var progressBar1 = new OO.ui.ProgressBarWidget( {
8824 * progress: 33
8825 * } );
8826 * var progressBar2 = new OO.ui.ProgressBarWidget();
8827 *
8828 * // Create a FieldsetLayout to layout progress bars.
8829 * var fieldset = new OO.ui.FieldsetLayout;
8830 * fieldset.addItems( [
8831 * new OO.ui.FieldLayout( progressBar1, {
8832 * label: 'Determinate',
8833 * align: 'top'
8834 * } ),
8835 * new OO.ui.FieldLayout( progressBar2, {
8836 * label: 'Indeterminate',
8837 * align: 'top'
8838 * } )
8839 * ] );
8840 * $( document.body ).append( fieldset.$element );
8841 *
8842 * @class
8843 * @extends OO.ui.Widget
8844 *
8845 * @constructor
8846 * @param {Object} [config] Configuration options
8847 * @cfg {number|boolean} [progress=false] The type of progress bar (determinate or indeterminate).
8848 * To create a determinate progress bar, specify a number that reflects the initial
8849 * percent complete.
8850 * By default, the progress bar is indeterminate.
8851 */
8852 OO.ui.ProgressBarWidget = function OoUiProgressBarWidget( config ) {
8853 // Configuration initialization
8854 config = config || {};
8855
8856 // Parent constructor
8857 OO.ui.ProgressBarWidget.parent.call( this, config );
8858
8859 // Properties
8860 this.$bar = $( '<div>' );
8861 this.progress = null;
8862
8863 // Initialization
8864 this.setProgress( config.progress !== undefined ? config.progress : false );
8865 this.$bar.addClass( 'oo-ui-progressBarWidget-bar' );
8866 this.$element
8867 .attr( {
8868 role: 'progressbar',
8869 'aria-valuemin': 0,
8870 'aria-valuemax': 100
8871 } )
8872 .addClass( 'oo-ui-progressBarWidget' )
8873 .append( this.$bar );
8874 };
8875
8876 /* Setup */
8877
8878 OO.inheritClass( OO.ui.ProgressBarWidget, OO.ui.Widget );
8879
8880 /* Static Properties */
8881
8882 /**
8883 * @static
8884 * @inheritdoc
8885 */
8886 OO.ui.ProgressBarWidget.static.tagName = 'div';
8887
8888 /* Methods */
8889
8890 /**
8891 * Get the percent of the progress that has been completed. Indeterminate progresses will
8892 * return `false`.
8893 *
8894 * @return {number|boolean} Progress percent
8895 */
8896 OO.ui.ProgressBarWidget.prototype.getProgress = function () {
8897 return this.progress;
8898 };
8899
8900 /**
8901 * Set the percent of the process completed or `false` for an indeterminate process.
8902 *
8903 * @param {number|boolean} progress Progress percent or `false` for indeterminate
8904 */
8905 OO.ui.ProgressBarWidget.prototype.setProgress = function ( progress ) {
8906 this.progress = progress;
8907
8908 if ( progress !== false ) {
8909 this.$bar.css( 'width', this.progress + '%' );
8910 this.$element.attr( 'aria-valuenow', this.progress );
8911 } else {
8912 this.$bar.css( 'width', '' );
8913 this.$element.removeAttr( 'aria-valuenow' );
8914 }
8915 this.$element.toggleClass( 'oo-ui-progressBarWidget-indeterminate', progress === false );
8916 };
8917
8918 /**
8919 * InputWidget is the base class for all input widgets, which
8920 * include {@link OO.ui.TextInputWidget text inputs}, {@link OO.ui.CheckboxInputWidget checkbox
8921 * inputs}, {@link OO.ui.RadioInputWidget radio inputs}, and
8922 * {@link OO.ui.ButtonInputWidget button inputs}.
8923 * See the [OOUI documentation on MediaWiki] [1] for more information and examples.
8924 *
8925 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
8926 *
8927 * @abstract
8928 * @class
8929 * @extends OO.ui.Widget
8930 * @mixins OO.ui.mixin.TabIndexedElement
8931 * @mixins OO.ui.mixin.TitledElement
8932 * @mixins OO.ui.mixin.AccessKeyedElement
8933 *
8934 * @constructor
8935 * @param {Object} [config] Configuration options
8936 * @cfg {string} [name=''] The value of the input’s HTML `name` attribute.
8937 * @cfg {string} [value=''] The value of the input.
8938 * @cfg {string} [dir] The directionality of the input (ltr/rtl).
8939 * @cfg {string} [inputId] The value of the input’s HTML `id` attribute.
8940 * @cfg {Function} [inputFilter] The name of an input filter function. Input filters modify the
8941 * value of an input before it is accepted.
8942 */
8943 OO.ui.InputWidget = function OoUiInputWidget( config ) {
8944 // Configuration initialization
8945 config = config || {};
8946
8947 // Parent constructor
8948 OO.ui.InputWidget.parent.call( this, config );
8949
8950 // Properties
8951 // See #reusePreInfuseDOM about config.$input
8952 this.$input = config.$input || this.getInputElement( config );
8953 this.value = '';
8954 this.inputFilter = config.inputFilter;
8955
8956 // Mixin constructors
8957 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {
8958 $tabIndexed: this.$input
8959 }, config ) );
8960 OO.ui.mixin.TitledElement.call( this, $.extend( {
8961 $titled: this.$input
8962 }, config ) );
8963 OO.ui.mixin.AccessKeyedElement.call( this, $.extend( {
8964 $accessKeyed: this.$input
8965 }, config ) );
8966
8967 // Events
8968 this.$input.on( 'keydown mouseup cut paste change input select', this.onEdit.bind( this ) );
8969
8970 // Initialization
8971 this.$input
8972 .addClass( 'oo-ui-inputWidget-input' )
8973 .attr( 'name', config.name )
8974 .prop( 'disabled', this.isDisabled() );
8975 this.$element
8976 .addClass( 'oo-ui-inputWidget' )
8977 .append( this.$input );
8978 this.setValue( config.value );
8979 if ( config.dir ) {
8980 this.setDir( config.dir );
8981 }
8982 if ( config.inputId !== undefined ) {
8983 this.setInputId( config.inputId );
8984 }
8985 };
8986
8987 /* Setup */
8988
8989 OO.inheritClass( OO.ui.InputWidget, OO.ui.Widget );
8990 OO.mixinClass( OO.ui.InputWidget, OO.ui.mixin.TabIndexedElement );
8991 OO.mixinClass( OO.ui.InputWidget, OO.ui.mixin.TitledElement );
8992 OO.mixinClass( OO.ui.InputWidget, OO.ui.mixin.AccessKeyedElement );
8993
8994 /* Static Methods */
8995
8996 /**
8997 * @inheritdoc
8998 */
8999 OO.ui.InputWidget.static.reusePreInfuseDOM = function ( node, config ) {
9000 config = OO.ui.InputWidget.parent.static.reusePreInfuseDOM( node, config );
9001 // Reusing `$input` lets browsers preserve inputted values across page reloads, see T114134.
9002 config.$input = $( node ).find( '.oo-ui-inputWidget-input' );
9003 return config;
9004 };
9005
9006 /**
9007 * @inheritdoc
9008 */
9009 OO.ui.InputWidget.static.gatherPreInfuseState = function ( node, config ) {
9010 var state = OO.ui.InputWidget.parent.static.gatherPreInfuseState( node, config );
9011 if ( config.$input && config.$input.length ) {
9012 state.value = config.$input.val();
9013 // Might be better in TabIndexedElement, but it's awkward to do there because
9014 // mixins are awkward
9015 state.focus = config.$input.is( ':focus' );
9016 }
9017 return state;
9018 };
9019
9020 /* Events */
9021
9022 /**
9023 * @event change
9024 *
9025 * A change event is emitted when the value of the input changes.
9026 *
9027 * @param {string} value
9028 */
9029
9030 /* Methods */
9031
9032 /**
9033 * Get input element.
9034 *
9035 * Subclasses of OO.ui.InputWidget use the `config` parameter to produce different elements in
9036 * different circumstances. The element must have a `value` property (like form elements).
9037 *
9038 * @protected
9039 * @param {Object} config Configuration options
9040 * @return {jQuery} Input element
9041 */
9042 OO.ui.InputWidget.prototype.getInputElement = function () {
9043 return $( '<input>' );
9044 };
9045
9046 /**
9047 * Handle potentially value-changing events.
9048 *
9049 * @private
9050 * @param {jQuery.Event} e Key down, mouse up, cut, paste, change, input, or select event
9051 */
9052 OO.ui.InputWidget.prototype.onEdit = function () {
9053 var widget = this;
9054 if ( !this.isDisabled() ) {
9055 // Allow the stack to clear so the value will be updated
9056 setTimeout( function () {
9057 widget.setValue( widget.$input.val() );
9058 } );
9059 }
9060 };
9061
9062 /**
9063 * Get the value of the input.
9064 *
9065 * @return {string} Input value
9066 */
9067 OO.ui.InputWidget.prototype.getValue = function () {
9068 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
9069 // it, and we won't know unless they're kind enough to trigger a 'change' event.
9070 var value = this.$input.val();
9071 if ( this.value !== value ) {
9072 this.setValue( value );
9073 }
9074 return this.value;
9075 };
9076
9077 /**
9078 * Set the directionality of the input.
9079 *
9080 * @param {string} dir Text directionality: 'ltr', 'rtl' or 'auto'
9081 * @chainable
9082 * @return {OO.ui.Widget} The widget, for chaining
9083 */
9084 OO.ui.InputWidget.prototype.setDir = function ( dir ) {
9085 this.$input.prop( 'dir', dir );
9086 return this;
9087 };
9088
9089 /**
9090 * Set the value of the input.
9091 *
9092 * @param {string} value New value
9093 * @fires change
9094 * @chainable
9095 * @return {OO.ui.Widget} The widget, for chaining
9096 */
9097 OO.ui.InputWidget.prototype.setValue = function ( value ) {
9098 value = this.cleanUpValue( value );
9099 // Update the DOM if it has changed. Note that with cleanUpValue, it
9100 // is possible for the DOM value to change without this.value changing.
9101 if ( this.$input.val() !== value ) {
9102 this.$input.val( value );
9103 }
9104 if ( this.value !== value ) {
9105 this.value = value;
9106 this.emit( 'change', this.value );
9107 }
9108 // The first time that the value is set (probably while constructing the widget),
9109 // remember it in defaultValue. This property can be later used to check whether
9110 // the value of the input has been changed since it was created.
9111 if ( this.defaultValue === undefined ) {
9112 this.defaultValue = this.value;
9113 this.$input[ 0 ].defaultValue = this.defaultValue;
9114 }
9115 return this;
9116 };
9117
9118 /**
9119 * Clean up incoming value.
9120 *
9121 * Ensures value is a string, and converts undefined and null to empty string.
9122 *
9123 * @private
9124 * @param {string} value Original value
9125 * @return {string} Cleaned up value
9126 */
9127 OO.ui.InputWidget.prototype.cleanUpValue = function ( value ) {
9128 if ( value === undefined || value === null ) {
9129 return '';
9130 } else if ( this.inputFilter ) {
9131 return this.inputFilter( String( value ) );
9132 } else {
9133 return String( value );
9134 }
9135 };
9136
9137 /**
9138 * @inheritdoc
9139 */
9140 OO.ui.InputWidget.prototype.setDisabled = function ( state ) {
9141 OO.ui.InputWidget.parent.prototype.setDisabled.call( this, state );
9142 if ( this.$input ) {
9143 this.$input.prop( 'disabled', this.isDisabled() );
9144 }
9145 return this;
9146 };
9147
9148 /**
9149 * Set the 'id' attribute of the `<input>` element.
9150 *
9151 * @param {string} id
9152 * @chainable
9153 * @return {OO.ui.Widget} The widget, for chaining
9154 */
9155 OO.ui.InputWidget.prototype.setInputId = function ( id ) {
9156 this.$input.attr( 'id', id );
9157 return this;
9158 };
9159
9160 /**
9161 * @inheritdoc
9162 */
9163 OO.ui.InputWidget.prototype.restorePreInfuseState = function ( state ) {
9164 OO.ui.InputWidget.parent.prototype.restorePreInfuseState.call( this, state );
9165 if ( state.value !== undefined && state.value !== this.getValue() ) {
9166 this.setValue( state.value );
9167 }
9168 if ( state.focus ) {
9169 this.focus();
9170 }
9171 };
9172
9173 /**
9174 * Data widget intended for creating `<input type="hidden">` inputs.
9175 *
9176 * @class
9177 * @extends OO.ui.Widget
9178 *
9179 * @constructor
9180 * @param {Object} [config] Configuration options
9181 * @cfg {string} [value=''] The value of the input.
9182 * @cfg {string} [name=''] The value of the input’s HTML `name` attribute.
9183 */
9184 OO.ui.HiddenInputWidget = function OoUiHiddenInputWidget( config ) {
9185 // Configuration initialization
9186 config = $.extend( { value: '', name: '' }, config );
9187
9188 // Parent constructor
9189 OO.ui.HiddenInputWidget.parent.call( this, config );
9190
9191 // Initialization
9192 this.$element.attr( {
9193 type: 'hidden',
9194 value: config.value,
9195 name: config.name
9196 } );
9197 this.$element.removeAttr( 'aria-disabled' );
9198 };
9199
9200 /* Setup */
9201
9202 OO.inheritClass( OO.ui.HiddenInputWidget, OO.ui.Widget );
9203
9204 /* Static Properties */
9205
9206 /**
9207 * @static
9208 * @inheritdoc
9209 */
9210 OO.ui.HiddenInputWidget.static.tagName = 'input';
9211
9212 /**
9213 * ButtonInputWidget is used to submit HTML forms and is intended to be used within
9214 * a OO.ui.FormLayout. If you do not need the button to work with HTML forms, you probably
9215 * want to use OO.ui.ButtonWidget instead. Button input widgets can be rendered as either an
9216 * HTML `<button>` (the default) or an HTML `<input>` tags. See the
9217 * [OOUI documentation on MediaWiki] [1] for more information.
9218 *
9219 * @example
9220 * // A ButtonInputWidget rendered as an HTML button, the default.
9221 * var button = new OO.ui.ButtonInputWidget( {
9222 * label: 'Input button',
9223 * icon: 'check',
9224 * value: 'check'
9225 * } );
9226 * $( document.body ).append( button.$element );
9227 *
9228 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs#Button_inputs
9229 *
9230 * @class
9231 * @extends OO.ui.InputWidget
9232 * @mixins OO.ui.mixin.ButtonElement
9233 * @mixins OO.ui.mixin.IconElement
9234 * @mixins OO.ui.mixin.IndicatorElement
9235 * @mixins OO.ui.mixin.LabelElement
9236 * @mixins OO.ui.mixin.FlaggedElement
9237 *
9238 * @constructor
9239 * @param {Object} [config] Configuration options
9240 * @cfg {string} [type='button'] The value of the HTML `'type'` attribute:
9241 * 'button', 'submit' or 'reset'.
9242 * @cfg {boolean} [useInputTag=false] Use an `<input>` tag instead of a `<button>` tag, the default.
9243 * Widgets configured to be an `<input>` do not support {@link #icon icons} and
9244 * {@link #indicator indicators},
9245 * non-plaintext {@link #label labels}, or {@link #value values}. In general, useInputTag should
9246 * only be set to `true` when there’s need to support IE 6 in a form with multiple buttons.
9247 */
9248 OO.ui.ButtonInputWidget = function OoUiButtonInputWidget( config ) {
9249 // Configuration initialization
9250 config = $.extend( { type: 'button', useInputTag: false }, config );
9251
9252 // See InputWidget#reusePreInfuseDOM about config.$input
9253 if ( config.$input ) {
9254 config.$input.empty();
9255 }
9256
9257 // Properties (must be set before parent constructor, which calls #setValue)
9258 this.useInputTag = config.useInputTag;
9259
9260 // Parent constructor
9261 OO.ui.ButtonInputWidget.parent.call( this, config );
9262
9263 // Mixin constructors
9264 OO.ui.mixin.ButtonElement.call( this, $.extend( {
9265 $button: this.$input
9266 }, config ) );
9267 OO.ui.mixin.IconElement.call( this, config );
9268 OO.ui.mixin.IndicatorElement.call( this, config );
9269 OO.ui.mixin.LabelElement.call( this, config );
9270 OO.ui.mixin.FlaggedElement.call( this, config );
9271
9272 // Initialization
9273 if ( !config.useInputTag ) {
9274 this.$input.append( this.$icon, this.$label, this.$indicator );
9275 }
9276 this.$element.addClass( 'oo-ui-buttonInputWidget' );
9277 };
9278
9279 /* Setup */
9280
9281 OO.inheritClass( OO.ui.ButtonInputWidget, OO.ui.InputWidget );
9282 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.ButtonElement );
9283 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.IconElement );
9284 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.IndicatorElement );
9285 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.LabelElement );
9286 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.FlaggedElement );
9287
9288 /* Static Properties */
9289
9290 /**
9291 * @static
9292 * @inheritdoc
9293 */
9294 OO.ui.ButtonInputWidget.static.tagName = 'span';
9295
9296 /* Methods */
9297
9298 /**
9299 * @inheritdoc
9300 * @protected
9301 */
9302 OO.ui.ButtonInputWidget.prototype.getInputElement = function ( config ) {
9303 var type;
9304 type = [ 'button', 'submit', 'reset' ].indexOf( config.type ) !== -1 ? config.type : 'button';
9305 return $( '<' + ( config.useInputTag ? 'input' : 'button' ) + ' type="' + type + '">' );
9306 };
9307
9308 /**
9309 * Set label value.
9310 *
9311 * If #useInputTag is `true`, the label is set as the `value` of the `<input>` tag.
9312 *
9313 * @param {jQuery|string|Function|null} label Label nodes, text, a function that returns nodes or
9314 * text, or `null` for no label
9315 * @chainable
9316 * @return {OO.ui.Widget} The widget, for chaining
9317 */
9318 OO.ui.ButtonInputWidget.prototype.setLabel = function ( label ) {
9319 if ( typeof label === 'function' ) {
9320 label = OO.ui.resolveMsg( label );
9321 }
9322
9323 if ( this.useInputTag ) {
9324 // Discard non-plaintext labels
9325 if ( typeof label !== 'string' ) {
9326 label = '';
9327 }
9328
9329 this.$input.val( label );
9330 }
9331
9332 return OO.ui.mixin.LabelElement.prototype.setLabel.call( this, label );
9333 };
9334
9335 /**
9336 * Set the value of the input.
9337 *
9338 * This method is disabled for button inputs configured as {@link #useInputTag <input> tags}, as
9339 * they do not support {@link #value values}.
9340 *
9341 * @param {string} value New value
9342 * @chainable
9343 * @return {OO.ui.Widget} The widget, for chaining
9344 */
9345 OO.ui.ButtonInputWidget.prototype.setValue = function ( value ) {
9346 if ( !this.useInputTag ) {
9347 OO.ui.ButtonInputWidget.parent.prototype.setValue.call( this, value );
9348 }
9349 return this;
9350 };
9351
9352 /**
9353 * @inheritdoc
9354 */
9355 OO.ui.ButtonInputWidget.prototype.getInputId = function () {
9356 // Disable generating `<label>` elements for buttons. One would very rarely need additional
9357 // label for a button, and it's already a big clickable target, and it causes
9358 // unexpected rendering.
9359 return null;
9360 };
9361
9362 /**
9363 * CheckboxInputWidgets, like HTML checkboxes, can be selected and/or configured with a value.
9364 * Note that these {@link OO.ui.InputWidget input widgets} are best laid out
9365 * in {@link OO.ui.FieldLayout field layouts} that use the {@link OO.ui.FieldLayout#align inline}
9366 * alignment. For more information, please see the [OOUI documentation on MediaWiki][1].
9367 *
9368 * This widget can be used inside an HTML form, such as a OO.ui.FormLayout.
9369 *
9370 * @example
9371 * // An example of selected, unselected, and disabled checkbox inputs.
9372 * var checkbox1 = new OO.ui.CheckboxInputWidget( {
9373 * value: 'a',
9374 * selected: true
9375 * } ),
9376 * checkbox2 = new OO.ui.CheckboxInputWidget( {
9377 * value: 'b'
9378 * } ),
9379 * checkbox3 = new OO.ui.CheckboxInputWidget( {
9380 * value:'c',
9381 * disabled: true
9382 * } ),
9383 * // Create a fieldset layout with fields for each checkbox.
9384 * fieldset = new OO.ui.FieldsetLayout( {
9385 * label: 'Checkboxes'
9386 * } );
9387 * fieldset.addItems( [
9388 * new OO.ui.FieldLayout( checkbox1, { label: 'Selected checkbox', align: 'inline' } ),
9389 * new OO.ui.FieldLayout( checkbox2, { label: 'Unselected checkbox', align: 'inline' } ),
9390 * new OO.ui.FieldLayout( checkbox3, { label: 'Disabled checkbox', align: 'inline' } ),
9391 * ] );
9392 * $( document.body ).append( fieldset.$element );
9393 *
9394 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
9395 *
9396 * @class
9397 * @extends OO.ui.InputWidget
9398 *
9399 * @constructor
9400 * @param {Object} [config] Configuration options
9401 * @cfg {boolean} [selected=false] Select the checkbox initially. By default, the checkbox is
9402 * not selected.
9403 */
9404 OO.ui.CheckboxInputWidget = function OoUiCheckboxInputWidget( config ) {
9405 // Configuration initialization
9406 config = config || {};
9407
9408 // Parent constructor
9409 OO.ui.CheckboxInputWidget.parent.call( this, config );
9410
9411 // Properties
9412 this.checkIcon = new OO.ui.IconWidget( {
9413 icon: 'check',
9414 classes: [ 'oo-ui-checkboxInputWidget-checkIcon' ]
9415 } );
9416
9417 // Initialization
9418 this.$element
9419 .addClass( 'oo-ui-checkboxInputWidget' )
9420 // Required for pretty styling in WikimediaUI theme
9421 .append( this.checkIcon.$element );
9422 this.setSelected( config.selected !== undefined ? config.selected : false );
9423 };
9424
9425 /* Setup */
9426
9427 OO.inheritClass( OO.ui.CheckboxInputWidget, OO.ui.InputWidget );
9428
9429 /* Static Properties */
9430
9431 /**
9432 * @static
9433 * @inheritdoc
9434 */
9435 OO.ui.CheckboxInputWidget.static.tagName = 'span';
9436
9437 /* Static Methods */
9438
9439 /**
9440 * @inheritdoc
9441 */
9442 OO.ui.CheckboxInputWidget.static.gatherPreInfuseState = function ( node, config ) {
9443 var state = OO.ui.CheckboxInputWidget.parent.static.gatherPreInfuseState( node, config );
9444 state.checked = config.$input.prop( 'checked' );
9445 return state;
9446 };
9447
9448 /* Methods */
9449
9450 /**
9451 * @inheritdoc
9452 * @protected
9453 */
9454 OO.ui.CheckboxInputWidget.prototype.getInputElement = function () {
9455 return $( '<input>' ).attr( 'type', 'checkbox' );
9456 };
9457
9458 /**
9459 * @inheritdoc
9460 */
9461 OO.ui.CheckboxInputWidget.prototype.onEdit = function () {
9462 var widget = this;
9463 if ( !this.isDisabled() ) {
9464 // Allow the stack to clear so the value will be updated
9465 setTimeout( function () {
9466 widget.setSelected( widget.$input.prop( 'checked' ) );
9467 } );
9468 }
9469 };
9470
9471 /**
9472 * Set selection state of this checkbox.
9473 *
9474 * @param {boolean} state `true` for selected
9475 * @chainable
9476 * @return {OO.ui.Widget} The widget, for chaining
9477 */
9478 OO.ui.CheckboxInputWidget.prototype.setSelected = function ( state ) {
9479 state = !!state;
9480 if ( this.selected !== state ) {
9481 this.selected = state;
9482 this.$input.prop( 'checked', this.selected );
9483 this.emit( 'change', this.selected );
9484 }
9485 // The first time that the selection state is set (probably while constructing the widget),
9486 // remember it in defaultSelected. This property can be later used to check whether
9487 // the selection state of the input has been changed since it was created.
9488 if ( this.defaultSelected === undefined ) {
9489 this.defaultSelected = this.selected;
9490 this.$input[ 0 ].defaultChecked = this.defaultSelected;
9491 }
9492 return this;
9493 };
9494
9495 /**
9496 * Check if this checkbox is selected.
9497 *
9498 * @return {boolean} Checkbox is selected
9499 */
9500 OO.ui.CheckboxInputWidget.prototype.isSelected = function () {
9501 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
9502 // it, and we won't know unless they're kind enough to trigger a 'change' event.
9503 var selected = this.$input.prop( 'checked' );
9504 if ( this.selected !== selected ) {
9505 this.setSelected( selected );
9506 }
9507 return this.selected;
9508 };
9509
9510 /**
9511 * @inheritdoc
9512 */
9513 OO.ui.CheckboxInputWidget.prototype.simulateLabelClick = function () {
9514 if ( !this.isDisabled() ) {
9515 this.$handle.trigger( 'click' );
9516 }
9517 this.focus();
9518 };
9519
9520 /**
9521 * @inheritdoc
9522 */
9523 OO.ui.CheckboxInputWidget.prototype.restorePreInfuseState = function ( state ) {
9524 OO.ui.CheckboxInputWidget.parent.prototype.restorePreInfuseState.call( this, state );
9525 if ( state.checked !== undefined && state.checked !== this.isSelected() ) {
9526 this.setSelected( state.checked );
9527 }
9528 };
9529
9530 /**
9531 * DropdownInputWidget is a {@link OO.ui.DropdownWidget DropdownWidget} intended to be used
9532 * within an HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with the
9533 * value of a hidden HTML `input` tag. Please see the [OOUI documentation on MediaWiki][1] for
9534 * more information about input widgets.
9535 *
9536 * A DropdownInputWidget always has a value (one of the options is always selected), unless there
9537 * are no options. If no `value` configuration option is provided, the first option is selected.
9538 * If you need a state representing no value (no option being selected), use a DropdownWidget.
9539 *
9540 * This and OO.ui.RadioSelectInputWidget support similar configuration options.
9541 *
9542 * @example
9543 * // A DropdownInputWidget with three options.
9544 * var dropdownInput = new OO.ui.DropdownInputWidget( {
9545 * options: [
9546 * { data: 'a', label: 'First' },
9547 * { data: 'b', label: 'Second', disabled: true },
9548 * { optgroup: 'Group label' },
9549 * { data: 'c', label: 'First sub-item)' }
9550 * ]
9551 * } );
9552 * $( document.body ).append( dropdownInput.$element );
9553 *
9554 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
9555 *
9556 * @class
9557 * @extends OO.ui.InputWidget
9558 *
9559 * @constructor
9560 * @param {Object} [config] Configuration options
9561 * @cfg {Object[]} [options=[]] Array of menu options in the format described above.
9562 * @cfg {Object} [dropdown] Configuration options for {@link OO.ui.DropdownWidget DropdownWidget}
9563 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful
9564 * in cases where the expanded menu is larger than its containing `<div>`. The specified overlay
9565 * layer is usually on top of the containing `<div>` and has a larger area. By default, the menu
9566 * uses relative positioning.
9567 * See <https://www.mediawiki.org/wiki/OOUI/Concepts#Overlays>.
9568 */
9569 OO.ui.DropdownInputWidget = function OoUiDropdownInputWidget( config ) {
9570 // Configuration initialization
9571 config = config || {};
9572
9573 // Properties (must be done before parent constructor which calls #setDisabled)
9574 this.dropdownWidget = new OO.ui.DropdownWidget( $.extend(
9575 {
9576 $overlay: config.$overlay
9577 },
9578 config.dropdown
9579 ) );
9580 // Set up the options before parent constructor, which uses them to validate config.value.
9581 // Use this instead of setOptions() because this.$input is not set up yet.
9582 this.setOptionsData( config.options || [] );
9583
9584 // Parent constructor
9585 OO.ui.DropdownInputWidget.parent.call( this, config );
9586
9587 // Events
9588 this.dropdownWidget.getMenu().connect( this, {
9589 select: 'onMenuSelect'
9590 } );
9591
9592 // Initialization
9593 this.$element
9594 .addClass( 'oo-ui-dropdownInputWidget' )
9595 .append( this.dropdownWidget.$element );
9596 this.setTabIndexedElement( this.dropdownWidget.$tabIndexed );
9597 this.setTitledElement( this.dropdownWidget.$handle );
9598 };
9599
9600 /* Setup */
9601
9602 OO.inheritClass( OO.ui.DropdownInputWidget, OO.ui.InputWidget );
9603
9604 /* Methods */
9605
9606 /**
9607 * @inheritdoc
9608 * @protected
9609 */
9610 OO.ui.DropdownInputWidget.prototype.getInputElement = function () {
9611 return $( '<select>' );
9612 };
9613
9614 /**
9615 * Handles menu select events.
9616 *
9617 * @private
9618 * @param {OO.ui.MenuOptionWidget|null} item Selected menu item
9619 */
9620 OO.ui.DropdownInputWidget.prototype.onMenuSelect = function ( item ) {
9621 this.setValue( item ? item.getData() : '' );
9622 };
9623
9624 /**
9625 * @inheritdoc
9626 */
9627 OO.ui.DropdownInputWidget.prototype.setValue = function ( value ) {
9628 var selected;
9629 value = this.cleanUpValue( value );
9630 // Only allow setting values that are actually present in the dropdown
9631 selected = this.dropdownWidget.getMenu().findItemFromData( value ) ||
9632 this.dropdownWidget.getMenu().findFirstSelectableItem();
9633 this.dropdownWidget.getMenu().selectItem( selected );
9634 value = selected ? selected.getData() : '';
9635 OO.ui.DropdownInputWidget.parent.prototype.setValue.call( this, value );
9636 if ( this.optionsDirty ) {
9637 // We reached this from the constructor or from #setOptions.
9638 // We have to update the <select> element.
9639 this.updateOptionsInterface();
9640 }
9641 return this;
9642 };
9643
9644 /**
9645 * @inheritdoc
9646 */
9647 OO.ui.DropdownInputWidget.prototype.setDisabled = function ( state ) {
9648 this.dropdownWidget.setDisabled( state );
9649 OO.ui.DropdownInputWidget.parent.prototype.setDisabled.call( this, state );
9650 return this;
9651 };
9652
9653 /**
9654 * Set the options available for this input.
9655 *
9656 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
9657 * @chainable
9658 * @return {OO.ui.Widget} The widget, for chaining
9659 */
9660 OO.ui.DropdownInputWidget.prototype.setOptions = function ( options ) {
9661 var value = this.getValue();
9662
9663 this.setOptionsData( options );
9664
9665 // Re-set the value to update the visible interface (DropdownWidget and <select>).
9666 // In case the previous value is no longer an available option, select the first valid one.
9667 this.setValue( value );
9668
9669 return this;
9670 };
9671
9672 /**
9673 * Set the internal list of options, used e.g. by setValue() to see which options are allowed.
9674 *
9675 * This method may be called before the parent constructor, so various properties may not be
9676 * initialized yet.
9677 *
9678 * @param {Object[]} options Array of menu options (see #constructor for details).
9679 * @private
9680 */
9681 OO.ui.DropdownInputWidget.prototype.setOptionsData = function ( options ) {
9682 var optionWidgets, optIndex, opt, previousOptgroup, optionWidget, optValue,
9683 widget = this;
9684
9685 this.optionsDirty = true;
9686
9687 // Go through all the supplied option configs and create either
9688 // MenuSectionOption or MenuOption widgets from each.
9689 optionWidgets = [];
9690 for ( optIndex = 0; optIndex < options.length; optIndex++ ) {
9691 opt = options[ optIndex ];
9692
9693 if ( opt.optgroup !== undefined ) {
9694 // Create a <optgroup> menu item.
9695 optionWidget = widget.createMenuSectionOptionWidget( opt.optgroup );
9696 previousOptgroup = optionWidget;
9697
9698 } else {
9699 // Create a normal <option> menu item.
9700 optValue = widget.cleanUpValue( opt.data );
9701 optionWidget = widget.createMenuOptionWidget(
9702 optValue,
9703 opt.label !== undefined ? opt.label : optValue
9704 );
9705 }
9706
9707 // Disable the menu option if it is itself disabled or if its parent optgroup is disabled.
9708 if (
9709 opt.disabled !== undefined ||
9710 previousOptgroup instanceof OO.ui.MenuSectionOptionWidget &&
9711 previousOptgroup.isDisabled()
9712 ) {
9713 optionWidget.setDisabled( true );
9714 }
9715
9716 optionWidgets.push( optionWidget );
9717 }
9718
9719 this.dropdownWidget.getMenu().clearItems().addItems( optionWidgets );
9720 };
9721
9722 /**
9723 * Create a menu option widget.
9724 *
9725 * @protected
9726 * @param {string} data Item data
9727 * @param {string} label Item label
9728 * @return {OO.ui.MenuOptionWidget} Option widget
9729 */
9730 OO.ui.DropdownInputWidget.prototype.createMenuOptionWidget = function ( data, label ) {
9731 return new OO.ui.MenuOptionWidget( {
9732 data: data,
9733 label: label
9734 } );
9735 };
9736
9737 /**
9738 * Create a menu section option widget.
9739 *
9740 * @protected
9741 * @param {string} label Section item label
9742 * @return {OO.ui.MenuSectionOptionWidget} Menu section option widget
9743 */
9744 OO.ui.DropdownInputWidget.prototype.createMenuSectionOptionWidget = function ( label ) {
9745 return new OO.ui.MenuSectionOptionWidget( {
9746 label: label
9747 } );
9748 };
9749
9750 /**
9751 * Update the user-visible interface to match the internal list of options and value.
9752 *
9753 * This method must only be called after the parent constructor.
9754 *
9755 * @private
9756 */
9757 OO.ui.DropdownInputWidget.prototype.updateOptionsInterface = function () {
9758 var
9759 $optionsContainer = this.$input,
9760 defaultValue = this.defaultValue,
9761 widget = this;
9762
9763 this.$input.empty();
9764
9765 this.dropdownWidget.getMenu().getItems().forEach( function ( optionWidget ) {
9766 var $optionNode;
9767
9768 if ( !( optionWidget instanceof OO.ui.MenuSectionOptionWidget ) ) {
9769 $optionNode = $( '<option>' )
9770 .attr( 'value', optionWidget.getData() )
9771 .text( optionWidget.getLabel() );
9772
9773 // Remember original selection state. This property can be later used to check whether
9774 // the selection state of the input has been changed since it was created.
9775 $optionNode[ 0 ].defaultSelected = ( optionWidget.getData() === defaultValue );
9776
9777 $optionsContainer.append( $optionNode );
9778 } else {
9779 $optionNode = $( '<optgroup>' )
9780 .attr( 'label', optionWidget.getLabel() );
9781 widget.$input.append( $optionNode );
9782 $optionsContainer = $optionNode;
9783 }
9784
9785 // Disable the option or optgroup if required.
9786 if ( optionWidget.isDisabled() ) {
9787 $optionNode.prop( 'disabled', true );
9788 }
9789 } );
9790
9791 this.optionsDirty = false;
9792 };
9793
9794 /**
9795 * @inheritdoc
9796 */
9797 OO.ui.DropdownInputWidget.prototype.focus = function () {
9798 this.dropdownWidget.focus();
9799 return this;
9800 };
9801
9802 /**
9803 * @inheritdoc
9804 */
9805 OO.ui.DropdownInputWidget.prototype.blur = function () {
9806 this.dropdownWidget.blur();
9807 return this;
9808 };
9809
9810 /**
9811 * RadioInputWidget creates a single radio button. Because radio buttons are usually used as a set,
9812 * in most cases you will want to use a {@link OO.ui.RadioSelectWidget radio select}
9813 * with {@link OO.ui.RadioOptionWidget radio options} instead of this class. For more information,
9814 * please see the [OOUI documentation on MediaWiki][1].
9815 *
9816 * This widget can be used inside an HTML form, such as a OO.ui.FormLayout.
9817 *
9818 * @example
9819 * // An example of selected, unselected, and disabled radio inputs
9820 * var radio1 = new OO.ui.RadioInputWidget( {
9821 * value: 'a',
9822 * selected: true
9823 * } );
9824 * var radio2 = new OO.ui.RadioInputWidget( {
9825 * value: 'b'
9826 * } );
9827 * var radio3 = new OO.ui.RadioInputWidget( {
9828 * value: 'c',
9829 * disabled: true
9830 * } );
9831 * // Create a fieldset layout with fields for each radio button.
9832 * var fieldset = new OO.ui.FieldsetLayout( {
9833 * label: 'Radio inputs'
9834 * } );
9835 * fieldset.addItems( [
9836 * new OO.ui.FieldLayout( radio1, { label: 'Selected', align: 'inline' } ),
9837 * new OO.ui.FieldLayout( radio2, { label: 'Unselected', align: 'inline' } ),
9838 * new OO.ui.FieldLayout( radio3, { label: 'Disabled', align: 'inline' } ),
9839 * ] );
9840 * $( document.body ).append( fieldset.$element );
9841 *
9842 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
9843 *
9844 * @class
9845 * @extends OO.ui.InputWidget
9846 *
9847 * @constructor
9848 * @param {Object} [config] Configuration options
9849 * @cfg {boolean} [selected=false] Select the radio button initially. By default, the radio button
9850 * is not selected.
9851 */
9852 OO.ui.RadioInputWidget = function OoUiRadioInputWidget( config ) {
9853 // Configuration initialization
9854 config = config || {};
9855
9856 // Parent constructor
9857 OO.ui.RadioInputWidget.parent.call( this, config );
9858
9859 // Initialization
9860 this.$element
9861 .addClass( 'oo-ui-radioInputWidget' )
9862 // Required for pretty styling in WikimediaUI theme
9863 .append( $( '<span>' ) );
9864 this.setSelected( config.selected !== undefined ? config.selected : false );
9865 };
9866
9867 /* Setup */
9868
9869 OO.inheritClass( OO.ui.RadioInputWidget, OO.ui.InputWidget );
9870
9871 /* Static Properties */
9872
9873 /**
9874 * @static
9875 * @inheritdoc
9876 */
9877 OO.ui.RadioInputWidget.static.tagName = 'span';
9878
9879 /* Static Methods */
9880
9881 /**
9882 * @inheritdoc
9883 */
9884 OO.ui.RadioInputWidget.static.gatherPreInfuseState = function ( node, config ) {
9885 var state = OO.ui.RadioInputWidget.parent.static.gatherPreInfuseState( node, config );
9886 state.checked = config.$input.prop( 'checked' );
9887 return state;
9888 };
9889
9890 /* Methods */
9891
9892 /**
9893 * @inheritdoc
9894 * @protected
9895 */
9896 OO.ui.RadioInputWidget.prototype.getInputElement = function () {
9897 return $( '<input>' ).attr( 'type', 'radio' );
9898 };
9899
9900 /**
9901 * @inheritdoc
9902 */
9903 OO.ui.RadioInputWidget.prototype.onEdit = function () {
9904 // RadioInputWidget doesn't track its state.
9905 };
9906
9907 /**
9908 * Set selection state of this radio button.
9909 *
9910 * @param {boolean} state `true` for selected
9911 * @chainable
9912 * @return {OO.ui.Widget} The widget, for chaining
9913 */
9914 OO.ui.RadioInputWidget.prototype.setSelected = function ( state ) {
9915 // RadioInputWidget doesn't track its state.
9916 this.$input.prop( 'checked', state );
9917 // The first time that the selection state is set (probably while constructing the widget),
9918 // remember it in defaultSelected. This property can be later used to check whether
9919 // the selection state of the input has been changed since it was created.
9920 if ( this.defaultSelected === undefined ) {
9921 this.defaultSelected = state;
9922 this.$input[ 0 ].defaultChecked = this.defaultSelected;
9923 }
9924 return this;
9925 };
9926
9927 /**
9928 * Check if this radio button is selected.
9929 *
9930 * @return {boolean} Radio is selected
9931 */
9932 OO.ui.RadioInputWidget.prototype.isSelected = function () {
9933 return this.$input.prop( 'checked' );
9934 };
9935
9936 /**
9937 * @inheritdoc
9938 */
9939 OO.ui.RadioInputWidget.prototype.simulateLabelClick = function () {
9940 if ( !this.isDisabled() ) {
9941 this.$input.trigger( 'click' );
9942 }
9943 this.focus();
9944 };
9945
9946 /**
9947 * @inheritdoc
9948 */
9949 OO.ui.RadioInputWidget.prototype.restorePreInfuseState = function ( state ) {
9950 OO.ui.RadioInputWidget.parent.prototype.restorePreInfuseState.call( this, state );
9951 if ( state.checked !== undefined && state.checked !== this.isSelected() ) {
9952 this.setSelected( state.checked );
9953 }
9954 };
9955
9956 /**
9957 * RadioSelectInputWidget is a {@link OO.ui.RadioSelectWidget RadioSelectWidget} intended to be
9958 * used within an HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with
9959 * the value of a hidden HTML `input` tag. Please see the [OOUI documentation on MediaWiki][1] for
9960 * more information about input widgets.
9961 *
9962 * This and OO.ui.DropdownInputWidget support similar configuration options.
9963 *
9964 * @example
9965 * // A RadioSelectInputWidget with three options
9966 * var radioSelectInput = new OO.ui.RadioSelectInputWidget( {
9967 * options: [
9968 * { data: 'a', label: 'First' },
9969 * { data: 'b', label: 'Second'},
9970 * { data: 'c', label: 'Third' }
9971 * ]
9972 * } );
9973 * $( document.body ).append( radioSelectInput.$element );
9974 *
9975 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
9976 *
9977 * @class
9978 * @extends OO.ui.InputWidget
9979 *
9980 * @constructor
9981 * @param {Object} [config] Configuration options
9982 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
9983 */
9984 OO.ui.RadioSelectInputWidget = function OoUiRadioSelectInputWidget( config ) {
9985 // Configuration initialization
9986 config = config || {};
9987
9988 // Properties (must be done before parent constructor which calls #setDisabled)
9989 this.radioSelectWidget = new OO.ui.RadioSelectWidget();
9990 // Set up the options before parent constructor, which uses them to validate config.value.
9991 // Use this instead of setOptions() because this.$input is not set up yet
9992 this.setOptionsData( config.options || [] );
9993
9994 // Parent constructor
9995 OO.ui.RadioSelectInputWidget.parent.call( this, config );
9996
9997 // Events
9998 this.radioSelectWidget.connect( this, {
9999 select: 'onMenuSelect'
10000 } );
10001
10002 // Initialization
10003 this.$element
10004 .addClass( 'oo-ui-radioSelectInputWidget' )
10005 .append( this.radioSelectWidget.$element );
10006 this.setTabIndexedElement( this.radioSelectWidget.$tabIndexed );
10007 };
10008
10009 /* Setup */
10010
10011 OO.inheritClass( OO.ui.RadioSelectInputWidget, OO.ui.InputWidget );
10012
10013 /* Static Methods */
10014
10015 /**
10016 * @inheritdoc
10017 */
10018 OO.ui.RadioSelectInputWidget.static.gatherPreInfuseState = function ( node, config ) {
10019 var state = OO.ui.RadioSelectInputWidget.parent.static.gatherPreInfuseState( node, config );
10020 state.value = $( node ).find( '.oo-ui-radioInputWidget .oo-ui-inputWidget-input:checked' ).val();
10021 return state;
10022 };
10023
10024 /**
10025 * @inheritdoc
10026 */
10027 OO.ui.RadioSelectInputWidget.static.reusePreInfuseDOM = function ( node, config ) {
10028 config = OO.ui.RadioSelectInputWidget.parent.static.reusePreInfuseDOM( node, config );
10029 // Cannot reuse the `<input type=radio>` set
10030 delete config.$input;
10031 return config;
10032 };
10033
10034 /* Methods */
10035
10036 /**
10037 * @inheritdoc
10038 * @protected
10039 */
10040 OO.ui.RadioSelectInputWidget.prototype.getInputElement = function () {
10041 // Use this instead of <input type="hidden">, because hidden inputs do not have separate
10042 // 'value' and 'defaultValue' properties, and InputWidget wants to handle 'defaultValue'.
10043 return $( '<input>' ).addClass( 'oo-ui-element-hidden' );
10044 };
10045
10046 /**
10047 * Handles menu select events.
10048 *
10049 * @private
10050 * @param {OO.ui.RadioOptionWidget} item Selected menu item
10051 */
10052 OO.ui.RadioSelectInputWidget.prototype.onMenuSelect = function ( item ) {
10053 this.setValue( item.getData() );
10054 };
10055
10056 /**
10057 * @inheritdoc
10058 */
10059 OO.ui.RadioSelectInputWidget.prototype.setValue = function ( value ) {
10060 var selected;
10061 value = this.cleanUpValue( value );
10062 // Only allow setting values that are actually present in the dropdown
10063 selected = this.radioSelectWidget.findItemFromData( value ) ||
10064 this.radioSelectWidget.findFirstSelectableItem();
10065 this.radioSelectWidget.selectItem( selected );
10066 value = selected ? selected.getData() : '';
10067 OO.ui.RadioSelectInputWidget.parent.prototype.setValue.call( this, value );
10068 return this;
10069 };
10070
10071 /**
10072 * @inheritdoc
10073 */
10074 OO.ui.RadioSelectInputWidget.prototype.setDisabled = function ( state ) {
10075 this.radioSelectWidget.setDisabled( state );
10076 OO.ui.RadioSelectInputWidget.parent.prototype.setDisabled.call( this, state );
10077 return this;
10078 };
10079
10080 /**
10081 * Set the options available for this input.
10082 *
10083 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
10084 * @chainable
10085 * @return {OO.ui.Widget} The widget, for chaining
10086 */
10087 OO.ui.RadioSelectInputWidget.prototype.setOptions = function ( options ) {
10088 var value = this.getValue();
10089
10090 this.setOptionsData( options );
10091
10092 // Re-set the value to update the visible interface (RadioSelectWidget).
10093 // In case the previous value is no longer an available option, select the first valid one.
10094 this.setValue( value );
10095
10096 return this;
10097 };
10098
10099 /**
10100 * Set the internal list of options, used e.g. by setValue() to see which options are allowed.
10101 *
10102 * This method may be called before the parent constructor, so various properties may not be
10103 * intialized yet.
10104 *
10105 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
10106 * @private
10107 */
10108 OO.ui.RadioSelectInputWidget.prototype.setOptionsData = function ( options ) {
10109 var widget = this;
10110
10111 this.radioSelectWidget
10112 .clearItems()
10113 .addItems( options.map( function ( opt ) {
10114 var optValue = widget.cleanUpValue( opt.data );
10115 return new OO.ui.RadioOptionWidget( {
10116 data: optValue,
10117 label: opt.label !== undefined ? opt.label : optValue
10118 } );
10119 } ) );
10120 };
10121
10122 /**
10123 * @inheritdoc
10124 */
10125 OO.ui.RadioSelectInputWidget.prototype.focus = function () {
10126 this.radioSelectWidget.focus();
10127 return this;
10128 };
10129
10130 /**
10131 * @inheritdoc
10132 */
10133 OO.ui.RadioSelectInputWidget.prototype.blur = function () {
10134 this.radioSelectWidget.blur();
10135 return this;
10136 };
10137
10138 /**
10139 * CheckboxMultiselectInputWidget is a
10140 * {@link OO.ui.CheckboxMultiselectWidget CheckboxMultiselectWidget} intended to be used within a
10141 * HTML form, such as a OO.ui.FormLayout. The selected values are synchronized with the value of
10142 * HTML `<input type=checkbox>` tags. Please see the [OOUI documentation on MediaWiki][1] for
10143 * more information about input widgets.
10144 *
10145 * @example
10146 * // A CheckboxMultiselectInputWidget with three options.
10147 * var multiselectInput = new OO.ui.CheckboxMultiselectInputWidget( {
10148 * options: [
10149 * { data: 'a', label: 'First' },
10150 * { data: 'b', label: 'Second' },
10151 * { data: 'c', label: 'Third' }
10152 * ]
10153 * } );
10154 * $( document.body ).append( multiselectInput.$element );
10155 *
10156 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
10157 *
10158 * @class
10159 * @extends OO.ui.InputWidget
10160 *
10161 * @constructor
10162 * @param {Object} [config] Configuration options
10163 * @cfg {Object[]} [options=[]] Array of menu options in the format
10164 * `{ data: …, label: …, disabled: … }`
10165 */
10166 OO.ui.CheckboxMultiselectInputWidget = function OoUiCheckboxMultiselectInputWidget( config ) {
10167 // Configuration initialization
10168 config = config || {};
10169
10170 // Properties (must be done before parent constructor which calls #setDisabled)
10171 this.checkboxMultiselectWidget = new OO.ui.CheckboxMultiselectWidget();
10172 // Must be set before the #setOptionsData call below
10173 this.inputName = config.name;
10174 // Set up the options before parent constructor, which uses them to validate config.value.
10175 // Use this instead of setOptions() because this.$input is not set up yet
10176 this.setOptionsData( config.options || [] );
10177
10178 // Parent constructor
10179 OO.ui.CheckboxMultiselectInputWidget.parent.call( this, config );
10180
10181 // Events
10182 this.checkboxMultiselectWidget.connect( this, {
10183 select: 'onCheckboxesSelect'
10184 } );
10185
10186 // Initialization
10187 this.$element
10188 .addClass( 'oo-ui-checkboxMultiselectInputWidget' )
10189 .append( this.checkboxMultiselectWidget.$element );
10190 // We don't use this.$input, but rather the CheckboxInputWidgets inside each option
10191 this.$input.detach();
10192 };
10193
10194 /* Setup */
10195
10196 OO.inheritClass( OO.ui.CheckboxMultiselectInputWidget, OO.ui.InputWidget );
10197
10198 /* Static Methods */
10199
10200 /**
10201 * @inheritdoc
10202 */
10203 OO.ui.CheckboxMultiselectInputWidget.static.gatherPreInfuseState = function ( node, config ) {
10204 var state = OO.ui.CheckboxMultiselectInputWidget.parent.static.gatherPreInfuseState(
10205 node, config
10206 );
10207 state.value = $( node ).find( '.oo-ui-checkboxInputWidget .oo-ui-inputWidget-input:checked' )
10208 .toArray().map( function ( el ) { return el.value; } );
10209 return state;
10210 };
10211
10212 /**
10213 * @inheritdoc
10214 */
10215 OO.ui.CheckboxMultiselectInputWidget.static.reusePreInfuseDOM = function ( node, config ) {
10216 config = OO.ui.CheckboxMultiselectInputWidget.parent.static.reusePreInfuseDOM( node, config );
10217 // Cannot reuse the `<input type=checkbox>` set
10218 delete config.$input;
10219 return config;
10220 };
10221
10222 /* Methods */
10223
10224 /**
10225 * @inheritdoc
10226 * @protected
10227 */
10228 OO.ui.CheckboxMultiselectInputWidget.prototype.getInputElement = function () {
10229 // Actually unused
10230 return $( '<unused>' );
10231 };
10232
10233 /**
10234 * Handles CheckboxMultiselectWidget select events.
10235 *
10236 * @private
10237 */
10238 OO.ui.CheckboxMultiselectInputWidget.prototype.onCheckboxesSelect = function () {
10239 this.setValue( this.checkboxMultiselectWidget.findSelectedItemsData() );
10240 };
10241
10242 /**
10243 * @inheritdoc
10244 */
10245 OO.ui.CheckboxMultiselectInputWidget.prototype.getValue = function () {
10246 var value = this.$element.find( '.oo-ui-checkboxInputWidget .oo-ui-inputWidget-input:checked' )
10247 .toArray().map( function ( el ) { return el.value; } );
10248 if ( this.value !== value ) {
10249 this.setValue( value );
10250 }
10251 return this.value;
10252 };
10253
10254 /**
10255 * @inheritdoc
10256 */
10257 OO.ui.CheckboxMultiselectInputWidget.prototype.setValue = function ( value ) {
10258 value = this.cleanUpValue( value );
10259 this.checkboxMultiselectWidget.selectItemsByData( value );
10260 OO.ui.CheckboxMultiselectInputWidget.parent.prototype.setValue.call( this, value );
10261 if ( this.optionsDirty ) {
10262 // We reached this from the constructor or from #setOptions.
10263 // We have to update the <select> element.
10264 this.updateOptionsInterface();
10265 }
10266 return this;
10267 };
10268
10269 /**
10270 * Clean up incoming value.
10271 *
10272 * @param {string[]} value Original value
10273 * @return {string[]} Cleaned up value
10274 */
10275 OO.ui.CheckboxMultiselectInputWidget.prototype.cleanUpValue = function ( value ) {
10276 var i, singleValue,
10277 cleanValue = [];
10278 if ( !Array.isArray( value ) ) {
10279 return cleanValue;
10280 }
10281 for ( i = 0; i < value.length; i++ ) {
10282 singleValue = OO.ui.CheckboxMultiselectInputWidget.parent.prototype.cleanUpValue
10283 .call( this, value[ i ] );
10284 // Remove options that we don't have here
10285 if ( !this.checkboxMultiselectWidget.findItemFromData( singleValue ) ) {
10286 continue;
10287 }
10288 cleanValue.push( singleValue );
10289 }
10290 return cleanValue;
10291 };
10292
10293 /**
10294 * @inheritdoc
10295 */
10296 OO.ui.CheckboxMultiselectInputWidget.prototype.setDisabled = function ( state ) {
10297 this.checkboxMultiselectWidget.setDisabled( state );
10298 OO.ui.CheckboxMultiselectInputWidget.parent.prototype.setDisabled.call( this, state );
10299 return this;
10300 };
10301
10302 /**
10303 * Set the options available for this input.
10304 *
10305 * @param {Object[]} options Array of menu options in the format
10306 * `{ data: …, label: …, disabled: … }`
10307 * @chainable
10308 * @return {OO.ui.Widget} The widget, for chaining
10309 */
10310 OO.ui.CheckboxMultiselectInputWidget.prototype.setOptions = function ( options ) {
10311 var value = this.getValue();
10312
10313 this.setOptionsData( options );
10314
10315 // Re-set the value to update the visible interface (CheckboxMultiselectWidget).
10316 // This will also get rid of any stale options that we just removed.
10317 this.setValue( value );
10318
10319 return this;
10320 };
10321
10322 /**
10323 * Set the internal list of options, used e.g. by setValue() to see which options are allowed.
10324 *
10325 * This method may be called before the parent constructor, so various properties may not be
10326 * intialized yet.
10327 *
10328 * @param {Object[]} options Array of menu options in the format
10329 * `{ data: …, label: … }`
10330 * @private
10331 */
10332 OO.ui.CheckboxMultiselectInputWidget.prototype.setOptionsData = function ( options ) {
10333 var widget = this;
10334
10335 this.optionsDirty = true;
10336
10337 this.checkboxMultiselectWidget
10338 .clearItems()
10339 .addItems( options.map( function ( opt ) {
10340 var optValue, item, optDisabled;
10341 optValue = OO.ui.CheckboxMultiselectInputWidget.parent.prototype.cleanUpValue
10342 .call( widget, opt.data );
10343 optDisabled = opt.disabled !== undefined ? opt.disabled : false;
10344 item = new OO.ui.CheckboxMultioptionWidget( {
10345 data: optValue,
10346 label: opt.label !== undefined ? opt.label : optValue,
10347 disabled: optDisabled
10348 } );
10349 // Set the 'name' and 'value' for form submission
10350 item.checkbox.$input.attr( 'name', widget.inputName );
10351 item.checkbox.setValue( optValue );
10352 return item;
10353 } ) );
10354 };
10355
10356 /**
10357 * Update the user-visible interface to match the internal list of options and value.
10358 *
10359 * This method must only be called after the parent constructor.
10360 *
10361 * @private
10362 */
10363 OO.ui.CheckboxMultiselectInputWidget.prototype.updateOptionsInterface = function () {
10364 var defaultValue = this.defaultValue;
10365
10366 this.checkboxMultiselectWidget.getItems().forEach( function ( item ) {
10367 // Remember original selection state. This property can be later used to check whether
10368 // the selection state of the input has been changed since it was created.
10369 var isDefault = defaultValue.indexOf( item.getData() ) !== -1;
10370 item.checkbox.defaultSelected = isDefault;
10371 item.checkbox.$input[ 0 ].defaultChecked = isDefault;
10372 } );
10373
10374 this.optionsDirty = false;
10375 };
10376
10377 /**
10378 * @inheritdoc
10379 */
10380 OO.ui.CheckboxMultiselectInputWidget.prototype.focus = function () {
10381 this.checkboxMultiselectWidget.focus();
10382 return this;
10383 };
10384
10385 /**
10386 * TextInputWidgets, like HTML text inputs, can be configured with options that customize the
10387 * size of the field as well as its presentation. In addition, these widgets can be configured
10388 * with {@link OO.ui.mixin.IconElement icons}, {@link OO.ui.mixin.IndicatorElement indicators}, an
10389 * optional validation-pattern (used to determine if an input value is valid or not) and an input
10390 * filter, which modifies incoming values rather than validating them.
10391 * Please see the [OOUI documentation on MediaWiki] [1] for more information and examples.
10392 *
10393 * This widget can be used inside an HTML form, such as a OO.ui.FormLayout.
10394 *
10395 * @example
10396 * // A TextInputWidget.
10397 * var textInput = new OO.ui.TextInputWidget( {
10398 * value: 'Text input'
10399 * } )
10400 * $( document.body ).append( textInput.$element );
10401 *
10402 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
10403 *
10404 * @class
10405 * @extends OO.ui.InputWidget
10406 * @mixins OO.ui.mixin.IconElement
10407 * @mixins OO.ui.mixin.IndicatorElement
10408 * @mixins OO.ui.mixin.PendingElement
10409 * @mixins OO.ui.mixin.LabelElement
10410 * @mixins OO.ui.mixin.FlaggedElement
10411 *
10412 * @constructor
10413 * @param {Object} [config] Configuration options
10414 * @cfg {string} [type='text'] The value of the HTML `type` attribute: 'text', 'password'
10415 * 'email', 'url' or 'number'.
10416 * @cfg {string} [placeholder] Placeholder text
10417 * @cfg {boolean} [autofocus=false] Use an HTML `autofocus` attribute to
10418 * instruct the browser to focus this widget.
10419 * @cfg {boolean} [readOnly=false] Prevent changes to the value of the text input.
10420 * @cfg {number} [maxLength] Maximum number of characters allowed in the input.
10421 *
10422 * For unfortunate historical reasons, this counts the number of UTF-16 code units rather than
10423 * Unicode codepoints, which means that codepoints outside the Basic Multilingual Plane (e.g.
10424 * many emojis) count as 2 characters each.
10425 * @cfg {string} [labelPosition='after'] The position of the inline label relative to that of
10426 * the value or placeholder text: `'before'` or `'after'`
10427 * @cfg {boolean} [required=false] Mark the field as required with `true`. Implies `indicator:
10428 * 'required'`. Note that `false` & setting `indicator: 'required' will result in no indicator
10429 * shown.
10430 * @cfg {boolean} [autocomplete=true] Should the browser support autocomplete for this field
10431 * @cfg {boolean} [spellcheck] Should the browser support spellcheck for this field (`undefined`
10432 * means leaving it up to the browser).
10433 * @cfg {RegExp|Function|string} [validate] Validation pattern: when string, a symbolic name of a
10434 * pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer'
10435 * (the value must contain only numbers); when RegExp, a regular expression that must match the
10436 * value for it to be considered valid; when Function, a function receiving the value as parameter
10437 * that must return true, or promise resolving to true, for it to be considered valid.
10438 */
10439 OO.ui.TextInputWidget = function OoUiTextInputWidget( config ) {
10440 // Configuration initialization
10441 config = $.extend( {
10442 type: 'text',
10443 labelPosition: 'after'
10444 }, config );
10445
10446 // Parent constructor
10447 OO.ui.TextInputWidget.parent.call( this, config );
10448
10449 // Mixin constructors
10450 OO.ui.mixin.IconElement.call( this, config );
10451 OO.ui.mixin.IndicatorElement.call( this, config );
10452 OO.ui.mixin.PendingElement.call( this, $.extend( { $pending: this.$input }, config ) );
10453 OO.ui.mixin.LabelElement.call( this, config );
10454 OO.ui.mixin.FlaggedElement.call( this, config );
10455
10456 // Properties
10457 this.type = this.getSaneType( config );
10458 this.readOnly = false;
10459 this.required = false;
10460 this.validate = null;
10461 this.scrollWidth = null;
10462
10463 this.setValidation( config.validate );
10464 this.setLabelPosition( config.labelPosition );
10465
10466 // Events
10467 this.$input.on( {
10468 keypress: this.onKeyPress.bind( this ),
10469 blur: this.onBlur.bind( this ),
10470 focus: this.onFocus.bind( this )
10471 } );
10472 this.$icon.on( 'mousedown', this.onIconMouseDown.bind( this ) );
10473 this.$indicator.on( 'mousedown', this.onIndicatorMouseDown.bind( this ) );
10474 this.on( 'labelChange', this.updatePosition.bind( this ) );
10475 this.on( 'change', OO.ui.debounce( this.onDebouncedChange.bind( this ), 250 ) );
10476
10477 // Initialization
10478 this.$element
10479 .addClass( 'oo-ui-textInputWidget oo-ui-textInputWidget-type-' + this.type )
10480 .append( this.$icon, this.$indicator );
10481 this.setReadOnly( !!config.readOnly );
10482 this.setRequired( !!config.required );
10483 if ( config.placeholder !== undefined ) {
10484 this.$input.attr( 'placeholder', config.placeholder );
10485 }
10486 if ( config.maxLength !== undefined ) {
10487 this.$input.attr( 'maxlength', config.maxLength );
10488 }
10489 if ( config.autofocus ) {
10490 this.$input.attr( 'autofocus', 'autofocus' );
10491 }
10492 if ( config.autocomplete === false ) {
10493 this.$input.attr( 'autocomplete', 'off' );
10494 // Turning off autocompletion also disables "form caching" when the user navigates to a
10495 // different page and then clicks "Back". Re-enable it when leaving.
10496 // Borrowed from jQuery UI.
10497 $( window ).on( {
10498 beforeunload: function () {
10499 this.$input.removeAttr( 'autocomplete' );
10500 }.bind( this ),
10501 pageshow: function () {
10502 // Browsers don't seem to actually fire this event on "Back", they instead just
10503 // reload the whole page... it shouldn't hurt, though.
10504 this.$input.attr( 'autocomplete', 'off' );
10505 }.bind( this )
10506 } );
10507 }
10508 if ( config.spellcheck !== undefined ) {
10509 this.$input.attr( 'spellcheck', config.spellcheck ? 'true' : 'false' );
10510 }
10511 if ( this.label ) {
10512 this.isWaitingToBeAttached = true;
10513 this.installParentChangeDetector();
10514 }
10515 };
10516
10517 /* Setup */
10518
10519 OO.inheritClass( OO.ui.TextInputWidget, OO.ui.InputWidget );
10520 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.mixin.IconElement );
10521 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.mixin.IndicatorElement );
10522 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.mixin.PendingElement );
10523 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.mixin.LabelElement );
10524 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.mixin.FlaggedElement );
10525
10526 /* Static Properties */
10527
10528 OO.ui.TextInputWidget.static.validationPatterns = {
10529 'non-empty': /.+/,
10530 integer: /^\d+$/
10531 };
10532
10533 /* Events */
10534
10535 /**
10536 * An `enter` event is emitted when the user presses Enter key inside the text box.
10537 *
10538 * @event enter
10539 */
10540
10541 /* Methods */
10542
10543 /**
10544 * Handle icon mouse down events.
10545 *
10546 * @private
10547 * @param {jQuery.Event} e Mouse down event
10548 * @return {undefined/boolean} False to prevent default if event is handled
10549 */
10550 OO.ui.TextInputWidget.prototype.onIconMouseDown = function ( e ) {
10551 if ( e.which === OO.ui.MouseButtons.LEFT ) {
10552 this.focus();
10553 return false;
10554 }
10555 };
10556
10557 /**
10558 * Handle indicator mouse down events.
10559 *
10560 * @private
10561 * @param {jQuery.Event} e Mouse down event
10562 * @return {undefined/boolean} False to prevent default if event is handled
10563 */
10564 OO.ui.TextInputWidget.prototype.onIndicatorMouseDown = function ( e ) {
10565 if ( e.which === OO.ui.MouseButtons.LEFT ) {
10566 this.focus();
10567 return false;
10568 }
10569 };
10570
10571 /**
10572 * Handle key press events.
10573 *
10574 * @private
10575 * @param {jQuery.Event} e Key press event
10576 * @fires enter If Enter key is pressed
10577 */
10578 OO.ui.TextInputWidget.prototype.onKeyPress = function ( e ) {
10579 if ( e.which === OO.ui.Keys.ENTER ) {
10580 this.emit( 'enter', e );
10581 }
10582 };
10583
10584 /**
10585 * Handle blur events.
10586 *
10587 * @private
10588 * @param {jQuery.Event} e Blur event
10589 */
10590 OO.ui.TextInputWidget.prototype.onBlur = function () {
10591 this.setValidityFlag();
10592 };
10593
10594 /**
10595 * Handle focus events.
10596 *
10597 * @private
10598 * @param {jQuery.Event} e Focus event
10599 */
10600 OO.ui.TextInputWidget.prototype.onFocus = function () {
10601 if ( this.isWaitingToBeAttached ) {
10602 // If we've received focus, then we must be attached to the document, and if
10603 // isWaitingToBeAttached is still true, that means the handler never fired. Fire it now.
10604 this.onElementAttach();
10605 }
10606 this.setValidityFlag( true );
10607 };
10608
10609 /**
10610 * Handle element attach events.
10611 *
10612 * @private
10613 * @param {jQuery.Event} e Element attach event
10614 */
10615 OO.ui.TextInputWidget.prototype.onElementAttach = function () {
10616 this.isWaitingToBeAttached = false;
10617 // Any previously calculated size is now probably invalid if we reattached elsewhere
10618 this.valCache = null;
10619 this.positionLabel();
10620 };
10621
10622 /**
10623 * Handle debounced change events.
10624 *
10625 * @param {string} value
10626 * @private
10627 */
10628 OO.ui.TextInputWidget.prototype.onDebouncedChange = function () {
10629 this.setValidityFlag();
10630 };
10631
10632 /**
10633 * Check if the input is {@link #readOnly read-only}.
10634 *
10635 * @return {boolean}
10636 */
10637 OO.ui.TextInputWidget.prototype.isReadOnly = function () {
10638 return this.readOnly;
10639 };
10640
10641 /**
10642 * Set the {@link #readOnly read-only} state of the input.
10643 *
10644 * @param {boolean} state Make input read-only
10645 * @chainable
10646 * @return {OO.ui.Widget} The widget, for chaining
10647 */
10648 OO.ui.TextInputWidget.prototype.setReadOnly = function ( state ) {
10649 this.readOnly = !!state;
10650 this.$input.prop( 'readOnly', this.readOnly );
10651 return this;
10652 };
10653
10654 /**
10655 * Check if the input is {@link #required required}.
10656 *
10657 * @return {boolean}
10658 */
10659 OO.ui.TextInputWidget.prototype.isRequired = function () {
10660 return this.required;
10661 };
10662
10663 /**
10664 * Set the {@link #required required} state of the input.
10665 *
10666 * @param {boolean} state Make input required
10667 * @chainable
10668 * @return {OO.ui.Widget} The widget, for chaining
10669 */
10670 OO.ui.TextInputWidget.prototype.setRequired = function ( state ) {
10671 this.required = !!state;
10672 if ( this.required ) {
10673 this.$input
10674 .prop( 'required', true )
10675 .attr( 'aria-required', 'true' );
10676 if ( this.getIndicator() === null ) {
10677 this.setIndicator( 'required' );
10678 }
10679 } else {
10680 this.$input
10681 .prop( 'required', false )
10682 .removeAttr( 'aria-required' );
10683 if ( this.getIndicator() === 'required' ) {
10684 this.setIndicator( null );
10685 }
10686 }
10687 return this;
10688 };
10689
10690 /**
10691 * Support function for making #onElementAttach work across browsers.
10692 *
10693 * This whole function could be replaced with one line of code using the DOMNodeInsertedIntoDocument
10694 * event, but it's not supported by Firefox and allegedly deprecated, so we only use it as fallback.
10695 *
10696 * Due to MutationObserver performance woes, #onElementAttach is only somewhat reliably called the
10697 * first time that the element gets attached to the documented.
10698 */
10699 OO.ui.TextInputWidget.prototype.installParentChangeDetector = function () {
10700 var mutationObserver, onRemove, topmostNode, fakeParentNode,
10701 MutationObserver = window.MutationObserver ||
10702 window.WebKitMutationObserver ||
10703 window.MozMutationObserver,
10704 widget = this;
10705
10706 if ( MutationObserver ) {
10707 // The new way. If only it wasn't so ugly.
10708
10709 if ( this.isElementAttached() ) {
10710 // Widget is attached already, do nothing. This breaks the functionality of this
10711 // function when the widget is detached and reattached. Alas, doing this correctly with
10712 // MutationObserver would require observation of the whole document, which would hurt
10713 // performance of other, more important code.
10714 return;
10715 }
10716
10717 // Find topmost node in the tree
10718 topmostNode = this.$element[ 0 ];
10719 while ( topmostNode.parentNode ) {
10720 topmostNode = topmostNode.parentNode;
10721 }
10722
10723 // We have no way to detect the $element being attached somewhere without observing the
10724 // entire DOM with subtree modifications, which would hurt performance. So we cheat: we hook
10725 // to the parent node of $element, and instead detect when $element is removed from it (and
10726 // thus probably attached somewhere else). If there is no parent, we create a "fake" one. If
10727 // it doesn't get attached, we end up back here and create the parent.
10728 mutationObserver = new MutationObserver( function ( mutations ) {
10729 var i, j, removedNodes;
10730 for ( i = 0; i < mutations.length; i++ ) {
10731 removedNodes = mutations[ i ].removedNodes;
10732 for ( j = 0; j < removedNodes.length; j++ ) {
10733 if ( removedNodes[ j ] === topmostNode ) {
10734 setTimeout( onRemove, 0 );
10735 return;
10736 }
10737 }
10738 }
10739 } );
10740
10741 onRemove = function () {
10742 // If the node was attached somewhere else, report it
10743 if ( widget.isElementAttached() ) {
10744 widget.onElementAttach();
10745 }
10746 mutationObserver.disconnect();
10747 widget.installParentChangeDetector();
10748 };
10749
10750 // Create a fake parent and observe it
10751 fakeParentNode = $( '<div>' ).append( topmostNode )[ 0 ];
10752 mutationObserver.observe( fakeParentNode, { childList: true } );
10753 } else {
10754 // Using the DOMNodeInsertedIntoDocument event is much nicer and less magical, and works for
10755 // detachment and reattachment, but it's not supported by Firefox and allegedly deprecated.
10756 this.$element.on( 'DOMNodeInsertedIntoDocument', this.onElementAttach.bind( this ) );
10757 }
10758 };
10759
10760 /**
10761 * @inheritdoc
10762 * @protected
10763 */
10764 OO.ui.TextInputWidget.prototype.getInputElement = function ( config ) {
10765 if ( this.getSaneType( config ) === 'number' ) {
10766 return $( '<input>' )
10767 .attr( 'step', 'any' )
10768 .attr( 'type', 'number' );
10769 } else {
10770 return $( '<input>' ).attr( 'type', this.getSaneType( config ) );
10771 }
10772 };
10773
10774 /**
10775 * Get sanitized value for 'type' for given config.
10776 *
10777 * @param {Object} config Configuration options
10778 * @return {string|null}
10779 * @protected
10780 */
10781 OO.ui.TextInputWidget.prototype.getSaneType = function ( config ) {
10782 var allowedTypes = [
10783 'text',
10784 'password',
10785 'email',
10786 'url',
10787 'number'
10788 ];
10789 return allowedTypes.indexOf( config.type ) !== -1 ? config.type : 'text';
10790 };
10791
10792 /**
10793 * Focus the input and select a specified range within the text.
10794 *
10795 * @param {number} from Select from offset
10796 * @param {number} [to] Select to offset, defaults to from
10797 * @chainable
10798 * @return {OO.ui.Widget} The widget, for chaining
10799 */
10800 OO.ui.TextInputWidget.prototype.selectRange = function ( from, to ) {
10801 var isBackwards, start, end,
10802 input = this.$input[ 0 ];
10803
10804 to = to || from;
10805
10806 isBackwards = to < from;
10807 start = isBackwards ? to : from;
10808 end = isBackwards ? from : to;
10809
10810 this.focus();
10811
10812 try {
10813 input.setSelectionRange( start, end, isBackwards ? 'backward' : 'forward' );
10814 } catch ( e ) {
10815 // IE throws an exception if you call setSelectionRange on a unattached DOM node.
10816 // Rather than expensively check if the input is attached every time, just check
10817 // if it was the cause of an error being thrown. If not, rethrow the error.
10818 if ( this.getElementDocument().body.contains( input ) ) {
10819 throw e;
10820 }
10821 }
10822 return this;
10823 };
10824
10825 /**
10826 * Get an object describing the current selection range in a directional manner
10827 *
10828 * @return {Object} Object containing 'from' and 'to' offsets
10829 */
10830 OO.ui.TextInputWidget.prototype.getRange = function () {
10831 var input = this.$input[ 0 ],
10832 start = input.selectionStart,
10833 end = input.selectionEnd,
10834 isBackwards = input.selectionDirection === 'backward';
10835
10836 return {
10837 from: isBackwards ? end : start,
10838 to: isBackwards ? start : end
10839 };
10840 };
10841
10842 /**
10843 * Get the length of the text input value.
10844 *
10845 * This could differ from the length of #getValue if the
10846 * value gets filtered
10847 *
10848 * @return {number} Input length
10849 */
10850 OO.ui.TextInputWidget.prototype.getInputLength = function () {
10851 return this.$input[ 0 ].value.length;
10852 };
10853
10854 /**
10855 * Focus the input and select the entire text.
10856 *
10857 * @chainable
10858 * @return {OO.ui.Widget} The widget, for chaining
10859 */
10860 OO.ui.TextInputWidget.prototype.select = function () {
10861 return this.selectRange( 0, this.getInputLength() );
10862 };
10863
10864 /**
10865 * Focus the input and move the cursor to the start.
10866 *
10867 * @chainable
10868 * @return {OO.ui.Widget} The widget, for chaining
10869 */
10870 OO.ui.TextInputWidget.prototype.moveCursorToStart = function () {
10871 return this.selectRange( 0 );
10872 };
10873
10874 /**
10875 * Focus the input and move the cursor to the end.
10876 *
10877 * @chainable
10878 * @return {OO.ui.Widget} The widget, for chaining
10879 */
10880 OO.ui.TextInputWidget.prototype.moveCursorToEnd = function () {
10881 return this.selectRange( this.getInputLength() );
10882 };
10883
10884 /**
10885 * Insert new content into the input.
10886 *
10887 * @param {string} content Content to be inserted
10888 * @chainable
10889 * @return {OO.ui.Widget} The widget, for chaining
10890 */
10891 OO.ui.TextInputWidget.prototype.insertContent = function ( content ) {
10892 var start, end,
10893 range = this.getRange(),
10894 value = this.getValue();
10895
10896 start = Math.min( range.from, range.to );
10897 end = Math.max( range.from, range.to );
10898
10899 this.setValue( value.slice( 0, start ) + content + value.slice( end ) );
10900 this.selectRange( start + content.length );
10901 return this;
10902 };
10903
10904 /**
10905 * Insert new content either side of a selection.
10906 *
10907 * @param {string} pre Content to be inserted before the selection
10908 * @param {string} post Content to be inserted after the selection
10909 * @chainable
10910 * @return {OO.ui.Widget} The widget, for chaining
10911 */
10912 OO.ui.TextInputWidget.prototype.encapsulateContent = function ( pre, post ) {
10913 var start, end,
10914 range = this.getRange(),
10915 offset = pre.length;
10916
10917 start = Math.min( range.from, range.to );
10918 end = Math.max( range.from, range.to );
10919
10920 this.selectRange( start ).insertContent( pre );
10921 this.selectRange( offset + end ).insertContent( post );
10922
10923 this.selectRange( offset + start, offset + end );
10924 return this;
10925 };
10926
10927 /**
10928 * Set the validation pattern.
10929 *
10930 * The validation pattern is either a regular expression, a function, or the symbolic name of a
10931 * pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer' (the
10932 * value must contain only numbers).
10933 *
10934 * @param {RegExp|Function|string|null} validate Regular expression, function, or the symbolic name
10935 * of a pattern (either ‘integer’ or ‘non-empty’) defined by the class.
10936 */
10937 OO.ui.TextInputWidget.prototype.setValidation = function ( validate ) {
10938 if ( validate instanceof RegExp || validate instanceof Function ) {
10939 this.validate = validate;
10940 } else {
10941 this.validate = this.constructor.static.validationPatterns[ validate ] || /.*/;
10942 }
10943 };
10944
10945 /**
10946 * Sets the 'invalid' flag appropriately.
10947 *
10948 * @param {boolean} [isValid] Optionally override validation result
10949 */
10950 OO.ui.TextInputWidget.prototype.setValidityFlag = function ( isValid ) {
10951 var widget = this,
10952 setFlag = function ( valid ) {
10953 if ( !valid ) {
10954 widget.$input.attr( 'aria-invalid', 'true' );
10955 } else {
10956 widget.$input.removeAttr( 'aria-invalid' );
10957 }
10958 widget.setFlags( { invalid: !valid } );
10959 };
10960
10961 if ( isValid !== undefined ) {
10962 setFlag( isValid );
10963 } else {
10964 this.getValidity().then( function () {
10965 setFlag( true );
10966 }, function () {
10967 setFlag( false );
10968 } );
10969 }
10970 };
10971
10972 /**
10973 * Get the validity of current value.
10974 *
10975 * This method returns a promise that resolves if the value is valid and rejects if
10976 * it isn't. Uses the {@link #validate validation pattern} to check for validity.
10977 *
10978 * @return {jQuery.Promise} A promise that resolves if the value is valid, rejects if not.
10979 */
10980 OO.ui.TextInputWidget.prototype.getValidity = function () {
10981 var result;
10982
10983 function rejectOrResolve( valid ) {
10984 if ( valid ) {
10985 return $.Deferred().resolve().promise();
10986 } else {
10987 return $.Deferred().reject().promise();
10988 }
10989 }
10990
10991 // Check browser validity and reject if it is invalid
10992 if (
10993 this.$input[ 0 ].checkValidity !== undefined &&
10994 this.$input[ 0 ].checkValidity() === false
10995 ) {
10996 return rejectOrResolve( false );
10997 }
10998
10999 // Run our checks if the browser thinks the field is valid
11000 if ( this.validate instanceof Function ) {
11001 result = this.validate( this.getValue() );
11002 if ( result && typeof result.promise === 'function' ) {
11003 return result.promise().then( function ( valid ) {
11004 return rejectOrResolve( valid );
11005 } );
11006 } else {
11007 return rejectOrResolve( result );
11008 }
11009 } else {
11010 return rejectOrResolve( this.getValue().match( this.validate ) );
11011 }
11012 };
11013
11014 /**
11015 * Set the position of the inline label relative to that of the value: `‘before’` or `‘after’`.
11016 *
11017 * @param {string} labelPosition Label position, 'before' or 'after'
11018 * @chainable
11019 * @return {OO.ui.Widget} The widget, for chaining
11020 */
11021 OO.ui.TextInputWidget.prototype.setLabelPosition = function ( labelPosition ) {
11022 this.labelPosition = labelPosition;
11023 if ( this.label ) {
11024 // If there is no label and we only change the position, #updatePosition is a no-op,
11025 // but it takes really a lot of work to do nothing.
11026 this.updatePosition();
11027 }
11028 return this;
11029 };
11030
11031 /**
11032 * Update the position of the inline label.
11033 *
11034 * This method is called by #setLabelPosition, and can also be called on its own if
11035 * something causes the label to be mispositioned.
11036 *
11037 * @chainable
11038 * @return {OO.ui.Widget} The widget, for chaining
11039 */
11040 OO.ui.TextInputWidget.prototype.updatePosition = function () {
11041 var after = this.labelPosition === 'after';
11042
11043 this.$element
11044 .toggleClass( 'oo-ui-textInputWidget-labelPosition-after', !!this.label && after )
11045 .toggleClass( 'oo-ui-textInputWidget-labelPosition-before', !!this.label && !after );
11046
11047 this.valCache = null;
11048 this.scrollWidth = null;
11049 this.positionLabel();
11050
11051 return this;
11052 };
11053
11054 /**
11055 * Position the label by setting the correct padding on the input.
11056 *
11057 * @private
11058 * @chainable
11059 * @return {OO.ui.Widget} The widget, for chaining
11060 */
11061 OO.ui.TextInputWidget.prototype.positionLabel = function () {
11062 var after, rtl, property, newCss;
11063
11064 if ( this.isWaitingToBeAttached ) {
11065 // #onElementAttach will be called soon, which calls this method
11066 return this;
11067 }
11068
11069 newCss = {
11070 'padding-right': '',
11071 'padding-left': ''
11072 };
11073
11074 if ( this.label ) {
11075 this.$element.append( this.$label );
11076 } else {
11077 this.$label.detach();
11078 // Clear old values if present
11079 this.$input.css( newCss );
11080 return;
11081 }
11082
11083 after = this.labelPosition === 'after';
11084 rtl = this.$element.css( 'direction' ) === 'rtl';
11085 property = after === rtl ? 'padding-left' : 'padding-right';
11086
11087 newCss[ property ] = this.$label.outerWidth( true ) + ( after ? this.scrollWidth : 0 );
11088 // We have to clear the padding on the other side, in case the element direction changed
11089 this.$input.css( newCss );
11090
11091 return this;
11092 };
11093
11094 /**
11095 * SearchInputWidgets are TextInputWidgets with `type="search"` assigned and feature a
11096 * {@link OO.ui.mixin.IconElement search icon} by default.
11097 * Please see the [OOUI documentation on MediaWiki] [1] for more information and examples.
11098 *
11099 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs#SearchInputWidget
11100 *
11101 * @class
11102 * @extends OO.ui.TextInputWidget
11103 *
11104 * @constructor
11105 * @param {Object} [config] Configuration options
11106 */
11107 OO.ui.SearchInputWidget = function OoUiSearchInputWidget( config ) {
11108 config = $.extend( {
11109 icon: 'search'
11110 }, config );
11111
11112 // Parent constructor
11113 OO.ui.SearchInputWidget.parent.call( this, config );
11114
11115 // Events
11116 this.connect( this, {
11117 change: 'onChange'
11118 } );
11119
11120 // Initialization
11121 this.updateSearchIndicator();
11122 this.connect( this, {
11123 disable: 'onDisable'
11124 } );
11125 };
11126
11127 /* Setup */
11128
11129 OO.inheritClass( OO.ui.SearchInputWidget, OO.ui.TextInputWidget );
11130
11131 /* Methods */
11132
11133 /**
11134 * @inheritdoc
11135 * @protected
11136 */
11137 OO.ui.SearchInputWidget.prototype.getSaneType = function () {
11138 return 'search';
11139 };
11140
11141 /**
11142 * @inheritdoc
11143 */
11144 OO.ui.SearchInputWidget.prototype.onIndicatorMouseDown = function ( e ) {
11145 if ( e.which === OO.ui.MouseButtons.LEFT ) {
11146 // Clear the text field
11147 this.setValue( '' );
11148 this.focus();
11149 return false;
11150 }
11151 };
11152
11153 /**
11154 * Update the 'clear' indicator displayed on type: 'search' text
11155 * fields, hiding it when the field is already empty or when it's not
11156 * editable.
11157 */
11158 OO.ui.SearchInputWidget.prototype.updateSearchIndicator = function () {
11159 if ( this.getValue() === '' || this.isDisabled() || this.isReadOnly() ) {
11160 this.setIndicator( null );
11161 } else {
11162 this.setIndicator( 'clear' );
11163 }
11164 };
11165
11166 /**
11167 * Handle change events.
11168 *
11169 * @private
11170 */
11171 OO.ui.SearchInputWidget.prototype.onChange = function () {
11172 this.updateSearchIndicator();
11173 };
11174
11175 /**
11176 * Handle disable events.
11177 *
11178 * @param {boolean} disabled Element is disabled
11179 * @private
11180 */
11181 OO.ui.SearchInputWidget.prototype.onDisable = function () {
11182 this.updateSearchIndicator();
11183 };
11184
11185 /**
11186 * @inheritdoc
11187 */
11188 OO.ui.SearchInputWidget.prototype.setReadOnly = function ( state ) {
11189 OO.ui.SearchInputWidget.parent.prototype.setReadOnly.call( this, state );
11190 this.updateSearchIndicator();
11191 return this;
11192 };
11193
11194 /**
11195 * MultilineTextInputWidgets, like HTML textareas, are featuring customization options to
11196 * configure number of rows visible. In addition, these widgets can be autosized to fit user
11197 * inputs and can show {@link OO.ui.mixin.IconElement icons} and
11198 * {@link OO.ui.mixin.IndicatorElement indicators}.
11199 * Please see the [OOUI documentation on MediaWiki] [1] for more information and examples.
11200 *
11201 * This widget can be used inside an HTML form, such as a OO.ui.FormLayout.
11202 *
11203 * @example
11204 * // A MultilineTextInputWidget.
11205 * var multilineTextInput = new OO.ui.MultilineTextInputWidget( {
11206 * value: 'Text input on multiple lines'
11207 * } )
11208 * $( 'body' ).append( multilineTextInput.$element );
11209 *
11210 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs#MultilineTextInputWidget
11211 *
11212 * @class
11213 * @extends OO.ui.TextInputWidget
11214 *
11215 * @constructor
11216 * @param {Object} [config] Configuration options
11217 * @cfg {number} [rows] Number of visible lines in textarea. If used with `autosize`,
11218 * specifies minimum number of rows to display.
11219 * @cfg {boolean} [autosize=false] Automatically resize the text input to fit its content.
11220 * Use the #maxRows config to specify a maximum number of displayed rows.
11221 * @cfg {number} [maxRows] Maximum number of rows to display when #autosize is set to true.
11222 * Defaults to the maximum of `10` and `2 * rows`, or `10` if `rows` isn't provided.
11223 */
11224 OO.ui.MultilineTextInputWidget = function OoUiMultilineTextInputWidget( config ) {
11225 config = $.extend( {
11226 type: 'text'
11227 }, config );
11228 // Parent constructor
11229 OO.ui.MultilineTextInputWidget.parent.call( this, config );
11230
11231 // Properties
11232 this.autosize = !!config.autosize;
11233 this.styleHeight = null;
11234 this.minRows = config.rows !== undefined ? config.rows : '';
11235 this.maxRows = config.maxRows || Math.max( 2 * ( this.minRows || 0 ), 10 );
11236
11237 // Clone for resizing
11238 if ( this.autosize ) {
11239 this.$clone = this.$input
11240 .clone()
11241 .removeAttr( 'id' )
11242 .removeAttr( 'name' )
11243 .insertAfter( this.$input )
11244 .attr( 'aria-hidden', 'true' )
11245 .addClass( 'oo-ui-element-hidden' );
11246 }
11247
11248 // Events
11249 this.connect( this, {
11250 change: 'onChange'
11251 } );
11252
11253 // Initialization
11254 if ( config.rows ) {
11255 this.$input.attr( 'rows', config.rows );
11256 }
11257 if ( this.autosize ) {
11258 this.$input.addClass( 'oo-ui-textInputWidget-autosized' );
11259 this.isWaitingToBeAttached = true;
11260 this.installParentChangeDetector();
11261 }
11262 };
11263
11264 /* Setup */
11265
11266 OO.inheritClass( OO.ui.MultilineTextInputWidget, OO.ui.TextInputWidget );
11267
11268 /* Static Methods */
11269
11270 /**
11271 * @inheritdoc
11272 */
11273 OO.ui.MultilineTextInputWidget.static.gatherPreInfuseState = function ( node, config ) {
11274 var state = OO.ui.MultilineTextInputWidget.parent.static.gatherPreInfuseState( node, config );
11275 state.scrollTop = config.$input.scrollTop();
11276 return state;
11277 };
11278
11279 /* Methods */
11280
11281 /**
11282 * @inheritdoc
11283 */
11284 OO.ui.MultilineTextInputWidget.prototype.onElementAttach = function () {
11285 OO.ui.MultilineTextInputWidget.parent.prototype.onElementAttach.call( this );
11286 this.adjustSize();
11287 };
11288
11289 /**
11290 * Handle change events.
11291 *
11292 * @private
11293 */
11294 OO.ui.MultilineTextInputWidget.prototype.onChange = function () {
11295 this.adjustSize();
11296 };
11297
11298 /**
11299 * @inheritdoc
11300 */
11301 OO.ui.MultilineTextInputWidget.prototype.updatePosition = function () {
11302 OO.ui.MultilineTextInputWidget.parent.prototype.updatePosition.call( this );
11303 this.adjustSize();
11304 };
11305
11306 /**
11307 * @inheritdoc
11308 *
11309 * Modify to emit 'enter' on Ctrl/Meta+Enter, instead of plain Enter
11310 */
11311 OO.ui.MultilineTextInputWidget.prototype.onKeyPress = function ( e ) {
11312 if (
11313 ( e.which === OO.ui.Keys.ENTER && ( e.ctrlKey || e.metaKey ) ) ||
11314 // Some platforms emit keycode 10 for Control+Enter keypress in a textarea
11315 e.which === 10
11316 ) {
11317 this.emit( 'enter', e );
11318 }
11319 };
11320
11321 /**
11322 * Automatically adjust the size of the text input.
11323 *
11324 * This only affects multiline inputs that are {@link #autosize autosized}.
11325 *
11326 * @chainable
11327 * @return {OO.ui.Widget} The widget, for chaining
11328 * @fires resize
11329 */
11330 OO.ui.MultilineTextInputWidget.prototype.adjustSize = function () {
11331 var scrollHeight, innerHeight, outerHeight, maxInnerHeight, measurementError,
11332 idealHeight, newHeight, scrollWidth, property;
11333
11334 if ( this.$input.val() !== this.valCache ) {
11335 if ( this.autosize ) {
11336 this.$clone
11337 .val( this.$input.val() )
11338 .attr( 'rows', this.minRows )
11339 // Set inline height property to 0 to measure scroll height
11340 .css( 'height', 0 );
11341
11342 this.$clone.removeClass( 'oo-ui-element-hidden' );
11343
11344 this.valCache = this.$input.val();
11345
11346 scrollHeight = this.$clone[ 0 ].scrollHeight;
11347
11348 // Remove inline height property to measure natural heights
11349 this.$clone.css( 'height', '' );
11350 innerHeight = this.$clone.innerHeight();
11351 outerHeight = this.$clone.outerHeight();
11352
11353 // Measure max rows height
11354 this.$clone
11355 .attr( 'rows', this.maxRows )
11356 .css( 'height', 'auto' )
11357 .val( '' );
11358 maxInnerHeight = this.$clone.innerHeight();
11359
11360 // Difference between reported innerHeight and scrollHeight with no scrollbars present.
11361 // This is sometimes non-zero on Blink-based browsers, depending on zoom level.
11362 measurementError = maxInnerHeight - this.$clone[ 0 ].scrollHeight;
11363 idealHeight = Math.min( maxInnerHeight, scrollHeight + measurementError );
11364
11365 this.$clone.addClass( 'oo-ui-element-hidden' );
11366
11367 // Only apply inline height when expansion beyond natural height is needed
11368 // Use the difference between the inner and outer height as a buffer
11369 newHeight = idealHeight > innerHeight ? idealHeight + ( outerHeight - innerHeight ) : '';
11370 if ( newHeight !== this.styleHeight ) {
11371 this.$input.css( 'height', newHeight );
11372 this.styleHeight = newHeight;
11373 this.emit( 'resize' );
11374 }
11375 }
11376 scrollWidth = this.$input[ 0 ].offsetWidth - this.$input[ 0 ].clientWidth;
11377 if ( scrollWidth !== this.scrollWidth ) {
11378 property = this.$element.css( 'direction' ) === 'rtl' ? 'left' : 'right';
11379 // Reset
11380 this.$label.css( { right: '', left: '' } );
11381 this.$indicator.css( { right: '', left: '' } );
11382
11383 if ( scrollWidth ) {
11384 this.$indicator.css( property, scrollWidth );
11385 if ( this.labelPosition === 'after' ) {
11386 this.$label.css( property, scrollWidth );
11387 }
11388 }
11389
11390 this.scrollWidth = scrollWidth;
11391 this.positionLabel();
11392 }
11393 }
11394 return this;
11395 };
11396
11397 /**
11398 * @inheritdoc
11399 * @protected
11400 */
11401 OO.ui.MultilineTextInputWidget.prototype.getInputElement = function () {
11402 return $( '<textarea>' );
11403 };
11404
11405 /**
11406 * Check if the input automatically adjusts its size.
11407 *
11408 * @return {boolean}
11409 */
11410 OO.ui.MultilineTextInputWidget.prototype.isAutosizing = function () {
11411 return !!this.autosize;
11412 };
11413
11414 /**
11415 * @inheritdoc
11416 */
11417 OO.ui.MultilineTextInputWidget.prototype.restorePreInfuseState = function ( state ) {
11418 OO.ui.MultilineTextInputWidget.parent.prototype.restorePreInfuseState.call( this, state );
11419 if ( state.scrollTop !== undefined ) {
11420 this.$input.scrollTop( state.scrollTop );
11421 }
11422 };
11423
11424 /**
11425 * ComboBoxInputWidgets combine a {@link OO.ui.TextInputWidget text input} (where a value
11426 * can be entered manually) and a {@link OO.ui.MenuSelectWidget menu of options} (from which
11427 * a value can be chosen instead). Users can choose options from the combo box in one of two ways:
11428 *
11429 * - by typing a value in the text input field. If the value exactly matches the value of a menu
11430 * option, that option will appear to be selected.
11431 * - by choosing a value from the menu. The value of the chosen option will then appear in the text
11432 * input field.
11433 *
11434 * After the user chooses an option, its `data` will be used as a new value for the widget.
11435 * A `label` also can be specified for each option: if given, it will be shown instead of the
11436 * `data` in the dropdown menu.
11437 *
11438 * This widget can be used inside an HTML form, such as a OO.ui.FormLayout.
11439 *
11440 * For more information about menus and options, please see the
11441 * [OOUI documentation on MediaWiki][1].
11442 *
11443 * @example
11444 * // A ComboBoxInputWidget.
11445 * var comboBox = new OO.ui.ComboBoxInputWidget( {
11446 * value: 'Option 1',
11447 * options: [
11448 * { data: 'Option 1' },
11449 * { data: 'Option 2' },
11450 * { data: 'Option 3' }
11451 * ]
11452 * } );
11453 * $( document.body ).append( comboBox.$element );
11454 *
11455 * @example
11456 * // Example: A ComboBoxInputWidget with additional option labels.
11457 * var comboBox = new OO.ui.ComboBoxInputWidget( {
11458 * value: 'Option 1',
11459 * options: [
11460 * {
11461 * data: 'Option 1',
11462 * label: 'Option One'
11463 * },
11464 * {
11465 * data: 'Option 2',
11466 * label: 'Option Two'
11467 * },
11468 * {
11469 * data: 'Option 3',
11470 * label: 'Option Three'
11471 * }
11472 * ]
11473 * } );
11474 * $( document.body ).append( comboBox.$element );
11475 *
11476 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options#Menu_selects_and_options
11477 *
11478 * @class
11479 * @extends OO.ui.TextInputWidget
11480 *
11481 * @constructor
11482 * @param {Object} [config] Configuration options
11483 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
11484 * @cfg {Object} [menu] Configuration options to pass to the {@link OO.ui.MenuSelectWidget menu
11485 * select widget}.
11486 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful
11487 * in cases where the expanded menu is larger than its containing `<div>`. The specified overlay
11488 * layer is usually on top of the containing `<div>` and has a larger area. By default, the menu
11489 * uses relative positioning.
11490 * See <https://www.mediawiki.org/wiki/OOUI/Concepts#Overlays>.
11491 */
11492 OO.ui.ComboBoxInputWidget = function OoUiComboBoxInputWidget( config ) {
11493 // Configuration initialization
11494 config = $.extend( {
11495 autocomplete: false
11496 }, config );
11497
11498 // ComboBoxInputWidget shouldn't support `multiline`
11499 config.multiline = false;
11500
11501 // See InputWidget#reusePreInfuseDOM about `config.$input`
11502 if ( config.$input ) {
11503 config.$input.removeAttr( 'list' );
11504 }
11505
11506 // Parent constructor
11507 OO.ui.ComboBoxInputWidget.parent.call( this, config );
11508
11509 // Properties
11510 this.$overlay = ( config.$overlay === true ?
11511 OO.ui.getDefaultOverlay() : config.$overlay ) || this.$element;
11512 this.dropdownButton = new OO.ui.ButtonWidget( {
11513 classes: [ 'oo-ui-comboBoxInputWidget-dropdownButton' ],
11514 label: OO.ui.msg( 'ooui-combobox-button-label' ),
11515 indicator: 'down',
11516 invisibleLabel: true,
11517 disabled: this.disabled
11518 } );
11519 this.menu = new OO.ui.MenuSelectWidget( $.extend(
11520 {
11521 widget: this,
11522 input: this,
11523 $floatableContainer: this.$element,
11524 disabled: this.isDisabled()
11525 },
11526 config.menu
11527 ) );
11528
11529 // Events
11530 this.connect( this, {
11531 change: 'onInputChange',
11532 enter: 'onInputEnter'
11533 } );
11534 this.dropdownButton.connect( this, {
11535 click: 'onDropdownButtonClick'
11536 } );
11537 this.menu.connect( this, {
11538 choose: 'onMenuChoose',
11539 add: 'onMenuItemsChange',
11540 remove: 'onMenuItemsChange',
11541 toggle: 'onMenuToggle'
11542 } );
11543
11544 // Initialization
11545 this.$input.attr( {
11546 role: 'combobox',
11547 'aria-owns': this.menu.getElementId(),
11548 'aria-autocomplete': 'list'
11549 } );
11550 this.dropdownButton.$button.attr( {
11551 'aria-controls': this.menu.getElementId()
11552 } );
11553 // Do not override options set via config.menu.items
11554 if ( config.options !== undefined ) {
11555 this.setOptions( config.options );
11556 }
11557 this.$field = $( '<div>' )
11558 .addClass( 'oo-ui-comboBoxInputWidget-field' )
11559 .append( this.$input, this.dropdownButton.$element );
11560 this.$element
11561 .addClass( 'oo-ui-comboBoxInputWidget' )
11562 .append( this.$field );
11563 this.$overlay.append( this.menu.$element );
11564 this.onMenuItemsChange();
11565 };
11566
11567 /* Setup */
11568
11569 OO.inheritClass( OO.ui.ComboBoxInputWidget, OO.ui.TextInputWidget );
11570
11571 /* Methods */
11572
11573 /**
11574 * Get the combobox's menu.
11575 *
11576 * @return {OO.ui.MenuSelectWidget} Menu widget
11577 */
11578 OO.ui.ComboBoxInputWidget.prototype.getMenu = function () {
11579 return this.menu;
11580 };
11581
11582 /**
11583 * Get the combobox's text input widget.
11584 *
11585 * @return {OO.ui.TextInputWidget} Text input widget
11586 */
11587 OO.ui.ComboBoxInputWidget.prototype.getInput = function () {
11588 return this;
11589 };
11590
11591 /**
11592 * Handle input change events.
11593 *
11594 * @private
11595 * @param {string} value New value
11596 */
11597 OO.ui.ComboBoxInputWidget.prototype.onInputChange = function ( value ) {
11598 var match = this.menu.findItemFromData( value );
11599
11600 this.menu.selectItem( match );
11601 if ( this.menu.findHighlightedItem() ) {
11602 this.menu.highlightItem( match );
11603 }
11604
11605 if ( !this.isDisabled() ) {
11606 this.menu.toggle( true );
11607 }
11608 };
11609
11610 /**
11611 * Handle input enter events.
11612 *
11613 * @private
11614 */
11615 OO.ui.ComboBoxInputWidget.prototype.onInputEnter = function () {
11616 if ( !this.isDisabled() ) {
11617 this.menu.toggle( false );
11618 }
11619 };
11620
11621 /**
11622 * Handle button click events.
11623 *
11624 * @private
11625 */
11626 OO.ui.ComboBoxInputWidget.prototype.onDropdownButtonClick = function () {
11627 this.menu.toggle();
11628 this.focus();
11629 };
11630
11631 /**
11632 * Handle menu choose events.
11633 *
11634 * @private
11635 * @param {OO.ui.OptionWidget} item Chosen item
11636 */
11637 OO.ui.ComboBoxInputWidget.prototype.onMenuChoose = function ( item ) {
11638 this.setValue( item.getData() );
11639 };
11640
11641 /**
11642 * Handle menu item change events.
11643 *
11644 * @private
11645 */
11646 OO.ui.ComboBoxInputWidget.prototype.onMenuItemsChange = function () {
11647 var match = this.menu.findItemFromData( this.getValue() );
11648 this.menu.selectItem( match );
11649 if ( this.menu.findHighlightedItem() ) {
11650 this.menu.highlightItem( match );
11651 }
11652 this.$element.toggleClass( 'oo-ui-comboBoxInputWidget-empty', this.menu.isEmpty() );
11653 };
11654
11655 /**
11656 * Handle menu toggle events.
11657 *
11658 * @private
11659 * @param {boolean} isVisible Open state of the menu
11660 */
11661 OO.ui.ComboBoxInputWidget.prototype.onMenuToggle = function ( isVisible ) {
11662 this.$element.toggleClass( 'oo-ui-comboBoxInputWidget-open', isVisible );
11663 };
11664
11665 /**
11666 * Update the disabled state of the controls
11667 *
11668 * @chainable
11669 * @protected
11670 * @return {OO.ui.ComboBoxInputWidget} The widget, for chaining
11671 */
11672 OO.ui.ComboBoxInputWidget.prototype.updateControlsDisabled = function () {
11673 var disabled = this.isDisabled() || this.isReadOnly();
11674 if ( this.dropdownButton ) {
11675 this.dropdownButton.setDisabled( disabled );
11676 }
11677 if ( this.menu ) {
11678 this.menu.setDisabled( disabled );
11679 }
11680 return this;
11681 };
11682
11683 /**
11684 * @inheritdoc
11685 */
11686 OO.ui.ComboBoxInputWidget.prototype.setDisabled = function () {
11687 // Parent method
11688 OO.ui.ComboBoxInputWidget.parent.prototype.setDisabled.apply( this, arguments );
11689 this.updateControlsDisabled();
11690 return this;
11691 };
11692
11693 /**
11694 * @inheritdoc
11695 */
11696 OO.ui.ComboBoxInputWidget.prototype.setReadOnly = function () {
11697 // Parent method
11698 OO.ui.ComboBoxInputWidget.parent.prototype.setReadOnly.apply( this, arguments );
11699 this.updateControlsDisabled();
11700 return this;
11701 };
11702
11703 /**
11704 * Set the options available for this input.
11705 *
11706 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
11707 * @chainable
11708 * @return {OO.ui.Widget} The widget, for chaining
11709 */
11710 OO.ui.ComboBoxInputWidget.prototype.setOptions = function ( options ) {
11711 this.getMenu()
11712 .clearItems()
11713 .addItems( options.map( function ( opt ) {
11714 return new OO.ui.MenuOptionWidget( {
11715 data: opt.data,
11716 label: opt.label !== undefined ? opt.label : opt.data
11717 } );
11718 } ) );
11719
11720 return this;
11721 };
11722
11723 /**
11724 * FieldLayouts are used with OO.ui.FieldsetLayout. Each FieldLayout requires a field-widget,
11725 * which is a widget that is specified by reference before any optional configuration settings.
11726 *
11727 * Field layouts can be configured with help text and/or labels. Labels are aligned in one of
11728 * four ways:
11729 *
11730 * - **left**: The label is placed before the field-widget and aligned with the left margin.
11731 * A left-alignment is used for forms with many fields.
11732 * - **right**: The label is placed before the field-widget and aligned to the right margin.
11733 * A right-alignment is used for long but familiar forms which users tab through,
11734 * verifying the current field with a quick glance at the label.
11735 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
11736 * that users fill out from top to bottom.
11737 * - **inline**: The label is placed after the field-widget and aligned to the left.
11738 * An inline-alignment is best used with checkboxes or radio buttons.
11739 *
11740 * Help text can either be:
11741 *
11742 * - accessed via a help icon that appears in the upper right corner of the rendered field layout,
11743 * or
11744 * - shown as a subtle explanation below the label.
11745 *
11746 * If the help text is brief, or is essential to always expose it, set `helpInline` to `true`.
11747 * If it is long or not essential, leave `helpInline` to its default, `false`.
11748 *
11749 * Please see the [OOUI documentation on MediaWiki] [1] for examples and more information.
11750 *
11751 * [1]: https://www.mediawiki.org/wiki/OOUI/Layouts/Fields_and_Fieldsets
11752 *
11753 * @class
11754 * @extends OO.ui.Layout
11755 * @mixins OO.ui.mixin.LabelElement
11756 * @mixins OO.ui.mixin.TitledElement
11757 *
11758 * @constructor
11759 * @param {OO.ui.Widget} fieldWidget Field widget
11760 * @param {Object} [config] Configuration options
11761 * @cfg {string} [align='left'] Alignment of the label: 'left', 'right', 'top'
11762 * or 'inline'
11763 * @cfg {Array} [errors] Error messages about the widget, which will be
11764 * displayed below the widget.
11765 * @cfg {Array} [warnings] Warning messages about the widget, which will be
11766 * displayed below the widget.
11767 * @cfg {Array} [successMessages] Success messages on user interactions with the widget,
11768 * which will be displayed below the widget.
11769 * The array may contain strings or OO.ui.HtmlSnippet instances.
11770 * @cfg {Array} [notices] Notices about the widget, which will be displayed
11771 * below the widget.
11772 * The array may contain strings or OO.ui.HtmlSnippet instances.
11773 * These are more visible than `help` messages when `helpInline` is set, and so
11774 * might be good for transient messages.
11775 * @cfg {string|OO.ui.HtmlSnippet} [help] Help text. When help text is specified
11776 * and `helpInline` is `false`, a "help" icon will appear in the upper-right
11777 * corner of the rendered field; clicking it will display the text in a popup.
11778 * If `helpInline` is `true`, then a subtle description will be shown after the
11779 * label.
11780 * @cfg {boolean} [helpInline=false] Whether or not the help should be inline,
11781 * or shown when the "help" icon is clicked.
11782 * @cfg {jQuery} [$overlay] Passed to OO.ui.PopupButtonWidget for help popup, if
11783 * `help` is given.
11784 * See <https://www.mediawiki.org/wiki/OOUI/Concepts#Overlays>.
11785 *
11786 * @throws {Error} An error is thrown if no widget is specified
11787 */
11788 OO.ui.FieldLayout = function OoUiFieldLayout( fieldWidget, config ) {
11789 // Allow passing positional parameters inside the config object
11790 if ( OO.isPlainObject( fieldWidget ) && config === undefined ) {
11791 config = fieldWidget;
11792 fieldWidget = config.fieldWidget;
11793 }
11794
11795 // Make sure we have required constructor arguments
11796 if ( fieldWidget === undefined ) {
11797 throw new Error( 'Widget not found' );
11798 }
11799
11800 // Configuration initialization
11801 config = $.extend( { align: 'left', helpInline: false }, config );
11802
11803 // Parent constructor
11804 OO.ui.FieldLayout.parent.call( this, config );
11805
11806 // Mixin constructors
11807 OO.ui.mixin.LabelElement.call( this, $.extend( {
11808 $label: $( '<label>' )
11809 }, config ) );
11810 OO.ui.mixin.TitledElement.call( this, $.extend( { $titled: this.$label }, config ) );
11811
11812 // Properties
11813 this.fieldWidget = fieldWidget;
11814 this.errors = [];
11815 this.warnings = [];
11816 this.successMessages = [];
11817 this.notices = [];
11818 this.$field = this.isFieldInline() ? $( '<span>' ) : $( '<div>' );
11819 this.$messages = $( '<ul>' );
11820 this.$header = $( '<span>' );
11821 this.$body = $( '<div>' );
11822 this.align = null;
11823 this.helpInline = config.helpInline;
11824
11825 // Events
11826 this.fieldWidget.connect( this, {
11827 disable: 'onFieldDisable'
11828 } );
11829
11830 // Initialization
11831 this.$help = config.help ?
11832 this.createHelpElement( config.help, config.$overlay ) :
11833 $( [] );
11834 if ( this.fieldWidget.getInputId() ) {
11835 this.$label.attr( 'for', this.fieldWidget.getInputId() );
11836 if ( this.helpInline ) {
11837 this.$help.attr( 'for', this.fieldWidget.getInputId() );
11838 }
11839 } else {
11840 this.$label.on( 'click', function () {
11841 this.fieldWidget.simulateLabelClick();
11842 }.bind( this ) );
11843 if ( this.helpInline ) {
11844 this.$help.on( 'click', function () {
11845 this.fieldWidget.simulateLabelClick();
11846 }.bind( this ) );
11847 }
11848 }
11849 this.$element
11850 .addClass( 'oo-ui-fieldLayout' )
11851 .toggleClass( 'oo-ui-fieldLayout-disabled', this.fieldWidget.isDisabled() )
11852 .append( this.$body );
11853 this.$body.addClass( 'oo-ui-fieldLayout-body' );
11854 this.$header.addClass( 'oo-ui-fieldLayout-header' );
11855 this.$messages.addClass( 'oo-ui-fieldLayout-messages' );
11856 this.$field
11857 .addClass( 'oo-ui-fieldLayout-field' )
11858 .append( this.fieldWidget.$element );
11859
11860 this.setErrors( config.errors || [] );
11861 this.setWarnings( config.warnings || [] );
11862 this.setSuccess( config.successMessages || [] );
11863 this.setNotices( config.notices || [] );
11864 this.setAlignment( config.align );
11865 // Call this again to take into account the widget's accessKey
11866 this.updateTitle();
11867 };
11868
11869 /* Setup */
11870
11871 OO.inheritClass( OO.ui.FieldLayout, OO.ui.Layout );
11872 OO.mixinClass( OO.ui.FieldLayout, OO.ui.mixin.LabelElement );
11873 OO.mixinClass( OO.ui.FieldLayout, OO.ui.mixin.TitledElement );
11874
11875 /* Methods */
11876
11877 /**
11878 * Handle field disable events.
11879 *
11880 * @private
11881 * @param {boolean} value Field is disabled
11882 */
11883 OO.ui.FieldLayout.prototype.onFieldDisable = function ( value ) {
11884 this.$element.toggleClass( 'oo-ui-fieldLayout-disabled', value );
11885 };
11886
11887 /**
11888 * Get the widget contained by the field.
11889 *
11890 * @return {OO.ui.Widget} Field widget
11891 */
11892 OO.ui.FieldLayout.prototype.getField = function () {
11893 return this.fieldWidget;
11894 };
11895
11896 /**
11897 * Return `true` if the given field widget can be used with `'inline'` alignment (see
11898 * #setAlignment). Return `false` if it can't or if this can't be determined.
11899 *
11900 * @return {boolean}
11901 */
11902 OO.ui.FieldLayout.prototype.isFieldInline = function () {
11903 // This is very simplistic, but should be good enough.
11904 return this.getField().$element.prop( 'tagName' ).toLowerCase() === 'span';
11905 };
11906
11907 /**
11908 * @protected
11909 * @param {string} kind 'error' or 'notice'
11910 * @param {string|OO.ui.HtmlSnippet} text
11911 * @return {jQuery}
11912 */
11913 OO.ui.FieldLayout.prototype.makeMessage = function ( kind, text ) {
11914 var $listItem, $icon, message;
11915 $listItem = $( '<li>' );
11916 if ( kind === 'error' ) {
11917 $icon = new OO.ui.IconWidget( { icon: 'alert', flags: [ 'error' ] } ).$element;
11918 $listItem.attr( 'role', 'alert' );
11919 } else if ( kind === 'warning' ) {
11920 $icon = new OO.ui.IconWidget( { icon: 'alert', flags: [ 'warning' ] } ).$element;
11921 $listItem.attr( 'role', 'alert' );
11922 } else if ( kind === 'success' ) {
11923 $icon = new OO.ui.IconWidget( { icon: 'check', flags: [ 'success' ] } ).$element;
11924 } else if ( kind === 'notice' ) {
11925 $icon = new OO.ui.IconWidget( { icon: 'notice' } ).$element;
11926 } else {
11927 $icon = '';
11928 }
11929 message = new OO.ui.LabelWidget( { label: text } );
11930 $listItem
11931 .append( $icon, message.$element )
11932 .addClass( 'oo-ui-fieldLayout-messages-' + kind );
11933 return $listItem;
11934 };
11935
11936 /**
11937 * Set the field alignment mode.
11938 *
11939 * @private
11940 * @param {string} value Alignment mode, either 'left', 'right', 'top' or 'inline'
11941 * @chainable
11942 * @return {OO.ui.BookletLayout} The layout, for chaining
11943 */
11944 OO.ui.FieldLayout.prototype.setAlignment = function ( value ) {
11945 if ( value !== this.align ) {
11946 // Default to 'left'
11947 if ( [ 'left', 'right', 'top', 'inline' ].indexOf( value ) === -1 ) {
11948 value = 'left';
11949 }
11950 // Validate
11951 if ( value === 'inline' && !this.isFieldInline() ) {
11952 value = 'top';
11953 }
11954 // Reorder elements
11955
11956 if ( this.helpInline ) {
11957 if ( value === 'top' ) {
11958 this.$header.append( this.$label );
11959 this.$body.append( this.$header, this.$field, this.$help );
11960 } else if ( value === 'inline' ) {
11961 this.$header.append( this.$label, this.$help );
11962 this.$body.append( this.$field, this.$header );
11963 } else {
11964 this.$header.append( this.$label, this.$help );
11965 this.$body.append( this.$header, this.$field );
11966 }
11967 } else {
11968 if ( value === 'top' ) {
11969 this.$header.append( this.$help, this.$label );
11970 this.$body.append( this.$header, this.$field );
11971 } else if ( value === 'inline' ) {
11972 this.$header.append( this.$help, this.$label );
11973 this.$body.append( this.$field, this.$header );
11974 } else {
11975 this.$header.append( this.$label );
11976 this.$body.append( this.$header, this.$help, this.$field );
11977 }
11978 }
11979 // Set classes. The following classes can be used here:
11980 // * oo-ui-fieldLayout-align-left
11981 // * oo-ui-fieldLayout-align-right
11982 // * oo-ui-fieldLayout-align-top
11983 // * oo-ui-fieldLayout-align-inline
11984 if ( this.align ) {
11985 this.$element.removeClass( 'oo-ui-fieldLayout-align-' + this.align );
11986 }
11987 this.$element.addClass( 'oo-ui-fieldLayout-align-' + value );
11988 this.align = value;
11989 }
11990
11991 return this;
11992 };
11993
11994 /**
11995 * Set the list of error messages.
11996 *
11997 * @param {Array} errors Error messages about the widget, which will be displayed below the widget.
11998 * The array may contain strings or OO.ui.HtmlSnippet instances.
11999 * @chainable
12000 * @return {OO.ui.BookletLayout} The layout, for chaining
12001 */
12002 OO.ui.FieldLayout.prototype.setErrors = function ( errors ) {
12003 this.errors = errors.slice();
12004 this.updateMessages();
12005 return this;
12006 };
12007
12008 /**
12009 * Set the list of warning messages.
12010 *
12011 * @param {Array} warnings Warning messages about the widget, which will be displayed below
12012 * the widget.
12013 * The array may contain strings or OO.ui.HtmlSnippet instances.
12014 * @chainable
12015 * @return {OO.ui.BookletLayout} The layout, for chaining
12016 */
12017 OO.ui.FieldLayout.prototype.setWarnings = function ( warnings ) {
12018 this.warnings = warnings.slice();
12019 this.updateMessages();
12020 return this;
12021 };
12022
12023 /**
12024 * Set the list of success messages.
12025 *
12026 * @param {Array} successMessages Success messages about the widget, which will be displayed below
12027 * the widget.
12028 * The array may contain strings or OO.ui.HtmlSnippet instances.
12029 * @chainable
12030 * @return {OO.ui.BookletLayout} The layout, for chaining
12031 */
12032 OO.ui.FieldLayout.prototype.setSuccess = function ( successMessages ) {
12033 this.successMessages = successMessages.slice();
12034 this.updateMessages();
12035 return this;
12036 };
12037
12038 /**
12039 * Set the list of notice messages.
12040 *
12041 * @param {Array} notices Notices about the widget, which will be displayed below the widget.
12042 * The array may contain strings or OO.ui.HtmlSnippet instances.
12043 * @chainable
12044 * @return {OO.ui.BookletLayout} The layout, for chaining
12045 */
12046 OO.ui.FieldLayout.prototype.setNotices = function ( notices ) {
12047 this.notices = notices.slice();
12048 this.updateMessages();
12049 return this;
12050 };
12051
12052 /**
12053 * Update the rendering of error, warning, success and notice messages.
12054 *
12055 * @private
12056 */
12057 OO.ui.FieldLayout.prototype.updateMessages = function () {
12058 var i;
12059 this.$messages.empty();
12060
12061 if (
12062 this.errors.length ||
12063 this.warnings.length ||
12064 this.successMessages.length ||
12065 this.notices.length
12066 ) {
12067 this.$body.after( this.$messages );
12068 } else {
12069 this.$messages.remove();
12070 return;
12071 }
12072
12073 for ( i = 0; i < this.errors.length; i++ ) {
12074 this.$messages.append( this.makeMessage( 'error', this.errors[ i ] ) );
12075 }
12076 for ( i = 0; i < this.warnings.length; i++ ) {
12077 this.$messages.append( this.makeMessage( 'warning', this.warnings[ i ] ) );
12078 }
12079 for ( i = 0; i < this.successMessages.length; i++ ) {
12080 this.$messages.append( this.makeMessage( 'success', this.successMessages[ i ] ) );
12081 }
12082 for ( i = 0; i < this.notices.length; i++ ) {
12083 this.$messages.append( this.makeMessage( 'notice', this.notices[ i ] ) );
12084 }
12085 };
12086
12087 /**
12088 * Include information about the widget's accessKey in our title. TitledElement calls this method.
12089 * (This is a bit of a hack.)
12090 *
12091 * @protected
12092 * @param {string} title Tooltip label for 'title' attribute
12093 * @return {string}
12094 */
12095 OO.ui.FieldLayout.prototype.formatTitleWithAccessKey = function ( title ) {
12096 if ( this.fieldWidget && this.fieldWidget.formatTitleWithAccessKey ) {
12097 return this.fieldWidget.formatTitleWithAccessKey( title );
12098 }
12099 return title;
12100 };
12101
12102 /**
12103 * Creates and returns the help element. Also sets the `aria-describedby`
12104 * attribute on the main element of the `fieldWidget`.
12105 *
12106 * @private
12107 * @param {string|OO.ui.HtmlSnippet} [help] Help text.
12108 * @param {jQuery} [$overlay] Passed to OO.ui.PopupButtonWidget for help popup.
12109 * @return {jQuery} The element that should become `this.$help`.
12110 */
12111 OO.ui.FieldLayout.prototype.createHelpElement = function ( help, $overlay ) {
12112 var helpId, helpWidget;
12113
12114 if ( this.helpInline ) {
12115 helpWidget = new OO.ui.LabelWidget( {
12116 label: help,
12117 classes: [ 'oo-ui-inline-help' ]
12118 } );
12119
12120 helpId = helpWidget.getElementId();
12121 } else {
12122 helpWidget = new OO.ui.PopupButtonWidget( {
12123 $overlay: $overlay,
12124 popup: {
12125 padded: true
12126 },
12127 classes: [ 'oo-ui-fieldLayout-help' ],
12128 framed: false,
12129 icon: 'info',
12130 label: OO.ui.msg( 'ooui-field-help' ),
12131 invisibleLabel: true
12132 } );
12133 if ( help instanceof OO.ui.HtmlSnippet ) {
12134 helpWidget.getPopup().$body.html( help.toString() );
12135 } else {
12136 helpWidget.getPopup().$body.text( help );
12137 }
12138
12139 helpId = helpWidget.getPopup().getBodyId();
12140 }
12141
12142 // Set the 'aria-describedby' attribute on the fieldWidget
12143 // Preference given to an input or a button
12144 (
12145 this.fieldWidget.$input ||
12146 this.fieldWidget.$button ||
12147 this.fieldWidget.$element
12148 ).attr( 'aria-describedby', helpId );
12149
12150 return helpWidget.$element;
12151 };
12152
12153 /**
12154 * ActionFieldLayouts are used with OO.ui.FieldsetLayout. The layout consists of a field-widget,
12155 * a button, and an optional label and/or help text. The field-widget (e.g., a
12156 * {@link OO.ui.TextInputWidget TextInputWidget}), is required and is specified before any optional
12157 * configuration settings.
12158 *
12159 * Labels can be aligned in one of four ways:
12160 *
12161 * - **left**: The label is placed before the field-widget and aligned with the left margin.
12162 * A left-alignment is used for forms with many fields.
12163 * - **right**: The label is placed before the field-widget and aligned to the right margin.
12164 * A right-alignment is used for long but familiar forms which users tab through,
12165 * verifying the current field with a quick glance at the label.
12166 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
12167 * that users fill out from top to bottom.
12168 * - **inline**: The label is placed after the field-widget and aligned to the left.
12169 * An inline-alignment is best used with checkboxes or radio buttons.
12170 *
12171 * Help text is accessed via a help icon that appears in the upper right corner of the rendered
12172 * field layout when help text is specified.
12173 *
12174 * @example
12175 * // Example of an ActionFieldLayout
12176 * var actionFieldLayout = new OO.ui.ActionFieldLayout(
12177 * new OO.ui.TextInputWidget( {
12178 * placeholder: 'Field widget'
12179 * } ),
12180 * new OO.ui.ButtonWidget( {
12181 * label: 'Button'
12182 * } ),
12183 * {
12184 * label: 'An ActionFieldLayout. This label is aligned top',
12185 * align: 'top',
12186 * help: 'This is help text'
12187 * }
12188 * );
12189 *
12190 * $( document.body ).append( actionFieldLayout.$element );
12191 *
12192 * @class
12193 * @extends OO.ui.FieldLayout
12194 *
12195 * @constructor
12196 * @param {OO.ui.Widget} fieldWidget Field widget
12197 * @param {OO.ui.ButtonWidget} buttonWidget Button widget
12198 * @param {Object} config
12199 */
12200 OO.ui.ActionFieldLayout = function OoUiActionFieldLayout( fieldWidget, buttonWidget, config ) {
12201 // Allow passing positional parameters inside the config object
12202 if ( OO.isPlainObject( fieldWidget ) && config === undefined ) {
12203 config = fieldWidget;
12204 fieldWidget = config.fieldWidget;
12205 buttonWidget = config.buttonWidget;
12206 }
12207
12208 // Parent constructor
12209 OO.ui.ActionFieldLayout.parent.call( this, fieldWidget, config );
12210
12211 // Properties
12212 this.buttonWidget = buttonWidget;
12213 this.$button = $( '<span>' );
12214 this.$input = this.isFieldInline() ? $( '<span>' ) : $( '<div>' );
12215
12216 // Initialization
12217 this.$element.addClass( 'oo-ui-actionFieldLayout' );
12218 this.$button
12219 .addClass( 'oo-ui-actionFieldLayout-button' )
12220 .append( this.buttonWidget.$element );
12221 this.$input
12222 .addClass( 'oo-ui-actionFieldLayout-input' )
12223 .append( this.fieldWidget.$element );
12224 this.$field.append( this.$input, this.$button );
12225 };
12226
12227 /* Setup */
12228
12229 OO.inheritClass( OO.ui.ActionFieldLayout, OO.ui.FieldLayout );
12230
12231 /**
12232 * FieldsetLayouts are composed of one or more {@link OO.ui.FieldLayout FieldLayouts},
12233 * which each contain an individual widget and, optionally, a label. Each Fieldset can be
12234 * configured with a label as well. For more information and examples,
12235 * please see the [OOUI documentation on MediaWiki][1].
12236 *
12237 * @example
12238 * // Example of a fieldset layout
12239 * var input1 = new OO.ui.TextInputWidget( {
12240 * placeholder: 'A text input field'
12241 * } );
12242 *
12243 * var input2 = new OO.ui.TextInputWidget( {
12244 * placeholder: 'A text input field'
12245 * } );
12246 *
12247 * var fieldset = new OO.ui.FieldsetLayout( {
12248 * label: 'Example of a fieldset layout'
12249 * } );
12250 *
12251 * fieldset.addItems( [
12252 * new OO.ui.FieldLayout( input1, {
12253 * label: 'Field One'
12254 * } ),
12255 * new OO.ui.FieldLayout( input2, {
12256 * label: 'Field Two'
12257 * } )
12258 * ] );
12259 * $( document.body ).append( fieldset.$element );
12260 *
12261 * [1]: https://www.mediawiki.org/wiki/OOUI/Layouts/Fields_and_Fieldsets
12262 *
12263 * @class
12264 * @extends OO.ui.Layout
12265 * @mixins OO.ui.mixin.IconElement
12266 * @mixins OO.ui.mixin.LabelElement
12267 * @mixins OO.ui.mixin.GroupElement
12268 *
12269 * @constructor
12270 * @param {Object} [config] Configuration options
12271 * @cfg {OO.ui.FieldLayout[]} [items] An array of fields to add to the fieldset.
12272 * See OO.ui.FieldLayout for more information about fields.
12273 * @cfg {string|OO.ui.HtmlSnippet} [help] Help text. When help text is specified, a "help" icon
12274 * will appear in the upper-right corner of the rendered field; clicking it will display the text
12275 * in a popup. For important messages, you are advised to use `notices`, as they are always shown.
12276 * @cfg {jQuery} [$overlay] Passed to OO.ui.PopupButtonWidget for help popup, if `help` is given.
12277 * See <https://www.mediawiki.org/wiki/OOUI/Concepts#Overlays>.
12278 */
12279 OO.ui.FieldsetLayout = function OoUiFieldsetLayout( config ) {
12280 // Configuration initialization
12281 config = config || {};
12282
12283 // Parent constructor
12284 OO.ui.FieldsetLayout.parent.call( this, config );
12285
12286 // Mixin constructors
12287 OO.ui.mixin.IconElement.call( this, config );
12288 OO.ui.mixin.LabelElement.call( this, config );
12289 OO.ui.mixin.GroupElement.call( this, config );
12290
12291 // Properties
12292 this.$header = $( '<legend>' );
12293 if ( config.help ) {
12294 this.popupButtonWidget = new OO.ui.PopupButtonWidget( {
12295 $overlay: config.$overlay,
12296 popup: {
12297 padded: true
12298 },
12299 classes: [ 'oo-ui-fieldsetLayout-help' ],
12300 framed: false,
12301 icon: 'info',
12302 label: OO.ui.msg( 'ooui-field-help' ),
12303 invisibleLabel: true
12304 } );
12305 if ( config.help instanceof OO.ui.HtmlSnippet ) {
12306 this.popupButtonWidget.getPopup().$body.html( config.help.toString() );
12307 } else {
12308 this.popupButtonWidget.getPopup().$body.text( config.help );
12309 }
12310 this.$help = this.popupButtonWidget.$element;
12311 } else {
12312 this.$help = $( [] );
12313 }
12314
12315 // Initialization
12316 this.$header
12317 .addClass( 'oo-ui-fieldsetLayout-header' )
12318 .append( this.$icon, this.$label, this.$help );
12319 this.$group.addClass( 'oo-ui-fieldsetLayout-group' );
12320 this.$element
12321 .addClass( 'oo-ui-fieldsetLayout' )
12322 .prepend( this.$header, this.$group );
12323 if ( Array.isArray( config.items ) ) {
12324 this.addItems( config.items );
12325 }
12326 };
12327
12328 /* Setup */
12329
12330 OO.inheritClass( OO.ui.FieldsetLayout, OO.ui.Layout );
12331 OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.mixin.IconElement );
12332 OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.mixin.LabelElement );
12333 OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.mixin.GroupElement );
12334
12335 /* Static Properties */
12336
12337 /**
12338 * @static
12339 * @inheritdoc
12340 */
12341 OO.ui.FieldsetLayout.static.tagName = 'fieldset';
12342
12343 /**
12344 * FormLayouts are used to wrap {@link OO.ui.FieldsetLayout FieldsetLayouts} when you intend to use
12345 * browser-based form submission for the fields instead of handling them in JavaScript. Form layouts
12346 * can be configured with an HTML form action, an encoding type, and a method using the #action,
12347 * #enctype, and #method configs, respectively.
12348 * See the [OOUI documentation on MediaWiki] [1] for more information and examples.
12349 *
12350 * Only widgets from the {@link OO.ui.InputWidget InputWidget} family support form submission. It
12351 * includes standard form elements like {@link OO.ui.CheckboxInputWidget checkboxes}, {@link
12352 * OO.ui.RadioInputWidget radio buttons} and {@link OO.ui.TextInputWidget text fields}, as well as
12353 * some fancier controls. Some controls have both regular and InputWidget variants, for example
12354 * OO.ui.DropdownWidget and OO.ui.DropdownInputWidget – only the latter support form submission and
12355 * often have simplified APIs to match the capabilities of HTML forms.
12356 * See the [OOUI documentation on MediaWiki] [2] for more information about InputWidgets.
12357 *
12358 * [1]: https://www.mediawiki.org/wiki/OOUI/Layouts/Forms
12359 * [2]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
12360 *
12361 * @example
12362 * // Example of a form layout that wraps a fieldset layout
12363 * var input1 = new OO.ui.TextInputWidget( {
12364 * placeholder: 'Username'
12365 * } );
12366 * var input2 = new OO.ui.TextInputWidget( {
12367 * placeholder: 'Password',
12368 * type: 'password'
12369 * } );
12370 * var submit = new OO.ui.ButtonInputWidget( {
12371 * label: 'Submit'
12372 * } );
12373 *
12374 * var fieldset = new OO.ui.FieldsetLayout( {
12375 * label: 'A form layout'
12376 * } );
12377 * fieldset.addItems( [
12378 * new OO.ui.FieldLayout( input1, {
12379 * label: 'Username',
12380 * align: 'top'
12381 * } ),
12382 * new OO.ui.FieldLayout( input2, {
12383 * label: 'Password',
12384 * align: 'top'
12385 * } ),
12386 * new OO.ui.FieldLayout( submit )
12387 * ] );
12388 * var form = new OO.ui.FormLayout( {
12389 * items: [ fieldset ],
12390 * action: '/api/formhandler',
12391 * method: 'get'
12392 * } )
12393 * $( document.body ).append( form.$element );
12394 *
12395 * @class
12396 * @extends OO.ui.Layout
12397 * @mixins OO.ui.mixin.GroupElement
12398 *
12399 * @constructor
12400 * @param {Object} [config] Configuration options
12401 * @cfg {string} [method] HTML form `method` attribute
12402 * @cfg {string} [action] HTML form `action` attribute
12403 * @cfg {string} [enctype] HTML form `enctype` attribute
12404 * @cfg {OO.ui.FieldsetLayout[]} [items] Fieldset layouts to add to the form layout.
12405 */
12406 OO.ui.FormLayout = function OoUiFormLayout( config ) {
12407 var action;
12408
12409 // Configuration initialization
12410 config = config || {};
12411
12412 // Parent constructor
12413 OO.ui.FormLayout.parent.call( this, config );
12414
12415 // Mixin constructors
12416 OO.ui.mixin.GroupElement.call( this, $.extend( { $group: this.$element }, config ) );
12417
12418 // Events
12419 this.$element.on( 'submit', this.onFormSubmit.bind( this ) );
12420
12421 // Make sure the action is safe
12422 action = config.action;
12423 if ( action !== undefined && !OO.ui.isSafeUrl( action ) ) {
12424 action = './' + action;
12425 }
12426
12427 // Initialization
12428 this.$element
12429 .addClass( 'oo-ui-formLayout' )
12430 .attr( {
12431 method: config.method,
12432 action: action,
12433 enctype: config.enctype
12434 } );
12435 if ( Array.isArray( config.items ) ) {
12436 this.addItems( config.items );
12437 }
12438 };
12439
12440 /* Setup */
12441
12442 OO.inheritClass( OO.ui.FormLayout, OO.ui.Layout );
12443 OO.mixinClass( OO.ui.FormLayout, OO.ui.mixin.GroupElement );
12444
12445 /* Events */
12446
12447 /**
12448 * A 'submit' event is emitted when the form is submitted.
12449 *
12450 * @event submit
12451 */
12452
12453 /* Static Properties */
12454
12455 /**
12456 * @static
12457 * @inheritdoc
12458 */
12459 OO.ui.FormLayout.static.tagName = 'form';
12460
12461 /* Methods */
12462
12463 /**
12464 * Handle form submit events.
12465 *
12466 * @private
12467 * @param {jQuery.Event} e Submit event
12468 * @fires submit
12469 * @return {OO.ui.FormLayout} The layout, for chaining
12470 */
12471 OO.ui.FormLayout.prototype.onFormSubmit = function () {
12472 if ( this.emit( 'submit' ) ) {
12473 return false;
12474 }
12475 };
12476
12477 /**
12478 * PanelLayouts expand to cover the entire area of their parent. They can be configured with
12479 * scrolling, padding, and a frame, and are often used together with
12480 * {@link OO.ui.StackLayout StackLayouts}.
12481 *
12482 * @example
12483 * // Example of a panel layout
12484 * var panel = new OO.ui.PanelLayout( {
12485 * expanded: false,
12486 * framed: true,
12487 * padded: true,
12488 * $content: $( '<p>A panel layout with padding and a frame.</p>' )
12489 * } );
12490 * $( document.body ).append( panel.$element );
12491 *
12492 * @class
12493 * @extends OO.ui.Layout
12494 *
12495 * @constructor
12496 * @param {Object} [config] Configuration options
12497 * @cfg {boolean} [scrollable=false] Allow vertical scrolling
12498 * @cfg {boolean} [padded=false] Add padding between the content and the edges of the panel.
12499 * @cfg {boolean} [expanded=true] Expand the panel to fill the entire parent element.
12500 * @cfg {boolean} [framed=false] Render the panel with a frame to visually separate it from outside
12501 * content.
12502 */
12503 OO.ui.PanelLayout = function OoUiPanelLayout( config ) {
12504 // Configuration initialization
12505 config = $.extend( {
12506 scrollable: false,
12507 padded: false,
12508 expanded: true,
12509 framed: false
12510 }, config );
12511
12512 // Parent constructor
12513 OO.ui.PanelLayout.parent.call( this, config );
12514
12515 // Initialization
12516 this.$element.addClass( 'oo-ui-panelLayout' );
12517 if ( config.scrollable ) {
12518 this.$element.addClass( 'oo-ui-panelLayout-scrollable' );
12519 }
12520 if ( config.padded ) {
12521 this.$element.addClass( 'oo-ui-panelLayout-padded' );
12522 }
12523 if ( config.expanded ) {
12524 this.$element.addClass( 'oo-ui-panelLayout-expanded' );
12525 }
12526 if ( config.framed ) {
12527 this.$element.addClass( 'oo-ui-panelLayout-framed' );
12528 }
12529 };
12530
12531 /* Setup */
12532
12533 OO.inheritClass( OO.ui.PanelLayout, OO.ui.Layout );
12534
12535 /* Static Methods */
12536
12537 /**
12538 * @inheritdoc
12539 */
12540 OO.ui.PanelLayout.static.reusePreInfuseDOM = function ( node, config ) {
12541 config = OO.ui.PanelLayout.parent.static.reusePreInfuseDOM( node, config );
12542 if ( config.preserveContent !== false ) {
12543 config.$content = $( node ).contents();
12544 }
12545 return config;
12546 };
12547
12548 /* Methods */
12549
12550 /**
12551 * Focus the panel layout
12552 *
12553 * The default implementation just focuses the first focusable element in the panel
12554 */
12555 OO.ui.PanelLayout.prototype.focus = function () {
12556 OO.ui.findFocusable( this.$element ).focus();
12557 };
12558
12559 /**
12560 * HorizontalLayout arranges its contents in a single line (using `display: inline-block` for its
12561 * items), with small margins between them. Convenient when you need to put a number of block-level
12562 * widgets on a single line next to each other.
12563 *
12564 * Note that inline elements, such as OO.ui.ButtonWidgets, do not need this wrapper.
12565 *
12566 * @example
12567 * // HorizontalLayout with a text input and a label
12568 * var layout = new OO.ui.HorizontalLayout( {
12569 * items: [
12570 * new OO.ui.LabelWidget( { label: 'Label' } ),
12571 * new OO.ui.TextInputWidget( { value: 'Text' } )
12572 * ]
12573 * } );
12574 * $( document.body ).append( layout.$element );
12575 *
12576 * @class
12577 * @extends OO.ui.Layout
12578 * @mixins OO.ui.mixin.GroupElement
12579 *
12580 * @constructor
12581 * @param {Object} [config] Configuration options
12582 * @cfg {OO.ui.Widget[]|OO.ui.Layout[]} [items] Widgets or other layouts to add to the layout.
12583 */
12584 OO.ui.HorizontalLayout = function OoUiHorizontalLayout( config ) {
12585 // Configuration initialization
12586 config = config || {};
12587
12588 // Parent constructor
12589 OO.ui.HorizontalLayout.parent.call( this, config );
12590
12591 // Mixin constructors
12592 OO.ui.mixin.GroupElement.call( this, $.extend( { $group: this.$element }, config ) );
12593
12594 // Initialization
12595 this.$element.addClass( 'oo-ui-horizontalLayout' );
12596 if ( Array.isArray( config.items ) ) {
12597 this.addItems( config.items );
12598 }
12599 };
12600
12601 /* Setup */
12602
12603 OO.inheritClass( OO.ui.HorizontalLayout, OO.ui.Layout );
12604 OO.mixinClass( OO.ui.HorizontalLayout, OO.ui.mixin.GroupElement );
12605
12606 /**
12607 * NumberInputWidgets combine a {@link OO.ui.TextInputWidget text input} (where a value
12608 * can be entered manually) and two {@link OO.ui.ButtonWidget button widgets}
12609 * (to adjust the value in increments) to allow the user to enter a number.
12610 *
12611 * @example
12612 * // A NumberInputWidget.
12613 * var numberInput = new OO.ui.NumberInputWidget( {
12614 * label: 'NumberInputWidget',
12615 * input: { value: 5 },
12616 * min: 1,
12617 * max: 10
12618 * } );
12619 * $( document.body ).append( numberInput.$element );
12620 *
12621 * @class
12622 * @extends OO.ui.TextInputWidget
12623 *
12624 * @constructor
12625 * @param {Object} [config] Configuration options
12626 * @cfg {Object} [minusButton] Configuration options to pass to the
12627 * {@link OO.ui.ButtonWidget decrementing button widget}.
12628 * @cfg {Object} [plusButton] Configuration options to pass to the
12629 * {@link OO.ui.ButtonWidget incrementing button widget}.
12630 * @cfg {number} [min=-Infinity] Minimum allowed value
12631 * @cfg {number} [max=Infinity] Maximum allowed value
12632 * @cfg {number|null} [step] If specified, the field only accepts values that are multiples of this.
12633 * @cfg {number} [buttonStep=step||1] Delta when using the buttons or Up/Down arrow keys.
12634 * Defaults to `step` if specified, otherwise `1`.
12635 * @cfg {number} [pageStep=10*buttonStep] Delta when using the Page-up/Page-down keys.
12636 * Defaults to 10 times `buttonStep`.
12637 * @cfg {boolean} [showButtons=true] Whether to show the plus and minus buttons.
12638 */
12639 OO.ui.NumberInputWidget = function OoUiNumberInputWidget( config ) {
12640 var $field = $( '<div>' ).addClass( 'oo-ui-numberInputWidget-field' );
12641
12642 // Configuration initialization
12643 config = $.extend( {
12644 min: -Infinity,
12645 max: Infinity,
12646 showButtons: true
12647 }, config );
12648
12649 // For backward compatibility
12650 $.extend( config, config.input );
12651 this.input = this;
12652
12653 // Parent constructor
12654 OO.ui.NumberInputWidget.parent.call( this, $.extend( config, {
12655 type: 'number'
12656 } ) );
12657
12658 if ( config.showButtons ) {
12659 this.minusButton = new OO.ui.ButtonWidget( $.extend(
12660 {
12661 disabled: this.isDisabled(),
12662 tabIndex: -1,
12663 classes: [ 'oo-ui-numberInputWidget-minusButton' ],
12664 icon: 'subtract'
12665 },
12666 config.minusButton
12667 ) );
12668 this.minusButton.$element.attr( 'aria-hidden', 'true' );
12669 this.plusButton = new OO.ui.ButtonWidget( $.extend(
12670 {
12671 disabled: this.isDisabled(),
12672 tabIndex: -1,
12673 classes: [ 'oo-ui-numberInputWidget-plusButton' ],
12674 icon: 'add'
12675 },
12676 config.plusButton
12677 ) );
12678 this.plusButton.$element.attr( 'aria-hidden', 'true' );
12679 }
12680
12681 // Events
12682 this.$input.on( {
12683 keydown: this.onKeyDown.bind( this ),
12684 'wheel mousewheel DOMMouseScroll': this.onWheel.bind( this )
12685 } );
12686 if ( config.showButtons ) {
12687 this.plusButton.connect( this, {
12688 click: [ 'onButtonClick', +1 ]
12689 } );
12690 this.minusButton.connect( this, {
12691 click: [ 'onButtonClick', -1 ]
12692 } );
12693 }
12694
12695 // Build the field
12696 $field.append( this.$input );
12697 if ( config.showButtons ) {
12698 $field
12699 .prepend( this.minusButton.$element )
12700 .append( this.plusButton.$element );
12701 }
12702
12703 // Initialization
12704 if ( config.allowInteger || config.isInteger ) {
12705 // Backward compatibility
12706 config.step = 1;
12707 }
12708 this.setRange( config.min, config.max );
12709 this.setStep( config.buttonStep, config.pageStep, config.step );
12710 // Set the validation method after we set step and range
12711 // so that it doesn't immediately call setValidityFlag
12712 this.setValidation( this.validateNumber.bind( this ) );
12713
12714 this.$element
12715 .addClass( 'oo-ui-numberInputWidget' )
12716 .toggleClass( 'oo-ui-numberInputWidget-buttoned', config.showButtons )
12717 .append( $field );
12718 };
12719
12720 /* Setup */
12721
12722 OO.inheritClass( OO.ui.NumberInputWidget, OO.ui.TextInputWidget );
12723
12724 /* Methods */
12725
12726 // Backward compatibility
12727 OO.ui.NumberInputWidget.prototype.setAllowInteger = function ( flag ) {
12728 this.setStep( flag ? 1 : null );
12729 };
12730 // Backward compatibility
12731 OO.ui.NumberInputWidget.prototype.setIsInteger = OO.ui.NumberInputWidget.prototype.setAllowInteger;
12732
12733 // Backward compatibility
12734 OO.ui.NumberInputWidget.prototype.getAllowInteger = function () {
12735 return this.step === 1;
12736 };
12737 // Backward compatibility
12738 OO.ui.NumberInputWidget.prototype.getIsInteger = OO.ui.NumberInputWidget.prototype.getAllowInteger;
12739
12740 /**
12741 * Set the range of allowed values
12742 *
12743 * @param {number} min Minimum allowed value
12744 * @param {number} max Maximum allowed value
12745 */
12746 OO.ui.NumberInputWidget.prototype.setRange = function ( min, max ) {
12747 if ( min > max ) {
12748 throw new Error( 'Minimum (' + min + ') must not be greater than maximum (' + max + ')' );
12749 }
12750 this.min = min;
12751 this.max = max;
12752 this.$input.attr( 'min', this.min );
12753 this.$input.attr( 'max', this.max );
12754 this.setValidityFlag();
12755 };
12756
12757 /**
12758 * Get the current range
12759 *
12760 * @return {number[]} Minimum and maximum values
12761 */
12762 OO.ui.NumberInputWidget.prototype.getRange = function () {
12763 return [ this.min, this.max ];
12764 };
12765
12766 /**
12767 * Set the stepping deltas
12768 *
12769 * @param {number} [buttonStep=step||1] Delta when using the buttons or up/down arrow keys.
12770 * Defaults to `step` if specified, otherwise `1`.
12771 * @param {number} [pageStep=10*buttonStep] Delta when using the page-up/page-down keys.
12772 * Defaults to 10 times `buttonStep`.
12773 * @param {number|null} [step] If specified, the field only accepts values that are multiples
12774 * of this.
12775 */
12776 OO.ui.NumberInputWidget.prototype.setStep = function ( buttonStep, pageStep, step ) {
12777 if ( buttonStep === undefined ) {
12778 buttonStep = step || 1;
12779 }
12780 if ( pageStep === undefined ) {
12781 pageStep = 10 * buttonStep;
12782 }
12783 if ( step !== null && step <= 0 ) {
12784 throw new Error( 'Step value, if given, must be positive' );
12785 }
12786 if ( buttonStep <= 0 ) {
12787 throw new Error( 'Button step value must be positive' );
12788 }
12789 if ( pageStep <= 0 ) {
12790 throw new Error( 'Page step value must be positive' );
12791 }
12792 this.step = step;
12793 this.buttonStep = buttonStep;
12794 this.pageStep = pageStep;
12795 this.$input.attr( 'step', this.step || 'any' );
12796 this.setValidityFlag();
12797 };
12798
12799 /**
12800 * @inheritdoc
12801 */
12802 OO.ui.NumberInputWidget.prototype.setValue = function ( value ) {
12803 if ( value === '' ) {
12804 // Some browsers allow a value in the input even if there isn't one reported by $input.val()
12805 // so here we make sure an 'empty' value is actually displayed as such.
12806 this.$input.val( '' );
12807 }
12808 return OO.ui.NumberInputWidget.parent.prototype.setValue.call( this, value );
12809 };
12810
12811 /**
12812 * Get the current stepping values
12813 *
12814 * @return {number[]} Button step, page step, and validity step
12815 */
12816 OO.ui.NumberInputWidget.prototype.getStep = function () {
12817 return [ this.buttonStep, this.pageStep, this.step ];
12818 };
12819
12820 /**
12821 * Get the current value of the widget as a number
12822 *
12823 * @return {number} May be NaN, or an invalid number
12824 */
12825 OO.ui.NumberInputWidget.prototype.getNumericValue = function () {
12826 return +this.getValue();
12827 };
12828
12829 /**
12830 * Adjust the value of the widget
12831 *
12832 * @param {number} delta Adjustment amount
12833 */
12834 OO.ui.NumberInputWidget.prototype.adjustValue = function ( delta ) {
12835 var n, v = this.getNumericValue();
12836
12837 delta = +delta;
12838 if ( isNaN( delta ) || !isFinite( delta ) ) {
12839 throw new Error( 'Delta must be a finite number' );
12840 }
12841
12842 if ( isNaN( v ) ) {
12843 n = 0;
12844 } else {
12845 n = v + delta;
12846 n = Math.max( Math.min( n, this.max ), this.min );
12847 if ( this.step ) {
12848 n = Math.round( n / this.step ) * this.step;
12849 }
12850 }
12851
12852 if ( n !== v ) {
12853 this.setValue( n );
12854 }
12855 };
12856 /**
12857 * Validate input
12858 *
12859 * @private
12860 * @param {string} value Field value
12861 * @return {boolean}
12862 */
12863 OO.ui.NumberInputWidget.prototype.validateNumber = function ( value ) {
12864 var n = +value;
12865 if ( value === '' ) {
12866 return !this.isRequired();
12867 }
12868
12869 if ( isNaN( n ) || !isFinite( n ) ) {
12870 return false;
12871 }
12872
12873 if ( this.step && Math.floor( n / this.step ) !== n / this.step ) {
12874 return false;
12875 }
12876
12877 if ( n < this.min || n > this.max ) {
12878 return false;
12879 }
12880
12881 return true;
12882 };
12883
12884 /**
12885 * Handle mouse click events.
12886 *
12887 * @private
12888 * @param {number} dir +1 or -1
12889 */
12890 OO.ui.NumberInputWidget.prototype.onButtonClick = function ( dir ) {
12891 this.adjustValue( dir * this.buttonStep );
12892 };
12893
12894 /**
12895 * Handle mouse wheel events.
12896 *
12897 * @private
12898 * @param {jQuery.Event} event
12899 * @return {undefined/boolean} False to prevent default if event is handled
12900 */
12901 OO.ui.NumberInputWidget.prototype.onWheel = function ( event ) {
12902 var delta = 0;
12903
12904 if ( !this.isDisabled() && this.$input.is( ':focus' ) ) {
12905 // Standard 'wheel' event
12906 if ( event.originalEvent.deltaMode !== undefined ) {
12907 this.sawWheelEvent = true;
12908 }
12909 if ( event.originalEvent.deltaY ) {
12910 delta = -event.originalEvent.deltaY;
12911 } else if ( event.originalEvent.deltaX ) {
12912 delta = event.originalEvent.deltaX;
12913 }
12914
12915 // Non-standard events
12916 if ( !this.sawWheelEvent ) {
12917 if ( event.originalEvent.wheelDeltaX ) {
12918 delta = -event.originalEvent.wheelDeltaX;
12919 } else if ( event.originalEvent.wheelDeltaY ) {
12920 delta = event.originalEvent.wheelDeltaY;
12921 } else if ( event.originalEvent.wheelDelta ) {
12922 delta = event.originalEvent.wheelDelta;
12923 } else if ( event.originalEvent.detail ) {
12924 delta = -event.originalEvent.detail;
12925 }
12926 }
12927
12928 if ( delta ) {
12929 delta = delta < 0 ? -1 : 1;
12930 this.adjustValue( delta * this.buttonStep );
12931 }
12932
12933 return false;
12934 }
12935 };
12936
12937 /**
12938 * Handle key down events.
12939 *
12940 * @private
12941 * @param {jQuery.Event} e Key down event
12942 * @return {undefined/boolean} False to prevent default if event is handled
12943 */
12944 OO.ui.NumberInputWidget.prototype.onKeyDown = function ( e ) {
12945 if ( !this.isDisabled() ) {
12946 switch ( e.which ) {
12947 case OO.ui.Keys.UP:
12948 this.adjustValue( this.buttonStep );
12949 return false;
12950 case OO.ui.Keys.DOWN:
12951 this.adjustValue( -this.buttonStep );
12952 return false;
12953 case OO.ui.Keys.PAGEUP:
12954 this.adjustValue( this.pageStep );
12955 return false;
12956 case OO.ui.Keys.PAGEDOWN:
12957 this.adjustValue( -this.pageStep );
12958 return false;
12959 }
12960 }
12961 };
12962
12963 /**
12964 * @inheritdoc
12965 */
12966 OO.ui.NumberInputWidget.prototype.setDisabled = function ( disabled ) {
12967 // Parent method
12968 OO.ui.NumberInputWidget.parent.prototype.setDisabled.call( this, disabled );
12969
12970 if ( this.minusButton ) {
12971 this.minusButton.setDisabled( this.isDisabled() );
12972 }
12973 if ( this.plusButton ) {
12974 this.plusButton.setDisabled( this.isDisabled() );
12975 }
12976
12977 return this;
12978 };
12979
12980 }( OO ) );
12981
12982 //# sourceMappingURL=oojs-ui-core.js.map.json