Merge "Add checkDependencies.php"
[lhc/web/wiklou.git] / resources / lib / ooui / oojs-ui-core.js
1 /*!
2 * OOUI v0.32.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-05-29T00:38:42Z
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 = Date.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 - ( Date.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 * @deprecated Since 0.31.1; use `Date.now()` instead.
327 * @return {number} Current timestamp, in milliseconds since the Unix epoch
328 */
329 OO.ui.now = function () {
330 OO.ui.warnDeprecation( 'OO.ui.now() is deprecated, use Date.now() instead' );
331 return Date.now();
332 };
333
334 /**
335 * Reconstitute a JavaScript object corresponding to a widget created by
336 * the PHP implementation.
337 *
338 * This is an alias for `OO.ui.Element.static.infuse()`.
339 *
340 * @param {string|HTMLElement|jQuery} idOrNode
341 * A DOM id (if a string) or node for the widget to infuse.
342 * @param {Object} [config] Configuration options
343 * @return {OO.ui.Element}
344 * The `OO.ui.Element` corresponding to this (infusable) document node.
345 */
346 OO.ui.infuse = function ( idOrNode, config ) {
347 return OO.ui.Element.static.infuse( idOrNode, config );
348 };
349
350 /**
351 * Get a localized message.
352 *
353 * After the message key, message parameters may optionally be passed. In the default
354 * implementation, any occurrences of $1 are replaced with the first parameter, $2 with the
355 * second parameter, etc.
356 * Alternative implementations of OO.ui.msg may use any substitution system they like, as long
357 * as they support unnamed, ordered message parameters.
358 *
359 * In environments that provide a localization system, this function should be overridden to
360 * return the message translated in the user's language. The default implementation always
361 * returns English messages. An example of doing this with
362 * [jQuery.i18n](https://github.com/wikimedia/jquery.i18n) follows.
363 *
364 * @example
365 * var i, iLen, button,
366 * messagePath = 'oojs-ui/dist/i18n/',
367 * languages = [ $.i18n().locale, 'ur', 'en' ],
368 * languageMap = {};
369 *
370 * for ( i = 0, iLen = languages.length; i < iLen; i++ ) {
371 * languageMap[ languages[ i ] ] = messagePath + languages[ i ].toLowerCase() + '.json';
372 * }
373 *
374 * $.i18n().load( languageMap ).done( function() {
375 * // Replace the built-in `msg` only once we've loaded the internationalization.
376 * // OOUI uses `OO.ui.deferMsg` for all initially-loaded messages. So long as
377 * // you put off creating any widgets until this promise is complete, no English
378 * // will be displayed.
379 * OO.ui.msg = $.i18n;
380 *
381 * // A button displaying "OK" in the default locale
382 * button = new OO.ui.ButtonWidget( {
383 * label: OO.ui.msg( 'ooui-dialog-message-accept' ),
384 * icon: 'check'
385 * } );
386 * $( document.body ).append( button.$element );
387 *
388 * // A button displaying "OK" in Urdu
389 * $.i18n().locale = 'ur';
390 * button = new OO.ui.ButtonWidget( {
391 * label: OO.ui.msg( 'ooui-dialog-message-accept' ),
392 * icon: 'check'
393 * } );
394 * $( document.body ).append( button.$element );
395 * } );
396 *
397 * @param {string} key Message key
398 * @param {...Mixed} [params] Message parameters
399 * @return {string} Translated message with parameters substituted
400 */
401 OO.ui.msg = function ( key ) {
402 // `OO.ui.msg.messages` is defined in code generated during the build process
403 var messages = OO.ui.msg.messages,
404 message = messages[ key ],
405 params = Array.prototype.slice.call( arguments, 1 );
406 if ( typeof message === 'string' ) {
407 // Perform $1 substitution
408 message = message.replace( /\$(\d+)/g, function ( unused, n ) {
409 var i = parseInt( n, 10 );
410 return params[ i - 1 ] !== undefined ? params[ i - 1 ] : '$' + n;
411 } );
412 } else {
413 // Return placeholder if message not found
414 message = '[' + key + ']';
415 }
416 return message;
417 };
418
419 /**
420 * Package a message and arguments for deferred resolution.
421 *
422 * Use this when you are statically specifying a message and the message may not yet be present.
423 *
424 * @param {string} key Message key
425 * @param {...Mixed} [params] Message parameters
426 * @return {Function} Function that returns the resolved message when executed
427 */
428 OO.ui.deferMsg = function () {
429 var args = arguments;
430 return function () {
431 return OO.ui.msg.apply( OO.ui, args );
432 };
433 };
434
435 /**
436 * Resolve a message.
437 *
438 * If the message is a function it will be executed, otherwise it will pass through directly.
439 *
440 * @param {Function|string} msg Deferred message, or message text
441 * @return {string} Resolved message
442 */
443 OO.ui.resolveMsg = function ( msg ) {
444 if ( typeof msg === 'function' ) {
445 return msg();
446 }
447 return msg;
448 };
449
450 /**
451 * @param {string} url
452 * @return {boolean}
453 */
454 OO.ui.isSafeUrl = function ( url ) {
455 // Keep this function in sync with php/Tag.php
456 var i, protocolWhitelist;
457
458 function stringStartsWith( haystack, needle ) {
459 return haystack.substr( 0, needle.length ) === needle;
460 }
461
462 protocolWhitelist = [
463 'bitcoin', 'ftp', 'ftps', 'geo', 'git', 'gopher', 'http', 'https', 'irc', 'ircs',
464 'magnet', 'mailto', 'mms', 'news', 'nntp', 'redis', 'sftp', 'sip', 'sips', 'sms', 'ssh',
465 'svn', 'tel', 'telnet', 'urn', 'worldwind', 'xmpp'
466 ];
467
468 if ( url === '' ) {
469 return true;
470 }
471
472 for ( i = 0; i < protocolWhitelist.length; i++ ) {
473 if ( stringStartsWith( url, protocolWhitelist[ i ] + ':' ) ) {
474 return true;
475 }
476 }
477
478 // This matches '//' too
479 if ( stringStartsWith( url, '/' ) || stringStartsWith( url, './' ) ) {
480 return true;
481 }
482 if ( stringStartsWith( url, '?' ) || stringStartsWith( url, '#' ) ) {
483 return true;
484 }
485
486 return false;
487 };
488
489 /**
490 * Check if the user has a 'mobile' device.
491 *
492 * For our purposes this means the user is primarily using an
493 * on-screen keyboard, touch input instead of a mouse and may
494 * have a physically small display.
495 *
496 * It is left up to implementors to decide how to compute this
497 * so the default implementation always returns false.
498 *
499 * @return {boolean} User is on a mobile device
500 */
501 OO.ui.isMobile = function () {
502 return false;
503 };
504
505 /**
506 * Get the additional spacing that should be taken into account when displaying elements that are
507 * clipped to the viewport, e.g. dropdown menus and popups. This is meant to be overridden to avoid
508 * such menus overlapping any fixed headers/toolbars/navigation used by the site.
509 *
510 * @return {Object} Object with the properties 'top', 'right', 'bottom', 'left', each representing
511 * the extra spacing from that edge of viewport (in pixels)
512 */
513 OO.ui.getViewportSpacing = function () {
514 return {
515 top: 0,
516 right: 0,
517 bottom: 0,
518 left: 0
519 };
520 };
521
522 /**
523 * Get the default overlay, which is used by various widgets when they are passed `$overlay: true`.
524 * See <https://www.mediawiki.org/wiki/OOUI/Concepts#Overlays>.
525 *
526 * @return {jQuery} Default overlay node
527 */
528 OO.ui.getDefaultOverlay = function () {
529 if ( !OO.ui.$defaultOverlay ) {
530 OO.ui.$defaultOverlay = $( '<div>' ).addClass( 'oo-ui-defaultOverlay' );
531 $( document.body ).append( OO.ui.$defaultOverlay );
532 }
533 return OO.ui.$defaultOverlay;
534 };
535
536 /**
537 * Message store for the default implementation of OO.ui.msg.
538 *
539 * Environments that provide a localization system should not use this, but should override
540 * OO.ui.msg altogether.
541 *
542 * @private
543 */
544 OO.ui.msg.messages = {
545 "ooui-outline-control-move-down": "Move item down",
546 "ooui-outline-control-move-up": "Move item up",
547 "ooui-outline-control-remove": "Remove item",
548 "ooui-toolbar-more": "More",
549 "ooui-toolgroup-expand": "More",
550 "ooui-toolgroup-collapse": "Fewer",
551 "ooui-item-remove": "Remove",
552 "ooui-dialog-message-accept": "OK",
553 "ooui-dialog-message-reject": "Cancel",
554 "ooui-dialog-process-error": "Something went wrong",
555 "ooui-dialog-process-dismiss": "Dismiss",
556 "ooui-dialog-process-retry": "Try again",
557 "ooui-dialog-process-continue": "Continue",
558 "ooui-combobox-button-label": "Dropdown for combobox",
559 "ooui-selectfile-button-select": "Select a file",
560 "ooui-selectfile-not-supported": "File selection is not supported",
561 "ooui-selectfile-placeholder": "No file is selected",
562 "ooui-selectfile-dragdrop-placeholder": "Drop file here",
563 "ooui-field-help": "Help"
564 };
565
566 /*!
567 * Mixin namespace.
568 */
569
570 /**
571 * Namespace for OOUI mixins.
572 *
573 * Mixins are named according to the type of object they are intended to
574 * be mixed in to. For example, OO.ui.mixin.GroupElement is intended to be
575 * mixed in to an instance of OO.ui.Element, and OO.ui.mixin.GroupWidget
576 * is intended to be mixed in to an instance of OO.ui.Widget.
577 *
578 * @class
579 * @singleton
580 */
581 OO.ui.mixin = {};
582
583 /**
584 * Each Element represents a rendering in the DOM—a button or an icon, for example, or anything
585 * that is visible to a user. Unlike {@link OO.ui.Widget widgets}, plain elements usually do not
586 * have events connected to them and can't be interacted with.
587 *
588 * @abstract
589 * @class
590 *
591 * @constructor
592 * @param {Object} [config] Configuration options
593 * @cfg {string[]} [classes] The names of the CSS classes to apply to the element. CSS styles are
594 * added to the top level (e.g., the outermost div) of the element. See the
595 * [OOUI documentation on MediaWiki][2] for an example.
596 * [2]: https://www.mediawiki.org/wiki/OOUI/Widgets/Buttons_and_Switches#cssExample
597 * @cfg {string} [id] The HTML id attribute used in the rendered tag.
598 * @cfg {string} [text] Text to insert
599 * @cfg {Array} [content] An array of content elements to append (after #text).
600 * Strings will be html-escaped; use an OO.ui.HtmlSnippet to append raw HTML.
601 * Instances of OO.ui.Element will have their $element appended.
602 * @cfg {jQuery} [$content] Content elements to append (after #text).
603 * @cfg {jQuery} [$element] Wrapper element. Defaults to a new element with #getTagName.
604 * @cfg {Mixed} [data] Custom data of any type or combination of types (e.g., string, number,
605 * array, object).
606 * Data can also be specified with the #setData method.
607 */
608 OO.ui.Element = function OoUiElement( config ) {
609 if ( OO.ui.isDemo ) {
610 this.initialConfig = config;
611 }
612 // Configuration initialization
613 config = config || {};
614
615 // Properties
616 this.$ = function () {
617 OO.ui.warnDeprecation( 'this.$ is deprecated, use global $ instead' );
618 return $.apply( this, arguments );
619 };
620 this.elementId = null;
621 this.visible = true;
622 this.data = config.data;
623 this.$element = config.$element ||
624 $( document.createElement( this.getTagName() ) );
625 this.elementGroup = null;
626
627 // Initialization
628 if ( Array.isArray( config.classes ) ) {
629 this.$element.addClass( config.classes );
630 }
631 if ( config.id ) {
632 this.setElementId( config.id );
633 }
634 if ( config.text ) {
635 this.$element.text( config.text );
636 }
637 if ( config.content ) {
638 // The `content` property treats plain strings as text; use an
639 // HtmlSnippet to append HTML content. `OO.ui.Element`s get their
640 // appropriate $element appended.
641 this.$element.append( config.content.map( function ( v ) {
642 if ( typeof v === 'string' ) {
643 // Escape string so it is properly represented in HTML.
644 // Don't create empty text nodes for empty strings.
645 return v ? document.createTextNode( v ) : undefined;
646 } else if ( v instanceof OO.ui.HtmlSnippet ) {
647 // Bypass escaping.
648 return v.toString();
649 } else if ( v instanceof OO.ui.Element ) {
650 return v.$element;
651 }
652 return v;
653 } ) );
654 }
655 if ( config.$content ) {
656 // The `$content` property treats plain strings as HTML.
657 this.$element.append( config.$content );
658 }
659 };
660
661 /* Setup */
662
663 OO.initClass( OO.ui.Element );
664
665 /* Static Properties */
666
667 /**
668 * The name of the HTML tag used by the element.
669 *
670 * The static value may be ignored if the #getTagName method is overridden.
671 *
672 * @static
673 * @inheritable
674 * @property {string}
675 */
676 OO.ui.Element.static.tagName = 'div';
677
678 /* Static Methods */
679
680 /**
681 * Reconstitute a JavaScript object corresponding to a widget created
682 * by the PHP implementation.
683 *
684 * @param {string|HTMLElement|jQuery} idOrNode
685 * A DOM id (if a string) or node for the widget to infuse.
686 * @param {Object} [config] Configuration options
687 * @return {OO.ui.Element}
688 * The `OO.ui.Element` corresponding to this (infusable) document node.
689 * For `Tag` objects emitted on the HTML side (used occasionally for content)
690 * the value returned is a newly-created Element wrapping around the existing
691 * DOM node.
692 */
693 OO.ui.Element.static.infuse = function ( idOrNode, config ) {
694 var obj = OO.ui.Element.static.unsafeInfuse( idOrNode, config, false );
695
696 if ( typeof idOrNode === 'string' ) {
697 // IDs deprecated since 0.29.7
698 OO.ui.warnDeprecation(
699 'Passing a string ID to infuse is deprecated. Use an HTMLElement or jQuery collection instead.'
700 );
701 }
702 // Verify that the type matches up.
703 // FIXME: uncomment after T89721 is fixed, see T90929.
704 /*
705 if ( !( obj instanceof this['class'] ) ) {
706 throw new Error( 'Infusion type mismatch!' );
707 }
708 */
709 return obj;
710 };
711
712 /**
713 * Implementation helper for `infuse`; skips the type check and has an
714 * extra property so that only the top-level invocation touches the DOM.
715 *
716 * @private
717 * @param {string|HTMLElement|jQuery} idOrNode
718 * @param {Object} [config] Configuration options
719 * @param {jQuery.Promise} [domPromise] A promise that will be resolved
720 * when the top-level widget of this infusion is inserted into DOM,
721 * replacing the original node; only used internally.
722 * @return {OO.ui.Element}
723 */
724 OO.ui.Element.static.unsafeInfuse = function ( idOrNode, config, domPromise ) {
725 // look for a cached result of a previous infusion.
726 var id, $elem, error, data, cls, parts, parent, obj, top, state, infusedChildren;
727 if ( typeof idOrNode === 'string' ) {
728 id = idOrNode;
729 $elem = $( document.getElementById( id ) );
730 } else {
731 $elem = $( idOrNode );
732 id = $elem.attr( 'id' );
733 }
734 if ( !$elem.length ) {
735 if ( typeof idOrNode === 'string' ) {
736 error = 'Widget not found: ' + idOrNode;
737 } else if ( idOrNode && idOrNode.selector ) {
738 error = 'Widget not found: ' + idOrNode.selector;
739 } else {
740 error = 'Widget not found';
741 }
742 throw new Error( error );
743 }
744 if ( $elem[ 0 ].oouiInfused ) {
745 $elem = $elem[ 0 ].oouiInfused;
746 }
747 data = $elem.data( 'ooui-infused' );
748 if ( data ) {
749 // cached!
750 if ( data === true ) {
751 throw new Error( 'Circular dependency! ' + id );
752 }
753 if ( domPromise ) {
754 // Pick up dynamic state, like focus, value of form inputs, scroll position, etc.
755 state = data.constructor.static.gatherPreInfuseState( $elem, data );
756 // Restore dynamic state after the new element is re-inserted into DOM under
757 // infused parent.
758 domPromise.done( data.restorePreInfuseState.bind( data, state ) );
759 infusedChildren = $elem.data( 'ooui-infused-children' );
760 if ( infusedChildren && infusedChildren.length ) {
761 infusedChildren.forEach( function ( data ) {
762 var state = data.constructor.static.gatherPreInfuseState( $elem, data );
763 domPromise.done( data.restorePreInfuseState.bind( data, state ) );
764 } );
765 }
766 }
767 return data;
768 }
769 data = $elem.attr( 'data-ooui' );
770 if ( !data ) {
771 throw new Error( 'No infusion data found: ' + id );
772 }
773 try {
774 data = JSON.parse( data );
775 } catch ( _ ) {
776 data = null;
777 }
778 if ( !( data && data._ ) ) {
779 throw new Error( 'No valid infusion data found: ' + id );
780 }
781 if ( data._ === 'Tag' ) {
782 // Special case: this is a raw Tag; wrap existing node, don't rebuild.
783 return new OO.ui.Element( $.extend( {}, config, { $element: $elem } ) );
784 }
785 parts = data._.split( '.' );
786 cls = OO.getProp.apply( OO, [ window ].concat( parts ) );
787 if ( cls === undefined ) {
788 throw new Error( 'Unknown widget type: id: ' + id + ', class: ' + data._ );
789 }
790
791 // Verify that we're creating an OO.ui.Element instance
792 parent = cls.parent;
793
794 while ( parent !== undefined ) {
795 if ( parent === OO.ui.Element ) {
796 // Safe
797 break;
798 }
799
800 parent = parent.parent;
801 }
802
803 if ( parent !== OO.ui.Element ) {
804 throw new Error( 'Unknown widget type: id: ' + id + ', class: ' + data._ );
805 }
806
807 if ( !domPromise ) {
808 top = $.Deferred();
809 domPromise = top.promise();
810 }
811 $elem.data( 'ooui-infused', true ); // prevent loops
812 data.id = id; // implicit
813 infusedChildren = [];
814 data = OO.copy( data, null, function deserialize( value ) {
815 var infused;
816 if ( OO.isPlainObject( value ) ) {
817 if ( value.tag ) {
818 infused = OO.ui.Element.static.unsafeInfuse( value.tag, config, domPromise );
819 infusedChildren.push( infused );
820 // Flatten the structure
821 infusedChildren.push.apply(
822 infusedChildren,
823 infused.$element.data( 'ooui-infused-children' ) || []
824 );
825 infused.$element.removeData( 'ooui-infused-children' );
826 return infused;
827 }
828 if ( value.html !== undefined ) {
829 return new OO.ui.HtmlSnippet( value.html );
830 }
831 }
832 } );
833 // allow widgets to reuse parts of the DOM
834 data = cls.static.reusePreInfuseDOM( $elem[ 0 ], data );
835 // pick up dynamic state, like focus, value of form inputs, scroll position, etc.
836 state = cls.static.gatherPreInfuseState( $elem[ 0 ], data );
837 // rebuild widget
838 // eslint-disable-next-line new-cap
839 obj = new cls( $.extend( {}, config, data ) );
840 // If anyone is holding a reference to the old DOM element,
841 // let's allow them to OO.ui.infuse() it and do what they expect, see T105828.
842 // Do not use jQuery.data(), as using it on detached nodes leaks memory in 1.x line by design.
843 $elem[ 0 ].oouiInfused = obj.$element;
844 // now replace old DOM with this new DOM.
845 if ( top ) {
846 // An efficient constructor might be able to reuse the entire DOM tree of the original
847 // element, so only mutate the DOM if we need to.
848 if ( $elem[ 0 ] !== obj.$element[ 0 ] ) {
849 $elem.replaceWith( obj.$element );
850 }
851 top.resolve();
852 }
853 obj.$element.data( 'ooui-infused', obj );
854 obj.$element.data( 'ooui-infused-children', infusedChildren );
855 // set the 'data-ooui' attribute so we can identify infused widgets
856 obj.$element.attr( 'data-ooui', '' );
857 // restore dynamic state after the new element is inserted into DOM
858 domPromise.done( obj.restorePreInfuseState.bind( obj, state ) );
859 return obj;
860 };
861
862 /**
863 * Pick out parts of `node`'s DOM to be reused when infusing a widget.
864 *
865 * This method **must not** make any changes to the DOM, only find interesting pieces and add them
866 * to `config` (which should then be returned). Actual DOM juggling should then be done by the
867 * constructor, which will be given the enhanced config.
868 *
869 * @protected
870 * @param {HTMLElement} node
871 * @param {Object} config
872 * @return {Object}
873 */
874 OO.ui.Element.static.reusePreInfuseDOM = function ( node, config ) {
875 return config;
876 };
877
878 /**
879 * Gather the dynamic state (focus, value of form inputs, scroll position, etc.) of an HTML DOM
880 * node (and its children) that represent an Element of the same class and the given configuration,
881 * generated by the PHP implementation.
882 *
883 * This method is called just before `node` is detached from the DOM. The return value of this
884 * function will be passed to #restorePreInfuseState after the newly created widget's #$element
885 * is inserted into DOM to replace `node`.
886 *
887 * @protected
888 * @param {HTMLElement} node
889 * @param {Object} config
890 * @return {Object}
891 */
892 OO.ui.Element.static.gatherPreInfuseState = function () {
893 return {};
894 };
895
896 /**
897 * Get a jQuery function within a specific document.
898 *
899 * @static
900 * @param {jQuery|HTMLElement|HTMLDocument|Window} context Context to bind the function to
901 * @param {jQuery} [$iframe] HTML iframe element that contains the document, omit if document is
902 * not in an iframe
903 * @return {Function} Bound jQuery function
904 */
905 OO.ui.Element.static.getJQuery = function ( context, $iframe ) {
906 function wrapper( selector ) {
907 return $( selector, wrapper.context );
908 }
909
910 wrapper.context = this.getDocument( context );
911
912 if ( $iframe ) {
913 wrapper.$iframe = $iframe;
914 }
915
916 return wrapper;
917 };
918
919 /**
920 * Get the document of an element.
921 *
922 * @static
923 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Object to get the document for
924 * @return {HTMLDocument|null} Document object
925 */
926 OO.ui.Element.static.getDocument = function ( obj ) {
927 // jQuery - selections created "offscreen" won't have a context, so .context isn't reliable
928 return ( obj[ 0 ] && obj[ 0 ].ownerDocument ) ||
929 // Empty jQuery selections might have a context
930 obj.context ||
931 // HTMLElement
932 obj.ownerDocument ||
933 // Window
934 obj.document ||
935 // HTMLDocument
936 ( obj.nodeType === Node.DOCUMENT_NODE && obj ) ||
937 null;
938 };
939
940 /**
941 * Get the window of an element or document.
942 *
943 * @static
944 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the window for
945 * @return {Window} Window object
946 */
947 OO.ui.Element.static.getWindow = function ( obj ) {
948 var doc = this.getDocument( obj );
949 return doc.defaultView;
950 };
951
952 /**
953 * Get the direction of an element or document.
954 *
955 * @static
956 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the direction for
957 * @return {string} Text direction, either 'ltr' or 'rtl'
958 */
959 OO.ui.Element.static.getDir = function ( obj ) {
960 var isDoc, isWin;
961
962 if ( obj instanceof $ ) {
963 obj = obj[ 0 ];
964 }
965 isDoc = obj.nodeType === Node.DOCUMENT_NODE;
966 isWin = obj.document !== undefined;
967 if ( isDoc || isWin ) {
968 if ( isWin ) {
969 obj = obj.document;
970 }
971 obj = obj.body;
972 }
973 return $( obj ).css( 'direction' );
974 };
975
976 /**
977 * Get the offset between two frames.
978 *
979 * TODO: Make this function not use recursion.
980 *
981 * @static
982 * @param {Window} from Window of the child frame
983 * @param {Window} [to=window] Window of the parent frame
984 * @param {Object} [offset] Offset to start with, used internally
985 * @return {Object} Offset object, containing left and top properties
986 */
987 OO.ui.Element.static.getFrameOffset = function ( from, to, offset ) {
988 var i, len, frames, frame, rect;
989
990 if ( !to ) {
991 to = window;
992 }
993 if ( !offset ) {
994 offset = { top: 0, left: 0 };
995 }
996 if ( from.parent === from ) {
997 return offset;
998 }
999
1000 // Get iframe element
1001 frames = from.parent.document.getElementsByTagName( 'iframe' );
1002 for ( i = 0, len = frames.length; i < len; i++ ) {
1003 if ( frames[ i ].contentWindow === from ) {
1004 frame = frames[ i ];
1005 break;
1006 }
1007 }
1008
1009 // Recursively accumulate offset values
1010 if ( frame ) {
1011 rect = frame.getBoundingClientRect();
1012 offset.left += rect.left;
1013 offset.top += rect.top;
1014 if ( from !== to ) {
1015 this.getFrameOffset( from.parent, offset );
1016 }
1017 }
1018 return offset;
1019 };
1020
1021 /**
1022 * Get the offset between two elements.
1023 *
1024 * The two elements may be in a different frame, but in that case the frame $element is in must
1025 * be contained in the frame $anchor is in.
1026 *
1027 * @static
1028 * @param {jQuery} $element Element whose position to get
1029 * @param {jQuery} $anchor Element to get $element's position relative to
1030 * @return {Object} Translated position coordinates, containing top and left properties
1031 */
1032 OO.ui.Element.static.getRelativePosition = function ( $element, $anchor ) {
1033 var iframe, iframePos,
1034 pos = $element.offset(),
1035 anchorPos = $anchor.offset(),
1036 elementDocument = this.getDocument( $element ),
1037 anchorDocument = this.getDocument( $anchor );
1038
1039 // If $element isn't in the same document as $anchor, traverse up
1040 while ( elementDocument !== anchorDocument ) {
1041 iframe = elementDocument.defaultView.frameElement;
1042 if ( !iframe ) {
1043 throw new Error( '$element frame is not contained in $anchor frame' );
1044 }
1045 iframePos = $( iframe ).offset();
1046 pos.left += iframePos.left;
1047 pos.top += iframePos.top;
1048 elementDocument = iframe.ownerDocument;
1049 }
1050 pos.left -= anchorPos.left;
1051 pos.top -= anchorPos.top;
1052 return pos;
1053 };
1054
1055 /**
1056 * Get element border sizes.
1057 *
1058 * @static
1059 * @param {HTMLElement} el Element to measure
1060 * @return {Object} Dimensions object with `top`, `left`, `bottom` and `right` properties
1061 */
1062 OO.ui.Element.static.getBorders = function ( el ) {
1063 var doc = el.ownerDocument,
1064 win = doc.defaultView,
1065 style = win.getComputedStyle( el, null ),
1066 $el = $( el ),
1067 top = parseFloat( style ? style.borderTopWidth : $el.css( 'borderTopWidth' ) ) || 0,
1068 left = parseFloat( style ? style.borderLeftWidth : $el.css( 'borderLeftWidth' ) ) || 0,
1069 bottom = parseFloat( style ? style.borderBottomWidth : $el.css( 'borderBottomWidth' ) ) || 0,
1070 right = parseFloat( style ? style.borderRightWidth : $el.css( 'borderRightWidth' ) ) || 0;
1071
1072 return {
1073 top: top,
1074 left: left,
1075 bottom: bottom,
1076 right: right
1077 };
1078 };
1079
1080 /**
1081 * Get dimensions of an element or window.
1082 *
1083 * @static
1084 * @param {HTMLElement|Window} el Element to measure
1085 * @return {Object} Dimensions object with `borders`, `scroll`, `scrollbar` and `rect` properties
1086 */
1087 OO.ui.Element.static.getDimensions = function ( el ) {
1088 var $el, $win,
1089 doc = el.ownerDocument || el.document,
1090 win = doc.defaultView;
1091
1092 if ( win === el || el === doc.documentElement ) {
1093 $win = $( win );
1094 return {
1095 borders: { top: 0, left: 0, bottom: 0, right: 0 },
1096 scroll: {
1097 top: $win.scrollTop(),
1098 left: $win.scrollLeft()
1099 },
1100 scrollbar: { right: 0, bottom: 0 },
1101 rect: {
1102 top: 0,
1103 left: 0,
1104 bottom: $win.innerHeight(),
1105 right: $win.innerWidth()
1106 }
1107 };
1108 } else {
1109 $el = $( el );
1110 return {
1111 borders: this.getBorders( el ),
1112 scroll: {
1113 top: $el.scrollTop(),
1114 left: $el.scrollLeft()
1115 },
1116 scrollbar: {
1117 right: $el.innerWidth() - el.clientWidth,
1118 bottom: $el.innerHeight() - el.clientHeight
1119 },
1120 rect: el.getBoundingClientRect()
1121 };
1122 }
1123 };
1124
1125 /**
1126 * Get the number of pixels that an element's content is scrolled to the left.
1127 *
1128 * Adapted from <https://github.com/othree/jquery.rtl-scroll-type>.
1129 * Original code copyright 2012 Wei-Ko Kao, licensed under the MIT License.
1130 *
1131 * This function smooths out browser inconsistencies (nicely described in the README at
1132 * <https://github.com/othree/jquery.rtl-scroll-type>) and produces a result consistent
1133 * with Firefox's 'scrollLeft', which seems the sanest.
1134 *
1135 * @static
1136 * @method
1137 * @param {HTMLElement|Window} el Element to measure
1138 * @return {number} Scroll position from the left.
1139 * If the element's direction is LTR, this is a positive number between `0` (initial scroll
1140 * position) and `el.scrollWidth - el.clientWidth` (furthest possible scroll position).
1141 * If the element's direction is RTL, this is a negative number between `0` (initial scroll
1142 * position) and `-el.scrollWidth + el.clientWidth` (furthest possible scroll position).
1143 */
1144 OO.ui.Element.static.getScrollLeft = ( function () {
1145 var rtlScrollType = null;
1146
1147 function test() {
1148 var $definer = $( '<div>' ).attr( {
1149 dir: 'rtl',
1150 style: 'font-size: 14px; width: 4px; height: 1px; position: absolute; top: -1000px; overflow: scroll;'
1151 } ).text( 'ABCD' ),
1152 definer = $definer[ 0 ];
1153
1154 $definer.appendTo( 'body' );
1155 if ( definer.scrollLeft > 0 ) {
1156 // Safari, Chrome
1157 rtlScrollType = 'default';
1158 } else {
1159 definer.scrollLeft = 1;
1160 if ( definer.scrollLeft === 0 ) {
1161 // Firefox, old Opera
1162 rtlScrollType = 'negative';
1163 } else {
1164 // Internet Explorer, Edge
1165 rtlScrollType = 'reverse';
1166 }
1167 }
1168 $definer.remove();
1169 }
1170
1171 return function getScrollLeft( el ) {
1172 var isRoot = el.window === el ||
1173 el === el.ownerDocument.body ||
1174 el === el.ownerDocument.documentElement,
1175 scrollLeft = isRoot ? $( window ).scrollLeft() : el.scrollLeft,
1176 // All browsers use the correct scroll type ('negative') on the root, so don't
1177 // do any fixups when looking at the root element
1178 direction = isRoot ? 'ltr' : $( el ).css( 'direction' );
1179
1180 if ( direction === 'rtl' ) {
1181 if ( rtlScrollType === null ) {
1182 test();
1183 }
1184 if ( rtlScrollType === 'reverse' ) {
1185 scrollLeft = -scrollLeft;
1186 } else if ( rtlScrollType === 'default' ) {
1187 scrollLeft = scrollLeft - el.scrollWidth + el.clientWidth;
1188 }
1189 }
1190
1191 return scrollLeft;
1192 };
1193 }() );
1194
1195 /**
1196 * Get the root scrollable element of given element's document.
1197 *
1198 * On Blink-based browsers (Chrome etc.), `document.documentElement` can't be used to get or set
1199 * the scrollTop property; instead we have to use `document.body`. Changing and testing the value
1200 * lets us use 'body' or 'documentElement' based on what is working.
1201 *
1202 * https://code.google.com/p/chromium/issues/detail?id=303131
1203 *
1204 * @static
1205 * @param {HTMLElement} el Element to find root scrollable parent for
1206 * @return {HTMLElement} Scrollable parent, `document.body` or `document.documentElement`
1207 * depending on browser
1208 */
1209 OO.ui.Element.static.getRootScrollableElement = function ( el ) {
1210 var scrollTop, body;
1211
1212 if ( OO.ui.scrollableElement === undefined ) {
1213 body = el.ownerDocument.body;
1214 scrollTop = body.scrollTop;
1215 body.scrollTop = 1;
1216
1217 // In some browsers (observed in Chrome 56 on Linux Mint 18.1),
1218 // body.scrollTop doesn't become exactly 1, but a fractional value like 0.76
1219 if ( Math.round( body.scrollTop ) === 1 ) {
1220 body.scrollTop = scrollTop;
1221 OO.ui.scrollableElement = 'body';
1222 } else {
1223 OO.ui.scrollableElement = 'documentElement';
1224 }
1225 }
1226
1227 return el.ownerDocument[ OO.ui.scrollableElement ];
1228 };
1229
1230 /**
1231 * Get closest scrollable container.
1232 *
1233 * Traverses up until either a scrollable element or the root is reached, in which case the root
1234 * scrollable element will be returned (see #getRootScrollableElement).
1235 *
1236 * @static
1237 * @param {HTMLElement} el Element to find scrollable container for
1238 * @param {string} [dimension] Dimension of scrolling to look for; `x`, `y` or omit for either
1239 * @return {HTMLElement} Closest scrollable container
1240 */
1241 OO.ui.Element.static.getClosestScrollableContainer = function ( el, dimension ) {
1242 var i, val,
1243 // Browsers do not correctly return the computed value of 'overflow' when 'overflow-x' and
1244 // 'overflow-y' have different values, so we need to check the separate properties.
1245 props = [ 'overflow-x', 'overflow-y' ],
1246 $parent = $( el ).parent();
1247
1248 if ( dimension === 'x' || dimension === 'y' ) {
1249 props = [ 'overflow-' + dimension ];
1250 }
1251
1252 // Special case for the document root (which doesn't really have any scrollable container,
1253 // since it is the ultimate scrollable container, but this is probably saner than null or
1254 // exception).
1255 if ( $( el ).is( 'html, body' ) ) {
1256 return this.getRootScrollableElement( el );
1257 }
1258
1259 while ( $parent.length ) {
1260 if ( $parent[ 0 ] === this.getRootScrollableElement( el ) ) {
1261 return $parent[ 0 ];
1262 }
1263 i = props.length;
1264 while ( i-- ) {
1265 val = $parent.css( props[ i ] );
1266 // We assume that elements with 'overflow' (in any direction) set to 'hidden' will
1267 // never be scrolled in that direction, but they can actually be scrolled
1268 // programatically. The user can unintentionally perform a scroll in such case even if
1269 // the application doesn't scroll programatically, e.g. when jumping to an anchor, or
1270 // when using built-in find functionality.
1271 // This could cause funny issues...
1272 if ( val === 'auto' || val === 'scroll' ) {
1273 return $parent[ 0 ];
1274 }
1275 }
1276 $parent = $parent.parent();
1277 }
1278 // The element is unattached... return something mostly sane
1279 return this.getRootScrollableElement( el );
1280 };
1281
1282 /**
1283 * Scroll element into view.
1284 *
1285 * @static
1286 * @param {HTMLElement|Object} elOrPosition Element to scroll into view
1287 * @param {Object} [config] Configuration options
1288 * @param {string} [config.animate=true] Animate to the new scroll offset.
1289 * @param {string} [config.duration='fast'] jQuery animation duration value
1290 * @param {string} [config.direction] Scroll in only one direction, e.g. 'x' or 'y', omit
1291 * to scroll in both directions
1292 * @param {Object} [config.padding] Additional padding on the container to scroll past.
1293 * Object containing any of 'top', 'bottom', 'left', or 'right' as numbers.
1294 * @param {Object} [config.scrollContainer] Scroll container. Defaults to
1295 * getClosestScrollableContainer of the element.
1296 * @return {jQuery.Promise} Promise which resolves when the scroll is complete
1297 */
1298 OO.ui.Element.static.scrollIntoView = function ( elOrPosition, config ) {
1299 var position, animations, container, $container, elementPosition, containerDimensions,
1300 $window, padding, animate, method,
1301 deferred = $.Deferred();
1302
1303 // Configuration initialization
1304 config = config || {};
1305
1306 padding = $.extend( {
1307 top: 0,
1308 bottom: 0,
1309 left: 0,
1310 right: 0
1311 }, config.padding );
1312
1313 animate = config.animate !== false;
1314
1315 animations = {};
1316 elementPosition = elOrPosition instanceof HTMLElement ?
1317 this.getDimensions( elOrPosition ).rect :
1318 elOrPosition;
1319 container = config.scrollContainer || (
1320 elOrPosition instanceof HTMLElement ?
1321 this.getClosestScrollableContainer( elOrPosition, config.direction ) :
1322 // No scrollContainer or element
1323 this.getClosestScrollableContainer( document.body )
1324 );
1325 $container = $( container );
1326 containerDimensions = this.getDimensions( container );
1327 $window = $( this.getWindow( container ) );
1328
1329 // Compute the element's position relative to the container
1330 if ( $container.is( 'html, body' ) ) {
1331 // If the scrollable container is the root, this is easy
1332 position = {
1333 top: elementPosition.top,
1334 bottom: $window.innerHeight() - elementPosition.bottom,
1335 left: elementPosition.left,
1336 right: $window.innerWidth() - elementPosition.right
1337 };
1338 } else {
1339 // Otherwise, we have to subtract el's coordinates from container's coordinates
1340 position = {
1341 top: elementPosition.top -
1342 ( containerDimensions.rect.top + containerDimensions.borders.top ),
1343 bottom: containerDimensions.rect.bottom - containerDimensions.borders.bottom -
1344 containerDimensions.scrollbar.bottom - elementPosition.bottom,
1345 left: elementPosition.left -
1346 ( containerDimensions.rect.left + containerDimensions.borders.left ),
1347 right: containerDimensions.rect.right - containerDimensions.borders.right -
1348 containerDimensions.scrollbar.right - elementPosition.right
1349 };
1350 }
1351
1352 if ( !config.direction || config.direction === 'y' ) {
1353 if ( position.top < padding.top ) {
1354 animations.scrollTop = containerDimensions.scroll.top + position.top - padding.top;
1355 } else if ( position.bottom < padding.bottom ) {
1356 animations.scrollTop = containerDimensions.scroll.top +
1357 // Scroll the bottom into view, but not at the expense
1358 // of scrolling the top out of view
1359 Math.min( position.top - padding.top, -position.bottom + padding.bottom );
1360 }
1361 }
1362 if ( !config.direction || config.direction === 'x' ) {
1363 if ( position.left < padding.left ) {
1364 animations.scrollLeft = containerDimensions.scroll.left + position.left - padding.left;
1365 } else if ( position.right < padding.right ) {
1366 animations.scrollLeft = containerDimensions.scroll.left +
1367 // Scroll the right into view, but not at the expense
1368 // of scrolling the left out of view
1369 Math.min( position.left - padding.left, -position.right + padding.right );
1370 }
1371 }
1372 if ( !$.isEmptyObject( animations ) ) {
1373 if ( animate ) {
1374 // eslint-disable-next-line no-jquery/no-animate
1375 $container.stop( true ).animate( animations, config.duration === undefined ? 'fast' : config.duration );
1376 $container.queue( function ( next ) {
1377 deferred.resolve();
1378 next();
1379 } );
1380 } else {
1381 $container.stop( true );
1382 for ( method in animations ) {
1383 $container[ method ]( animations[ method ] );
1384 }
1385 deferred.resolve();
1386 }
1387 } else {
1388 deferred.resolve();
1389 }
1390 return deferred.promise();
1391 };
1392
1393 /**
1394 * Force the browser to reconsider whether it really needs to render scrollbars inside the element
1395 * and reserve space for them, because it probably doesn't.
1396 *
1397 * Workaround primarily for <https://code.google.com/p/chromium/issues/detail?id=387290>, but also
1398 * similar bugs in other browsers. "Just" forcing a reflow is not sufficient in all cases, we need
1399 * to first actually detach (or hide, but detaching is simpler) all children, *then* force a
1400 * reflow, and then reattach (or show) them back.
1401 *
1402 * @static
1403 * @param {HTMLElement} el Element to reconsider the scrollbars on
1404 */
1405 OO.ui.Element.static.reconsiderScrollbars = function ( el ) {
1406 var i, len, scrollLeft, scrollTop, nodes = [];
1407 // Save scroll position
1408 scrollLeft = el.scrollLeft;
1409 scrollTop = el.scrollTop;
1410 // Detach all children
1411 while ( el.firstChild ) {
1412 nodes.push( el.firstChild );
1413 el.removeChild( el.firstChild );
1414 }
1415 // Force reflow
1416 // eslint-disable-next-line no-void
1417 void el.offsetHeight;
1418 // Reattach all children
1419 for ( i = 0, len = nodes.length; i < len; i++ ) {
1420 el.appendChild( nodes[ i ] );
1421 }
1422 // Restore scroll position (no-op if scrollbars disappeared)
1423 el.scrollLeft = scrollLeft;
1424 el.scrollTop = scrollTop;
1425 };
1426
1427 /* Methods */
1428
1429 /**
1430 * Toggle visibility of an element.
1431 *
1432 * @param {boolean} [show] Make element visible, omit to toggle visibility
1433 * @fires visible
1434 * @chainable
1435 * @return {OO.ui.Element} The element, for chaining
1436 */
1437 OO.ui.Element.prototype.toggle = function ( show ) {
1438 show = show === undefined ? !this.visible : !!show;
1439
1440 if ( show !== this.isVisible() ) {
1441 this.visible = show;
1442 this.$element.toggleClass( 'oo-ui-element-hidden', !this.visible );
1443 this.emit( 'toggle', show );
1444 }
1445
1446 return this;
1447 };
1448
1449 /**
1450 * Check if element is visible.
1451 *
1452 * @return {boolean} element is visible
1453 */
1454 OO.ui.Element.prototype.isVisible = function () {
1455 return this.visible;
1456 };
1457
1458 /**
1459 * Get element data.
1460 *
1461 * @return {Mixed} Element data
1462 */
1463 OO.ui.Element.prototype.getData = function () {
1464 return this.data;
1465 };
1466
1467 /**
1468 * Set element data.
1469 *
1470 * @param {Mixed} data Element data
1471 * @chainable
1472 * @return {OO.ui.Element} The element, for chaining
1473 */
1474 OO.ui.Element.prototype.setData = function ( data ) {
1475 this.data = data;
1476 return this;
1477 };
1478
1479 /**
1480 * Set the element has an 'id' attribute.
1481 *
1482 * @param {string} id
1483 * @chainable
1484 * @return {OO.ui.Element} The element, for chaining
1485 */
1486 OO.ui.Element.prototype.setElementId = function ( id ) {
1487 this.elementId = id;
1488 this.$element.attr( 'id', id );
1489 return this;
1490 };
1491
1492 /**
1493 * Ensure that the element has an 'id' attribute, setting it to an unique value if it's missing,
1494 * and return its value.
1495 *
1496 * @return {string}
1497 */
1498 OO.ui.Element.prototype.getElementId = function () {
1499 if ( this.elementId === null ) {
1500 this.setElementId( OO.ui.generateElementId() );
1501 }
1502 return this.elementId;
1503 };
1504
1505 /**
1506 * Check if element supports one or more methods.
1507 *
1508 * @param {string|string[]} methods Method or list of methods to check
1509 * @return {boolean} All methods are supported
1510 */
1511 OO.ui.Element.prototype.supports = function ( methods ) {
1512 var i, len,
1513 support = 0;
1514
1515 methods = Array.isArray( methods ) ? methods : [ methods ];
1516 for ( i = 0, len = methods.length; i < len; i++ ) {
1517 if ( typeof this[ methods[ i ] ] === 'function' ) {
1518 support++;
1519 }
1520 }
1521
1522 return methods.length === support;
1523 };
1524
1525 /**
1526 * Update the theme-provided classes.
1527 *
1528 * @localdoc This is called in element mixins and widget classes any time state changes.
1529 * Updating is debounced, minimizing overhead of changing multiple attributes and
1530 * guaranteeing that theme updates do not occur within an element's constructor
1531 */
1532 OO.ui.Element.prototype.updateThemeClasses = function () {
1533 OO.ui.theme.queueUpdateElementClasses( this );
1534 };
1535
1536 /**
1537 * Get the HTML tag name.
1538 *
1539 * Override this method to base the result on instance information.
1540 *
1541 * @return {string} HTML tag name
1542 */
1543 OO.ui.Element.prototype.getTagName = function () {
1544 return this.constructor.static.tagName;
1545 };
1546
1547 /**
1548 * Check if the element is attached to the DOM
1549 *
1550 * @return {boolean} The element is attached to the DOM
1551 */
1552 OO.ui.Element.prototype.isElementAttached = function () {
1553 return $.contains( this.getElementDocument(), this.$element[ 0 ] );
1554 };
1555
1556 /**
1557 * Get the DOM document.
1558 *
1559 * @return {HTMLDocument} Document object
1560 */
1561 OO.ui.Element.prototype.getElementDocument = function () {
1562 // Don't cache this in other ways either because subclasses could can change this.$element
1563 return OO.ui.Element.static.getDocument( this.$element );
1564 };
1565
1566 /**
1567 * Get the DOM window.
1568 *
1569 * @return {Window} Window object
1570 */
1571 OO.ui.Element.prototype.getElementWindow = function () {
1572 return OO.ui.Element.static.getWindow( this.$element );
1573 };
1574
1575 /**
1576 * Get closest scrollable container.
1577 *
1578 * @return {HTMLElement} Closest scrollable container
1579 */
1580 OO.ui.Element.prototype.getClosestScrollableElementContainer = function () {
1581 return OO.ui.Element.static.getClosestScrollableContainer( this.$element[ 0 ] );
1582 };
1583
1584 /**
1585 * Get group element is in.
1586 *
1587 * @return {OO.ui.mixin.GroupElement|null} Group element, null if none
1588 */
1589 OO.ui.Element.prototype.getElementGroup = function () {
1590 return this.elementGroup;
1591 };
1592
1593 /**
1594 * Set group element is in.
1595 *
1596 * @param {OO.ui.mixin.GroupElement|null} group Group element, null if none
1597 * @chainable
1598 * @return {OO.ui.Element} The element, for chaining
1599 */
1600 OO.ui.Element.prototype.setElementGroup = function ( group ) {
1601 this.elementGroup = group;
1602 return this;
1603 };
1604
1605 /**
1606 * Scroll element into view.
1607 *
1608 * @param {Object} [config] Configuration options
1609 * @return {jQuery.Promise} Promise which resolves when the scroll is complete
1610 */
1611 OO.ui.Element.prototype.scrollElementIntoView = function ( config ) {
1612 if (
1613 !this.isElementAttached() ||
1614 !this.isVisible() ||
1615 ( this.getElementGroup() && !this.getElementGroup().isVisible() )
1616 ) {
1617 return $.Deferred().resolve();
1618 }
1619 return OO.ui.Element.static.scrollIntoView( this.$element[ 0 ], config );
1620 };
1621
1622 /**
1623 * Restore the pre-infusion dynamic state for this widget.
1624 *
1625 * This method is called after #$element has been inserted into DOM. The parameter is the return
1626 * value of #gatherPreInfuseState.
1627 *
1628 * @protected
1629 * @param {Object} state
1630 */
1631 OO.ui.Element.prototype.restorePreInfuseState = function () {
1632 };
1633
1634 /**
1635 * Wraps an HTML snippet for use with configuration values which default
1636 * to strings. This bypasses the default html-escaping done to string
1637 * values.
1638 *
1639 * @class
1640 *
1641 * @constructor
1642 * @param {string} [content] HTML content
1643 */
1644 OO.ui.HtmlSnippet = function OoUiHtmlSnippet( content ) {
1645 // Properties
1646 this.content = content;
1647 };
1648
1649 /* Setup */
1650
1651 OO.initClass( OO.ui.HtmlSnippet );
1652
1653 /* Methods */
1654
1655 /**
1656 * Render into HTML.
1657 *
1658 * @return {string} Unchanged HTML snippet.
1659 */
1660 OO.ui.HtmlSnippet.prototype.toString = function () {
1661 return this.content;
1662 };
1663
1664 /**
1665 * Layouts are containers for elements and are used to arrange other widgets of arbitrary type in
1666 * a way that is centrally controlled and can be updated dynamically. Layouts can be, and usually
1667 * are, combined.
1668 * See {@link OO.ui.FieldsetLayout FieldsetLayout}, {@link OO.ui.FieldLayout FieldLayout},
1669 * {@link OO.ui.FormLayout FormLayout}, {@link OO.ui.PanelLayout PanelLayout},
1670 * {@link OO.ui.StackLayout StackLayout}, {@link OO.ui.PageLayout PageLayout},
1671 * {@link OO.ui.HorizontalLayout HorizontalLayout}, and {@link OO.ui.BookletLayout BookletLayout}
1672 * for more information and examples.
1673 *
1674 * @abstract
1675 * @class
1676 * @extends OO.ui.Element
1677 * @mixins OO.EventEmitter
1678 *
1679 * @constructor
1680 * @param {Object} [config] Configuration options
1681 */
1682 OO.ui.Layout = function OoUiLayout( config ) {
1683 // Configuration initialization
1684 config = config || {};
1685
1686 // Parent constructor
1687 OO.ui.Layout.parent.call( this, config );
1688
1689 // Mixin constructors
1690 OO.EventEmitter.call( this );
1691
1692 // Initialization
1693 this.$element.addClass( 'oo-ui-layout' );
1694 };
1695
1696 /* Setup */
1697
1698 OO.inheritClass( OO.ui.Layout, OO.ui.Element );
1699 OO.mixinClass( OO.ui.Layout, OO.EventEmitter );
1700
1701 /* Methods */
1702
1703 /**
1704 * Reset scroll offsets
1705 *
1706 * @chainable
1707 * @return {OO.ui.Layout} The layout, for chaining
1708 */
1709 OO.ui.Layout.prototype.resetScroll = function () {
1710 this.$element[ 0 ].scrollTop = 0;
1711 // TODO: Reset scrollLeft in an RTL-aware manner, see OO.ui.Element.static.getScrollLeft.
1712
1713 return this;
1714 };
1715
1716 /**
1717 * Widgets are compositions of one or more OOUI elements that users can both view
1718 * and interact with. All widgets can be configured and modified via a standard API,
1719 * and their state can change dynamically according to a model.
1720 *
1721 * @abstract
1722 * @class
1723 * @extends OO.ui.Element
1724 * @mixins OO.EventEmitter
1725 *
1726 * @constructor
1727 * @param {Object} [config] Configuration options
1728 * @cfg {boolean} [disabled=false] Disable the widget. Disabled widgets cannot be used and their
1729 * appearance reflects this state.
1730 */
1731 OO.ui.Widget = function OoUiWidget( config ) {
1732 // Initialize config
1733 config = $.extend( { disabled: false }, config );
1734
1735 // Parent constructor
1736 OO.ui.Widget.parent.call( this, config );
1737
1738 // Mixin constructors
1739 OO.EventEmitter.call( this );
1740
1741 // Properties
1742 this.disabled = null;
1743 this.wasDisabled = null;
1744
1745 // Initialization
1746 this.$element.addClass( 'oo-ui-widget' );
1747 this.setDisabled( !!config.disabled );
1748 };
1749
1750 /* Setup */
1751
1752 OO.inheritClass( OO.ui.Widget, OO.ui.Element );
1753 OO.mixinClass( OO.ui.Widget, OO.EventEmitter );
1754
1755 /* Events */
1756
1757 /**
1758 * @event disable
1759 *
1760 * A 'disable' event is emitted when the disabled state of the widget changes
1761 * (i.e. on disable **and** enable).
1762 *
1763 * @param {boolean} disabled Widget is disabled
1764 */
1765
1766 /**
1767 * @event toggle
1768 *
1769 * A 'toggle' event is emitted when the visibility of the widget changes.
1770 *
1771 * @param {boolean} visible Widget is visible
1772 */
1773
1774 /* Methods */
1775
1776 /**
1777 * Check if the widget is disabled.
1778 *
1779 * @return {boolean} Widget is disabled
1780 */
1781 OO.ui.Widget.prototype.isDisabled = function () {
1782 return this.disabled;
1783 };
1784
1785 /**
1786 * Set the 'disabled' state of the widget.
1787 *
1788 * When a widget is disabled, it cannot be used and its appearance is updated to reflect this state.
1789 *
1790 * @param {boolean} disabled Disable widget
1791 * @chainable
1792 * @return {OO.ui.Widget} The widget, for chaining
1793 */
1794 OO.ui.Widget.prototype.setDisabled = function ( disabled ) {
1795 var isDisabled;
1796
1797 this.disabled = !!disabled;
1798 isDisabled = this.isDisabled();
1799 if ( isDisabled !== this.wasDisabled ) {
1800 this.$element.toggleClass( 'oo-ui-widget-disabled', isDisabled );
1801 this.$element.toggleClass( 'oo-ui-widget-enabled', !isDisabled );
1802 this.$element.attr( 'aria-disabled', isDisabled.toString() );
1803 this.emit( 'disable', isDisabled );
1804 this.updateThemeClasses();
1805 }
1806 this.wasDisabled = isDisabled;
1807
1808 return this;
1809 };
1810
1811 /**
1812 * Update the disabled state, in case of changes in parent widget.
1813 *
1814 * @chainable
1815 * @return {OO.ui.Widget} The widget, for chaining
1816 */
1817 OO.ui.Widget.prototype.updateDisabled = function () {
1818 this.setDisabled( this.disabled );
1819 return this;
1820 };
1821
1822 /**
1823 * Get an ID of a labelable node which is part of this widget, if any, to be used for `<label for>`
1824 * value.
1825 *
1826 * If this function returns null, the widget should have a meaningful #simulateLabelClick method
1827 * instead.
1828 *
1829 * @return {string|null} The ID of the labelable element
1830 */
1831 OO.ui.Widget.prototype.getInputId = function () {
1832 return null;
1833 };
1834
1835 /**
1836 * Simulate the behavior of clicking on a label (a HTML `<label>` element) bound to this input.
1837 * HTML only allows `<label>` to act on specific "labelable" elements; complex widgets might need to
1838 * override this method to provide intuitive, accessible behavior.
1839 *
1840 * By default, this does nothing. OO.ui.mixin.TabIndexedElement overrides it for focusable widgets.
1841 * Individual widgets may override it too.
1842 *
1843 * This method is called by OO.ui.LabelWidget and OO.ui.FieldLayout. It should not be called
1844 * directly.
1845 */
1846 OO.ui.Widget.prototype.simulateLabelClick = function () {
1847 };
1848
1849 /**
1850 * Theme logic.
1851 *
1852 * @abstract
1853 * @class
1854 *
1855 * @constructor
1856 */
1857 OO.ui.Theme = function OoUiTheme() {
1858 this.elementClassesQueue = [];
1859 this.debouncedUpdateQueuedElementClasses = OO.ui.debounce( this.updateQueuedElementClasses );
1860 };
1861
1862 /* Setup */
1863
1864 OO.initClass( OO.ui.Theme );
1865
1866 /* Methods */
1867
1868 /**
1869 * Get a list of classes to be applied to a widget.
1870 *
1871 * The 'on' and 'off' lists combined MUST contain keys for all classes the theme adds or removes,
1872 * otherwise state transitions will not work properly.
1873 *
1874 * @param {OO.ui.Element} element Element for which to get classes
1875 * @return {Object.<string,string[]>} Categorized class names with `on` and `off` lists
1876 */
1877 OO.ui.Theme.prototype.getElementClasses = function () {
1878 return { on: [], off: [] };
1879 };
1880
1881 /**
1882 * Update CSS classes provided by the theme.
1883 *
1884 * For elements with theme logic hooks, this should be called any time there's a state change.
1885 *
1886 * @param {OO.ui.Element} element Element for which to update classes
1887 */
1888 OO.ui.Theme.prototype.updateElementClasses = function ( element ) {
1889 var $elements = $( [] ),
1890 classes = this.getElementClasses( element );
1891
1892 if ( element.$icon ) {
1893 $elements = $elements.add( element.$icon );
1894 }
1895 if ( element.$indicator ) {
1896 $elements = $elements.add( element.$indicator );
1897 }
1898
1899 $elements
1900 .removeClass( classes.off )
1901 .addClass( classes.on );
1902 };
1903
1904 /**
1905 * @private
1906 */
1907 OO.ui.Theme.prototype.updateQueuedElementClasses = function () {
1908 var i;
1909 for ( i = 0; i < this.elementClassesQueue.length; i++ ) {
1910 this.updateElementClasses( this.elementClassesQueue[ i ] );
1911 }
1912 // Clear the queue
1913 this.elementClassesQueue = [];
1914 };
1915
1916 /**
1917 * Queue #updateElementClasses to be called for this element.
1918 *
1919 * @localdoc QUnit tests override this method to directly call #queueUpdateElementClasses,
1920 * to make them synchronous.
1921 *
1922 * @param {OO.ui.Element} element Element for which to update classes
1923 */
1924 OO.ui.Theme.prototype.queueUpdateElementClasses = function ( element ) {
1925 // Keep items in the queue unique. Use lastIndexOf to start checking from the end because that's
1926 // the most common case (this method is often called repeatedly for the same element).
1927 if ( this.elementClassesQueue.lastIndexOf( element ) !== -1 ) {
1928 return;
1929 }
1930 this.elementClassesQueue.push( element );
1931 this.debouncedUpdateQueuedElementClasses();
1932 };
1933
1934 /**
1935 * Get the transition duration in milliseconds for dialogs opening/closing
1936 *
1937 * The dialog should be fully rendered this many milliseconds after the
1938 * ready process has executed.
1939 *
1940 * @return {number} Transition duration in milliseconds
1941 */
1942 OO.ui.Theme.prototype.getDialogTransitionDuration = function () {
1943 return 0;
1944 };
1945
1946 /**
1947 * The TabIndexedElement class is an attribute mixin used to add additional functionality to an
1948 * element created by another class. The mixin provides a ‘tabIndex’ property, which specifies the
1949 * order in which users will navigate through the focusable elements via the Tab key.
1950 *
1951 * @example
1952 * // TabIndexedElement is mixed into the ButtonWidget class
1953 * // to provide a tabIndex property.
1954 * var button1 = new OO.ui.ButtonWidget( {
1955 * label: 'fourth',
1956 * tabIndex: 4
1957 * } ),
1958 * button2 = new OO.ui.ButtonWidget( {
1959 * label: 'second',
1960 * tabIndex: 2
1961 * } ),
1962 * button3 = new OO.ui.ButtonWidget( {
1963 * label: 'third',
1964 * tabIndex: 3
1965 * } ),
1966 * button4 = new OO.ui.ButtonWidget( {
1967 * label: 'first',
1968 * tabIndex: 1
1969 * } );
1970 * $( document.body ).append(
1971 * button1.$element,
1972 * button2.$element,
1973 * button3.$element,
1974 * button4.$element
1975 * );
1976 *
1977 * @abstract
1978 * @class
1979 *
1980 * @constructor
1981 * @param {Object} [config] Configuration options
1982 * @cfg {jQuery} [$tabIndexed] The element that should use the tabindex functionality. By default,
1983 * the functionality is applied to the element created by the class ($element). If a different
1984 * element is specified, the tabindex functionality will be applied to it instead.
1985 * @cfg {string|number|null} [tabIndex=0] Number that specifies the element’s position in the
1986 * tab-navigation order (e.g., 1 for the first focusable element). Use 0 to use the default
1987 * navigation order; use -1 to remove the element from the tab-navigation flow.
1988 */
1989 OO.ui.mixin.TabIndexedElement = function OoUiMixinTabIndexedElement( config ) {
1990 // Configuration initialization
1991 config = $.extend( { tabIndex: 0 }, config );
1992
1993 // Properties
1994 this.$tabIndexed = null;
1995 this.tabIndex = null;
1996
1997 // Events
1998 this.connect( this, {
1999 disable: 'onTabIndexedElementDisable'
2000 } );
2001
2002 // Initialization
2003 this.setTabIndex( config.tabIndex );
2004 this.setTabIndexedElement( config.$tabIndexed || this.$element );
2005 };
2006
2007 /* Setup */
2008
2009 OO.initClass( OO.ui.mixin.TabIndexedElement );
2010
2011 /* Methods */
2012
2013 /**
2014 * Set the element that should use the tabindex functionality.
2015 *
2016 * This method is used to retarget a tabindex mixin so that its functionality applies
2017 * to the specified element. If an element is currently using the functionality, the mixin’s
2018 * effect on that element is removed before the new element is set up.
2019 *
2020 * @param {jQuery} $tabIndexed Element that should use the tabindex functionality
2021 * @chainable
2022 * @return {OO.ui.Element} The element, for chaining
2023 */
2024 OO.ui.mixin.TabIndexedElement.prototype.setTabIndexedElement = function ( $tabIndexed ) {
2025 var tabIndex = this.tabIndex;
2026 // Remove attributes from old $tabIndexed
2027 this.setTabIndex( null );
2028 // Force update of new $tabIndexed
2029 this.$tabIndexed = $tabIndexed;
2030 this.tabIndex = tabIndex;
2031 return this.updateTabIndex();
2032 };
2033
2034 /**
2035 * Set the value of the tabindex.
2036 *
2037 * @param {string|number|null} tabIndex Tabindex value, or `null` for no tabindex
2038 * @chainable
2039 * @return {OO.ui.Element} The element, for chaining
2040 */
2041 OO.ui.mixin.TabIndexedElement.prototype.setTabIndex = function ( tabIndex ) {
2042 tabIndex = /^-?\d+$/.test( tabIndex ) ? Number( tabIndex ) : null;
2043
2044 if ( this.tabIndex !== tabIndex ) {
2045 this.tabIndex = tabIndex;
2046 this.updateTabIndex();
2047 }
2048
2049 return this;
2050 };
2051
2052 /**
2053 * Update the `tabindex` attribute, in case of changes to tab index or
2054 * disabled state.
2055 *
2056 * @private
2057 * @chainable
2058 * @return {OO.ui.Element} The element, for chaining
2059 */
2060 OO.ui.mixin.TabIndexedElement.prototype.updateTabIndex = function () {
2061 if ( this.$tabIndexed ) {
2062 if ( this.tabIndex !== null ) {
2063 // Do not index over disabled elements
2064 this.$tabIndexed.attr( {
2065 tabindex: this.isDisabled() ? -1 : this.tabIndex,
2066 // Support: ChromeVox and NVDA
2067 // These do not seem to inherit aria-disabled from parent elements
2068 'aria-disabled': this.isDisabled().toString()
2069 } );
2070 } else {
2071 this.$tabIndexed.removeAttr( 'tabindex aria-disabled' );
2072 }
2073 }
2074 return this;
2075 };
2076
2077 /**
2078 * Handle disable events.
2079 *
2080 * @private
2081 * @param {boolean} disabled Element is disabled
2082 */
2083 OO.ui.mixin.TabIndexedElement.prototype.onTabIndexedElementDisable = function () {
2084 this.updateTabIndex();
2085 };
2086
2087 /**
2088 * Get the value of the tabindex.
2089 *
2090 * @return {number|null} Tabindex value
2091 */
2092 OO.ui.mixin.TabIndexedElement.prototype.getTabIndex = function () {
2093 return this.tabIndex;
2094 };
2095
2096 /**
2097 * Get an ID of a focusable element of this widget, if any, to be used for `<label for>` value.
2098 *
2099 * If the element already has an ID then that is returned, otherwise unique ID is
2100 * generated, set on the element, and returned.
2101 *
2102 * @return {string|null} The ID of the focusable element
2103 */
2104 OO.ui.mixin.TabIndexedElement.prototype.getInputId = function () {
2105 var id;
2106
2107 if ( !this.$tabIndexed ) {
2108 return null;
2109 }
2110 if ( !this.isLabelableNode( this.$tabIndexed ) ) {
2111 return null;
2112 }
2113
2114 id = this.$tabIndexed.attr( 'id' );
2115 if ( id === undefined ) {
2116 id = OO.ui.generateElementId();
2117 this.$tabIndexed.attr( 'id', id );
2118 }
2119
2120 return id;
2121 };
2122
2123 /**
2124 * Whether the node is 'labelable' according to the HTML spec
2125 * (i.e., whether it can be interacted with through a `<label for="…">`).
2126 * See: <https://html.spec.whatwg.org/multipage/forms.html#category-label>.
2127 *
2128 * @private
2129 * @param {jQuery} $node
2130 * @return {boolean}
2131 */
2132 OO.ui.mixin.TabIndexedElement.prototype.isLabelableNode = function ( $node ) {
2133 var
2134 labelableTags = [ 'button', 'meter', 'output', 'progress', 'select', 'textarea' ],
2135 tagName = ( $node.prop( 'tagName' ) || '' ).toLowerCase();
2136
2137 if ( tagName === 'input' && $node.attr( 'type' ) !== 'hidden' ) {
2138 return true;
2139 }
2140 if ( labelableTags.indexOf( tagName ) !== -1 ) {
2141 return true;
2142 }
2143 return false;
2144 };
2145
2146 /**
2147 * Focus this element.
2148 *
2149 * @chainable
2150 * @return {OO.ui.Element} The element, for chaining
2151 */
2152 OO.ui.mixin.TabIndexedElement.prototype.focus = function () {
2153 if ( !this.isDisabled() ) {
2154 this.$tabIndexed.trigger( 'focus' );
2155 }
2156 return this;
2157 };
2158
2159 /**
2160 * Blur this element.
2161 *
2162 * @chainable
2163 * @return {OO.ui.Element} The element, for chaining
2164 */
2165 OO.ui.mixin.TabIndexedElement.prototype.blur = function () {
2166 this.$tabIndexed.trigger( 'blur' );
2167 return this;
2168 };
2169
2170 /**
2171 * @inheritdoc OO.ui.Widget
2172 */
2173 OO.ui.mixin.TabIndexedElement.prototype.simulateLabelClick = function () {
2174 this.focus();
2175 };
2176
2177 /**
2178 * ButtonElement is often mixed into other classes to generate a button, which is a clickable
2179 * interface element that can be configured with access keys for keyboard interaction.
2180 * See the [OOUI documentation on MediaWiki] [1] for examples.
2181 *
2182 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Buttons_and_Switches#Buttons
2183 *
2184 * @abstract
2185 * @class
2186 *
2187 * @constructor
2188 * @param {Object} [config] Configuration options
2189 * @cfg {jQuery} [$button] The button element created by the class.
2190 * If this configuration is omitted, the button element will use a generated `<a>`.
2191 * @cfg {boolean} [framed=true] Render the button with a frame
2192 */
2193 OO.ui.mixin.ButtonElement = function OoUiMixinButtonElement( config ) {
2194 // Configuration initialization
2195 config = config || {};
2196
2197 // Properties
2198 this.$button = null;
2199 this.framed = null;
2200 this.active = config.active !== undefined && config.active;
2201 this.onDocumentMouseUpHandler = this.onDocumentMouseUp.bind( this );
2202 this.onMouseDownHandler = this.onMouseDown.bind( this );
2203 this.onDocumentKeyUpHandler = this.onDocumentKeyUp.bind( this );
2204 this.onKeyDownHandler = this.onKeyDown.bind( this );
2205 this.onClickHandler = this.onClick.bind( this );
2206 this.onKeyPressHandler = this.onKeyPress.bind( this );
2207
2208 // Initialization
2209 this.$element.addClass( 'oo-ui-buttonElement' );
2210 this.toggleFramed( config.framed === undefined || config.framed );
2211 this.setButtonElement( config.$button || $( '<a>' ) );
2212 };
2213
2214 /* Setup */
2215
2216 OO.initClass( OO.ui.mixin.ButtonElement );
2217
2218 /* Static Properties */
2219
2220 /**
2221 * Cancel mouse down events.
2222 *
2223 * This property is usually set to `true` to prevent the focus from changing when the button is
2224 * clicked.
2225 * Classes such as {@link OO.ui.mixin.DraggableElement DraggableElement} and
2226 * {@link OO.ui.ButtonOptionWidget ButtonOptionWidget} use a value of `false` so that dragging
2227 * behavior is possible and mousedown events can be handled by a parent widget.
2228 *
2229 * @static
2230 * @inheritable
2231 * @property {boolean}
2232 */
2233 OO.ui.mixin.ButtonElement.static.cancelButtonMouseDownEvents = true;
2234
2235 /* Events */
2236
2237 /**
2238 * A 'click' event is emitted when the button element is clicked.
2239 *
2240 * @event click
2241 */
2242
2243 /* Methods */
2244
2245 /**
2246 * Set the button element.
2247 *
2248 * This method is used to retarget a button mixin so that its functionality applies to
2249 * the specified button element instead of the one created by the class. If a button element
2250 * is already set, the method will remove the mixin’s effect on that element.
2251 *
2252 * @param {jQuery} $button Element to use as button
2253 */
2254 OO.ui.mixin.ButtonElement.prototype.setButtonElement = function ( $button ) {
2255 if ( this.$button ) {
2256 this.$button
2257 .removeClass( 'oo-ui-buttonElement-button' )
2258 .removeAttr( 'role accesskey' )
2259 .off( {
2260 mousedown: this.onMouseDownHandler,
2261 keydown: this.onKeyDownHandler,
2262 click: this.onClickHandler,
2263 keypress: this.onKeyPressHandler
2264 } );
2265 }
2266
2267 this.$button = $button
2268 .addClass( 'oo-ui-buttonElement-button' )
2269 .on( {
2270 mousedown: this.onMouseDownHandler,
2271 keydown: this.onKeyDownHandler,
2272 click: this.onClickHandler,
2273 keypress: this.onKeyPressHandler
2274 } );
2275
2276 // Add `role="button"` on `<a>` elements, where it's needed
2277 // `toUpperCase()` is added for XHTML documents
2278 if ( this.$button.prop( 'tagName' ).toUpperCase() === 'A' ) {
2279 this.$button.attr( 'role', 'button' );
2280 }
2281 };
2282
2283 /**
2284 * Handles mouse down events.
2285 *
2286 * @protected
2287 * @param {jQuery.Event} e Mouse down event
2288 * @return {undefined|boolean} False to prevent default if event is handled
2289 */
2290 OO.ui.mixin.ButtonElement.prototype.onMouseDown = function ( e ) {
2291 if ( this.isDisabled() || e.which !== OO.ui.MouseButtons.LEFT ) {
2292 return;
2293 }
2294 this.$element.addClass( 'oo-ui-buttonElement-pressed' );
2295 // Run the mouseup handler no matter where the mouse is when the button is let go, so we can
2296 // reliably remove the pressed class
2297 this.getElementDocument().addEventListener( 'mouseup', this.onDocumentMouseUpHandler, true );
2298 // Prevent change of focus unless specifically configured otherwise
2299 if ( this.constructor.static.cancelButtonMouseDownEvents ) {
2300 return false;
2301 }
2302 };
2303
2304 /**
2305 * Handles document mouse up events.
2306 *
2307 * @protected
2308 * @param {MouseEvent} e Mouse up event
2309 */
2310 OO.ui.mixin.ButtonElement.prototype.onDocumentMouseUp = function ( e ) {
2311 if ( this.isDisabled() || e.which !== OO.ui.MouseButtons.LEFT ) {
2312 return;
2313 }
2314 this.$element.removeClass( 'oo-ui-buttonElement-pressed' );
2315 // Stop listening for mouseup, since we only needed this once
2316 this.getElementDocument().removeEventListener( 'mouseup', this.onDocumentMouseUpHandler, true );
2317 };
2318
2319 /**
2320 * Handles mouse click events.
2321 *
2322 * @protected
2323 * @param {jQuery.Event} e Mouse click event
2324 * @fires click
2325 * @return {undefined|boolean} False to prevent default if event is handled
2326 */
2327 OO.ui.mixin.ButtonElement.prototype.onClick = function ( e ) {
2328 if ( !this.isDisabled() && e.which === OO.ui.MouseButtons.LEFT ) {
2329 if ( this.emit( 'click' ) ) {
2330 return false;
2331 }
2332 }
2333 };
2334
2335 /**
2336 * Handles key down events.
2337 *
2338 * @protected
2339 * @param {jQuery.Event} e Key down event
2340 */
2341 OO.ui.mixin.ButtonElement.prototype.onKeyDown = function ( e ) {
2342 if ( this.isDisabled() || ( e.which !== OO.ui.Keys.SPACE && e.which !== OO.ui.Keys.ENTER ) ) {
2343 return;
2344 }
2345 this.$element.addClass( 'oo-ui-buttonElement-pressed' );
2346 // Run the keyup handler no matter where the key is when the button is let go, so we can
2347 // reliably remove the pressed class
2348 this.getElementDocument().addEventListener( 'keyup', this.onDocumentKeyUpHandler, true );
2349 };
2350
2351 /**
2352 * Handles document key up events.
2353 *
2354 * @protected
2355 * @param {KeyboardEvent} e Key up event
2356 */
2357 OO.ui.mixin.ButtonElement.prototype.onDocumentKeyUp = function ( e ) {
2358 if ( this.isDisabled() || ( e.which !== OO.ui.Keys.SPACE && e.which !== OO.ui.Keys.ENTER ) ) {
2359 return;
2360 }
2361 this.$element.removeClass( 'oo-ui-buttonElement-pressed' );
2362 // Stop listening for keyup, since we only needed this once
2363 this.getElementDocument().removeEventListener( 'keyup', this.onDocumentKeyUpHandler, true );
2364 };
2365
2366 /**
2367 * Handles key press events.
2368 *
2369 * @protected
2370 * @param {jQuery.Event} e Key press event
2371 * @fires click
2372 * @return {undefined|boolean} False to prevent default if event is handled
2373 */
2374 OO.ui.mixin.ButtonElement.prototype.onKeyPress = function ( e ) {
2375 if ( !this.isDisabled() && ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER ) ) {
2376 if ( this.emit( 'click' ) ) {
2377 return false;
2378 }
2379 }
2380 };
2381
2382 /**
2383 * Check if button has a frame.
2384 *
2385 * @return {boolean} Button is framed
2386 */
2387 OO.ui.mixin.ButtonElement.prototype.isFramed = function () {
2388 return this.framed;
2389 };
2390
2391 /**
2392 * Render the button with or without a frame. Omit the `framed` parameter to toggle the button frame
2393 * on and off.
2394 *
2395 * @param {boolean} [framed] Make button framed, omit to toggle
2396 * @chainable
2397 * @return {OO.ui.Element} The element, for chaining
2398 */
2399 OO.ui.mixin.ButtonElement.prototype.toggleFramed = function ( framed ) {
2400 framed = framed === undefined ? !this.framed : !!framed;
2401 if ( framed !== this.framed ) {
2402 this.framed = framed;
2403 this.$element
2404 .toggleClass( 'oo-ui-buttonElement-frameless', !framed )
2405 .toggleClass( 'oo-ui-buttonElement-framed', framed );
2406 this.updateThemeClasses();
2407 }
2408
2409 return this;
2410 };
2411
2412 /**
2413 * Set the button's active state.
2414 *
2415 * The active state can be set on:
2416 *
2417 * - {@link OO.ui.ButtonOptionWidget ButtonOptionWidget} when it is selected
2418 * - {@link OO.ui.ToggleButtonWidget ToggleButtonWidget} when it is toggle on
2419 * - {@link OO.ui.ButtonWidget ButtonWidget} when clicking the button would only refresh the page
2420 *
2421 * @protected
2422 * @param {boolean} value Make button active
2423 * @chainable
2424 * @return {OO.ui.Element} The element, for chaining
2425 */
2426 OO.ui.mixin.ButtonElement.prototype.setActive = function ( value ) {
2427 this.active = !!value;
2428 this.$element.toggleClass( 'oo-ui-buttonElement-active', this.active );
2429 this.updateThemeClasses();
2430 return this;
2431 };
2432
2433 /**
2434 * Check if the button is active
2435 *
2436 * @protected
2437 * @return {boolean} The button is active
2438 */
2439 OO.ui.mixin.ButtonElement.prototype.isActive = function () {
2440 return this.active;
2441 };
2442
2443 /**
2444 * Any OOUI widget that contains other widgets (such as {@link OO.ui.ButtonWidget buttons} or
2445 * {@link OO.ui.OptionWidget options}) mixes in GroupElement. Adding, removing, and clearing
2446 * items from the group is done through the interface the class provides.
2447 * For more information, please see the [OOUI documentation on MediaWiki] [1].
2448 *
2449 * [1]: https://www.mediawiki.org/wiki/OOUI/Elements/Groups
2450 *
2451 * @abstract
2452 * @mixins OO.EmitterList
2453 * @class
2454 *
2455 * @constructor
2456 * @param {Object} [config] Configuration options
2457 * @cfg {jQuery} [$group] The container element created by the class. If this configuration
2458 * is omitted, the group element will use a generated `<div>`.
2459 */
2460 OO.ui.mixin.GroupElement = function OoUiMixinGroupElement( config ) {
2461 // Configuration initialization
2462 config = config || {};
2463
2464 // Mixin constructors
2465 OO.EmitterList.call( this, config );
2466
2467 // Properties
2468 this.$group = null;
2469
2470 // Initialization
2471 this.setGroupElement( config.$group || $( '<div>' ) );
2472 };
2473
2474 /* Setup */
2475
2476 OO.mixinClass( OO.ui.mixin.GroupElement, OO.EmitterList );
2477
2478 /* Events */
2479
2480 /**
2481 * @event change
2482 *
2483 * A change event is emitted when the set of selected items changes.
2484 *
2485 * @param {OO.ui.Element[]} items Items currently in the group
2486 */
2487
2488 /* Methods */
2489
2490 /**
2491 * Set the group element.
2492 *
2493 * If an element is already set, items will be moved to the new element.
2494 *
2495 * @param {jQuery} $group Element to use as group
2496 */
2497 OO.ui.mixin.GroupElement.prototype.setGroupElement = function ( $group ) {
2498 var i, len;
2499
2500 this.$group = $group;
2501 for ( i = 0, len = this.items.length; i < len; i++ ) {
2502 this.$group.append( this.items[ i ].$element );
2503 }
2504 };
2505
2506 /**
2507 * Find an item by its data.
2508 *
2509 * Only the first item with matching data will be returned. To return all matching items,
2510 * use the #findItemsFromData method.
2511 *
2512 * @param {Object} data Item data to search for
2513 * @return {OO.ui.Element|null} Item with equivalent data, `null` if none exists
2514 */
2515 OO.ui.mixin.GroupElement.prototype.findItemFromData = function ( data ) {
2516 var i, len, item,
2517 hash = OO.getHash( data );
2518
2519 for ( i = 0, len = this.items.length; i < len; i++ ) {
2520 item = this.items[ i ];
2521 if ( hash === OO.getHash( item.getData() ) ) {
2522 return item;
2523 }
2524 }
2525
2526 return null;
2527 };
2528
2529 /**
2530 * Find items by their data.
2531 *
2532 * All items with matching data will be returned. To return only the first match, use the
2533 * #findItemFromData method instead.
2534 *
2535 * @param {Object} data Item data to search for
2536 * @return {OO.ui.Element[]} Items with equivalent data
2537 */
2538 OO.ui.mixin.GroupElement.prototype.findItemsFromData = function ( data ) {
2539 var i, len, item,
2540 hash = OO.getHash( data ),
2541 items = [];
2542
2543 for ( i = 0, len = this.items.length; i < len; i++ ) {
2544 item = this.items[ i ];
2545 if ( hash === OO.getHash( item.getData() ) ) {
2546 items.push( item );
2547 }
2548 }
2549
2550 return items;
2551 };
2552
2553 /**
2554 * Add items to the group.
2555 *
2556 * Items will be added to the end of the group array unless the optional `index` parameter
2557 * specifies a different insertion point. Adding an existing item will move it to the end of the
2558 * array or the point specified by the `index`.
2559 *
2560 * @param {OO.ui.Element[]} items An array of items to add to the group
2561 * @param {number} [index] Index of the insertion point
2562 * @chainable
2563 * @return {OO.ui.Element} The element, for chaining
2564 */
2565 OO.ui.mixin.GroupElement.prototype.addItems = function ( items, index ) {
2566
2567 if ( items.length === 0 ) {
2568 return this;
2569 }
2570
2571 // Mixin method
2572 OO.EmitterList.prototype.addItems.call( this, items, index );
2573
2574 this.emit( 'change', this.getItems() );
2575 return this;
2576 };
2577
2578 /**
2579 * @inheritdoc
2580 */
2581 OO.ui.mixin.GroupElement.prototype.moveItem = function ( items, newIndex ) {
2582 // insertItemElements expects this.items to not have been modified yet, so call before the mixin
2583 this.insertItemElements( items, newIndex );
2584
2585 // Mixin method
2586 newIndex = OO.EmitterList.prototype.moveItem.call( this, items, newIndex );
2587
2588 return newIndex;
2589 };
2590
2591 /**
2592 * @inheritdoc
2593 */
2594 OO.ui.mixin.GroupElement.prototype.insertItem = function ( item, index ) {
2595 item.setElementGroup( this );
2596 this.insertItemElements( item, index );
2597
2598 // Mixin method
2599 index = OO.EmitterList.prototype.insertItem.call( this, item, index );
2600
2601 return index;
2602 };
2603
2604 /**
2605 * Insert elements into the group
2606 *
2607 * @private
2608 * @param {OO.ui.Element} itemWidget Item to insert
2609 * @param {number} index Insertion index
2610 */
2611 OO.ui.mixin.GroupElement.prototype.insertItemElements = function ( itemWidget, index ) {
2612 if ( index === undefined || index < 0 || index >= this.items.length ) {
2613 this.$group.append( itemWidget.$element );
2614 } else if ( index === 0 ) {
2615 this.$group.prepend( itemWidget.$element );
2616 } else {
2617 this.items[ index ].$element.before( itemWidget.$element );
2618 }
2619 };
2620
2621 /**
2622 * Remove the specified items from a group.
2623 *
2624 * Removed items are detached (not removed) from the DOM so that they may be reused.
2625 * To remove all items from a group, you may wish to use the #clearItems method instead.
2626 *
2627 * @param {OO.ui.Element[]} items An array of items to remove
2628 * @chainable
2629 * @return {OO.ui.Element} The element, for chaining
2630 */
2631 OO.ui.mixin.GroupElement.prototype.removeItems = function ( items ) {
2632 var i, len, item, index;
2633
2634 if ( items.length === 0 ) {
2635 return this;
2636 }
2637
2638 // Remove specific items elements
2639 for ( i = 0, len = items.length; i < len; i++ ) {
2640 item = items[ i ];
2641 index = this.items.indexOf( item );
2642 if ( index !== -1 ) {
2643 item.setElementGroup( null );
2644 item.$element.detach();
2645 }
2646 }
2647
2648 // Mixin method
2649 OO.EmitterList.prototype.removeItems.call( this, items );
2650
2651 this.emit( 'change', this.getItems() );
2652 return this;
2653 };
2654
2655 /**
2656 * Clear all items from the group.
2657 *
2658 * Cleared items are detached from the DOM, not removed, so that they may be reused.
2659 * To remove only a subset of items from a group, use the #removeItems method.
2660 *
2661 * @chainable
2662 * @return {OO.ui.Element} The element, for chaining
2663 */
2664 OO.ui.mixin.GroupElement.prototype.clearItems = function () {
2665 var i, len;
2666
2667 // Remove all item elements
2668 for ( i = 0, len = this.items.length; i < len; i++ ) {
2669 this.items[ i ].setElementGroup( null );
2670 this.items[ i ].$element.detach();
2671 }
2672
2673 // Mixin method
2674 OO.EmitterList.prototype.clearItems.call( this );
2675
2676 this.emit( 'change', this.getItems() );
2677 return this;
2678 };
2679
2680 /**
2681 * LabelElement is often mixed into other classes to generate a label, which
2682 * helps identify the function of an interface element.
2683 * See the [OOUI documentation on MediaWiki] [1] for more information.
2684 *
2685 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Icons,_Indicators,_and_Labels#Labels
2686 *
2687 * @abstract
2688 * @class
2689 *
2690 * @constructor
2691 * @param {Object} [config] Configuration options
2692 * @cfg {jQuery} [$label] The label element created by the class. If this
2693 * configuration is omitted, the label element will use a generated `<span>`.
2694 * @cfg {jQuery|string|Function|OO.ui.HtmlSnippet} [label] The label text. The label can be
2695 * specified as a plaintext string, a jQuery selection of elements, or a function that will
2696 * produce a string in the future. See the [OOUI documentation on MediaWiki] [2] for examples.
2697 * [2]: https://www.mediawiki.org/wiki/OOUI/Widgets/Icons,_Indicators,_and_Labels#Labels
2698 * @cfg {boolean} [invisibleLabel] Whether the label should be visually hidden (but still
2699 * accessible to screen-readers).
2700 */
2701 OO.ui.mixin.LabelElement = function OoUiMixinLabelElement( config ) {
2702 // Configuration initialization
2703 config = config || {};
2704
2705 // Properties
2706 this.$label = null;
2707 this.label = null;
2708 this.invisibleLabel = null;
2709
2710 // Initialization
2711 this.setLabel( config.label || this.constructor.static.label );
2712 this.setLabelElement( config.$label || $( '<span>' ) );
2713 this.setInvisibleLabel( config.invisibleLabel );
2714 };
2715
2716 /* Setup */
2717
2718 OO.initClass( OO.ui.mixin.LabelElement );
2719
2720 /* Events */
2721
2722 /**
2723 * @event labelChange
2724 * @param {string} value
2725 */
2726
2727 /* Static Properties */
2728
2729 /**
2730 * The label text. The label can be specified as a plaintext string, a function that will
2731 * produce a string in the future, or `null` for no label. The static value will
2732 * be overridden if a label is specified with the #label config option.
2733 *
2734 * @static
2735 * @inheritable
2736 * @property {string|Function|null}
2737 */
2738 OO.ui.mixin.LabelElement.static.label = null;
2739
2740 /* Static methods */
2741
2742 /**
2743 * Highlight the first occurrence of the query in the given text
2744 *
2745 * @param {string} text Text
2746 * @param {string} query Query to find
2747 * @param {Function} [compare] Optional string comparator, e.g. Intl.Collator().compare
2748 * @return {jQuery} Text with the first match of the query
2749 * sub-string wrapped in highlighted span
2750 */
2751 OO.ui.mixin.LabelElement.static.highlightQuery = function ( text, query, compare ) {
2752 var i, tLen, qLen,
2753 offset = -1,
2754 $result = $( '<span>' );
2755
2756 if ( compare ) {
2757 tLen = text.length;
2758 qLen = query.length;
2759 for ( i = 0; offset === -1 && i <= tLen - qLen; i++ ) {
2760 if ( compare( query, text.slice( i, i + qLen ) ) === 0 ) {
2761 offset = i;
2762 }
2763 }
2764 } else {
2765 offset = text.toLowerCase().indexOf( query.toLowerCase() );
2766 }
2767
2768 if ( !query.length || offset === -1 ) {
2769 $result.text( text );
2770 } else {
2771 $result.append(
2772 document.createTextNode( text.slice( 0, offset ) ),
2773 $( '<span>' )
2774 .addClass( 'oo-ui-labelElement-label-highlight' )
2775 .text( text.slice( offset, offset + query.length ) ),
2776 document.createTextNode( text.slice( offset + query.length ) )
2777 );
2778 }
2779 return $result.contents();
2780 };
2781
2782 /* Methods */
2783
2784 /**
2785 * Set the label element.
2786 *
2787 * If an element is already set, it will be cleaned up before setting up the new element.
2788 *
2789 * @param {jQuery} $label Element to use as label
2790 */
2791 OO.ui.mixin.LabelElement.prototype.setLabelElement = function ( $label ) {
2792 if ( this.$label ) {
2793 this.$label.removeClass( 'oo-ui-labelElement-label' ).empty();
2794 }
2795
2796 this.$label = $label.addClass( 'oo-ui-labelElement-label' );
2797 this.setLabelContent( this.label );
2798 };
2799
2800 /**
2801 * Set the label.
2802 *
2803 * An empty string will result in the label being hidden. A string containing only whitespace will
2804 * be converted to a single `&nbsp;`.
2805 *
2806 * @param {jQuery|string|OO.ui.HtmlSnippet|Function|null} label Label nodes; text; a function that
2807 * returns nodes or text; or null for no label
2808 * @chainable
2809 * @return {OO.ui.Element} The element, for chaining
2810 */
2811 OO.ui.mixin.LabelElement.prototype.setLabel = function ( label ) {
2812 label = typeof label === 'function' ? OO.ui.resolveMsg( label ) : label;
2813 label = ( ( typeof label === 'string' || label instanceof $ ) && label.length ) || ( label instanceof OO.ui.HtmlSnippet && label.toString().length ) ? label : null;
2814
2815 if ( this.label !== label ) {
2816 if ( this.$label ) {
2817 this.setLabelContent( label );
2818 }
2819 this.label = label;
2820 this.emit( 'labelChange' );
2821 }
2822
2823 this.$element.toggleClass( 'oo-ui-labelElement', !!this.label && !this.invisibleLabel );
2824
2825 return this;
2826 };
2827
2828 /**
2829 * Set whether the label should be visually hidden (but still accessible to screen-readers).
2830 *
2831 * @param {boolean} invisibleLabel
2832 * @chainable
2833 * @return {OO.ui.Element} The element, for chaining
2834 */
2835 OO.ui.mixin.LabelElement.prototype.setInvisibleLabel = function ( invisibleLabel ) {
2836 invisibleLabel = !!invisibleLabel;
2837
2838 if ( this.invisibleLabel !== invisibleLabel ) {
2839 this.invisibleLabel = invisibleLabel;
2840 this.emit( 'labelChange' );
2841 }
2842
2843 this.$label.toggleClass( 'oo-ui-labelElement-invisible', this.invisibleLabel );
2844 // Pretend that there is no label, a lot of CSS has been written with this assumption
2845 this.$element.toggleClass( 'oo-ui-labelElement', !!this.label && !this.invisibleLabel );
2846
2847 return this;
2848 };
2849
2850 /**
2851 * Set the label as plain text with a highlighted query
2852 *
2853 * @param {string} text Text label to set
2854 * @param {string} query Substring of text to highlight
2855 * @param {Function} [compare] Optional string comparator, e.g. Intl.Collator().compare
2856 * @chainable
2857 * @return {OO.ui.Element} The element, for chaining
2858 */
2859 OO.ui.mixin.LabelElement.prototype.setHighlightedQuery = function ( text, query, compare ) {
2860 return this.setLabel( this.constructor.static.highlightQuery( text, query, compare ) );
2861 };
2862
2863 /**
2864 * Get the label.
2865 *
2866 * @return {jQuery|string|Function|null} Label nodes; text; a function that returns nodes or
2867 * text; or null for no label
2868 */
2869 OO.ui.mixin.LabelElement.prototype.getLabel = function () {
2870 return this.label;
2871 };
2872
2873 /**
2874 * Set the content of the label.
2875 *
2876 * Do not call this method until after the label element has been set by #setLabelElement.
2877 *
2878 * @private
2879 * @param {jQuery|string|Function|null} label Label nodes; text; a function that returns nodes or
2880 * text; or null for no label
2881 */
2882 OO.ui.mixin.LabelElement.prototype.setLabelContent = function ( label ) {
2883 if ( typeof label === 'string' ) {
2884 if ( label.match( /^\s*$/ ) ) {
2885 // Convert whitespace only string to a single non-breaking space
2886 this.$label.html( '&nbsp;' );
2887 } else {
2888 this.$label.text( label );
2889 }
2890 } else if ( label instanceof OO.ui.HtmlSnippet ) {
2891 this.$label.html( label.toString() );
2892 } else if ( label instanceof $ ) {
2893 this.$label.empty().append( label );
2894 } else {
2895 this.$label.empty();
2896 }
2897 };
2898
2899 /**
2900 * IconElement is often mixed into other classes to generate an icon.
2901 * Icons are graphics, about the size of normal text. They are used to aid the user
2902 * in locating a control or to convey information in a space-efficient way. See the
2903 * [OOUI documentation on MediaWiki] [1] for a list of icons
2904 * included in the library.
2905 *
2906 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Icons,_Indicators,_and_Labels#Icons
2907 *
2908 * @abstract
2909 * @class
2910 *
2911 * @constructor
2912 * @param {Object} [config] Configuration options
2913 * @cfg {jQuery} [$icon] The icon element created by the class. If this configuration is omitted,
2914 * the icon element will use a generated `<span>`. To use a different HTML tag, or to specify that
2915 * the icon element be set to an existing icon instead of the one generated by this class, set a
2916 * value using a jQuery selection. For example:
2917 *
2918 * // Use a <div> tag instead of a <span>
2919 * $icon: $( '<div>' )
2920 * // Use an existing icon element instead of the one generated by the class
2921 * $icon: this.$element
2922 * // Use an icon element from a child widget
2923 * $icon: this.childwidget.$element
2924 * @cfg {Object|string} [icon=''] The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a
2925 * map of symbolic names. A map is used for i18n purposes and contains a `default` icon
2926 * name and additional names keyed by language code. The `default` name is used when no icon is
2927 * keyed by the user's language.
2928 *
2929 * Example of an i18n map:
2930 *
2931 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
2932 * See the [OOUI documentation on MediaWiki] [2] for a list of icons included in the library.
2933 * [2]: https://www.mediawiki.org/wiki/OOUI/Widgets/Icons,_Indicators,_and_Labels#Icons
2934 */
2935 OO.ui.mixin.IconElement = function OoUiMixinIconElement( config ) {
2936 // Configuration initialization
2937 config = config || {};
2938
2939 // Properties
2940 this.$icon = null;
2941 this.icon = null;
2942
2943 // Initialization
2944 this.setIcon( config.icon || this.constructor.static.icon );
2945 this.setIconElement( config.$icon || $( '<span>' ) );
2946 };
2947
2948 /* Setup */
2949
2950 OO.initClass( OO.ui.mixin.IconElement );
2951
2952 /* Static Properties */
2953
2954 /**
2955 * The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of symbolic names. A map
2956 * is used for i18n purposes and contains a `default` icon name and additional names keyed by
2957 * language code. The `default` name is used when no icon is keyed by the user's language.
2958 *
2959 * Example of an i18n map:
2960 *
2961 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
2962 *
2963 * Note: the static property will be overridden if the #icon configuration is used.
2964 *
2965 * @static
2966 * @inheritable
2967 * @property {Object|string}
2968 */
2969 OO.ui.mixin.IconElement.static.icon = null;
2970
2971 /**
2972 * The icon title, displayed when users move the mouse over the icon. The value can be text, a
2973 * function that returns title text, or `null` for no title.
2974 *
2975 * The static property will be overridden if the #iconTitle configuration is used.
2976 *
2977 * @static
2978 * @inheritable
2979 * @property {string|Function|null}
2980 */
2981 OO.ui.mixin.IconElement.static.iconTitle = null;
2982
2983 /* Methods */
2984
2985 /**
2986 * Set the icon element. This method is used to retarget an icon mixin so that its functionality
2987 * applies to the specified icon element instead of the one created by the class. If an icon
2988 * element is already set, the mixin’s effect on that element is removed. Generated CSS classes
2989 * and mixin methods will no longer affect the element.
2990 *
2991 * @param {jQuery} $icon Element to use as icon
2992 */
2993 OO.ui.mixin.IconElement.prototype.setIconElement = function ( $icon ) {
2994 if ( this.$icon ) {
2995 this.$icon
2996 .removeClass( 'oo-ui-iconElement-icon oo-ui-icon-' + this.icon )
2997 .removeAttr( 'title' );
2998 }
2999
3000 this.$icon = $icon
3001 .addClass( 'oo-ui-iconElement-icon' )
3002 .toggleClass( 'oo-ui-iconElement-noIcon', !this.icon )
3003 .toggleClass( 'oo-ui-icon-' + this.icon, !!this.icon );
3004 if ( this.iconTitle !== null ) {
3005 this.$icon.attr( 'title', this.iconTitle );
3006 }
3007
3008 this.updateThemeClasses();
3009 };
3010
3011 /**
3012 * Set icon by symbolic name (e.g., ‘remove’ or ‘menu’). Use `null` to remove an icon.
3013 * The icon parameter can also be set to a map of icon names. See the #icon config setting
3014 * for an example.
3015 *
3016 * @param {Object|string|null} icon A symbolic icon name, a {@link #icon map of icon names} keyed
3017 * by language code, or `null` to remove the icon.
3018 * @chainable
3019 * @return {OO.ui.Element} The element, for chaining
3020 */
3021 OO.ui.mixin.IconElement.prototype.setIcon = function ( icon ) {
3022 icon = OO.isPlainObject( icon ) ? OO.ui.getLocalValue( icon, null, 'default' ) : icon;
3023 icon = typeof icon === 'string' && icon.trim().length ? icon.trim() : null;
3024
3025 if ( this.icon !== icon ) {
3026 if ( this.$icon ) {
3027 if ( this.icon !== null ) {
3028 this.$icon.removeClass( 'oo-ui-icon-' + this.icon );
3029 }
3030 if ( icon !== null ) {
3031 this.$icon.addClass( 'oo-ui-icon-' + icon );
3032 }
3033 }
3034 this.icon = icon;
3035 }
3036
3037 this.$element.toggleClass( 'oo-ui-iconElement', !!this.icon );
3038 if ( this.$icon ) {
3039 this.$icon.toggleClass( 'oo-ui-iconElement-noIcon', !this.icon );
3040 }
3041 this.updateThemeClasses();
3042
3043 return this;
3044 };
3045
3046 /**
3047 * Get the symbolic name of the icon.
3048 *
3049 * @return {string} Icon name
3050 */
3051 OO.ui.mixin.IconElement.prototype.getIcon = function () {
3052 return this.icon;
3053 };
3054
3055 /**
3056 * Get the icon title. The title text is displayed when a user moves the mouse over the icon.
3057 *
3058 * @return {string} Icon title text
3059 * @deprecated
3060 */
3061 OO.ui.mixin.IconElement.prototype.getIconTitle = function () {
3062 return this.iconTitle;
3063 };
3064
3065 /**
3066 * IndicatorElement is often mixed into other classes to generate an indicator.
3067 * Indicators are small graphics that are generally used in two ways:
3068 *
3069 * - To draw attention to the status of an item. For example, an indicator might be
3070 * used to show that an item in a list has errors that need to be resolved.
3071 * - To clarify the function of a control that acts in an exceptional way (a button
3072 * that opens a menu instead of performing an action directly, for example).
3073 *
3074 * For a list of indicators included in the library, please see the
3075 * [OOUI documentation on MediaWiki] [1].
3076 *
3077 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Icons,_Indicators,_and_Labels#Indicators
3078 *
3079 * @abstract
3080 * @class
3081 *
3082 * @constructor
3083 * @param {Object} [config] Configuration options
3084 * @cfg {jQuery} [$indicator] The indicator element created by the class. If this
3085 * configuration is omitted, the indicator element will use a generated `<span>`.
3086 * @cfg {string} [indicator] Symbolic name of the indicator (e.g., ‘clear’ or ‘down’).
3087 * See the [OOUI documentation on MediaWiki][2] for a list of indicators included
3088 * in the library.
3089 * [2]: https://www.mediawiki.org/wiki/OOUI/Widgets/Icons,_Indicators,_and_Labels#Indicators
3090 */
3091 OO.ui.mixin.IndicatorElement = function OoUiMixinIndicatorElement( config ) {
3092 // Configuration initialization
3093 config = config || {};
3094
3095 // Properties
3096 this.$indicator = null;
3097 this.indicator = null;
3098
3099 // Initialization
3100 this.setIndicator( config.indicator || this.constructor.static.indicator );
3101 this.setIndicatorElement( config.$indicator || $( '<span>' ) );
3102 };
3103
3104 /* Setup */
3105
3106 OO.initClass( OO.ui.mixin.IndicatorElement );
3107
3108 /* Static Properties */
3109
3110 /**
3111 * Symbolic name of the indicator (e.g., ‘clear’ or ‘down’).
3112 * The static property will be overridden if the #indicator configuration is used.
3113 *
3114 * @static
3115 * @inheritable
3116 * @property {string|null}
3117 */
3118 OO.ui.mixin.IndicatorElement.static.indicator = null;
3119
3120 /**
3121 * A text string used as the indicator title, a function that returns title text, or `null`
3122 * for no title. The static property will be overridden if the #indicatorTitle configuration is
3123 * used.
3124 *
3125 * @static
3126 * @inheritable
3127 * @property {string|Function|null}
3128 */
3129 OO.ui.mixin.IndicatorElement.static.indicatorTitle = null;
3130
3131 /* Methods */
3132
3133 /**
3134 * Set the indicator element.
3135 *
3136 * If an element is already set, it will be cleaned up before setting up the new element.
3137 *
3138 * @param {jQuery} $indicator Element to use as indicator
3139 */
3140 OO.ui.mixin.IndicatorElement.prototype.setIndicatorElement = function ( $indicator ) {
3141 if ( this.$indicator ) {
3142 this.$indicator
3143 .removeClass( 'oo-ui-indicatorElement-indicator oo-ui-indicator-' + this.indicator )
3144 .removeAttr( 'title' );
3145 }
3146
3147 this.$indicator = $indicator
3148 .addClass( 'oo-ui-indicatorElement-indicator' )
3149 .toggleClass( 'oo-ui-indicatorElement-noIndicator', !this.indicator )
3150 .toggleClass( 'oo-ui-indicator-' + this.indicator, !!this.indicator );
3151 if ( this.indicatorTitle !== null ) {
3152 this.$indicator.attr( 'title', this.indicatorTitle );
3153 }
3154
3155 this.updateThemeClasses();
3156 };
3157
3158 /**
3159 * Set the indicator by its symbolic name: ‘clear’, ‘down’, ‘required’, ‘search’, ‘up’. Use `null`
3160 * to remove the indicator.
3161 *
3162 * @param {string|null} indicator Symbolic name of indicator, or `null` for no indicator
3163 * @chainable
3164 * @return {OO.ui.Element} The element, for chaining
3165 */
3166 OO.ui.mixin.IndicatorElement.prototype.setIndicator = function ( indicator ) {
3167 indicator = typeof indicator === 'string' && indicator.length ? indicator.trim() : null;
3168
3169 if ( this.indicator !== indicator ) {
3170 if ( this.$indicator ) {
3171 if ( this.indicator !== null ) {
3172 this.$indicator.removeClass( 'oo-ui-indicator-' + this.indicator );
3173 }
3174 if ( indicator !== null ) {
3175 this.$indicator.addClass( 'oo-ui-indicator-' + indicator );
3176 }
3177 }
3178 this.indicator = indicator;
3179 }
3180
3181 this.$element.toggleClass( 'oo-ui-indicatorElement', !!this.indicator );
3182 if ( this.$indicator ) {
3183 this.$indicator.toggleClass( 'oo-ui-indicatorElement-noIndicator', !this.indicator );
3184 }
3185 this.updateThemeClasses();
3186
3187 return this;
3188 };
3189
3190 /**
3191 * Get the symbolic name of the indicator (e.g., ‘clear’ or ‘down’).
3192 *
3193 * @return {string} Symbolic name of indicator
3194 */
3195 OO.ui.mixin.IndicatorElement.prototype.getIndicator = function () {
3196 return this.indicator;
3197 };
3198
3199 /**
3200 * Get the indicator title.
3201 *
3202 * The title is displayed when a user moves the mouse over the indicator.
3203 *
3204 * @return {string} Indicator title text
3205 * @deprecated
3206 */
3207 OO.ui.mixin.IndicatorElement.prototype.getIndicatorTitle = function () {
3208 return this.indicatorTitle;
3209 };
3210
3211 /**
3212 * The FlaggedElement class is an attribute mixin, meaning that it is used to add
3213 * additional functionality to an element created by another class. The class provides
3214 * a ‘flags’ property assigned the name (or an array of names) of styling flags,
3215 * which are used to customize the look and feel of a widget to better describe its
3216 * importance and functionality.
3217 *
3218 * The library currently contains the following styling flags for general use:
3219 *
3220 * - **progressive**: Progressive styling is applied to convey that the widget will move the user
3221 * forward in a process.
3222 * - **destructive**: Destructive styling is applied to convey that the widget will remove
3223 * something.
3224 *
3225 * The flags affect the appearance of the buttons:
3226 *
3227 * @example
3228 * // FlaggedElement is mixed into ButtonWidget to provide styling flags
3229 * var button1 = new OO.ui.ButtonWidget( {
3230 * label: 'Progressive',
3231 * flags: 'progressive'
3232 * } ),
3233 * button2 = new OO.ui.ButtonWidget( {
3234 * label: 'Destructive',
3235 * flags: 'destructive'
3236 * } );
3237 * $( document.body ).append( button1.$element, button2.$element );
3238 *
3239 * {@link OO.ui.ActionWidget ActionWidgets}, which are a special kind of button that execute an
3240 * action, use these flags: **primary** and **safe**.
3241 * Please see the [OOUI documentation on MediaWiki] [1] for more information.
3242 *
3243 * [1]: https://www.mediawiki.org/wiki/OOUI/Elements/Flagged
3244 *
3245 * @abstract
3246 * @class
3247 *
3248 * @constructor
3249 * @param {Object} [config] Configuration options
3250 * @cfg {string|string[]} [flags] The name or names of the flags (e.g., 'progressive' or 'primary')
3251 * to apply.
3252 * Please see the [OOUI documentation on MediaWiki] [2] for more information about available flags.
3253 * [2]: https://www.mediawiki.org/wiki/OOUI/Elements/Flagged
3254 * @cfg {jQuery} [$flagged] The flagged element. By default,
3255 * the flagged functionality is applied to the element created by the class ($element).
3256 * If a different element is specified, the flagged functionality will be applied to it instead.
3257 */
3258 OO.ui.mixin.FlaggedElement = function OoUiMixinFlaggedElement( config ) {
3259 // Configuration initialization
3260 config = config || {};
3261
3262 // Properties
3263 this.flags = {};
3264 this.$flagged = null;
3265
3266 // Initialization
3267 this.setFlags( config.flags || this.constructor.static.flags );
3268 this.setFlaggedElement( config.$flagged || this.$element );
3269 };
3270
3271 /* Setup */
3272
3273 OO.initClass( OO.ui.mixin.FlaggedElement );
3274
3275 /* Events */
3276
3277 /**
3278 * @event flag
3279 * A flag event is emitted when the #clearFlags or #setFlags methods are used. The `changes`
3280 * parameter contains the name of each modified flag and indicates whether it was
3281 * added or removed.
3282 *
3283 * @param {Object.<string,boolean>} changes Object keyed by flag name. A Boolean `true` indicates
3284 * that the flag was added, `false` that the flag was removed.
3285 */
3286
3287 /* Static Properties */
3288
3289 /**
3290 * Initial value to pass to setFlags if no value is provided in config.
3291 *
3292 * @static
3293 * @inheritable
3294 * @property {string|string[]|Object.<string, boolean>}
3295 */
3296 OO.ui.mixin.FlaggedElement.static.flags = null;
3297
3298 /* Methods */
3299
3300 /**
3301 * Set the flagged element.
3302 *
3303 * This method is used to retarget a flagged mixin so that its functionality applies to the
3304 * specified element.
3305 * If an element is already set, the method will remove the mixin’s effect on that element.
3306 *
3307 * @param {jQuery} $flagged Element that should be flagged
3308 */
3309 OO.ui.mixin.FlaggedElement.prototype.setFlaggedElement = function ( $flagged ) {
3310 var classNames = Object.keys( this.flags ).map( function ( flag ) {
3311 return 'oo-ui-flaggedElement-' + flag;
3312 } );
3313
3314 if ( this.$flagged ) {
3315 this.$flagged.removeClass( classNames );
3316 }
3317
3318 this.$flagged = $flagged.addClass( classNames );
3319 };
3320
3321 /**
3322 * Check if the specified flag is set.
3323 *
3324 * @param {string} flag Name of flag
3325 * @return {boolean} The flag is set
3326 */
3327 OO.ui.mixin.FlaggedElement.prototype.hasFlag = function ( flag ) {
3328 // This may be called before the constructor, thus before this.flags is set
3329 return this.flags && ( flag in this.flags );
3330 };
3331
3332 /**
3333 * Get the names of all flags set.
3334 *
3335 * @return {string[]} Flag names
3336 */
3337 OO.ui.mixin.FlaggedElement.prototype.getFlags = function () {
3338 // This may be called before the constructor, thus before this.flags is set
3339 return Object.keys( this.flags || {} );
3340 };
3341
3342 /**
3343 * Clear all flags.
3344 *
3345 * @chainable
3346 * @return {OO.ui.Element} The element, for chaining
3347 * @fires flag
3348 */
3349 OO.ui.mixin.FlaggedElement.prototype.clearFlags = function () {
3350 var flag, className,
3351 changes = {},
3352 remove = [],
3353 classPrefix = 'oo-ui-flaggedElement-';
3354
3355 for ( flag in this.flags ) {
3356 className = classPrefix + flag;
3357 changes[ flag ] = false;
3358 delete this.flags[ flag ];
3359 remove.push( className );
3360 }
3361
3362 if ( this.$flagged ) {
3363 this.$flagged.removeClass( remove );
3364 }
3365
3366 this.updateThemeClasses();
3367 this.emit( 'flag', changes );
3368
3369 return this;
3370 };
3371
3372 /**
3373 * Add one or more flags.
3374 *
3375 * @param {string|string[]|Object.<string, boolean>} flags A flag name, an array of flag names,
3376 * or an object keyed by flag name with a boolean value that indicates whether the flag should
3377 * be added (`true`) or removed (`false`).
3378 * @chainable
3379 * @return {OO.ui.Element} The element, for chaining
3380 * @fires flag
3381 */
3382 OO.ui.mixin.FlaggedElement.prototype.setFlags = function ( flags ) {
3383 var i, len, flag, className,
3384 changes = {},
3385 add = [],
3386 remove = [],
3387 classPrefix = 'oo-ui-flaggedElement-';
3388
3389 if ( typeof flags === 'string' ) {
3390 className = classPrefix + flags;
3391 // Set
3392 if ( !this.flags[ flags ] ) {
3393 this.flags[ flags ] = true;
3394 add.push( className );
3395 }
3396 } else if ( Array.isArray( flags ) ) {
3397 for ( i = 0, len = flags.length; i < len; i++ ) {
3398 flag = flags[ i ];
3399 className = classPrefix + flag;
3400 // Set
3401 if ( !this.flags[ flag ] ) {
3402 changes[ flag ] = true;
3403 this.flags[ flag ] = true;
3404 add.push( className );
3405 }
3406 }
3407 } else if ( OO.isPlainObject( flags ) ) {
3408 for ( flag in flags ) {
3409 className = classPrefix + flag;
3410 if ( flags[ flag ] ) {
3411 // Set
3412 if ( !this.flags[ flag ] ) {
3413 changes[ flag ] = true;
3414 this.flags[ flag ] = true;
3415 add.push( className );
3416 }
3417 } else {
3418 // Remove
3419 if ( this.flags[ flag ] ) {
3420 changes[ flag ] = false;
3421 delete this.flags[ flag ];
3422 remove.push( className );
3423 }
3424 }
3425 }
3426 }
3427
3428 if ( this.$flagged ) {
3429 this.$flagged
3430 .addClass( add )
3431 .removeClass( remove );
3432 }
3433
3434 this.updateThemeClasses();
3435 this.emit( 'flag', changes );
3436
3437 return this;
3438 };
3439
3440 /**
3441 * TitledElement is mixed into other classes to provide a `title` attribute.
3442 * Titles are rendered by the browser and are made visible when the user moves
3443 * the mouse over the element. Titles are not visible on touch devices.
3444 *
3445 * @example
3446 * // TitledElement provides a `title` attribute to the
3447 * // ButtonWidget class.
3448 * var button = new OO.ui.ButtonWidget( {
3449 * label: 'Button with Title',
3450 * title: 'I am a button'
3451 * } );
3452 * $( document.body ).append( button.$element );
3453 *
3454 * @abstract
3455 * @class
3456 *
3457 * @constructor
3458 * @param {Object} [config] Configuration options
3459 * @cfg {jQuery} [$titled] The element to which the `title` attribute is applied.
3460 * If this config is omitted, the title functionality is applied to $element, the
3461 * element created by the class.
3462 * @cfg {string|Function} [title] The title text or a function that returns text. If
3463 * this config is omitted, the value of the {@link #static-title static title} property is used.
3464 */
3465 OO.ui.mixin.TitledElement = function OoUiMixinTitledElement( config ) {
3466 // Configuration initialization
3467 config = config || {};
3468
3469 // Properties
3470 this.$titled = null;
3471 this.title = null;
3472
3473 // Initialization
3474 this.setTitle( config.title !== undefined ? config.title : this.constructor.static.title );
3475 this.setTitledElement( config.$titled || this.$element );
3476 };
3477
3478 /* Setup */
3479
3480 OO.initClass( OO.ui.mixin.TitledElement );
3481
3482 /* Static Properties */
3483
3484 /**
3485 * The title text, a function that returns text, or `null` for no title. The value of the static
3486 * property is overridden if the #title config option is used.
3487 *
3488 * If the element has a default title (e.g. `<input type=file>`), `null` will allow that title to be
3489 * shown. Use empty string to suppress it.
3490 *
3491 * @static
3492 * @inheritable
3493 * @property {string|Function|null}
3494 */
3495 OO.ui.mixin.TitledElement.static.title = null;
3496
3497 /* Methods */
3498
3499 /**
3500 * Set the titled element.
3501 *
3502 * This method is used to retarget a TitledElement mixin so that its functionality applies to the
3503 * specified element.
3504 * If an element is already set, the mixin’s effect on that element is removed before the new
3505 * element is set up.
3506 *
3507 * @param {jQuery} $titled Element that should use the 'titled' functionality
3508 */
3509 OO.ui.mixin.TitledElement.prototype.setTitledElement = function ( $titled ) {
3510 if ( this.$titled ) {
3511 this.$titled.removeAttr( 'title' );
3512 }
3513
3514 this.$titled = $titled;
3515 this.updateTitle();
3516 };
3517
3518 /**
3519 * Set title.
3520 *
3521 * @param {string|Function|null} title Title text, a function that returns text, or `null`
3522 * for no title
3523 * @chainable
3524 * @return {OO.ui.Element} The element, for chaining
3525 */
3526 OO.ui.mixin.TitledElement.prototype.setTitle = function ( title ) {
3527 title = typeof title === 'function' ? OO.ui.resolveMsg( title ) : title;
3528 title = typeof title === 'string' ? title : null;
3529
3530 if ( this.title !== title ) {
3531 this.title = title;
3532 this.updateTitle();
3533 }
3534
3535 return this;
3536 };
3537
3538 /**
3539 * Update the title attribute, in case of changes to title or accessKey.
3540 *
3541 * @protected
3542 * @chainable
3543 * @return {OO.ui.Element} The element, for chaining
3544 */
3545 OO.ui.mixin.TitledElement.prototype.updateTitle = function () {
3546 var title = this.getTitle();
3547 if ( this.$titled ) {
3548 if ( title !== null ) {
3549 // Only if this is an AccessKeyedElement
3550 if ( this.formatTitleWithAccessKey ) {
3551 title = this.formatTitleWithAccessKey( title );
3552 }
3553 this.$titled.attr( 'title', title );
3554 } else {
3555 this.$titled.removeAttr( 'title' );
3556 }
3557 }
3558 return this;
3559 };
3560
3561 /**
3562 * Get title.
3563 *
3564 * @return {string} Title string
3565 */
3566 OO.ui.mixin.TitledElement.prototype.getTitle = function () {
3567 return this.title;
3568 };
3569
3570 /**
3571 * AccessKeyedElement is mixed into other classes to provide an `accesskey` HTML attribute.
3572 * Access keys allow an user to go to a specific element by using
3573 * a shortcut combination of a browser specific keys + the key
3574 * set to the field.
3575 *
3576 * @example
3577 * // AccessKeyedElement provides an `accesskey` attribute to the
3578 * // ButtonWidget class.
3579 * var button = new OO.ui.ButtonWidget( {
3580 * label: 'Button with access key',
3581 * accessKey: 'k'
3582 * } );
3583 * $( document.body ).append( button.$element );
3584 *
3585 * @abstract
3586 * @class
3587 *
3588 * @constructor
3589 * @param {Object} [config] Configuration options
3590 * @cfg {jQuery} [$accessKeyed] The element to which the `accesskey` attribute is applied.
3591 * If this config is omitted, the access key functionality is applied to $element, the
3592 * element created by the class.
3593 * @cfg {string|Function} [accessKey] The key or a function that returns the key. If
3594 * this config is omitted, no access key will be added.
3595 */
3596 OO.ui.mixin.AccessKeyedElement = function OoUiMixinAccessKeyedElement( config ) {
3597 // Configuration initialization
3598 config = config || {};
3599
3600 // Properties
3601 this.$accessKeyed = null;
3602 this.accessKey = null;
3603
3604 // Initialization
3605 this.setAccessKey( config.accessKey || null );
3606 this.setAccessKeyedElement( config.$accessKeyed || this.$element );
3607
3608 // If this is also a TitledElement and it initialized before we did, we may have
3609 // to update the title with the access key
3610 if ( this.updateTitle ) {
3611 this.updateTitle();
3612 }
3613 };
3614
3615 /* Setup */
3616
3617 OO.initClass( OO.ui.mixin.AccessKeyedElement );
3618
3619 /* Static Properties */
3620
3621 /**
3622 * The access key, a function that returns a key, or `null` for no access key.
3623 *
3624 * @static
3625 * @inheritable
3626 * @property {string|Function|null}
3627 */
3628 OO.ui.mixin.AccessKeyedElement.static.accessKey = null;
3629
3630 /* Methods */
3631
3632 /**
3633 * Set the access keyed element.
3634 *
3635 * This method is used to retarget a AccessKeyedElement mixin so that its functionality applies to
3636 * the specified element.
3637 * If an element is already set, the mixin's effect on that element is removed before the new
3638 * element is set up.
3639 *
3640 * @param {jQuery} $accessKeyed Element that should use the 'access keyed' functionality
3641 */
3642 OO.ui.mixin.AccessKeyedElement.prototype.setAccessKeyedElement = function ( $accessKeyed ) {
3643 if ( this.$accessKeyed ) {
3644 this.$accessKeyed.removeAttr( 'accesskey' );
3645 }
3646
3647 this.$accessKeyed = $accessKeyed;
3648 if ( this.accessKey ) {
3649 this.$accessKeyed.attr( 'accesskey', this.accessKey );
3650 }
3651 };
3652
3653 /**
3654 * Set access key.
3655 *
3656 * @param {string|Function|null} accessKey Key, a function that returns a key, or `null` for no
3657 * access key
3658 * @chainable
3659 * @return {OO.ui.Element} The element, for chaining
3660 */
3661 OO.ui.mixin.AccessKeyedElement.prototype.setAccessKey = function ( accessKey ) {
3662 accessKey = typeof accessKey === 'string' ? OO.ui.resolveMsg( accessKey ) : null;
3663
3664 if ( this.accessKey !== accessKey ) {
3665 if ( this.$accessKeyed ) {
3666 if ( accessKey !== null ) {
3667 this.$accessKeyed.attr( 'accesskey', accessKey );
3668 } else {
3669 this.$accessKeyed.removeAttr( 'accesskey' );
3670 }
3671 }
3672 this.accessKey = accessKey;
3673
3674 // Only if this is a TitledElement
3675 if ( this.updateTitle ) {
3676 this.updateTitle();
3677 }
3678 }
3679
3680 return this;
3681 };
3682
3683 /**
3684 * Get access key.
3685 *
3686 * @return {string} accessKey string
3687 */
3688 OO.ui.mixin.AccessKeyedElement.prototype.getAccessKey = function () {
3689 return this.accessKey;
3690 };
3691
3692 /**
3693 * Add information about the access key to the element's tooltip label.
3694 * (This is only public for hacky usage in FieldLayout.)
3695 *
3696 * @param {string} title Tooltip label for `title` attribute
3697 * @return {string}
3698 */
3699 OO.ui.mixin.AccessKeyedElement.prototype.formatTitleWithAccessKey = function ( title ) {
3700 var accessKey;
3701
3702 if ( !this.$accessKeyed ) {
3703 // Not initialized yet; the constructor will call updateTitle() which will rerun this
3704 // function.
3705 return title;
3706 }
3707 // Use jquery.accessKeyLabel if available to show modifiers, otherwise just display the
3708 // single key.
3709 if ( $.fn.updateTooltipAccessKeys && $.fn.updateTooltipAccessKeys.getAccessKeyLabel ) {
3710 accessKey = $.fn.updateTooltipAccessKeys.getAccessKeyLabel( this.$accessKeyed[ 0 ] );
3711 } else {
3712 accessKey = this.getAccessKey();
3713 }
3714 if ( accessKey ) {
3715 title += ' [' + accessKey + ']';
3716 }
3717 return title;
3718 };
3719
3720 /**
3721 * ButtonWidget is a generic widget for buttons. A wide variety of looks,
3722 * feels, and functionality can be customized via the class’s configuration options
3723 * and methods. Please see the [OOUI documentation on MediaWiki] [1] for more information
3724 * and examples.
3725 *
3726 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Buttons_and_Switches
3727 *
3728 * @example
3729 * // A button widget.
3730 * var button = new OO.ui.ButtonWidget( {
3731 * label: 'Button with Icon',
3732 * icon: 'trash',
3733 * title: 'Remove'
3734 * } );
3735 * $( document.body ).append( button.$element );
3736 *
3737 * NOTE: HTML form buttons should use the OO.ui.ButtonInputWidget class.
3738 *
3739 * @class
3740 * @extends OO.ui.Widget
3741 * @mixins OO.ui.mixin.ButtonElement
3742 * @mixins OO.ui.mixin.IconElement
3743 * @mixins OO.ui.mixin.IndicatorElement
3744 * @mixins OO.ui.mixin.LabelElement
3745 * @mixins OO.ui.mixin.TitledElement
3746 * @mixins OO.ui.mixin.FlaggedElement
3747 * @mixins OO.ui.mixin.TabIndexedElement
3748 * @mixins OO.ui.mixin.AccessKeyedElement
3749 *
3750 * @constructor
3751 * @param {Object} [config] Configuration options
3752 * @cfg {boolean} [active=false] Whether button should be shown as active
3753 * @cfg {string} [href] Hyperlink to visit when the button is clicked.
3754 * @cfg {string} [target] The frame or window in which to open the hyperlink.
3755 * @cfg {boolean} [noFollow] Search engine traversal hint (default: true)
3756 */
3757 OO.ui.ButtonWidget = function OoUiButtonWidget( config ) {
3758 // Configuration initialization
3759 config = config || {};
3760
3761 // Parent constructor
3762 OO.ui.ButtonWidget.parent.call( this, config );
3763
3764 // Mixin constructors
3765 OO.ui.mixin.ButtonElement.call( this, config );
3766 OO.ui.mixin.IconElement.call( this, config );
3767 OO.ui.mixin.IndicatorElement.call( this, config );
3768 OO.ui.mixin.LabelElement.call( this, config );
3769 OO.ui.mixin.TitledElement.call( this, $.extend( {
3770 $titled: this.$button
3771 }, config ) );
3772 OO.ui.mixin.FlaggedElement.call( this, config );
3773 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {
3774 $tabIndexed: this.$button
3775 }, config ) );
3776 OO.ui.mixin.AccessKeyedElement.call( this, $.extend( {
3777 $accessKeyed: this.$button
3778 }, config ) );
3779
3780 // Properties
3781 this.href = null;
3782 this.target = null;
3783 this.noFollow = false;
3784
3785 // Events
3786 this.connect( this, {
3787 disable: 'onDisable'
3788 } );
3789
3790 // Initialization
3791 this.$button.append( this.$icon, this.$label, this.$indicator );
3792 this.$element
3793 .addClass( 'oo-ui-buttonWidget' )
3794 .append( this.$button );
3795 this.setActive( config.active );
3796 this.setHref( config.href );
3797 this.setTarget( config.target );
3798 this.setNoFollow( config.noFollow );
3799 };
3800
3801 /* Setup */
3802
3803 OO.inheritClass( OO.ui.ButtonWidget, OO.ui.Widget );
3804 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.ButtonElement );
3805 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.IconElement );
3806 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.IndicatorElement );
3807 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.LabelElement );
3808 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.TitledElement );
3809 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.FlaggedElement );
3810 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.TabIndexedElement );
3811 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.AccessKeyedElement );
3812
3813 /* Static Properties */
3814
3815 /**
3816 * @static
3817 * @inheritdoc
3818 */
3819 OO.ui.ButtonWidget.static.cancelButtonMouseDownEvents = false;
3820
3821 /**
3822 * @static
3823 * @inheritdoc
3824 */
3825 OO.ui.ButtonWidget.static.tagName = 'span';
3826
3827 /* Methods */
3828
3829 /**
3830 * Get hyperlink location.
3831 *
3832 * @return {string} Hyperlink location
3833 */
3834 OO.ui.ButtonWidget.prototype.getHref = function () {
3835 return this.href;
3836 };
3837
3838 /**
3839 * Get hyperlink target.
3840 *
3841 * @return {string} Hyperlink target
3842 */
3843 OO.ui.ButtonWidget.prototype.getTarget = function () {
3844 return this.target;
3845 };
3846
3847 /**
3848 * Get search engine traversal hint.
3849 *
3850 * @return {boolean} Whether search engines should avoid traversing this hyperlink
3851 */
3852 OO.ui.ButtonWidget.prototype.getNoFollow = function () {
3853 return this.noFollow;
3854 };
3855
3856 /**
3857 * Set hyperlink location.
3858 *
3859 * @param {string|null} href Hyperlink location, null to remove
3860 * @chainable
3861 * @return {OO.ui.Widget} The widget, for chaining
3862 */
3863 OO.ui.ButtonWidget.prototype.setHref = function ( href ) {
3864 href = typeof href === 'string' ? href : null;
3865 if ( href !== null && !OO.ui.isSafeUrl( href ) ) {
3866 href = './' + href;
3867 }
3868
3869 if ( href !== this.href ) {
3870 this.href = href;
3871 this.updateHref();
3872 }
3873
3874 return this;
3875 };
3876
3877 /**
3878 * Update the `href` attribute, in case of changes to href or
3879 * disabled state.
3880 *
3881 * @private
3882 * @chainable
3883 * @return {OO.ui.Widget} The widget, for chaining
3884 */
3885 OO.ui.ButtonWidget.prototype.updateHref = function () {
3886 if ( this.href !== null && !this.isDisabled() ) {
3887 this.$button.attr( 'href', this.href );
3888 } else {
3889 this.$button.removeAttr( 'href' );
3890 }
3891
3892 return this;
3893 };
3894
3895 /**
3896 * Handle disable events.
3897 *
3898 * @private
3899 * @param {boolean} disabled Element is disabled
3900 */
3901 OO.ui.ButtonWidget.prototype.onDisable = function () {
3902 this.updateHref();
3903 };
3904
3905 /**
3906 * Set hyperlink target.
3907 *
3908 * @param {string|null} target Hyperlink target, null to remove
3909 * @return {OO.ui.Widget} The widget, for chaining
3910 */
3911 OO.ui.ButtonWidget.prototype.setTarget = function ( target ) {
3912 target = typeof target === 'string' ? target : null;
3913
3914 if ( target !== this.target ) {
3915 this.target = target;
3916 if ( target !== null ) {
3917 this.$button.attr( 'target', target );
3918 } else {
3919 this.$button.removeAttr( 'target' );
3920 }
3921 }
3922
3923 return this;
3924 };
3925
3926 /**
3927 * Set search engine traversal hint.
3928 *
3929 * @param {boolean} noFollow True if search engines should avoid traversing this hyperlink
3930 * @return {OO.ui.Widget} The widget, for chaining
3931 */
3932 OO.ui.ButtonWidget.prototype.setNoFollow = function ( noFollow ) {
3933 noFollow = typeof noFollow === 'boolean' ? noFollow : true;
3934
3935 if ( noFollow !== this.noFollow ) {
3936 this.noFollow = noFollow;
3937 if ( noFollow ) {
3938 this.$button.attr( 'rel', 'nofollow' );
3939 } else {
3940 this.$button.removeAttr( 'rel' );
3941 }
3942 }
3943
3944 return this;
3945 };
3946
3947 // Override method visibility hints from ButtonElement
3948 /**
3949 * @method setActive
3950 * @inheritdoc
3951 */
3952 /**
3953 * @method isActive
3954 * @inheritdoc
3955 */
3956
3957 /**
3958 * A ButtonGroupWidget groups related buttons and is used together with OO.ui.ButtonWidget and
3959 * its subclasses. Each button in a group is addressed by a unique reference. Buttons can be added,
3960 * removed, and cleared from the group.
3961 *
3962 * @example
3963 * // A ButtonGroupWidget with two buttons.
3964 * var button1 = new OO.ui.PopupButtonWidget( {
3965 * label: 'Select a category',
3966 * icon: 'menu',
3967 * popup: {
3968 * $content: $( '<p>List of categories…</p>' ),
3969 * padded: true,
3970 * align: 'left'
3971 * }
3972 * } ),
3973 * button2 = new OO.ui.ButtonWidget( {
3974 * label: 'Add item'
3975 * } ),
3976 * buttonGroup = new OO.ui.ButtonGroupWidget( {
3977 * items: [ button1, button2 ]
3978 * } );
3979 * $( document.body ).append( buttonGroup.$element );
3980 *
3981 * @class
3982 * @extends OO.ui.Widget
3983 * @mixins OO.ui.mixin.GroupElement
3984 * @mixins OO.ui.mixin.TitledElement
3985 *
3986 * @constructor
3987 * @param {Object} [config] Configuration options
3988 * @cfg {OO.ui.ButtonWidget[]} [items] Buttons to add
3989 */
3990 OO.ui.ButtonGroupWidget = function OoUiButtonGroupWidget( config ) {
3991 // Configuration initialization
3992 config = config || {};
3993
3994 // Parent constructor
3995 OO.ui.ButtonGroupWidget.parent.call( this, config );
3996
3997 // Mixin constructors
3998 OO.ui.mixin.GroupElement.call( this, $.extend( {
3999 $group: this.$element
4000 }, config ) );
4001 OO.ui.mixin.TitledElement.call( this, config );
4002
4003 // Initialization
4004 this.$element.addClass( 'oo-ui-buttonGroupWidget' );
4005 if ( Array.isArray( config.items ) ) {
4006 this.addItems( config.items );
4007 }
4008 };
4009
4010 /* Setup */
4011
4012 OO.inheritClass( OO.ui.ButtonGroupWidget, OO.ui.Widget );
4013 OO.mixinClass( OO.ui.ButtonGroupWidget, OO.ui.mixin.GroupElement );
4014 OO.mixinClass( OO.ui.ButtonGroupWidget, OO.ui.mixin.TitledElement );
4015
4016 /* Static Properties */
4017
4018 /**
4019 * @static
4020 * @inheritdoc
4021 */
4022 OO.ui.ButtonGroupWidget.static.tagName = 'span';
4023
4024 /* Methods */
4025
4026 /**
4027 * Focus the widget
4028 *
4029 * @chainable
4030 * @return {OO.ui.Widget} The widget, for chaining
4031 */
4032 OO.ui.ButtonGroupWidget.prototype.focus = function () {
4033 if ( !this.isDisabled() ) {
4034 if ( this.items[ 0 ] ) {
4035 this.items[ 0 ].focus();
4036 }
4037 }
4038 return this;
4039 };
4040
4041 /**
4042 * @inheritdoc
4043 */
4044 OO.ui.ButtonGroupWidget.prototype.simulateLabelClick = function () {
4045 this.focus();
4046 };
4047
4048 /**
4049 * IconWidget is a generic widget for {@link OO.ui.mixin.IconElement icons}.
4050 * In general, IconWidgets should be used with OO.ui.LabelWidget, which creates a label that
4051 * identifies the icon’s function. See the [OOUI documentation on MediaWiki] [1]
4052 * for a list of icons included in the library.
4053 *
4054 * @example
4055 * // An IconWidget with a label via LabelWidget.
4056 * var myIcon = new OO.ui.IconWidget( {
4057 * icon: 'help',
4058 * title: 'Help'
4059 * } ),
4060 * // Create a label.
4061 * iconLabel = new OO.ui.LabelWidget( {
4062 * label: 'Help'
4063 * } );
4064 * $( document.body ).append( myIcon.$element, iconLabel.$element );
4065 *
4066 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Icons,_Indicators,_and_Labels#Icons
4067 *
4068 * @class
4069 * @extends OO.ui.Widget
4070 * @mixins OO.ui.mixin.IconElement
4071 * @mixins OO.ui.mixin.TitledElement
4072 * @mixins OO.ui.mixin.LabelElement
4073 * @mixins OO.ui.mixin.FlaggedElement
4074 *
4075 * @constructor
4076 * @param {Object} [config] Configuration options
4077 */
4078 OO.ui.IconWidget = function OoUiIconWidget( config ) {
4079 // Configuration initialization
4080 config = config || {};
4081
4082 // Parent constructor
4083 OO.ui.IconWidget.parent.call( this, config );
4084
4085 // Mixin constructors
4086 OO.ui.mixin.IconElement.call( this, $.extend( {
4087 $icon: this.$element
4088 }, config ) );
4089 OO.ui.mixin.TitledElement.call( this, $.extend( {
4090 $titled: this.$element
4091 }, config ) );
4092 OO.ui.mixin.LabelElement.call( this, $.extend( {
4093 $label: this.$element,
4094 invisibleLabel: true
4095 }, config ) );
4096 OO.ui.mixin.FlaggedElement.call( this, $.extend( {
4097 $flagged: this.$element
4098 }, config ) );
4099
4100 // Initialization
4101 this.$element.addClass( 'oo-ui-iconWidget' );
4102 // Remove class added by LabelElement initialization. It causes unexpected CSS to apply when
4103 // nested in other widgets, because this widget used to not mix in LabelElement.
4104 this.$element.removeClass( 'oo-ui-labelElement-label' );
4105 };
4106
4107 /* Setup */
4108
4109 OO.inheritClass( OO.ui.IconWidget, OO.ui.Widget );
4110 OO.mixinClass( OO.ui.IconWidget, OO.ui.mixin.IconElement );
4111 OO.mixinClass( OO.ui.IconWidget, OO.ui.mixin.TitledElement );
4112 OO.mixinClass( OO.ui.IconWidget, OO.ui.mixin.LabelElement );
4113 OO.mixinClass( OO.ui.IconWidget, OO.ui.mixin.FlaggedElement );
4114
4115 /* Static Properties */
4116
4117 /**
4118 * @static
4119 * @inheritdoc
4120 */
4121 OO.ui.IconWidget.static.tagName = 'span';
4122
4123 /**
4124 * IndicatorWidgets create indicators, which are small graphics that are generally used to draw
4125 * attention to the status of an item or to clarify the function within a control. For a list of
4126 * indicators included in the library, please see the [OOUI documentation on MediaWiki][1].
4127 *
4128 * @example
4129 * // An indicator widget.
4130 * var indicator1 = new OO.ui.IndicatorWidget( {
4131 * indicator: 'required'
4132 * } ),
4133 * // Create a fieldset layout to add a label.
4134 * fieldset = new OO.ui.FieldsetLayout();
4135 * fieldset.addItems( [
4136 * new OO.ui.FieldLayout( indicator1, {
4137 * label: 'A required indicator:'
4138 * } )
4139 * ] );
4140 * $( document.body ).append( fieldset.$element );
4141 *
4142 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Icons,_Indicators,_and_Labels#Indicators
4143 *
4144 * @class
4145 * @extends OO.ui.Widget
4146 * @mixins OO.ui.mixin.IndicatorElement
4147 * @mixins OO.ui.mixin.TitledElement
4148 * @mixins OO.ui.mixin.LabelElement
4149 *
4150 * @constructor
4151 * @param {Object} [config] Configuration options
4152 */
4153 OO.ui.IndicatorWidget = function OoUiIndicatorWidget( config ) {
4154 // Configuration initialization
4155 config = config || {};
4156
4157 // Parent constructor
4158 OO.ui.IndicatorWidget.parent.call( this, config );
4159
4160 // Mixin constructors
4161 OO.ui.mixin.IndicatorElement.call( this, $.extend( {
4162 $indicator: this.$element
4163 }, config ) );
4164 OO.ui.mixin.TitledElement.call( this, $.extend( {
4165 $titled: this.$element
4166 }, config ) );
4167 OO.ui.mixin.LabelElement.call( this, $.extend( {
4168 $label: this.$element,
4169 invisibleLabel: true
4170 }, config ) );
4171
4172 // Initialization
4173 this.$element.addClass( 'oo-ui-indicatorWidget' );
4174 // Remove class added by LabelElement initialization. It causes unexpected CSS to apply when
4175 // nested in other widgets, because this widget used to not mix in LabelElement.
4176 this.$element.removeClass( 'oo-ui-labelElement-label' );
4177 };
4178
4179 /* Setup */
4180
4181 OO.inheritClass( OO.ui.IndicatorWidget, OO.ui.Widget );
4182 OO.mixinClass( OO.ui.IndicatorWidget, OO.ui.mixin.IndicatorElement );
4183 OO.mixinClass( OO.ui.IndicatorWidget, OO.ui.mixin.TitledElement );
4184 OO.mixinClass( OO.ui.IndicatorWidget, OO.ui.mixin.LabelElement );
4185
4186 /* Static Properties */
4187
4188 /**
4189 * @static
4190 * @inheritdoc
4191 */
4192 OO.ui.IndicatorWidget.static.tagName = 'span';
4193
4194 /**
4195 * LabelWidgets help identify the function of interface elements. Each LabelWidget can
4196 * be configured with a `label` option that is set to a string, a label node, or a function:
4197 *
4198 * - String: a plaintext string
4199 * - jQuery selection: a jQuery selection, used for anything other than a plaintext label, e.g., a
4200 * label that includes a link or special styling, such as a gray color or additional
4201 * graphical elements.
4202 * - Function: a function that will produce a string in the future. Functions are used
4203 * in cases where the value of the label is not currently defined.
4204 *
4205 * In addition, the LabelWidget can be associated with an {@link OO.ui.InputWidget input widget},
4206 * which will come into focus when the label is clicked.
4207 *
4208 * @example
4209 * // Two LabelWidgets.
4210 * var label1 = new OO.ui.LabelWidget( {
4211 * label: 'plaintext label'
4212 * } ),
4213 * label2 = new OO.ui.LabelWidget( {
4214 * label: $( '<a>' ).attr( 'href', 'default.html' ).text( 'jQuery label' )
4215 * } ),
4216 * // Create a fieldset layout with fields for each example.
4217 * fieldset = new OO.ui.FieldsetLayout();
4218 * fieldset.addItems( [
4219 * new OO.ui.FieldLayout( label1 ),
4220 * new OO.ui.FieldLayout( label2 )
4221 * ] );
4222 * $( document.body ).append( fieldset.$element );
4223 *
4224 * @class
4225 * @extends OO.ui.Widget
4226 * @mixins OO.ui.mixin.LabelElement
4227 * @mixins OO.ui.mixin.TitledElement
4228 *
4229 * @constructor
4230 * @param {Object} [config] Configuration options
4231 * @cfg {OO.ui.InputWidget} [input] {@link OO.ui.InputWidget Input widget} that uses the label.
4232 * Clicking the label will focus the specified input field.
4233 */
4234 OO.ui.LabelWidget = function OoUiLabelWidget( config ) {
4235 // Configuration initialization
4236 config = config || {};
4237
4238 // Parent constructor
4239 OO.ui.LabelWidget.parent.call( this, config );
4240
4241 // Mixin constructors
4242 OO.ui.mixin.LabelElement.call( this, $.extend( {
4243 $label: this.$element
4244 }, config ) );
4245 OO.ui.mixin.TitledElement.call( this, config );
4246
4247 // Properties
4248 this.input = config.input;
4249
4250 // Initialization
4251 if ( this.input ) {
4252 if ( this.input.getInputId() ) {
4253 this.$element.attr( 'for', this.input.getInputId() );
4254 } else {
4255 this.$label.on( 'click', function () {
4256 this.input.simulateLabelClick();
4257 }.bind( this ) );
4258 }
4259 }
4260 this.$element.addClass( 'oo-ui-labelWidget' );
4261 };
4262
4263 /* Setup */
4264
4265 OO.inheritClass( OO.ui.LabelWidget, OO.ui.Widget );
4266 OO.mixinClass( OO.ui.LabelWidget, OO.ui.mixin.LabelElement );
4267 OO.mixinClass( OO.ui.LabelWidget, OO.ui.mixin.TitledElement );
4268
4269 /* Static Properties */
4270
4271 /**
4272 * @static
4273 * @inheritdoc
4274 */
4275 OO.ui.LabelWidget.static.tagName = 'label';
4276
4277 /**
4278 * PendingElement is a mixin that is used to create elements that notify users that something is
4279 * happening and that they should wait before proceeding. The pending state is visually represented
4280 * with a pending texture that appears in the head of a pending
4281 * {@link OO.ui.ProcessDialog process dialog} or in the input field of a
4282 * {@link OO.ui.TextInputWidget text input widget}.
4283 *
4284 * Currently, {@link OO.ui.ActionWidget Action widgets}, which mix in this class, can also be marked
4285 * as pending, but only when used in {@link OO.ui.MessageDialog message dialogs}. The behavior is
4286 * not currently supported for action widgets used in process dialogs.
4287 *
4288 * @example
4289 * function MessageDialog( config ) {
4290 * MessageDialog.parent.call( this, config );
4291 * }
4292 * OO.inheritClass( MessageDialog, OO.ui.MessageDialog );
4293 *
4294 * MessageDialog.static.name = 'myMessageDialog';
4295 * MessageDialog.static.actions = [
4296 * { action: 'save', label: 'Done', flags: 'primary' },
4297 * { label: 'Cancel', flags: 'safe' }
4298 * ];
4299 *
4300 * MessageDialog.prototype.initialize = function () {
4301 * MessageDialog.parent.prototype.initialize.apply( this, arguments );
4302 * this.content = new OO.ui.PanelLayout( { padded: true } );
4303 * this.content.$element.append( '<p>Click the \'Done\' action widget to see its pending ' +
4304 * 'state. Note that action widgets can be marked pending in message dialogs but not ' +
4305 * 'process dialogs.</p>' );
4306 * this.$body.append( this.content.$element );
4307 * };
4308 * MessageDialog.prototype.getBodyHeight = function () {
4309 * return 100;
4310 * }
4311 * MessageDialog.prototype.getActionProcess = function ( action ) {
4312 * var dialog = this;
4313 * if ( action === 'save' ) {
4314 * dialog.getActions().get({actions: 'save'})[0].pushPending();
4315 * return new OO.ui.Process()
4316 * .next( 1000 )
4317 * .next( function () {
4318 * dialog.getActions().get({actions: 'save'})[0].popPending();
4319 * } );
4320 * }
4321 * return MessageDialog.parent.prototype.getActionProcess.call( this, action );
4322 * };
4323 *
4324 * var windowManager = new OO.ui.WindowManager();
4325 * $( document.body ).append( windowManager.$element );
4326 *
4327 * var dialog = new MessageDialog();
4328 * windowManager.addWindows( [ dialog ] );
4329 * windowManager.openWindow( dialog );
4330 *
4331 * @abstract
4332 * @class
4333 *
4334 * @constructor
4335 * @param {Object} [config] Configuration options
4336 * @cfg {jQuery} [$pending] Element to mark as pending, defaults to this.$element
4337 */
4338 OO.ui.mixin.PendingElement = function OoUiMixinPendingElement( config ) {
4339 // Configuration initialization
4340 config = config || {};
4341
4342 // Properties
4343 this.pending = 0;
4344 this.$pending = null;
4345
4346 // Initialisation
4347 this.setPendingElement( config.$pending || this.$element );
4348 };
4349
4350 /* Setup */
4351
4352 OO.initClass( OO.ui.mixin.PendingElement );
4353
4354 /* Methods */
4355
4356 /**
4357 * Set the pending element (and clean up any existing one).
4358 *
4359 * @param {jQuery} $pending The element to set to pending.
4360 */
4361 OO.ui.mixin.PendingElement.prototype.setPendingElement = function ( $pending ) {
4362 if ( this.$pending ) {
4363 this.$pending.removeClass( 'oo-ui-pendingElement-pending' );
4364 }
4365
4366 this.$pending = $pending;
4367 if ( this.pending > 0 ) {
4368 this.$pending.addClass( 'oo-ui-pendingElement-pending' );
4369 }
4370 };
4371
4372 /**
4373 * Check if an element is pending.
4374 *
4375 * @return {boolean} Element is pending
4376 */
4377 OO.ui.mixin.PendingElement.prototype.isPending = function () {
4378 return !!this.pending;
4379 };
4380
4381 /**
4382 * Increase the pending counter. The pending state will remain active until the counter is zero
4383 * (i.e., the number of calls to #pushPending and #popPending is the same).
4384 *
4385 * @chainable
4386 * @return {OO.ui.Element} The element, for chaining
4387 */
4388 OO.ui.mixin.PendingElement.prototype.pushPending = function () {
4389 if ( this.pending === 0 ) {
4390 this.$pending.addClass( 'oo-ui-pendingElement-pending' );
4391 this.updateThemeClasses();
4392 }
4393 this.pending++;
4394
4395 return this;
4396 };
4397
4398 /**
4399 * Decrease the pending counter. The pending state will remain active until the counter is zero
4400 * (i.e., the number of calls to #pushPending and #popPending is the same).
4401 *
4402 * @chainable
4403 * @return {OO.ui.Element} The element, for chaining
4404 */
4405 OO.ui.mixin.PendingElement.prototype.popPending = function () {
4406 if ( this.pending === 1 ) {
4407 this.$pending.removeClass( 'oo-ui-pendingElement-pending' );
4408 this.updateThemeClasses();
4409 }
4410 this.pending = Math.max( 0, this.pending - 1 );
4411
4412 return this;
4413 };
4414
4415 /**
4416 * Element that will stick adjacent to a specified container, even when it is inserted elsewhere
4417 * in the document (for example, in an OO.ui.Window's $overlay).
4418 *
4419 * The elements's position is automatically calculated and maintained when window is resized or the
4420 * page is scrolled. If you reposition the container manually, you have to call #position to make
4421 * sure the element is still placed correctly.
4422 *
4423 * As positioning is only possible when both the element and the container are attached to the DOM
4424 * and visible, it's only done after you call #togglePositioning. You might want to do this inside
4425 * the #toggle method to display a floating popup, for example.
4426 *
4427 * @abstract
4428 * @class
4429 *
4430 * @constructor
4431 * @param {Object} [config] Configuration options
4432 * @cfg {jQuery} [$floatable] Node to position, assigned to #$floatable, omit to use #$element
4433 * @cfg {jQuery} [$floatableContainer] Node to position adjacent to
4434 * @cfg {string} [verticalPosition='below'] Where to position $floatable vertically:
4435 * 'below': Directly below $floatableContainer, aligning f's top edge with fC's bottom edge
4436 * 'above': Directly above $floatableContainer, aligning f's bottom edge with fC's top edge
4437 * 'top': Align the top edge with $floatableContainer's top edge
4438 * 'bottom': Align the bottom edge with $floatableContainer's bottom edge
4439 * 'center': Vertically align the center with $floatableContainer's center
4440 * @cfg {string} [horizontalPosition='start'] Where to position $floatable horizontally:
4441 * 'before': Directly before $floatableContainer, aligning f's end edge with fC's start edge
4442 * 'after': Directly after $floatableContainer, aligning f's start edge with fC's end edge
4443 * 'start': Align the start (left in LTR, right in RTL) edge with $floatableContainer's start edge
4444 * 'end': Align the end (right in LTR, left in RTL) edge with $floatableContainer's end edge
4445 * 'center': Horizontally align the center with $floatableContainer's center
4446 * @cfg {boolean} [hideWhenOutOfView=true] Whether to hide the floatable element if the container
4447 * is out of view
4448 */
4449 OO.ui.mixin.FloatableElement = function OoUiMixinFloatableElement( config ) {
4450 // Configuration initialization
4451 config = config || {};
4452
4453 // Properties
4454 this.$floatable = null;
4455 this.$floatableContainer = null;
4456 this.$floatableWindow = null;
4457 this.$floatableClosestScrollable = null;
4458 this.floatableOutOfView = false;
4459 this.onFloatableScrollHandler = this.position.bind( this );
4460 this.onFloatableWindowResizeHandler = this.position.bind( this );
4461
4462 // Initialization
4463 this.setFloatableContainer( config.$floatableContainer );
4464 this.setFloatableElement( config.$floatable || this.$element );
4465 this.setVerticalPosition( config.verticalPosition || 'below' );
4466 this.setHorizontalPosition( config.horizontalPosition || 'start' );
4467 this.hideWhenOutOfView = config.hideWhenOutOfView === undefined ?
4468 true : !!config.hideWhenOutOfView;
4469 };
4470
4471 /* Methods */
4472
4473 /**
4474 * Set floatable element.
4475 *
4476 * If an element is already set, it will be cleaned up before setting up the new element.
4477 *
4478 * @param {jQuery} $floatable Element to make floatable
4479 */
4480 OO.ui.mixin.FloatableElement.prototype.setFloatableElement = function ( $floatable ) {
4481 if ( this.$floatable ) {
4482 this.$floatable.removeClass( 'oo-ui-floatableElement-floatable' );
4483 this.$floatable.css( { left: '', top: '' } );
4484 }
4485
4486 this.$floatable = $floatable.addClass( 'oo-ui-floatableElement-floatable' );
4487 this.position();
4488 };
4489
4490 /**
4491 * Set floatable container.
4492 *
4493 * The element will be positioned relative to the specified container.
4494 *
4495 * @param {jQuery|null} $floatableContainer Container to keep visible, or null to unset
4496 */
4497 OO.ui.mixin.FloatableElement.prototype.setFloatableContainer = function ( $floatableContainer ) {
4498 this.$floatableContainer = $floatableContainer;
4499 if ( this.$floatable ) {
4500 this.position();
4501 }
4502 };
4503
4504 /**
4505 * Change how the element is positioned vertically.
4506 *
4507 * @param {string} position 'below', 'above', 'top', 'bottom' or 'center'
4508 */
4509 OO.ui.mixin.FloatableElement.prototype.setVerticalPosition = function ( position ) {
4510 if ( [ 'below', 'above', 'top', 'bottom', 'center' ].indexOf( position ) === -1 ) {
4511 throw new Error( 'Invalid value for vertical position: ' + position );
4512 }
4513 if ( this.verticalPosition !== position ) {
4514 this.verticalPosition = position;
4515 if ( this.$floatable ) {
4516 this.position();
4517 }
4518 }
4519 };
4520
4521 /**
4522 * Change how the element is positioned horizontally.
4523 *
4524 * @param {string} position 'before', 'after', 'start', 'end' or 'center'
4525 */
4526 OO.ui.mixin.FloatableElement.prototype.setHorizontalPosition = function ( position ) {
4527 if ( [ 'before', 'after', 'start', 'end', 'center' ].indexOf( position ) === -1 ) {
4528 throw new Error( 'Invalid value for horizontal position: ' + position );
4529 }
4530 if ( this.horizontalPosition !== position ) {
4531 this.horizontalPosition = position;
4532 if ( this.$floatable ) {
4533 this.position();
4534 }
4535 }
4536 };
4537
4538 /**
4539 * Toggle positioning.
4540 *
4541 * Do not turn positioning on until after the element is attached to the DOM and visible.
4542 *
4543 * @param {boolean} [positioning] Enable positioning, omit to toggle
4544 * @chainable
4545 * @return {OO.ui.Element} The element, for chaining
4546 */
4547 OO.ui.mixin.FloatableElement.prototype.togglePositioning = function ( positioning ) {
4548 var closestScrollableOfContainer;
4549
4550 if ( !this.$floatable || !this.$floatableContainer ) {
4551 return this;
4552 }
4553
4554 positioning = positioning === undefined ? !this.positioning : !!positioning;
4555
4556 if ( positioning && !this.warnedUnattached && !this.isElementAttached() ) {
4557 OO.ui.warnDeprecation( 'FloatableElement#togglePositioning: Before calling this method, the element must be attached to the DOM.' );
4558 this.warnedUnattached = true;
4559 }
4560
4561 if ( this.positioning !== positioning ) {
4562 this.positioning = positioning;
4563
4564 closestScrollableOfContainer = OO.ui.Element.static.getClosestScrollableContainer(
4565 this.$floatableContainer[ 0 ]
4566 );
4567 // If the scrollable is the root, we have to listen to scroll events
4568 // on the window because of browser inconsistencies.
4569 if ( $( closestScrollableOfContainer ).is( 'html, body' ) ) {
4570 closestScrollableOfContainer = OO.ui.Element.static.getWindow(
4571 closestScrollableOfContainer
4572 );
4573 }
4574
4575 if ( positioning ) {
4576 this.$floatableWindow = $( this.getElementWindow() );
4577 this.$floatableWindow.on( 'resize', this.onFloatableWindowResizeHandler );
4578
4579 this.$floatableClosestScrollable = $( closestScrollableOfContainer );
4580 this.$floatableClosestScrollable.on( 'scroll', this.onFloatableScrollHandler );
4581
4582 // Initial position after visible
4583 this.position();
4584 } else {
4585 if ( this.$floatableWindow ) {
4586 this.$floatableWindow.off( 'resize', this.onFloatableWindowResizeHandler );
4587 this.$floatableWindow = null;
4588 }
4589
4590 if ( this.$floatableClosestScrollable ) {
4591 this.$floatableClosestScrollable.off( 'scroll', this.onFloatableScrollHandler );
4592 this.$floatableClosestScrollable = null;
4593 }
4594
4595 this.$floatable.css( { left: '', right: '', top: '' } );
4596 }
4597 }
4598
4599 return this;
4600 };
4601
4602 /**
4603 * Check whether the bottom edge of the given element is within the viewport of the given
4604 * container.
4605 *
4606 * @private
4607 * @param {jQuery} $element
4608 * @param {jQuery} $container
4609 * @return {boolean}
4610 */
4611 OO.ui.mixin.FloatableElement.prototype.isElementInViewport = function ( $element, $container ) {
4612 var elemRect, contRect, topEdgeInBounds, bottomEdgeInBounds, leftEdgeInBounds,
4613 rightEdgeInBounds, startEdgeInBounds, endEdgeInBounds, viewportSpacing,
4614 direction = $element.css( 'direction' );
4615
4616 elemRect = $element[ 0 ].getBoundingClientRect();
4617 if ( $container[ 0 ] === window ) {
4618 viewportSpacing = OO.ui.getViewportSpacing();
4619 contRect = {
4620 top: 0,
4621 left: 0,
4622 right: document.documentElement.clientWidth,
4623 bottom: document.documentElement.clientHeight
4624 };
4625 contRect.top += viewportSpacing.top;
4626 contRect.left += viewportSpacing.left;
4627 contRect.right -= viewportSpacing.right;
4628 contRect.bottom -= viewportSpacing.bottom;
4629 } else {
4630 contRect = $container[ 0 ].getBoundingClientRect();
4631 }
4632
4633 topEdgeInBounds = elemRect.top >= contRect.top && elemRect.top <= contRect.bottom;
4634 bottomEdgeInBounds = elemRect.bottom >= contRect.top && elemRect.bottom <= contRect.bottom;
4635 leftEdgeInBounds = elemRect.left >= contRect.left && elemRect.left <= contRect.right;
4636 rightEdgeInBounds = elemRect.right >= contRect.left && elemRect.right <= contRect.right;
4637 if ( direction === 'rtl' ) {
4638 startEdgeInBounds = rightEdgeInBounds;
4639 endEdgeInBounds = leftEdgeInBounds;
4640 } else {
4641 startEdgeInBounds = leftEdgeInBounds;
4642 endEdgeInBounds = rightEdgeInBounds;
4643 }
4644
4645 if ( this.verticalPosition === 'below' && !bottomEdgeInBounds ) {
4646 return false;
4647 }
4648 if ( this.verticalPosition === 'above' && !topEdgeInBounds ) {
4649 return false;
4650 }
4651 if ( this.horizontalPosition === 'before' && !startEdgeInBounds ) {
4652 return false;
4653 }
4654 if ( this.horizontalPosition === 'after' && !endEdgeInBounds ) {
4655 return false;
4656 }
4657
4658 // The other positioning values are all about being inside the container,
4659 // so in those cases all we care about is that any part of the container is visible.
4660 return elemRect.top <= contRect.bottom && elemRect.bottom >= contRect.top &&
4661 elemRect.left <= contRect.right && elemRect.right >= contRect.left;
4662 };
4663
4664 /**
4665 * Check if the floatable is hidden to the user because it was offscreen.
4666 *
4667 * @return {boolean} Floatable is out of view
4668 */
4669 OO.ui.mixin.FloatableElement.prototype.isFloatableOutOfView = function () {
4670 return this.floatableOutOfView;
4671 };
4672
4673 /**
4674 * Position the floatable below its container.
4675 *
4676 * This should only be done when both of them are attached to the DOM and visible.
4677 *
4678 * @chainable
4679 * @return {OO.ui.Element} The element, for chaining
4680 */
4681 OO.ui.mixin.FloatableElement.prototype.position = function () {
4682 if ( !this.positioning ) {
4683 return this;
4684 }
4685
4686 if ( !(
4687 // To continue, some things need to be true:
4688 // The element must actually be in the DOM
4689 this.isElementAttached() && (
4690 // The closest scrollable is the current window
4691 this.$floatableClosestScrollable[ 0 ] === this.getElementWindow() ||
4692 // OR is an element in the element's DOM
4693 $.contains( this.getElementDocument(), this.$floatableClosestScrollable[ 0 ] )
4694 )
4695 ) ) {
4696 // Abort early if important parts of the widget are no longer attached to the DOM
4697 return this;
4698 }
4699
4700 this.floatableOutOfView = this.hideWhenOutOfView &&
4701 !this.isElementInViewport( this.$floatableContainer, this.$floatableClosestScrollable );
4702 if ( this.floatableOutOfView ) {
4703 this.$floatable.addClass( 'oo-ui-element-hidden' );
4704 return this;
4705 } else {
4706 this.$floatable.removeClass( 'oo-ui-element-hidden' );
4707 }
4708
4709 this.$floatable.css( this.computePosition() );
4710
4711 // We updated the position, so re-evaluate the clipping state.
4712 // (ClippableElement does not listen to 'scroll' events on $floatableContainer's parent, and so
4713 // will not notice the need to update itself.)
4714 // TODO: This is terrible, we shouldn't need to know about ClippableElement at all here.
4715 // Why does it not listen to the right events in the right places?
4716 if ( this.clip ) {
4717 this.clip();
4718 }
4719
4720 return this;
4721 };
4722
4723 /**
4724 * Compute how #$floatable should be positioned based on the position of #$floatableContainer
4725 * and the positioning settings. This is a helper for #position that shouldn't be called directly,
4726 * but may be overridden by subclasses if they want to change or add to the positioning logic.
4727 *
4728 * @return {Object} New position to apply with .css(). Keys are 'top', 'left', 'bottom' and 'right'.
4729 */
4730 OO.ui.mixin.FloatableElement.prototype.computePosition = function () {
4731 var isBody, scrollableX, scrollableY, containerPos,
4732 horizScrollbarHeight, vertScrollbarWidth, scrollTop, scrollLeft,
4733 newPos = { top: '', left: '', bottom: '', right: '' },
4734 direction = this.$floatableContainer.css( 'direction' ),
4735 $offsetParent = this.$floatable.offsetParent();
4736
4737 if ( $offsetParent.is( 'html' ) ) {
4738 // The innerHeight/Width and clientHeight/Width calculations don't work well on the
4739 // <html> element, but they do work on the <body>
4740 $offsetParent = $( $offsetParent[ 0 ].ownerDocument.body );
4741 }
4742 isBody = $offsetParent.is( 'body' );
4743 scrollableX = $offsetParent.css( 'overflow-x' ) === 'scroll' ||
4744 $offsetParent.css( 'overflow-x' ) === 'auto';
4745 scrollableY = $offsetParent.css( 'overflow-y' ) === 'scroll' ||
4746 $offsetParent.css( 'overflow-y' ) === 'auto';
4747
4748 vertScrollbarWidth = $offsetParent.innerWidth() - $offsetParent.prop( 'clientWidth' );
4749 horizScrollbarHeight = $offsetParent.innerHeight() - $offsetParent.prop( 'clientHeight' );
4750 // We don't need to compute and add scrollTop and scrollLeft if the scrollable container
4751 // is the body, or if it isn't scrollable
4752 scrollTop = scrollableY && !isBody ?
4753 $offsetParent.scrollTop() : 0;
4754 scrollLeft = scrollableX && !isBody ?
4755 OO.ui.Element.static.getScrollLeft( $offsetParent[ 0 ] ) : 0;
4756
4757 // Avoid passing the <body> to getRelativePosition(), because it won't return what we expect
4758 // if the <body> has a margin
4759 containerPos = isBody ?
4760 this.$floatableContainer.offset() :
4761 OO.ui.Element.static.getRelativePosition( this.$floatableContainer, $offsetParent );
4762 containerPos.bottom = containerPos.top + this.$floatableContainer.outerHeight();
4763 containerPos.right = containerPos.left + this.$floatableContainer.outerWidth();
4764 containerPos.start = direction === 'rtl' ? containerPos.right : containerPos.left;
4765 containerPos.end = direction === 'rtl' ? containerPos.left : containerPos.right;
4766
4767 if ( this.verticalPosition === 'below' ) {
4768 newPos.top = containerPos.bottom;
4769 } else if ( this.verticalPosition === 'above' ) {
4770 newPos.bottom = $offsetParent.outerHeight() - containerPos.top;
4771 } else if ( this.verticalPosition === 'top' ) {
4772 newPos.top = containerPos.top;
4773 } else if ( this.verticalPosition === 'bottom' ) {
4774 newPos.bottom = $offsetParent.outerHeight() - containerPos.bottom;
4775 } else if ( this.verticalPosition === 'center' ) {
4776 newPos.top = containerPos.top +
4777 ( this.$floatableContainer.height() - this.$floatable.height() ) / 2;
4778 }
4779
4780 if ( this.horizontalPosition === 'before' ) {
4781 newPos.end = containerPos.start;
4782 } else if ( this.horizontalPosition === 'after' ) {
4783 newPos.start = containerPos.end;
4784 } else if ( this.horizontalPosition === 'start' ) {
4785 newPos.start = containerPos.start;
4786 } else if ( this.horizontalPosition === 'end' ) {
4787 newPos.end = containerPos.end;
4788 } else if ( this.horizontalPosition === 'center' ) {
4789 newPos.left = containerPos.left +
4790 ( this.$floatableContainer.width() - this.$floatable.width() ) / 2;
4791 }
4792
4793 if ( newPos.start !== undefined ) {
4794 if ( direction === 'rtl' ) {
4795 newPos.right = ( isBody ? $( $offsetParent[ 0 ].ownerDocument.documentElement ) :
4796 $offsetParent ).outerWidth() - newPos.start;
4797 } else {
4798 newPos.left = newPos.start;
4799 }
4800 delete newPos.start;
4801 }
4802 if ( newPos.end !== undefined ) {
4803 if ( direction === 'rtl' ) {
4804 newPos.left = newPos.end;
4805 } else {
4806 newPos.right = ( isBody ? $( $offsetParent[ 0 ].ownerDocument.documentElement ) :
4807 $offsetParent ).outerWidth() - newPos.end;
4808 }
4809 delete newPos.end;
4810 }
4811
4812 // Account for scroll position
4813 if ( newPos.top !== '' ) {
4814 newPos.top += scrollTop;
4815 }
4816 if ( newPos.bottom !== '' ) {
4817 newPos.bottom -= scrollTop;
4818 }
4819 if ( newPos.left !== '' ) {
4820 newPos.left += scrollLeft;
4821 }
4822 if ( newPos.right !== '' ) {
4823 newPos.right -= scrollLeft;
4824 }
4825
4826 // Account for scrollbar gutter
4827 if ( newPos.bottom !== '' ) {
4828 newPos.bottom -= horizScrollbarHeight;
4829 }
4830 if ( direction === 'rtl' ) {
4831 if ( newPos.left !== '' ) {
4832 newPos.left -= vertScrollbarWidth;
4833 }
4834 } else {
4835 if ( newPos.right !== '' ) {
4836 newPos.right -= vertScrollbarWidth;
4837 }
4838 }
4839
4840 return newPos;
4841 };
4842
4843 /**
4844 * Element that can be automatically clipped to visible boundaries.
4845 *
4846 * Whenever the element's natural height changes, you have to call
4847 * {@link OO.ui.mixin.ClippableElement#clip} to make sure it's still
4848 * clipping correctly.
4849 *
4850 * The dimensions of #$clippableContainer will be compared to the boundaries of the
4851 * nearest scrollable container. If #$clippableContainer is too tall and/or too wide,
4852 * then #$clippable will be given a fixed reduced height and/or width and will be made
4853 * scrollable. By default, #$clippable and #$clippableContainer are the same element,
4854 * but you can build a static footer by setting #$clippableContainer to an element that contains
4855 * #$clippable and the footer.
4856 *
4857 * @abstract
4858 * @class
4859 *
4860 * @constructor
4861 * @param {Object} [config] Configuration options
4862 * @cfg {jQuery} [$clippable] Node to clip, assigned to #$clippable, omit to use #$element
4863 * @cfg {jQuery} [$clippableContainer] Node to keep visible, assigned to #$clippableContainer,
4864 * omit to use #$clippable
4865 */
4866 OO.ui.mixin.ClippableElement = function OoUiMixinClippableElement( config ) {
4867 // Configuration initialization
4868 config = config || {};
4869
4870 // Properties
4871 this.$clippable = null;
4872 this.$clippableContainer = null;
4873 this.clipping = false;
4874 this.clippedHorizontally = false;
4875 this.clippedVertically = false;
4876 this.$clippableScrollableContainer = null;
4877 this.$clippableScroller = null;
4878 this.$clippableWindow = null;
4879 this.idealWidth = null;
4880 this.idealHeight = null;
4881 this.onClippableScrollHandler = this.clip.bind( this );
4882 this.onClippableWindowResizeHandler = this.clip.bind( this );
4883
4884 // Initialization
4885 if ( config.$clippableContainer ) {
4886 this.setClippableContainer( config.$clippableContainer );
4887 }
4888 this.setClippableElement( config.$clippable || this.$element );
4889 };
4890
4891 /* Methods */
4892
4893 /**
4894 * Set clippable element.
4895 *
4896 * If an element is already set, it will be cleaned up before setting up the new element.
4897 *
4898 * @param {jQuery} $clippable Element to make clippable
4899 */
4900 OO.ui.mixin.ClippableElement.prototype.setClippableElement = function ( $clippable ) {
4901 if ( this.$clippable ) {
4902 this.$clippable.removeClass( 'oo-ui-clippableElement-clippable' );
4903 this.$clippable.css( { width: '', height: '', overflowX: '', overflowY: '' } );
4904 OO.ui.Element.static.reconsiderScrollbars( this.$clippable[ 0 ] );
4905 }
4906
4907 this.$clippable = $clippable.addClass( 'oo-ui-clippableElement-clippable' );
4908 this.clip();
4909 };
4910
4911 /**
4912 * Set clippable container.
4913 *
4914 * This is the container that will be measured when deciding whether to clip. When clipping,
4915 * #$clippable will be resized in order to keep the clippable container fully visible.
4916 *
4917 * If the clippable container is unset, #$clippable will be used.
4918 *
4919 * @param {jQuery|null} $clippableContainer Container to keep visible, or null to unset
4920 */
4921 OO.ui.mixin.ClippableElement.prototype.setClippableContainer = function ( $clippableContainer ) {
4922 this.$clippableContainer = $clippableContainer;
4923 if ( this.$clippable ) {
4924 this.clip();
4925 }
4926 };
4927
4928 /**
4929 * Toggle clipping.
4930 *
4931 * Do not turn clipping on until after the element is attached to the DOM and visible.
4932 *
4933 * @param {boolean} [clipping] Enable clipping, omit to toggle
4934 * @chainable
4935 * @return {OO.ui.Element} The element, for chaining
4936 */
4937 OO.ui.mixin.ClippableElement.prototype.toggleClipping = function ( clipping ) {
4938 clipping = clipping === undefined ? !this.clipping : !!clipping;
4939
4940 if ( clipping && !this.warnedUnattached && !this.isElementAttached() ) {
4941 OO.ui.warnDeprecation( 'ClippableElement#toggleClipping: Before calling this method, the element must be attached to the DOM.' );
4942 this.warnedUnattached = true;
4943 }
4944
4945 if ( this.clipping !== clipping ) {
4946 this.clipping = clipping;
4947 if ( clipping ) {
4948 this.$clippableScrollableContainer = $( this.getClosestScrollableElementContainer() );
4949 // If the clippable container is the root, we have to listen to scroll events and check
4950 // jQuery.scrollTop on the window because of browser inconsistencies
4951 this.$clippableScroller = this.$clippableScrollableContainer.is( 'html, body' ) ?
4952 $( OO.ui.Element.static.getWindow( this.$clippableScrollableContainer ) ) :
4953 this.$clippableScrollableContainer;
4954 this.$clippableScroller.on( 'scroll', this.onClippableScrollHandler );
4955 this.$clippableWindow = $( this.getElementWindow() )
4956 .on( 'resize', this.onClippableWindowResizeHandler );
4957 // Initial clip after visible
4958 this.clip();
4959 } else {
4960 this.$clippable.css( {
4961 width: '',
4962 height: '',
4963 maxWidth: '',
4964 maxHeight: '',
4965 overflowX: '',
4966 overflowY: ''
4967 } );
4968 OO.ui.Element.static.reconsiderScrollbars( this.$clippable[ 0 ] );
4969
4970 this.$clippableScrollableContainer = null;
4971 this.$clippableScroller.off( 'scroll', this.onClippableScrollHandler );
4972 this.$clippableScroller = null;
4973 this.$clippableWindow.off( 'resize', this.onClippableWindowResizeHandler );
4974 this.$clippableWindow = null;
4975 }
4976 }
4977
4978 return this;
4979 };
4980
4981 /**
4982 * Check if the element will be clipped to fit the visible area of the nearest scrollable container.
4983 *
4984 * @return {boolean} Element will be clipped to the visible area
4985 */
4986 OO.ui.mixin.ClippableElement.prototype.isClipping = function () {
4987 return this.clipping;
4988 };
4989
4990 /**
4991 * Check if the bottom or right of the element is being clipped by the nearest scrollable container.
4992 *
4993 * @return {boolean} Part of the element is being clipped
4994 */
4995 OO.ui.mixin.ClippableElement.prototype.isClipped = function () {
4996 return this.clippedHorizontally || this.clippedVertically;
4997 };
4998
4999 /**
5000 * Check if the right of the element is being clipped by the nearest scrollable container.
5001 *
5002 * @return {boolean} Part of the element is being clipped
5003 */
5004 OO.ui.mixin.ClippableElement.prototype.isClippedHorizontally = function () {
5005 return this.clippedHorizontally;
5006 };
5007
5008 /**
5009 * Check if the bottom of the element is being clipped by the nearest scrollable container.
5010 *
5011 * @return {boolean} Part of the element is being clipped
5012 */
5013 OO.ui.mixin.ClippableElement.prototype.isClippedVertically = function () {
5014 return this.clippedVertically;
5015 };
5016
5017 /**
5018 * Set the ideal size. These are the dimensions #$clippable will have when it's not being clipped.
5019 *
5020 * @param {number|string} [width] Width as a number of pixels or CSS string with unit suffix
5021 * @param {number|string} [height] Height as a number of pixels or CSS string with unit suffix
5022 */
5023 OO.ui.mixin.ClippableElement.prototype.setIdealSize = function ( width, height ) {
5024 this.idealWidth = width;
5025 this.idealHeight = height;
5026
5027 if ( !this.clipping ) {
5028 // Update dimensions
5029 this.$clippable.css( { width: width, height: height } );
5030 }
5031 // While clipping, idealWidth and idealHeight are not considered
5032 };
5033
5034 /**
5035 * Return the side of the clippable on which it is "anchored" (aligned to something else).
5036 * ClippableElement will clip the opposite side when reducing element's width.
5037 *
5038 * Classes that mix in ClippableElement should override this to return 'right' if their
5039 * clippable is absolutely positioned and using 'right: Npx' (and not using 'left').
5040 * If your class also mixes in FloatableElement, this is handled automatically.
5041 *
5042 * (This can't be guessed from the actual CSS because the computed values for 'left'/'right' are
5043 * always in pixels, even if they were unset or set to 'auto'.)
5044 *
5045 * When in doubt, 'left' (or 'right' in RTL) is a sane fallback.
5046 *
5047 * @return {string} 'left' or 'right'
5048 */
5049 OO.ui.mixin.ClippableElement.prototype.getHorizontalAnchorEdge = function () {
5050 if ( this.computePosition && this.positioning && this.computePosition().right !== '' ) {
5051 return 'right';
5052 }
5053 return 'left';
5054 };
5055
5056 /**
5057 * Return the side of the clippable on which it is "anchored" (aligned to something else).
5058 * ClippableElement will clip the opposite side when reducing element's width.
5059 *
5060 * Classes that mix in ClippableElement should override this to return 'bottom' if their
5061 * clippable is absolutely positioned and using 'bottom: Npx' (and not using 'top').
5062 * If your class also mixes in FloatableElement, this is handled automatically.
5063 *
5064 * (This can't be guessed from the actual CSS because the computed values for 'left'/'right' are
5065 * always in pixels, even if they were unset or set to 'auto'.)
5066 *
5067 * When in doubt, 'top' is a sane fallback.
5068 *
5069 * @return {string} 'top' or 'bottom'
5070 */
5071 OO.ui.mixin.ClippableElement.prototype.getVerticalAnchorEdge = function () {
5072 if ( this.computePosition && this.positioning && this.computePosition().bottom !== '' ) {
5073 return 'bottom';
5074 }
5075 return 'top';
5076 };
5077
5078 /**
5079 * Clip element to visible boundaries and allow scrolling when needed. You should call this method
5080 * when the element's natural height changes.
5081 *
5082 * Element will be clipped the bottom or right of the element is within 10px of the edge of, or
5083 * overlapped by, the visible area of the nearest scrollable container.
5084 *
5085 * Because calling clip() when the natural height changes isn't always possible, we also set
5086 * max-height when the element isn't being clipped. This means that if the element tries to grow
5087 * beyond the edge, something reasonable will happen before clip() is called.
5088 *
5089 * @chainable
5090 * @return {OO.ui.Element} The element, for chaining
5091 */
5092 OO.ui.mixin.ClippableElement.prototype.clip = function () {
5093 var extraHeight, extraWidth, viewportSpacing,
5094 desiredWidth, desiredHeight, allotedWidth, allotedHeight,
5095 naturalWidth, naturalHeight, clipWidth, clipHeight,
5096 $item, itemRect, $viewport, viewportRect, availableRect,
5097 direction, vertScrollbarWidth, horizScrollbarHeight,
5098 // Extra tolerance so that the sloppy code below doesn't result in results that are off
5099 // by one or two pixels. (And also so that we have space to display drop shadows.)
5100 // Chosen by fair dice roll.
5101 buffer = 7;
5102
5103 if ( !this.clipping ) {
5104 // this.$clippableScrollableContainer and this.$clippableWindow are null, so the below
5105 // will fail
5106 return this;
5107 }
5108
5109 function rectIntersection( a, b ) {
5110 var out = {};
5111 out.top = Math.max( a.top, b.top );
5112 out.left = Math.max( a.left, b.left );
5113 out.bottom = Math.min( a.bottom, b.bottom );
5114 out.right = Math.min( a.right, b.right );
5115 return out;
5116 }
5117
5118 viewportSpacing = OO.ui.getViewportSpacing();
5119
5120 if ( this.$clippableScrollableContainer.is( 'html, body' ) ) {
5121 $viewport = $( this.$clippableScrollableContainer[ 0 ].ownerDocument.body );
5122 // Dimensions of the browser window, rather than the element!
5123 viewportRect = {
5124 top: 0,
5125 left: 0,
5126 right: document.documentElement.clientWidth,
5127 bottom: document.documentElement.clientHeight
5128 };
5129 viewportRect.top += viewportSpacing.top;
5130 viewportRect.left += viewportSpacing.left;
5131 viewportRect.right -= viewportSpacing.right;
5132 viewportRect.bottom -= viewportSpacing.bottom;
5133 } else {
5134 $viewport = this.$clippableScrollableContainer;
5135 viewportRect = $viewport[ 0 ].getBoundingClientRect();
5136 // Convert into a plain object
5137 viewportRect = $.extend( {}, viewportRect );
5138 }
5139
5140 // Account for scrollbar gutter
5141 direction = $viewport.css( 'direction' );
5142 vertScrollbarWidth = $viewport.innerWidth() - $viewport.prop( 'clientWidth' );
5143 horizScrollbarHeight = $viewport.innerHeight() - $viewport.prop( 'clientHeight' );
5144 viewportRect.bottom -= horizScrollbarHeight;
5145 if ( direction === 'rtl' ) {
5146 viewportRect.left += vertScrollbarWidth;
5147 } else {
5148 viewportRect.right -= vertScrollbarWidth;
5149 }
5150
5151 // Add arbitrary tolerance
5152 viewportRect.top += buffer;
5153 viewportRect.left += buffer;
5154 viewportRect.right -= buffer;
5155 viewportRect.bottom -= buffer;
5156
5157 $item = this.$clippableContainer || this.$clippable;
5158
5159 extraHeight = $item.outerHeight() - this.$clippable.outerHeight();
5160 extraWidth = $item.outerWidth() - this.$clippable.outerWidth();
5161
5162 itemRect = $item[ 0 ].getBoundingClientRect();
5163 // Convert into a plain object
5164 itemRect = $.extend( {}, itemRect );
5165
5166 // Item might already be clipped, so we can't just use its dimensions (in case we might need to
5167 // make it larger than before). Extend the rectangle to the maximum size we are allowed to take.
5168 if ( this.getHorizontalAnchorEdge() === 'right' ) {
5169 itemRect.left = viewportRect.left;
5170 } else {
5171 itemRect.right = viewportRect.right;
5172 }
5173 if ( this.getVerticalAnchorEdge() === 'bottom' ) {
5174 itemRect.top = viewportRect.top;
5175 } else {
5176 itemRect.bottom = viewportRect.bottom;
5177 }
5178
5179 availableRect = rectIntersection( viewportRect, itemRect );
5180
5181 desiredWidth = Math.max( 0, availableRect.right - availableRect.left );
5182 desiredHeight = Math.max( 0, availableRect.bottom - availableRect.top );
5183 // It should never be desirable to exceed the dimensions of the browser viewport... right?
5184 desiredWidth = Math.min( desiredWidth,
5185 document.documentElement.clientWidth - viewportSpacing.left - viewportSpacing.right );
5186 desiredHeight = Math.min( desiredHeight,
5187 document.documentElement.clientHeight - viewportSpacing.top - viewportSpacing.right );
5188 allotedWidth = Math.ceil( desiredWidth - extraWidth );
5189 allotedHeight = Math.ceil( desiredHeight - extraHeight );
5190 naturalWidth = this.$clippable.prop( 'scrollWidth' );
5191 naturalHeight = this.$clippable.prop( 'scrollHeight' );
5192 clipWidth = allotedWidth < naturalWidth;
5193 clipHeight = allotedHeight < naturalHeight;
5194
5195 if ( clipWidth ) {
5196 // The order matters here. If overflow is not set first, Chrome displays bogus scrollbars.
5197 // See T157672.
5198 // Forcing a reflow is a smaller workaround than calling reconsiderScrollbars() for
5199 // this case.
5200 this.$clippable.css( 'overflowX', 'scroll' );
5201 // eslint-disable-next-line no-void
5202 void this.$clippable[ 0 ].offsetHeight; // Force reflow
5203 this.$clippable.css( {
5204 width: Math.max( 0, allotedWidth ),
5205 maxWidth: ''
5206 } );
5207 } else {
5208 this.$clippable.css( {
5209 overflowX: '',
5210 width: this.idealWidth || '',
5211 maxWidth: Math.max( 0, allotedWidth )
5212 } );
5213 }
5214 if ( clipHeight ) {
5215 // The order matters here. If overflow is not set first, Chrome displays bogus scrollbars.
5216 // See T157672.
5217 // Forcing a reflow is a smaller workaround than calling reconsiderScrollbars() for
5218 // this case.
5219 this.$clippable.css( 'overflowY', 'scroll' );
5220 // eslint-disable-next-line no-void
5221 void this.$clippable[ 0 ].offsetHeight; // Force reflow
5222 this.$clippable.css( {
5223 height: Math.max( 0, allotedHeight ),
5224 maxHeight: ''
5225 } );
5226 } else {
5227 this.$clippable.css( {
5228 overflowY: '',
5229 height: this.idealHeight || '',
5230 maxHeight: Math.max( 0, allotedHeight )
5231 } );
5232 }
5233
5234 // If we stopped clipping in at least one of the dimensions
5235 if ( ( this.clippedHorizontally && !clipWidth ) || ( this.clippedVertically && !clipHeight ) ) {
5236 OO.ui.Element.static.reconsiderScrollbars( this.$clippable[ 0 ] );
5237 }
5238
5239 this.clippedHorizontally = clipWidth;
5240 this.clippedVertically = clipHeight;
5241
5242 return this;
5243 };
5244
5245 /**
5246 * PopupWidget is a container for content. The popup is overlaid and positioned absolutely.
5247 * By default, each popup has an anchor that points toward its origin.
5248 * Please see the [OOUI documentation on MediaWiki.org] [1] for more information and examples.
5249 *
5250 * Unlike most widgets, PopupWidget is initially hidden and must be shown by calling #toggle.
5251 *
5252 * @example
5253 * // A PopupWidget.
5254 * var popup = new OO.ui.PopupWidget( {
5255 * $content: $( '<p>Hi there!</p>' ),
5256 * padded: true,
5257 * width: 300
5258 * } );
5259 *
5260 * $( document.body ).append( popup.$element );
5261 * // To display the popup, toggle the visibility to 'true'.
5262 * popup.toggle( true );
5263 *
5264 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Popups
5265 *
5266 * @class
5267 * @extends OO.ui.Widget
5268 * @mixins OO.ui.mixin.LabelElement
5269 * @mixins OO.ui.mixin.ClippableElement
5270 * @mixins OO.ui.mixin.FloatableElement
5271 *
5272 * @constructor
5273 * @param {Object} [config] Configuration options
5274 * @cfg {number|null} [width=320] Width of popup in pixels. Pass `null` to use automatic width.
5275 * @cfg {number|null} [height=null] Height of popup in pixels. Pass `null` to use automatic height.
5276 * @cfg {boolean} [anchor=true] Show anchor pointing to origin of popup
5277 * @cfg {string} [position='below'] Where to position the popup relative to $floatableContainer
5278 * 'above': Put popup above $floatableContainer; anchor points down to the horizontal center
5279 * of $floatableContainer
5280 * 'below': Put popup below $floatableContainer; anchor points up to the horizontal center
5281 * of $floatableContainer
5282 * 'before': Put popup to the left (LTR) / right (RTL) of $floatableContainer; anchor points
5283 * endwards (right/left) to the vertical center of $floatableContainer
5284 * 'after': Put popup to the right (LTR) / left (RTL) of $floatableContainer; anchor points
5285 * startwards (left/right) to the vertical center of $floatableContainer
5286 * @cfg {string} [align='center'] How to align the popup to $floatableContainer
5287 * 'forwards': If position is above/below, move the popup as far endwards (right in LTR, left in
5288 * RTL) as possible while still keeping the anchor within the popup; if position is before/after,
5289 * move the popup as far downwards as possible.
5290 * 'backwards': If position is above/below, move the popup as far startwards (left in LTR, right in
5291 * RTL) as possible while still keeping the anchor within the popup; if position is before/after,
5292 * move the popup as far upwards as possible.
5293 * 'center': Horizontally (if position is above/below) or vertically (before/after) align the
5294 * center of the popup with the center of $floatableContainer.
5295 * 'force-left': Alias for 'forwards' in LTR and 'backwards' in RTL
5296 * 'force-right': Alias for 'backwards' in RTL and 'forwards' in LTR
5297 * @cfg {boolean} [autoFlip=true] Whether to automatically switch the popup's position between
5298 * 'above' and 'below', or between 'before' and 'after', if there is not enough space in the
5299 * desired direction to display the popup without clipping
5300 * @cfg {jQuery} [$container] Constrain the popup to the boundaries of the specified container.
5301 * See the [OOUI docs on MediaWiki][3] for an example.
5302 * [3]: https://www.mediawiki.org/wiki/OOUI/Widgets/Popups#containerExample
5303 * @cfg {number} [containerPadding=10] Padding between the popup and its container, specified as a
5304 * number of pixels.
5305 * @cfg {jQuery} [$content] Content to append to the popup's body
5306 * @cfg {jQuery} [$footer] Content to append to the popup's footer
5307 * @cfg {boolean} [autoClose=false] Automatically close the popup when it loses focus.
5308 * @cfg {jQuery} [$autoCloseIgnore] Elements that will not close the popup when clicked.
5309 * This config option is only relevant if #autoClose is set to `true`. See the
5310 * [OOUI documentation on MediaWiki][2] for an example.
5311 * [2]: https://www.mediawiki.org/wiki/OOUI/Widgets/Popups#autocloseExample
5312 * @cfg {boolean} [head=false] Show a popup header that contains a #label (if specified) and close
5313 * button.
5314 * @cfg {boolean} [padded=false] Add padding to the popup's body
5315 */
5316 OO.ui.PopupWidget = function OoUiPopupWidget( config ) {
5317 // Configuration initialization
5318 config = config || {};
5319
5320 // Parent constructor
5321 OO.ui.PopupWidget.parent.call( this, config );
5322
5323 // Properties (must be set before ClippableElement constructor call)
5324 this.$body = $( '<div>' );
5325 this.$popup = $( '<div>' );
5326
5327 // Mixin constructors
5328 OO.ui.mixin.LabelElement.call( this, config );
5329 OO.ui.mixin.ClippableElement.call( this, $.extend( {
5330 $clippable: this.$body,
5331 $clippableContainer: this.$popup
5332 }, config ) );
5333 OO.ui.mixin.FloatableElement.call( this, config );
5334
5335 // Properties
5336 this.$anchor = $( '<div>' );
5337 // If undefined, will be computed lazily in computePosition()
5338 this.$container = config.$container;
5339 this.containerPadding = config.containerPadding !== undefined ? config.containerPadding : 10;
5340 this.autoClose = !!config.autoClose;
5341 this.transitionTimeout = null;
5342 this.anchored = false;
5343 this.onDocumentMouseDownHandler = this.onDocumentMouseDown.bind( this );
5344 this.onDocumentKeyDownHandler = this.onDocumentKeyDown.bind( this );
5345
5346 // Initialization
5347 this.setSize( config.width, config.height );
5348 this.toggleAnchor( config.anchor === undefined || config.anchor );
5349 this.setAlignment( config.align || 'center' );
5350 this.setPosition( config.position || 'below' );
5351 this.setAutoFlip( config.autoFlip === undefined || config.autoFlip );
5352 this.setAutoCloseIgnore( config.$autoCloseIgnore );
5353 this.$body.addClass( 'oo-ui-popupWidget-body' );
5354 this.$anchor.addClass( 'oo-ui-popupWidget-anchor' );
5355 this.$popup
5356 .addClass( 'oo-ui-popupWidget-popup' )
5357 .append( this.$body );
5358 this.$element
5359 .addClass( 'oo-ui-popupWidget' )
5360 .append( this.$popup, this.$anchor );
5361 // Move content, which was added to #$element by OO.ui.Widget, to the body
5362 // FIXME This is gross, we should use '$body' or something for the config
5363 if ( config.$content instanceof $ ) {
5364 this.$body.append( config.$content );
5365 }
5366
5367 if ( config.padded ) {
5368 this.$body.addClass( 'oo-ui-popupWidget-body-padded' );
5369 }
5370
5371 if ( config.head ) {
5372 this.closeButton = new OO.ui.ButtonWidget( {
5373 framed: false,
5374 icon: 'close'
5375 } );
5376 this.closeButton.connect( this, {
5377 click: 'onCloseButtonClick'
5378 } );
5379 this.$head = $( '<div>' )
5380 .addClass( 'oo-ui-popupWidget-head' )
5381 .append( this.$label, this.closeButton.$element );
5382 this.$popup.prepend( this.$head );
5383 }
5384
5385 if ( config.$footer ) {
5386 this.$footer = $( '<div>' )
5387 .addClass( 'oo-ui-popupWidget-footer' )
5388 .append( config.$footer );
5389 this.$popup.append( this.$footer );
5390 }
5391
5392 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
5393 // that reference properties not initialized at that time of parent class construction
5394 // TODO: Find a better way to handle post-constructor setup
5395 this.visible = false;
5396 this.$element.addClass( 'oo-ui-element-hidden' );
5397 };
5398
5399 /* Setup */
5400
5401 OO.inheritClass( OO.ui.PopupWidget, OO.ui.Widget );
5402 OO.mixinClass( OO.ui.PopupWidget, OO.ui.mixin.LabelElement );
5403 OO.mixinClass( OO.ui.PopupWidget, OO.ui.mixin.ClippableElement );
5404 OO.mixinClass( OO.ui.PopupWidget, OO.ui.mixin.FloatableElement );
5405
5406 /* Events */
5407
5408 /**
5409 * @event ready
5410 *
5411 * The popup is ready: it is visible and has been positioned and clipped.
5412 */
5413
5414 /* Methods */
5415
5416 /**
5417 * Handles document mouse down events.
5418 *
5419 * @private
5420 * @param {MouseEvent} e Mouse down event
5421 */
5422 OO.ui.PopupWidget.prototype.onDocumentMouseDown = function ( e ) {
5423 if (
5424 this.isVisible() &&
5425 !OO.ui.contains( this.$element.add( this.$autoCloseIgnore ).get(), e.target, true )
5426 ) {
5427 this.toggle( false );
5428 }
5429 };
5430
5431 /**
5432 * Bind document mouse down listener.
5433 *
5434 * @private
5435 */
5436 OO.ui.PopupWidget.prototype.bindDocumentMouseDownListener = function () {
5437 // Capture clicks outside popup
5438 this.getElementDocument().addEventListener( 'mousedown', this.onDocumentMouseDownHandler, true );
5439 // We add 'click' event because iOS safari needs to respond to this event.
5440 // We can't use 'touchstart' (as is usually the equivalent to 'mousedown') because
5441 // then it will trigger when scrolling. While iOS Safari has some reported behavior
5442 // of occasionally not emitting 'click' properly, that event seems to be the standard
5443 // that it should be emitting, so we add it to this and will operate the event handler
5444 // on whichever of these events was triggered first
5445 this.getElementDocument().addEventListener( 'click', this.onDocumentMouseDownHandler, true );
5446 };
5447
5448 /**
5449 * Handles close button click events.
5450 *
5451 * @private
5452 */
5453 OO.ui.PopupWidget.prototype.onCloseButtonClick = function () {
5454 if ( this.isVisible() ) {
5455 this.toggle( false );
5456 }
5457 };
5458
5459 /**
5460 * Unbind document mouse down listener.
5461 *
5462 * @private
5463 */
5464 OO.ui.PopupWidget.prototype.unbindDocumentMouseDownListener = function () {
5465 this.getElementDocument().removeEventListener( 'mousedown', this.onDocumentMouseDownHandler, true );
5466 this.getElementDocument().removeEventListener( 'click', this.onDocumentMouseDownHandler, true );
5467 };
5468
5469 /**
5470 * Handles document key down events.
5471 *
5472 * @private
5473 * @param {KeyboardEvent} e Key down event
5474 */
5475 OO.ui.PopupWidget.prototype.onDocumentKeyDown = function ( e ) {
5476 if (
5477 e.which === OO.ui.Keys.ESCAPE &&
5478 this.isVisible()
5479 ) {
5480 this.toggle( false );
5481 e.preventDefault();
5482 e.stopPropagation();
5483 }
5484 };
5485
5486 /**
5487 * Bind document key down listener.
5488 *
5489 * @private
5490 */
5491 OO.ui.PopupWidget.prototype.bindDocumentKeyDownListener = function () {
5492 this.getElementDocument().addEventListener( 'keydown', this.onDocumentKeyDownHandler, true );
5493 };
5494
5495 /**
5496 * Unbind document key down listener.
5497 *
5498 * @private
5499 */
5500 OO.ui.PopupWidget.prototype.unbindDocumentKeyDownListener = function () {
5501 this.getElementDocument().removeEventListener( 'keydown', this.onDocumentKeyDownHandler, true );
5502 };
5503
5504 /**
5505 * Show, hide, or toggle the visibility of the anchor.
5506 *
5507 * @param {boolean} [show] Show anchor, omit to toggle
5508 */
5509 OO.ui.PopupWidget.prototype.toggleAnchor = function ( show ) {
5510 show = show === undefined ? !this.anchored : !!show;
5511
5512 if ( this.anchored !== show ) {
5513 if ( show ) {
5514 this.$element.addClass( 'oo-ui-popupWidget-anchored' );
5515 this.$element.addClass( 'oo-ui-popupWidget-anchored-' + this.anchorEdge );
5516 } else {
5517 this.$element.removeClass( 'oo-ui-popupWidget-anchored' );
5518 this.$element.removeClass( 'oo-ui-popupWidget-anchored-' + this.anchorEdge );
5519 }
5520 this.anchored = show;
5521 }
5522 };
5523
5524 /**
5525 * Change which edge the anchor appears on.
5526 *
5527 * @param {string} edge 'top', 'bottom', 'start' or 'end'
5528 */
5529 OO.ui.PopupWidget.prototype.setAnchorEdge = function ( edge ) {
5530 if ( [ 'top', 'bottom', 'start', 'end' ].indexOf( edge ) === -1 ) {
5531 throw new Error( 'Invalid value for edge: ' + edge );
5532 }
5533 if ( this.anchorEdge !== null ) {
5534 this.$element.removeClass( 'oo-ui-popupWidget-anchored-' + this.anchorEdge );
5535 }
5536 this.anchorEdge = edge;
5537 if ( this.anchored ) {
5538 this.$element.addClass( 'oo-ui-popupWidget-anchored-' + edge );
5539 }
5540 };
5541
5542 /**
5543 * Check if the anchor is visible.
5544 *
5545 * @return {boolean} Anchor is visible
5546 */
5547 OO.ui.PopupWidget.prototype.hasAnchor = function () {
5548 return this.anchored;
5549 };
5550
5551 /**
5552 * Toggle visibility of the popup. The popup is initially hidden and must be shown by calling
5553 * `.toggle( true )` after its #$element is attached to the DOM.
5554 *
5555 * Do not show the popup while it is not attached to the DOM. The calculations required to display
5556 * it in the right place and with the right dimensions only work correctly while it is attached.
5557 * Side-effects may include broken interface and exceptions being thrown. This wasn't always
5558 * strictly enforced, so currently it only generates a warning in the browser console.
5559 *
5560 * @fires ready
5561 * @inheritdoc
5562 */
5563 OO.ui.PopupWidget.prototype.toggle = function ( show ) {
5564 var change, normalHeight, oppositeHeight, normalWidth, oppositeWidth;
5565 show = show === undefined ? !this.isVisible() : !!show;
5566
5567 change = show !== this.isVisible();
5568
5569 if ( show && !this.warnedUnattached && !this.isElementAttached() ) {
5570 OO.ui.warnDeprecation( 'PopupWidget#toggle: Before calling this method, the popup must be attached to the DOM.' );
5571 this.warnedUnattached = true;
5572 }
5573 if ( show && !this.$floatableContainer && this.isElementAttached() ) {
5574 // Fall back to the parent node if the floatableContainer is not set
5575 this.setFloatableContainer( this.$element.parent() );
5576 }
5577
5578 if ( change && show && this.autoFlip ) {
5579 // Reset auto-flipping before showing the popup again. It's possible we no longer need to
5580 // flip (e.g. if the user scrolled).
5581 this.isAutoFlipped = false;
5582 }
5583
5584 // Parent method
5585 OO.ui.PopupWidget.parent.prototype.toggle.call( this, show );
5586
5587 if ( change ) {
5588 this.togglePositioning( show && !!this.$floatableContainer );
5589
5590 if ( show ) {
5591 if ( this.autoClose ) {
5592 this.bindDocumentMouseDownListener();
5593 this.bindDocumentKeyDownListener();
5594 }
5595 this.updateDimensions();
5596 this.toggleClipping( true );
5597
5598 if ( this.autoFlip ) {
5599 if ( this.popupPosition === 'above' || this.popupPosition === 'below' ) {
5600 if ( this.isClippedVertically() || this.isFloatableOutOfView() ) {
5601 // If opening the popup in the normal direction causes it to be clipped,
5602 // open in the opposite one instead
5603 normalHeight = this.$element.height();
5604 this.isAutoFlipped = !this.isAutoFlipped;
5605 this.position();
5606 if ( this.isClippedVertically() || this.isFloatableOutOfView() ) {
5607 // If that also causes it to be clipped, open in whichever direction
5608 // we have more space
5609 oppositeHeight = this.$element.height();
5610 if ( oppositeHeight < normalHeight ) {
5611 this.isAutoFlipped = !this.isAutoFlipped;
5612 this.position();
5613 }
5614 }
5615 }
5616 }
5617 if ( this.popupPosition === 'before' || this.popupPosition === 'after' ) {
5618 if ( this.isClippedHorizontally() || this.isFloatableOutOfView() ) {
5619 // If opening the popup in the normal direction causes it to be clipped,
5620 // open in the opposite one instead
5621 normalWidth = this.$element.width();
5622 this.isAutoFlipped = !this.isAutoFlipped;
5623 // Due to T180173 horizontally clipped PopupWidgets have messed up
5624 // dimensions, which causes positioning to be off. Toggle clipping back and
5625 // forth to work around.
5626 this.toggleClipping( false );
5627 this.position();
5628 this.toggleClipping( true );
5629 if ( this.isClippedHorizontally() || this.isFloatableOutOfView() ) {
5630 // If that also causes it to be clipped, open in whichever direction
5631 // we have more space
5632 oppositeWidth = this.$element.width();
5633 if ( oppositeWidth < normalWidth ) {
5634 this.isAutoFlipped = !this.isAutoFlipped;
5635 // Due to T180173, horizontally clipped PopupWidgets have messed up
5636 // dimensions, which causes positioning to be off. Toggle clipping
5637 // back and forth to work around.
5638 this.toggleClipping( false );
5639 this.position();
5640 this.toggleClipping( true );
5641 }
5642 }
5643 }
5644 }
5645 }
5646
5647 this.emit( 'ready' );
5648 } else {
5649 this.toggleClipping( false );
5650 if ( this.autoClose ) {
5651 this.unbindDocumentMouseDownListener();
5652 this.unbindDocumentKeyDownListener();
5653 }
5654 }
5655 }
5656
5657 return this;
5658 };
5659
5660 /**
5661 * Set the size of the popup.
5662 *
5663 * Changing the size may also change the popup's position depending on the alignment.
5664 *
5665 * @param {number|null} [width=320] Width in pixels. Pass `null` to use automatic width.
5666 * @param {number|null} [height=null] Height in pixels. Pass `null` to use automatic height.
5667 * @param {boolean} [transition=false] Use a smooth transition
5668 * @chainable
5669 */
5670 OO.ui.PopupWidget.prototype.setSize = function ( width, height, transition ) {
5671 this.width = width !== undefined ? width : 320;
5672 this.height = height !== undefined ? height : null;
5673 if ( this.isVisible() ) {
5674 this.updateDimensions( transition );
5675 }
5676 };
5677
5678 /**
5679 * Update the size and position.
5680 *
5681 * Only use this to keep the popup properly anchored. Use #setSize to change the size, and this will
5682 * be called automatically.
5683 *
5684 * @param {boolean} [transition=false] Use a smooth transition
5685 * @chainable
5686 */
5687 OO.ui.PopupWidget.prototype.updateDimensions = function ( transition ) {
5688 var widget = this;
5689
5690 // Prevent transition from being interrupted
5691 clearTimeout( this.transitionTimeout );
5692 if ( transition ) {
5693 // Enable transition
5694 this.$element.addClass( 'oo-ui-popupWidget-transitioning' );
5695 }
5696
5697 this.position();
5698
5699 if ( transition ) {
5700 // Prevent transitioning after transition is complete
5701 this.transitionTimeout = setTimeout( function () {
5702 widget.$element.removeClass( 'oo-ui-popupWidget-transitioning' );
5703 }, 200 );
5704 } else {
5705 // Prevent transitioning immediately
5706 this.$element.removeClass( 'oo-ui-popupWidget-transitioning' );
5707 }
5708 };
5709
5710 /**
5711 * @inheritdoc
5712 */
5713 OO.ui.PopupWidget.prototype.computePosition = function () {
5714 var direction, align, vertical, start, end, near, far, sizeProp, popupSize, anchorSize,
5715 anchorPos, anchorOffset, anchorMargin, parentPosition, positionProp, positionAdjustment,
5716 floatablePos, offsetParentPos, containerPos, popupPosition, viewportSpacing,
5717 popupPos = {},
5718 anchorCss = { left: '', right: '', top: '', bottom: '' },
5719 popupPositionOppositeMap = {
5720 above: 'below',
5721 below: 'above',
5722 before: 'after',
5723 after: 'before'
5724 },
5725 alignMap = {
5726 ltr: {
5727 'force-left': 'backwards',
5728 'force-right': 'forwards'
5729 },
5730 rtl: {
5731 'force-left': 'forwards',
5732 'force-right': 'backwards'
5733 }
5734 },
5735 anchorEdgeMap = {
5736 above: 'bottom',
5737 below: 'top',
5738 before: 'end',
5739 after: 'start'
5740 },
5741 hPosMap = {
5742 forwards: 'start',
5743 center: 'center',
5744 backwards: this.anchored ? 'before' : 'end'
5745 },
5746 vPosMap = {
5747 forwards: 'top',
5748 center: 'center',
5749 backwards: 'bottom'
5750 };
5751
5752 if ( !this.$container ) {
5753 // Lazy-initialize $container if not specified in constructor
5754 this.$container = $( this.getClosestScrollableElementContainer() );
5755 }
5756 direction = this.$container.css( 'direction' );
5757
5758 // Set height and width before we do anything else, since it might cause our measurements
5759 // to change (e.g. due to scrollbars appearing or disappearing), and it also affects centering
5760 this.$popup.css( {
5761 width: this.width !== null ? this.width : 'auto',
5762 height: this.height !== null ? this.height : 'auto'
5763 } );
5764
5765 align = alignMap[ direction ][ this.align ] || this.align;
5766 popupPosition = this.popupPosition;
5767 if ( this.isAutoFlipped ) {
5768 popupPosition = popupPositionOppositeMap[ popupPosition ];
5769 }
5770
5771 // If the popup is positioned before or after, then the anchor positioning is vertical,
5772 // otherwise horizontal
5773 vertical = popupPosition === 'before' || popupPosition === 'after';
5774 start = vertical ? 'top' : ( direction === 'rtl' ? 'right' : 'left' );
5775 end = vertical ? 'bottom' : ( direction === 'rtl' ? 'left' : 'right' );
5776 near = vertical ? 'top' : 'left';
5777 far = vertical ? 'bottom' : 'right';
5778 sizeProp = vertical ? 'Height' : 'Width';
5779 popupSize = vertical ?
5780 ( this.height || this.$popup.height() ) :
5781 ( this.width || this.$popup.width() );
5782
5783 this.setAnchorEdge( anchorEdgeMap[ popupPosition ] );
5784 this.horizontalPosition = vertical ? popupPosition : hPosMap[ align ];
5785 this.verticalPosition = vertical ? vPosMap[ align ] : popupPosition;
5786
5787 // Parent method
5788 parentPosition = OO.ui.mixin.FloatableElement.prototype.computePosition.call( this );
5789 // Find out which property FloatableElement used for positioning, and adjust that value
5790 positionProp = vertical ?
5791 ( parentPosition.top !== '' ? 'top' : 'bottom' ) :
5792 ( parentPosition.left !== '' ? 'left' : 'right' );
5793
5794 // Figure out where the near and far edges of the popup and $floatableContainer are
5795 floatablePos = this.$floatableContainer.offset();
5796 floatablePos[ far ] = floatablePos[ near ] + this.$floatableContainer[ 'outer' + sizeProp ]();
5797 // Measure where the offsetParent is and compute our position based on that and parentPosition
5798 offsetParentPos = this.$element.offsetParent()[ 0 ] === document.documentElement ?
5799 { top: 0, left: 0 } :
5800 this.$element.offsetParent().offset();
5801
5802 if ( positionProp === near ) {
5803 popupPos[ near ] = offsetParentPos[ near ] + parentPosition[ near ];
5804 popupPos[ far ] = popupPos[ near ] + popupSize;
5805 } else {
5806 popupPos[ far ] = offsetParentPos[ near ] +
5807 this.$element.offsetParent()[ 'inner' + sizeProp ]() - parentPosition[ far ];
5808 popupPos[ near ] = popupPos[ far ] - popupSize;
5809 }
5810
5811 if ( this.anchored ) {
5812 // Position the anchor (which is positioned relative to the popup) to point to
5813 // $floatableContainer
5814 anchorPos = ( floatablePos[ start ] + floatablePos[ end ] ) / 2;
5815 anchorOffset = ( start === far ? -1 : 1 ) * ( anchorPos - popupPos[ start ] );
5816
5817 // If the anchor is less than 2*anchorSize from either edge, move the popup to make more
5818 // space this.$anchor.width()/height() returns 0 because of the CSS trickery we use, so use
5819 // scrollWidth/Height
5820 anchorSize = this.$anchor[ 0 ][ 'scroll' + sizeProp ];
5821 anchorMargin = parseFloat( this.$anchor.css( 'margin-' + start ) );
5822 if ( anchorOffset + anchorMargin < 2 * anchorSize ) {
5823 // Not enough space for the anchor on the start side; pull the popup startwards
5824 positionAdjustment = ( positionProp === start ? -1 : 1 ) *
5825 ( 2 * anchorSize - ( anchorOffset + anchorMargin ) );
5826 } else if ( anchorOffset + anchorMargin > popupSize - 2 * anchorSize ) {
5827 // Not enough space for the anchor on the end side; pull the popup endwards
5828 positionAdjustment = ( positionProp === end ? -1 : 1 ) *
5829 ( anchorOffset + anchorMargin - ( popupSize - 2 * anchorSize ) );
5830 } else {
5831 positionAdjustment = 0;
5832 }
5833 } else {
5834 positionAdjustment = 0;
5835 }
5836
5837 // Check if the popup will go beyond the edge of this.$container
5838 containerPos = this.$container[ 0 ] === document.documentElement ?
5839 { top: 0, left: 0 } :
5840 this.$container.offset();
5841 containerPos[ far ] = containerPos[ near ] + this.$container[ 'inner' + sizeProp ]();
5842 if ( this.$container[ 0 ] === document.documentElement ) {
5843 viewportSpacing = OO.ui.getViewportSpacing();
5844 containerPos[ near ] += viewportSpacing[ near ];
5845 containerPos[ far ] -= viewportSpacing[ far ];
5846 }
5847 // Take into account how much the popup will move because of the adjustments we're going to make
5848 popupPos[ near ] += ( positionProp === near ? 1 : -1 ) * positionAdjustment;
5849 popupPos[ far ] += ( positionProp === near ? 1 : -1 ) * positionAdjustment;
5850 if ( containerPos[ near ] + this.containerPadding > popupPos[ near ] ) {
5851 // Popup goes beyond the near (left/top) edge, move it to the right/bottom
5852 positionAdjustment += ( positionProp === near ? 1 : -1 ) *
5853 ( containerPos[ near ] + this.containerPadding - popupPos[ near ] );
5854 } else if ( containerPos[ far ] - this.containerPadding < popupPos[ far ] ) {
5855 // Popup goes beyond the far (right/bottom) edge, move it to the left/top
5856 positionAdjustment += ( positionProp === far ? 1 : -1 ) *
5857 ( popupPos[ far ] - ( containerPos[ far ] - this.containerPadding ) );
5858 }
5859
5860 if ( this.anchored ) {
5861 // Adjust anchorOffset for positionAdjustment
5862 anchorOffset += ( positionProp === start ? -1 : 1 ) * positionAdjustment;
5863
5864 // Position the anchor
5865 anchorCss[ start ] = anchorOffset;
5866 this.$anchor.css( anchorCss );
5867 }
5868
5869 // Move the popup if needed
5870 parentPosition[ positionProp ] += positionAdjustment;
5871
5872 return parentPosition;
5873 };
5874
5875 /**
5876 * Set popup alignment
5877 *
5878 * @param {string} [align=center] Alignment of the popup, `center`, `force-left`, `force-right`,
5879 * `backwards` or `forwards`.
5880 */
5881 OO.ui.PopupWidget.prototype.setAlignment = function ( align ) {
5882 // Validate alignment
5883 if ( [ 'force-left', 'force-right', 'backwards', 'forwards', 'center' ].indexOf( align ) > -1 ) {
5884 this.align = align;
5885 } else {
5886 this.align = 'center';
5887 }
5888 this.position();
5889 };
5890
5891 /**
5892 * Get popup alignment
5893 *
5894 * @return {string} Alignment of the popup, `center`, `force-left`, `force-right`,
5895 * `backwards` or `forwards`.
5896 */
5897 OO.ui.PopupWidget.prototype.getAlignment = function () {
5898 return this.align;
5899 };
5900
5901 /**
5902 * Change the positioning of the popup.
5903 *
5904 * @param {string} position 'above', 'below', 'before' or 'after'
5905 */
5906 OO.ui.PopupWidget.prototype.setPosition = function ( position ) {
5907 if ( [ 'above', 'below', 'before', 'after' ].indexOf( position ) === -1 ) {
5908 position = 'below';
5909 }
5910 this.popupPosition = position;
5911 this.position();
5912 };
5913
5914 /**
5915 * Get popup positioning.
5916 *
5917 * @return {string} 'above', 'below', 'before' or 'after'
5918 */
5919 OO.ui.PopupWidget.prototype.getPosition = function () {
5920 return this.popupPosition;
5921 };
5922
5923 /**
5924 * Set popup auto-flipping.
5925 *
5926 * @param {boolean} autoFlip Whether to automatically switch the popup's position between
5927 * 'above' and 'below', or between 'before' and 'after', if there is not enough space in the
5928 * desired direction to display the popup without clipping
5929 */
5930 OO.ui.PopupWidget.prototype.setAutoFlip = function ( autoFlip ) {
5931 autoFlip = !!autoFlip;
5932
5933 if ( this.autoFlip !== autoFlip ) {
5934 this.autoFlip = autoFlip;
5935 }
5936 };
5937
5938 /**
5939 * Set which elements will not close the popup when clicked.
5940 *
5941 * For auto-closing popups, clicks on these elements will not cause the popup to auto-close.
5942 *
5943 * @param {jQuery} $autoCloseIgnore Elements to ignore for auto-closing
5944 */
5945 OO.ui.PopupWidget.prototype.setAutoCloseIgnore = function ( $autoCloseIgnore ) {
5946 this.$autoCloseIgnore = $autoCloseIgnore;
5947 };
5948
5949 /**
5950 * Get an ID of the body element, this can be used as the
5951 * `aria-describedby` attribute for an input field.
5952 *
5953 * @return {string} The ID of the body element
5954 */
5955 OO.ui.PopupWidget.prototype.getBodyId = function () {
5956 var id = this.$body.attr( 'id' );
5957 if ( id === undefined ) {
5958 id = OO.ui.generateElementId();
5959 this.$body.attr( 'id', id );
5960 }
5961 return id;
5962 };
5963
5964 /**
5965 * PopupElement is mixed into other classes to generate a {@link OO.ui.PopupWidget popup widget}.
5966 * A popup is a container for content. It is overlaid and positioned absolutely. By default, each
5967 * popup has an anchor, which is an arrow-like protrusion that points toward the popup’s origin.
5968 * See {@link OO.ui.PopupWidget PopupWidget} for an example.
5969 *
5970 * @abstract
5971 * @class
5972 *
5973 * @constructor
5974 * @param {Object} [config] Configuration options
5975 * @cfg {Object} [popup] Configuration to pass to popup
5976 * @cfg {boolean} [popup.autoClose=true] Popup auto-closes when it loses focus
5977 */
5978 OO.ui.mixin.PopupElement = function OoUiMixinPopupElement( config ) {
5979 // Configuration initialization
5980 config = config || {};
5981
5982 // Properties
5983 this.popup = new OO.ui.PopupWidget( $.extend(
5984 {
5985 autoClose: true,
5986 $floatableContainer: this.$element
5987 },
5988 config.popup,
5989 {
5990 $autoCloseIgnore: this.$element.add( config.popup && config.popup.$autoCloseIgnore )
5991 }
5992 ) );
5993 };
5994
5995 /* Methods */
5996
5997 /**
5998 * Get popup.
5999 *
6000 * @return {OO.ui.PopupWidget} Popup widget
6001 */
6002 OO.ui.mixin.PopupElement.prototype.getPopup = function () {
6003 return this.popup;
6004 };
6005
6006 /**
6007 * PopupButtonWidgets toggle the visibility of a contained {@link OO.ui.PopupWidget PopupWidget},
6008 * which is used to display additional information or options.
6009 *
6010 * @example
6011 * // A PopupButtonWidget.
6012 * var popupButton = new OO.ui.PopupButtonWidget( {
6013 * label: 'Popup button with options',
6014 * icon: 'menu',
6015 * popup: {
6016 * $content: $( '<p>Additional options here.</p>' ),
6017 * padded: true,
6018 * align: 'force-left'
6019 * }
6020 * } );
6021 * // Append the button to the DOM.
6022 * $( document.body ).append( popupButton.$element );
6023 *
6024 * @class
6025 * @extends OO.ui.ButtonWidget
6026 * @mixins OO.ui.mixin.PopupElement
6027 *
6028 * @constructor
6029 * @param {Object} [config] Configuration options
6030 * @cfg {jQuery} [$overlay] Render the popup into a separate layer. This configuration is useful
6031 * in cases where the expanded popup is larger than its containing `<div>`. The specified overlay
6032 * layer is usually on top of the containing `<div>` and has a larger area. By default, the popup
6033 * uses relative positioning.
6034 * See <https://www.mediawiki.org/wiki/OOUI/Concepts#Overlays>.
6035 */
6036 OO.ui.PopupButtonWidget = function OoUiPopupButtonWidget( config ) {
6037 // Configuration initialization
6038 config = config || {};
6039
6040 // Parent constructor
6041 OO.ui.PopupButtonWidget.parent.call( this, config );
6042
6043 // Mixin constructors
6044 OO.ui.mixin.PopupElement.call( this, config );
6045
6046 // Properties
6047 this.$overlay = ( config.$overlay === true ?
6048 OO.ui.getDefaultOverlay() : config.$overlay ) || this.$element;
6049
6050 // Events
6051 this.connect( this, {
6052 click: 'onAction'
6053 } );
6054
6055 // Initialization
6056 this.$element.addClass( 'oo-ui-popupButtonWidget' );
6057 this.popup.$element
6058 .addClass( 'oo-ui-popupButtonWidget-popup' )
6059 .toggleClass( 'oo-ui-popupButtonWidget-framed-popup', this.isFramed() )
6060 .toggleClass( 'oo-ui-popupButtonWidget-frameless-popup', !this.isFramed() );
6061 this.$overlay.append( this.popup.$element );
6062 };
6063
6064 /* Setup */
6065
6066 OO.inheritClass( OO.ui.PopupButtonWidget, OO.ui.ButtonWidget );
6067 OO.mixinClass( OO.ui.PopupButtonWidget, OO.ui.mixin.PopupElement );
6068
6069 /* Methods */
6070
6071 /**
6072 * Handle the button action being triggered.
6073 *
6074 * @private
6075 */
6076 OO.ui.PopupButtonWidget.prototype.onAction = function () {
6077 this.popup.toggle();
6078 };
6079
6080 /**
6081 * Mixin for OO.ui.Widget subclasses to provide OO.ui.mixin.GroupElement.
6082 *
6083 * Use together with OO.ui.mixin.ItemWidget to make disabled state inheritable.
6084 *
6085 * @private
6086 * @abstract
6087 * @class
6088 * @mixins OO.ui.mixin.GroupElement
6089 *
6090 * @constructor
6091 * @param {Object} [config] Configuration options
6092 */
6093 OO.ui.mixin.GroupWidget = function OoUiMixinGroupWidget( config ) {
6094 // Mixin constructors
6095 OO.ui.mixin.GroupElement.call( this, config );
6096 };
6097
6098 /* Setup */
6099
6100 OO.mixinClass( OO.ui.mixin.GroupWidget, OO.ui.mixin.GroupElement );
6101
6102 /* Methods */
6103
6104 /**
6105 * Set the disabled state of the widget.
6106 *
6107 * This will also update the disabled state of child widgets.
6108 *
6109 * @param {boolean} disabled Disable widget
6110 * @chainable
6111 * @return {OO.ui.Widget} The widget, for chaining
6112 */
6113 OO.ui.mixin.GroupWidget.prototype.setDisabled = function ( disabled ) {
6114 var i, len;
6115
6116 // Parent method
6117 // Note: Calling #setDisabled this way assumes this is mixed into an OO.ui.Widget
6118 OO.ui.Widget.prototype.setDisabled.call( this, disabled );
6119
6120 // During construction, #setDisabled is called before the OO.ui.mixin.GroupElement constructor
6121 if ( this.items ) {
6122 for ( i = 0, len = this.items.length; i < len; i++ ) {
6123 this.items[ i ].updateDisabled();
6124 }
6125 }
6126
6127 return this;
6128 };
6129
6130 /**
6131 * Mixin for widgets used as items in widgets that mix in OO.ui.mixin.GroupWidget.
6132 *
6133 * Item widgets have a reference to a OO.ui.mixin.GroupWidget while they are attached to the group.
6134 * This allows bidirectional communication.
6135 *
6136 * Use together with OO.ui.mixin.GroupWidget to make disabled state inheritable.
6137 *
6138 * @private
6139 * @abstract
6140 * @class
6141 *
6142 * @constructor
6143 */
6144 OO.ui.mixin.ItemWidget = function OoUiMixinItemWidget() {
6145 //
6146 };
6147
6148 /* Methods */
6149
6150 /**
6151 * Check if widget is disabled.
6152 *
6153 * Checks parent if present, making disabled state inheritable.
6154 *
6155 * @return {boolean} Widget is disabled
6156 */
6157 OO.ui.mixin.ItemWidget.prototype.isDisabled = function () {
6158 return this.disabled ||
6159 ( this.elementGroup instanceof OO.ui.Widget && this.elementGroup.isDisabled() );
6160 };
6161
6162 /**
6163 * Set group element is in.
6164 *
6165 * @param {OO.ui.mixin.GroupElement|null} group Group element, null if none
6166 * @chainable
6167 * @return {OO.ui.Widget} The widget, for chaining
6168 */
6169 OO.ui.mixin.ItemWidget.prototype.setElementGroup = function ( group ) {
6170 // Parent method
6171 // Note: Calling #setElementGroup this way assumes this is mixed into an OO.ui.Element
6172 OO.ui.Element.prototype.setElementGroup.call( this, group );
6173
6174 // Initialize item disabled states
6175 this.updateDisabled();
6176
6177 return this;
6178 };
6179
6180 /**
6181 * OptionWidgets are special elements that can be selected and configured with data. The
6182 * data is often unique for each option, but it does not have to be. OptionWidgets are used
6183 * with OO.ui.SelectWidget to create a selection of mutually exclusive options. For more information
6184 * and examples, please see the [OOUI documentation on MediaWiki][1].
6185 *
6186 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options
6187 *
6188 * @class
6189 * @extends OO.ui.Widget
6190 * @mixins OO.ui.mixin.ItemWidget
6191 * @mixins OO.ui.mixin.LabelElement
6192 * @mixins OO.ui.mixin.FlaggedElement
6193 * @mixins OO.ui.mixin.AccessKeyedElement
6194 * @mixins OO.ui.mixin.TitledElement
6195 *
6196 * @constructor
6197 * @param {Object} [config] Configuration options
6198 */
6199 OO.ui.OptionWidget = function OoUiOptionWidget( config ) {
6200 // Configuration initialization
6201 config = config || {};
6202
6203 // Parent constructor
6204 OO.ui.OptionWidget.parent.call( this, config );
6205
6206 // Mixin constructors
6207 OO.ui.mixin.ItemWidget.call( this );
6208 OO.ui.mixin.LabelElement.call( this, config );
6209 OO.ui.mixin.FlaggedElement.call( this, config );
6210 OO.ui.mixin.AccessKeyedElement.call( this, config );
6211 OO.ui.mixin.TitledElement.call( this, config );
6212
6213 // Properties
6214 this.highlighted = false;
6215 this.pressed = false;
6216 this.setSelected( !!config.selected );
6217
6218 // Initialization
6219 this.$element
6220 .data( 'oo-ui-optionWidget', this )
6221 // Allow programmatic focussing (and by access key), but not tabbing
6222 .attr( 'tabindex', '-1' )
6223 .attr( 'role', 'option' )
6224 .addClass( 'oo-ui-optionWidget' )
6225 .append( this.$label );
6226 };
6227
6228 /* Setup */
6229
6230 OO.inheritClass( OO.ui.OptionWidget, OO.ui.Widget );
6231 OO.mixinClass( OO.ui.OptionWidget, OO.ui.mixin.ItemWidget );
6232 OO.mixinClass( OO.ui.OptionWidget, OO.ui.mixin.LabelElement );
6233 OO.mixinClass( OO.ui.OptionWidget, OO.ui.mixin.FlaggedElement );
6234 OO.mixinClass( OO.ui.OptionWidget, OO.ui.mixin.AccessKeyedElement );
6235 OO.mixinClass( OO.ui.OptionWidget, OO.ui.mixin.TitledElement );
6236
6237 /* Static Properties */
6238
6239 /**
6240 * Whether this option can be selected. See #setSelected.
6241 *
6242 * @static
6243 * @inheritable
6244 * @property {boolean}
6245 */
6246 OO.ui.OptionWidget.static.selectable = true;
6247
6248 /**
6249 * Whether this option can be highlighted. See #setHighlighted.
6250 *
6251 * @static
6252 * @inheritable
6253 * @property {boolean}
6254 */
6255 OO.ui.OptionWidget.static.highlightable = true;
6256
6257 /**
6258 * Whether this option can be pressed. See #setPressed.
6259 *
6260 * @static
6261 * @inheritable
6262 * @property {boolean}
6263 */
6264 OO.ui.OptionWidget.static.pressable = true;
6265
6266 /**
6267 * Whether this option will be scrolled into view when it is selected.
6268 *
6269 * @static
6270 * @inheritable
6271 * @property {boolean}
6272 */
6273 OO.ui.OptionWidget.static.scrollIntoViewOnSelect = false;
6274
6275 /* Methods */
6276
6277 /**
6278 * Check if the option can be selected.
6279 *
6280 * @return {boolean} Item is selectable
6281 */
6282 OO.ui.OptionWidget.prototype.isSelectable = function () {
6283 return this.constructor.static.selectable && !this.disabled && this.isVisible();
6284 };
6285
6286 /**
6287 * Check if the option can be highlighted. A highlight indicates that the option
6288 * may be selected when a user presses Enter key or clicks. Disabled items cannot
6289 * be highlighted.
6290 *
6291 * @return {boolean} Item is highlightable
6292 */
6293 OO.ui.OptionWidget.prototype.isHighlightable = function () {
6294 return this.constructor.static.highlightable && !this.disabled && this.isVisible();
6295 };
6296
6297 /**
6298 * Check if the option can be pressed. The pressed state occurs when a user mouses
6299 * down on an item, but has not yet let go of the mouse.
6300 *
6301 * @return {boolean} Item is pressable
6302 */
6303 OO.ui.OptionWidget.prototype.isPressable = function () {
6304 return this.constructor.static.pressable && !this.disabled && this.isVisible();
6305 };
6306
6307 /**
6308 * Check if the option is selected.
6309 *
6310 * @return {boolean} Item is selected
6311 */
6312 OO.ui.OptionWidget.prototype.isSelected = function () {
6313 return this.selected;
6314 };
6315
6316 /**
6317 * Check if the option is highlighted. A highlight indicates that the
6318 * item may be selected when a user presses Enter key or clicks.
6319 *
6320 * @return {boolean} Item is highlighted
6321 */
6322 OO.ui.OptionWidget.prototype.isHighlighted = function () {
6323 return this.highlighted;
6324 };
6325
6326 /**
6327 * Check if the option is pressed. The pressed state occurs when a user mouses
6328 * down on an item, but has not yet let go of the mouse. The item may appear
6329 * selected, but it will not be selected until the user releases the mouse.
6330 *
6331 * @return {boolean} Item is pressed
6332 */
6333 OO.ui.OptionWidget.prototype.isPressed = function () {
6334 return this.pressed;
6335 };
6336
6337 /**
6338 * Set the option’s selected state. In general, all modifications to the selection
6339 * should be handled by the SelectWidget’s
6340 * {@link OO.ui.SelectWidget#selectItem selectItem( [item] )} method instead of this method.
6341 *
6342 * @param {boolean} [state=false] Select option
6343 * @chainable
6344 * @return {OO.ui.Widget} The widget, for chaining
6345 */
6346 OO.ui.OptionWidget.prototype.setSelected = function ( state ) {
6347 if ( this.constructor.static.selectable ) {
6348 this.selected = !!state;
6349 this.$element
6350 .toggleClass( 'oo-ui-optionWidget-selected', state )
6351 .attr( 'aria-selected', state.toString() );
6352 if ( state && this.constructor.static.scrollIntoViewOnSelect ) {
6353 this.scrollElementIntoView();
6354 }
6355 this.updateThemeClasses();
6356 }
6357 return this;
6358 };
6359
6360 /**
6361 * Set the option’s highlighted state. In general, all programmatic
6362 * modifications to the highlight should be handled by the
6363 * SelectWidget’s {@link OO.ui.SelectWidget#highlightItem highlightItem( [item] )}
6364 * method instead of this method.
6365 *
6366 * @param {boolean} [state=false] Highlight option
6367 * @chainable
6368 * @return {OO.ui.Widget} The widget, for chaining
6369 */
6370 OO.ui.OptionWidget.prototype.setHighlighted = function ( state ) {
6371 if ( this.constructor.static.highlightable ) {
6372 this.highlighted = !!state;
6373 this.$element.toggleClass( 'oo-ui-optionWidget-highlighted', state );
6374 this.updateThemeClasses();
6375 }
6376 return this;
6377 };
6378
6379 /**
6380 * Set the option’s pressed state. In general, all
6381 * programmatic modifications to the pressed state should be handled by the
6382 * SelectWidget’s {@link OO.ui.SelectWidget#pressItem pressItem( [item] )}
6383 * method instead of this method.
6384 *
6385 * @param {boolean} [state=false] Press option
6386 * @chainable
6387 * @return {OO.ui.Widget} The widget, for chaining
6388 */
6389 OO.ui.OptionWidget.prototype.setPressed = function ( state ) {
6390 if ( this.constructor.static.pressable ) {
6391 this.pressed = !!state;
6392 this.$element.toggleClass( 'oo-ui-optionWidget-pressed', state );
6393 this.updateThemeClasses();
6394 }
6395 return this;
6396 };
6397
6398 /**
6399 * Get text to match search strings against.
6400 *
6401 * The default implementation returns the label text, but subclasses
6402 * can override this to provide more complex behavior.
6403 *
6404 * @return {string|boolean} String to match search string against
6405 */
6406 OO.ui.OptionWidget.prototype.getMatchText = function () {
6407 var label = this.getLabel();
6408 return typeof label === 'string' ? label : this.$label.text();
6409 };
6410
6411 /**
6412 * A SelectWidget is of a generic selection of options. The OOUI library contains several types of
6413 * select widgets, including {@link OO.ui.ButtonSelectWidget button selects},
6414 * {@link OO.ui.RadioSelectWidget radio selects}, and {@link OO.ui.MenuSelectWidget
6415 * menu selects}.
6416 *
6417 * This class should be used together with OO.ui.OptionWidget or OO.ui.DecoratedOptionWidget. For
6418 * more information, please see the [OOUI documentation on MediaWiki][1].
6419 *
6420 * @example
6421 * // A select widget with three options.
6422 * var select = new OO.ui.SelectWidget( {
6423 * items: [
6424 * new OO.ui.OptionWidget( {
6425 * data: 'a',
6426 * label: 'Option One',
6427 * } ),
6428 * new OO.ui.OptionWidget( {
6429 * data: 'b',
6430 * label: 'Option Two',
6431 * } ),
6432 * new OO.ui.OptionWidget( {
6433 * data: 'c',
6434 * label: 'Option Three',
6435 * } )
6436 * ]
6437 * } );
6438 * $( document.body ).append( select.$element );
6439 *
6440 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options
6441 *
6442 * @abstract
6443 * @class
6444 * @extends OO.ui.Widget
6445 * @mixins OO.ui.mixin.GroupWidget
6446 *
6447 * @constructor
6448 * @param {Object} [config] Configuration options
6449 * @cfg {OO.ui.OptionWidget[]} [items] An array of options to add to the select.
6450 * Options are created with {@link OO.ui.OptionWidget OptionWidget} classes. See
6451 * the [OOUI documentation on MediaWiki] [2] for examples.
6452 * [2]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options
6453 * @cfg {boolean} [multiselect] Allow for multiple selections
6454 */
6455 OO.ui.SelectWidget = function OoUiSelectWidget( config ) {
6456 // Configuration initialization
6457 config = config || {};
6458
6459 // Parent constructor
6460 OO.ui.SelectWidget.parent.call( this, config );
6461
6462 // Mixin constructors
6463 OO.ui.mixin.GroupWidget.call( this, $.extend( {
6464 $group: this.$element
6465 }, config ) );
6466
6467 // Properties
6468 this.pressed = false;
6469 this.selecting = null;
6470 this.multiselect = !!config.multiselect;
6471 this.onDocumentMouseUpHandler = this.onDocumentMouseUp.bind( this );
6472 this.onDocumentMouseMoveHandler = this.onDocumentMouseMove.bind( this );
6473 this.onDocumentKeyDownHandler = this.onDocumentKeyDown.bind( this );
6474 this.onDocumentKeyPressHandler = this.onDocumentKeyPress.bind( this );
6475 this.keyPressBuffer = '';
6476 this.keyPressBufferTimer = null;
6477 this.blockMouseOverEvents = 0;
6478
6479 // Events
6480 this.connect( this, {
6481 toggle: 'onToggle'
6482 } );
6483 this.$element.on( {
6484 focusin: this.onFocus.bind( this ),
6485 mousedown: this.onMouseDown.bind( this ),
6486 mouseover: this.onMouseOver.bind( this ),
6487 mouseleave: this.onMouseLeave.bind( this )
6488 } );
6489
6490 // Initialization
6491 this.$element
6492 .addClass( 'oo-ui-selectWidget oo-ui-selectWidget-unpressed' )
6493 .attr( 'role', 'listbox' );
6494 this.setFocusOwner( this.$element );
6495 if ( Array.isArray( config.items ) ) {
6496 this.addItems( config.items );
6497 }
6498 };
6499
6500 /* Setup */
6501
6502 OO.inheritClass( OO.ui.SelectWidget, OO.ui.Widget );
6503 OO.mixinClass( OO.ui.SelectWidget, OO.ui.mixin.GroupWidget );
6504
6505 /* Events */
6506
6507 /**
6508 * @event highlight
6509 *
6510 * A `highlight` event is emitted when the highlight is changed with the #highlightItem method.
6511 *
6512 * @param {OO.ui.OptionWidget|null} item Highlighted item
6513 */
6514
6515 /**
6516 * @event press
6517 *
6518 * A `press` event is emitted when the #pressItem method is used to programmatically modify the
6519 * pressed state of an option.
6520 *
6521 * @param {OO.ui.OptionWidget|null} item Pressed item
6522 */
6523
6524 /**
6525 * @event select
6526 *
6527 * A `select` event is emitted when the selection is modified programmatically with the #selectItem
6528 * method.
6529 *
6530 * @param {OO.ui.OptionWidget[]|OO.ui.OptionWidget|null} items Currently selected items
6531 */
6532
6533 /**
6534 * @event choose
6535 *
6536 * A `choose` event is emitted when an item is chosen with the #chooseItem method.
6537 *
6538 * @param {OO.ui.OptionWidget} item Chosen item
6539 * @param {boolean} selected Item is selected
6540 */
6541
6542 /**
6543 * @event add
6544 *
6545 * An `add` event is emitted when options are added to the select with the #addItems method.
6546 *
6547 * @param {OO.ui.OptionWidget[]} items Added items
6548 * @param {number} index Index of insertion point
6549 */
6550
6551 /**
6552 * @event remove
6553 *
6554 * A `remove` event is emitted when options are removed from the select with the #clearItems
6555 * or #removeItems methods.
6556 *
6557 * @param {OO.ui.OptionWidget[]} items Removed items
6558 */
6559
6560 /* Static methods */
6561
6562 /**
6563 * Normalize text for filter matching
6564 *
6565 * @param {string} text Text
6566 * @return {string} Normalized text
6567 */
6568 OO.ui.SelectWidget.static.normalizeForMatching = function ( text ) {
6569 // Replace trailing whitespace, normalize multiple spaces and make case insensitive
6570 var normalized = text.trim().replace( /\s+/, ' ' ).toLowerCase();
6571
6572 // Normalize Unicode
6573 // eslint-disable-next-line no-restricted-properties
6574 if ( normalized.normalize ) {
6575 // eslint-disable-next-line no-restricted-properties
6576 normalized = normalized.normalize();
6577 }
6578 return normalized;
6579 };
6580
6581 /* Methods */
6582
6583 /**
6584 * Handle focus events
6585 *
6586 * @private
6587 * @param {jQuery.Event} event
6588 */
6589 OO.ui.SelectWidget.prototype.onFocus = function ( event ) {
6590 var item;
6591 if ( event.target === this.$element[ 0 ] ) {
6592 // This widget was focussed, e.g. by the user tabbing to it.
6593 // The styles for focus state depend on one of the items being selected.
6594 if ( !this.findSelectedItem() ) {
6595 item = this.findFirstSelectableItem();
6596 }
6597 } else {
6598 if ( event.target.tabIndex === -1 ) {
6599 // One of the options got focussed (and the event bubbled up here).
6600 // They can't be tabbed to, but they can be activated using access keys.
6601 // OptionWidgets and focusable UI elements inside them have tabindex="-1" set.
6602 item = this.findTargetItem( event );
6603 } else {
6604 // There is something actually user-focusable in one of the labels of the options, and
6605 // the user focussed it (e.g. by tabbing to it). Do nothing (especially, don't change
6606 // the focus).
6607 return;
6608 }
6609 }
6610
6611 if ( item ) {
6612 if ( item.constructor.static.highlightable ) {
6613 this.highlightItem( item );
6614 } else {
6615 this.selectItem( item );
6616 }
6617 }
6618
6619 if ( event.target !== this.$element[ 0 ] ) {
6620 this.$focusOwner.trigger( 'focus' );
6621 }
6622 };
6623
6624 /**
6625 * Handle mouse down events.
6626 *
6627 * @private
6628 * @param {jQuery.Event} e Mouse down event
6629 * @return {undefined|boolean} False to prevent default if event is handled
6630 */
6631 OO.ui.SelectWidget.prototype.onMouseDown = function ( e ) {
6632 var item;
6633
6634 if ( !this.isDisabled() && e.which === OO.ui.MouseButtons.LEFT ) {
6635 this.togglePressed( true );
6636 item = this.findTargetItem( e );
6637 if ( item && item.isSelectable() ) {
6638 this.pressItem( item );
6639 this.selecting = item;
6640 this.getElementDocument().addEventListener( 'mouseup', this.onDocumentMouseUpHandler, true );
6641 this.getElementDocument().addEventListener( 'mousemove', this.onDocumentMouseMoveHandler, true );
6642 }
6643 }
6644 return false;
6645 };
6646
6647 /**
6648 * Handle document mouse up events.
6649 *
6650 * @private
6651 * @param {MouseEvent} e Mouse up event
6652 * @return {undefined|boolean} False to prevent default if event is handled
6653 */
6654 OO.ui.SelectWidget.prototype.onDocumentMouseUp = function ( e ) {
6655 var item;
6656
6657 this.togglePressed( false );
6658 if ( !this.selecting ) {
6659 item = this.findTargetItem( e );
6660 if ( item && item.isSelectable() ) {
6661 this.selecting = item;
6662 }
6663 }
6664 if ( !this.isDisabled() && e.which === OO.ui.MouseButtons.LEFT && this.selecting ) {
6665 this.pressItem( null );
6666 this.chooseItem( this.selecting );
6667 this.selecting = null;
6668 }
6669
6670 this.getElementDocument().removeEventListener( 'mouseup', this.onDocumentMouseUpHandler, true );
6671 this.getElementDocument().removeEventListener( 'mousemove', this.onDocumentMouseMoveHandler, true );
6672
6673 return false;
6674 };
6675
6676 /**
6677 * Handle document mouse move events.
6678 *
6679 * @private
6680 * @param {MouseEvent} e Mouse move event
6681 */
6682 OO.ui.SelectWidget.prototype.onDocumentMouseMove = function ( e ) {
6683 var item;
6684
6685 if ( !this.isDisabled() && this.pressed ) {
6686 item = this.findTargetItem( e );
6687 if ( item && item !== this.selecting && item.isSelectable() ) {
6688 this.pressItem( item );
6689 this.selecting = item;
6690 }
6691 }
6692 };
6693
6694 /**
6695 * Handle mouse over events.
6696 *
6697 * @private
6698 * @param {jQuery.Event} e Mouse over event
6699 * @return {undefined|boolean} False to prevent default if event is handled
6700 */
6701 OO.ui.SelectWidget.prototype.onMouseOver = function ( e ) {
6702 var item;
6703 if ( this.blockMouseOverEvents ) {
6704 return;
6705 }
6706 if ( !this.isDisabled() ) {
6707 item = this.findTargetItem( e );
6708 this.highlightItem( item && item.isHighlightable() ? item : null );
6709 }
6710 return false;
6711 };
6712
6713 /**
6714 * Handle mouse leave events.
6715 *
6716 * @private
6717 * @param {jQuery.Event} e Mouse over event
6718 * @return {undefined|boolean} False to prevent default if event is handled
6719 */
6720 OO.ui.SelectWidget.prototype.onMouseLeave = function () {
6721 if ( !this.isDisabled() ) {
6722 this.highlightItem( null );
6723 }
6724 return false;
6725 };
6726
6727 /**
6728 * Handle document key down events.
6729 *
6730 * @protected
6731 * @param {KeyboardEvent} e Key down event
6732 */
6733 OO.ui.SelectWidget.prototype.onDocumentKeyDown = function ( e ) {
6734 var nextItem,
6735 handled = false,
6736 selected = this.findSelectedItems(),
6737 currentItem = this.findHighlightedItem() || (
6738 Array.isArray( selected ) ? selected[ 0 ] : selected
6739 ),
6740 firstItem = this.getItems()[ 0 ];
6741
6742 if ( !this.isDisabled() && this.isVisible() ) {
6743 switch ( e.keyCode ) {
6744 case OO.ui.Keys.ENTER:
6745 if ( currentItem ) {
6746 // Was only highlighted, now let's select it. No-op if already selected.
6747 this.chooseItem( currentItem );
6748 handled = true;
6749 }
6750 break;
6751 case OO.ui.Keys.UP:
6752 case OO.ui.Keys.LEFT:
6753 this.clearKeyPressBuffer();
6754 nextItem = currentItem ?
6755 this.findRelativeSelectableItem( currentItem, -1 ) : firstItem;
6756 handled = true;
6757 break;
6758 case OO.ui.Keys.DOWN:
6759 case OO.ui.Keys.RIGHT:
6760 this.clearKeyPressBuffer();
6761 nextItem = currentItem ?
6762 this.findRelativeSelectableItem( currentItem, 1 ) : firstItem;
6763 handled = true;
6764 break;
6765 case OO.ui.Keys.ESCAPE:
6766 case OO.ui.Keys.TAB:
6767 if ( currentItem ) {
6768 currentItem.setHighlighted( false );
6769 }
6770 this.unbindDocumentKeyDownListener();
6771 this.unbindDocumentKeyPressListener();
6772 // Don't prevent tabbing away / defocusing
6773 handled = false;
6774 break;
6775 }
6776
6777 if ( nextItem ) {
6778 if ( nextItem.constructor.static.highlightable ) {
6779 this.highlightItem( nextItem );
6780 } else {
6781 this.chooseItem( nextItem );
6782 }
6783 this.scrollItemIntoView( nextItem );
6784 }
6785
6786 if ( handled ) {
6787 e.preventDefault();
6788 e.stopPropagation();
6789 }
6790 }
6791 };
6792
6793 /**
6794 * Bind document key down listener.
6795 *
6796 * @protected
6797 */
6798 OO.ui.SelectWidget.prototype.bindDocumentKeyDownListener = function () {
6799 this.getElementDocument().addEventListener( 'keydown', this.onDocumentKeyDownHandler, true );
6800 };
6801
6802 /**
6803 * Unbind document key down listener.
6804 *
6805 * @protected
6806 */
6807 OO.ui.SelectWidget.prototype.unbindDocumentKeyDownListener = function () {
6808 this.getElementDocument().removeEventListener( 'keydown', this.onDocumentKeyDownHandler, true );
6809 };
6810
6811 /**
6812 * Scroll item into view, preventing spurious mouse highlight actions from happening.
6813 *
6814 * @param {OO.ui.OptionWidget} item Item to scroll into view
6815 */
6816 OO.ui.SelectWidget.prototype.scrollItemIntoView = function ( item ) {
6817 var widget = this;
6818 // Chromium's Blink engine will generate spurious 'mouseover' events during programmatic
6819 // scrolling and around 100-150 ms after it is finished.
6820 this.blockMouseOverEvents++;
6821 item.scrollElementIntoView().done( function () {
6822 setTimeout( function () {
6823 widget.blockMouseOverEvents--;
6824 }, 200 );
6825 } );
6826 };
6827
6828 /**
6829 * Clear the key-press buffer
6830 *
6831 * @protected
6832 */
6833 OO.ui.SelectWidget.prototype.clearKeyPressBuffer = function () {
6834 if ( this.keyPressBufferTimer ) {
6835 clearTimeout( this.keyPressBufferTimer );
6836 this.keyPressBufferTimer = null;
6837 }
6838 this.keyPressBuffer = '';
6839 };
6840
6841 /**
6842 * Handle key press events.
6843 *
6844 * @protected
6845 * @param {KeyboardEvent} e Key press event
6846 * @return {undefined|boolean} False to prevent default if event is handled
6847 */
6848 OO.ui.SelectWidget.prototype.onDocumentKeyPress = function ( e ) {
6849 var c, filter, item, selected;
6850
6851 if ( !e.charCode ) {
6852 if ( e.keyCode === OO.ui.Keys.BACKSPACE && this.keyPressBuffer !== '' ) {
6853 this.keyPressBuffer = this.keyPressBuffer.substr( 0, this.keyPressBuffer.length - 1 );
6854 return false;
6855 }
6856 return;
6857 }
6858 // eslint-disable-next-line no-restricted-properties
6859 if ( String.fromCodePoint ) {
6860 // eslint-disable-next-line no-restricted-properties
6861 c = String.fromCodePoint( e.charCode );
6862 } else {
6863 c = String.fromCharCode( e.charCode );
6864 }
6865
6866 if ( this.keyPressBufferTimer ) {
6867 clearTimeout( this.keyPressBufferTimer );
6868 }
6869 this.keyPressBufferTimer = setTimeout( this.clearKeyPressBuffer.bind( this ), 1500 );
6870
6871 selected = this.findSelectedItems();
6872 item = this.findHighlightedItem() || (
6873 Array.isArray( selected ) ? selected[ 0 ] : selected
6874 );
6875
6876 if ( this.keyPressBuffer === c ) {
6877 // Common (if weird) special case: typing "xxxx" will cycle through all
6878 // the items beginning with "x".
6879 if ( item ) {
6880 item = this.findRelativeSelectableItem( item, 1 );
6881 }
6882 } else {
6883 this.keyPressBuffer += c;
6884 }
6885
6886 filter = this.getItemMatcher( this.keyPressBuffer, false );
6887 if ( !item || !filter( item ) ) {
6888 item = this.findRelativeSelectableItem( item, 1, filter );
6889 }
6890 if ( item ) {
6891 if ( this.isVisible() && item.constructor.static.highlightable ) {
6892 this.highlightItem( item );
6893 } else {
6894 this.chooseItem( item );
6895 }
6896 this.scrollItemIntoView( item );
6897 }
6898
6899 e.preventDefault();
6900 e.stopPropagation();
6901 };
6902
6903 /**
6904 * Get a matcher for the specific string
6905 *
6906 * @protected
6907 * @param {string} query String to match against items
6908 * @param {string} [mode='prefix'] Matching mode: 'substring', 'prefix', or 'exact'
6909 * @return {Function} function ( OO.ui.OptionWidget ) => boolean
6910 */
6911 OO.ui.SelectWidget.prototype.getItemMatcher = function ( query, mode ) {
6912 var normalizeForMatching = this.constructor.static.normalizeForMatching,
6913 normalizedQuery = normalizeForMatching( query );
6914
6915 // Support deprecated exact=true argument
6916 if ( mode === true ) {
6917 mode = 'exact';
6918 }
6919
6920 return function ( item ) {
6921 var matchText = normalizeForMatching( item.getMatchText() );
6922
6923 if ( normalizedQuery === '' ) {
6924 // Empty string matches all, except if we are in 'exact'
6925 // mode, where it doesn't match at all
6926 return mode !== 'exact';
6927 }
6928
6929 switch ( mode ) {
6930 case 'exact':
6931 return matchText === normalizedQuery;
6932 case 'substring':
6933 return matchText.indexOf( normalizedQuery ) !== -1;
6934 // 'prefix'
6935 default:
6936 return matchText.indexOf( normalizedQuery ) === 0;
6937 }
6938 };
6939 };
6940
6941 /**
6942 * Bind document key press listener.
6943 *
6944 * @protected
6945 */
6946 OO.ui.SelectWidget.prototype.bindDocumentKeyPressListener = function () {
6947 this.getElementDocument().addEventListener( 'keypress', this.onDocumentKeyPressHandler, true );
6948 };
6949
6950 /**
6951 * Unbind document key down listener.
6952 *
6953 * If you override this, be sure to call this.clearKeyPressBuffer() from your
6954 * implementation.
6955 *
6956 * @protected
6957 */
6958 OO.ui.SelectWidget.prototype.unbindDocumentKeyPressListener = function () {
6959 this.getElementDocument().removeEventListener( 'keypress', this.onDocumentKeyPressHandler, true );
6960 this.clearKeyPressBuffer();
6961 };
6962
6963 /**
6964 * Visibility change handler
6965 *
6966 * @protected
6967 * @param {boolean} visible
6968 */
6969 OO.ui.SelectWidget.prototype.onToggle = function ( visible ) {
6970 if ( !visible ) {
6971 this.clearKeyPressBuffer();
6972 }
6973 };
6974
6975 /**
6976 * Get the closest item to a jQuery.Event.
6977 *
6978 * @private
6979 * @param {jQuery.Event} e
6980 * @return {OO.ui.OptionWidget|null} Outline item widget, `null` if none was found
6981 */
6982 OO.ui.SelectWidget.prototype.findTargetItem = function ( e ) {
6983 var $option = $( e.target ).closest( '.oo-ui-optionWidget' );
6984 if ( !$option.closest( '.oo-ui-selectWidget' ).is( this.$element ) ) {
6985 return null;
6986 }
6987 return $option.data( 'oo-ui-optionWidget' ) || null;
6988 };
6989
6990 /**
6991 * Find all selected items, if there are any. If the widget allows for multiselect
6992 * it will return an array of selected options. If the widget doesn't allow for
6993 * multiselect, it will return the selected option or null if no item is selected.
6994 *
6995 * @return {OO.ui.OptionWidget[]|OO.ui.OptionWidget|null} If the widget is multiselect
6996 * then return an array of selected items (or empty array),
6997 * if the widget is not multiselect, return a single selected item, or `null`
6998 * if no item is selected
6999 */
7000 OO.ui.SelectWidget.prototype.findSelectedItems = function () {
7001 var selected = this.items.filter( function ( item ) {
7002 return item.isSelected();
7003 } );
7004
7005 return this.multiselect ?
7006 selected :
7007 selected[ 0 ] || null;
7008 };
7009
7010 /**
7011 * Find selected item.
7012 *
7013 * @return {OO.ui.OptionWidget[]|OO.ui.OptionWidget|null} If the widget is multiselect
7014 * then return an array of selected items (or empty array),
7015 * if the widget is not multiselect, return a single selected item, or `null`
7016 * if no item is selected
7017 */
7018 OO.ui.SelectWidget.prototype.findSelectedItem = function () {
7019 return this.findSelectedItems();
7020 };
7021
7022 /**
7023 * Find highlighted item.
7024 *
7025 * @return {OO.ui.OptionWidget|null} Highlighted item, `null` if no item is highlighted
7026 */
7027 OO.ui.SelectWidget.prototype.findHighlightedItem = function () {
7028 var i, len;
7029
7030 for ( i = 0, len = this.items.length; i < len; i++ ) {
7031 if ( this.items[ i ].isHighlighted() ) {
7032 return this.items[ i ];
7033 }
7034 }
7035 return null;
7036 };
7037
7038 /**
7039 * Toggle pressed state.
7040 *
7041 * Press is a state that occurs when a user mouses down on an item, but
7042 * has not yet let go of the mouse. The item may appear selected, but it will not be selected
7043 * until the user releases the mouse.
7044 *
7045 * @param {boolean} pressed An option is being pressed
7046 */
7047 OO.ui.SelectWidget.prototype.togglePressed = function ( pressed ) {
7048 if ( pressed === undefined ) {
7049 pressed = !this.pressed;
7050 }
7051 if ( pressed !== this.pressed ) {
7052 this.$element
7053 .toggleClass( 'oo-ui-selectWidget-pressed', pressed )
7054 .toggleClass( 'oo-ui-selectWidget-unpressed', !pressed );
7055 this.pressed = pressed;
7056 }
7057 };
7058
7059 /**
7060 * Highlight an option. If the `item` param is omitted, no options will be highlighted
7061 * and any existing highlight will be removed. The highlight is mutually exclusive.
7062 *
7063 * @param {OO.ui.OptionWidget} [item] Item to highlight, omit for no highlight
7064 * @fires highlight
7065 * @chainable
7066 * @return {OO.ui.Widget} The widget, for chaining
7067 */
7068 OO.ui.SelectWidget.prototype.highlightItem = function ( item ) {
7069 var i, len, highlighted,
7070 changed = false;
7071
7072 for ( i = 0, len = this.items.length; i < len; i++ ) {
7073 highlighted = this.items[ i ] === item;
7074 if ( this.items[ i ].isHighlighted() !== highlighted ) {
7075 this.items[ i ].setHighlighted( highlighted );
7076 changed = true;
7077 }
7078 }
7079 if ( changed ) {
7080 if ( item ) {
7081 this.$focusOwner.attr( 'aria-activedescendant', item.getElementId() );
7082 } else {
7083 this.$focusOwner.removeAttr( 'aria-activedescendant' );
7084 }
7085 this.emit( 'highlight', item );
7086 }
7087
7088 return this;
7089 };
7090
7091 /**
7092 * Fetch an item by its label.
7093 *
7094 * @param {string} label Label of the item to select.
7095 * @param {boolean} [prefix=false] Allow a prefix match, if only a single item matches
7096 * @return {OO.ui.Element|null} Item with equivalent label, `null` if none exists
7097 */
7098 OO.ui.SelectWidget.prototype.getItemFromLabel = function ( label, prefix ) {
7099 var i, item, found,
7100 len = this.items.length,
7101 filter = this.getItemMatcher( label, 'exact' );
7102
7103 for ( i = 0; i < len; i++ ) {
7104 item = this.items[ i ];
7105 if ( item instanceof OO.ui.OptionWidget && item.isSelectable() && filter( item ) ) {
7106 return item;
7107 }
7108 }
7109
7110 if ( prefix ) {
7111 found = null;
7112 filter = this.getItemMatcher( label, 'prefix' );
7113 for ( i = 0; i < len; i++ ) {
7114 item = this.items[ i ];
7115 if ( item instanceof OO.ui.OptionWidget && item.isSelectable() && filter( item ) ) {
7116 if ( found ) {
7117 return null;
7118 }
7119 found = item;
7120 }
7121 }
7122 if ( found ) {
7123 return found;
7124 }
7125 }
7126
7127 return null;
7128 };
7129
7130 /**
7131 * Programmatically select an option by its label. If the item does not exist,
7132 * all options will be deselected.
7133 *
7134 * @param {string} [label] Label of the item to select.
7135 * @param {boolean} [prefix=false] Allow a prefix match, if only a single item matches
7136 * @fires select
7137 * @chainable
7138 * @return {OO.ui.Widget} The widget, for chaining
7139 */
7140 OO.ui.SelectWidget.prototype.selectItemByLabel = function ( label, prefix ) {
7141 var itemFromLabel = this.getItemFromLabel( label, !!prefix );
7142 if ( label === undefined || !itemFromLabel ) {
7143 return this.selectItem();
7144 }
7145 return this.selectItem( itemFromLabel );
7146 };
7147
7148 /**
7149 * Programmatically select an option by its data. If the `data` parameter is omitted,
7150 * or if the item does not exist, all options will be deselected.
7151 *
7152 * @param {Object|string} [data] Value of the item to select, omit to deselect all
7153 * @fires select
7154 * @chainable
7155 * @return {OO.ui.Widget} The widget, for chaining
7156 */
7157 OO.ui.SelectWidget.prototype.selectItemByData = function ( data ) {
7158 var itemFromData = this.findItemFromData( data );
7159 if ( data === undefined || !itemFromData ) {
7160 return this.selectItem();
7161 }
7162 return this.selectItem( itemFromData );
7163 };
7164
7165 /**
7166 * Programmatically unselect an option by its reference. If the widget
7167 * allows for multiple selections, there may be other items still selected;
7168 * otherwise, no items will be selected.
7169 * If no item is given, all selected items will be unselected.
7170 *
7171 * @param {OO.ui.OptionWidget} [item] Item to unselect
7172 * @fires select
7173 * @chainable
7174 * @return {OO.ui.Widget} The widget, for chaining
7175 */
7176 OO.ui.SelectWidget.prototype.unselectItem = function ( item ) {
7177 if ( item ) {
7178 item.setSelected( false );
7179 } else {
7180 this.items.forEach( function ( item ) {
7181 item.setSelected( false );
7182 } );
7183 }
7184
7185 this.emit( 'select', this.findSelectedItems() );
7186 return this;
7187 };
7188
7189 /**
7190 * Programmatically select an option by its reference. If the `item` parameter is omitted,
7191 * all options will be deselected.
7192 *
7193 * @param {OO.ui.OptionWidget} [item] Item to select, omit to deselect all
7194 * @fires select
7195 * @chainable
7196 * @return {OO.ui.Widget} The widget, for chaining
7197 */
7198 OO.ui.SelectWidget.prototype.selectItem = function ( item ) {
7199 var i, len, selected,
7200 changed = false;
7201
7202 if ( this.multiselect && item ) {
7203 // Select the item directly
7204 item.setSelected( true );
7205 } else {
7206 for ( i = 0, len = this.items.length; i < len; i++ ) {
7207 selected = this.items[ i ] === item;
7208 if ( this.items[ i ].isSelected() !== selected ) {
7209 this.items[ i ].setSelected( selected );
7210 changed = true;
7211 }
7212 }
7213 }
7214 if ( changed ) {
7215 // TODO: When should a non-highlightable element be selected?
7216 if ( item && !item.constructor.static.highlightable ) {
7217 if ( item ) {
7218 this.$focusOwner.attr( 'aria-activedescendant', item.getElementId() );
7219 } else {
7220 this.$focusOwner.removeAttr( 'aria-activedescendant' );
7221 }
7222 }
7223 this.emit( 'select', this.findSelectedItems() );
7224 }
7225
7226 return this;
7227 };
7228
7229 /**
7230 * Press an item.
7231 *
7232 * Press is a state that occurs when a user mouses down on an item, but has not
7233 * yet let go of the mouse. The item may appear selected, but it will not be selected until the user
7234 * releases the mouse.
7235 *
7236 * @param {OO.ui.OptionWidget} [item] Item to press, omit to depress all
7237 * @fires press
7238 * @chainable
7239 * @return {OO.ui.Widget} The widget, for chaining
7240 */
7241 OO.ui.SelectWidget.prototype.pressItem = function ( item ) {
7242 var i, len, pressed,
7243 changed = false;
7244
7245 for ( i = 0, len = this.items.length; i < len; i++ ) {
7246 pressed = this.items[ i ] === item;
7247 if ( this.items[ i ].isPressed() !== pressed ) {
7248 this.items[ i ].setPressed( pressed );
7249 changed = true;
7250 }
7251 }
7252 if ( changed ) {
7253 this.emit( 'press', item );
7254 }
7255
7256 return this;
7257 };
7258
7259 /**
7260 * Choose an item.
7261 *
7262 * Note that ‘choose’ should never be modified programmatically. A user can choose
7263 * an option with the keyboard or mouse and it becomes selected. To select an item programmatically,
7264 * use the #selectItem method.
7265 *
7266 * This method is identical to #selectItem, but may vary in subclasses that take additional action
7267 * when users choose an item with the keyboard or mouse.
7268 *
7269 * @param {OO.ui.OptionWidget} item Item to choose
7270 * @fires choose
7271 * @chainable
7272 * @return {OO.ui.Widget} The widget, for chaining
7273 */
7274 OO.ui.SelectWidget.prototype.chooseItem = function ( item ) {
7275 if ( item ) {
7276 if ( this.multiselect && item.isSelected() ) {
7277 this.unselectItem( item );
7278 } else {
7279 this.selectItem( item );
7280 }
7281
7282 this.emit( 'choose', item, item.isSelected() );
7283 }
7284
7285 return this;
7286 };
7287
7288 /**
7289 * Find an option by its position relative to the specified item (or to the start of the option
7290 * array, if item is `null`). The direction in which to search through the option array is specified
7291 * with a number: -1 for reverse (the default) or 1 for forward. The method will return an option,
7292 * or `null` if there are no options in the array.
7293 *
7294 * @param {OO.ui.OptionWidget|null} item Item to describe the start position, or `null` to start at
7295 * the beginning of the array.
7296 * @param {number} direction Direction to move in: -1 to move backward, 1 to move forward
7297 * @param {Function} [filter] Only consider items for which this function returns
7298 * true. Function takes an OO.ui.OptionWidget and returns a boolean.
7299 * @return {OO.ui.OptionWidget|null} Item at position, `null` if there are no items in the select
7300 */
7301 OO.ui.SelectWidget.prototype.findRelativeSelectableItem = function ( item, direction, filter ) {
7302 var currentIndex, nextIndex, i,
7303 increase = direction > 0 ? 1 : -1,
7304 len = this.items.length;
7305
7306 if ( item instanceof OO.ui.OptionWidget ) {
7307 currentIndex = this.items.indexOf( item );
7308 nextIndex = ( currentIndex + increase + len ) % len;
7309 } else {
7310 // If no item is selected and moving forward, start at the beginning.
7311 // If moving backward, start at the end.
7312 nextIndex = direction > 0 ? 0 : len - 1;
7313 }
7314
7315 for ( i = 0; i < len; i++ ) {
7316 item = this.items[ nextIndex ];
7317 if (
7318 item instanceof OO.ui.OptionWidget && item.isSelectable() &&
7319 ( !filter || filter( item ) )
7320 ) {
7321 return item;
7322 }
7323 nextIndex = ( nextIndex + increase + len ) % len;
7324 }
7325 return null;
7326 };
7327
7328 /**
7329 * Find the next selectable item or `null` if there are no selectable items.
7330 * Disabled options and menu-section markers and breaks are not selectable.
7331 *
7332 * @return {OO.ui.OptionWidget|null} Item, `null` if there aren't any selectable items
7333 */
7334 OO.ui.SelectWidget.prototype.findFirstSelectableItem = function () {
7335 return this.findRelativeSelectableItem( null, 1 );
7336 };
7337
7338 /**
7339 * Add an array of options to the select. Optionally, an index number can be used to
7340 * specify an insertion point.
7341 *
7342 * @param {OO.ui.OptionWidget[]} items Items to add
7343 * @param {number} [index] Index to insert items after
7344 * @fires add
7345 * @chainable
7346 * @return {OO.ui.Widget} The widget, for chaining
7347 */
7348 OO.ui.SelectWidget.prototype.addItems = function ( items, index ) {
7349 // Mixin method
7350 OO.ui.mixin.GroupWidget.prototype.addItems.call( this, items, index );
7351
7352 // Always provide an index, even if it was omitted
7353 this.emit( 'add', items, index === undefined ? this.items.length - items.length - 1 : index );
7354
7355 return this;
7356 };
7357
7358 /**
7359 * Remove the specified array of options from the select. Options will be detached
7360 * from the DOM, not removed, so they can be reused later. To remove all options from
7361 * the select, you may wish to use the #clearItems method instead.
7362 *
7363 * @param {OO.ui.OptionWidget[]} items Items to remove
7364 * @fires remove
7365 * @chainable
7366 * @return {OO.ui.Widget} The widget, for chaining
7367 */
7368 OO.ui.SelectWidget.prototype.removeItems = function ( items ) {
7369 var i, len, item;
7370
7371 // Deselect items being removed
7372 for ( i = 0, len = items.length; i < len; i++ ) {
7373 item = items[ i ];
7374 if ( item.isSelected() ) {
7375 this.selectItem( null );
7376 }
7377 }
7378
7379 // Mixin method
7380 OO.ui.mixin.GroupWidget.prototype.removeItems.call( this, items );
7381
7382 this.emit( 'remove', items );
7383
7384 return this;
7385 };
7386
7387 /**
7388 * Clear all options from the select. Options will be detached from the DOM, not removed,
7389 * so that they can be reused later. To remove a subset of options from the select, use
7390 * the #removeItems method.
7391 *
7392 * @fires remove
7393 * @chainable
7394 * @return {OO.ui.Widget} The widget, for chaining
7395 */
7396 OO.ui.SelectWidget.prototype.clearItems = function () {
7397 var items = this.items.slice();
7398
7399 // Mixin method
7400 OO.ui.mixin.GroupWidget.prototype.clearItems.call( this );
7401
7402 // Clear selection
7403 this.selectItem( null );
7404
7405 this.emit( 'remove', items );
7406
7407 return this;
7408 };
7409
7410 /**
7411 * Set the DOM element which has focus while the user is interacting with this SelectWidget.
7412 *
7413 * This is used to set `aria-activedescendant` and `aria-expanded` on it.
7414 *
7415 * @protected
7416 * @param {jQuery} $focusOwner
7417 */
7418 OO.ui.SelectWidget.prototype.setFocusOwner = function ( $focusOwner ) {
7419 this.$focusOwner = $focusOwner;
7420 };
7421
7422 /**
7423 * DecoratedOptionWidgets are {@link OO.ui.OptionWidget options} that can be configured
7424 * with an {@link OO.ui.mixin.IconElement icon} and/or
7425 * {@link OO.ui.mixin.IndicatorElement indicator}.
7426 * This class is used with OO.ui.SelectWidget to create a selection of mutually exclusive
7427 * options. For more information about options and selects, please see the
7428 * [OOUI documentation on MediaWiki][1].
7429 *
7430 * @example
7431 * // Decorated options in a select widget.
7432 * var select = new OO.ui.SelectWidget( {
7433 * items: [
7434 * new OO.ui.DecoratedOptionWidget( {
7435 * data: 'a',
7436 * label: 'Option with icon',
7437 * icon: 'help'
7438 * } ),
7439 * new OO.ui.DecoratedOptionWidget( {
7440 * data: 'b',
7441 * label: 'Option with indicator',
7442 * indicator: 'next'
7443 * } )
7444 * ]
7445 * } );
7446 * $( document.body ).append( select.$element );
7447 *
7448 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options
7449 *
7450 * @class
7451 * @extends OO.ui.OptionWidget
7452 * @mixins OO.ui.mixin.IconElement
7453 * @mixins OO.ui.mixin.IndicatorElement
7454 *
7455 * @constructor
7456 * @param {Object} [config] Configuration options
7457 */
7458 OO.ui.DecoratedOptionWidget = function OoUiDecoratedOptionWidget( config ) {
7459 // Parent constructor
7460 OO.ui.DecoratedOptionWidget.parent.call( this, config );
7461
7462 // Mixin constructors
7463 OO.ui.mixin.IconElement.call( this, config );
7464 OO.ui.mixin.IndicatorElement.call( this, config );
7465
7466 // Initialization
7467 this.$element
7468 .addClass( 'oo-ui-decoratedOptionWidget' )
7469 .prepend( this.$icon )
7470 .append( this.$indicator );
7471 };
7472
7473 /* Setup */
7474
7475 OO.inheritClass( OO.ui.DecoratedOptionWidget, OO.ui.OptionWidget );
7476 OO.mixinClass( OO.ui.DecoratedOptionWidget, OO.ui.mixin.IconElement );
7477 OO.mixinClass( OO.ui.DecoratedOptionWidget, OO.ui.mixin.IndicatorElement );
7478
7479 /**
7480 * MenuOptionWidget is an option widget that looks like a menu item. The class is used with
7481 * OO.ui.MenuSelectWidget to create a menu of mutually exclusive options. Please see
7482 * the [OOUI documentation on MediaWiki] [1] for more information.
7483 *
7484 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options#Menu_selects_and_options
7485 *
7486 * @class
7487 * @extends OO.ui.DecoratedOptionWidget
7488 *
7489 * @constructor
7490 * @param {Object} [config] Configuration options
7491 */
7492 OO.ui.MenuOptionWidget = function OoUiMenuOptionWidget( config ) {
7493 // Parent constructor
7494 OO.ui.MenuOptionWidget.parent.call( this, config );
7495
7496 // Properties
7497 this.checkIcon = new OO.ui.IconWidget( {
7498 icon: 'check',
7499 classes: [ 'oo-ui-menuOptionWidget-checkIcon' ]
7500 } );
7501
7502 // Initialization
7503 this.$element
7504 .prepend( this.checkIcon.$element )
7505 .addClass( 'oo-ui-menuOptionWidget' );
7506 };
7507
7508 /* Setup */
7509
7510 OO.inheritClass( OO.ui.MenuOptionWidget, OO.ui.DecoratedOptionWidget );
7511
7512 /* Static Properties */
7513
7514 /**
7515 * @static
7516 * @inheritdoc
7517 */
7518 OO.ui.MenuOptionWidget.static.scrollIntoViewOnSelect = true;
7519
7520 /**
7521 * MenuSectionOptionWidgets are used inside {@link OO.ui.MenuSelectWidget menu select widgets} to
7522 * group one or more related {@link OO.ui.MenuOptionWidget menu options}. MenuSectionOptionWidgets
7523 * cannot be highlighted or selected.
7524 *
7525 * @example
7526 * var dropdown = new OO.ui.DropdownWidget( {
7527 * menu: {
7528 * items: [
7529 * new OO.ui.MenuSectionOptionWidget( {
7530 * label: 'Dogs'
7531 * } ),
7532 * new OO.ui.MenuOptionWidget( {
7533 * data: 'corgi',
7534 * label: 'Welsh Corgi'
7535 * } ),
7536 * new OO.ui.MenuOptionWidget( {
7537 * data: 'poodle',
7538 * label: 'Standard Poodle'
7539 * } ),
7540 * new OO.ui.MenuSectionOptionWidget( {
7541 * label: 'Cats'
7542 * } ),
7543 * new OO.ui.MenuOptionWidget( {
7544 * data: 'lion',
7545 * label: 'Lion'
7546 * } )
7547 * ]
7548 * }
7549 * } );
7550 * $( document.body ).append( dropdown.$element );
7551 *
7552 * @class
7553 * @extends OO.ui.DecoratedOptionWidget
7554 *
7555 * @constructor
7556 * @param {Object} [config] Configuration options
7557 */
7558 OO.ui.MenuSectionOptionWidget = function OoUiMenuSectionOptionWidget( config ) {
7559 // Parent constructor
7560 OO.ui.MenuSectionOptionWidget.parent.call( this, config );
7561
7562 // Initialization
7563 this.$element
7564 .addClass( 'oo-ui-menuSectionOptionWidget' )
7565 .removeAttr( 'role aria-selected' );
7566 this.selected = false;
7567 };
7568
7569 /* Setup */
7570
7571 OO.inheritClass( OO.ui.MenuSectionOptionWidget, OO.ui.DecoratedOptionWidget );
7572
7573 /* Static Properties */
7574
7575 /**
7576 * @static
7577 * @inheritdoc
7578 */
7579 OO.ui.MenuSectionOptionWidget.static.selectable = false;
7580
7581 /**
7582 * @static
7583 * @inheritdoc
7584 */
7585 OO.ui.MenuSectionOptionWidget.static.highlightable = false;
7586
7587 /**
7588 * MenuSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains options and
7589 * is used together with OO.ui.MenuOptionWidget. It is designed be used as part of another widget.
7590 * See {@link OO.ui.DropdownWidget DropdownWidget},
7591 * {@link OO.ui.ComboBoxInputWidget ComboBoxInputWidget}, and
7592 * {@link OO.ui.mixin.LookupElement LookupElement} for examples of widgets that contain menus.
7593 * MenuSelectWidgets themselves are not instantiated directly, rather subclassed
7594 * and customized to be opened, closed, and displayed as needed.
7595 *
7596 * By default, menus are clipped to the visible viewport and are not visible when a user presses the
7597 * mouse outside the menu.
7598 *
7599 * Menus also have support for keyboard interaction:
7600 *
7601 * - Enter/Return key: choose and select a menu option
7602 * - Up-arrow key: highlight the previous menu option
7603 * - Down-arrow key: highlight the next menu option
7604 * - Escape key: hide the menu
7605 *
7606 * Unlike most widgets, MenuSelectWidget is initially hidden and must be shown by calling #toggle.
7607 *
7608 * Please see the [OOUI documentation on MediaWiki][1] for more information.
7609 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options
7610 *
7611 * @class
7612 * @extends OO.ui.SelectWidget
7613 * @mixins OO.ui.mixin.ClippableElement
7614 * @mixins OO.ui.mixin.FloatableElement
7615 *
7616 * @constructor
7617 * @param {Object} [config] Configuration options
7618 * @cfg {OO.ui.TextInputWidget} [input] Text input used to implement option highlighting for menu
7619 * items that match the text the user types. This config is used by
7620 * {@link OO.ui.ComboBoxInputWidget ComboBoxInputWidget} and
7621 * {@link OO.ui.mixin.LookupElement LookupElement}
7622 * @cfg {jQuery} [$input] Text input used to implement option highlighting for menu items that match
7623 * the text the user types. This config is used by
7624 * {@link OO.ui.TagMultiselectWidget TagMultiselectWidget}
7625 * @cfg {OO.ui.Widget} [widget] Widget associated with the menu's active state. If the user clicks
7626 * the mouse anywhere on the page outside of this widget, the menu is hidden. For example, if
7627 * there is a button that toggles the menu's visibility on click, the menu will be hidden then
7628 * re-shown when the user clicks that button, unless the button (or its parent widget) is passed
7629 * in here.
7630 * @cfg {boolean} [autoHide=true] Hide the menu when the mouse is pressed outside the menu.
7631 * @cfg {jQuery} [$autoCloseIgnore] If these elements are clicked, don't auto-hide the menu.
7632 * @cfg {boolean} [hideOnChoose=true] Hide the menu when the user chooses an option.
7633 * @cfg {boolean} [filterFromInput=false] Filter the displayed options from the input
7634 * @cfg {boolean} [highlightOnFilter] Highlight the first result when filtering
7635 * @cfg {string} [filterMode='prefix'] The mode by which the menu filters the results.
7636 * Options are 'exact', 'prefix' or 'substring'. See `OO.ui.SelectWidget#getItemMatcher`
7637 * @param {number|string} [width] Width of the menu as a number of pixels or CSS string with unit
7638 * suffix, used by {@link OO.ui.mixin.ClippableElement ClippableElement}
7639 */
7640 OO.ui.MenuSelectWidget = function OoUiMenuSelectWidget( config ) {
7641 // Configuration initialization
7642 config = config || {};
7643
7644 // Parent constructor
7645 OO.ui.MenuSelectWidget.parent.call( this, config );
7646
7647 // Mixin constructors
7648 OO.ui.mixin.ClippableElement.call( this, $.extend( { $clippable: this.$group }, config ) );
7649 OO.ui.mixin.FloatableElement.call( this, config );
7650
7651 // Initial vertical positions other than 'center' will result in
7652 // the menu being flipped if there is not enough space in the container.
7653 // Store the original position so we know what to reset to.
7654 this.originalVerticalPosition = this.verticalPosition;
7655
7656 // Properties
7657 this.autoHide = config.autoHide === undefined || !!config.autoHide;
7658 this.hideOnChoose = config.hideOnChoose === undefined || !!config.hideOnChoose;
7659 this.filterFromInput = !!config.filterFromInput;
7660 this.$input = config.$input ? config.$input : config.input ? config.input.$input : null;
7661 this.$widget = config.widget ? config.widget.$element : null;
7662 this.$autoCloseIgnore = config.$autoCloseIgnore || $( [] );
7663 this.onDocumentMouseDownHandler = this.onDocumentMouseDown.bind( this );
7664 this.onInputEditHandler = OO.ui.debounce( this.updateItemVisibility.bind( this ), 100 );
7665 this.highlightOnFilter = !!config.highlightOnFilter;
7666 this.lastHighlightedItem = null;
7667 this.width = config.width;
7668 this.filterMode = config.filterMode;
7669
7670 // Initialization
7671 this.$element.addClass( 'oo-ui-menuSelectWidget' );
7672 if ( config.widget ) {
7673 this.setFocusOwner( config.widget.$tabIndexed );
7674 }
7675
7676 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
7677 // that reference properties not initialized at that time of parent class construction
7678 // TODO: Find a better way to handle post-constructor setup
7679 this.visible = false;
7680 this.$element.addClass( 'oo-ui-element-hidden' );
7681 this.$focusOwner.attr( 'aria-expanded', 'false' );
7682 };
7683
7684 /* Setup */
7685
7686 OO.inheritClass( OO.ui.MenuSelectWidget, OO.ui.SelectWidget );
7687 OO.mixinClass( OO.ui.MenuSelectWidget, OO.ui.mixin.ClippableElement );
7688 OO.mixinClass( OO.ui.MenuSelectWidget, OO.ui.mixin.FloatableElement );
7689
7690 /* Events */
7691
7692 /**
7693 * @event ready
7694 *
7695 * The menu is ready: it is visible and has been positioned and clipped.
7696 */
7697
7698 /* Static properties */
7699
7700 /**
7701 * Positions to flip to if there isn't room in the container for the
7702 * menu in a specific direction.
7703 *
7704 * @property {Object.<string,string>}
7705 */
7706 OO.ui.MenuSelectWidget.static.flippedPositions = {
7707 below: 'above',
7708 above: 'below',
7709 top: 'bottom',
7710 bottom: 'top'
7711 };
7712
7713 /* Methods */
7714
7715 /**
7716 * Handles document mouse down events.
7717 *
7718 * @protected
7719 * @param {MouseEvent} e Mouse down event
7720 */
7721 OO.ui.MenuSelectWidget.prototype.onDocumentMouseDown = function ( e ) {
7722 if (
7723 this.isVisible() &&
7724 !OO.ui.contains(
7725 this.$element.add( this.$widget ).add( this.$autoCloseIgnore ).get(),
7726 e.target,
7727 true
7728 )
7729 ) {
7730 this.toggle( false );
7731 }
7732 };
7733
7734 /**
7735 * @inheritdoc
7736 */
7737 OO.ui.MenuSelectWidget.prototype.onDocumentKeyDown = function ( e ) {
7738 var currentItem = this.findHighlightedItem() || this.findSelectedItem();
7739
7740 if ( !this.isDisabled() && this.isVisible() ) {
7741 switch ( e.keyCode ) {
7742 case OO.ui.Keys.LEFT:
7743 case OO.ui.Keys.RIGHT:
7744 // Do nothing if a text field is associated, arrow keys will be handled natively
7745 if ( !this.$input ) {
7746 OO.ui.MenuSelectWidget.parent.prototype.onDocumentKeyDown.call( this, e );
7747 }
7748 break;
7749 case OO.ui.Keys.ESCAPE:
7750 case OO.ui.Keys.TAB:
7751 if ( currentItem && !this.multiselect ) {
7752 currentItem.setHighlighted( false );
7753 }
7754 this.toggle( false );
7755 // Don't prevent tabbing away, prevent defocusing
7756 if ( e.keyCode === OO.ui.Keys.ESCAPE ) {
7757 e.preventDefault();
7758 e.stopPropagation();
7759 }
7760 break;
7761 default:
7762 OO.ui.MenuSelectWidget.parent.prototype.onDocumentKeyDown.call( this, e );
7763 return;
7764 }
7765 }
7766 };
7767
7768 /**
7769 * Update menu item visibility and clipping after input changes (if filterFromInput is enabled)
7770 * or after items were added/removed (always).
7771 *
7772 * @protected
7773 */
7774 OO.ui.MenuSelectWidget.prototype.updateItemVisibility = function () {
7775 var i, item, items, visible, section, sectionEmpty, filter, exactFilter,
7776 anyVisible = false,
7777 len = this.items.length,
7778 showAll = !this.isVisible(),
7779 exactMatch = false;
7780
7781 if ( this.$input && this.filterFromInput ) {
7782 filter = showAll ? null : this.getItemMatcher( this.$input.val(), this.filterMode );
7783 exactFilter = this.getItemMatcher( this.$input.val(), 'exact' );
7784 // Hide non-matching options, and also hide section headers if all options
7785 // in their section are hidden.
7786 for ( i = 0; i < len; i++ ) {
7787 item = this.items[ i ];
7788 if ( item instanceof OO.ui.MenuSectionOptionWidget ) {
7789 if ( section ) {
7790 // If the previous section was empty, hide its header
7791 section.toggle( showAll || !sectionEmpty );
7792 }
7793 section = item;
7794 sectionEmpty = true;
7795 } else if ( item instanceof OO.ui.OptionWidget ) {
7796 visible = showAll || filter( item );
7797 exactMatch = exactMatch || exactFilter( item );
7798 anyVisible = anyVisible || visible;
7799 sectionEmpty = sectionEmpty && !visible;
7800 item.toggle( visible );
7801 }
7802 }
7803 // Process the final section
7804 if ( section ) {
7805 section.toggle( showAll || !sectionEmpty );
7806 }
7807
7808 if ( !anyVisible ) {
7809 this.highlightItem( null );
7810 }
7811
7812 this.$element.toggleClass( 'oo-ui-menuSelectWidget-invisible', !anyVisible );
7813
7814 if (
7815 this.highlightOnFilter &&
7816 !( this.lastHighlightedItem && this.lastHighlightedItem.isVisible() )
7817 ) {
7818 // Highlight the first item on the list
7819 item = null;
7820 items = this.getItems();
7821 for ( i = 0; i < items.length; i++ ) {
7822 if ( items[ i ].isVisible() ) {
7823 item = items[ i ];
7824 break;
7825 }
7826 }
7827 this.highlightItem( item );
7828 this.lastHighlightedItem = item;
7829 }
7830
7831 }
7832
7833 // Reevaluate clipping
7834 this.clip();
7835 };
7836
7837 /**
7838 * @inheritdoc
7839 */
7840 OO.ui.MenuSelectWidget.prototype.bindDocumentKeyDownListener = function () {
7841 if ( this.$input ) {
7842 this.$input.on( 'keydown', this.onDocumentKeyDownHandler );
7843 } else {
7844 OO.ui.MenuSelectWidget.parent.prototype.bindDocumentKeyDownListener.call( this );
7845 }
7846 };
7847
7848 /**
7849 * @inheritdoc
7850 */
7851 OO.ui.MenuSelectWidget.prototype.unbindDocumentKeyDownListener = function () {
7852 if ( this.$input ) {
7853 this.$input.off( 'keydown', this.onDocumentKeyDownHandler );
7854 } else {
7855 OO.ui.MenuSelectWidget.parent.prototype.unbindDocumentKeyDownListener.call( this );
7856 }
7857 };
7858
7859 /**
7860 * @inheritdoc
7861 */
7862 OO.ui.MenuSelectWidget.prototype.bindDocumentKeyPressListener = function () {
7863 if ( this.$input ) {
7864 if ( this.filterFromInput ) {
7865 this.$input.on(
7866 'keydown mouseup cut paste change input select',
7867 this.onInputEditHandler
7868 );
7869 this.updateItemVisibility();
7870 }
7871 } else {
7872 OO.ui.MenuSelectWidget.parent.prototype.bindDocumentKeyPressListener.call( this );
7873 }
7874 };
7875
7876 /**
7877 * @inheritdoc
7878 */
7879 OO.ui.MenuSelectWidget.prototype.unbindDocumentKeyPressListener = function () {
7880 if ( this.$input ) {
7881 if ( this.filterFromInput ) {
7882 this.$input.off(
7883 'keydown mouseup cut paste change input select',
7884 this.onInputEditHandler
7885 );
7886 this.updateItemVisibility();
7887 }
7888 } else {
7889 OO.ui.MenuSelectWidget.parent.prototype.unbindDocumentKeyPressListener.call( this );
7890 }
7891 };
7892
7893 /**
7894 * Choose an item.
7895 *
7896 * When a user chooses an item, the menu is closed, unless the hideOnChoose config option is
7897 * set to false.
7898 *
7899 * Note that ‘choose’ should never be modified programmatically. A user can choose an option with
7900 * the keyboard or mouse and it becomes selected. To select an item programmatically,
7901 * use the #selectItem method.
7902 *
7903 * @param {OO.ui.OptionWidget} item Item to choose
7904 * @chainable
7905 * @return {OO.ui.Widget} The widget, for chaining
7906 */
7907 OO.ui.MenuSelectWidget.prototype.chooseItem = function ( item ) {
7908 OO.ui.MenuSelectWidget.parent.prototype.chooseItem.call( this, item );
7909 if ( this.hideOnChoose ) {
7910 this.toggle( false );
7911 }
7912 return this;
7913 };
7914
7915 /**
7916 * @inheritdoc
7917 */
7918 OO.ui.MenuSelectWidget.prototype.addItems = function ( items, index ) {
7919 // Parent method
7920 OO.ui.MenuSelectWidget.parent.prototype.addItems.call( this, items, index );
7921
7922 this.updateItemVisibility();
7923
7924 return this;
7925 };
7926
7927 /**
7928 * @inheritdoc
7929 */
7930 OO.ui.MenuSelectWidget.prototype.removeItems = function ( items ) {
7931 // Parent method
7932 OO.ui.MenuSelectWidget.parent.prototype.removeItems.call( this, items );
7933
7934 this.updateItemVisibility();
7935
7936 return this;
7937 };
7938
7939 /**
7940 * @inheritdoc
7941 */
7942 OO.ui.MenuSelectWidget.prototype.clearItems = function () {
7943 // Parent method
7944 OO.ui.MenuSelectWidget.parent.prototype.clearItems.call( this );
7945
7946 this.updateItemVisibility();
7947
7948 return this;
7949 };
7950
7951 /**
7952 * Toggle visibility of the menu. The menu is initially hidden and must be shown by calling
7953 * `.toggle( true )` after its #$element is attached to the DOM.
7954 *
7955 * Do not show the menu while it is not attached to the DOM. The calculations required to display
7956 * it in the right place and with the right dimensions only work correctly while it is attached.
7957 * Side-effects may include broken interface and exceptions being thrown. This wasn't always
7958 * strictly enforced, so currently it only generates a warning in the browser console.
7959 *
7960 * @fires ready
7961 * @inheritdoc
7962 */
7963 OO.ui.MenuSelectWidget.prototype.toggle = function ( visible ) {
7964 var change, originalHeight, flippedHeight, selectedItem;
7965
7966 visible = ( visible === undefined ? !this.visible : !!visible ) && !!this.items.length;
7967 change = visible !== this.isVisible();
7968
7969 if ( visible && !this.warnedUnattached && !this.isElementAttached() ) {
7970 OO.ui.warnDeprecation( 'MenuSelectWidget#toggle: Before calling this method, the menu must be attached to the DOM.' );
7971 this.warnedUnattached = true;
7972 }
7973
7974 if ( change && visible ) {
7975 // Reset position before showing the popup again. It's possible we no longer need to flip
7976 // (e.g. if the user scrolled).
7977 this.setVerticalPosition( this.originalVerticalPosition );
7978 }
7979
7980 // Parent method
7981 OO.ui.MenuSelectWidget.parent.prototype.toggle.call( this, visible );
7982
7983 if ( change ) {
7984 if ( visible ) {
7985
7986 if ( this.width ) {
7987 this.setIdealSize( this.width );
7988 } else if ( this.$floatableContainer ) {
7989 this.$clippable.css( 'width', 'auto' );
7990 this.setIdealSize(
7991 this.$floatableContainer[ 0 ].offsetWidth > this.$clippable[ 0 ].offsetWidth ?
7992 // Dropdown is smaller than handle so expand to width
7993 this.$floatableContainer[ 0 ].offsetWidth :
7994 // Dropdown is larger than handle so auto size
7995 'auto'
7996 );
7997 this.$clippable.css( 'width', '' );
7998 }
7999
8000 this.togglePositioning( !!this.$floatableContainer );
8001 this.toggleClipping( true );
8002
8003 this.bindDocumentKeyDownListener();
8004 this.bindDocumentKeyPressListener();
8005
8006 if (
8007 ( this.isClippedVertically() || this.isFloatableOutOfView() ) &&
8008 this.originalVerticalPosition !== 'center'
8009 ) {
8010 // If opening the menu in one direction causes it to be clipped, flip it
8011 originalHeight = this.$element.height();
8012 this.setVerticalPosition(
8013 this.constructor.static.flippedPositions[ this.originalVerticalPosition ]
8014 );
8015 if ( this.isClippedVertically() || this.isFloatableOutOfView() ) {
8016 // If flipping also causes it to be clipped, open in whichever direction
8017 // we have more space
8018 flippedHeight = this.$element.height();
8019 if ( originalHeight > flippedHeight ) {
8020 this.setVerticalPosition( this.originalVerticalPosition );
8021 }
8022 }
8023 }
8024 // Note that we do not flip the menu's opening direction if the clipping changes
8025 // later (e.g. after the user scrolls), that seems like it would be annoying
8026
8027 this.$focusOwner.attr( 'aria-expanded', 'true' );
8028
8029 selectedItem = this.findSelectedItem();
8030 if ( !this.multiselect && selectedItem ) {
8031 // TODO: Verify if this is even needed; This is already done on highlight changes
8032 // in SelectWidget#highlightItem, so we should just need to highlight the item
8033 // we need to highlight here and not bother with attr or checking selections.
8034 this.$focusOwner.attr( 'aria-activedescendant', selectedItem.getElementId() );
8035 selectedItem.scrollElementIntoView( { duration: 0 } );
8036 }
8037
8038 // Auto-hide
8039 if ( this.autoHide ) {
8040 this.getElementDocument().addEventListener( 'mousedown', this.onDocumentMouseDownHandler, true );
8041 }
8042
8043 this.emit( 'ready' );
8044 } else {
8045 this.$focusOwner.removeAttr( 'aria-activedescendant' );
8046 this.unbindDocumentKeyDownListener();
8047 this.unbindDocumentKeyPressListener();
8048 this.$focusOwner.attr( 'aria-expanded', 'false' );
8049 this.getElementDocument().removeEventListener( 'mousedown', this.onDocumentMouseDownHandler, true );
8050 this.togglePositioning( false );
8051 this.toggleClipping( false );
8052 this.lastHighlightedItem = null;
8053 }
8054 }
8055
8056 return this;
8057 };
8058
8059 /**
8060 * Scroll to the top of the menu
8061 */
8062 OO.ui.MenuSelectWidget.prototype.scrollToTop = function () {
8063 this.$element.scrollTop( 0 );
8064 };
8065
8066 /**
8067 * DropdownWidgets are not menus themselves, rather they contain a menu of options created with
8068 * OO.ui.MenuOptionWidget. The DropdownWidget takes care of opening and displaying the menu so that
8069 * users can interact with it.
8070 *
8071 * If you want to use this within an HTML form, such as a OO.ui.FormLayout, use
8072 * OO.ui.DropdownInputWidget instead.
8073 *
8074 * @example
8075 * // A DropdownWidget with a menu that contains three options.
8076 * var dropDown = new OO.ui.DropdownWidget( {
8077 * label: 'Dropdown menu: Select a menu option',
8078 * menu: {
8079 * items: [
8080 * new OO.ui.MenuOptionWidget( {
8081 * data: 'a',
8082 * label: 'First'
8083 * } ),
8084 * new OO.ui.MenuOptionWidget( {
8085 * data: 'b',
8086 * label: 'Second'
8087 * } ),
8088 * new OO.ui.MenuOptionWidget( {
8089 * data: 'c',
8090 * label: 'Third'
8091 * } )
8092 * ]
8093 * }
8094 * } );
8095 *
8096 * $( document.body ).append( dropDown.$element );
8097 *
8098 * dropDown.getMenu().selectItemByData( 'b' );
8099 *
8100 * dropDown.getMenu().findSelectedItem().getData(); // Returns 'b'.
8101 *
8102 * For more information, please see the [OOUI documentation on MediaWiki] [1].
8103 *
8104 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options#Menu_selects_and_options
8105 *
8106 * @class
8107 * @extends OO.ui.Widget
8108 * @mixins OO.ui.mixin.IconElement
8109 * @mixins OO.ui.mixin.IndicatorElement
8110 * @mixins OO.ui.mixin.LabelElement
8111 * @mixins OO.ui.mixin.TitledElement
8112 * @mixins OO.ui.mixin.TabIndexedElement
8113 *
8114 * @constructor
8115 * @param {Object} [config] Configuration options
8116 * @cfg {Object} [menu] Configuration options to pass to
8117 * {@link OO.ui.MenuSelectWidget menu select widget}.
8118 * @cfg {jQuery|boolean} [$overlay] Render the menu into a separate layer. This configuration is
8119 * useful in cases where the expanded menu is larger than its containing `<div>`. The specified
8120 * overlay layer is usually on top of the containing `<div>` and has a larger area. By default,
8121 * the menu uses relative positioning. Pass 'true' to use the default overlay.
8122 * See <https://www.mediawiki.org/wiki/OOUI/Concepts#Overlays>.
8123 */
8124 OO.ui.DropdownWidget = function OoUiDropdownWidget( config ) {
8125 // Configuration initialization
8126 config = $.extend( { indicator: 'down' }, config );
8127
8128 // Parent constructor
8129 OO.ui.DropdownWidget.parent.call( this, config );
8130
8131 // Properties (must be set before TabIndexedElement constructor call)
8132 this.$handle = $( '<span>' );
8133 this.$overlay = ( config.$overlay === true ?
8134 OO.ui.getDefaultOverlay() : config.$overlay ) || this.$element;
8135
8136 // Mixin constructors
8137 OO.ui.mixin.IconElement.call( this, config );
8138 OO.ui.mixin.IndicatorElement.call( this, config );
8139 OO.ui.mixin.LabelElement.call( this, config );
8140 OO.ui.mixin.TitledElement.call( this, $.extend( {
8141 $titled: this.$label
8142 }, config ) );
8143 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {
8144 $tabIndexed: this.$handle
8145 }, config ) );
8146
8147 // Properties
8148 this.menu = new OO.ui.MenuSelectWidget( $.extend( {
8149 widget: this,
8150 $floatableContainer: this.$element
8151 }, config.menu ) );
8152
8153 // Events
8154 this.$handle.on( {
8155 click: this.onClick.bind( this ),
8156 keydown: this.onKeyDown.bind( this ),
8157 // Hack? Handle type-to-search when menu is not expanded and not handling its own events.
8158 keypress: this.menu.onDocumentKeyPressHandler,
8159 blur: this.menu.clearKeyPressBuffer.bind( this.menu )
8160 } );
8161 this.menu.connect( this, {
8162 select: 'onMenuSelect',
8163 toggle: 'onMenuToggle'
8164 } );
8165
8166 // Initialization
8167 this.$label
8168 .attr( {
8169 role: 'textbox',
8170 'aria-readonly': 'true'
8171 } );
8172 this.$handle
8173 .addClass( 'oo-ui-dropdownWidget-handle' )
8174 .append( this.$icon, this.$label, this.$indicator )
8175 .attr( {
8176 role: 'combobox',
8177 'aria-autocomplete': 'list',
8178 'aria-expanded': 'false',
8179 'aria-haspopup': 'true',
8180 'aria-owns': this.menu.getElementId()
8181 } );
8182 this.$element
8183 .addClass( 'oo-ui-dropdownWidget' )
8184 .append( this.$handle );
8185 this.$overlay.append( this.menu.$element );
8186 };
8187
8188 /* Setup */
8189
8190 OO.inheritClass( OO.ui.DropdownWidget, OO.ui.Widget );
8191 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.IconElement );
8192 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.IndicatorElement );
8193 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.LabelElement );
8194 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.TitledElement );
8195 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.TabIndexedElement );
8196
8197 /* Methods */
8198
8199 /**
8200 * Get the menu.
8201 *
8202 * @return {OO.ui.MenuSelectWidget} Menu of widget
8203 */
8204 OO.ui.DropdownWidget.prototype.getMenu = function () {
8205 return this.menu;
8206 };
8207
8208 /**
8209 * Handles menu select events.
8210 *
8211 * @private
8212 * @param {OO.ui.MenuOptionWidget} item Selected menu item
8213 */
8214 OO.ui.DropdownWidget.prototype.onMenuSelect = function ( item ) {
8215 var selectedLabel;
8216
8217 if ( !item ) {
8218 this.setLabel( null );
8219 return;
8220 }
8221
8222 selectedLabel = item.getLabel();
8223
8224 // If the label is a DOM element, clone it, because setLabel will append() it
8225 if ( selectedLabel instanceof $ ) {
8226 selectedLabel = selectedLabel.clone();
8227 }
8228
8229 this.setLabel( selectedLabel );
8230 };
8231
8232 /**
8233 * Handle menu toggle events.
8234 *
8235 * @private
8236 * @param {boolean} isVisible Open state of the menu
8237 */
8238 OO.ui.DropdownWidget.prototype.onMenuToggle = function ( isVisible ) {
8239 this.$element.toggleClass( 'oo-ui-dropdownWidget-open', isVisible );
8240 };
8241
8242 /**
8243 * Handle mouse click events.
8244 *
8245 * @private
8246 * @param {jQuery.Event} e Mouse click event
8247 * @return {undefined|boolean} False to prevent default if event is handled
8248 */
8249 OO.ui.DropdownWidget.prototype.onClick = function ( e ) {
8250 if ( !this.isDisabled() && e.which === OO.ui.MouseButtons.LEFT ) {
8251 this.menu.toggle();
8252 }
8253 return false;
8254 };
8255
8256 /**
8257 * Handle key down events.
8258 *
8259 * @private
8260 * @param {jQuery.Event} e Key down event
8261 * @return {undefined|boolean} False to prevent default if event is handled
8262 */
8263 OO.ui.DropdownWidget.prototype.onKeyDown = function ( e ) {
8264 if (
8265 !this.isDisabled() &&
8266 (
8267 e.which === OO.ui.Keys.ENTER ||
8268 (
8269 e.which === OO.ui.Keys.SPACE &&
8270 // Avoid conflicts with type-to-search, see SelectWidget#onKeyPress.
8271 // Space only closes the menu is the user is not typing to search.
8272 this.menu.keyPressBuffer === ''
8273 ) ||
8274 (
8275 !this.menu.isVisible() &&
8276 (
8277 e.which === OO.ui.Keys.UP ||
8278 e.which === OO.ui.Keys.DOWN
8279 )
8280 )
8281 )
8282 ) {
8283 this.menu.toggle();
8284 return false;
8285 }
8286 };
8287
8288 /**
8289 * RadioOptionWidget is an option widget that looks like a radio button.
8290 * The class is used with OO.ui.RadioSelectWidget to create a selection of radio options.
8291 * Please see the [OOUI documentation on MediaWiki] [1] for more information.
8292 *
8293 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options#Button_selects_and_option
8294 *
8295 * @class
8296 * @extends OO.ui.OptionWidget
8297 *
8298 * @constructor
8299 * @param {Object} [config] Configuration options
8300 */
8301 OO.ui.RadioOptionWidget = function OoUiRadioOptionWidget( config ) {
8302 // Configuration initialization
8303 config = config || {};
8304
8305 // Properties (must be done before parent constructor which calls #setDisabled)
8306 this.radio = new OO.ui.RadioInputWidget( { value: config.data, tabIndex: -1 } );
8307
8308 // Parent constructor
8309 OO.ui.RadioOptionWidget.parent.call( this, config );
8310
8311 // Initialization
8312 // Remove implicit role, we're handling it ourselves
8313 this.radio.$input.attr( 'role', 'presentation' );
8314 this.$element
8315 .addClass( 'oo-ui-radioOptionWidget' )
8316 .attr( 'role', 'radio' )
8317 .attr( 'aria-checked', 'false' )
8318 .removeAttr( 'aria-selected' )
8319 .prepend( this.radio.$element );
8320 };
8321
8322 /* Setup */
8323
8324 OO.inheritClass( OO.ui.RadioOptionWidget, OO.ui.OptionWidget );
8325
8326 /* Static Properties */
8327
8328 /**
8329 * @static
8330 * @inheritdoc
8331 */
8332 OO.ui.RadioOptionWidget.static.highlightable = false;
8333
8334 /**
8335 * @static
8336 * @inheritdoc
8337 */
8338 OO.ui.RadioOptionWidget.static.scrollIntoViewOnSelect = true;
8339
8340 /**
8341 * @static
8342 * @inheritdoc
8343 */
8344 OO.ui.RadioOptionWidget.static.pressable = false;
8345
8346 /**
8347 * @static
8348 * @inheritdoc
8349 */
8350 OO.ui.RadioOptionWidget.static.tagName = 'label';
8351
8352 /* Methods */
8353
8354 /**
8355 * @inheritdoc
8356 */
8357 OO.ui.RadioOptionWidget.prototype.setSelected = function ( state ) {
8358 OO.ui.RadioOptionWidget.parent.prototype.setSelected.call( this, state );
8359
8360 this.radio.setSelected( state );
8361 this.$element
8362 .attr( 'aria-checked', state.toString() )
8363 .removeAttr( 'aria-selected' );
8364
8365 return this;
8366 };
8367
8368 /**
8369 * @inheritdoc
8370 */
8371 OO.ui.RadioOptionWidget.prototype.setDisabled = function ( disabled ) {
8372 OO.ui.RadioOptionWidget.parent.prototype.setDisabled.call( this, disabled );
8373
8374 this.radio.setDisabled( this.isDisabled() );
8375
8376 return this;
8377 };
8378
8379 /**
8380 * RadioSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains radio
8381 * options and is used together with OO.ui.RadioOptionWidget. The RadioSelectWidget provides
8382 * an interface for adding, removing and selecting options.
8383 * Please see the [OOUI documentation on MediaWiki][1] for more information.
8384 *
8385 * If you want to use this within an HTML form, such as a OO.ui.FormLayout, use
8386 * OO.ui.RadioSelectInputWidget instead.
8387 *
8388 * @example
8389 * // A RadioSelectWidget with RadioOptions.
8390 * var option1 = new OO.ui.RadioOptionWidget( {
8391 * data: 'a',
8392 * label: 'Selected radio option'
8393 * } ),
8394 * option2 = new OO.ui.RadioOptionWidget( {
8395 * data: 'b',
8396 * label: 'Unselected radio option'
8397 * } );
8398 * radioSelect = new OO.ui.RadioSelectWidget( {
8399 * items: [ option1, option2 ]
8400 * } );
8401 *
8402 * // Select 'option 1' using the RadioSelectWidget's selectItem() method.
8403 * radioSelect.selectItem( option1 );
8404 *
8405 * $( document.body ).append( radioSelect.$element );
8406 *
8407 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options
8408
8409 *
8410 * @class
8411 * @extends OO.ui.SelectWidget
8412 * @mixins OO.ui.mixin.TabIndexedElement
8413 *
8414 * @constructor
8415 * @param {Object} [config] Configuration options
8416 */
8417 OO.ui.RadioSelectWidget = function OoUiRadioSelectWidget( config ) {
8418 // Parent constructor
8419 OO.ui.RadioSelectWidget.parent.call( this, config );
8420
8421 // Mixin constructors
8422 OO.ui.mixin.TabIndexedElement.call( this, config );
8423
8424 // Events
8425 this.$element.on( {
8426 focus: this.bindDocumentKeyDownListener.bind( this ),
8427 blur: this.unbindDocumentKeyDownListener.bind( this )
8428 } );
8429
8430 // Initialization
8431 this.$element
8432 .addClass( 'oo-ui-radioSelectWidget' )
8433 .attr( 'role', 'radiogroup' );
8434 };
8435
8436 /* Setup */
8437
8438 OO.inheritClass( OO.ui.RadioSelectWidget, OO.ui.SelectWidget );
8439 OO.mixinClass( OO.ui.RadioSelectWidget, OO.ui.mixin.TabIndexedElement );
8440
8441 /**
8442 * MultioptionWidgets are special elements that can be selected and configured with data. The
8443 * data is often unique for each option, but it does not have to be. MultioptionWidgets are used
8444 * with OO.ui.SelectWidget to create a selection of mutually exclusive options. For more information
8445 * and examples, please see the [OOUI documentation on MediaWiki][1].
8446 *
8447 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options
8448 *
8449 * @class
8450 * @extends OO.ui.Widget
8451 * @mixins OO.ui.mixin.ItemWidget
8452 * @mixins OO.ui.mixin.LabelElement
8453 * @mixins OO.ui.mixin.TitledElement
8454 *
8455 * @constructor
8456 * @param {Object} [config] Configuration options
8457 * @cfg {boolean} [selected=false] Whether the option is initially selected
8458 */
8459 OO.ui.MultioptionWidget = function OoUiMultioptionWidget( config ) {
8460 // Configuration initialization
8461 config = config || {};
8462
8463 // Parent constructor
8464 OO.ui.MultioptionWidget.parent.call( this, config );
8465
8466 // Mixin constructors
8467 OO.ui.mixin.ItemWidget.call( this );
8468 OO.ui.mixin.LabelElement.call( this, config );
8469 OO.ui.mixin.TitledElement.call( this, config );
8470
8471 // Properties
8472 this.selected = null;
8473
8474 // Initialization
8475 this.$element
8476 .addClass( 'oo-ui-multioptionWidget' )
8477 .append( this.$label );
8478 this.setSelected( config.selected );
8479 };
8480
8481 /* Setup */
8482
8483 OO.inheritClass( OO.ui.MultioptionWidget, OO.ui.Widget );
8484 OO.mixinClass( OO.ui.MultioptionWidget, OO.ui.mixin.ItemWidget );
8485 OO.mixinClass( OO.ui.MultioptionWidget, OO.ui.mixin.LabelElement );
8486 OO.mixinClass( OO.ui.MultioptionWidget, OO.ui.mixin.TitledElement );
8487
8488 /* Events */
8489
8490 /**
8491 * @event change
8492 *
8493 * A change event is emitted when the selected state of the option changes.
8494 *
8495 * @param {boolean} selected Whether the option is now selected
8496 */
8497
8498 /* Methods */
8499
8500 /**
8501 * Check if the option is selected.
8502 *
8503 * @return {boolean} Item is selected
8504 */
8505 OO.ui.MultioptionWidget.prototype.isSelected = function () {
8506 return this.selected;
8507 };
8508
8509 /**
8510 * Set the option’s selected state. In general, all modifications to the selection
8511 * should be handled by the SelectWidget’s
8512 * {@link OO.ui.SelectWidget#selectItem selectItem( [item] )} method instead of this method.
8513 *
8514 * @param {boolean} [state=false] Select option
8515 * @chainable
8516 * @return {OO.ui.Widget} The widget, for chaining
8517 */
8518 OO.ui.MultioptionWidget.prototype.setSelected = function ( state ) {
8519 state = !!state;
8520 if ( this.selected !== state ) {
8521 this.selected = state;
8522 this.emit( 'change', state );
8523 this.$element.toggleClass( 'oo-ui-multioptionWidget-selected', state );
8524 }
8525 return this;
8526 };
8527
8528 /**
8529 * MultiselectWidget allows selecting multiple options from a list.
8530 *
8531 * For more information about menus and options, please see the [OOUI documentation
8532 * on MediaWiki][1].
8533 *
8534 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options#Menu_selects_and_options
8535 *
8536 * @class
8537 * @abstract
8538 * @extends OO.ui.Widget
8539 * @mixins OO.ui.mixin.GroupWidget
8540 * @mixins OO.ui.mixin.TitledElement
8541 *
8542 * @constructor
8543 * @param {Object} [config] Configuration options
8544 * @cfg {OO.ui.MultioptionWidget[]} [items] An array of options to add to the multiselect.
8545 */
8546 OO.ui.MultiselectWidget = function OoUiMultiselectWidget( config ) {
8547 // Parent constructor
8548 OO.ui.MultiselectWidget.parent.call( this, config );
8549
8550 // Configuration initialization
8551 config = config || {};
8552
8553 // Mixin constructors
8554 OO.ui.mixin.GroupWidget.call( this, config );
8555 OO.ui.mixin.TitledElement.call( this, config );
8556
8557 // Events
8558 this.aggregate( {
8559 change: 'select'
8560 } );
8561 // This is mostly for compatibility with TagMultiselectWidget... normally, 'change' is emitted
8562 // by GroupElement only when items are added/removed
8563 this.connect( this, {
8564 select: [ 'emit', 'change' ]
8565 } );
8566
8567 // Initialization
8568 if ( config.items ) {
8569 this.addItems( config.items );
8570 }
8571 this.$group.addClass( 'oo-ui-multiselectWidget-group' );
8572 this.$element.addClass( 'oo-ui-multiselectWidget' )
8573 .append( this.$group );
8574 };
8575
8576 /* Setup */
8577
8578 OO.inheritClass( OO.ui.MultiselectWidget, OO.ui.Widget );
8579 OO.mixinClass( OO.ui.MultiselectWidget, OO.ui.mixin.GroupWidget );
8580 OO.mixinClass( OO.ui.MultiselectWidget, OO.ui.mixin.TitledElement );
8581
8582 /* Events */
8583
8584 /**
8585 * @event change
8586 *
8587 * A change event is emitted when the set of items changes, or an item is selected or deselected.
8588 */
8589
8590 /**
8591 * @event select
8592 *
8593 * A select event is emitted when an item is selected or deselected.
8594 */
8595
8596 /* Methods */
8597
8598 /**
8599 * Find options that are selected.
8600 *
8601 * @return {OO.ui.MultioptionWidget[]} Selected options
8602 */
8603 OO.ui.MultiselectWidget.prototype.findSelectedItems = function () {
8604 return this.items.filter( function ( item ) {
8605 return item.isSelected();
8606 } );
8607 };
8608
8609 /**
8610 * Find the data of options that are selected.
8611 *
8612 * @return {Object[]|string[]} Values of selected options
8613 */
8614 OO.ui.MultiselectWidget.prototype.findSelectedItemsData = function () {
8615 return this.findSelectedItems().map( function ( item ) {
8616 return item.data;
8617 } );
8618 };
8619
8620 /**
8621 * Select options by reference. Options not mentioned in the `items` array will be deselected.
8622 *
8623 * @param {OO.ui.MultioptionWidget[]} items Items to select
8624 * @chainable
8625 * @return {OO.ui.Widget} The widget, for chaining
8626 */
8627 OO.ui.MultiselectWidget.prototype.selectItems = function ( items ) {
8628 this.items.forEach( function ( item ) {
8629 var selected = items.indexOf( item ) !== -1;
8630 item.setSelected( selected );
8631 } );
8632 return this;
8633 };
8634
8635 /**
8636 * Select items by their data. Options not mentioned in the `datas` array will be deselected.
8637 *
8638 * @param {Object[]|string[]} datas Values of items to select
8639 * @chainable
8640 * @return {OO.ui.Widget} The widget, for chaining
8641 */
8642 OO.ui.MultiselectWidget.prototype.selectItemsByData = function ( datas ) {
8643 var items,
8644 widget = this;
8645 items = datas.map( function ( data ) {
8646 return widget.findItemFromData( data );
8647 } );
8648 this.selectItems( items );
8649 return this;
8650 };
8651
8652 /**
8653 * CheckboxMultioptionWidget is an option widget that looks like a checkbox.
8654 * The class is used with OO.ui.CheckboxMultiselectWidget to create a selection of checkbox options.
8655 * Please see the [OOUI documentation on MediaWiki] [1] for more information.
8656 *
8657 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options#Button_selects_and_option
8658 *
8659 * @class
8660 * @extends OO.ui.MultioptionWidget
8661 *
8662 * @constructor
8663 * @param {Object} [config] Configuration options
8664 */
8665 OO.ui.CheckboxMultioptionWidget = function OoUiCheckboxMultioptionWidget( config ) {
8666 // Configuration initialization
8667 config = config || {};
8668
8669 // Properties (must be done before parent constructor which calls #setDisabled)
8670 this.checkbox = new OO.ui.CheckboxInputWidget();
8671
8672 // Parent constructor
8673 OO.ui.CheckboxMultioptionWidget.parent.call( this, config );
8674
8675 // Events
8676 this.checkbox.on( 'change', this.onCheckboxChange.bind( this ) );
8677 this.$element.on( 'keydown', this.onKeyDown.bind( this ) );
8678
8679 // Initialization
8680 this.$element
8681 .addClass( 'oo-ui-checkboxMultioptionWidget' )
8682 .prepend( this.checkbox.$element );
8683 };
8684
8685 /* Setup */
8686
8687 OO.inheritClass( OO.ui.CheckboxMultioptionWidget, OO.ui.MultioptionWidget );
8688
8689 /* Static Properties */
8690
8691 /**
8692 * @static
8693 * @inheritdoc
8694 */
8695 OO.ui.CheckboxMultioptionWidget.static.tagName = 'label';
8696
8697 /* Methods */
8698
8699 /**
8700 * Handle checkbox selected state change.
8701 *
8702 * @private
8703 */
8704 OO.ui.CheckboxMultioptionWidget.prototype.onCheckboxChange = function () {
8705 this.setSelected( this.checkbox.isSelected() );
8706 };
8707
8708 /**
8709 * @inheritdoc
8710 */
8711 OO.ui.CheckboxMultioptionWidget.prototype.setSelected = function ( state ) {
8712 OO.ui.CheckboxMultioptionWidget.parent.prototype.setSelected.call( this, state );
8713 this.checkbox.setSelected( state );
8714 return this;
8715 };
8716
8717 /**
8718 * @inheritdoc
8719 */
8720 OO.ui.CheckboxMultioptionWidget.prototype.setDisabled = function ( disabled ) {
8721 OO.ui.CheckboxMultioptionWidget.parent.prototype.setDisabled.call( this, disabled );
8722 this.checkbox.setDisabled( this.isDisabled() );
8723 return this;
8724 };
8725
8726 /**
8727 * Focus the widget.
8728 */
8729 OO.ui.CheckboxMultioptionWidget.prototype.focus = function () {
8730 this.checkbox.focus();
8731 };
8732
8733 /**
8734 * Handle key down events.
8735 *
8736 * @protected
8737 * @param {jQuery.Event} e
8738 */
8739 OO.ui.CheckboxMultioptionWidget.prototype.onKeyDown = function ( e ) {
8740 var
8741 element = this.getElementGroup(),
8742 nextItem;
8743
8744 if ( e.keyCode === OO.ui.Keys.LEFT || e.keyCode === OO.ui.Keys.UP ) {
8745 nextItem = element.getRelativeFocusableItem( this, -1 );
8746 } else if ( e.keyCode === OO.ui.Keys.RIGHT || e.keyCode === OO.ui.Keys.DOWN ) {
8747 nextItem = element.getRelativeFocusableItem( this, 1 );
8748 }
8749
8750 if ( nextItem ) {
8751 e.preventDefault();
8752 nextItem.focus();
8753 }
8754 };
8755
8756 /**
8757 * CheckboxMultiselectWidget is a {@link OO.ui.MultiselectWidget multiselect widget} that contains
8758 * checkboxes and is used together with OO.ui.CheckboxMultioptionWidget. The
8759 * CheckboxMultiselectWidget provides an interface for adding, removing and selecting options.
8760 * Please see the [OOUI documentation on MediaWiki][1] for more information.
8761 *
8762 * If you want to use this within an HTML form, such as a OO.ui.FormLayout, use
8763 * OO.ui.CheckboxMultiselectInputWidget instead.
8764 *
8765 * @example
8766 * // A CheckboxMultiselectWidget with CheckboxMultioptions.
8767 * var option1 = new OO.ui.CheckboxMultioptionWidget( {
8768 * data: 'a',
8769 * selected: true,
8770 * label: 'Selected checkbox'
8771 * } ),
8772 * option2 = new OO.ui.CheckboxMultioptionWidget( {
8773 * data: 'b',
8774 * label: 'Unselected checkbox'
8775 * } ),
8776 * multiselect = new OO.ui.CheckboxMultiselectWidget( {
8777 * items: [ option1, option2 ]
8778 * } );
8779 * $( document.body ).append( multiselect.$element );
8780 *
8781 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options
8782 *
8783 * @class
8784 * @extends OO.ui.MultiselectWidget
8785 *
8786 * @constructor
8787 * @param {Object} [config] Configuration options
8788 */
8789 OO.ui.CheckboxMultiselectWidget = function OoUiCheckboxMultiselectWidget( config ) {
8790 // Parent constructor
8791 OO.ui.CheckboxMultiselectWidget.parent.call( this, config );
8792
8793 // Properties
8794 this.$lastClicked = null;
8795
8796 // Events
8797 this.$group.on( 'click', this.onClick.bind( this ) );
8798
8799 // Initialization
8800 this.$element.addClass( 'oo-ui-checkboxMultiselectWidget' );
8801 };
8802
8803 /* Setup */
8804
8805 OO.inheritClass( OO.ui.CheckboxMultiselectWidget, OO.ui.MultiselectWidget );
8806
8807 /* Methods */
8808
8809 /**
8810 * Get an option by its position relative to the specified item (or to the start of the
8811 * option array, if item is `null`). The direction in which to search through the option array
8812 * is specified with a number: -1 for reverse (the default) or 1 for forward. The method will
8813 * return an option, or `null` if there are no options in the array.
8814 *
8815 * @param {OO.ui.CheckboxMultioptionWidget|null} item Item to describe the start position, or
8816 * `null` to start at the beginning of the array.
8817 * @param {number} direction Direction to move in: -1 to move backward, 1 to move forward
8818 * @return {OO.ui.CheckboxMultioptionWidget|null} Item at position, `null` if there are no items
8819 * in the select.
8820 */
8821 OO.ui.CheckboxMultiselectWidget.prototype.getRelativeFocusableItem = function ( item, direction ) {
8822 var currentIndex, nextIndex, i,
8823 increase = direction > 0 ? 1 : -1,
8824 len = this.items.length;
8825
8826 if ( item ) {
8827 currentIndex = this.items.indexOf( item );
8828 nextIndex = ( currentIndex + increase + len ) % len;
8829 } else {
8830 // If no item is selected and moving forward, start at the beginning.
8831 // If moving backward, start at the end.
8832 nextIndex = direction > 0 ? 0 : len - 1;
8833 }
8834
8835 for ( i = 0; i < len; i++ ) {
8836 item = this.items[ nextIndex ];
8837 if ( item && !item.isDisabled() ) {
8838 return item;
8839 }
8840 nextIndex = ( nextIndex + increase + len ) % len;
8841 }
8842 return null;
8843 };
8844
8845 /**
8846 * Handle click events on checkboxes.
8847 *
8848 * @param {jQuery.Event} e
8849 */
8850 OO.ui.CheckboxMultiselectWidget.prototype.onClick = function ( e ) {
8851 var $options, lastClickedIndex, nowClickedIndex, i, direction, wasSelected, items,
8852 $lastClicked = this.$lastClicked,
8853 $nowClicked = $( e.target ).closest( '.oo-ui-checkboxMultioptionWidget' )
8854 .not( '.oo-ui-widget-disabled' );
8855
8856 // Allow selecting multiple options at once by Shift-clicking them
8857 if ( $lastClicked && $nowClicked.length && e.shiftKey ) {
8858 $options = this.$group.find( '.oo-ui-checkboxMultioptionWidget' );
8859 lastClickedIndex = $options.index( $lastClicked );
8860 nowClickedIndex = $options.index( $nowClicked );
8861 // If it's the same item, either the user is being silly, or it's a fake event generated
8862 // by the browser. In either case we don't need custom handling.
8863 if ( nowClickedIndex !== lastClickedIndex ) {
8864 items = this.items;
8865 wasSelected = items[ nowClickedIndex ].isSelected();
8866 direction = nowClickedIndex > lastClickedIndex ? 1 : -1;
8867
8868 // This depends on the DOM order of the items and the order of the .items array being
8869 // the same.
8870 for ( i = lastClickedIndex; i !== nowClickedIndex; i += direction ) {
8871 if ( !items[ i ].isDisabled() ) {
8872 items[ i ].setSelected( !wasSelected );
8873 }
8874 }
8875 // For the now-clicked element, use immediate timeout to allow the browser to do its own
8876 // handling first, then set our value. The order in which events happen is different for
8877 // clicks on the <input> and on the <label> and there are additional fake clicks fired
8878 // for non-click actions that change the checkboxes.
8879 e.preventDefault();
8880 setTimeout( function () {
8881 if ( !items[ nowClickedIndex ].isDisabled() ) {
8882 items[ nowClickedIndex ].setSelected( !wasSelected );
8883 }
8884 } );
8885 }
8886 }
8887
8888 if ( $nowClicked.length ) {
8889 this.$lastClicked = $nowClicked;
8890 }
8891 };
8892
8893 /**
8894 * Focus the widget
8895 *
8896 * @chainable
8897 * @return {OO.ui.Widget} The widget, for chaining
8898 */
8899 OO.ui.CheckboxMultiselectWidget.prototype.focus = function () {
8900 var item;
8901 if ( !this.isDisabled() ) {
8902 item = this.getRelativeFocusableItem( null, 1 );
8903 if ( item ) {
8904 item.focus();
8905 }
8906 }
8907 return this;
8908 };
8909
8910 /**
8911 * @inheritdoc
8912 */
8913 OO.ui.CheckboxMultiselectWidget.prototype.simulateLabelClick = function () {
8914 this.focus();
8915 };
8916
8917 /**
8918 * Progress bars visually display the status of an operation, such as a download,
8919 * and can be either determinate or indeterminate:
8920 *
8921 * - **determinate** process bars show the percent of an operation that is complete.
8922 *
8923 * - **indeterminate** process bars use a visual display of motion to indicate that an operation
8924 * is taking place. Because the extent of an indeterminate operation is unknown, the bar does
8925 * not use percentages.
8926 *
8927 * The value of the `progress` configuration determines whether the bar is determinate
8928 * or indeterminate.
8929 *
8930 * @example
8931 * // Examples of determinate and indeterminate progress bars.
8932 * var progressBar1 = new OO.ui.ProgressBarWidget( {
8933 * progress: 33
8934 * } );
8935 * var progressBar2 = new OO.ui.ProgressBarWidget();
8936 *
8937 * // Create a FieldsetLayout to layout progress bars.
8938 * var fieldset = new OO.ui.FieldsetLayout;
8939 * fieldset.addItems( [
8940 * new OO.ui.FieldLayout( progressBar1, {
8941 * label: 'Determinate',
8942 * align: 'top'
8943 * } ),
8944 * new OO.ui.FieldLayout( progressBar2, {
8945 * label: 'Indeterminate',
8946 * align: 'top'
8947 * } )
8948 * ] );
8949 * $( document.body ).append( fieldset.$element );
8950 *
8951 * @class
8952 * @extends OO.ui.Widget
8953 *
8954 * @constructor
8955 * @param {Object} [config] Configuration options
8956 * @cfg {number|boolean} [progress=false] The type of progress bar (determinate or indeterminate).
8957 * To create a determinate progress bar, specify a number that reflects the initial
8958 * percent complete.
8959 * By default, the progress bar is indeterminate.
8960 */
8961 OO.ui.ProgressBarWidget = function OoUiProgressBarWidget( config ) {
8962 // Configuration initialization
8963 config = config || {};
8964
8965 // Parent constructor
8966 OO.ui.ProgressBarWidget.parent.call( this, config );
8967
8968 // Properties
8969 this.$bar = $( '<div>' );
8970 this.progress = null;
8971
8972 // Initialization
8973 this.setProgress( config.progress !== undefined ? config.progress : false );
8974 this.$bar.addClass( 'oo-ui-progressBarWidget-bar' );
8975 this.$element
8976 .attr( {
8977 role: 'progressbar',
8978 'aria-valuemin': 0,
8979 'aria-valuemax': 100
8980 } )
8981 .addClass( 'oo-ui-progressBarWidget' )
8982 .append( this.$bar );
8983 };
8984
8985 /* Setup */
8986
8987 OO.inheritClass( OO.ui.ProgressBarWidget, OO.ui.Widget );
8988
8989 /* Static Properties */
8990
8991 /**
8992 * @static
8993 * @inheritdoc
8994 */
8995 OO.ui.ProgressBarWidget.static.tagName = 'div';
8996
8997 /* Methods */
8998
8999 /**
9000 * Get the percent of the progress that has been completed. Indeterminate progresses will
9001 * return `false`.
9002 *
9003 * @return {number|boolean} Progress percent
9004 */
9005 OO.ui.ProgressBarWidget.prototype.getProgress = function () {
9006 return this.progress;
9007 };
9008
9009 /**
9010 * Set the percent of the process completed or `false` for an indeterminate process.
9011 *
9012 * @param {number|boolean} progress Progress percent or `false` for indeterminate
9013 */
9014 OO.ui.ProgressBarWidget.prototype.setProgress = function ( progress ) {
9015 this.progress = progress;
9016
9017 if ( progress !== false ) {
9018 this.$bar.css( 'width', this.progress + '%' );
9019 this.$element.attr( 'aria-valuenow', this.progress );
9020 } else {
9021 this.$bar.css( 'width', '' );
9022 this.$element.removeAttr( 'aria-valuenow' );
9023 }
9024 this.$element.toggleClass( 'oo-ui-progressBarWidget-indeterminate', progress === false );
9025 };
9026
9027 /**
9028 * InputWidget is the base class for all input widgets, which
9029 * include {@link OO.ui.TextInputWidget text inputs}, {@link OO.ui.CheckboxInputWidget checkbox
9030 * inputs}, {@link OO.ui.RadioInputWidget radio inputs}, and
9031 * {@link OO.ui.ButtonInputWidget button inputs}.
9032 * See the [OOUI documentation on MediaWiki] [1] for more information and examples.
9033 *
9034 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
9035 *
9036 * @abstract
9037 * @class
9038 * @extends OO.ui.Widget
9039 * @mixins OO.ui.mixin.TabIndexedElement
9040 * @mixins OO.ui.mixin.TitledElement
9041 * @mixins OO.ui.mixin.AccessKeyedElement
9042 *
9043 * @constructor
9044 * @param {Object} [config] Configuration options
9045 * @cfg {string} [name=''] The value of the input’s HTML `name` attribute.
9046 * @cfg {string} [value=''] The value of the input.
9047 * @cfg {string} [dir] The directionality of the input (ltr/rtl).
9048 * @cfg {string} [inputId] The value of the input’s HTML `id` attribute.
9049 * @cfg {Function} [inputFilter] The name of an input filter function. Input filters modify the
9050 * value of an input before it is accepted.
9051 */
9052 OO.ui.InputWidget = function OoUiInputWidget( config ) {
9053 // Configuration initialization
9054 config = config || {};
9055
9056 // Parent constructor
9057 OO.ui.InputWidget.parent.call( this, config );
9058
9059 // Properties
9060 // See #reusePreInfuseDOM about config.$input
9061 this.$input = config.$input || this.getInputElement( config );
9062 this.value = '';
9063 this.inputFilter = config.inputFilter;
9064
9065 // Mixin constructors
9066 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {
9067 $tabIndexed: this.$input
9068 }, config ) );
9069 OO.ui.mixin.TitledElement.call( this, $.extend( {
9070 $titled: this.$input
9071 }, config ) );
9072 OO.ui.mixin.AccessKeyedElement.call( this, $.extend( {
9073 $accessKeyed: this.$input
9074 }, config ) );
9075
9076 // Events
9077 this.$input.on( 'keydown mouseup cut paste change input select', this.onEdit.bind( this ) );
9078
9079 // Initialization
9080 this.$input
9081 .addClass( 'oo-ui-inputWidget-input' )
9082 .attr( 'name', config.name )
9083 .prop( 'disabled', this.isDisabled() );
9084 this.$element
9085 .addClass( 'oo-ui-inputWidget' )
9086 .append( this.$input );
9087 this.setValue( config.value );
9088 if ( config.dir ) {
9089 this.setDir( config.dir );
9090 }
9091 if ( config.inputId !== undefined ) {
9092 this.setInputId( config.inputId );
9093 }
9094 };
9095
9096 /* Setup */
9097
9098 OO.inheritClass( OO.ui.InputWidget, OO.ui.Widget );
9099 OO.mixinClass( OO.ui.InputWidget, OO.ui.mixin.TabIndexedElement );
9100 OO.mixinClass( OO.ui.InputWidget, OO.ui.mixin.TitledElement );
9101 OO.mixinClass( OO.ui.InputWidget, OO.ui.mixin.AccessKeyedElement );
9102
9103 /* Static Methods */
9104
9105 /**
9106 * @inheritdoc
9107 */
9108 OO.ui.InputWidget.static.reusePreInfuseDOM = function ( node, config ) {
9109 config = OO.ui.InputWidget.parent.static.reusePreInfuseDOM( node, config );
9110 // Reusing `$input` lets browsers preserve inputted values across page reloads, see T114134.
9111 config.$input = $( node ).find( '.oo-ui-inputWidget-input' );
9112 return config;
9113 };
9114
9115 /**
9116 * @inheritdoc
9117 */
9118 OO.ui.InputWidget.static.gatherPreInfuseState = function ( node, config ) {
9119 var state = OO.ui.InputWidget.parent.static.gatherPreInfuseState( node, config );
9120 if ( config.$input && config.$input.length ) {
9121 state.value = config.$input.val();
9122 // Might be better in TabIndexedElement, but it's awkward to do there because
9123 // mixins are awkward
9124 state.focus = config.$input.is( ':focus' );
9125 }
9126 return state;
9127 };
9128
9129 /* Events */
9130
9131 /**
9132 * @event change
9133 *
9134 * A change event is emitted when the value of the input changes.
9135 *
9136 * @param {string} value
9137 */
9138
9139 /* Methods */
9140
9141 /**
9142 * Get input element.
9143 *
9144 * Subclasses of OO.ui.InputWidget use the `config` parameter to produce different elements in
9145 * different circumstances. The element must have a `value` property (like form elements).
9146 *
9147 * @protected
9148 * @param {Object} config Configuration options
9149 * @return {jQuery} Input element
9150 */
9151 OO.ui.InputWidget.prototype.getInputElement = function () {
9152 return $( '<input>' );
9153 };
9154
9155 /**
9156 * Handle potentially value-changing events.
9157 *
9158 * @private
9159 * @param {jQuery.Event} e Key down, mouse up, cut, paste, change, input, or select event
9160 */
9161 OO.ui.InputWidget.prototype.onEdit = function () {
9162 var widget = this;
9163 if ( !this.isDisabled() ) {
9164 // Allow the stack to clear so the value will be updated
9165 setTimeout( function () {
9166 widget.setValue( widget.$input.val() );
9167 } );
9168 }
9169 };
9170
9171 /**
9172 * Get the value of the input.
9173 *
9174 * @return {string} Input value
9175 */
9176 OO.ui.InputWidget.prototype.getValue = function () {
9177 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
9178 // it, and we won't know unless they're kind enough to trigger a 'change' event.
9179 var value = this.$input.val();
9180 if ( this.value !== value ) {
9181 this.setValue( value );
9182 }
9183 return this.value;
9184 };
9185
9186 /**
9187 * Set the directionality of the input.
9188 *
9189 * @param {string} dir Text directionality: 'ltr', 'rtl' or 'auto'
9190 * @chainable
9191 * @return {OO.ui.Widget} The widget, for chaining
9192 */
9193 OO.ui.InputWidget.prototype.setDir = function ( dir ) {
9194 this.$input.prop( 'dir', dir );
9195 return this;
9196 };
9197
9198 /**
9199 * Set the value of the input.
9200 *
9201 * @param {string} value New value
9202 * @fires change
9203 * @chainable
9204 * @return {OO.ui.Widget} The widget, for chaining
9205 */
9206 OO.ui.InputWidget.prototype.setValue = function ( value ) {
9207 value = this.cleanUpValue( value );
9208 // Update the DOM if it has changed. Note that with cleanUpValue, it
9209 // is possible for the DOM value to change without this.value changing.
9210 if ( this.$input.val() !== value ) {
9211 this.$input.val( value );
9212 }
9213 if ( this.value !== value ) {
9214 this.value = value;
9215 this.emit( 'change', this.value );
9216 }
9217 // The first time that the value is set (probably while constructing the widget),
9218 // remember it in defaultValue. This property can be later used to check whether
9219 // the value of the input has been changed since it was created.
9220 if ( this.defaultValue === undefined ) {
9221 this.defaultValue = this.value;
9222 this.$input[ 0 ].defaultValue = this.defaultValue;
9223 }
9224 return this;
9225 };
9226
9227 /**
9228 * Clean up incoming value.
9229 *
9230 * Ensures value is a string, and converts undefined and null to empty string.
9231 *
9232 * @private
9233 * @param {string} value Original value
9234 * @return {string} Cleaned up value
9235 */
9236 OO.ui.InputWidget.prototype.cleanUpValue = function ( value ) {
9237 if ( value === undefined || value === null ) {
9238 return '';
9239 } else if ( this.inputFilter ) {
9240 return this.inputFilter( String( value ) );
9241 } else {
9242 return String( value );
9243 }
9244 };
9245
9246 /**
9247 * @inheritdoc
9248 */
9249 OO.ui.InputWidget.prototype.setDisabled = function ( state ) {
9250 OO.ui.InputWidget.parent.prototype.setDisabled.call( this, state );
9251 if ( this.$input ) {
9252 this.$input.prop( 'disabled', this.isDisabled() );
9253 }
9254 return this;
9255 };
9256
9257 /**
9258 * Set the 'id' attribute of the `<input>` element.
9259 *
9260 * @param {string} id
9261 * @chainable
9262 * @return {OO.ui.Widget} The widget, for chaining
9263 */
9264 OO.ui.InputWidget.prototype.setInputId = function ( id ) {
9265 this.$input.attr( 'id', id );
9266 return this;
9267 };
9268
9269 /**
9270 * @inheritdoc
9271 */
9272 OO.ui.InputWidget.prototype.restorePreInfuseState = function ( state ) {
9273 OO.ui.InputWidget.parent.prototype.restorePreInfuseState.call( this, state );
9274 if ( state.value !== undefined && state.value !== this.getValue() ) {
9275 this.setValue( state.value );
9276 }
9277 if ( state.focus ) {
9278 this.focus();
9279 }
9280 };
9281
9282 /**
9283 * Data widget intended for creating `<input type="hidden">` inputs.
9284 *
9285 * @class
9286 * @extends OO.ui.Widget
9287 *
9288 * @constructor
9289 * @param {Object} [config] Configuration options
9290 * @cfg {string} [value=''] The value of the input.
9291 * @cfg {string} [name=''] The value of the input’s HTML `name` attribute.
9292 */
9293 OO.ui.HiddenInputWidget = function OoUiHiddenInputWidget( config ) {
9294 // Configuration initialization
9295 config = $.extend( { value: '', name: '' }, config );
9296
9297 // Parent constructor
9298 OO.ui.HiddenInputWidget.parent.call( this, config );
9299
9300 // Initialization
9301 this.$element.attr( {
9302 type: 'hidden',
9303 value: config.value,
9304 name: config.name
9305 } );
9306 this.$element.removeAttr( 'aria-disabled' );
9307 };
9308
9309 /* Setup */
9310
9311 OO.inheritClass( OO.ui.HiddenInputWidget, OO.ui.Widget );
9312
9313 /* Static Properties */
9314
9315 /**
9316 * @static
9317 * @inheritdoc
9318 */
9319 OO.ui.HiddenInputWidget.static.tagName = 'input';
9320
9321 /**
9322 * ButtonInputWidget is used to submit HTML forms and is intended to be used within
9323 * a OO.ui.FormLayout. If you do not need the button to work with HTML forms, you probably
9324 * want to use OO.ui.ButtonWidget instead. Button input widgets can be rendered as either an
9325 * HTML `<button>` (the default) or an HTML `<input>` tags. See the
9326 * [OOUI documentation on MediaWiki] [1] for more information.
9327 *
9328 * @example
9329 * // A ButtonInputWidget rendered as an HTML button, the default.
9330 * var button = new OO.ui.ButtonInputWidget( {
9331 * label: 'Input button',
9332 * icon: 'check',
9333 * value: 'check'
9334 * } );
9335 * $( document.body ).append( button.$element );
9336 *
9337 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs#Button_inputs
9338 *
9339 * @class
9340 * @extends OO.ui.InputWidget
9341 * @mixins OO.ui.mixin.ButtonElement
9342 * @mixins OO.ui.mixin.IconElement
9343 * @mixins OO.ui.mixin.IndicatorElement
9344 * @mixins OO.ui.mixin.LabelElement
9345 * @mixins OO.ui.mixin.FlaggedElement
9346 *
9347 * @constructor
9348 * @param {Object} [config] Configuration options
9349 * @cfg {string} [type='button'] The value of the HTML `'type'` attribute:
9350 * 'button', 'submit' or 'reset'.
9351 * @cfg {boolean} [useInputTag=false] Use an `<input>` tag instead of a `<button>` tag, the default.
9352 * Widgets configured to be an `<input>` do not support {@link #icon icons} and
9353 * {@link #indicator indicators},
9354 * non-plaintext {@link #label labels}, or {@link #value values}. In general, useInputTag should
9355 * only be set to `true` when there’s need to support IE 6 in a form with multiple buttons.
9356 */
9357 OO.ui.ButtonInputWidget = function OoUiButtonInputWidget( config ) {
9358 // Configuration initialization
9359 config = $.extend( { type: 'button', useInputTag: false }, config );
9360
9361 // See InputWidget#reusePreInfuseDOM about config.$input
9362 if ( config.$input ) {
9363 config.$input.empty();
9364 }
9365
9366 // Properties (must be set before parent constructor, which calls #setValue)
9367 this.useInputTag = config.useInputTag;
9368
9369 // Parent constructor
9370 OO.ui.ButtonInputWidget.parent.call( this, config );
9371
9372 // Mixin constructors
9373 OO.ui.mixin.ButtonElement.call( this, $.extend( {
9374 $button: this.$input
9375 }, config ) );
9376 OO.ui.mixin.IconElement.call( this, config );
9377 OO.ui.mixin.IndicatorElement.call( this, config );
9378 OO.ui.mixin.LabelElement.call( this, config );
9379 OO.ui.mixin.FlaggedElement.call( this, config );
9380
9381 // Initialization
9382 if ( !config.useInputTag ) {
9383 this.$input.append( this.$icon, this.$label, this.$indicator );
9384 }
9385 this.$element.addClass( 'oo-ui-buttonInputWidget' );
9386 };
9387
9388 /* Setup */
9389
9390 OO.inheritClass( OO.ui.ButtonInputWidget, OO.ui.InputWidget );
9391 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.ButtonElement );
9392 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.IconElement );
9393 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.IndicatorElement );
9394 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.LabelElement );
9395 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.FlaggedElement );
9396
9397 /* Static Properties */
9398
9399 /**
9400 * @static
9401 * @inheritdoc
9402 */
9403 OO.ui.ButtonInputWidget.static.tagName = 'span';
9404
9405 /* Methods */
9406
9407 /**
9408 * @inheritdoc
9409 * @protected
9410 */
9411 OO.ui.ButtonInputWidget.prototype.getInputElement = function ( config ) {
9412 var type;
9413 type = [ 'button', 'submit', 'reset' ].indexOf( config.type ) !== -1 ? config.type : 'button';
9414 return $( '<' + ( config.useInputTag ? 'input' : 'button' ) + ' type="' + type + '">' );
9415 };
9416
9417 /**
9418 * Set label value.
9419 *
9420 * If #useInputTag is `true`, the label is set as the `value` of the `<input>` tag.
9421 *
9422 * @param {jQuery|string|Function|null} label Label nodes, text, a function that returns nodes or
9423 * text, or `null` for no label
9424 * @chainable
9425 * @return {OO.ui.Widget} The widget, for chaining
9426 */
9427 OO.ui.ButtonInputWidget.prototype.setLabel = function ( label ) {
9428 if ( typeof label === 'function' ) {
9429 label = OO.ui.resolveMsg( label );
9430 }
9431
9432 if ( this.useInputTag ) {
9433 // Discard non-plaintext labels
9434 if ( typeof label !== 'string' ) {
9435 label = '';
9436 }
9437
9438 this.$input.val( label );
9439 }
9440
9441 return OO.ui.mixin.LabelElement.prototype.setLabel.call( this, label );
9442 };
9443
9444 /**
9445 * Set the value of the input.
9446 *
9447 * This method is disabled for button inputs configured as {@link #useInputTag <input> tags}, as
9448 * they do not support {@link #value values}.
9449 *
9450 * @param {string} value New value
9451 * @chainable
9452 * @return {OO.ui.Widget} The widget, for chaining
9453 */
9454 OO.ui.ButtonInputWidget.prototype.setValue = function ( value ) {
9455 if ( !this.useInputTag ) {
9456 OO.ui.ButtonInputWidget.parent.prototype.setValue.call( this, value );
9457 }
9458 return this;
9459 };
9460
9461 /**
9462 * @inheritdoc
9463 */
9464 OO.ui.ButtonInputWidget.prototype.getInputId = function () {
9465 // Disable generating `<label>` elements for buttons. One would very rarely need additional
9466 // label for a button, and it's already a big clickable target, and it causes
9467 // unexpected rendering.
9468 return null;
9469 };
9470
9471 /**
9472 * CheckboxInputWidgets, like HTML checkboxes, can be selected and/or configured with a value.
9473 * Note that these {@link OO.ui.InputWidget input widgets} are best laid out
9474 * in {@link OO.ui.FieldLayout field layouts} that use the {@link OO.ui.FieldLayout#align inline}
9475 * alignment. For more information, please see the [OOUI documentation on MediaWiki][1].
9476 *
9477 * This widget can be used inside an HTML form, such as a OO.ui.FormLayout.
9478 *
9479 * @example
9480 * // An example of selected, unselected, and disabled checkbox inputs.
9481 * var checkbox1 = new OO.ui.CheckboxInputWidget( {
9482 * value: 'a',
9483 * selected: true
9484 * } ),
9485 * checkbox2 = new OO.ui.CheckboxInputWidget( {
9486 * value: 'b'
9487 * } ),
9488 * checkbox3 = new OO.ui.CheckboxInputWidget( {
9489 * value:'c',
9490 * disabled: true
9491 * } ),
9492 * // Create a fieldset layout with fields for each checkbox.
9493 * fieldset = new OO.ui.FieldsetLayout( {
9494 * label: 'Checkboxes'
9495 * } );
9496 * fieldset.addItems( [
9497 * new OO.ui.FieldLayout( checkbox1, { label: 'Selected checkbox', align: 'inline' } ),
9498 * new OO.ui.FieldLayout( checkbox2, { label: 'Unselected checkbox', align: 'inline' } ),
9499 * new OO.ui.FieldLayout( checkbox3, { label: 'Disabled checkbox', align: 'inline' } ),
9500 * ] );
9501 * $( document.body ).append( fieldset.$element );
9502 *
9503 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
9504 *
9505 * @class
9506 * @extends OO.ui.InputWidget
9507 *
9508 * @constructor
9509 * @param {Object} [config] Configuration options
9510 * @cfg {boolean} [selected=false] Select the checkbox initially. By default, the checkbox is
9511 * not selected.
9512 * @cfg {boolean} [indeterminate=false] Whether the checkbox is in the indeterminate state.
9513 */
9514 OO.ui.CheckboxInputWidget = function OoUiCheckboxInputWidget( config ) {
9515 // Configuration initialization
9516 config = config || {};
9517
9518 // Parent constructor
9519 OO.ui.CheckboxInputWidget.parent.call( this, config );
9520
9521 // Properties
9522 this.checkIcon = new OO.ui.IconWidget( {
9523 icon: 'check',
9524 classes: [ 'oo-ui-checkboxInputWidget-checkIcon' ]
9525 } );
9526
9527 // Initialization
9528 this.$element
9529 .addClass( 'oo-ui-checkboxInputWidget' )
9530 // Required for pretty styling in WikimediaUI theme
9531 .append( this.checkIcon.$element );
9532 this.setSelected( config.selected !== undefined ? config.selected : false );
9533 this.setIndeterminate( config.indeterminate !== undefined ? config.indeterminate : false );
9534 };
9535
9536 /* Setup */
9537
9538 OO.inheritClass( OO.ui.CheckboxInputWidget, OO.ui.InputWidget );
9539
9540 /* Events */
9541
9542 /**
9543 * @event change
9544 *
9545 * A change event is emitted when the state of the input changes.
9546 *
9547 * @param {boolean} selected
9548 * @param {boolean} indeterminate
9549 */
9550
9551 /* Static Properties */
9552
9553 /**
9554 * @static
9555 * @inheritdoc
9556 */
9557 OO.ui.CheckboxInputWidget.static.tagName = 'span';
9558
9559 /* Static Methods */
9560
9561 /**
9562 * @inheritdoc
9563 */
9564 OO.ui.CheckboxInputWidget.static.gatherPreInfuseState = function ( node, config ) {
9565 var state = OO.ui.CheckboxInputWidget.parent.static.gatherPreInfuseState( node, config );
9566 state.checked = config.$input.prop( 'checked' );
9567 return state;
9568 };
9569
9570 /* Methods */
9571
9572 /**
9573 * @inheritdoc
9574 * @protected
9575 */
9576 OO.ui.CheckboxInputWidget.prototype.getInputElement = function () {
9577 return $( '<input>' ).attr( 'type', 'checkbox' );
9578 };
9579
9580 /**
9581 * @inheritdoc
9582 */
9583 OO.ui.CheckboxInputWidget.prototype.onEdit = function () {
9584 var widget = this;
9585 if ( !this.isDisabled() ) {
9586 // Allow the stack to clear so the value will be updated
9587 setTimeout( function () {
9588 widget.setSelected( widget.$input.prop( 'checked' ) );
9589 widget.setIndeterminate( widget.$input.prop( 'indeterminate' ) );
9590 } );
9591 }
9592 };
9593
9594 /**
9595 * Set selection state of this checkbox.
9596 *
9597 * @param {boolean} state Selected state
9598 * @param {boolean} internal Used for internal calls to suppress events
9599 * @chainable
9600 * @return {OO.ui.CheckboxInputWidget} The widget, for chaining
9601 */
9602 OO.ui.CheckboxInputWidget.prototype.setSelected = function ( state, internal ) {
9603 state = !!state;
9604 if ( this.selected !== state ) {
9605 this.selected = state;
9606 this.$input.prop( 'checked', this.selected );
9607 if ( !internal ) {
9608 this.setIndeterminate( false, true );
9609 this.emit( 'change', this.selected, this.indeterminate );
9610 }
9611 }
9612 // The first time that the selection state is set (probably while constructing the widget),
9613 // remember it in defaultSelected. This property can be later used to check whether
9614 // the selection state of the input has been changed since it was created.
9615 if ( this.defaultSelected === undefined ) {
9616 this.defaultSelected = this.selected;
9617 this.$input[ 0 ].defaultChecked = this.defaultSelected;
9618 }
9619 return this;
9620 };
9621
9622 /**
9623 * Check if this checkbox is selected.
9624 *
9625 * @return {boolean} Checkbox is selected
9626 */
9627 OO.ui.CheckboxInputWidget.prototype.isSelected = function () {
9628 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
9629 // it, and we won't know unless they're kind enough to trigger a 'change' event.
9630 var selected = this.$input.prop( 'checked' );
9631 if ( this.selected !== selected ) {
9632 this.setSelected( selected );
9633 }
9634 return this.selected;
9635 };
9636
9637 /**
9638 * Set indeterminate state of this checkbox.
9639 *
9640 * @param {boolean} state Indeterminate state
9641 * @param {boolean} internal Used for internal calls to suppress events
9642 * @chainable
9643 * @return {OO.ui.CheckboxInputWidget} The widget, for chaining
9644 */
9645 OO.ui.CheckboxInputWidget.prototype.setIndeterminate = function ( state, internal ) {
9646 state = !!state;
9647 if ( this.indeterminate !== state ) {
9648 this.indeterminate = state;
9649 this.$input.prop( 'indeterminate', this.indeterminate );
9650 if ( !internal ) {
9651 this.setSelected( false, true );
9652 this.emit( 'change', this.selected, this.indeterminate );
9653 }
9654 }
9655 return this;
9656 };
9657
9658 /**
9659 * Check if this checkbox is selected.
9660 *
9661 * @return {boolean} Checkbox is selected
9662 */
9663 OO.ui.CheckboxInputWidget.prototype.isIndeterminate = function () {
9664 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
9665 // it, and we won't know unless they're kind enough to trigger a 'change' event.
9666 var indeterminate = this.$input.prop( 'indeterminate' );
9667 if ( this.indeterminate !== indeterminate ) {
9668 this.setIndeterminate( indeterminate );
9669 }
9670 return this.indeterminate;
9671 };
9672
9673 /**
9674 * @inheritdoc
9675 */
9676 OO.ui.CheckboxInputWidget.prototype.simulateLabelClick = function () {
9677 if ( !this.isDisabled() ) {
9678 this.$handle.trigger( 'click' );
9679 }
9680 this.focus();
9681 };
9682
9683 /**
9684 * @inheritdoc
9685 */
9686 OO.ui.CheckboxInputWidget.prototype.restorePreInfuseState = function ( state ) {
9687 OO.ui.CheckboxInputWidget.parent.prototype.restorePreInfuseState.call( this, state );
9688 if ( state.checked !== undefined && state.checked !== this.isSelected() ) {
9689 this.setSelected( state.checked );
9690 }
9691 };
9692
9693 /**
9694 * DropdownInputWidget is a {@link OO.ui.DropdownWidget DropdownWidget} intended to be used
9695 * within an HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with the
9696 * value of a hidden HTML `input` tag. Please see the [OOUI documentation on MediaWiki][1] for
9697 * more information about input widgets.
9698 *
9699 * A DropdownInputWidget always has a value (one of the options is always selected), unless there
9700 * are no options. If no `value` configuration option is provided, the first option is selected.
9701 * If you need a state representing no value (no option being selected), use a DropdownWidget.
9702 *
9703 * This and OO.ui.RadioSelectInputWidget support similar configuration options.
9704 *
9705 * @example
9706 * // A DropdownInputWidget with three options.
9707 * var dropdownInput = new OO.ui.DropdownInputWidget( {
9708 * options: [
9709 * { data: 'a', label: 'First' },
9710 * { data: 'b', label: 'Second', disabled: true },
9711 * { optgroup: 'Group label' },
9712 * { data: 'c', label: 'First sub-item)' }
9713 * ]
9714 * } );
9715 * $( document.body ).append( dropdownInput.$element );
9716 *
9717 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
9718 *
9719 * @class
9720 * @extends OO.ui.InputWidget
9721 *
9722 * @constructor
9723 * @param {Object} [config] Configuration options
9724 * @cfg {Object[]} [options=[]] Array of menu options in the format described above.
9725 * @cfg {Object} [dropdown] Configuration options for {@link OO.ui.DropdownWidget DropdownWidget}
9726 * @cfg {jQuery|boolean} [$overlay] Render the menu into a separate layer. This configuration is
9727 * useful in cases where the expanded menu is larger than its containing `<div>`. The specified
9728 * overlay layer is usually on top of the containing `<div>` and has a larger area. By default,
9729 * the menu uses relative positioning. Pass 'true' to use the default overlay.
9730 * See <https://www.mediawiki.org/wiki/OOUI/Concepts#Overlays>.
9731 */
9732 OO.ui.DropdownInputWidget = function OoUiDropdownInputWidget( config ) {
9733 // Configuration initialization
9734 config = config || {};
9735
9736 // Properties (must be done before parent constructor which calls #setDisabled)
9737 this.dropdownWidget = new OO.ui.DropdownWidget( $.extend(
9738 {
9739 $overlay: config.$overlay
9740 },
9741 config.dropdown
9742 ) );
9743 // Set up the options before parent constructor, which uses them to validate config.value.
9744 // Use this instead of setOptions() because this.$input is not set up yet.
9745 this.setOptionsData( config.options || [] );
9746
9747 // Parent constructor
9748 OO.ui.DropdownInputWidget.parent.call( this, config );
9749
9750 // Events
9751 this.dropdownWidget.getMenu().connect( this, {
9752 select: 'onMenuSelect'
9753 } );
9754
9755 // Initialization
9756 this.$element
9757 .addClass( 'oo-ui-dropdownInputWidget' )
9758 .append( this.dropdownWidget.$element );
9759 if ( OO.ui.isMobile() ) {
9760 this.$element.addClass( 'oo-ui-isMobile' );
9761 }
9762 this.setTabIndexedElement( this.dropdownWidget.$tabIndexed );
9763 this.setTitledElement( this.dropdownWidget.$handle );
9764 };
9765
9766 /* Setup */
9767
9768 OO.inheritClass( OO.ui.DropdownInputWidget, OO.ui.InputWidget );
9769
9770 /* Methods */
9771
9772 /**
9773 * @inheritdoc
9774 * @protected
9775 */
9776 OO.ui.DropdownInputWidget.prototype.getInputElement = function () {
9777 return $( '<select>' ).addClass( 'oo-ui-indicator-down' );
9778 };
9779
9780 /**
9781 * Handles menu select events.
9782 *
9783 * @private
9784 * @param {OO.ui.MenuOptionWidget|null} item Selected menu item
9785 */
9786 OO.ui.DropdownInputWidget.prototype.onMenuSelect = function ( item ) {
9787 this.setValue( item ? item.getData() : '' );
9788 };
9789
9790 /**
9791 * @inheritdoc
9792 */
9793 OO.ui.DropdownInputWidget.prototype.setValue = function ( value ) {
9794 var selected;
9795 value = this.cleanUpValue( value );
9796 // Only allow setting values that are actually present in the dropdown
9797 selected = this.dropdownWidget.getMenu().findItemFromData( value ) ||
9798 this.dropdownWidget.getMenu().findFirstSelectableItem();
9799 this.dropdownWidget.getMenu().selectItem( selected );
9800 value = selected ? selected.getData() : '';
9801 OO.ui.DropdownInputWidget.parent.prototype.setValue.call( this, value );
9802 if ( this.optionsDirty ) {
9803 // We reached this from the constructor or from #setOptions.
9804 // We have to update the <select> element.
9805 this.updateOptionsInterface();
9806 }
9807 return this;
9808 };
9809
9810 /**
9811 * @inheritdoc
9812 */
9813 OO.ui.DropdownInputWidget.prototype.setDisabled = function ( state ) {
9814 this.dropdownWidget.setDisabled( state );
9815 OO.ui.DropdownInputWidget.parent.prototype.setDisabled.call( this, state );
9816 return this;
9817 };
9818
9819 /**
9820 * Set the options available for this input.
9821 *
9822 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
9823 * @chainable
9824 * @return {OO.ui.Widget} The widget, for chaining
9825 */
9826 OO.ui.DropdownInputWidget.prototype.setOptions = function ( options ) {
9827 var value = this.getValue();
9828
9829 this.setOptionsData( options );
9830
9831 // Re-set the value to update the visible interface (DropdownWidget and <select>).
9832 // In case the previous value is no longer an available option, select the first valid one.
9833 this.setValue( value );
9834
9835 return this;
9836 };
9837
9838 /**
9839 * Set the internal list of options, used e.g. by setValue() to see which options are allowed.
9840 *
9841 * This method may be called before the parent constructor, so various properties may not be
9842 * initialized yet.
9843 *
9844 * @param {Object[]} options Array of menu options (see #constructor for details).
9845 * @private
9846 */
9847 OO.ui.DropdownInputWidget.prototype.setOptionsData = function ( options ) {
9848 var optionWidgets, optIndex, opt, previousOptgroup, optionWidget, optValue,
9849 widget = this;
9850
9851 this.optionsDirty = true;
9852
9853 // Go through all the supplied option configs and create either
9854 // MenuSectionOption or MenuOption widgets from each.
9855 optionWidgets = [];
9856 for ( optIndex = 0; optIndex < options.length; optIndex++ ) {
9857 opt = options[ optIndex ];
9858
9859 if ( opt.optgroup !== undefined ) {
9860 // Create a <optgroup> menu item.
9861 optionWidget = widget.createMenuSectionOptionWidget( opt.optgroup );
9862 previousOptgroup = optionWidget;
9863
9864 } else {
9865 // Create a normal <option> menu item.
9866 optValue = widget.cleanUpValue( opt.data );
9867 optionWidget = widget.createMenuOptionWidget(
9868 optValue,
9869 opt.label !== undefined ? opt.label : optValue
9870 );
9871 }
9872
9873 // Disable the menu option if it is itself disabled or if its parent optgroup is disabled.
9874 if (
9875 opt.disabled !== undefined ||
9876 previousOptgroup instanceof OO.ui.MenuSectionOptionWidget &&
9877 previousOptgroup.isDisabled()
9878 ) {
9879 optionWidget.setDisabled( true );
9880 }
9881
9882 optionWidgets.push( optionWidget );
9883 }
9884
9885 this.dropdownWidget.getMenu().clearItems().addItems( optionWidgets );
9886 };
9887
9888 /**
9889 * Create a menu option widget.
9890 *
9891 * @protected
9892 * @param {string} data Item data
9893 * @param {string} label Item label
9894 * @return {OO.ui.MenuOptionWidget} Option widget
9895 */
9896 OO.ui.DropdownInputWidget.prototype.createMenuOptionWidget = function ( data, label ) {
9897 return new OO.ui.MenuOptionWidget( {
9898 data: data,
9899 label: label
9900 } );
9901 };
9902
9903 /**
9904 * Create a menu section option widget.
9905 *
9906 * @protected
9907 * @param {string} label Section item label
9908 * @return {OO.ui.MenuSectionOptionWidget} Menu section option widget
9909 */
9910 OO.ui.DropdownInputWidget.prototype.createMenuSectionOptionWidget = function ( label ) {
9911 return new OO.ui.MenuSectionOptionWidget( {
9912 label: label
9913 } );
9914 };
9915
9916 /**
9917 * Update the user-visible interface to match the internal list of options and value.
9918 *
9919 * This method must only be called after the parent constructor.
9920 *
9921 * @private
9922 */
9923 OO.ui.DropdownInputWidget.prototype.updateOptionsInterface = function () {
9924 var
9925 $optionsContainer = this.$input,
9926 defaultValue = this.defaultValue,
9927 widget = this;
9928
9929 this.$input.empty();
9930
9931 this.dropdownWidget.getMenu().getItems().forEach( function ( optionWidget ) {
9932 var $optionNode;
9933
9934 if ( !( optionWidget instanceof OO.ui.MenuSectionOptionWidget ) ) {
9935 $optionNode = $( '<option>' )
9936 .attr( 'value', optionWidget.getData() )
9937 .text( optionWidget.getLabel() );
9938
9939 // Remember original selection state. This property can be later used to check whether
9940 // the selection state of the input has been changed since it was created.
9941 $optionNode[ 0 ].defaultSelected = ( optionWidget.getData() === defaultValue );
9942
9943 $optionsContainer.append( $optionNode );
9944 } else {
9945 $optionNode = $( '<optgroup>' )
9946 .attr( 'label', optionWidget.getLabel() );
9947 widget.$input.append( $optionNode );
9948 $optionsContainer = $optionNode;
9949 }
9950
9951 // Disable the option or optgroup if required.
9952 if ( optionWidget.isDisabled() ) {
9953 $optionNode.prop( 'disabled', true );
9954 }
9955 } );
9956
9957 this.optionsDirty = false;
9958 };
9959
9960 /**
9961 * @inheritdoc
9962 */
9963 OO.ui.DropdownInputWidget.prototype.focus = function () {
9964 this.dropdownWidget.focus();
9965 return this;
9966 };
9967
9968 /**
9969 * @inheritdoc
9970 */
9971 OO.ui.DropdownInputWidget.prototype.blur = function () {
9972 this.dropdownWidget.blur();
9973 return this;
9974 };
9975
9976 /**
9977 * RadioInputWidget creates a single radio button. Because radio buttons are usually used as a set,
9978 * in most cases you will want to use a {@link OO.ui.RadioSelectWidget radio select}
9979 * with {@link OO.ui.RadioOptionWidget radio options} instead of this class. For more information,
9980 * please see the [OOUI documentation on MediaWiki][1].
9981 *
9982 * This widget can be used inside an HTML form, such as a OO.ui.FormLayout.
9983 *
9984 * @example
9985 * // An example of selected, unselected, and disabled radio inputs
9986 * var radio1 = new OO.ui.RadioInputWidget( {
9987 * value: 'a',
9988 * selected: true
9989 * } );
9990 * var radio2 = new OO.ui.RadioInputWidget( {
9991 * value: 'b'
9992 * } );
9993 * var radio3 = new OO.ui.RadioInputWidget( {
9994 * value: 'c',
9995 * disabled: true
9996 * } );
9997 * // Create a fieldset layout with fields for each radio button.
9998 * var fieldset = new OO.ui.FieldsetLayout( {
9999 * label: 'Radio inputs'
10000 * } );
10001 * fieldset.addItems( [
10002 * new OO.ui.FieldLayout( radio1, { label: 'Selected', align: 'inline' } ),
10003 * new OO.ui.FieldLayout( radio2, { label: 'Unselected', align: 'inline' } ),
10004 * new OO.ui.FieldLayout( radio3, { label: 'Disabled', align: 'inline' } ),
10005 * ] );
10006 * $( document.body ).append( fieldset.$element );
10007 *
10008 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
10009 *
10010 * @class
10011 * @extends OO.ui.InputWidget
10012 *
10013 * @constructor
10014 * @param {Object} [config] Configuration options
10015 * @cfg {boolean} [selected=false] Select the radio button initially. By default, the radio button
10016 * is not selected.
10017 */
10018 OO.ui.RadioInputWidget = function OoUiRadioInputWidget( config ) {
10019 // Configuration initialization
10020 config = config || {};
10021
10022 // Parent constructor
10023 OO.ui.RadioInputWidget.parent.call( this, config );
10024
10025 // Initialization
10026 this.$element
10027 .addClass( 'oo-ui-radioInputWidget' )
10028 // Required for pretty styling in WikimediaUI theme
10029 .append( $( '<span>' ) );
10030 this.setSelected( config.selected !== undefined ? config.selected : false );
10031 };
10032
10033 /* Setup */
10034
10035 OO.inheritClass( OO.ui.RadioInputWidget, OO.ui.InputWidget );
10036
10037 /* Static Properties */
10038
10039 /**
10040 * @static
10041 * @inheritdoc
10042 */
10043 OO.ui.RadioInputWidget.static.tagName = 'span';
10044
10045 /* Static Methods */
10046
10047 /**
10048 * @inheritdoc
10049 */
10050 OO.ui.RadioInputWidget.static.gatherPreInfuseState = function ( node, config ) {
10051 var state = OO.ui.RadioInputWidget.parent.static.gatherPreInfuseState( node, config );
10052 state.checked = config.$input.prop( 'checked' );
10053 return state;
10054 };
10055
10056 /* Methods */
10057
10058 /**
10059 * @inheritdoc
10060 * @protected
10061 */
10062 OO.ui.RadioInputWidget.prototype.getInputElement = function () {
10063 return $( '<input>' ).attr( 'type', 'radio' );
10064 };
10065
10066 /**
10067 * @inheritdoc
10068 */
10069 OO.ui.RadioInputWidget.prototype.onEdit = function () {
10070 // RadioInputWidget doesn't track its state.
10071 };
10072
10073 /**
10074 * Set selection state of this radio button.
10075 *
10076 * @param {boolean} state `true` for selected
10077 * @chainable
10078 * @return {OO.ui.Widget} The widget, for chaining
10079 */
10080 OO.ui.RadioInputWidget.prototype.setSelected = function ( state ) {
10081 // RadioInputWidget doesn't track its state.
10082 this.$input.prop( 'checked', state );
10083 // The first time that the selection state is set (probably while constructing the widget),
10084 // remember it in defaultSelected. This property can be later used to check whether
10085 // the selection state of the input has been changed since it was created.
10086 if ( this.defaultSelected === undefined ) {
10087 this.defaultSelected = state;
10088 this.$input[ 0 ].defaultChecked = this.defaultSelected;
10089 }
10090 return this;
10091 };
10092
10093 /**
10094 * Check if this radio button is selected.
10095 *
10096 * @return {boolean} Radio is selected
10097 */
10098 OO.ui.RadioInputWidget.prototype.isSelected = function () {
10099 return this.$input.prop( 'checked' );
10100 };
10101
10102 /**
10103 * @inheritdoc
10104 */
10105 OO.ui.RadioInputWidget.prototype.simulateLabelClick = function () {
10106 if ( !this.isDisabled() ) {
10107 this.$input.trigger( 'click' );
10108 }
10109 this.focus();
10110 };
10111
10112 /**
10113 * @inheritdoc
10114 */
10115 OO.ui.RadioInputWidget.prototype.restorePreInfuseState = function ( state ) {
10116 OO.ui.RadioInputWidget.parent.prototype.restorePreInfuseState.call( this, state );
10117 if ( state.checked !== undefined && state.checked !== this.isSelected() ) {
10118 this.setSelected( state.checked );
10119 }
10120 };
10121
10122 /**
10123 * RadioSelectInputWidget is a {@link OO.ui.RadioSelectWidget RadioSelectWidget} intended to be
10124 * used within an HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with
10125 * the value of a hidden HTML `input` tag. Please see the [OOUI documentation on MediaWiki][1] for
10126 * more information about input widgets.
10127 *
10128 * This and OO.ui.DropdownInputWidget support similar configuration options.
10129 *
10130 * @example
10131 * // A RadioSelectInputWidget with three options
10132 * var radioSelectInput = new OO.ui.RadioSelectInputWidget( {
10133 * options: [
10134 * { data: 'a', label: 'First' },
10135 * { data: 'b', label: 'Second'},
10136 * { data: 'c', label: 'Third' }
10137 * ]
10138 * } );
10139 * $( document.body ).append( radioSelectInput.$element );
10140 *
10141 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
10142 *
10143 * @class
10144 * @extends OO.ui.InputWidget
10145 *
10146 * @constructor
10147 * @param {Object} [config] Configuration options
10148 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
10149 */
10150 OO.ui.RadioSelectInputWidget = function OoUiRadioSelectInputWidget( config ) {
10151 // Configuration initialization
10152 config = config || {};
10153
10154 // Properties (must be done before parent constructor which calls #setDisabled)
10155 this.radioSelectWidget = new OO.ui.RadioSelectWidget();
10156 // Set up the options before parent constructor, which uses them to validate config.value.
10157 // Use this instead of setOptions() because this.$input is not set up yet
10158 this.setOptionsData( config.options || [] );
10159
10160 // Parent constructor
10161 OO.ui.RadioSelectInputWidget.parent.call( this, config );
10162
10163 // Events
10164 this.radioSelectWidget.connect( this, {
10165 select: 'onMenuSelect'
10166 } );
10167
10168 // Initialization
10169 this.$element
10170 .addClass( 'oo-ui-radioSelectInputWidget' )
10171 .append( this.radioSelectWidget.$element );
10172 this.setTabIndexedElement( this.radioSelectWidget.$tabIndexed );
10173 };
10174
10175 /* Setup */
10176
10177 OO.inheritClass( OO.ui.RadioSelectInputWidget, OO.ui.InputWidget );
10178
10179 /* Static Methods */
10180
10181 /**
10182 * @inheritdoc
10183 */
10184 OO.ui.RadioSelectInputWidget.static.gatherPreInfuseState = function ( node, config ) {
10185 var state = OO.ui.RadioSelectInputWidget.parent.static.gatherPreInfuseState( node, config );
10186 state.value = $( node ).find( '.oo-ui-radioInputWidget .oo-ui-inputWidget-input:checked' ).val();
10187 return state;
10188 };
10189
10190 /**
10191 * @inheritdoc
10192 */
10193 OO.ui.RadioSelectInputWidget.static.reusePreInfuseDOM = function ( node, config ) {
10194 config = OO.ui.RadioSelectInputWidget.parent.static.reusePreInfuseDOM( node, config );
10195 // Cannot reuse the `<input type=radio>` set
10196 delete config.$input;
10197 return config;
10198 };
10199
10200 /* Methods */
10201
10202 /**
10203 * @inheritdoc
10204 * @protected
10205 */
10206 OO.ui.RadioSelectInputWidget.prototype.getInputElement = function () {
10207 // Use this instead of <input type="hidden">, because hidden inputs do not have separate
10208 // 'value' and 'defaultValue' properties, and InputWidget wants to handle 'defaultValue'.
10209 return $( '<input>' ).addClass( 'oo-ui-element-hidden' );
10210 };
10211
10212 /**
10213 * Handles menu select events.
10214 *
10215 * @private
10216 * @param {OO.ui.RadioOptionWidget} item Selected menu item
10217 */
10218 OO.ui.RadioSelectInputWidget.prototype.onMenuSelect = function ( item ) {
10219 this.setValue( item.getData() );
10220 };
10221
10222 /**
10223 * @inheritdoc
10224 */
10225 OO.ui.RadioSelectInputWidget.prototype.setValue = function ( value ) {
10226 var selected;
10227 value = this.cleanUpValue( value );
10228 // Only allow setting values that are actually present in the dropdown
10229 selected = this.radioSelectWidget.findItemFromData( value ) ||
10230 this.radioSelectWidget.findFirstSelectableItem();
10231 this.radioSelectWidget.selectItem( selected );
10232 value = selected ? selected.getData() : '';
10233 OO.ui.RadioSelectInputWidget.parent.prototype.setValue.call( this, value );
10234 return this;
10235 };
10236
10237 /**
10238 * @inheritdoc
10239 */
10240 OO.ui.RadioSelectInputWidget.prototype.setDisabled = function ( state ) {
10241 this.radioSelectWidget.setDisabled( state );
10242 OO.ui.RadioSelectInputWidget.parent.prototype.setDisabled.call( this, state );
10243 return this;
10244 };
10245
10246 /**
10247 * Set the options available for this input.
10248 *
10249 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
10250 * @chainable
10251 * @return {OO.ui.Widget} The widget, for chaining
10252 */
10253 OO.ui.RadioSelectInputWidget.prototype.setOptions = function ( options ) {
10254 var value = this.getValue();
10255
10256 this.setOptionsData( options );
10257
10258 // Re-set the value to update the visible interface (RadioSelectWidget).
10259 // In case the previous value is no longer an available option, select the first valid one.
10260 this.setValue( value );
10261
10262 return this;
10263 };
10264
10265 /**
10266 * Set the internal list of options, used e.g. by setValue() to see which options are allowed.
10267 *
10268 * This method may be called before the parent constructor, so various properties may not be
10269 * intialized yet.
10270 *
10271 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
10272 * @private
10273 */
10274 OO.ui.RadioSelectInputWidget.prototype.setOptionsData = function ( options ) {
10275 var widget = this;
10276
10277 this.radioSelectWidget
10278 .clearItems()
10279 .addItems( options.map( function ( opt ) {
10280 var optValue = widget.cleanUpValue( opt.data );
10281 return new OO.ui.RadioOptionWidget( {
10282 data: optValue,
10283 label: opt.label !== undefined ? opt.label : optValue
10284 } );
10285 } ) );
10286 };
10287
10288 /**
10289 * @inheritdoc
10290 */
10291 OO.ui.RadioSelectInputWidget.prototype.focus = function () {
10292 this.radioSelectWidget.focus();
10293 return this;
10294 };
10295
10296 /**
10297 * @inheritdoc
10298 */
10299 OO.ui.RadioSelectInputWidget.prototype.blur = function () {
10300 this.radioSelectWidget.blur();
10301 return this;
10302 };
10303
10304 /**
10305 * CheckboxMultiselectInputWidget is a
10306 * {@link OO.ui.CheckboxMultiselectWidget CheckboxMultiselectWidget} intended to be used within a
10307 * HTML form, such as a OO.ui.FormLayout. The selected values are synchronized with the value of
10308 * HTML `<input type=checkbox>` tags. Please see the [OOUI documentation on MediaWiki][1] for
10309 * more information about input widgets.
10310 *
10311 * @example
10312 * // A CheckboxMultiselectInputWidget with three options.
10313 * var multiselectInput = new OO.ui.CheckboxMultiselectInputWidget( {
10314 * options: [
10315 * { data: 'a', label: 'First' },
10316 * { data: 'b', label: 'Second' },
10317 * { data: 'c', label: 'Third' }
10318 * ]
10319 * } );
10320 * $( document.body ).append( multiselectInput.$element );
10321 *
10322 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
10323 *
10324 * @class
10325 * @extends OO.ui.InputWidget
10326 *
10327 * @constructor
10328 * @param {Object} [config] Configuration options
10329 * @cfg {Object[]} [options=[]] Array of menu options in the format
10330 * `{ data: …, label: …, disabled: … }`
10331 */
10332 OO.ui.CheckboxMultiselectInputWidget = function OoUiCheckboxMultiselectInputWidget( config ) {
10333 // Configuration initialization
10334 config = config || {};
10335
10336 // Properties (must be done before parent constructor which calls #setDisabled)
10337 this.checkboxMultiselectWidget = new OO.ui.CheckboxMultiselectWidget();
10338 // Must be set before the #setOptionsData call below
10339 this.inputName = config.name;
10340 // Set up the options before parent constructor, which uses them to validate config.value.
10341 // Use this instead of setOptions() because this.$input is not set up yet
10342 this.setOptionsData( config.options || [] );
10343
10344 // Parent constructor
10345 OO.ui.CheckboxMultiselectInputWidget.parent.call( this, config );
10346
10347 // Events
10348 this.checkboxMultiselectWidget.connect( this, {
10349 select: 'onCheckboxesSelect'
10350 } );
10351
10352 // Initialization
10353 this.$element
10354 .addClass( 'oo-ui-checkboxMultiselectInputWidget' )
10355 .append( this.checkboxMultiselectWidget.$element );
10356 // We don't use this.$input, but rather the CheckboxInputWidgets inside each option
10357 this.$input.detach();
10358 };
10359
10360 /* Setup */
10361
10362 OO.inheritClass( OO.ui.CheckboxMultiselectInputWidget, OO.ui.InputWidget );
10363
10364 /* Static Methods */
10365
10366 /**
10367 * @inheritdoc
10368 */
10369 OO.ui.CheckboxMultiselectInputWidget.static.gatherPreInfuseState = function ( node, config ) {
10370 var state = OO.ui.CheckboxMultiselectInputWidget.parent.static.gatherPreInfuseState(
10371 node, config
10372 );
10373 state.value = $( node ).find( '.oo-ui-checkboxInputWidget .oo-ui-inputWidget-input:checked' )
10374 .toArray().map( function ( el ) { return el.value; } );
10375 return state;
10376 };
10377
10378 /**
10379 * @inheritdoc
10380 */
10381 OO.ui.CheckboxMultiselectInputWidget.static.reusePreInfuseDOM = function ( node, config ) {
10382 config = OO.ui.CheckboxMultiselectInputWidget.parent.static.reusePreInfuseDOM( node, config );
10383 // Cannot reuse the `<input type=checkbox>` set
10384 delete config.$input;
10385 return config;
10386 };
10387
10388 /* Methods */
10389
10390 /**
10391 * @inheritdoc
10392 * @protected
10393 */
10394 OO.ui.CheckboxMultiselectInputWidget.prototype.getInputElement = function () {
10395 // Actually unused
10396 return $( '<unused>' );
10397 };
10398
10399 /**
10400 * Handles CheckboxMultiselectWidget select events.
10401 *
10402 * @private
10403 */
10404 OO.ui.CheckboxMultiselectInputWidget.prototype.onCheckboxesSelect = function () {
10405 this.setValue( this.checkboxMultiselectWidget.findSelectedItemsData() );
10406 };
10407
10408 /**
10409 * @inheritdoc
10410 */
10411 OO.ui.CheckboxMultiselectInputWidget.prototype.getValue = function () {
10412 var value = this.$element.find( '.oo-ui-checkboxInputWidget .oo-ui-inputWidget-input:checked' )
10413 .toArray().map( function ( el ) { return el.value; } );
10414 if ( this.value !== value ) {
10415 this.setValue( value );
10416 }
10417 return this.value;
10418 };
10419
10420 /**
10421 * @inheritdoc
10422 */
10423 OO.ui.CheckboxMultiselectInputWidget.prototype.setValue = function ( value ) {
10424 value = this.cleanUpValue( value );
10425 this.checkboxMultiselectWidget.selectItemsByData( value );
10426 OO.ui.CheckboxMultiselectInputWidget.parent.prototype.setValue.call( this, value );
10427 if ( this.optionsDirty ) {
10428 // We reached this from the constructor or from #setOptions.
10429 // We have to update the <select> element.
10430 this.updateOptionsInterface();
10431 }
10432 return this;
10433 };
10434
10435 /**
10436 * Clean up incoming value.
10437 *
10438 * @param {string[]} value Original value
10439 * @return {string[]} Cleaned up value
10440 */
10441 OO.ui.CheckboxMultiselectInputWidget.prototype.cleanUpValue = function ( value ) {
10442 var i, singleValue,
10443 cleanValue = [];
10444 if ( !Array.isArray( value ) ) {
10445 return cleanValue;
10446 }
10447 for ( i = 0; i < value.length; i++ ) {
10448 singleValue = OO.ui.CheckboxMultiselectInputWidget.parent.prototype.cleanUpValue
10449 .call( this, value[ i ] );
10450 // Remove options that we don't have here
10451 if ( !this.checkboxMultiselectWidget.findItemFromData( singleValue ) ) {
10452 continue;
10453 }
10454 cleanValue.push( singleValue );
10455 }
10456 return cleanValue;
10457 };
10458
10459 /**
10460 * @inheritdoc
10461 */
10462 OO.ui.CheckboxMultiselectInputWidget.prototype.setDisabled = function ( state ) {
10463 this.checkboxMultiselectWidget.setDisabled( state );
10464 OO.ui.CheckboxMultiselectInputWidget.parent.prototype.setDisabled.call( this, state );
10465 return this;
10466 };
10467
10468 /**
10469 * Set the options available for this input.
10470 *
10471 * @param {Object[]} options Array of menu options in the format
10472 * `{ data: …, label: …, disabled: … }`
10473 * @chainable
10474 * @return {OO.ui.Widget} The widget, for chaining
10475 */
10476 OO.ui.CheckboxMultiselectInputWidget.prototype.setOptions = function ( options ) {
10477 var value = this.getValue();
10478
10479 this.setOptionsData( options );
10480
10481 // Re-set the value to update the visible interface (CheckboxMultiselectWidget).
10482 // This will also get rid of any stale options that we just removed.
10483 this.setValue( value );
10484
10485 return this;
10486 };
10487
10488 /**
10489 * Set the internal list of options, used e.g. by setValue() to see which options are allowed.
10490 *
10491 * This method may be called before the parent constructor, so various properties may not be
10492 * intialized yet.
10493 *
10494 * @param {Object[]} options Array of menu options in the format
10495 * `{ data: …, label: … }`
10496 * @private
10497 */
10498 OO.ui.CheckboxMultiselectInputWidget.prototype.setOptionsData = function ( options ) {
10499 var widget = this;
10500
10501 this.optionsDirty = true;
10502
10503 this.checkboxMultiselectWidget
10504 .clearItems()
10505 .addItems( options.map( function ( opt ) {
10506 var optValue, item, optDisabled;
10507 optValue = OO.ui.CheckboxMultiselectInputWidget.parent.prototype.cleanUpValue
10508 .call( widget, opt.data );
10509 optDisabled = opt.disabled !== undefined ? opt.disabled : false;
10510 item = new OO.ui.CheckboxMultioptionWidget( {
10511 data: optValue,
10512 label: opt.label !== undefined ? opt.label : optValue,
10513 disabled: optDisabled
10514 } );
10515 // Set the 'name' and 'value' for form submission
10516 item.checkbox.$input.attr( 'name', widget.inputName );
10517 item.checkbox.setValue( optValue );
10518 return item;
10519 } ) );
10520 };
10521
10522 /**
10523 * Update the user-visible interface to match the internal list of options and value.
10524 *
10525 * This method must only be called after the parent constructor.
10526 *
10527 * @private
10528 */
10529 OO.ui.CheckboxMultiselectInputWidget.prototype.updateOptionsInterface = function () {
10530 var defaultValue = this.defaultValue;
10531
10532 this.checkboxMultiselectWidget.getItems().forEach( function ( item ) {
10533 // Remember original selection state. This property can be later used to check whether
10534 // the selection state of the input has been changed since it was created.
10535 var isDefault = defaultValue.indexOf( item.getData() ) !== -1;
10536 item.checkbox.defaultSelected = isDefault;
10537 item.checkbox.$input[ 0 ].defaultChecked = isDefault;
10538 } );
10539
10540 this.optionsDirty = false;
10541 };
10542
10543 /**
10544 * @inheritdoc
10545 */
10546 OO.ui.CheckboxMultiselectInputWidget.prototype.focus = function () {
10547 this.checkboxMultiselectWidget.focus();
10548 return this;
10549 };
10550
10551 /**
10552 * TextInputWidgets, like HTML text inputs, can be configured with options that customize the
10553 * size of the field as well as its presentation. In addition, these widgets can be configured
10554 * with {@link OO.ui.mixin.IconElement icons}, {@link OO.ui.mixin.IndicatorElement indicators}, an
10555 * optional validation-pattern (used to determine if an input value is valid or not) and an input
10556 * filter, which modifies incoming values rather than validating them.
10557 * Please see the [OOUI documentation on MediaWiki] [1] for more information and examples.
10558 *
10559 * This widget can be used inside an HTML form, such as a OO.ui.FormLayout.
10560 *
10561 * @example
10562 * // A TextInputWidget.
10563 * var textInput = new OO.ui.TextInputWidget( {
10564 * value: 'Text input'
10565 * } );
10566 * $( document.body ).append( textInput.$element );
10567 *
10568 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
10569 *
10570 * @class
10571 * @extends OO.ui.InputWidget
10572 * @mixins OO.ui.mixin.IconElement
10573 * @mixins OO.ui.mixin.IndicatorElement
10574 * @mixins OO.ui.mixin.PendingElement
10575 * @mixins OO.ui.mixin.LabelElement
10576 * @mixins OO.ui.mixin.FlaggedElement
10577 *
10578 * @constructor
10579 * @param {Object} [config] Configuration options
10580 * @cfg {string} [type='text'] The value of the HTML `type` attribute: 'text', 'password'
10581 * 'email', 'url' or 'number'.
10582 * @cfg {string} [placeholder] Placeholder text
10583 * @cfg {boolean} [autofocus=false] Use an HTML `autofocus` attribute to
10584 * instruct the browser to focus this widget.
10585 * @cfg {boolean} [readOnly=false] Prevent changes to the value of the text input.
10586 * @cfg {number} [maxLength] Maximum number of characters allowed in the input.
10587 *
10588 * For unfortunate historical reasons, this counts the number of UTF-16 code units rather than
10589 * Unicode codepoints, which means that codepoints outside the Basic Multilingual Plane (e.g.
10590 * many emojis) count as 2 characters each.
10591 * @cfg {string} [labelPosition='after'] The position of the inline label relative to that of
10592 * the value or placeholder text: `'before'` or `'after'`
10593 * @cfg {boolean} [required=false] Mark the field as required with `true`. Implies `indicator:
10594 * 'required'`. Note that `false` & setting `indicator: 'required' will result in no indicator
10595 * shown.
10596 * @cfg {boolean} [autocomplete=true] Should the browser support autocomplete for this field
10597 * @cfg {boolean} [spellcheck] Should the browser support spellcheck for this field (`undefined`
10598 * means leaving it up to the browser).
10599 * @cfg {RegExp|Function|string} [validate] Validation pattern: when string, a symbolic name of a
10600 * pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer'
10601 * (the value must contain only numbers); when RegExp, a regular expression that must match the
10602 * value for it to be considered valid; when Function, a function receiving the value as parameter
10603 * that must return true, or promise resolving to true, for it to be considered valid.
10604 */
10605 OO.ui.TextInputWidget = function OoUiTextInputWidget( config ) {
10606 // Configuration initialization
10607 config = $.extend( {
10608 type: 'text',
10609 labelPosition: 'after'
10610 }, config );
10611
10612 // Parent constructor
10613 OO.ui.TextInputWidget.parent.call( this, config );
10614
10615 // Mixin constructors
10616 OO.ui.mixin.IconElement.call( this, config );
10617 OO.ui.mixin.IndicatorElement.call( this, config );
10618 OO.ui.mixin.PendingElement.call( this, $.extend( { $pending: this.$input }, config ) );
10619 OO.ui.mixin.LabelElement.call( this, config );
10620 OO.ui.mixin.FlaggedElement.call( this, config );
10621
10622 // Properties
10623 this.type = this.getSaneType( config );
10624 this.readOnly = false;
10625 this.required = false;
10626 this.validate = null;
10627 this.scrollWidth = null;
10628
10629 this.setValidation( config.validate );
10630 this.setLabelPosition( config.labelPosition );
10631
10632 // Events
10633 this.$input.on( {
10634 keypress: this.onKeyPress.bind( this ),
10635 blur: this.onBlur.bind( this ),
10636 focus: this.onFocus.bind( this )
10637 } );
10638 this.$icon.on( 'mousedown', this.onIconMouseDown.bind( this ) );
10639 this.$indicator.on( 'mousedown', this.onIndicatorMouseDown.bind( this ) );
10640 this.on( 'labelChange', this.updatePosition.bind( this ) );
10641 this.on( 'change', OO.ui.debounce( this.onDebouncedChange.bind( this ), 250 ) );
10642
10643 // Initialization
10644 this.$element
10645 .addClass( 'oo-ui-textInputWidget oo-ui-textInputWidget-type-' + this.type )
10646 .append( this.$icon, this.$indicator );
10647 this.setReadOnly( !!config.readOnly );
10648 this.setRequired( !!config.required );
10649 if ( config.placeholder !== undefined ) {
10650 this.$input.attr( 'placeholder', config.placeholder );
10651 }
10652 if ( config.maxLength !== undefined ) {
10653 this.$input.attr( 'maxlength', config.maxLength );
10654 }
10655 if ( config.autofocus ) {
10656 this.$input.attr( 'autofocus', 'autofocus' );
10657 }
10658 if ( config.autocomplete === false ) {
10659 this.$input.attr( 'autocomplete', 'off' );
10660 // Turning off autocompletion also disables "form caching" when the user navigates to a
10661 // different page and then clicks "Back". Re-enable it when leaving.
10662 // Borrowed from jQuery UI.
10663 $( window ).on( {
10664 beforeunload: function () {
10665 this.$input.removeAttr( 'autocomplete' );
10666 }.bind( this ),
10667 pageshow: function () {
10668 // Browsers don't seem to actually fire this event on "Back", they instead just
10669 // reload the whole page... it shouldn't hurt, though.
10670 this.$input.attr( 'autocomplete', 'off' );
10671 }.bind( this )
10672 } );
10673 }
10674 if ( config.spellcheck !== undefined ) {
10675 this.$input.attr( 'spellcheck', config.spellcheck ? 'true' : 'false' );
10676 }
10677 if ( this.label ) {
10678 this.isWaitingToBeAttached = true;
10679 this.installParentChangeDetector();
10680 }
10681 };
10682
10683 /* Setup */
10684
10685 OO.inheritClass( OO.ui.TextInputWidget, OO.ui.InputWidget );
10686 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.mixin.IconElement );
10687 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.mixin.IndicatorElement );
10688 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.mixin.PendingElement );
10689 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.mixin.LabelElement );
10690 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.mixin.FlaggedElement );
10691
10692 /* Static Properties */
10693
10694 OO.ui.TextInputWidget.static.validationPatterns = {
10695 'non-empty': /.+/,
10696 integer: /^\d+$/
10697 };
10698
10699 /* Events */
10700
10701 /**
10702 * An `enter` event is emitted when the user presses Enter key inside the text box.
10703 *
10704 * @event enter
10705 */
10706
10707 /* Methods */
10708
10709 /**
10710 * Handle icon mouse down events.
10711 *
10712 * @private
10713 * @param {jQuery.Event} e Mouse down event
10714 * @return {undefined|boolean} False to prevent default if event is handled
10715 */
10716 OO.ui.TextInputWidget.prototype.onIconMouseDown = function ( e ) {
10717 if ( e.which === OO.ui.MouseButtons.LEFT ) {
10718 this.focus();
10719 return false;
10720 }
10721 };
10722
10723 /**
10724 * Handle indicator mouse down events.
10725 *
10726 * @private
10727 * @param {jQuery.Event} e Mouse down event
10728 * @return {undefined|boolean} False to prevent default if event is handled
10729 */
10730 OO.ui.TextInputWidget.prototype.onIndicatorMouseDown = function ( e ) {
10731 if ( e.which === OO.ui.MouseButtons.LEFT ) {
10732 this.focus();
10733 return false;
10734 }
10735 };
10736
10737 /**
10738 * Handle key press events.
10739 *
10740 * @private
10741 * @param {jQuery.Event} e Key press event
10742 * @fires enter If Enter key is pressed
10743 */
10744 OO.ui.TextInputWidget.prototype.onKeyPress = function ( e ) {
10745 if ( e.which === OO.ui.Keys.ENTER ) {
10746 this.emit( 'enter', e );
10747 }
10748 };
10749
10750 /**
10751 * Handle blur events.
10752 *
10753 * @private
10754 * @param {jQuery.Event} e Blur event
10755 */
10756 OO.ui.TextInputWidget.prototype.onBlur = function () {
10757 this.setValidityFlag();
10758 };
10759
10760 /**
10761 * Handle focus events.
10762 *
10763 * @private
10764 * @param {jQuery.Event} e Focus event
10765 */
10766 OO.ui.TextInputWidget.prototype.onFocus = function () {
10767 if ( this.isWaitingToBeAttached ) {
10768 // If we've received focus, then we must be attached to the document, and if
10769 // isWaitingToBeAttached is still true, that means the handler never fired. Fire it now.
10770 this.onElementAttach();
10771 }
10772 this.setValidityFlag( true );
10773 };
10774
10775 /**
10776 * Handle element attach events.
10777 *
10778 * @private
10779 * @param {jQuery.Event} e Element attach event
10780 */
10781 OO.ui.TextInputWidget.prototype.onElementAttach = function () {
10782 this.isWaitingToBeAttached = false;
10783 // Any previously calculated size is now probably invalid if we reattached elsewhere
10784 this.valCache = null;
10785 this.positionLabel();
10786 };
10787
10788 /**
10789 * Handle debounced change events.
10790 *
10791 * @param {string} value
10792 * @private
10793 */
10794 OO.ui.TextInputWidget.prototype.onDebouncedChange = function () {
10795 this.setValidityFlag();
10796 };
10797
10798 /**
10799 * Check if the input is {@link #readOnly read-only}.
10800 *
10801 * @return {boolean}
10802 */
10803 OO.ui.TextInputWidget.prototype.isReadOnly = function () {
10804 return this.readOnly;
10805 };
10806
10807 /**
10808 * Set the {@link #readOnly read-only} state of the input.
10809 *
10810 * @param {boolean} state Make input read-only
10811 * @chainable
10812 * @return {OO.ui.Widget} The widget, for chaining
10813 */
10814 OO.ui.TextInputWidget.prototype.setReadOnly = function ( state ) {
10815 this.readOnly = !!state;
10816 this.$input.prop( 'readOnly', this.readOnly );
10817 return this;
10818 };
10819
10820 /**
10821 * Check if the input is {@link #required required}.
10822 *
10823 * @return {boolean}
10824 */
10825 OO.ui.TextInputWidget.prototype.isRequired = function () {
10826 return this.required;
10827 };
10828
10829 /**
10830 * Set the {@link #required required} state of the input.
10831 *
10832 * @param {boolean} state Make input required
10833 * @chainable
10834 * @return {OO.ui.Widget} The widget, for chaining
10835 */
10836 OO.ui.TextInputWidget.prototype.setRequired = function ( state ) {
10837 this.required = !!state;
10838 if ( this.required ) {
10839 this.$input
10840 .prop( 'required', true )
10841 .attr( 'aria-required', 'true' );
10842 if ( this.getIndicator() === null ) {
10843 this.setIndicator( 'required' );
10844 }
10845 } else {
10846 this.$input
10847 .prop( 'required', false )
10848 .removeAttr( 'aria-required' );
10849 if ( this.getIndicator() === 'required' ) {
10850 this.setIndicator( null );
10851 }
10852 }
10853 return this;
10854 };
10855
10856 /**
10857 * Support function for making #onElementAttach work across browsers.
10858 *
10859 * This whole function could be replaced with one line of code using the DOMNodeInsertedIntoDocument
10860 * event, but it's not supported by Firefox and allegedly deprecated, so we only use it as fallback.
10861 *
10862 * Due to MutationObserver performance woes, #onElementAttach is only somewhat reliably called the
10863 * first time that the element gets attached to the documented.
10864 */
10865 OO.ui.TextInputWidget.prototype.installParentChangeDetector = function () {
10866 var mutationObserver, onRemove, topmostNode, fakeParentNode,
10867 MutationObserver = window.MutationObserver ||
10868 window.WebKitMutationObserver ||
10869 window.MozMutationObserver,
10870 widget = this;
10871
10872 if ( MutationObserver ) {
10873 // The new way. If only it wasn't so ugly.
10874
10875 if ( this.isElementAttached() ) {
10876 // Widget is attached already, do nothing. This breaks the functionality of this
10877 // function when the widget is detached and reattached. Alas, doing this correctly with
10878 // MutationObserver would require observation of the whole document, which would hurt
10879 // performance of other, more important code.
10880 return;
10881 }
10882
10883 // Find topmost node in the tree
10884 topmostNode = this.$element[ 0 ];
10885 while ( topmostNode.parentNode ) {
10886 topmostNode = topmostNode.parentNode;
10887 }
10888
10889 // We have no way to detect the $element being attached somewhere without observing the
10890 // entire DOM with subtree modifications, which would hurt performance. So we cheat: we hook
10891 // to the parent node of $element, and instead detect when $element is removed from it (and
10892 // thus probably attached somewhere else). If there is no parent, we create a "fake" one. If
10893 // it doesn't get attached, we end up back here and create the parent.
10894 mutationObserver = new MutationObserver( function ( mutations ) {
10895 var i, j, removedNodes;
10896 for ( i = 0; i < mutations.length; i++ ) {
10897 removedNodes = mutations[ i ].removedNodes;
10898 for ( j = 0; j < removedNodes.length; j++ ) {
10899 if ( removedNodes[ j ] === topmostNode ) {
10900 setTimeout( onRemove, 0 );
10901 return;
10902 }
10903 }
10904 }
10905 } );
10906
10907 onRemove = function () {
10908 // If the node was attached somewhere else, report it
10909 if ( widget.isElementAttached() ) {
10910 widget.onElementAttach();
10911 }
10912 mutationObserver.disconnect();
10913 widget.installParentChangeDetector();
10914 };
10915
10916 // Create a fake parent and observe it
10917 fakeParentNode = $( '<div>' ).append( topmostNode )[ 0 ];
10918 mutationObserver.observe( fakeParentNode, { childList: true } );
10919 } else {
10920 // Using the DOMNodeInsertedIntoDocument event is much nicer and less magical, and works for
10921 // detachment and reattachment, but it's not supported by Firefox and allegedly deprecated.
10922 this.$element.on( 'DOMNodeInsertedIntoDocument', this.onElementAttach.bind( this ) );
10923 }
10924 };
10925
10926 /**
10927 * @inheritdoc
10928 * @protected
10929 */
10930 OO.ui.TextInputWidget.prototype.getInputElement = function ( config ) {
10931 if ( this.getSaneType( config ) === 'number' ) {
10932 return $( '<input>' )
10933 .attr( 'step', 'any' )
10934 .attr( 'type', 'number' );
10935 } else {
10936 return $( '<input>' ).attr( 'type', this.getSaneType( config ) );
10937 }
10938 };
10939
10940 /**
10941 * Get sanitized value for 'type' for given config.
10942 *
10943 * @param {Object} config Configuration options
10944 * @return {string|null}
10945 * @protected
10946 */
10947 OO.ui.TextInputWidget.prototype.getSaneType = function ( config ) {
10948 var allowedTypes = [
10949 'text',
10950 'password',
10951 'email',
10952 'url',
10953 'number'
10954 ];
10955 return allowedTypes.indexOf( config.type ) !== -1 ? config.type : 'text';
10956 };
10957
10958 /**
10959 * Focus the input and select a specified range within the text.
10960 *
10961 * @param {number} from Select from offset
10962 * @param {number} [to] Select to offset, defaults to from
10963 * @chainable
10964 * @return {OO.ui.Widget} The widget, for chaining
10965 */
10966 OO.ui.TextInputWidget.prototype.selectRange = function ( from, to ) {
10967 var isBackwards, start, end,
10968 input = this.$input[ 0 ];
10969
10970 to = to || from;
10971
10972 isBackwards = to < from;
10973 start = isBackwards ? to : from;
10974 end = isBackwards ? from : to;
10975
10976 this.focus();
10977
10978 try {
10979 input.setSelectionRange( start, end, isBackwards ? 'backward' : 'forward' );
10980 } catch ( e ) {
10981 // IE throws an exception if you call setSelectionRange on a unattached DOM node.
10982 // Rather than expensively check if the input is attached every time, just check
10983 // if it was the cause of an error being thrown. If not, rethrow the error.
10984 if ( this.getElementDocument().body.contains( input ) ) {
10985 throw e;
10986 }
10987 }
10988 return this;
10989 };
10990
10991 /**
10992 * Get an object describing the current selection range in a directional manner
10993 *
10994 * @return {Object} Object containing 'from' and 'to' offsets
10995 */
10996 OO.ui.TextInputWidget.prototype.getRange = function () {
10997 var input = this.$input[ 0 ],
10998 start = input.selectionStart,
10999 end = input.selectionEnd,
11000 isBackwards = input.selectionDirection === 'backward';
11001
11002 return {
11003 from: isBackwards ? end : start,
11004 to: isBackwards ? start : end
11005 };
11006 };
11007
11008 /**
11009 * Get the length of the text input value.
11010 *
11011 * This could differ from the length of #getValue if the
11012 * value gets filtered
11013 *
11014 * @return {number} Input length
11015 */
11016 OO.ui.TextInputWidget.prototype.getInputLength = function () {
11017 return this.$input[ 0 ].value.length;
11018 };
11019
11020 /**
11021 * Focus the input and select the entire text.
11022 *
11023 * @chainable
11024 * @return {OO.ui.Widget} The widget, for chaining
11025 */
11026 OO.ui.TextInputWidget.prototype.select = function () {
11027 return this.selectRange( 0, this.getInputLength() );
11028 };
11029
11030 /**
11031 * Focus the input and move the cursor to the start.
11032 *
11033 * @chainable
11034 * @return {OO.ui.Widget} The widget, for chaining
11035 */
11036 OO.ui.TextInputWidget.prototype.moveCursorToStart = function () {
11037 return this.selectRange( 0 );
11038 };
11039
11040 /**
11041 * Focus the input and move the cursor to the end.
11042 *
11043 * @chainable
11044 * @return {OO.ui.Widget} The widget, for chaining
11045 */
11046 OO.ui.TextInputWidget.prototype.moveCursorToEnd = function () {
11047 return this.selectRange( this.getInputLength() );
11048 };
11049
11050 /**
11051 * Insert new content into the input.
11052 *
11053 * @param {string} content Content to be inserted
11054 * @chainable
11055 * @return {OO.ui.Widget} The widget, for chaining
11056 */
11057 OO.ui.TextInputWidget.prototype.insertContent = function ( content ) {
11058 var start, end,
11059 range = this.getRange(),
11060 value = this.getValue();
11061
11062 start = Math.min( range.from, range.to );
11063 end = Math.max( range.from, range.to );
11064
11065 this.setValue( value.slice( 0, start ) + content + value.slice( end ) );
11066 this.selectRange( start + content.length );
11067 return this;
11068 };
11069
11070 /**
11071 * Insert new content either side of a selection.
11072 *
11073 * @param {string} pre Content to be inserted before the selection
11074 * @param {string} post Content to be inserted after the selection
11075 * @chainable
11076 * @return {OO.ui.Widget} The widget, for chaining
11077 */
11078 OO.ui.TextInputWidget.prototype.encapsulateContent = function ( pre, post ) {
11079 var start, end,
11080 range = this.getRange(),
11081 offset = pre.length;
11082
11083 start = Math.min( range.from, range.to );
11084 end = Math.max( range.from, range.to );
11085
11086 this.selectRange( start ).insertContent( pre );
11087 this.selectRange( offset + end ).insertContent( post );
11088
11089 this.selectRange( offset + start, offset + end );
11090 return this;
11091 };
11092
11093 /**
11094 * Set the validation pattern.
11095 *
11096 * The validation pattern is either a regular expression, a function, or the symbolic name of a
11097 * pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer' (the
11098 * value must contain only numbers).
11099 *
11100 * @param {RegExp|Function|string|null} validate Regular expression, function, or the symbolic name
11101 * of a pattern (either ‘integer’ or ‘non-empty’) defined by the class.
11102 */
11103 OO.ui.TextInputWidget.prototype.setValidation = function ( validate ) {
11104 if ( validate instanceof RegExp || validate instanceof Function ) {
11105 this.validate = validate;
11106 } else {
11107 this.validate = this.constructor.static.validationPatterns[ validate ] || /.*/;
11108 }
11109 };
11110
11111 /**
11112 * Sets the 'invalid' flag appropriately.
11113 *
11114 * @param {boolean} [isValid] Optionally override validation result
11115 */
11116 OO.ui.TextInputWidget.prototype.setValidityFlag = function ( isValid ) {
11117 var widget = this,
11118 setFlag = function ( valid ) {
11119 if ( !valid ) {
11120 widget.$input.attr( 'aria-invalid', 'true' );
11121 } else {
11122 widget.$input.removeAttr( 'aria-invalid' );
11123 }
11124 widget.setFlags( { invalid: !valid } );
11125 };
11126
11127 if ( isValid !== undefined ) {
11128 setFlag( isValid );
11129 } else {
11130 this.getValidity().then( function () {
11131 setFlag( true );
11132 }, function () {
11133 setFlag( false );
11134 } );
11135 }
11136 };
11137
11138 /**
11139 * Get the validity of current value.
11140 *
11141 * This method returns a promise that resolves if the value is valid and rejects if
11142 * it isn't. Uses the {@link #validate validation pattern} to check for validity.
11143 *
11144 * @return {jQuery.Promise} A promise that resolves if the value is valid, rejects if not.
11145 */
11146 OO.ui.TextInputWidget.prototype.getValidity = function () {
11147 var result;
11148
11149 function rejectOrResolve( valid ) {
11150 if ( valid ) {
11151 return $.Deferred().resolve().promise();
11152 } else {
11153 return $.Deferred().reject().promise();
11154 }
11155 }
11156
11157 // Check browser validity and reject if it is invalid
11158 if (
11159 this.$input[ 0 ].checkValidity !== undefined &&
11160 this.$input[ 0 ].checkValidity() === false
11161 ) {
11162 return rejectOrResolve( false );
11163 }
11164
11165 // Run our checks if the browser thinks the field is valid
11166 if ( this.validate instanceof Function ) {
11167 result = this.validate( this.getValue() );
11168 if ( result && typeof result.promise === 'function' ) {
11169 return result.promise().then( function ( valid ) {
11170 return rejectOrResolve( valid );
11171 } );
11172 } else {
11173 return rejectOrResolve( result );
11174 }
11175 } else {
11176 return rejectOrResolve( this.getValue().match( this.validate ) );
11177 }
11178 };
11179
11180 /**
11181 * Set the position of the inline label relative to that of the value: `‘before’` or `‘after’`.
11182 *
11183 * @param {string} labelPosition Label position, 'before' or 'after'
11184 * @chainable
11185 * @return {OO.ui.Widget} The widget, for chaining
11186 */
11187 OO.ui.TextInputWidget.prototype.setLabelPosition = function ( labelPosition ) {
11188 this.labelPosition = labelPosition;
11189 if ( this.label ) {
11190 // If there is no label and we only change the position, #updatePosition is a no-op,
11191 // but it takes really a lot of work to do nothing.
11192 this.updatePosition();
11193 }
11194 return this;
11195 };
11196
11197 /**
11198 * Update the position of the inline label.
11199 *
11200 * This method is called by #setLabelPosition, and can also be called on its own if
11201 * something causes the label to be mispositioned.
11202 *
11203 * @chainable
11204 * @return {OO.ui.Widget} The widget, for chaining
11205 */
11206 OO.ui.TextInputWidget.prototype.updatePosition = function () {
11207 var after = this.labelPosition === 'after';
11208
11209 this.$element
11210 .toggleClass( 'oo-ui-textInputWidget-labelPosition-after', !!this.label && after )
11211 .toggleClass( 'oo-ui-textInputWidget-labelPosition-before', !!this.label && !after );
11212
11213 this.valCache = null;
11214 this.scrollWidth = null;
11215 this.positionLabel();
11216
11217 return this;
11218 };
11219
11220 /**
11221 * Position the label by setting the correct padding on the input.
11222 *
11223 * @private
11224 * @chainable
11225 * @return {OO.ui.Widget} The widget, for chaining
11226 */
11227 OO.ui.TextInputWidget.prototype.positionLabel = function () {
11228 var after, rtl, property, newCss;
11229
11230 if ( this.isWaitingToBeAttached ) {
11231 // #onElementAttach will be called soon, which calls this method
11232 return this;
11233 }
11234
11235 newCss = {
11236 'padding-right': '',
11237 'padding-left': ''
11238 };
11239
11240 if ( this.label ) {
11241 this.$element.append( this.$label );
11242 } else {
11243 this.$label.detach();
11244 // Clear old values if present
11245 this.$input.css( newCss );
11246 return;
11247 }
11248
11249 after = this.labelPosition === 'after';
11250 rtl = this.$element.css( 'direction' ) === 'rtl';
11251 property = after === rtl ? 'padding-left' : 'padding-right';
11252
11253 newCss[ property ] = this.$label.outerWidth( true ) + ( after ? this.scrollWidth : 0 );
11254 // We have to clear the padding on the other side, in case the element direction changed
11255 this.$input.css( newCss );
11256
11257 return this;
11258 };
11259
11260 /**
11261 * SearchInputWidgets are TextInputWidgets with `type="search"` assigned and feature a
11262 * {@link OO.ui.mixin.IconElement search icon} by default.
11263 * Please see the [OOUI documentation on MediaWiki] [1] for more information and examples.
11264 *
11265 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs#SearchInputWidget
11266 *
11267 * @class
11268 * @extends OO.ui.TextInputWidget
11269 *
11270 * @constructor
11271 * @param {Object} [config] Configuration options
11272 */
11273 OO.ui.SearchInputWidget = function OoUiSearchInputWidget( config ) {
11274 config = $.extend( {
11275 icon: 'search'
11276 }, config );
11277
11278 // Parent constructor
11279 OO.ui.SearchInputWidget.parent.call( this, config );
11280
11281 // Events
11282 this.connect( this, {
11283 change: 'onChange'
11284 } );
11285 this.$indicator.on( 'click', this.onIndicatorClick.bind( this ) );
11286
11287 // Initialization
11288 this.updateSearchIndicator();
11289 this.connect( this, {
11290 disable: 'onDisable'
11291 } );
11292 };
11293
11294 /* Setup */
11295
11296 OO.inheritClass( OO.ui.SearchInputWidget, OO.ui.TextInputWidget );
11297
11298 /* Methods */
11299
11300 /**
11301 * @inheritdoc
11302 * @protected
11303 */
11304 OO.ui.SearchInputWidget.prototype.getSaneType = function () {
11305 return 'search';
11306 };
11307
11308 /**
11309 * Handle click events on the indicator
11310 *
11311 * @param {jQuery.Event} e Click event
11312 * @return {boolean}
11313 */
11314 OO.ui.SearchInputWidget.prototype.onIndicatorClick = function ( e ) {
11315 if ( e.which === OO.ui.MouseButtons.LEFT ) {
11316 // Clear the text field
11317 this.setValue( '' );
11318 this.focus();
11319 return false;
11320 }
11321 };
11322
11323 /**
11324 * Update the 'clear' indicator displayed on type: 'search' text
11325 * fields, hiding it when the field is already empty or when it's not
11326 * editable.
11327 */
11328 OO.ui.SearchInputWidget.prototype.updateSearchIndicator = function () {
11329 if ( this.getValue() === '' || this.isDisabled() || this.isReadOnly() ) {
11330 this.setIndicator( null );
11331 } else {
11332 this.setIndicator( 'clear' );
11333 }
11334 };
11335
11336 /**
11337 * Handle change events.
11338 *
11339 * @private
11340 */
11341 OO.ui.SearchInputWidget.prototype.onChange = function () {
11342 this.updateSearchIndicator();
11343 };
11344
11345 /**
11346 * Handle disable events.
11347 *
11348 * @param {boolean} disabled Element is disabled
11349 * @private
11350 */
11351 OO.ui.SearchInputWidget.prototype.onDisable = function () {
11352 this.updateSearchIndicator();
11353 };
11354
11355 /**
11356 * @inheritdoc
11357 */
11358 OO.ui.SearchInputWidget.prototype.setReadOnly = function ( state ) {
11359 OO.ui.SearchInputWidget.parent.prototype.setReadOnly.call( this, state );
11360 this.updateSearchIndicator();
11361 return this;
11362 };
11363
11364 /**
11365 * MultilineTextInputWidgets, like HTML textareas, are featuring customization options to
11366 * configure number of rows visible. In addition, these widgets can be autosized to fit user
11367 * inputs and can show {@link OO.ui.mixin.IconElement icons} and
11368 * {@link OO.ui.mixin.IndicatorElement indicators}.
11369 * Please see the [OOUI documentation on MediaWiki] [1] for more information and examples.
11370 *
11371 * This widget can be used inside an HTML form, such as a OO.ui.FormLayout.
11372 *
11373 * @example
11374 * // A MultilineTextInputWidget.
11375 * var multilineTextInput = new OO.ui.MultilineTextInputWidget( {
11376 * value: 'Text input on multiple lines'
11377 * } );
11378 * $( document.body ).append( multilineTextInput.$element );
11379 *
11380 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs#MultilineTextInputWidget
11381 *
11382 * @class
11383 * @extends OO.ui.TextInputWidget
11384 *
11385 * @constructor
11386 * @param {Object} [config] Configuration options
11387 * @cfg {number} [rows] Number of visible lines in textarea. If used with `autosize`,
11388 * specifies minimum number of rows to display.
11389 * @cfg {boolean} [autosize=false] Automatically resize the text input to fit its content.
11390 * Use the #maxRows config to specify a maximum number of displayed rows.
11391 * @cfg {number} [maxRows] Maximum number of rows to display when #autosize is set to true.
11392 * Defaults to the maximum of `10` and `2 * rows`, or `10` if `rows` isn't provided.
11393 */
11394 OO.ui.MultilineTextInputWidget = function OoUiMultilineTextInputWidget( config ) {
11395 config = $.extend( {
11396 type: 'text'
11397 }, config );
11398 // Parent constructor
11399 OO.ui.MultilineTextInputWidget.parent.call( this, config );
11400
11401 // Properties
11402 this.autosize = !!config.autosize;
11403 this.styleHeight = null;
11404 this.minRows = config.rows !== undefined ? config.rows : '';
11405 this.maxRows = config.maxRows || Math.max( 2 * ( this.minRows || 0 ), 10 );
11406
11407 // Clone for resizing
11408 if ( this.autosize ) {
11409 this.$clone = this.$input
11410 .clone()
11411 .removeAttr( 'id' )
11412 .removeAttr( 'name' )
11413 .insertAfter( this.$input )
11414 .attr( 'aria-hidden', 'true' )
11415 .addClass( 'oo-ui-element-hidden' );
11416 }
11417
11418 // Events
11419 this.connect( this, {
11420 change: 'onChange'
11421 } );
11422
11423 // Initialization
11424 if ( config.rows ) {
11425 this.$input.attr( 'rows', config.rows );
11426 }
11427 if ( this.autosize ) {
11428 this.$input.addClass( 'oo-ui-textInputWidget-autosized' );
11429 this.isWaitingToBeAttached = true;
11430 this.installParentChangeDetector();
11431 }
11432 };
11433
11434 /* Setup */
11435
11436 OO.inheritClass( OO.ui.MultilineTextInputWidget, OO.ui.TextInputWidget );
11437
11438 /* Static Methods */
11439
11440 /**
11441 * @inheritdoc
11442 */
11443 OO.ui.MultilineTextInputWidget.static.gatherPreInfuseState = function ( node, config ) {
11444 var state = OO.ui.MultilineTextInputWidget.parent.static.gatherPreInfuseState( node, config );
11445 state.scrollTop = config.$input.scrollTop();
11446 return state;
11447 };
11448
11449 /* Methods */
11450
11451 /**
11452 * @inheritdoc
11453 */
11454 OO.ui.MultilineTextInputWidget.prototype.onElementAttach = function () {
11455 OO.ui.MultilineTextInputWidget.parent.prototype.onElementAttach.call( this );
11456 this.adjustSize();
11457 };
11458
11459 /**
11460 * Handle change events.
11461 *
11462 * @private
11463 */
11464 OO.ui.MultilineTextInputWidget.prototype.onChange = function () {
11465 this.adjustSize();
11466 };
11467
11468 /**
11469 * @inheritdoc
11470 */
11471 OO.ui.MultilineTextInputWidget.prototype.updatePosition = function () {
11472 OO.ui.MultilineTextInputWidget.parent.prototype.updatePosition.call( this );
11473 this.adjustSize();
11474 };
11475
11476 /**
11477 * @inheritdoc
11478 *
11479 * Modify to emit 'enter' on Ctrl/Meta+Enter, instead of plain Enter
11480 */
11481 OO.ui.MultilineTextInputWidget.prototype.onKeyPress = function ( e ) {
11482 if (
11483 ( e.which === OO.ui.Keys.ENTER && ( e.ctrlKey || e.metaKey ) ) ||
11484 // Some platforms emit keycode 10 for Control+Enter keypress in a textarea
11485 e.which === 10
11486 ) {
11487 this.emit( 'enter', e );
11488 }
11489 };
11490
11491 /**
11492 * Automatically adjust the size of the text input.
11493 *
11494 * This only affects multiline inputs that are {@link #autosize autosized}.
11495 *
11496 * @chainable
11497 * @return {OO.ui.Widget} The widget, for chaining
11498 * @fires resize
11499 */
11500 OO.ui.MultilineTextInputWidget.prototype.adjustSize = function () {
11501 var scrollHeight, innerHeight, outerHeight, maxInnerHeight, measurementError,
11502 idealHeight, newHeight, scrollWidth, property;
11503
11504 if ( this.$input.val() !== this.valCache ) {
11505 if ( this.autosize ) {
11506 this.$clone
11507 .val( this.$input.val() )
11508 .attr( 'rows', this.minRows )
11509 // Set inline height property to 0 to measure scroll height
11510 .css( 'height', 0 );
11511
11512 this.$clone.removeClass( 'oo-ui-element-hidden' );
11513
11514 this.valCache = this.$input.val();
11515
11516 scrollHeight = this.$clone[ 0 ].scrollHeight;
11517
11518 // Remove inline height property to measure natural heights
11519 this.$clone.css( 'height', '' );
11520 innerHeight = this.$clone.innerHeight();
11521 outerHeight = this.$clone.outerHeight();
11522
11523 // Measure max rows height
11524 this.$clone
11525 .attr( 'rows', this.maxRows )
11526 .css( 'height', 'auto' )
11527 .val( '' );
11528 maxInnerHeight = this.$clone.innerHeight();
11529
11530 // Difference between reported innerHeight and scrollHeight with no scrollbars present.
11531 // This is sometimes non-zero on Blink-based browsers, depending on zoom level.
11532 measurementError = maxInnerHeight - this.$clone[ 0 ].scrollHeight;
11533 idealHeight = Math.min( maxInnerHeight, scrollHeight + measurementError );
11534
11535 this.$clone.addClass( 'oo-ui-element-hidden' );
11536
11537 // Only apply inline height when expansion beyond natural height is needed
11538 // Use the difference between the inner and outer height as a buffer
11539 newHeight = idealHeight > innerHeight ? idealHeight + ( outerHeight - innerHeight ) : '';
11540 if ( newHeight !== this.styleHeight ) {
11541 this.$input.css( 'height', newHeight );
11542 this.styleHeight = newHeight;
11543 this.emit( 'resize' );
11544 }
11545 }
11546 scrollWidth = this.$input[ 0 ].offsetWidth - this.$input[ 0 ].clientWidth;
11547 if ( scrollWidth !== this.scrollWidth ) {
11548 property = this.$element.css( 'direction' ) === 'rtl' ? 'left' : 'right';
11549 // Reset
11550 this.$label.css( { right: '', left: '' } );
11551 this.$indicator.css( { right: '', left: '' } );
11552
11553 if ( scrollWidth ) {
11554 this.$indicator.css( property, scrollWidth );
11555 if ( this.labelPosition === 'after' ) {
11556 this.$label.css( property, scrollWidth );
11557 }
11558 }
11559
11560 this.scrollWidth = scrollWidth;
11561 this.positionLabel();
11562 }
11563 }
11564 return this;
11565 };
11566
11567 /**
11568 * @inheritdoc
11569 * @protected
11570 */
11571 OO.ui.MultilineTextInputWidget.prototype.getInputElement = function () {
11572 return $( '<textarea>' );
11573 };
11574
11575 /**
11576 * Check if the input automatically adjusts its size.
11577 *
11578 * @return {boolean}
11579 */
11580 OO.ui.MultilineTextInputWidget.prototype.isAutosizing = function () {
11581 return !!this.autosize;
11582 };
11583
11584 /**
11585 * @inheritdoc
11586 */
11587 OO.ui.MultilineTextInputWidget.prototype.restorePreInfuseState = function ( state ) {
11588 OO.ui.MultilineTextInputWidget.parent.prototype.restorePreInfuseState.call( this, state );
11589 if ( state.scrollTop !== undefined ) {
11590 this.$input.scrollTop( state.scrollTop );
11591 }
11592 };
11593
11594 /**
11595 * ComboBoxInputWidgets combine a {@link OO.ui.TextInputWidget text input} (where a value
11596 * can be entered manually) and a {@link OO.ui.MenuSelectWidget menu of options} (from which
11597 * a value can be chosen instead). Users can choose options from the combo box in one of two ways:
11598 *
11599 * - by typing a value in the text input field. If the value exactly matches the value of a menu
11600 * option, that option will appear to be selected.
11601 * - by choosing a value from the menu. The value of the chosen option will then appear in the text
11602 * input field.
11603 *
11604 * After the user chooses an option, its `data` will be used as a new value for the widget.
11605 * A `label` also can be specified for each option: if given, it will be shown instead of the
11606 * `data` in the dropdown menu.
11607 *
11608 * This widget can be used inside an HTML form, such as a OO.ui.FormLayout.
11609 *
11610 * For more information about menus and options, please see the
11611 * [OOUI documentation on MediaWiki][1].
11612 *
11613 * @example
11614 * // A ComboBoxInputWidget.
11615 * var comboBox = new OO.ui.ComboBoxInputWidget( {
11616 * value: 'Option 1',
11617 * options: [
11618 * { data: 'Option 1' },
11619 * { data: 'Option 2' },
11620 * { data: 'Option 3' }
11621 * ]
11622 * } );
11623 * $( document.body ).append( comboBox.$element );
11624 *
11625 * @example
11626 * // Example: A ComboBoxInputWidget with additional option labels.
11627 * var comboBox = new OO.ui.ComboBoxInputWidget( {
11628 * value: 'Option 1',
11629 * options: [
11630 * {
11631 * data: 'Option 1',
11632 * label: 'Option One'
11633 * },
11634 * {
11635 * data: 'Option 2',
11636 * label: 'Option Two'
11637 * },
11638 * {
11639 * data: 'Option 3',
11640 * label: 'Option Three'
11641 * }
11642 * ]
11643 * } );
11644 * $( document.body ).append( comboBox.$element );
11645 *
11646 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options#Menu_selects_and_options
11647 *
11648 * @class
11649 * @extends OO.ui.TextInputWidget
11650 *
11651 * @constructor
11652 * @param {Object} [config] Configuration options
11653 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
11654 * @cfg {Object} [menu] Configuration options to pass to the {@link OO.ui.MenuSelectWidget menu
11655 * select widget}.
11656 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful
11657 * in cases where the expanded menu is larger than its containing `<div>`. The specified overlay
11658 * layer is usually on top of the containing `<div>` and has a larger area. By default, the menu
11659 * uses relative positioning.
11660 * See <https://www.mediawiki.org/wiki/OOUI/Concepts#Overlays>.
11661 */
11662 OO.ui.ComboBoxInputWidget = function OoUiComboBoxInputWidget( config ) {
11663 // Configuration initialization
11664 config = $.extend( {
11665 autocomplete: false
11666 }, config );
11667
11668 // ComboBoxInputWidget shouldn't support `multiline`
11669 config.multiline = false;
11670
11671 // See InputWidget#reusePreInfuseDOM about `config.$input`
11672 if ( config.$input ) {
11673 config.$input.removeAttr( 'list' );
11674 }
11675
11676 // Parent constructor
11677 OO.ui.ComboBoxInputWidget.parent.call( this, config );
11678
11679 // Properties
11680 this.$overlay = ( config.$overlay === true ?
11681 OO.ui.getDefaultOverlay() : config.$overlay ) || this.$element;
11682 this.dropdownButton = new OO.ui.ButtonWidget( {
11683 classes: [ 'oo-ui-comboBoxInputWidget-dropdownButton' ],
11684 label: OO.ui.msg( 'ooui-combobox-button-label' ),
11685 indicator: 'down',
11686 invisibleLabel: true,
11687 disabled: this.disabled
11688 } );
11689 this.menu = new OO.ui.MenuSelectWidget( $.extend(
11690 {
11691 widget: this,
11692 input: this,
11693 $floatableContainer: this.$element,
11694 disabled: this.isDisabled()
11695 },
11696 config.menu
11697 ) );
11698
11699 // Events
11700 this.connect( this, {
11701 change: 'onInputChange',
11702 enter: 'onInputEnter'
11703 } );
11704 this.dropdownButton.connect( this, {
11705 click: 'onDropdownButtonClick'
11706 } );
11707 this.menu.connect( this, {
11708 choose: 'onMenuChoose',
11709 add: 'onMenuItemsChange',
11710 remove: 'onMenuItemsChange',
11711 toggle: 'onMenuToggle'
11712 } );
11713
11714 // Initialization
11715 this.$input.attr( {
11716 role: 'combobox',
11717 'aria-owns': this.menu.getElementId(),
11718 'aria-autocomplete': 'list'
11719 } );
11720 this.dropdownButton.$button.attr( {
11721 'aria-controls': this.menu.getElementId()
11722 } );
11723 // Do not override options set via config.menu.items
11724 if ( config.options !== undefined ) {
11725 this.setOptions( config.options );
11726 }
11727 this.$field = $( '<div>' )
11728 .addClass( 'oo-ui-comboBoxInputWidget-field' )
11729 .append( this.$input, this.dropdownButton.$element );
11730 this.$element
11731 .addClass( 'oo-ui-comboBoxInputWidget' )
11732 .append( this.$field );
11733 this.$overlay.append( this.menu.$element );
11734 this.onMenuItemsChange();
11735 };
11736
11737 /* Setup */
11738
11739 OO.inheritClass( OO.ui.ComboBoxInputWidget, OO.ui.TextInputWidget );
11740
11741 /* Methods */
11742
11743 /**
11744 * Get the combobox's menu.
11745 *
11746 * @return {OO.ui.MenuSelectWidget} Menu widget
11747 */
11748 OO.ui.ComboBoxInputWidget.prototype.getMenu = function () {
11749 return this.menu;
11750 };
11751
11752 /**
11753 * Get the combobox's text input widget.
11754 *
11755 * @return {OO.ui.TextInputWidget} Text input widget
11756 */
11757 OO.ui.ComboBoxInputWidget.prototype.getInput = function () {
11758 return this;
11759 };
11760
11761 /**
11762 * Handle input change events.
11763 *
11764 * @private
11765 * @param {string} value New value
11766 */
11767 OO.ui.ComboBoxInputWidget.prototype.onInputChange = function ( value ) {
11768 var match = this.menu.findItemFromData( value );
11769
11770 this.menu.selectItem( match );
11771 if ( this.menu.findHighlightedItem() ) {
11772 this.menu.highlightItem( match );
11773 }
11774
11775 if ( !this.isDisabled() ) {
11776 this.menu.toggle( true );
11777 }
11778 };
11779
11780 /**
11781 * Handle input enter events.
11782 *
11783 * @private
11784 */
11785 OO.ui.ComboBoxInputWidget.prototype.onInputEnter = function () {
11786 if ( !this.isDisabled() ) {
11787 this.menu.toggle( false );
11788 }
11789 };
11790
11791 /**
11792 * Handle button click events.
11793 *
11794 * @private
11795 */
11796 OO.ui.ComboBoxInputWidget.prototype.onDropdownButtonClick = function () {
11797 this.menu.toggle();
11798 this.focus();
11799 };
11800
11801 /**
11802 * Handle menu choose events.
11803 *
11804 * @private
11805 * @param {OO.ui.OptionWidget} item Chosen item
11806 */
11807 OO.ui.ComboBoxInputWidget.prototype.onMenuChoose = function ( item ) {
11808 this.setValue( item.getData() );
11809 };
11810
11811 /**
11812 * Handle menu item change events.
11813 *
11814 * @private
11815 */
11816 OO.ui.ComboBoxInputWidget.prototype.onMenuItemsChange = function () {
11817 var match = this.menu.findItemFromData( this.getValue() );
11818 this.menu.selectItem( match );
11819 if ( this.menu.findHighlightedItem() ) {
11820 this.menu.highlightItem( match );
11821 }
11822 this.$element.toggleClass( 'oo-ui-comboBoxInputWidget-empty', this.menu.isEmpty() );
11823 };
11824
11825 /**
11826 * Handle menu toggle events.
11827 *
11828 * @private
11829 * @param {boolean} isVisible Open state of the menu
11830 */
11831 OO.ui.ComboBoxInputWidget.prototype.onMenuToggle = function ( isVisible ) {
11832 this.$element.toggleClass( 'oo-ui-comboBoxInputWidget-open', isVisible );
11833 };
11834
11835 /**
11836 * Update the disabled state of the controls
11837 *
11838 * @chainable
11839 * @protected
11840 * @return {OO.ui.ComboBoxInputWidget} The widget, for chaining
11841 */
11842 OO.ui.ComboBoxInputWidget.prototype.updateControlsDisabled = function () {
11843 var disabled = this.isDisabled() || this.isReadOnly();
11844 if ( this.dropdownButton ) {
11845 this.dropdownButton.setDisabled( disabled );
11846 }
11847 if ( this.menu ) {
11848 this.menu.setDisabled( disabled );
11849 }
11850 return this;
11851 };
11852
11853 /**
11854 * @inheritdoc
11855 */
11856 OO.ui.ComboBoxInputWidget.prototype.setDisabled = function () {
11857 // Parent method
11858 OO.ui.ComboBoxInputWidget.parent.prototype.setDisabled.apply( this, arguments );
11859 this.updateControlsDisabled();
11860 return this;
11861 };
11862
11863 /**
11864 * @inheritdoc
11865 */
11866 OO.ui.ComboBoxInputWidget.prototype.setReadOnly = function () {
11867 // Parent method
11868 OO.ui.ComboBoxInputWidget.parent.prototype.setReadOnly.apply( this, arguments );
11869 this.updateControlsDisabled();
11870 return this;
11871 };
11872
11873 /**
11874 * Set the options available for this input.
11875 *
11876 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
11877 * @chainable
11878 * @return {OO.ui.Widget} The widget, for chaining
11879 */
11880 OO.ui.ComboBoxInputWidget.prototype.setOptions = function ( options ) {
11881 this.getMenu()
11882 .clearItems()
11883 .addItems( options.map( function ( opt ) {
11884 return new OO.ui.MenuOptionWidget( {
11885 data: opt.data,
11886 label: opt.label !== undefined ? opt.label : opt.data
11887 } );
11888 } ) );
11889
11890 return this;
11891 };
11892
11893 /**
11894 * FieldLayouts are used with OO.ui.FieldsetLayout. Each FieldLayout requires a field-widget,
11895 * which is a widget that is specified by reference before any optional configuration settings.
11896 *
11897 * Field layouts can be configured with help text and/or labels. Labels are aligned in one of
11898 * four ways:
11899 *
11900 * - **left**: The label is placed before the field-widget and aligned with the left margin.
11901 * A left-alignment is used for forms with many fields.
11902 * - **right**: The label is placed before the field-widget and aligned to the right margin.
11903 * A right-alignment is used for long but familiar forms which users tab through,
11904 * verifying the current field with a quick glance at the label.
11905 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
11906 * that users fill out from top to bottom.
11907 * - **inline**: The label is placed after the field-widget and aligned to the left.
11908 * An inline-alignment is best used with checkboxes or radio buttons.
11909 *
11910 * Help text can either be:
11911 *
11912 * - accessed via a help icon that appears in the upper right corner of the rendered field layout,
11913 * or
11914 * - shown as a subtle explanation below the label.
11915 *
11916 * If the help text is brief, or is essential to always expose it, set `helpInline` to `true`.
11917 * If it is long or not essential, leave `helpInline` to its default, `false`.
11918 *
11919 * Please see the [OOUI documentation on MediaWiki] [1] for examples and more information.
11920 *
11921 * [1]: https://www.mediawiki.org/wiki/OOUI/Layouts/Fields_and_Fieldsets
11922 *
11923 * @class
11924 * @extends OO.ui.Layout
11925 * @mixins OO.ui.mixin.LabelElement
11926 * @mixins OO.ui.mixin.TitledElement
11927 *
11928 * @constructor
11929 * @param {OO.ui.Widget} fieldWidget Field widget
11930 * @param {Object} [config] Configuration options
11931 * @cfg {string} [align='left'] Alignment of the label: 'left', 'right', 'top'
11932 * or 'inline'
11933 * @cfg {Array} [errors] Error messages about the widget, which will be
11934 * displayed below the widget.
11935 * @cfg {Array} [warnings] Warning messages about the widget, which will be
11936 * displayed below the widget.
11937 * @cfg {Array} [successMessages] Success messages on user interactions with the widget,
11938 * which will be displayed below the widget.
11939 * The array may contain strings or OO.ui.HtmlSnippet instances.
11940 * @cfg {Array} [notices] Notices about the widget, which will be displayed
11941 * below the widget.
11942 * The array may contain strings or OO.ui.HtmlSnippet instances.
11943 * These are more visible than `help` messages when `helpInline` is set, and so
11944 * might be good for transient messages.
11945 * @cfg {string|OO.ui.HtmlSnippet} [help] Help text. When help text is specified
11946 * and `helpInline` is `false`, a "help" icon will appear in the upper-right
11947 * corner of the rendered field; clicking it will display the text in a popup.
11948 * If `helpInline` is `true`, then a subtle description will be shown after the
11949 * label.
11950 * @cfg {boolean} [helpInline=false] Whether or not the help should be inline,
11951 * or shown when the "help" icon is clicked.
11952 * @cfg {jQuery} [$overlay] Passed to OO.ui.PopupButtonWidget for help popup, if
11953 * `help` is given.
11954 * See <https://www.mediawiki.org/wiki/OOUI/Concepts#Overlays>.
11955 *
11956 * @throws {Error} An error is thrown if no widget is specified
11957 */
11958 OO.ui.FieldLayout = function OoUiFieldLayout( fieldWidget, config ) {
11959 // Allow passing positional parameters inside the config object
11960 if ( OO.isPlainObject( fieldWidget ) && config === undefined ) {
11961 config = fieldWidget;
11962 fieldWidget = config.fieldWidget;
11963 }
11964
11965 // Make sure we have required constructor arguments
11966 if ( fieldWidget === undefined ) {
11967 throw new Error( 'Widget not found' );
11968 }
11969
11970 // Configuration initialization
11971 config = $.extend( { align: 'left', helpInline: false }, config );
11972
11973 // Parent constructor
11974 OO.ui.FieldLayout.parent.call( this, config );
11975
11976 // Mixin constructors
11977 OO.ui.mixin.LabelElement.call( this, $.extend( {
11978 $label: $( '<label>' )
11979 }, config ) );
11980 OO.ui.mixin.TitledElement.call( this, $.extend( { $titled: this.$label }, config ) );
11981
11982 // Properties
11983 this.fieldWidget = fieldWidget;
11984 this.errors = [];
11985 this.warnings = [];
11986 this.successMessages = [];
11987 this.notices = [];
11988 this.$field = this.isFieldInline() ? $( '<span>' ) : $( '<div>' );
11989 this.$messages = $( '<ul>' );
11990 this.$header = $( '<span>' );
11991 this.$body = $( '<div>' );
11992 this.align = null;
11993 this.helpInline = config.helpInline;
11994
11995 // Events
11996 this.fieldWidget.connect( this, {
11997 disable: 'onFieldDisable'
11998 } );
11999
12000 // Initialization
12001 this.$help = config.help ?
12002 this.createHelpElement( config.help, config.$overlay ) :
12003 $( [] );
12004 if ( this.fieldWidget.getInputId() ) {
12005 this.$label.attr( 'for', this.fieldWidget.getInputId() );
12006 if ( this.helpInline ) {
12007 this.$help.attr( 'for', this.fieldWidget.getInputId() );
12008 }
12009 } else {
12010 this.$label.on( 'click', function () {
12011 this.fieldWidget.simulateLabelClick();
12012 }.bind( this ) );
12013 if ( this.helpInline ) {
12014 this.$help.on( 'click', function () {
12015 this.fieldWidget.simulateLabelClick();
12016 }.bind( this ) );
12017 }
12018 }
12019 this.$element
12020 .addClass( 'oo-ui-fieldLayout' )
12021 .toggleClass( 'oo-ui-fieldLayout-disabled', this.fieldWidget.isDisabled() )
12022 .append( this.$body );
12023 this.$body.addClass( 'oo-ui-fieldLayout-body' );
12024 this.$header.addClass( 'oo-ui-fieldLayout-header' );
12025 this.$messages.addClass( 'oo-ui-fieldLayout-messages' );
12026 this.$field
12027 .addClass( 'oo-ui-fieldLayout-field' )
12028 .append( this.fieldWidget.$element );
12029
12030 this.setErrors( config.errors || [] );
12031 this.setWarnings( config.warnings || [] );
12032 this.setSuccess( config.successMessages || [] );
12033 this.setNotices( config.notices || [] );
12034 this.setAlignment( config.align );
12035 // Call this again to take into account the widget's accessKey
12036 this.updateTitle();
12037 };
12038
12039 /* Setup */
12040
12041 OO.inheritClass( OO.ui.FieldLayout, OO.ui.Layout );
12042 OO.mixinClass( OO.ui.FieldLayout, OO.ui.mixin.LabelElement );
12043 OO.mixinClass( OO.ui.FieldLayout, OO.ui.mixin.TitledElement );
12044
12045 /* Methods */
12046
12047 /**
12048 * Handle field disable events.
12049 *
12050 * @private
12051 * @param {boolean} value Field is disabled
12052 */
12053 OO.ui.FieldLayout.prototype.onFieldDisable = function ( value ) {
12054 this.$element.toggleClass( 'oo-ui-fieldLayout-disabled', value );
12055 };
12056
12057 /**
12058 * Get the widget contained by the field.
12059 *
12060 * @return {OO.ui.Widget} Field widget
12061 */
12062 OO.ui.FieldLayout.prototype.getField = function () {
12063 return this.fieldWidget;
12064 };
12065
12066 /**
12067 * Return `true` if the given field widget can be used with `'inline'` alignment (see
12068 * #setAlignment). Return `false` if it can't or if this can't be determined.
12069 *
12070 * @return {boolean}
12071 */
12072 OO.ui.FieldLayout.prototype.isFieldInline = function () {
12073 // This is very simplistic, but should be good enough.
12074 return this.getField().$element.prop( 'tagName' ).toLowerCase() === 'span';
12075 };
12076
12077 /**
12078 * @protected
12079 * @param {string} kind 'error' or 'notice'
12080 * @param {string|OO.ui.HtmlSnippet} text
12081 * @return {jQuery}
12082 */
12083 OO.ui.FieldLayout.prototype.makeMessage = function ( kind, text ) {
12084 var $listItem, $icon, message;
12085 $listItem = $( '<li>' );
12086 if ( kind === 'error' ) {
12087 $icon = new OO.ui.IconWidget( { icon: 'error', flags: [ 'error' ] } ).$element;
12088 $listItem.attr( 'role', 'alert' );
12089 } else if ( kind === 'warning' ) {
12090 $icon = new OO.ui.IconWidget( { icon: 'alert', flags: [ 'warning' ] } ).$element;
12091 $listItem.attr( 'role', 'alert' );
12092 } else if ( kind === 'success' ) {
12093 $icon = new OO.ui.IconWidget( { icon: 'check', flags: [ 'success' ] } ).$element;
12094 } else if ( kind === 'notice' ) {
12095 $icon = new OO.ui.IconWidget( { icon: 'notice' } ).$element;
12096 } else {
12097 $icon = '';
12098 }
12099 message = new OO.ui.LabelWidget( { label: text } );
12100 $listItem
12101 .append( $icon, message.$element )
12102 .addClass( 'oo-ui-fieldLayout-messages-' + kind );
12103 return $listItem;
12104 };
12105
12106 /**
12107 * Set the field alignment mode.
12108 *
12109 * @private
12110 * @param {string} value Alignment mode, either 'left', 'right', 'top' or 'inline'
12111 * @chainable
12112 * @return {OO.ui.BookletLayout} The layout, for chaining
12113 */
12114 OO.ui.FieldLayout.prototype.setAlignment = function ( value ) {
12115 if ( value !== this.align ) {
12116 // Default to 'left'
12117 if ( [ 'left', 'right', 'top', 'inline' ].indexOf( value ) === -1 ) {
12118 value = 'left';
12119 }
12120 // Validate
12121 if ( value === 'inline' && !this.isFieldInline() ) {
12122 value = 'top';
12123 }
12124 // Reorder elements
12125
12126 if ( this.helpInline ) {
12127 if ( value === 'top' ) {
12128 this.$header.append( this.$label );
12129 this.$body.append( this.$header, this.$field, this.$help );
12130 } else if ( value === 'inline' ) {
12131 this.$header.append( this.$label, this.$help );
12132 this.$body.append( this.$field, this.$header );
12133 } else {
12134 this.$header.append( this.$label, this.$help );
12135 this.$body.append( this.$header, this.$field );
12136 }
12137 } else {
12138 if ( value === 'top' ) {
12139 this.$header.append( this.$help, this.$label );
12140 this.$body.append( this.$header, this.$field );
12141 } else if ( value === 'inline' ) {
12142 this.$header.append( this.$help, this.$label );
12143 this.$body.append( this.$field, this.$header );
12144 } else {
12145 this.$header.append( this.$label );
12146 this.$body.append( this.$header, this.$help, this.$field );
12147 }
12148 }
12149 // Set classes. The following classes can be used here:
12150 // * oo-ui-fieldLayout-align-left
12151 // * oo-ui-fieldLayout-align-right
12152 // * oo-ui-fieldLayout-align-top
12153 // * oo-ui-fieldLayout-align-inline
12154 if ( this.align ) {
12155 this.$element.removeClass( 'oo-ui-fieldLayout-align-' + this.align );
12156 }
12157 this.$element.addClass( 'oo-ui-fieldLayout-align-' + value );
12158 this.align = value;
12159 }
12160
12161 return this;
12162 };
12163
12164 /**
12165 * Set the list of error messages.
12166 *
12167 * @param {Array} errors Error messages about the widget, which will be displayed below the widget.
12168 * The array may contain strings or OO.ui.HtmlSnippet instances.
12169 * @chainable
12170 * @return {OO.ui.BookletLayout} The layout, for chaining
12171 */
12172 OO.ui.FieldLayout.prototype.setErrors = function ( errors ) {
12173 this.errors = errors.slice();
12174 this.updateMessages();
12175 return this;
12176 };
12177
12178 /**
12179 * Set the list of warning messages.
12180 *
12181 * @param {Array} warnings Warning messages about the widget, which will be displayed below
12182 * the widget.
12183 * The array may contain strings or OO.ui.HtmlSnippet instances.
12184 * @chainable
12185 * @return {OO.ui.BookletLayout} The layout, for chaining
12186 */
12187 OO.ui.FieldLayout.prototype.setWarnings = function ( warnings ) {
12188 this.warnings = warnings.slice();
12189 this.updateMessages();
12190 return this;
12191 };
12192
12193 /**
12194 * Set the list of success messages.
12195 *
12196 * @param {Array} successMessages Success messages about the widget, which will be displayed below
12197 * the widget.
12198 * The array may contain strings or OO.ui.HtmlSnippet instances.
12199 * @chainable
12200 * @return {OO.ui.BookletLayout} The layout, for chaining
12201 */
12202 OO.ui.FieldLayout.prototype.setSuccess = function ( successMessages ) {
12203 this.successMessages = successMessages.slice();
12204 this.updateMessages();
12205 return this;
12206 };
12207
12208 /**
12209 * Set the list of notice messages.
12210 *
12211 * @param {Array} notices Notices about the widget, which will be displayed below the widget.
12212 * The array may contain strings or OO.ui.HtmlSnippet instances.
12213 * @chainable
12214 * @return {OO.ui.BookletLayout} The layout, for chaining
12215 */
12216 OO.ui.FieldLayout.prototype.setNotices = function ( notices ) {
12217 this.notices = notices.slice();
12218 this.updateMessages();
12219 return this;
12220 };
12221
12222 /**
12223 * Update the rendering of error, warning, success and notice messages.
12224 *
12225 * @private
12226 */
12227 OO.ui.FieldLayout.prototype.updateMessages = function () {
12228 var i;
12229 this.$messages.empty();
12230
12231 if (
12232 this.errors.length ||
12233 this.warnings.length ||
12234 this.successMessages.length ||
12235 this.notices.length
12236 ) {
12237 this.$body.after( this.$messages );
12238 } else {
12239 this.$messages.remove();
12240 return;
12241 }
12242
12243 for ( i = 0; i < this.errors.length; i++ ) {
12244 this.$messages.append( this.makeMessage( 'error', this.errors[ i ] ) );
12245 }
12246 for ( i = 0; i < this.warnings.length; i++ ) {
12247 this.$messages.append( this.makeMessage( 'warning', this.warnings[ i ] ) );
12248 }
12249 for ( i = 0; i < this.successMessages.length; i++ ) {
12250 this.$messages.append( this.makeMessage( 'success', this.successMessages[ i ] ) );
12251 }
12252 for ( i = 0; i < this.notices.length; i++ ) {
12253 this.$messages.append( this.makeMessage( 'notice', this.notices[ i ] ) );
12254 }
12255 };
12256
12257 /**
12258 * Include information about the widget's accessKey in our title. TitledElement calls this method.
12259 * (This is a bit of a hack.)
12260 *
12261 * @protected
12262 * @param {string} title Tooltip label for 'title' attribute
12263 * @return {string}
12264 */
12265 OO.ui.FieldLayout.prototype.formatTitleWithAccessKey = function ( title ) {
12266 if ( this.fieldWidget && this.fieldWidget.formatTitleWithAccessKey ) {
12267 return this.fieldWidget.formatTitleWithAccessKey( title );
12268 }
12269 return title;
12270 };
12271
12272 /**
12273 * Creates and returns the help element. Also sets the `aria-describedby`
12274 * attribute on the main element of the `fieldWidget`.
12275 *
12276 * @private
12277 * @param {string|OO.ui.HtmlSnippet} [help] Help text.
12278 * @param {jQuery} [$overlay] Passed to OO.ui.PopupButtonWidget for help popup.
12279 * @return {jQuery} The element that should become `this.$help`.
12280 */
12281 OO.ui.FieldLayout.prototype.createHelpElement = function ( help, $overlay ) {
12282 var helpId, helpWidget;
12283
12284 if ( this.helpInline ) {
12285 helpWidget = new OO.ui.LabelWidget( {
12286 label: help,
12287 classes: [ 'oo-ui-inline-help' ]
12288 } );
12289
12290 helpId = helpWidget.getElementId();
12291 } else {
12292 helpWidget = new OO.ui.PopupButtonWidget( {
12293 $overlay: $overlay,
12294 popup: {
12295 padded: true
12296 },
12297 classes: [ 'oo-ui-fieldLayout-help' ],
12298 framed: false,
12299 icon: 'info',
12300 label: OO.ui.msg( 'ooui-field-help' ),
12301 invisibleLabel: true
12302 } );
12303 if ( help instanceof OO.ui.HtmlSnippet ) {
12304 helpWidget.getPopup().$body.html( help.toString() );
12305 } else {
12306 helpWidget.getPopup().$body.text( help );
12307 }
12308
12309 helpId = helpWidget.getPopup().getBodyId();
12310 }
12311
12312 // Set the 'aria-describedby' attribute on the fieldWidget
12313 // Preference given to an input or a button
12314 (
12315 this.fieldWidget.$input ||
12316 this.fieldWidget.$button ||
12317 this.fieldWidget.$element
12318 ).attr( 'aria-describedby', helpId );
12319
12320 return helpWidget.$element;
12321 };
12322
12323 /**
12324 * ActionFieldLayouts are used with OO.ui.FieldsetLayout. The layout consists of a field-widget,
12325 * a button, and an optional label and/or help text. The field-widget (e.g., a
12326 * {@link OO.ui.TextInputWidget TextInputWidget}), is required and is specified before any optional
12327 * configuration settings.
12328 *
12329 * Labels can be aligned in one of four ways:
12330 *
12331 * - **left**: The label is placed before the field-widget and aligned with the left margin.
12332 * A left-alignment is used for forms with many fields.
12333 * - **right**: The label is placed before the field-widget and aligned to the right margin.
12334 * A right-alignment is used for long but familiar forms which users tab through,
12335 * verifying the current field with a quick glance at the label.
12336 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
12337 * that users fill out from top to bottom.
12338 * - **inline**: The label is placed after the field-widget and aligned to the left.
12339 * An inline-alignment is best used with checkboxes or radio buttons.
12340 *
12341 * Help text is accessed via a help icon that appears in the upper right corner of the rendered
12342 * field layout when help text is specified.
12343 *
12344 * @example
12345 * // Example of an ActionFieldLayout
12346 * var actionFieldLayout = new OO.ui.ActionFieldLayout(
12347 * new OO.ui.TextInputWidget( {
12348 * placeholder: 'Field widget'
12349 * } ),
12350 * new OO.ui.ButtonWidget( {
12351 * label: 'Button'
12352 * } ),
12353 * {
12354 * label: 'An ActionFieldLayout. This label is aligned top',
12355 * align: 'top',
12356 * help: 'This is help text'
12357 * }
12358 * );
12359 *
12360 * $( document.body ).append( actionFieldLayout.$element );
12361 *
12362 * @class
12363 * @extends OO.ui.FieldLayout
12364 *
12365 * @constructor
12366 * @param {OO.ui.Widget} fieldWidget Field widget
12367 * @param {OO.ui.ButtonWidget} buttonWidget Button widget
12368 * @param {Object} config
12369 */
12370 OO.ui.ActionFieldLayout = function OoUiActionFieldLayout( fieldWidget, buttonWidget, config ) {
12371 // Allow passing positional parameters inside the config object
12372 if ( OO.isPlainObject( fieldWidget ) && config === undefined ) {
12373 config = fieldWidget;
12374 fieldWidget = config.fieldWidget;
12375 buttonWidget = config.buttonWidget;
12376 }
12377
12378 // Parent constructor
12379 OO.ui.ActionFieldLayout.parent.call( this, fieldWidget, config );
12380
12381 // Properties
12382 this.buttonWidget = buttonWidget;
12383 this.$button = $( '<span>' );
12384 this.$input = this.isFieldInline() ? $( '<span>' ) : $( '<div>' );
12385
12386 // Initialization
12387 this.$element.addClass( 'oo-ui-actionFieldLayout' );
12388 this.$button
12389 .addClass( 'oo-ui-actionFieldLayout-button' )
12390 .append( this.buttonWidget.$element );
12391 this.$input
12392 .addClass( 'oo-ui-actionFieldLayout-input' )
12393 .append( this.fieldWidget.$element );
12394 this.$field.append( this.$input, this.$button );
12395 };
12396
12397 /* Setup */
12398
12399 OO.inheritClass( OO.ui.ActionFieldLayout, OO.ui.FieldLayout );
12400
12401 /**
12402 * FieldsetLayouts are composed of one or more {@link OO.ui.FieldLayout FieldLayouts},
12403 * which each contain an individual widget and, optionally, a label. Each Fieldset can be
12404 * configured with a label as well. For more information and examples,
12405 * please see the [OOUI documentation on MediaWiki][1].
12406 *
12407 * @example
12408 * // Example of a fieldset layout
12409 * var input1 = new OO.ui.TextInputWidget( {
12410 * placeholder: 'A text input field'
12411 * } );
12412 *
12413 * var input2 = new OO.ui.TextInputWidget( {
12414 * placeholder: 'A text input field'
12415 * } );
12416 *
12417 * var fieldset = new OO.ui.FieldsetLayout( {
12418 * label: 'Example of a fieldset layout'
12419 * } );
12420 *
12421 * fieldset.addItems( [
12422 * new OO.ui.FieldLayout( input1, {
12423 * label: 'Field One'
12424 * } ),
12425 * new OO.ui.FieldLayout( input2, {
12426 * label: 'Field Two'
12427 * } )
12428 * ] );
12429 * $( document.body ).append( fieldset.$element );
12430 *
12431 * [1]: https://www.mediawiki.org/wiki/OOUI/Layouts/Fields_and_Fieldsets
12432 *
12433 * @class
12434 * @extends OO.ui.Layout
12435 * @mixins OO.ui.mixin.IconElement
12436 * @mixins OO.ui.mixin.LabelElement
12437 * @mixins OO.ui.mixin.GroupElement
12438 *
12439 * @constructor
12440 * @param {Object} [config] Configuration options
12441 * @cfg {OO.ui.FieldLayout[]} [items] An array of fields to add to the fieldset.
12442 * See OO.ui.FieldLayout for more information about fields.
12443 * @cfg {string|OO.ui.HtmlSnippet} [help] Help text. When help text is specified, a "help" icon
12444 * will appear in the upper-right corner of the rendered field; clicking it will display the text
12445 * in a popup. For important messages, you are advised to use `notices`, as they are always shown.
12446 * @cfg {jQuery} [$overlay] Passed to OO.ui.PopupButtonWidget for help popup, if `help` is given.
12447 * See <https://www.mediawiki.org/wiki/OOUI/Concepts#Overlays>.
12448 */
12449 OO.ui.FieldsetLayout = function OoUiFieldsetLayout( config ) {
12450 // Configuration initialization
12451 config = config || {};
12452
12453 // Parent constructor
12454 OO.ui.FieldsetLayout.parent.call( this, config );
12455
12456 // Mixin constructors
12457 OO.ui.mixin.IconElement.call( this, config );
12458 OO.ui.mixin.LabelElement.call( this, config );
12459 OO.ui.mixin.GroupElement.call( this, config );
12460
12461 // Properties
12462 this.$header = $( '<legend>' );
12463 if ( config.help ) {
12464 this.popupButtonWidget = new OO.ui.PopupButtonWidget( {
12465 $overlay: config.$overlay,
12466 popup: {
12467 padded: true
12468 },
12469 classes: [ 'oo-ui-fieldsetLayout-help' ],
12470 framed: false,
12471 icon: 'info',
12472 label: OO.ui.msg( 'ooui-field-help' ),
12473 invisibleLabel: true
12474 } );
12475 if ( config.help instanceof OO.ui.HtmlSnippet ) {
12476 this.popupButtonWidget.getPopup().$body.html( config.help.toString() );
12477 } else {
12478 this.popupButtonWidget.getPopup().$body.text( config.help );
12479 }
12480 this.$help = this.popupButtonWidget.$element;
12481 } else {
12482 this.$help = $( [] );
12483 }
12484
12485 // Initialization
12486 this.$header
12487 .addClass( 'oo-ui-fieldsetLayout-header' )
12488 .append( this.$icon, this.$label, this.$help );
12489 this.$group.addClass( 'oo-ui-fieldsetLayout-group' );
12490 this.$element
12491 .addClass( 'oo-ui-fieldsetLayout' )
12492 .prepend( this.$header, this.$group );
12493 if ( Array.isArray( config.items ) ) {
12494 this.addItems( config.items );
12495 }
12496 };
12497
12498 /* Setup */
12499
12500 OO.inheritClass( OO.ui.FieldsetLayout, OO.ui.Layout );
12501 OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.mixin.IconElement );
12502 OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.mixin.LabelElement );
12503 OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.mixin.GroupElement );
12504
12505 /* Static Properties */
12506
12507 /**
12508 * @static
12509 * @inheritdoc
12510 */
12511 OO.ui.FieldsetLayout.static.tagName = 'fieldset';
12512
12513 /**
12514 * FormLayouts are used to wrap {@link OO.ui.FieldsetLayout FieldsetLayouts} when you intend to use
12515 * browser-based form submission for the fields instead of handling them in JavaScript. Form layouts
12516 * can be configured with an HTML form action, an encoding type, and a method using the #action,
12517 * #enctype, and #method configs, respectively.
12518 * See the [OOUI documentation on MediaWiki] [1] for more information and examples.
12519 *
12520 * Only widgets from the {@link OO.ui.InputWidget InputWidget} family support form submission. It
12521 * includes standard form elements like {@link OO.ui.CheckboxInputWidget checkboxes}, {@link
12522 * OO.ui.RadioInputWidget radio buttons} and {@link OO.ui.TextInputWidget text fields}, as well as
12523 * some fancier controls. Some controls have both regular and InputWidget variants, for example
12524 * OO.ui.DropdownWidget and OO.ui.DropdownInputWidget – only the latter support form submission and
12525 * often have simplified APIs to match the capabilities of HTML forms.
12526 * See the [OOUI documentation on MediaWiki] [2] for more information about InputWidgets.
12527 *
12528 * [1]: https://www.mediawiki.org/wiki/OOUI/Layouts/Forms
12529 * [2]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
12530 *
12531 * @example
12532 * // Example of a form layout that wraps a fieldset layout.
12533 * var input1 = new OO.ui.TextInputWidget( {
12534 * placeholder: 'Username'
12535 * } ),
12536 * input2 = new OO.ui.TextInputWidget( {
12537 * placeholder: 'Password',
12538 * type: 'password'
12539 * } ),
12540 * submit = new OO.ui.ButtonInputWidget( {
12541 * label: 'Submit'
12542 * } ),
12543 * fieldset = new OO.ui.FieldsetLayout( {
12544 * label: 'A form layout'
12545 * } );
12546 *
12547 * fieldset.addItems( [
12548 * new OO.ui.FieldLayout( input1, {
12549 * label: 'Username',
12550 * align: 'top'
12551 * } ),
12552 * new OO.ui.FieldLayout( input2, {
12553 * label: 'Password',
12554 * align: 'top'
12555 * } ),
12556 * new OO.ui.FieldLayout( submit )
12557 * ] );
12558 * var form = new OO.ui.FormLayout( {
12559 * items: [ fieldset ],
12560 * action: '/api/formhandler',
12561 * method: 'get'
12562 * } )
12563 * $( document.body ).append( form.$element );
12564 *
12565 * @class
12566 * @extends OO.ui.Layout
12567 * @mixins OO.ui.mixin.GroupElement
12568 *
12569 * @constructor
12570 * @param {Object} [config] Configuration options
12571 * @cfg {string} [method] HTML form `method` attribute
12572 * @cfg {string} [action] HTML form `action` attribute
12573 * @cfg {string} [enctype] HTML form `enctype` attribute
12574 * @cfg {OO.ui.FieldsetLayout[]} [items] Fieldset layouts to add to the form layout.
12575 */
12576 OO.ui.FormLayout = function OoUiFormLayout( config ) {
12577 var action;
12578
12579 // Configuration initialization
12580 config = config || {};
12581
12582 // Parent constructor
12583 OO.ui.FormLayout.parent.call( this, config );
12584
12585 // Mixin constructors
12586 OO.ui.mixin.GroupElement.call( this, $.extend( { $group: this.$element }, config ) );
12587
12588 // Events
12589 this.$element.on( 'submit', this.onFormSubmit.bind( this ) );
12590
12591 // Make sure the action is safe
12592 action = config.action;
12593 if ( action !== undefined && !OO.ui.isSafeUrl( action ) ) {
12594 action = './' + action;
12595 }
12596
12597 // Initialization
12598 this.$element
12599 .addClass( 'oo-ui-formLayout' )
12600 .attr( {
12601 method: config.method,
12602 action: action,
12603 enctype: config.enctype
12604 } );
12605 if ( Array.isArray( config.items ) ) {
12606 this.addItems( config.items );
12607 }
12608 };
12609
12610 /* Setup */
12611
12612 OO.inheritClass( OO.ui.FormLayout, OO.ui.Layout );
12613 OO.mixinClass( OO.ui.FormLayout, OO.ui.mixin.GroupElement );
12614
12615 /* Events */
12616
12617 /**
12618 * A 'submit' event is emitted when the form is submitted.
12619 *
12620 * @event submit
12621 */
12622
12623 /* Static Properties */
12624
12625 /**
12626 * @static
12627 * @inheritdoc
12628 */
12629 OO.ui.FormLayout.static.tagName = 'form';
12630
12631 /* Methods */
12632
12633 /**
12634 * Handle form submit events.
12635 *
12636 * @private
12637 * @param {jQuery.Event} e Submit event
12638 * @fires submit
12639 * @return {OO.ui.FormLayout} The layout, for chaining
12640 */
12641 OO.ui.FormLayout.prototype.onFormSubmit = function () {
12642 if ( this.emit( 'submit' ) ) {
12643 return false;
12644 }
12645 };
12646
12647 /**
12648 * PanelLayouts expand to cover the entire area of their parent. They can be configured with
12649 * scrolling, padding, and a frame, and are often used together with
12650 * {@link OO.ui.StackLayout StackLayouts}.
12651 *
12652 * @example
12653 * // Example of a panel layout
12654 * var panel = new OO.ui.PanelLayout( {
12655 * expanded: false,
12656 * framed: true,
12657 * padded: true,
12658 * $content: $( '<p>A panel layout with padding and a frame.</p>' )
12659 * } );
12660 * $( document.body ).append( panel.$element );
12661 *
12662 * @class
12663 * @extends OO.ui.Layout
12664 *
12665 * @constructor
12666 * @param {Object} [config] Configuration options
12667 * @cfg {boolean} [scrollable=false] Allow vertical scrolling
12668 * @cfg {boolean} [padded=false] Add padding between the content and the edges of the panel.
12669 * @cfg {boolean} [expanded=true] Expand the panel to fill the entire parent element.
12670 * @cfg {boolean} [framed=false] Render the panel with a frame to visually separate it from outside
12671 * content.
12672 */
12673 OO.ui.PanelLayout = function OoUiPanelLayout( config ) {
12674 // Configuration initialization
12675 config = $.extend( {
12676 scrollable: false,
12677 padded: false,
12678 expanded: true,
12679 framed: false
12680 }, config );
12681
12682 // Parent constructor
12683 OO.ui.PanelLayout.parent.call( this, config );
12684
12685 // Initialization
12686 this.$element.addClass( 'oo-ui-panelLayout' );
12687 if ( config.scrollable ) {
12688 this.$element.addClass( 'oo-ui-panelLayout-scrollable' );
12689 }
12690 if ( config.padded ) {
12691 this.$element.addClass( 'oo-ui-panelLayout-padded' );
12692 }
12693 if ( config.expanded ) {
12694 this.$element.addClass( 'oo-ui-panelLayout-expanded' );
12695 }
12696 if ( config.framed ) {
12697 this.$element.addClass( 'oo-ui-panelLayout-framed' );
12698 }
12699 };
12700
12701 /* Setup */
12702
12703 OO.inheritClass( OO.ui.PanelLayout, OO.ui.Layout );
12704
12705 /* Static Methods */
12706
12707 /**
12708 * @inheritdoc
12709 */
12710 OO.ui.PanelLayout.static.reusePreInfuseDOM = function ( node, config ) {
12711 config = OO.ui.PanelLayout.parent.static.reusePreInfuseDOM( node, config );
12712 if ( config.preserveContent !== false ) {
12713 config.$content = $( node ).contents();
12714 }
12715 return config;
12716 };
12717
12718 /* Methods */
12719
12720 /**
12721 * Focus the panel layout
12722 *
12723 * The default implementation just focuses the first focusable element in the panel
12724 */
12725 OO.ui.PanelLayout.prototype.focus = function () {
12726 OO.ui.findFocusable( this.$element ).focus();
12727 };
12728
12729 /**
12730 * HorizontalLayout arranges its contents in a single line (using `display: inline-block` for its
12731 * items), with small margins between them. Convenient when you need to put a number of block-level
12732 * widgets on a single line next to each other.
12733 *
12734 * Note that inline elements, such as OO.ui.ButtonWidgets, do not need this wrapper.
12735 *
12736 * @example
12737 * // HorizontalLayout with a text input and a label.
12738 * var layout = new OO.ui.HorizontalLayout( {
12739 * items: [
12740 * new OO.ui.LabelWidget( { label: 'Label' } ),
12741 * new OO.ui.TextInputWidget( { value: 'Text' } )
12742 * ]
12743 * } );
12744 * $( document.body ).append( layout.$element );
12745 *
12746 * @class
12747 * @extends OO.ui.Layout
12748 * @mixins OO.ui.mixin.GroupElement
12749 *
12750 * @constructor
12751 * @param {Object} [config] Configuration options
12752 * @cfg {OO.ui.Widget[]|OO.ui.Layout[]} [items] Widgets or other layouts to add to the layout.
12753 */
12754 OO.ui.HorizontalLayout = function OoUiHorizontalLayout( config ) {
12755 // Configuration initialization
12756 config = config || {};
12757
12758 // Parent constructor
12759 OO.ui.HorizontalLayout.parent.call( this, config );
12760
12761 // Mixin constructors
12762 OO.ui.mixin.GroupElement.call( this, $.extend( { $group: this.$element }, config ) );
12763
12764 // Initialization
12765 this.$element.addClass( 'oo-ui-horizontalLayout' );
12766 if ( Array.isArray( config.items ) ) {
12767 this.addItems( config.items );
12768 }
12769 };
12770
12771 /* Setup */
12772
12773 OO.inheritClass( OO.ui.HorizontalLayout, OO.ui.Layout );
12774 OO.mixinClass( OO.ui.HorizontalLayout, OO.ui.mixin.GroupElement );
12775
12776 /**
12777 * NumberInputWidgets combine a {@link OO.ui.TextInputWidget text input} (where a value
12778 * can be entered manually) and two {@link OO.ui.ButtonWidget button widgets}
12779 * (to adjust the value in increments) to allow the user to enter a number.
12780 *
12781 * @example
12782 * // A NumberInputWidget.
12783 * var numberInput = new OO.ui.NumberInputWidget( {
12784 * label: 'NumberInputWidget',
12785 * input: { value: 5 },
12786 * min: 1,
12787 * max: 10
12788 * } );
12789 * $( document.body ).append( numberInput.$element );
12790 *
12791 * @class
12792 * @extends OO.ui.TextInputWidget
12793 *
12794 * @constructor
12795 * @param {Object} [config] Configuration options
12796 * @cfg {Object} [minusButton] Configuration options to pass to the
12797 * {@link OO.ui.ButtonWidget decrementing button widget}.
12798 * @cfg {Object} [plusButton] Configuration options to pass to the
12799 * {@link OO.ui.ButtonWidget incrementing button widget}.
12800 * @cfg {number} [min=-Infinity] Minimum allowed value
12801 * @cfg {number} [max=Infinity] Maximum allowed value
12802 * @cfg {number|null} [step] If specified, the field only accepts values that are multiples of this.
12803 * @cfg {number} [buttonStep=step||1] Delta when using the buttons or Up/Down arrow keys.
12804 * Defaults to `step` if specified, otherwise `1`.
12805 * @cfg {number} [pageStep=10*buttonStep] Delta when using the Page-up/Page-down keys.
12806 * Defaults to 10 times `buttonStep`.
12807 * @cfg {boolean} [showButtons=true] Whether to show the plus and minus buttons.
12808 */
12809 OO.ui.NumberInputWidget = function OoUiNumberInputWidget( config ) {
12810 var $field = $( '<div>' ).addClass( 'oo-ui-numberInputWidget-field' );
12811
12812 // Configuration initialization
12813 config = $.extend( {
12814 min: -Infinity,
12815 max: Infinity,
12816 showButtons: true
12817 }, config );
12818
12819 // For backward compatibility
12820 $.extend( config, config.input );
12821 this.input = this;
12822
12823 // Parent constructor
12824 OO.ui.NumberInputWidget.parent.call( this, $.extend( config, {
12825 type: 'number'
12826 } ) );
12827
12828 if ( config.showButtons ) {
12829 this.minusButton = new OO.ui.ButtonWidget( $.extend(
12830 {
12831 disabled: this.isDisabled(),
12832 tabIndex: -1,
12833 classes: [ 'oo-ui-numberInputWidget-minusButton' ],
12834 icon: 'subtract'
12835 },
12836 config.minusButton
12837 ) );
12838 this.minusButton.$element.attr( 'aria-hidden', 'true' );
12839 this.plusButton = new OO.ui.ButtonWidget( $.extend(
12840 {
12841 disabled: this.isDisabled(),
12842 tabIndex: -1,
12843 classes: [ 'oo-ui-numberInputWidget-plusButton' ],
12844 icon: 'add'
12845 },
12846 config.plusButton
12847 ) );
12848 this.plusButton.$element.attr( 'aria-hidden', 'true' );
12849 }
12850
12851 // Events
12852 this.$input.on( {
12853 keydown: this.onKeyDown.bind( this ),
12854 'wheel mousewheel DOMMouseScroll': this.onWheel.bind( this )
12855 } );
12856 if ( config.showButtons ) {
12857 this.plusButton.connect( this, {
12858 click: [ 'onButtonClick', +1 ]
12859 } );
12860 this.minusButton.connect( this, {
12861 click: [ 'onButtonClick', -1 ]
12862 } );
12863 }
12864
12865 // Build the field
12866 $field.append( this.$input );
12867 if ( config.showButtons ) {
12868 $field
12869 .prepend( this.minusButton.$element )
12870 .append( this.plusButton.$element );
12871 }
12872
12873 // Initialization
12874 if ( config.allowInteger || config.isInteger ) {
12875 // Backward compatibility
12876 config.step = 1;
12877 }
12878 this.setRange( config.min, config.max );
12879 this.setStep( config.buttonStep, config.pageStep, config.step );
12880 // Set the validation method after we set step and range
12881 // so that it doesn't immediately call setValidityFlag
12882 this.setValidation( this.validateNumber.bind( this ) );
12883
12884 this.$element
12885 .addClass( 'oo-ui-numberInputWidget' )
12886 .toggleClass( 'oo-ui-numberInputWidget-buttoned', config.showButtons )
12887 .append( $field );
12888 };
12889
12890 /* Setup */
12891
12892 OO.inheritClass( OO.ui.NumberInputWidget, OO.ui.TextInputWidget );
12893
12894 /* Methods */
12895
12896 // Backward compatibility
12897 OO.ui.NumberInputWidget.prototype.setAllowInteger = function ( flag ) {
12898 this.setStep( flag ? 1 : null );
12899 };
12900 // Backward compatibility
12901 OO.ui.NumberInputWidget.prototype.setIsInteger = OO.ui.NumberInputWidget.prototype.setAllowInteger;
12902
12903 // Backward compatibility
12904 OO.ui.NumberInputWidget.prototype.getAllowInteger = function () {
12905 return this.step === 1;
12906 };
12907 // Backward compatibility
12908 OO.ui.NumberInputWidget.prototype.getIsInteger = OO.ui.NumberInputWidget.prototype.getAllowInteger;
12909
12910 /**
12911 * Set the range of allowed values
12912 *
12913 * @param {number} min Minimum allowed value
12914 * @param {number} max Maximum allowed value
12915 */
12916 OO.ui.NumberInputWidget.prototype.setRange = function ( min, max ) {
12917 if ( min > max ) {
12918 throw new Error( 'Minimum (' + min + ') must not be greater than maximum (' + max + ')' );
12919 }
12920 this.min = min;
12921 this.max = max;
12922 this.$input.attr( 'min', this.min );
12923 this.$input.attr( 'max', this.max );
12924 this.setValidityFlag();
12925 };
12926
12927 /**
12928 * Get the current range
12929 *
12930 * @return {number[]} Minimum and maximum values
12931 */
12932 OO.ui.NumberInputWidget.prototype.getRange = function () {
12933 return [ this.min, this.max ];
12934 };
12935
12936 /**
12937 * Set the stepping deltas
12938 *
12939 * @param {number} [buttonStep=step||1] Delta when using the buttons or up/down arrow keys.
12940 * Defaults to `step` if specified, otherwise `1`.
12941 * @param {number} [pageStep=10*buttonStep] Delta when using the page-up/page-down keys.
12942 * Defaults to 10 times `buttonStep`.
12943 * @param {number|null} [step] If specified, the field only accepts values that are multiples
12944 * of this.
12945 */
12946 OO.ui.NumberInputWidget.prototype.setStep = function ( buttonStep, pageStep, step ) {
12947 if ( buttonStep === undefined ) {
12948 buttonStep = step || 1;
12949 }
12950 if ( pageStep === undefined ) {
12951 pageStep = 10 * buttonStep;
12952 }
12953 if ( step !== null && step <= 0 ) {
12954 throw new Error( 'Step value, if given, must be positive' );
12955 }
12956 if ( buttonStep <= 0 ) {
12957 throw new Error( 'Button step value must be positive' );
12958 }
12959 if ( pageStep <= 0 ) {
12960 throw new Error( 'Page step value must be positive' );
12961 }
12962 this.step = step;
12963 this.buttonStep = buttonStep;
12964 this.pageStep = pageStep;
12965 this.$input.attr( 'step', this.step || 'any' );
12966 this.setValidityFlag();
12967 };
12968
12969 /**
12970 * @inheritdoc
12971 */
12972 OO.ui.NumberInputWidget.prototype.setValue = function ( value ) {
12973 if ( value === '' ) {
12974 // Some browsers allow a value in the input even if there isn't one reported by $input.val()
12975 // so here we make sure an 'empty' value is actually displayed as such.
12976 this.$input.val( '' );
12977 }
12978 return OO.ui.NumberInputWidget.parent.prototype.setValue.call( this, value );
12979 };
12980
12981 /**
12982 * Get the current stepping values
12983 *
12984 * @return {number[]} Button step, page step, and validity step
12985 */
12986 OO.ui.NumberInputWidget.prototype.getStep = function () {
12987 return [ this.buttonStep, this.pageStep, this.step ];
12988 };
12989
12990 /**
12991 * Get the current value of the widget as a number
12992 *
12993 * @return {number} May be NaN, or an invalid number
12994 */
12995 OO.ui.NumberInputWidget.prototype.getNumericValue = function () {
12996 return +this.getValue();
12997 };
12998
12999 /**
13000 * Adjust the value of the widget
13001 *
13002 * @param {number} delta Adjustment amount
13003 */
13004 OO.ui.NumberInputWidget.prototype.adjustValue = function ( delta ) {
13005 var n, v = this.getNumericValue();
13006
13007 delta = +delta;
13008 if ( isNaN( delta ) || !isFinite( delta ) ) {
13009 throw new Error( 'Delta must be a finite number' );
13010 }
13011
13012 if ( isNaN( v ) ) {
13013 n = 0;
13014 } else {
13015 n = v + delta;
13016 n = Math.max( Math.min( n, this.max ), this.min );
13017 if ( this.step ) {
13018 n = Math.round( n / this.step ) * this.step;
13019 }
13020 }
13021
13022 if ( n !== v ) {
13023 this.setValue( n );
13024 }
13025 };
13026 /**
13027 * Validate input
13028 *
13029 * @private
13030 * @param {string} value Field value
13031 * @return {boolean}
13032 */
13033 OO.ui.NumberInputWidget.prototype.validateNumber = function ( value ) {
13034 var n = +value;
13035 if ( value === '' ) {
13036 return !this.isRequired();
13037 }
13038
13039 if ( isNaN( n ) || !isFinite( n ) ) {
13040 return false;
13041 }
13042
13043 if ( this.step && Math.floor( n / this.step ) !== n / this.step ) {
13044 return false;
13045 }
13046
13047 if ( n < this.min || n > this.max ) {
13048 return false;
13049 }
13050
13051 return true;
13052 };
13053
13054 /**
13055 * Handle mouse click events.
13056 *
13057 * @private
13058 * @param {number} dir +1 or -1
13059 */
13060 OO.ui.NumberInputWidget.prototype.onButtonClick = function ( dir ) {
13061 this.adjustValue( dir * this.buttonStep );
13062 };
13063
13064 /**
13065 * Handle mouse wheel events.
13066 *
13067 * @private
13068 * @param {jQuery.Event} event
13069 * @return {undefined|boolean} False to prevent default if event is handled
13070 */
13071 OO.ui.NumberInputWidget.prototype.onWheel = function ( event ) {
13072 var delta = 0;
13073
13074 if ( this.isDisabled() || this.isReadOnly() ) {
13075 return;
13076 }
13077
13078 if ( this.$input.is( ':focus' ) ) {
13079 // Standard 'wheel' event
13080 if ( event.originalEvent.deltaMode !== undefined ) {
13081 this.sawWheelEvent = true;
13082 }
13083 if ( event.originalEvent.deltaY ) {
13084 delta = -event.originalEvent.deltaY;
13085 } else if ( event.originalEvent.deltaX ) {
13086 delta = event.originalEvent.deltaX;
13087 }
13088
13089 // Non-standard events
13090 if ( !this.sawWheelEvent ) {
13091 if ( event.originalEvent.wheelDeltaX ) {
13092 delta = -event.originalEvent.wheelDeltaX;
13093 } else if ( event.originalEvent.wheelDeltaY ) {
13094 delta = event.originalEvent.wheelDeltaY;
13095 } else if ( event.originalEvent.wheelDelta ) {
13096 delta = event.originalEvent.wheelDelta;
13097 } else if ( event.originalEvent.detail ) {
13098 delta = -event.originalEvent.detail;
13099 }
13100 }
13101
13102 if ( delta ) {
13103 delta = delta < 0 ? -1 : 1;
13104 this.adjustValue( delta * this.buttonStep );
13105 }
13106
13107 return false;
13108 }
13109 };
13110
13111 /**
13112 * Handle key down events.
13113 *
13114 * @private
13115 * @param {jQuery.Event} e Key down event
13116 * @return {undefined|boolean} False to prevent default if event is handled
13117 */
13118 OO.ui.NumberInputWidget.prototype.onKeyDown = function ( e ) {
13119 if ( this.isDisabled() || this.isReadOnly() ) {
13120 return;
13121 }
13122
13123 switch ( e.which ) {
13124 case OO.ui.Keys.UP:
13125 this.adjustValue( this.buttonStep );
13126 return false;
13127 case OO.ui.Keys.DOWN:
13128 this.adjustValue( -this.buttonStep );
13129 return false;
13130 case OO.ui.Keys.PAGEUP:
13131 this.adjustValue( this.pageStep );
13132 return false;
13133 case OO.ui.Keys.PAGEDOWN:
13134 this.adjustValue( -this.pageStep );
13135 return false;
13136 }
13137 };
13138
13139 /**
13140 * Update the disabled state of the controls
13141 *
13142 * @chainable
13143 * @protected
13144 * @return {OO.ui.NumberInputWidget} The widget, for chaining
13145 */
13146 OO.ui.NumberInputWidget.prototype.updateControlsDisabled = function () {
13147 var disabled = this.isDisabled() || this.isReadOnly();
13148 if ( this.minusButton ) {
13149 this.minusButton.setDisabled( disabled );
13150 }
13151 if ( this.plusButton ) {
13152 this.plusButton.setDisabled( disabled );
13153 }
13154 return this;
13155 };
13156
13157 /**
13158 * @inheritdoc
13159 */
13160 OO.ui.NumberInputWidget.prototype.setDisabled = function ( disabled ) {
13161 // Parent method
13162 OO.ui.NumberInputWidget.parent.prototype.setDisabled.call( this, disabled );
13163 this.updateControlsDisabled();
13164 return this;
13165 };
13166
13167 /**
13168 * @inheritdoc
13169 */
13170 OO.ui.NumberInputWidget.prototype.setReadOnly = function () {
13171 // Parent method
13172 OO.ui.NumberInputWidget.parent.prototype.setReadOnly.apply( this, arguments );
13173 this.updateControlsDisabled();
13174 return this;
13175 };
13176
13177 /**
13178 * SelectFileInputWidgets allow for selecting files, using <input type="file">. These
13179 * widgets can be configured with {@link OO.ui.mixin.IconElement icons}, {@link
13180 * OO.ui.mixin.IndicatorElement indicators} and {@link OO.ui.mixin.TitledElement titles}.
13181 * Please see the [OOUI documentation on MediaWiki] [1] for more information and examples.
13182 *
13183 * SelectFileInputWidgets must be used in HTML forms, as getValue only returns the filename.
13184 *
13185 * @example
13186 * // A file select input widget.
13187 * var selectFile = new OO.ui.SelectFileInputWidget();
13188 * $( document.body ).append( selectFile.$element );
13189 *
13190 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets
13191 *
13192 * @class
13193 * @extends OO.ui.InputWidget
13194 *
13195 * @constructor
13196 * @param {Object} [config] Configuration options
13197 * @cfg {string[]|null} [accept=null] MIME types to accept. null accepts all types.
13198 * @cfg {boolean} [multiple=false] Allow multiple files to be selected.
13199 * @cfg {string} [placeholder] Text to display when no file is selected.
13200 * @cfg {Object} [button] Config to pass to select file button.
13201 * @cfg {string} [icon] Icon to show next to file info
13202 */
13203 OO.ui.SelectFileInputWidget = function OoUiSelectFileInputWidget( config ) {
13204 var widget = this;
13205
13206 config = config || {};
13207
13208 // Construct buttons before parent method is called (calling setDisabled)
13209 this.selectButton = new OO.ui.ButtonWidget( $.extend( {
13210 $element: $( '<label>' ),
13211 classes: [ 'oo-ui-selectFileInputWidget-selectButton' ],
13212 label: OO.ui.msg( 'ooui-selectfile-button-select' )
13213 }, config.button ) );
13214
13215 // Configuration initialization
13216 config = $.extend( {
13217 accept: null,
13218 placeholder: OO.ui.msg( 'ooui-selectfile-placeholder' ),
13219 $tabIndexed: this.selectButton.$tabIndexed
13220 }, config );
13221
13222 this.info = new OO.ui.SearchInputWidget( {
13223 classes: [ 'oo-ui-selectFileInputWidget-info' ],
13224 placeholder: config.placeholder,
13225 // Pass an empty collection so that .focus() always does nothing
13226 $tabIndexed: $( [] )
13227 } ).setIcon( config.icon );
13228 // Set tabindex manually on $input as $tabIndexed has been overridden
13229 this.info.$input.attr( 'tabindex', -1 );
13230
13231 // Parent constructor
13232 OO.ui.SelectFileInputWidget.parent.call( this, config );
13233
13234 // Properties
13235 this.currentFiles = this.filterFiles( this.$input[ 0 ].files || [] );
13236 if ( Array.isArray( config.accept ) ) {
13237 this.accept = config.accept;
13238 } else {
13239 this.accept = null;
13240 }
13241 this.multiple = !!config.multiple;
13242
13243 // Events
13244 this.info.connect( this, { change: 'onInfoChange' } );
13245 this.selectButton.$button.on( {
13246 keypress: this.onKeyPress.bind( this )
13247 } );
13248 this.$input.on( {
13249 change: this.onFileSelected.bind( this ),
13250 // Support: IE11
13251 // In IE 11, focussing a file input (by clicking on it) displays a text cursor and scrolls
13252 // the cursor into view (in this case, it scrolls the button, which has 'overflow: hidden').
13253 // Since this messes with our custom styling (the file input has large dimensions and this
13254 // causes the label to scroll out of view), scroll the button back to top. (T192131)
13255 focus: function () {
13256 widget.$input.parent().prop( 'scrollTop', 0 );
13257 }
13258 } );
13259 this.connect( this, { change: 'updateUI' } );
13260
13261 this.fieldLayout = new OO.ui.ActionFieldLayout( this.info, this.selectButton, { align: 'top' } );
13262
13263 this.$input
13264 .attr( {
13265 type: 'file',
13266 // this.selectButton is tabindexed
13267 tabindex: -1,
13268 // Infused input may have previously by
13269 // TabIndexed, so remove aria-disabled attr.
13270 'aria-disabled': null
13271 } );
13272
13273 if ( this.accept ) {
13274 this.$input.attr( 'accept', this.accept.join( ', ' ) );
13275 }
13276 if ( this.multiple ) {
13277 this.$input.attr( 'multiple', '' );
13278 }
13279 this.selectButton.$button.append( this.$input );
13280
13281 this.$element
13282 .addClass( 'oo-ui-selectFileInputWidget' )
13283 .append( this.fieldLayout.$element );
13284
13285 this.updateUI();
13286 };
13287
13288 /* Setup */
13289
13290 OO.inheritClass( OO.ui.SelectFileInputWidget, OO.ui.InputWidget );
13291
13292 /* Static properties */
13293
13294 // Set empty title so that browser default tooltips like "No file chosen" don't appear.
13295 // On SelectFileWidget this tooltip will often be incorrect, so create a consistent
13296 // experience on SelectFileInputWidget.
13297 OO.ui.SelectFileInputWidget.static.title = '';
13298
13299 /* Methods */
13300
13301 /**
13302 * Get the filename of the currently selected file.
13303 *
13304 * @return {string} Filename
13305 */
13306 OO.ui.SelectFileInputWidget.prototype.getFilename = function () {
13307 if ( this.currentFiles.length ) {
13308 return this.currentFiles.map( function ( file ) {
13309 return file.name;
13310 } ).join( ', ' );
13311 } else {
13312 // Try to strip leading fakepath.
13313 return this.getValue().split( '\\' ).pop();
13314 }
13315 };
13316
13317 /**
13318 * @inheritdoc
13319 */
13320 OO.ui.SelectFileInputWidget.prototype.setValue = function ( value ) {
13321 if ( value === undefined ) {
13322 // Called during init, don't replace value if just infusing.
13323 return;
13324 }
13325 if ( value ) {
13326 // We need to update this.value, but without trying to modify
13327 // the DOM value, which would throw an exception.
13328 if ( this.value !== value ) {
13329 this.value = value;
13330 this.emit( 'change', this.value );
13331 }
13332 } else {
13333 this.currentFiles = [];
13334 // Parent method
13335 OO.ui.SelectFileInputWidget.super.prototype.setValue.call( this, '' );
13336 }
13337 };
13338
13339 /**
13340 * Handle file selection from the input.
13341 *
13342 * @protected
13343 * @param {jQuery.Event} e
13344 */
13345 OO.ui.SelectFileInputWidget.prototype.onFileSelected = function ( e ) {
13346 this.currentFiles = this.filterFiles( e.target.files || [] );
13347 };
13348
13349 /**
13350 * Update the user interface when a file is selected or unselected.
13351 *
13352 * @protected
13353 */
13354 OO.ui.SelectFileInputWidget.prototype.updateUI = function () {
13355 this.info.setValue( this.getFilename() );
13356 };
13357
13358 /**
13359 * Determine if we should accept this file.
13360 *
13361 * @private
13362 * @param {FileList|File[]} files Files to filter
13363 * @return {File[]} Filter files
13364 */
13365 OO.ui.SelectFileInputWidget.prototype.filterFiles = function ( files ) {
13366 var accept = this.accept;
13367
13368 function mimeAllowed( file ) {
13369 var i, mimeTest,
13370 mimeType = file.type;
13371
13372 if ( !accept || !mimeType ) {
13373 return true;
13374 }
13375
13376 for ( i = 0; i < accept.length; i++ ) {
13377 mimeTest = accept[ i ];
13378 if ( mimeTest === mimeType ) {
13379 return true;
13380 } else if ( mimeTest.substr( -2 ) === '/*' ) {
13381 mimeTest = mimeTest.substr( 0, mimeTest.length - 1 );
13382 if ( mimeType.substr( 0, mimeTest.length ) === mimeTest ) {
13383 return true;
13384 }
13385 }
13386 }
13387 return false;
13388 }
13389
13390 return Array.prototype.filter.call( files, mimeAllowed );
13391 };
13392
13393 /**
13394 * Handle info input change events
13395 *
13396 * The info widget can only be changed by the user
13397 * with the clear button.
13398 *
13399 * @private
13400 * @param {string} value
13401 */
13402 OO.ui.SelectFileInputWidget.prototype.onInfoChange = function ( value ) {
13403 if ( value === '' ) {
13404 this.setValue( null );
13405 }
13406 };
13407
13408 /**
13409 * Handle key press events.
13410 *
13411 * @private
13412 * @param {jQuery.Event} e Key press event
13413 * @return {undefined|boolean} False to prevent default if event is handled
13414 */
13415 OO.ui.SelectFileInputWidget.prototype.onKeyPress = function ( e ) {
13416 if ( !this.isDisabled() && this.$input &&
13417 ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
13418 ) {
13419 // Emit a click to open the file selector.
13420 this.$input.trigger( 'click' );
13421 // Taking focus from the selectButton means keyUp isn't fired, so fire it manually.
13422 this.selectButton.onDocumentKeyUp( e );
13423 return false;
13424 }
13425 };
13426
13427 /**
13428 * @inheritdoc
13429 */
13430 OO.ui.SelectFileInputWidget.prototype.setDisabled = function ( disabled ) {
13431 // Parent method
13432 OO.ui.SelectFileInputWidget.parent.prototype.setDisabled.call( this, disabled );
13433
13434 this.selectButton.setDisabled( disabled );
13435 this.info.setDisabled( disabled );
13436
13437 return this;
13438 };
13439
13440 }( OO ) );
13441
13442 //# sourceMappingURL=oojs-ui-core.js.map.json