Merge "Avoid expensive array_shift where possible"
[lhc/web/wiklou.git] / resources / lib / ooui / oojs-ui-core.js
1 /*!
2 * OOUI v0.29.6
3 * https://www.mediawiki.org/wiki/OOUI
4 *
5 * Copyright 2011–2018 OOUI Team and other contributors.
6 * Released under the MIT license
7 * http://oojs.mit-license.org
8 *
9 * Date: 2018-12-05T00:15:55Z
10 */
11 ( function ( OO ) {
12
13 'use strict';
14
15 /**
16 * Namespace for all classes, static methods and static properties.
17 *
18 * @class
19 * @singleton
20 */
21 OO.ui = {};
22
23 OO.ui.bind = $.proxy;
24
25 /**
26 * @property {Object}
27 */
28 OO.ui.Keys = {
29 UNDEFINED: 0,
30 BACKSPACE: 8,
31 DELETE: 46,
32 LEFT: 37,
33 RIGHT: 39,
34 UP: 38,
35 DOWN: 40,
36 ENTER: 13,
37 END: 35,
38 HOME: 36,
39 TAB: 9,
40 PAGEUP: 33,
41 PAGEDOWN: 34,
42 ESCAPE: 27,
43 SHIFT: 16,
44 SPACE: 32
45 };
46
47 /**
48 * Constants for MouseEvent.which
49 *
50 * @property {Object}
51 */
52 OO.ui.MouseButtons = {
53 LEFT: 1,
54 MIDDLE: 2,
55 RIGHT: 3
56 };
57
58 /**
59 * @property {number}
60 * @private
61 */
62 OO.ui.elementId = 0;
63
64 /**
65 * Generate a unique ID for element
66 *
67 * @return {string} ID
68 */
69 OO.ui.generateElementId = function () {
70 OO.ui.elementId++;
71 return 'ooui-' + OO.ui.elementId;
72 };
73
74 /**
75 * Check if an element is focusable.
76 * Inspired by :focusable in jQueryUI v1.11.4 - 2015-04-14
77 *
78 * @param {jQuery} $element Element to test
79 * @return {boolean} Element is focusable
80 */
81 OO.ui.isFocusableElement = function ( $element ) {
82 var nodeName,
83 element = $element[ 0 ];
84
85 // Anything disabled is not focusable
86 if ( element.disabled ) {
87 return false;
88 }
89
90 // Check if the element is visible
91 if ( !(
92 // This is quicker than calling $element.is( ':visible' )
93 $.expr.pseudos.visible( element ) &&
94 // Check that all parents are visible
95 !$element.parents().addBack().filter( function () {
96 return $.css( this, 'visibility' ) === 'hidden';
97 } ).length
98 ) ) {
99 return false;
100 }
101
102 // Check if the element is ContentEditable, which is the string 'true'
103 if ( element.contentEditable === 'true' ) {
104 return true;
105 }
106
107 // Anything with a non-negative numeric tabIndex is focusable.
108 // Use .prop to avoid browser bugs
109 if ( $element.prop( 'tabIndex' ) >= 0 ) {
110 return true;
111 }
112
113 // Some element types are naturally focusable
114 // (indexOf is much faster than regex in Chrome and about the
115 // same in FF: https://jsperf.com/regex-vs-indexof-array2)
116 nodeName = element.nodeName.toLowerCase();
117 if ( [ 'input', 'select', 'textarea', 'button', 'object' ].indexOf( nodeName ) !== -1 ) {
118 return true;
119 }
120
121 // Links and areas are focusable if they have an href
122 if ( ( nodeName === 'a' || nodeName === 'area' ) && $element.attr( 'href' ) !== undefined ) {
123 return true;
124 }
125
126 return false;
127 };
128
129 /**
130 * Find a focusable child
131 *
132 * @param {jQuery} $container Container to search in
133 * @param {boolean} [backwards] Search backwards
134 * @return {jQuery} Focusable child, or an empty jQuery object if none found
135 */
136 OO.ui.findFocusable = function ( $container, backwards ) {
137 var $focusable = $( [] ),
138 // $focusableCandidates is a superset of things that
139 // could get matched by isFocusableElement
140 $focusableCandidates = $container
141 .find( 'input, select, textarea, button, object, a, area, [contenteditable], [tabindex]' );
142
143 if ( backwards ) {
144 $focusableCandidates = Array.prototype.reverse.call( $focusableCandidates );
145 }
146
147 $focusableCandidates.each( function () {
148 var $this = $( this );
149 if ( OO.ui.isFocusableElement( $this ) ) {
150 $focusable = $this;
151 return false;
152 }
153 } );
154 return $focusable;
155 };
156
157 /**
158 * Get the user's language and any fallback languages.
159 *
160 * These language codes are used to localize user interface elements in the user's language.
161 *
162 * In environments that provide a localization system, this function should be overridden to
163 * return the user's language(s). The default implementation returns English (en) only.
164 *
165 * @return {string[]} Language codes, in descending order of priority
166 */
167 OO.ui.getUserLanguages = function () {
168 return [ 'en' ];
169 };
170
171 /**
172 * Get a value in an object keyed by language code.
173 *
174 * @param {Object.<string,Mixed>} obj Object keyed by language code
175 * @param {string|null} [lang] Language code, if omitted or null defaults to any user language
176 * @param {string} [fallback] Fallback code, used if no matching language can be found
177 * @return {Mixed} Local value
178 */
179 OO.ui.getLocalValue = function ( obj, lang, fallback ) {
180 var i, len, langs;
181
182 // Requested language
183 if ( obj[ lang ] ) {
184 return obj[ lang ];
185 }
186 // Known user language
187 langs = OO.ui.getUserLanguages();
188 for ( i = 0, len = langs.length; i < len; i++ ) {
189 lang = langs[ i ];
190 if ( obj[ lang ] ) {
191 return obj[ lang ];
192 }
193 }
194 // Fallback language
195 if ( obj[ fallback ] ) {
196 return obj[ fallback ];
197 }
198 // First existing language
199 for ( lang in obj ) {
200 return obj[ lang ];
201 }
202
203 return undefined;
204 };
205
206 /**
207 * Check if a node is contained within another node
208 *
209 * Similar to jQuery#contains except a list of containers can be supplied
210 * and a boolean argument allows you to include the container in the match list
211 *
212 * @param {HTMLElement|HTMLElement[]} containers Container node(s) to search in
213 * @param {HTMLElement} contained Node to find
214 * @param {boolean} [matchContainers] Include the container(s) in the list of nodes to match, otherwise only match descendants
215 * @return {boolean} The node is in the list of target nodes
216 */
217 OO.ui.contains = function ( containers, contained, matchContainers ) {
218 var i;
219 if ( !Array.isArray( containers ) ) {
220 containers = [ containers ];
221 }
222 for ( i = containers.length - 1; i >= 0; i-- ) {
223 if ( ( matchContainers && contained === containers[ i ] ) || $.contains( containers[ i ], contained ) ) {
224 return true;
225 }
226 }
227 return false;
228 };
229
230 /**
231 * Return a function, that, as long as it continues to be invoked, will not
232 * be triggered. The function will be called after it stops being called for
233 * N milliseconds. If `immediate` is passed, trigger the function on the
234 * leading edge, instead of the trailing.
235 *
236 * Ported from: http://underscorejs.org/underscore.js
237 *
238 * @param {Function} func Function to debounce
239 * @param {number} [wait=0] Wait period in milliseconds
240 * @param {boolean} [immediate] Trigger on leading edge
241 * @return {Function} Debounced function
242 */
243 OO.ui.debounce = function ( func, wait, immediate ) {
244 var timeout;
245 return function () {
246 var context = this,
247 args = arguments,
248 later = function () {
249 timeout = null;
250 if ( !immediate ) {
251 func.apply( context, args );
252 }
253 };
254 if ( immediate && !timeout ) {
255 func.apply( context, args );
256 }
257 if ( !timeout || wait ) {
258 clearTimeout( timeout );
259 timeout = setTimeout( later, wait );
260 }
261 };
262 };
263
264 /**
265 * Puts a console warning with provided message.
266 *
267 * @param {string} message Message
268 */
269 OO.ui.warnDeprecation = function ( message ) {
270 if ( OO.getProp( window, 'console', 'warn' ) !== undefined ) {
271 // eslint-disable-next-line no-console
272 console.warn( message );
273 }
274 };
275
276 /**
277 * Returns a function, that, when invoked, will only be triggered at most once
278 * during a given window of time. If called again during that window, it will
279 * wait until the window ends and then trigger itself again.
280 *
281 * As it's not knowable to the caller whether the function will actually run
282 * when the wrapper is called, return values from the function are entirely
283 * discarded.
284 *
285 * @param {Function} func Function to throttle
286 * @param {number} wait Throttle window length, in milliseconds
287 * @return {Function} Throttled function
288 */
289 OO.ui.throttle = function ( func, wait ) {
290 var context, args, timeout,
291 previous = 0,
292 run = function () {
293 timeout = null;
294 previous = OO.ui.now();
295 func.apply( context, args );
296 };
297 return function () {
298 // Check how long it's been since the last time the function was
299 // called, and whether it's more or less than the requested throttle
300 // period. If it's less, run the function immediately. If it's more,
301 // set a timeout for the remaining time -- but don't replace an
302 // existing timeout, since that'd indefinitely prolong the wait.
303 var remaining = wait - ( OO.ui.now() - previous );
304 context = this;
305 args = arguments;
306 if ( remaining <= 0 ) {
307 // Note: unless wait was ridiculously large, this means we'll
308 // automatically run the first time the function was called in a
309 // given period. (If you provide a wait period larger than the
310 // current Unix timestamp, you *deserve* unexpected behavior.)
311 clearTimeout( timeout );
312 run();
313 } else if ( !timeout ) {
314 timeout = setTimeout( run, remaining );
315 }
316 };
317 };
318
319 /**
320 * A (possibly faster) way to get the current timestamp as an integer
321 *
322 * @return {number} Current timestamp, in milliseconds since the Unix epoch
323 */
324 OO.ui.now = Date.now || function () {
325 return new Date().getTime();
326 };
327
328 /**
329 * Reconstitute a JavaScript object corresponding to a widget created by
330 * the PHP implementation.
331 *
332 * This is an alias for `OO.ui.Element.static.infuse()`.
333 *
334 * @param {string|HTMLElement|jQuery} idOrNode
335 * A DOM id (if a string) or node for the widget to infuse.
336 * @param {Object} [config] Configuration options
337 * @return {OO.ui.Element}
338 * The `OO.ui.Element` corresponding to this (infusable) document node.
339 */
340 OO.ui.infuse = function ( idOrNode, config ) {
341 return OO.ui.Element.static.infuse( idOrNode, config );
342 };
343
344 ( function () {
345 /**
346 * Message store for the default implementation of OO.ui.msg
347 *
348 * Environments that provide a localization system should not use this, but should override
349 * OO.ui.msg altogether.
350 *
351 * @private
352 */
353 var messages = {
354 // Tool tip for a button that moves items in a list down one place
355 'ooui-outline-control-move-down': 'Move item down',
356 // Tool tip for a button that moves items in a list up one place
357 'ooui-outline-control-move-up': 'Move item up',
358 // Tool tip for a button that removes items from a list
359 'ooui-outline-control-remove': 'Remove item',
360 // Label for the toolbar group that contains a list of all other available tools
361 'ooui-toolbar-more': 'More',
362 // Label for the fake tool that expands the full list of tools in a toolbar group
363 'ooui-toolgroup-expand': 'More',
364 // Label for the fake tool that collapses the full list of tools in a toolbar group
365 'ooui-toolgroup-collapse': 'Fewer',
366 // Default label for the tooltip for the button that removes a tag item
367 'ooui-item-remove': 'Remove',
368 // Default label for the accept button of a confirmation dialog
369 'ooui-dialog-message-accept': 'OK',
370 // Default label for the reject button of a confirmation dialog
371 'ooui-dialog-message-reject': 'Cancel',
372 // Title for process dialog error description
373 'ooui-dialog-process-error': 'Something went wrong',
374 // Label for process dialog dismiss error button, visible when describing errors
375 'ooui-dialog-process-dismiss': 'Dismiss',
376 // Label for process dialog retry action button, visible when describing only recoverable errors
377 'ooui-dialog-process-retry': 'Try again',
378 // Label for process dialog retry action button, visible when describing only warnings
379 'ooui-dialog-process-continue': 'Continue',
380 // Label for the file selection widget's select file button
381 'ooui-selectfile-button-select': 'Select a file',
382 // Label for the file selection widget if file selection is not supported
383 'ooui-selectfile-not-supported': 'File selection is not supported',
384 // Label for the file selection widget when no file is currently selected
385 'ooui-selectfile-placeholder': 'No file is selected',
386 // Label for the file selection widget's drop target
387 'ooui-selectfile-dragdrop-placeholder': 'Drop file here',
388 // Label for the help icon attached to a form field
389 'ooui-field-help': 'Help'
390 };
391
392 /**
393 * Get a localized message.
394 *
395 * After the message key, message parameters may optionally be passed. In the default implementation,
396 * any occurrences of $1 are replaced with the first parameter, $2 with the second parameter, etc.
397 * Alternative implementations of OO.ui.msg may use any substitution system they like, as long as
398 * they support unnamed, ordered message parameters.
399 *
400 * In environments that provide a localization system, this function should be overridden to
401 * return the message translated in the user's language. The default implementation always returns
402 * English messages. An example of doing this with [jQuery.i18n](https://github.com/wikimedia/jquery.i18n)
403 * follows.
404 *
405 * @example
406 * var i, iLen, button,
407 * messagePath = 'oojs-ui/dist/i18n/',
408 * languages = [ $.i18n().locale, 'ur', 'en' ],
409 * languageMap = {};
410 *
411 * for ( i = 0, iLen = languages.length; i < iLen; i++ ) {
412 * languageMap[ languages[ i ] ] = messagePath + languages[ i ].toLowerCase() + '.json';
413 * }
414 *
415 * $.i18n().load( languageMap ).done( function() {
416 * // Replace the built-in `msg` only once we've loaded the internationalization.
417 * // OOUI uses `OO.ui.deferMsg` for all initially-loaded messages. So long as
418 * // you put off creating any widgets until this promise is complete, no English
419 * // will be displayed.
420 * OO.ui.msg = $.i18n;
421 *
422 * // A button displaying "OK" in the default locale
423 * button = new OO.ui.ButtonWidget( {
424 * label: OO.ui.msg( 'ooui-dialog-message-accept' ),
425 * icon: 'check'
426 * } );
427 * $( 'body' ).append( button.$element );
428 *
429 * // A button displaying "OK" in Urdu
430 * $.i18n().locale = 'ur';
431 * button = new OO.ui.ButtonWidget( {
432 * label: OO.ui.msg( 'ooui-dialog-message-accept' ),
433 * icon: 'check'
434 * } );
435 * $( 'body' ).append( button.$element );
436 * } );
437 *
438 * @param {string} key Message key
439 * @param {...Mixed} [params] Message parameters
440 * @return {string} Translated message with parameters substituted
441 */
442 OO.ui.msg = function ( key ) {
443 var message = messages[ key ],
444 params = Array.prototype.slice.call( arguments, 1 );
445 if ( typeof message === 'string' ) {
446 // Perform $1 substitution
447 message = message.replace( /\$(\d+)/g, function ( unused, n ) {
448 var i = parseInt( n, 10 );
449 return params[ i - 1 ] !== undefined ? params[ i - 1 ] : '$' + n;
450 } );
451 } else {
452 // Return placeholder if message not found
453 message = '[' + key + ']';
454 }
455 return message;
456 };
457 }() );
458
459 /**
460 * Package a message and arguments for deferred resolution.
461 *
462 * Use this when you are statically specifying a message and the message may not yet be present.
463 *
464 * @param {string} key Message key
465 * @param {...Mixed} [params] Message parameters
466 * @return {Function} Function that returns the resolved message when executed
467 */
468 OO.ui.deferMsg = function () {
469 var args = arguments;
470 return function () {
471 return OO.ui.msg.apply( OO.ui, args );
472 };
473 };
474
475 /**
476 * Resolve a message.
477 *
478 * If the message is a function it will be executed, otherwise it will pass through directly.
479 *
480 * @param {Function|string} msg Deferred message, or message text
481 * @return {string} Resolved message
482 */
483 OO.ui.resolveMsg = function ( msg ) {
484 if ( typeof msg === 'function' ) {
485 return msg();
486 }
487 return msg;
488 };
489
490 /**
491 * @param {string} url
492 * @return {boolean}
493 */
494 OO.ui.isSafeUrl = function ( url ) {
495 // Keep this function in sync with php/Tag.php
496 var i, protocolWhitelist;
497
498 function stringStartsWith( haystack, needle ) {
499 return haystack.substr( 0, needle.length ) === needle;
500 }
501
502 protocolWhitelist = [
503 'bitcoin', 'ftp', 'ftps', 'geo', 'git', 'gopher', 'http', 'https', 'irc', 'ircs',
504 'magnet', 'mailto', 'mms', 'news', 'nntp', 'redis', 'sftp', 'sip', 'sips', 'sms', 'ssh',
505 'svn', 'tel', 'telnet', 'urn', 'worldwind', 'xmpp'
506 ];
507
508 if ( url === '' ) {
509 return true;
510 }
511
512 for ( i = 0; i < protocolWhitelist.length; i++ ) {
513 if ( stringStartsWith( url, protocolWhitelist[ i ] + ':' ) ) {
514 return true;
515 }
516 }
517
518 // This matches '//' too
519 if ( stringStartsWith( url, '/' ) || stringStartsWith( url, './' ) ) {
520 return true;
521 }
522 if ( stringStartsWith( url, '?' ) || stringStartsWith( url, '#' ) ) {
523 return true;
524 }
525
526 return false;
527 };
528
529 /**
530 * Check if the user has a 'mobile' device.
531 *
532 * For our purposes this means the user is primarily using an
533 * on-screen keyboard, touch input instead of a mouse and may
534 * have a physically small display.
535 *
536 * It is left up to implementors to decide how to compute this
537 * so the default implementation always returns false.
538 *
539 * @return {boolean} User is on a mobile device
540 */
541 OO.ui.isMobile = function () {
542 return false;
543 };
544
545 /**
546 * Get the additional spacing that should be taken into account when displaying elements that are
547 * clipped to the viewport, e.g. dropdown menus and popups. This is meant to be overridden to avoid
548 * such menus overlapping any fixed headers/toolbars/navigation used by the site.
549 *
550 * @return {Object} Object with the properties 'top', 'right', 'bottom', 'left', each representing
551 * the extra spacing from that edge of viewport (in pixels)
552 */
553 OO.ui.getViewportSpacing = function () {
554 return {
555 top: 0,
556 right: 0,
557 bottom: 0,
558 left: 0
559 };
560 };
561
562 /**
563 * Get the default overlay, which is used by various widgets when they are passed `$overlay: true`.
564 * See <https://www.mediawiki.org/wiki/OOUI/Concepts#Overlays>.
565 *
566 * @return {jQuery} Default overlay node
567 */
568 OO.ui.getDefaultOverlay = function () {
569 if ( !OO.ui.$defaultOverlay ) {
570 OO.ui.$defaultOverlay = $( '<div>' ).addClass( 'oo-ui-defaultOverlay' );
571 $( 'body' ).append( OO.ui.$defaultOverlay );
572 }
573 return OO.ui.$defaultOverlay;
574 };
575
576 /*!
577 * Mixin namespace.
578 */
579
580 /**
581 * Namespace for OOUI mixins.
582 *
583 * Mixins are named according to the type of object they are intended to
584 * be mixed in to. For example, OO.ui.mixin.GroupElement is intended to be
585 * mixed in to an instance of OO.ui.Element, and OO.ui.mixin.GroupWidget
586 * is intended to be mixed in to an instance of OO.ui.Widget.
587 *
588 * @class
589 * @singleton
590 */
591 OO.ui.mixin = {};
592
593 /**
594 * Each Element represents a rendering in the DOM—a button or an icon, for example, or anything
595 * that is visible to a user. Unlike {@link OO.ui.Widget widgets}, plain elements usually do not have events
596 * connected to them and can't be interacted with.
597 *
598 * @abstract
599 * @class
600 *
601 * @constructor
602 * @param {Object} [config] Configuration options
603 * @cfg {string[]} [classes] The names of the CSS classes to apply to the element. CSS styles are added
604 * to the top level (e.g., the outermost div) of the element. See the [OOUI documentation on MediaWiki][2]
605 * for an example.
606 * [2]: https://www.mediawiki.org/wiki/OOUI/Widgets/Buttons_and_Switches#cssExample
607 * @cfg {string} [id] The HTML id attribute used in the rendered tag.
608 * @cfg {string} [text] Text to insert
609 * @cfg {Array} [content] An array of content elements to append (after #text).
610 * Strings will be html-escaped; use an OO.ui.HtmlSnippet to append raw HTML.
611 * Instances of OO.ui.Element will have their $element appended.
612 * @cfg {jQuery} [$content] Content elements to append (after #text).
613 * @cfg {jQuery} [$element] Wrapper element. Defaults to a new element with #getTagName.
614 * @cfg {Mixed} [data] Custom data of any type or combination of types (e.g., string, number, array, object).
615 * Data can also be specified with the #setData method.
616 */
617 OO.ui.Element = function OoUiElement( config ) {
618 if ( OO.ui.isDemo ) {
619 this.initialConfig = config;
620 }
621 // Configuration initialization
622 config = config || {};
623
624 // Properties
625 this.$ = $;
626 this.elementId = null;
627 this.visible = true;
628 this.data = config.data;
629 this.$element = config.$element ||
630 $( document.createElement( this.getTagName() ) );
631 this.elementGroup = null;
632
633 // Initialization
634 if ( Array.isArray( config.classes ) ) {
635 this.$element.addClass( config.classes );
636 }
637 if ( config.id ) {
638 this.setElementId( config.id );
639 }
640 if ( config.text ) {
641 this.$element.text( config.text );
642 }
643 if ( config.content ) {
644 // The `content` property treats plain strings as text; use an
645 // HtmlSnippet to append HTML content. `OO.ui.Element`s get their
646 // appropriate $element appended.
647 this.$element.append( config.content.map( function ( v ) {
648 if ( typeof v === 'string' ) {
649 // Escape string so it is properly represented in HTML.
650 return document.createTextNode( v );
651 } else if ( v instanceof OO.ui.HtmlSnippet ) {
652 // Bypass escaping.
653 return v.toString();
654 } else if ( v instanceof OO.ui.Element ) {
655 return v.$element;
656 }
657 return v;
658 } ) );
659 }
660 if ( config.$content ) {
661 // The `$content` property treats plain strings as HTML.
662 this.$element.append( config.$content );
663 }
664 };
665
666 /* Setup */
667
668 OO.initClass( OO.ui.Element );
669
670 /* Static Properties */
671
672 /**
673 * The name of the HTML tag used by the element.
674 *
675 * The static value may be ignored if the #getTagName method is overridden.
676 *
677 * @static
678 * @inheritable
679 * @property {string}
680 */
681 OO.ui.Element.static.tagName = 'div';
682
683 /* Static Methods */
684
685 /**
686 * Reconstitute a JavaScript object corresponding to a widget created
687 * by the PHP implementation.
688 *
689 * @param {string|HTMLElement|jQuery} idOrNode
690 * A DOM id (if a string) or node for the widget to infuse.
691 * @param {Object} [config] Configuration options
692 * @return {OO.ui.Element}
693 * The `OO.ui.Element` corresponding to this (infusable) document node.
694 * For `Tag` objects emitted on the HTML side (used occasionally for content)
695 * the value returned is a newly-created Element wrapping around the existing
696 * DOM node.
697 */
698 OO.ui.Element.static.infuse = function ( idOrNode, config ) {
699 var obj = OO.ui.Element.static.unsafeInfuse( idOrNode, config, false );
700 // Verify that the type matches up.
701 // FIXME: uncomment after T89721 is fixed, see T90929.
702 /*
703 if ( !( obj instanceof this['class'] ) ) {
704 throw new Error( 'Infusion type mismatch!' );
705 }
706 */
707 return obj;
708 };
709
710 /**
711 * Implementation helper for `infuse`; skips the type check and has an
712 * extra property so that only the top-level invocation touches the DOM.
713 *
714 * @private
715 * @param {string|HTMLElement|jQuery} idOrNode
716 * @param {Object} [config] Configuration options
717 * @param {jQuery.Promise} [domPromise] A promise that will be resolved
718 * when the top-level widget of this infusion is inserted into DOM,
719 * replacing the original node; only used internally.
720 * @return {OO.ui.Element}
721 */
722 OO.ui.Element.static.unsafeInfuse = function ( idOrNode, config, domPromise ) {
723 // look for a cached result of a previous infusion.
724 var id, $elem, error, data, cls, parts, parent, obj, top, state, infusedChildren;
725 if ( typeof idOrNode === 'string' ) {
726 id = idOrNode;
727 $elem = $( document.getElementById( id ) );
728 } else {
729 $elem = $( idOrNode );
730 id = $elem.attr( 'id' );
731 }
732 if ( !$elem.length ) {
733 if ( typeof idOrNode === 'string' ) {
734 error = 'Widget not found: ' + idOrNode;
735 } else if ( idOrNode && idOrNode.selector ) {
736 error = 'Widget not found: ' + idOrNode.selector;
737 } else {
738 error = 'Widget not found';
739 }
740 throw new Error( error );
741 }
742 if ( $elem[ 0 ].oouiInfused ) {
743 $elem = $elem[ 0 ].oouiInfused;
744 }
745 data = $elem.data( 'ooui-infused' );
746 if ( data ) {
747 // cached!
748 if ( data === true ) {
749 throw new Error( 'Circular dependency! ' + id );
750 }
751 if ( domPromise ) {
752 // pick up dynamic state, like focus, value of form inputs, scroll position, etc.
753 state = data.constructor.static.gatherPreInfuseState( $elem, data );
754 // restore dynamic state after the new element is re-inserted into DOM under infused parent
755 domPromise.done( data.restorePreInfuseState.bind( data, state ) );
756 infusedChildren = $elem.data( 'ooui-infused-children' );
757 if ( infusedChildren && infusedChildren.length ) {
758 infusedChildren.forEach( function ( data ) {
759 var state = data.constructor.static.gatherPreInfuseState( $elem, data );
760 domPromise.done( data.restorePreInfuseState.bind( data, state ) );
761 } );
762 }
763 }
764 return data;
765 }
766 data = $elem.attr( 'data-ooui' );
767 if ( !data ) {
768 throw new Error( 'No infusion data found: ' + id );
769 }
770 try {
771 data = JSON.parse( data );
772 } catch ( _ ) {
773 data = null;
774 }
775 if ( !( data && data._ ) ) {
776 throw new Error( 'No valid infusion data found: ' + id );
777 }
778 if ( data._ === 'Tag' ) {
779 // Special case: this is a raw Tag; wrap existing node, don't rebuild.
780 return new OO.ui.Element( $.extend( {}, config, { $element: $elem } ) );
781 }
782 parts = data._.split( '.' );
783 cls = OO.getProp.apply( OO, [ window ].concat( parts ) );
784 if ( cls === undefined ) {
785 throw new Error( 'Unknown widget type: id: ' + id + ', class: ' + data._ );
786 }
787
788 // Verify that we're creating an OO.ui.Element instance
789 parent = cls.parent;
790
791 while ( parent !== undefined ) {
792 if ( parent === OO.ui.Element ) {
793 // Safe
794 break;
795 }
796
797 parent = parent.parent;
798 }
799
800 if ( parent !== OO.ui.Element ) {
801 throw new Error( 'Unknown widget type: id: ' + id + ', class: ' + data._ );
802 }
803
804 if ( !domPromise ) {
805 top = $.Deferred();
806 domPromise = top.promise();
807 }
808 $elem.data( 'ooui-infused', true ); // prevent loops
809 data.id = id; // implicit
810 infusedChildren = [];
811 data = OO.copy( data, null, function deserialize( value ) {
812 var infused;
813 if ( OO.isPlainObject( value ) ) {
814 if ( value.tag ) {
815 infused = OO.ui.Element.static.unsafeInfuse( value.tag, config, domPromise );
816 infusedChildren.push( infused );
817 // Flatten the structure
818 infusedChildren.push.apply( infusedChildren, infused.$element.data( 'ooui-infused-children' ) || [] );
819 infused.$element.removeData( 'ooui-infused-children' );
820 return infused;
821 }
822 if ( value.html !== undefined ) {
823 return new OO.ui.HtmlSnippet( value.html );
824 }
825 }
826 } );
827 // allow widgets to reuse parts of the DOM
828 data = cls.static.reusePreInfuseDOM( $elem[ 0 ], data );
829 // pick up dynamic state, like focus, value of form inputs, scroll position, etc.
830 state = cls.static.gatherPreInfuseState( $elem[ 0 ], data );
831 // rebuild widget
832 // eslint-disable-next-line new-cap
833 obj = new cls( $.extend( {}, config, data ) );
834 // If anyone is holding a reference to the old DOM element,
835 // let's allow them to OO.ui.infuse() it and do what they expect, see T105828.
836 // Do not use jQuery.data(), as using it on detached nodes leaks memory in 1.x line by design.
837 $elem[ 0 ].oouiInfused = obj.$element;
838 // now replace old DOM with this new DOM.
839 if ( top ) {
840 // An efficient constructor might be able to reuse the entire DOM tree of the original element,
841 // so only mutate the DOM if we need to.
842 if ( $elem[ 0 ] !== obj.$element[ 0 ] ) {
843 $elem.replaceWith( obj.$element );
844 }
845 top.resolve();
846 }
847 obj.$element.data( 'ooui-infused', obj );
848 obj.$element.data( 'ooui-infused-children', infusedChildren );
849 // set the 'data-ooui' attribute so we can identify infused widgets
850 obj.$element.attr( 'data-ooui', '' );
851 // restore dynamic state after the new element is inserted into DOM
852 domPromise.done( obj.restorePreInfuseState.bind( obj, state ) );
853 return obj;
854 };
855
856 /**
857 * Pick out parts of `node`'s DOM to be reused when infusing a widget.
858 *
859 * This method **must not** make any changes to the DOM, only find interesting pieces and add them
860 * to `config` (which should then be returned). Actual DOM juggling should then be done by the
861 * constructor, which will be given the enhanced config.
862 *
863 * @protected
864 * @param {HTMLElement} node
865 * @param {Object} config
866 * @return {Object}
867 */
868 OO.ui.Element.static.reusePreInfuseDOM = function ( node, config ) {
869 return config;
870 };
871
872 /**
873 * Gather the dynamic state (focus, value of form inputs, scroll position, etc.) of an HTML DOM node
874 * (and its children) that represent an Element of the same class and the given configuration,
875 * generated by the PHP implementation.
876 *
877 * This method is called just before `node` is detached from the DOM. The return value of this
878 * function will be passed to #restorePreInfuseState after the newly created widget's #$element
879 * is inserted into DOM to replace `node`.
880 *
881 * @protected
882 * @param {HTMLElement} node
883 * @param {Object} config
884 * @return {Object}
885 */
886 OO.ui.Element.static.gatherPreInfuseState = function () {
887 return {};
888 };
889
890 /**
891 * Get a jQuery function within a specific document.
892 *
893 * @static
894 * @param {jQuery|HTMLElement|HTMLDocument|Window} context Context to bind the function to
895 * @param {jQuery} [$iframe] HTML iframe element that contains the document, omit if document is
896 * not in an iframe
897 * @return {Function} Bound jQuery function
898 */
899 OO.ui.Element.static.getJQuery = function ( context, $iframe ) {
900 function wrapper( selector ) {
901 return $( selector, wrapper.context );
902 }
903
904 wrapper.context = this.getDocument( context );
905
906 if ( $iframe ) {
907 wrapper.$iframe = $iframe;
908 }
909
910 return wrapper;
911 };
912
913 /**
914 * Get the document of an element.
915 *
916 * @static
917 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Object to get the document for
918 * @return {HTMLDocument|null} Document object
919 */
920 OO.ui.Element.static.getDocument = function ( obj ) {
921 // jQuery - selections created "offscreen" won't have a context, so .context isn't reliable
922 return ( obj[ 0 ] && obj[ 0 ].ownerDocument ) ||
923 // Empty jQuery selections might have a context
924 obj.context ||
925 // HTMLElement
926 obj.ownerDocument ||
927 // Window
928 obj.document ||
929 // HTMLDocument
930 ( obj.nodeType === Node.DOCUMENT_NODE && obj ) ||
931 null;
932 };
933
934 /**
935 * Get the window of an element or document.
936 *
937 * @static
938 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the window for
939 * @return {Window} Window object
940 */
941 OO.ui.Element.static.getWindow = function ( obj ) {
942 var doc = this.getDocument( obj );
943 return doc.defaultView;
944 };
945
946 /**
947 * Get the direction of an element or document.
948 *
949 * @static
950 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the direction for
951 * @return {string} Text direction, either 'ltr' or 'rtl'
952 */
953 OO.ui.Element.static.getDir = function ( obj ) {
954 var isDoc, isWin;
955
956 if ( obj instanceof $ ) {
957 obj = obj[ 0 ];
958 }
959 isDoc = obj.nodeType === Node.DOCUMENT_NODE;
960 isWin = obj.document !== undefined;
961 if ( isDoc || isWin ) {
962 if ( isWin ) {
963 obj = obj.document;
964 }
965 obj = obj.body;
966 }
967 return $( obj ).css( 'direction' );
968 };
969
970 /**
971 * Get the offset between two frames.
972 *
973 * TODO: Make this function not use recursion.
974 *
975 * @static
976 * @param {Window} from Window of the child frame
977 * @param {Window} [to=window] Window of the parent frame
978 * @param {Object} [offset] Offset to start with, used internally
979 * @return {Object} Offset object, containing left and top properties
980 */
981 OO.ui.Element.static.getFrameOffset = function ( from, to, offset ) {
982 var i, len, frames, frame, rect;
983
984 if ( !to ) {
985 to = window;
986 }
987 if ( !offset ) {
988 offset = { top: 0, left: 0 };
989 }
990 if ( from.parent === from ) {
991 return offset;
992 }
993
994 // Get iframe element
995 frames = from.parent.document.getElementsByTagName( 'iframe' );
996 for ( i = 0, len = frames.length; i < len; i++ ) {
997 if ( frames[ i ].contentWindow === from ) {
998 frame = frames[ i ];
999 break;
1000 }
1001 }
1002
1003 // Recursively accumulate offset values
1004 if ( frame ) {
1005 rect = frame.getBoundingClientRect();
1006 offset.left += rect.left;
1007 offset.top += rect.top;
1008 if ( from !== to ) {
1009 this.getFrameOffset( from.parent, offset );
1010 }
1011 }
1012 return offset;
1013 };
1014
1015 /**
1016 * Get the offset between two elements.
1017 *
1018 * The two elements may be in a different frame, but in that case the frame $element is in must
1019 * be contained in the frame $anchor is in.
1020 *
1021 * @static
1022 * @param {jQuery} $element Element whose position to get
1023 * @param {jQuery} $anchor Element to get $element's position relative to
1024 * @return {Object} Translated position coordinates, containing top and left properties
1025 */
1026 OO.ui.Element.static.getRelativePosition = function ( $element, $anchor ) {
1027 var iframe, iframePos,
1028 pos = $element.offset(),
1029 anchorPos = $anchor.offset(),
1030 elementDocument = this.getDocument( $element ),
1031 anchorDocument = this.getDocument( $anchor );
1032
1033 // If $element isn't in the same document as $anchor, traverse up
1034 while ( elementDocument !== anchorDocument ) {
1035 iframe = elementDocument.defaultView.frameElement;
1036 if ( !iframe ) {
1037 throw new Error( '$element frame is not contained in $anchor frame' );
1038 }
1039 iframePos = $( iframe ).offset();
1040 pos.left += iframePos.left;
1041 pos.top += iframePos.top;
1042 elementDocument = iframe.ownerDocument;
1043 }
1044 pos.left -= anchorPos.left;
1045 pos.top -= anchorPos.top;
1046 return pos;
1047 };
1048
1049 /**
1050 * Get element border sizes.
1051 *
1052 * @static
1053 * @param {HTMLElement} el Element to measure
1054 * @return {Object} Dimensions object with `top`, `left`, `bottom` and `right` properties
1055 */
1056 OO.ui.Element.static.getBorders = function ( el ) {
1057 var doc = el.ownerDocument,
1058 win = doc.defaultView,
1059 style = win.getComputedStyle( el, null ),
1060 $el = $( el ),
1061 top = parseFloat( style ? style.borderTopWidth : $el.css( 'borderTopWidth' ) ) || 0,
1062 left = parseFloat( style ? style.borderLeftWidth : $el.css( 'borderLeftWidth' ) ) || 0,
1063 bottom = parseFloat( style ? style.borderBottomWidth : $el.css( 'borderBottomWidth' ) ) || 0,
1064 right = parseFloat( style ? style.borderRightWidth : $el.css( 'borderRightWidth' ) ) || 0;
1065
1066 return {
1067 top: top,
1068 left: left,
1069 bottom: bottom,
1070 right: right
1071 };
1072 };
1073
1074 /**
1075 * Get dimensions of an element or window.
1076 *
1077 * @static
1078 * @param {HTMLElement|Window} el Element to measure
1079 * @return {Object} Dimensions object with `borders`, `scroll`, `scrollbar` and `rect` properties
1080 */
1081 OO.ui.Element.static.getDimensions = function ( el ) {
1082 var $el, $win,
1083 doc = el.ownerDocument || el.document,
1084 win = doc.defaultView;
1085
1086 if ( win === el || el === doc.documentElement ) {
1087 $win = $( win );
1088 return {
1089 borders: { top: 0, left: 0, bottom: 0, right: 0 },
1090 scroll: {
1091 top: $win.scrollTop(),
1092 left: $win.scrollLeft()
1093 },
1094 scrollbar: { right: 0, bottom: 0 },
1095 rect: {
1096 top: 0,
1097 left: 0,
1098 bottom: $win.innerHeight(),
1099 right: $win.innerWidth()
1100 }
1101 };
1102 } else {
1103 $el = $( el );
1104 return {
1105 borders: this.getBorders( el ),
1106 scroll: {
1107 top: $el.scrollTop(),
1108 left: $el.scrollLeft()
1109 },
1110 scrollbar: {
1111 right: $el.innerWidth() - el.clientWidth,
1112 bottom: $el.innerHeight() - el.clientHeight
1113 },
1114 rect: el.getBoundingClientRect()
1115 };
1116 }
1117 };
1118
1119 /**
1120 * Get the number of pixels that an element's content is scrolled to the left.
1121 *
1122 * Adapted from <https://github.com/othree/jquery.rtl-scroll-type>.
1123 * Original code copyright 2012 Wei-Ko Kao, licensed under the MIT License.
1124 *
1125 * This function smooths out browser inconsistencies (nicely described in the README at
1126 * <https://github.com/othree/jquery.rtl-scroll-type>) and produces a result consistent
1127 * with Firefox's 'scrollLeft', which seems the sanest.
1128 *
1129 * @static
1130 * @method
1131 * @param {HTMLElement|Window} el Element to measure
1132 * @return {number} Scroll position from the left.
1133 * If the element's direction is LTR, this is a positive number between `0` (initial scroll position)
1134 * and `el.scrollWidth - el.clientWidth` (furthest possible scroll position).
1135 * If the element's direction is RTL, this is a negative number between `0` (initial scroll position)
1136 * and `-el.scrollWidth + el.clientWidth` (furthest possible scroll position).
1137 */
1138 OO.ui.Element.static.getScrollLeft = ( function () {
1139 var rtlScrollType = null;
1140
1141 function test() {
1142 var $definer = $( '<div dir="rtl" style="font-size: 14px; width: 1px; height: 1px; position: absolute; top: -1000px; overflow: scroll">A</div>' ),
1143 definer = $definer[ 0 ];
1144
1145 $definer.appendTo( 'body' );
1146 if ( definer.scrollLeft > 0 ) {
1147 // Safari, Chrome
1148 rtlScrollType = 'default';
1149 } else {
1150 definer.scrollLeft = 1;
1151 if ( definer.scrollLeft === 0 ) {
1152 // Firefox, old Opera
1153 rtlScrollType = 'negative';
1154 } else {
1155 // Internet Explorer, Edge
1156 rtlScrollType = 'reverse';
1157 }
1158 }
1159 $definer.remove();
1160 }
1161
1162 return function getScrollLeft( el ) {
1163 var isRoot = el.window === el ||
1164 el === el.ownerDocument.body ||
1165 el === el.ownerDocument.documentElement,
1166 scrollLeft = isRoot ? $( window ).scrollLeft() : el.scrollLeft,
1167 // All browsers use the correct scroll type ('negative') on the root, so don't
1168 // do any fixups when looking at the root element
1169 direction = isRoot ? 'ltr' : $( el ).css( 'direction' );
1170
1171 if ( direction === 'rtl' ) {
1172 if ( rtlScrollType === null ) {
1173 test();
1174 }
1175 if ( rtlScrollType === 'reverse' ) {
1176 scrollLeft = -scrollLeft;
1177 } else if ( rtlScrollType === 'default' ) {
1178 scrollLeft = scrollLeft - el.scrollWidth + el.clientWidth;
1179 }
1180 }
1181
1182 return scrollLeft;
1183 };
1184 }() );
1185
1186 /**
1187 * Get the root scrollable element of given element's document.
1188 *
1189 * On Blink-based browsers (Chrome etc.), `document.documentElement` can't be used to get or set
1190 * the scrollTop property; instead we have to use `document.body`. Changing and testing the value
1191 * lets us use 'body' or 'documentElement' based on what is working.
1192 *
1193 * https://code.google.com/p/chromium/issues/detail?id=303131
1194 *
1195 * @static
1196 * @param {HTMLElement} el Element to find root scrollable parent for
1197 * @return {HTMLElement} Scrollable parent, `document.body` or `document.documentElement`
1198 * depending on browser
1199 */
1200 OO.ui.Element.static.getRootScrollableElement = function ( el ) {
1201 var scrollTop, body;
1202
1203 if ( OO.ui.scrollableElement === undefined ) {
1204 body = el.ownerDocument.body;
1205 scrollTop = body.scrollTop;
1206 body.scrollTop = 1;
1207
1208 // In some browsers (observed in Chrome 56 on Linux Mint 18.1),
1209 // body.scrollTop doesn't become exactly 1, but a fractional value like 0.76
1210 if ( Math.round( body.scrollTop ) === 1 ) {
1211 body.scrollTop = scrollTop;
1212 OO.ui.scrollableElement = 'body';
1213 } else {
1214 OO.ui.scrollableElement = 'documentElement';
1215 }
1216 }
1217
1218 return el.ownerDocument[ OO.ui.scrollableElement ];
1219 };
1220
1221 /**
1222 * Get closest scrollable container.
1223 *
1224 * Traverses up until either a scrollable element or the root is reached, in which case the root
1225 * scrollable element will be returned (see #getRootScrollableElement).
1226 *
1227 * @static
1228 * @param {HTMLElement} el Element to find scrollable container for
1229 * @param {string} [dimension] Dimension of scrolling to look for; `x`, `y` or omit for either
1230 * @return {HTMLElement} Closest scrollable container
1231 */
1232 OO.ui.Element.static.getClosestScrollableContainer = function ( el, dimension ) {
1233 var i, val,
1234 // Browsers do not correctly return the computed value of 'overflow' when 'overflow-x' and
1235 // 'overflow-y' have different values, so we need to check the separate properties.
1236 props = [ 'overflow-x', 'overflow-y' ],
1237 $parent = $( el ).parent();
1238
1239 if ( dimension === 'x' || dimension === 'y' ) {
1240 props = [ 'overflow-' + dimension ];
1241 }
1242
1243 // Special case for the document root (which doesn't really have any scrollable container, since
1244 // it is the ultimate scrollable container, but this is probably saner than null or exception)
1245 if ( $( el ).is( 'html, body' ) ) {
1246 return this.getRootScrollableElement( el );
1247 }
1248
1249 while ( $parent.length ) {
1250 if ( $parent[ 0 ] === this.getRootScrollableElement( el ) ) {
1251 return $parent[ 0 ];
1252 }
1253 i = props.length;
1254 while ( i-- ) {
1255 val = $parent.css( props[ i ] );
1256 // We assume that elements with 'overflow' (in any direction) set to 'hidden' will never be
1257 // scrolled in that direction, but they can actually be scrolled programatically. The user can
1258 // unintentionally perform a scroll in such case even if the application doesn't scroll
1259 // programatically, e.g. when jumping to an anchor, or when using built-in find functionality.
1260 // This could cause funny issues...
1261 if ( val === 'auto' || val === 'scroll' ) {
1262 return $parent[ 0 ];
1263 }
1264 }
1265 $parent = $parent.parent();
1266 }
1267 // The element is unattached... return something mostly sane
1268 return this.getRootScrollableElement( el );
1269 };
1270
1271 /**
1272 * Scroll element into view.
1273 *
1274 * @static
1275 * @param {HTMLElement} el Element to scroll into view
1276 * @param {Object} [config] Configuration options
1277 * @param {string} [config.duration='fast'] jQuery animation duration value
1278 * @param {string} [config.direction] Scroll in only one direction, e.g. 'x' or 'y', omit
1279 * to scroll in both directions
1280 * @return {jQuery.Promise} Promise which resolves when the scroll is complete
1281 */
1282 OO.ui.Element.static.scrollIntoView = function ( el, config ) {
1283 var position, animations, container, $container, elementDimensions, containerDimensions, $window,
1284 deferred = $.Deferred();
1285
1286 // Configuration initialization
1287 config = config || {};
1288
1289 animations = {};
1290 container = this.getClosestScrollableContainer( el, config.direction );
1291 $container = $( container );
1292 elementDimensions = this.getDimensions( el );
1293 containerDimensions = this.getDimensions( container );
1294 $window = $( this.getWindow( el ) );
1295
1296 // Compute the element's position relative to the container
1297 if ( $container.is( 'html, body' ) ) {
1298 // If the scrollable container is the root, this is easy
1299 position = {
1300 top: elementDimensions.rect.top,
1301 bottom: $window.innerHeight() - elementDimensions.rect.bottom,
1302 left: elementDimensions.rect.left,
1303 right: $window.innerWidth() - elementDimensions.rect.right
1304 };
1305 } else {
1306 // Otherwise, we have to subtract el's coordinates from container's coordinates
1307 position = {
1308 top: elementDimensions.rect.top - ( containerDimensions.rect.top + containerDimensions.borders.top ),
1309 bottom: containerDimensions.rect.bottom - containerDimensions.borders.bottom - containerDimensions.scrollbar.bottom - elementDimensions.rect.bottom,
1310 left: elementDimensions.rect.left - ( containerDimensions.rect.left + containerDimensions.borders.left ),
1311 right: containerDimensions.rect.right - containerDimensions.borders.right - containerDimensions.scrollbar.right - elementDimensions.rect.right
1312 };
1313 }
1314
1315 if ( !config.direction || config.direction === 'y' ) {
1316 if ( position.top < 0 ) {
1317 animations.scrollTop = containerDimensions.scroll.top + position.top;
1318 } else if ( position.top > 0 && position.bottom < 0 ) {
1319 animations.scrollTop = containerDimensions.scroll.top + Math.min( position.top, -position.bottom );
1320 }
1321 }
1322 if ( !config.direction || config.direction === 'x' ) {
1323 if ( position.left < 0 ) {
1324 animations.scrollLeft = containerDimensions.scroll.left + position.left;
1325 } else if ( position.left > 0 && position.right < 0 ) {
1326 animations.scrollLeft = containerDimensions.scroll.left + Math.min( position.left, -position.right );
1327 }
1328 }
1329 if ( !$.isEmptyObject( animations ) ) {
1330 $container.stop( true ).animate( animations, config.duration === undefined ? 'fast' : config.duration );
1331 $container.queue( function ( next ) {
1332 deferred.resolve();
1333 next();
1334 } );
1335 } else {
1336 deferred.resolve();
1337 }
1338 return deferred.promise();
1339 };
1340
1341 /**
1342 * Force the browser to reconsider whether it really needs to render scrollbars inside the element
1343 * and reserve space for them, because it probably doesn't.
1344 *
1345 * Workaround primarily for <https://code.google.com/p/chromium/issues/detail?id=387290>, but also
1346 * similar bugs in other browsers. "Just" forcing a reflow is not sufficient in all cases, we need
1347 * to first actually detach (or hide, but detaching is simpler) all children, *then* force a reflow,
1348 * and then reattach (or show) them back.
1349 *
1350 * @static
1351 * @param {HTMLElement} el Element to reconsider the scrollbars on
1352 */
1353 OO.ui.Element.static.reconsiderScrollbars = function ( el ) {
1354 var i, len, scrollLeft, scrollTop, nodes = [];
1355 // Save scroll position
1356 scrollLeft = el.scrollLeft;
1357 scrollTop = el.scrollTop;
1358 // Detach all children
1359 while ( el.firstChild ) {
1360 nodes.push( el.firstChild );
1361 el.removeChild( el.firstChild );
1362 }
1363 // Force reflow
1364 // eslint-disable-next-line no-void
1365 void el.offsetHeight;
1366 // Reattach all children
1367 for ( i = 0, len = nodes.length; i < len; i++ ) {
1368 el.appendChild( nodes[ i ] );
1369 }
1370 // Restore scroll position (no-op if scrollbars disappeared)
1371 el.scrollLeft = scrollLeft;
1372 el.scrollTop = scrollTop;
1373 };
1374
1375 /* Methods */
1376
1377 /**
1378 * Toggle visibility of an element.
1379 *
1380 * @param {boolean} [show] Make element visible, omit to toggle visibility
1381 * @fires visible
1382 * @chainable
1383 * @return {OO.ui.Element} The element, for chaining
1384 */
1385 OO.ui.Element.prototype.toggle = function ( show ) {
1386 show = show === undefined ? !this.visible : !!show;
1387
1388 if ( show !== this.isVisible() ) {
1389 this.visible = show;
1390 this.$element.toggleClass( 'oo-ui-element-hidden', !this.visible );
1391 this.emit( 'toggle', show );
1392 }
1393
1394 return this;
1395 };
1396
1397 /**
1398 * Check if element is visible.
1399 *
1400 * @return {boolean} element is visible
1401 */
1402 OO.ui.Element.prototype.isVisible = function () {
1403 return this.visible;
1404 };
1405
1406 /**
1407 * Get element data.
1408 *
1409 * @return {Mixed} Element data
1410 */
1411 OO.ui.Element.prototype.getData = function () {
1412 return this.data;
1413 };
1414
1415 /**
1416 * Set element data.
1417 *
1418 * @param {Mixed} data Element data
1419 * @chainable
1420 * @return {OO.ui.Element} The element, for chaining
1421 */
1422 OO.ui.Element.prototype.setData = function ( data ) {
1423 this.data = data;
1424 return this;
1425 };
1426
1427 /**
1428 * Set the element has an 'id' attribute.
1429 *
1430 * @param {string} id
1431 * @chainable
1432 * @return {OO.ui.Element} The element, for chaining
1433 */
1434 OO.ui.Element.prototype.setElementId = function ( id ) {
1435 this.elementId = id;
1436 this.$element.attr( 'id', id );
1437 return this;
1438 };
1439
1440 /**
1441 * Ensure that the element has an 'id' attribute, setting it to an unique value if it's missing,
1442 * and return its value.
1443 *
1444 * @return {string}
1445 */
1446 OO.ui.Element.prototype.getElementId = function () {
1447 if ( this.elementId === null ) {
1448 this.setElementId( OO.ui.generateElementId() );
1449 }
1450 return this.elementId;
1451 };
1452
1453 /**
1454 * Check if element supports one or more methods.
1455 *
1456 * @param {string|string[]} methods Method or list of methods to check
1457 * @return {boolean} All methods are supported
1458 */
1459 OO.ui.Element.prototype.supports = function ( methods ) {
1460 var i, len,
1461 support = 0;
1462
1463 methods = Array.isArray( methods ) ? methods : [ methods ];
1464 for ( i = 0, len = methods.length; i < len; i++ ) {
1465 if ( typeof this[ methods[ i ] ] === 'function' ) {
1466 support++;
1467 }
1468 }
1469
1470 return methods.length === support;
1471 };
1472
1473 /**
1474 * Update the theme-provided classes.
1475 *
1476 * @localdoc This is called in element mixins and widget classes any time state changes.
1477 * Updating is debounced, minimizing overhead of changing multiple attributes and
1478 * guaranteeing that theme updates do not occur within an element's constructor
1479 */
1480 OO.ui.Element.prototype.updateThemeClasses = function () {
1481 OO.ui.theme.queueUpdateElementClasses( this );
1482 };
1483
1484 /**
1485 * Get the HTML tag name.
1486 *
1487 * Override this method to base the result on instance information.
1488 *
1489 * @return {string} HTML tag name
1490 */
1491 OO.ui.Element.prototype.getTagName = function () {
1492 return this.constructor.static.tagName;
1493 };
1494
1495 /**
1496 * Check if the element is attached to the DOM
1497 *
1498 * @return {boolean} The element is attached to the DOM
1499 */
1500 OO.ui.Element.prototype.isElementAttached = function () {
1501 return $.contains( this.getElementDocument(), this.$element[ 0 ] );
1502 };
1503
1504 /**
1505 * Get the DOM document.
1506 *
1507 * @return {HTMLDocument} Document object
1508 */
1509 OO.ui.Element.prototype.getElementDocument = function () {
1510 // Don't cache this in other ways either because subclasses could can change this.$element
1511 return OO.ui.Element.static.getDocument( this.$element );
1512 };
1513
1514 /**
1515 * Get the DOM window.
1516 *
1517 * @return {Window} Window object
1518 */
1519 OO.ui.Element.prototype.getElementWindow = function () {
1520 return OO.ui.Element.static.getWindow( this.$element );
1521 };
1522
1523 /**
1524 * Get closest scrollable container.
1525 *
1526 * @return {HTMLElement} Closest scrollable container
1527 */
1528 OO.ui.Element.prototype.getClosestScrollableElementContainer = function () {
1529 return OO.ui.Element.static.getClosestScrollableContainer( this.$element[ 0 ] );
1530 };
1531
1532 /**
1533 * Get group element is in.
1534 *
1535 * @return {OO.ui.mixin.GroupElement|null} Group element, null if none
1536 */
1537 OO.ui.Element.prototype.getElementGroup = function () {
1538 return this.elementGroup;
1539 };
1540
1541 /**
1542 * Set group element is in.
1543 *
1544 * @param {OO.ui.mixin.GroupElement|null} group Group element, null if none
1545 * @chainable
1546 * @return {OO.ui.Element} The element, for chaining
1547 */
1548 OO.ui.Element.prototype.setElementGroup = function ( group ) {
1549 this.elementGroup = group;
1550 return this;
1551 };
1552
1553 /**
1554 * Scroll element into view.
1555 *
1556 * @param {Object} [config] Configuration options
1557 * @return {jQuery.Promise} Promise which resolves when the scroll is complete
1558 */
1559 OO.ui.Element.prototype.scrollElementIntoView = function ( config ) {
1560 if (
1561 !this.isElementAttached() ||
1562 !this.isVisible() ||
1563 ( this.getElementGroup() && !this.getElementGroup().isVisible() )
1564 ) {
1565 return $.Deferred().resolve();
1566 }
1567 return OO.ui.Element.static.scrollIntoView( this.$element[ 0 ], config );
1568 };
1569
1570 /**
1571 * Restore the pre-infusion dynamic state for this widget.
1572 *
1573 * This method is called after #$element has been inserted into DOM. The parameter is the return
1574 * value of #gatherPreInfuseState.
1575 *
1576 * @protected
1577 * @param {Object} state
1578 */
1579 OO.ui.Element.prototype.restorePreInfuseState = function () {
1580 };
1581
1582 /**
1583 * Wraps an HTML snippet for use with configuration values which default
1584 * to strings. This bypasses the default html-escaping done to string
1585 * values.
1586 *
1587 * @class
1588 *
1589 * @constructor
1590 * @param {string} [content] HTML content
1591 */
1592 OO.ui.HtmlSnippet = function OoUiHtmlSnippet( content ) {
1593 // Properties
1594 this.content = content;
1595 };
1596
1597 /* Setup */
1598
1599 OO.initClass( OO.ui.HtmlSnippet );
1600
1601 /* Methods */
1602
1603 /**
1604 * Render into HTML.
1605 *
1606 * @return {string} Unchanged HTML snippet.
1607 */
1608 OO.ui.HtmlSnippet.prototype.toString = function () {
1609 return this.content;
1610 };
1611
1612 /**
1613 * Layouts are containers for elements and are used to arrange other widgets of arbitrary type in a way
1614 * that is centrally controlled and can be updated dynamically. Layouts can be, and usually are, combined.
1615 * See {@link OO.ui.FieldsetLayout FieldsetLayout}, {@link OO.ui.FieldLayout FieldLayout}, {@link OO.ui.FormLayout FormLayout},
1616 * {@link OO.ui.PanelLayout PanelLayout}, {@link OO.ui.StackLayout StackLayout}, {@link OO.ui.PageLayout PageLayout},
1617 * {@link OO.ui.HorizontalLayout HorizontalLayout}, and {@link OO.ui.BookletLayout BookletLayout} for more information and examples.
1618 *
1619 * @abstract
1620 * @class
1621 * @extends OO.ui.Element
1622 * @mixins OO.EventEmitter
1623 *
1624 * @constructor
1625 * @param {Object} [config] Configuration options
1626 */
1627 OO.ui.Layout = function OoUiLayout( config ) {
1628 // Configuration initialization
1629 config = config || {};
1630
1631 // Parent constructor
1632 OO.ui.Layout.parent.call( this, config );
1633
1634 // Mixin constructors
1635 OO.EventEmitter.call( this );
1636
1637 // Initialization
1638 this.$element.addClass( 'oo-ui-layout' );
1639 };
1640
1641 /* Setup */
1642
1643 OO.inheritClass( OO.ui.Layout, OO.ui.Element );
1644 OO.mixinClass( OO.ui.Layout, OO.EventEmitter );
1645
1646 /* Methods */
1647
1648 /**
1649 * Reset scroll offsets
1650 *
1651 * @chainable
1652 * @return {OO.ui.Layout} The layout, for chaining
1653 */
1654 OO.ui.Layout.prototype.resetScroll = function () {
1655 this.$element[ 0 ].scrollTop = 0;
1656 // TODO: Reset scrollLeft in an RTL-aware manner, see OO.ui.Element.static.getScrollLeft.
1657
1658 return this;
1659 };
1660
1661 /**
1662 * Widgets are compositions of one or more OOUI elements that users can both view
1663 * and interact with. All widgets can be configured and modified via a standard API,
1664 * and their state can change dynamically according to a model.
1665 *
1666 * @abstract
1667 * @class
1668 * @extends OO.ui.Element
1669 * @mixins OO.EventEmitter
1670 *
1671 * @constructor
1672 * @param {Object} [config] Configuration options
1673 * @cfg {boolean} [disabled=false] Disable the widget. Disabled widgets cannot be used and their
1674 * appearance reflects this state.
1675 */
1676 OO.ui.Widget = function OoUiWidget( config ) {
1677 // Initialize config
1678 config = $.extend( { disabled: false }, config );
1679
1680 // Parent constructor
1681 OO.ui.Widget.parent.call( this, config );
1682
1683 // Mixin constructors
1684 OO.EventEmitter.call( this );
1685
1686 // Properties
1687 this.disabled = null;
1688 this.wasDisabled = null;
1689
1690 // Initialization
1691 this.$element.addClass( 'oo-ui-widget' );
1692 this.setDisabled( !!config.disabled );
1693 };
1694
1695 /* Setup */
1696
1697 OO.inheritClass( OO.ui.Widget, OO.ui.Element );
1698 OO.mixinClass( OO.ui.Widget, OO.EventEmitter );
1699
1700 /* Events */
1701
1702 /**
1703 * @event disable
1704 *
1705 * A 'disable' event is emitted when the disabled state of the widget changes
1706 * (i.e. on disable **and** enable).
1707 *
1708 * @param {boolean} disabled Widget is disabled
1709 */
1710
1711 /**
1712 * @event toggle
1713 *
1714 * A 'toggle' event is emitted when the visibility of the widget changes.
1715 *
1716 * @param {boolean} visible Widget is visible
1717 */
1718
1719 /* Methods */
1720
1721 /**
1722 * Check if the widget is disabled.
1723 *
1724 * @return {boolean} Widget is disabled
1725 */
1726 OO.ui.Widget.prototype.isDisabled = function () {
1727 return this.disabled;
1728 };
1729
1730 /**
1731 * Set the 'disabled' state of the widget.
1732 *
1733 * When a widget is disabled, it cannot be used and its appearance is updated to reflect this state.
1734 *
1735 * @param {boolean} disabled Disable widget
1736 * @chainable
1737 * @return {OO.ui.Widget} The widget, for chaining
1738 */
1739 OO.ui.Widget.prototype.setDisabled = function ( disabled ) {
1740 var isDisabled;
1741
1742 this.disabled = !!disabled;
1743 isDisabled = this.isDisabled();
1744 if ( isDisabled !== this.wasDisabled ) {
1745 this.$element.toggleClass( 'oo-ui-widget-disabled', isDisabled );
1746 this.$element.toggleClass( 'oo-ui-widget-enabled', !isDisabled );
1747 this.$element.attr( 'aria-disabled', isDisabled.toString() );
1748 this.emit( 'disable', isDisabled );
1749 this.updateThemeClasses();
1750 }
1751 this.wasDisabled = isDisabled;
1752
1753 return this;
1754 };
1755
1756 /**
1757 * Update the disabled state, in case of changes in parent widget.
1758 *
1759 * @chainable
1760 * @return {OO.ui.Widget} The widget, for chaining
1761 */
1762 OO.ui.Widget.prototype.updateDisabled = function () {
1763 this.setDisabled( this.disabled );
1764 return this;
1765 };
1766
1767 /**
1768 * Get an ID of a labelable node which is part of this widget, if any, to be used for `<label for>`
1769 * value.
1770 *
1771 * If this function returns null, the widget should have a meaningful #simulateLabelClick method
1772 * instead.
1773 *
1774 * @return {string|null} The ID of the labelable element
1775 */
1776 OO.ui.Widget.prototype.getInputId = function () {
1777 return null;
1778 };
1779
1780 /**
1781 * Simulate the behavior of clicking on a label (a HTML `<label>` element) bound to this input.
1782 * HTML only allows `<label>` to act on specific "labelable" elements; complex widgets might need to
1783 * override this method to provide intuitive, accessible behavior.
1784 *
1785 * By default, this does nothing. OO.ui.mixin.TabIndexedElement overrides it for focusable widgets.
1786 * Individual widgets may override it too.
1787 *
1788 * This method is called by OO.ui.LabelWidget and OO.ui.FieldLayout. It should not be called
1789 * directly.
1790 */
1791 OO.ui.Widget.prototype.simulateLabelClick = function () {
1792 };
1793
1794 /**
1795 * Theme logic.
1796 *
1797 * @abstract
1798 * @class
1799 *
1800 * @constructor
1801 */
1802 OO.ui.Theme = function OoUiTheme() {
1803 this.elementClassesQueue = [];
1804 this.debouncedUpdateQueuedElementClasses = OO.ui.debounce( this.updateQueuedElementClasses );
1805 };
1806
1807 /* Setup */
1808
1809 OO.initClass( OO.ui.Theme );
1810
1811 /* Methods */
1812
1813 /**
1814 * Get a list of classes to be applied to a widget.
1815 *
1816 * The 'on' and 'off' lists combined MUST contain keys for all classes the theme adds or removes,
1817 * otherwise state transitions will not work properly.
1818 *
1819 * @param {OO.ui.Element} element Element for which to get classes
1820 * @return {Object.<string,string[]>} Categorized class names with `on` and `off` lists
1821 */
1822 OO.ui.Theme.prototype.getElementClasses = function () {
1823 return { on: [], off: [] };
1824 };
1825
1826 /**
1827 * Update CSS classes provided by the theme.
1828 *
1829 * For elements with theme logic hooks, this should be called any time there's a state change.
1830 *
1831 * @param {OO.ui.Element} element Element for which to update classes
1832 */
1833 OO.ui.Theme.prototype.updateElementClasses = function ( element ) {
1834 var $elements = $( [] ),
1835 classes = this.getElementClasses( element );
1836
1837 if ( element.$icon ) {
1838 $elements = $elements.add( element.$icon );
1839 }
1840 if ( element.$indicator ) {
1841 $elements = $elements.add( element.$indicator );
1842 }
1843
1844 $elements
1845 .removeClass( classes.off )
1846 .addClass( classes.on );
1847 };
1848
1849 /**
1850 * @private
1851 */
1852 OO.ui.Theme.prototype.updateQueuedElementClasses = function () {
1853 var i;
1854 for ( i = 0; i < this.elementClassesQueue.length; i++ ) {
1855 this.updateElementClasses( this.elementClassesQueue[ i ] );
1856 }
1857 // Clear the queue
1858 this.elementClassesQueue = [];
1859 };
1860
1861 /**
1862 * Queue #updateElementClasses to be called for this element.
1863 *
1864 * @localdoc QUnit tests override this method to directly call #queueUpdateElementClasses,
1865 * to make them synchronous.
1866 *
1867 * @param {OO.ui.Element} element Element for which to update classes
1868 */
1869 OO.ui.Theme.prototype.queueUpdateElementClasses = function ( element ) {
1870 // Keep items in the queue unique. Use lastIndexOf to start checking from the end because that's
1871 // the most common case (this method is often called repeatedly for the same element).
1872 if ( this.elementClassesQueue.lastIndexOf( element ) !== -1 ) {
1873 return;
1874 }
1875 this.elementClassesQueue.push( element );
1876 this.debouncedUpdateQueuedElementClasses();
1877 };
1878
1879 /**
1880 * Get the transition duration in milliseconds for dialogs opening/closing
1881 *
1882 * The dialog should be fully rendered this many milliseconds after the
1883 * ready process has executed.
1884 *
1885 * @return {number} Transition duration in milliseconds
1886 */
1887 OO.ui.Theme.prototype.getDialogTransitionDuration = function () {
1888 return 0;
1889 };
1890
1891 /**
1892 * The TabIndexedElement class is an attribute mixin used to add additional functionality to an
1893 * element created by another class. The mixin provides a ‘tabIndex’ property, which specifies the
1894 * order in which users will navigate through the focusable elements via the "tab" key.
1895 *
1896 * @example
1897 * // TabIndexedElement is mixed into the ButtonWidget class
1898 * // to provide a tabIndex property.
1899 * var button1 = new OO.ui.ButtonWidget( {
1900 * label: 'fourth',
1901 * tabIndex: 4
1902 * } );
1903 * var button2 = new OO.ui.ButtonWidget( {
1904 * label: 'second',
1905 * tabIndex: 2
1906 * } );
1907 * var button3 = new OO.ui.ButtonWidget( {
1908 * label: 'third',
1909 * tabIndex: 3
1910 * } );
1911 * var button4 = new OO.ui.ButtonWidget( {
1912 * label: 'first',
1913 * tabIndex: 1
1914 * } );
1915 * $( 'body' ).append( button1.$element, button2.$element, button3.$element, button4.$element );
1916 *
1917 * @abstract
1918 * @class
1919 *
1920 * @constructor
1921 * @param {Object} [config] Configuration options
1922 * @cfg {jQuery} [$tabIndexed] The element that should use the tabindex functionality. By default,
1923 * the functionality is applied to the element created by the class ($element). If a different element is specified, the tabindex
1924 * functionality will be applied to it instead.
1925 * @cfg {string|number|null} [tabIndex=0] Number that specifies the element’s position in the tab-navigation
1926 * order (e.g., 1 for the first focusable element). Use 0 to use the default navigation order; use -1
1927 * to remove the element from the tab-navigation flow.
1928 */
1929 OO.ui.mixin.TabIndexedElement = function OoUiMixinTabIndexedElement( config ) {
1930 // Configuration initialization
1931 config = $.extend( { tabIndex: 0 }, config );
1932
1933 // Properties
1934 this.$tabIndexed = null;
1935 this.tabIndex = null;
1936
1937 // Events
1938 this.connect( this, { disable: 'onTabIndexedElementDisable' } );
1939
1940 // Initialization
1941 this.setTabIndex( config.tabIndex );
1942 this.setTabIndexedElement( config.$tabIndexed || this.$element );
1943 };
1944
1945 /* Setup */
1946
1947 OO.initClass( OO.ui.mixin.TabIndexedElement );
1948
1949 /* Methods */
1950
1951 /**
1952 * Set the element that should use the tabindex functionality.
1953 *
1954 * This method is used to retarget a tabindex mixin so that its functionality applies
1955 * to the specified element. If an element is currently using the functionality, the mixin’s
1956 * effect on that element is removed before the new element is set up.
1957 *
1958 * @param {jQuery} $tabIndexed Element that should use the tabindex functionality
1959 * @chainable
1960 * @return {OO.ui.Element} The element, for chaining
1961 */
1962 OO.ui.mixin.TabIndexedElement.prototype.setTabIndexedElement = function ( $tabIndexed ) {
1963 var tabIndex = this.tabIndex;
1964 // Remove attributes from old $tabIndexed
1965 this.setTabIndex( null );
1966 // Force update of new $tabIndexed
1967 this.$tabIndexed = $tabIndexed;
1968 this.tabIndex = tabIndex;
1969 return this.updateTabIndex();
1970 };
1971
1972 /**
1973 * Set the value of the tabindex.
1974 *
1975 * @param {string|number|null} tabIndex Tabindex value, or `null` for no tabindex
1976 * @chainable
1977 * @return {OO.ui.Element} The element, for chaining
1978 */
1979 OO.ui.mixin.TabIndexedElement.prototype.setTabIndex = function ( tabIndex ) {
1980 tabIndex = /^-?\d+$/.test( tabIndex ) ? Number( tabIndex ) : null;
1981
1982 if ( this.tabIndex !== tabIndex ) {
1983 this.tabIndex = tabIndex;
1984 this.updateTabIndex();
1985 }
1986
1987 return this;
1988 };
1989
1990 /**
1991 * Update the `tabindex` attribute, in case of changes to tab index or
1992 * disabled state.
1993 *
1994 * @private
1995 * @chainable
1996 * @return {OO.ui.Element} The element, for chaining
1997 */
1998 OO.ui.mixin.TabIndexedElement.prototype.updateTabIndex = function () {
1999 if ( this.$tabIndexed ) {
2000 if ( this.tabIndex !== null ) {
2001 // Do not index over disabled elements
2002 this.$tabIndexed.attr( {
2003 tabindex: this.isDisabled() ? -1 : this.tabIndex,
2004 // Support: ChromeVox and NVDA
2005 // These do not seem to inherit aria-disabled from parent elements
2006 'aria-disabled': this.isDisabled().toString()
2007 } );
2008 } else {
2009 this.$tabIndexed.removeAttr( 'tabindex aria-disabled' );
2010 }
2011 }
2012 return this;
2013 };
2014
2015 /**
2016 * Handle disable events.
2017 *
2018 * @private
2019 * @param {boolean} disabled Element is disabled
2020 */
2021 OO.ui.mixin.TabIndexedElement.prototype.onTabIndexedElementDisable = function () {
2022 this.updateTabIndex();
2023 };
2024
2025 /**
2026 * Get the value of the tabindex.
2027 *
2028 * @return {number|null} Tabindex value
2029 */
2030 OO.ui.mixin.TabIndexedElement.prototype.getTabIndex = function () {
2031 return this.tabIndex;
2032 };
2033
2034 /**
2035 * Get an ID of a focusable element of this widget, if any, to be used for `<label for>` value.
2036 *
2037 * If the element already has an ID then that is returned, otherwise unique ID is
2038 * generated, set on the element, and returned.
2039 *
2040 * @return {string|null} The ID of the focusable element
2041 */
2042 OO.ui.mixin.TabIndexedElement.prototype.getInputId = function () {
2043 var id;
2044
2045 if ( !this.$tabIndexed ) {
2046 return null;
2047 }
2048 if ( !this.isLabelableNode( this.$tabIndexed ) ) {
2049 return null;
2050 }
2051
2052 id = this.$tabIndexed.attr( 'id' );
2053 if ( id === undefined ) {
2054 id = OO.ui.generateElementId();
2055 this.$tabIndexed.attr( 'id', id );
2056 }
2057
2058 return id;
2059 };
2060
2061 /**
2062 * Whether the node is 'labelable' according to the HTML spec
2063 * (i.e., whether it can be interacted with through a `<label for="…">`).
2064 * See: <https://html.spec.whatwg.org/multipage/forms.html#category-label>.
2065 *
2066 * @private
2067 * @param {jQuery} $node
2068 * @return {boolean}
2069 */
2070 OO.ui.mixin.TabIndexedElement.prototype.isLabelableNode = function ( $node ) {
2071 var
2072 labelableTags = [ 'button', 'meter', 'output', 'progress', 'select', 'textarea' ],
2073 tagName = $node.prop( 'tagName' ).toLowerCase();
2074
2075 if ( tagName === 'input' && $node.attr( 'type' ) !== 'hidden' ) {
2076 return true;
2077 }
2078 if ( labelableTags.indexOf( tagName ) !== -1 ) {
2079 return true;
2080 }
2081 return false;
2082 };
2083
2084 /**
2085 * Focus this element.
2086 *
2087 * @chainable
2088 * @return {OO.ui.Element} The element, for chaining
2089 */
2090 OO.ui.mixin.TabIndexedElement.prototype.focus = function () {
2091 if ( !this.isDisabled() ) {
2092 this.$tabIndexed.focus();
2093 }
2094 return this;
2095 };
2096
2097 /**
2098 * Blur this element.
2099 *
2100 * @chainable
2101 * @return {OO.ui.Element} The element, for chaining
2102 */
2103 OO.ui.mixin.TabIndexedElement.prototype.blur = function () {
2104 this.$tabIndexed.blur();
2105 return this;
2106 };
2107
2108 /**
2109 * @inheritdoc OO.ui.Widget
2110 */
2111 OO.ui.mixin.TabIndexedElement.prototype.simulateLabelClick = function () {
2112 this.focus();
2113 };
2114
2115 /**
2116 * ButtonElement is often mixed into other classes to generate a button, which is a clickable
2117 * interface element that can be configured with access keys for accessibility.
2118 * See the [OOUI documentation on MediaWiki] [1] for examples.
2119 *
2120 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Buttons_and_Switches#Buttons
2121 *
2122 * @abstract
2123 * @class
2124 *
2125 * @constructor
2126 * @param {Object} [config] Configuration options
2127 * @cfg {jQuery} [$button] The button element created by the class.
2128 * If this configuration is omitted, the button element will use a generated `<a>`.
2129 * @cfg {boolean} [framed=true] Render the button with a frame
2130 */
2131 OO.ui.mixin.ButtonElement = function OoUiMixinButtonElement( config ) {
2132 // Configuration initialization
2133 config = config || {};
2134
2135 // Properties
2136 this.$button = null;
2137 this.framed = null;
2138 this.active = config.active !== undefined && config.active;
2139 this.onDocumentMouseUpHandler = this.onDocumentMouseUp.bind( this );
2140 this.onMouseDownHandler = this.onMouseDown.bind( this );
2141 this.onDocumentKeyUpHandler = this.onDocumentKeyUp.bind( this );
2142 this.onKeyDownHandler = this.onKeyDown.bind( this );
2143 this.onClickHandler = this.onClick.bind( this );
2144 this.onKeyPressHandler = this.onKeyPress.bind( this );
2145
2146 // Initialization
2147 this.$element.addClass( 'oo-ui-buttonElement' );
2148 this.toggleFramed( config.framed === undefined || config.framed );
2149 this.setButtonElement( config.$button || $( '<a>' ) );
2150 };
2151
2152 /* Setup */
2153
2154 OO.initClass( OO.ui.mixin.ButtonElement );
2155
2156 /* Static Properties */
2157
2158 /**
2159 * Cancel mouse down events.
2160 *
2161 * This property is usually set to `true` to prevent the focus from changing when the button is clicked.
2162 * Classes such as {@link OO.ui.mixin.DraggableElement DraggableElement} and {@link OO.ui.ButtonOptionWidget ButtonOptionWidget}
2163 * use a value of `false` so that dragging behavior is possible and mousedown events can be handled by a
2164 * parent widget.
2165 *
2166 * @static
2167 * @inheritable
2168 * @property {boolean}
2169 */
2170 OO.ui.mixin.ButtonElement.static.cancelButtonMouseDownEvents = true;
2171
2172 /* Events */
2173
2174 /**
2175 * A 'click' event is emitted when the button element is clicked.
2176 *
2177 * @event click
2178 */
2179
2180 /* Methods */
2181
2182 /**
2183 * Set the button element.
2184 *
2185 * This method is used to retarget a button mixin so that its functionality applies to
2186 * the specified button element instead of the one created by the class. If a button element
2187 * is already set, the method will remove the mixin’s effect on that element.
2188 *
2189 * @param {jQuery} $button Element to use as button
2190 */
2191 OO.ui.mixin.ButtonElement.prototype.setButtonElement = function ( $button ) {
2192 if ( this.$button ) {
2193 this.$button
2194 .removeClass( 'oo-ui-buttonElement-button' )
2195 .removeAttr( 'role accesskey' )
2196 .off( {
2197 mousedown: this.onMouseDownHandler,
2198 keydown: this.onKeyDownHandler,
2199 click: this.onClickHandler,
2200 keypress: this.onKeyPressHandler
2201 } );
2202 }
2203
2204 this.$button = $button
2205 .addClass( 'oo-ui-buttonElement-button' )
2206 .on( {
2207 mousedown: this.onMouseDownHandler,
2208 keydown: this.onKeyDownHandler,
2209 click: this.onClickHandler,
2210 keypress: this.onKeyPressHandler
2211 } );
2212
2213 // Add `role="button"` on `<a>` elements, where it's needed
2214 // `toUpperCase()` is added for XHTML documents
2215 if ( this.$button.prop( 'tagName' ).toUpperCase() === 'A' ) {
2216 this.$button.attr( 'role', 'button' );
2217 }
2218 };
2219
2220 /**
2221 * Handles mouse down events.
2222 *
2223 * @protected
2224 * @param {jQuery.Event} e Mouse down event
2225 * @return {undefined/boolean} False to prevent default if event is handled
2226 */
2227 OO.ui.mixin.ButtonElement.prototype.onMouseDown = function ( e ) {
2228 if ( this.isDisabled() || e.which !== OO.ui.MouseButtons.LEFT ) {
2229 return;
2230 }
2231 this.$element.addClass( 'oo-ui-buttonElement-pressed' );
2232 // Run the mouseup handler no matter where the mouse is when the button is let go, so we can
2233 // reliably remove the pressed class
2234 this.getElementDocument().addEventListener( 'mouseup', this.onDocumentMouseUpHandler, true );
2235 // Prevent change of focus unless specifically configured otherwise
2236 if ( this.constructor.static.cancelButtonMouseDownEvents ) {
2237 return false;
2238 }
2239 };
2240
2241 /**
2242 * Handles document mouse up events.
2243 *
2244 * @protected
2245 * @param {MouseEvent} e Mouse up event
2246 */
2247 OO.ui.mixin.ButtonElement.prototype.onDocumentMouseUp = function ( e ) {
2248 if ( this.isDisabled() || e.which !== OO.ui.MouseButtons.LEFT ) {
2249 return;
2250 }
2251 this.$element.removeClass( 'oo-ui-buttonElement-pressed' );
2252 // Stop listening for mouseup, since we only needed this once
2253 this.getElementDocument().removeEventListener( 'mouseup', this.onDocumentMouseUpHandler, true );
2254 };
2255
2256 // Deprecated alias since 0.28.3
2257 OO.ui.mixin.ButtonElement.prototype.onMouseUp = function () {
2258 OO.ui.warnDeprecation( 'onMouseUp is deprecated, use onDocumentMouseUp instead' );
2259 this.onDocumentMouseUp.apply( this, arguments );
2260 };
2261
2262 /**
2263 * Handles mouse click events.
2264 *
2265 * @protected
2266 * @param {jQuery.Event} e Mouse click event
2267 * @fires click
2268 * @return {undefined/boolean} False to prevent default if event is handled
2269 */
2270 OO.ui.mixin.ButtonElement.prototype.onClick = function ( e ) {
2271 if ( !this.isDisabled() && e.which === OO.ui.MouseButtons.LEFT ) {
2272 if ( this.emit( 'click' ) ) {
2273 return false;
2274 }
2275 }
2276 };
2277
2278 /**
2279 * Handles key down events.
2280 *
2281 * @protected
2282 * @param {jQuery.Event} e Key down event
2283 */
2284 OO.ui.mixin.ButtonElement.prototype.onKeyDown = function ( e ) {
2285 if ( this.isDisabled() || ( e.which !== OO.ui.Keys.SPACE && e.which !== OO.ui.Keys.ENTER ) ) {
2286 return;
2287 }
2288 this.$element.addClass( 'oo-ui-buttonElement-pressed' );
2289 // Run the keyup handler no matter where the key is when the button is let go, so we can
2290 // reliably remove the pressed class
2291 this.getElementDocument().addEventListener( 'keyup', this.onDocumentKeyUpHandler, true );
2292 };
2293
2294 /**
2295 * Handles document key up events.
2296 *
2297 * @protected
2298 * @param {KeyboardEvent} e Key up event
2299 */
2300 OO.ui.mixin.ButtonElement.prototype.onDocumentKeyUp = function ( e ) {
2301 if ( this.isDisabled() || ( e.which !== OO.ui.Keys.SPACE && e.which !== OO.ui.Keys.ENTER ) ) {
2302 return;
2303 }
2304 this.$element.removeClass( 'oo-ui-buttonElement-pressed' );
2305 // Stop listening for keyup, since we only needed this once
2306 this.getElementDocument().removeEventListener( 'keyup', this.onDocumentKeyUpHandler, true );
2307 };
2308
2309 // Deprecated alias since 0.28.3
2310 OO.ui.mixin.ButtonElement.prototype.onKeyUp = function () {
2311 OO.ui.warnDeprecation( 'onKeyUp is deprecated, use onDocumentKeyUp instead' );
2312 this.onDocumentKeyUp.apply( this, arguments );
2313 };
2314
2315 /**
2316 * Handles key press events.
2317 *
2318 * @protected
2319 * @param {jQuery.Event} e Key press event
2320 * @fires click
2321 * @return {undefined/boolean} False to prevent default if event is handled
2322 */
2323 OO.ui.mixin.ButtonElement.prototype.onKeyPress = function ( e ) {
2324 if ( !this.isDisabled() && ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER ) ) {
2325 if ( this.emit( 'click' ) ) {
2326 return false;
2327 }
2328 }
2329 };
2330
2331 /**
2332 * Check if button has a frame.
2333 *
2334 * @return {boolean} Button is framed
2335 */
2336 OO.ui.mixin.ButtonElement.prototype.isFramed = function () {
2337 return this.framed;
2338 };
2339
2340 /**
2341 * Render the button with or without a frame. Omit the `framed` parameter to toggle the button frame on and off.
2342 *
2343 * @param {boolean} [framed] Make button framed, omit to toggle
2344 * @chainable
2345 * @return {OO.ui.Element} The element, for chaining
2346 */
2347 OO.ui.mixin.ButtonElement.prototype.toggleFramed = function ( framed ) {
2348 framed = framed === undefined ? !this.framed : !!framed;
2349 if ( framed !== this.framed ) {
2350 this.framed = framed;
2351 this.$element
2352 .toggleClass( 'oo-ui-buttonElement-frameless', !framed )
2353 .toggleClass( 'oo-ui-buttonElement-framed', framed );
2354 this.updateThemeClasses();
2355 }
2356
2357 return this;
2358 };
2359
2360 /**
2361 * Set the button's active state.
2362 *
2363 * The active state can be set on:
2364 *
2365 * - {@link OO.ui.ButtonOptionWidget ButtonOptionWidget} when it is selected
2366 * - {@link OO.ui.ToggleButtonWidget ToggleButtonWidget} when it is toggle on
2367 * - {@link OO.ui.ButtonWidget ButtonWidget} when clicking the button would only refresh the page
2368 *
2369 * @protected
2370 * @param {boolean} value Make button active
2371 * @chainable
2372 * @return {OO.ui.Element} The element, for chaining
2373 */
2374 OO.ui.mixin.ButtonElement.prototype.setActive = function ( value ) {
2375 this.active = !!value;
2376 this.$element.toggleClass( 'oo-ui-buttonElement-active', this.active );
2377 this.updateThemeClasses();
2378 return this;
2379 };
2380
2381 /**
2382 * Check if the button is active
2383 *
2384 * @protected
2385 * @return {boolean} The button is active
2386 */
2387 OO.ui.mixin.ButtonElement.prototype.isActive = function () {
2388 return this.active;
2389 };
2390
2391 /**
2392 * Any OOUI widget that contains other widgets (such as {@link OO.ui.ButtonWidget buttons} or
2393 * {@link OO.ui.OptionWidget options}) mixes in GroupElement. Adding, removing, and clearing
2394 * items from the group is done through the interface the class provides.
2395 * For more information, please see the [OOUI documentation on MediaWiki] [1].
2396 *
2397 * [1]: https://www.mediawiki.org/wiki/OOUI/Elements/Groups
2398 *
2399 * @abstract
2400 * @mixins OO.EmitterList
2401 * @class
2402 *
2403 * @constructor
2404 * @param {Object} [config] Configuration options
2405 * @cfg {jQuery} [$group] The container element created by the class. If this configuration
2406 * is omitted, the group element will use a generated `<div>`.
2407 */
2408 OO.ui.mixin.GroupElement = function OoUiMixinGroupElement( config ) {
2409 // Configuration initialization
2410 config = config || {};
2411
2412 // Mixin constructors
2413 OO.EmitterList.call( this, config );
2414
2415 // Properties
2416 this.$group = null;
2417
2418 // Initialization
2419 this.setGroupElement( config.$group || $( '<div>' ) );
2420 };
2421
2422 /* Setup */
2423
2424 OO.mixinClass( OO.ui.mixin.GroupElement, OO.EmitterList );
2425
2426 /* Events */
2427
2428 /**
2429 * @event change
2430 *
2431 * A change event is emitted when the set of selected items changes.
2432 *
2433 * @param {OO.ui.Element[]} items Items currently in the group
2434 */
2435
2436 /* Methods */
2437
2438 /**
2439 * Set the group element.
2440 *
2441 * If an element is already set, items will be moved to the new element.
2442 *
2443 * @param {jQuery} $group Element to use as group
2444 */
2445 OO.ui.mixin.GroupElement.prototype.setGroupElement = function ( $group ) {
2446 var i, len;
2447
2448 this.$group = $group;
2449 for ( i = 0, len = this.items.length; i < len; i++ ) {
2450 this.$group.append( this.items[ i ].$element );
2451 }
2452 };
2453
2454 /**
2455 * Find an item by its data.
2456 *
2457 * Only the first item with matching data will be returned. To return all matching items,
2458 * use the #findItemsFromData method.
2459 *
2460 * @param {Object} data Item data to search for
2461 * @return {OO.ui.Element|null} Item with equivalent data, `null` if none exists
2462 */
2463 OO.ui.mixin.GroupElement.prototype.findItemFromData = function ( data ) {
2464 var i, len, item,
2465 hash = OO.getHash( data );
2466
2467 for ( i = 0, len = this.items.length; i < len; i++ ) {
2468 item = this.items[ i ];
2469 if ( hash === OO.getHash( item.getData() ) ) {
2470 return item;
2471 }
2472 }
2473
2474 return null;
2475 };
2476
2477 /**
2478 * Find items by their data.
2479 *
2480 * All items with matching data will be returned. To return only the first match, use the #findItemFromData method instead.
2481 *
2482 * @param {Object} data Item data to search for
2483 * @return {OO.ui.Element[]} Items with equivalent data
2484 */
2485 OO.ui.mixin.GroupElement.prototype.findItemsFromData = function ( data ) {
2486 var i, len, item,
2487 hash = OO.getHash( data ),
2488 items = [];
2489
2490 for ( i = 0, len = this.items.length; i < len; i++ ) {
2491 item = this.items[ i ];
2492 if ( hash === OO.getHash( item.getData() ) ) {
2493 items.push( item );
2494 }
2495 }
2496
2497 return items;
2498 };
2499
2500 /**
2501 * Add items to the group.
2502 *
2503 * Items will be added to the end of the group array unless the optional `index` parameter specifies
2504 * a different insertion point. Adding an existing item will move it to the end of the array or the point specified by the `index`.
2505 *
2506 * @param {OO.ui.Element[]} items An array of items to add to the group
2507 * @param {number} [index] Index of the insertion point
2508 * @chainable
2509 * @return {OO.ui.Element} The element, for chaining
2510 */
2511 OO.ui.mixin.GroupElement.prototype.addItems = function ( items, index ) {
2512 // Mixin method
2513 OO.EmitterList.prototype.addItems.call( this, items, index );
2514
2515 this.emit( 'change', this.getItems() );
2516 return this;
2517 };
2518
2519 /**
2520 * @inheritdoc
2521 */
2522 OO.ui.mixin.GroupElement.prototype.moveItem = function ( items, newIndex ) {
2523 // insertItemElements expects this.items to not have been modified yet, so call before the mixin
2524 this.insertItemElements( items, newIndex );
2525
2526 // Mixin method
2527 newIndex = OO.EmitterList.prototype.moveItem.call( this, items, newIndex );
2528
2529 return newIndex;
2530 };
2531
2532 /**
2533 * @inheritdoc
2534 */
2535 OO.ui.mixin.GroupElement.prototype.insertItem = function ( item, index ) {
2536 item.setElementGroup( this );
2537 this.insertItemElements( item, index );
2538
2539 // Mixin method
2540 index = OO.EmitterList.prototype.insertItem.call( this, item, index );
2541
2542 return index;
2543 };
2544
2545 /**
2546 * Insert elements into the group
2547 *
2548 * @private
2549 * @param {OO.ui.Element} itemWidget Item to insert
2550 * @param {number} index Insertion index
2551 */
2552 OO.ui.mixin.GroupElement.prototype.insertItemElements = function ( itemWidget, index ) {
2553 if ( index === undefined || index < 0 || index >= this.items.length ) {
2554 this.$group.append( itemWidget.$element );
2555 } else if ( index === 0 ) {
2556 this.$group.prepend( itemWidget.$element );
2557 } else {
2558 this.items[ index ].$element.before( itemWidget.$element );
2559 }
2560 };
2561
2562 /**
2563 * Remove the specified items from a group.
2564 *
2565 * Removed items are detached (not removed) from the DOM so that they may be reused.
2566 * To remove all items from a group, you may wish to use the #clearItems method instead.
2567 *
2568 * @param {OO.ui.Element[]} items An array of items to remove
2569 * @chainable
2570 * @return {OO.ui.Element} The element, for chaining
2571 */
2572 OO.ui.mixin.GroupElement.prototype.removeItems = function ( items ) {
2573 var i, len, item, index;
2574
2575 // Remove specific items elements
2576 for ( i = 0, len = items.length; i < len; i++ ) {
2577 item = items[ i ];
2578 index = this.items.indexOf( item );
2579 if ( index !== -1 ) {
2580 item.setElementGroup( null );
2581 item.$element.detach();
2582 }
2583 }
2584
2585 // Mixin method
2586 OO.EmitterList.prototype.removeItems.call( this, items );
2587
2588 this.emit( 'change', this.getItems() );
2589 return this;
2590 };
2591
2592 /**
2593 * Clear all items from the group.
2594 *
2595 * Cleared items are detached from the DOM, not removed, so that they may be reused.
2596 * To remove only a subset of items from a group, use the #removeItems method.
2597 *
2598 * @chainable
2599 * @return {OO.ui.Element} The element, for chaining
2600 */
2601 OO.ui.mixin.GroupElement.prototype.clearItems = function () {
2602 var i, len;
2603
2604 // Remove all item elements
2605 for ( i = 0, len = this.items.length; i < len; i++ ) {
2606 this.items[ i ].setElementGroup( null );
2607 this.items[ i ].$element.detach();
2608 }
2609
2610 // Mixin method
2611 OO.EmitterList.prototype.clearItems.call( this );
2612
2613 this.emit( 'change', this.getItems() );
2614 return this;
2615 };
2616
2617 /**
2618 * LabelElement is often mixed into other classes to generate a label, which
2619 * helps identify the function of an interface element.
2620 * See the [OOUI documentation on MediaWiki] [1] for more information.
2621 *
2622 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Icons,_Indicators,_and_Labels#Labels
2623 *
2624 * @abstract
2625 * @class
2626 *
2627 * @constructor
2628 * @param {Object} [config] Configuration options
2629 * @cfg {jQuery} [$label] The label element created by the class. If this
2630 * configuration is omitted, the label element will use a generated `<span>`.
2631 * @cfg {jQuery|string|Function|OO.ui.HtmlSnippet} [label] The label text. The label can be specified
2632 * as a plaintext string, a jQuery selection of elements, or a function that will produce a string
2633 * in the future. See the [OOUI documentation on MediaWiki] [2] for examples.
2634 * [2]: https://www.mediawiki.org/wiki/OOUI/Widgets/Icons,_Indicators,_and_Labels#Labels
2635 * @cfg {boolean} [invisibleLabel] Whether the label should be visually hidden (but still accessible
2636 * to screen-readers).
2637 */
2638 OO.ui.mixin.LabelElement = function OoUiMixinLabelElement( config ) {
2639 // Configuration initialization
2640 config = config || {};
2641
2642 // Properties
2643 this.$label = null;
2644 this.label = null;
2645 this.invisibleLabel = null;
2646
2647 // Initialization
2648 this.setLabel( config.label || this.constructor.static.label );
2649 this.setLabelElement( config.$label || $( '<span>' ) );
2650 this.setInvisibleLabel( config.invisibleLabel );
2651 };
2652
2653 /* Setup */
2654
2655 OO.initClass( OO.ui.mixin.LabelElement );
2656
2657 /* Events */
2658
2659 /**
2660 * @event labelChange
2661 * @param {string} value
2662 */
2663
2664 /* Static Properties */
2665
2666 /**
2667 * The label text. The label can be specified as a plaintext string, a function that will
2668 * produce a string in the future, or `null` for no label. The static value will
2669 * be overridden if a label is specified with the #label config option.
2670 *
2671 * @static
2672 * @inheritable
2673 * @property {string|Function|null}
2674 */
2675 OO.ui.mixin.LabelElement.static.label = null;
2676
2677 /* Static methods */
2678
2679 /**
2680 * Highlight the first occurrence of the query in the given text
2681 *
2682 * @param {string} text Text
2683 * @param {string} query Query to find
2684 * @param {Function} [compare] Optional string comparator, e.g. Intl.Collator().compare
2685 * @return {jQuery} Text with the first match of the query
2686 * sub-string wrapped in highlighted span
2687 */
2688 OO.ui.mixin.LabelElement.static.highlightQuery = function ( text, query, compare ) {
2689 var i, tLen, qLen,
2690 offset = -1,
2691 $result = $( '<span>' );
2692
2693 if ( compare ) {
2694 tLen = text.length;
2695 qLen = query.length;
2696 for ( i = 0; offset === -1 && i <= tLen - qLen; i++ ) {
2697 if ( compare( query, text.slice( i, i + qLen ) ) === 0 ) {
2698 offset = i;
2699 }
2700 }
2701 } else {
2702 offset = text.toLowerCase().indexOf( query.toLowerCase() );
2703 }
2704
2705 if ( !query.length || offset === -1 ) {
2706 $result.text( text );
2707 } else {
2708 $result.append(
2709 document.createTextNode( text.slice( 0, offset ) ),
2710 $( '<span>' )
2711 .addClass( 'oo-ui-labelElement-label-highlight' )
2712 .text( text.slice( offset, offset + query.length ) ),
2713 document.createTextNode( text.slice( offset + query.length ) )
2714 );
2715 }
2716 return $result.contents();
2717 };
2718
2719 /* Methods */
2720
2721 /**
2722 * Set the label element.
2723 *
2724 * If an element is already set, it will be cleaned up before setting up the new element.
2725 *
2726 * @param {jQuery} $label Element to use as label
2727 */
2728 OO.ui.mixin.LabelElement.prototype.setLabelElement = function ( $label ) {
2729 if ( this.$label ) {
2730 this.$label.removeClass( 'oo-ui-labelElement-label' ).empty();
2731 }
2732
2733 this.$label = $label.addClass( 'oo-ui-labelElement-label' );
2734 this.setLabelContent( this.label );
2735 };
2736
2737 /**
2738 * Set the label.
2739 *
2740 * An empty string will result in the label being hidden. A string containing only whitespace will
2741 * be converted to a single `&nbsp;`.
2742 *
2743 * @param {jQuery|string|OO.ui.HtmlSnippet|Function|null} label Label nodes; text; a function that returns nodes or
2744 * text; or null for no label
2745 * @chainable
2746 * @return {OO.ui.Element} The element, for chaining
2747 */
2748 OO.ui.mixin.LabelElement.prototype.setLabel = function ( label ) {
2749 label = typeof label === 'function' ? OO.ui.resolveMsg( label ) : label;
2750 label = ( ( typeof label === 'string' || label instanceof $ ) && label.length ) || ( label instanceof OO.ui.HtmlSnippet && label.toString().length ) ? label : null;
2751
2752 if ( this.label !== label ) {
2753 if ( this.$label ) {
2754 this.setLabelContent( label );
2755 }
2756 this.label = label;
2757 this.emit( 'labelChange' );
2758 }
2759
2760 this.$element.toggleClass( 'oo-ui-labelElement', !!this.label && !this.invisibleLabel );
2761
2762 return this;
2763 };
2764
2765 /**
2766 * Set whether the label should be visually hidden (but still accessible to screen-readers).
2767 *
2768 * @param {boolean} invisibleLabel
2769 * @chainable
2770 * @return {OO.ui.Element} The element, for chaining
2771 */
2772 OO.ui.mixin.LabelElement.prototype.setInvisibleLabel = function ( invisibleLabel ) {
2773 invisibleLabel = !!invisibleLabel;
2774
2775 if ( this.invisibleLabel !== invisibleLabel ) {
2776 this.invisibleLabel = invisibleLabel;
2777 this.emit( 'labelChange' );
2778 }
2779
2780 this.$label.toggleClass( 'oo-ui-labelElement-invisible', this.invisibleLabel );
2781 // Pretend that there is no label, a lot of CSS has been written with this assumption
2782 this.$element.toggleClass( 'oo-ui-labelElement', !!this.label && !this.invisibleLabel );
2783
2784 return this;
2785 };
2786
2787 /**
2788 * Set the label as plain text with a highlighted query
2789 *
2790 * @param {string} text Text label to set
2791 * @param {string} query Substring of text to highlight
2792 * @param {Function} [compare] Optional string comparator, e.g. Intl.Collator().compare
2793 * @chainable
2794 * @return {OO.ui.Element} The element, for chaining
2795 */
2796 OO.ui.mixin.LabelElement.prototype.setHighlightedQuery = function ( text, query, compare ) {
2797 return this.setLabel( this.constructor.static.highlightQuery( text, query, compare ) );
2798 };
2799
2800 /**
2801 * Get the label.
2802 *
2803 * @return {jQuery|string|Function|null} Label nodes; text; a function that returns nodes or
2804 * text; or null for no label
2805 */
2806 OO.ui.mixin.LabelElement.prototype.getLabel = function () {
2807 return this.label;
2808 };
2809
2810 /**
2811 * Set the content of the label.
2812 *
2813 * Do not call this method until after the label element has been set by #setLabelElement.
2814 *
2815 * @private
2816 * @param {jQuery|string|Function|null} label Label nodes; text; a function that returns nodes or
2817 * text; or null for no label
2818 */
2819 OO.ui.mixin.LabelElement.prototype.setLabelContent = function ( label ) {
2820 if ( typeof label === 'string' ) {
2821 if ( label.match( /^\s*$/ ) ) {
2822 // Convert whitespace only string to a single non-breaking space
2823 this.$label.html( '&nbsp;' );
2824 } else {
2825 this.$label.text( label );
2826 }
2827 } else if ( label instanceof OO.ui.HtmlSnippet ) {
2828 this.$label.html( label.toString() );
2829 } else if ( label instanceof $ ) {
2830 this.$label.empty().append( label );
2831 } else {
2832 this.$label.empty();
2833 }
2834 };
2835
2836 /**
2837 * IconElement is often mixed into other classes to generate an icon.
2838 * Icons are graphics, about the size of normal text. They are used to aid the user
2839 * in locating a control or to convey information in a space-efficient way. See the
2840 * [OOUI documentation on MediaWiki] [1] for a list of icons
2841 * included in the library.
2842 *
2843 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Icons,_Indicators,_and_Labels#Icons
2844 *
2845 * @abstract
2846 * @class
2847 *
2848 * @constructor
2849 * @param {Object} [config] Configuration options
2850 * @cfg {jQuery} [$icon] The icon element created by the class. If this configuration is omitted,
2851 * the icon element will use a generated `<span>`. To use a different HTML tag, or to specify that
2852 * the icon element be set to an existing icon instead of the one generated by this class, set a
2853 * value using a jQuery selection. For example:
2854 *
2855 * // Use a <div> tag instead of a <span>
2856 * $icon: $("<div>")
2857 * // Use an existing icon element instead of the one generated by the class
2858 * $icon: this.$element
2859 * // Use an icon element from a child widget
2860 * $icon: this.childwidget.$element
2861 * @cfg {Object|string} [icon=''] The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of
2862 * symbolic names. A map is used for i18n purposes and contains a `default` icon
2863 * name and additional names keyed by language code. The `default` name is used when no icon is keyed
2864 * by the user's language.
2865 *
2866 * Example of an i18n map:
2867 *
2868 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
2869 * See the [OOUI documentation on MediaWiki] [2] for a list of icons included in the library.
2870 * [2]: https://www.mediawiki.org/wiki/OOUI/Widgets/Icons,_Indicators,_and_Labels#Icons
2871 * @cfg {string|Function} [iconTitle] A text string used as the icon title, or a function that returns title
2872 * text. The icon title is displayed when users move the mouse over the icon.
2873 */
2874 OO.ui.mixin.IconElement = function OoUiMixinIconElement( config ) {
2875 // Configuration initialization
2876 config = config || {};
2877
2878 // Properties
2879 this.$icon = null;
2880 this.icon = null;
2881 this.iconTitle = null;
2882
2883 // Initialization
2884 this.setIcon( config.icon || this.constructor.static.icon );
2885 this.setIconTitle( config.iconTitle || this.constructor.static.iconTitle );
2886 this.setIconElement( config.$icon || $( '<span>' ) );
2887 };
2888
2889 /* Setup */
2890
2891 OO.initClass( OO.ui.mixin.IconElement );
2892
2893 /* Static Properties */
2894
2895 /**
2896 * The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of symbolic names. A map is used
2897 * for i18n purposes and contains a `default` icon name and additional names keyed by
2898 * language code. The `default` name is used when no icon is keyed by the user's language.
2899 *
2900 * Example of an i18n map:
2901 *
2902 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
2903 *
2904 * Note: the static property will be overridden if the #icon configuration is used.
2905 *
2906 * @static
2907 * @inheritable
2908 * @property {Object|string}
2909 */
2910 OO.ui.mixin.IconElement.static.icon = null;
2911
2912 /**
2913 * The icon title, displayed when users move the mouse over the icon. The value can be text, a
2914 * function that returns title text, or `null` for no title.
2915 *
2916 * The static property will be overridden if the #iconTitle configuration is used.
2917 *
2918 * @static
2919 * @inheritable
2920 * @property {string|Function|null}
2921 */
2922 OO.ui.mixin.IconElement.static.iconTitle = null;
2923
2924 /* Methods */
2925
2926 /**
2927 * Set the icon element. This method is used to retarget an icon mixin so that its functionality
2928 * applies to the specified icon element instead of the one created by the class. If an icon
2929 * element is already set, the mixin’s effect on that element is removed. Generated CSS classes
2930 * and mixin methods will no longer affect the element.
2931 *
2932 * @param {jQuery} $icon Element to use as icon
2933 */
2934 OO.ui.mixin.IconElement.prototype.setIconElement = function ( $icon ) {
2935 if ( this.$icon ) {
2936 this.$icon
2937 .removeClass( 'oo-ui-iconElement-icon oo-ui-icon-' + this.icon )
2938 .removeAttr( 'title' );
2939 }
2940
2941 this.$icon = $icon
2942 .addClass( 'oo-ui-iconElement-icon' )
2943 .toggleClass( 'oo-ui-iconElement-noIcon', !this.icon )
2944 .toggleClass( 'oo-ui-icon-' + this.icon, !!this.icon );
2945 if ( this.iconTitle !== null ) {
2946 this.$icon.attr( 'title', this.iconTitle );
2947 }
2948
2949 this.updateThemeClasses();
2950 };
2951
2952 /**
2953 * Set icon by symbolic name (e.g., ‘remove’ or ‘menu’). Use `null` to remove an icon.
2954 * The icon parameter can also be set to a map of icon names. See the #icon config setting
2955 * for an example.
2956 *
2957 * @param {Object|string|null} icon A symbolic icon name, a {@link #icon map of icon names} keyed
2958 * by language code, or `null` to remove the icon.
2959 * @chainable
2960 * @return {OO.ui.Element} The element, for chaining
2961 */
2962 OO.ui.mixin.IconElement.prototype.setIcon = function ( icon ) {
2963 icon = OO.isPlainObject( icon ) ? OO.ui.getLocalValue( icon, null, 'default' ) : icon;
2964 icon = typeof icon === 'string' && icon.trim().length ? icon.trim() : null;
2965
2966 if ( this.icon !== icon ) {
2967 if ( this.$icon ) {
2968 if ( this.icon !== null ) {
2969 this.$icon.removeClass( 'oo-ui-icon-' + this.icon );
2970 }
2971 if ( icon !== null ) {
2972 this.$icon.addClass( 'oo-ui-icon-' + icon );
2973 }
2974 }
2975 this.icon = icon;
2976 }
2977
2978 this.$element.toggleClass( 'oo-ui-iconElement', !!this.icon );
2979 if ( this.$icon ) {
2980 this.$icon.toggleClass( 'oo-ui-iconElement-noIcon', !this.icon );
2981 }
2982 this.updateThemeClasses();
2983
2984 return this;
2985 };
2986
2987 /**
2988 * Set the icon title. Use `null` to remove the title.
2989 *
2990 * @param {string|Function|null} iconTitle A text string used as the icon title,
2991 * a function that returns title text, or `null` for no title.
2992 * @chainable
2993 * @return {OO.ui.Element} The element, for chaining
2994 */
2995 OO.ui.mixin.IconElement.prototype.setIconTitle = function ( iconTitle ) {
2996 iconTitle =
2997 ( typeof iconTitle === 'function' || ( typeof iconTitle === 'string' && iconTitle.length ) ) ?
2998 OO.ui.resolveMsg( iconTitle ) : null;
2999
3000 if ( this.iconTitle !== iconTitle ) {
3001 this.iconTitle = iconTitle;
3002 if ( this.$icon ) {
3003 if ( this.iconTitle !== null ) {
3004 this.$icon.attr( 'title', iconTitle );
3005 } else {
3006 this.$icon.removeAttr( 'title' );
3007 }
3008 }
3009 }
3010
3011 return this;
3012 };
3013
3014 /**
3015 * Get the symbolic name of the icon.
3016 *
3017 * @return {string} Icon name
3018 */
3019 OO.ui.mixin.IconElement.prototype.getIcon = function () {
3020 return this.icon;
3021 };
3022
3023 /**
3024 * Get the icon title. The title text is displayed when a user moves the mouse over the icon.
3025 *
3026 * @return {string} Icon title text
3027 */
3028 OO.ui.mixin.IconElement.prototype.getIconTitle = function () {
3029 return this.iconTitle;
3030 };
3031
3032 /**
3033 * IndicatorElement is often mixed into other classes to generate an indicator.
3034 * Indicators are small graphics that are generally used in two ways:
3035 *
3036 * - To draw attention to the status of an item. For example, an indicator might be
3037 * used to show that an item in a list has errors that need to be resolved.
3038 * - To clarify the function of a control that acts in an exceptional way (a button
3039 * that opens a menu instead of performing an action directly, for example).
3040 *
3041 * For a list of indicators included in the library, please see the
3042 * [OOUI documentation on MediaWiki] [1].
3043 *
3044 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Icons,_Indicators,_and_Labels#Indicators
3045 *
3046 * @abstract
3047 * @class
3048 *
3049 * @constructor
3050 * @param {Object} [config] Configuration options
3051 * @cfg {jQuery} [$indicator] The indicator element created by the class. If this
3052 * configuration is omitted, the indicator element will use a generated `<span>`.
3053 * @cfg {string} [indicator] Symbolic name of the indicator (e.g., ‘clear’ or ‘down’).
3054 * See the [OOUI documentation on MediaWiki][2] for a list of indicators included
3055 * in the library.
3056 * [2]: https://www.mediawiki.org/wiki/OOUI/Widgets/Icons,_Indicators,_and_Labels#Indicators
3057 * @cfg {string|Function} [indicatorTitle] A text string used as the indicator title,
3058 * or a function that returns title text. The indicator title is displayed when users move
3059 * the mouse over the indicator.
3060 */
3061 OO.ui.mixin.IndicatorElement = function OoUiMixinIndicatorElement( config ) {
3062 // Configuration initialization
3063 config = config || {};
3064
3065 // Properties
3066 this.$indicator = null;
3067 this.indicator = null;
3068 this.indicatorTitle = null;
3069
3070 // Initialization
3071 this.setIndicator( config.indicator || this.constructor.static.indicator );
3072 this.setIndicatorTitle( config.indicatorTitle || this.constructor.static.indicatorTitle );
3073 this.setIndicatorElement( config.$indicator || $( '<span>' ) );
3074 };
3075
3076 /* Setup */
3077
3078 OO.initClass( OO.ui.mixin.IndicatorElement );
3079
3080 /* Static Properties */
3081
3082 /**
3083 * Symbolic name of the indicator (e.g., ‘clear’ or ‘down’).
3084 * The static property will be overridden if the #indicator configuration is used.
3085 *
3086 * @static
3087 * @inheritable
3088 * @property {string|null}
3089 */
3090 OO.ui.mixin.IndicatorElement.static.indicator = null;
3091
3092 /**
3093 * A text string used as the indicator title, a function that returns title text, or `null`
3094 * for no title. The static property will be overridden if the #indicatorTitle configuration is used.
3095 *
3096 * @static
3097 * @inheritable
3098 * @property {string|Function|null}
3099 */
3100 OO.ui.mixin.IndicatorElement.static.indicatorTitle = null;
3101
3102 /* Methods */
3103
3104 /**
3105 * Set the indicator element.
3106 *
3107 * If an element is already set, it will be cleaned up before setting up the new element.
3108 *
3109 * @param {jQuery} $indicator Element to use as indicator
3110 */
3111 OO.ui.mixin.IndicatorElement.prototype.setIndicatorElement = function ( $indicator ) {
3112 if ( this.$indicator ) {
3113 this.$indicator
3114 .removeClass( 'oo-ui-indicatorElement-indicator oo-ui-indicator-' + this.indicator )
3115 .removeAttr( 'title' );
3116 }
3117
3118 this.$indicator = $indicator
3119 .addClass( 'oo-ui-indicatorElement-indicator' )
3120 .toggleClass( 'oo-ui-indicatorElement-noIndicator', !this.indicator )
3121 .toggleClass( 'oo-ui-indicator-' + this.indicator, !!this.indicator );
3122 if ( this.indicatorTitle !== null ) {
3123 this.$indicator.attr( 'title', this.indicatorTitle );
3124 }
3125
3126 this.updateThemeClasses();
3127 };
3128
3129 /**
3130 * Set the indicator by its symbolic name: ‘clear’, ‘down’, ‘required’, ‘search’, ‘up’. Use `null` to remove the indicator.
3131 *
3132 * @param {string|null} indicator Symbolic name of indicator, or `null` for no indicator
3133 * @chainable
3134 * @return {OO.ui.Element} The element, for chaining
3135 */
3136 OO.ui.mixin.IndicatorElement.prototype.setIndicator = function ( indicator ) {
3137 indicator = typeof indicator === 'string' && indicator.length ? indicator.trim() : null;
3138
3139 if ( this.indicator !== indicator ) {
3140 if ( this.$indicator ) {
3141 if ( this.indicator !== null ) {
3142 this.$indicator.removeClass( 'oo-ui-indicator-' + this.indicator );
3143 }
3144 if ( indicator !== null ) {
3145 this.$indicator.addClass( 'oo-ui-indicator-' + indicator );
3146 }
3147 }
3148 this.indicator = indicator;
3149 }
3150
3151 this.$element.toggleClass( 'oo-ui-indicatorElement', !!this.indicator );
3152 if ( this.$indicator ) {
3153 this.$indicator.toggleClass( 'oo-ui-indicatorElement-noIndicator', !this.indicator );
3154 }
3155 this.updateThemeClasses();
3156
3157 return this;
3158 };
3159
3160 /**
3161 * Set the indicator title.
3162 *
3163 * The title is displayed when a user moves the mouse over the indicator.
3164 *
3165 * @param {string|Function|null} indicatorTitle Indicator title text, a function that returns text, or
3166 * `null` for no indicator title
3167 * @chainable
3168 * @return {OO.ui.Element} The element, for chaining
3169 */
3170 OO.ui.mixin.IndicatorElement.prototype.setIndicatorTitle = function ( indicatorTitle ) {
3171 indicatorTitle =
3172 ( typeof indicatorTitle === 'function' || ( typeof indicatorTitle === 'string' && indicatorTitle.length ) ) ?
3173 OO.ui.resolveMsg( indicatorTitle ) : null;
3174
3175 if ( this.indicatorTitle !== indicatorTitle ) {
3176 this.indicatorTitle = indicatorTitle;
3177 if ( this.$indicator ) {
3178 if ( this.indicatorTitle !== null ) {
3179 this.$indicator.attr( 'title', indicatorTitle );
3180 } else {
3181 this.$indicator.removeAttr( 'title' );
3182 }
3183 }
3184 }
3185
3186 return this;
3187 };
3188
3189 /**
3190 * Get the symbolic name of the indicator (e.g., ‘clear’ or ‘down’).
3191 *
3192 * @return {string} Symbolic name of indicator
3193 */
3194 OO.ui.mixin.IndicatorElement.prototype.getIndicator = function () {
3195 return this.indicator;
3196 };
3197
3198 /**
3199 * Get the indicator title.
3200 *
3201 * The title is displayed when a user moves the mouse over the indicator.
3202 *
3203 * @return {string} Indicator title text
3204 */
3205 OO.ui.mixin.IndicatorElement.prototype.getIndicatorTitle = function () {
3206 return this.indicatorTitle;
3207 };
3208
3209 /**
3210 * The FlaggedElement class is an attribute mixin, meaning that it is used to add
3211 * additional functionality to an element created by another class. The class provides
3212 * a ‘flags’ property assigned the name (or an array of names) of styling flags,
3213 * which are used to customize the look and feel of a widget to better describe its
3214 * importance and functionality.
3215 *
3216 * The library currently contains the following styling flags for general use:
3217 *
3218 * - **progressive**: Progressive styling is applied to convey that the widget will move the user forward in a process.
3219 * - **destructive**: Destructive styling is applied to convey that the widget will remove something.
3220 *
3221 * The flags affect the appearance of the buttons:
3222 *
3223 * @example
3224 * // FlaggedElement is mixed into ButtonWidget to provide styling flags
3225 * var button1 = new OO.ui.ButtonWidget( {
3226 * label: 'Progressive',
3227 * flags: 'progressive'
3228 * } );
3229 * var button2 = new OO.ui.ButtonWidget( {
3230 * label: 'Destructive',
3231 * flags: 'destructive'
3232 * } );
3233 * $( 'body' ).append( button1.$element, button2.$element );
3234 *
3235 * {@link OO.ui.ActionWidget ActionWidgets}, which are a special kind of button that execute an action, use these flags: **primary** and **safe**.
3236 * Please see the [OOUI documentation on MediaWiki] [1] for more information.
3237 *
3238 * [1]: https://www.mediawiki.org/wiki/OOUI/Elements/Flagged
3239 *
3240 * @abstract
3241 * @class
3242 *
3243 * @constructor
3244 * @param {Object} [config] Configuration options
3245 * @cfg {string|string[]} [flags] The name or names of the flags (e.g., 'progressive' or 'primary') to apply.
3246 * Please see the [OOUI documentation on MediaWiki] [2] for more information about available flags.
3247 * [2]: https://www.mediawiki.org/wiki/OOUI/Elements/Flagged
3248 * @cfg {jQuery} [$flagged] The flagged element. By default,
3249 * the flagged functionality is applied to the element created by the class ($element).
3250 * If a different element is specified, the flagged functionality will be applied to it instead.
3251 */
3252 OO.ui.mixin.FlaggedElement = function OoUiMixinFlaggedElement( config ) {
3253 // Configuration initialization
3254 config = config || {};
3255
3256 // Properties
3257 this.flags = {};
3258 this.$flagged = null;
3259
3260 // Initialization
3261 this.setFlags( config.flags );
3262 this.setFlaggedElement( config.$flagged || this.$element );
3263 };
3264
3265 /* Events */
3266
3267 /**
3268 * @event flag
3269 * A flag event is emitted when the #clearFlags or #setFlags methods are used. The `changes`
3270 * parameter contains the name of each modified flag and indicates whether it was
3271 * added or removed.
3272 *
3273 * @param {Object.<string,boolean>} changes Object keyed by flag name. A Boolean `true` indicates
3274 * that the flag was added, `false` that the flag was removed.
3275 */
3276
3277 /* Methods */
3278
3279 /**
3280 * Set the flagged element.
3281 *
3282 * This method is used to retarget a flagged mixin so that its functionality applies to the specified element.
3283 * If an element is already set, the method will remove the mixin’s effect on that element.
3284 *
3285 * @param {jQuery} $flagged Element that should be flagged
3286 */
3287 OO.ui.mixin.FlaggedElement.prototype.setFlaggedElement = function ( $flagged ) {
3288 var classNames = Object.keys( this.flags ).map( function ( flag ) {
3289 return 'oo-ui-flaggedElement-' + flag;
3290 } );
3291
3292 if ( this.$flagged ) {
3293 this.$flagged.removeClass( classNames );
3294 }
3295
3296 this.$flagged = $flagged.addClass( classNames );
3297 };
3298
3299 /**
3300 * Check if the specified flag is set.
3301 *
3302 * @param {string} flag Name of flag
3303 * @return {boolean} The flag is set
3304 */
3305 OO.ui.mixin.FlaggedElement.prototype.hasFlag = function ( flag ) {
3306 // This may be called before the constructor, thus before this.flags is set
3307 return this.flags && ( flag in this.flags );
3308 };
3309
3310 /**
3311 * Get the names of all flags set.
3312 *
3313 * @return {string[]} Flag names
3314 */
3315 OO.ui.mixin.FlaggedElement.prototype.getFlags = function () {
3316 // This may be called before the constructor, thus before this.flags is set
3317 return Object.keys( this.flags || {} );
3318 };
3319
3320 /**
3321 * Clear all flags.
3322 *
3323 * @chainable
3324 * @return {OO.ui.Element} The element, for chaining
3325 * @fires flag
3326 */
3327 OO.ui.mixin.FlaggedElement.prototype.clearFlags = function () {
3328 var flag, className,
3329 changes = {},
3330 remove = [],
3331 classPrefix = 'oo-ui-flaggedElement-';
3332
3333 for ( flag in this.flags ) {
3334 className = classPrefix + flag;
3335 changes[ flag ] = false;
3336 delete this.flags[ flag ];
3337 remove.push( className );
3338 }
3339
3340 if ( this.$flagged ) {
3341 this.$flagged.removeClass( remove );
3342 }
3343
3344 this.updateThemeClasses();
3345 this.emit( 'flag', changes );
3346
3347 return this;
3348 };
3349
3350 /**
3351 * Add one or more flags.
3352 *
3353 * @param {string|string[]|Object.<string, boolean>} flags A flag name, an array of flag names,
3354 * or an object keyed by flag name with a boolean value that indicates whether the flag should
3355 * be added (`true`) or removed (`false`).
3356 * @chainable
3357 * @return {OO.ui.Element} The element, for chaining
3358 * @fires flag
3359 */
3360 OO.ui.mixin.FlaggedElement.prototype.setFlags = function ( flags ) {
3361 var i, len, flag, className,
3362 changes = {},
3363 add = [],
3364 remove = [],
3365 classPrefix = 'oo-ui-flaggedElement-';
3366
3367 if ( typeof flags === 'string' ) {
3368 className = classPrefix + flags;
3369 // Set
3370 if ( !this.flags[ flags ] ) {
3371 this.flags[ flags ] = true;
3372 add.push( className );
3373 }
3374 } else if ( Array.isArray( flags ) ) {
3375 for ( i = 0, len = flags.length; i < len; i++ ) {
3376 flag = flags[ i ];
3377 className = classPrefix + flag;
3378 // Set
3379 if ( !this.flags[ flag ] ) {
3380 changes[ flag ] = true;
3381 this.flags[ flag ] = true;
3382 add.push( className );
3383 }
3384 }
3385 } else if ( OO.isPlainObject( flags ) ) {
3386 for ( flag in flags ) {
3387 className = classPrefix + flag;
3388 if ( flags[ flag ] ) {
3389 // Set
3390 if ( !this.flags[ flag ] ) {
3391 changes[ flag ] = true;
3392 this.flags[ flag ] = true;
3393 add.push( className );
3394 }
3395 } else {
3396 // Remove
3397 if ( this.flags[ flag ] ) {
3398 changes[ flag ] = false;
3399 delete this.flags[ flag ];
3400 remove.push( className );
3401 }
3402 }
3403 }
3404 }
3405
3406 if ( this.$flagged ) {
3407 this.$flagged
3408 .addClass( add )
3409 .removeClass( remove );
3410 }
3411
3412 this.updateThemeClasses();
3413 this.emit( 'flag', changes );
3414
3415 return this;
3416 };
3417
3418 /**
3419 * TitledElement is mixed into other classes to provide a `title` attribute.
3420 * Titles are rendered by the browser and are made visible when the user moves
3421 * the mouse over the element. Titles are not visible on touch devices.
3422 *
3423 * @example
3424 * // TitledElement provides a 'title' attribute to the
3425 * // ButtonWidget class
3426 * var button = new OO.ui.ButtonWidget( {
3427 * label: 'Button with Title',
3428 * title: 'I am a button'
3429 * } );
3430 * $( 'body' ).append( button.$element );
3431 *
3432 * @abstract
3433 * @class
3434 *
3435 * @constructor
3436 * @param {Object} [config] Configuration options
3437 * @cfg {jQuery} [$titled] The element to which the `title` attribute is applied.
3438 * If this config is omitted, the title functionality is applied to $element, the
3439 * element created by the class.
3440 * @cfg {string|Function} [title] The title text or a function that returns text. If
3441 * this config is omitted, the value of the {@link #static-title static title} property is used.
3442 */
3443 OO.ui.mixin.TitledElement = function OoUiMixinTitledElement( config ) {
3444 // Configuration initialization
3445 config = config || {};
3446
3447 // Properties
3448 this.$titled = null;
3449 this.title = null;
3450
3451 // Initialization
3452 this.setTitle( config.title !== undefined ? config.title : this.constructor.static.title );
3453 this.setTitledElement( config.$titled || this.$element );
3454 };
3455
3456 /* Setup */
3457
3458 OO.initClass( OO.ui.mixin.TitledElement );
3459
3460 /* Static Properties */
3461
3462 /**
3463 * The title text, a function that returns text, or `null` for no title. The value of the static property
3464 * is overridden if the #title config option is used.
3465 *
3466 * @static
3467 * @inheritable
3468 * @property {string|Function|null}
3469 */
3470 OO.ui.mixin.TitledElement.static.title = null;
3471
3472 /* Methods */
3473
3474 /**
3475 * Set the titled element.
3476 *
3477 * This method is used to retarget a TitledElement mixin so that its functionality applies to the specified element.
3478 * If an element is already set, the mixin’s effect on that element is removed before the new element is set up.
3479 *
3480 * @param {jQuery} $titled Element that should use the 'titled' functionality
3481 */
3482 OO.ui.mixin.TitledElement.prototype.setTitledElement = function ( $titled ) {
3483 if ( this.$titled ) {
3484 this.$titled.removeAttr( 'title' );
3485 }
3486
3487 this.$titled = $titled;
3488 if ( this.title ) {
3489 this.updateTitle();
3490 }
3491 };
3492
3493 /**
3494 * Set title.
3495 *
3496 * @param {string|Function|null} title Title text, a function that returns text, or `null` for no title
3497 * @chainable
3498 * @return {OO.ui.Element} The element, for chaining
3499 */
3500 OO.ui.mixin.TitledElement.prototype.setTitle = function ( title ) {
3501 title = typeof title === 'function' ? OO.ui.resolveMsg( title ) : title;
3502 title = ( typeof title === 'string' && title.length ) ? title : null;
3503
3504 if ( this.title !== title ) {
3505 this.title = title;
3506 this.updateTitle();
3507 }
3508
3509 return this;
3510 };
3511
3512 /**
3513 * Update the title attribute, in case of changes to title or accessKey.
3514 *
3515 * @protected
3516 * @chainable
3517 * @return {OO.ui.Element} The element, for chaining
3518 */
3519 OO.ui.mixin.TitledElement.prototype.updateTitle = function () {
3520 var title = this.getTitle();
3521 if ( this.$titled ) {
3522 if ( title !== null ) {
3523 // Only if this is an AccessKeyedElement
3524 if ( this.formatTitleWithAccessKey ) {
3525 title = this.formatTitleWithAccessKey( title );
3526 }
3527 this.$titled.attr( 'title', title );
3528 } else {
3529 this.$titled.removeAttr( 'title' );
3530 }
3531 }
3532 return this;
3533 };
3534
3535 /**
3536 * Get title.
3537 *
3538 * @return {string} Title string
3539 */
3540 OO.ui.mixin.TitledElement.prototype.getTitle = function () {
3541 return this.title;
3542 };
3543
3544 /**
3545 * AccessKeyedElement is mixed into other classes to provide an `accesskey` attribute.
3546 * Accesskeys allow an user to go to a specific element by using
3547 * a shortcut combination of a browser specific keys + the key
3548 * set to the field.
3549 *
3550 * @example
3551 * // AccessKeyedElement provides an 'accesskey' attribute to the
3552 * // ButtonWidget class
3553 * var button = new OO.ui.ButtonWidget( {
3554 * label: 'Button with Accesskey',
3555 * accessKey: 'k'
3556 * } );
3557 * $( 'body' ).append( button.$element );
3558 *
3559 * @abstract
3560 * @class
3561 *
3562 * @constructor
3563 * @param {Object} [config] Configuration options
3564 * @cfg {jQuery} [$accessKeyed] The element to which the `accesskey` attribute is applied.
3565 * If this config is omitted, the accesskey functionality is applied to $element, the
3566 * element created by the class.
3567 * @cfg {string|Function} [accessKey] The key or a function that returns the key. If
3568 * this config is omitted, no accesskey will be added.
3569 */
3570 OO.ui.mixin.AccessKeyedElement = function OoUiMixinAccessKeyedElement( config ) {
3571 // Configuration initialization
3572 config = config || {};
3573
3574 // Properties
3575 this.$accessKeyed = null;
3576 this.accessKey = null;
3577
3578 // Initialization
3579 this.setAccessKey( config.accessKey || null );
3580 this.setAccessKeyedElement( config.$accessKeyed || this.$element );
3581
3582 // If this is also a TitledElement and it initialized before we did, we may have
3583 // to update the title with the access key
3584 if ( this.updateTitle ) {
3585 this.updateTitle();
3586 }
3587 };
3588
3589 /* Setup */
3590
3591 OO.initClass( OO.ui.mixin.AccessKeyedElement );
3592
3593 /* Static Properties */
3594
3595 /**
3596 * The access key, a function that returns a key, or `null` for no accesskey.
3597 *
3598 * @static
3599 * @inheritable
3600 * @property {string|Function|null}
3601 */
3602 OO.ui.mixin.AccessKeyedElement.static.accessKey = null;
3603
3604 /* Methods */
3605
3606 /**
3607 * Set the accesskeyed element.
3608 *
3609 * This method is used to retarget a AccessKeyedElement mixin so that its functionality applies to the specified element.
3610 * If an element is already set, the mixin's effect on that element is removed before the new element is set up.
3611 *
3612 * @param {jQuery} $accessKeyed Element that should use the 'accesskeyed' functionality
3613 */
3614 OO.ui.mixin.AccessKeyedElement.prototype.setAccessKeyedElement = function ( $accessKeyed ) {
3615 if ( this.$accessKeyed ) {
3616 this.$accessKeyed.removeAttr( 'accesskey' );
3617 }
3618
3619 this.$accessKeyed = $accessKeyed;
3620 if ( this.accessKey ) {
3621 this.$accessKeyed.attr( 'accesskey', this.accessKey );
3622 }
3623 };
3624
3625 /**
3626 * Set accesskey.
3627 *
3628 * @param {string|Function|null} accessKey Key, a function that returns a key, or `null` for no accesskey
3629 * @chainable
3630 * @return {OO.ui.Element} The element, for chaining
3631 */
3632 OO.ui.mixin.AccessKeyedElement.prototype.setAccessKey = function ( accessKey ) {
3633 accessKey = typeof accessKey === 'string' ? OO.ui.resolveMsg( accessKey ) : null;
3634
3635 if ( this.accessKey !== accessKey ) {
3636 if ( this.$accessKeyed ) {
3637 if ( accessKey !== null ) {
3638 this.$accessKeyed.attr( 'accesskey', accessKey );
3639 } else {
3640 this.$accessKeyed.removeAttr( 'accesskey' );
3641 }
3642 }
3643 this.accessKey = accessKey;
3644
3645 // Only if this is a TitledElement
3646 if ( this.updateTitle ) {
3647 this.updateTitle();
3648 }
3649 }
3650
3651 return this;
3652 };
3653
3654 /**
3655 * Get accesskey.
3656 *
3657 * @return {string} accessKey string
3658 */
3659 OO.ui.mixin.AccessKeyedElement.prototype.getAccessKey = function () {
3660 return this.accessKey;
3661 };
3662
3663 /**
3664 * Add information about the access key to the element's tooltip label.
3665 * (This is only public for hacky usage in FieldLayout.)
3666 *
3667 * @param {string} title Tooltip label for `title` attribute
3668 * @return {string}
3669 */
3670 OO.ui.mixin.AccessKeyedElement.prototype.formatTitleWithAccessKey = function ( title ) {
3671 var accessKey;
3672
3673 if ( !this.$accessKeyed ) {
3674 // Not initialized yet; the constructor will call updateTitle() which will rerun this function
3675 return title;
3676 }
3677 // Use jquery.accessKeyLabel if available to show modifiers, otherwise just display the single key
3678 if ( $.fn.updateTooltipAccessKeys && $.fn.updateTooltipAccessKeys.getAccessKeyLabel ) {
3679 accessKey = $.fn.updateTooltipAccessKeys.getAccessKeyLabel( this.$accessKeyed[ 0 ] );
3680 } else {
3681 accessKey = this.getAccessKey();
3682 }
3683 if ( accessKey ) {
3684 title += ' [' + accessKey + ']';
3685 }
3686 return title;
3687 };
3688
3689 /**
3690 * ButtonWidget is a generic widget for buttons. A wide variety of looks,
3691 * feels, and functionality can be customized via the class’s configuration options
3692 * and methods. Please see the [OOUI documentation on MediaWiki] [1] for more information
3693 * and examples.
3694 *
3695 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Buttons_and_Switches
3696 *
3697 * @example
3698 * // A button widget
3699 * var button = new OO.ui.ButtonWidget( {
3700 * label: 'Button with Icon',
3701 * icon: 'trash',
3702 * title: 'Remove'
3703 * } );
3704 * $( 'body' ).append( button.$element );
3705 *
3706 * NOTE: HTML form buttons should use the OO.ui.ButtonInputWidget class.
3707 *
3708 * @class
3709 * @extends OO.ui.Widget
3710 * @mixins OO.ui.mixin.ButtonElement
3711 * @mixins OO.ui.mixin.IconElement
3712 * @mixins OO.ui.mixin.IndicatorElement
3713 * @mixins OO.ui.mixin.LabelElement
3714 * @mixins OO.ui.mixin.TitledElement
3715 * @mixins OO.ui.mixin.FlaggedElement
3716 * @mixins OO.ui.mixin.TabIndexedElement
3717 * @mixins OO.ui.mixin.AccessKeyedElement
3718 *
3719 * @constructor
3720 * @param {Object} [config] Configuration options
3721 * @cfg {boolean} [active=false] Whether button should be shown as active
3722 * @cfg {string} [href] Hyperlink to visit when the button is clicked.
3723 * @cfg {string} [target] The frame or window in which to open the hyperlink.
3724 * @cfg {boolean} [noFollow] Search engine traversal hint (default: true)
3725 */
3726 OO.ui.ButtonWidget = function OoUiButtonWidget( config ) {
3727 // Configuration initialization
3728 config = config || {};
3729
3730 // Parent constructor
3731 OO.ui.ButtonWidget.parent.call( this, config );
3732
3733 // Mixin constructors
3734 OO.ui.mixin.ButtonElement.call( this, config );
3735 OO.ui.mixin.IconElement.call( this, config );
3736 OO.ui.mixin.IndicatorElement.call( this, config );
3737 OO.ui.mixin.LabelElement.call( this, config );
3738 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$button } ) );
3739 OO.ui.mixin.FlaggedElement.call( this, config );
3740 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$button } ) );
3741 OO.ui.mixin.AccessKeyedElement.call( this, $.extend( {}, config, { $accessKeyed: this.$button } ) );
3742
3743 // Properties
3744 this.href = null;
3745 this.target = null;
3746 this.noFollow = false;
3747
3748 // Events
3749 this.connect( this, { disable: 'onDisable' } );
3750
3751 // Initialization
3752 this.$button.append( this.$icon, this.$label, this.$indicator );
3753 this.$element
3754 .addClass( 'oo-ui-buttonWidget' )
3755 .append( this.$button );
3756 this.setActive( config.active );
3757 this.setHref( config.href );
3758 this.setTarget( config.target );
3759 this.setNoFollow( config.noFollow );
3760 };
3761
3762 /* Setup */
3763
3764 OO.inheritClass( OO.ui.ButtonWidget, OO.ui.Widget );
3765 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.ButtonElement );
3766 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.IconElement );
3767 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.IndicatorElement );
3768 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.LabelElement );
3769 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.TitledElement );
3770 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.FlaggedElement );
3771 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.TabIndexedElement );
3772 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.AccessKeyedElement );
3773
3774 /* Static Properties */
3775
3776 /**
3777 * @static
3778 * @inheritdoc
3779 */
3780 OO.ui.ButtonWidget.static.cancelButtonMouseDownEvents = false;
3781
3782 /**
3783 * @static
3784 * @inheritdoc
3785 */
3786 OO.ui.ButtonWidget.static.tagName = 'span';
3787
3788 /* Methods */
3789
3790 /**
3791 * Get hyperlink location.
3792 *
3793 * @return {string} Hyperlink location
3794 */
3795 OO.ui.ButtonWidget.prototype.getHref = function () {
3796 return this.href;
3797 };
3798
3799 /**
3800 * Get hyperlink target.
3801 *
3802 * @return {string} Hyperlink target
3803 */
3804 OO.ui.ButtonWidget.prototype.getTarget = function () {
3805 return this.target;
3806 };
3807
3808 /**
3809 * Get search engine traversal hint.
3810 *
3811 * @return {boolean} Whether search engines should avoid traversing this hyperlink
3812 */
3813 OO.ui.ButtonWidget.prototype.getNoFollow = function () {
3814 return this.noFollow;
3815 };
3816
3817 /**
3818 * Set hyperlink location.
3819 *
3820 * @param {string|null} href Hyperlink location, null to remove
3821 * @chainable
3822 * @return {OO.ui.Widget} The widget, for chaining
3823 */
3824 OO.ui.ButtonWidget.prototype.setHref = function ( href ) {
3825 href = typeof href === 'string' ? href : null;
3826 if ( href !== null && !OO.ui.isSafeUrl( href ) ) {
3827 href = './' + href;
3828 }
3829
3830 if ( href !== this.href ) {
3831 this.href = href;
3832 this.updateHref();
3833 }
3834
3835 return this;
3836 };
3837
3838 /**
3839 * Update the `href` attribute, in case of changes to href or
3840 * disabled state.
3841 *
3842 * @private
3843 * @chainable
3844 * @return {OO.ui.Widget} The widget, for chaining
3845 */
3846 OO.ui.ButtonWidget.prototype.updateHref = function () {
3847 if ( this.href !== null && !this.isDisabled() ) {
3848 this.$button.attr( 'href', this.href );
3849 } else {
3850 this.$button.removeAttr( 'href' );
3851 }
3852
3853 return this;
3854 };
3855
3856 /**
3857 * Handle disable events.
3858 *
3859 * @private
3860 * @param {boolean} disabled Element is disabled
3861 */
3862 OO.ui.ButtonWidget.prototype.onDisable = function () {
3863 this.updateHref();
3864 };
3865
3866 /**
3867 * Set hyperlink target.
3868 *
3869 * @param {string|null} target Hyperlink target, null to remove
3870 * @return {OO.ui.Widget} The widget, for chaining
3871 */
3872 OO.ui.ButtonWidget.prototype.setTarget = function ( target ) {
3873 target = typeof target === 'string' ? target : null;
3874
3875 if ( target !== this.target ) {
3876 this.target = target;
3877 if ( target !== null ) {
3878 this.$button.attr( 'target', target );
3879 } else {
3880 this.$button.removeAttr( 'target' );
3881 }
3882 }
3883
3884 return this;
3885 };
3886
3887 /**
3888 * Set search engine traversal hint.
3889 *
3890 * @param {boolean} noFollow True if search engines should avoid traversing this hyperlink
3891 * @return {OO.ui.Widget} The widget, for chaining
3892 */
3893 OO.ui.ButtonWidget.prototype.setNoFollow = function ( noFollow ) {
3894 noFollow = typeof noFollow === 'boolean' ? noFollow : true;
3895
3896 if ( noFollow !== this.noFollow ) {
3897 this.noFollow = noFollow;
3898 if ( noFollow ) {
3899 this.$button.attr( 'rel', 'nofollow' );
3900 } else {
3901 this.$button.removeAttr( 'rel' );
3902 }
3903 }
3904
3905 return this;
3906 };
3907
3908 // Override method visibility hints from ButtonElement
3909 /**
3910 * @method setActive
3911 * @inheritdoc
3912 */
3913 /**
3914 * @method isActive
3915 * @inheritdoc
3916 */
3917
3918 /**
3919 * A ButtonGroupWidget groups related buttons and is used together with OO.ui.ButtonWidget and
3920 * its subclasses. Each button in a group is addressed by a unique reference. Buttons can be added,
3921 * removed, and cleared from the group.
3922 *
3923 * @example
3924 * // Example: A ButtonGroupWidget with two buttons
3925 * var button1 = new OO.ui.PopupButtonWidget( {
3926 * label: 'Select a category',
3927 * icon: 'menu',
3928 * popup: {
3929 * $content: $( '<p>List of categories...</p>' ),
3930 * padded: true,
3931 * align: 'left'
3932 * }
3933 * } );
3934 * var button2 = new OO.ui.ButtonWidget( {
3935 * label: 'Add item'
3936 * });
3937 * var buttonGroup = new OO.ui.ButtonGroupWidget( {
3938 * items: [button1, button2]
3939 * } );
3940 * $( 'body' ).append( buttonGroup.$element );
3941 *
3942 * @class
3943 * @extends OO.ui.Widget
3944 * @mixins OO.ui.mixin.GroupElement
3945 *
3946 * @constructor
3947 * @param {Object} [config] Configuration options
3948 * @cfg {OO.ui.ButtonWidget[]} [items] Buttons to add
3949 */
3950 OO.ui.ButtonGroupWidget = function OoUiButtonGroupWidget( config ) {
3951 // Configuration initialization
3952 config = config || {};
3953
3954 // Parent constructor
3955 OO.ui.ButtonGroupWidget.parent.call( this, config );
3956
3957 // Mixin constructors
3958 OO.ui.mixin.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) );
3959
3960 // Initialization
3961 this.$element.addClass( 'oo-ui-buttonGroupWidget' );
3962 if ( Array.isArray( config.items ) ) {
3963 this.addItems( config.items );
3964 }
3965 };
3966
3967 /* Setup */
3968
3969 OO.inheritClass( OO.ui.ButtonGroupWidget, OO.ui.Widget );
3970 OO.mixinClass( OO.ui.ButtonGroupWidget, OO.ui.mixin.GroupElement );
3971
3972 /* Static Properties */
3973
3974 /**
3975 * @static
3976 * @inheritdoc
3977 */
3978 OO.ui.ButtonGroupWidget.static.tagName = 'span';
3979
3980 /* Methods */
3981
3982 /**
3983 * Focus the widget
3984 *
3985 * @chainable
3986 * @return {OO.ui.Widget} The widget, for chaining
3987 */
3988 OO.ui.ButtonGroupWidget.prototype.focus = function () {
3989 if ( !this.isDisabled() ) {
3990 if ( this.items[ 0 ] ) {
3991 this.items[ 0 ].focus();
3992 }
3993 }
3994 return this;
3995 };
3996
3997 /**
3998 * @inheritdoc
3999 */
4000 OO.ui.ButtonGroupWidget.prototype.simulateLabelClick = function () {
4001 this.focus();
4002 };
4003
4004 /**
4005 * IconWidget is a generic widget for {@link OO.ui.mixin.IconElement icons}. In general, IconWidgets should be used with OO.ui.LabelWidget,
4006 * which creates a label that identifies the icon’s function. See the [OOUI documentation on MediaWiki] [1]
4007 * for a list of icons included in the library.
4008 *
4009 * @example
4010 * // An icon widget with a label
4011 * var myIcon = new OO.ui.IconWidget( {
4012 * icon: 'help',
4013 * title: 'Help'
4014 * } );
4015 * // Create a label.
4016 * var iconLabel = new OO.ui.LabelWidget( {
4017 * label: 'Help'
4018 * } );
4019 * $( 'body' ).append( myIcon.$element, iconLabel.$element );
4020 *
4021 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Icons,_Indicators,_and_Labels#Icons
4022 *
4023 * @class
4024 * @extends OO.ui.Widget
4025 * @mixins OO.ui.mixin.IconElement
4026 * @mixins OO.ui.mixin.TitledElement
4027 * @mixins OO.ui.mixin.LabelElement
4028 * @mixins OO.ui.mixin.FlaggedElement
4029 *
4030 * @constructor
4031 * @param {Object} [config] Configuration options
4032 */
4033 OO.ui.IconWidget = function OoUiIconWidget( config ) {
4034 // Configuration initialization
4035 config = config || {};
4036
4037 // Parent constructor
4038 OO.ui.IconWidget.parent.call( this, config );
4039
4040 // Mixin constructors
4041 OO.ui.mixin.IconElement.call( this, $.extend( {}, config, { $icon: this.$element } ) );
4042 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$element } ) );
4043 OO.ui.mixin.LabelElement.call( this, $.extend( {}, config, { $label: this.$element, invisibleLabel: true } ) );
4044 OO.ui.mixin.FlaggedElement.call( this, $.extend( {}, config, { $flagged: this.$element } ) );
4045
4046 // Initialization
4047 this.$element.addClass( 'oo-ui-iconWidget' );
4048 // Remove class added by LabelElement initialization. It causes unexpected CSS to apply when
4049 // nested in other widgets, because this widget used to not mix in LabelElement.
4050 this.$element.removeClass( 'oo-ui-labelElement-label' );
4051 };
4052
4053 /* Setup */
4054
4055 OO.inheritClass( OO.ui.IconWidget, OO.ui.Widget );
4056 OO.mixinClass( OO.ui.IconWidget, OO.ui.mixin.IconElement );
4057 OO.mixinClass( OO.ui.IconWidget, OO.ui.mixin.TitledElement );
4058 OO.mixinClass( OO.ui.IconWidget, OO.ui.mixin.LabelElement );
4059 OO.mixinClass( OO.ui.IconWidget, OO.ui.mixin.FlaggedElement );
4060
4061 /* Static Properties */
4062
4063 /**
4064 * @static
4065 * @inheritdoc
4066 */
4067 OO.ui.IconWidget.static.tagName = 'span';
4068
4069 /**
4070 * IndicatorWidgets create indicators, which are small graphics that are generally used to draw
4071 * attention to the status of an item or to clarify the function within a control. For a list of
4072 * indicators included in the library, please see the [OOUI documentation on MediaWiki][1].
4073 *
4074 * @example
4075 * // Example of an indicator widget
4076 * var indicator1 = new OO.ui.IndicatorWidget( {
4077 * indicator: 'required'
4078 * } );
4079 *
4080 * // Create a fieldset layout to add a label
4081 * var fieldset = new OO.ui.FieldsetLayout();
4082 * fieldset.addItems( [
4083 * new OO.ui.FieldLayout( indicator1, { label: 'A required indicator:' } )
4084 * ] );
4085 * $( 'body' ).append( fieldset.$element );
4086 *
4087 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Icons,_Indicators,_and_Labels#Indicators
4088 *
4089 * @class
4090 * @extends OO.ui.Widget
4091 * @mixins OO.ui.mixin.IndicatorElement
4092 * @mixins OO.ui.mixin.TitledElement
4093 * @mixins OO.ui.mixin.LabelElement
4094 *
4095 * @constructor
4096 * @param {Object} [config] Configuration options
4097 */
4098 OO.ui.IndicatorWidget = function OoUiIndicatorWidget( config ) {
4099 // Configuration initialization
4100 config = config || {};
4101
4102 // Parent constructor
4103 OO.ui.IndicatorWidget.parent.call( this, config );
4104
4105 // Mixin constructors
4106 OO.ui.mixin.IndicatorElement.call( this, $.extend( {}, config, { $indicator: this.$element } ) );
4107 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$element } ) );
4108 OO.ui.mixin.LabelElement.call( this, $.extend( {}, config, { $label: this.$element, invisibleLabel: true } ) );
4109
4110 // Initialization
4111 this.$element.addClass( 'oo-ui-indicatorWidget' );
4112 // Remove class added by LabelElement initialization. It causes unexpected CSS to apply when
4113 // nested in other widgets, because this widget used to not mix in LabelElement.
4114 this.$element.removeClass( 'oo-ui-labelElement-label' );
4115 };
4116
4117 /* Setup */
4118
4119 OO.inheritClass( OO.ui.IndicatorWidget, OO.ui.Widget );
4120 OO.mixinClass( OO.ui.IndicatorWidget, OO.ui.mixin.IndicatorElement );
4121 OO.mixinClass( OO.ui.IndicatorWidget, OO.ui.mixin.TitledElement );
4122 OO.mixinClass( OO.ui.IndicatorWidget, OO.ui.mixin.LabelElement );
4123
4124 /* Static Properties */
4125
4126 /**
4127 * @static
4128 * @inheritdoc
4129 */
4130 OO.ui.IndicatorWidget.static.tagName = 'span';
4131
4132 /**
4133 * LabelWidgets help identify the function of interface elements. Each LabelWidget can
4134 * be configured with a `label` option that is set to a string, a label node, or a function:
4135 *
4136 * - String: a plaintext string
4137 * - jQuery selection: a jQuery selection, used for anything other than a plaintext label, e.g., a
4138 * label that includes a link or special styling, such as a gray color or additional graphical elements.
4139 * - Function: a function that will produce a string in the future. Functions are used
4140 * in cases where the value of the label is not currently defined.
4141 *
4142 * In addition, the LabelWidget can be associated with an {@link OO.ui.InputWidget input widget}, which
4143 * will come into focus when the label is clicked.
4144 *
4145 * @example
4146 * // Examples of LabelWidgets
4147 * var label1 = new OO.ui.LabelWidget( {
4148 * label: 'plaintext label'
4149 * } );
4150 * var label2 = new OO.ui.LabelWidget( {
4151 * label: $( '<a href="default.html">jQuery label</a>' )
4152 * } );
4153 * // Create a fieldset layout with fields for each example
4154 * var fieldset = new OO.ui.FieldsetLayout();
4155 * fieldset.addItems( [
4156 * new OO.ui.FieldLayout( label1 ),
4157 * new OO.ui.FieldLayout( label2 )
4158 * ] );
4159 * $( 'body' ).append( fieldset.$element );
4160 *
4161 * @class
4162 * @extends OO.ui.Widget
4163 * @mixins OO.ui.mixin.LabelElement
4164 * @mixins OO.ui.mixin.TitledElement
4165 *
4166 * @constructor
4167 * @param {Object} [config] Configuration options
4168 * @cfg {OO.ui.InputWidget} [input] {@link OO.ui.InputWidget Input widget} that uses the label.
4169 * Clicking the label will focus the specified input field.
4170 */
4171 OO.ui.LabelWidget = function OoUiLabelWidget( config ) {
4172 // Configuration initialization
4173 config = config || {};
4174
4175 // Parent constructor
4176 OO.ui.LabelWidget.parent.call( this, config );
4177
4178 // Mixin constructors
4179 OO.ui.mixin.LabelElement.call( this, $.extend( {}, config, { $label: this.$element } ) );
4180 OO.ui.mixin.TitledElement.call( this, config );
4181
4182 // Properties
4183 this.input = config.input;
4184
4185 // Initialization
4186 if ( this.input ) {
4187 if ( this.input.getInputId() ) {
4188 this.$element.attr( 'for', this.input.getInputId() );
4189 } else {
4190 this.$label.on( 'click', function () {
4191 this.input.simulateLabelClick();
4192 }.bind( this ) );
4193 }
4194 }
4195 this.$element.addClass( 'oo-ui-labelWidget' );
4196 };
4197
4198 /* Setup */
4199
4200 OO.inheritClass( OO.ui.LabelWidget, OO.ui.Widget );
4201 OO.mixinClass( OO.ui.LabelWidget, OO.ui.mixin.LabelElement );
4202 OO.mixinClass( OO.ui.LabelWidget, OO.ui.mixin.TitledElement );
4203
4204 /* Static Properties */
4205
4206 /**
4207 * @static
4208 * @inheritdoc
4209 */
4210 OO.ui.LabelWidget.static.tagName = 'label';
4211
4212 /**
4213 * PendingElement is a mixin that is used to create elements that notify users that something is happening
4214 * and that they should wait before proceeding. The pending state is visually represented with a pending
4215 * texture that appears in the head of a pending {@link OO.ui.ProcessDialog process dialog} or in the input
4216 * field of a {@link OO.ui.TextInputWidget text input widget}.
4217 *
4218 * Currently, {@link OO.ui.ActionWidget Action widgets}, which mix in this class, can also be marked as pending, but only when
4219 * used in {@link OO.ui.MessageDialog message dialogs}. The behavior is not currently supported for action widgets used
4220 * in process dialogs.
4221 *
4222 * @example
4223 * function MessageDialog( config ) {
4224 * MessageDialog.parent.call( this, config );
4225 * }
4226 * OO.inheritClass( MessageDialog, OO.ui.MessageDialog );
4227 *
4228 * MessageDialog.static.name = 'myMessageDialog';
4229 * MessageDialog.static.actions = [
4230 * { action: 'save', label: 'Done', flags: 'primary' },
4231 * { label: 'Cancel', flags: 'safe' }
4232 * ];
4233 *
4234 * MessageDialog.prototype.initialize = function () {
4235 * MessageDialog.parent.prototype.initialize.apply( this, arguments );
4236 * this.content = new OO.ui.PanelLayout( { padded: true } );
4237 * this.content.$element.append( '<p>Click the \'Done\' action widget to see its pending state. Note that action widgets can be marked pending in message dialogs but not process dialogs.</p>' );
4238 * this.$body.append( this.content.$element );
4239 * };
4240 * MessageDialog.prototype.getBodyHeight = function () {
4241 * return 100;
4242 * }
4243 * MessageDialog.prototype.getActionProcess = function ( action ) {
4244 * var dialog = this;
4245 * if ( action === 'save' ) {
4246 * dialog.getActions().get({actions: 'save'})[0].pushPending();
4247 * return new OO.ui.Process()
4248 * .next( 1000 )
4249 * .next( function () {
4250 * dialog.getActions().get({actions: 'save'})[0].popPending();
4251 * } );
4252 * }
4253 * return MessageDialog.parent.prototype.getActionProcess.call( this, action );
4254 * };
4255 *
4256 * var windowManager = new OO.ui.WindowManager();
4257 * $( 'body' ).append( windowManager.$element );
4258 *
4259 * var dialog = new MessageDialog();
4260 * windowManager.addWindows( [ dialog ] );
4261 * windowManager.openWindow( dialog );
4262 *
4263 * @abstract
4264 * @class
4265 *
4266 * @constructor
4267 * @param {Object} [config] Configuration options
4268 * @cfg {jQuery} [$pending] Element to mark as pending, defaults to this.$element
4269 */
4270 OO.ui.mixin.PendingElement = function OoUiMixinPendingElement( config ) {
4271 // Configuration initialization
4272 config = config || {};
4273
4274 // Properties
4275 this.pending = 0;
4276 this.$pending = null;
4277
4278 // Initialisation
4279 this.setPendingElement( config.$pending || this.$element );
4280 };
4281
4282 /* Setup */
4283
4284 OO.initClass( OO.ui.mixin.PendingElement );
4285
4286 /* Methods */
4287
4288 /**
4289 * Set the pending element (and clean up any existing one).
4290 *
4291 * @param {jQuery} $pending The element to set to pending.
4292 */
4293 OO.ui.mixin.PendingElement.prototype.setPendingElement = function ( $pending ) {
4294 if ( this.$pending ) {
4295 this.$pending.removeClass( 'oo-ui-pendingElement-pending' );
4296 }
4297
4298 this.$pending = $pending;
4299 if ( this.pending > 0 ) {
4300 this.$pending.addClass( 'oo-ui-pendingElement-pending' );
4301 }
4302 };
4303
4304 /**
4305 * Check if an element is pending.
4306 *
4307 * @return {boolean} Element is pending
4308 */
4309 OO.ui.mixin.PendingElement.prototype.isPending = function () {
4310 return !!this.pending;
4311 };
4312
4313 /**
4314 * Increase the pending counter. The pending state will remain active until the counter is zero
4315 * (i.e., the number of calls to #pushPending and #popPending is the same).
4316 *
4317 * @chainable
4318 * @return {OO.ui.Element} The element, for chaining
4319 */
4320 OO.ui.mixin.PendingElement.prototype.pushPending = function () {
4321 if ( this.pending === 0 ) {
4322 this.$pending.addClass( 'oo-ui-pendingElement-pending' );
4323 this.updateThemeClasses();
4324 }
4325 this.pending++;
4326
4327 return this;
4328 };
4329
4330 /**
4331 * Decrease the pending counter. The pending state will remain active until the counter is zero
4332 * (i.e., the number of calls to #pushPending and #popPending is the same).
4333 *
4334 * @chainable
4335 * @return {OO.ui.Element} The element, for chaining
4336 */
4337 OO.ui.mixin.PendingElement.prototype.popPending = function () {
4338 if ( this.pending === 1 ) {
4339 this.$pending.removeClass( 'oo-ui-pendingElement-pending' );
4340 this.updateThemeClasses();
4341 }
4342 this.pending = Math.max( 0, this.pending - 1 );
4343
4344 return this;
4345 };
4346
4347 /**
4348 * Element that will stick adjacent to a specified container, even when it is inserted elsewhere
4349 * in the document (for example, in an OO.ui.Window's $overlay).
4350 *
4351 * The elements's position is automatically calculated and maintained when window is resized or the
4352 * page is scrolled. If you reposition the container manually, you have to call #position to make
4353 * sure the element is still placed correctly.
4354 *
4355 * As positioning is only possible when both the element and the container are attached to the DOM
4356 * and visible, it's only done after you call #togglePositioning. You might want to do this inside
4357 * the #toggle method to display a floating popup, for example.
4358 *
4359 * @abstract
4360 * @class
4361 *
4362 * @constructor
4363 * @param {Object} [config] Configuration options
4364 * @cfg {jQuery} [$floatable] Node to position, assigned to #$floatable, omit to use #$element
4365 * @cfg {jQuery} [$floatableContainer] Node to position adjacent to
4366 * @cfg {string} [verticalPosition='below'] Where to position $floatable vertically:
4367 * 'below': Directly below $floatableContainer, aligning f's top edge with fC's bottom edge
4368 * 'above': Directly above $floatableContainer, aligning f's bottom edge with fC's top edge
4369 * 'top': Align the top edge with $floatableContainer's top edge
4370 * 'bottom': Align the bottom edge with $floatableContainer's bottom edge
4371 * 'center': Vertically align the center with $floatableContainer's center
4372 * @cfg {string} [horizontalPosition='start'] Where to position $floatable horizontally:
4373 * 'before': Directly before $floatableContainer, aligning f's end edge with fC's start edge
4374 * 'after': Directly after $floatableContainer, aligning f's start edge with fC's end edge
4375 * 'start': Align the start (left in LTR, right in RTL) edge with $floatableContainer's start edge
4376 * 'end': Align the end (right in LTR, left in RTL) edge with $floatableContainer's end edge
4377 * 'center': Horizontally align the center with $floatableContainer's center
4378 * @cfg {boolean} [hideWhenOutOfView=true] Whether to hide the floatable element if the container
4379 * is out of view
4380 */
4381 OO.ui.mixin.FloatableElement = function OoUiMixinFloatableElement( config ) {
4382 // Configuration initialization
4383 config = config || {};
4384
4385 // Properties
4386 this.$floatable = null;
4387 this.$floatableContainer = null;
4388 this.$floatableWindow = null;
4389 this.$floatableClosestScrollable = null;
4390 this.floatableOutOfView = false;
4391 this.onFloatableScrollHandler = this.position.bind( this );
4392 this.onFloatableWindowResizeHandler = this.position.bind( this );
4393
4394 // Initialization
4395 this.setFloatableContainer( config.$floatableContainer );
4396 this.setFloatableElement( config.$floatable || this.$element );
4397 this.setVerticalPosition( config.verticalPosition || 'below' );
4398 this.setHorizontalPosition( config.horizontalPosition || 'start' );
4399 this.hideWhenOutOfView = config.hideWhenOutOfView === undefined ? true : !!config.hideWhenOutOfView;
4400 };
4401
4402 /* Methods */
4403
4404 /**
4405 * Set floatable element.
4406 *
4407 * If an element is already set, it will be cleaned up before setting up the new element.
4408 *
4409 * @param {jQuery} $floatable Element to make floatable
4410 */
4411 OO.ui.mixin.FloatableElement.prototype.setFloatableElement = function ( $floatable ) {
4412 if ( this.$floatable ) {
4413 this.$floatable.removeClass( 'oo-ui-floatableElement-floatable' );
4414 this.$floatable.css( { left: '', top: '' } );
4415 }
4416
4417 this.$floatable = $floatable.addClass( 'oo-ui-floatableElement-floatable' );
4418 this.position();
4419 };
4420
4421 /**
4422 * Set floatable container.
4423 *
4424 * The element will be positioned relative to the specified container.
4425 *
4426 * @param {jQuery|null} $floatableContainer Container to keep visible, or null to unset
4427 */
4428 OO.ui.mixin.FloatableElement.prototype.setFloatableContainer = function ( $floatableContainer ) {
4429 this.$floatableContainer = $floatableContainer;
4430 if ( this.$floatable ) {
4431 this.position();
4432 }
4433 };
4434
4435 /**
4436 * Change how the element is positioned vertically.
4437 *
4438 * @param {string} position 'below', 'above', 'top', 'bottom' or 'center'
4439 */
4440 OO.ui.mixin.FloatableElement.prototype.setVerticalPosition = function ( position ) {
4441 if ( [ 'below', 'above', 'top', 'bottom', 'center' ].indexOf( position ) === -1 ) {
4442 throw new Error( 'Invalid value for vertical position: ' + position );
4443 }
4444 if ( this.verticalPosition !== position ) {
4445 this.verticalPosition = position;
4446 if ( this.$floatable ) {
4447 this.position();
4448 }
4449 }
4450 };
4451
4452 /**
4453 * Change how the element is positioned horizontally.
4454 *
4455 * @param {string} position 'before', 'after', 'start', 'end' or 'center'
4456 */
4457 OO.ui.mixin.FloatableElement.prototype.setHorizontalPosition = function ( position ) {
4458 if ( [ 'before', 'after', 'start', 'end', 'center' ].indexOf( position ) === -1 ) {
4459 throw new Error( 'Invalid value for horizontal position: ' + position );
4460 }
4461 if ( this.horizontalPosition !== position ) {
4462 this.horizontalPosition = position;
4463 if ( this.$floatable ) {
4464 this.position();
4465 }
4466 }
4467 };
4468
4469 /**
4470 * Toggle positioning.
4471 *
4472 * Do not turn positioning on until after the element is attached to the DOM and visible.
4473 *
4474 * @param {boolean} [positioning] Enable positioning, omit to toggle
4475 * @chainable
4476 * @return {OO.ui.Element} The element, for chaining
4477 */
4478 OO.ui.mixin.FloatableElement.prototype.togglePositioning = function ( positioning ) {
4479 var closestScrollableOfContainer;
4480
4481 if ( !this.$floatable || !this.$floatableContainer ) {
4482 return this;
4483 }
4484
4485 positioning = positioning === undefined ? !this.positioning : !!positioning;
4486
4487 if ( positioning && !this.warnedUnattached && !this.isElementAttached() ) {
4488 OO.ui.warnDeprecation( 'FloatableElement#togglePositioning: Before calling this method, the element must be attached to the DOM.' );
4489 this.warnedUnattached = true;
4490 }
4491
4492 if ( this.positioning !== positioning ) {
4493 this.positioning = positioning;
4494
4495 closestScrollableOfContainer = OO.ui.Element.static.getClosestScrollableContainer( this.$floatableContainer[ 0 ] );
4496 // If the scrollable is the root, we have to listen to scroll events
4497 // on the window because of browser inconsistencies.
4498 if ( $( closestScrollableOfContainer ).is( 'html, body' ) ) {
4499 closestScrollableOfContainer = OO.ui.Element.static.getWindow( closestScrollableOfContainer );
4500 }
4501
4502 if ( positioning ) {
4503 this.$floatableWindow = $( this.getElementWindow() );
4504 this.$floatableWindow.on( 'resize', this.onFloatableWindowResizeHandler );
4505
4506 this.$floatableClosestScrollable = $( closestScrollableOfContainer );
4507 this.$floatableClosestScrollable.on( 'scroll', this.onFloatableScrollHandler );
4508
4509 // Initial position after visible
4510 this.position();
4511 } else {
4512 if ( this.$floatableWindow ) {
4513 this.$floatableWindow.off( 'resize', this.onFloatableWindowResizeHandler );
4514 this.$floatableWindow = null;
4515 }
4516
4517 if ( this.$floatableClosestScrollable ) {
4518 this.$floatableClosestScrollable.off( 'scroll', this.onFloatableScrollHandler );
4519 this.$floatableClosestScrollable = null;
4520 }
4521
4522 this.$floatable.css( { left: '', right: '', top: '' } );
4523 }
4524 }
4525
4526 return this;
4527 };
4528
4529 /**
4530 * Check whether the bottom edge of the given element is within the viewport of the given container.
4531 *
4532 * @private
4533 * @param {jQuery} $element
4534 * @param {jQuery} $container
4535 * @return {boolean}
4536 */
4537 OO.ui.mixin.FloatableElement.prototype.isElementInViewport = function ( $element, $container ) {
4538 var elemRect, contRect, topEdgeInBounds, bottomEdgeInBounds, leftEdgeInBounds, rightEdgeInBounds,
4539 startEdgeInBounds, endEdgeInBounds, viewportSpacing,
4540 direction = $element.css( 'direction' );
4541
4542 elemRect = $element[ 0 ].getBoundingClientRect();
4543 if ( $container[ 0 ] === window ) {
4544 viewportSpacing = OO.ui.getViewportSpacing();
4545 contRect = {
4546 top: 0,
4547 left: 0,
4548 right: document.documentElement.clientWidth,
4549 bottom: document.documentElement.clientHeight
4550 };
4551 contRect.top += viewportSpacing.top;
4552 contRect.left += viewportSpacing.left;
4553 contRect.right -= viewportSpacing.right;
4554 contRect.bottom -= viewportSpacing.bottom;
4555 } else {
4556 contRect = $container[ 0 ].getBoundingClientRect();
4557 }
4558
4559 topEdgeInBounds = elemRect.top >= contRect.top && elemRect.top <= contRect.bottom;
4560 bottomEdgeInBounds = elemRect.bottom >= contRect.top && elemRect.bottom <= contRect.bottom;
4561 leftEdgeInBounds = elemRect.left >= contRect.left && elemRect.left <= contRect.right;
4562 rightEdgeInBounds = elemRect.right >= contRect.left && elemRect.right <= contRect.right;
4563 if ( direction === 'rtl' ) {
4564 startEdgeInBounds = rightEdgeInBounds;
4565 endEdgeInBounds = leftEdgeInBounds;
4566 } else {
4567 startEdgeInBounds = leftEdgeInBounds;
4568 endEdgeInBounds = rightEdgeInBounds;
4569 }
4570
4571 if ( this.verticalPosition === 'below' && !bottomEdgeInBounds ) {
4572 return false;
4573 }
4574 if ( this.verticalPosition === 'above' && !topEdgeInBounds ) {
4575 return false;
4576 }
4577 if ( this.horizontalPosition === 'before' && !startEdgeInBounds ) {
4578 return false;
4579 }
4580 if ( this.horizontalPosition === 'after' && !endEdgeInBounds ) {
4581 return false;
4582 }
4583
4584 // The other positioning values are all about being inside the container,
4585 // so in those cases all we care about is that any part of the container is visible.
4586 return elemRect.top <= contRect.bottom && elemRect.bottom >= contRect.top &&
4587 elemRect.left <= contRect.right && elemRect.right >= contRect.left;
4588 };
4589
4590 /**
4591 * Check if the floatable is hidden to the user because it was offscreen.
4592 *
4593 * @return {boolean} Floatable is out of view
4594 */
4595 OO.ui.mixin.FloatableElement.prototype.isFloatableOutOfView = function () {
4596 return this.floatableOutOfView;
4597 };
4598
4599 /**
4600 * Position the floatable below its container.
4601 *
4602 * This should only be done when both of them are attached to the DOM and visible.
4603 *
4604 * @chainable
4605 * @return {OO.ui.Element} The element, for chaining
4606 */
4607 OO.ui.mixin.FloatableElement.prototype.position = function () {
4608 if ( !this.positioning ) {
4609 return this;
4610 }
4611
4612 if ( !(
4613 // To continue, some things need to be true:
4614 // The element must actually be in the DOM
4615 this.isElementAttached() && (
4616 // The closest scrollable is the current window
4617 this.$floatableClosestScrollable[ 0 ] === this.getElementWindow() ||
4618 // OR is an element in the element's DOM
4619 $.contains( this.getElementDocument(), this.$floatableClosestScrollable[ 0 ] )
4620 )
4621 ) ) {
4622 // Abort early if important parts of the widget are no longer attached to the DOM
4623 return this;
4624 }
4625
4626 this.floatableOutOfView = this.hideWhenOutOfView && !this.isElementInViewport( this.$floatableContainer, this.$floatableClosestScrollable );
4627 if ( this.floatableOutOfView ) {
4628 this.$floatable.addClass( 'oo-ui-element-hidden' );
4629 return this;
4630 } else {
4631 this.$floatable.removeClass( 'oo-ui-element-hidden' );
4632 }
4633
4634 this.$floatable.css( this.computePosition() );
4635
4636 // We updated the position, so re-evaluate the clipping state.
4637 // (ClippableElement does not listen to 'scroll' events on $floatableContainer's parent, and so
4638 // will not notice the need to update itself.)
4639 // TODO: This is terrible, we shouldn't need to know about ClippableElement at all here. Why does
4640 // it not listen to the right events in the right places?
4641 if ( this.clip ) {
4642 this.clip();
4643 }
4644
4645 return this;
4646 };
4647
4648 /**
4649 * Compute how #$floatable should be positioned based on the position of #$floatableContainer
4650 * and the positioning settings. This is a helper for #position that shouldn't be called directly,
4651 * but may be overridden by subclasses if they want to change or add to the positioning logic.
4652 *
4653 * @return {Object} New position to apply with .css(). Keys are 'top', 'left', 'bottom' and 'right'.
4654 */
4655 OO.ui.mixin.FloatableElement.prototype.computePosition = function () {
4656 var isBody, scrollableX, scrollableY, containerPos,
4657 horizScrollbarHeight, vertScrollbarWidth, scrollTop, scrollLeft,
4658 newPos = { top: '', left: '', bottom: '', right: '' },
4659 direction = this.$floatableContainer.css( 'direction' ),
4660 $offsetParent = this.$floatable.offsetParent();
4661
4662 if ( $offsetParent.is( 'html' ) ) {
4663 // The innerHeight/Width and clientHeight/Width calculations don't work well on the
4664 // <html> element, but they do work on the <body>
4665 $offsetParent = $( $offsetParent[ 0 ].ownerDocument.body );
4666 }
4667 isBody = $offsetParent.is( 'body' );
4668 scrollableX = $offsetParent.css( 'overflow-x' ) === 'scroll' || $offsetParent.css( 'overflow-x' ) === 'auto';
4669 scrollableY = $offsetParent.css( 'overflow-y' ) === 'scroll' || $offsetParent.css( 'overflow-y' ) === 'auto';
4670
4671 vertScrollbarWidth = $offsetParent.innerWidth() - $offsetParent.prop( 'clientWidth' );
4672 horizScrollbarHeight = $offsetParent.innerHeight() - $offsetParent.prop( 'clientHeight' );
4673 // We don't need to compute and add scrollTop and scrollLeft if the scrollable container is the body,
4674 // or if it isn't scrollable
4675 scrollTop = scrollableY && !isBody ? $offsetParent.scrollTop() : 0;
4676 scrollLeft = scrollableX && !isBody ? OO.ui.Element.static.getScrollLeft( $offsetParent[ 0 ] ) : 0;
4677
4678 // Avoid passing the <body> to getRelativePosition(), because it won't return what we expect
4679 // if the <body> has a margin
4680 containerPos = isBody ?
4681 this.$floatableContainer.offset() :
4682 OO.ui.Element.static.getRelativePosition( this.$floatableContainer, $offsetParent );
4683 containerPos.bottom = containerPos.top + this.$floatableContainer.outerHeight();
4684 containerPos.right = containerPos.left + this.$floatableContainer.outerWidth();
4685 containerPos.start = direction === 'rtl' ? containerPos.right : containerPos.left;
4686 containerPos.end = direction === 'rtl' ? containerPos.left : containerPos.right;
4687
4688 if ( this.verticalPosition === 'below' ) {
4689 newPos.top = containerPos.bottom;
4690 } else if ( this.verticalPosition === 'above' ) {
4691 newPos.bottom = $offsetParent.outerHeight() - containerPos.top;
4692 } else if ( this.verticalPosition === 'top' ) {
4693 newPos.top = containerPos.top;
4694 } else if ( this.verticalPosition === 'bottom' ) {
4695 newPos.bottom = $offsetParent.outerHeight() - containerPos.bottom;
4696 } else if ( this.verticalPosition === 'center' ) {
4697 newPos.top = containerPos.top +
4698 ( this.$floatableContainer.height() - this.$floatable.height() ) / 2;
4699 }
4700
4701 if ( this.horizontalPosition === 'before' ) {
4702 newPos.end = containerPos.start;
4703 } else if ( this.horizontalPosition === 'after' ) {
4704 newPos.start = containerPos.end;
4705 } else if ( this.horizontalPosition === 'start' ) {
4706 newPos.start = containerPos.start;
4707 } else if ( this.horizontalPosition === 'end' ) {
4708 newPos.end = containerPos.end;
4709 } else if ( this.horizontalPosition === 'center' ) {
4710 newPos.left = containerPos.left +
4711 ( this.$floatableContainer.width() - this.$floatable.width() ) / 2;
4712 }
4713
4714 if ( newPos.start !== undefined ) {
4715 if ( direction === 'rtl' ) {
4716 newPos.right = ( isBody ? $( $offsetParent[ 0 ].ownerDocument.documentElement ) : $offsetParent ).outerWidth() - newPos.start;
4717 } else {
4718 newPos.left = newPos.start;
4719 }
4720 delete newPos.start;
4721 }
4722 if ( newPos.end !== undefined ) {
4723 if ( direction === 'rtl' ) {
4724 newPos.left = newPos.end;
4725 } else {
4726 newPos.right = ( isBody ? $( $offsetParent[ 0 ].ownerDocument.documentElement ) : $offsetParent ).outerWidth() - newPos.end;
4727 }
4728 delete newPos.end;
4729 }
4730
4731 // Account for scroll position
4732 if ( newPos.top !== '' ) {
4733 newPos.top += scrollTop;
4734 }
4735 if ( newPos.bottom !== '' ) {
4736 newPos.bottom -= scrollTop;
4737 }
4738 if ( newPos.left !== '' ) {
4739 newPos.left += scrollLeft;
4740 }
4741 if ( newPos.right !== '' ) {
4742 newPos.right -= scrollLeft;
4743 }
4744
4745 // Account for scrollbar gutter
4746 if ( newPos.bottom !== '' ) {
4747 newPos.bottom -= horizScrollbarHeight;
4748 }
4749 if ( direction === 'rtl' ) {
4750 if ( newPos.left !== '' ) {
4751 newPos.left -= vertScrollbarWidth;
4752 }
4753 } else {
4754 if ( newPos.right !== '' ) {
4755 newPos.right -= vertScrollbarWidth;
4756 }
4757 }
4758
4759 return newPos;
4760 };
4761
4762 /**
4763 * Element that can be automatically clipped to visible boundaries.
4764 *
4765 * Whenever the element's natural height changes, you have to call
4766 * {@link OO.ui.mixin.ClippableElement#clip} to make sure it's still
4767 * clipping correctly.
4768 *
4769 * The dimensions of #$clippableContainer will be compared to the boundaries of the
4770 * nearest scrollable container. If #$clippableContainer is too tall and/or too wide,
4771 * then #$clippable will be given a fixed reduced height and/or width and will be made
4772 * scrollable. By default, #$clippable and #$clippableContainer are the same element,
4773 * but you can build a static footer by setting #$clippableContainer to an element that contains
4774 * #$clippable and the footer.
4775 *
4776 * @abstract
4777 * @class
4778 *
4779 * @constructor
4780 * @param {Object} [config] Configuration options
4781 * @cfg {jQuery} [$clippable] Node to clip, assigned to #$clippable, omit to use #$element
4782 * @cfg {jQuery} [$clippableContainer] Node to keep visible, assigned to #$clippableContainer,
4783 * omit to use #$clippable
4784 */
4785 OO.ui.mixin.ClippableElement = function OoUiMixinClippableElement( config ) {
4786 // Configuration initialization
4787 config = config || {};
4788
4789 // Properties
4790 this.$clippable = null;
4791 this.$clippableContainer = null;
4792 this.clipping = false;
4793 this.clippedHorizontally = false;
4794 this.clippedVertically = false;
4795 this.$clippableScrollableContainer = null;
4796 this.$clippableScroller = null;
4797 this.$clippableWindow = null;
4798 this.idealWidth = null;
4799 this.idealHeight = null;
4800 this.onClippableScrollHandler = this.clip.bind( this );
4801 this.onClippableWindowResizeHandler = this.clip.bind( this );
4802
4803 // Initialization
4804 if ( config.$clippableContainer ) {
4805 this.setClippableContainer( config.$clippableContainer );
4806 }
4807 this.setClippableElement( config.$clippable || this.$element );
4808 };
4809
4810 /* Methods */
4811
4812 /**
4813 * Set clippable element.
4814 *
4815 * If an element is already set, it will be cleaned up before setting up the new element.
4816 *
4817 * @param {jQuery} $clippable Element to make clippable
4818 */
4819 OO.ui.mixin.ClippableElement.prototype.setClippableElement = function ( $clippable ) {
4820 if ( this.$clippable ) {
4821 this.$clippable.removeClass( 'oo-ui-clippableElement-clippable' );
4822 this.$clippable.css( { width: '', height: '', overflowX: '', overflowY: '' } );
4823 OO.ui.Element.static.reconsiderScrollbars( this.$clippable[ 0 ] );
4824 }
4825
4826 this.$clippable = $clippable.addClass( 'oo-ui-clippableElement-clippable' );
4827 this.clip();
4828 };
4829
4830 /**
4831 * Set clippable container.
4832 *
4833 * This is the container that will be measured when deciding whether to clip. When clipping,
4834 * #$clippable will be resized in order to keep the clippable container fully visible.
4835 *
4836 * If the clippable container is unset, #$clippable will be used.
4837 *
4838 * @param {jQuery|null} $clippableContainer Container to keep visible, or null to unset
4839 */
4840 OO.ui.mixin.ClippableElement.prototype.setClippableContainer = function ( $clippableContainer ) {
4841 this.$clippableContainer = $clippableContainer;
4842 if ( this.$clippable ) {
4843 this.clip();
4844 }
4845 };
4846
4847 /**
4848 * Toggle clipping.
4849 *
4850 * Do not turn clipping on until after the element is attached to the DOM and visible.
4851 *
4852 * @param {boolean} [clipping] Enable clipping, omit to toggle
4853 * @chainable
4854 * @return {OO.ui.Element} The element, for chaining
4855 */
4856 OO.ui.mixin.ClippableElement.prototype.toggleClipping = function ( clipping ) {
4857 clipping = clipping === undefined ? !this.clipping : !!clipping;
4858
4859 if ( clipping && !this.warnedUnattached && !this.isElementAttached() ) {
4860 OO.ui.warnDeprecation( 'ClippableElement#toggleClipping: Before calling this method, the element must be attached to the DOM.' );
4861 this.warnedUnattached = true;
4862 }
4863
4864 if ( this.clipping !== clipping ) {
4865 this.clipping = clipping;
4866 if ( clipping ) {
4867 this.$clippableScrollableContainer = $( this.getClosestScrollableElementContainer() );
4868 // If the clippable container is the root, we have to listen to scroll events and check
4869 // jQuery.scrollTop on the window because of browser inconsistencies
4870 this.$clippableScroller = this.$clippableScrollableContainer.is( 'html, body' ) ?
4871 $( OO.ui.Element.static.getWindow( this.$clippableScrollableContainer ) ) :
4872 this.$clippableScrollableContainer;
4873 this.$clippableScroller.on( 'scroll', this.onClippableScrollHandler );
4874 this.$clippableWindow = $( this.getElementWindow() )
4875 .on( 'resize', this.onClippableWindowResizeHandler );
4876 // Initial clip after visible
4877 this.clip();
4878 } else {
4879 this.$clippable.css( {
4880 width: '',
4881 height: '',
4882 maxWidth: '',
4883 maxHeight: '',
4884 overflowX: '',
4885 overflowY: ''
4886 } );
4887 OO.ui.Element.static.reconsiderScrollbars( this.$clippable[ 0 ] );
4888
4889 this.$clippableScrollableContainer = null;
4890 this.$clippableScroller.off( 'scroll', this.onClippableScrollHandler );
4891 this.$clippableScroller = null;
4892 this.$clippableWindow.off( 'resize', this.onClippableWindowResizeHandler );
4893 this.$clippableWindow = null;
4894 }
4895 }
4896
4897 return this;
4898 };
4899
4900 /**
4901 * Check if the element will be clipped to fit the visible area of the nearest scrollable container.
4902 *
4903 * @return {boolean} Element will be clipped to the visible area
4904 */
4905 OO.ui.mixin.ClippableElement.prototype.isClipping = function () {
4906 return this.clipping;
4907 };
4908
4909 /**
4910 * Check if the bottom or right of the element is being clipped by the nearest scrollable container.
4911 *
4912 * @return {boolean} Part of the element is being clipped
4913 */
4914 OO.ui.mixin.ClippableElement.prototype.isClipped = function () {
4915 return this.clippedHorizontally || this.clippedVertically;
4916 };
4917
4918 /**
4919 * Check if the right of the element is being clipped by the nearest scrollable container.
4920 *
4921 * @return {boolean} Part of the element is being clipped
4922 */
4923 OO.ui.mixin.ClippableElement.prototype.isClippedHorizontally = function () {
4924 return this.clippedHorizontally;
4925 };
4926
4927 /**
4928 * Check if the bottom of the element is being clipped by the nearest scrollable container.
4929 *
4930 * @return {boolean} Part of the element is being clipped
4931 */
4932 OO.ui.mixin.ClippableElement.prototype.isClippedVertically = function () {
4933 return this.clippedVertically;
4934 };
4935
4936 /**
4937 * Set the ideal size. These are the dimensions #$clippable will have when it's not being clipped.
4938 *
4939 * @param {number|string} [width] Width as a number of pixels or CSS string with unit suffix
4940 * @param {number|string} [height] Height as a number of pixels or CSS string with unit suffix
4941 */
4942 OO.ui.mixin.ClippableElement.prototype.setIdealSize = function ( width, height ) {
4943 this.idealWidth = width;
4944 this.idealHeight = height;
4945
4946 if ( !this.clipping ) {
4947 // Update dimensions
4948 this.$clippable.css( { width: width, height: height } );
4949 }
4950 // While clipping, idealWidth and idealHeight are not considered
4951 };
4952
4953 /**
4954 * Return the side of the clippable on which it is "anchored" (aligned to something else).
4955 * ClippableElement will clip the opposite side when reducing element's width.
4956 *
4957 * Classes that mix in ClippableElement should override this to return 'right' if their
4958 * clippable is absolutely positioned and using 'right: Npx' (and not using 'left').
4959 * If your class also mixes in FloatableElement, this is handled automatically.
4960 *
4961 * (This can't be guessed from the actual CSS because the computed values for 'left'/'right' are
4962 * always in pixels, even if they were unset or set to 'auto'.)
4963 *
4964 * When in doubt, 'left' (or 'right' in RTL) is a sane fallback.
4965 *
4966 * @return {string} 'left' or 'right'
4967 */
4968 OO.ui.mixin.ClippableElement.prototype.getHorizontalAnchorEdge = function () {
4969 if ( this.computePosition && this.positioning && this.computePosition().right !== '' ) {
4970 return 'right';
4971 }
4972 return 'left';
4973 };
4974
4975 /**
4976 * Return the side of the clippable on which it is "anchored" (aligned to something else).
4977 * ClippableElement will clip the opposite side when reducing element's width.
4978 *
4979 * Classes that mix in ClippableElement should override this to return 'bottom' if their
4980 * clippable is absolutely positioned and using 'bottom: Npx' (and not using 'top').
4981 * If your class also mixes in FloatableElement, this is handled automatically.
4982 *
4983 * (This can't be guessed from the actual CSS because the computed values for 'left'/'right' are
4984 * always in pixels, even if they were unset or set to 'auto'.)
4985 *
4986 * When in doubt, 'top' is a sane fallback.
4987 *
4988 * @return {string} 'top' or 'bottom'
4989 */
4990 OO.ui.mixin.ClippableElement.prototype.getVerticalAnchorEdge = function () {
4991 if ( this.computePosition && this.positioning && this.computePosition().bottom !== '' ) {
4992 return 'bottom';
4993 }
4994 return 'top';
4995 };
4996
4997 /**
4998 * Clip element to visible boundaries and allow scrolling when needed. You should call this method
4999 * when the element's natural height changes.
5000 *
5001 * Element will be clipped the bottom or right of the element is within 10px of the edge of, or
5002 * overlapped by, the visible area of the nearest scrollable container.
5003 *
5004 * Because calling clip() when the natural height changes isn't always possible, we also set
5005 * max-height when the element isn't being clipped. This means that if the element tries to grow
5006 * beyond the edge, something reasonable will happen before clip() is called.
5007 *
5008 * @chainable
5009 * @return {OO.ui.Element} The element, for chaining
5010 */
5011 OO.ui.mixin.ClippableElement.prototype.clip = function () {
5012 var extraHeight, extraWidth, viewportSpacing,
5013 desiredWidth, desiredHeight, allotedWidth, allotedHeight,
5014 naturalWidth, naturalHeight, clipWidth, clipHeight,
5015 $item, itemRect, $viewport, viewportRect, availableRect,
5016 direction, vertScrollbarWidth, horizScrollbarHeight,
5017 // Extra tolerance so that the sloppy code below doesn't result in results that are off
5018 // by one or two pixels. (And also so that we have space to display drop shadows.)
5019 // Chosen by fair dice roll.
5020 buffer = 7;
5021
5022 if ( !this.clipping ) {
5023 // this.$clippableScrollableContainer and this.$clippableWindow are null, so the below will fail
5024 return this;
5025 }
5026
5027 function rectIntersection( a, b ) {
5028 var out = {};
5029 out.top = Math.max( a.top, b.top );
5030 out.left = Math.max( a.left, b.left );
5031 out.bottom = Math.min( a.bottom, b.bottom );
5032 out.right = Math.min( a.right, b.right );
5033 return out;
5034 }
5035
5036 viewportSpacing = OO.ui.getViewportSpacing();
5037
5038 if ( this.$clippableScrollableContainer.is( 'html, body' ) ) {
5039 $viewport = $( this.$clippableScrollableContainer[ 0 ].ownerDocument.body );
5040 // Dimensions of the browser window, rather than the element!
5041 viewportRect = {
5042 top: 0,
5043 left: 0,
5044 right: document.documentElement.clientWidth,
5045 bottom: document.documentElement.clientHeight
5046 };
5047 viewportRect.top += viewportSpacing.top;
5048 viewportRect.left += viewportSpacing.left;
5049 viewportRect.right -= viewportSpacing.right;
5050 viewportRect.bottom -= viewportSpacing.bottom;
5051 } else {
5052 $viewport = this.$clippableScrollableContainer;
5053 viewportRect = $viewport[ 0 ].getBoundingClientRect();
5054 // Convert into a plain object
5055 viewportRect = $.extend( {}, viewportRect );
5056 }
5057
5058 // Account for scrollbar gutter
5059 direction = $viewport.css( 'direction' );
5060 vertScrollbarWidth = $viewport.innerWidth() - $viewport.prop( 'clientWidth' );
5061 horizScrollbarHeight = $viewport.innerHeight() - $viewport.prop( 'clientHeight' );
5062 viewportRect.bottom -= horizScrollbarHeight;
5063 if ( direction === 'rtl' ) {
5064 viewportRect.left += vertScrollbarWidth;
5065 } else {
5066 viewportRect.right -= vertScrollbarWidth;
5067 }
5068
5069 // Add arbitrary tolerance
5070 viewportRect.top += buffer;
5071 viewportRect.left += buffer;
5072 viewportRect.right -= buffer;
5073 viewportRect.bottom -= buffer;
5074
5075 $item = this.$clippableContainer || this.$clippable;
5076
5077 extraHeight = $item.outerHeight() - this.$clippable.outerHeight();
5078 extraWidth = $item.outerWidth() - this.$clippable.outerWidth();
5079
5080 itemRect = $item[ 0 ].getBoundingClientRect();
5081 // Convert into a plain object
5082 itemRect = $.extend( {}, itemRect );
5083
5084 // Item might already be clipped, so we can't just use its dimensions (in case we might need to
5085 // make it larger than before). Extend the rectangle to the maximum size we are allowed to take.
5086 if ( this.getHorizontalAnchorEdge() === 'right' ) {
5087 itemRect.left = viewportRect.left;
5088 } else {
5089 itemRect.right = viewportRect.right;
5090 }
5091 if ( this.getVerticalAnchorEdge() === 'bottom' ) {
5092 itemRect.top = viewportRect.top;
5093 } else {
5094 itemRect.bottom = viewportRect.bottom;
5095 }
5096
5097 availableRect = rectIntersection( viewportRect, itemRect );
5098
5099 desiredWidth = Math.max( 0, availableRect.right - availableRect.left );
5100 desiredHeight = Math.max( 0, availableRect.bottom - availableRect.top );
5101 // It should never be desirable to exceed the dimensions of the browser viewport... right?
5102 desiredWidth = Math.min( desiredWidth,
5103 document.documentElement.clientWidth - viewportSpacing.left - viewportSpacing.right );
5104 desiredHeight = Math.min( desiredHeight,
5105 document.documentElement.clientHeight - viewportSpacing.top - viewportSpacing.right );
5106 allotedWidth = Math.ceil( desiredWidth - extraWidth );
5107 allotedHeight = Math.ceil( desiredHeight - extraHeight );
5108 naturalWidth = this.$clippable.prop( 'scrollWidth' );
5109 naturalHeight = this.$clippable.prop( 'scrollHeight' );
5110 clipWidth = allotedWidth < naturalWidth;
5111 clipHeight = allotedHeight < naturalHeight;
5112
5113 if ( clipWidth ) {
5114 // The order matters here. If overflow is not set first, Chrome displays bogus scrollbars. See T157672.
5115 // Forcing a reflow is a smaller workaround than calling reconsiderScrollbars() for this case.
5116 this.$clippable.css( 'overflowX', 'scroll' );
5117 // eslint-disable-next-line no-void
5118 void this.$clippable[ 0 ].offsetHeight; // Force reflow
5119 this.$clippable.css( {
5120 width: Math.max( 0, allotedWidth ),
5121 maxWidth: ''
5122 } );
5123 } else {
5124 this.$clippable.css( {
5125 overflowX: '',
5126 width: this.idealWidth || '',
5127 maxWidth: Math.max( 0, allotedWidth )
5128 } );
5129 }
5130 if ( clipHeight ) {
5131 // The order matters here. If overflow is not set first, Chrome displays bogus scrollbars. See T157672.
5132 // Forcing a reflow is a smaller workaround than calling reconsiderScrollbars() for this case.
5133 this.$clippable.css( 'overflowY', 'scroll' );
5134 // eslint-disable-next-line no-void
5135 void this.$clippable[ 0 ].offsetHeight; // Force reflow
5136 this.$clippable.css( {
5137 height: Math.max( 0, allotedHeight ),
5138 maxHeight: ''
5139 } );
5140 } else {
5141 this.$clippable.css( {
5142 overflowY: '',
5143 height: this.idealHeight || '',
5144 maxHeight: Math.max( 0, allotedHeight )
5145 } );
5146 }
5147
5148 // If we stopped clipping in at least one of the dimensions
5149 if ( ( this.clippedHorizontally && !clipWidth ) || ( this.clippedVertically && !clipHeight ) ) {
5150 OO.ui.Element.static.reconsiderScrollbars( this.$clippable[ 0 ] );
5151 }
5152
5153 this.clippedHorizontally = clipWidth;
5154 this.clippedVertically = clipHeight;
5155
5156 return this;
5157 };
5158
5159 /**
5160 * PopupWidget is a container for content. The popup is overlaid and positioned absolutely.
5161 * By default, each popup has an anchor that points toward its origin.
5162 * Please see the [OOUI documentation on MediaWiki.org] [1] for more information and examples.
5163 *
5164 * Unlike most widgets, PopupWidget is initially hidden and must be shown by calling #toggle.
5165 *
5166 * @example
5167 * // A popup widget.
5168 * var popup = new OO.ui.PopupWidget( {
5169 * $content: $( '<p>Hi there!</p>' ),
5170 * padded: true,
5171 * width: 300
5172 * } );
5173 *
5174 * $( 'body' ).append( popup.$element );
5175 * // To display the popup, toggle the visibility to 'true'.
5176 * popup.toggle( true );
5177 *
5178 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Popups
5179 *
5180 * @class
5181 * @extends OO.ui.Widget
5182 * @mixins OO.ui.mixin.LabelElement
5183 * @mixins OO.ui.mixin.ClippableElement
5184 * @mixins OO.ui.mixin.FloatableElement
5185 *
5186 * @constructor
5187 * @param {Object} [config] Configuration options
5188 * @cfg {number|null} [width=320] Width of popup in pixels. Pass `null` to use automatic width.
5189 * @cfg {number|null} [height=null] Height of popup in pixels. Pass `null` to use automatic height.
5190 * @cfg {boolean} [anchor=true] Show anchor pointing to origin of popup
5191 * @cfg {string} [position='below'] Where to position the popup relative to $floatableContainer
5192 * 'above': Put popup above $floatableContainer; anchor points down to the horizontal center
5193 * of $floatableContainer
5194 * 'below': Put popup below $floatableContainer; anchor points up to the horizontal center
5195 * of $floatableContainer
5196 * 'before': Put popup to the left (LTR) / right (RTL) of $floatableContainer; anchor points
5197 * endwards (right/left) to the vertical center of $floatableContainer
5198 * 'after': Put popup to the right (LTR) / left (RTL) of $floatableContainer; anchor points
5199 * startwards (left/right) to the vertical center of $floatableContainer
5200 * @cfg {string} [align='center'] How to align the popup to $floatableContainer
5201 * 'forwards': If position is above/below, move the popup as far endwards (right in LTR, left in RTL)
5202 * as possible while still keeping the anchor within the popup;
5203 * if position is before/after, move the popup as far downwards as possible.
5204 * 'backwards': If position is above/below, move the popup as far startwards (left in LTR, right in RTL)
5205 * as possible while still keeping the anchor within the popup;
5206 * if position in before/after, move the popup as far upwards as possible.
5207 * 'center': Horizontally (if position is above/below) or vertically (before/after) align the center
5208 * of the popup with the center of $floatableContainer.
5209 * 'force-left': Alias for 'forwards' in LTR and 'backwards' in RTL
5210 * 'force-right': Alias for 'backwards' in RTL and 'forwards' in LTR
5211 * @cfg {boolean} [autoFlip=true] Whether to automatically switch the popup's position between
5212 * 'above' and 'below', or between 'before' and 'after', if there is not enough space in the
5213 * desired direction to display the popup without clipping
5214 * @cfg {jQuery} [$container] Constrain the popup to the boundaries of the specified container.
5215 * See the [OOUI docs on MediaWiki][3] for an example.
5216 * [3]: https://www.mediawiki.org/wiki/OOUI/Widgets/Popups#containerExample
5217 * @cfg {number} [containerPadding=10] Padding between the popup and its container, specified as a number of pixels.
5218 * @cfg {jQuery} [$content] Content to append to the popup's body
5219 * @cfg {jQuery} [$footer] Content to append to the popup's footer
5220 * @cfg {boolean} [autoClose=false] Automatically close the popup when it loses focus.
5221 * @cfg {jQuery} [$autoCloseIgnore] Elements that will not close the popup when clicked.
5222 * This config option is only relevant if #autoClose is set to `true`. See the [OOUI documentation on MediaWiki][2]
5223 * for an example.
5224 * [2]: https://www.mediawiki.org/wiki/OOUI/Widgets/Popups#autocloseExample
5225 * @cfg {boolean} [head=false] Show a popup header that contains a #label (if specified) and close
5226 * button.
5227 * @cfg {boolean} [padded=false] Add padding to the popup's body
5228 */
5229 OO.ui.PopupWidget = function OoUiPopupWidget( config ) {
5230 // Configuration initialization
5231 config = config || {};
5232
5233 // Parent constructor
5234 OO.ui.PopupWidget.parent.call( this, config );
5235
5236 // Properties (must be set before ClippableElement constructor call)
5237 this.$body = $( '<div>' );
5238 this.$popup = $( '<div>' );
5239
5240 // Mixin constructors
5241 OO.ui.mixin.LabelElement.call( this, config );
5242 OO.ui.mixin.ClippableElement.call( this, $.extend( {}, config, {
5243 $clippable: this.$body,
5244 $clippableContainer: this.$popup
5245 } ) );
5246 OO.ui.mixin.FloatableElement.call( this, config );
5247
5248 // Properties
5249 this.$anchor = $( '<div>' );
5250 // If undefined, will be computed lazily in computePosition()
5251 this.$container = config.$container;
5252 this.containerPadding = config.containerPadding !== undefined ? config.containerPadding : 10;
5253 this.autoClose = !!config.autoClose;
5254 this.transitionTimeout = null;
5255 this.anchored = false;
5256 this.onDocumentMouseDownHandler = this.onDocumentMouseDown.bind( this );
5257 this.onDocumentKeyDownHandler = this.onDocumentKeyDown.bind( this );
5258
5259 // Initialization
5260 this.setSize( config.width, config.height );
5261 this.toggleAnchor( config.anchor === undefined || config.anchor );
5262 this.setAlignment( config.align || 'center' );
5263 this.setPosition( config.position || 'below' );
5264 this.setAutoFlip( config.autoFlip === undefined || config.autoFlip );
5265 this.setAutoCloseIgnore( config.$autoCloseIgnore );
5266 this.$body.addClass( 'oo-ui-popupWidget-body' );
5267 this.$anchor.addClass( 'oo-ui-popupWidget-anchor' );
5268 this.$popup
5269 .addClass( 'oo-ui-popupWidget-popup' )
5270 .append( this.$body );
5271 this.$element
5272 .addClass( 'oo-ui-popupWidget' )
5273 .append( this.$popup, this.$anchor );
5274 // Move content, which was added to #$element by OO.ui.Widget, to the body
5275 // FIXME This is gross, we should use '$body' or something for the config
5276 if ( config.$content instanceof $ ) {
5277 this.$body.append( config.$content );
5278 }
5279
5280 if ( config.padded ) {
5281 this.$body.addClass( 'oo-ui-popupWidget-body-padded' );
5282 }
5283
5284 if ( config.head ) {
5285 this.closeButton = new OO.ui.ButtonWidget( { framed: false, icon: 'close' } );
5286 this.closeButton.connect( this, { click: 'onCloseButtonClick' } );
5287 this.$head = $( '<div>' )
5288 .addClass( 'oo-ui-popupWidget-head' )
5289 .append( this.$label, this.closeButton.$element );
5290 this.$popup.prepend( this.$head );
5291 }
5292
5293 if ( config.$footer ) {
5294 this.$footer = $( '<div>' )
5295 .addClass( 'oo-ui-popupWidget-footer' )
5296 .append( config.$footer );
5297 this.$popup.append( this.$footer );
5298 }
5299
5300 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
5301 // that reference properties not initialized at that time of parent class construction
5302 // TODO: Find a better way to handle post-constructor setup
5303 this.visible = false;
5304 this.$element.addClass( 'oo-ui-element-hidden' );
5305 };
5306
5307 /* Setup */
5308
5309 OO.inheritClass( OO.ui.PopupWidget, OO.ui.Widget );
5310 OO.mixinClass( OO.ui.PopupWidget, OO.ui.mixin.LabelElement );
5311 OO.mixinClass( OO.ui.PopupWidget, OO.ui.mixin.ClippableElement );
5312 OO.mixinClass( OO.ui.PopupWidget, OO.ui.mixin.FloatableElement );
5313
5314 /* Events */
5315
5316 /**
5317 * @event ready
5318 *
5319 * The popup is ready: it is visible and has been positioned and clipped.
5320 */
5321
5322 /* Methods */
5323
5324 /**
5325 * Handles document mouse down events.
5326 *
5327 * @private
5328 * @param {MouseEvent} e Mouse down event
5329 */
5330 OO.ui.PopupWidget.prototype.onDocumentMouseDown = function ( e ) {
5331 if (
5332 this.isVisible() &&
5333 !OO.ui.contains( this.$element.add( this.$autoCloseIgnore ).get(), e.target, true )
5334 ) {
5335 this.toggle( false );
5336 }
5337 };
5338
5339 // Deprecated alias since 0.28.3
5340 OO.ui.PopupWidget.prototype.onMouseDown = function () {
5341 OO.ui.warnDeprecation( 'onMouseDown is deprecated, use onDocumentMouseDown instead' );
5342 this.onDocumentMouseDown.apply( this, arguments );
5343 };
5344
5345 /**
5346 * Bind document mouse down listener.
5347 *
5348 * @private
5349 */
5350 OO.ui.PopupWidget.prototype.bindDocumentMouseDownListener = function () {
5351 // Capture clicks outside popup
5352 this.getElementDocument().addEventListener( 'mousedown', this.onDocumentMouseDownHandler, true );
5353 // We add 'click' event because iOS safari needs to respond to this event.
5354 // We can't use 'touchstart' (as is usually the equivalent to 'mousedown') because
5355 // then it will trigger when scrolling. While iOS Safari has some reported behavior
5356 // of occasionally not emitting 'click' properly, that event seems to be the standard
5357 // that it should be emitting, so we add it to this and will operate the event handler
5358 // on whichever of these events was triggered first
5359 this.getElementDocument().addEventListener( 'click', this.onDocumentMouseDownHandler, true );
5360 };
5361
5362 // Deprecated alias since 0.28.3
5363 OO.ui.PopupWidget.prototype.bindMouseDownListener = function () {
5364 OO.ui.warnDeprecation( 'bindMouseDownListener is deprecated, use bindDocumentMouseDownListener instead' );
5365 this.bindDocumentMouseDownListener.apply( this, arguments );
5366 };
5367
5368 /**
5369 * Handles close button click events.
5370 *
5371 * @private
5372 */
5373 OO.ui.PopupWidget.prototype.onCloseButtonClick = function () {
5374 if ( this.isVisible() ) {
5375 this.toggle( false );
5376 }
5377 };
5378
5379 /**
5380 * Unbind document mouse down listener.
5381 *
5382 * @private
5383 */
5384 OO.ui.PopupWidget.prototype.unbindDocumentMouseDownListener = function () {
5385 this.getElementDocument().removeEventListener( 'mousedown', this.onDocumentMouseDownHandler, true );
5386 this.getElementDocument().removeEventListener( 'click', this.onDocumentMouseDownHandler, true );
5387 };
5388
5389 // Deprecated alias since 0.28.3
5390 OO.ui.PopupWidget.prototype.unbindMouseDownListener = function () {
5391 OO.ui.warnDeprecation( 'unbindMouseDownListener is deprecated, use unbindDocumentMouseDownListener instead' );
5392 this.unbindDocumentMouseDownListener.apply( this, arguments );
5393 };
5394
5395 /**
5396 * Handles document key down events.
5397 *
5398 * @private
5399 * @param {KeyboardEvent} e Key down event
5400 */
5401 OO.ui.PopupWidget.prototype.onDocumentKeyDown = function ( e ) {
5402 if (
5403 e.which === OO.ui.Keys.ESCAPE &&
5404 this.isVisible()
5405 ) {
5406 this.toggle( false );
5407 e.preventDefault();
5408 e.stopPropagation();
5409 }
5410 };
5411
5412 /**
5413 * Bind document key down listener.
5414 *
5415 * @private
5416 */
5417 OO.ui.PopupWidget.prototype.bindDocumentKeyDownListener = function () {
5418 this.getElementDocument().addEventListener( 'keydown', this.onDocumentKeyDownHandler, true );
5419 };
5420
5421 // Deprecated alias since 0.28.3
5422 OO.ui.PopupWidget.prototype.bindKeyDownListener = function () {
5423 OO.ui.warnDeprecation( 'bindKeyDownListener is deprecated, use bindDocumentKeyDownListener instead' );
5424 this.bindDocumentKeyDownListener.apply( this, arguments );
5425 };
5426
5427 /**
5428 * Unbind document key down listener.
5429 *
5430 * @private
5431 */
5432 OO.ui.PopupWidget.prototype.unbindDocumentKeyDownListener = function () {
5433 this.getElementDocument().removeEventListener( 'keydown', this.onDocumentKeyDownHandler, true );
5434 };
5435
5436 // Deprecated alias since 0.28.3
5437 OO.ui.PopupWidget.prototype.unbindKeyDownListener = function () {
5438 OO.ui.warnDeprecation( 'unbindKeyDownListener is deprecated, use unbindDocumentKeyDownListener instead' );
5439 this.unbindDocumentKeyDownListener.apply( this, arguments );
5440 };
5441
5442 /**
5443 * Show, hide, or toggle the visibility of the anchor.
5444 *
5445 * @param {boolean} [show] Show anchor, omit to toggle
5446 */
5447 OO.ui.PopupWidget.prototype.toggleAnchor = function ( show ) {
5448 show = show === undefined ? !this.anchored : !!show;
5449
5450 if ( this.anchored !== show ) {
5451 if ( show ) {
5452 this.$element.addClass( 'oo-ui-popupWidget-anchored' );
5453 this.$element.addClass( 'oo-ui-popupWidget-anchored-' + this.anchorEdge );
5454 } else {
5455 this.$element.removeClass( 'oo-ui-popupWidget-anchored' );
5456 this.$element.removeClass( 'oo-ui-popupWidget-anchored-' + this.anchorEdge );
5457 }
5458 this.anchored = show;
5459 }
5460 };
5461
5462 /**
5463 * Change which edge the anchor appears on.
5464 *
5465 * @param {string} edge 'top', 'bottom', 'start' or 'end'
5466 */
5467 OO.ui.PopupWidget.prototype.setAnchorEdge = function ( edge ) {
5468 if ( [ 'top', 'bottom', 'start', 'end' ].indexOf( edge ) === -1 ) {
5469 throw new Error( 'Invalid value for edge: ' + edge );
5470 }
5471 if ( this.anchorEdge !== null ) {
5472 this.$element.removeClass( 'oo-ui-popupWidget-anchored-' + this.anchorEdge );
5473 }
5474 this.anchorEdge = edge;
5475 if ( this.anchored ) {
5476 this.$element.addClass( 'oo-ui-popupWidget-anchored-' + edge );
5477 }
5478 };
5479
5480 /**
5481 * Check if the anchor is visible.
5482 *
5483 * @return {boolean} Anchor is visible
5484 */
5485 OO.ui.PopupWidget.prototype.hasAnchor = function () {
5486 return this.anchored;
5487 };
5488
5489 /**
5490 * Toggle visibility of the popup. The popup is initially hidden and must be shown by calling
5491 * `.toggle( true )` after its #$element is attached to the DOM.
5492 *
5493 * Do not show the popup while it is not attached to the DOM. The calculations required to display
5494 * it in the right place and with the right dimensions only work correctly while it is attached.
5495 * Side-effects may include broken interface and exceptions being thrown. This wasn't always
5496 * strictly enforced, so currently it only generates a warning in the browser console.
5497 *
5498 * @fires ready
5499 * @inheritdoc
5500 */
5501 OO.ui.PopupWidget.prototype.toggle = function ( show ) {
5502 var change, normalHeight, oppositeHeight, normalWidth, oppositeWidth;
5503 show = show === undefined ? !this.isVisible() : !!show;
5504
5505 change = show !== this.isVisible();
5506
5507 if ( show && !this.warnedUnattached && !this.isElementAttached() ) {
5508 OO.ui.warnDeprecation( 'PopupWidget#toggle: Before calling this method, the popup must be attached to the DOM.' );
5509 this.warnedUnattached = true;
5510 }
5511 if ( show && !this.$floatableContainer && this.isElementAttached() ) {
5512 // Fall back to the parent node if the floatableContainer is not set
5513 this.setFloatableContainer( this.$element.parent() );
5514 }
5515
5516 if ( change && show && this.autoFlip ) {
5517 // Reset auto-flipping before showing the popup again. It's possible we no longer need to flip
5518 // (e.g. if the user scrolled).
5519 this.isAutoFlipped = false;
5520 }
5521
5522 // Parent method
5523 OO.ui.PopupWidget.parent.prototype.toggle.call( this, show );
5524
5525 if ( change ) {
5526 this.togglePositioning( show && !!this.$floatableContainer );
5527
5528 if ( show ) {
5529 if ( this.autoClose ) {
5530 this.bindDocumentMouseDownListener();
5531 this.bindDocumentKeyDownListener();
5532 }
5533 this.updateDimensions();
5534 this.toggleClipping( true );
5535
5536 if ( this.autoFlip ) {
5537 if ( this.popupPosition === 'above' || this.popupPosition === 'below' ) {
5538 if ( this.isClippedVertically() || this.isFloatableOutOfView() ) {
5539 // If opening the popup in the normal direction causes it to be clipped, open
5540 // in the opposite one instead
5541 normalHeight = this.$element.height();
5542 this.isAutoFlipped = !this.isAutoFlipped;
5543 this.position();
5544 if ( this.isClippedVertically() || this.isFloatableOutOfView() ) {
5545 // If that also causes it to be clipped, open in whichever direction
5546 // we have more space
5547 oppositeHeight = this.$element.height();
5548 if ( oppositeHeight < normalHeight ) {
5549 this.isAutoFlipped = !this.isAutoFlipped;
5550 this.position();
5551 }
5552 }
5553 }
5554 }
5555 if ( this.popupPosition === 'before' || this.popupPosition === 'after' ) {
5556 if ( this.isClippedHorizontally() || this.isFloatableOutOfView() ) {
5557 // If opening the popup in the normal direction causes it to be clipped, open
5558 // in the opposite one instead
5559 normalWidth = this.$element.width();
5560 this.isAutoFlipped = !this.isAutoFlipped;
5561 // Due to T180173 horizontally clipped PopupWidgets have messed up dimensions,
5562 // which causes positioning to be off. Toggle clipping back and fort to work around.
5563 this.toggleClipping( false );
5564 this.position();
5565 this.toggleClipping( true );
5566 if ( this.isClippedHorizontally() || this.isFloatableOutOfView() ) {
5567 // If that also causes it to be clipped, open in whichever direction
5568 // we have more space
5569 oppositeWidth = this.$element.width();
5570 if ( oppositeWidth < normalWidth ) {
5571 this.isAutoFlipped = !this.isAutoFlipped;
5572 // Due to T180173 horizontally clipped PopupWidgets have messed up dimensions,
5573 // which causes positioning to be off. Toggle clipping back and fort to work around.
5574 this.toggleClipping( false );
5575 this.position();
5576 this.toggleClipping( true );
5577 }
5578 }
5579 }
5580 }
5581 }
5582
5583 this.emit( 'ready' );
5584 } else {
5585 this.toggleClipping( false );
5586 if ( this.autoClose ) {
5587 this.unbindDocumentMouseDownListener();
5588 this.unbindDocumentKeyDownListener();
5589 }
5590 }
5591 }
5592
5593 return this;
5594 };
5595
5596 /**
5597 * Set the size of the popup.
5598 *
5599 * Changing the size may also change the popup's position depending on the alignment.
5600 *
5601 * @param {number|null} [width=320] Width in pixels. Pass `null` to use automatic width.
5602 * @param {number|null} [height=null] Height in pixels. Pass `null` to use automatic height.
5603 * @param {boolean} [transition=false] Use a smooth transition
5604 * @chainable
5605 */
5606 OO.ui.PopupWidget.prototype.setSize = function ( width, height, transition ) {
5607 this.width = width !== undefined ? width : 320;
5608 this.height = height !== undefined ? height : null;
5609 if ( this.isVisible() ) {
5610 this.updateDimensions( transition );
5611 }
5612 };
5613
5614 /**
5615 * Update the size and position.
5616 *
5617 * Only use this to keep the popup properly anchored. Use #setSize to change the size, and this will
5618 * be called automatically.
5619 *
5620 * @param {boolean} [transition=false] Use a smooth transition
5621 * @chainable
5622 */
5623 OO.ui.PopupWidget.prototype.updateDimensions = function ( transition ) {
5624 var widget = this;
5625
5626 // Prevent transition from being interrupted
5627 clearTimeout( this.transitionTimeout );
5628 if ( transition ) {
5629 // Enable transition
5630 this.$element.addClass( 'oo-ui-popupWidget-transitioning' );
5631 }
5632
5633 this.position();
5634
5635 if ( transition ) {
5636 // Prevent transitioning after transition is complete
5637 this.transitionTimeout = setTimeout( function () {
5638 widget.$element.removeClass( 'oo-ui-popupWidget-transitioning' );
5639 }, 200 );
5640 } else {
5641 // Prevent transitioning immediately
5642 this.$element.removeClass( 'oo-ui-popupWidget-transitioning' );
5643 }
5644 };
5645
5646 /**
5647 * @inheritdoc
5648 */
5649 OO.ui.PopupWidget.prototype.computePosition = function () {
5650 var direction, align, vertical, start, end, near, far, sizeProp, popupSize, anchorSize, anchorPos,
5651 anchorOffset, anchorMargin, parentPosition, positionProp, positionAdjustment, floatablePos,
5652 offsetParentPos, containerPos, popupPosition, viewportSpacing,
5653 popupPos = {},
5654 anchorCss = { left: '', right: '', top: '', bottom: '' },
5655 popupPositionOppositeMap = {
5656 above: 'below',
5657 below: 'above',
5658 before: 'after',
5659 after: 'before'
5660 },
5661 alignMap = {
5662 ltr: {
5663 'force-left': 'backwards',
5664 'force-right': 'forwards'
5665 },
5666 rtl: {
5667 'force-left': 'forwards',
5668 'force-right': 'backwards'
5669 }
5670 },
5671 anchorEdgeMap = {
5672 above: 'bottom',
5673 below: 'top',
5674 before: 'end',
5675 after: 'start'
5676 },
5677 hPosMap = {
5678 forwards: 'start',
5679 center: 'center',
5680 backwards: this.anchored ? 'before' : 'end'
5681 },
5682 vPosMap = {
5683 forwards: 'top',
5684 center: 'center',
5685 backwards: 'bottom'
5686 };
5687
5688 if ( !this.$container ) {
5689 // Lazy-initialize $container if not specified in constructor
5690 this.$container = $( this.getClosestScrollableElementContainer() );
5691 }
5692 direction = this.$container.css( 'direction' );
5693
5694 // Set height and width before we do anything else, since it might cause our measurements
5695 // to change (e.g. due to scrollbars appearing or disappearing), and it also affects centering
5696 this.$popup.css( {
5697 width: this.width !== null ? this.width : 'auto',
5698 height: this.height !== null ? this.height : 'auto'
5699 } );
5700
5701 align = alignMap[ direction ][ this.align ] || this.align;
5702 popupPosition = this.popupPosition;
5703 if ( this.isAutoFlipped ) {
5704 popupPosition = popupPositionOppositeMap[ popupPosition ];
5705 }
5706
5707 // If the popup is positioned before or after, then the anchor positioning is vertical, otherwise horizontal
5708 vertical = popupPosition === 'before' || popupPosition === 'after';
5709 start = vertical ? 'top' : ( direction === 'rtl' ? 'right' : 'left' );
5710 end = vertical ? 'bottom' : ( direction === 'rtl' ? 'left' : 'right' );
5711 near = vertical ? 'top' : 'left';
5712 far = vertical ? 'bottom' : 'right';
5713 sizeProp = vertical ? 'Height' : 'Width';
5714 popupSize = vertical ? ( this.height || this.$popup.height() ) : ( this.width || this.$popup.width() );
5715
5716 this.setAnchorEdge( anchorEdgeMap[ popupPosition ] );
5717 this.horizontalPosition = vertical ? popupPosition : hPosMap[ align ];
5718 this.verticalPosition = vertical ? vPosMap[ align ] : popupPosition;
5719
5720 // Parent method
5721 parentPosition = OO.ui.mixin.FloatableElement.prototype.computePosition.call( this );
5722 // Find out which property FloatableElement used for positioning, and adjust that value
5723 positionProp = vertical ?
5724 ( parentPosition.top !== '' ? 'top' : 'bottom' ) :
5725 ( parentPosition.left !== '' ? 'left' : 'right' );
5726
5727 // Figure out where the near and far edges of the popup and $floatableContainer are
5728 floatablePos = this.$floatableContainer.offset();
5729 floatablePos[ far ] = floatablePos[ near ] + this.$floatableContainer[ 'outer' + sizeProp ]();
5730 // Measure where the offsetParent is and compute our position based on that and parentPosition
5731 offsetParentPos = this.$element.offsetParent()[ 0 ] === document.documentElement ?
5732 { top: 0, left: 0 } :
5733 this.$element.offsetParent().offset();
5734
5735 if ( positionProp === near ) {
5736 popupPos[ near ] = offsetParentPos[ near ] + parentPosition[ near ];
5737 popupPos[ far ] = popupPos[ near ] + popupSize;
5738 } else {
5739 popupPos[ far ] = offsetParentPos[ near ] +
5740 this.$element.offsetParent()[ 'inner' + sizeProp ]() - parentPosition[ far ];
5741 popupPos[ near ] = popupPos[ far ] - popupSize;
5742 }
5743
5744 if ( this.anchored ) {
5745 // Position the anchor (which is positioned relative to the popup) to point to $floatableContainer
5746 anchorPos = ( floatablePos[ start ] + floatablePos[ end ] ) / 2;
5747 anchorOffset = ( start === far ? -1 : 1 ) * ( anchorPos - popupPos[ start ] );
5748
5749 // If the anchor is less than 2*anchorSize from either edge, move the popup to make more space
5750 // this.$anchor.width()/height() returns 0 because of the CSS trickery we use, so use scrollWidth/Height
5751 anchorSize = this.$anchor[ 0 ][ 'scroll' + sizeProp ];
5752 anchorMargin = parseFloat( this.$anchor.css( 'margin-' + start ) );
5753 if ( anchorOffset + anchorMargin < 2 * anchorSize ) {
5754 // Not enough space for the anchor on the start side; pull the popup startwards
5755 positionAdjustment = ( positionProp === start ? -1 : 1 ) *
5756 ( 2 * anchorSize - ( anchorOffset + anchorMargin ) );
5757 } else if ( anchorOffset + anchorMargin > popupSize - 2 * anchorSize ) {
5758 // Not enough space for the anchor on the end side; pull the popup endwards
5759 positionAdjustment = ( positionProp === end ? -1 : 1 ) *
5760 ( anchorOffset + anchorMargin - ( popupSize - 2 * anchorSize ) );
5761 } else {
5762 positionAdjustment = 0;
5763 }
5764 } else {
5765 positionAdjustment = 0;
5766 }
5767
5768 // Check if the popup will go beyond the edge of this.$container
5769 containerPos = this.$container[ 0 ] === document.documentElement ?
5770 { top: 0, left: 0 } :
5771 this.$container.offset();
5772 containerPos[ far ] = containerPos[ near ] + this.$container[ 'inner' + sizeProp ]();
5773 if ( this.$container[ 0 ] === document.documentElement ) {
5774 viewportSpacing = OO.ui.getViewportSpacing();
5775 containerPos[ near ] += viewportSpacing[ near ];
5776 containerPos[ far ] -= viewportSpacing[ far ];
5777 }
5778 // Take into account how much the popup will move because of the adjustments we're going to make
5779 popupPos[ near ] += ( positionProp === near ? 1 : -1 ) * positionAdjustment;
5780 popupPos[ far ] += ( positionProp === near ? 1 : -1 ) * positionAdjustment;
5781 if ( containerPos[ near ] + this.containerPadding > popupPos[ near ] ) {
5782 // Popup goes beyond the near (left/top) edge, move it to the right/bottom
5783 positionAdjustment += ( positionProp === near ? 1 : -1 ) *
5784 ( containerPos[ near ] + this.containerPadding - popupPos[ near ] );
5785 } else if ( containerPos[ far ] - this.containerPadding < popupPos[ far ] ) {
5786 // Popup goes beyond the far (right/bottom) edge, move it to the left/top
5787 positionAdjustment += ( positionProp === far ? 1 : -1 ) *
5788 ( popupPos[ far ] - ( containerPos[ far ] - this.containerPadding ) );
5789 }
5790
5791 if ( this.anchored ) {
5792 // Adjust anchorOffset for positionAdjustment
5793 anchorOffset += ( positionProp === start ? -1 : 1 ) * positionAdjustment;
5794
5795 // Position the anchor
5796 anchorCss[ start ] = anchorOffset;
5797 this.$anchor.css( anchorCss );
5798 }
5799
5800 // Move the popup if needed
5801 parentPosition[ positionProp ] += positionAdjustment;
5802
5803 return parentPosition;
5804 };
5805
5806 /**
5807 * Set popup alignment
5808 *
5809 * @param {string} [align=center] Alignment of the popup, `center`, `force-left`, `force-right`,
5810 * `backwards` or `forwards`.
5811 */
5812 OO.ui.PopupWidget.prototype.setAlignment = function ( align ) {
5813 // Validate alignment
5814 if ( [ 'force-left', 'force-right', 'backwards', 'forwards', 'center' ].indexOf( align ) > -1 ) {
5815 this.align = align;
5816 } else {
5817 this.align = 'center';
5818 }
5819 this.position();
5820 };
5821
5822 /**
5823 * Get popup alignment
5824 *
5825 * @return {string} Alignment of the popup, `center`, `force-left`, `force-right`,
5826 * `backwards` or `forwards`.
5827 */
5828 OO.ui.PopupWidget.prototype.getAlignment = function () {
5829 return this.align;
5830 };
5831
5832 /**
5833 * Change the positioning of the popup.
5834 *
5835 * @param {string} position 'above', 'below', 'before' or 'after'
5836 */
5837 OO.ui.PopupWidget.prototype.setPosition = function ( position ) {
5838 if ( [ 'above', 'below', 'before', 'after' ].indexOf( position ) === -1 ) {
5839 position = 'below';
5840 }
5841 this.popupPosition = position;
5842 this.position();
5843 };
5844
5845 /**
5846 * Get popup positioning.
5847 *
5848 * @return {string} 'above', 'below', 'before' or 'after'
5849 */
5850 OO.ui.PopupWidget.prototype.getPosition = function () {
5851 return this.popupPosition;
5852 };
5853
5854 /**
5855 * Set popup auto-flipping.
5856 *
5857 * @param {boolean} autoFlip Whether to automatically switch the popup's position between
5858 * 'above' and 'below', or between 'before' and 'after', if there is not enough space in the
5859 * desired direction to display the popup without clipping
5860 */
5861 OO.ui.PopupWidget.prototype.setAutoFlip = function ( autoFlip ) {
5862 autoFlip = !!autoFlip;
5863
5864 if ( this.autoFlip !== autoFlip ) {
5865 this.autoFlip = autoFlip;
5866 }
5867 };
5868
5869 /**
5870 * Set which elements will not close the popup when clicked.
5871 *
5872 * For auto-closing popups, clicks on these elements will not cause the popup to auto-close.
5873 *
5874 * @param {jQuery} $autoCloseIgnore Elements to ignore for auto-closing
5875 */
5876 OO.ui.PopupWidget.prototype.setAutoCloseIgnore = function ( $autoCloseIgnore ) {
5877 this.$autoCloseIgnore = $autoCloseIgnore;
5878 };
5879
5880 /**
5881 * Get an ID of the body element, this can be used as the
5882 * `aria-describedby` attribute for an input field.
5883 *
5884 * @return {string} The ID of the body element
5885 */
5886 OO.ui.PopupWidget.prototype.getBodyId = function () {
5887 var id = this.$body.attr( 'id' );
5888 if ( id === undefined ) {
5889 id = OO.ui.generateElementId();
5890 this.$body.attr( 'id', id );
5891 }
5892 return id;
5893 };
5894
5895 /**
5896 * PopupElement is mixed into other classes to generate a {@link OO.ui.PopupWidget popup widget}.
5897 * A popup is a container for content. It is overlaid and positioned absolutely. By default, each
5898 * popup has an anchor, which is an arrow-like protrusion that points toward the popup’s origin.
5899 * See {@link OO.ui.PopupWidget PopupWidget} for an example.
5900 *
5901 * @abstract
5902 * @class
5903 *
5904 * @constructor
5905 * @param {Object} [config] Configuration options
5906 * @cfg {Object} [popup] Configuration to pass to popup
5907 * @cfg {boolean} [popup.autoClose=true] Popup auto-closes when it loses focus
5908 */
5909 OO.ui.mixin.PopupElement = function OoUiMixinPopupElement( config ) {
5910 // Configuration initialization
5911 config = config || {};
5912
5913 // Properties
5914 this.popup = new OO.ui.PopupWidget( $.extend(
5915 {
5916 autoClose: true,
5917 $floatableContainer: this.$element
5918 },
5919 config.popup,
5920 {
5921 $autoCloseIgnore: this.$element.add( config.popup && config.popup.$autoCloseIgnore )
5922 }
5923 ) );
5924 };
5925
5926 /* Methods */
5927
5928 /**
5929 * Get popup.
5930 *
5931 * @return {OO.ui.PopupWidget} Popup widget
5932 */
5933 OO.ui.mixin.PopupElement.prototype.getPopup = function () {
5934 return this.popup;
5935 };
5936
5937 /**
5938 * PopupButtonWidgets toggle the visibility of a contained {@link OO.ui.PopupWidget PopupWidget},
5939 * which is used to display additional information or options.
5940 *
5941 * @example
5942 * // Example of a popup button.
5943 * var popupButton = new OO.ui.PopupButtonWidget( {
5944 * label: 'Popup button with options',
5945 * icon: 'menu',
5946 * popup: {
5947 * $content: $( '<p>Additional options here.</p>' ),
5948 * padded: true,
5949 * align: 'force-left'
5950 * }
5951 * } );
5952 * // Append the button to the DOM.
5953 * $( 'body' ).append( popupButton.$element );
5954 *
5955 * @class
5956 * @extends OO.ui.ButtonWidget
5957 * @mixins OO.ui.mixin.PopupElement
5958 *
5959 * @constructor
5960 * @param {Object} [config] Configuration options
5961 * @cfg {jQuery} [$overlay] Render the popup into a separate layer. This configuration is useful in cases where
5962 * the expanded popup is larger than its containing `<div>`. The specified overlay layer is usually on top of the
5963 * containing `<div>` and has a larger area. By default, the popup uses relative positioning.
5964 * See <https://www.mediawiki.org/wiki/OOUI/Concepts#Overlays>.
5965 */
5966 OO.ui.PopupButtonWidget = function OoUiPopupButtonWidget( config ) {
5967 // Configuration initialization
5968 config = config || {};
5969
5970 // Parent constructor
5971 OO.ui.PopupButtonWidget.parent.call( this, config );
5972
5973 // Mixin constructors
5974 OO.ui.mixin.PopupElement.call( this, config );
5975
5976 // Properties
5977 this.$overlay = ( config.$overlay === true ? OO.ui.getDefaultOverlay() : config.$overlay ) || this.$element;
5978
5979 // Events
5980 this.connect( this, { click: 'onAction' } );
5981
5982 // Initialization
5983 this.$element
5984 .addClass( 'oo-ui-popupButtonWidget' );
5985 this.popup.$element
5986 .addClass( 'oo-ui-popupButtonWidget-popup' )
5987 .toggleClass( 'oo-ui-popupButtonWidget-framed-popup', this.isFramed() )
5988 .toggleClass( 'oo-ui-popupButtonWidget-frameless-popup', !this.isFramed() );
5989 this.$overlay.append( this.popup.$element );
5990 };
5991
5992 /* Setup */
5993
5994 OO.inheritClass( OO.ui.PopupButtonWidget, OO.ui.ButtonWidget );
5995 OO.mixinClass( OO.ui.PopupButtonWidget, OO.ui.mixin.PopupElement );
5996
5997 /* Methods */
5998
5999 /**
6000 * Handle the button action being triggered.
6001 *
6002 * @private
6003 */
6004 OO.ui.PopupButtonWidget.prototype.onAction = function () {
6005 this.popup.toggle();
6006 };
6007
6008 /**
6009 * Mixin for OO.ui.Widget subclasses to provide OO.ui.mixin.GroupElement.
6010 *
6011 * Use together with OO.ui.mixin.ItemWidget to make disabled state inheritable.
6012 *
6013 * @private
6014 * @abstract
6015 * @class
6016 * @mixins OO.ui.mixin.GroupElement
6017 *
6018 * @constructor
6019 * @param {Object} [config] Configuration options
6020 */
6021 OO.ui.mixin.GroupWidget = function OoUiMixinGroupWidget( config ) {
6022 // Mixin constructors
6023 OO.ui.mixin.GroupElement.call( this, config );
6024 };
6025
6026 /* Setup */
6027
6028 OO.mixinClass( OO.ui.mixin.GroupWidget, OO.ui.mixin.GroupElement );
6029
6030 /* Methods */
6031
6032 /**
6033 * Set the disabled state of the widget.
6034 *
6035 * This will also update the disabled state of child widgets.
6036 *
6037 * @param {boolean} disabled Disable widget
6038 * @chainable
6039 * @return {OO.ui.Widget} The widget, for chaining
6040 */
6041 OO.ui.mixin.GroupWidget.prototype.setDisabled = function ( disabled ) {
6042 var i, len;
6043
6044 // Parent method
6045 // Note: Calling #setDisabled this way assumes this is mixed into an OO.ui.Widget
6046 OO.ui.Widget.prototype.setDisabled.call( this, disabled );
6047
6048 // During construction, #setDisabled is called before the OO.ui.mixin.GroupElement constructor
6049 if ( this.items ) {
6050 for ( i = 0, len = this.items.length; i < len; i++ ) {
6051 this.items[ i ].updateDisabled();
6052 }
6053 }
6054
6055 return this;
6056 };
6057
6058 /**
6059 * Mixin for widgets used as items in widgets that mix in OO.ui.mixin.GroupWidget.
6060 *
6061 * Item widgets have a reference to a OO.ui.mixin.GroupWidget while they are attached to the group. This
6062 * allows bidirectional communication.
6063 *
6064 * Use together with OO.ui.mixin.GroupWidget to make disabled state inheritable.
6065 *
6066 * @private
6067 * @abstract
6068 * @class
6069 *
6070 * @constructor
6071 */
6072 OO.ui.mixin.ItemWidget = function OoUiMixinItemWidget() {
6073 //
6074 };
6075
6076 /* Methods */
6077
6078 /**
6079 * Check if widget is disabled.
6080 *
6081 * Checks parent if present, making disabled state inheritable.
6082 *
6083 * @return {boolean} Widget is disabled
6084 */
6085 OO.ui.mixin.ItemWidget.prototype.isDisabled = function () {
6086 return this.disabled ||
6087 ( this.elementGroup instanceof OO.ui.Widget && this.elementGroup.isDisabled() );
6088 };
6089
6090 /**
6091 * Set group element is in.
6092 *
6093 * @param {OO.ui.mixin.GroupElement|null} group Group element, null if none
6094 * @chainable
6095 * @return {OO.ui.Widget} The widget, for chaining
6096 */
6097 OO.ui.mixin.ItemWidget.prototype.setElementGroup = function ( group ) {
6098 // Parent method
6099 // Note: Calling #setElementGroup this way assumes this is mixed into an OO.ui.Element
6100 OO.ui.Element.prototype.setElementGroup.call( this, group );
6101
6102 // Initialize item disabled states
6103 this.updateDisabled();
6104
6105 return this;
6106 };
6107
6108 /**
6109 * OptionWidgets are special elements that can be selected and configured with data. The
6110 * data is often unique for each option, but it does not have to be. OptionWidgets are used
6111 * with OO.ui.SelectWidget to create a selection of mutually exclusive options. For more information
6112 * and examples, please see the [OOUI documentation on MediaWiki][1].
6113 *
6114 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options
6115 *
6116 * @class
6117 * @extends OO.ui.Widget
6118 * @mixins OO.ui.mixin.ItemWidget
6119 * @mixins OO.ui.mixin.LabelElement
6120 * @mixins OO.ui.mixin.FlaggedElement
6121 * @mixins OO.ui.mixin.AccessKeyedElement
6122 *
6123 * @constructor
6124 * @param {Object} [config] Configuration options
6125 */
6126 OO.ui.OptionWidget = function OoUiOptionWidget( config ) {
6127 // Configuration initialization
6128 config = config || {};
6129
6130 // Parent constructor
6131 OO.ui.OptionWidget.parent.call( this, config );
6132
6133 // Mixin constructors
6134 OO.ui.mixin.ItemWidget.call( this );
6135 OO.ui.mixin.LabelElement.call( this, config );
6136 OO.ui.mixin.FlaggedElement.call( this, config );
6137 OO.ui.mixin.AccessKeyedElement.call( this, config );
6138
6139 // Properties
6140 this.selected = false;
6141 this.highlighted = false;
6142 this.pressed = false;
6143
6144 // Initialization
6145 this.$element
6146 .data( 'oo-ui-optionWidget', this )
6147 // Allow programmatic focussing (and by accesskey), but not tabbing
6148 .attr( 'tabindex', '-1' )
6149 .attr( 'role', 'option' )
6150 .attr( 'aria-selected', 'false' )
6151 .addClass( 'oo-ui-optionWidget' )
6152 .append( this.$label );
6153 };
6154
6155 /* Setup */
6156
6157 OO.inheritClass( OO.ui.OptionWidget, OO.ui.Widget );
6158 OO.mixinClass( OO.ui.OptionWidget, OO.ui.mixin.ItemWidget );
6159 OO.mixinClass( OO.ui.OptionWidget, OO.ui.mixin.LabelElement );
6160 OO.mixinClass( OO.ui.OptionWidget, OO.ui.mixin.FlaggedElement );
6161 OO.mixinClass( OO.ui.OptionWidget, OO.ui.mixin.AccessKeyedElement );
6162
6163 /* Static Properties */
6164
6165 /**
6166 * Whether this option can be selected. See #setSelected.
6167 *
6168 * @static
6169 * @inheritable
6170 * @property {boolean}
6171 */
6172 OO.ui.OptionWidget.static.selectable = true;
6173
6174 /**
6175 * Whether this option can be highlighted. See #setHighlighted.
6176 *
6177 * @static
6178 * @inheritable
6179 * @property {boolean}
6180 */
6181 OO.ui.OptionWidget.static.highlightable = true;
6182
6183 /**
6184 * Whether this option can be pressed. See #setPressed.
6185 *
6186 * @static
6187 * @inheritable
6188 * @property {boolean}
6189 */
6190 OO.ui.OptionWidget.static.pressable = true;
6191
6192 /**
6193 * Whether this option will be scrolled into view when it is selected.
6194 *
6195 * @static
6196 * @inheritable
6197 * @property {boolean}
6198 */
6199 OO.ui.OptionWidget.static.scrollIntoViewOnSelect = false;
6200
6201 /* Methods */
6202
6203 /**
6204 * Check if the option can be selected.
6205 *
6206 * @return {boolean} Item is selectable
6207 */
6208 OO.ui.OptionWidget.prototype.isSelectable = function () {
6209 return this.constructor.static.selectable && !this.disabled && this.isVisible();
6210 };
6211
6212 /**
6213 * Check if the option can be highlighted. A highlight indicates that the option
6214 * may be selected when a user presses enter or clicks. Disabled items cannot
6215 * be highlighted.
6216 *
6217 * @return {boolean} Item is highlightable
6218 */
6219 OO.ui.OptionWidget.prototype.isHighlightable = function () {
6220 return this.constructor.static.highlightable && !this.disabled && this.isVisible();
6221 };
6222
6223 /**
6224 * Check if the option can be pressed. The pressed state occurs when a user mouses
6225 * down on an item, but has not yet let go of the mouse.
6226 *
6227 * @return {boolean} Item is pressable
6228 */
6229 OO.ui.OptionWidget.prototype.isPressable = function () {
6230 return this.constructor.static.pressable && !this.disabled && this.isVisible();
6231 };
6232
6233 /**
6234 * Check if the option is selected.
6235 *
6236 * @return {boolean} Item is selected
6237 */
6238 OO.ui.OptionWidget.prototype.isSelected = function () {
6239 return this.selected;
6240 };
6241
6242 /**
6243 * Check if the option is highlighted. A highlight indicates that the
6244 * item may be selected when a user presses enter or clicks.
6245 *
6246 * @return {boolean} Item is highlighted
6247 */
6248 OO.ui.OptionWidget.prototype.isHighlighted = function () {
6249 return this.highlighted;
6250 };
6251
6252 /**
6253 * Check if the option is pressed. The pressed state occurs when a user mouses
6254 * down on an item, but has not yet let go of the mouse. The item may appear
6255 * selected, but it will not be selected until the user releases the mouse.
6256 *
6257 * @return {boolean} Item is pressed
6258 */
6259 OO.ui.OptionWidget.prototype.isPressed = function () {
6260 return this.pressed;
6261 };
6262
6263 /**
6264 * Set the option’s selected state. In general, all modifications to the selection
6265 * should be handled by the SelectWidget’s {@link OO.ui.SelectWidget#selectItem selectItem( [item] )}
6266 * method instead of this method.
6267 *
6268 * @param {boolean} [state=false] Select option
6269 * @chainable
6270 * @return {OO.ui.Widget} The widget, for chaining
6271 */
6272 OO.ui.OptionWidget.prototype.setSelected = function ( state ) {
6273 if ( this.constructor.static.selectable ) {
6274 this.selected = !!state;
6275 this.$element
6276 .toggleClass( 'oo-ui-optionWidget-selected', state )
6277 .attr( 'aria-selected', state.toString() );
6278 if ( state && this.constructor.static.scrollIntoViewOnSelect ) {
6279 this.scrollElementIntoView();
6280 }
6281 this.updateThemeClasses();
6282 }
6283 return this;
6284 };
6285
6286 /**
6287 * Set the option’s highlighted state. In general, all programmatic
6288 * modifications to the highlight should be handled by the
6289 * SelectWidget’s {@link OO.ui.SelectWidget#highlightItem highlightItem( [item] )}
6290 * method instead of this method.
6291 *
6292 * @param {boolean} [state=false] Highlight option
6293 * @chainable
6294 * @return {OO.ui.Widget} The widget, for chaining
6295 */
6296 OO.ui.OptionWidget.prototype.setHighlighted = function ( state ) {
6297 if ( this.constructor.static.highlightable ) {
6298 this.highlighted = !!state;
6299 this.$element.toggleClass( 'oo-ui-optionWidget-highlighted', state );
6300 this.updateThemeClasses();
6301 }
6302 return this;
6303 };
6304
6305 /**
6306 * Set the option’s pressed state. In general, all
6307 * programmatic modifications to the pressed state should be handled by the
6308 * SelectWidget’s {@link OO.ui.SelectWidget#pressItem pressItem( [item] )}
6309 * method instead of this method.
6310 *
6311 * @param {boolean} [state=false] Press option
6312 * @chainable
6313 * @return {OO.ui.Widget} The widget, for chaining
6314 */
6315 OO.ui.OptionWidget.prototype.setPressed = function ( state ) {
6316 if ( this.constructor.static.pressable ) {
6317 this.pressed = !!state;
6318 this.$element.toggleClass( 'oo-ui-optionWidget-pressed', state );
6319 this.updateThemeClasses();
6320 }
6321 return this;
6322 };
6323
6324 /**
6325 * Get text to match search strings against.
6326 *
6327 * The default implementation returns the label text, but subclasses
6328 * can override this to provide more complex behavior.
6329 *
6330 * @return {string|boolean} String to match search string against
6331 */
6332 OO.ui.OptionWidget.prototype.getMatchText = function () {
6333 var label = this.getLabel();
6334 return typeof label === 'string' ? label : this.$label.text();
6335 };
6336
6337 /**
6338 * A SelectWidget is of a generic selection of options. The OOUI library contains several types of
6339 * select widgets, including {@link OO.ui.ButtonSelectWidget button selects},
6340 * {@link OO.ui.RadioSelectWidget radio selects}, and {@link OO.ui.MenuSelectWidget
6341 * menu selects}.
6342 *
6343 * This class should be used together with OO.ui.OptionWidget or OO.ui.DecoratedOptionWidget. For more
6344 * information, please see the [OOUI documentation on MediaWiki][1].
6345 *
6346 * @example
6347 * // Example of a select widget with three options
6348 * var select = new OO.ui.SelectWidget( {
6349 * items: [
6350 * new OO.ui.OptionWidget( {
6351 * data: 'a',
6352 * label: 'Option One',
6353 * } ),
6354 * new OO.ui.OptionWidget( {
6355 * data: 'b',
6356 * label: 'Option Two',
6357 * } ),
6358 * new OO.ui.OptionWidget( {
6359 * data: 'c',
6360 * label: 'Option Three',
6361 * } )
6362 * ]
6363 * } );
6364 * $( 'body' ).append( select.$element );
6365 *
6366 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options
6367 *
6368 * @abstract
6369 * @class
6370 * @extends OO.ui.Widget
6371 * @mixins OO.ui.mixin.GroupWidget
6372 *
6373 * @constructor
6374 * @param {Object} [config] Configuration options
6375 * @cfg {OO.ui.OptionWidget[]} [items] An array of options to add to the select.
6376 * Options are created with {@link OO.ui.OptionWidget OptionWidget} classes. See
6377 * the [OOUI documentation on MediaWiki] [2] for examples.
6378 * [2]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options
6379 */
6380 OO.ui.SelectWidget = function OoUiSelectWidget( config ) {
6381 // Configuration initialization
6382 config = config || {};
6383
6384 // Parent constructor
6385 OO.ui.SelectWidget.parent.call( this, config );
6386
6387 // Mixin constructors
6388 OO.ui.mixin.GroupWidget.call( this, $.extend( {}, config, { $group: this.$element } ) );
6389
6390 // Properties
6391 this.pressed = false;
6392 this.selecting = null;
6393 this.onDocumentMouseUpHandler = this.onDocumentMouseUp.bind( this );
6394 this.onDocumentMouseMoveHandler = this.onDocumentMouseMove.bind( this );
6395 this.onDocumentKeyDownHandler = this.onDocumentKeyDown.bind( this );
6396 this.onDocumentKeyPressHandler = this.onDocumentKeyPress.bind( this );
6397 this.keyPressBuffer = '';
6398 this.keyPressBufferTimer = null;
6399 this.blockMouseOverEvents = 0;
6400
6401 // Events
6402 this.connect( this, {
6403 toggle: 'onToggle'
6404 } );
6405 this.$element.on( {
6406 focusin: this.onFocus.bind( this ),
6407 mousedown: this.onMouseDown.bind( this ),
6408 mouseover: this.onMouseOver.bind( this ),
6409 mouseleave: this.onMouseLeave.bind( this )
6410 } );
6411
6412 // Initialization
6413 this.$element
6414 .addClass( 'oo-ui-selectWidget oo-ui-selectWidget-depressed' )
6415 .attr( 'role', 'listbox' );
6416 this.setFocusOwner( this.$element );
6417 if ( Array.isArray( config.items ) ) {
6418 this.addItems( config.items );
6419 }
6420 };
6421
6422 /* Setup */
6423
6424 OO.inheritClass( OO.ui.SelectWidget, OO.ui.Widget );
6425 OO.mixinClass( OO.ui.SelectWidget, OO.ui.mixin.GroupWidget );
6426
6427 /* Events */
6428
6429 /**
6430 * @event highlight
6431 *
6432 * A `highlight` event is emitted when the highlight is changed with the #highlightItem method.
6433 *
6434 * @param {OO.ui.OptionWidget|null} item Highlighted item
6435 */
6436
6437 /**
6438 * @event press
6439 *
6440 * A `press` event is emitted when the #pressItem method is used to programmatically modify the
6441 * pressed state of an option.
6442 *
6443 * @param {OO.ui.OptionWidget|null} item Pressed item
6444 */
6445
6446 /**
6447 * @event select
6448 *
6449 * A `select` event is emitted when the selection is modified programmatically with the #selectItem method.
6450 *
6451 * @param {OO.ui.OptionWidget|null} item Selected item
6452 */
6453
6454 /**
6455 * @event choose
6456 * A `choose` event is emitted when an item is chosen with the #chooseItem method.
6457 * @param {OO.ui.OptionWidget} item Chosen item
6458 */
6459
6460 /**
6461 * @event add
6462 *
6463 * An `add` event is emitted when options are added to the select with the #addItems method.
6464 *
6465 * @param {OO.ui.OptionWidget[]} items Added items
6466 * @param {number} index Index of insertion point
6467 */
6468
6469 /**
6470 * @event remove
6471 *
6472 * A `remove` event is emitted when options are removed from the select with the #clearItems
6473 * or #removeItems methods.
6474 *
6475 * @param {OO.ui.OptionWidget[]} items Removed items
6476 */
6477
6478 /* Methods */
6479
6480 /**
6481 * Handle focus events
6482 *
6483 * @private
6484 * @param {jQuery.Event} event
6485 */
6486 OO.ui.SelectWidget.prototype.onFocus = function ( event ) {
6487 var item;
6488 if ( event.target === this.$element[ 0 ] ) {
6489 // This widget was focussed, e.g. by the user tabbing to it.
6490 // The styles for focus state depend on one of the items being selected.
6491 if ( !this.findSelectedItem() ) {
6492 item = this.findFirstSelectableItem();
6493 }
6494 } else {
6495 if ( event.target.tabIndex === -1 ) {
6496 // One of the options got focussed (and the event bubbled up here).
6497 // They can't be tabbed to, but they can be activated using accesskeys.
6498 // OptionWidgets and focusable UI elements inside them have tabindex="-1" set.
6499 item = this.findTargetItem( event );
6500 } else {
6501 // There is something actually user-focusable in one of the labels of the options, and the
6502 // user focussed it (e.g. by tabbing to it). Do nothing (especially, don't change the focus).
6503 return;
6504 }
6505 }
6506
6507 if ( item ) {
6508 if ( item.constructor.static.highlightable ) {
6509 this.highlightItem( item );
6510 } else {
6511 this.selectItem( item );
6512 }
6513 }
6514
6515 if ( event.target !== this.$element[ 0 ] ) {
6516 this.$focusOwner.focus();
6517 }
6518 };
6519
6520 /**
6521 * Handle mouse down events.
6522 *
6523 * @private
6524 * @param {jQuery.Event} e Mouse down event
6525 * @return {undefined/boolean} False to prevent default if event is handled
6526 */
6527 OO.ui.SelectWidget.prototype.onMouseDown = function ( e ) {
6528 var item;
6529
6530 if ( !this.isDisabled() && e.which === OO.ui.MouseButtons.LEFT ) {
6531 this.togglePressed( true );
6532 item = this.findTargetItem( e );
6533 if ( item && item.isSelectable() ) {
6534 this.pressItem( item );
6535 this.selecting = item;
6536 this.getElementDocument().addEventListener( 'mouseup', this.onDocumentMouseUpHandler, true );
6537 this.getElementDocument().addEventListener( 'mousemove', this.onDocumentMouseMoveHandler, true );
6538 }
6539 }
6540 return false;
6541 };
6542
6543 /**
6544 * Handle document mouse up events.
6545 *
6546 * @private
6547 * @param {MouseEvent} e Mouse up event
6548 * @return {undefined/boolean} False to prevent default if event is handled
6549 */
6550 OO.ui.SelectWidget.prototype.onDocumentMouseUp = function ( e ) {
6551 var item;
6552
6553 this.togglePressed( false );
6554 if ( !this.selecting ) {
6555 item = this.findTargetItem( e );
6556 if ( item && item.isSelectable() ) {
6557 this.selecting = item;
6558 }
6559 }
6560 if ( !this.isDisabled() && e.which === OO.ui.MouseButtons.LEFT && this.selecting ) {
6561 this.pressItem( null );
6562 this.chooseItem( this.selecting );
6563 this.selecting = null;
6564 }
6565
6566 this.getElementDocument().removeEventListener( 'mouseup', this.onDocumentMouseUpHandler, true );
6567 this.getElementDocument().removeEventListener( 'mousemove', this.onDocumentMouseMoveHandler, true );
6568
6569 return false;
6570 };
6571
6572 // Deprecated alias since 0.28.3
6573 OO.ui.SelectWidget.prototype.onMouseUp = function () {
6574 OO.ui.warnDeprecation( 'onMouseUp is deprecated, use onDocumentMouseUp instead' );
6575 this.onDocumentMouseUp.apply( this, arguments );
6576 };
6577
6578 /**
6579 * Handle document mouse move events.
6580 *
6581 * @private
6582 * @param {MouseEvent} e Mouse move event
6583 */
6584 OO.ui.SelectWidget.prototype.onDocumentMouseMove = function ( e ) {
6585 var item;
6586
6587 if ( !this.isDisabled() && this.pressed ) {
6588 item = this.findTargetItem( e );
6589 if ( item && item !== this.selecting && item.isSelectable() ) {
6590 this.pressItem( item );
6591 this.selecting = item;
6592 }
6593 }
6594 };
6595
6596 // Deprecated alias since 0.28.3
6597 OO.ui.SelectWidget.prototype.onMouseMove = function () {
6598 OO.ui.warnDeprecation( 'onMouseMove is deprecated, use onDocumentMouseMove instead' );
6599 this.onDocumentMouseMove.apply( this, arguments );
6600 };
6601
6602 /**
6603 * Handle mouse over events.
6604 *
6605 * @private
6606 * @param {jQuery.Event} e Mouse over event
6607 * @return {undefined/boolean} False to prevent default if event is handled
6608 */
6609 OO.ui.SelectWidget.prototype.onMouseOver = function ( e ) {
6610 var item;
6611 if ( this.blockMouseOverEvents ) {
6612 return;
6613 }
6614 if ( !this.isDisabled() ) {
6615 item = this.findTargetItem( e );
6616 this.highlightItem( item && item.isHighlightable() ? item : null );
6617 }
6618 return false;
6619 };
6620
6621 /**
6622 * Handle mouse leave events.
6623 *
6624 * @private
6625 * @param {jQuery.Event} e Mouse over event
6626 * @return {undefined/boolean} False to prevent default if event is handled
6627 */
6628 OO.ui.SelectWidget.prototype.onMouseLeave = function () {
6629 if ( !this.isDisabled() ) {
6630 this.highlightItem( null );
6631 }
6632 return false;
6633 };
6634
6635 /**
6636 * Handle document key down events.
6637 *
6638 * @protected
6639 * @param {KeyboardEvent} e Key down event
6640 */
6641 OO.ui.SelectWidget.prototype.onDocumentKeyDown = function ( e ) {
6642 var nextItem,
6643 handled = false,
6644 currentItem = this.findHighlightedItem() || this.findSelectedItem();
6645
6646 if ( !this.isDisabled() && this.isVisible() ) {
6647 switch ( e.keyCode ) {
6648 case OO.ui.Keys.ENTER:
6649 if ( currentItem && currentItem.constructor.static.highlightable ) {
6650 // Was only highlighted, now let's select it. No-op if already selected.
6651 this.chooseItem( currentItem );
6652 handled = true;
6653 }
6654 break;
6655 case OO.ui.Keys.UP:
6656 case OO.ui.Keys.LEFT:
6657 this.clearKeyPressBuffer();
6658 nextItem = this.findRelativeSelectableItem( currentItem, -1 );
6659 handled = true;
6660 break;
6661 case OO.ui.Keys.DOWN:
6662 case OO.ui.Keys.RIGHT:
6663 this.clearKeyPressBuffer();
6664 nextItem = this.findRelativeSelectableItem( currentItem, 1 );
6665 handled = true;
6666 break;
6667 case OO.ui.Keys.ESCAPE:
6668 case OO.ui.Keys.TAB:
6669 if ( currentItem && currentItem.constructor.static.highlightable ) {
6670 currentItem.setHighlighted( false );
6671 }
6672 this.unbindDocumentKeyDownListener();
6673 this.unbindDocumentKeyPressListener();
6674 // Don't prevent tabbing away / defocusing
6675 handled = false;
6676 break;
6677 }
6678
6679 if ( nextItem ) {
6680 if ( nextItem.constructor.static.highlightable ) {
6681 this.highlightItem( nextItem );
6682 } else {
6683 this.chooseItem( nextItem );
6684 }
6685 this.scrollItemIntoView( nextItem );
6686 }
6687
6688 if ( handled ) {
6689 e.preventDefault();
6690 e.stopPropagation();
6691 }
6692 }
6693 };
6694
6695 // Deprecated alias since 0.28.3
6696 OO.ui.SelectWidget.prototype.onKeyDown = function () {
6697 OO.ui.warnDeprecation( 'onKeyDown is deprecated, use onDocumentKeyDown instead' );
6698 this.onDocumentKeyDown.apply( this, arguments );
6699 };
6700
6701 /**
6702 * Bind document key down listener.
6703 *
6704 * @protected
6705 */
6706 OO.ui.SelectWidget.prototype.bindDocumentKeyDownListener = function () {
6707 this.getElementDocument().addEventListener( 'keydown', this.onDocumentKeyDownHandler, true );
6708 };
6709
6710 // Deprecated alias since 0.28.3
6711 OO.ui.SelectWidget.prototype.bindKeyDownListener = function () {
6712 OO.ui.warnDeprecation( 'bindKeyDownListener is deprecated, use bindDocumentKeyDownListener instead' );
6713 this.bindDocumentKeyDownListener.apply( this, arguments );
6714 };
6715
6716 /**
6717 * Unbind document key down listener.
6718 *
6719 * @protected
6720 */
6721 OO.ui.SelectWidget.prototype.unbindDocumentKeyDownListener = function () {
6722 this.getElementDocument().removeEventListener( 'keydown', this.onDocumentKeyDownHandler, true );
6723 };
6724
6725 // Deprecated alias since 0.28.3
6726 OO.ui.SelectWidget.prototype.unbindKeyDownListener = function () {
6727 OO.ui.warnDeprecation( 'unbindKeyDownListener is deprecated, use unbindDocumentKeyDownListener instead' );
6728 this.unbindDocumentKeyDownListener.apply( this, arguments );
6729 };
6730
6731 /**
6732 * Scroll item into view, preventing spurious mouse highlight actions from happening.
6733 *
6734 * @param {OO.ui.OptionWidget} item Item to scroll into view
6735 */
6736 OO.ui.SelectWidget.prototype.scrollItemIntoView = function ( item ) {
6737 var widget = this;
6738 // Chromium's Blink engine will generate spurious 'mouseover' events during programmatic scrolling
6739 // and around 100-150 ms after it is finished.
6740 this.blockMouseOverEvents++;
6741 item.scrollElementIntoView().done( function () {
6742 setTimeout( function () {
6743 widget.blockMouseOverEvents--;
6744 }, 200 );
6745 } );
6746 };
6747
6748 /**
6749 * Clear the key-press buffer
6750 *
6751 * @protected
6752 */
6753 OO.ui.SelectWidget.prototype.clearKeyPressBuffer = function () {
6754 if ( this.keyPressBufferTimer ) {
6755 clearTimeout( this.keyPressBufferTimer );
6756 this.keyPressBufferTimer = null;
6757 }
6758 this.keyPressBuffer = '';
6759 };
6760
6761 /**
6762 * Handle key press events.
6763 *
6764 * @protected
6765 * @param {KeyboardEvent} e Key press event
6766 * @return {undefined/boolean} False to prevent default if event is handled
6767 */
6768 OO.ui.SelectWidget.prototype.onDocumentKeyPress = function ( e ) {
6769 var c, filter, item;
6770
6771 if ( !e.charCode ) {
6772 if ( e.keyCode === OO.ui.Keys.BACKSPACE && this.keyPressBuffer !== '' ) {
6773 this.keyPressBuffer = this.keyPressBuffer.substr( 0, this.keyPressBuffer.length - 1 );
6774 return false;
6775 }
6776 return;
6777 }
6778 // eslint-disable-next-line no-restricted-properties
6779 if ( String.fromCodePoint ) {
6780 // eslint-disable-next-line no-restricted-properties
6781 c = String.fromCodePoint( e.charCode );
6782 } else {
6783 c = String.fromCharCode( e.charCode );
6784 }
6785
6786 if ( this.keyPressBufferTimer ) {
6787 clearTimeout( this.keyPressBufferTimer );
6788 }
6789 this.keyPressBufferTimer = setTimeout( this.clearKeyPressBuffer.bind( this ), 1500 );
6790
6791 item = this.findHighlightedItem() || this.findSelectedItem();
6792
6793 if ( this.keyPressBuffer === c ) {
6794 // Common (if weird) special case: typing "xxxx" will cycle through all
6795 // the items beginning with "x".
6796 if ( item ) {
6797 item = this.findRelativeSelectableItem( item, 1 );
6798 }
6799 } else {
6800 this.keyPressBuffer += c;
6801 }
6802
6803 filter = this.getItemMatcher( this.keyPressBuffer, false );
6804 if ( !item || !filter( item ) ) {
6805 item = this.findRelativeSelectableItem( item, 1, filter );
6806 }
6807 if ( item ) {
6808 if ( this.isVisible() && item.constructor.static.highlightable ) {
6809 this.highlightItem( item );
6810 } else {
6811 this.chooseItem( item );
6812 }
6813 this.scrollItemIntoView( item );
6814 }
6815
6816 e.preventDefault();
6817 e.stopPropagation();
6818 };
6819
6820 // Deprecated alias since 0.28.3
6821 OO.ui.SelectWidget.prototype.onKeyPress = function () {
6822 OO.ui.warnDeprecation( 'onKeyPress is deprecated, use onDocumentKeyPress instead' );
6823 this.onDocumentKeyPress.apply( this, arguments );
6824 };
6825
6826 /**
6827 * Get a matcher for the specific string
6828 *
6829 * @protected
6830 * @param {string} s String to match against items
6831 * @param {boolean} [exact=false] Only accept exact matches
6832 * @return {Function} function ( OO.ui.OptionWidget ) => boolean
6833 */
6834 OO.ui.SelectWidget.prototype.getItemMatcher = function ( s, exact ) {
6835 var re;
6836
6837 // eslint-disable-next-line no-restricted-properties
6838 if ( s.normalize ) {
6839 // eslint-disable-next-line no-restricted-properties
6840 s = s.normalize();
6841 }
6842 s = exact ? s.trim() : s.replace( /^\s+/, '' );
6843 re = '^\\s*' + s.replace( /([\\{}()|.?*+\-^$[\]])/g, '\\$1' ).replace( /\s+/g, '\\s+' );
6844 if ( exact ) {
6845 re += '\\s*$';
6846 }
6847 re = new RegExp( re, 'i' );
6848 return function ( item ) {
6849 var matchText = item.getMatchText();
6850 // eslint-disable-next-line no-restricted-properties
6851 if ( matchText.normalize ) {
6852 // eslint-disable-next-line no-restricted-properties
6853 matchText = matchText.normalize();
6854 }
6855 return re.test( matchText );
6856 };
6857 };
6858
6859 /**
6860 * Bind document key press listener.
6861 *
6862 * @protected
6863 */
6864 OO.ui.SelectWidget.prototype.bindDocumentKeyPressListener = function () {
6865 this.getElementDocument().addEventListener( 'keypress', this.onDocumentKeyPressHandler, true );
6866 };
6867
6868 // Deprecated alias since 0.28.3
6869 OO.ui.SelectWidget.prototype.bindKeyPressListener = function () {
6870 OO.ui.warnDeprecation( 'bindKeyPressListener is deprecated, use bindDocumentKeyPressListener instead' );
6871 this.bindDocumentKeyPressListener.apply( this, arguments );
6872 };
6873
6874 /**
6875 * Unbind document key down listener.
6876 *
6877 * If you override this, be sure to call this.clearKeyPressBuffer() from your
6878 * implementation.
6879 *
6880 * @protected
6881 */
6882 OO.ui.SelectWidget.prototype.unbindDocumentKeyPressListener = function () {
6883 this.getElementDocument().removeEventListener( 'keypress', this.onDocumentKeyPressHandler, true );
6884 this.clearKeyPressBuffer();
6885 };
6886
6887 // Deprecated alias since 0.28.3
6888 OO.ui.SelectWidget.prototype.unbindKeyPressListener = function () {
6889 OO.ui.warnDeprecation( 'unbindKeyPressListener is deprecated, use unbindDocumentKeyPressListener instead' );
6890 this.unbindDocumentKeyPressListener.apply( this, arguments );
6891 };
6892
6893 /**
6894 * Visibility change handler
6895 *
6896 * @protected
6897 * @param {boolean} visible
6898 */
6899 OO.ui.SelectWidget.prototype.onToggle = function ( visible ) {
6900 if ( !visible ) {
6901 this.clearKeyPressBuffer();
6902 }
6903 };
6904
6905 /**
6906 * Get the closest item to a jQuery.Event.
6907 *
6908 * @private
6909 * @param {jQuery.Event} e
6910 * @return {OO.ui.OptionWidget|null} Outline item widget, `null` if none was found
6911 */
6912 OO.ui.SelectWidget.prototype.findTargetItem = function ( e ) {
6913 var $option = $( e.target ).closest( '.oo-ui-optionWidget' );
6914 if ( !$option.closest( '.oo-ui-selectWidget' ).is( this.$element ) ) {
6915 return null;
6916 }
6917 return $option.data( 'oo-ui-optionWidget' ) || null;
6918 };
6919
6920 /**
6921 * Find selected item.
6922 *
6923 * @return {OO.ui.OptionWidget|null} Selected item, `null` if no item is selected
6924 */
6925 OO.ui.SelectWidget.prototype.findSelectedItem = function () {
6926 var i, len;
6927
6928 for ( i = 0, len = this.items.length; i < len; i++ ) {
6929 if ( this.items[ i ].isSelected() ) {
6930 return this.items[ i ];
6931 }
6932 }
6933 return null;
6934 };
6935
6936 /**
6937 * Find highlighted item.
6938 *
6939 * @return {OO.ui.OptionWidget|null} Highlighted item, `null` if no item is highlighted
6940 */
6941 OO.ui.SelectWidget.prototype.findHighlightedItem = function () {
6942 var i, len;
6943
6944 for ( i = 0, len = this.items.length; i < len; i++ ) {
6945 if ( this.items[ i ].isHighlighted() ) {
6946 return this.items[ i ];
6947 }
6948 }
6949 return null;
6950 };
6951
6952 /**
6953 * Toggle pressed state.
6954 *
6955 * Press is a state that occurs when a user mouses down on an item, but
6956 * has not yet let go of the mouse. The item may appear selected, but it will not be selected
6957 * until the user releases the mouse.
6958 *
6959 * @param {boolean} pressed An option is being pressed
6960 */
6961 OO.ui.SelectWidget.prototype.togglePressed = function ( pressed ) {
6962 if ( pressed === undefined ) {
6963 pressed = !this.pressed;
6964 }
6965 if ( pressed !== this.pressed ) {
6966 this.$element
6967 .toggleClass( 'oo-ui-selectWidget-pressed', pressed )
6968 .toggleClass( 'oo-ui-selectWidget-depressed', !pressed );
6969 this.pressed = pressed;
6970 }
6971 };
6972
6973 /**
6974 * Highlight an option. If the `item` param is omitted, no options will be highlighted
6975 * and any existing highlight will be removed. The highlight is mutually exclusive.
6976 *
6977 * @param {OO.ui.OptionWidget} [item] Item to highlight, omit for no highlight
6978 * @fires highlight
6979 * @chainable
6980 * @return {OO.ui.Widget} The widget, for chaining
6981 */
6982 OO.ui.SelectWidget.prototype.highlightItem = function ( item ) {
6983 var i, len, highlighted,
6984 changed = false;
6985
6986 for ( i = 0, len = this.items.length; i < len; i++ ) {
6987 highlighted = this.items[ i ] === item;
6988 if ( this.items[ i ].isHighlighted() !== highlighted ) {
6989 this.items[ i ].setHighlighted( highlighted );
6990 changed = true;
6991 }
6992 }
6993 if ( changed ) {
6994 if ( item ) {
6995 this.$focusOwner.attr( 'aria-activedescendant', item.getElementId() );
6996 } else {
6997 this.$focusOwner.removeAttr( 'aria-activedescendant' );
6998 }
6999 this.emit( 'highlight', item );
7000 }
7001
7002 return this;
7003 };
7004
7005 /**
7006 * Fetch an item by its label.
7007 *
7008 * @param {string} label Label of the item to select.
7009 * @param {boolean} [prefix=false] Allow a prefix match, if only a single item matches
7010 * @return {OO.ui.Element|null} Item with equivalent label, `null` if none exists
7011 */
7012 OO.ui.SelectWidget.prototype.getItemFromLabel = function ( label, prefix ) {
7013 var i, item, found,
7014 len = this.items.length,
7015 filter = this.getItemMatcher( label, true );
7016
7017 for ( i = 0; i < len; i++ ) {
7018 item = this.items[ i ];
7019 if ( item instanceof OO.ui.OptionWidget && item.isSelectable() && filter( item ) ) {
7020 return item;
7021 }
7022 }
7023
7024 if ( prefix ) {
7025 found = null;
7026 filter = this.getItemMatcher( label, false );
7027 for ( i = 0; i < len; i++ ) {
7028 item = this.items[ i ];
7029 if ( item instanceof OO.ui.OptionWidget && item.isSelectable() && filter( item ) ) {
7030 if ( found ) {
7031 return null;
7032 }
7033 found = item;
7034 }
7035 }
7036 if ( found ) {
7037 return found;
7038 }
7039 }
7040
7041 return null;
7042 };
7043
7044 /**
7045 * Programmatically select an option by its label. If the item does not exist,
7046 * all options will be deselected.
7047 *
7048 * @param {string} [label] Label of the item to select.
7049 * @param {boolean} [prefix=false] Allow a prefix match, if only a single item matches
7050 * @fires select
7051 * @chainable
7052 * @return {OO.ui.Widget} The widget, for chaining
7053 */
7054 OO.ui.SelectWidget.prototype.selectItemByLabel = function ( label, prefix ) {
7055 var itemFromLabel = this.getItemFromLabel( label, !!prefix );
7056 if ( label === undefined || !itemFromLabel ) {
7057 return this.selectItem();
7058 }
7059 return this.selectItem( itemFromLabel );
7060 };
7061
7062 /**
7063 * Programmatically select an option by its data. If the `data` parameter is omitted,
7064 * or if the item does not exist, all options will be deselected.
7065 *
7066 * @param {Object|string} [data] Value of the item to select, omit to deselect all
7067 * @fires select
7068 * @chainable
7069 * @return {OO.ui.Widget} The widget, for chaining
7070 */
7071 OO.ui.SelectWidget.prototype.selectItemByData = function ( data ) {
7072 var itemFromData = this.findItemFromData( data );
7073 if ( data === undefined || !itemFromData ) {
7074 return this.selectItem();
7075 }
7076 return this.selectItem( itemFromData );
7077 };
7078
7079 /**
7080 * Programmatically select an option by its reference. If the `item` parameter is omitted,
7081 * all options will be deselected.
7082 *
7083 * @param {OO.ui.OptionWidget} [item] Item to select, omit to deselect all
7084 * @fires select
7085 * @chainable
7086 * @return {OO.ui.Widget} The widget, for chaining
7087 */
7088 OO.ui.SelectWidget.prototype.selectItem = function ( item ) {
7089 var i, len, selected,
7090 changed = false;
7091
7092 for ( i = 0, len = this.items.length; i < len; i++ ) {
7093 selected = this.items[ i ] === item;
7094 if ( this.items[ i ].isSelected() !== selected ) {
7095 this.items[ i ].setSelected( selected );
7096 changed = true;
7097 }
7098 }
7099 if ( changed ) {
7100 if ( item && !item.constructor.static.highlightable ) {
7101 if ( item ) {
7102 this.$focusOwner.attr( 'aria-activedescendant', item.getElementId() );
7103 } else {
7104 this.$focusOwner.removeAttr( 'aria-activedescendant' );
7105 }
7106 }
7107 this.emit( 'select', item );
7108 }
7109
7110 return this;
7111 };
7112
7113 /**
7114 * Press an item.
7115 *
7116 * Press is a state that occurs when a user mouses down on an item, but has not
7117 * yet let go of the mouse. The item may appear selected, but it will not be selected until the user
7118 * releases the mouse.
7119 *
7120 * @param {OO.ui.OptionWidget} [item] Item to press, omit to depress all
7121 * @fires press
7122 * @chainable
7123 * @return {OO.ui.Widget} The widget, for chaining
7124 */
7125 OO.ui.SelectWidget.prototype.pressItem = function ( item ) {
7126 var i, len, pressed,
7127 changed = false;
7128
7129 for ( i = 0, len = this.items.length; i < len; i++ ) {
7130 pressed = this.items[ i ] === item;
7131 if ( this.items[ i ].isPressed() !== pressed ) {
7132 this.items[ i ].setPressed( pressed );
7133 changed = true;
7134 }
7135 }
7136 if ( changed ) {
7137 this.emit( 'press', item );
7138 }
7139
7140 return this;
7141 };
7142
7143 /**
7144 * Choose an item.
7145 *
7146 * Note that ‘choose’ should never be modified programmatically. A user can choose
7147 * an option with the keyboard or mouse and it becomes selected. To select an item programmatically,
7148 * use the #selectItem method.
7149 *
7150 * This method is identical to #selectItem, but may vary in subclasses that take additional action
7151 * when users choose an item with the keyboard or mouse.
7152 *
7153 * @param {OO.ui.OptionWidget} item Item to choose
7154 * @fires choose
7155 * @chainable
7156 * @return {OO.ui.Widget} The widget, for chaining
7157 */
7158 OO.ui.SelectWidget.prototype.chooseItem = function ( item ) {
7159 if ( item ) {
7160 this.selectItem( item );
7161 this.emit( 'choose', item );
7162 }
7163
7164 return this;
7165 };
7166
7167 /**
7168 * Find an option by its position relative to the specified item (or to the start of the option array,
7169 * if item is `null`). The direction in which to search through the option array is specified with a
7170 * number: -1 for reverse (the default) or 1 for forward. The method will return an option, or
7171 * `null` if there are no options in the array.
7172 *
7173 * @param {OO.ui.OptionWidget|null} item Item to describe the start position, or `null` to start at the beginning of the array.
7174 * @param {number} direction Direction to move in: -1 to move backward, 1 to move forward
7175 * @param {Function} [filter] Only consider items for which this function returns
7176 * true. Function takes an OO.ui.OptionWidget and returns a boolean.
7177 * @return {OO.ui.OptionWidget|null} Item at position, `null` if there are no items in the select
7178 */
7179 OO.ui.SelectWidget.prototype.findRelativeSelectableItem = function ( item, direction, filter ) {
7180 var currentIndex, nextIndex, i,
7181 increase = direction > 0 ? 1 : -1,
7182 len = this.items.length;
7183
7184 if ( item instanceof OO.ui.OptionWidget ) {
7185 currentIndex = this.items.indexOf( item );
7186 nextIndex = ( currentIndex + increase + len ) % len;
7187 } else {
7188 // If no item is selected and moving forward, start at the beginning.
7189 // If moving backward, start at the end.
7190 nextIndex = direction > 0 ? 0 : len - 1;
7191 }
7192
7193 for ( i = 0; i < len; i++ ) {
7194 item = this.items[ nextIndex ];
7195 if (
7196 item instanceof OO.ui.OptionWidget && item.isSelectable() &&
7197 ( !filter || filter( item ) )
7198 ) {
7199 return item;
7200 }
7201 nextIndex = ( nextIndex + increase + len ) % len;
7202 }
7203 return null;
7204 };
7205
7206 /**
7207 * Find the next selectable item or `null` if there are no selectable items.
7208 * Disabled options and menu-section markers and breaks are not selectable.
7209 *
7210 * @return {OO.ui.OptionWidget|null} Item, `null` if there aren't any selectable items
7211 */
7212 OO.ui.SelectWidget.prototype.findFirstSelectableItem = function () {
7213 return this.findRelativeSelectableItem( null, 1 );
7214 };
7215
7216 /**
7217 * Add an array of options to the select. Optionally, an index number can be used to
7218 * specify an insertion point.
7219 *
7220 * @param {OO.ui.OptionWidget[]} items Items to add
7221 * @param {number} [index] Index to insert items after
7222 * @fires add
7223 * @chainable
7224 * @return {OO.ui.Widget} The widget, for chaining
7225 */
7226 OO.ui.SelectWidget.prototype.addItems = function ( items, index ) {
7227 // Mixin method
7228 OO.ui.mixin.GroupWidget.prototype.addItems.call( this, items, index );
7229
7230 // Always provide an index, even if it was omitted
7231 this.emit( 'add', items, index === undefined ? this.items.length - items.length - 1 : index );
7232
7233 return this;
7234 };
7235
7236 /**
7237 * Remove the specified array of options from the select. Options will be detached
7238 * from the DOM, not removed, so they can be reused later. To remove all options from
7239 * the select, you may wish to use the #clearItems method instead.
7240 *
7241 * @param {OO.ui.OptionWidget[]} items Items to remove
7242 * @fires remove
7243 * @chainable
7244 * @return {OO.ui.Widget} The widget, for chaining
7245 */
7246 OO.ui.SelectWidget.prototype.removeItems = function ( items ) {
7247 var i, len, item;
7248
7249 // Deselect items being removed
7250 for ( i = 0, len = items.length; i < len; i++ ) {
7251 item = items[ i ];
7252 if ( item.isSelected() ) {
7253 this.selectItem( null );
7254 }
7255 }
7256
7257 // Mixin method
7258 OO.ui.mixin.GroupWidget.prototype.removeItems.call( this, items );
7259
7260 this.emit( 'remove', items );
7261
7262 return this;
7263 };
7264
7265 /**
7266 * Clear all options from the select. Options will be detached from the DOM, not removed,
7267 * so that they can be reused later. To remove a subset of options from the select, use
7268 * the #removeItems method.
7269 *
7270 * @fires remove
7271 * @chainable
7272 * @return {OO.ui.Widget} The widget, for chaining
7273 */
7274 OO.ui.SelectWidget.prototype.clearItems = function () {
7275 var items = this.items.slice();
7276
7277 // Mixin method
7278 OO.ui.mixin.GroupWidget.prototype.clearItems.call( this );
7279
7280 // Clear selection
7281 this.selectItem( null );
7282
7283 this.emit( 'remove', items );
7284
7285 return this;
7286 };
7287
7288 /**
7289 * Set the DOM element which has focus while the user is interacting with this SelectWidget.
7290 *
7291 * Currently this is just used to set `aria-activedescendant` on it.
7292 *
7293 * @protected
7294 * @param {jQuery} $focusOwner
7295 */
7296 OO.ui.SelectWidget.prototype.setFocusOwner = function ( $focusOwner ) {
7297 this.$focusOwner = $focusOwner;
7298 };
7299
7300 /**
7301 * DecoratedOptionWidgets are {@link OO.ui.OptionWidget options} that can be configured
7302 * with an {@link OO.ui.mixin.IconElement icon} and/or {@link OO.ui.mixin.IndicatorElement indicator}.
7303 * This class is used with OO.ui.SelectWidget to create a selection of mutually exclusive
7304 * options. For more information about options and selects, please see the
7305 * [OOUI documentation on MediaWiki][1].
7306 *
7307 * @example
7308 * // Decorated options in a select widget
7309 * var select = new OO.ui.SelectWidget( {
7310 * items: [
7311 * new OO.ui.DecoratedOptionWidget( {
7312 * data: 'a',
7313 * label: 'Option with icon',
7314 * icon: 'help'
7315 * } ),
7316 * new OO.ui.DecoratedOptionWidget( {
7317 * data: 'b',
7318 * label: 'Option with indicator',
7319 * indicator: 'next'
7320 * } )
7321 * ]
7322 * } );
7323 * $( 'body' ).append( select.$element );
7324 *
7325 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options
7326 *
7327 * @class
7328 * @extends OO.ui.OptionWidget
7329 * @mixins OO.ui.mixin.IconElement
7330 * @mixins OO.ui.mixin.IndicatorElement
7331 *
7332 * @constructor
7333 * @param {Object} [config] Configuration options
7334 */
7335 OO.ui.DecoratedOptionWidget = function OoUiDecoratedOptionWidget( config ) {
7336 // Parent constructor
7337 OO.ui.DecoratedOptionWidget.parent.call( this, config );
7338
7339 // Mixin constructors
7340 OO.ui.mixin.IconElement.call( this, config );
7341 OO.ui.mixin.IndicatorElement.call( this, config );
7342
7343 // Initialization
7344 this.$element
7345 .addClass( 'oo-ui-decoratedOptionWidget' )
7346 .prepend( this.$icon )
7347 .append( this.$indicator );
7348 };
7349
7350 /* Setup */
7351
7352 OO.inheritClass( OO.ui.DecoratedOptionWidget, OO.ui.OptionWidget );
7353 OO.mixinClass( OO.ui.DecoratedOptionWidget, OO.ui.mixin.IconElement );
7354 OO.mixinClass( OO.ui.DecoratedOptionWidget, OO.ui.mixin.IndicatorElement );
7355
7356 /**
7357 * MenuOptionWidget is an option widget that looks like a menu item. The class is used with
7358 * OO.ui.MenuSelectWidget to create a menu of mutually exclusive options. Please see
7359 * the [OOUI documentation on MediaWiki] [1] for more information.
7360 *
7361 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options#Menu_selects_and_options
7362 *
7363 * @class
7364 * @extends OO.ui.DecoratedOptionWidget
7365 *
7366 * @constructor
7367 * @param {Object} [config] Configuration options
7368 */
7369 OO.ui.MenuOptionWidget = function OoUiMenuOptionWidget( config ) {
7370 // Parent constructor
7371 OO.ui.MenuOptionWidget.parent.call( this, config );
7372
7373 // Properties
7374 this.checkIcon = new OO.ui.IconWidget( {
7375 icon: 'check',
7376 classes: [ 'oo-ui-menuOptionWidget-checkIcon' ]
7377 } );
7378
7379 // Initialization
7380 this.$element
7381 .prepend( this.checkIcon.$element )
7382 .addClass( 'oo-ui-menuOptionWidget' );
7383 };
7384
7385 /* Setup */
7386
7387 OO.inheritClass( OO.ui.MenuOptionWidget, OO.ui.DecoratedOptionWidget );
7388
7389 /* Static Properties */
7390
7391 /**
7392 * @static
7393 * @inheritdoc
7394 */
7395 OO.ui.MenuOptionWidget.static.scrollIntoViewOnSelect = true;
7396
7397 /**
7398 * MenuSectionOptionWidgets are used inside {@link OO.ui.MenuSelectWidget menu select widgets} to group one or more related
7399 * {@link OO.ui.MenuOptionWidget menu options}. MenuSectionOptionWidgets cannot be highlighted or selected.
7400 *
7401 * @example
7402 * var myDropdown = new OO.ui.DropdownWidget( {
7403 * menu: {
7404 * items: [
7405 * new OO.ui.MenuSectionOptionWidget( {
7406 * label: 'Dogs'
7407 * } ),
7408 * new OO.ui.MenuOptionWidget( {
7409 * data: 'corgi',
7410 * label: 'Welsh Corgi'
7411 * } ),
7412 * new OO.ui.MenuOptionWidget( {
7413 * data: 'poodle',
7414 * label: 'Standard Poodle'
7415 * } ),
7416 * new OO.ui.MenuSectionOptionWidget( {
7417 * label: 'Cats'
7418 * } ),
7419 * new OO.ui.MenuOptionWidget( {
7420 * data: 'lion',
7421 * label: 'Lion'
7422 * } )
7423 * ]
7424 * }
7425 * } );
7426 * $( 'body' ).append( myDropdown.$element );
7427 *
7428 * @class
7429 * @extends OO.ui.DecoratedOptionWidget
7430 *
7431 * @constructor
7432 * @param {Object} [config] Configuration options
7433 */
7434 OO.ui.MenuSectionOptionWidget = function OoUiMenuSectionOptionWidget( config ) {
7435 // Parent constructor
7436 OO.ui.MenuSectionOptionWidget.parent.call( this, config );
7437
7438 // Initialization
7439 this.$element.addClass( 'oo-ui-menuSectionOptionWidget' )
7440 .removeAttr( 'role aria-selected' );
7441 };
7442
7443 /* Setup */
7444
7445 OO.inheritClass( OO.ui.MenuSectionOptionWidget, OO.ui.DecoratedOptionWidget );
7446
7447 /* Static Properties */
7448
7449 /**
7450 * @static
7451 * @inheritdoc
7452 */
7453 OO.ui.MenuSectionOptionWidget.static.selectable = false;
7454
7455 /**
7456 * @static
7457 * @inheritdoc
7458 */
7459 OO.ui.MenuSectionOptionWidget.static.highlightable = false;
7460
7461 /**
7462 * MenuSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains options and
7463 * is used together with OO.ui.MenuOptionWidget. It is designed be used as part of another widget.
7464 * See {@link OO.ui.DropdownWidget DropdownWidget}, {@link OO.ui.ComboBoxInputWidget ComboBoxInputWidget},
7465 * and {@link OO.ui.mixin.LookupElement LookupElement} for examples of widgets that contain menus.
7466 * MenuSelectWidgets themselves are not instantiated directly, rather subclassed
7467 * and customized to be opened, closed, and displayed as needed.
7468 *
7469 * By default, menus are clipped to the visible viewport and are not visible when a user presses the
7470 * mouse outside the menu.
7471 *
7472 * Menus also have support for keyboard interaction:
7473 *
7474 * - Enter/Return key: choose and select a menu option
7475 * - Up-arrow key: highlight the previous menu option
7476 * - Down-arrow key: highlight the next menu option
7477 * - Esc key: hide the menu
7478 *
7479 * Unlike most widgets, MenuSelectWidget is initially hidden and must be shown by calling #toggle.
7480 *
7481 * Please see the [OOUI documentation on MediaWiki][1] for more information.
7482 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options
7483 *
7484 * @class
7485 * @extends OO.ui.SelectWidget
7486 * @mixins OO.ui.mixin.ClippableElement
7487 * @mixins OO.ui.mixin.FloatableElement
7488 *
7489 * @constructor
7490 * @param {Object} [config] Configuration options
7491 * @cfg {OO.ui.TextInputWidget} [input] Text input used to implement option highlighting for menu items that match
7492 * the text the user types. This config is used by {@link OO.ui.ComboBoxInputWidget ComboBoxInputWidget}
7493 * and {@link OO.ui.mixin.LookupElement LookupElement}
7494 * @cfg {jQuery} [$input] Text input used to implement option highlighting for menu items that match
7495 * the text the user types. This config is used by {@link OO.ui.TagMultiselectWidget TagMultiselectWidget}
7496 * @cfg {OO.ui.Widget} [widget] Widget associated with the menu's active state. If the user clicks the mouse
7497 * anywhere on the page outside of this widget, the menu is hidden. For example, if there is a button
7498 * that toggles the menu's visibility on click, the menu will be hidden then re-shown when the user clicks
7499 * that button, unless the button (or its parent widget) is passed in here.
7500 * @cfg {boolean} [autoHide=true] Hide the menu when the mouse is pressed outside the menu.
7501 * @cfg {jQuery} [$autoCloseIgnore] If these elements are clicked, don't auto-hide the menu.
7502 * @cfg {boolean} [hideOnChoose=true] Hide the menu when the user chooses an option.
7503 * @cfg {boolean} [filterFromInput=false] Filter the displayed options from the input
7504 * @cfg {boolean} [highlightOnFilter] Highlight the first result when filtering
7505 * @cfg {number} [width] Width of the menu
7506 */
7507 OO.ui.MenuSelectWidget = function OoUiMenuSelectWidget( config ) {
7508 // Configuration initialization
7509 config = config || {};
7510
7511 // Parent constructor
7512 OO.ui.MenuSelectWidget.parent.call( this, config );
7513
7514 // Mixin constructors
7515 OO.ui.mixin.ClippableElement.call( this, $.extend( {}, config, { $clippable: this.$group } ) );
7516 OO.ui.mixin.FloatableElement.call( this, config );
7517
7518 // Initial vertical positions other than 'center' will result in
7519 // the menu being flipped if there is not enough space in the container.
7520 // Store the original position so we know what to reset to.
7521 this.originalVerticalPosition = this.verticalPosition;
7522
7523 // Properties
7524 this.autoHide = config.autoHide === undefined || !!config.autoHide;
7525 this.hideOnChoose = config.hideOnChoose === undefined || !!config.hideOnChoose;
7526 this.filterFromInput = !!config.filterFromInput;
7527 this.$input = config.$input ? config.$input : config.input ? config.input.$input : null;
7528 this.$widget = config.widget ? config.widget.$element : null;
7529 this.$autoCloseIgnore = config.$autoCloseIgnore || $( [] );
7530 this.onDocumentMouseDownHandler = this.onDocumentMouseDown.bind( this );
7531 this.onInputEditHandler = OO.ui.debounce( this.updateItemVisibility.bind( this ), 100 );
7532 this.highlightOnFilter = !!config.highlightOnFilter;
7533 this.width = config.width;
7534
7535 // Initialization
7536 this.$element.addClass( 'oo-ui-menuSelectWidget' );
7537 if ( config.widget ) {
7538 this.setFocusOwner( config.widget.$tabIndexed );
7539 }
7540
7541 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
7542 // that reference properties not initialized at that time of parent class construction
7543 // TODO: Find a better way to handle post-constructor setup
7544 this.visible = false;
7545 this.$element.addClass( 'oo-ui-element-hidden' );
7546 };
7547
7548 /* Setup */
7549
7550 OO.inheritClass( OO.ui.MenuSelectWidget, OO.ui.SelectWidget );
7551 OO.mixinClass( OO.ui.MenuSelectWidget, OO.ui.mixin.ClippableElement );
7552 OO.mixinClass( OO.ui.MenuSelectWidget, OO.ui.mixin.FloatableElement );
7553
7554 /* Events */
7555
7556 /**
7557 * @event ready
7558 *
7559 * The menu is ready: it is visible and has been positioned and clipped.
7560 */
7561
7562 /* Static properties */
7563
7564 /**
7565 * Positions to flip to if there isn't room in the container for the
7566 * menu in a specific direction.
7567 *
7568 * @property {Object.<string,string>}
7569 */
7570 OO.ui.MenuSelectWidget.static.flippedPositions = {
7571 below: 'above',
7572 above: 'below',
7573 top: 'bottom',
7574 bottom: 'top'
7575 };
7576
7577 /* Methods */
7578
7579 /**
7580 * Handles document mouse down events.
7581 *
7582 * @protected
7583 * @param {MouseEvent} e Mouse down event
7584 */
7585 OO.ui.MenuSelectWidget.prototype.onDocumentMouseDown = function ( e ) {
7586 if (
7587 this.isVisible() &&
7588 !OO.ui.contains(
7589 this.$element.add( this.$widget ).add( this.$autoCloseIgnore ).get(),
7590 e.target,
7591 true
7592 )
7593 ) {
7594 this.toggle( false );
7595 }
7596 };
7597
7598 /**
7599 * @inheritdoc
7600 */
7601 OO.ui.MenuSelectWidget.prototype.onDocumentKeyDown = function ( e ) {
7602 var currentItem = this.findHighlightedItem() || this.findSelectedItem();
7603
7604 if ( !this.isDisabled() && this.isVisible() ) {
7605 switch ( e.keyCode ) {
7606 case OO.ui.Keys.LEFT:
7607 case OO.ui.Keys.RIGHT:
7608 // Do nothing if a text field is associated, arrow keys will be handled natively
7609 if ( !this.$input ) {
7610 OO.ui.MenuSelectWidget.parent.prototype.onDocumentKeyDown.call( this, e );
7611 }
7612 break;
7613 case OO.ui.Keys.ESCAPE:
7614 case OO.ui.Keys.TAB:
7615 if ( currentItem ) {
7616 currentItem.setHighlighted( false );
7617 }
7618 this.toggle( false );
7619 // Don't prevent tabbing away, prevent defocusing
7620 if ( e.keyCode === OO.ui.Keys.ESCAPE ) {
7621 e.preventDefault();
7622 e.stopPropagation();
7623 }
7624 break;
7625 default:
7626 OO.ui.MenuSelectWidget.parent.prototype.onDocumentKeyDown.call( this, e );
7627 return;
7628 }
7629 }
7630 };
7631
7632 /**
7633 * Update menu item visibility and clipping after input changes (if filterFromInput is enabled)
7634 * or after items were added/removed (always).
7635 *
7636 * @protected
7637 */
7638 OO.ui.MenuSelectWidget.prototype.updateItemVisibility = function () {
7639 var i, item, items, visible, section, sectionEmpty, filter, exactFilter,
7640 anyVisible = false,
7641 len = this.items.length,
7642 showAll = !this.isVisible(),
7643 exactMatch = false;
7644
7645 if ( this.$input && this.filterFromInput ) {
7646 filter = showAll ? null : this.getItemMatcher( this.$input.val() );
7647 exactFilter = this.getItemMatcher( this.$input.val(), true );
7648 // Hide non-matching options, and also hide section headers if all options
7649 // in their section are hidden.
7650 for ( i = 0; i < len; i++ ) {
7651 item = this.items[ i ];
7652 if ( item instanceof OO.ui.MenuSectionOptionWidget ) {
7653 if ( section ) {
7654 // If the previous section was empty, hide its header
7655 section.toggle( showAll || !sectionEmpty );
7656 }
7657 section = item;
7658 sectionEmpty = true;
7659 } else if ( item instanceof OO.ui.OptionWidget ) {
7660 visible = showAll || filter( item );
7661 exactMatch = exactMatch || exactFilter( item );
7662 anyVisible = anyVisible || visible;
7663 sectionEmpty = sectionEmpty && !visible;
7664 item.toggle( visible );
7665 }
7666 }
7667 // Process the final section
7668 if ( section ) {
7669 section.toggle( showAll || !sectionEmpty );
7670 }
7671
7672 if ( anyVisible && this.items.length && !exactMatch ) {
7673 this.scrollItemIntoView( this.items[ 0 ] );
7674 }
7675
7676 if ( !anyVisible ) {
7677 this.highlightItem( null );
7678 }
7679
7680 this.$element.toggleClass( 'oo-ui-menuSelectWidget-invisible', !anyVisible );
7681
7682 if ( this.highlightOnFilter ) {
7683 // Highlight the first item on the list
7684 item = null;
7685 items = this.getItems();
7686 for ( i = 0; i < items.length; i++ ) {
7687 if ( items[ i ].isVisible() ) {
7688 item = items[ i ];
7689 break;
7690 }
7691 }
7692 this.highlightItem( item );
7693 }
7694
7695 }
7696
7697 // Reevaluate clipping
7698 this.clip();
7699 };
7700
7701 /**
7702 * @inheritdoc
7703 */
7704 OO.ui.MenuSelectWidget.prototype.bindDocumentKeyDownListener = function () {
7705 if ( this.$input ) {
7706 this.$input.on( 'keydown', this.onDocumentKeyDownHandler );
7707 } else {
7708 OO.ui.MenuSelectWidget.parent.prototype.bindDocumentKeyDownListener.call( this );
7709 }
7710 };
7711
7712 /**
7713 * @inheritdoc
7714 */
7715 OO.ui.MenuSelectWidget.prototype.unbindDocumentKeyDownListener = function () {
7716 if ( this.$input ) {
7717 this.$input.off( 'keydown', this.onDocumentKeyDownHandler );
7718 } else {
7719 OO.ui.MenuSelectWidget.parent.prototype.unbindDocumentKeyDownListener.call( this );
7720 }
7721 };
7722
7723 /**
7724 * @inheritdoc
7725 */
7726 OO.ui.MenuSelectWidget.prototype.bindDocumentKeyPressListener = function () {
7727 if ( this.$input ) {
7728 if ( this.filterFromInput ) {
7729 this.$input.on( 'keydown mouseup cut paste change input select', this.onInputEditHandler );
7730 this.updateItemVisibility();
7731 }
7732 } else {
7733 OO.ui.MenuSelectWidget.parent.prototype.bindDocumentKeyPressListener.call( this );
7734 }
7735 };
7736
7737 /**
7738 * @inheritdoc
7739 */
7740 OO.ui.MenuSelectWidget.prototype.unbindDocumentKeyPressListener = function () {
7741 if ( this.$input ) {
7742 if ( this.filterFromInput ) {
7743 this.$input.off( 'keydown mouseup cut paste change input select', this.onInputEditHandler );
7744 this.updateItemVisibility();
7745 }
7746 } else {
7747 OO.ui.MenuSelectWidget.parent.prototype.unbindDocumentKeyPressListener.call( this );
7748 }
7749 };
7750
7751 /**
7752 * Choose an item.
7753 *
7754 * When a user chooses an item, the menu is closed, unless the hideOnChoose config option is set to false.
7755 *
7756 * Note that ‘choose’ should never be modified programmatically. A user can choose an option with the keyboard
7757 * or mouse and it becomes selected. To select an item programmatically, use the #selectItem method.
7758 *
7759 * @param {OO.ui.OptionWidget} item Item to choose
7760 * @chainable
7761 * @return {OO.ui.Widget} The widget, for chaining
7762 */
7763 OO.ui.MenuSelectWidget.prototype.chooseItem = function ( item ) {
7764 OO.ui.MenuSelectWidget.parent.prototype.chooseItem.call( this, item );
7765 if ( this.hideOnChoose ) {
7766 this.toggle( false );
7767 }
7768 return this;
7769 };
7770
7771 /**
7772 * @inheritdoc
7773 */
7774 OO.ui.MenuSelectWidget.prototype.addItems = function ( items, index ) {
7775 // Parent method
7776 OO.ui.MenuSelectWidget.parent.prototype.addItems.call( this, items, index );
7777
7778 this.updateItemVisibility();
7779
7780 return this;
7781 };
7782
7783 /**
7784 * @inheritdoc
7785 */
7786 OO.ui.MenuSelectWidget.prototype.removeItems = function ( items ) {
7787 // Parent method
7788 OO.ui.MenuSelectWidget.parent.prototype.removeItems.call( this, items );
7789
7790 this.updateItemVisibility();
7791
7792 return this;
7793 };
7794
7795 /**
7796 * @inheritdoc
7797 */
7798 OO.ui.MenuSelectWidget.prototype.clearItems = function () {
7799 // Parent method
7800 OO.ui.MenuSelectWidget.parent.prototype.clearItems.call( this );
7801
7802 this.updateItemVisibility();
7803
7804 return this;
7805 };
7806
7807 /**
7808 * Toggle visibility of the menu. The menu is initially hidden and must be shown by calling
7809 * `.toggle( true )` after its #$element is attached to the DOM.
7810 *
7811 * Do not show the menu while it is not attached to the DOM. The calculations required to display
7812 * it in the right place and with the right dimensions only work correctly while it is attached.
7813 * Side-effects may include broken interface and exceptions being thrown. This wasn't always
7814 * strictly enforced, so currently it only generates a warning in the browser console.
7815 *
7816 * @fires ready
7817 * @inheritdoc
7818 */
7819 OO.ui.MenuSelectWidget.prototype.toggle = function ( visible ) {
7820 var change, originalHeight, flippedHeight;
7821
7822 visible = ( visible === undefined ? !this.visible : !!visible ) && !!this.items.length;
7823 change = visible !== this.isVisible();
7824
7825 if ( visible && !this.warnedUnattached && !this.isElementAttached() ) {
7826 OO.ui.warnDeprecation( 'MenuSelectWidget#toggle: Before calling this method, the menu must be attached to the DOM.' );
7827 this.warnedUnattached = true;
7828 }
7829
7830 if ( change && visible ) {
7831 // Reset position before showing the popup again. It's possible we no longer need to flip
7832 // (e.g. if the user scrolled).
7833 this.setVerticalPosition( this.originalVerticalPosition );
7834 }
7835
7836 // Parent method
7837 OO.ui.MenuSelectWidget.parent.prototype.toggle.call( this, visible );
7838
7839 if ( change ) {
7840 if ( visible ) {
7841
7842 if ( this.width ) {
7843 this.setIdealSize( this.width );
7844 } else if ( this.$floatableContainer ) {
7845 this.$clippable.css( 'width', 'auto' );
7846 this.setIdealSize(
7847 this.$floatableContainer[ 0 ].offsetWidth > this.$clippable[ 0 ].offsetWidth ?
7848 // Dropdown is smaller than handle so expand to width
7849 this.$floatableContainer[ 0 ].offsetWidth :
7850 // Dropdown is larger than handle so auto size
7851 'auto'
7852 );
7853 this.$clippable.css( 'width', '' );
7854 }
7855
7856 this.togglePositioning( !!this.$floatableContainer );
7857 this.toggleClipping( true );
7858
7859 this.bindDocumentKeyDownListener();
7860 this.bindDocumentKeyPressListener();
7861
7862 if (
7863 ( this.isClippedVertically() || this.isFloatableOutOfView() ) &&
7864 this.originalVerticalPosition !== 'center'
7865 ) {
7866 // If opening the menu in one direction causes it to be clipped, flip it
7867 originalHeight = this.$element.height();
7868 this.setVerticalPosition(
7869 this.constructor.static.flippedPositions[ this.originalVerticalPosition ]
7870 );
7871 if ( this.isClippedVertically() || this.isFloatableOutOfView() ) {
7872 // If flipping also causes it to be clipped, open in whichever direction
7873 // we have more space
7874 flippedHeight = this.$element.height();
7875 if ( originalHeight > flippedHeight ) {
7876 this.setVerticalPosition( this.originalVerticalPosition );
7877 }
7878 }
7879 }
7880 // Note that we do not flip the menu's opening direction if the clipping changes
7881 // later (e.g. after the user scrolls), that seems like it would be annoying
7882
7883 this.$focusOwner.attr( 'aria-expanded', 'true' );
7884
7885 if ( this.findSelectedItem() ) {
7886 this.$focusOwner.attr( 'aria-activedescendant', this.findSelectedItem().getElementId() );
7887 this.findSelectedItem().scrollElementIntoView( { duration: 0 } );
7888 }
7889
7890 // Auto-hide
7891 if ( this.autoHide ) {
7892 this.getElementDocument().addEventListener( 'mousedown', this.onDocumentMouseDownHandler, true );
7893 }
7894
7895 this.emit( 'ready' );
7896 } else {
7897 this.$focusOwner.removeAttr( 'aria-activedescendant' );
7898 this.unbindDocumentKeyDownListener();
7899 this.unbindDocumentKeyPressListener();
7900 this.$focusOwner.attr( 'aria-expanded', 'false' );
7901 this.getElementDocument().removeEventListener( 'mousedown', this.onDocumentMouseDownHandler, true );
7902 this.togglePositioning( false );
7903 this.toggleClipping( false );
7904 }
7905 }
7906
7907 return this;
7908 };
7909
7910 /**
7911 * DropdownWidgets are not menus themselves, rather they contain a menu of options created with
7912 * OO.ui.MenuOptionWidget. The DropdownWidget takes care of opening and displaying the menu so that
7913 * users can interact with it.
7914 *
7915 * If you want to use this within an HTML form, such as a OO.ui.FormLayout, use
7916 * OO.ui.DropdownInputWidget instead.
7917 *
7918 * @example
7919 * // Example: A DropdownWidget with a menu that contains three options
7920 * var dropDown = new OO.ui.DropdownWidget( {
7921 * label: 'Dropdown menu: Select a menu option',
7922 * menu: {
7923 * items: [
7924 * new OO.ui.MenuOptionWidget( {
7925 * data: 'a',
7926 * label: 'First'
7927 * } ),
7928 * new OO.ui.MenuOptionWidget( {
7929 * data: 'b',
7930 * label: 'Second'
7931 * } ),
7932 * new OO.ui.MenuOptionWidget( {
7933 * data: 'c',
7934 * label: 'Third'
7935 * } )
7936 * ]
7937 * }
7938 * } );
7939 *
7940 * $( 'body' ).append( dropDown.$element );
7941 *
7942 * dropDown.getMenu().selectItemByData( 'b' );
7943 *
7944 * dropDown.getMenu().findSelectedItem().getData(); // returns 'b'
7945 *
7946 * For more information, please see the [OOUI documentation on MediaWiki] [1].
7947 *
7948 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options#Menu_selects_and_options
7949 *
7950 * @class
7951 * @extends OO.ui.Widget
7952 * @mixins OO.ui.mixin.IconElement
7953 * @mixins OO.ui.mixin.IndicatorElement
7954 * @mixins OO.ui.mixin.LabelElement
7955 * @mixins OO.ui.mixin.TitledElement
7956 * @mixins OO.ui.mixin.TabIndexedElement
7957 *
7958 * @constructor
7959 * @param {Object} [config] Configuration options
7960 * @cfg {Object} [menu] Configuration options to pass to {@link OO.ui.MenuSelectWidget menu select widget}
7961 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
7962 * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
7963 * containing `<div>` and has a larger area. By default, the menu uses relative positioning.
7964 * See <https://www.mediawiki.org/wiki/OOUI/Concepts#Overlays>.
7965 */
7966 OO.ui.DropdownWidget = function OoUiDropdownWidget( config ) {
7967 // Configuration initialization
7968 config = $.extend( { indicator: 'down' }, config );
7969
7970 // Parent constructor
7971 OO.ui.DropdownWidget.parent.call( this, config );
7972
7973 // Properties (must be set before TabIndexedElement constructor call)
7974 this.$handle = $( '<span>' );
7975 this.$overlay = ( config.$overlay === true ? OO.ui.getDefaultOverlay() : config.$overlay ) || this.$element;
7976
7977 // Mixin constructors
7978 OO.ui.mixin.IconElement.call( this, config );
7979 OO.ui.mixin.IndicatorElement.call( this, config );
7980 OO.ui.mixin.LabelElement.call( this, config );
7981 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$label } ) );
7982 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$handle } ) );
7983
7984 // Properties
7985 this.menu = new OO.ui.MenuSelectWidget( $.extend( {
7986 widget: this,
7987 $floatableContainer: this.$element
7988 }, config.menu ) );
7989
7990 // Events
7991 this.$handle.on( {
7992 click: this.onClick.bind( this ),
7993 keydown: this.onKeyDown.bind( this ),
7994 // Hack? Handle type-to-search when menu is not expanded and not handling its own events
7995 keypress: this.menu.onDocumentKeyPressHandler,
7996 blur: this.menu.clearKeyPressBuffer.bind( this.menu )
7997 } );
7998 this.menu.connect( this, {
7999 select: 'onMenuSelect',
8000 toggle: 'onMenuToggle'
8001 } );
8002
8003 // Initialization
8004 this.$handle
8005 .addClass( 'oo-ui-dropdownWidget-handle' )
8006 .attr( {
8007 role: 'combobox',
8008 'aria-owns': this.menu.getElementId(),
8009 'aria-autocomplete': 'list'
8010 } )
8011 .append( this.$icon, this.$label, this.$indicator );
8012 this.$element
8013 .addClass( 'oo-ui-dropdownWidget' )
8014 .append( this.$handle );
8015 this.$overlay.append( this.menu.$element );
8016 };
8017
8018 /* Setup */
8019
8020 OO.inheritClass( OO.ui.DropdownWidget, OO.ui.Widget );
8021 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.IconElement );
8022 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.IndicatorElement );
8023 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.LabelElement );
8024 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.TitledElement );
8025 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.TabIndexedElement );
8026
8027 /* Methods */
8028
8029 /**
8030 * Get the menu.
8031 *
8032 * @return {OO.ui.MenuSelectWidget} Menu of widget
8033 */
8034 OO.ui.DropdownWidget.prototype.getMenu = function () {
8035 return this.menu;
8036 };
8037
8038 /**
8039 * Handles menu select events.
8040 *
8041 * @private
8042 * @param {OO.ui.MenuOptionWidget} item Selected menu item
8043 */
8044 OO.ui.DropdownWidget.prototype.onMenuSelect = function ( item ) {
8045 var selectedLabel;
8046
8047 if ( !item ) {
8048 this.setLabel( null );
8049 return;
8050 }
8051
8052 selectedLabel = item.getLabel();
8053
8054 // If the label is a DOM element, clone it, because setLabel will append() it
8055 if ( selectedLabel instanceof $ ) {
8056 selectedLabel = selectedLabel.clone();
8057 }
8058
8059 this.setLabel( selectedLabel );
8060 };
8061
8062 /**
8063 * Handle menu toggle events.
8064 *
8065 * @private
8066 * @param {boolean} isVisible Open state of the menu
8067 */
8068 OO.ui.DropdownWidget.prototype.onMenuToggle = function ( isVisible ) {
8069 this.$element.toggleClass( 'oo-ui-dropdownWidget-open', isVisible );
8070 this.$handle.attr(
8071 'aria-expanded',
8072 this.$element.hasClass( 'oo-ui-dropdownWidget-open' ).toString()
8073 );
8074 };
8075
8076 /**
8077 * Handle mouse click events.
8078 *
8079 * @private
8080 * @param {jQuery.Event} e Mouse click event
8081 * @return {undefined/boolean} False to prevent default if event is handled
8082 */
8083 OO.ui.DropdownWidget.prototype.onClick = function ( e ) {
8084 if ( !this.isDisabled() && e.which === OO.ui.MouseButtons.LEFT ) {
8085 this.menu.toggle();
8086 }
8087 return false;
8088 };
8089
8090 /**
8091 * Handle key down events.
8092 *
8093 * @private
8094 * @param {jQuery.Event} e Key down event
8095 * @return {undefined/boolean} False to prevent default if event is handled
8096 */
8097 OO.ui.DropdownWidget.prototype.onKeyDown = function ( e ) {
8098 if (
8099 !this.isDisabled() &&
8100 (
8101 e.which === OO.ui.Keys.ENTER ||
8102 (
8103 e.which === OO.ui.Keys.SPACE &&
8104 // Avoid conflicts with type-to-search, see SelectWidget#onKeyPress.
8105 // Space only closes the menu is the user is not typing to search.
8106 this.menu.keyPressBuffer === ''
8107 ) ||
8108 (
8109 !this.menu.isVisible() &&
8110 (
8111 e.which === OO.ui.Keys.UP ||
8112 e.which === OO.ui.Keys.DOWN
8113 )
8114 )
8115 )
8116 ) {
8117 this.menu.toggle();
8118 return false;
8119 }
8120 };
8121
8122 /**
8123 * RadioOptionWidget is an option widget that looks like a radio button.
8124 * The class is used with OO.ui.RadioSelectWidget to create a selection of radio options.
8125 * Please see the [OOUI documentation on MediaWiki] [1] for more information.
8126 *
8127 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options#Button_selects_and_option
8128 *
8129 * @class
8130 * @extends OO.ui.OptionWidget
8131 *
8132 * @constructor
8133 * @param {Object} [config] Configuration options
8134 */
8135 OO.ui.RadioOptionWidget = function OoUiRadioOptionWidget( config ) {
8136 // Configuration initialization
8137 config = config || {};
8138
8139 // Properties (must be done before parent constructor which calls #setDisabled)
8140 this.radio = new OO.ui.RadioInputWidget( { value: config.data, tabIndex: -1 } );
8141
8142 // Parent constructor
8143 OO.ui.RadioOptionWidget.parent.call( this, config );
8144
8145 // Initialization
8146 // Remove implicit role, we're handling it ourselves
8147 this.radio.$input.attr( 'role', 'presentation' );
8148 this.$element
8149 .addClass( 'oo-ui-radioOptionWidget' )
8150 .attr( 'role', 'radio' )
8151 .attr( 'aria-checked', 'false' )
8152 .removeAttr( 'aria-selected' )
8153 .prepend( this.radio.$element );
8154 };
8155
8156 /* Setup */
8157
8158 OO.inheritClass( OO.ui.RadioOptionWidget, OO.ui.OptionWidget );
8159
8160 /* Static Properties */
8161
8162 /**
8163 * @static
8164 * @inheritdoc
8165 */
8166 OO.ui.RadioOptionWidget.static.highlightable = false;
8167
8168 /**
8169 * @static
8170 * @inheritdoc
8171 */
8172 OO.ui.RadioOptionWidget.static.scrollIntoViewOnSelect = true;
8173
8174 /**
8175 * @static
8176 * @inheritdoc
8177 */
8178 OO.ui.RadioOptionWidget.static.pressable = false;
8179
8180 /**
8181 * @static
8182 * @inheritdoc
8183 */
8184 OO.ui.RadioOptionWidget.static.tagName = 'label';
8185
8186 /* Methods */
8187
8188 /**
8189 * @inheritdoc
8190 */
8191 OO.ui.RadioOptionWidget.prototype.setSelected = function ( state ) {
8192 OO.ui.RadioOptionWidget.parent.prototype.setSelected.call( this, state );
8193
8194 this.radio.setSelected( state );
8195 this.$element
8196 .attr( 'aria-checked', state.toString() )
8197 .removeAttr( 'aria-selected' );
8198
8199 return this;
8200 };
8201
8202 /**
8203 * @inheritdoc
8204 */
8205 OO.ui.RadioOptionWidget.prototype.setDisabled = function ( disabled ) {
8206 OO.ui.RadioOptionWidget.parent.prototype.setDisabled.call( this, disabled );
8207
8208 this.radio.setDisabled( this.isDisabled() );
8209
8210 return this;
8211 };
8212
8213 /**
8214 * RadioSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains radio
8215 * options and is used together with OO.ui.RadioOptionWidget. The RadioSelectWidget provides
8216 * an interface for adding, removing and selecting options.
8217 * Please see the [OOUI documentation on MediaWiki][1] for more information.
8218 *
8219 * If you want to use this within an HTML form, such as a OO.ui.FormLayout, use
8220 * OO.ui.RadioSelectInputWidget instead.
8221 *
8222 * @example
8223 * // A RadioSelectWidget with RadioOptions.
8224 * var option1 = new OO.ui.RadioOptionWidget( {
8225 * data: 'a',
8226 * label: 'Selected radio option'
8227 * } );
8228 *
8229 * var option2 = new OO.ui.RadioOptionWidget( {
8230 * data: 'b',
8231 * label: 'Unselected radio option'
8232 * } );
8233 *
8234 * var radioSelect=new OO.ui.RadioSelectWidget( {
8235 * items: [ option1, option2 ]
8236 * } );
8237 *
8238 * // Select 'option 1' using the RadioSelectWidget's selectItem() method.
8239 * radioSelect.selectItem( option1 );
8240 *
8241 * $( 'body' ).append( radioSelect.$element );
8242 *
8243 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options
8244
8245 *
8246 * @class
8247 * @extends OO.ui.SelectWidget
8248 * @mixins OO.ui.mixin.TabIndexedElement
8249 *
8250 * @constructor
8251 * @param {Object} [config] Configuration options
8252 */
8253 OO.ui.RadioSelectWidget = function OoUiRadioSelectWidget( config ) {
8254 // Parent constructor
8255 OO.ui.RadioSelectWidget.parent.call( this, config );
8256
8257 // Mixin constructors
8258 OO.ui.mixin.TabIndexedElement.call( this, config );
8259
8260 // Events
8261 this.$element.on( {
8262 focus: this.bindDocumentKeyDownListener.bind( this ),
8263 blur: this.unbindDocumentKeyDownListener.bind( this )
8264 } );
8265
8266 // Initialization
8267 this.$element
8268 .addClass( 'oo-ui-radioSelectWidget' )
8269 .attr( 'role', 'radiogroup' );
8270 };
8271
8272 /* Setup */
8273
8274 OO.inheritClass( OO.ui.RadioSelectWidget, OO.ui.SelectWidget );
8275 OO.mixinClass( OO.ui.RadioSelectWidget, OO.ui.mixin.TabIndexedElement );
8276
8277 /**
8278 * MultioptionWidgets are special elements that can be selected and configured with data. The
8279 * data is often unique for each option, but it does not have to be. MultioptionWidgets are used
8280 * with OO.ui.SelectWidget to create a selection of mutually exclusive options. For more information
8281 * and examples, please see the [OOUI documentation on MediaWiki][1].
8282 *
8283 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Multioptions
8284 *
8285 * @class
8286 * @extends OO.ui.Widget
8287 * @mixins OO.ui.mixin.ItemWidget
8288 * @mixins OO.ui.mixin.LabelElement
8289 *
8290 * @constructor
8291 * @param {Object} [config] Configuration options
8292 * @cfg {boolean} [selected=false] Whether the option is initially selected
8293 */
8294 OO.ui.MultioptionWidget = function OoUiMultioptionWidget( config ) {
8295 // Configuration initialization
8296 config = config || {};
8297
8298 // Parent constructor
8299 OO.ui.MultioptionWidget.parent.call( this, config );
8300
8301 // Mixin constructors
8302 OO.ui.mixin.ItemWidget.call( this );
8303 OO.ui.mixin.LabelElement.call( this, config );
8304
8305 // Properties
8306 this.selected = null;
8307
8308 // Initialization
8309 this.$element
8310 .addClass( 'oo-ui-multioptionWidget' )
8311 .append( this.$label );
8312 this.setSelected( config.selected );
8313 };
8314
8315 /* Setup */
8316
8317 OO.inheritClass( OO.ui.MultioptionWidget, OO.ui.Widget );
8318 OO.mixinClass( OO.ui.MultioptionWidget, OO.ui.mixin.ItemWidget );
8319 OO.mixinClass( OO.ui.MultioptionWidget, OO.ui.mixin.LabelElement );
8320
8321 /* Events */
8322
8323 /**
8324 * @event change
8325 *
8326 * A change event is emitted when the selected state of the option changes.
8327 *
8328 * @param {boolean} selected Whether the option is now selected
8329 */
8330
8331 /* Methods */
8332
8333 /**
8334 * Check if the option is selected.
8335 *
8336 * @return {boolean} Item is selected
8337 */
8338 OO.ui.MultioptionWidget.prototype.isSelected = function () {
8339 return this.selected;
8340 };
8341
8342 /**
8343 * Set the option’s selected state. In general, all modifications to the selection
8344 * should be handled by the SelectWidget’s {@link OO.ui.SelectWidget#selectItem selectItem( [item] )}
8345 * method instead of this method.
8346 *
8347 * @param {boolean} [state=false] Select option
8348 * @chainable
8349 * @return {OO.ui.Widget} The widget, for chaining
8350 */
8351 OO.ui.MultioptionWidget.prototype.setSelected = function ( state ) {
8352 state = !!state;
8353 if ( this.selected !== state ) {
8354 this.selected = state;
8355 this.emit( 'change', state );
8356 this.$element.toggleClass( 'oo-ui-multioptionWidget-selected', state );
8357 }
8358 return this;
8359 };
8360
8361 /**
8362 * MultiselectWidget allows selecting multiple options from a list.
8363 *
8364 * For more information about menus and options, please see the [OOUI documentation on MediaWiki][1].
8365 *
8366 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options#Menu_selects_and_options
8367 *
8368 * @class
8369 * @abstract
8370 * @extends OO.ui.Widget
8371 * @mixins OO.ui.mixin.GroupWidget
8372 *
8373 * @constructor
8374 * @param {Object} [config] Configuration options
8375 * @cfg {OO.ui.MultioptionWidget[]} [items] An array of options to add to the multiselect.
8376 */
8377 OO.ui.MultiselectWidget = function OoUiMultiselectWidget( config ) {
8378 // Parent constructor
8379 OO.ui.MultiselectWidget.parent.call( this, config );
8380
8381 // Configuration initialization
8382 config = config || {};
8383
8384 // Mixin constructors
8385 OO.ui.mixin.GroupWidget.call( this, config );
8386
8387 // Events
8388 this.aggregate( { change: 'select' } );
8389 // This is mostly for compatibility with TagMultiselectWidget... normally, 'change' is emitted
8390 // by GroupElement only when items are added/removed
8391 this.connect( this, { select: [ 'emit', 'change' ] } );
8392
8393 // Initialization
8394 if ( config.items ) {
8395 this.addItems( config.items );
8396 }
8397 this.$group.addClass( 'oo-ui-multiselectWidget-group' );
8398 this.$element.addClass( 'oo-ui-multiselectWidget' )
8399 .append( this.$group );
8400 };
8401
8402 /* Setup */
8403
8404 OO.inheritClass( OO.ui.MultiselectWidget, OO.ui.Widget );
8405 OO.mixinClass( OO.ui.MultiselectWidget, OO.ui.mixin.GroupWidget );
8406
8407 /* Events */
8408
8409 /**
8410 * @event change
8411 *
8412 * A change event is emitted when the set of items changes, or an item is selected or deselected.
8413 */
8414
8415 /**
8416 * @event select
8417 *
8418 * A select event is emitted when an item is selected or deselected.
8419 */
8420
8421 /* Methods */
8422
8423 /**
8424 * Find options that are selected.
8425 *
8426 * @return {OO.ui.MultioptionWidget[]} Selected options
8427 */
8428 OO.ui.MultiselectWidget.prototype.findSelectedItems = function () {
8429 return this.items.filter( function ( item ) {
8430 return item.isSelected();
8431 } );
8432 };
8433
8434 /**
8435 * Find the data of options that are selected.
8436 *
8437 * @return {Object[]|string[]} Values of selected options
8438 */
8439 OO.ui.MultiselectWidget.prototype.findSelectedItemsData = function () {
8440 return this.findSelectedItems().map( function ( item ) {
8441 return item.data;
8442 } );
8443 };
8444
8445 /**
8446 * Select options by reference. Options not mentioned in the `items` array will be deselected.
8447 *
8448 * @param {OO.ui.MultioptionWidget[]} items Items to select
8449 * @chainable
8450 * @return {OO.ui.Widget} The widget, for chaining
8451 */
8452 OO.ui.MultiselectWidget.prototype.selectItems = function ( items ) {
8453 this.items.forEach( function ( item ) {
8454 var selected = items.indexOf( item ) !== -1;
8455 item.setSelected( selected );
8456 } );
8457 return this;
8458 };
8459
8460 /**
8461 * Select items by their data. Options not mentioned in the `datas` array will be deselected.
8462 *
8463 * @param {Object[]|string[]} datas Values of items to select
8464 * @chainable
8465 * @return {OO.ui.Widget} The widget, for chaining
8466 */
8467 OO.ui.MultiselectWidget.prototype.selectItemsByData = function ( datas ) {
8468 var items,
8469 widget = this;
8470 items = datas.map( function ( data ) {
8471 return widget.findItemFromData( data );
8472 } );
8473 this.selectItems( items );
8474 return this;
8475 };
8476
8477 /**
8478 * CheckboxMultioptionWidget is an option widget that looks like a checkbox.
8479 * The class is used with OO.ui.CheckboxMultiselectWidget to create a selection of checkbox options.
8480 * Please see the [OOUI documentation on MediaWiki] [1] for more information.
8481 *
8482 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options#Button_selects_and_option
8483 *
8484 * @class
8485 * @extends OO.ui.MultioptionWidget
8486 *
8487 * @constructor
8488 * @param {Object} [config] Configuration options
8489 */
8490 OO.ui.CheckboxMultioptionWidget = function OoUiCheckboxMultioptionWidget( config ) {
8491 // Configuration initialization
8492 config = config || {};
8493
8494 // Properties (must be done before parent constructor which calls #setDisabled)
8495 this.checkbox = new OO.ui.CheckboxInputWidget();
8496
8497 // Parent constructor
8498 OO.ui.CheckboxMultioptionWidget.parent.call( this, config );
8499
8500 // Events
8501 this.checkbox.on( 'change', this.onCheckboxChange.bind( this ) );
8502 this.$element.on( 'keydown', this.onKeyDown.bind( this ) );
8503
8504 // Initialization
8505 this.$element
8506 .addClass( 'oo-ui-checkboxMultioptionWidget' )
8507 .prepend( this.checkbox.$element );
8508 };
8509
8510 /* Setup */
8511
8512 OO.inheritClass( OO.ui.CheckboxMultioptionWidget, OO.ui.MultioptionWidget );
8513
8514 /* Static Properties */
8515
8516 /**
8517 * @static
8518 * @inheritdoc
8519 */
8520 OO.ui.CheckboxMultioptionWidget.static.tagName = 'label';
8521
8522 /* Methods */
8523
8524 /**
8525 * Handle checkbox selected state change.
8526 *
8527 * @private
8528 */
8529 OO.ui.CheckboxMultioptionWidget.prototype.onCheckboxChange = function () {
8530 this.setSelected( this.checkbox.isSelected() );
8531 };
8532
8533 /**
8534 * @inheritdoc
8535 */
8536 OO.ui.CheckboxMultioptionWidget.prototype.setSelected = function ( state ) {
8537 OO.ui.CheckboxMultioptionWidget.parent.prototype.setSelected.call( this, state );
8538 this.checkbox.setSelected( state );
8539 return this;
8540 };
8541
8542 /**
8543 * @inheritdoc
8544 */
8545 OO.ui.CheckboxMultioptionWidget.prototype.setDisabled = function ( disabled ) {
8546 OO.ui.CheckboxMultioptionWidget.parent.prototype.setDisabled.call( this, disabled );
8547 this.checkbox.setDisabled( this.isDisabled() );
8548 return this;
8549 };
8550
8551 /**
8552 * Focus the widget.
8553 */
8554 OO.ui.CheckboxMultioptionWidget.prototype.focus = function () {
8555 this.checkbox.focus();
8556 };
8557
8558 /**
8559 * Handle key down events.
8560 *
8561 * @protected
8562 * @param {jQuery.Event} e
8563 */
8564 OO.ui.CheckboxMultioptionWidget.prototype.onKeyDown = function ( e ) {
8565 var
8566 element = this.getElementGroup(),
8567 nextItem;
8568
8569 if ( e.keyCode === OO.ui.Keys.LEFT || e.keyCode === OO.ui.Keys.UP ) {
8570 nextItem = element.getRelativeFocusableItem( this, -1 );
8571 } else if ( e.keyCode === OO.ui.Keys.RIGHT || e.keyCode === OO.ui.Keys.DOWN ) {
8572 nextItem = element.getRelativeFocusableItem( this, 1 );
8573 }
8574
8575 if ( nextItem ) {
8576 e.preventDefault();
8577 nextItem.focus();
8578 }
8579 };
8580
8581 /**
8582 * CheckboxMultiselectWidget is a {@link OO.ui.MultiselectWidget multiselect widget} that contains
8583 * checkboxes and is used together with OO.ui.CheckboxMultioptionWidget. The
8584 * CheckboxMultiselectWidget provides an interface for adding, removing and selecting options.
8585 * Please see the [OOUI documentation on MediaWiki][1] for more information.
8586 *
8587 * If you want to use this within an HTML form, such as a OO.ui.FormLayout, use
8588 * OO.ui.CheckboxMultiselectInputWidget instead.
8589 *
8590 * @example
8591 * // A CheckboxMultiselectWidget with CheckboxMultioptions.
8592 * var option1 = new OO.ui.CheckboxMultioptionWidget( {
8593 * data: 'a',
8594 * selected: true,
8595 * label: 'Selected checkbox'
8596 * } );
8597 *
8598 * var option2 = new OO.ui.CheckboxMultioptionWidget( {
8599 * data: 'b',
8600 * label: 'Unselected checkbox'
8601 * } );
8602 *
8603 * var multiselect=new OO.ui.CheckboxMultiselectWidget( {
8604 * items: [ option1, option2 ]
8605 * } );
8606 *
8607 * $( 'body' ).append( multiselect.$element );
8608 *
8609 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options
8610 *
8611 * @class
8612 * @extends OO.ui.MultiselectWidget
8613 *
8614 * @constructor
8615 * @param {Object} [config] Configuration options
8616 */
8617 OO.ui.CheckboxMultiselectWidget = function OoUiCheckboxMultiselectWidget( config ) {
8618 // Parent constructor
8619 OO.ui.CheckboxMultiselectWidget.parent.call( this, config );
8620
8621 // Properties
8622 this.$lastClicked = null;
8623
8624 // Events
8625 this.$group.on( 'click', this.onClick.bind( this ) );
8626
8627 // Initialization
8628 this.$element
8629 .addClass( 'oo-ui-checkboxMultiselectWidget' );
8630 };
8631
8632 /* Setup */
8633
8634 OO.inheritClass( OO.ui.CheckboxMultiselectWidget, OO.ui.MultiselectWidget );
8635
8636 /* Methods */
8637
8638 /**
8639 * Get an option by its position relative to the specified item (or to the start of the option array,
8640 * if item is `null`). The direction in which to search through the option array is specified with a
8641 * number: -1 for reverse (the default) or 1 for forward. The method will return an option, or
8642 * `null` if there are no options in the array.
8643 *
8644 * @param {OO.ui.CheckboxMultioptionWidget|null} item Item to describe the start position, or `null` to start at the beginning of the array.
8645 * @param {number} direction Direction to move in: -1 to move backward, 1 to move forward
8646 * @return {OO.ui.CheckboxMultioptionWidget|null} Item at position, `null` if there are no items in the select
8647 */
8648 OO.ui.CheckboxMultiselectWidget.prototype.getRelativeFocusableItem = function ( item, direction ) {
8649 var currentIndex, nextIndex, i,
8650 increase = direction > 0 ? 1 : -1,
8651 len = this.items.length;
8652
8653 if ( item ) {
8654 currentIndex = this.items.indexOf( item );
8655 nextIndex = ( currentIndex + increase + len ) % len;
8656 } else {
8657 // If no item is selected and moving forward, start at the beginning.
8658 // If moving backward, start at the end.
8659 nextIndex = direction > 0 ? 0 : len - 1;
8660 }
8661
8662 for ( i = 0; i < len; i++ ) {
8663 item = this.items[ nextIndex ];
8664 if ( item && !item.isDisabled() ) {
8665 return item;
8666 }
8667 nextIndex = ( nextIndex + increase + len ) % len;
8668 }
8669 return null;
8670 };
8671
8672 /**
8673 * Handle click events on checkboxes.
8674 *
8675 * @param {jQuery.Event} e
8676 */
8677 OO.ui.CheckboxMultiselectWidget.prototype.onClick = function ( e ) {
8678 var $options, lastClickedIndex, nowClickedIndex, i, direction, wasSelected, items,
8679 $lastClicked = this.$lastClicked,
8680 $nowClicked = $( e.target ).closest( '.oo-ui-checkboxMultioptionWidget' )
8681 .not( '.oo-ui-widget-disabled' );
8682
8683 // Allow selecting multiple options at once by Shift-clicking them
8684 if ( $lastClicked && $nowClicked.length && e.shiftKey ) {
8685 $options = this.$group.find( '.oo-ui-checkboxMultioptionWidget' );
8686 lastClickedIndex = $options.index( $lastClicked );
8687 nowClickedIndex = $options.index( $nowClicked );
8688 // If it's the same item, either the user is being silly, or it's a fake event generated by the
8689 // browser. In either case we don't need custom handling.
8690 if ( nowClickedIndex !== lastClickedIndex ) {
8691 items = this.items;
8692 wasSelected = items[ nowClickedIndex ].isSelected();
8693 direction = nowClickedIndex > lastClickedIndex ? 1 : -1;
8694
8695 // This depends on the DOM order of the items and the order of the .items array being the same.
8696 for ( i = lastClickedIndex; i !== nowClickedIndex; i += direction ) {
8697 if ( !items[ i ].isDisabled() ) {
8698 items[ i ].setSelected( !wasSelected );
8699 }
8700 }
8701 // For the now-clicked element, use immediate timeout to allow the browser to do its own
8702 // handling first, then set our value. The order in which events happen is different for
8703 // clicks on the <input> and on the <label> and there are additional fake clicks fired for
8704 // non-click actions that change the checkboxes.
8705 e.preventDefault();
8706 setTimeout( function () {
8707 if ( !items[ nowClickedIndex ].isDisabled() ) {
8708 items[ nowClickedIndex ].setSelected( !wasSelected );
8709 }
8710 } );
8711 }
8712 }
8713
8714 if ( $nowClicked.length ) {
8715 this.$lastClicked = $nowClicked;
8716 }
8717 };
8718
8719 /**
8720 * Focus the widget
8721 *
8722 * @chainable
8723 * @return {OO.ui.Widget} The widget, for chaining
8724 */
8725 OO.ui.CheckboxMultiselectWidget.prototype.focus = function () {
8726 var item;
8727 if ( !this.isDisabled() ) {
8728 item = this.getRelativeFocusableItem( null, 1 );
8729 if ( item ) {
8730 item.focus();
8731 }
8732 }
8733 return this;
8734 };
8735
8736 /**
8737 * @inheritdoc
8738 */
8739 OO.ui.CheckboxMultiselectWidget.prototype.simulateLabelClick = function () {
8740 this.focus();
8741 };
8742
8743 /**
8744 * Progress bars visually display the status of an operation, such as a download,
8745 * and can be either determinate or indeterminate:
8746 *
8747 * - **determinate** process bars show the percent of an operation that is complete.
8748 *
8749 * - **indeterminate** process bars use a visual display of motion to indicate that an operation
8750 * is taking place. Because the extent of an indeterminate operation is unknown, the bar does
8751 * not use percentages.
8752 *
8753 * The value of the `progress` configuration determines whether the bar is determinate or indeterminate.
8754 *
8755 * @example
8756 * // Examples of determinate and indeterminate progress bars.
8757 * var progressBar1 = new OO.ui.ProgressBarWidget( {
8758 * progress: 33
8759 * } );
8760 * var progressBar2 = new OO.ui.ProgressBarWidget();
8761 *
8762 * // Create a FieldsetLayout to layout progress bars
8763 * var fieldset = new OO.ui.FieldsetLayout;
8764 * fieldset.addItems( [
8765 * new OO.ui.FieldLayout( progressBar1, {label: 'Determinate', align: 'top'}),
8766 * new OO.ui.FieldLayout( progressBar2, {label: 'Indeterminate', align: 'top'})
8767 * ] );
8768 * $( 'body' ).append( fieldset.$element );
8769 *
8770 * @class
8771 * @extends OO.ui.Widget
8772 *
8773 * @constructor
8774 * @param {Object} [config] Configuration options
8775 * @cfg {number|boolean} [progress=false] The type of progress bar (determinate or indeterminate).
8776 * To create a determinate progress bar, specify a number that reflects the initial percent complete.
8777 * By default, the progress bar is indeterminate.
8778 */
8779 OO.ui.ProgressBarWidget = function OoUiProgressBarWidget( config ) {
8780 // Configuration initialization
8781 config = config || {};
8782
8783 // Parent constructor
8784 OO.ui.ProgressBarWidget.parent.call( this, config );
8785
8786 // Properties
8787 this.$bar = $( '<div>' );
8788 this.progress = null;
8789
8790 // Initialization
8791 this.setProgress( config.progress !== undefined ? config.progress : false );
8792 this.$bar.addClass( 'oo-ui-progressBarWidget-bar' );
8793 this.$element
8794 .attr( {
8795 role: 'progressbar',
8796 'aria-valuemin': 0,
8797 'aria-valuemax': 100
8798 } )
8799 .addClass( 'oo-ui-progressBarWidget' )
8800 .append( this.$bar );
8801 };
8802
8803 /* Setup */
8804
8805 OO.inheritClass( OO.ui.ProgressBarWidget, OO.ui.Widget );
8806
8807 /* Static Properties */
8808
8809 /**
8810 * @static
8811 * @inheritdoc
8812 */
8813 OO.ui.ProgressBarWidget.static.tagName = 'div';
8814
8815 /* Methods */
8816
8817 /**
8818 * Get the percent of the progress that has been completed. Indeterminate progresses will return `false`.
8819 *
8820 * @return {number|boolean} Progress percent
8821 */
8822 OO.ui.ProgressBarWidget.prototype.getProgress = function () {
8823 return this.progress;
8824 };
8825
8826 /**
8827 * Set the percent of the process completed or `false` for an indeterminate process.
8828 *
8829 * @param {number|boolean} progress Progress percent or `false` for indeterminate
8830 */
8831 OO.ui.ProgressBarWidget.prototype.setProgress = function ( progress ) {
8832 this.progress = progress;
8833
8834 if ( progress !== false ) {
8835 this.$bar.css( 'width', this.progress + '%' );
8836 this.$element.attr( 'aria-valuenow', this.progress );
8837 } else {
8838 this.$bar.css( 'width', '' );
8839 this.$element.removeAttr( 'aria-valuenow' );
8840 }
8841 this.$element.toggleClass( 'oo-ui-progressBarWidget-indeterminate', progress === false );
8842 };
8843
8844 /**
8845 * InputWidget is the base class for all input widgets, which
8846 * include {@link OO.ui.TextInputWidget text inputs}, {@link OO.ui.CheckboxInputWidget checkbox inputs},
8847 * {@link OO.ui.RadioInputWidget radio inputs}, and {@link OO.ui.ButtonInputWidget button inputs}.
8848 * See the [OOUI documentation on MediaWiki] [1] for more information and examples.
8849 *
8850 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
8851 *
8852 * @abstract
8853 * @class
8854 * @extends OO.ui.Widget
8855 * @mixins OO.ui.mixin.FlaggedElement
8856 * @mixins OO.ui.mixin.TabIndexedElement
8857 * @mixins OO.ui.mixin.TitledElement
8858 * @mixins OO.ui.mixin.AccessKeyedElement
8859 *
8860 * @constructor
8861 * @param {Object} [config] Configuration options
8862 * @cfg {string} [name=''] The value of the input’s HTML `name` attribute.
8863 * @cfg {string} [value=''] The value of the input.
8864 * @cfg {string} [dir] The directionality of the input (ltr/rtl).
8865 * @cfg {string} [inputId] The value of the input’s HTML `id` attribute.
8866 * @cfg {Function} [inputFilter] The name of an input filter function. Input filters modify the value of an input
8867 * before it is accepted.
8868 */
8869 OO.ui.InputWidget = function OoUiInputWidget( config ) {
8870 // Configuration initialization
8871 config = config || {};
8872
8873 // Parent constructor
8874 OO.ui.InputWidget.parent.call( this, config );
8875
8876 // Properties
8877 // See #reusePreInfuseDOM about config.$input
8878 this.$input = config.$input || this.getInputElement( config );
8879 this.value = '';
8880 this.inputFilter = config.inputFilter;
8881
8882 // Mixin constructors
8883 OO.ui.mixin.FlaggedElement.call( this, config );
8884 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$input } ) );
8885 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$input } ) );
8886 OO.ui.mixin.AccessKeyedElement.call( this, $.extend( {}, config, { $accessKeyed: this.$input } ) );
8887
8888 // Events
8889 this.$input.on( 'keydown mouseup cut paste change input select', this.onEdit.bind( this ) );
8890
8891 // Initialization
8892 this.$input
8893 .addClass( 'oo-ui-inputWidget-input' )
8894 .attr( 'name', config.name )
8895 .prop( 'disabled', this.isDisabled() );
8896 this.$element
8897 .addClass( 'oo-ui-inputWidget' )
8898 .append( this.$input );
8899 this.setValue( config.value );
8900 if ( config.dir ) {
8901 this.setDir( config.dir );
8902 }
8903 if ( config.inputId !== undefined ) {
8904 this.setInputId( config.inputId );
8905 }
8906 };
8907
8908 /* Setup */
8909
8910 OO.inheritClass( OO.ui.InputWidget, OO.ui.Widget );
8911 OO.mixinClass( OO.ui.InputWidget, OO.ui.mixin.FlaggedElement );
8912 OO.mixinClass( OO.ui.InputWidget, OO.ui.mixin.TabIndexedElement );
8913 OO.mixinClass( OO.ui.InputWidget, OO.ui.mixin.TitledElement );
8914 OO.mixinClass( OO.ui.InputWidget, OO.ui.mixin.AccessKeyedElement );
8915
8916 /* Static Methods */
8917
8918 /**
8919 * @inheritdoc
8920 */
8921 OO.ui.InputWidget.static.reusePreInfuseDOM = function ( node, config ) {
8922 config = OO.ui.InputWidget.parent.static.reusePreInfuseDOM( node, config );
8923 // Reusing `$input` lets browsers preserve inputted values across page reloads, see T114134.
8924 config.$input = $( node ).find( '.oo-ui-inputWidget-input' );
8925 return config;
8926 };
8927
8928 /**
8929 * @inheritdoc
8930 */
8931 OO.ui.InputWidget.static.gatherPreInfuseState = function ( node, config ) {
8932 var state = OO.ui.InputWidget.parent.static.gatherPreInfuseState( node, config );
8933 if ( config.$input && config.$input.length ) {
8934 state.value = config.$input.val();
8935 // Might be better in TabIndexedElement, but it's awkward to do there because mixins are awkward
8936 state.focus = config.$input.is( ':focus' );
8937 }
8938 return state;
8939 };
8940
8941 /* Events */
8942
8943 /**
8944 * @event change
8945 *
8946 * A change event is emitted when the value of the input changes.
8947 *
8948 * @param {string} value
8949 */
8950
8951 /* Methods */
8952
8953 /**
8954 * Get input element.
8955 *
8956 * Subclasses of OO.ui.InputWidget use the `config` parameter to produce different elements in
8957 * different circumstances. The element must have a `value` property (like form elements).
8958 *
8959 * @protected
8960 * @param {Object} config Configuration options
8961 * @return {jQuery} Input element
8962 */
8963 OO.ui.InputWidget.prototype.getInputElement = function () {
8964 return $( '<input>' );
8965 };
8966
8967 /**
8968 * Handle potentially value-changing events.
8969 *
8970 * @private
8971 * @param {jQuery.Event} e Key down, mouse up, cut, paste, change, input, or select event
8972 */
8973 OO.ui.InputWidget.prototype.onEdit = function () {
8974 var widget = this;
8975 if ( !this.isDisabled() ) {
8976 // Allow the stack to clear so the value will be updated
8977 setTimeout( function () {
8978 widget.setValue( widget.$input.val() );
8979 } );
8980 }
8981 };
8982
8983 /**
8984 * Get the value of the input.
8985 *
8986 * @return {string} Input value
8987 */
8988 OO.ui.InputWidget.prototype.getValue = function () {
8989 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
8990 // it, and we won't know unless they're kind enough to trigger a 'change' event.
8991 var value = this.$input.val();
8992 if ( this.value !== value ) {
8993 this.setValue( value );
8994 }
8995 return this.value;
8996 };
8997
8998 /**
8999 * Set the directionality of the input.
9000 *
9001 * @param {string} dir Text directionality: 'ltr', 'rtl' or 'auto'
9002 * @chainable
9003 * @return {OO.ui.Widget} The widget, for chaining
9004 */
9005 OO.ui.InputWidget.prototype.setDir = function ( dir ) {
9006 this.$input.prop( 'dir', dir );
9007 return this;
9008 };
9009
9010 /**
9011 * Set the value of the input.
9012 *
9013 * @param {string} value New value
9014 * @fires change
9015 * @chainable
9016 * @return {OO.ui.Widget} The widget, for chaining
9017 */
9018 OO.ui.InputWidget.prototype.setValue = function ( value ) {
9019 value = this.cleanUpValue( value );
9020 // Update the DOM if it has changed. Note that with cleanUpValue, it
9021 // is possible for the DOM value to change without this.value changing.
9022 if ( this.$input.val() !== value ) {
9023 this.$input.val( value );
9024 }
9025 if ( this.value !== value ) {
9026 this.value = value;
9027 this.emit( 'change', this.value );
9028 }
9029 // The first time that the value is set (probably while constructing the widget),
9030 // remember it in defaultValue. This property can be later used to check whether
9031 // the value of the input has been changed since it was created.
9032 if ( this.defaultValue === undefined ) {
9033 this.defaultValue = this.value;
9034 this.$input[ 0 ].defaultValue = this.defaultValue;
9035 }
9036 return this;
9037 };
9038
9039 /**
9040 * Clean up incoming value.
9041 *
9042 * Ensures value is a string, and converts undefined and null to empty string.
9043 *
9044 * @private
9045 * @param {string} value Original value
9046 * @return {string} Cleaned up value
9047 */
9048 OO.ui.InputWidget.prototype.cleanUpValue = function ( value ) {
9049 if ( value === undefined || value === null ) {
9050 return '';
9051 } else if ( this.inputFilter ) {
9052 return this.inputFilter( String( value ) );
9053 } else {
9054 return String( value );
9055 }
9056 };
9057
9058 /**
9059 * @inheritdoc
9060 */
9061 OO.ui.InputWidget.prototype.setDisabled = function ( state ) {
9062 OO.ui.InputWidget.parent.prototype.setDisabled.call( this, state );
9063 if ( this.$input ) {
9064 this.$input.prop( 'disabled', this.isDisabled() );
9065 }
9066 return this;
9067 };
9068
9069 /**
9070 * Set the 'id' attribute of the `<input>` element.
9071 *
9072 * @param {string} id
9073 * @chainable
9074 * @return {OO.ui.Widget} The widget, for chaining
9075 */
9076 OO.ui.InputWidget.prototype.setInputId = function ( id ) {
9077 this.$input.attr( 'id', id );
9078 return this;
9079 };
9080
9081 /**
9082 * @inheritdoc
9083 */
9084 OO.ui.InputWidget.prototype.restorePreInfuseState = function ( state ) {
9085 OO.ui.InputWidget.parent.prototype.restorePreInfuseState.call( this, state );
9086 if ( state.value !== undefined && state.value !== this.getValue() ) {
9087 this.setValue( state.value );
9088 }
9089 if ( state.focus ) {
9090 this.focus();
9091 }
9092 };
9093
9094 /**
9095 * Data widget intended for creating 'hidden'-type inputs.
9096 *
9097 * @class
9098 * @extends OO.ui.Widget
9099 *
9100 * @constructor
9101 * @param {Object} [config] Configuration options
9102 * @cfg {string} [value=''] The value of the input.
9103 * @cfg {string} [name=''] The value of the input’s HTML `name` attribute.
9104 */
9105 OO.ui.HiddenInputWidget = function OoUiHiddenInputWidget( config ) {
9106 // Configuration initialization
9107 config = $.extend( { value: '', name: '' }, config );
9108
9109 // Parent constructor
9110 OO.ui.HiddenInputWidget.parent.call( this, config );
9111
9112 // Initialization
9113 this.$element.attr( {
9114 type: 'hidden',
9115 value: config.value,
9116 name: config.name
9117 } );
9118 this.$element.removeAttr( 'aria-disabled' );
9119 };
9120
9121 /* Setup */
9122
9123 OO.inheritClass( OO.ui.HiddenInputWidget, OO.ui.Widget );
9124
9125 /* Static Properties */
9126
9127 /**
9128 * @static
9129 * @inheritdoc
9130 */
9131 OO.ui.HiddenInputWidget.static.tagName = 'input';
9132
9133 /**
9134 * ButtonInputWidget is used to submit HTML forms and is intended to be used within
9135 * a OO.ui.FormLayout. If you do not need the button to work with HTML forms, you probably
9136 * want to use OO.ui.ButtonWidget instead. Button input widgets can be rendered as either an
9137 * HTML `<button>` (the default) or an HTML `<input>` tags. See the
9138 * [OOUI documentation on MediaWiki] [1] for more information.
9139 *
9140 * @example
9141 * // A ButtonInputWidget rendered as an HTML button, the default.
9142 * var button = new OO.ui.ButtonInputWidget( {
9143 * label: 'Input button',
9144 * icon: 'check',
9145 * value: 'check'
9146 * } );
9147 * $( 'body' ).append( button.$element );
9148 *
9149 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs#Button_inputs
9150 *
9151 * @class
9152 * @extends OO.ui.InputWidget
9153 * @mixins OO.ui.mixin.ButtonElement
9154 * @mixins OO.ui.mixin.IconElement
9155 * @mixins OO.ui.mixin.IndicatorElement
9156 * @mixins OO.ui.mixin.LabelElement
9157 * @mixins OO.ui.mixin.TitledElement
9158 *
9159 * @constructor
9160 * @param {Object} [config] Configuration options
9161 * @cfg {string} [type='button'] The value of the HTML `'type'` attribute: 'button', 'submit' or 'reset'.
9162 * @cfg {boolean} [useInputTag=false] Use an `<input>` tag instead of a `<button>` tag, the default.
9163 * Widgets configured to be an `<input>` do not support {@link #icon icons} and {@link #indicator indicators},
9164 * non-plaintext {@link #label labels}, or {@link #value values}. In general, useInputTag should only
9165 * be set to `true` when there’s need to support IE 6 in a form with multiple buttons.
9166 */
9167 OO.ui.ButtonInputWidget = function OoUiButtonInputWidget( config ) {
9168 // Configuration initialization
9169 config = $.extend( { type: 'button', useInputTag: false }, config );
9170
9171 // See InputWidget#reusePreInfuseDOM about config.$input
9172 if ( config.$input ) {
9173 config.$input.empty();
9174 }
9175
9176 // Properties (must be set before parent constructor, which calls #setValue)
9177 this.useInputTag = config.useInputTag;
9178
9179 // Parent constructor
9180 OO.ui.ButtonInputWidget.parent.call( this, config );
9181
9182 // Mixin constructors
9183 OO.ui.mixin.ButtonElement.call( this, $.extend( {}, config, { $button: this.$input } ) );
9184 OO.ui.mixin.IconElement.call( this, config );
9185 OO.ui.mixin.IndicatorElement.call( this, config );
9186 OO.ui.mixin.LabelElement.call( this, config );
9187 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$input } ) );
9188
9189 // Initialization
9190 if ( !config.useInputTag ) {
9191 this.$input.append( this.$icon, this.$label, this.$indicator );
9192 }
9193 this.$element.addClass( 'oo-ui-buttonInputWidget' );
9194 };
9195
9196 /* Setup */
9197
9198 OO.inheritClass( OO.ui.ButtonInputWidget, OO.ui.InputWidget );
9199 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.ButtonElement );
9200 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.IconElement );
9201 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.IndicatorElement );
9202 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.LabelElement );
9203 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.TitledElement );
9204
9205 /* Static Properties */
9206
9207 /**
9208 * @static
9209 * @inheritdoc
9210 */
9211 OO.ui.ButtonInputWidget.static.tagName = 'span';
9212
9213 /* Methods */
9214
9215 /**
9216 * @inheritdoc
9217 * @protected
9218 */
9219 OO.ui.ButtonInputWidget.prototype.getInputElement = function ( config ) {
9220 var type;
9221 type = [ 'button', 'submit', 'reset' ].indexOf( config.type ) !== -1 ? config.type : 'button';
9222 return $( '<' + ( config.useInputTag ? 'input' : 'button' ) + ' type="' + type + '">' );
9223 };
9224
9225 /**
9226 * Set label value.
9227 *
9228 * If #useInputTag is `true`, the label is set as the `value` of the `<input>` tag.
9229 *
9230 * @param {jQuery|string|Function|null} label Label nodes, text, a function that returns nodes or
9231 * text, or `null` for no label
9232 * @chainable
9233 * @return {OO.ui.Widget} The widget, for chaining
9234 */
9235 OO.ui.ButtonInputWidget.prototype.setLabel = function ( label ) {
9236 if ( typeof label === 'function' ) {
9237 label = OO.ui.resolveMsg( label );
9238 }
9239
9240 if ( this.useInputTag ) {
9241 // Discard non-plaintext labels
9242 if ( typeof label !== 'string' ) {
9243 label = '';
9244 }
9245
9246 this.$input.val( label );
9247 }
9248
9249 return OO.ui.mixin.LabelElement.prototype.setLabel.call( this, label );
9250 };
9251
9252 /**
9253 * Set the value of the input.
9254 *
9255 * This method is disabled for button inputs configured as {@link #useInputTag <input> tags}, as
9256 * they do not support {@link #value values}.
9257 *
9258 * @param {string} value New value
9259 * @chainable
9260 * @return {OO.ui.Widget} The widget, for chaining
9261 */
9262 OO.ui.ButtonInputWidget.prototype.setValue = function ( value ) {
9263 if ( !this.useInputTag ) {
9264 OO.ui.ButtonInputWidget.parent.prototype.setValue.call( this, value );
9265 }
9266 return this;
9267 };
9268
9269 /**
9270 * @inheritdoc
9271 */
9272 OO.ui.ButtonInputWidget.prototype.getInputId = function () {
9273 // Disable generating `<label>` elements for buttons. One would very rarely need additional label
9274 // for a button, and it's already a big clickable target, and it causes unexpected rendering.
9275 return null;
9276 };
9277
9278 /**
9279 * CheckboxInputWidgets, like HTML checkboxes, can be selected and/or configured with a value.
9280 * Note that these {@link OO.ui.InputWidget input widgets} are best laid out
9281 * in {@link OO.ui.FieldLayout field layouts} that use the {@link OO.ui.FieldLayout#align inline}
9282 * alignment. For more information, please see the [OOUI documentation on MediaWiki][1].
9283 *
9284 * This widget can be used inside an HTML form, such as a OO.ui.FormLayout.
9285 *
9286 * @example
9287 * // An example of selected, unselected, and disabled checkbox inputs
9288 * var checkbox1=new OO.ui.CheckboxInputWidget( {
9289 * value: 'a',
9290 * selected: true
9291 * } );
9292 * var checkbox2=new OO.ui.CheckboxInputWidget( {
9293 * value: 'b'
9294 * } );
9295 * var checkbox3=new OO.ui.CheckboxInputWidget( {
9296 * value:'c',
9297 * disabled: true
9298 * } );
9299 * // Create a fieldset layout with fields for each checkbox.
9300 * var fieldset = new OO.ui.FieldsetLayout( {
9301 * label: 'Checkboxes'
9302 * } );
9303 * fieldset.addItems( [
9304 * new OO.ui.FieldLayout( checkbox1, { label: 'Selected checkbox', align: 'inline' } ),
9305 * new OO.ui.FieldLayout( checkbox2, { label: 'Unselected checkbox', align: 'inline' } ),
9306 * new OO.ui.FieldLayout( checkbox3, { label: 'Disabled checkbox', align: 'inline' } ),
9307 * ] );
9308 * $( 'body' ).append( fieldset.$element );
9309 *
9310 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
9311 *
9312 * @class
9313 * @extends OO.ui.InputWidget
9314 *
9315 * @constructor
9316 * @param {Object} [config] Configuration options
9317 * @cfg {boolean} [selected=false] Select the checkbox initially. By default, the checkbox is not selected.
9318 */
9319 OO.ui.CheckboxInputWidget = function OoUiCheckboxInputWidget( config ) {
9320 // Configuration initialization
9321 config = config || {};
9322
9323 // Parent constructor
9324 OO.ui.CheckboxInputWidget.parent.call( this, config );
9325
9326 // Properties
9327 this.checkIcon = new OO.ui.IconWidget( {
9328 icon: 'check',
9329 classes: [ 'oo-ui-checkboxInputWidget-checkIcon' ]
9330 } );
9331
9332 // Initialization
9333 this.$element
9334 .addClass( 'oo-ui-checkboxInputWidget' )
9335 // Required for pretty styling in WikimediaUI theme
9336 .append( this.checkIcon.$element );
9337 this.setSelected( config.selected !== undefined ? config.selected : false );
9338 };
9339
9340 /* Setup */
9341
9342 OO.inheritClass( OO.ui.CheckboxInputWidget, OO.ui.InputWidget );
9343
9344 /* Static Properties */
9345
9346 /**
9347 * @static
9348 * @inheritdoc
9349 */
9350 OO.ui.CheckboxInputWidget.static.tagName = 'span';
9351
9352 /* Static Methods */
9353
9354 /**
9355 * @inheritdoc
9356 */
9357 OO.ui.CheckboxInputWidget.static.gatherPreInfuseState = function ( node, config ) {
9358 var state = OO.ui.CheckboxInputWidget.parent.static.gatherPreInfuseState( node, config );
9359 state.checked = config.$input.prop( 'checked' );
9360 return state;
9361 };
9362
9363 /* Methods */
9364
9365 /**
9366 * @inheritdoc
9367 * @protected
9368 */
9369 OO.ui.CheckboxInputWidget.prototype.getInputElement = function () {
9370 return $( '<input>' ).attr( 'type', 'checkbox' );
9371 };
9372
9373 /**
9374 * @inheritdoc
9375 */
9376 OO.ui.CheckboxInputWidget.prototype.onEdit = function () {
9377 var widget = this;
9378 if ( !this.isDisabled() ) {
9379 // Allow the stack to clear so the value will be updated
9380 setTimeout( function () {
9381 widget.setSelected( widget.$input.prop( 'checked' ) );
9382 } );
9383 }
9384 };
9385
9386 /**
9387 * Set selection state of this checkbox.
9388 *
9389 * @param {boolean} state `true` for selected
9390 * @chainable
9391 * @return {OO.ui.Widget} The widget, for chaining
9392 */
9393 OO.ui.CheckboxInputWidget.prototype.setSelected = function ( state ) {
9394 state = !!state;
9395 if ( this.selected !== state ) {
9396 this.selected = state;
9397 this.$input.prop( 'checked', this.selected );
9398 this.emit( 'change', this.selected );
9399 }
9400 // The first time that the selection state is set (probably while constructing the widget),
9401 // remember it in defaultSelected. This property can be later used to check whether
9402 // the selection state of the input has been changed since it was created.
9403 if ( this.defaultSelected === undefined ) {
9404 this.defaultSelected = this.selected;
9405 this.$input[ 0 ].defaultChecked = this.defaultSelected;
9406 }
9407 return this;
9408 };
9409
9410 /**
9411 * Check if this checkbox is selected.
9412 *
9413 * @return {boolean} Checkbox is selected
9414 */
9415 OO.ui.CheckboxInputWidget.prototype.isSelected = function () {
9416 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
9417 // it, and we won't know unless they're kind enough to trigger a 'change' event.
9418 var selected = this.$input.prop( 'checked' );
9419 if ( this.selected !== selected ) {
9420 this.setSelected( selected );
9421 }
9422 return this.selected;
9423 };
9424
9425 /**
9426 * @inheritdoc
9427 */
9428 OO.ui.CheckboxInputWidget.prototype.simulateLabelClick = function () {
9429 if ( !this.isDisabled() ) {
9430 this.$input.click();
9431 }
9432 this.focus();
9433 };
9434
9435 /**
9436 * @inheritdoc
9437 */
9438 OO.ui.CheckboxInputWidget.prototype.restorePreInfuseState = function ( state ) {
9439 OO.ui.CheckboxInputWidget.parent.prototype.restorePreInfuseState.call( this, state );
9440 if ( state.checked !== undefined && state.checked !== this.isSelected() ) {
9441 this.setSelected( state.checked );
9442 }
9443 };
9444
9445 /**
9446 * DropdownInputWidget is a {@link OO.ui.DropdownWidget DropdownWidget} intended to be used
9447 * within an HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with the value
9448 * of a hidden HTML `input` tag. Please see the [OOUI documentation on MediaWiki][1] for
9449 * more information about input widgets.
9450 *
9451 * A DropdownInputWidget always has a value (one of the options is always selected), unless there
9452 * are no options. If no `value` configuration option is provided, the first option is selected.
9453 * If you need a state representing no value (no option being selected), use a DropdownWidget.
9454 *
9455 * This and OO.ui.RadioSelectInputWidget support the same configuration options.
9456 *
9457 * @example
9458 * // Example: A DropdownInputWidget with three options
9459 * var dropdownInput = new OO.ui.DropdownInputWidget( {
9460 * options: [
9461 * { data: 'a', label: 'First' },
9462 * { data: 'b', label: 'Second'},
9463 * { data: 'c', label: 'Third' }
9464 * ]
9465 * } );
9466 * $( 'body' ).append( dropdownInput.$element );
9467 *
9468 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
9469 *
9470 * @class
9471 * @extends OO.ui.InputWidget
9472 *
9473 * @constructor
9474 * @param {Object} [config] Configuration options
9475 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
9476 * @cfg {Object} [dropdown] Configuration options for {@link OO.ui.DropdownWidget DropdownWidget}
9477 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
9478 * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
9479 * containing `<div>` and has a larger area. By default, the menu uses relative positioning.
9480 * See <https://www.mediawiki.org/wiki/OOUI/Concepts#Overlays>.
9481 */
9482 OO.ui.DropdownInputWidget = function OoUiDropdownInputWidget( config ) {
9483 // Configuration initialization
9484 config = config || {};
9485
9486 // Properties (must be done before parent constructor which calls #setDisabled)
9487 this.dropdownWidget = new OO.ui.DropdownWidget( $.extend(
9488 {
9489 $overlay: config.$overlay
9490 },
9491 config.dropdown
9492 ) );
9493 // Set up the options before parent constructor, which uses them to validate config.value.
9494 // Use this instead of setOptions() because this.$input is not set up yet.
9495 this.setOptionsData( config.options || [] );
9496
9497 // Parent constructor
9498 OO.ui.DropdownInputWidget.parent.call( this, config );
9499
9500 // Events
9501 this.dropdownWidget.getMenu().connect( this, { select: 'onMenuSelect' } );
9502
9503 // Initialization
9504 this.$element
9505 .addClass( 'oo-ui-dropdownInputWidget' )
9506 .append( this.dropdownWidget.$element );
9507 this.setTabIndexedElement( this.dropdownWidget.$tabIndexed );
9508 };
9509
9510 /* Setup */
9511
9512 OO.inheritClass( OO.ui.DropdownInputWidget, OO.ui.InputWidget );
9513
9514 /* Methods */
9515
9516 /**
9517 * @inheritdoc
9518 * @protected
9519 */
9520 OO.ui.DropdownInputWidget.prototype.getInputElement = function () {
9521 return $( '<select>' );
9522 };
9523
9524 /**
9525 * Handles menu select events.
9526 *
9527 * @private
9528 * @param {OO.ui.MenuOptionWidget|null} item Selected menu item
9529 */
9530 OO.ui.DropdownInputWidget.prototype.onMenuSelect = function ( item ) {
9531 this.setValue( item ? item.getData() : '' );
9532 };
9533
9534 /**
9535 * @inheritdoc
9536 */
9537 OO.ui.DropdownInputWidget.prototype.setValue = function ( value ) {
9538 var selected;
9539 value = this.cleanUpValue( value );
9540 // Only allow setting values that are actually present in the dropdown
9541 selected = this.dropdownWidget.getMenu().findItemFromData( value ) ||
9542 this.dropdownWidget.getMenu().findFirstSelectableItem();
9543 this.dropdownWidget.getMenu().selectItem( selected );
9544 value = selected ? selected.getData() : '';
9545 OO.ui.DropdownInputWidget.parent.prototype.setValue.call( this, value );
9546 if ( this.optionsDirty ) {
9547 // We reached this from the constructor or from #setOptions.
9548 // We have to update the <select> element.
9549 this.updateOptionsInterface();
9550 }
9551 return this;
9552 };
9553
9554 /**
9555 * @inheritdoc
9556 */
9557 OO.ui.DropdownInputWidget.prototype.setDisabled = function ( state ) {
9558 this.dropdownWidget.setDisabled( state );
9559 OO.ui.DropdownInputWidget.parent.prototype.setDisabled.call( this, state );
9560 return this;
9561 };
9562
9563 /**
9564 * Set the options available for this input.
9565 *
9566 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
9567 * @chainable
9568 * @return {OO.ui.Widget} The widget, for chaining
9569 */
9570 OO.ui.DropdownInputWidget.prototype.setOptions = function ( options ) {
9571 var value = this.getValue();
9572
9573 this.setOptionsData( options );
9574
9575 // Re-set the value to update the visible interface (DropdownWidget and <select>).
9576 // In case the previous value is no longer an available option, select the first valid one.
9577 this.setValue( value );
9578
9579 return this;
9580 };
9581
9582 /**
9583 * Set the internal list of options, used e.g. by setValue() to see which options are allowed.
9584 *
9585 * This method may be called before the parent constructor, so various properties may not be
9586 * intialized yet.
9587 *
9588 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
9589 * @private
9590 */
9591 OO.ui.DropdownInputWidget.prototype.setOptionsData = function ( options ) {
9592 var
9593 optionWidgets,
9594 widget = this;
9595
9596 this.optionsDirty = true;
9597
9598 optionWidgets = options.map( function ( opt ) {
9599 var optValue;
9600
9601 if ( opt.optgroup !== undefined ) {
9602 return widget.createMenuSectionOptionWidget( opt.optgroup );
9603 }
9604
9605 optValue = widget.cleanUpValue( opt.data );
9606 return widget.createMenuOptionWidget(
9607 optValue,
9608 opt.label !== undefined ? opt.label : optValue
9609 );
9610
9611 } );
9612
9613 this.dropdownWidget.getMenu().clearItems().addItems( optionWidgets );
9614 };
9615
9616 /**
9617 * Create a menu option widget.
9618 *
9619 * @protected
9620 * @param {string} data Item data
9621 * @param {string} label Item label
9622 * @return {OO.ui.MenuOptionWidget} Option widget
9623 */
9624 OO.ui.DropdownInputWidget.prototype.createMenuOptionWidget = function ( data, label ) {
9625 return new OO.ui.MenuOptionWidget( {
9626 data: data,
9627 label: label
9628 } );
9629 };
9630
9631 /**
9632 * Create a menu section option widget.
9633 *
9634 * @protected
9635 * @param {string} label Section item label
9636 * @return {OO.ui.MenuSectionOptionWidget} Menu section option widget
9637 */
9638 OO.ui.DropdownInputWidget.prototype.createMenuSectionOptionWidget = function ( label ) {
9639 return new OO.ui.MenuSectionOptionWidget( {
9640 label: label
9641 } );
9642 };
9643
9644 /**
9645 * Update the user-visible interface to match the internal list of options and value.
9646 *
9647 * This method must only be called after the parent constructor.
9648 *
9649 * @private
9650 */
9651 OO.ui.DropdownInputWidget.prototype.updateOptionsInterface = function () {
9652 var
9653 $optionsContainer = this.$input,
9654 defaultValue = this.defaultValue,
9655 widget = this;
9656
9657 this.$input.empty();
9658
9659 this.dropdownWidget.getMenu().getItems().forEach( function ( optionWidget ) {
9660 var $optionNode;
9661
9662 if ( !( optionWidget instanceof OO.ui.MenuSectionOptionWidget ) ) {
9663 $optionNode = $( '<option>' )
9664 .attr( 'value', optionWidget.getData() )
9665 .text( optionWidget.getLabel() );
9666
9667 // Remember original selection state. This property can be later used to check whether
9668 // the selection state of the input has been changed since it was created.
9669 $optionNode[ 0 ].defaultSelected = ( optionWidget.getData() === defaultValue );
9670
9671 $optionsContainer.append( $optionNode );
9672 } else {
9673 $optionNode = $( '<optgroup>' )
9674 .attr( 'label', optionWidget.getLabel() );
9675 widget.$input.append( $optionNode );
9676 $optionsContainer = $optionNode;
9677 }
9678 } );
9679
9680 this.optionsDirty = false;
9681 };
9682
9683 /**
9684 * @inheritdoc
9685 */
9686 OO.ui.DropdownInputWidget.prototype.focus = function () {
9687 this.dropdownWidget.focus();
9688 return this;
9689 };
9690
9691 /**
9692 * @inheritdoc
9693 */
9694 OO.ui.DropdownInputWidget.prototype.blur = function () {
9695 this.dropdownWidget.blur();
9696 return this;
9697 };
9698
9699 /**
9700 * RadioInputWidget creates a single radio button. Because radio buttons are usually used as a set,
9701 * in most cases you will want to use a {@link OO.ui.RadioSelectWidget radio select}
9702 * with {@link OO.ui.RadioOptionWidget radio options} instead of this class. For more information,
9703 * please see the [OOUI documentation on MediaWiki][1].
9704 *
9705 * This widget can be used inside an HTML form, such as a OO.ui.FormLayout.
9706 *
9707 * @example
9708 * // An example of selected, unselected, and disabled radio inputs
9709 * var radio1 = new OO.ui.RadioInputWidget( {
9710 * value: 'a',
9711 * selected: true
9712 * } );
9713 * var radio2 = new OO.ui.RadioInputWidget( {
9714 * value: 'b'
9715 * } );
9716 * var radio3 = new OO.ui.RadioInputWidget( {
9717 * value: 'c',
9718 * disabled: true
9719 * } );
9720 * // Create a fieldset layout with fields for each radio button.
9721 * var fieldset = new OO.ui.FieldsetLayout( {
9722 * label: 'Radio inputs'
9723 * } );
9724 * fieldset.addItems( [
9725 * new OO.ui.FieldLayout( radio1, { label: 'Selected', align: 'inline' } ),
9726 * new OO.ui.FieldLayout( radio2, { label: 'Unselected', align: 'inline' } ),
9727 * new OO.ui.FieldLayout( radio3, { label: 'Disabled', align: 'inline' } ),
9728 * ] );
9729 * $( 'body' ).append( fieldset.$element );
9730 *
9731 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
9732 *
9733 * @class
9734 * @extends OO.ui.InputWidget
9735 *
9736 * @constructor
9737 * @param {Object} [config] Configuration options
9738 * @cfg {boolean} [selected=false] Select the radio button initially. By default, the radio button is not selected.
9739 */
9740 OO.ui.RadioInputWidget = function OoUiRadioInputWidget( config ) {
9741 // Configuration initialization
9742 config = config || {};
9743
9744 // Parent constructor
9745 OO.ui.RadioInputWidget.parent.call( this, config );
9746
9747 // Initialization
9748 this.$element
9749 .addClass( 'oo-ui-radioInputWidget' )
9750 // Required for pretty styling in WikimediaUI theme
9751 .append( $( '<span>' ) );
9752 this.setSelected( config.selected !== undefined ? config.selected : false );
9753 };
9754
9755 /* Setup */
9756
9757 OO.inheritClass( OO.ui.RadioInputWidget, OO.ui.InputWidget );
9758
9759 /* Static Properties */
9760
9761 /**
9762 * @static
9763 * @inheritdoc
9764 */
9765 OO.ui.RadioInputWidget.static.tagName = 'span';
9766
9767 /* Static Methods */
9768
9769 /**
9770 * @inheritdoc
9771 */
9772 OO.ui.RadioInputWidget.static.gatherPreInfuseState = function ( node, config ) {
9773 var state = OO.ui.RadioInputWidget.parent.static.gatherPreInfuseState( node, config );
9774 state.checked = config.$input.prop( 'checked' );
9775 return state;
9776 };
9777
9778 /* Methods */
9779
9780 /**
9781 * @inheritdoc
9782 * @protected
9783 */
9784 OO.ui.RadioInputWidget.prototype.getInputElement = function () {
9785 return $( '<input>' ).attr( 'type', 'radio' );
9786 };
9787
9788 /**
9789 * @inheritdoc
9790 */
9791 OO.ui.RadioInputWidget.prototype.onEdit = function () {
9792 // RadioInputWidget doesn't track its state.
9793 };
9794
9795 /**
9796 * Set selection state of this radio button.
9797 *
9798 * @param {boolean} state `true` for selected
9799 * @chainable
9800 * @return {OO.ui.Widget} The widget, for chaining
9801 */
9802 OO.ui.RadioInputWidget.prototype.setSelected = function ( state ) {
9803 // RadioInputWidget doesn't track its state.
9804 this.$input.prop( 'checked', state );
9805 // The first time that the selection state is set (probably while constructing the widget),
9806 // remember it in defaultSelected. This property can be later used to check whether
9807 // the selection state of the input has been changed since it was created.
9808 if ( this.defaultSelected === undefined ) {
9809 this.defaultSelected = state;
9810 this.$input[ 0 ].defaultChecked = this.defaultSelected;
9811 }
9812 return this;
9813 };
9814
9815 /**
9816 * Check if this radio button is selected.
9817 *
9818 * @return {boolean} Radio is selected
9819 */
9820 OO.ui.RadioInputWidget.prototype.isSelected = function () {
9821 return this.$input.prop( 'checked' );
9822 };
9823
9824 /**
9825 * @inheritdoc
9826 */
9827 OO.ui.RadioInputWidget.prototype.simulateLabelClick = function () {
9828 if ( !this.isDisabled() ) {
9829 this.$input.click();
9830 }
9831 this.focus();
9832 };
9833
9834 /**
9835 * @inheritdoc
9836 */
9837 OO.ui.RadioInputWidget.prototype.restorePreInfuseState = function ( state ) {
9838 OO.ui.RadioInputWidget.parent.prototype.restorePreInfuseState.call( this, state );
9839 if ( state.checked !== undefined && state.checked !== this.isSelected() ) {
9840 this.setSelected( state.checked );
9841 }
9842 };
9843
9844 /**
9845 * RadioSelectInputWidget is a {@link OO.ui.RadioSelectWidget RadioSelectWidget} intended to be used
9846 * within an HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with the value
9847 * of a hidden HTML `input` tag. Please see the [OOUI documentation on MediaWiki][1] for
9848 * more information about input widgets.
9849 *
9850 * This and OO.ui.DropdownInputWidget support the same configuration options.
9851 *
9852 * @example
9853 * // Example: A RadioSelectInputWidget with three options
9854 * var radioSelectInput = new OO.ui.RadioSelectInputWidget( {
9855 * options: [
9856 * { data: 'a', label: 'First' },
9857 * { data: 'b', label: 'Second'},
9858 * { data: 'c', label: 'Third' }
9859 * ]
9860 * } );
9861 * $( 'body' ).append( radioSelectInput.$element );
9862 *
9863 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
9864 *
9865 * @class
9866 * @extends OO.ui.InputWidget
9867 *
9868 * @constructor
9869 * @param {Object} [config] Configuration options
9870 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
9871 */
9872 OO.ui.RadioSelectInputWidget = function OoUiRadioSelectInputWidget( config ) {
9873 // Configuration initialization
9874 config = config || {};
9875
9876 // Properties (must be done before parent constructor which calls #setDisabled)
9877 this.radioSelectWidget = new OO.ui.RadioSelectWidget();
9878 // Set up the options before parent constructor, which uses them to validate config.value.
9879 // Use this instead of setOptions() because this.$input is not set up yet
9880 this.setOptionsData( config.options || [] );
9881
9882 // Parent constructor
9883 OO.ui.RadioSelectInputWidget.parent.call( this, config );
9884
9885 // Events
9886 this.radioSelectWidget.connect( this, { select: 'onMenuSelect' } );
9887
9888 // Initialization
9889 this.$element
9890 .addClass( 'oo-ui-radioSelectInputWidget' )
9891 .append( this.radioSelectWidget.$element );
9892 this.setTabIndexedElement( this.radioSelectWidget.$tabIndexed );
9893 };
9894
9895 /* Setup */
9896
9897 OO.inheritClass( OO.ui.RadioSelectInputWidget, OO.ui.InputWidget );
9898
9899 /* Static Methods */
9900
9901 /**
9902 * @inheritdoc
9903 */
9904 OO.ui.RadioSelectInputWidget.static.gatherPreInfuseState = function ( node, config ) {
9905 var state = OO.ui.RadioSelectInputWidget.parent.static.gatherPreInfuseState( node, config );
9906 state.value = $( node ).find( '.oo-ui-radioInputWidget .oo-ui-inputWidget-input:checked' ).val();
9907 return state;
9908 };
9909
9910 /**
9911 * @inheritdoc
9912 */
9913 OO.ui.RadioSelectInputWidget.static.reusePreInfuseDOM = function ( node, config ) {
9914 config = OO.ui.RadioSelectInputWidget.parent.static.reusePreInfuseDOM( node, config );
9915 // Cannot reuse the `<input type=radio>` set
9916 delete config.$input;
9917 return config;
9918 };
9919
9920 /* Methods */
9921
9922 /**
9923 * @inheritdoc
9924 * @protected
9925 */
9926 OO.ui.RadioSelectInputWidget.prototype.getInputElement = function () {
9927 // Use this instead of <input type="hidden">, because hidden inputs do not have separate
9928 // 'value' and 'defaultValue' properties, and InputWidget wants to handle 'defaultValue'.
9929 return $( '<input>' ).addClass( 'oo-ui-element-hidden' );
9930 };
9931
9932 /**
9933 * Handles menu select events.
9934 *
9935 * @private
9936 * @param {OO.ui.RadioOptionWidget} item Selected menu item
9937 */
9938 OO.ui.RadioSelectInputWidget.prototype.onMenuSelect = function ( item ) {
9939 this.setValue( item.getData() );
9940 };
9941
9942 /**
9943 * @inheritdoc
9944 */
9945 OO.ui.RadioSelectInputWidget.prototype.setValue = function ( value ) {
9946 var selected;
9947 value = this.cleanUpValue( value );
9948 // Only allow setting values that are actually present in the dropdown
9949 selected = this.radioSelectWidget.findItemFromData( value ) ||
9950 this.radioSelectWidget.findFirstSelectableItem();
9951 this.radioSelectWidget.selectItem( selected );
9952 value = selected ? selected.getData() : '';
9953 OO.ui.RadioSelectInputWidget.parent.prototype.setValue.call( this, value );
9954 return this;
9955 };
9956
9957 /**
9958 * @inheritdoc
9959 */
9960 OO.ui.RadioSelectInputWidget.prototype.setDisabled = function ( state ) {
9961 this.radioSelectWidget.setDisabled( state );
9962 OO.ui.RadioSelectInputWidget.parent.prototype.setDisabled.call( this, state );
9963 return this;
9964 };
9965
9966 /**
9967 * Set the options available for this input.
9968 *
9969 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
9970 * @chainable
9971 * @return {OO.ui.Widget} The widget, for chaining
9972 */
9973 OO.ui.RadioSelectInputWidget.prototype.setOptions = function ( options ) {
9974 var value = this.getValue();
9975
9976 this.setOptionsData( options );
9977
9978 // Re-set the value to update the visible interface (RadioSelectWidget).
9979 // In case the previous value is no longer an available option, select the first valid one.
9980 this.setValue( value );
9981
9982 return this;
9983 };
9984
9985 /**
9986 * Set the internal list of options, used e.g. by setValue() to see which options are allowed.
9987 *
9988 * This method may be called before the parent constructor, so various properties may not be
9989 * intialized yet.
9990 *
9991 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
9992 * @private
9993 */
9994 OO.ui.RadioSelectInputWidget.prototype.setOptionsData = function ( options ) {
9995 var widget = this;
9996
9997 this.radioSelectWidget
9998 .clearItems()
9999 .addItems( options.map( function ( opt ) {
10000 var optValue = widget.cleanUpValue( opt.data );
10001 return new OO.ui.RadioOptionWidget( {
10002 data: optValue,
10003 label: opt.label !== undefined ? opt.label : optValue
10004 } );
10005 } ) );
10006 };
10007
10008 /**
10009 * @inheritdoc
10010 */
10011 OO.ui.RadioSelectInputWidget.prototype.focus = function () {
10012 this.radioSelectWidget.focus();
10013 return this;
10014 };
10015
10016 /**
10017 * @inheritdoc
10018 */
10019 OO.ui.RadioSelectInputWidget.prototype.blur = function () {
10020 this.radioSelectWidget.blur();
10021 return this;
10022 };
10023
10024 /**
10025 * CheckboxMultiselectInputWidget is a
10026 * {@link OO.ui.CheckboxMultiselectWidget CheckboxMultiselectWidget} intended to be used within a
10027 * HTML form, such as a OO.ui.FormLayout. The selected values are synchronized with the value of
10028 * HTML `<input type=checkbox>` tags. Please see the [OOUI documentation on MediaWiki][1] for
10029 * more information about input widgets.
10030 *
10031 * @example
10032 * // Example: A CheckboxMultiselectInputWidget with three options
10033 * var multiselectInput = new OO.ui.CheckboxMultiselectInputWidget( {
10034 * options: [
10035 * { data: 'a', label: 'First' },
10036 * { data: 'b', label: 'Second'},
10037 * { data: 'c', label: 'Third' }
10038 * ]
10039 * } );
10040 * $( 'body' ).append( multiselectInput.$element );
10041 *
10042 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
10043 *
10044 * @class
10045 * @extends OO.ui.InputWidget
10046 *
10047 * @constructor
10048 * @param {Object} [config] Configuration options
10049 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: …, disabled: … }`
10050 */
10051 OO.ui.CheckboxMultiselectInputWidget = function OoUiCheckboxMultiselectInputWidget( config ) {
10052 // Configuration initialization
10053 config = config || {};
10054
10055 // Properties (must be done before parent constructor which calls #setDisabled)
10056 this.checkboxMultiselectWidget = new OO.ui.CheckboxMultiselectWidget();
10057 // Must be set before the #setOptionsData call below
10058 this.inputName = config.name;
10059 // Set up the options before parent constructor, which uses them to validate config.value.
10060 // Use this instead of setOptions() because this.$input is not set up yet
10061 this.setOptionsData( config.options || [] );
10062
10063 // Parent constructor
10064 OO.ui.CheckboxMultiselectInputWidget.parent.call( this, config );
10065
10066 // Events
10067 this.checkboxMultiselectWidget.connect( this, { select: 'onCheckboxesSelect' } );
10068
10069 // Initialization
10070 this.$element
10071 .addClass( 'oo-ui-checkboxMultiselectInputWidget' )
10072 .append( this.checkboxMultiselectWidget.$element );
10073 // We don't use this.$input, but rather the CheckboxInputWidgets inside each option
10074 this.$input.detach();
10075 };
10076
10077 /* Setup */
10078
10079 OO.inheritClass( OO.ui.CheckboxMultiselectInputWidget, OO.ui.InputWidget );
10080
10081 /* Static Methods */
10082
10083 /**
10084 * @inheritdoc
10085 */
10086 OO.ui.CheckboxMultiselectInputWidget.static.gatherPreInfuseState = function ( node, config ) {
10087 var state = OO.ui.CheckboxMultiselectInputWidget.parent.static.gatherPreInfuseState( node, config );
10088 state.value = $( node ).find( '.oo-ui-checkboxInputWidget .oo-ui-inputWidget-input:checked' )
10089 .toArray().map( function ( el ) { return el.value; } );
10090 return state;
10091 };
10092
10093 /**
10094 * @inheritdoc
10095 */
10096 OO.ui.CheckboxMultiselectInputWidget.static.reusePreInfuseDOM = function ( node, config ) {
10097 config = OO.ui.CheckboxMultiselectInputWidget.parent.static.reusePreInfuseDOM( node, config );
10098 // Cannot reuse the `<input type=checkbox>` set
10099 delete config.$input;
10100 return config;
10101 };
10102
10103 /* Methods */
10104
10105 /**
10106 * @inheritdoc
10107 * @protected
10108 */
10109 OO.ui.CheckboxMultiselectInputWidget.prototype.getInputElement = function () {
10110 // Actually unused
10111 return $( '<unused>' );
10112 };
10113
10114 /**
10115 * Handles CheckboxMultiselectWidget select events.
10116 *
10117 * @private
10118 */
10119 OO.ui.CheckboxMultiselectInputWidget.prototype.onCheckboxesSelect = function () {
10120 this.setValue( this.checkboxMultiselectWidget.findSelectedItemsData() );
10121 };
10122
10123 /**
10124 * @inheritdoc
10125 */
10126 OO.ui.CheckboxMultiselectInputWidget.prototype.getValue = function () {
10127 var value = this.$element.find( '.oo-ui-checkboxInputWidget .oo-ui-inputWidget-input:checked' )
10128 .toArray().map( function ( el ) { return el.value; } );
10129 if ( this.value !== value ) {
10130 this.setValue( value );
10131 }
10132 return this.value;
10133 };
10134
10135 /**
10136 * @inheritdoc
10137 */
10138 OO.ui.CheckboxMultiselectInputWidget.prototype.setValue = function ( value ) {
10139 value = this.cleanUpValue( value );
10140 this.checkboxMultiselectWidget.selectItemsByData( value );
10141 OO.ui.CheckboxMultiselectInputWidget.parent.prototype.setValue.call( this, value );
10142 if ( this.optionsDirty ) {
10143 // We reached this from the constructor or from #setOptions.
10144 // We have to update the <select> element.
10145 this.updateOptionsInterface();
10146 }
10147 return this;
10148 };
10149
10150 /**
10151 * Clean up incoming value.
10152 *
10153 * @param {string[]} value Original value
10154 * @return {string[]} Cleaned up value
10155 */
10156 OO.ui.CheckboxMultiselectInputWidget.prototype.cleanUpValue = function ( value ) {
10157 var i, singleValue,
10158 cleanValue = [];
10159 if ( !Array.isArray( value ) ) {
10160 return cleanValue;
10161 }
10162 for ( i = 0; i < value.length; i++ ) {
10163 singleValue =
10164 OO.ui.CheckboxMultiselectInputWidget.parent.prototype.cleanUpValue.call( this, value[ i ] );
10165 // Remove options that we don't have here
10166 if ( !this.checkboxMultiselectWidget.findItemFromData( singleValue ) ) {
10167 continue;
10168 }
10169 cleanValue.push( singleValue );
10170 }
10171 return cleanValue;
10172 };
10173
10174 /**
10175 * @inheritdoc
10176 */
10177 OO.ui.CheckboxMultiselectInputWidget.prototype.setDisabled = function ( state ) {
10178 this.checkboxMultiselectWidget.setDisabled( state );
10179 OO.ui.CheckboxMultiselectInputWidget.parent.prototype.setDisabled.call( this, state );
10180 return this;
10181 };
10182
10183 /**
10184 * Set the options available for this input.
10185 *
10186 * @param {Object[]} options Array of menu options in the format `{ data: …, label: …, disabled: … }`
10187 * @chainable
10188 * @return {OO.ui.Widget} The widget, for chaining
10189 */
10190 OO.ui.CheckboxMultiselectInputWidget.prototype.setOptions = function ( options ) {
10191 var value = this.getValue();
10192
10193 this.setOptionsData( options );
10194
10195 // Re-set the value to update the visible interface (CheckboxMultiselectWidget).
10196 // This will also get rid of any stale options that we just removed.
10197 this.setValue( value );
10198
10199 return this;
10200 };
10201
10202 /**
10203 * Set the internal list of options, used e.g. by setValue() to see which options are allowed.
10204 *
10205 * This method may be called before the parent constructor, so various properties may not be
10206 * intialized yet.
10207 *
10208 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
10209 * @private
10210 */
10211 OO.ui.CheckboxMultiselectInputWidget.prototype.setOptionsData = function ( options ) {
10212 var widget = this;
10213
10214 this.optionsDirty = true;
10215
10216 this.checkboxMultiselectWidget
10217 .clearItems()
10218 .addItems( options.map( function ( opt ) {
10219 var optValue, item, optDisabled;
10220 optValue =
10221 OO.ui.CheckboxMultiselectInputWidget.parent.prototype.cleanUpValue.call( widget, opt.data );
10222 optDisabled = opt.disabled !== undefined ? opt.disabled : false;
10223 item = new OO.ui.CheckboxMultioptionWidget( {
10224 data: optValue,
10225 label: opt.label !== undefined ? opt.label : optValue,
10226 disabled: optDisabled
10227 } );
10228 // Set the 'name' and 'value' for form submission
10229 item.checkbox.$input.attr( 'name', widget.inputName );
10230 item.checkbox.setValue( optValue );
10231 return item;
10232 } ) );
10233 };
10234
10235 /**
10236 * Update the user-visible interface to match the internal list of options and value.
10237 *
10238 * This method must only be called after the parent constructor.
10239 *
10240 * @private
10241 */
10242 OO.ui.CheckboxMultiselectInputWidget.prototype.updateOptionsInterface = function () {
10243 var defaultValue = this.defaultValue;
10244
10245 this.checkboxMultiselectWidget.getItems().forEach( function ( item ) {
10246 // Remember original selection state. This property can be later used to check whether
10247 // the selection state of the input has been changed since it was created.
10248 var isDefault = defaultValue.indexOf( item.getData() ) !== -1;
10249 item.checkbox.defaultSelected = isDefault;
10250 item.checkbox.$input[ 0 ].defaultChecked = isDefault;
10251 } );
10252
10253 this.optionsDirty = false;
10254 };
10255
10256 /**
10257 * @inheritdoc
10258 */
10259 OO.ui.CheckboxMultiselectInputWidget.prototype.focus = function () {
10260 this.checkboxMultiselectWidget.focus();
10261 return this;
10262 };
10263
10264 /**
10265 * TextInputWidgets, like HTML text inputs, can be configured with options that customize the
10266 * size of the field as well as its presentation. In addition, these widgets can be configured
10267 * with {@link OO.ui.mixin.IconElement icons}, {@link OO.ui.mixin.IndicatorElement indicators}, an optional
10268 * validation-pattern (used to determine if an input value is valid or not) and an input filter,
10269 * which modifies incoming values rather than validating them.
10270 * Please see the [OOUI documentation on MediaWiki] [1] for more information and examples.
10271 *
10272 * This widget can be used inside an HTML form, such as a OO.ui.FormLayout.
10273 *
10274 * @example
10275 * // Example of a text input widget
10276 * var textInput = new OO.ui.TextInputWidget( {
10277 * value: 'Text input'
10278 * } )
10279 * $( 'body' ).append( textInput.$element );
10280 *
10281 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
10282 *
10283 * @class
10284 * @extends OO.ui.InputWidget
10285 * @mixins OO.ui.mixin.IconElement
10286 * @mixins OO.ui.mixin.IndicatorElement
10287 * @mixins OO.ui.mixin.PendingElement
10288 * @mixins OO.ui.mixin.LabelElement
10289 *
10290 * @constructor
10291 * @param {Object} [config] Configuration options
10292 * @cfg {string} [type='text'] The value of the HTML `type` attribute: 'text', 'password'
10293 * 'email', 'url' or 'number'.
10294 * @cfg {string} [placeholder] Placeholder text
10295 * @cfg {boolean} [autofocus=false] Use an HTML `autofocus` attribute to
10296 * instruct the browser to focus this widget.
10297 * @cfg {boolean} [readOnly=false] Prevent changes to the value of the text input.
10298 * @cfg {number} [maxLength] Maximum number of characters allowed in the input.
10299 *
10300 * For unfortunate historical reasons, this counts the number of UTF-16 code units rather than
10301 * Unicode codepoints, which means that codepoints outside the Basic Multilingual Plane (e.g.
10302 * many emojis) count as 2 characters each.
10303 * @cfg {string} [labelPosition='after'] The position of the inline label relative to that of
10304 * the value or placeholder text: `'before'` or `'after'`
10305 * @cfg {boolean} [required=false] Mark the field as required with `true`. Implies `indicator: 'required'`.
10306 * Note that `false` & setting `indicator: 'required' will result in no indicator shown.
10307 * @cfg {boolean} [autocomplete=true] Should the browser support autocomplete for this field
10308 * @cfg {boolean} [spellcheck] Should the browser support spellcheck for this field (`undefined` means
10309 * leaving it up to the browser).
10310 * @cfg {RegExp|Function|string} [validate] Validation pattern: when string, a symbolic name of a
10311 * pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer'
10312 * (the value must contain only numbers); when RegExp, a regular expression that must match the
10313 * value for it to be considered valid; when Function, a function receiving the value as parameter
10314 * that must return true, or promise resolving to true, for it to be considered valid.
10315 */
10316 OO.ui.TextInputWidget = function OoUiTextInputWidget( config ) {
10317 // Configuration initialization
10318 config = $.extend( {
10319 type: 'text',
10320 labelPosition: 'after'
10321 }, config );
10322
10323 // Parent constructor
10324 OO.ui.TextInputWidget.parent.call( this, config );
10325
10326 // Mixin constructors
10327 OO.ui.mixin.IconElement.call( this, config );
10328 OO.ui.mixin.IndicatorElement.call( this, config );
10329 OO.ui.mixin.PendingElement.call( this, $.extend( {}, config, { $pending: this.$input } ) );
10330 OO.ui.mixin.LabelElement.call( this, config );
10331
10332 // Properties
10333 this.type = this.getSaneType( config );
10334 this.readOnly = false;
10335 this.required = false;
10336 this.validate = null;
10337 this.styleHeight = null;
10338 this.scrollWidth = null;
10339
10340 this.setValidation( config.validate );
10341 this.setLabelPosition( config.labelPosition );
10342
10343 // Events
10344 this.$input.on( {
10345 keypress: this.onKeyPress.bind( this ),
10346 blur: this.onBlur.bind( this ),
10347 focus: this.onFocus.bind( this )
10348 } );
10349 this.$icon.on( 'mousedown', this.onIconMouseDown.bind( this ) );
10350 this.$indicator.on( 'mousedown', this.onIndicatorMouseDown.bind( this ) );
10351 this.on( 'labelChange', this.updatePosition.bind( this ) );
10352 this.on( 'change', OO.ui.debounce( this.onDebouncedChange.bind( this ), 250 ) );
10353
10354 // Initialization
10355 this.$element
10356 .addClass( 'oo-ui-textInputWidget oo-ui-textInputWidget-type-' + this.type )
10357 .append( this.$icon, this.$indicator );
10358 this.setReadOnly( !!config.readOnly );
10359 this.setRequired( !!config.required );
10360 if ( config.placeholder !== undefined ) {
10361 this.$input.attr( 'placeholder', config.placeholder );
10362 }
10363 if ( config.maxLength !== undefined ) {
10364 this.$input.attr( 'maxlength', config.maxLength );
10365 }
10366 if ( config.autofocus ) {
10367 this.$input.attr( 'autofocus', 'autofocus' );
10368 }
10369 if ( config.autocomplete === false ) {
10370 this.$input.attr( 'autocomplete', 'off' );
10371 // Turning off autocompletion also disables "form caching" when the user navigates to a
10372 // different page and then clicks "Back". Re-enable it when leaving. Borrowed from jQuery UI.
10373 $( window ).on( {
10374 beforeunload: function () {
10375 this.$input.removeAttr( 'autocomplete' );
10376 }.bind( this ),
10377 pageshow: function () {
10378 // Browsers don't seem to actually fire this event on "Back", they instead just reload the
10379 // whole page... it shouldn't hurt, though.
10380 this.$input.attr( 'autocomplete', 'off' );
10381 }.bind( this )
10382 } );
10383 }
10384 if ( config.spellcheck !== undefined ) {
10385 this.$input.attr( 'spellcheck', config.spellcheck ? 'true' : 'false' );
10386 }
10387 if ( this.label ) {
10388 this.isWaitingToBeAttached = true;
10389 this.installParentChangeDetector();
10390 }
10391 };
10392
10393 /* Setup */
10394
10395 OO.inheritClass( OO.ui.TextInputWidget, OO.ui.InputWidget );
10396 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.mixin.IconElement );
10397 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.mixin.IndicatorElement );
10398 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.mixin.PendingElement );
10399 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.mixin.LabelElement );
10400
10401 /* Static Properties */
10402
10403 OO.ui.TextInputWidget.static.validationPatterns = {
10404 'non-empty': /.+/,
10405 integer: /^\d+$/
10406 };
10407
10408 /* Events */
10409
10410 /**
10411 * An `enter` event is emitted when the user presses 'enter' inside the text box.
10412 *
10413 * @event enter
10414 */
10415
10416 /* Methods */
10417
10418 /**
10419 * Handle icon mouse down events.
10420 *
10421 * @private
10422 * @param {jQuery.Event} e Mouse down event
10423 * @return {undefined/boolean} False to prevent default if event is handled
10424 */
10425 OO.ui.TextInputWidget.prototype.onIconMouseDown = function ( e ) {
10426 if ( e.which === OO.ui.MouseButtons.LEFT ) {
10427 this.focus();
10428 return false;
10429 }
10430 };
10431
10432 /**
10433 * Handle indicator mouse down events.
10434 *
10435 * @private
10436 * @param {jQuery.Event} e Mouse down event
10437 * @return {undefined/boolean} False to prevent default if event is handled
10438 */
10439 OO.ui.TextInputWidget.prototype.onIndicatorMouseDown = function ( e ) {
10440 if ( e.which === OO.ui.MouseButtons.LEFT ) {
10441 this.focus();
10442 return false;
10443 }
10444 };
10445
10446 /**
10447 * Handle key press events.
10448 *
10449 * @private
10450 * @param {jQuery.Event} e Key press event
10451 * @fires enter If enter key is pressed
10452 */
10453 OO.ui.TextInputWidget.prototype.onKeyPress = function ( e ) {
10454 if ( e.which === OO.ui.Keys.ENTER ) {
10455 this.emit( 'enter', e );
10456 }
10457 };
10458
10459 /**
10460 * Handle blur events.
10461 *
10462 * @private
10463 * @param {jQuery.Event} e Blur event
10464 */
10465 OO.ui.TextInputWidget.prototype.onBlur = function () {
10466 this.setValidityFlag();
10467 };
10468
10469 /**
10470 * Handle focus events.
10471 *
10472 * @private
10473 * @param {jQuery.Event} e Focus event
10474 */
10475 OO.ui.TextInputWidget.prototype.onFocus = function () {
10476 if ( this.isWaitingToBeAttached ) {
10477 // If we've received focus, then we must be attached to the document, and if
10478 // isWaitingToBeAttached is still true, that means the handler never fired. Fire it now.
10479 this.onElementAttach();
10480 }
10481 this.setValidityFlag( true );
10482 };
10483
10484 /**
10485 * Handle element attach events.
10486 *
10487 * @private
10488 * @param {jQuery.Event} e Element attach event
10489 */
10490 OO.ui.TextInputWidget.prototype.onElementAttach = function () {
10491 this.isWaitingToBeAttached = false;
10492 // Any previously calculated size is now probably invalid if we reattached elsewhere
10493 this.valCache = null;
10494 this.positionLabel();
10495 };
10496
10497 /**
10498 * Handle debounced change events.
10499 *
10500 * @param {string} value
10501 * @private
10502 */
10503 OO.ui.TextInputWidget.prototype.onDebouncedChange = function () {
10504 this.setValidityFlag();
10505 };
10506
10507 /**
10508 * Check if the input is {@link #readOnly read-only}.
10509 *
10510 * @return {boolean}
10511 */
10512 OO.ui.TextInputWidget.prototype.isReadOnly = function () {
10513 return this.readOnly;
10514 };
10515
10516 /**
10517 * Set the {@link #readOnly read-only} state of the input.
10518 *
10519 * @param {boolean} state Make input read-only
10520 * @chainable
10521 * @return {OO.ui.Widget} The widget, for chaining
10522 */
10523 OO.ui.TextInputWidget.prototype.setReadOnly = function ( state ) {
10524 this.readOnly = !!state;
10525 this.$input.prop( 'readOnly', this.readOnly );
10526 return this;
10527 };
10528
10529 /**
10530 * Check if the input is {@link #required required}.
10531 *
10532 * @return {boolean}
10533 */
10534 OO.ui.TextInputWidget.prototype.isRequired = function () {
10535 return this.required;
10536 };
10537
10538 /**
10539 * Set the {@link #required required} state of the input.
10540 *
10541 * @param {boolean} state Make input required
10542 * @chainable
10543 * @return {OO.ui.Widget} The widget, for chaining
10544 */
10545 OO.ui.TextInputWidget.prototype.setRequired = function ( state ) {
10546 this.required = !!state;
10547 if ( this.required ) {
10548 this.$input
10549 .prop( 'required', true )
10550 .attr( 'aria-required', 'true' );
10551 if ( this.getIndicator() === null ) {
10552 this.setIndicator( 'required' );
10553 }
10554 } else {
10555 this.$input
10556 .prop( 'required', false )
10557 .removeAttr( 'aria-required' );
10558 if ( this.getIndicator() === 'required' ) {
10559 this.setIndicator( null );
10560 }
10561 }
10562 return this;
10563 };
10564
10565 /**
10566 * Support function for making #onElementAttach work across browsers.
10567 *
10568 * This whole function could be replaced with one line of code using the DOMNodeInsertedIntoDocument
10569 * event, but it's not supported by Firefox and allegedly deprecated, so we only use it as fallback.
10570 *
10571 * Due to MutationObserver performance woes, #onElementAttach is only somewhat reliably called the
10572 * first time that the element gets attached to the documented.
10573 */
10574 OO.ui.TextInputWidget.prototype.installParentChangeDetector = function () {
10575 var mutationObserver, onRemove, topmostNode, fakeParentNode,
10576 MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver,
10577 widget = this;
10578
10579 if ( MutationObserver ) {
10580 // The new way. If only it wasn't so ugly.
10581
10582 if ( this.isElementAttached() ) {
10583 // Widget is attached already, do nothing. This breaks the functionality of this function when
10584 // the widget is detached and reattached. Alas, doing this correctly with MutationObserver
10585 // would require observation of the whole document, which would hurt performance of other,
10586 // more important code.
10587 return;
10588 }
10589
10590 // Find topmost node in the tree
10591 topmostNode = this.$element[ 0 ];
10592 while ( topmostNode.parentNode ) {
10593 topmostNode = topmostNode.parentNode;
10594 }
10595
10596 // We have no way to detect the $element being attached somewhere without observing the entire
10597 // DOM with subtree modifications, which would hurt performance. So we cheat: we hook to the
10598 // parent node of $element, and instead detect when $element is removed from it (and thus
10599 // probably attached somewhere else). If there is no parent, we create a "fake" one. If it
10600 // doesn't get attached, we end up back here and create the parent.
10601
10602 mutationObserver = new MutationObserver( function ( mutations ) {
10603 var i, j, removedNodes;
10604 for ( i = 0; i < mutations.length; i++ ) {
10605 removedNodes = mutations[ i ].removedNodes;
10606 for ( j = 0; j < removedNodes.length; j++ ) {
10607 if ( removedNodes[ j ] === topmostNode ) {
10608 setTimeout( onRemove, 0 );
10609 return;
10610 }
10611 }
10612 }
10613 } );
10614
10615 onRemove = function () {
10616 // If the node was attached somewhere else, report it
10617 if ( widget.isElementAttached() ) {
10618 widget.onElementAttach();
10619 }
10620 mutationObserver.disconnect();
10621 widget.installParentChangeDetector();
10622 };
10623
10624 // Create a fake parent and observe it
10625 fakeParentNode = $( '<div>' ).append( topmostNode )[ 0 ];
10626 mutationObserver.observe( fakeParentNode, { childList: true } );
10627 } else {
10628 // Using the DOMNodeInsertedIntoDocument event is much nicer and less magical, and works for
10629 // detachment and reattachment, but it's not supported by Firefox and allegedly deprecated.
10630 this.$element.on( 'DOMNodeInsertedIntoDocument', this.onElementAttach.bind( this ) );
10631 }
10632 };
10633
10634 /**
10635 * @inheritdoc
10636 * @protected
10637 */
10638 OO.ui.TextInputWidget.prototype.getInputElement = function ( config ) {
10639 if ( this.getSaneType( config ) === 'number' ) {
10640 return $( '<input>' )
10641 .attr( 'step', 'any' )
10642 .attr( 'type', 'number' );
10643 } else {
10644 return $( '<input>' ).attr( 'type', this.getSaneType( config ) );
10645 }
10646 };
10647
10648 /**
10649 * Get sanitized value for 'type' for given config.
10650 *
10651 * @param {Object} config Configuration options
10652 * @return {string|null}
10653 * @protected
10654 */
10655 OO.ui.TextInputWidget.prototype.getSaneType = function ( config ) {
10656 var allowedTypes = [
10657 'text',
10658 'password',
10659 'email',
10660 'url',
10661 'number'
10662 ];
10663 return allowedTypes.indexOf( config.type ) !== -1 ? config.type : 'text';
10664 };
10665
10666 /**
10667 * Focus the input and select a specified range within the text.
10668 *
10669 * @param {number} from Select from offset
10670 * @param {number} [to] Select to offset, defaults to from
10671 * @chainable
10672 * @return {OO.ui.Widget} The widget, for chaining
10673 */
10674 OO.ui.TextInputWidget.prototype.selectRange = function ( from, to ) {
10675 var isBackwards, start, end,
10676 input = this.$input[ 0 ];
10677
10678 to = to || from;
10679
10680 isBackwards = to < from;
10681 start = isBackwards ? to : from;
10682 end = isBackwards ? from : to;
10683
10684 this.focus();
10685
10686 try {
10687 input.setSelectionRange( start, end, isBackwards ? 'backward' : 'forward' );
10688 } catch ( e ) {
10689 // IE throws an exception if you call setSelectionRange on a unattached DOM node.
10690 // Rather than expensively check if the input is attached every time, just check
10691 // if it was the cause of an error being thrown. If not, rethrow the error.
10692 if ( this.getElementDocument().body.contains( input ) ) {
10693 throw e;
10694 }
10695 }
10696 return this;
10697 };
10698
10699 /**
10700 * Get an object describing the current selection range in a directional manner
10701 *
10702 * @return {Object} Object containing 'from' and 'to' offsets
10703 */
10704 OO.ui.TextInputWidget.prototype.getRange = function () {
10705 var input = this.$input[ 0 ],
10706 start = input.selectionStart,
10707 end = input.selectionEnd,
10708 isBackwards = input.selectionDirection === 'backward';
10709
10710 return {
10711 from: isBackwards ? end : start,
10712 to: isBackwards ? start : end
10713 };
10714 };
10715
10716 /**
10717 * Get the length of the text input value.
10718 *
10719 * This could differ from the length of #getValue if the
10720 * value gets filtered
10721 *
10722 * @return {number} Input length
10723 */
10724 OO.ui.TextInputWidget.prototype.getInputLength = function () {
10725 return this.$input[ 0 ].value.length;
10726 };
10727
10728 /**
10729 * Focus the input and select the entire text.
10730 *
10731 * @chainable
10732 * @return {OO.ui.Widget} The widget, for chaining
10733 */
10734 OO.ui.TextInputWidget.prototype.select = function () {
10735 return this.selectRange( 0, this.getInputLength() );
10736 };
10737
10738 /**
10739 * Focus the input and move the cursor to the start.
10740 *
10741 * @chainable
10742 * @return {OO.ui.Widget} The widget, for chaining
10743 */
10744 OO.ui.TextInputWidget.prototype.moveCursorToStart = function () {
10745 return this.selectRange( 0 );
10746 };
10747
10748 /**
10749 * Focus the input and move the cursor to the end.
10750 *
10751 * @chainable
10752 * @return {OO.ui.Widget} The widget, for chaining
10753 */
10754 OO.ui.TextInputWidget.prototype.moveCursorToEnd = function () {
10755 return this.selectRange( this.getInputLength() );
10756 };
10757
10758 /**
10759 * Insert new content into the input.
10760 *
10761 * @param {string} content Content to be inserted
10762 * @chainable
10763 * @return {OO.ui.Widget} The widget, for chaining
10764 */
10765 OO.ui.TextInputWidget.prototype.insertContent = function ( content ) {
10766 var start, end,
10767 range = this.getRange(),
10768 value = this.getValue();
10769
10770 start = Math.min( range.from, range.to );
10771 end = Math.max( range.from, range.to );
10772
10773 this.setValue( value.slice( 0, start ) + content + value.slice( end ) );
10774 this.selectRange( start + content.length );
10775 return this;
10776 };
10777
10778 /**
10779 * Insert new content either side of a selection.
10780 *
10781 * @param {string} pre Content to be inserted before the selection
10782 * @param {string} post Content to be inserted after the selection
10783 * @chainable
10784 * @return {OO.ui.Widget} The widget, for chaining
10785 */
10786 OO.ui.TextInputWidget.prototype.encapsulateContent = function ( pre, post ) {
10787 var start, end,
10788 range = this.getRange(),
10789 offset = pre.length;
10790
10791 start = Math.min( range.from, range.to );
10792 end = Math.max( range.from, range.to );
10793
10794 this.selectRange( start ).insertContent( pre );
10795 this.selectRange( offset + end ).insertContent( post );
10796
10797 this.selectRange( offset + start, offset + end );
10798 return this;
10799 };
10800
10801 /**
10802 * Set the validation pattern.
10803 *
10804 * The validation pattern is either a regular expression, a function, or the symbolic name of a
10805 * pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer' (the
10806 * value must contain only numbers).
10807 *
10808 * @param {RegExp|Function|string|null} validate Regular expression, function, or the symbolic name
10809 * of a pattern (either ‘integer’ or ‘non-empty’) defined by the class.
10810 */
10811 OO.ui.TextInputWidget.prototype.setValidation = function ( validate ) {
10812 if ( validate instanceof RegExp || validate instanceof Function ) {
10813 this.validate = validate;
10814 } else {
10815 this.validate = this.constructor.static.validationPatterns[ validate ] || /.*/;
10816 }
10817 };
10818
10819 /**
10820 * Sets the 'invalid' flag appropriately.
10821 *
10822 * @param {boolean} [isValid] Optionally override validation result
10823 */
10824 OO.ui.TextInputWidget.prototype.setValidityFlag = function ( isValid ) {
10825 var widget = this,
10826 setFlag = function ( valid ) {
10827 if ( !valid ) {
10828 widget.$input.attr( 'aria-invalid', 'true' );
10829 } else {
10830 widget.$input.removeAttr( 'aria-invalid' );
10831 }
10832 widget.setFlags( { invalid: !valid } );
10833 };
10834
10835 if ( isValid !== undefined ) {
10836 setFlag( isValid );
10837 } else {
10838 this.getValidity().then( function () {
10839 setFlag( true );
10840 }, function () {
10841 setFlag( false );
10842 } );
10843 }
10844 };
10845
10846 /**
10847 * Get the validity of current value.
10848 *
10849 * This method returns a promise that resolves if the value is valid and rejects if
10850 * it isn't. Uses the {@link #validate validation pattern} to check for validity.
10851 *
10852 * @return {jQuery.Promise} A promise that resolves if the value is valid, rejects if not.
10853 */
10854 OO.ui.TextInputWidget.prototype.getValidity = function () {
10855 var result;
10856
10857 function rejectOrResolve( valid ) {
10858 if ( valid ) {
10859 return $.Deferred().resolve().promise();
10860 } else {
10861 return $.Deferred().reject().promise();
10862 }
10863 }
10864
10865 // Check browser validity and reject if it is invalid
10866 if (
10867 this.$input[ 0 ].checkValidity !== undefined &&
10868 this.$input[ 0 ].checkValidity() === false
10869 ) {
10870 return rejectOrResolve( false );
10871 }
10872
10873 // Run our checks if the browser thinks the field is valid
10874 if ( this.validate instanceof Function ) {
10875 result = this.validate( this.getValue() );
10876 if ( result && typeof result.promise === 'function' ) {
10877 return result.promise().then( function ( valid ) {
10878 return rejectOrResolve( valid );
10879 } );
10880 } else {
10881 return rejectOrResolve( result );
10882 }
10883 } else {
10884 return rejectOrResolve( this.getValue().match( this.validate ) );
10885 }
10886 };
10887
10888 /**
10889 * Set the position of the inline label relative to that of the value: `‘before’` or `‘after’`.
10890 *
10891 * @param {string} labelPosition Label position, 'before' or 'after'
10892 * @chainable
10893 * @return {OO.ui.Widget} The widget, for chaining
10894 */
10895 OO.ui.TextInputWidget.prototype.setLabelPosition = function ( labelPosition ) {
10896 this.labelPosition = labelPosition;
10897 if ( this.label ) {
10898 // If there is no label and we only change the position, #updatePosition is a no-op,
10899 // but it takes really a lot of work to do nothing.
10900 this.updatePosition();
10901 }
10902 return this;
10903 };
10904
10905 /**
10906 * Update the position of the inline label.
10907 *
10908 * This method is called by #setLabelPosition, and can also be called on its own if
10909 * something causes the label to be mispositioned.
10910 *
10911 * @chainable
10912 * @return {OO.ui.Widget} The widget, for chaining
10913 */
10914 OO.ui.TextInputWidget.prototype.updatePosition = function () {
10915 var after = this.labelPosition === 'after';
10916
10917 this.$element
10918 .toggleClass( 'oo-ui-textInputWidget-labelPosition-after', !!this.label && after )
10919 .toggleClass( 'oo-ui-textInputWidget-labelPosition-before', !!this.label && !after );
10920
10921 this.valCache = null;
10922 this.scrollWidth = null;
10923 this.positionLabel();
10924
10925 return this;
10926 };
10927
10928 /**
10929 * Position the label by setting the correct padding on the input.
10930 *
10931 * @private
10932 * @chainable
10933 * @return {OO.ui.Widget} The widget, for chaining
10934 */
10935 OO.ui.TextInputWidget.prototype.positionLabel = function () {
10936 var after, rtl, property, newCss;
10937
10938 if ( this.isWaitingToBeAttached ) {
10939 // #onElementAttach will be called soon, which calls this method
10940 return this;
10941 }
10942
10943 newCss = {
10944 'padding-right': '',
10945 'padding-left': ''
10946 };
10947
10948 if ( this.label ) {
10949 this.$element.append( this.$label );
10950 } else {
10951 this.$label.detach();
10952 // Clear old values if present
10953 this.$input.css( newCss );
10954 return;
10955 }
10956
10957 after = this.labelPosition === 'after';
10958 rtl = this.$element.css( 'direction' ) === 'rtl';
10959 property = after === rtl ? 'padding-left' : 'padding-right';
10960
10961 newCss[ property ] = this.$label.outerWidth( true ) + ( after ? this.scrollWidth : 0 );
10962 // We have to clear the padding on the other side, in case the element direction changed
10963 this.$input.css( newCss );
10964
10965 return this;
10966 };
10967
10968 /**
10969 * @class
10970 * @extends OO.ui.TextInputWidget
10971 *
10972 * @constructor
10973 * @param {Object} [config] Configuration options
10974 */
10975 OO.ui.SearchInputWidget = function OoUiSearchInputWidget( config ) {
10976 config = $.extend( {
10977 icon: 'search'
10978 }, config );
10979
10980 // Parent constructor
10981 OO.ui.SearchInputWidget.parent.call( this, config );
10982
10983 // Events
10984 this.connect( this, {
10985 change: 'onChange'
10986 } );
10987
10988 // Initialization
10989 this.updateSearchIndicator();
10990 this.connect( this, {
10991 disable: 'onDisable'
10992 } );
10993 };
10994
10995 /* Setup */
10996
10997 OO.inheritClass( OO.ui.SearchInputWidget, OO.ui.TextInputWidget );
10998
10999 /* Methods */
11000
11001 /**
11002 * @inheritdoc
11003 * @protected
11004 */
11005 OO.ui.SearchInputWidget.prototype.getSaneType = function () {
11006 return 'search';
11007 };
11008
11009 /**
11010 * @inheritdoc
11011 */
11012 OO.ui.SearchInputWidget.prototype.onIndicatorMouseDown = function ( e ) {
11013 if ( e.which === OO.ui.MouseButtons.LEFT ) {
11014 // Clear the text field
11015 this.setValue( '' );
11016 this.focus();
11017 return false;
11018 }
11019 };
11020
11021 /**
11022 * Update the 'clear' indicator displayed on type: 'search' text
11023 * fields, hiding it when the field is already empty or when it's not
11024 * editable.
11025 */
11026 OO.ui.SearchInputWidget.prototype.updateSearchIndicator = function () {
11027 if ( this.getValue() === '' || this.isDisabled() || this.isReadOnly() ) {
11028 this.setIndicator( null );
11029 } else {
11030 this.setIndicator( 'clear' );
11031 }
11032 };
11033
11034 /**
11035 * Handle change events.
11036 *
11037 * @private
11038 */
11039 OO.ui.SearchInputWidget.prototype.onChange = function () {
11040 this.updateSearchIndicator();
11041 };
11042
11043 /**
11044 * Handle disable events.
11045 *
11046 * @param {boolean} disabled Element is disabled
11047 * @private
11048 */
11049 OO.ui.SearchInputWidget.prototype.onDisable = function () {
11050 this.updateSearchIndicator();
11051 };
11052
11053 /**
11054 * @inheritdoc
11055 */
11056 OO.ui.SearchInputWidget.prototype.setReadOnly = function ( state ) {
11057 OO.ui.SearchInputWidget.parent.prototype.setReadOnly.call( this, state );
11058 this.updateSearchIndicator();
11059 return this;
11060 };
11061
11062 /**
11063 * @class
11064 * @extends OO.ui.TextInputWidget
11065 *
11066 * @constructor
11067 * @param {Object} [config] Configuration options
11068 * @cfg {number} [rows] Number of visible lines in textarea. If used with `autosize`,
11069 * specifies minimum number of rows to display.
11070 * @cfg {boolean} [autosize=false] Automatically resize the text input to fit its content.
11071 * Use the #maxRows config to specify a maximum number of displayed rows.
11072 * @cfg {number} [maxRows] Maximum number of rows to display when #autosize is set to true.
11073 * Defaults to the maximum of `10` and `2 * rows`, or `10` if `rows` isn't provided.
11074 */
11075 OO.ui.MultilineTextInputWidget = function OoUiMultilineTextInputWidget( config ) {
11076 config = $.extend( {
11077 type: 'text'
11078 }, config );
11079 // Parent constructor
11080 OO.ui.MultilineTextInputWidget.parent.call( this, config );
11081
11082 // Properties
11083 this.autosize = !!config.autosize;
11084 this.minRows = config.rows !== undefined ? config.rows : '';
11085 this.maxRows = config.maxRows || Math.max( 2 * ( this.minRows || 0 ), 10 );
11086
11087 // Clone for resizing
11088 if ( this.autosize ) {
11089 this.$clone = this.$input
11090 .clone()
11091 .removeAttr( 'id' )
11092 .removeAttr( 'name' )
11093 .insertAfter( this.$input )
11094 .attr( 'aria-hidden', 'true' )
11095 .addClass( 'oo-ui-element-hidden' );
11096 }
11097
11098 // Events
11099 this.connect( this, {
11100 change: 'onChange'
11101 } );
11102
11103 // Initialization
11104 if ( config.rows ) {
11105 this.$input.attr( 'rows', config.rows );
11106 }
11107 if ( this.autosize ) {
11108 this.$input.addClass( 'oo-ui-textInputWidget-autosized' );
11109 this.isWaitingToBeAttached = true;
11110 this.installParentChangeDetector();
11111 }
11112 };
11113
11114 /* Setup */
11115
11116 OO.inheritClass( OO.ui.MultilineTextInputWidget, OO.ui.TextInputWidget );
11117
11118 /* Static Methods */
11119
11120 /**
11121 * @inheritdoc
11122 */
11123 OO.ui.MultilineTextInputWidget.static.gatherPreInfuseState = function ( node, config ) {
11124 var state = OO.ui.MultilineTextInputWidget.parent.static.gatherPreInfuseState( node, config );
11125 state.scrollTop = config.$input.scrollTop();
11126 return state;
11127 };
11128
11129 /* Methods */
11130
11131 /**
11132 * @inheritdoc
11133 */
11134 OO.ui.MultilineTextInputWidget.prototype.onElementAttach = function () {
11135 OO.ui.MultilineTextInputWidget.parent.prototype.onElementAttach.call( this );
11136 this.adjustSize();
11137 };
11138
11139 /**
11140 * Handle change events.
11141 *
11142 * @private
11143 */
11144 OO.ui.MultilineTextInputWidget.prototype.onChange = function () {
11145 this.adjustSize();
11146 };
11147
11148 /**
11149 * @inheritdoc
11150 */
11151 OO.ui.MultilineTextInputWidget.prototype.updatePosition = function () {
11152 OO.ui.MultilineTextInputWidget.parent.prototype.updatePosition.call( this );
11153 this.adjustSize();
11154 };
11155
11156 /**
11157 * @inheritdoc
11158 *
11159 * Modify to emit 'enter' on Ctrl/Meta+Enter, instead of plain Enter
11160 */
11161 OO.ui.MultilineTextInputWidget.prototype.onKeyPress = function ( e ) {
11162 if (
11163 ( e.which === OO.ui.Keys.ENTER && ( e.ctrlKey || e.metaKey ) ) ||
11164 // Some platforms emit keycode 10 for ctrl+enter in a textarea
11165 e.which === 10
11166 ) {
11167 this.emit( 'enter', e );
11168 }
11169 };
11170
11171 /**
11172 * Automatically adjust the size of the text input.
11173 *
11174 * This only affects multiline inputs that are {@link #autosize autosized}.
11175 *
11176 * @chainable
11177 * @return {OO.ui.Widget} The widget, for chaining
11178 * @fires resize
11179 */
11180 OO.ui.MultilineTextInputWidget.prototype.adjustSize = function () {
11181 var scrollHeight, innerHeight, outerHeight, maxInnerHeight, measurementError,
11182 idealHeight, newHeight, scrollWidth, property;
11183
11184 if ( this.$input.val() !== this.valCache ) {
11185 if ( this.autosize ) {
11186 this.$clone
11187 .val( this.$input.val() )
11188 .attr( 'rows', this.minRows )
11189 // Set inline height property to 0 to measure scroll height
11190 .css( 'height', 0 );
11191
11192 this.$clone.removeClass( 'oo-ui-element-hidden' );
11193
11194 this.valCache = this.$input.val();
11195
11196 scrollHeight = this.$clone[ 0 ].scrollHeight;
11197
11198 // Remove inline height property to measure natural heights
11199 this.$clone.css( 'height', '' );
11200 innerHeight = this.$clone.innerHeight();
11201 outerHeight = this.$clone.outerHeight();
11202
11203 // Measure max rows height
11204 this.$clone
11205 .attr( 'rows', this.maxRows )
11206 .css( 'height', 'auto' )
11207 .val( '' );
11208 maxInnerHeight = this.$clone.innerHeight();
11209
11210 // Difference between reported innerHeight and scrollHeight with no scrollbars present.
11211 // This is sometimes non-zero on Blink-based browsers, depending on zoom level.
11212 measurementError = maxInnerHeight - this.$clone[ 0 ].scrollHeight;
11213 idealHeight = Math.min( maxInnerHeight, scrollHeight + measurementError );
11214
11215 this.$clone.addClass( 'oo-ui-element-hidden' );
11216
11217 // Only apply inline height when expansion beyond natural height is needed
11218 // Use the difference between the inner and outer height as a buffer
11219 newHeight = idealHeight > innerHeight ? idealHeight + ( outerHeight - innerHeight ) : '';
11220 if ( newHeight !== this.styleHeight ) {
11221 this.$input.css( 'height', newHeight );
11222 this.styleHeight = newHeight;
11223 this.emit( 'resize' );
11224 }
11225 }
11226 scrollWidth = this.$input[ 0 ].offsetWidth - this.$input[ 0 ].clientWidth;
11227 if ( scrollWidth !== this.scrollWidth ) {
11228 property = this.$element.css( 'direction' ) === 'rtl' ? 'left' : 'right';
11229 // Reset
11230 this.$label.css( { right: '', left: '' } );
11231 this.$indicator.css( { right: '', left: '' } );
11232
11233 if ( scrollWidth ) {
11234 this.$indicator.css( property, scrollWidth );
11235 if ( this.labelPosition === 'after' ) {
11236 this.$label.css( property, scrollWidth );
11237 }
11238 }
11239
11240 this.scrollWidth = scrollWidth;
11241 this.positionLabel();
11242 }
11243 }
11244 return this;
11245 };
11246
11247 /**
11248 * @inheritdoc
11249 * @protected
11250 */
11251 OO.ui.MultilineTextInputWidget.prototype.getInputElement = function () {
11252 return $( '<textarea>' );
11253 };
11254
11255 /**
11256 * Check if the input automatically adjusts its size.
11257 *
11258 * @return {boolean}
11259 */
11260 OO.ui.MultilineTextInputWidget.prototype.isAutosizing = function () {
11261 return !!this.autosize;
11262 };
11263
11264 /**
11265 * @inheritdoc
11266 */
11267 OO.ui.MultilineTextInputWidget.prototype.restorePreInfuseState = function ( state ) {
11268 OO.ui.MultilineTextInputWidget.parent.prototype.restorePreInfuseState.call( this, state );
11269 if ( state.scrollTop !== undefined ) {
11270 this.$input.scrollTop( state.scrollTop );
11271 }
11272 };
11273
11274 /**
11275 * ComboBoxInputWidgets combine a {@link OO.ui.TextInputWidget text input} (where a value
11276 * can be entered manually) and a {@link OO.ui.MenuSelectWidget menu of options} (from which
11277 * a value can be chosen instead). Users can choose options from the combo box in one of two ways:
11278 *
11279 * - by typing a value in the text input field. If the value exactly matches the value of a menu
11280 * option, that option will appear to be selected.
11281 * - by choosing a value from the menu. The value of the chosen option will then appear in the text
11282 * input field.
11283 *
11284 * After the user chooses an option, its `data` will be used as a new value for the widget.
11285 * A `label` also can be specified for each option: if given, it will be shown instead of the
11286 * `data` in the dropdown menu.
11287 *
11288 * This widget can be used inside an HTML form, such as a OO.ui.FormLayout.
11289 *
11290 * For more information about menus and options, please see the [OOUI documentation on MediaWiki][1].
11291 *
11292 * @example
11293 * // Example: A ComboBoxInputWidget.
11294 * var comboBox = new OO.ui.ComboBoxInputWidget( {
11295 * value: 'Option 1',
11296 * options: [
11297 * { data: 'Option 1' },
11298 * { data: 'Option 2' },
11299 * { data: 'Option 3' }
11300 * ]
11301 * } );
11302 * $( 'body' ).append( comboBox.$element );
11303 *
11304 * @example
11305 * // Example: A ComboBoxInputWidget with additional option labels.
11306 * var comboBox = new OO.ui.ComboBoxInputWidget( {
11307 * value: 'Option 1',
11308 * options: [
11309 * {
11310 * data: 'Option 1',
11311 * label: 'Option One'
11312 * },
11313 * {
11314 * data: 'Option 2',
11315 * label: 'Option Two'
11316 * },
11317 * {
11318 * data: 'Option 3',
11319 * label: 'Option Three'
11320 * }
11321 * ]
11322 * } );
11323 * $( 'body' ).append( comboBox.$element );
11324 *
11325 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options#Menu_selects_and_options
11326 *
11327 * @class
11328 * @extends OO.ui.TextInputWidget
11329 *
11330 * @constructor
11331 * @param {Object} [config] Configuration options
11332 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
11333 * @cfg {Object} [menu] Configuration options to pass to the {@link OO.ui.MenuSelectWidget menu select widget}.
11334 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
11335 * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
11336 * containing `<div>` and has a larger area. By default, the menu uses relative positioning.
11337 * See <https://www.mediawiki.org/wiki/OOUI/Concepts#Overlays>.
11338 */
11339 OO.ui.ComboBoxInputWidget = function OoUiComboBoxInputWidget( config ) {
11340 // Configuration initialization
11341 config = $.extend( {
11342 autocomplete: false
11343 }, config );
11344
11345 // ComboBoxInputWidget shouldn't support `multiline`
11346 config.multiline = false;
11347
11348 // See InputWidget#reusePreInfuseDOM about `config.$input`
11349 if ( config.$input ) {
11350 config.$input.removeAttr( 'list' );
11351 }
11352
11353 // Parent constructor
11354 OO.ui.ComboBoxInputWidget.parent.call( this, config );
11355
11356 // Properties
11357 this.$overlay = ( config.$overlay === true ? OO.ui.getDefaultOverlay() : config.$overlay ) || this.$element;
11358 this.dropdownButton = new OO.ui.ButtonWidget( {
11359 classes: [ 'oo-ui-comboBoxInputWidget-dropdownButton' ],
11360 indicator: 'down',
11361 disabled: this.disabled
11362 } );
11363 this.menu = new OO.ui.MenuSelectWidget( $.extend(
11364 {
11365 widget: this,
11366 input: this,
11367 $floatableContainer: this.$element,
11368 disabled: this.isDisabled()
11369 },
11370 config.menu
11371 ) );
11372
11373 // Events
11374 this.connect( this, {
11375 change: 'onInputChange',
11376 enter: 'onInputEnter'
11377 } );
11378 this.dropdownButton.connect( this, {
11379 click: 'onDropdownButtonClick'
11380 } );
11381 this.menu.connect( this, {
11382 choose: 'onMenuChoose',
11383 add: 'onMenuItemsChange',
11384 remove: 'onMenuItemsChange',
11385 toggle: 'onMenuToggle'
11386 } );
11387
11388 // Initialization
11389 this.$input.attr( {
11390 role: 'combobox',
11391 'aria-owns': this.menu.getElementId(),
11392 'aria-autocomplete': 'list'
11393 } );
11394 // Do not override options set via config.menu.items
11395 if ( config.options !== undefined ) {
11396 this.setOptions( config.options );
11397 }
11398 this.$field = $( '<div>' )
11399 .addClass( 'oo-ui-comboBoxInputWidget-field' )
11400 .append( this.$input, this.dropdownButton.$element );
11401 this.$element
11402 .addClass( 'oo-ui-comboBoxInputWidget' )
11403 .append( this.$field );
11404 this.$overlay.append( this.menu.$element );
11405 this.onMenuItemsChange();
11406 };
11407
11408 /* Setup */
11409
11410 OO.inheritClass( OO.ui.ComboBoxInputWidget, OO.ui.TextInputWidget );
11411
11412 /* Methods */
11413
11414 /**
11415 * Get the combobox's menu.
11416 *
11417 * @return {OO.ui.MenuSelectWidget} Menu widget
11418 */
11419 OO.ui.ComboBoxInputWidget.prototype.getMenu = function () {
11420 return this.menu;
11421 };
11422
11423 /**
11424 * Get the combobox's text input widget.
11425 *
11426 * @return {OO.ui.TextInputWidget} Text input widget
11427 */
11428 OO.ui.ComboBoxInputWidget.prototype.getInput = function () {
11429 return this;
11430 };
11431
11432 /**
11433 * Handle input change events.
11434 *
11435 * @private
11436 * @param {string} value New value
11437 */
11438 OO.ui.ComboBoxInputWidget.prototype.onInputChange = function ( value ) {
11439 var match = this.menu.findItemFromData( value );
11440
11441 this.menu.selectItem( match );
11442 if ( this.menu.findHighlightedItem() ) {
11443 this.menu.highlightItem( match );
11444 }
11445
11446 if ( !this.isDisabled() ) {
11447 this.menu.toggle( true );
11448 }
11449 };
11450
11451 /**
11452 * Handle input enter events.
11453 *
11454 * @private
11455 */
11456 OO.ui.ComboBoxInputWidget.prototype.onInputEnter = function () {
11457 if ( !this.isDisabled() ) {
11458 this.menu.toggle( false );
11459 }
11460 };
11461
11462 /**
11463 * Handle button click events.
11464 *
11465 * @private
11466 */
11467 OO.ui.ComboBoxInputWidget.prototype.onDropdownButtonClick = function () {
11468 this.menu.toggle();
11469 this.focus();
11470 };
11471
11472 /**
11473 * Handle menu choose events.
11474 *
11475 * @private
11476 * @param {OO.ui.OptionWidget} item Chosen item
11477 */
11478 OO.ui.ComboBoxInputWidget.prototype.onMenuChoose = function ( item ) {
11479 this.setValue( item.getData() );
11480 };
11481
11482 /**
11483 * Handle menu item change events.
11484 *
11485 * @private
11486 */
11487 OO.ui.ComboBoxInputWidget.prototype.onMenuItemsChange = function () {
11488 var match = this.menu.findItemFromData( this.getValue() );
11489 this.menu.selectItem( match );
11490 if ( this.menu.findHighlightedItem() ) {
11491 this.menu.highlightItem( match );
11492 }
11493 this.$element.toggleClass( 'oo-ui-comboBoxInputWidget-empty', this.menu.isEmpty() );
11494 };
11495
11496 /**
11497 * Handle menu toggle events.
11498 *
11499 * @private
11500 * @param {boolean} isVisible Open state of the menu
11501 */
11502 OO.ui.ComboBoxInputWidget.prototype.onMenuToggle = function ( isVisible ) {
11503 this.$element.toggleClass( 'oo-ui-comboBoxInputWidget-open', isVisible );
11504 };
11505
11506 /**
11507 * @inheritdoc
11508 */
11509 OO.ui.ComboBoxInputWidget.prototype.setDisabled = function ( disabled ) {
11510 // Parent method
11511 OO.ui.ComboBoxInputWidget.parent.prototype.setDisabled.call( this, disabled );
11512
11513 if ( this.dropdownButton ) {
11514 this.dropdownButton.setDisabled( this.isDisabled() );
11515 }
11516 if ( this.menu ) {
11517 this.menu.setDisabled( this.isDisabled() );
11518 }
11519
11520 return this;
11521 };
11522
11523 /**
11524 * Set the options available for this input.
11525 *
11526 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
11527 * @chainable
11528 * @return {OO.ui.Widget} The widget, for chaining
11529 */
11530 OO.ui.ComboBoxInputWidget.prototype.setOptions = function ( options ) {
11531 this.getMenu()
11532 .clearItems()
11533 .addItems( options.map( function ( opt ) {
11534 return new OO.ui.MenuOptionWidget( {
11535 data: opt.data,
11536 label: opt.label !== undefined ? opt.label : opt.data
11537 } );
11538 } ) );
11539
11540 return this;
11541 };
11542
11543 /**
11544 * FieldLayouts are used with OO.ui.FieldsetLayout. Each FieldLayout requires a field-widget,
11545 * which is a widget that is specified by reference before any optional configuration settings.
11546 *
11547 * Field layouts can be configured with help text and/or labels. Labels are aligned in one of four ways:
11548 *
11549 * - **left**: The label is placed before the field-widget and aligned with the left margin.
11550 * A left-alignment is used for forms with many fields.
11551 * - **right**: The label is placed before the field-widget and aligned to the right margin.
11552 * A right-alignment is used for long but familiar forms which users tab through,
11553 * verifying the current field with a quick glance at the label.
11554 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
11555 * that users fill out from top to bottom.
11556 * - **inline**: The label is placed after the field-widget and aligned to the left.
11557 * An inline-alignment is best used with checkboxes or radio buttons.
11558 *
11559 * Help text can either be:
11560 *
11561 * - accessed via a help icon that appears in the upper right corner of the rendered field layout, or
11562 * - shown as a subtle explanation below the label.
11563 *
11564 * If the help text is brief, or is essential to always expose it, set `helpInline` to `true`. If it
11565 * is long or not essential, leave `helpInline` to its default, `false`.
11566 *
11567 * Please see the [OOUI documentation on MediaWiki] [1] for examples and more information.
11568 *
11569 * [1]: https://www.mediawiki.org/wiki/OOUI/Layouts/Fields_and_Fieldsets
11570 *
11571 * @class
11572 * @extends OO.ui.Layout
11573 * @mixins OO.ui.mixin.LabelElement
11574 * @mixins OO.ui.mixin.TitledElement
11575 *
11576 * @constructor
11577 * @param {OO.ui.Widget} fieldWidget Field widget
11578 * @param {Object} [config] Configuration options
11579 * @cfg {string} [align='left'] Alignment of the label: 'left', 'right', 'top'
11580 * or 'inline'
11581 * @cfg {Array} [errors] Error messages about the widget, which will be
11582 * displayed below the widget.
11583 * The array may contain strings or OO.ui.HtmlSnippet instances.
11584 * @cfg {Array} [notices] Notices about the widget, which will be displayed
11585 * below the widget.
11586 * The array may contain strings or OO.ui.HtmlSnippet instances.
11587 * These are more visible than `help` messages when `helpInline` is set, and so
11588 * might be good for transient messages.
11589 * @cfg {string|OO.ui.HtmlSnippet} [help] Help text. When help text is specified
11590 * and `helpInline` is `false`, a "help" icon will appear in the upper-right
11591 * corner of the rendered field; clicking it will display the text in a popup.
11592 * If `helpInline` is `true`, then a subtle description will be shown after the
11593 * label.
11594 * @cfg {boolean} [helpInline=false] Whether or not the help should be inline,
11595 * or shown when the "help" icon is clicked.
11596 * @cfg {jQuery} [$overlay] Passed to OO.ui.PopupButtonWidget for help popup, if
11597 * `help` is given.
11598 * See <https://www.mediawiki.org/wiki/OOUI/Concepts#Overlays>.
11599 *
11600 * @throws {Error} An error is thrown if no widget is specified
11601 */
11602 OO.ui.FieldLayout = function OoUiFieldLayout( fieldWidget, config ) {
11603 // Allow passing positional parameters inside the config object
11604 if ( OO.isPlainObject( fieldWidget ) && config === undefined ) {
11605 config = fieldWidget;
11606 fieldWidget = config.fieldWidget;
11607 }
11608
11609 // Make sure we have required constructor arguments
11610 if ( fieldWidget === undefined ) {
11611 throw new Error( 'Widget not found' );
11612 }
11613
11614 // Configuration initialization
11615 config = $.extend( { align: 'left', helpInline: false }, config );
11616
11617 // Parent constructor
11618 OO.ui.FieldLayout.parent.call( this, config );
11619
11620 // Mixin constructors
11621 OO.ui.mixin.LabelElement.call( this, $.extend( {}, config, {
11622 $label: $( '<label>' )
11623 } ) );
11624 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$label } ) );
11625
11626 // Properties
11627 this.fieldWidget = fieldWidget;
11628 this.errors = [];
11629 this.notices = [];
11630 this.$field = this.isFieldInline() ? $( '<span>' ) : $( '<div>' );
11631 this.$messages = $( '<ul>' );
11632 this.$header = $( '<span>' );
11633 this.$body = $( '<div>' );
11634 this.align = null;
11635 this.helpInline = config.helpInline;
11636
11637 // Events
11638 this.fieldWidget.connect( this, { disable: 'onFieldDisable' } );
11639
11640 // Initialization
11641 this.$help = config.help ?
11642 this.createHelpElement( config.help, config.$overlay ) :
11643 $( [] );
11644 if ( this.fieldWidget.getInputId() ) {
11645 this.$label.attr( 'for', this.fieldWidget.getInputId() );
11646 if ( this.helpInline ) {
11647 this.$help.attr( 'for', this.fieldWidget.getInputId() );
11648 }
11649 } else {
11650 this.$label.on( 'click', function () {
11651 this.fieldWidget.simulateLabelClick();
11652 }.bind( this ) );
11653 if ( this.helpInline ) {
11654 this.$help.on( 'click', function () {
11655 this.fieldWidget.simulateLabelClick();
11656 }.bind( this ) );
11657 }
11658 }
11659 this.$element
11660 .addClass( 'oo-ui-fieldLayout' )
11661 .toggleClass( 'oo-ui-fieldLayout-disabled', this.fieldWidget.isDisabled() )
11662 .append( this.$body );
11663 this.$body.addClass( 'oo-ui-fieldLayout-body' );
11664 this.$header.addClass( 'oo-ui-fieldLayout-header' );
11665 this.$messages.addClass( 'oo-ui-fieldLayout-messages' );
11666 this.$field
11667 .addClass( 'oo-ui-fieldLayout-field' )
11668 .append( this.fieldWidget.$element );
11669
11670 this.setErrors( config.errors || [] );
11671 this.setNotices( config.notices || [] );
11672 this.setAlignment( config.align );
11673 // Call this again to take into account the widget's accessKey
11674 this.updateTitle();
11675 };
11676
11677 /* Setup */
11678
11679 OO.inheritClass( OO.ui.FieldLayout, OO.ui.Layout );
11680 OO.mixinClass( OO.ui.FieldLayout, OO.ui.mixin.LabelElement );
11681 OO.mixinClass( OO.ui.FieldLayout, OO.ui.mixin.TitledElement );
11682
11683 /* Methods */
11684
11685 /**
11686 * Handle field disable events.
11687 *
11688 * @private
11689 * @param {boolean} value Field is disabled
11690 */
11691 OO.ui.FieldLayout.prototype.onFieldDisable = function ( value ) {
11692 this.$element.toggleClass( 'oo-ui-fieldLayout-disabled', value );
11693 };
11694
11695 /**
11696 * Get the widget contained by the field.
11697 *
11698 * @return {OO.ui.Widget} Field widget
11699 */
11700 OO.ui.FieldLayout.prototype.getField = function () {
11701 return this.fieldWidget;
11702 };
11703
11704 /**
11705 * Return `true` if the given field widget can be used with `'inline'` alignment (see
11706 * #setAlignment). Return `false` if it can't or if this can't be determined.
11707 *
11708 * @return {boolean}
11709 */
11710 OO.ui.FieldLayout.prototype.isFieldInline = function () {
11711 // This is very simplistic, but should be good enough.
11712 return this.getField().$element.prop( 'tagName' ).toLowerCase() === 'span';
11713 };
11714
11715 /**
11716 * @protected
11717 * @param {string} kind 'error' or 'notice'
11718 * @param {string|OO.ui.HtmlSnippet} text
11719 * @return {jQuery}
11720 */
11721 OO.ui.FieldLayout.prototype.makeMessage = function ( kind, text ) {
11722 var $listItem, $icon, message;
11723 $listItem = $( '<li>' );
11724 if ( kind === 'error' ) {
11725 $icon = new OO.ui.IconWidget( { icon: 'alert', flags: [ 'warning' ] } ).$element;
11726 $listItem.attr( 'role', 'alert' );
11727 } else if ( kind === 'notice' ) {
11728 $icon = new OO.ui.IconWidget( { icon: 'notice' } ).$element;
11729 } else {
11730 $icon = '';
11731 }
11732 message = new OO.ui.LabelWidget( { label: text } );
11733 $listItem
11734 .append( $icon, message.$element )
11735 .addClass( 'oo-ui-fieldLayout-messages-' + kind );
11736 return $listItem;
11737 };
11738
11739 /**
11740 * Set the field alignment mode.
11741 *
11742 * @private
11743 * @param {string} value Alignment mode, either 'left', 'right', 'top' or 'inline'
11744 * @chainable
11745 * @return {OO.ui.BookletLayout} The layout, for chaining
11746 */
11747 OO.ui.FieldLayout.prototype.setAlignment = function ( value ) {
11748 if ( value !== this.align ) {
11749 // Default to 'left'
11750 if ( [ 'left', 'right', 'top', 'inline' ].indexOf( value ) === -1 ) {
11751 value = 'left';
11752 }
11753 // Validate
11754 if ( value === 'inline' && !this.isFieldInline() ) {
11755 value = 'top';
11756 }
11757 // Reorder elements
11758
11759 if ( this.helpInline ) {
11760 if ( value === 'top' ) {
11761 this.$header.append( this.$label );
11762 this.$body.append( this.$header, this.$field, this.$help );
11763 } else if ( value === 'inline' ) {
11764 this.$header.append( this.$label, this.$help );
11765 this.$body.append( this.$field, this.$header );
11766 } else {
11767 this.$header.append( this.$label, this.$help );
11768 this.$body.append( this.$header, this.$field );
11769 }
11770 } else {
11771 if ( value === 'top' ) {
11772 this.$header.append( this.$help, this.$label );
11773 this.$body.append( this.$header, this.$field );
11774 } else if ( value === 'inline' ) {
11775 this.$header.append( this.$help, this.$label );
11776 this.$body.append( this.$field, this.$header );
11777 } else {
11778 this.$header.append( this.$label );
11779 this.$body.append( this.$header, this.$help, this.$field );
11780 }
11781 }
11782 // Set classes. The following classes can be used here:
11783 // * oo-ui-fieldLayout-align-left
11784 // * oo-ui-fieldLayout-align-right
11785 // * oo-ui-fieldLayout-align-top
11786 // * oo-ui-fieldLayout-align-inline
11787 if ( this.align ) {
11788 this.$element.removeClass( 'oo-ui-fieldLayout-align-' + this.align );
11789 }
11790 this.$element.addClass( 'oo-ui-fieldLayout-align-' + value );
11791 this.align = value;
11792 }
11793
11794 return this;
11795 };
11796
11797 /**
11798 * Set the list of error messages.
11799 *
11800 * @param {Array} errors Error messages about the widget, which will be displayed below the widget.
11801 * The array may contain strings or OO.ui.HtmlSnippet instances.
11802 * @chainable
11803 * @return {OO.ui.BookletLayout} The layout, for chaining
11804 */
11805 OO.ui.FieldLayout.prototype.setErrors = function ( errors ) {
11806 this.errors = errors.slice();
11807 this.updateMessages();
11808 return this;
11809 };
11810
11811 /**
11812 * Set the list of notice messages.
11813 *
11814 * @param {Array} notices Notices about the widget, which will be displayed below the widget.
11815 * The array may contain strings or OO.ui.HtmlSnippet instances.
11816 * @chainable
11817 * @return {OO.ui.BookletLayout} The layout, for chaining
11818 */
11819 OO.ui.FieldLayout.prototype.setNotices = function ( notices ) {
11820 this.notices = notices.slice();
11821 this.updateMessages();
11822 return this;
11823 };
11824
11825 /**
11826 * Update the rendering of error and notice messages.
11827 *
11828 * @private
11829 */
11830 OO.ui.FieldLayout.prototype.updateMessages = function () {
11831 var i;
11832 this.$messages.empty();
11833
11834 if ( this.errors.length || this.notices.length ) {
11835 this.$body.after( this.$messages );
11836 } else {
11837 this.$messages.remove();
11838 return;
11839 }
11840
11841 for ( i = 0; i < this.notices.length; i++ ) {
11842 this.$messages.append( this.makeMessage( 'notice', this.notices[ i ] ) );
11843 }
11844 for ( i = 0; i < this.errors.length; i++ ) {
11845 this.$messages.append( this.makeMessage( 'error', this.errors[ i ] ) );
11846 }
11847 };
11848
11849 /**
11850 * Include information about the widget's accessKey in our title. TitledElement calls this method.
11851 * (This is a bit of a hack.)
11852 *
11853 * @protected
11854 * @param {string} title Tooltip label for 'title' attribute
11855 * @return {string}
11856 */
11857 OO.ui.FieldLayout.prototype.formatTitleWithAccessKey = function ( title ) {
11858 if ( this.fieldWidget && this.fieldWidget.formatTitleWithAccessKey ) {
11859 return this.fieldWidget.formatTitleWithAccessKey( title );
11860 }
11861 return title;
11862 };
11863
11864 /**
11865 * Creates and returns the help element. Also sets the `aria-describedby`
11866 * attribute on the main element of the `fieldWidget`.
11867 *
11868 * @private
11869 * @param {string|OO.ui.HtmlSnippet} [help] Help text.
11870 * @param {jQuery} [$overlay] Passed to OO.ui.PopupButtonWidget for help popup.
11871 * @return {jQuery} The element that should become `this.$help`.
11872 */
11873 OO.ui.FieldLayout.prototype.createHelpElement = function ( help, $overlay ) {
11874 var helpId, helpWidget;
11875
11876 if ( this.helpInline ) {
11877 helpWidget = new OO.ui.LabelWidget( {
11878 label: help,
11879 classes: [ 'oo-ui-inline-help' ]
11880 } );
11881
11882 helpId = helpWidget.getElementId();
11883 } else {
11884 helpWidget = new OO.ui.PopupButtonWidget( {
11885 $overlay: $overlay,
11886 popup: {
11887 padded: true
11888 },
11889 classes: [ 'oo-ui-fieldLayout-help' ],
11890 framed: false,
11891 icon: 'info',
11892 label: OO.ui.msg( 'ooui-field-help' ),
11893 invisibleLabel: true
11894 } );
11895 if ( help instanceof OO.ui.HtmlSnippet ) {
11896 helpWidget.getPopup().$body.html( help.toString() );
11897 } else {
11898 helpWidget.getPopup().$body.text( help );
11899 }
11900
11901 helpId = helpWidget.getPopup().getBodyId();
11902 }
11903
11904 // Set the 'aria-describedby' attribute on the fieldWidget
11905 // Preference given to an input or a button
11906 (
11907 this.fieldWidget.$input ||
11908 this.fieldWidget.$button ||
11909 this.fieldWidget.$element
11910 ).attr( 'aria-describedby', helpId );
11911
11912 return helpWidget.$element;
11913 };
11914
11915 /**
11916 * ActionFieldLayouts are used with OO.ui.FieldsetLayout. The layout consists of a field-widget, a button,
11917 * and an optional label and/or help text. The field-widget (e.g., a {@link OO.ui.TextInputWidget TextInputWidget}),
11918 * is required and is specified before any optional configuration settings.
11919 *
11920 * Labels can be aligned in one of four ways:
11921 *
11922 * - **left**: The label is placed before the field-widget and aligned with the left margin.
11923 * A left-alignment is used for forms with many fields.
11924 * - **right**: The label is placed before the field-widget and aligned to the right margin.
11925 * A right-alignment is used for long but familiar forms which users tab through,
11926 * verifying the current field with a quick glance at the label.
11927 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
11928 * that users fill out from top to bottom.
11929 * - **inline**: The label is placed after the field-widget and aligned to the left.
11930 * An inline-alignment is best used with checkboxes or radio buttons.
11931 *
11932 * Help text is accessed via a help icon that appears in the upper right corner of the rendered field layout when help
11933 * text is specified.
11934 *
11935 * @example
11936 * // Example of an ActionFieldLayout
11937 * var actionFieldLayout = new OO.ui.ActionFieldLayout(
11938 * new OO.ui.TextInputWidget( {
11939 * placeholder: 'Field widget'
11940 * } ),
11941 * new OO.ui.ButtonWidget( {
11942 * label: 'Button'
11943 * } ),
11944 * {
11945 * label: 'An ActionFieldLayout. This label is aligned top',
11946 * align: 'top',
11947 * help: 'This is help text'
11948 * }
11949 * );
11950 *
11951 * $( 'body' ).append( actionFieldLayout.$element );
11952 *
11953 * @class
11954 * @extends OO.ui.FieldLayout
11955 *
11956 * @constructor
11957 * @param {OO.ui.Widget} fieldWidget Field widget
11958 * @param {OO.ui.ButtonWidget} buttonWidget Button widget
11959 * @param {Object} config
11960 */
11961 OO.ui.ActionFieldLayout = function OoUiActionFieldLayout( fieldWidget, buttonWidget, config ) {
11962 // Allow passing positional parameters inside the config object
11963 if ( OO.isPlainObject( fieldWidget ) && config === undefined ) {
11964 config = fieldWidget;
11965 fieldWidget = config.fieldWidget;
11966 buttonWidget = config.buttonWidget;
11967 }
11968
11969 // Parent constructor
11970 OO.ui.ActionFieldLayout.parent.call( this, fieldWidget, config );
11971
11972 // Properties
11973 this.buttonWidget = buttonWidget;
11974 this.$button = $( '<span>' );
11975 this.$input = this.isFieldInline() ? $( '<span>' ) : $( '<div>' );
11976
11977 // Initialization
11978 this.$element
11979 .addClass( 'oo-ui-actionFieldLayout' );
11980 this.$button
11981 .addClass( 'oo-ui-actionFieldLayout-button' )
11982 .append( this.buttonWidget.$element );
11983 this.$input
11984 .addClass( 'oo-ui-actionFieldLayout-input' )
11985 .append( this.fieldWidget.$element );
11986 this.$field
11987 .append( this.$input, this.$button );
11988 };
11989
11990 /* Setup */
11991
11992 OO.inheritClass( OO.ui.ActionFieldLayout, OO.ui.FieldLayout );
11993
11994 /**
11995 * FieldsetLayouts are composed of one or more {@link OO.ui.FieldLayout FieldLayouts},
11996 * which each contain an individual widget and, optionally, a label. Each Fieldset can be
11997 * configured with a label as well. For more information and examples,
11998 * please see the [OOUI documentation on MediaWiki][1].
11999 *
12000 * @example
12001 * // Example of a fieldset layout
12002 * var input1 = new OO.ui.TextInputWidget( {
12003 * placeholder: 'A text input field'
12004 * } );
12005 *
12006 * var input2 = new OO.ui.TextInputWidget( {
12007 * placeholder: 'A text input field'
12008 * } );
12009 *
12010 * var fieldset = new OO.ui.FieldsetLayout( {
12011 * label: 'Example of a fieldset layout'
12012 * } );
12013 *
12014 * fieldset.addItems( [
12015 * new OO.ui.FieldLayout( input1, {
12016 * label: 'Field One'
12017 * } ),
12018 * new OO.ui.FieldLayout( input2, {
12019 * label: 'Field Two'
12020 * } )
12021 * ] );
12022 * $( 'body' ).append( fieldset.$element );
12023 *
12024 * [1]: https://www.mediawiki.org/wiki/OOUI/Layouts/Fields_and_Fieldsets
12025 *
12026 * @class
12027 * @extends OO.ui.Layout
12028 * @mixins OO.ui.mixin.IconElement
12029 * @mixins OO.ui.mixin.LabelElement
12030 * @mixins OO.ui.mixin.GroupElement
12031 *
12032 * @constructor
12033 * @param {Object} [config] Configuration options
12034 * @cfg {OO.ui.FieldLayout[]} [items] An array of fields to add to the fieldset. See OO.ui.FieldLayout for more information about fields.
12035 * @cfg {string|OO.ui.HtmlSnippet} [help] Help text. When help text is specified, a "help" icon will appear
12036 * in the upper-right corner of the rendered field; clicking it will display the text in a popup.
12037 * For important messages, you are advised to use `notices`, as they are always shown.
12038 * @cfg {jQuery} [$overlay] Passed to OO.ui.PopupButtonWidget for help popup, if `help` is given.
12039 * See <https://www.mediawiki.org/wiki/OOUI/Concepts#Overlays>.
12040 */
12041 OO.ui.FieldsetLayout = function OoUiFieldsetLayout( config ) {
12042 // Configuration initialization
12043 config = config || {};
12044
12045 // Parent constructor
12046 OO.ui.FieldsetLayout.parent.call( this, config );
12047
12048 // Mixin constructors
12049 OO.ui.mixin.IconElement.call( this, config );
12050 OO.ui.mixin.LabelElement.call( this, config );
12051 OO.ui.mixin.GroupElement.call( this, config );
12052
12053 // Properties
12054 this.$header = $( '<legend>' );
12055 if ( config.help ) {
12056 this.popupButtonWidget = new OO.ui.PopupButtonWidget( {
12057 $overlay: config.$overlay,
12058 popup: {
12059 padded: true
12060 },
12061 classes: [ 'oo-ui-fieldsetLayout-help' ],
12062 framed: false,
12063 icon: 'info',
12064 label: OO.ui.msg( 'ooui-field-help' ),
12065 invisibleLabel: true
12066 } );
12067 if ( config.help instanceof OO.ui.HtmlSnippet ) {
12068 this.popupButtonWidget.getPopup().$body.html( config.help.toString() );
12069 } else {
12070 this.popupButtonWidget.getPopup().$body.text( config.help );
12071 }
12072 this.$help = this.popupButtonWidget.$element;
12073 } else {
12074 this.$help = $( [] );
12075 }
12076
12077 // Initialization
12078 this.$header
12079 .addClass( 'oo-ui-fieldsetLayout-header' )
12080 .append( this.$icon, this.$label, this.$help );
12081 this.$group.addClass( 'oo-ui-fieldsetLayout-group' );
12082 this.$element
12083 .addClass( 'oo-ui-fieldsetLayout' )
12084 .prepend( this.$header, this.$group );
12085 if ( Array.isArray( config.items ) ) {
12086 this.addItems( config.items );
12087 }
12088 };
12089
12090 /* Setup */
12091
12092 OO.inheritClass( OO.ui.FieldsetLayout, OO.ui.Layout );
12093 OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.mixin.IconElement );
12094 OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.mixin.LabelElement );
12095 OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.mixin.GroupElement );
12096
12097 /* Static Properties */
12098
12099 /**
12100 * @static
12101 * @inheritdoc
12102 */
12103 OO.ui.FieldsetLayout.static.tagName = 'fieldset';
12104
12105 /**
12106 * FormLayouts are used to wrap {@link OO.ui.FieldsetLayout FieldsetLayouts} when you intend to use browser-based
12107 * form submission for the fields instead of handling them in JavaScript. Form layouts can be configured with an
12108 * HTML form action, an encoding type, and a method using the #action, #enctype, and #method configs, respectively.
12109 * See the [OOUI documentation on MediaWiki] [1] for more information and examples.
12110 *
12111 * Only widgets from the {@link OO.ui.InputWidget InputWidget} family support form submission. It
12112 * includes standard form elements like {@link OO.ui.CheckboxInputWidget checkboxes}, {@link
12113 * OO.ui.RadioInputWidget radio buttons} and {@link OO.ui.TextInputWidget text fields}, as well as
12114 * some fancier controls. Some controls have both regular and InputWidget variants, for example
12115 * OO.ui.DropdownWidget and OO.ui.DropdownInputWidget – only the latter support form submission and
12116 * often have simplified APIs to match the capabilities of HTML forms.
12117 * See the [OOUI documentation on MediaWiki] [2] for more information about InputWidgets.
12118 *
12119 * [1]: https://www.mediawiki.org/wiki/OOUI/Layouts/Forms
12120 * [2]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
12121 *
12122 * @example
12123 * // Example of a form layout that wraps a fieldset layout
12124 * var input1 = new OO.ui.TextInputWidget( {
12125 * placeholder: 'Username'
12126 * } );
12127 * var input2 = new OO.ui.TextInputWidget( {
12128 * placeholder: 'Password',
12129 * type: 'password'
12130 * } );
12131 * var submit = new OO.ui.ButtonInputWidget( {
12132 * label: 'Submit'
12133 * } );
12134 *
12135 * var fieldset = new OO.ui.FieldsetLayout( {
12136 * label: 'A form layout'
12137 * } );
12138 * fieldset.addItems( [
12139 * new OO.ui.FieldLayout( input1, {
12140 * label: 'Username',
12141 * align: 'top'
12142 * } ),
12143 * new OO.ui.FieldLayout( input2, {
12144 * label: 'Password',
12145 * align: 'top'
12146 * } ),
12147 * new OO.ui.FieldLayout( submit )
12148 * ] );
12149 * var form = new OO.ui.FormLayout( {
12150 * items: [ fieldset ],
12151 * action: '/api/formhandler',
12152 * method: 'get'
12153 * } )
12154 * $( 'body' ).append( form.$element );
12155 *
12156 * @class
12157 * @extends OO.ui.Layout
12158 * @mixins OO.ui.mixin.GroupElement
12159 *
12160 * @constructor
12161 * @param {Object} [config] Configuration options
12162 * @cfg {string} [method] HTML form `method` attribute
12163 * @cfg {string} [action] HTML form `action` attribute
12164 * @cfg {string} [enctype] HTML form `enctype` attribute
12165 * @cfg {OO.ui.FieldsetLayout[]} [items] Fieldset layouts to add to the form layout.
12166 */
12167 OO.ui.FormLayout = function OoUiFormLayout( config ) {
12168 var action;
12169
12170 // Configuration initialization
12171 config = config || {};
12172
12173 // Parent constructor
12174 OO.ui.FormLayout.parent.call( this, config );
12175
12176 // Mixin constructors
12177 OO.ui.mixin.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) );
12178
12179 // Events
12180 this.$element.on( 'submit', this.onFormSubmit.bind( this ) );
12181
12182 // Make sure the action is safe
12183 action = config.action;
12184 if ( action !== undefined && !OO.ui.isSafeUrl( action ) ) {
12185 action = './' + action;
12186 }
12187
12188 // Initialization
12189 this.$element
12190 .addClass( 'oo-ui-formLayout' )
12191 .attr( {
12192 method: config.method,
12193 action: action,
12194 enctype: config.enctype
12195 } );
12196 if ( Array.isArray( config.items ) ) {
12197 this.addItems( config.items );
12198 }
12199 };
12200
12201 /* Setup */
12202
12203 OO.inheritClass( OO.ui.FormLayout, OO.ui.Layout );
12204 OO.mixinClass( OO.ui.FormLayout, OO.ui.mixin.GroupElement );
12205
12206 /* Events */
12207
12208 /**
12209 * A 'submit' event is emitted when the form is submitted.
12210 *
12211 * @event submit
12212 */
12213
12214 /* Static Properties */
12215
12216 /**
12217 * @static
12218 * @inheritdoc
12219 */
12220 OO.ui.FormLayout.static.tagName = 'form';
12221
12222 /* Methods */
12223
12224 /**
12225 * Handle form submit events.
12226 *
12227 * @private
12228 * @param {jQuery.Event} e Submit event
12229 * @fires submit
12230 * @return {OO.ui.FormLayout} The layout, for chaining
12231 */
12232 OO.ui.FormLayout.prototype.onFormSubmit = function () {
12233 if ( this.emit( 'submit' ) ) {
12234 return false;
12235 }
12236 };
12237
12238 /**
12239 * PanelLayouts expand to cover the entire area of their parent. They can be configured with scrolling, padding,
12240 * and a frame, and are often used together with {@link OO.ui.StackLayout StackLayouts}.
12241 *
12242 * @example
12243 * // Example of a panel layout
12244 * var panel = new OO.ui.PanelLayout( {
12245 * expanded: false,
12246 * framed: true,
12247 * padded: true,
12248 * $content: $( '<p>A panel layout with padding and a frame.</p>' )
12249 * } );
12250 * $( 'body' ).append( panel.$element );
12251 *
12252 * @class
12253 * @extends OO.ui.Layout
12254 *
12255 * @constructor
12256 * @param {Object} [config] Configuration options
12257 * @cfg {boolean} [scrollable=false] Allow vertical scrolling
12258 * @cfg {boolean} [padded=false] Add padding between the content and the edges of the panel.
12259 * @cfg {boolean} [expanded=true] Expand the panel to fill the entire parent element.
12260 * @cfg {boolean} [framed=false] Render the panel with a frame to visually separate it from outside content.
12261 */
12262 OO.ui.PanelLayout = function OoUiPanelLayout( config ) {
12263 // Configuration initialization
12264 config = $.extend( {
12265 scrollable: false,
12266 padded: false,
12267 expanded: true,
12268 framed: false
12269 }, config );
12270
12271 // Parent constructor
12272 OO.ui.PanelLayout.parent.call( this, config );
12273
12274 // Initialization
12275 this.$element.addClass( 'oo-ui-panelLayout' );
12276 if ( config.scrollable ) {
12277 this.$element.addClass( 'oo-ui-panelLayout-scrollable' );
12278 }
12279 if ( config.padded ) {
12280 this.$element.addClass( 'oo-ui-panelLayout-padded' );
12281 }
12282 if ( config.expanded ) {
12283 this.$element.addClass( 'oo-ui-panelLayout-expanded' );
12284 }
12285 if ( config.framed ) {
12286 this.$element.addClass( 'oo-ui-panelLayout-framed' );
12287 }
12288 };
12289
12290 /* Setup */
12291
12292 OO.inheritClass( OO.ui.PanelLayout, OO.ui.Layout );
12293
12294 /* Methods */
12295
12296 /**
12297 * Focus the panel layout
12298 *
12299 * The default implementation just focuses the first focusable element in the panel
12300 */
12301 OO.ui.PanelLayout.prototype.focus = function () {
12302 OO.ui.findFocusable( this.$element ).focus();
12303 };
12304
12305 /**
12306 * HorizontalLayout arranges its contents in a single line (using `display: inline-block` for its
12307 * items), with small margins between them. Convenient when you need to put a number of block-level
12308 * widgets on a single line next to each other.
12309 *
12310 * Note that inline elements, such as OO.ui.ButtonWidgets, do not need this wrapper.
12311 *
12312 * @example
12313 * // HorizontalLayout with a text input and a label
12314 * var layout = new OO.ui.HorizontalLayout( {
12315 * items: [
12316 * new OO.ui.LabelWidget( { label: 'Label' } ),
12317 * new OO.ui.TextInputWidget( { value: 'Text' } )
12318 * ]
12319 * } );
12320 * $( 'body' ).append( layout.$element );
12321 *
12322 * @class
12323 * @extends OO.ui.Layout
12324 * @mixins OO.ui.mixin.GroupElement
12325 *
12326 * @constructor
12327 * @param {Object} [config] Configuration options
12328 * @cfg {OO.ui.Widget[]|OO.ui.Layout[]} [items] Widgets or other layouts to add to the layout.
12329 */
12330 OO.ui.HorizontalLayout = function OoUiHorizontalLayout( config ) {
12331 // Configuration initialization
12332 config = config || {};
12333
12334 // Parent constructor
12335 OO.ui.HorizontalLayout.parent.call( this, config );
12336
12337 // Mixin constructors
12338 OO.ui.mixin.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) );
12339
12340 // Initialization
12341 this.$element.addClass( 'oo-ui-horizontalLayout' );
12342 if ( Array.isArray( config.items ) ) {
12343 this.addItems( config.items );
12344 }
12345 };
12346
12347 /* Setup */
12348
12349 OO.inheritClass( OO.ui.HorizontalLayout, OO.ui.Layout );
12350 OO.mixinClass( OO.ui.HorizontalLayout, OO.ui.mixin.GroupElement );
12351
12352 /**
12353 * NumberInputWidgets combine a {@link OO.ui.TextInputWidget text input} (where a value
12354 * can be entered manually) and two {@link OO.ui.ButtonWidget button widgets}
12355 * (to adjust the value in increments) to allow the user to enter a number.
12356 *
12357 * @example
12358 * // Example: A NumberInputWidget.
12359 * var numberInput = new OO.ui.NumberInputWidget( {
12360 * label: 'NumberInputWidget',
12361 * input: { value: 5 },
12362 * min: 1,
12363 * max: 10
12364 * } );
12365 * $( 'body' ).append( numberInput.$element );
12366 *
12367 * @class
12368 * @extends OO.ui.TextInputWidget
12369 *
12370 * @constructor
12371 * @param {Object} [config] Configuration options
12372 * @cfg {Object} [minusButton] Configuration options to pass to the
12373 * {@link OO.ui.ButtonWidget decrementing button widget}.
12374 * @cfg {Object} [plusButton] Configuration options to pass to the
12375 * {@link OO.ui.ButtonWidget incrementing button widget}.
12376 * @cfg {number} [min=-Infinity] Minimum allowed value
12377 * @cfg {number} [max=Infinity] Maximum allowed value
12378 * @cfg {number|null} [step] If specified, the field only accepts values that are multiples of this.
12379 * @cfg {number} [buttonStep=step||1] Delta when using the buttons or up/down arrow keys.
12380 * Defaults to `step` if specified, otherwise `1`.
12381 * @cfg {number} [pageStep=10*buttonStep] Delta when using the page-up/page-down keys.
12382 * Defaults to 10 times `buttonStep`.
12383 * @cfg {boolean} [showButtons=true] Whether to show the plus and minus buttons.
12384 */
12385 OO.ui.NumberInputWidget = function OoUiNumberInputWidget( config ) {
12386 var $field = $( '<div>' )
12387 .addClass( 'oo-ui-numberInputWidget-field' );
12388
12389 // Configuration initialization
12390 config = $.extend( {
12391 min: -Infinity,
12392 max: Infinity,
12393 showButtons: true
12394 }, config );
12395
12396 // For backward compatibility
12397 $.extend( config, config.input );
12398 this.input = this;
12399
12400 // Parent constructor
12401 OO.ui.NumberInputWidget.parent.call( this, $.extend( config, {
12402 type: 'number'
12403 } ) );
12404
12405 if ( config.showButtons ) {
12406 this.minusButton = new OO.ui.ButtonWidget( $.extend(
12407 {
12408 disabled: this.isDisabled(),
12409 tabIndex: -1,
12410 classes: [ 'oo-ui-numberInputWidget-minusButton' ],
12411 icon: 'subtract'
12412 },
12413 config.minusButton
12414 ) );
12415 this.minusButton.$element.attr( 'aria-hidden', 'true' );
12416 this.plusButton = new OO.ui.ButtonWidget( $.extend(
12417 {
12418 disabled: this.isDisabled(),
12419 tabIndex: -1,
12420 classes: [ 'oo-ui-numberInputWidget-plusButton' ],
12421 icon: 'add'
12422 },
12423 config.plusButton
12424 ) );
12425 this.plusButton.$element.attr( 'aria-hidden', 'true' );
12426 }
12427
12428 // Events
12429 this.$input.on( {
12430 keydown: this.onKeyDown.bind( this ),
12431 'wheel mousewheel DOMMouseScroll': this.onWheel.bind( this )
12432 } );
12433 if ( config.showButtons ) {
12434 this.plusButton.connect( this, {
12435 click: [ 'onButtonClick', +1 ]
12436 } );
12437 this.minusButton.connect( this, {
12438 click: [ 'onButtonClick', -1 ]
12439 } );
12440 }
12441
12442 // Build the field
12443 $field.append( this.$input );
12444 if ( config.showButtons ) {
12445 $field
12446 .prepend( this.minusButton.$element )
12447 .append( this.plusButton.$element );
12448 }
12449
12450 // Initialization
12451 if ( config.allowInteger || config.isInteger ) {
12452 // Backward compatibility
12453 config.step = 1;
12454 }
12455 this.setRange( config.min, config.max );
12456 this.setStep( config.buttonStep, config.pageStep, config.step );
12457 // Set the validation method after we set step and range
12458 // so that it doesn't immediately call setValidityFlag
12459 this.setValidation( this.validateNumber.bind( this ) );
12460
12461 this.$element
12462 .addClass( 'oo-ui-numberInputWidget' )
12463 .toggleClass( 'oo-ui-numberInputWidget-buttoned', config.showButtons )
12464 .append( $field );
12465 };
12466
12467 /* Setup */
12468
12469 OO.inheritClass( OO.ui.NumberInputWidget, OO.ui.TextInputWidget );
12470
12471 /* Methods */
12472
12473 // Backward compatibility
12474 OO.ui.NumberInputWidget.prototype.setAllowInteger = function ( flag ) {
12475 this.setStep( flag ? 1 : null );
12476 };
12477 // Backward compatibility
12478 OO.ui.NumberInputWidget.prototype.setIsInteger = OO.ui.NumberInputWidget.prototype.setAllowInteger;
12479
12480 // Backward compatibility
12481 OO.ui.NumberInputWidget.prototype.getAllowInteger = function () {
12482 return this.step === 1;
12483 };
12484 // Backward compatibility
12485 OO.ui.NumberInputWidget.prototype.getIsInteger = OO.ui.NumberInputWidget.prototype.getAllowInteger;
12486
12487 /**
12488 * Set the range of allowed values
12489 *
12490 * @param {number} min Minimum allowed value
12491 * @param {number} max Maximum allowed value
12492 */
12493 OO.ui.NumberInputWidget.prototype.setRange = function ( min, max ) {
12494 if ( min > max ) {
12495 throw new Error( 'Minimum (' + min + ') must not be greater than maximum (' + max + ')' );
12496 }
12497 this.min = min;
12498 this.max = max;
12499 this.$input.attr( 'min', this.min );
12500 this.$input.attr( 'max', this.max );
12501 this.setValidityFlag();
12502 };
12503
12504 /**
12505 * Get the current range
12506 *
12507 * @return {number[]} Minimum and maximum values
12508 */
12509 OO.ui.NumberInputWidget.prototype.getRange = function () {
12510 return [ this.min, this.max ];
12511 };
12512
12513 /**
12514 * Set the stepping deltas
12515 *
12516 * @param {number} [buttonStep=step||1] Delta when using the buttons or up/down arrow keys.
12517 * Defaults to `step` if specified, otherwise `1`.
12518 * @param {number} [pageStep=10*buttonStep] Delta when using the page-up/page-down keys.
12519 * Defaults to 10 times `buttonStep`.
12520 * @param {number|null} [step] If specified, the field only accepts values that are multiples of this.
12521 */
12522 OO.ui.NumberInputWidget.prototype.setStep = function ( buttonStep, pageStep, step ) {
12523 if ( buttonStep === undefined ) {
12524 buttonStep = step || 1;
12525 }
12526 if ( pageStep === undefined ) {
12527 pageStep = 10 * buttonStep;
12528 }
12529 if ( step !== null && step <= 0 ) {
12530 throw new Error( 'Step value, if given, must be positive' );
12531 }
12532 if ( buttonStep <= 0 ) {
12533 throw new Error( 'Button step value must be positive' );
12534 }
12535 if ( pageStep <= 0 ) {
12536 throw new Error( 'Page step value must be positive' );
12537 }
12538 this.step = step;
12539 this.buttonStep = buttonStep;
12540 this.pageStep = pageStep;
12541 this.$input.attr( 'step', this.step || 'any' );
12542 this.setValidityFlag();
12543 };
12544
12545 /**
12546 * @inheritdoc
12547 */
12548 OO.ui.NumberInputWidget.prototype.setValue = function ( value ) {
12549 if ( value === '' ) {
12550 // Some browsers allow a value in the input even if there isn't one reported by $input.val()
12551 // so here we make sure an 'empty' value is actually displayed as such.
12552 this.$input.val( '' );
12553 }
12554 return OO.ui.NumberInputWidget.parent.prototype.setValue.call( this, value );
12555 };
12556
12557 /**
12558 * Get the current stepping values
12559 *
12560 * @return {number[]} Button step, page step, and validity step
12561 */
12562 OO.ui.NumberInputWidget.prototype.getStep = function () {
12563 return [ this.buttonStep, this.pageStep, this.step ];
12564 };
12565
12566 /**
12567 * Get the current value of the widget as a number
12568 *
12569 * @return {number} May be NaN, or an invalid number
12570 */
12571 OO.ui.NumberInputWidget.prototype.getNumericValue = function () {
12572 return +this.getValue();
12573 };
12574
12575 /**
12576 * Adjust the value of the widget
12577 *
12578 * @param {number} delta Adjustment amount
12579 */
12580 OO.ui.NumberInputWidget.prototype.adjustValue = function ( delta ) {
12581 var n, v = this.getNumericValue();
12582
12583 delta = +delta;
12584 if ( isNaN( delta ) || !isFinite( delta ) ) {
12585 throw new Error( 'Delta must be a finite number' );
12586 }
12587
12588 if ( isNaN( v ) ) {
12589 n = 0;
12590 } else {
12591 n = v + delta;
12592 n = Math.max( Math.min( n, this.max ), this.min );
12593 if ( this.step ) {
12594 n = Math.round( n / this.step ) * this.step;
12595 }
12596 }
12597
12598 if ( n !== v ) {
12599 this.setValue( n );
12600 }
12601 };
12602 /**
12603 * Validate input
12604 *
12605 * @private
12606 * @param {string} value Field value
12607 * @return {boolean}
12608 */
12609 OO.ui.NumberInputWidget.prototype.validateNumber = function ( value ) {
12610 var n = +value;
12611 if ( value === '' ) {
12612 return !this.isRequired();
12613 }
12614
12615 if ( isNaN( n ) || !isFinite( n ) ) {
12616 return false;
12617 }
12618
12619 if ( this.step && Math.floor( n / this.step ) !== n / this.step ) {
12620 return false;
12621 }
12622
12623 if ( n < this.min || n > this.max ) {
12624 return false;
12625 }
12626
12627 return true;
12628 };
12629
12630 /**
12631 * Handle mouse click events.
12632 *
12633 * @private
12634 * @param {number} dir +1 or -1
12635 */
12636 OO.ui.NumberInputWidget.prototype.onButtonClick = function ( dir ) {
12637 this.adjustValue( dir * this.buttonStep );
12638 };
12639
12640 /**
12641 * Handle mouse wheel events.
12642 *
12643 * @private
12644 * @param {jQuery.Event} event
12645 * @return {undefined/boolean} False to prevent default if event is handled
12646 */
12647 OO.ui.NumberInputWidget.prototype.onWheel = function ( event ) {
12648 var delta = 0;
12649
12650 if ( !this.isDisabled() && this.$input.is( ':focus' ) ) {
12651 // Standard 'wheel' event
12652 if ( event.originalEvent.deltaMode !== undefined ) {
12653 this.sawWheelEvent = true;
12654 }
12655 if ( event.originalEvent.deltaY ) {
12656 delta = -event.originalEvent.deltaY;
12657 } else if ( event.originalEvent.deltaX ) {
12658 delta = event.originalEvent.deltaX;
12659 }
12660
12661 // Non-standard events
12662 if ( !this.sawWheelEvent ) {
12663 if ( event.originalEvent.wheelDeltaX ) {
12664 delta = -event.originalEvent.wheelDeltaX;
12665 } else if ( event.originalEvent.wheelDeltaY ) {
12666 delta = event.originalEvent.wheelDeltaY;
12667 } else if ( event.originalEvent.wheelDelta ) {
12668 delta = event.originalEvent.wheelDelta;
12669 } else if ( event.originalEvent.detail ) {
12670 delta = -event.originalEvent.detail;
12671 }
12672 }
12673
12674 if ( delta ) {
12675 delta = delta < 0 ? -1 : 1;
12676 this.adjustValue( delta * this.buttonStep );
12677 }
12678
12679 return false;
12680 }
12681 };
12682
12683 /**
12684 * Handle key down events.
12685 *
12686 * @private
12687 * @param {jQuery.Event} e Key down event
12688 * @return {undefined/boolean} False to prevent default if event is handled
12689 */
12690 OO.ui.NumberInputWidget.prototype.onKeyDown = function ( e ) {
12691 if ( !this.isDisabled() ) {
12692 switch ( e.which ) {
12693 case OO.ui.Keys.UP:
12694 this.adjustValue( this.buttonStep );
12695 return false;
12696 case OO.ui.Keys.DOWN:
12697 this.adjustValue( -this.buttonStep );
12698 return false;
12699 case OO.ui.Keys.PAGEUP:
12700 this.adjustValue( this.pageStep );
12701 return false;
12702 case OO.ui.Keys.PAGEDOWN:
12703 this.adjustValue( -this.pageStep );
12704 return false;
12705 }
12706 }
12707 };
12708
12709 /**
12710 * @inheritdoc
12711 */
12712 OO.ui.NumberInputWidget.prototype.setDisabled = function ( disabled ) {
12713 // Parent method
12714 OO.ui.NumberInputWidget.parent.prototype.setDisabled.call( this, disabled );
12715
12716 if ( this.minusButton ) {
12717 this.minusButton.setDisabled( this.isDisabled() );
12718 }
12719 if ( this.plusButton ) {
12720 this.plusButton.setDisabled( this.isDisabled() );
12721 }
12722
12723 return this;
12724 };
12725
12726 }( OO ) );
12727
12728 //# sourceMappingURL=oojs-ui-core.js.map.json