Merge "Use PHP 7 '??' operator instead of '?:' with 'isset()' where convenient"
[lhc/web/wiklou.git] / resources / lib / oojs-ui / oojs-ui-core.js
1 /*!
2 * OOUI v0.27.1
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-05-29T23:24:49Z
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 * @return {OO.ui.Element}
337 * The `OO.ui.Element` corresponding to this (infusable) document node.
338 */
339 OO.ui.infuse = function ( idOrNode ) {
340 return OO.ui.Element.static.infuse( idOrNode );
341 };
342
343 ( function () {
344 /**
345 * Message store for the default implementation of OO.ui.msg
346 *
347 * Environments that provide a localization system should not use this, but should override
348 * OO.ui.msg altogether.
349 *
350 * @private
351 */
352 var messages = {
353 // Tool tip for a button that moves items in a list down one place
354 'ooui-outline-control-move-down': 'Move item down',
355 // Tool tip for a button that moves items in a list up one place
356 'ooui-outline-control-move-up': 'Move item up',
357 // Tool tip for a button that removes items from a list
358 'ooui-outline-control-remove': 'Remove item',
359 // Label for the toolbar group that contains a list of all other available tools
360 'ooui-toolbar-more': 'More',
361 // Label for the fake tool that expands the full list of tools in a toolbar group
362 'ooui-toolgroup-expand': 'More',
363 // Label for the fake tool that collapses the full list of tools in a toolbar group
364 'ooui-toolgroup-collapse': 'Fewer',
365 // Default label for the tooltip for the button that removes a tag item
366 'ooui-item-remove': 'Remove',
367 // Default label for the accept button of a confirmation dialog
368 'ooui-dialog-message-accept': 'OK',
369 // Default label for the reject button of a confirmation dialog
370 'ooui-dialog-message-reject': 'Cancel',
371 // Title for process dialog error description
372 'ooui-dialog-process-error': 'Something went wrong',
373 // Label for process dialog dismiss error button, visible when describing errors
374 'ooui-dialog-process-dismiss': 'Dismiss',
375 // Label for process dialog retry action button, visible when describing only recoverable errors
376 'ooui-dialog-process-retry': 'Try again',
377 // Label for process dialog retry action button, visible when describing only warnings
378 'ooui-dialog-process-continue': 'Continue',
379 // Label for the file selection widget's select file button
380 'ooui-selectfile-button-select': 'Select a file',
381 // Label for the file selection widget if file selection is not supported
382 'ooui-selectfile-not-supported': 'File selection is not supported',
383 // Label for the file selection widget when no file is currently selected
384 'ooui-selectfile-placeholder': 'No file is selected',
385 // Label for the file selection widget's drop target
386 'ooui-selectfile-dragdrop-placeholder': 'Drop file here'
387 };
388
389 /**
390 * Get a localized message.
391 *
392 * After the message key, message parameters may optionally be passed. In the default implementation,
393 * any occurrences of $1 are replaced with the first parameter, $2 with the second parameter, etc.
394 * Alternative implementations of OO.ui.msg may use any substitution system they like, as long as
395 * they support unnamed, ordered message parameters.
396 *
397 * In environments that provide a localization system, this function should be overridden to
398 * return the message translated in the user's language. The default implementation always returns
399 * English messages. An example of doing this with [jQuery.i18n](https://github.com/wikimedia/jquery.i18n)
400 * follows.
401 *
402 * @example
403 * var i, iLen, button,
404 * messagePath = 'oojs-ui/dist/i18n/',
405 * languages = [ $.i18n().locale, 'ur', 'en' ],
406 * languageMap = {};
407 *
408 * for ( i = 0, iLen = languages.length; i < iLen; i++ ) {
409 * languageMap[ languages[ i ] ] = messagePath + languages[ i ].toLowerCase() + '.json';
410 * }
411 *
412 * $.i18n().load( languageMap ).done( function() {
413 * // Replace the built-in `msg` only once we've loaded the internationalization.
414 * // OOUI uses `OO.ui.deferMsg` for all initially-loaded messages. So long as
415 * // you put off creating any widgets until this promise is complete, no English
416 * // will be displayed.
417 * OO.ui.msg = $.i18n;
418 *
419 * // A button displaying "OK" in the default locale
420 * button = new OO.ui.ButtonWidget( {
421 * label: OO.ui.msg( 'ooui-dialog-message-accept' ),
422 * icon: 'check'
423 * } );
424 * $( 'body' ).append( button.$element );
425 *
426 * // A button displaying "OK" in Urdu
427 * $.i18n().locale = 'ur';
428 * button = new OO.ui.ButtonWidget( {
429 * label: OO.ui.msg( 'ooui-dialog-message-accept' ),
430 * icon: 'check'
431 * } );
432 * $( 'body' ).append( button.$element );
433 * } );
434 *
435 * @param {string} key Message key
436 * @param {...Mixed} [params] Message parameters
437 * @return {string} Translated message with parameters substituted
438 */
439 OO.ui.msg = function ( key ) {
440 var message = messages[ key ],
441 params = Array.prototype.slice.call( arguments, 1 );
442 if ( typeof message === 'string' ) {
443 // Perform $1 substitution
444 message = message.replace( /\$(\d+)/g, function ( unused, n ) {
445 var i = parseInt( n, 10 );
446 return params[ i - 1 ] !== undefined ? params[ i - 1 ] : '$' + n;
447 } );
448 } else {
449 // Return placeholder if message not found
450 message = '[' + key + ']';
451 }
452 return message;
453 };
454 }() );
455
456 /**
457 * Package a message and arguments for deferred resolution.
458 *
459 * Use this when you are statically specifying a message and the message may not yet be present.
460 *
461 * @param {string} key Message key
462 * @param {...Mixed} [params] Message parameters
463 * @return {Function} Function that returns the resolved message when executed
464 */
465 OO.ui.deferMsg = function () {
466 var args = arguments;
467 return function () {
468 return OO.ui.msg.apply( OO.ui, args );
469 };
470 };
471
472 /**
473 * Resolve a message.
474 *
475 * If the message is a function it will be executed, otherwise it will pass through directly.
476 *
477 * @param {Function|string} msg Deferred message, or message text
478 * @return {string} Resolved message
479 */
480 OO.ui.resolveMsg = function ( msg ) {
481 if ( $.isFunction( msg ) ) {
482 return msg();
483 }
484 return msg;
485 };
486
487 /**
488 * @param {string} url
489 * @return {boolean}
490 */
491 OO.ui.isSafeUrl = function ( url ) {
492 // Keep this function in sync with php/Tag.php
493 var i, protocolWhitelist;
494
495 function stringStartsWith( haystack, needle ) {
496 return haystack.substr( 0, needle.length ) === needle;
497 }
498
499 protocolWhitelist = [
500 'bitcoin', 'ftp', 'ftps', 'geo', 'git', 'gopher', 'http', 'https', 'irc', 'ircs',
501 'magnet', 'mailto', 'mms', 'news', 'nntp', 'redis', 'sftp', 'sip', 'sips', 'sms', 'ssh',
502 'svn', 'tel', 'telnet', 'urn', 'worldwind', 'xmpp'
503 ];
504
505 if ( url === '' ) {
506 return true;
507 }
508
509 for ( i = 0; i < protocolWhitelist.length; i++ ) {
510 if ( stringStartsWith( url, protocolWhitelist[ i ] + ':' ) ) {
511 return true;
512 }
513 }
514
515 // This matches '//' too
516 if ( stringStartsWith( url, '/' ) || stringStartsWith( url, './' ) ) {
517 return true;
518 }
519 if ( stringStartsWith( url, '?' ) || stringStartsWith( url, '#' ) ) {
520 return true;
521 }
522
523 return false;
524 };
525
526 /**
527 * Check if the user has a 'mobile' device.
528 *
529 * For our purposes this means the user is primarily using an
530 * on-screen keyboard, touch input instead of a mouse and may
531 * have a physically small display.
532 *
533 * It is left up to implementors to decide how to compute this
534 * so the default implementation always returns false.
535 *
536 * @return {boolean} User is on a mobile device
537 */
538 OO.ui.isMobile = function () {
539 return false;
540 };
541
542 /**
543 * Get the additional spacing that should be taken into account when displaying elements that are
544 * clipped to the viewport, e.g. dropdown menus and popups. This is meant to be overridden to avoid
545 * such menus overlapping any fixed headers/toolbars/navigation used by the site.
546 *
547 * @return {Object} Object with the properties 'top', 'right', 'bottom', 'left', each representing
548 * the extra spacing from that edge of viewport (in pixels)
549 */
550 OO.ui.getViewportSpacing = function () {
551 return {
552 top: 0,
553 right: 0,
554 bottom: 0,
555 left: 0
556 };
557 };
558
559 /**
560 * Get the default overlay, which is used by various widgets when they are passed `$overlay: true`.
561 * See <https://www.mediawiki.org/wiki/OOUI/Concepts#Overlays>.
562 *
563 * @return {jQuery} Default overlay node
564 */
565 OO.ui.getDefaultOverlay = function () {
566 if ( !OO.ui.$defaultOverlay ) {
567 OO.ui.$defaultOverlay = $( '<div>' ).addClass( 'oo-ui-defaultOverlay' );
568 $( 'body' ).append( OO.ui.$defaultOverlay );
569 }
570 return OO.ui.$defaultOverlay;
571 };
572
573 /*!
574 * Mixin namespace.
575 */
576
577 /**
578 * Namespace for OOUI mixins.
579 *
580 * Mixins are named according to the type of object they are intended to
581 * be mixed in to. For example, OO.ui.mixin.GroupElement is intended to be
582 * mixed in to an instance of OO.ui.Element, and OO.ui.mixin.GroupWidget
583 * is intended to be mixed in to an instance of OO.ui.Widget.
584 *
585 * @class
586 * @singleton
587 */
588 OO.ui.mixin = {};
589
590 /**
591 * Each Element represents a rendering in the DOM—a button or an icon, for example, or anything
592 * that is visible to a user. Unlike {@link OO.ui.Widget widgets}, plain elements usually do not have events
593 * connected to them and can't be interacted with.
594 *
595 * @abstract
596 * @class
597 *
598 * @constructor
599 * @param {Object} [config] Configuration options
600 * @cfg {string[]} [classes] The names of the CSS classes to apply to the element. CSS styles are added
601 * to the top level (e.g., the outermost div) of the element. See the [OOUI documentation on MediaWiki][2]
602 * for an example.
603 * [2]: https://www.mediawiki.org/wiki/OOUI/Widgets/Buttons_and_Switches#cssExample
604 * @cfg {string} [id] The HTML id attribute used in the rendered tag.
605 * @cfg {string} [text] Text to insert
606 * @cfg {Array} [content] An array of content elements to append (after #text).
607 * Strings will be html-escaped; use an OO.ui.HtmlSnippet to append raw HTML.
608 * Instances of OO.ui.Element will have their $element appended.
609 * @cfg {jQuery} [$content] Content elements to append (after #text).
610 * @cfg {jQuery} [$element] Wrapper element. Defaults to a new element with #getTagName.
611 * @cfg {Mixed} [data] Custom data of any type or combination of types (e.g., string, number, array, object).
612 * Data can also be specified with the #setData method.
613 */
614 OO.ui.Element = function OoUiElement( config ) {
615 if ( OO.ui.isDemo ) {
616 this.initialConfig = config;
617 }
618 // Configuration initialization
619 config = config || {};
620
621 // Properties
622 this.$ = $;
623 this.elementId = null;
624 this.visible = true;
625 this.data = config.data;
626 this.$element = config.$element ||
627 $( document.createElement( this.getTagName() ) );
628 this.elementGroup = null;
629
630 // Initialization
631 if ( Array.isArray( config.classes ) ) {
632 this.$element.addClass( config.classes.join( ' ' ) );
633 }
634 if ( config.id ) {
635 this.setElementId( config.id );
636 }
637 if ( config.text ) {
638 this.$element.text( config.text );
639 }
640 if ( config.content ) {
641 // The `content` property treats plain strings as text; use an
642 // HtmlSnippet to append HTML content. `OO.ui.Element`s get their
643 // appropriate $element appended.
644 this.$element.append( config.content.map( function ( v ) {
645 if ( typeof v === 'string' ) {
646 // Escape string so it is properly represented in HTML.
647 return document.createTextNode( v );
648 } else if ( v instanceof OO.ui.HtmlSnippet ) {
649 // Bypass escaping.
650 return v.toString();
651 } else if ( v instanceof OO.ui.Element ) {
652 return v.$element;
653 }
654 return v;
655 } ) );
656 }
657 if ( config.$content ) {
658 // The `$content` property treats plain strings as HTML.
659 this.$element.append( config.$content );
660 }
661 };
662
663 /* Setup */
664
665 OO.initClass( OO.ui.Element );
666
667 /* Static Properties */
668
669 /**
670 * The name of the HTML tag used by the element.
671 *
672 * The static value may be ignored if the #getTagName method is overridden.
673 *
674 * @static
675 * @inheritable
676 * @property {string}
677 */
678 OO.ui.Element.static.tagName = 'div';
679
680 /* Static Methods */
681
682 /**
683 * Reconstitute a JavaScript object corresponding to a widget created
684 * by the PHP implementation.
685 *
686 * @param {string|HTMLElement|jQuery} idOrNode
687 * A DOM id (if a string) or node for the widget to infuse.
688 * @return {OO.ui.Element}
689 * The `OO.ui.Element` corresponding to this (infusable) document node.
690 * For `Tag` objects emitted on the HTML side (used occasionally for content)
691 * the value returned is a newly-created Element wrapping around the existing
692 * DOM node.
693 */
694 OO.ui.Element.static.infuse = function ( idOrNode ) {
695 var obj = OO.ui.Element.static.unsafeInfuse( idOrNode, false );
696 // Verify that the type matches up.
697 // FIXME: uncomment after T89721 is fixed, see T90929.
698 /*
699 if ( !( obj instanceof this['class'] ) ) {
700 throw new Error( 'Infusion type mismatch!' );
701 }
702 */
703 return obj;
704 };
705
706 /**
707 * Implementation helper for `infuse`; skips the type check and has an
708 * extra property so that only the top-level invocation touches the DOM.
709 *
710 * @private
711 * @param {string|HTMLElement|jQuery} idOrNode
712 * @param {jQuery.Promise|boolean} domPromise A promise that will be resolved
713 * when the top-level widget of this infusion is inserted into DOM,
714 * replacing the original node; or false for top-level invocation.
715 * @return {OO.ui.Element}
716 */
717 OO.ui.Element.static.unsafeInfuse = function ( idOrNode, domPromise ) {
718 // look for a cached result of a previous infusion.
719 var id, $elem, error, data, cls, parts, parent, obj, top, state, infusedChildren;
720 if ( typeof idOrNode === 'string' ) {
721 id = idOrNode;
722 $elem = $( document.getElementById( id ) );
723 } else {
724 $elem = $( idOrNode );
725 id = $elem.attr( 'id' );
726 }
727 if ( !$elem.length ) {
728 if ( typeof idOrNode === 'string' ) {
729 error = 'Widget not found: ' + idOrNode;
730 } else if ( idOrNode && idOrNode.selector ) {
731 error = 'Widget not found: ' + idOrNode.selector;
732 } else {
733 error = 'Widget not found';
734 }
735 throw new Error( error );
736 }
737 if ( $elem[ 0 ].oouiInfused ) {
738 $elem = $elem[ 0 ].oouiInfused;
739 }
740 data = $elem.data( 'ooui-infused' );
741 if ( data ) {
742 // cached!
743 if ( data === true ) {
744 throw new Error( 'Circular dependency! ' + id );
745 }
746 if ( domPromise ) {
747 // pick up dynamic state, like focus, value of form inputs, scroll position, etc.
748 state = data.constructor.static.gatherPreInfuseState( $elem, data );
749 // restore dynamic state after the new element is re-inserted into DOM under infused parent
750 domPromise.done( data.restorePreInfuseState.bind( data, state ) );
751 infusedChildren = $elem.data( 'ooui-infused-children' );
752 if ( infusedChildren && infusedChildren.length ) {
753 infusedChildren.forEach( function ( data ) {
754 var state = data.constructor.static.gatherPreInfuseState( $elem, data );
755 domPromise.done( data.restorePreInfuseState.bind( data, state ) );
756 } );
757 }
758 }
759 return data;
760 }
761 data = $elem.attr( 'data-ooui' );
762 if ( !data ) {
763 throw new Error( 'No infusion data found: ' + id );
764 }
765 try {
766 data = JSON.parse( data );
767 } catch ( _ ) {
768 data = null;
769 }
770 if ( !( data && data._ ) ) {
771 throw new Error( 'No valid infusion data found: ' + id );
772 }
773 if ( data._ === 'Tag' ) {
774 // Special case: this is a raw Tag; wrap existing node, don't rebuild.
775 return new OO.ui.Element( { $element: $elem } );
776 }
777 parts = data._.split( '.' );
778 cls = OO.getProp.apply( OO, [ window ].concat( parts ) );
779 if ( cls === undefined ) {
780 throw new Error( 'Unknown widget type: id: ' + id + ', class: ' + data._ );
781 }
782
783 // Verify that we're creating an OO.ui.Element instance
784 parent = cls.parent;
785
786 while ( parent !== undefined ) {
787 if ( parent === OO.ui.Element ) {
788 // Safe
789 break;
790 }
791
792 parent = parent.parent;
793 }
794
795 if ( parent !== OO.ui.Element ) {
796 throw new Error( 'Unknown widget type: id: ' + id + ', class: ' + data._ );
797 }
798
799 if ( domPromise === false ) {
800 top = $.Deferred();
801 domPromise = top.promise();
802 }
803 $elem.data( 'ooui-infused', true ); // prevent loops
804 data.id = id; // implicit
805 infusedChildren = [];
806 data = OO.copy( data, null, function deserialize( value ) {
807 var infused;
808 if ( OO.isPlainObject( value ) ) {
809 if ( value.tag ) {
810 infused = OO.ui.Element.static.unsafeInfuse( value.tag, domPromise );
811 infusedChildren.push( infused );
812 // Flatten the structure
813 infusedChildren.push.apply( infusedChildren, infused.$element.data( 'ooui-infused-children' ) || [] );
814 infused.$element.removeData( 'ooui-infused-children' );
815 return infused;
816 }
817 if ( value.html !== undefined ) {
818 return new OO.ui.HtmlSnippet( value.html );
819 }
820 }
821 } );
822 // allow widgets to reuse parts of the DOM
823 data = cls.static.reusePreInfuseDOM( $elem[ 0 ], data );
824 // pick up dynamic state, like focus, value of form inputs, scroll position, etc.
825 state = cls.static.gatherPreInfuseState( $elem[ 0 ], data );
826 // rebuild widget
827 // eslint-disable-next-line new-cap
828 obj = new cls( data );
829 // If anyone is holding a reference to the old DOM element,
830 // let's allow them to OO.ui.infuse() it and do what they expect, see T105828.
831 // Do not use jQuery.data(), as using it on detached nodes leaks memory in 1.x line by design.
832 $elem[ 0 ].oouiInfused = obj.$element;
833 // now replace old DOM with this new DOM.
834 if ( top ) {
835 // An efficient constructor might be able to reuse the entire DOM tree of the original element,
836 // so only mutate the DOM if we need to.
837 if ( $elem[ 0 ] !== obj.$element[ 0 ] ) {
838 $elem.replaceWith( obj.$element );
839 }
840 top.resolve();
841 }
842 obj.$element.data( 'ooui-infused', obj );
843 obj.$element.data( 'ooui-infused-children', infusedChildren );
844 // set the 'data-ooui' attribute so we can identify infused widgets
845 obj.$element.attr( 'data-ooui', '' );
846 // restore dynamic state after the new element is inserted into DOM
847 domPromise.done( obj.restorePreInfuseState.bind( obj, state ) );
848 return obj;
849 };
850
851 /**
852 * Pick out parts of `node`'s DOM to be reused when infusing a widget.
853 *
854 * This method **must not** make any changes to the DOM, only find interesting pieces and add them
855 * to `config` (which should then be returned). Actual DOM juggling should then be done by the
856 * constructor, which will be given the enhanced config.
857 *
858 * @protected
859 * @param {HTMLElement} node
860 * @param {Object} config
861 * @return {Object}
862 */
863 OO.ui.Element.static.reusePreInfuseDOM = function ( node, config ) {
864 return config;
865 };
866
867 /**
868 * Gather the dynamic state (focus, value of form inputs, scroll position, etc.) of an HTML DOM node
869 * (and its children) that represent an Element of the same class and the given configuration,
870 * generated by the PHP implementation.
871 *
872 * This method is called just before `node` is detached from the DOM. The return value of this
873 * function will be passed to #restorePreInfuseState after the newly created widget's #$element
874 * is inserted into DOM to replace `node`.
875 *
876 * @protected
877 * @param {HTMLElement} node
878 * @param {Object} config
879 * @return {Object}
880 */
881 OO.ui.Element.static.gatherPreInfuseState = function () {
882 return {};
883 };
884
885 /**
886 * Get a jQuery function within a specific document.
887 *
888 * @static
889 * @param {jQuery|HTMLElement|HTMLDocument|Window} context Context to bind the function to
890 * @param {jQuery} [$iframe] HTML iframe element that contains the document, omit if document is
891 * not in an iframe
892 * @return {Function} Bound jQuery function
893 */
894 OO.ui.Element.static.getJQuery = function ( context, $iframe ) {
895 function wrapper( selector ) {
896 return $( selector, wrapper.context );
897 }
898
899 wrapper.context = this.getDocument( context );
900
901 if ( $iframe ) {
902 wrapper.$iframe = $iframe;
903 }
904
905 return wrapper;
906 };
907
908 /**
909 * Get the document of an element.
910 *
911 * @static
912 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Object to get the document for
913 * @return {HTMLDocument|null} Document object
914 */
915 OO.ui.Element.static.getDocument = function ( obj ) {
916 // jQuery - selections created "offscreen" won't have a context, so .context isn't reliable
917 return ( obj[ 0 ] && obj[ 0 ].ownerDocument ) ||
918 // Empty jQuery selections might have a context
919 obj.context ||
920 // HTMLElement
921 obj.ownerDocument ||
922 // Window
923 obj.document ||
924 // HTMLDocument
925 ( obj.nodeType === Node.DOCUMENT_NODE && obj ) ||
926 null;
927 };
928
929 /**
930 * Get the window of an element or document.
931 *
932 * @static
933 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the window for
934 * @return {Window} Window object
935 */
936 OO.ui.Element.static.getWindow = function ( obj ) {
937 var doc = this.getDocument( obj );
938 return doc.defaultView;
939 };
940
941 /**
942 * Get the direction of an element or document.
943 *
944 * @static
945 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the direction for
946 * @return {string} Text direction, either 'ltr' or 'rtl'
947 */
948 OO.ui.Element.static.getDir = function ( obj ) {
949 var isDoc, isWin;
950
951 if ( obj instanceof jQuery ) {
952 obj = obj[ 0 ];
953 }
954 isDoc = obj.nodeType === Node.DOCUMENT_NODE;
955 isWin = obj.document !== undefined;
956 if ( isDoc || isWin ) {
957 if ( isWin ) {
958 obj = obj.document;
959 }
960 obj = obj.body;
961 }
962 return $( obj ).css( 'direction' );
963 };
964
965 /**
966 * Get the offset between two frames.
967 *
968 * TODO: Make this function not use recursion.
969 *
970 * @static
971 * @param {Window} from Window of the child frame
972 * @param {Window} [to=window] Window of the parent frame
973 * @param {Object} [offset] Offset to start with, used internally
974 * @return {Object} Offset object, containing left and top properties
975 */
976 OO.ui.Element.static.getFrameOffset = function ( from, to, offset ) {
977 var i, len, frames, frame, rect;
978
979 if ( !to ) {
980 to = window;
981 }
982 if ( !offset ) {
983 offset = { top: 0, left: 0 };
984 }
985 if ( from.parent === from ) {
986 return offset;
987 }
988
989 // Get iframe element
990 frames = from.parent.document.getElementsByTagName( 'iframe' );
991 for ( i = 0, len = frames.length; i < len; i++ ) {
992 if ( frames[ i ].contentWindow === from ) {
993 frame = frames[ i ];
994 break;
995 }
996 }
997
998 // Recursively accumulate offset values
999 if ( frame ) {
1000 rect = frame.getBoundingClientRect();
1001 offset.left += rect.left;
1002 offset.top += rect.top;
1003 if ( from !== to ) {
1004 this.getFrameOffset( from.parent, offset );
1005 }
1006 }
1007 return offset;
1008 };
1009
1010 /**
1011 * Get the offset between two elements.
1012 *
1013 * The two elements may be in a different frame, but in that case the frame $element is in must
1014 * be contained in the frame $anchor is in.
1015 *
1016 * @static
1017 * @param {jQuery} $element Element whose position to get
1018 * @param {jQuery} $anchor Element to get $element's position relative to
1019 * @return {Object} Translated position coordinates, containing top and left properties
1020 */
1021 OO.ui.Element.static.getRelativePosition = function ( $element, $anchor ) {
1022 var iframe, iframePos,
1023 pos = $element.offset(),
1024 anchorPos = $anchor.offset(),
1025 elementDocument = this.getDocument( $element ),
1026 anchorDocument = this.getDocument( $anchor );
1027
1028 // If $element isn't in the same document as $anchor, traverse up
1029 while ( elementDocument !== anchorDocument ) {
1030 iframe = elementDocument.defaultView.frameElement;
1031 if ( !iframe ) {
1032 throw new Error( '$element frame is not contained in $anchor frame' );
1033 }
1034 iframePos = $( iframe ).offset();
1035 pos.left += iframePos.left;
1036 pos.top += iframePos.top;
1037 elementDocument = iframe.ownerDocument;
1038 }
1039 pos.left -= anchorPos.left;
1040 pos.top -= anchorPos.top;
1041 return pos;
1042 };
1043
1044 /**
1045 * Get element border sizes.
1046 *
1047 * @static
1048 * @param {HTMLElement} el Element to measure
1049 * @return {Object} Dimensions object with `top`, `left`, `bottom` and `right` properties
1050 */
1051 OO.ui.Element.static.getBorders = function ( el ) {
1052 var doc = el.ownerDocument,
1053 win = doc.defaultView,
1054 style = win.getComputedStyle( el, null ),
1055 $el = $( el ),
1056 top = parseFloat( style ? style.borderTopWidth : $el.css( 'borderTopWidth' ) ) || 0,
1057 left = parseFloat( style ? style.borderLeftWidth : $el.css( 'borderLeftWidth' ) ) || 0,
1058 bottom = parseFloat( style ? style.borderBottomWidth : $el.css( 'borderBottomWidth' ) ) || 0,
1059 right = parseFloat( style ? style.borderRightWidth : $el.css( 'borderRightWidth' ) ) || 0;
1060
1061 return {
1062 top: top,
1063 left: left,
1064 bottom: bottom,
1065 right: right
1066 };
1067 };
1068
1069 /**
1070 * Get dimensions of an element or window.
1071 *
1072 * @static
1073 * @param {HTMLElement|Window} el Element to measure
1074 * @return {Object} Dimensions object with `borders`, `scroll`, `scrollbar` and `rect` properties
1075 */
1076 OO.ui.Element.static.getDimensions = function ( el ) {
1077 var $el, $win,
1078 doc = el.ownerDocument || el.document,
1079 win = doc.defaultView;
1080
1081 if ( win === el || el === doc.documentElement ) {
1082 $win = $( win );
1083 return {
1084 borders: { top: 0, left: 0, bottom: 0, right: 0 },
1085 scroll: {
1086 top: $win.scrollTop(),
1087 left: $win.scrollLeft()
1088 },
1089 scrollbar: { right: 0, bottom: 0 },
1090 rect: {
1091 top: 0,
1092 left: 0,
1093 bottom: $win.innerHeight(),
1094 right: $win.innerWidth()
1095 }
1096 };
1097 } else {
1098 $el = $( el );
1099 return {
1100 borders: this.getBorders( el ),
1101 scroll: {
1102 top: $el.scrollTop(),
1103 left: $el.scrollLeft()
1104 },
1105 scrollbar: {
1106 right: $el.innerWidth() - el.clientWidth,
1107 bottom: $el.innerHeight() - el.clientHeight
1108 },
1109 rect: el.getBoundingClientRect()
1110 };
1111 }
1112 };
1113
1114 /**
1115 * Get the number of pixels that an element's content is scrolled to the left.
1116 *
1117 * Adapted from <https://github.com/othree/jquery.rtl-scroll-type>.
1118 * Original code copyright 2012 Wei-Ko Kao, licensed under the MIT License.
1119 *
1120 * This function smooths out browser inconsistencies (nicely described in the README at
1121 * <https://github.com/othree/jquery.rtl-scroll-type>) and produces a result consistent
1122 * with Firefox's 'scrollLeft', which seems the sanest.
1123 *
1124 * @static
1125 * @method
1126 * @param {HTMLElement|Window} el Element to measure
1127 * @return {number} Scroll position from the left.
1128 * If the element's direction is LTR, this is a positive number between `0` (initial scroll position)
1129 * and `el.scrollWidth - el.clientWidth` (furthest possible scroll position).
1130 * If the element's direction is RTL, this is a negative number between `0` (initial scroll position)
1131 * and `-el.scrollWidth + el.clientWidth` (furthest possible scroll position).
1132 */
1133 OO.ui.Element.static.getScrollLeft = ( function () {
1134 var rtlScrollType = null;
1135
1136 function test() {
1137 var $definer = $( '<div dir="rtl" style="font-size: 14px; width: 1px; height: 1px; position: absolute; top: -1000px; overflow: scroll">A</div>' ),
1138 definer = $definer[ 0 ];
1139
1140 $definer.appendTo( 'body' );
1141 if ( definer.scrollLeft > 0 ) {
1142 // Safari, Chrome
1143 rtlScrollType = 'default';
1144 } else {
1145 definer.scrollLeft = 1;
1146 if ( definer.scrollLeft === 0 ) {
1147 // Firefox, old Opera
1148 rtlScrollType = 'negative';
1149 } else {
1150 // Internet Explorer, Edge
1151 rtlScrollType = 'reverse';
1152 }
1153 }
1154 $definer.remove();
1155 }
1156
1157 return function getScrollLeft( el ) {
1158 var isRoot = el.window === el ||
1159 el === el.ownerDocument.body ||
1160 el === el.ownerDocument.documentElement,
1161 scrollLeft = isRoot ? $( window ).scrollLeft() : el.scrollLeft,
1162 // All browsers use the correct scroll type ('negative') on the root, so don't
1163 // do any fixups when looking at the root element
1164 direction = isRoot ? 'ltr' : $( el ).css( 'direction' );
1165
1166 if ( direction === 'rtl' ) {
1167 if ( rtlScrollType === null ) {
1168 test();
1169 }
1170 if ( rtlScrollType === 'reverse' ) {
1171 scrollLeft = -scrollLeft;
1172 } else if ( rtlScrollType === 'default' ) {
1173 scrollLeft = scrollLeft - el.scrollWidth + el.clientWidth;
1174 }
1175 }
1176
1177 return scrollLeft;
1178 };
1179 }() );
1180
1181 /**
1182 * Get the root scrollable element of given element's document.
1183 *
1184 * On Blink-based browsers (Chrome etc.), `document.documentElement` can't be used to get or set
1185 * the scrollTop property; instead we have to use `document.body`. Changing and testing the value
1186 * lets us use 'body' or 'documentElement' based on what is working.
1187 *
1188 * https://code.google.com/p/chromium/issues/detail?id=303131
1189 *
1190 * @static
1191 * @param {HTMLElement} el Element to find root scrollable parent for
1192 * @return {HTMLElement} Scrollable parent, `document.body` or `document.documentElement`
1193 * depending on browser
1194 */
1195 OO.ui.Element.static.getRootScrollableElement = function ( el ) {
1196 var scrollTop, body;
1197
1198 if ( OO.ui.scrollableElement === undefined ) {
1199 body = el.ownerDocument.body;
1200 scrollTop = body.scrollTop;
1201 body.scrollTop = 1;
1202
1203 // In some browsers (observed in Chrome 56 on Linux Mint 18.1),
1204 // body.scrollTop doesn't become exactly 1, but a fractional value like 0.76
1205 if ( Math.round( body.scrollTop ) === 1 ) {
1206 body.scrollTop = scrollTop;
1207 OO.ui.scrollableElement = 'body';
1208 } else {
1209 OO.ui.scrollableElement = 'documentElement';
1210 }
1211 }
1212
1213 return el.ownerDocument[ OO.ui.scrollableElement ];
1214 };
1215
1216 /**
1217 * Get closest scrollable container.
1218 *
1219 * Traverses up until either a scrollable element or the root is reached, in which case the root
1220 * scrollable element will be returned (see #getRootScrollableElement).
1221 *
1222 * @static
1223 * @param {HTMLElement} el Element to find scrollable container for
1224 * @param {string} [dimension] Dimension of scrolling to look for; `x`, `y` or omit for either
1225 * @return {HTMLElement} Closest scrollable container
1226 */
1227 OO.ui.Element.static.getClosestScrollableContainer = function ( el, dimension ) {
1228 var i, val,
1229 // Browsers do not correctly return the computed value of 'overflow' when 'overflow-x' and
1230 // 'overflow-y' have different values, so we need to check the separate properties.
1231 props = [ 'overflow-x', 'overflow-y' ],
1232 $parent = $( el ).parent();
1233
1234 if ( dimension === 'x' || dimension === 'y' ) {
1235 props = [ 'overflow-' + dimension ];
1236 }
1237
1238 // Special case for the document root (which doesn't really have any scrollable container, since
1239 // it is the ultimate scrollable container, but this is probably saner than null or exception)
1240 if ( $( el ).is( 'html, body' ) ) {
1241 return this.getRootScrollableElement( el );
1242 }
1243
1244 while ( $parent.length ) {
1245 if ( $parent[ 0 ] === this.getRootScrollableElement( el ) ) {
1246 return $parent[ 0 ];
1247 }
1248 i = props.length;
1249 while ( i-- ) {
1250 val = $parent.css( props[ i ] );
1251 // We assume that elements with 'overflow' (in any direction) set to 'hidden' will never be
1252 // scrolled in that direction, but they can actually be scrolled programatically. The user can
1253 // unintentionally perform a scroll in such case even if the application doesn't scroll
1254 // programatically, e.g. when jumping to an anchor, or when using built-in find functionality.
1255 // This could cause funny issues...
1256 if ( val === 'auto' || val === 'scroll' ) {
1257 return $parent[ 0 ];
1258 }
1259 }
1260 $parent = $parent.parent();
1261 }
1262 // The element is unattached... return something mostly sane
1263 return this.getRootScrollableElement( el );
1264 };
1265
1266 /**
1267 * Scroll element into view.
1268 *
1269 * @static
1270 * @param {HTMLElement} el Element to scroll into view
1271 * @param {Object} [config] Configuration options
1272 * @param {string} [config.duration='fast'] jQuery animation duration value
1273 * @param {string} [config.direction] Scroll in only one direction, e.g. 'x' or 'y', omit
1274 * to scroll in both directions
1275 * @return {jQuery.Promise} Promise which resolves when the scroll is complete
1276 */
1277 OO.ui.Element.static.scrollIntoView = function ( el, config ) {
1278 var position, animations, container, $container, elementDimensions, containerDimensions, $window,
1279 deferred = $.Deferred();
1280
1281 // Configuration initialization
1282 config = config || {};
1283
1284 animations = {};
1285 container = this.getClosestScrollableContainer( el, config.direction );
1286 $container = $( container );
1287 elementDimensions = this.getDimensions( el );
1288 containerDimensions = this.getDimensions( container );
1289 $window = $( this.getWindow( el ) );
1290
1291 // Compute the element's position relative to the container
1292 if ( $container.is( 'html, body' ) ) {
1293 // If the scrollable container is the root, this is easy
1294 position = {
1295 top: elementDimensions.rect.top,
1296 bottom: $window.innerHeight() - elementDimensions.rect.bottom,
1297 left: elementDimensions.rect.left,
1298 right: $window.innerWidth() - elementDimensions.rect.right
1299 };
1300 } else {
1301 // Otherwise, we have to subtract el's coordinates from container's coordinates
1302 position = {
1303 top: elementDimensions.rect.top - ( containerDimensions.rect.top + containerDimensions.borders.top ),
1304 bottom: containerDimensions.rect.bottom - containerDimensions.borders.bottom - containerDimensions.scrollbar.bottom - elementDimensions.rect.bottom,
1305 left: elementDimensions.rect.left - ( containerDimensions.rect.left + containerDimensions.borders.left ),
1306 right: containerDimensions.rect.right - containerDimensions.borders.right - containerDimensions.scrollbar.right - elementDimensions.rect.right
1307 };
1308 }
1309
1310 if ( !config.direction || config.direction === 'y' ) {
1311 if ( position.top < 0 ) {
1312 animations.scrollTop = containerDimensions.scroll.top + position.top;
1313 } else if ( position.top > 0 && position.bottom < 0 ) {
1314 animations.scrollTop = containerDimensions.scroll.top + Math.min( position.top, -position.bottom );
1315 }
1316 }
1317 if ( !config.direction || config.direction === 'x' ) {
1318 if ( position.left < 0 ) {
1319 animations.scrollLeft = containerDimensions.scroll.left + position.left;
1320 } else if ( position.left > 0 && position.right < 0 ) {
1321 animations.scrollLeft = containerDimensions.scroll.left + Math.min( position.left, -position.right );
1322 }
1323 }
1324 if ( !$.isEmptyObject( animations ) ) {
1325 $container.stop( true ).animate( animations, config.duration === undefined ? 'fast' : config.duration );
1326 $container.queue( function ( next ) {
1327 deferred.resolve();
1328 next();
1329 } );
1330 } else {
1331 deferred.resolve();
1332 }
1333 return deferred.promise();
1334 };
1335
1336 /**
1337 * Force the browser to reconsider whether it really needs to render scrollbars inside the element
1338 * and reserve space for them, because it probably doesn't.
1339 *
1340 * Workaround primarily for <https://code.google.com/p/chromium/issues/detail?id=387290>, but also
1341 * similar bugs in other browsers. "Just" forcing a reflow is not sufficient in all cases, we need
1342 * to first actually detach (or hide, but detaching is simpler) all children, *then* force a reflow,
1343 * and then reattach (or show) them back.
1344 *
1345 * @static
1346 * @param {HTMLElement} el Element to reconsider the scrollbars on
1347 */
1348 OO.ui.Element.static.reconsiderScrollbars = function ( el ) {
1349 var i, len, scrollLeft, scrollTop, nodes = [];
1350 // Save scroll position
1351 scrollLeft = el.scrollLeft;
1352 scrollTop = el.scrollTop;
1353 // Detach all children
1354 while ( el.firstChild ) {
1355 nodes.push( el.firstChild );
1356 el.removeChild( el.firstChild );
1357 }
1358 // Force reflow
1359 void el.offsetHeight;
1360 // Reattach all children
1361 for ( i = 0, len = nodes.length; i < len; i++ ) {
1362 el.appendChild( nodes[ i ] );
1363 }
1364 // Restore scroll position (no-op if scrollbars disappeared)
1365 el.scrollLeft = scrollLeft;
1366 el.scrollTop = scrollTop;
1367 };
1368
1369 /* Methods */
1370
1371 /**
1372 * Toggle visibility of an element.
1373 *
1374 * @param {boolean} [show] Make element visible, omit to toggle visibility
1375 * @fires visible
1376 * @chainable
1377 */
1378 OO.ui.Element.prototype.toggle = function ( show ) {
1379 show = show === undefined ? !this.visible : !!show;
1380
1381 if ( show !== this.isVisible() ) {
1382 this.visible = show;
1383 this.$element.toggleClass( 'oo-ui-element-hidden', !this.visible );
1384 this.emit( 'toggle', show );
1385 }
1386
1387 return this;
1388 };
1389
1390 /**
1391 * Check if element is visible.
1392 *
1393 * @return {boolean} element is visible
1394 */
1395 OO.ui.Element.prototype.isVisible = function () {
1396 return this.visible;
1397 };
1398
1399 /**
1400 * Get element data.
1401 *
1402 * @return {Mixed} Element data
1403 */
1404 OO.ui.Element.prototype.getData = function () {
1405 return this.data;
1406 };
1407
1408 /**
1409 * Set element data.
1410 *
1411 * @param {Mixed} data Element data
1412 * @chainable
1413 */
1414 OO.ui.Element.prototype.setData = function ( data ) {
1415 this.data = data;
1416 return this;
1417 };
1418
1419 /**
1420 * Set the element has an 'id' attribute.
1421 *
1422 * @param {string} id
1423 * @chainable
1424 */
1425 OO.ui.Element.prototype.setElementId = function ( id ) {
1426 this.elementId = id;
1427 this.$element.attr( 'id', id );
1428 return this;
1429 };
1430
1431 /**
1432 * Ensure that the element has an 'id' attribute, setting it to an unique value if it's missing,
1433 * and return its value.
1434 *
1435 * @return {string}
1436 */
1437 OO.ui.Element.prototype.getElementId = function () {
1438 if ( this.elementId === null ) {
1439 this.setElementId( OO.ui.generateElementId() );
1440 }
1441 return this.elementId;
1442 };
1443
1444 /**
1445 * Check if element supports one or more methods.
1446 *
1447 * @param {string|string[]} methods Method or list of methods to check
1448 * @return {boolean} All methods are supported
1449 */
1450 OO.ui.Element.prototype.supports = function ( methods ) {
1451 var i, len,
1452 support = 0;
1453
1454 methods = Array.isArray( methods ) ? methods : [ methods ];
1455 for ( i = 0, len = methods.length; i < len; i++ ) {
1456 if ( $.isFunction( this[ methods[ i ] ] ) ) {
1457 support++;
1458 }
1459 }
1460
1461 return methods.length === support;
1462 };
1463
1464 /**
1465 * Update the theme-provided classes.
1466 *
1467 * @localdoc This is called in element mixins and widget classes any time state changes.
1468 * Updating is debounced, minimizing overhead of changing multiple attributes and
1469 * guaranteeing that theme updates do not occur within an element's constructor
1470 */
1471 OO.ui.Element.prototype.updateThemeClasses = function () {
1472 OO.ui.theme.queueUpdateElementClasses( this );
1473 };
1474
1475 /**
1476 * Get the HTML tag name.
1477 *
1478 * Override this method to base the result on instance information.
1479 *
1480 * @return {string} HTML tag name
1481 */
1482 OO.ui.Element.prototype.getTagName = function () {
1483 return this.constructor.static.tagName;
1484 };
1485
1486 /**
1487 * Check if the element is attached to the DOM
1488 *
1489 * @return {boolean} The element is attached to the DOM
1490 */
1491 OO.ui.Element.prototype.isElementAttached = function () {
1492 return $.contains( this.getElementDocument(), this.$element[ 0 ] );
1493 };
1494
1495 /**
1496 * Get the DOM document.
1497 *
1498 * @return {HTMLDocument} Document object
1499 */
1500 OO.ui.Element.prototype.getElementDocument = function () {
1501 // Don't cache this in other ways either because subclasses could can change this.$element
1502 return OO.ui.Element.static.getDocument( this.$element );
1503 };
1504
1505 /**
1506 * Get the DOM window.
1507 *
1508 * @return {Window} Window object
1509 */
1510 OO.ui.Element.prototype.getElementWindow = function () {
1511 return OO.ui.Element.static.getWindow( this.$element );
1512 };
1513
1514 /**
1515 * Get closest scrollable container.
1516 *
1517 * @return {HTMLElement} Closest scrollable container
1518 */
1519 OO.ui.Element.prototype.getClosestScrollableElementContainer = function () {
1520 return OO.ui.Element.static.getClosestScrollableContainer( this.$element[ 0 ] );
1521 };
1522
1523 /**
1524 * Get group element is in.
1525 *
1526 * @return {OO.ui.mixin.GroupElement|null} Group element, null if none
1527 */
1528 OO.ui.Element.prototype.getElementGroup = function () {
1529 return this.elementGroup;
1530 };
1531
1532 /**
1533 * Set group element is in.
1534 *
1535 * @param {OO.ui.mixin.GroupElement|null} group Group element, null if none
1536 * @chainable
1537 */
1538 OO.ui.Element.prototype.setElementGroup = function ( group ) {
1539 this.elementGroup = group;
1540 return this;
1541 };
1542
1543 /**
1544 * Scroll element into view.
1545 *
1546 * @param {Object} [config] Configuration options
1547 * @return {jQuery.Promise} Promise which resolves when the scroll is complete
1548 */
1549 OO.ui.Element.prototype.scrollElementIntoView = function ( config ) {
1550 if (
1551 !this.isElementAttached() ||
1552 !this.isVisible() ||
1553 ( this.getElementGroup() && !this.getElementGroup().isVisible() )
1554 ) {
1555 return $.Deferred().resolve();
1556 }
1557 return OO.ui.Element.static.scrollIntoView( this.$element[ 0 ], config );
1558 };
1559
1560 /**
1561 * Restore the pre-infusion dynamic state for this widget.
1562 *
1563 * This method is called after #$element has been inserted into DOM. The parameter is the return
1564 * value of #gatherPreInfuseState.
1565 *
1566 * @protected
1567 * @param {Object} state
1568 */
1569 OO.ui.Element.prototype.restorePreInfuseState = function () {
1570 };
1571
1572 /**
1573 * Wraps an HTML snippet for use with configuration values which default
1574 * to strings. This bypasses the default html-escaping done to string
1575 * values.
1576 *
1577 * @class
1578 *
1579 * @constructor
1580 * @param {string} [content] HTML content
1581 */
1582 OO.ui.HtmlSnippet = function OoUiHtmlSnippet( content ) {
1583 // Properties
1584 this.content = content;
1585 };
1586
1587 /* Setup */
1588
1589 OO.initClass( OO.ui.HtmlSnippet );
1590
1591 /* Methods */
1592
1593 /**
1594 * Render into HTML.
1595 *
1596 * @return {string} Unchanged HTML snippet.
1597 */
1598 OO.ui.HtmlSnippet.prototype.toString = function () {
1599 return this.content;
1600 };
1601
1602 /**
1603 * Layouts are containers for elements and are used to arrange other widgets of arbitrary type in a way
1604 * that is centrally controlled and can be updated dynamically. Layouts can be, and usually are, combined.
1605 * See {@link OO.ui.FieldsetLayout FieldsetLayout}, {@link OO.ui.FieldLayout FieldLayout}, {@link OO.ui.FormLayout FormLayout},
1606 * {@link OO.ui.PanelLayout PanelLayout}, {@link OO.ui.StackLayout StackLayout}, {@link OO.ui.PageLayout PageLayout},
1607 * {@link OO.ui.HorizontalLayout HorizontalLayout}, and {@link OO.ui.BookletLayout BookletLayout} for more information and examples.
1608 *
1609 * @abstract
1610 * @class
1611 * @extends OO.ui.Element
1612 * @mixins OO.EventEmitter
1613 *
1614 * @constructor
1615 * @param {Object} [config] Configuration options
1616 */
1617 OO.ui.Layout = function OoUiLayout( config ) {
1618 // Configuration initialization
1619 config = config || {};
1620
1621 // Parent constructor
1622 OO.ui.Layout.parent.call( this, config );
1623
1624 // Mixin constructors
1625 OO.EventEmitter.call( this );
1626
1627 // Initialization
1628 this.$element.addClass( 'oo-ui-layout' );
1629 };
1630
1631 /* Setup */
1632
1633 OO.inheritClass( OO.ui.Layout, OO.ui.Element );
1634 OO.mixinClass( OO.ui.Layout, OO.EventEmitter );
1635
1636 /**
1637 * Widgets are compositions of one or more OOUI elements that users can both view
1638 * and interact with. All widgets can be configured and modified via a standard API,
1639 * and their state can change dynamically according to a model.
1640 *
1641 * @abstract
1642 * @class
1643 * @extends OO.ui.Element
1644 * @mixins OO.EventEmitter
1645 *
1646 * @constructor
1647 * @param {Object} [config] Configuration options
1648 * @cfg {boolean} [disabled=false] Disable the widget. Disabled widgets cannot be used and their
1649 * appearance reflects this state.
1650 */
1651 OO.ui.Widget = function OoUiWidget( config ) {
1652 // Initialize config
1653 config = $.extend( { disabled: false }, config );
1654
1655 // Parent constructor
1656 OO.ui.Widget.parent.call( this, config );
1657
1658 // Mixin constructors
1659 OO.EventEmitter.call( this );
1660
1661 // Properties
1662 this.disabled = null;
1663 this.wasDisabled = null;
1664
1665 // Initialization
1666 this.$element.addClass( 'oo-ui-widget' );
1667 this.setDisabled( !!config.disabled );
1668 };
1669
1670 /* Setup */
1671
1672 OO.inheritClass( OO.ui.Widget, OO.ui.Element );
1673 OO.mixinClass( OO.ui.Widget, OO.EventEmitter );
1674
1675 /* Events */
1676
1677 /**
1678 * @event disable
1679 *
1680 * A 'disable' event is emitted when the disabled state of the widget changes
1681 * (i.e. on disable **and** enable).
1682 *
1683 * @param {boolean} disabled Widget is disabled
1684 */
1685
1686 /**
1687 * @event toggle
1688 *
1689 * A 'toggle' event is emitted when the visibility of the widget changes.
1690 *
1691 * @param {boolean} visible Widget is visible
1692 */
1693
1694 /* Methods */
1695
1696 /**
1697 * Check if the widget is disabled.
1698 *
1699 * @return {boolean} Widget is disabled
1700 */
1701 OO.ui.Widget.prototype.isDisabled = function () {
1702 return this.disabled;
1703 };
1704
1705 /**
1706 * Set the 'disabled' state of the widget.
1707 *
1708 * When a widget is disabled, it cannot be used and its appearance is updated to reflect this state.
1709 *
1710 * @param {boolean} disabled Disable widget
1711 * @chainable
1712 */
1713 OO.ui.Widget.prototype.setDisabled = function ( disabled ) {
1714 var isDisabled;
1715
1716 this.disabled = !!disabled;
1717 isDisabled = this.isDisabled();
1718 if ( isDisabled !== this.wasDisabled ) {
1719 this.$element.toggleClass( 'oo-ui-widget-disabled', isDisabled );
1720 this.$element.toggleClass( 'oo-ui-widget-enabled', !isDisabled );
1721 this.$element.attr( 'aria-disabled', isDisabled.toString() );
1722 this.emit( 'disable', isDisabled );
1723 this.updateThemeClasses();
1724 }
1725 this.wasDisabled = isDisabled;
1726
1727 return this;
1728 };
1729
1730 /**
1731 * Update the disabled state, in case of changes in parent widget.
1732 *
1733 * @chainable
1734 */
1735 OO.ui.Widget.prototype.updateDisabled = function () {
1736 this.setDisabled( this.disabled );
1737 return this;
1738 };
1739
1740 /**
1741 * Get an ID of a labelable node which is part of this widget, if any, to be used for `<label for>`
1742 * value.
1743 *
1744 * If this function returns null, the widget should have a meaningful #simulateLabelClick method
1745 * instead.
1746 *
1747 * @return {string|null} The ID of the labelable element
1748 */
1749 OO.ui.Widget.prototype.getInputId = function () {
1750 return null;
1751 };
1752
1753 /**
1754 * Simulate the behavior of clicking on a label (a HTML `<label>` element) bound to this input.
1755 * HTML only allows `<label>` to act on specific "labelable" elements; complex widgets might need to
1756 * override this method to provide intuitive, accessible behavior.
1757 *
1758 * By default, this does nothing. OO.ui.mixin.TabIndexedElement overrides it for focusable widgets.
1759 * Individual widgets may override it too.
1760 *
1761 * This method is called by OO.ui.LabelWidget and OO.ui.FieldLayout. It should not be called
1762 * directly.
1763 */
1764 OO.ui.Widget.prototype.simulateLabelClick = function () {
1765 };
1766
1767 /**
1768 * Theme logic.
1769 *
1770 * @abstract
1771 * @class
1772 *
1773 * @constructor
1774 */
1775 OO.ui.Theme = function OoUiTheme() {
1776 this.elementClassesQueue = [];
1777 this.debouncedUpdateQueuedElementClasses = OO.ui.debounce( this.updateQueuedElementClasses );
1778 };
1779
1780 /* Setup */
1781
1782 OO.initClass( OO.ui.Theme );
1783
1784 /* Methods */
1785
1786 /**
1787 * Get a list of classes to be applied to a widget.
1788 *
1789 * The 'on' and 'off' lists combined MUST contain keys for all classes the theme adds or removes,
1790 * otherwise state transitions will not work properly.
1791 *
1792 * @param {OO.ui.Element} element Element for which to get classes
1793 * @return {Object.<string,string[]>} Categorized class names with `on` and `off` lists
1794 */
1795 OO.ui.Theme.prototype.getElementClasses = function () {
1796 return { on: [], off: [] };
1797 };
1798
1799 /**
1800 * Update CSS classes provided by the theme.
1801 *
1802 * For elements with theme logic hooks, this should be called any time there's a state change.
1803 *
1804 * @param {OO.ui.Element} element Element for which to update classes
1805 */
1806 OO.ui.Theme.prototype.updateElementClasses = function ( element ) {
1807 var $elements = $( [] ),
1808 classes = this.getElementClasses( element );
1809
1810 if ( element.$icon ) {
1811 $elements = $elements.add( element.$icon );
1812 }
1813 if ( element.$indicator ) {
1814 $elements = $elements.add( element.$indicator );
1815 }
1816
1817 $elements
1818 .removeClass( classes.off.join( ' ' ) )
1819 .addClass( classes.on.join( ' ' ) );
1820 };
1821
1822 /**
1823 * @private
1824 */
1825 OO.ui.Theme.prototype.updateQueuedElementClasses = function () {
1826 var i;
1827 for ( i = 0; i < this.elementClassesQueue.length; i++ ) {
1828 this.updateElementClasses( this.elementClassesQueue[ i ] );
1829 }
1830 // Clear the queue
1831 this.elementClassesQueue = [];
1832 };
1833
1834 /**
1835 * Queue #updateElementClasses to be called for this element.
1836 *
1837 * @localdoc QUnit tests override this method to directly call #queueUpdateElementClasses,
1838 * to make them synchronous.
1839 *
1840 * @param {OO.ui.Element} element Element for which to update classes
1841 */
1842 OO.ui.Theme.prototype.queueUpdateElementClasses = function ( element ) {
1843 // Keep items in the queue unique. Use lastIndexOf to start checking from the end because that's
1844 // the most common case (this method is often called repeatedly for the same element).
1845 if ( this.elementClassesQueue.lastIndexOf( element ) !== -1 ) {
1846 return;
1847 }
1848 this.elementClassesQueue.push( element );
1849 this.debouncedUpdateQueuedElementClasses();
1850 };
1851
1852 /**
1853 * Get the transition duration in milliseconds for dialogs opening/closing
1854 *
1855 * The dialog should be fully rendered this many milliseconds after the
1856 * ready process has executed.
1857 *
1858 * @return {number} Transition duration in milliseconds
1859 */
1860 OO.ui.Theme.prototype.getDialogTransitionDuration = function () {
1861 return 0;
1862 };
1863
1864 /**
1865 * The TabIndexedElement class is an attribute mixin used to add additional functionality to an
1866 * element created by another class. The mixin provides a ‘tabIndex’ property, which specifies the
1867 * order in which users will navigate through the focusable elements via the "tab" key.
1868 *
1869 * @example
1870 * // TabIndexedElement is mixed into the ButtonWidget class
1871 * // to provide a tabIndex property.
1872 * var button1 = new OO.ui.ButtonWidget( {
1873 * label: 'fourth',
1874 * tabIndex: 4
1875 * } );
1876 * var button2 = new OO.ui.ButtonWidget( {
1877 * label: 'second',
1878 * tabIndex: 2
1879 * } );
1880 * var button3 = new OO.ui.ButtonWidget( {
1881 * label: 'third',
1882 * tabIndex: 3
1883 * } );
1884 * var button4 = new OO.ui.ButtonWidget( {
1885 * label: 'first',
1886 * tabIndex: 1
1887 * } );
1888 * $( 'body' ).append( button1.$element, button2.$element, button3.$element, button4.$element );
1889 *
1890 * @abstract
1891 * @class
1892 *
1893 * @constructor
1894 * @param {Object} [config] Configuration options
1895 * @cfg {jQuery} [$tabIndexed] The element that should use the tabindex functionality. By default,
1896 * the functionality is applied to the element created by the class ($element). If a different element is specified, the tabindex
1897 * functionality will be applied to it instead.
1898 * @cfg {string|number|null} [tabIndex=0] Number that specifies the element’s position in the tab-navigation
1899 * order (e.g., 1 for the first focusable element). Use 0 to use the default navigation order; use -1
1900 * to remove the element from the tab-navigation flow.
1901 */
1902 OO.ui.mixin.TabIndexedElement = function OoUiMixinTabIndexedElement( config ) {
1903 // Configuration initialization
1904 config = $.extend( { tabIndex: 0 }, config );
1905
1906 // Properties
1907 this.$tabIndexed = null;
1908 this.tabIndex = null;
1909
1910 // Events
1911 this.connect( this, { disable: 'onTabIndexedElementDisable' } );
1912
1913 // Initialization
1914 this.setTabIndex( config.tabIndex );
1915 this.setTabIndexedElement( config.$tabIndexed || this.$element );
1916 };
1917
1918 /* Setup */
1919
1920 OO.initClass( OO.ui.mixin.TabIndexedElement );
1921
1922 /* Methods */
1923
1924 /**
1925 * Set the element that should use the tabindex functionality.
1926 *
1927 * This method is used to retarget a tabindex mixin so that its functionality applies
1928 * to the specified element. If an element is currently using the functionality, the mixin’s
1929 * effect on that element is removed before the new element is set up.
1930 *
1931 * @param {jQuery} $tabIndexed Element that should use the tabindex functionality
1932 * @chainable
1933 */
1934 OO.ui.mixin.TabIndexedElement.prototype.setTabIndexedElement = function ( $tabIndexed ) {
1935 var tabIndex = this.tabIndex;
1936 // Remove attributes from old $tabIndexed
1937 this.setTabIndex( null );
1938 // Force update of new $tabIndexed
1939 this.$tabIndexed = $tabIndexed;
1940 this.tabIndex = tabIndex;
1941 return this.updateTabIndex();
1942 };
1943
1944 /**
1945 * Set the value of the tabindex.
1946 *
1947 * @param {string|number|null} tabIndex Tabindex value, or `null` for no tabindex
1948 * @chainable
1949 */
1950 OO.ui.mixin.TabIndexedElement.prototype.setTabIndex = function ( tabIndex ) {
1951 tabIndex = /^-?\d+$/.test( tabIndex ) ? Number( tabIndex ) : null;
1952
1953 if ( this.tabIndex !== tabIndex ) {
1954 this.tabIndex = tabIndex;
1955 this.updateTabIndex();
1956 }
1957
1958 return this;
1959 };
1960
1961 /**
1962 * Update the `tabindex` attribute, in case of changes to tab index or
1963 * disabled state.
1964 *
1965 * @private
1966 * @chainable
1967 */
1968 OO.ui.mixin.TabIndexedElement.prototype.updateTabIndex = function () {
1969 if ( this.$tabIndexed ) {
1970 if ( this.tabIndex !== null ) {
1971 // Do not index over disabled elements
1972 this.$tabIndexed.attr( {
1973 tabindex: this.isDisabled() ? -1 : this.tabIndex,
1974 // Support: ChromeVox and NVDA
1975 // These do not seem to inherit aria-disabled from parent elements
1976 'aria-disabled': this.isDisabled().toString()
1977 } );
1978 } else {
1979 this.$tabIndexed.removeAttr( 'tabindex aria-disabled' );
1980 }
1981 }
1982 return this;
1983 };
1984
1985 /**
1986 * Handle disable events.
1987 *
1988 * @private
1989 * @param {boolean} disabled Element is disabled
1990 */
1991 OO.ui.mixin.TabIndexedElement.prototype.onTabIndexedElementDisable = function () {
1992 this.updateTabIndex();
1993 };
1994
1995 /**
1996 * Get the value of the tabindex.
1997 *
1998 * @return {number|null} Tabindex value
1999 */
2000 OO.ui.mixin.TabIndexedElement.prototype.getTabIndex = function () {
2001 return this.tabIndex;
2002 };
2003
2004 /**
2005 * Get an ID of a focusable element of this widget, if any, to be used for `<label for>` value.
2006 *
2007 * If the element already has an ID then that is returned, otherwise unique ID is
2008 * generated, set on the element, and returned.
2009 *
2010 * @return {string|null} The ID of the focusable element
2011 */
2012 OO.ui.mixin.TabIndexedElement.prototype.getInputId = function () {
2013 var id;
2014
2015 if ( !this.$tabIndexed ) {
2016 return null;
2017 }
2018 if ( !this.isLabelableNode( this.$tabIndexed ) ) {
2019 return null;
2020 }
2021
2022 id = this.$tabIndexed.attr( 'id' );
2023 if ( id === undefined ) {
2024 id = OO.ui.generateElementId();
2025 this.$tabIndexed.attr( 'id', id );
2026 }
2027
2028 return id;
2029 };
2030
2031 /**
2032 * Whether the node is 'labelable' according to the HTML spec
2033 * (i.e., whether it can be interacted with through a `<label for="…">`).
2034 * See: <https://html.spec.whatwg.org/multipage/forms.html#category-label>.
2035 *
2036 * @private
2037 * @param {jQuery} $node
2038 * @return {boolean}
2039 */
2040 OO.ui.mixin.TabIndexedElement.prototype.isLabelableNode = function ( $node ) {
2041 var
2042 labelableTags = [ 'button', 'meter', 'output', 'progress', 'select', 'textarea' ],
2043 tagName = $node.prop( 'tagName' ).toLowerCase();
2044
2045 if ( tagName === 'input' && $node.attr( 'type' ) !== 'hidden' ) {
2046 return true;
2047 }
2048 if ( labelableTags.indexOf( tagName ) !== -1 ) {
2049 return true;
2050 }
2051 return false;
2052 };
2053
2054 /**
2055 * Focus this element.
2056 *
2057 * @chainable
2058 */
2059 OO.ui.mixin.TabIndexedElement.prototype.focus = function () {
2060 if ( !this.isDisabled() ) {
2061 this.$tabIndexed.focus();
2062 }
2063 return this;
2064 };
2065
2066 /**
2067 * Blur this element.
2068 *
2069 * @chainable
2070 */
2071 OO.ui.mixin.TabIndexedElement.prototype.blur = function () {
2072 this.$tabIndexed.blur();
2073 return this;
2074 };
2075
2076 /**
2077 * @inheritdoc OO.ui.Widget
2078 */
2079 OO.ui.mixin.TabIndexedElement.prototype.simulateLabelClick = function () {
2080 this.focus();
2081 };
2082
2083 /**
2084 * ButtonElement is often mixed into other classes to generate a button, which is a clickable
2085 * interface element that can be configured with access keys for accessibility.
2086 * See the [OOUI documentation on MediaWiki] [1] for examples.
2087 *
2088 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Buttons_and_Switches#Buttons
2089 *
2090 * @abstract
2091 * @class
2092 *
2093 * @constructor
2094 * @param {Object} [config] Configuration options
2095 * @cfg {jQuery} [$button] The button element created by the class.
2096 * If this configuration is omitted, the button element will use a generated `<a>`.
2097 * @cfg {boolean} [framed=true] Render the button with a frame
2098 */
2099 OO.ui.mixin.ButtonElement = function OoUiMixinButtonElement( config ) {
2100 // Configuration initialization
2101 config = config || {};
2102
2103 // Properties
2104 this.$button = null;
2105 this.framed = null;
2106 this.active = config.active !== undefined && config.active;
2107 this.onMouseUpHandler = this.onMouseUp.bind( this );
2108 this.onMouseDownHandler = this.onMouseDown.bind( this );
2109 this.onKeyDownHandler = this.onKeyDown.bind( this );
2110 this.onKeyUpHandler = this.onKeyUp.bind( this );
2111 this.onClickHandler = this.onClick.bind( this );
2112 this.onKeyPressHandler = this.onKeyPress.bind( this );
2113
2114 // Initialization
2115 this.$element.addClass( 'oo-ui-buttonElement' );
2116 this.toggleFramed( config.framed === undefined || config.framed );
2117 this.setButtonElement( config.$button || $( '<a>' ) );
2118 };
2119
2120 /* Setup */
2121
2122 OO.initClass( OO.ui.mixin.ButtonElement );
2123
2124 /* Static Properties */
2125
2126 /**
2127 * Cancel mouse down events.
2128 *
2129 * This property is usually set to `true` to prevent the focus from changing when the button is clicked.
2130 * Classes such as {@link OO.ui.mixin.DraggableElement DraggableElement} and {@link OO.ui.ButtonOptionWidget ButtonOptionWidget}
2131 * use a value of `false` so that dragging behavior is possible and mousedown events can be handled by a
2132 * parent widget.
2133 *
2134 * @static
2135 * @inheritable
2136 * @property {boolean}
2137 */
2138 OO.ui.mixin.ButtonElement.static.cancelButtonMouseDownEvents = true;
2139
2140 /* Events */
2141
2142 /**
2143 * A 'click' event is emitted when the button element is clicked.
2144 *
2145 * @event click
2146 */
2147
2148 /* Methods */
2149
2150 /**
2151 * Set the button element.
2152 *
2153 * This method is used to retarget a button mixin so that its functionality applies to
2154 * the specified button element instead of the one created by the class. If a button element
2155 * is already set, the method will remove the mixin’s effect on that element.
2156 *
2157 * @param {jQuery} $button Element to use as button
2158 */
2159 OO.ui.mixin.ButtonElement.prototype.setButtonElement = function ( $button ) {
2160 if ( this.$button ) {
2161 this.$button
2162 .removeClass( 'oo-ui-buttonElement-button' )
2163 .removeAttr( 'role accesskey' )
2164 .off( {
2165 mousedown: this.onMouseDownHandler,
2166 keydown: this.onKeyDownHandler,
2167 click: this.onClickHandler,
2168 keypress: this.onKeyPressHandler
2169 } );
2170 }
2171
2172 this.$button = $button
2173 .addClass( 'oo-ui-buttonElement-button' )
2174 .on( {
2175 mousedown: this.onMouseDownHandler,
2176 keydown: this.onKeyDownHandler,
2177 click: this.onClickHandler,
2178 keypress: this.onKeyPressHandler
2179 } );
2180
2181 // Add `role="button"` on `<a>` elements, where it's needed
2182 // `toUppercase()` is added for XHTML documents
2183 if ( this.$button.prop( 'tagName' ).toUpperCase() === 'A' ) {
2184 this.$button.attr( 'role', 'button' );
2185 }
2186 };
2187
2188 /**
2189 * Handles mouse down events.
2190 *
2191 * @protected
2192 * @param {jQuery.Event} e Mouse down event
2193 */
2194 OO.ui.mixin.ButtonElement.prototype.onMouseDown = function ( e ) {
2195 if ( this.isDisabled() || e.which !== OO.ui.MouseButtons.LEFT ) {
2196 return;
2197 }
2198 this.$element.addClass( 'oo-ui-buttonElement-pressed' );
2199 // Run the mouseup handler no matter where the mouse is when the button is let go, so we can
2200 // reliably remove the pressed class
2201 this.getElementDocument().addEventListener( 'mouseup', this.onMouseUpHandler, true );
2202 // Prevent change of focus unless specifically configured otherwise
2203 if ( this.constructor.static.cancelButtonMouseDownEvents ) {
2204 return false;
2205 }
2206 };
2207
2208 /**
2209 * Handles mouse up events.
2210 *
2211 * @protected
2212 * @param {MouseEvent} e Mouse up event
2213 */
2214 OO.ui.mixin.ButtonElement.prototype.onMouseUp = function ( e ) {
2215 if ( this.isDisabled() || e.which !== OO.ui.MouseButtons.LEFT ) {
2216 return;
2217 }
2218 this.$element.removeClass( 'oo-ui-buttonElement-pressed' );
2219 // Stop listening for mouseup, since we only needed this once
2220 this.getElementDocument().removeEventListener( 'mouseup', this.onMouseUpHandler, true );
2221 };
2222
2223 /**
2224 * Handles mouse click events.
2225 *
2226 * @protected
2227 * @param {jQuery.Event} e Mouse click event
2228 * @fires click
2229 */
2230 OO.ui.mixin.ButtonElement.prototype.onClick = function ( e ) {
2231 if ( !this.isDisabled() && e.which === OO.ui.MouseButtons.LEFT ) {
2232 if ( this.emit( 'click' ) ) {
2233 return false;
2234 }
2235 }
2236 };
2237
2238 /**
2239 * Handles key down events.
2240 *
2241 * @protected
2242 * @param {jQuery.Event} e Key down event
2243 */
2244 OO.ui.mixin.ButtonElement.prototype.onKeyDown = function ( e ) {
2245 if ( this.isDisabled() || ( e.which !== OO.ui.Keys.SPACE && e.which !== OO.ui.Keys.ENTER ) ) {
2246 return;
2247 }
2248 this.$element.addClass( 'oo-ui-buttonElement-pressed' );
2249 // Run the keyup handler no matter where the key is when the button is let go, so we can
2250 // reliably remove the pressed class
2251 this.getElementDocument().addEventListener( 'keyup', this.onKeyUpHandler, true );
2252 };
2253
2254 /**
2255 * Handles key up events.
2256 *
2257 * @protected
2258 * @param {KeyboardEvent} e Key up event
2259 */
2260 OO.ui.mixin.ButtonElement.prototype.onKeyUp = function ( e ) {
2261 if ( this.isDisabled() || ( e.which !== OO.ui.Keys.SPACE && e.which !== OO.ui.Keys.ENTER ) ) {
2262 return;
2263 }
2264 this.$element.removeClass( 'oo-ui-buttonElement-pressed' );
2265 // Stop listening for keyup, since we only needed this once
2266 this.getElementDocument().removeEventListener( 'keyup', this.onKeyUpHandler, true );
2267 };
2268
2269 /**
2270 * Handles key press events.
2271 *
2272 * @protected
2273 * @param {jQuery.Event} e Key press event
2274 * @fires click
2275 */
2276 OO.ui.mixin.ButtonElement.prototype.onKeyPress = function ( e ) {
2277 if ( !this.isDisabled() && ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER ) ) {
2278 if ( this.emit( 'click' ) ) {
2279 return false;
2280 }
2281 }
2282 };
2283
2284 /**
2285 * Check if button has a frame.
2286 *
2287 * @return {boolean} Button is framed
2288 */
2289 OO.ui.mixin.ButtonElement.prototype.isFramed = function () {
2290 return this.framed;
2291 };
2292
2293 /**
2294 * Render the button with or without a frame. Omit the `framed` parameter to toggle the button frame on and off.
2295 *
2296 * @param {boolean} [framed] Make button framed, omit to toggle
2297 * @chainable
2298 */
2299 OO.ui.mixin.ButtonElement.prototype.toggleFramed = function ( framed ) {
2300 framed = framed === undefined ? !this.framed : !!framed;
2301 if ( framed !== this.framed ) {
2302 this.framed = framed;
2303 this.$element
2304 .toggleClass( 'oo-ui-buttonElement-frameless', !framed )
2305 .toggleClass( 'oo-ui-buttonElement-framed', framed );
2306 this.updateThemeClasses();
2307 }
2308
2309 return this;
2310 };
2311
2312 /**
2313 * Set the button's active state.
2314 *
2315 * The active state can be set on:
2316 *
2317 * - {@link OO.ui.ButtonOptionWidget ButtonOptionWidget} when it is selected
2318 * - {@link OO.ui.ToggleButtonWidget ToggleButtonWidget} when it is toggle on
2319 * - {@link OO.ui.ButtonWidget ButtonWidget} when clicking the button would only refresh the page
2320 *
2321 * @protected
2322 * @param {boolean} value Make button active
2323 * @chainable
2324 */
2325 OO.ui.mixin.ButtonElement.prototype.setActive = function ( value ) {
2326 this.active = !!value;
2327 this.$element.toggleClass( 'oo-ui-buttonElement-active', this.active );
2328 this.updateThemeClasses();
2329 return this;
2330 };
2331
2332 /**
2333 * Check if the button is active
2334 *
2335 * @protected
2336 * @return {boolean} The button is active
2337 */
2338 OO.ui.mixin.ButtonElement.prototype.isActive = function () {
2339 return this.active;
2340 };
2341
2342 /**
2343 * Any OOUI widget that contains other widgets (such as {@link OO.ui.ButtonWidget buttons} or
2344 * {@link OO.ui.OptionWidget options}) mixes in GroupElement. Adding, removing, and clearing
2345 * items from the group is done through the interface the class provides.
2346 * For more information, please see the [OOUI documentation on MediaWiki] [1].
2347 *
2348 * [1]: https://www.mediawiki.org/wiki/OOUI/Elements/Groups
2349 *
2350 * @abstract
2351 * @mixins OO.EmitterList
2352 * @class
2353 *
2354 * @constructor
2355 * @param {Object} [config] Configuration options
2356 * @cfg {jQuery} [$group] The container element created by the class. If this configuration
2357 * is omitted, the group element will use a generated `<div>`.
2358 */
2359 OO.ui.mixin.GroupElement = function OoUiMixinGroupElement( config ) {
2360 // Configuration initialization
2361 config = config || {};
2362
2363 // Mixin constructors
2364 OO.EmitterList.call( this, config );
2365
2366 // Properties
2367 this.$group = null;
2368
2369 // Initialization
2370 this.setGroupElement( config.$group || $( '<div>' ) );
2371 };
2372
2373 /* Setup */
2374
2375 OO.mixinClass( OO.ui.mixin.GroupElement, OO.EmitterList );
2376
2377 /* Events */
2378
2379 /**
2380 * @event change
2381 *
2382 * A change event is emitted when the set of selected items changes.
2383 *
2384 * @param {OO.ui.Element[]} items Items currently in the group
2385 */
2386
2387 /* Methods */
2388
2389 /**
2390 * Set the group element.
2391 *
2392 * If an element is already set, items will be moved to the new element.
2393 *
2394 * @param {jQuery} $group Element to use as group
2395 */
2396 OO.ui.mixin.GroupElement.prototype.setGroupElement = function ( $group ) {
2397 var i, len;
2398
2399 this.$group = $group;
2400 for ( i = 0, len = this.items.length; i < len; i++ ) {
2401 this.$group.append( this.items[ i ].$element );
2402 }
2403 };
2404
2405 /**
2406 * Find an item by its data.
2407 *
2408 * Only the first item with matching data will be returned. To return all matching items,
2409 * use the #findItemsFromData method.
2410 *
2411 * @param {Object} data Item data to search for
2412 * @return {OO.ui.Element|null} Item with equivalent data, `null` if none exists
2413 */
2414 OO.ui.mixin.GroupElement.prototype.findItemFromData = function ( data ) {
2415 var i, len, item,
2416 hash = OO.getHash( data );
2417
2418 for ( i = 0, len = this.items.length; i < len; i++ ) {
2419 item = this.items[ i ];
2420 if ( hash === OO.getHash( item.getData() ) ) {
2421 return item;
2422 }
2423 }
2424
2425 return null;
2426 };
2427
2428 /**
2429 * Find items by their data.
2430 *
2431 * All items with matching data will be returned. To return only the first match, use the #findItemFromData method instead.
2432 *
2433 * @param {Object} data Item data to search for
2434 * @return {OO.ui.Element[]} Items with equivalent data
2435 */
2436 OO.ui.mixin.GroupElement.prototype.findItemsFromData = function ( data ) {
2437 var i, len, item,
2438 hash = OO.getHash( data ),
2439 items = [];
2440
2441 for ( i = 0, len = this.items.length; i < len; i++ ) {
2442 item = this.items[ i ];
2443 if ( hash === OO.getHash( item.getData() ) ) {
2444 items.push( item );
2445 }
2446 }
2447
2448 return items;
2449 };
2450
2451 /**
2452 * Add items to the group.
2453 *
2454 * Items will be added to the end of the group array unless the optional `index` parameter specifies
2455 * a different insertion point. Adding an existing item will move it to the end of the array or the point specified by the `index`.
2456 *
2457 * @param {OO.ui.Element[]} items An array of items to add to the group
2458 * @param {number} [index] Index of the insertion point
2459 * @chainable
2460 */
2461 OO.ui.mixin.GroupElement.prototype.addItems = function ( items, index ) {
2462 // Mixin method
2463 OO.EmitterList.prototype.addItems.call( this, items, index );
2464
2465 this.emit( 'change', this.getItems() );
2466 return this;
2467 };
2468
2469 /**
2470 * @inheritdoc
2471 */
2472 OO.ui.mixin.GroupElement.prototype.moveItem = function ( items, newIndex ) {
2473 // insertItemElements expects this.items to not have been modified yet, so call before the mixin
2474 this.insertItemElements( items, newIndex );
2475
2476 // Mixin method
2477 newIndex = OO.EmitterList.prototype.moveItem.call( this, items, newIndex );
2478
2479 return newIndex;
2480 };
2481
2482 /**
2483 * @inheritdoc
2484 */
2485 OO.ui.mixin.GroupElement.prototype.insertItem = function ( item, index ) {
2486 item.setElementGroup( this );
2487 this.insertItemElements( item, index );
2488
2489 // Mixin method
2490 index = OO.EmitterList.prototype.insertItem.call( this, item, index );
2491
2492 return index;
2493 };
2494
2495 /**
2496 * Insert elements into the group
2497 *
2498 * @private
2499 * @param {OO.ui.Element} itemWidget Item to insert
2500 * @param {number} index Insertion index
2501 */
2502 OO.ui.mixin.GroupElement.prototype.insertItemElements = function ( itemWidget, index ) {
2503 if ( index === undefined || index < 0 || index >= this.items.length ) {
2504 this.$group.append( itemWidget.$element );
2505 } else if ( index === 0 ) {
2506 this.$group.prepend( itemWidget.$element );
2507 } else {
2508 this.items[ index ].$element.before( itemWidget.$element );
2509 }
2510 };
2511
2512 /**
2513 * Remove the specified items from a group.
2514 *
2515 * Removed items are detached (not removed) from the DOM so that they may be reused.
2516 * To remove all items from a group, you may wish to use the #clearItems method instead.
2517 *
2518 * @param {OO.ui.Element[]} items An array of items to remove
2519 * @chainable
2520 */
2521 OO.ui.mixin.GroupElement.prototype.removeItems = function ( items ) {
2522 var i, len, item, index;
2523
2524 // Remove specific items elements
2525 for ( i = 0, len = items.length; i < len; i++ ) {
2526 item = items[ i ];
2527 index = this.items.indexOf( item );
2528 if ( index !== -1 ) {
2529 item.setElementGroup( null );
2530 item.$element.detach();
2531 }
2532 }
2533
2534 // Mixin method
2535 OO.EmitterList.prototype.removeItems.call( this, items );
2536
2537 this.emit( 'change', this.getItems() );
2538 return this;
2539 };
2540
2541 /**
2542 * Clear all items from the group.
2543 *
2544 * Cleared items are detached from the DOM, not removed, so that they may be reused.
2545 * To remove only a subset of items from a group, use the #removeItems method.
2546 *
2547 * @chainable
2548 */
2549 OO.ui.mixin.GroupElement.prototype.clearItems = function () {
2550 var i, len;
2551
2552 // Remove all item elements
2553 for ( i = 0, len = this.items.length; i < len; i++ ) {
2554 this.items[ i ].setElementGroup( null );
2555 this.items[ i ].$element.detach();
2556 }
2557
2558 // Mixin method
2559 OO.EmitterList.prototype.clearItems.call( this );
2560
2561 this.emit( 'change', this.getItems() );
2562 return this;
2563 };
2564
2565 /**
2566 * IconElement is often mixed into other classes to generate an icon.
2567 * Icons are graphics, about the size of normal text. They are used to aid the user
2568 * in locating a control or to convey information in a space-efficient way. See the
2569 * [OOUI documentation on MediaWiki] [1] for a list of icons
2570 * included in the library.
2571 *
2572 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Icons,_Indicators,_and_Labels#Icons
2573 *
2574 * @abstract
2575 * @class
2576 *
2577 * @constructor
2578 * @param {Object} [config] Configuration options
2579 * @cfg {jQuery} [$icon] The icon element created by the class. If this configuration is omitted,
2580 * the icon element will use a generated `<span>`. To use a different HTML tag, or to specify that
2581 * the icon element be set to an existing icon instead of the one generated by this class, set a
2582 * value using a jQuery selection. For example:
2583 *
2584 * // Use a <div> tag instead of a <span>
2585 * $icon: $("<div>")
2586 * // Use an existing icon element instead of the one generated by the class
2587 * $icon: this.$element
2588 * // Use an icon element from a child widget
2589 * $icon: this.childwidget.$element
2590 * @cfg {Object|string} [icon=''] The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of
2591 * symbolic names. A map is used for i18n purposes and contains a `default` icon
2592 * name and additional names keyed by language code. The `default` name is used when no icon is keyed
2593 * by the user's language.
2594 *
2595 * Example of an i18n map:
2596 *
2597 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
2598 * See the [OOUI documentation on MediaWiki] [2] for a list of icons included in the library.
2599 * [2]: https://www.mediawiki.org/wiki/OOUI/Widgets/Icons,_Indicators,_and_Labels#Icons
2600 * @cfg {string|Function} [iconTitle] A text string used as the icon title, or a function that returns title
2601 * text. The icon title is displayed when users move the mouse over the icon.
2602 */
2603 OO.ui.mixin.IconElement = function OoUiMixinIconElement( config ) {
2604 // Configuration initialization
2605 config = config || {};
2606
2607 // Properties
2608 this.$icon = null;
2609 this.icon = null;
2610 this.iconTitle = null;
2611
2612 // Initialization
2613 this.setIcon( config.icon || this.constructor.static.icon );
2614 this.setIconTitle( config.iconTitle || this.constructor.static.iconTitle );
2615 this.setIconElement( config.$icon || $( '<span>' ) );
2616 };
2617
2618 /* Setup */
2619
2620 OO.initClass( OO.ui.mixin.IconElement );
2621
2622 /* Static Properties */
2623
2624 /**
2625 * The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of symbolic names. A map is used
2626 * for i18n purposes and contains a `default` icon name and additional names keyed by
2627 * language code. The `default` name is used when no icon is keyed by the user's language.
2628 *
2629 * Example of an i18n map:
2630 *
2631 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
2632 *
2633 * Note: the static property will be overridden if the #icon configuration is used.
2634 *
2635 * @static
2636 * @inheritable
2637 * @property {Object|string}
2638 */
2639 OO.ui.mixin.IconElement.static.icon = null;
2640
2641 /**
2642 * The icon title, displayed when users move the mouse over the icon. The value can be text, a
2643 * function that returns title text, or `null` for no title.
2644 *
2645 * The static property will be overridden if the #iconTitle configuration is used.
2646 *
2647 * @static
2648 * @inheritable
2649 * @property {string|Function|null}
2650 */
2651 OO.ui.mixin.IconElement.static.iconTitle = null;
2652
2653 /* Methods */
2654
2655 /**
2656 * Set the icon element. This method is used to retarget an icon mixin so that its functionality
2657 * applies to the specified icon element instead of the one created by the class. If an icon
2658 * element is already set, the mixin’s effect on that element is removed. Generated CSS classes
2659 * and mixin methods will no longer affect the element.
2660 *
2661 * @param {jQuery} $icon Element to use as icon
2662 */
2663 OO.ui.mixin.IconElement.prototype.setIconElement = function ( $icon ) {
2664 if ( this.$icon ) {
2665 this.$icon
2666 .removeClass( 'oo-ui-iconElement-icon oo-ui-icon-' + this.icon )
2667 .removeAttr( 'title' );
2668 }
2669
2670 this.$icon = $icon
2671 .addClass( 'oo-ui-iconElement-icon' )
2672 .toggleClass( 'oo-ui-icon-' + this.icon, !!this.icon );
2673 if ( this.iconTitle !== null ) {
2674 this.$icon.attr( 'title', this.iconTitle );
2675 }
2676
2677 this.updateThemeClasses();
2678 };
2679
2680 /**
2681 * Set icon by symbolic name (e.g., ‘remove’ or ‘menu’). Use `null` to remove an icon.
2682 * The icon parameter can also be set to a map of icon names. See the #icon config setting
2683 * for an example.
2684 *
2685 * @param {Object|string|null} icon A symbolic icon name, a {@link #icon map of icon names} keyed
2686 * by language code, or `null` to remove the icon.
2687 * @chainable
2688 */
2689 OO.ui.mixin.IconElement.prototype.setIcon = function ( icon ) {
2690 icon = OO.isPlainObject( icon ) ? OO.ui.getLocalValue( icon, null, 'default' ) : icon;
2691 icon = typeof icon === 'string' && icon.trim().length ? icon.trim() : null;
2692
2693 if ( this.icon !== icon ) {
2694 if ( this.$icon ) {
2695 if ( this.icon !== null ) {
2696 this.$icon.removeClass( 'oo-ui-icon-' + this.icon );
2697 }
2698 if ( icon !== null ) {
2699 this.$icon.addClass( 'oo-ui-icon-' + icon );
2700 }
2701 }
2702 this.icon = icon;
2703 }
2704
2705 this.$element.toggleClass( 'oo-ui-iconElement', !!this.icon );
2706 this.updateThemeClasses();
2707
2708 return this;
2709 };
2710
2711 /**
2712 * Set the icon title. Use `null` to remove the title.
2713 *
2714 * @param {string|Function|null} iconTitle A text string used as the icon title,
2715 * a function that returns title text, or `null` for no title.
2716 * @chainable
2717 */
2718 OO.ui.mixin.IconElement.prototype.setIconTitle = function ( iconTitle ) {
2719 iconTitle =
2720 ( typeof iconTitle === 'function' || ( typeof iconTitle === 'string' && iconTitle.length ) ) ?
2721 OO.ui.resolveMsg( iconTitle ) : null;
2722
2723 if ( this.iconTitle !== iconTitle ) {
2724 this.iconTitle = iconTitle;
2725 if ( this.$icon ) {
2726 if ( this.iconTitle !== null ) {
2727 this.$icon.attr( 'title', iconTitle );
2728 } else {
2729 this.$icon.removeAttr( 'title' );
2730 }
2731 }
2732 }
2733
2734 return this;
2735 };
2736
2737 /**
2738 * Get the symbolic name of the icon.
2739 *
2740 * @return {string} Icon name
2741 */
2742 OO.ui.mixin.IconElement.prototype.getIcon = function () {
2743 return this.icon;
2744 };
2745
2746 /**
2747 * Get the icon title. The title text is displayed when a user moves the mouse over the icon.
2748 *
2749 * @return {string} Icon title text
2750 */
2751 OO.ui.mixin.IconElement.prototype.getIconTitle = function () {
2752 return this.iconTitle;
2753 };
2754
2755 /**
2756 * IndicatorElement is often mixed into other classes to generate an indicator.
2757 * Indicators are small graphics that are generally used in two ways:
2758 *
2759 * - To draw attention to the status of an item. For example, an indicator might be
2760 * used to show that an item in a list has errors that need to be resolved.
2761 * - To clarify the function of a control that acts in an exceptional way (a button
2762 * that opens a menu instead of performing an action directly, for example).
2763 *
2764 * For a list of indicators included in the library, please see the
2765 * [OOUI documentation on MediaWiki] [1].
2766 *
2767 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Icons,_Indicators,_and_Labels#Indicators
2768 *
2769 * @abstract
2770 * @class
2771 *
2772 * @constructor
2773 * @param {Object} [config] Configuration options
2774 * @cfg {jQuery} [$indicator] The indicator element created by the class. If this
2775 * configuration is omitted, the indicator element will use a generated `<span>`.
2776 * @cfg {string} [indicator] Symbolic name of the indicator (e.g., ‘clear’ or ‘down’).
2777 * See the [OOUI documentation on MediaWiki][2] for a list of indicators included
2778 * in the library.
2779 * [2]: https://www.mediawiki.org/wiki/OOUI/Widgets/Icons,_Indicators,_and_Labels#Indicators
2780 * @cfg {string|Function} [indicatorTitle] A text string used as the indicator title,
2781 * or a function that returns title text. The indicator title is displayed when users move
2782 * the mouse over the indicator.
2783 */
2784 OO.ui.mixin.IndicatorElement = function OoUiMixinIndicatorElement( config ) {
2785 // Configuration initialization
2786 config = config || {};
2787
2788 // Properties
2789 this.$indicator = null;
2790 this.indicator = null;
2791 this.indicatorTitle = null;
2792
2793 // Initialization
2794 this.setIndicator( config.indicator || this.constructor.static.indicator );
2795 this.setIndicatorTitle( config.indicatorTitle || this.constructor.static.indicatorTitle );
2796 this.setIndicatorElement( config.$indicator || $( '<span>' ) );
2797 };
2798
2799 /* Setup */
2800
2801 OO.initClass( OO.ui.mixin.IndicatorElement );
2802
2803 /* Static Properties */
2804
2805 /**
2806 * Symbolic name of the indicator (e.g., ‘clear’ or ‘down’).
2807 * The static property will be overridden if the #indicator configuration is used.
2808 *
2809 * @static
2810 * @inheritable
2811 * @property {string|null}
2812 */
2813 OO.ui.mixin.IndicatorElement.static.indicator = null;
2814
2815 /**
2816 * A text string used as the indicator title, a function that returns title text, or `null`
2817 * for no title. The static property will be overridden if the #indicatorTitle configuration is used.
2818 *
2819 * @static
2820 * @inheritable
2821 * @property {string|Function|null}
2822 */
2823 OO.ui.mixin.IndicatorElement.static.indicatorTitle = null;
2824
2825 /* Methods */
2826
2827 /**
2828 * Set the indicator element.
2829 *
2830 * If an element is already set, it will be cleaned up before setting up the new element.
2831 *
2832 * @param {jQuery} $indicator Element to use as indicator
2833 */
2834 OO.ui.mixin.IndicatorElement.prototype.setIndicatorElement = function ( $indicator ) {
2835 if ( this.$indicator ) {
2836 this.$indicator
2837 .removeClass( 'oo-ui-indicatorElement-indicator oo-ui-indicator-' + this.indicator )
2838 .removeAttr( 'title' );
2839 }
2840
2841 this.$indicator = $indicator
2842 .addClass( 'oo-ui-indicatorElement-indicator' )
2843 .toggleClass( 'oo-ui-indicator-' + this.indicator, !!this.indicator );
2844 if ( this.indicatorTitle !== null ) {
2845 this.$indicator.attr( 'title', this.indicatorTitle );
2846 }
2847
2848 this.updateThemeClasses();
2849 };
2850
2851 /**
2852 * Set the indicator by its symbolic name: ‘clear’, ‘down’, ‘required’, ‘search’, ‘up’. Use `null` to remove the indicator.
2853 *
2854 * @param {string|null} indicator Symbolic name of indicator, or `null` for no indicator
2855 * @chainable
2856 */
2857 OO.ui.mixin.IndicatorElement.prototype.setIndicator = function ( indicator ) {
2858 indicator = typeof indicator === 'string' && indicator.length ? indicator.trim() : null;
2859
2860 if ( this.indicator !== indicator ) {
2861 if ( this.$indicator ) {
2862 if ( this.indicator !== null ) {
2863 this.$indicator.removeClass( 'oo-ui-indicator-' + this.indicator );
2864 }
2865 if ( indicator !== null ) {
2866 this.$indicator.addClass( 'oo-ui-indicator-' + indicator );
2867 }
2868 }
2869 this.indicator = indicator;
2870 }
2871
2872 this.$element.toggleClass( 'oo-ui-indicatorElement', !!this.indicator );
2873 this.updateThemeClasses();
2874
2875 return this;
2876 };
2877
2878 /**
2879 * Set the indicator title.
2880 *
2881 * The title is displayed when a user moves the mouse over the indicator.
2882 *
2883 * @param {string|Function|null} indicatorTitle Indicator title text, a function that returns text, or
2884 * `null` for no indicator title
2885 * @chainable
2886 */
2887 OO.ui.mixin.IndicatorElement.prototype.setIndicatorTitle = function ( indicatorTitle ) {
2888 indicatorTitle =
2889 ( typeof indicatorTitle === 'function' || ( typeof indicatorTitle === 'string' && indicatorTitle.length ) ) ?
2890 OO.ui.resolveMsg( indicatorTitle ) : null;
2891
2892 if ( this.indicatorTitle !== indicatorTitle ) {
2893 this.indicatorTitle = indicatorTitle;
2894 if ( this.$indicator ) {
2895 if ( this.indicatorTitle !== null ) {
2896 this.$indicator.attr( 'title', indicatorTitle );
2897 } else {
2898 this.$indicator.removeAttr( 'title' );
2899 }
2900 }
2901 }
2902
2903 return this;
2904 };
2905
2906 /**
2907 * Get the symbolic name of the indicator (e.g., ‘clear’ or ‘down’).
2908 *
2909 * @return {string} Symbolic name of indicator
2910 */
2911 OO.ui.mixin.IndicatorElement.prototype.getIndicator = function () {
2912 return this.indicator;
2913 };
2914
2915 /**
2916 * Get the indicator title.
2917 *
2918 * The title is displayed when a user moves the mouse over the indicator.
2919 *
2920 * @return {string} Indicator title text
2921 */
2922 OO.ui.mixin.IndicatorElement.prototype.getIndicatorTitle = function () {
2923 return this.indicatorTitle;
2924 };
2925
2926 /**
2927 * LabelElement is often mixed into other classes to generate a label, which
2928 * helps identify the function of an interface element.
2929 * See the [OOUI documentation on MediaWiki] [1] for more information.
2930 *
2931 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Icons,_Indicators,_and_Labels#Labels
2932 *
2933 * @abstract
2934 * @class
2935 *
2936 * @constructor
2937 * @param {Object} [config] Configuration options
2938 * @cfg {jQuery} [$label] The label element created by the class. If this
2939 * configuration is omitted, the label element will use a generated `<span>`.
2940 * @cfg {jQuery|string|Function|OO.ui.HtmlSnippet} [label] The label text. The label can be specified
2941 * as a plaintext string, a jQuery selection of elements, or a function that will produce a string
2942 * in the future. See the [OOUI documentation on MediaWiki] [2] for examples.
2943 * [2]: https://www.mediawiki.org/wiki/OOUI/Widgets/Icons,_Indicators,_and_Labels#Labels
2944 */
2945 OO.ui.mixin.LabelElement = function OoUiMixinLabelElement( config ) {
2946 // Configuration initialization
2947 config = config || {};
2948
2949 // Properties
2950 this.$label = null;
2951 this.label = null;
2952
2953 // Initialization
2954 this.setLabel( config.label || this.constructor.static.label );
2955 this.setLabelElement( config.$label || $( '<span>' ) );
2956 };
2957
2958 /* Setup */
2959
2960 OO.initClass( OO.ui.mixin.LabelElement );
2961
2962 /* Events */
2963
2964 /**
2965 * @event labelChange
2966 * @param {string} value
2967 */
2968
2969 /* Static Properties */
2970
2971 /**
2972 * The label text. The label can be specified as a plaintext string, a function that will
2973 * produce a string in the future, or `null` for no label. The static value will
2974 * be overridden if a label is specified with the #label config option.
2975 *
2976 * @static
2977 * @inheritable
2978 * @property {string|Function|null}
2979 */
2980 OO.ui.mixin.LabelElement.static.label = null;
2981
2982 /* Static methods */
2983
2984 /**
2985 * Highlight the first occurrence of the query in the given text
2986 *
2987 * @param {string} text Text
2988 * @param {string} query Query to find
2989 * @param {Function} [compare] Optional string comparator, e.g. Intl.Collator().compare
2990 * @return {jQuery} Text with the first match of the query
2991 * sub-string wrapped in highlighted span
2992 */
2993 OO.ui.mixin.LabelElement.static.highlightQuery = function ( text, query, compare ) {
2994 var i, tLen, qLen,
2995 offset = -1,
2996 $result = $( '<span>' );
2997
2998 if ( compare ) {
2999 tLen = text.length;
3000 qLen = query.length;
3001 for ( i = 0; offset === -1 && i <= tLen - qLen; i++ ) {
3002 if ( compare( query, text.slice( i, i + qLen ) ) === 0 ) {
3003 offset = i;
3004 }
3005 }
3006 } else {
3007 offset = text.toLowerCase().indexOf( query.toLowerCase() );
3008 }
3009
3010 if ( !query.length || offset === -1 ) {
3011 $result.text( text );
3012 } else {
3013 $result.append(
3014 document.createTextNode( text.slice( 0, offset ) ),
3015 $( '<span>' )
3016 .addClass( 'oo-ui-labelElement-label-highlight' )
3017 .text( text.slice( offset, offset + query.length ) ),
3018 document.createTextNode( text.slice( offset + query.length ) )
3019 );
3020 }
3021 return $result.contents();
3022 };
3023
3024 /* Methods */
3025
3026 /**
3027 * Set the label element.
3028 *
3029 * If an element is already set, it will be cleaned up before setting up the new element.
3030 *
3031 * @param {jQuery} $label Element to use as label
3032 */
3033 OO.ui.mixin.LabelElement.prototype.setLabelElement = function ( $label ) {
3034 if ( this.$label ) {
3035 this.$label.removeClass( 'oo-ui-labelElement-label' ).empty();
3036 }
3037
3038 this.$label = $label.addClass( 'oo-ui-labelElement-label' );
3039 this.setLabelContent( this.label );
3040 };
3041
3042 /**
3043 * Set the label.
3044 *
3045 * An empty string will result in the label being hidden. A string containing only whitespace will
3046 * be converted to a single `&nbsp;`.
3047 *
3048 * @param {jQuery|string|OO.ui.HtmlSnippet|Function|null} label Label nodes; text; a function that returns nodes or
3049 * text; or null for no label
3050 * @chainable
3051 */
3052 OO.ui.mixin.LabelElement.prototype.setLabel = function ( label ) {
3053 label = typeof label === 'function' ? OO.ui.resolveMsg( label ) : label;
3054 label = ( ( typeof label === 'string' || label instanceof jQuery ) && label.length ) || ( label instanceof OO.ui.HtmlSnippet && label.toString().length ) ? label : null;
3055
3056 if ( this.label !== label ) {
3057 if ( this.$label ) {
3058 this.setLabelContent( label );
3059 }
3060 this.label = label;
3061 this.emit( 'labelChange' );
3062 }
3063
3064 this.$element.toggleClass( 'oo-ui-labelElement', !!this.label );
3065
3066 return this;
3067 };
3068
3069 /**
3070 * Set the label as plain text with a highlighted query
3071 *
3072 * @param {string} text Text label to set
3073 * @param {string} query Substring of text to highlight
3074 * @param {Function} [compare] Optional string comparator, e.g. Intl.Collator().compare
3075 * @chainable
3076 */
3077 OO.ui.mixin.LabelElement.prototype.setHighlightedQuery = function ( text, query, compare ) {
3078 return this.setLabel( this.constructor.static.highlightQuery( text, query, compare ) );
3079 };
3080
3081 /**
3082 * Get the label.
3083 *
3084 * @return {jQuery|string|Function|null} Label nodes; text; a function that returns nodes or
3085 * text; or null for no label
3086 */
3087 OO.ui.mixin.LabelElement.prototype.getLabel = function () {
3088 return this.label;
3089 };
3090
3091 /**
3092 * Set the content of the label.
3093 *
3094 * Do not call this method until after the label element has been set by #setLabelElement.
3095 *
3096 * @private
3097 * @param {jQuery|string|Function|null} label Label nodes; text; a function that returns nodes or
3098 * text; or null for no label
3099 */
3100 OO.ui.mixin.LabelElement.prototype.setLabelContent = function ( label ) {
3101 if ( typeof label === 'string' ) {
3102 if ( label.match( /^\s*$/ ) ) {
3103 // Convert whitespace only string to a single non-breaking space
3104 this.$label.html( '&nbsp;' );
3105 } else {
3106 this.$label.text( label );
3107 }
3108 } else if ( label instanceof OO.ui.HtmlSnippet ) {
3109 this.$label.html( label.toString() );
3110 } else if ( label instanceof jQuery ) {
3111 this.$label.empty().append( label );
3112 } else {
3113 this.$label.empty();
3114 }
3115 };
3116
3117 /**
3118 * The FlaggedElement class is an attribute mixin, meaning that it is used to add
3119 * additional functionality to an element created by another class. The class provides
3120 * a ‘flags’ property assigned the name (or an array of names) of styling flags,
3121 * which are used to customize the look and feel of a widget to better describe its
3122 * importance and functionality.
3123 *
3124 * The library currently contains the following styling flags for general use:
3125 *
3126 * - **progressive**: Progressive styling is applied to convey that the widget will move the user forward in a process.
3127 * - **destructive**: Destructive styling is applied to convey that the widget will remove something.
3128 *
3129 * The flags affect the appearance of the buttons:
3130 *
3131 * @example
3132 * // FlaggedElement is mixed into ButtonWidget to provide styling flags
3133 * var button1 = new OO.ui.ButtonWidget( {
3134 * label: 'Progressive',
3135 * flags: 'progressive'
3136 * } );
3137 * var button2 = new OO.ui.ButtonWidget( {
3138 * label: 'Destructive',
3139 * flags: 'destructive'
3140 * } );
3141 * $( 'body' ).append( button1.$element, button2.$element );
3142 *
3143 * {@link OO.ui.ActionWidget ActionWidgets}, which are a special kind of button that execute an action, use these flags: **primary** and **safe**.
3144 * Please see the [OOUI documentation on MediaWiki] [1] for more information.
3145 *
3146 * [1]: https://www.mediawiki.org/wiki/OOUI/Elements/Flagged
3147 *
3148 * @abstract
3149 * @class
3150 *
3151 * @constructor
3152 * @param {Object} [config] Configuration options
3153 * @cfg {string|string[]} [flags] The name or names of the flags (e.g., 'progressive' or 'primary') to apply.
3154 * Please see the [OOUI documentation on MediaWiki] [2] for more information about available flags.
3155 * [2]: https://www.mediawiki.org/wiki/OOUI/Elements/Flagged
3156 * @cfg {jQuery} [$flagged] The flagged element. By default,
3157 * the flagged functionality is applied to the element created by the class ($element).
3158 * If a different element is specified, the flagged functionality will be applied to it instead.
3159 */
3160 OO.ui.mixin.FlaggedElement = function OoUiMixinFlaggedElement( config ) {
3161 // Configuration initialization
3162 config = config || {};
3163
3164 // Properties
3165 this.flags = {};
3166 this.$flagged = null;
3167
3168 // Initialization
3169 this.setFlags( config.flags );
3170 this.setFlaggedElement( config.$flagged || this.$element );
3171 };
3172
3173 /* Events */
3174
3175 /**
3176 * @event flag
3177 * A flag event is emitted when the #clearFlags or #setFlags methods are used. The `changes`
3178 * parameter contains the name of each modified flag and indicates whether it was
3179 * added or removed.
3180 *
3181 * @param {Object.<string,boolean>} changes Object keyed by flag name. A Boolean `true` indicates
3182 * that the flag was added, `false` that the flag was removed.
3183 */
3184
3185 /* Methods */
3186
3187 /**
3188 * Set the flagged element.
3189 *
3190 * This method is used to retarget a flagged mixin so that its functionality applies to the specified element.
3191 * If an element is already set, the method will remove the mixin’s effect on that element.
3192 *
3193 * @param {jQuery} $flagged Element that should be flagged
3194 */
3195 OO.ui.mixin.FlaggedElement.prototype.setFlaggedElement = function ( $flagged ) {
3196 var classNames = Object.keys( this.flags ).map( function ( flag ) {
3197 return 'oo-ui-flaggedElement-' + flag;
3198 } ).join( ' ' );
3199
3200 if ( this.$flagged ) {
3201 this.$flagged.removeClass( classNames );
3202 }
3203
3204 this.$flagged = $flagged.addClass( classNames );
3205 };
3206
3207 /**
3208 * Check if the specified flag is set.
3209 *
3210 * @param {string} flag Name of flag
3211 * @return {boolean} The flag is set
3212 */
3213 OO.ui.mixin.FlaggedElement.prototype.hasFlag = function ( flag ) {
3214 // This may be called before the constructor, thus before this.flags is set
3215 return this.flags && ( flag in this.flags );
3216 };
3217
3218 /**
3219 * Get the names of all flags set.
3220 *
3221 * @return {string[]} Flag names
3222 */
3223 OO.ui.mixin.FlaggedElement.prototype.getFlags = function () {
3224 // This may be called before the constructor, thus before this.flags is set
3225 return Object.keys( this.flags || {} );
3226 };
3227
3228 /**
3229 * Clear all flags.
3230 *
3231 * @chainable
3232 * @fires flag
3233 */
3234 OO.ui.mixin.FlaggedElement.prototype.clearFlags = function () {
3235 var flag, className,
3236 changes = {},
3237 remove = [],
3238 classPrefix = 'oo-ui-flaggedElement-';
3239
3240 for ( flag in this.flags ) {
3241 className = classPrefix + flag;
3242 changes[ flag ] = false;
3243 delete this.flags[ flag ];
3244 remove.push( className );
3245 }
3246
3247 if ( this.$flagged ) {
3248 this.$flagged.removeClass( remove.join( ' ' ) );
3249 }
3250
3251 this.updateThemeClasses();
3252 this.emit( 'flag', changes );
3253
3254 return this;
3255 };
3256
3257 /**
3258 * Add one or more flags.
3259 *
3260 * @param {string|string[]|Object.<string, boolean>} flags A flag name, an array of flag names,
3261 * or an object keyed by flag name with a boolean value that indicates whether the flag should
3262 * be added (`true`) or removed (`false`).
3263 * @chainable
3264 * @fires flag
3265 */
3266 OO.ui.mixin.FlaggedElement.prototype.setFlags = function ( flags ) {
3267 var i, len, flag, className,
3268 changes = {},
3269 add = [],
3270 remove = [],
3271 classPrefix = 'oo-ui-flaggedElement-';
3272
3273 if ( typeof flags === 'string' ) {
3274 className = classPrefix + flags;
3275 // Set
3276 if ( !this.flags[ flags ] ) {
3277 this.flags[ flags ] = true;
3278 add.push( className );
3279 }
3280 } else if ( Array.isArray( flags ) ) {
3281 for ( i = 0, len = flags.length; i < len; i++ ) {
3282 flag = flags[ i ];
3283 className = classPrefix + flag;
3284 // Set
3285 if ( !this.flags[ flag ] ) {
3286 changes[ flag ] = true;
3287 this.flags[ flag ] = true;
3288 add.push( className );
3289 }
3290 }
3291 } else if ( OO.isPlainObject( flags ) ) {
3292 for ( flag in flags ) {
3293 className = classPrefix + flag;
3294 if ( flags[ flag ] ) {
3295 // Set
3296 if ( !this.flags[ flag ] ) {
3297 changes[ flag ] = true;
3298 this.flags[ flag ] = true;
3299 add.push( className );
3300 }
3301 } else {
3302 // Remove
3303 if ( this.flags[ flag ] ) {
3304 changes[ flag ] = false;
3305 delete this.flags[ flag ];
3306 remove.push( className );
3307 }
3308 }
3309 }
3310 }
3311
3312 if ( this.$flagged ) {
3313 this.$flagged
3314 .addClass( add.join( ' ' ) )
3315 .removeClass( remove.join( ' ' ) );
3316 }
3317
3318 this.updateThemeClasses();
3319 this.emit( 'flag', changes );
3320
3321 return this;
3322 };
3323
3324 /**
3325 * TitledElement is mixed into other classes to provide a `title` attribute.
3326 * Titles are rendered by the browser and are made visible when the user moves
3327 * the mouse over the element. Titles are not visible on touch devices.
3328 *
3329 * @example
3330 * // TitledElement provides a 'title' attribute to the
3331 * // ButtonWidget class
3332 * var button = new OO.ui.ButtonWidget( {
3333 * label: 'Button with Title',
3334 * title: 'I am a button'
3335 * } );
3336 * $( 'body' ).append( button.$element );
3337 *
3338 * @abstract
3339 * @class
3340 *
3341 * @constructor
3342 * @param {Object} [config] Configuration options
3343 * @cfg {jQuery} [$titled] The element to which the `title` attribute is applied.
3344 * If this config is omitted, the title functionality is applied to $element, the
3345 * element created by the class.
3346 * @cfg {string|Function} [title] The title text or a function that returns text. If
3347 * this config is omitted, the value of the {@link #static-title static title} property is used.
3348 */
3349 OO.ui.mixin.TitledElement = function OoUiMixinTitledElement( config ) {
3350 // Configuration initialization
3351 config = config || {};
3352
3353 // Properties
3354 this.$titled = null;
3355 this.title = null;
3356
3357 // Initialization
3358 this.setTitle( config.title !== undefined ? config.title : this.constructor.static.title );
3359 this.setTitledElement( config.$titled || this.$element );
3360 };
3361
3362 /* Setup */
3363
3364 OO.initClass( OO.ui.mixin.TitledElement );
3365
3366 /* Static Properties */
3367
3368 /**
3369 * The title text, a function that returns text, or `null` for no title. The value of the static property
3370 * is overridden if the #title config option is used.
3371 *
3372 * @static
3373 * @inheritable
3374 * @property {string|Function|null}
3375 */
3376 OO.ui.mixin.TitledElement.static.title = null;
3377
3378 /* Methods */
3379
3380 /**
3381 * Set the titled element.
3382 *
3383 * This method is used to retarget a titledElement mixin so that its functionality applies to the specified element.
3384 * If an element is already set, the mixin’s effect on that element is removed before the new element is set up.
3385 *
3386 * @param {jQuery} $titled Element that should use the 'titled' functionality
3387 */
3388 OO.ui.mixin.TitledElement.prototype.setTitledElement = function ( $titled ) {
3389 if ( this.$titled ) {
3390 this.$titled.removeAttr( 'title' );
3391 }
3392
3393 this.$titled = $titled;
3394 if ( this.title ) {
3395 this.updateTitle();
3396 }
3397 };
3398
3399 /**
3400 * Set title.
3401 *
3402 * @param {string|Function|null} title Title text, a function that returns text, or `null` for no title
3403 * @chainable
3404 */
3405 OO.ui.mixin.TitledElement.prototype.setTitle = function ( title ) {
3406 title = typeof title === 'function' ? OO.ui.resolveMsg( title ) : title;
3407 title = ( typeof title === 'string' && title.length ) ? title : null;
3408
3409 if ( this.title !== title ) {
3410 this.title = title;
3411 this.updateTitle();
3412 }
3413
3414 return this;
3415 };
3416
3417 /**
3418 * Update the title attribute, in case of changes to title or accessKey.
3419 *
3420 * @protected
3421 * @chainable
3422 */
3423 OO.ui.mixin.TitledElement.prototype.updateTitle = function () {
3424 var title = this.getTitle();
3425 if ( this.$titled ) {
3426 if ( title !== null ) {
3427 // Only if this is an AccessKeyedElement
3428 if ( this.formatTitleWithAccessKey ) {
3429 title = this.formatTitleWithAccessKey( title );
3430 }
3431 this.$titled.attr( 'title', title );
3432 } else {
3433 this.$titled.removeAttr( 'title' );
3434 }
3435 }
3436 return this;
3437 };
3438
3439 /**
3440 * Get title.
3441 *
3442 * @return {string} Title string
3443 */
3444 OO.ui.mixin.TitledElement.prototype.getTitle = function () {
3445 return this.title;
3446 };
3447
3448 /**
3449 * AccessKeyedElement is mixed into other classes to provide an `accesskey` attribute.
3450 * Accesskeys allow an user to go to a specific element by using
3451 * a shortcut combination of a browser specific keys + the key
3452 * set to the field.
3453 *
3454 * @example
3455 * // AccessKeyedElement provides an 'accesskey' attribute to the
3456 * // ButtonWidget class
3457 * var button = new OO.ui.ButtonWidget( {
3458 * label: 'Button with Accesskey',
3459 * accessKey: 'k'
3460 * } );
3461 * $( 'body' ).append( button.$element );
3462 *
3463 * @abstract
3464 * @class
3465 *
3466 * @constructor
3467 * @param {Object} [config] Configuration options
3468 * @cfg {jQuery} [$accessKeyed] The element to which the `accesskey` attribute is applied.
3469 * If this config is omitted, the accesskey functionality is applied to $element, the
3470 * element created by the class.
3471 * @cfg {string|Function} [accessKey] The key or a function that returns the key. If
3472 * this config is omitted, no accesskey will be added.
3473 */
3474 OO.ui.mixin.AccessKeyedElement = function OoUiMixinAccessKeyedElement( config ) {
3475 // Configuration initialization
3476 config = config || {};
3477
3478 // Properties
3479 this.$accessKeyed = null;
3480 this.accessKey = null;
3481
3482 // Initialization
3483 this.setAccessKey( config.accessKey || null );
3484 this.setAccessKeyedElement( config.$accessKeyed || this.$element );
3485
3486 // If this is also a TitledElement and it initialized before we did, we may have
3487 // to update the title with the access key
3488 if ( this.updateTitle ) {
3489 this.updateTitle();
3490 }
3491 };
3492
3493 /* Setup */
3494
3495 OO.initClass( OO.ui.mixin.AccessKeyedElement );
3496
3497 /* Static Properties */
3498
3499 /**
3500 * The access key, a function that returns a key, or `null` for no accesskey.
3501 *
3502 * @static
3503 * @inheritable
3504 * @property {string|Function|null}
3505 */
3506 OO.ui.mixin.AccessKeyedElement.static.accessKey = null;
3507
3508 /* Methods */
3509
3510 /**
3511 * Set the accesskeyed element.
3512 *
3513 * This method is used to retarget a AccessKeyedElement mixin so that its functionality applies to the specified element.
3514 * If an element is already set, the mixin's effect on that element is removed before the new element is set up.
3515 *
3516 * @param {jQuery} $accessKeyed Element that should use the 'accesskeyes' functionality
3517 */
3518 OO.ui.mixin.AccessKeyedElement.prototype.setAccessKeyedElement = function ( $accessKeyed ) {
3519 if ( this.$accessKeyed ) {
3520 this.$accessKeyed.removeAttr( 'accesskey' );
3521 }
3522
3523 this.$accessKeyed = $accessKeyed;
3524 if ( this.accessKey ) {
3525 this.$accessKeyed.attr( 'accesskey', this.accessKey );
3526 }
3527 };
3528
3529 /**
3530 * Set accesskey.
3531 *
3532 * @param {string|Function|null} accessKey Key, a function that returns a key, or `null` for no accesskey
3533 * @chainable
3534 */
3535 OO.ui.mixin.AccessKeyedElement.prototype.setAccessKey = function ( accessKey ) {
3536 accessKey = typeof accessKey === 'string' ? OO.ui.resolveMsg( accessKey ) : null;
3537
3538 if ( this.accessKey !== accessKey ) {
3539 if ( this.$accessKeyed ) {
3540 if ( accessKey !== null ) {
3541 this.$accessKeyed.attr( 'accesskey', accessKey );
3542 } else {
3543 this.$accessKeyed.removeAttr( 'accesskey' );
3544 }
3545 }
3546 this.accessKey = accessKey;
3547
3548 // Only if this is a TitledElement
3549 if ( this.updateTitle ) {
3550 this.updateTitle();
3551 }
3552 }
3553
3554 return this;
3555 };
3556
3557 /**
3558 * Get accesskey.
3559 *
3560 * @return {string} accessKey string
3561 */
3562 OO.ui.mixin.AccessKeyedElement.prototype.getAccessKey = function () {
3563 return this.accessKey;
3564 };
3565
3566 /**
3567 * Add information about the access key to the element's tooltip label.
3568 * (This is only public for hacky usage in FieldLayout.)
3569 *
3570 * @param {string} title Tooltip label for `title` attribute
3571 * @return {string}
3572 */
3573 OO.ui.mixin.AccessKeyedElement.prototype.formatTitleWithAccessKey = function ( title ) {
3574 var accessKey;
3575
3576 if ( !this.$accessKeyed ) {
3577 // Not initialized yet; the constructor will call updateTitle() which will rerun this function
3578 return title;
3579 }
3580 // Use jquery.accessKeyLabel if available to show modifiers, otherwise just display the single key
3581 if ( $.fn.updateTooltipAccessKeys && $.fn.updateTooltipAccessKeys.getAccessKeyLabel ) {
3582 accessKey = $.fn.updateTooltipAccessKeys.getAccessKeyLabel( this.$accessKeyed[ 0 ] );
3583 } else {
3584 accessKey = this.getAccessKey();
3585 }
3586 if ( accessKey ) {
3587 title += ' [' + accessKey + ']';
3588 }
3589 return title;
3590 };
3591
3592 /**
3593 * ButtonWidget is a generic widget for buttons. A wide variety of looks,
3594 * feels, and functionality can be customized via the class’s configuration options
3595 * and methods. Please see the [OOUI documentation on MediaWiki] [1] for more information
3596 * and examples.
3597 *
3598 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Buttons_and_Switches
3599 *
3600 * @example
3601 * // A button widget
3602 * var button = new OO.ui.ButtonWidget( {
3603 * label: 'Button with Icon',
3604 * icon: 'trash',
3605 * iconTitle: 'Remove'
3606 * } );
3607 * $( 'body' ).append( button.$element );
3608 *
3609 * NOTE: HTML form buttons should use the OO.ui.ButtonInputWidget class.
3610 *
3611 * @class
3612 * @extends OO.ui.Widget
3613 * @mixins OO.ui.mixin.ButtonElement
3614 * @mixins OO.ui.mixin.IconElement
3615 * @mixins OO.ui.mixin.IndicatorElement
3616 * @mixins OO.ui.mixin.LabelElement
3617 * @mixins OO.ui.mixin.TitledElement
3618 * @mixins OO.ui.mixin.FlaggedElement
3619 * @mixins OO.ui.mixin.TabIndexedElement
3620 * @mixins OO.ui.mixin.AccessKeyedElement
3621 *
3622 * @constructor
3623 * @param {Object} [config] Configuration options
3624 * @cfg {boolean} [active=false] Whether button should be shown as active
3625 * @cfg {string} [href] Hyperlink to visit when the button is clicked.
3626 * @cfg {string} [target] The frame or window in which to open the hyperlink.
3627 * @cfg {boolean} [noFollow] Search engine traversal hint (default: true)
3628 */
3629 OO.ui.ButtonWidget = function OoUiButtonWidget( config ) {
3630 // Configuration initialization
3631 config = config || {};
3632
3633 // Parent constructor
3634 OO.ui.ButtonWidget.parent.call( this, config );
3635
3636 // Mixin constructors
3637 OO.ui.mixin.ButtonElement.call( this, config );
3638 OO.ui.mixin.IconElement.call( this, config );
3639 OO.ui.mixin.IndicatorElement.call( this, config );
3640 OO.ui.mixin.LabelElement.call( this, config );
3641 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$button } ) );
3642 OO.ui.mixin.FlaggedElement.call( this, config );
3643 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$button } ) );
3644 OO.ui.mixin.AccessKeyedElement.call( this, $.extend( {}, config, { $accessKeyed: this.$button } ) );
3645
3646 // Properties
3647 this.href = null;
3648 this.target = null;
3649 this.noFollow = false;
3650
3651 // Events
3652 this.connect( this, { disable: 'onDisable' } );
3653
3654 // Initialization
3655 this.$button.append( this.$icon, this.$label, this.$indicator );
3656 this.$element
3657 .addClass( 'oo-ui-buttonWidget' )
3658 .append( this.$button );
3659 this.setActive( config.active );
3660 this.setHref( config.href );
3661 this.setTarget( config.target );
3662 this.setNoFollow( config.noFollow );
3663 };
3664
3665 /* Setup */
3666
3667 OO.inheritClass( OO.ui.ButtonWidget, OO.ui.Widget );
3668 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.ButtonElement );
3669 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.IconElement );
3670 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.IndicatorElement );
3671 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.LabelElement );
3672 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.TitledElement );
3673 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.FlaggedElement );
3674 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.TabIndexedElement );
3675 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.AccessKeyedElement );
3676
3677 /* Static Properties */
3678
3679 /**
3680 * @static
3681 * @inheritdoc
3682 */
3683 OO.ui.ButtonWidget.static.cancelButtonMouseDownEvents = false;
3684
3685 /**
3686 * @static
3687 * @inheritdoc
3688 */
3689 OO.ui.ButtonWidget.static.tagName = 'span';
3690
3691 /* Methods */
3692
3693 /**
3694 * Get hyperlink location.
3695 *
3696 * @return {string} Hyperlink location
3697 */
3698 OO.ui.ButtonWidget.prototype.getHref = function () {
3699 return this.href;
3700 };
3701
3702 /**
3703 * Get hyperlink target.
3704 *
3705 * @return {string} Hyperlink target
3706 */
3707 OO.ui.ButtonWidget.prototype.getTarget = function () {
3708 return this.target;
3709 };
3710
3711 /**
3712 * Get search engine traversal hint.
3713 *
3714 * @return {boolean} Whether search engines should avoid traversing this hyperlink
3715 */
3716 OO.ui.ButtonWidget.prototype.getNoFollow = function () {
3717 return this.noFollow;
3718 };
3719
3720 /**
3721 * Set hyperlink location.
3722 *
3723 * @param {string|null} href Hyperlink location, null to remove
3724 */
3725 OO.ui.ButtonWidget.prototype.setHref = function ( href ) {
3726 href = typeof href === 'string' ? href : null;
3727 if ( href !== null && !OO.ui.isSafeUrl( href ) ) {
3728 href = './' + href;
3729 }
3730
3731 if ( href !== this.href ) {
3732 this.href = href;
3733 this.updateHref();
3734 }
3735
3736 return this;
3737 };
3738
3739 /**
3740 * Update the `href` attribute, in case of changes to href or
3741 * disabled state.
3742 *
3743 * @private
3744 * @chainable
3745 */
3746 OO.ui.ButtonWidget.prototype.updateHref = function () {
3747 if ( this.href !== null && !this.isDisabled() ) {
3748 this.$button.attr( 'href', this.href );
3749 } else {
3750 this.$button.removeAttr( 'href' );
3751 }
3752
3753 return this;
3754 };
3755
3756 /**
3757 * Handle disable events.
3758 *
3759 * @private
3760 * @param {boolean} disabled Element is disabled
3761 */
3762 OO.ui.ButtonWidget.prototype.onDisable = function () {
3763 this.updateHref();
3764 };
3765
3766 /**
3767 * Set hyperlink target.
3768 *
3769 * @param {string|null} target Hyperlink target, null to remove
3770 */
3771 OO.ui.ButtonWidget.prototype.setTarget = function ( target ) {
3772 target = typeof target === 'string' ? target : null;
3773
3774 if ( target !== this.target ) {
3775 this.target = target;
3776 if ( target !== null ) {
3777 this.$button.attr( 'target', target );
3778 } else {
3779 this.$button.removeAttr( 'target' );
3780 }
3781 }
3782
3783 return this;
3784 };
3785
3786 /**
3787 * Set search engine traversal hint.
3788 *
3789 * @param {boolean} noFollow True if search engines should avoid traversing this hyperlink
3790 */
3791 OO.ui.ButtonWidget.prototype.setNoFollow = function ( noFollow ) {
3792 noFollow = typeof noFollow === 'boolean' ? noFollow : true;
3793
3794 if ( noFollow !== this.noFollow ) {
3795 this.noFollow = noFollow;
3796 if ( noFollow ) {
3797 this.$button.attr( 'rel', 'nofollow' );
3798 } else {
3799 this.$button.removeAttr( 'rel' );
3800 }
3801 }
3802
3803 return this;
3804 };
3805
3806 // Override method visibility hints from ButtonElement
3807 /**
3808 * @method setActive
3809 * @inheritdoc
3810 */
3811 /**
3812 * @method isActive
3813 * @inheritdoc
3814 */
3815
3816 /**
3817 * A ButtonGroupWidget groups related buttons and is used together with OO.ui.ButtonWidget and
3818 * its subclasses. Each button in a group is addressed by a unique reference. Buttons can be added,
3819 * removed, and cleared from the group.
3820 *
3821 * @example
3822 * // Example: A ButtonGroupWidget with two buttons
3823 * var button1 = new OO.ui.PopupButtonWidget( {
3824 * label: 'Select a category',
3825 * icon: 'menu',
3826 * popup: {
3827 * $content: $( '<p>List of categories...</p>' ),
3828 * padded: true,
3829 * align: 'left'
3830 * }
3831 * } );
3832 * var button2 = new OO.ui.ButtonWidget( {
3833 * label: 'Add item'
3834 * });
3835 * var buttonGroup = new OO.ui.ButtonGroupWidget( {
3836 * items: [button1, button2]
3837 * } );
3838 * $( 'body' ).append( buttonGroup.$element );
3839 *
3840 * @class
3841 * @extends OO.ui.Widget
3842 * @mixins OO.ui.mixin.GroupElement
3843 *
3844 * @constructor
3845 * @param {Object} [config] Configuration options
3846 * @cfg {OO.ui.ButtonWidget[]} [items] Buttons to add
3847 */
3848 OO.ui.ButtonGroupWidget = function OoUiButtonGroupWidget( config ) {
3849 // Configuration initialization
3850 config = config || {};
3851
3852 // Parent constructor
3853 OO.ui.ButtonGroupWidget.parent.call( this, config );
3854
3855 // Mixin constructors
3856 OO.ui.mixin.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) );
3857
3858 // Initialization
3859 this.$element.addClass( 'oo-ui-buttonGroupWidget' );
3860 if ( Array.isArray( config.items ) ) {
3861 this.addItems( config.items );
3862 }
3863 };
3864
3865 /* Setup */
3866
3867 OO.inheritClass( OO.ui.ButtonGroupWidget, OO.ui.Widget );
3868 OO.mixinClass( OO.ui.ButtonGroupWidget, OO.ui.mixin.GroupElement );
3869
3870 /* Static Properties */
3871
3872 /**
3873 * @static
3874 * @inheritdoc
3875 */
3876 OO.ui.ButtonGroupWidget.static.tagName = 'span';
3877
3878 /* Methods */
3879
3880 /**
3881 * Focus the widget
3882 *
3883 * @chainable
3884 */
3885 OO.ui.ButtonGroupWidget.prototype.focus = function () {
3886 if ( !this.isDisabled() ) {
3887 if ( this.items[ 0 ] ) {
3888 this.items[ 0 ].focus();
3889 }
3890 }
3891 return this;
3892 };
3893
3894 /**
3895 * @inheritdoc
3896 */
3897 OO.ui.ButtonGroupWidget.prototype.simulateLabelClick = function () {
3898 this.focus();
3899 };
3900
3901 /**
3902 * IconWidget is a generic widget for {@link OO.ui.mixin.IconElement icons}. In general, IconWidgets should be used with OO.ui.LabelWidget,
3903 * which creates a label that identifies the icon’s function. See the [OOUI documentation on MediaWiki] [1]
3904 * for a list of icons included in the library.
3905 *
3906 * @example
3907 * // An icon widget with a label
3908 * var myIcon = new OO.ui.IconWidget( {
3909 * icon: 'help',
3910 * iconTitle: 'Help'
3911 * } );
3912 * // Create a label.
3913 * var iconLabel = new OO.ui.LabelWidget( {
3914 * label: 'Help'
3915 * } );
3916 * $( 'body' ).append( myIcon.$element, iconLabel.$element );
3917 *
3918 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Icons,_Indicators,_and_Labels#Icons
3919 *
3920 * @class
3921 * @extends OO.ui.Widget
3922 * @mixins OO.ui.mixin.IconElement
3923 * @mixins OO.ui.mixin.TitledElement
3924 * @mixins OO.ui.mixin.FlaggedElement
3925 *
3926 * @constructor
3927 * @param {Object} [config] Configuration options
3928 */
3929 OO.ui.IconWidget = function OoUiIconWidget( config ) {
3930 // Configuration initialization
3931 config = config || {};
3932
3933 // Parent constructor
3934 OO.ui.IconWidget.parent.call( this, config );
3935
3936 // Mixin constructors
3937 OO.ui.mixin.IconElement.call( this, $.extend( {}, config, { $icon: this.$element } ) );
3938 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$element } ) );
3939 OO.ui.mixin.FlaggedElement.call( this, $.extend( {}, config, { $flagged: this.$element } ) );
3940
3941 // Initialization
3942 this.$element.addClass( 'oo-ui-iconWidget' );
3943 };
3944
3945 /* Setup */
3946
3947 OO.inheritClass( OO.ui.IconWidget, OO.ui.Widget );
3948 OO.mixinClass( OO.ui.IconWidget, OO.ui.mixin.IconElement );
3949 OO.mixinClass( OO.ui.IconWidget, OO.ui.mixin.TitledElement );
3950 OO.mixinClass( OO.ui.IconWidget, OO.ui.mixin.FlaggedElement );
3951
3952 /* Static Properties */
3953
3954 /**
3955 * @static
3956 * @inheritdoc
3957 */
3958 OO.ui.IconWidget.static.tagName = 'span';
3959
3960 /**
3961 * IndicatorWidgets create indicators, which are small graphics that are generally used to draw
3962 * attention to the status of an item or to clarify the function within a control. For a list of
3963 * indicators included in the library, please see the [OOUI documentation on MediaWiki][1].
3964 *
3965 * @example
3966 * // Example of an indicator widget
3967 * var indicator1 = new OO.ui.IndicatorWidget( {
3968 * indicator: 'required'
3969 * } );
3970 *
3971 * // Create a fieldset layout to add a label
3972 * var fieldset = new OO.ui.FieldsetLayout();
3973 * fieldset.addItems( [
3974 * new OO.ui.FieldLayout( indicator1, { label: 'A required indicator:' } )
3975 * ] );
3976 * $( 'body' ).append( fieldset.$element );
3977 *
3978 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Icons,_Indicators,_and_Labels#Indicators
3979 *
3980 * @class
3981 * @extends OO.ui.Widget
3982 * @mixins OO.ui.mixin.IndicatorElement
3983 * @mixins OO.ui.mixin.TitledElement
3984 *
3985 * @constructor
3986 * @param {Object} [config] Configuration options
3987 */
3988 OO.ui.IndicatorWidget = function OoUiIndicatorWidget( config ) {
3989 // Configuration initialization
3990 config = config || {};
3991
3992 // Parent constructor
3993 OO.ui.IndicatorWidget.parent.call( this, config );
3994
3995 // Mixin constructors
3996 OO.ui.mixin.IndicatorElement.call( this, $.extend( {}, config, { $indicator: this.$element } ) );
3997 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$element } ) );
3998
3999 // Initialization
4000 this.$element.addClass( 'oo-ui-indicatorWidget' );
4001 };
4002
4003 /* Setup */
4004
4005 OO.inheritClass( OO.ui.IndicatorWidget, OO.ui.Widget );
4006 OO.mixinClass( OO.ui.IndicatorWidget, OO.ui.mixin.IndicatorElement );
4007 OO.mixinClass( OO.ui.IndicatorWidget, OO.ui.mixin.TitledElement );
4008
4009 /* Static Properties */
4010
4011 /**
4012 * @static
4013 * @inheritdoc
4014 */
4015 OO.ui.IndicatorWidget.static.tagName = 'span';
4016
4017 /**
4018 * LabelWidgets help identify the function of interface elements. Each LabelWidget can
4019 * be configured with a `label` option that is set to a string, a label node, or a function:
4020 *
4021 * - String: a plaintext string
4022 * - jQuery selection: a jQuery selection, used for anything other than a plaintext label, e.g., a
4023 * label that includes a link or special styling, such as a gray color or additional graphical elements.
4024 * - Function: a function that will produce a string in the future. Functions are used
4025 * in cases where the value of the label is not currently defined.
4026 *
4027 * In addition, the LabelWidget can be associated with an {@link OO.ui.InputWidget input widget}, which
4028 * will come into focus when the label is clicked.
4029 *
4030 * @example
4031 * // Examples of LabelWidgets
4032 * var label1 = new OO.ui.LabelWidget( {
4033 * label: 'plaintext label'
4034 * } );
4035 * var label2 = new OO.ui.LabelWidget( {
4036 * label: $( '<a href="default.html">jQuery label</a>' )
4037 * } );
4038 * // Create a fieldset layout with fields for each example
4039 * var fieldset = new OO.ui.FieldsetLayout();
4040 * fieldset.addItems( [
4041 * new OO.ui.FieldLayout( label1 ),
4042 * new OO.ui.FieldLayout( label2 )
4043 * ] );
4044 * $( 'body' ).append( fieldset.$element );
4045 *
4046 * @class
4047 * @extends OO.ui.Widget
4048 * @mixins OO.ui.mixin.LabelElement
4049 * @mixins OO.ui.mixin.TitledElement
4050 *
4051 * @constructor
4052 * @param {Object} [config] Configuration options
4053 * @cfg {OO.ui.InputWidget} [input] {@link OO.ui.InputWidget Input widget} that uses the label.
4054 * Clicking the label will focus the specified input field.
4055 */
4056 OO.ui.LabelWidget = function OoUiLabelWidget( config ) {
4057 // Configuration initialization
4058 config = config || {};
4059
4060 // Parent constructor
4061 OO.ui.LabelWidget.parent.call( this, config );
4062
4063 // Mixin constructors
4064 OO.ui.mixin.LabelElement.call( this, $.extend( {}, config, { $label: this.$element } ) );
4065 OO.ui.mixin.TitledElement.call( this, config );
4066
4067 // Properties
4068 this.input = config.input;
4069
4070 // Initialization
4071 if ( this.input ) {
4072 if ( this.input.getInputId() ) {
4073 this.$element.attr( 'for', this.input.getInputId() );
4074 } else {
4075 this.$label.on( 'click', function () {
4076 this.input.simulateLabelClick();
4077 }.bind( this ) );
4078 }
4079 }
4080 this.$element.addClass( 'oo-ui-labelWidget' );
4081 };
4082
4083 /* Setup */
4084
4085 OO.inheritClass( OO.ui.LabelWidget, OO.ui.Widget );
4086 OO.mixinClass( OO.ui.LabelWidget, OO.ui.mixin.LabelElement );
4087 OO.mixinClass( OO.ui.LabelWidget, OO.ui.mixin.TitledElement );
4088
4089 /* Static Properties */
4090
4091 /**
4092 * @static
4093 * @inheritdoc
4094 */
4095 OO.ui.LabelWidget.static.tagName = 'label';
4096
4097 /**
4098 * PendingElement is a mixin that is used to create elements that notify users that something is happening
4099 * and that they should wait before proceeding. The pending state is visually represented with a pending
4100 * texture that appears in the head of a pending {@link OO.ui.ProcessDialog process dialog} or in the input
4101 * field of a {@link OO.ui.TextInputWidget text input widget}.
4102 *
4103 * Currently, {@link OO.ui.ActionWidget Action widgets}, which mix in this class, can also be marked as pending, but only when
4104 * used in {@link OO.ui.MessageDialog message dialogs}. The behavior is not currently supported for action widgets used
4105 * in process dialogs.
4106 *
4107 * @example
4108 * function MessageDialog( config ) {
4109 * MessageDialog.parent.call( this, config );
4110 * }
4111 * OO.inheritClass( MessageDialog, OO.ui.MessageDialog );
4112 *
4113 * MessageDialog.static.name = 'myMessageDialog';
4114 * MessageDialog.static.actions = [
4115 * { action: 'save', label: 'Done', flags: 'primary' },
4116 * { label: 'Cancel', flags: 'safe' }
4117 * ];
4118 *
4119 * MessageDialog.prototype.initialize = function () {
4120 * MessageDialog.parent.prototype.initialize.apply( this, arguments );
4121 * this.content = new OO.ui.PanelLayout( { $: this.$, padded: true } );
4122 * 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>' );
4123 * this.$body.append( this.content.$element );
4124 * };
4125 * MessageDialog.prototype.getBodyHeight = function () {
4126 * return 100;
4127 * }
4128 * MessageDialog.prototype.getActionProcess = function ( action ) {
4129 * var dialog = this;
4130 * if ( action === 'save' ) {
4131 * dialog.getActions().get({actions: 'save'})[0].pushPending();
4132 * return new OO.ui.Process()
4133 * .next( 1000 )
4134 * .next( function () {
4135 * dialog.getActions().get({actions: 'save'})[0].popPending();
4136 * } );
4137 * }
4138 * return MessageDialog.parent.prototype.getActionProcess.call( this, action );
4139 * };
4140 *
4141 * var windowManager = new OO.ui.WindowManager();
4142 * $( 'body' ).append( windowManager.$element );
4143 *
4144 * var dialog = new MessageDialog();
4145 * windowManager.addWindows( [ dialog ] );
4146 * windowManager.openWindow( dialog );
4147 *
4148 * @abstract
4149 * @class
4150 *
4151 * @constructor
4152 * @param {Object} [config] Configuration options
4153 * @cfg {jQuery} [$pending] Element to mark as pending, defaults to this.$element
4154 */
4155 OO.ui.mixin.PendingElement = function OoUiMixinPendingElement( config ) {
4156 // Configuration initialization
4157 config = config || {};
4158
4159 // Properties
4160 this.pending = 0;
4161 this.$pending = null;
4162
4163 // Initialisation
4164 this.setPendingElement( config.$pending || this.$element );
4165 };
4166
4167 /* Setup */
4168
4169 OO.initClass( OO.ui.mixin.PendingElement );
4170
4171 /* Methods */
4172
4173 /**
4174 * Set the pending element (and clean up any existing one).
4175 *
4176 * @param {jQuery} $pending The element to set to pending.
4177 */
4178 OO.ui.mixin.PendingElement.prototype.setPendingElement = function ( $pending ) {
4179 if ( this.$pending ) {
4180 this.$pending.removeClass( 'oo-ui-pendingElement-pending' );
4181 }
4182
4183 this.$pending = $pending;
4184 if ( this.pending > 0 ) {
4185 this.$pending.addClass( 'oo-ui-pendingElement-pending' );
4186 }
4187 };
4188
4189 /**
4190 * Check if an element is pending.
4191 *
4192 * @return {boolean} Element is pending
4193 */
4194 OO.ui.mixin.PendingElement.prototype.isPending = function () {
4195 return !!this.pending;
4196 };
4197
4198 /**
4199 * Increase the pending counter. The pending state will remain active until the counter is zero
4200 * (i.e., the number of calls to #pushPending and #popPending is the same).
4201 *
4202 * @chainable
4203 */
4204 OO.ui.mixin.PendingElement.prototype.pushPending = function () {
4205 if ( this.pending === 0 ) {
4206 this.$pending.addClass( 'oo-ui-pendingElement-pending' );
4207 this.updateThemeClasses();
4208 }
4209 this.pending++;
4210
4211 return this;
4212 };
4213
4214 /**
4215 * Decrease the pending counter. The pending state will remain active until the counter is zero
4216 * (i.e., the number of calls to #pushPending and #popPending is the same).
4217 *
4218 * @chainable
4219 */
4220 OO.ui.mixin.PendingElement.prototype.popPending = function () {
4221 if ( this.pending === 1 ) {
4222 this.$pending.removeClass( 'oo-ui-pendingElement-pending' );
4223 this.updateThemeClasses();
4224 }
4225 this.pending = Math.max( 0, this.pending - 1 );
4226
4227 return this;
4228 };
4229
4230 /**
4231 * Element that will stick adjacent to a specified container, even when it is inserted elsewhere
4232 * in the document (for example, in an OO.ui.Window's $overlay).
4233 *
4234 * The elements's position is automatically calculated and maintained when window is resized or the
4235 * page is scrolled. If you reposition the container manually, you have to call #position to make
4236 * sure the element is still placed correctly.
4237 *
4238 * As positioning is only possible when both the element and the container are attached to the DOM
4239 * and visible, it's only done after you call #togglePositioning. You might want to do this inside
4240 * the #toggle method to display a floating popup, for example.
4241 *
4242 * @abstract
4243 * @class
4244 *
4245 * @constructor
4246 * @param {Object} [config] Configuration options
4247 * @cfg {jQuery} [$floatable] Node to position, assigned to #$floatable, omit to use #$element
4248 * @cfg {jQuery} [$floatableContainer] Node to position adjacent to
4249 * @cfg {string} [verticalPosition='below'] Where to position $floatable vertically:
4250 * 'below': Directly below $floatableContainer, aligning f's top edge with fC's bottom edge
4251 * 'above': Directly above $floatableContainer, aligning f's bottom edge with fC's top edge
4252 * 'top': Align the top edge with $floatableContainer's top edge
4253 * 'bottom': Align the bottom edge with $floatableContainer's bottom edge
4254 * 'center': Vertically align the center with $floatableContainer's center
4255 * @cfg {string} [horizontalPosition='start'] Where to position $floatable horizontally:
4256 * 'before': Directly before $floatableContainer, aligning f's end edge with fC's start edge
4257 * 'after': Directly after $floatableContainer, algining f's start edge with fC's end edge
4258 * 'start': Align the start (left in LTR, right in RTL) edge with $floatableContainer's start edge
4259 * 'end': Align the end (right in LTR, left in RTL) edge with $floatableContainer's end edge
4260 * 'center': Horizontally align the center with $floatableContainer's center
4261 * @cfg {boolean} [hideWhenOutOfView=true] Whether to hide the floatable element if the container
4262 * is out of view
4263 */
4264 OO.ui.mixin.FloatableElement = function OoUiMixinFloatableElement( config ) {
4265 // Configuration initialization
4266 config = config || {};
4267
4268 // Properties
4269 this.$floatable = null;
4270 this.$floatableContainer = null;
4271 this.$floatableWindow = null;
4272 this.$floatableClosestScrollable = null;
4273 this.floatableOutOfView = false;
4274 this.onFloatableScrollHandler = this.position.bind( this );
4275 this.onFloatableWindowResizeHandler = this.position.bind( this );
4276
4277 // Initialization
4278 this.setFloatableContainer( config.$floatableContainer );
4279 this.setFloatableElement( config.$floatable || this.$element );
4280 this.setVerticalPosition( config.verticalPosition || 'below' );
4281 this.setHorizontalPosition( config.horizontalPosition || 'start' );
4282 this.hideWhenOutOfView = config.hideWhenOutOfView === undefined ? true : !!config.hideWhenOutOfView;
4283 };
4284
4285 /* Methods */
4286
4287 /**
4288 * Set floatable element.
4289 *
4290 * If an element is already set, it will be cleaned up before setting up the new element.
4291 *
4292 * @param {jQuery} $floatable Element to make floatable
4293 */
4294 OO.ui.mixin.FloatableElement.prototype.setFloatableElement = function ( $floatable ) {
4295 if ( this.$floatable ) {
4296 this.$floatable.removeClass( 'oo-ui-floatableElement-floatable' );
4297 this.$floatable.css( { left: '', top: '' } );
4298 }
4299
4300 this.$floatable = $floatable.addClass( 'oo-ui-floatableElement-floatable' );
4301 this.position();
4302 };
4303
4304 /**
4305 * Set floatable container.
4306 *
4307 * The element will be positioned relative to the specified container.
4308 *
4309 * @param {jQuery|null} $floatableContainer Container to keep visible, or null to unset
4310 */
4311 OO.ui.mixin.FloatableElement.prototype.setFloatableContainer = function ( $floatableContainer ) {
4312 this.$floatableContainer = $floatableContainer;
4313 if ( this.$floatable ) {
4314 this.position();
4315 }
4316 };
4317
4318 /**
4319 * Change how the element is positioned vertically.
4320 *
4321 * @param {string} position 'below', 'above', 'top', 'bottom' or 'center'
4322 */
4323 OO.ui.mixin.FloatableElement.prototype.setVerticalPosition = function ( position ) {
4324 if ( [ 'below', 'above', 'top', 'bottom', 'center' ].indexOf( position ) === -1 ) {
4325 throw new Error( 'Invalid value for vertical position: ' + position );
4326 }
4327 if ( this.verticalPosition !== position ) {
4328 this.verticalPosition = position;
4329 if ( this.$floatable ) {
4330 this.position();
4331 }
4332 }
4333 };
4334
4335 /**
4336 * Change how the element is positioned horizontally.
4337 *
4338 * @param {string} position 'before', 'after', 'start', 'end' or 'center'
4339 */
4340 OO.ui.mixin.FloatableElement.prototype.setHorizontalPosition = function ( position ) {
4341 if ( [ 'before', 'after', 'start', 'end', 'center' ].indexOf( position ) === -1 ) {
4342 throw new Error( 'Invalid value for horizontal position: ' + position );
4343 }
4344 if ( this.horizontalPosition !== position ) {
4345 this.horizontalPosition = position;
4346 if ( this.$floatable ) {
4347 this.position();
4348 }
4349 }
4350 };
4351
4352 /**
4353 * Toggle positioning.
4354 *
4355 * Do not turn positioning on until after the element is attached to the DOM and visible.
4356 *
4357 * @param {boolean} [positioning] Enable positioning, omit to toggle
4358 * @chainable
4359 */
4360 OO.ui.mixin.FloatableElement.prototype.togglePositioning = function ( positioning ) {
4361 var closestScrollableOfContainer;
4362
4363 if ( !this.$floatable || !this.$floatableContainer ) {
4364 return this;
4365 }
4366
4367 positioning = positioning === undefined ? !this.positioning : !!positioning;
4368
4369 if ( positioning && !this.warnedUnattached && !this.isElementAttached() ) {
4370 OO.ui.warnDeprecation( 'FloatableElement#togglePositioning: Before calling this method, the element must be attached to the DOM.' );
4371 this.warnedUnattached = true;
4372 }
4373
4374 if ( this.positioning !== positioning ) {
4375 this.positioning = positioning;
4376
4377 this.needsCustomPosition =
4378 this.verticalPostion !== 'below' ||
4379 this.horizontalPosition !== 'start' ||
4380 !OO.ui.contains( this.$floatableContainer[ 0 ], this.$floatable[ 0 ] );
4381
4382 closestScrollableOfContainer = OO.ui.Element.static.getClosestScrollableContainer( this.$floatableContainer[ 0 ] );
4383 // If the scrollable is the root, we have to listen to scroll events
4384 // on the window because of browser inconsistencies.
4385 if ( $( closestScrollableOfContainer ).is( 'html, body' ) ) {
4386 closestScrollableOfContainer = OO.ui.Element.static.getWindow( closestScrollableOfContainer );
4387 }
4388
4389 if ( positioning ) {
4390 this.$floatableWindow = $( this.getElementWindow() );
4391 this.$floatableWindow.on( 'resize', this.onFloatableWindowResizeHandler );
4392
4393 this.$floatableClosestScrollable = $( closestScrollableOfContainer );
4394 this.$floatableClosestScrollable.on( 'scroll', this.onFloatableScrollHandler );
4395
4396 // Initial position after visible
4397 this.position();
4398 } else {
4399 if ( this.$floatableWindow ) {
4400 this.$floatableWindow.off( 'resize', this.onFloatableWindowResizeHandler );
4401 this.$floatableWindow = null;
4402 }
4403
4404 if ( this.$floatableClosestScrollable ) {
4405 this.$floatableClosestScrollable.off( 'scroll', this.onFloatableScrollHandler );
4406 this.$floatableClosestScrollable = null;
4407 }
4408
4409 this.$floatable.css( { left: '', right: '', top: '' } );
4410 }
4411 }
4412
4413 return this;
4414 };
4415
4416 /**
4417 * Check whether the bottom edge of the given element is within the viewport of the given container.
4418 *
4419 * @private
4420 * @param {jQuery} $element
4421 * @param {jQuery} $container
4422 * @return {boolean}
4423 */
4424 OO.ui.mixin.FloatableElement.prototype.isElementInViewport = function ( $element, $container ) {
4425 var elemRect, contRect, topEdgeInBounds, bottomEdgeInBounds, leftEdgeInBounds, rightEdgeInBounds,
4426 startEdgeInBounds, endEdgeInBounds, viewportSpacing,
4427 direction = $element.css( 'direction' );
4428
4429 elemRect = $element[ 0 ].getBoundingClientRect();
4430 if ( $container[ 0 ] === window ) {
4431 viewportSpacing = OO.ui.getViewportSpacing();
4432 contRect = {
4433 top: 0,
4434 left: 0,
4435 right: document.documentElement.clientWidth,
4436 bottom: document.documentElement.clientHeight
4437 };
4438 contRect.top += viewportSpacing.top;
4439 contRect.left += viewportSpacing.left;
4440 contRect.right -= viewportSpacing.right;
4441 contRect.bottom -= viewportSpacing.bottom;
4442 } else {
4443 contRect = $container[ 0 ].getBoundingClientRect();
4444 }
4445
4446 topEdgeInBounds = elemRect.top >= contRect.top && elemRect.top <= contRect.bottom;
4447 bottomEdgeInBounds = elemRect.bottom >= contRect.top && elemRect.bottom <= contRect.bottom;
4448 leftEdgeInBounds = elemRect.left >= contRect.left && elemRect.left <= contRect.right;
4449 rightEdgeInBounds = elemRect.right >= contRect.left && elemRect.right <= contRect.right;
4450 if ( direction === 'rtl' ) {
4451 startEdgeInBounds = rightEdgeInBounds;
4452 endEdgeInBounds = leftEdgeInBounds;
4453 } else {
4454 startEdgeInBounds = leftEdgeInBounds;
4455 endEdgeInBounds = rightEdgeInBounds;
4456 }
4457
4458 if ( this.verticalPosition === 'below' && !bottomEdgeInBounds ) {
4459 return false;
4460 }
4461 if ( this.verticalPosition === 'above' && !topEdgeInBounds ) {
4462 return false;
4463 }
4464 if ( this.horizontalPosition === 'before' && !startEdgeInBounds ) {
4465 return false;
4466 }
4467 if ( this.horizontalPosition === 'after' && !endEdgeInBounds ) {
4468 return false;
4469 }
4470
4471 // The other positioning values are all about being inside the container,
4472 // so in those cases all we care about is that any part of the container is visible.
4473 return elemRect.top <= contRect.bottom && elemRect.bottom >= contRect.top &&
4474 elemRect.left <= contRect.right && elemRect.right >= contRect.left;
4475 };
4476
4477 /**
4478 * Check if the floatable is hidden to the user because it was offscreen.
4479 *
4480 * @return {boolean} Floatable is out of view
4481 */
4482 OO.ui.mixin.FloatableElement.prototype.isFloatableOutOfView = function () {
4483 return this.floatableOutOfView;
4484 };
4485
4486 /**
4487 * Position the floatable below its container.
4488 *
4489 * This should only be done when both of them are attached to the DOM and visible.
4490 *
4491 * @chainable
4492 */
4493 OO.ui.mixin.FloatableElement.prototype.position = function () {
4494 if ( !this.positioning ) {
4495 return this;
4496 }
4497
4498 if ( !(
4499 // To continue, some things need to be true:
4500 // The element must actually be in the DOM
4501 this.isElementAttached() && (
4502 // The closest scrollable is the current window
4503 this.$floatableClosestScrollable[ 0 ] === this.getElementWindow() ||
4504 // OR is an element in the element's DOM
4505 $.contains( this.getElementDocument(), this.$floatableClosestScrollable[ 0 ] )
4506 )
4507 ) ) {
4508 // Abort early if important parts of the widget are no longer attached to the DOM
4509 return this;
4510 }
4511
4512 this.floatableOutOfView = this.hideWhenOutOfView && !this.isElementInViewport( this.$floatableContainer, this.$floatableClosestScrollable );
4513 if ( this.floatableOutOfView ) {
4514 this.$floatable.addClass( 'oo-ui-element-hidden' );
4515 return this;
4516 } else {
4517 this.$floatable.removeClass( 'oo-ui-element-hidden' );
4518 }
4519
4520 if ( !this.needsCustomPosition ) {
4521 return this;
4522 }
4523
4524 this.$floatable.css( this.computePosition() );
4525
4526 // We updated the position, so re-evaluate the clipping state.
4527 // (ClippableElement does not listen to 'scroll' events on $floatableContainer's parent, and so
4528 // will not notice the need to update itself.)
4529 // TODO: This is terrible, we shouldn't need to know about ClippableElement at all here. Why does
4530 // it not listen to the right events in the right places?
4531 if ( this.clip ) {
4532 this.clip();
4533 }
4534
4535 return this;
4536 };
4537
4538 /**
4539 * Compute how #$floatable should be positioned based on the position of #$floatableContainer
4540 * and the positioning settings. This is a helper for #position that shouldn't be called directly,
4541 * but may be overridden by subclasses if they want to change or add to the positioning logic.
4542 *
4543 * @return {Object} New position to apply with .css(). Keys are 'top', 'left', 'bottom' and 'right'.
4544 */
4545 OO.ui.mixin.FloatableElement.prototype.computePosition = function () {
4546 var isBody, scrollableX, scrollableY, containerPos,
4547 horizScrollbarHeight, vertScrollbarWidth, scrollTop, scrollLeft,
4548 newPos = { top: '', left: '', bottom: '', right: '' },
4549 direction = this.$floatableContainer.css( 'direction' ),
4550 $offsetParent = this.$floatable.offsetParent();
4551
4552 if ( $offsetParent.is( 'html' ) ) {
4553 // The innerHeight/Width and clientHeight/Width calculations don't work well on the
4554 // <html> element, but they do work on the <body>
4555 $offsetParent = $( $offsetParent[ 0 ].ownerDocument.body );
4556 }
4557 isBody = $offsetParent.is( 'body' );
4558 scrollableX = $offsetParent.css( 'overflow-x' ) === 'scroll' || $offsetParent.css( 'overflow-x' ) === 'auto';
4559 scrollableY = $offsetParent.css( 'overflow-y' ) === 'scroll' || $offsetParent.css( 'overflow-y' ) === 'auto';
4560
4561 vertScrollbarWidth = $offsetParent.innerWidth() - $offsetParent.prop( 'clientWidth' );
4562 horizScrollbarHeight = $offsetParent.innerHeight() - $offsetParent.prop( 'clientHeight' );
4563 // We don't need to compute and add scrollTop and scrollLeft if the scrollable container is the body,
4564 // or if it isn't scrollable
4565 scrollTop = scrollableY && !isBody ? $offsetParent.scrollTop() : 0;
4566 scrollLeft = scrollableX && !isBody ? OO.ui.Element.static.getScrollLeft( $offsetParent[ 0 ] ) : 0;
4567
4568 // Avoid passing the <body> to getRelativePosition(), because it won't return what we expect
4569 // if the <body> has a margin
4570 containerPos = isBody ?
4571 this.$floatableContainer.offset() :
4572 OO.ui.Element.static.getRelativePosition( this.$floatableContainer, $offsetParent );
4573 containerPos.bottom = containerPos.top + this.$floatableContainer.outerHeight();
4574 containerPos.right = containerPos.left + this.$floatableContainer.outerWidth();
4575 containerPos.start = direction === 'rtl' ? containerPos.right : containerPos.left;
4576 containerPos.end = direction === 'rtl' ? containerPos.left : containerPos.right;
4577
4578 if ( this.verticalPosition === 'below' ) {
4579 newPos.top = containerPos.bottom;
4580 } else if ( this.verticalPosition === 'above' ) {
4581 newPos.bottom = $offsetParent.outerHeight() - containerPos.top;
4582 } else if ( this.verticalPosition === 'top' ) {
4583 newPos.top = containerPos.top;
4584 } else if ( this.verticalPosition === 'bottom' ) {
4585 newPos.bottom = $offsetParent.outerHeight() - containerPos.bottom;
4586 } else if ( this.verticalPosition === 'center' ) {
4587 newPos.top = containerPos.top +
4588 ( this.$floatableContainer.height() - this.$floatable.height() ) / 2;
4589 }
4590
4591 if ( this.horizontalPosition === 'before' ) {
4592 newPos.end = containerPos.start;
4593 } else if ( this.horizontalPosition === 'after' ) {
4594 newPos.start = containerPos.end;
4595 } else if ( this.horizontalPosition === 'start' ) {
4596 newPos.start = containerPos.start;
4597 } else if ( this.horizontalPosition === 'end' ) {
4598 newPos.end = containerPos.end;
4599 } else if ( this.horizontalPosition === 'center' ) {
4600 newPos.left = containerPos.left +
4601 ( this.$floatableContainer.width() - this.$floatable.width() ) / 2;
4602 }
4603
4604 if ( newPos.start !== undefined ) {
4605 if ( direction === 'rtl' ) {
4606 newPos.right = ( isBody ? $( $offsetParent[ 0 ].ownerDocument.documentElement ) : $offsetParent ).outerWidth() - newPos.start;
4607 } else {
4608 newPos.left = newPos.start;
4609 }
4610 delete newPos.start;
4611 }
4612 if ( newPos.end !== undefined ) {
4613 if ( direction === 'rtl' ) {
4614 newPos.left = newPos.end;
4615 } else {
4616 newPos.right = ( isBody ? $( $offsetParent[ 0 ].ownerDocument.documentElement ) : $offsetParent ).outerWidth() - newPos.end;
4617 }
4618 delete newPos.end;
4619 }
4620
4621 // Account for scroll position
4622 if ( newPos.top !== '' ) {
4623 newPos.top += scrollTop;
4624 }
4625 if ( newPos.bottom !== '' ) {
4626 newPos.bottom -= scrollTop;
4627 }
4628 if ( newPos.left !== '' ) {
4629 newPos.left += scrollLeft;
4630 }
4631 if ( newPos.right !== '' ) {
4632 newPos.right -= scrollLeft;
4633 }
4634
4635 // Account for scrollbar gutter
4636 if ( newPos.bottom !== '' ) {
4637 newPos.bottom -= horizScrollbarHeight;
4638 }
4639 if ( direction === 'rtl' ) {
4640 if ( newPos.left !== '' ) {
4641 newPos.left -= vertScrollbarWidth;
4642 }
4643 } else {
4644 if ( newPos.right !== '' ) {
4645 newPos.right -= vertScrollbarWidth;
4646 }
4647 }
4648
4649 return newPos;
4650 };
4651
4652 /**
4653 * Element that can be automatically clipped to visible boundaries.
4654 *
4655 * Whenever the element's natural height changes, you have to call
4656 * {@link OO.ui.mixin.ClippableElement#clip} to make sure it's still
4657 * clipping correctly.
4658 *
4659 * The dimensions of #$clippableContainer will be compared to the boundaries of the
4660 * nearest scrollable container. If #$clippableContainer is too tall and/or too wide,
4661 * then #$clippable will be given a fixed reduced height and/or width and will be made
4662 * scrollable. By default, #$clippable and #$clippableContainer are the same element,
4663 * but you can build a static footer by setting #$clippableContainer to an element that contains
4664 * #$clippable and the footer.
4665 *
4666 * @abstract
4667 * @class
4668 *
4669 * @constructor
4670 * @param {Object} [config] Configuration options
4671 * @cfg {jQuery} [$clippable] Node to clip, assigned to #$clippable, omit to use #$element
4672 * @cfg {jQuery} [$clippableContainer] Node to keep visible, assigned to #$clippableContainer,
4673 * omit to use #$clippable
4674 */
4675 OO.ui.mixin.ClippableElement = function OoUiMixinClippableElement( config ) {
4676 // Configuration initialization
4677 config = config || {};
4678
4679 // Properties
4680 this.$clippable = null;
4681 this.$clippableContainer = null;
4682 this.clipping = false;
4683 this.clippedHorizontally = false;
4684 this.clippedVertically = false;
4685 this.$clippableScrollableContainer = null;
4686 this.$clippableScroller = null;
4687 this.$clippableWindow = null;
4688 this.idealWidth = null;
4689 this.idealHeight = null;
4690 this.onClippableScrollHandler = this.clip.bind( this );
4691 this.onClippableWindowResizeHandler = this.clip.bind( this );
4692
4693 // Initialization
4694 if ( config.$clippableContainer ) {
4695 this.setClippableContainer( config.$clippableContainer );
4696 }
4697 this.setClippableElement( config.$clippable || this.$element );
4698 };
4699
4700 /* Methods */
4701
4702 /**
4703 * Set clippable element.
4704 *
4705 * If an element is already set, it will be cleaned up before setting up the new element.
4706 *
4707 * @param {jQuery} $clippable Element to make clippable
4708 */
4709 OO.ui.mixin.ClippableElement.prototype.setClippableElement = function ( $clippable ) {
4710 if ( this.$clippable ) {
4711 this.$clippable.removeClass( 'oo-ui-clippableElement-clippable' );
4712 this.$clippable.css( { width: '', height: '', overflowX: '', overflowY: '' } );
4713 OO.ui.Element.static.reconsiderScrollbars( this.$clippable[ 0 ] );
4714 }
4715
4716 this.$clippable = $clippable.addClass( 'oo-ui-clippableElement-clippable' );
4717 this.clip();
4718 };
4719
4720 /**
4721 * Set clippable container.
4722 *
4723 * This is the container that will be measured when deciding whether to clip. When clipping,
4724 * #$clippable will be resized in order to keep the clippable container fully visible.
4725 *
4726 * If the clippable container is unset, #$clippable will be used.
4727 *
4728 * @param {jQuery|null} $clippableContainer Container to keep visible, or null to unset
4729 */
4730 OO.ui.mixin.ClippableElement.prototype.setClippableContainer = function ( $clippableContainer ) {
4731 this.$clippableContainer = $clippableContainer;
4732 if ( this.$clippable ) {
4733 this.clip();
4734 }
4735 };
4736
4737 /**
4738 * Toggle clipping.
4739 *
4740 * Do not turn clipping on until after the element is attached to the DOM and visible.
4741 *
4742 * @param {boolean} [clipping] Enable clipping, omit to toggle
4743 * @chainable
4744 */
4745 OO.ui.mixin.ClippableElement.prototype.toggleClipping = function ( clipping ) {
4746 clipping = clipping === undefined ? !this.clipping : !!clipping;
4747
4748 if ( clipping && !this.warnedUnattached && !this.isElementAttached() ) {
4749 OO.ui.warnDeprecation( 'ClippableElement#toggleClipping: Before calling this method, the element must be attached to the DOM.' );
4750 this.warnedUnattached = true;
4751 }
4752
4753 if ( this.clipping !== clipping ) {
4754 this.clipping = clipping;
4755 if ( clipping ) {
4756 this.$clippableScrollableContainer = $( this.getClosestScrollableElementContainer() );
4757 // If the clippable container is the root, we have to listen to scroll events and check
4758 // jQuery.scrollTop on the window because of browser inconsistencies
4759 this.$clippableScroller = this.$clippableScrollableContainer.is( 'html, body' ) ?
4760 $( OO.ui.Element.static.getWindow( this.$clippableScrollableContainer ) ) :
4761 this.$clippableScrollableContainer;
4762 this.$clippableScroller.on( 'scroll', this.onClippableScrollHandler );
4763 this.$clippableWindow = $( this.getElementWindow() )
4764 .on( 'resize', this.onClippableWindowResizeHandler );
4765 // Initial clip after visible
4766 this.clip();
4767 } else {
4768 this.$clippable.css( {
4769 width: '',
4770 height: '',
4771 maxWidth: '',
4772 maxHeight: '',
4773 overflowX: '',
4774 overflowY: ''
4775 } );
4776 OO.ui.Element.static.reconsiderScrollbars( this.$clippable[ 0 ] );
4777
4778 this.$clippableScrollableContainer = null;
4779 this.$clippableScroller.off( 'scroll', this.onClippableScrollHandler );
4780 this.$clippableScroller = null;
4781 this.$clippableWindow.off( 'resize', this.onClippableWindowResizeHandler );
4782 this.$clippableWindow = null;
4783 }
4784 }
4785
4786 return this;
4787 };
4788
4789 /**
4790 * Check if the element will be clipped to fit the visible area of the nearest scrollable container.
4791 *
4792 * @return {boolean} Element will be clipped to the visible area
4793 */
4794 OO.ui.mixin.ClippableElement.prototype.isClipping = function () {
4795 return this.clipping;
4796 };
4797
4798 /**
4799 * Check if the bottom or right of the element is being clipped by the nearest scrollable container.
4800 *
4801 * @return {boolean} Part of the element is being clipped
4802 */
4803 OO.ui.mixin.ClippableElement.prototype.isClipped = function () {
4804 return this.clippedHorizontally || this.clippedVertically;
4805 };
4806
4807 /**
4808 * Check if the right of the element is being clipped by the nearest scrollable container.
4809 *
4810 * @return {boolean} Part of the element is being clipped
4811 */
4812 OO.ui.mixin.ClippableElement.prototype.isClippedHorizontally = function () {
4813 return this.clippedHorizontally;
4814 };
4815
4816 /**
4817 * Check if the bottom of the element is being clipped by the nearest scrollable container.
4818 *
4819 * @return {boolean} Part of the element is being clipped
4820 */
4821 OO.ui.mixin.ClippableElement.prototype.isClippedVertically = function () {
4822 return this.clippedVertically;
4823 };
4824
4825 /**
4826 * Set the ideal size. These are the dimensions #$clippable will have when it's not being clipped.
4827 *
4828 * @param {number|string} [width] Width as a number of pixels or CSS string with unit suffix
4829 * @param {number|string} [height] Height as a number of pixels or CSS string with unit suffix
4830 */
4831 OO.ui.mixin.ClippableElement.prototype.setIdealSize = function ( width, height ) {
4832 this.idealWidth = width;
4833 this.idealHeight = height;
4834
4835 if ( !this.clipping ) {
4836 // Update dimensions
4837 this.$clippable.css( { width: width, height: height } );
4838 }
4839 // While clipping, idealWidth and idealHeight are not considered
4840 };
4841
4842 /**
4843 * Return the side of the clippable on which it is "anchored" (aligned to something else).
4844 * ClippableElement will clip the opposite side when reducing element's width.
4845 *
4846 * Classes that mix in ClippableElement should override this to return 'right' if their
4847 * clippable is absolutely positioned and using 'right: Npx' (and not using 'left').
4848 * If your class also mixes in FloatableElement, this is handled automatically.
4849 *
4850 * (This can't be guessed from the actual CSS because the computed values for 'left'/'right' are
4851 * always in pixels, even if they were unset or set to 'auto'.)
4852 *
4853 * When in doubt, 'left' (or 'right' in RTL) is a sane fallback.
4854 *
4855 * @return {string} 'left' or 'right'
4856 */
4857 OO.ui.mixin.ClippableElement.prototype.getHorizontalAnchorEdge = function () {
4858 if ( this.computePosition && this.positioning && this.computePosition().right !== '' ) {
4859 return 'right';
4860 }
4861 return 'left';
4862 };
4863
4864 /**
4865 * Return the side of the clippable on which it is "anchored" (aligned to something else).
4866 * ClippableElement will clip the opposite side when reducing element's width.
4867 *
4868 * Classes that mix in ClippableElement should override this to return 'bottom' if their
4869 * clippable is absolutely positioned and using 'bottom: Npx' (and not using 'top').
4870 * If your class also mixes in FloatableElement, this is handled automatically.
4871 *
4872 * (This can't be guessed from the actual CSS because the computed values for 'left'/'right' are
4873 * always in pixels, even if they were unset or set to 'auto'.)
4874 *
4875 * When in doubt, 'top' is a sane fallback.
4876 *
4877 * @return {string} 'top' or 'bottom'
4878 */
4879 OO.ui.mixin.ClippableElement.prototype.getVerticalAnchorEdge = function () {
4880 if ( this.computePosition && this.positioning && this.computePosition().bottom !== '' ) {
4881 return 'bottom';
4882 }
4883 return 'top';
4884 };
4885
4886 /**
4887 * Clip element to visible boundaries and allow scrolling when needed. You should call this method
4888 * when the element's natural height changes.
4889 *
4890 * Element will be clipped the bottom or right of the element is within 10px of the edge of, or
4891 * overlapped by, the visible area of the nearest scrollable container.
4892 *
4893 * Because calling clip() when the natural height changes isn't always possible, we also set
4894 * max-height when the element isn't being clipped. This means that if the element tries to grow
4895 * beyond the edge, something reasonable will happen before clip() is called.
4896 *
4897 * @chainable
4898 */
4899 OO.ui.mixin.ClippableElement.prototype.clip = function () {
4900 var extraHeight, extraWidth, viewportSpacing,
4901 desiredWidth, desiredHeight, allotedWidth, allotedHeight,
4902 naturalWidth, naturalHeight, clipWidth, clipHeight,
4903 $item, itemRect, $viewport, viewportRect, availableRect,
4904 direction, vertScrollbarWidth, horizScrollbarHeight,
4905 // Extra tolerance so that the sloppy code below doesn't result in results that are off
4906 // by one or two pixels. (And also so that we have space to display drop shadows.)
4907 // Chosen by fair dice roll.
4908 buffer = 7;
4909
4910 if ( !this.clipping ) {
4911 // this.$clippableScrollableContainer and this.$clippableWindow are null, so the below will fail
4912 return this;
4913 }
4914
4915 function rectIntersection( a, b ) {
4916 var out = {};
4917 out.top = Math.max( a.top, b.top );
4918 out.left = Math.max( a.left, b.left );
4919 out.bottom = Math.min( a.bottom, b.bottom );
4920 out.right = Math.min( a.right, b.right );
4921 return out;
4922 }
4923
4924 viewportSpacing = OO.ui.getViewportSpacing();
4925
4926 if ( this.$clippableScrollableContainer.is( 'html, body' ) ) {
4927 $viewport = $( this.$clippableScrollableContainer[ 0 ].ownerDocument.body );
4928 // Dimensions of the browser window, rather than the element!
4929 viewportRect = {
4930 top: 0,
4931 left: 0,
4932 right: document.documentElement.clientWidth,
4933 bottom: document.documentElement.clientHeight
4934 };
4935 viewportRect.top += viewportSpacing.top;
4936 viewportRect.left += viewportSpacing.left;
4937 viewportRect.right -= viewportSpacing.right;
4938 viewportRect.bottom -= viewportSpacing.bottom;
4939 } else {
4940 $viewport = this.$clippableScrollableContainer;
4941 viewportRect = $viewport[ 0 ].getBoundingClientRect();
4942 // Convert into a plain object
4943 viewportRect = $.extend( {}, viewportRect );
4944 }
4945
4946 // Account for scrollbar gutter
4947 direction = $viewport.css( 'direction' );
4948 vertScrollbarWidth = $viewport.innerWidth() - $viewport.prop( 'clientWidth' );
4949 horizScrollbarHeight = $viewport.innerHeight() - $viewport.prop( 'clientHeight' );
4950 viewportRect.bottom -= horizScrollbarHeight;
4951 if ( direction === 'rtl' ) {
4952 viewportRect.left += vertScrollbarWidth;
4953 } else {
4954 viewportRect.right -= vertScrollbarWidth;
4955 }
4956
4957 // Add arbitrary tolerance
4958 viewportRect.top += buffer;
4959 viewportRect.left += buffer;
4960 viewportRect.right -= buffer;
4961 viewportRect.bottom -= buffer;
4962
4963 $item = this.$clippableContainer || this.$clippable;
4964
4965 extraHeight = $item.outerHeight() - this.$clippable.outerHeight();
4966 extraWidth = $item.outerWidth() - this.$clippable.outerWidth();
4967
4968 itemRect = $item[ 0 ].getBoundingClientRect();
4969 // Convert into a plain object
4970 itemRect = $.extend( {}, itemRect );
4971
4972 // Item might already be clipped, so we can't just use its dimensions (in case we might need to
4973 // make it larger than before). Extend the rectangle to the maximum size we are allowed to take.
4974 if ( this.getHorizontalAnchorEdge() === 'right' ) {
4975 itemRect.left = viewportRect.left;
4976 } else {
4977 itemRect.right = viewportRect.right;
4978 }
4979 if ( this.getVerticalAnchorEdge() === 'bottom' ) {
4980 itemRect.top = viewportRect.top;
4981 } else {
4982 itemRect.bottom = viewportRect.bottom;
4983 }
4984
4985 availableRect = rectIntersection( viewportRect, itemRect );
4986
4987 desiredWidth = Math.max( 0, availableRect.right - availableRect.left );
4988 desiredHeight = Math.max( 0, availableRect.bottom - availableRect.top );
4989 // It should never be desirable to exceed the dimensions of the browser viewport... right?
4990 desiredWidth = Math.min( desiredWidth,
4991 document.documentElement.clientWidth - viewportSpacing.left - viewportSpacing.right );
4992 desiredHeight = Math.min( desiredHeight,
4993 document.documentElement.clientHeight - viewportSpacing.top - viewportSpacing.right );
4994 allotedWidth = Math.ceil( desiredWidth - extraWidth );
4995 allotedHeight = Math.ceil( desiredHeight - extraHeight );
4996 naturalWidth = this.$clippable.prop( 'scrollWidth' );
4997 naturalHeight = this.$clippable.prop( 'scrollHeight' );
4998 clipWidth = allotedWidth < naturalWidth;
4999 clipHeight = allotedHeight < naturalHeight;
5000
5001 if ( clipWidth ) {
5002 // The order matters here. If overflow is not set first, Chrome displays bogus scrollbars. See T157672.
5003 // Forcing a reflow is a smaller workaround than calling reconsiderScrollbars() for this case.
5004 this.$clippable.css( 'overflowX', 'scroll' );
5005 void this.$clippable[ 0 ].offsetHeight; // Force reflow
5006 this.$clippable.css( {
5007 width: Math.max( 0, allotedWidth ),
5008 maxWidth: ''
5009 } );
5010 } else {
5011 this.$clippable.css( {
5012 overflowX: '',
5013 width: this.idealWidth || '',
5014 maxWidth: Math.max( 0, allotedWidth )
5015 } );
5016 }
5017 if ( clipHeight ) {
5018 // The order matters here. If overflow is not set first, Chrome displays bogus scrollbars. See T157672.
5019 // Forcing a reflow is a smaller workaround than calling reconsiderScrollbars() for this case.
5020 this.$clippable.css( 'overflowY', 'scroll' );
5021 void this.$clippable[ 0 ].offsetHeight; // Force reflow
5022 this.$clippable.css( {
5023 height: Math.max( 0, allotedHeight ),
5024 maxHeight: ''
5025 } );
5026 } else {
5027 this.$clippable.css( {
5028 overflowY: '',
5029 height: this.idealHeight || '',
5030 maxHeight: Math.max( 0, allotedHeight )
5031 } );
5032 }
5033
5034 // If we stopped clipping in at least one of the dimensions
5035 if ( ( this.clippedHorizontally && !clipWidth ) || ( this.clippedVertically && !clipHeight ) ) {
5036 OO.ui.Element.static.reconsiderScrollbars( this.$clippable[ 0 ] );
5037 }
5038
5039 this.clippedHorizontally = clipWidth;
5040 this.clippedVertically = clipHeight;
5041
5042 return this;
5043 };
5044
5045 /**
5046 * PopupWidget is a container for content. The popup is overlaid and positioned absolutely.
5047 * By default, each popup has an anchor that points toward its origin.
5048 * Please see the [OOUI documentation on Mediawiki] [1] for more information and examples.
5049 *
5050 * Unlike most widgets, PopupWidget is initially hidden and must be shown by calling #toggle.
5051 *
5052 * @example
5053 * // A popup widget.
5054 * var popup = new OO.ui.PopupWidget( {
5055 * $content: $( '<p>Hi there!</p>' ),
5056 * padded: true,
5057 * width: 300
5058 * } );
5059 *
5060 * $( 'body' ).append( popup.$element );
5061 * // To display the popup, toggle the visibility to 'true'.
5062 * popup.toggle( true );
5063 *
5064 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Popups
5065 *
5066 * @class
5067 * @extends OO.ui.Widget
5068 * @mixins OO.ui.mixin.LabelElement
5069 * @mixins OO.ui.mixin.ClippableElement
5070 * @mixins OO.ui.mixin.FloatableElement
5071 *
5072 * @constructor
5073 * @param {Object} [config] Configuration options
5074 * @cfg {number} [width=320] Width of popup in pixels
5075 * @cfg {number} [height] Height of popup in pixels. Omit to use the automatic height.
5076 * @cfg {boolean} [anchor=true] Show anchor pointing to origin of popup
5077 * @cfg {string} [position='below'] Where to position the popup relative to $floatableContainer
5078 * 'above': Put popup above $floatableContainer; anchor points down to the horizontal center
5079 * of $floatableContainer
5080 * 'below': Put popup below $floatableContainer; anchor points up to the horizontal center
5081 * of $floatableContainer
5082 * 'before': Put popup to the left (LTR) / right (RTL) of $floatableContainer; anchor points
5083 * endwards (right/left) to the vertical center of $floatableContainer
5084 * 'after': Put popup to the right (LTR) / left (RTL) of $floatableContainer; anchor points
5085 * startwards (left/right) to the vertical center of $floatableContainer
5086 * @cfg {string} [align='center'] How to align the popup to $floatableContainer
5087 * 'forwards': If position is above/below, move the popup as far endwards (right in LTR, left in RTL)
5088 * as possible while still keeping the anchor within the popup;
5089 * if position is before/after, move the popup as far downwards as possible.
5090 * 'backwards': If position is above/below, move the popup as far startwards (left in LTR, right in RTL)
5091 * as possible while still keeping the anchor within the popup;
5092 * if position in before/after, move the popup as far upwards as possible.
5093 * 'center': Horizontally (if position is above/below) or vertically (before/after) align the center
5094 * of the popup with the center of $floatableContainer.
5095 * 'force-left': Alias for 'forwards' in LTR and 'backwards' in RTL
5096 * 'force-right': Alias for 'backwards' in RTL and 'forwards' in LTR
5097 * @cfg {boolean} [autoFlip=true] Whether to automatically switch the popup's position between
5098 * 'above' and 'below', or between 'before' and 'after', if there is not enough space in the
5099 * desired direction to display the popup without clipping
5100 * @cfg {jQuery} [$container] Constrain the popup to the boundaries of the specified container.
5101 * See the [OOUI docs on MediaWiki][3] for an example.
5102 * [3]: https://www.mediawiki.org/wiki/OOUI/Widgets/Popups#containerExample
5103 * @cfg {number} [containerPadding=10] Padding between the popup and its container, specified as a number of pixels.
5104 * @cfg {jQuery} [$content] Content to append to the popup's body
5105 * @cfg {jQuery} [$footer] Content to append to the popup's footer
5106 * @cfg {boolean} [autoClose=false] Automatically close the popup when it loses focus.
5107 * @cfg {jQuery} [$autoCloseIgnore] Elements that will not close the popup when clicked.
5108 * This config option is only relevant if #autoClose is set to `true`. See the [OOUI documentation on MediaWiki][2]
5109 * for an example.
5110 * [2]: https://www.mediawiki.org/wiki/OOUI/Widgets/Popups#autocloseExample
5111 * @cfg {boolean} [head=false] Show a popup header that contains a #label (if specified) and close
5112 * button.
5113 * @cfg {boolean} [padded=false] Add padding to the popup's body
5114 */
5115 OO.ui.PopupWidget = function OoUiPopupWidget( config ) {
5116 // Configuration initialization
5117 config = config || {};
5118
5119 // Parent constructor
5120 OO.ui.PopupWidget.parent.call( this, config );
5121
5122 // Properties (must be set before ClippableElement constructor call)
5123 this.$body = $( '<div>' );
5124 this.$popup = $( '<div>' );
5125
5126 // Mixin constructors
5127 OO.ui.mixin.LabelElement.call( this, config );
5128 OO.ui.mixin.ClippableElement.call( this, $.extend( {}, config, {
5129 $clippable: this.$body,
5130 $clippableContainer: this.$popup
5131 } ) );
5132 OO.ui.mixin.FloatableElement.call( this, config );
5133
5134 // Properties
5135 this.$anchor = $( '<div>' );
5136 // If undefined, will be computed lazily in computePosition()
5137 this.$container = config.$container;
5138 this.containerPadding = config.containerPadding !== undefined ? config.containerPadding : 10;
5139 this.autoClose = !!config.autoClose;
5140 this.$autoCloseIgnore = config.$autoCloseIgnore;
5141 this.transitionTimeout = null;
5142 this.anchored = false;
5143 this.width = config.width !== undefined ? config.width : 320;
5144 this.height = config.height !== undefined ? config.height : null;
5145 this.onMouseDownHandler = this.onMouseDown.bind( this );
5146 this.onDocumentKeyDownHandler = this.onDocumentKeyDown.bind( this );
5147
5148 // Initialization
5149 this.toggleAnchor( config.anchor === undefined || config.anchor );
5150 this.setAlignment( config.align || 'center' );
5151 this.setPosition( config.position || 'below' );
5152 this.setAutoFlip( config.autoFlip === undefined || config.autoFlip );
5153 this.$body.addClass( 'oo-ui-popupWidget-body' );
5154 this.$anchor.addClass( 'oo-ui-popupWidget-anchor' );
5155 this.$popup
5156 .addClass( 'oo-ui-popupWidget-popup' )
5157 .append( this.$body );
5158 this.$element
5159 .addClass( 'oo-ui-popupWidget' )
5160 .append( this.$popup, this.$anchor );
5161 // Move content, which was added to #$element by OO.ui.Widget, to the body
5162 // FIXME This is gross, we should use '$body' or something for the config
5163 if ( config.$content instanceof jQuery ) {
5164 this.$body.append( config.$content );
5165 }
5166
5167 if ( config.padded ) {
5168 this.$body.addClass( 'oo-ui-popupWidget-body-padded' );
5169 }
5170
5171 if ( config.head ) {
5172 this.closeButton = new OO.ui.ButtonWidget( { framed: false, icon: 'close' } );
5173 this.closeButton.connect( this, { click: 'onCloseButtonClick' } );
5174 this.$head = $( '<div>' )
5175 .addClass( 'oo-ui-popupWidget-head' )
5176 .append( this.$label, this.closeButton.$element );
5177 this.$popup.prepend( this.$head );
5178 }
5179
5180 if ( config.$footer ) {
5181 this.$footer = $( '<div>' )
5182 .addClass( 'oo-ui-popupWidget-footer' )
5183 .append( config.$footer );
5184 this.$popup.append( this.$footer );
5185 }
5186
5187 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
5188 // that reference properties not initialized at that time of parent class construction
5189 // TODO: Find a better way to handle post-constructor setup
5190 this.visible = false;
5191 this.$element.addClass( 'oo-ui-element-hidden' );
5192 };
5193
5194 /* Setup */
5195
5196 OO.inheritClass( OO.ui.PopupWidget, OO.ui.Widget );
5197 OO.mixinClass( OO.ui.PopupWidget, OO.ui.mixin.LabelElement );
5198 OO.mixinClass( OO.ui.PopupWidget, OO.ui.mixin.ClippableElement );
5199 OO.mixinClass( OO.ui.PopupWidget, OO.ui.mixin.FloatableElement );
5200
5201 /* Events */
5202
5203 /**
5204 * @event ready
5205 *
5206 * The popup is ready: it is visible and has been positioned and clipped.
5207 */
5208
5209 /* Methods */
5210
5211 /**
5212 * Handles mouse down events.
5213 *
5214 * @private
5215 * @param {MouseEvent} e Mouse down event
5216 */
5217 OO.ui.PopupWidget.prototype.onMouseDown = function ( e ) {
5218 if (
5219 this.isVisible() &&
5220 !OO.ui.contains( this.$element.add( this.$autoCloseIgnore ).get(), e.target, true )
5221 ) {
5222 this.toggle( false );
5223 }
5224 };
5225
5226 /**
5227 * Bind mouse down listener.
5228 *
5229 * @private
5230 */
5231 OO.ui.PopupWidget.prototype.bindMouseDownListener = function () {
5232 // Capture clicks outside popup
5233 this.getElementWindow().addEventListener( 'mousedown', this.onMouseDownHandler, true );
5234 };
5235
5236 /**
5237 * Handles close button click events.
5238 *
5239 * @private
5240 */
5241 OO.ui.PopupWidget.prototype.onCloseButtonClick = function () {
5242 if ( this.isVisible() ) {
5243 this.toggle( false );
5244 }
5245 };
5246
5247 /**
5248 * Unbind mouse down listener.
5249 *
5250 * @private
5251 */
5252 OO.ui.PopupWidget.prototype.unbindMouseDownListener = function () {
5253 this.getElementWindow().removeEventListener( 'mousedown', this.onMouseDownHandler, true );
5254 };
5255
5256 /**
5257 * Handles key down events.
5258 *
5259 * @private
5260 * @param {KeyboardEvent} e Key down event
5261 */
5262 OO.ui.PopupWidget.prototype.onDocumentKeyDown = function ( e ) {
5263 if (
5264 e.which === OO.ui.Keys.ESCAPE &&
5265 this.isVisible()
5266 ) {
5267 this.toggle( false );
5268 e.preventDefault();
5269 e.stopPropagation();
5270 }
5271 };
5272
5273 /**
5274 * Bind key down listener.
5275 *
5276 * @private
5277 */
5278 OO.ui.PopupWidget.prototype.bindKeyDownListener = function () {
5279 this.getElementWindow().addEventListener( 'keydown', this.onDocumentKeyDownHandler, true );
5280 };
5281
5282 /**
5283 * Unbind key down listener.
5284 *
5285 * @private
5286 */
5287 OO.ui.PopupWidget.prototype.unbindKeyDownListener = function () {
5288 this.getElementWindow().removeEventListener( 'keydown', this.onDocumentKeyDownHandler, true );
5289 };
5290
5291 /**
5292 * Show, hide, or toggle the visibility of the anchor.
5293 *
5294 * @param {boolean} [show] Show anchor, omit to toggle
5295 */
5296 OO.ui.PopupWidget.prototype.toggleAnchor = function ( show ) {
5297 show = show === undefined ? !this.anchored : !!show;
5298
5299 if ( this.anchored !== show ) {
5300 if ( show ) {
5301 this.$element.addClass( 'oo-ui-popupWidget-anchored' );
5302 this.$element.addClass( 'oo-ui-popupWidget-anchored-' + this.anchorEdge );
5303 } else {
5304 this.$element.removeClass( 'oo-ui-popupWidget-anchored' );
5305 this.$element.removeClass( 'oo-ui-popupWidget-anchored-' + this.anchorEdge );
5306 }
5307 this.anchored = show;
5308 }
5309 };
5310
5311 /**
5312 * Change which edge the anchor appears on.
5313 *
5314 * @param {string} edge 'top', 'bottom', 'start' or 'end'
5315 */
5316 OO.ui.PopupWidget.prototype.setAnchorEdge = function ( edge ) {
5317 if ( [ 'top', 'bottom', 'start', 'end' ].indexOf( edge ) === -1 ) {
5318 throw new Error( 'Invalid value for edge: ' + edge );
5319 }
5320 if ( this.anchorEdge !== null ) {
5321 this.$element.removeClass( 'oo-ui-popupWidget-anchored-' + this.anchorEdge );
5322 }
5323 this.anchorEdge = edge;
5324 if ( this.anchored ) {
5325 this.$element.addClass( 'oo-ui-popupWidget-anchored-' + edge );
5326 }
5327 };
5328
5329 /**
5330 * Check if the anchor is visible.
5331 *
5332 * @return {boolean} Anchor is visible
5333 */
5334 OO.ui.PopupWidget.prototype.hasAnchor = function () {
5335 return this.anchored;
5336 };
5337
5338 /**
5339 * Toggle visibility of the popup. The popup is initially hidden and must be shown by calling
5340 * `.toggle( true )` after its #$element is attached to the DOM.
5341 *
5342 * Do not show the popup while it is not attached to the DOM. The calculations required to display
5343 * it in the right place and with the right dimensions only work correctly while it is attached.
5344 * Side-effects may include broken interface and exceptions being thrown. This wasn't always
5345 * strictly enforced, so currently it only generates a warning in the browser console.
5346 *
5347 * @fires ready
5348 * @inheritdoc
5349 */
5350 OO.ui.PopupWidget.prototype.toggle = function ( show ) {
5351 var change, normalHeight, oppositeHeight, normalWidth, oppositeWidth;
5352 show = show === undefined ? !this.isVisible() : !!show;
5353
5354 change = show !== this.isVisible();
5355
5356 if ( show && !this.warnedUnattached && !this.isElementAttached() ) {
5357 OO.ui.warnDeprecation( 'PopupWidget#toggle: Before calling this method, the popup must be attached to the DOM.' );
5358 this.warnedUnattached = true;
5359 }
5360 if ( show && !this.$floatableContainer && this.isElementAttached() ) {
5361 // Fall back to the parent node if the floatableContainer is not set
5362 this.setFloatableContainer( this.$element.parent() );
5363 }
5364
5365 if ( change && show && this.autoFlip ) {
5366 // Reset auto-flipping before showing the popup again. It's possible we no longer need to flip
5367 // (e.g. if the user scrolled).
5368 this.isAutoFlipped = false;
5369 }
5370
5371 // Parent method
5372 OO.ui.PopupWidget.parent.prototype.toggle.call( this, show );
5373
5374 if ( change ) {
5375 this.togglePositioning( show && !!this.$floatableContainer );
5376
5377 if ( show ) {
5378 if ( this.autoClose ) {
5379 this.bindMouseDownListener();
5380 this.bindKeyDownListener();
5381 }
5382 this.updateDimensions();
5383 this.toggleClipping( true );
5384
5385 if ( this.autoFlip ) {
5386 if ( this.popupPosition === 'above' || this.popupPosition === 'below' ) {
5387 if ( this.isClippedVertically() || this.isFloatableOutOfView() ) {
5388 // If opening the popup in the normal direction causes it to be clipped, open
5389 // in the opposite one instead
5390 normalHeight = this.$element.height();
5391 this.isAutoFlipped = !this.isAutoFlipped;
5392 this.position();
5393 if ( this.isClippedVertically() || this.isFloatableOutOfView() ) {
5394 // If that also causes it to be clipped, open in whichever direction
5395 // we have more space
5396 oppositeHeight = this.$element.height();
5397 if ( oppositeHeight < normalHeight ) {
5398 this.isAutoFlipped = !this.isAutoFlipped;
5399 this.position();
5400 }
5401 }
5402 }
5403 }
5404 if ( this.popupPosition === 'before' || this.popupPosition === 'after' ) {
5405 if ( this.isClippedHorizontally() || this.isFloatableOutOfView() ) {
5406 // If opening the popup in the normal direction causes it to be clipped, open
5407 // in the opposite one instead
5408 normalWidth = this.$element.width();
5409 this.isAutoFlipped = !this.isAutoFlipped;
5410 // Due to T180173 horizontally clipped PopupWidgets have messed up dimensions,
5411 // which causes positioning to be off. Toggle clipping back and fort to work around.
5412 this.toggleClipping( false );
5413 this.position();
5414 this.toggleClipping( true );
5415 if ( this.isClippedHorizontally() || this.isFloatableOutOfView() ) {
5416 // If that also causes it to be clipped, open in whichever direction
5417 // we have more space
5418 oppositeWidth = this.$element.width();
5419 if ( oppositeWidth < normalWidth ) {
5420 this.isAutoFlipped = !this.isAutoFlipped;
5421 // Due to T180173 horizontally clipped PopupWidgets have messed up dimensions,
5422 // which causes positioning to be off. Toggle clipping back and fort to work around.
5423 this.toggleClipping( false );
5424 this.position();
5425 this.toggleClipping( true );
5426 }
5427 }
5428 }
5429 }
5430 }
5431
5432 this.emit( 'ready' );
5433 } else {
5434 this.toggleClipping( false );
5435 if ( this.autoClose ) {
5436 this.unbindMouseDownListener();
5437 this.unbindKeyDownListener();
5438 }
5439 }
5440 }
5441
5442 return this;
5443 };
5444
5445 /**
5446 * Set the size of the popup.
5447 *
5448 * Changing the size may also change the popup's position depending on the alignment.
5449 *
5450 * @param {number} width Width in pixels
5451 * @param {number} height Height in pixels
5452 * @param {boolean} [transition=false] Use a smooth transition
5453 * @chainable
5454 */
5455 OO.ui.PopupWidget.prototype.setSize = function ( width, height, transition ) {
5456 this.width = width;
5457 this.height = height !== undefined ? height : null;
5458 if ( this.isVisible() ) {
5459 this.updateDimensions( transition );
5460 }
5461 };
5462
5463 /**
5464 * Update the size and position.
5465 *
5466 * Only use this to keep the popup properly anchored. Use #setSize to change the size, and this will
5467 * be called automatically.
5468 *
5469 * @param {boolean} [transition=false] Use a smooth transition
5470 * @chainable
5471 */
5472 OO.ui.PopupWidget.prototype.updateDimensions = function ( transition ) {
5473 var widget = this;
5474
5475 // Prevent transition from being interrupted
5476 clearTimeout( this.transitionTimeout );
5477 if ( transition ) {
5478 // Enable transition
5479 this.$element.addClass( 'oo-ui-popupWidget-transitioning' );
5480 }
5481
5482 this.position();
5483
5484 if ( transition ) {
5485 // Prevent transitioning after transition is complete
5486 this.transitionTimeout = setTimeout( function () {
5487 widget.$element.removeClass( 'oo-ui-popupWidget-transitioning' );
5488 }, 200 );
5489 } else {
5490 // Prevent transitioning immediately
5491 this.$element.removeClass( 'oo-ui-popupWidget-transitioning' );
5492 }
5493 };
5494
5495 /**
5496 * @inheritdoc
5497 */
5498 OO.ui.PopupWidget.prototype.computePosition = function () {
5499 var direction, align, vertical, start, end, near, far, sizeProp, popupSize, anchorSize, anchorPos,
5500 anchorOffset, anchorMargin, parentPosition, positionProp, positionAdjustment, floatablePos,
5501 offsetParentPos, containerPos, popupPosition, viewportSpacing,
5502 popupPos = {},
5503 anchorCss = { left: '', right: '', top: '', bottom: '' },
5504 popupPositionOppositeMap = {
5505 above: 'below',
5506 below: 'above',
5507 before: 'after',
5508 after: 'before'
5509 },
5510 alignMap = {
5511 ltr: {
5512 'force-left': 'backwards',
5513 'force-right': 'forwards'
5514 },
5515 rtl: {
5516 'force-left': 'forwards',
5517 'force-right': 'backwards'
5518 }
5519 },
5520 anchorEdgeMap = {
5521 above: 'bottom',
5522 below: 'top',
5523 before: 'end',
5524 after: 'start'
5525 },
5526 hPosMap = {
5527 forwards: 'start',
5528 center: 'center',
5529 backwards: this.anchored ? 'before' : 'end'
5530 },
5531 vPosMap = {
5532 forwards: 'top',
5533 center: 'center',
5534 backwards: 'bottom'
5535 };
5536
5537 if ( !this.$container ) {
5538 // Lazy-initialize $container if not specified in constructor
5539 this.$container = $( this.getClosestScrollableElementContainer() );
5540 }
5541 direction = this.$container.css( 'direction' );
5542
5543 // Set height and width before we do anything else, since it might cause our measurements
5544 // to change (e.g. due to scrollbars appearing or disappearing), and it also affects centering
5545 this.$popup.css( {
5546 width: this.width,
5547 height: this.height !== null ? this.height : 'auto'
5548 } );
5549
5550 align = alignMap[ direction ][ this.align ] || this.align;
5551 popupPosition = this.popupPosition;
5552 if ( this.isAutoFlipped ) {
5553 popupPosition = popupPositionOppositeMap[ popupPosition ];
5554 }
5555
5556 // If the popup is positioned before or after, then the anchor positioning is vertical, otherwise horizontal
5557 vertical = popupPosition === 'before' || popupPosition === 'after';
5558 start = vertical ? 'top' : ( direction === 'rtl' ? 'right' : 'left' );
5559 end = vertical ? 'bottom' : ( direction === 'rtl' ? 'left' : 'right' );
5560 near = vertical ? 'top' : 'left';
5561 far = vertical ? 'bottom' : 'right';
5562 sizeProp = vertical ? 'Height' : 'Width';
5563 popupSize = vertical ? ( this.height || this.$popup.height() ) : this.width;
5564
5565 this.setAnchorEdge( anchorEdgeMap[ popupPosition ] );
5566 this.horizontalPosition = vertical ? popupPosition : hPosMap[ align ];
5567 this.verticalPosition = vertical ? vPosMap[ align ] : popupPosition;
5568
5569 // Parent method
5570 parentPosition = OO.ui.mixin.FloatableElement.prototype.computePosition.call( this );
5571 // Find out which property FloatableElement used for positioning, and adjust that value
5572 positionProp = vertical ?
5573 ( parentPosition.top !== '' ? 'top' : 'bottom' ) :
5574 ( parentPosition.left !== '' ? 'left' : 'right' );
5575
5576 // Figure out where the near and far edges of the popup and $floatableContainer are
5577 floatablePos = this.$floatableContainer.offset();
5578 floatablePos[ far ] = floatablePos[ near ] + this.$floatableContainer[ 'outer' + sizeProp ]();
5579 // Measure where the offsetParent is and compute our position based on that and parentPosition
5580 offsetParentPos = this.$element.offsetParent()[ 0 ] === document.documentElement ?
5581 { top: 0, left: 0 } :
5582 this.$element.offsetParent().offset();
5583
5584 if ( positionProp === near ) {
5585 popupPos[ near ] = offsetParentPos[ near ] + parentPosition[ near ];
5586 popupPos[ far ] = popupPos[ near ] + popupSize;
5587 } else {
5588 popupPos[ far ] = offsetParentPos[ near ] +
5589 this.$element.offsetParent()[ 'inner' + sizeProp ]() - parentPosition[ far ];
5590 popupPos[ near ] = popupPos[ far ] - popupSize;
5591 }
5592
5593 if ( this.anchored ) {
5594 // Position the anchor (which is positioned relative to the popup) to point to $floatableContainer
5595 anchorPos = ( floatablePos[ start ] + floatablePos[ end ] ) / 2;
5596 anchorOffset = ( start === far ? -1 : 1 ) * ( anchorPos - popupPos[ start ] );
5597
5598 // If the anchor is less than 2*anchorSize from either edge, move the popup to make more space
5599 // this.$anchor.width()/height() returns 0 because of the CSS trickery we use, so use scrollWidth/Height
5600 anchorSize = this.$anchor[ 0 ][ 'scroll' + sizeProp ];
5601 anchorMargin = parseFloat( this.$anchor.css( 'margin-' + start ) );
5602 if ( anchorOffset + anchorMargin < 2 * anchorSize ) {
5603 // Not enough space for the anchor on the start side; pull the popup startwards
5604 positionAdjustment = ( positionProp === start ? -1 : 1 ) *
5605 ( 2 * anchorSize - ( anchorOffset + anchorMargin ) );
5606 } else if ( anchorOffset + anchorMargin > popupSize - 2 * anchorSize ) {
5607 // Not enough space for the anchor on the end side; pull the popup endwards
5608 positionAdjustment = ( positionProp === end ? -1 : 1 ) *
5609 ( anchorOffset + anchorMargin - ( popupSize - 2 * anchorSize ) );
5610 } else {
5611 positionAdjustment = 0;
5612 }
5613 } else {
5614 positionAdjustment = 0;
5615 }
5616
5617 // Check if the popup will go beyond the edge of this.$container
5618 containerPos = this.$container[ 0 ] === document.documentElement ?
5619 { top: 0, left: 0 } :
5620 this.$container.offset();
5621 containerPos[ far ] = containerPos[ near ] + this.$container[ 'inner' + sizeProp ]();
5622 if ( this.$container[ 0 ] === document.documentElement ) {
5623 viewportSpacing = OO.ui.getViewportSpacing();
5624 containerPos[ near ] += viewportSpacing[ near ];
5625 containerPos[ far ] -= viewportSpacing[ far ];
5626 }
5627 // Take into account how much the popup will move because of the adjustments we're going to make
5628 popupPos[ near ] += ( positionProp === near ? 1 : -1 ) * positionAdjustment;
5629 popupPos[ far ] += ( positionProp === near ? 1 : -1 ) * positionAdjustment;
5630 if ( containerPos[ near ] + this.containerPadding > popupPos[ near ] ) {
5631 // Popup goes beyond the near (left/top) edge, move it to the right/bottom
5632 positionAdjustment += ( positionProp === near ? 1 : -1 ) *
5633 ( containerPos[ near ] + this.containerPadding - popupPos[ near ] );
5634 } else if ( containerPos[ far ] - this.containerPadding < popupPos[ far ] ) {
5635 // Popup goes beyond the far (right/bottom) edge, move it to the left/top
5636 positionAdjustment += ( positionProp === far ? 1 : -1 ) *
5637 ( popupPos[ far ] - ( containerPos[ far ] - this.containerPadding ) );
5638 }
5639
5640 if ( this.anchored ) {
5641 // Adjust anchorOffset for positionAdjustment
5642 anchorOffset += ( positionProp === start ? -1 : 1 ) * positionAdjustment;
5643
5644 // Position the anchor
5645 anchorCss[ start ] = anchorOffset;
5646 this.$anchor.css( anchorCss );
5647 }
5648
5649 // Move the popup if needed
5650 parentPosition[ positionProp ] += positionAdjustment;
5651
5652 return parentPosition;
5653 };
5654
5655 /**
5656 * Set popup alignment
5657 *
5658 * @param {string} [align=center] Alignment of the popup, `center`, `force-left`, `force-right`,
5659 * `backwards` or `forwards`.
5660 */
5661 OO.ui.PopupWidget.prototype.setAlignment = function ( align ) {
5662 // Validate alignment
5663 if ( [ 'force-left', 'force-right', 'backwards', 'forwards', 'center' ].indexOf( align ) > -1 ) {
5664 this.align = align;
5665 } else {
5666 this.align = 'center';
5667 }
5668 this.position();
5669 };
5670
5671 /**
5672 * Get popup alignment
5673 *
5674 * @return {string} Alignment of the popup, `center`, `force-left`, `force-right`,
5675 * `backwards` or `forwards`.
5676 */
5677 OO.ui.PopupWidget.prototype.getAlignment = function () {
5678 return this.align;
5679 };
5680
5681 /**
5682 * Change the positioning of the popup.
5683 *
5684 * @param {string} position 'above', 'below', 'before' or 'after'
5685 */
5686 OO.ui.PopupWidget.prototype.setPosition = function ( position ) {
5687 if ( [ 'above', 'below', 'before', 'after' ].indexOf( position ) === -1 ) {
5688 position = 'below';
5689 }
5690 this.popupPosition = position;
5691 this.position();
5692 };
5693
5694 /**
5695 * Get popup positioning.
5696 *
5697 * @return {string} 'above', 'below', 'before' or 'after'
5698 */
5699 OO.ui.PopupWidget.prototype.getPosition = function () {
5700 return this.popupPosition;
5701 };
5702
5703 /**
5704 * Set popup auto-flipping.
5705 *
5706 * @param {boolean} autoFlip Whether to automatically switch the popup's position between
5707 * 'above' and 'below', or between 'before' and 'after', if there is not enough space in the
5708 * desired direction to display the popup without clipping
5709 */
5710 OO.ui.PopupWidget.prototype.setAutoFlip = function ( autoFlip ) {
5711 autoFlip = !!autoFlip;
5712
5713 if ( this.autoFlip !== autoFlip ) {
5714 this.autoFlip = autoFlip;
5715 }
5716 };
5717
5718 /**
5719 * Get an ID of the body element, this can be used as the
5720 * `aria-describedby` attribute for an input field.
5721 *
5722 * @return {string} The ID of the body element
5723 */
5724 OO.ui.PopupWidget.prototype.getBodyId = function () {
5725 var id = this.$body.attr( 'id' );
5726 if ( id === undefined ) {
5727 id = OO.ui.generateElementId();
5728 this.$body.attr( 'id', id );
5729 }
5730 return id;
5731 };
5732
5733 /**
5734 * PopupElement is mixed into other classes to generate a {@link OO.ui.PopupWidget popup widget}.
5735 * A popup is a container for content. It is overlaid and positioned absolutely. By default, each
5736 * popup has an anchor, which is an arrow-like protrusion that points toward the popup’s origin.
5737 * See {@link OO.ui.PopupWidget PopupWidget} for an example.
5738 *
5739 * @abstract
5740 * @class
5741 *
5742 * @constructor
5743 * @param {Object} [config] Configuration options
5744 * @cfg {Object} [popup] Configuration to pass to popup
5745 * @cfg {boolean} [popup.autoClose=true] Popup auto-closes when it loses focus
5746 */
5747 OO.ui.mixin.PopupElement = function OoUiMixinPopupElement( config ) {
5748 // Configuration initialization
5749 config = config || {};
5750
5751 // Properties
5752 this.popup = new OO.ui.PopupWidget( $.extend(
5753 {
5754 autoClose: true,
5755 $floatableContainer: this.$element
5756 },
5757 config.popup,
5758 {
5759 $autoCloseIgnore: this.$element.add( config.popup && config.popup.$autoCloseIgnore )
5760 }
5761 ) );
5762 };
5763
5764 /* Methods */
5765
5766 /**
5767 * Get popup.
5768 *
5769 * @return {OO.ui.PopupWidget} Popup widget
5770 */
5771 OO.ui.mixin.PopupElement.prototype.getPopup = function () {
5772 return this.popup;
5773 };
5774
5775 /**
5776 * PopupButtonWidgets toggle the visibility of a contained {@link OO.ui.PopupWidget PopupWidget},
5777 * which is used to display additional information or options.
5778 *
5779 * @example
5780 * // Example of a popup button.
5781 * var popupButton = new OO.ui.PopupButtonWidget( {
5782 * label: 'Popup button with options',
5783 * icon: 'menu',
5784 * popup: {
5785 * $content: $( '<p>Additional options here.</p>' ),
5786 * padded: true,
5787 * align: 'force-left'
5788 * }
5789 * } );
5790 * // Append the button to the DOM.
5791 * $( 'body' ).append( popupButton.$element );
5792 *
5793 * @class
5794 * @extends OO.ui.ButtonWidget
5795 * @mixins OO.ui.mixin.PopupElement
5796 *
5797 * @constructor
5798 * @param {Object} [config] Configuration options
5799 * @cfg {jQuery} [$overlay] Render the popup into a separate layer. This configuration is useful in cases where
5800 * the expanded popup is larger than its containing `<div>`. The specified overlay layer is usually on top of the
5801 * containing `<div>` and has a larger area. By default, the popup uses relative positioning.
5802 * See <https://www.mediawiki.org/wiki/OOUI/Concepts#Overlays>.
5803 */
5804 OO.ui.PopupButtonWidget = function OoUiPopupButtonWidget( config ) {
5805 // Configuration initialization
5806 config = config || {};
5807
5808 // Parent constructor
5809 OO.ui.PopupButtonWidget.parent.call( this, config );
5810
5811 // Mixin constructors
5812 OO.ui.mixin.PopupElement.call( this, config );
5813
5814 // Properties
5815 this.$overlay = ( config.$overlay === true ? OO.ui.getDefaultOverlay() : config.$overlay ) || this.$element;
5816
5817 // Events
5818 this.connect( this, { click: 'onAction' } );
5819
5820 // Initialization
5821 this.$element
5822 .addClass( 'oo-ui-popupButtonWidget' )
5823 .attr( 'aria-haspopup', 'true' );
5824 this.popup.$element
5825 .addClass( 'oo-ui-popupButtonWidget-popup' )
5826 .toggleClass( 'oo-ui-popupButtonWidget-framed-popup', this.isFramed() )
5827 .toggleClass( 'oo-ui-popupButtonWidget-frameless-popup', !this.isFramed() );
5828 this.$overlay.append( this.popup.$element );
5829 };
5830
5831 /* Setup */
5832
5833 OO.inheritClass( OO.ui.PopupButtonWidget, OO.ui.ButtonWidget );
5834 OO.mixinClass( OO.ui.PopupButtonWidget, OO.ui.mixin.PopupElement );
5835
5836 /* Methods */
5837
5838 /**
5839 * Handle the button action being triggered.
5840 *
5841 * @private
5842 */
5843 OO.ui.PopupButtonWidget.prototype.onAction = function () {
5844 this.popup.toggle();
5845 };
5846
5847 /**
5848 * Mixin for OO.ui.Widget subclasses to provide OO.ui.mixin.GroupElement.
5849 *
5850 * Use together with OO.ui.mixin.ItemWidget to make disabled state inheritable.
5851 *
5852 * @private
5853 * @abstract
5854 * @class
5855 * @mixins OO.ui.mixin.GroupElement
5856 *
5857 * @constructor
5858 * @param {Object} [config] Configuration options
5859 */
5860 OO.ui.mixin.GroupWidget = function OoUiMixinGroupWidget( config ) {
5861 // Mixin constructors
5862 OO.ui.mixin.GroupElement.call( this, config );
5863 };
5864
5865 /* Setup */
5866
5867 OO.mixinClass( OO.ui.mixin.GroupWidget, OO.ui.mixin.GroupElement );
5868
5869 /* Methods */
5870
5871 /**
5872 * Set the disabled state of the widget.
5873 *
5874 * This will also update the disabled state of child widgets.
5875 *
5876 * @param {boolean} disabled Disable widget
5877 * @chainable
5878 */
5879 OO.ui.mixin.GroupWidget.prototype.setDisabled = function ( disabled ) {
5880 var i, len;
5881
5882 // Parent method
5883 // Note: Calling #setDisabled this way assumes this is mixed into an OO.ui.Widget
5884 OO.ui.Widget.prototype.setDisabled.call( this, disabled );
5885
5886 // During construction, #setDisabled is called before the OO.ui.mixin.GroupElement constructor
5887 if ( this.items ) {
5888 for ( i = 0, len = this.items.length; i < len; i++ ) {
5889 this.items[ i ].updateDisabled();
5890 }
5891 }
5892
5893 return this;
5894 };
5895
5896 /**
5897 * Mixin for widgets used as items in widgets that mix in OO.ui.mixin.GroupWidget.
5898 *
5899 * Item widgets have a reference to a OO.ui.mixin.GroupWidget while they are attached to the group. This
5900 * allows bidirectional communication.
5901 *
5902 * Use together with OO.ui.mixin.GroupWidget to make disabled state inheritable.
5903 *
5904 * @private
5905 * @abstract
5906 * @class
5907 *
5908 * @constructor
5909 */
5910 OO.ui.mixin.ItemWidget = function OoUiMixinItemWidget() {
5911 //
5912 };
5913
5914 /* Methods */
5915
5916 /**
5917 * Check if widget is disabled.
5918 *
5919 * Checks parent if present, making disabled state inheritable.
5920 *
5921 * @return {boolean} Widget is disabled
5922 */
5923 OO.ui.mixin.ItemWidget.prototype.isDisabled = function () {
5924 return this.disabled ||
5925 ( this.elementGroup instanceof OO.ui.Widget && this.elementGroup.isDisabled() );
5926 };
5927
5928 /**
5929 * Set group element is in.
5930 *
5931 * @param {OO.ui.mixin.GroupElement|null} group Group element, null if none
5932 * @chainable
5933 */
5934 OO.ui.mixin.ItemWidget.prototype.setElementGroup = function ( group ) {
5935 // Parent method
5936 // Note: Calling #setElementGroup this way assumes this is mixed into an OO.ui.Element
5937 OO.ui.Element.prototype.setElementGroup.call( this, group );
5938
5939 // Initialize item disabled states
5940 this.updateDisabled();
5941
5942 return this;
5943 };
5944
5945 /**
5946 * OptionWidgets are special elements that can be selected and configured with data. The
5947 * data is often unique for each option, but it does not have to be. OptionWidgets are used
5948 * with OO.ui.SelectWidget to create a selection of mutually exclusive options. For more information
5949 * and examples, please see the [OOUI documentation on MediaWiki][1].
5950 *
5951 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options
5952 *
5953 * @class
5954 * @extends OO.ui.Widget
5955 * @mixins OO.ui.mixin.ItemWidget
5956 * @mixins OO.ui.mixin.LabelElement
5957 * @mixins OO.ui.mixin.FlaggedElement
5958 * @mixins OO.ui.mixin.AccessKeyedElement
5959 *
5960 * @constructor
5961 * @param {Object} [config] Configuration options
5962 */
5963 OO.ui.OptionWidget = function OoUiOptionWidget( config ) {
5964 // Configuration initialization
5965 config = config || {};
5966
5967 // Parent constructor
5968 OO.ui.OptionWidget.parent.call( this, config );
5969
5970 // Mixin constructors
5971 OO.ui.mixin.ItemWidget.call( this );
5972 OO.ui.mixin.LabelElement.call( this, config );
5973 OO.ui.mixin.FlaggedElement.call( this, config );
5974 OO.ui.mixin.AccessKeyedElement.call( this, config );
5975
5976 // Properties
5977 this.selected = false;
5978 this.highlighted = false;
5979 this.pressed = false;
5980
5981 // Initialization
5982 this.$element
5983 .data( 'oo-ui-optionWidget', this )
5984 // Allow programmatic focussing (and by accesskey), but not tabbing
5985 .attr( 'tabindex', '-1' )
5986 .attr( 'role', 'option' )
5987 .attr( 'aria-selected', 'false' )
5988 .addClass( 'oo-ui-optionWidget' )
5989 .append( this.$label );
5990 };
5991
5992 /* Setup */
5993
5994 OO.inheritClass( OO.ui.OptionWidget, OO.ui.Widget );
5995 OO.mixinClass( OO.ui.OptionWidget, OO.ui.mixin.ItemWidget );
5996 OO.mixinClass( OO.ui.OptionWidget, OO.ui.mixin.LabelElement );
5997 OO.mixinClass( OO.ui.OptionWidget, OO.ui.mixin.FlaggedElement );
5998 OO.mixinClass( OO.ui.OptionWidget, OO.ui.mixin.AccessKeyedElement );
5999
6000 /* Static Properties */
6001
6002 /**
6003 * Whether this option can be selected. See #setSelected.
6004 *
6005 * @static
6006 * @inheritable
6007 * @property {boolean}
6008 */
6009 OO.ui.OptionWidget.static.selectable = true;
6010
6011 /**
6012 * Whether this option can be highlighted. See #setHighlighted.
6013 *
6014 * @static
6015 * @inheritable
6016 * @property {boolean}
6017 */
6018 OO.ui.OptionWidget.static.highlightable = true;
6019
6020 /**
6021 * Whether this option can be pressed. See #setPressed.
6022 *
6023 * @static
6024 * @inheritable
6025 * @property {boolean}
6026 */
6027 OO.ui.OptionWidget.static.pressable = true;
6028
6029 /**
6030 * Whether this option will be scrolled into view when it is selected.
6031 *
6032 * @static
6033 * @inheritable
6034 * @property {boolean}
6035 */
6036 OO.ui.OptionWidget.static.scrollIntoViewOnSelect = false;
6037
6038 /* Methods */
6039
6040 /**
6041 * Check if the option can be selected.
6042 *
6043 * @return {boolean} Item is selectable
6044 */
6045 OO.ui.OptionWidget.prototype.isSelectable = function () {
6046 return this.constructor.static.selectable && !this.disabled && this.isVisible();
6047 };
6048
6049 /**
6050 * Check if the option can be highlighted. A highlight indicates that the option
6051 * may be selected when a user presses enter or clicks. Disabled items cannot
6052 * be highlighted.
6053 *
6054 * @return {boolean} Item is highlightable
6055 */
6056 OO.ui.OptionWidget.prototype.isHighlightable = function () {
6057 return this.constructor.static.highlightable && !this.disabled && this.isVisible();
6058 };
6059
6060 /**
6061 * Check if the option can be pressed. The pressed state occurs when a user mouses
6062 * down on an item, but has not yet let go of the mouse.
6063 *
6064 * @return {boolean} Item is pressable
6065 */
6066 OO.ui.OptionWidget.prototype.isPressable = function () {
6067 return this.constructor.static.pressable && !this.disabled && this.isVisible();
6068 };
6069
6070 /**
6071 * Check if the option is selected.
6072 *
6073 * @return {boolean} Item is selected
6074 */
6075 OO.ui.OptionWidget.prototype.isSelected = function () {
6076 return this.selected;
6077 };
6078
6079 /**
6080 * Check if the option is highlighted. A highlight indicates that the
6081 * item may be selected when a user presses enter or clicks.
6082 *
6083 * @return {boolean} Item is highlighted
6084 */
6085 OO.ui.OptionWidget.prototype.isHighlighted = function () {
6086 return this.highlighted;
6087 };
6088
6089 /**
6090 * Check if the option is pressed. The pressed state occurs when a user mouses
6091 * down on an item, but has not yet let go of the mouse. The item may appear
6092 * selected, but it will not be selected until the user releases the mouse.
6093 *
6094 * @return {boolean} Item is pressed
6095 */
6096 OO.ui.OptionWidget.prototype.isPressed = function () {
6097 return this.pressed;
6098 };
6099
6100 /**
6101 * Set the option’s selected state. In general, all modifications to the selection
6102 * should be handled by the SelectWidget’s {@link OO.ui.SelectWidget#selectItem selectItem( [item] )}
6103 * method instead of this method.
6104 *
6105 * @param {boolean} [state=false] Select option
6106 * @chainable
6107 */
6108 OO.ui.OptionWidget.prototype.setSelected = function ( state ) {
6109 if ( this.constructor.static.selectable ) {
6110 this.selected = !!state;
6111 this.$element
6112 .toggleClass( 'oo-ui-optionWidget-selected', state )
6113 .attr( 'aria-selected', state.toString() );
6114 if ( state && this.constructor.static.scrollIntoViewOnSelect ) {
6115 this.scrollElementIntoView();
6116 }
6117 this.updateThemeClasses();
6118 }
6119 return this;
6120 };
6121
6122 /**
6123 * Set the option’s highlighted state. In general, all programmatic
6124 * modifications to the highlight should be handled by the
6125 * SelectWidget’s {@link OO.ui.SelectWidget#highlightItem highlightItem( [item] )}
6126 * method instead of this method.
6127 *
6128 * @param {boolean} [state=false] Highlight option
6129 * @chainable
6130 */
6131 OO.ui.OptionWidget.prototype.setHighlighted = function ( state ) {
6132 if ( this.constructor.static.highlightable ) {
6133 this.highlighted = !!state;
6134 this.$element.toggleClass( 'oo-ui-optionWidget-highlighted', state );
6135 this.updateThemeClasses();
6136 }
6137 return this;
6138 };
6139
6140 /**
6141 * Set the option’s pressed state. In general, all
6142 * programmatic modifications to the pressed state should be handled by the
6143 * SelectWidget’s {@link OO.ui.SelectWidget#pressItem pressItem( [item] )}
6144 * method instead of this method.
6145 *
6146 * @param {boolean} [state=false] Press option
6147 * @chainable
6148 */
6149 OO.ui.OptionWidget.prototype.setPressed = function ( state ) {
6150 if ( this.constructor.static.pressable ) {
6151 this.pressed = !!state;
6152 this.$element.toggleClass( 'oo-ui-optionWidget-pressed', state );
6153 this.updateThemeClasses();
6154 }
6155 return this;
6156 };
6157
6158 /**
6159 * Get text to match search strings against.
6160 *
6161 * The default implementation returns the label text, but subclasses
6162 * can override this to provide more complex behavior.
6163 *
6164 * @return {string|boolean} String to match search string against
6165 */
6166 OO.ui.OptionWidget.prototype.getMatchText = function () {
6167 var label = this.getLabel();
6168 return typeof label === 'string' ? label : this.$label.text();
6169 };
6170
6171 /**
6172 * A SelectWidget is of a generic selection of options. The OOUI library contains several types of
6173 * select widgets, including {@link OO.ui.ButtonSelectWidget button selects},
6174 * {@link OO.ui.RadioSelectWidget radio selects}, and {@link OO.ui.MenuSelectWidget
6175 * menu selects}.
6176 *
6177 * This class should be used together with OO.ui.OptionWidget or OO.ui.DecoratedOptionWidget. For more
6178 * information, please see the [OOUI documentation on MediaWiki][1].
6179 *
6180 * @example
6181 * // Example of a select widget with three options
6182 * var select = new OO.ui.SelectWidget( {
6183 * items: [
6184 * new OO.ui.OptionWidget( {
6185 * data: 'a',
6186 * label: 'Option One',
6187 * } ),
6188 * new OO.ui.OptionWidget( {
6189 * data: 'b',
6190 * label: 'Option Two',
6191 * } ),
6192 * new OO.ui.OptionWidget( {
6193 * data: 'c',
6194 * label: 'Option Three',
6195 * } )
6196 * ]
6197 * } );
6198 * $( 'body' ).append( select.$element );
6199 *
6200 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options
6201 *
6202 * @abstract
6203 * @class
6204 * @extends OO.ui.Widget
6205 * @mixins OO.ui.mixin.GroupWidget
6206 *
6207 * @constructor
6208 * @param {Object} [config] Configuration options
6209 * @cfg {OO.ui.OptionWidget[]} [items] An array of options to add to the select.
6210 * Options are created with {@link OO.ui.OptionWidget OptionWidget} classes. See
6211 * the [OOUI documentation on MediaWiki] [2] for examples.
6212 * [2]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options
6213 */
6214 OO.ui.SelectWidget = function OoUiSelectWidget( config ) {
6215 // Configuration initialization
6216 config = config || {};
6217
6218 // Parent constructor
6219 OO.ui.SelectWidget.parent.call( this, config );
6220
6221 // Mixin constructors
6222 OO.ui.mixin.GroupWidget.call( this, $.extend( {}, config, { $group: this.$element } ) );
6223
6224 // Properties
6225 this.pressed = false;
6226 this.selecting = null;
6227 this.onMouseUpHandler = this.onMouseUp.bind( this );
6228 this.onMouseMoveHandler = this.onMouseMove.bind( this );
6229 this.onKeyDownHandler = this.onKeyDown.bind( this );
6230 this.onKeyPressHandler = this.onKeyPress.bind( this );
6231 this.keyPressBuffer = '';
6232 this.keyPressBufferTimer = null;
6233 this.blockMouseOverEvents = 0;
6234
6235 // Events
6236 this.connect( this, {
6237 toggle: 'onToggle'
6238 } );
6239 this.$element.on( {
6240 focusin: this.onFocus.bind( this ),
6241 mousedown: this.onMouseDown.bind( this ),
6242 mouseover: this.onMouseOver.bind( this ),
6243 mouseleave: this.onMouseLeave.bind( this )
6244 } );
6245
6246 // Initialization
6247 this.$element
6248 .addClass( 'oo-ui-selectWidget oo-ui-selectWidget-depressed' )
6249 .attr( 'role', 'listbox' );
6250 this.setFocusOwner( this.$element );
6251 if ( Array.isArray( config.items ) ) {
6252 this.addItems( config.items );
6253 }
6254 };
6255
6256 /* Setup */
6257
6258 OO.inheritClass( OO.ui.SelectWidget, OO.ui.Widget );
6259 OO.mixinClass( OO.ui.SelectWidget, OO.ui.mixin.GroupWidget );
6260
6261 /* Events */
6262
6263 /**
6264 * @event highlight
6265 *
6266 * A `highlight` event is emitted when the highlight is changed with the #highlightItem method.
6267 *
6268 * @param {OO.ui.OptionWidget|null} item Highlighted item
6269 */
6270
6271 /**
6272 * @event press
6273 *
6274 * A `press` event is emitted when the #pressItem method is used to programmatically modify the
6275 * pressed state of an option.
6276 *
6277 * @param {OO.ui.OptionWidget|null} item Pressed item
6278 */
6279
6280 /**
6281 * @event select
6282 *
6283 * A `select` event is emitted when the selection is modified programmatically with the #selectItem method.
6284 *
6285 * @param {OO.ui.OptionWidget|null} item Selected item
6286 */
6287
6288 /**
6289 * @event choose
6290 * A `choose` event is emitted when an item is chosen with the #chooseItem method.
6291 * @param {OO.ui.OptionWidget} item Chosen item
6292 */
6293
6294 /**
6295 * @event add
6296 *
6297 * An `add` event is emitted when options are added to the select with the #addItems method.
6298 *
6299 * @param {OO.ui.OptionWidget[]} items Added items
6300 * @param {number} index Index of insertion point
6301 */
6302
6303 /**
6304 * @event remove
6305 *
6306 * A `remove` event is emitted when options are removed from the select with the #clearItems
6307 * or #removeItems methods.
6308 *
6309 * @param {OO.ui.OptionWidget[]} items Removed items
6310 */
6311
6312 /* Methods */
6313
6314 /**
6315 * Handle focus events
6316 *
6317 * @private
6318 * @param {jQuery.Event} event
6319 */
6320 OO.ui.SelectWidget.prototype.onFocus = function ( event ) {
6321 var item;
6322 if ( event.target === this.$element[ 0 ] ) {
6323 // This widget was focussed, e.g. by the user tabbing to it.
6324 // The styles for focus state depend on one of the items being selected.
6325 if ( !this.findSelectedItem() ) {
6326 item = this.findFirstSelectableItem();
6327 }
6328 } else {
6329 if ( event.target.tabIndex === -1 ) {
6330 // One of the options got focussed (and the event bubbled up here).
6331 // They can't be tabbed to, but they can be activated using accesskeys.
6332 // OptionWidgets and focusable UI elements inside them have tabindex="-1" set.
6333 item = this.findTargetItem( event );
6334 } else {
6335 // There is something actually user-focusable in one of the labels of the options, and the
6336 // user focussed it (e.g. by tabbing to it). Do nothing (especially, don't change the focus).
6337 return;
6338 }
6339 }
6340
6341 if ( item ) {
6342 if ( item.constructor.static.highlightable ) {
6343 this.highlightItem( item );
6344 } else {
6345 this.selectItem( item );
6346 }
6347 }
6348
6349 if ( event.target !== this.$element[ 0 ] ) {
6350 this.$focusOwner.focus();
6351 }
6352 };
6353
6354 /**
6355 * Handle mouse down events.
6356 *
6357 * @private
6358 * @param {jQuery.Event} e Mouse down event
6359 */
6360 OO.ui.SelectWidget.prototype.onMouseDown = function ( e ) {
6361 var item;
6362
6363 if ( !this.isDisabled() && e.which === OO.ui.MouseButtons.LEFT ) {
6364 this.togglePressed( true );
6365 item = this.findTargetItem( e );
6366 if ( item && item.isSelectable() ) {
6367 this.pressItem( item );
6368 this.selecting = item;
6369 this.getElementDocument().addEventListener( 'mouseup', this.onMouseUpHandler, true );
6370 this.getElementDocument().addEventListener( 'mousemove', this.onMouseMoveHandler, true );
6371 }
6372 }
6373 return false;
6374 };
6375
6376 /**
6377 * Handle mouse up events.
6378 *
6379 * @private
6380 * @param {MouseEvent} e Mouse up event
6381 */
6382 OO.ui.SelectWidget.prototype.onMouseUp = function ( e ) {
6383 var item;
6384
6385 this.togglePressed( false );
6386 if ( !this.selecting ) {
6387 item = this.findTargetItem( e );
6388 if ( item && item.isSelectable() ) {
6389 this.selecting = item;
6390 }
6391 }
6392 if ( !this.isDisabled() && e.which === OO.ui.MouseButtons.LEFT && this.selecting ) {
6393 this.pressItem( null );
6394 this.chooseItem( this.selecting );
6395 this.selecting = null;
6396 }
6397
6398 this.getElementDocument().removeEventListener( 'mouseup', this.onMouseUpHandler, true );
6399 this.getElementDocument().removeEventListener( 'mousemove', this.onMouseMoveHandler, true );
6400
6401 return false;
6402 };
6403
6404 /**
6405 * Handle mouse move events.
6406 *
6407 * @private
6408 * @param {MouseEvent} e Mouse move event
6409 */
6410 OO.ui.SelectWidget.prototype.onMouseMove = function ( e ) {
6411 var item;
6412
6413 if ( !this.isDisabled() && this.pressed ) {
6414 item = this.findTargetItem( e );
6415 if ( item && item !== this.selecting && item.isSelectable() ) {
6416 this.pressItem( item );
6417 this.selecting = item;
6418 }
6419 }
6420 };
6421
6422 /**
6423 * Handle mouse over events.
6424 *
6425 * @private
6426 * @param {jQuery.Event} e Mouse over event
6427 */
6428 OO.ui.SelectWidget.prototype.onMouseOver = function ( e ) {
6429 var item;
6430 if ( this.blockMouseOverEvents ) {
6431 return;
6432 }
6433 if ( !this.isDisabled() ) {
6434 item = this.findTargetItem( e );
6435 this.highlightItem( item && item.isHighlightable() ? item : null );
6436 }
6437 return false;
6438 };
6439
6440 /**
6441 * Handle mouse leave events.
6442 *
6443 * @private
6444 * @param {jQuery.Event} e Mouse over event
6445 */
6446 OO.ui.SelectWidget.prototype.onMouseLeave = function () {
6447 if ( !this.isDisabled() ) {
6448 this.highlightItem( null );
6449 }
6450 return false;
6451 };
6452
6453 /**
6454 * Handle key down events.
6455 *
6456 * @protected
6457 * @param {KeyboardEvent} e Key down event
6458 */
6459 OO.ui.SelectWidget.prototype.onKeyDown = function ( e ) {
6460 var nextItem,
6461 handled = false,
6462 currentItem = this.findHighlightedItem() || this.findSelectedItem();
6463
6464 if ( !this.isDisabled() && this.isVisible() ) {
6465 switch ( e.keyCode ) {
6466 case OO.ui.Keys.ENTER:
6467 if ( currentItem && currentItem.constructor.static.highlightable ) {
6468 // Was only highlighted, now let's select it. No-op if already selected.
6469 this.chooseItem( currentItem );
6470 handled = true;
6471 }
6472 break;
6473 case OO.ui.Keys.UP:
6474 case OO.ui.Keys.LEFT:
6475 this.clearKeyPressBuffer();
6476 nextItem = this.findRelativeSelectableItem( currentItem, -1 );
6477 handled = true;
6478 break;
6479 case OO.ui.Keys.DOWN:
6480 case OO.ui.Keys.RIGHT:
6481 this.clearKeyPressBuffer();
6482 nextItem = this.findRelativeSelectableItem( currentItem, 1 );
6483 handled = true;
6484 break;
6485 case OO.ui.Keys.ESCAPE:
6486 case OO.ui.Keys.TAB:
6487 if ( currentItem && currentItem.constructor.static.highlightable ) {
6488 currentItem.setHighlighted( false );
6489 }
6490 this.unbindKeyDownListener();
6491 this.unbindKeyPressListener();
6492 // Don't prevent tabbing away / defocusing
6493 handled = false;
6494 break;
6495 }
6496
6497 if ( nextItem ) {
6498 if ( nextItem.constructor.static.highlightable ) {
6499 this.highlightItem( nextItem );
6500 } else {
6501 this.chooseItem( nextItem );
6502 }
6503 this.scrollItemIntoView( nextItem );
6504 }
6505
6506 if ( handled ) {
6507 e.preventDefault();
6508 e.stopPropagation();
6509 }
6510 }
6511 };
6512
6513 /**
6514 * Bind key down listener.
6515 *
6516 * @protected
6517 */
6518 OO.ui.SelectWidget.prototype.bindKeyDownListener = function () {
6519 this.getElementWindow().addEventListener( 'keydown', this.onKeyDownHandler, true );
6520 };
6521
6522 /**
6523 * Unbind key down listener.
6524 *
6525 * @protected
6526 */
6527 OO.ui.SelectWidget.prototype.unbindKeyDownListener = function () {
6528 this.getElementWindow().removeEventListener( 'keydown', this.onKeyDownHandler, true );
6529 };
6530
6531 /**
6532 * Scroll item into view, preventing spurious mouse highlight actions from happening.
6533 *
6534 * @param {OO.ui.OptionWidget} item Item to scroll into view
6535 */
6536 OO.ui.SelectWidget.prototype.scrollItemIntoView = function ( item ) {
6537 var widget = this;
6538 // Chromium's Blink engine will generate spurious 'mouseover' events during programmatic scrolling
6539 // and around 100-150 ms after it is finished.
6540 this.blockMouseOverEvents++;
6541 item.scrollElementIntoView().done( function () {
6542 setTimeout( function () {
6543 widget.blockMouseOverEvents--;
6544 }, 200 );
6545 } );
6546 };
6547
6548 /**
6549 * Clear the key-press buffer
6550 *
6551 * @protected
6552 */
6553 OO.ui.SelectWidget.prototype.clearKeyPressBuffer = function () {
6554 if ( this.keyPressBufferTimer ) {
6555 clearTimeout( this.keyPressBufferTimer );
6556 this.keyPressBufferTimer = null;
6557 }
6558 this.keyPressBuffer = '';
6559 };
6560
6561 /**
6562 * Handle key press events.
6563 *
6564 * @protected
6565 * @param {KeyboardEvent} e Key press event
6566 */
6567 OO.ui.SelectWidget.prototype.onKeyPress = function ( e ) {
6568 var c, filter, item;
6569
6570 if ( !e.charCode ) {
6571 if ( e.keyCode === OO.ui.Keys.BACKSPACE && this.keyPressBuffer !== '' ) {
6572 this.keyPressBuffer = this.keyPressBuffer.substr( 0, this.keyPressBuffer.length - 1 );
6573 return false;
6574 }
6575 return;
6576 }
6577 if ( String.fromCodePoint ) {
6578 c = String.fromCodePoint( e.charCode );
6579 } else {
6580 c = String.fromCharCode( e.charCode );
6581 }
6582
6583 if ( this.keyPressBufferTimer ) {
6584 clearTimeout( this.keyPressBufferTimer );
6585 }
6586 this.keyPressBufferTimer = setTimeout( this.clearKeyPressBuffer.bind( this ), 1500 );
6587
6588 item = this.findHighlightedItem() || this.findSelectedItem();
6589
6590 if ( this.keyPressBuffer === c ) {
6591 // Common (if weird) special case: typing "xxxx" will cycle through all
6592 // the items beginning with "x".
6593 if ( item ) {
6594 item = this.findRelativeSelectableItem( item, 1 );
6595 }
6596 } else {
6597 this.keyPressBuffer += c;
6598 }
6599
6600 filter = this.getItemMatcher( this.keyPressBuffer, false );
6601 if ( !item || !filter( item ) ) {
6602 item = this.findRelativeSelectableItem( item, 1, filter );
6603 }
6604 if ( item ) {
6605 if ( this.isVisible() && item.constructor.static.highlightable ) {
6606 this.highlightItem( item );
6607 } else {
6608 this.chooseItem( item );
6609 }
6610 this.scrollItemIntoView( item );
6611 }
6612
6613 e.preventDefault();
6614 e.stopPropagation();
6615 };
6616
6617 /**
6618 * Get a matcher for the specific string
6619 *
6620 * @protected
6621 * @param {string} s String to match against items
6622 * @param {boolean} [exact=false] Only accept exact matches
6623 * @return {Function} function ( OO.ui.OptionWidget ) => boolean
6624 */
6625 OO.ui.SelectWidget.prototype.getItemMatcher = function ( s, exact ) {
6626 var re;
6627
6628 if ( s.normalize ) {
6629 s = s.normalize();
6630 }
6631 s = exact ? s.trim() : s.replace( /^\s+/, '' );
6632 re = '^\\s*' + s.replace( /([\\{}()|.?*+\-^$[\]])/g, '\\$1' ).replace( /\s+/g, '\\s+' );
6633 if ( exact ) {
6634 re += '\\s*$';
6635 }
6636 re = new RegExp( re, 'i' );
6637 return function ( item ) {
6638 var matchText = item.getMatchText();
6639 if ( matchText.normalize ) {
6640 matchText = matchText.normalize();
6641 }
6642 return re.test( matchText );
6643 };
6644 };
6645
6646 /**
6647 * Bind key press listener.
6648 *
6649 * @protected
6650 */
6651 OO.ui.SelectWidget.prototype.bindKeyPressListener = function () {
6652 this.getElementWindow().addEventListener( 'keypress', this.onKeyPressHandler, true );
6653 };
6654
6655 /**
6656 * Unbind key down listener.
6657 *
6658 * If you override this, be sure to call this.clearKeyPressBuffer() from your
6659 * implementation.
6660 *
6661 * @protected
6662 */
6663 OO.ui.SelectWidget.prototype.unbindKeyPressListener = function () {
6664 this.getElementWindow().removeEventListener( 'keypress', this.onKeyPressHandler, true );
6665 this.clearKeyPressBuffer();
6666 };
6667
6668 /**
6669 * Visibility change handler
6670 *
6671 * @protected
6672 * @param {boolean} visible
6673 */
6674 OO.ui.SelectWidget.prototype.onToggle = function ( visible ) {
6675 if ( !visible ) {
6676 this.clearKeyPressBuffer();
6677 }
6678 };
6679
6680 /**
6681 * Get the closest item to a jQuery.Event.
6682 *
6683 * @private
6684 * @param {jQuery.Event} e
6685 * @return {OO.ui.OptionWidget|null} Outline item widget, `null` if none was found
6686 */
6687 OO.ui.SelectWidget.prototype.findTargetItem = function ( e ) {
6688 var $option = $( e.target ).closest( '.oo-ui-optionWidget' );
6689 if ( !$option.closest( '.oo-ui-selectWidget' ).is( this.$element ) ) {
6690 return null;
6691 }
6692 return $option.data( 'oo-ui-optionWidget' ) || null;
6693 };
6694
6695 /**
6696 * Find selected item.
6697 *
6698 * @return {OO.ui.OptionWidget|null} Selected item, `null` if no item is selected
6699 */
6700 OO.ui.SelectWidget.prototype.findSelectedItem = function () {
6701 var i, len;
6702
6703 for ( i = 0, len = this.items.length; i < len; i++ ) {
6704 if ( this.items[ i ].isSelected() ) {
6705 return this.items[ i ];
6706 }
6707 }
6708 return null;
6709 };
6710
6711 /**
6712 * Find highlighted item.
6713 *
6714 * @return {OO.ui.OptionWidget|null} Highlighted item, `null` if no item is highlighted
6715 */
6716 OO.ui.SelectWidget.prototype.findHighlightedItem = function () {
6717 var i, len;
6718
6719 for ( i = 0, len = this.items.length; i < len; i++ ) {
6720 if ( this.items[ i ].isHighlighted() ) {
6721 return this.items[ i ];
6722 }
6723 }
6724 return null;
6725 };
6726
6727 /**
6728 * Toggle pressed state.
6729 *
6730 * Press is a state that occurs when a user mouses down on an item, but
6731 * has not yet let go of the mouse. The item may appear selected, but it will not be selected
6732 * until the user releases the mouse.
6733 *
6734 * @param {boolean} pressed An option is being pressed
6735 */
6736 OO.ui.SelectWidget.prototype.togglePressed = function ( pressed ) {
6737 if ( pressed === undefined ) {
6738 pressed = !this.pressed;
6739 }
6740 if ( pressed !== this.pressed ) {
6741 this.$element
6742 .toggleClass( 'oo-ui-selectWidget-pressed', pressed )
6743 .toggleClass( 'oo-ui-selectWidget-depressed', !pressed );
6744 this.pressed = pressed;
6745 }
6746 };
6747
6748 /**
6749 * Highlight an option. If the `item` param is omitted, no options will be highlighted
6750 * and any existing highlight will be removed. The highlight is mutually exclusive.
6751 *
6752 * @param {OO.ui.OptionWidget} [item] Item to highlight, omit for no highlight
6753 * @fires highlight
6754 * @chainable
6755 */
6756 OO.ui.SelectWidget.prototype.highlightItem = function ( item ) {
6757 var i, len, highlighted,
6758 changed = false;
6759
6760 for ( i = 0, len = this.items.length; i < len; i++ ) {
6761 highlighted = this.items[ i ] === item;
6762 if ( this.items[ i ].isHighlighted() !== highlighted ) {
6763 this.items[ i ].setHighlighted( highlighted );
6764 changed = true;
6765 }
6766 }
6767 if ( changed ) {
6768 if ( item ) {
6769 this.$focusOwner.attr( 'aria-activedescendant', item.getElementId() );
6770 } else {
6771 this.$focusOwner.removeAttr( 'aria-activedescendant' );
6772 }
6773 this.emit( 'highlight', item );
6774 }
6775
6776 return this;
6777 };
6778
6779 /**
6780 * Fetch an item by its label.
6781 *
6782 * @param {string} label Label of the item to select.
6783 * @param {boolean} [prefix=false] Allow a prefix match, if only a single item matches
6784 * @return {OO.ui.Element|null} Item with equivalent label, `null` if none exists
6785 */
6786 OO.ui.SelectWidget.prototype.getItemFromLabel = function ( label, prefix ) {
6787 var i, item, found,
6788 len = this.items.length,
6789 filter = this.getItemMatcher( label, true );
6790
6791 for ( i = 0; i < len; i++ ) {
6792 item = this.items[ i ];
6793 if ( item instanceof OO.ui.OptionWidget && item.isSelectable() && filter( item ) ) {
6794 return item;
6795 }
6796 }
6797
6798 if ( prefix ) {
6799 found = null;
6800 filter = this.getItemMatcher( label, false );
6801 for ( i = 0; i < len; i++ ) {
6802 item = this.items[ i ];
6803 if ( item instanceof OO.ui.OptionWidget && item.isSelectable() && filter( item ) ) {
6804 if ( found ) {
6805 return null;
6806 }
6807 found = item;
6808 }
6809 }
6810 if ( found ) {
6811 return found;
6812 }
6813 }
6814
6815 return null;
6816 };
6817
6818 /**
6819 * Programmatically select an option by its label. If the item does not exist,
6820 * all options will be deselected.
6821 *
6822 * @param {string} [label] Label of the item to select.
6823 * @param {boolean} [prefix=false] Allow a prefix match, if only a single item matches
6824 * @fires select
6825 * @chainable
6826 */
6827 OO.ui.SelectWidget.prototype.selectItemByLabel = function ( label, prefix ) {
6828 var itemFromLabel = this.getItemFromLabel( label, !!prefix );
6829 if ( label === undefined || !itemFromLabel ) {
6830 return this.selectItem();
6831 }
6832 return this.selectItem( itemFromLabel );
6833 };
6834
6835 /**
6836 * Programmatically select an option by its data. If the `data` parameter is omitted,
6837 * or if the item does not exist, all options will be deselected.
6838 *
6839 * @param {Object|string} [data] Value of the item to select, omit to deselect all
6840 * @fires select
6841 * @chainable
6842 */
6843 OO.ui.SelectWidget.prototype.selectItemByData = function ( data ) {
6844 var itemFromData = this.findItemFromData( data );
6845 if ( data === undefined || !itemFromData ) {
6846 return this.selectItem();
6847 }
6848 return this.selectItem( itemFromData );
6849 };
6850
6851 /**
6852 * Programmatically select an option by its reference. If the `item` parameter is omitted,
6853 * all options will be deselected.
6854 *
6855 * @param {OO.ui.OptionWidget} [item] Item to select, omit to deselect all
6856 * @fires select
6857 * @chainable
6858 */
6859 OO.ui.SelectWidget.prototype.selectItem = function ( item ) {
6860 var i, len, selected,
6861 changed = false;
6862
6863 for ( i = 0, len = this.items.length; i < len; i++ ) {
6864 selected = this.items[ i ] === item;
6865 if ( this.items[ i ].isSelected() !== selected ) {
6866 this.items[ i ].setSelected( selected );
6867 changed = true;
6868 }
6869 }
6870 if ( changed ) {
6871 if ( item && !item.constructor.static.highlightable ) {
6872 if ( item ) {
6873 this.$focusOwner.attr( 'aria-activedescendant', item.getElementId() );
6874 } else {
6875 this.$focusOwner.removeAttr( 'aria-activedescendant' );
6876 }
6877 }
6878 this.emit( 'select', item );
6879 }
6880
6881 return this;
6882 };
6883
6884 /**
6885 * Press an item.
6886 *
6887 * Press is a state that occurs when a user mouses down on an item, but has not
6888 * yet let go of the mouse. The item may appear selected, but it will not be selected until the user
6889 * releases the mouse.
6890 *
6891 * @param {OO.ui.OptionWidget} [item] Item to press, omit to depress all
6892 * @fires press
6893 * @chainable
6894 */
6895 OO.ui.SelectWidget.prototype.pressItem = function ( item ) {
6896 var i, len, pressed,
6897 changed = false;
6898
6899 for ( i = 0, len = this.items.length; i < len; i++ ) {
6900 pressed = this.items[ i ] === item;
6901 if ( this.items[ i ].isPressed() !== pressed ) {
6902 this.items[ i ].setPressed( pressed );
6903 changed = true;
6904 }
6905 }
6906 if ( changed ) {
6907 this.emit( 'press', item );
6908 }
6909
6910 return this;
6911 };
6912
6913 /**
6914 * Choose an item.
6915 *
6916 * Note that ‘choose’ should never be modified programmatically. A user can choose
6917 * an option with the keyboard or mouse and it becomes selected. To select an item programmatically,
6918 * use the #selectItem method.
6919 *
6920 * This method is identical to #selectItem, but may vary in subclasses that take additional action
6921 * when users choose an item with the keyboard or mouse.
6922 *
6923 * @param {OO.ui.OptionWidget} item Item to choose
6924 * @fires choose
6925 * @chainable
6926 */
6927 OO.ui.SelectWidget.prototype.chooseItem = function ( item ) {
6928 if ( item ) {
6929 this.selectItem( item );
6930 this.emit( 'choose', item );
6931 }
6932
6933 return this;
6934 };
6935
6936 /**
6937 * Find an option by its position relative to the specified item (or to the start of the option array,
6938 * if item is `null`). The direction in which to search through the option array is specified with a
6939 * number: -1 for reverse (the default) or 1 for forward. The method will return an option, or
6940 * `null` if there are no options in the array.
6941 *
6942 * @param {OO.ui.OptionWidget|null} item Item to describe the start position, or `null` to start at the beginning of the array.
6943 * @param {number} direction Direction to move in: -1 to move backward, 1 to move forward
6944 * @param {Function} [filter] Only consider items for which this function returns
6945 * true. Function takes an OO.ui.OptionWidget and returns a boolean.
6946 * @return {OO.ui.OptionWidget|null} Item at position, `null` if there are no items in the select
6947 */
6948 OO.ui.SelectWidget.prototype.findRelativeSelectableItem = function ( item, direction, filter ) {
6949 var currentIndex, nextIndex, i,
6950 increase = direction > 0 ? 1 : -1,
6951 len = this.items.length;
6952
6953 if ( item instanceof OO.ui.OptionWidget ) {
6954 currentIndex = this.items.indexOf( item );
6955 nextIndex = ( currentIndex + increase + len ) % len;
6956 } else {
6957 // If no item is selected and moving forward, start at the beginning.
6958 // If moving backward, start at the end.
6959 nextIndex = direction > 0 ? 0 : len - 1;
6960 }
6961
6962 for ( i = 0; i < len; i++ ) {
6963 item = this.items[ nextIndex ];
6964 if (
6965 item instanceof OO.ui.OptionWidget && item.isSelectable() &&
6966 ( !filter || filter( item ) )
6967 ) {
6968 return item;
6969 }
6970 nextIndex = ( nextIndex + increase + len ) % len;
6971 }
6972 return null;
6973 };
6974
6975 /**
6976 * Find the next selectable item or `null` if there are no selectable items.
6977 * Disabled options and menu-section markers and breaks are not selectable.
6978 *
6979 * @return {OO.ui.OptionWidget|null} Item, `null` if there aren't any selectable items
6980 */
6981 OO.ui.SelectWidget.prototype.findFirstSelectableItem = function () {
6982 return this.findRelativeSelectableItem( null, 1 );
6983 };
6984
6985 /**
6986 * Add an array of options to the select. Optionally, an index number can be used to
6987 * specify an insertion point.
6988 *
6989 * @param {OO.ui.OptionWidget[]} items Items to add
6990 * @param {number} [index] Index to insert items after
6991 * @fires add
6992 * @chainable
6993 */
6994 OO.ui.SelectWidget.prototype.addItems = function ( items, index ) {
6995 // Mixin method
6996 OO.ui.mixin.GroupWidget.prototype.addItems.call( this, items, index );
6997
6998 // Always provide an index, even if it was omitted
6999 this.emit( 'add', items, index === undefined ? this.items.length - items.length - 1 : index );
7000
7001 return this;
7002 };
7003
7004 /**
7005 * Remove the specified array of options from the select. Options will be detached
7006 * from the DOM, not removed, so they can be reused later. To remove all options from
7007 * the select, you may wish to use the #clearItems method instead.
7008 *
7009 * @param {OO.ui.OptionWidget[]} items Items to remove
7010 * @fires remove
7011 * @chainable
7012 */
7013 OO.ui.SelectWidget.prototype.removeItems = function ( items ) {
7014 var i, len, item;
7015
7016 // Deselect items being removed
7017 for ( i = 0, len = items.length; i < len; i++ ) {
7018 item = items[ i ];
7019 if ( item.isSelected() ) {
7020 this.selectItem( null );
7021 }
7022 }
7023
7024 // Mixin method
7025 OO.ui.mixin.GroupWidget.prototype.removeItems.call( this, items );
7026
7027 this.emit( 'remove', items );
7028
7029 return this;
7030 };
7031
7032 /**
7033 * Clear all options from the select. Options will be detached from the DOM, not removed,
7034 * so that they can be reused later. To remove a subset of options from the select, use
7035 * the #removeItems method.
7036 *
7037 * @fires remove
7038 * @chainable
7039 */
7040 OO.ui.SelectWidget.prototype.clearItems = function () {
7041 var items = this.items.slice();
7042
7043 // Mixin method
7044 OO.ui.mixin.GroupWidget.prototype.clearItems.call( this );
7045
7046 // Clear selection
7047 this.selectItem( null );
7048
7049 this.emit( 'remove', items );
7050
7051 return this;
7052 };
7053
7054 /**
7055 * Set the DOM element which has focus while the user is interacting with this SelectWidget.
7056 *
7057 * Currently this is just used to set `aria-activedescendant` on it.
7058 *
7059 * @protected
7060 * @param {jQuery} $focusOwner
7061 */
7062 OO.ui.SelectWidget.prototype.setFocusOwner = function ( $focusOwner ) {
7063 this.$focusOwner = $focusOwner;
7064 };
7065
7066 /**
7067 * DecoratedOptionWidgets are {@link OO.ui.OptionWidget options} that can be configured
7068 * with an {@link OO.ui.mixin.IconElement icon} and/or {@link OO.ui.mixin.IndicatorElement indicator}.
7069 * This class is used with OO.ui.SelectWidget to create a selection of mutually exclusive
7070 * options. For more information about options and selects, please see the
7071 * [OOUI documentation on MediaWiki][1].
7072 *
7073 * @example
7074 * // Decorated options in a select widget
7075 * var select = new OO.ui.SelectWidget( {
7076 * items: [
7077 * new OO.ui.DecoratedOptionWidget( {
7078 * data: 'a',
7079 * label: 'Option with icon',
7080 * icon: 'help'
7081 * } ),
7082 * new OO.ui.DecoratedOptionWidget( {
7083 * data: 'b',
7084 * label: 'Option with indicator',
7085 * indicator: 'next'
7086 * } )
7087 * ]
7088 * } );
7089 * $( 'body' ).append( select.$element );
7090 *
7091 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options
7092 *
7093 * @class
7094 * @extends OO.ui.OptionWidget
7095 * @mixins OO.ui.mixin.IconElement
7096 * @mixins OO.ui.mixin.IndicatorElement
7097 *
7098 * @constructor
7099 * @param {Object} [config] Configuration options
7100 */
7101 OO.ui.DecoratedOptionWidget = function OoUiDecoratedOptionWidget( config ) {
7102 // Parent constructor
7103 OO.ui.DecoratedOptionWidget.parent.call( this, config );
7104
7105 // Mixin constructors
7106 OO.ui.mixin.IconElement.call( this, config );
7107 OO.ui.mixin.IndicatorElement.call( this, config );
7108
7109 // Initialization
7110 this.$element
7111 .addClass( 'oo-ui-decoratedOptionWidget' )
7112 .prepend( this.$icon )
7113 .append( this.$indicator );
7114 };
7115
7116 /* Setup */
7117
7118 OO.inheritClass( OO.ui.DecoratedOptionWidget, OO.ui.OptionWidget );
7119 OO.mixinClass( OO.ui.DecoratedOptionWidget, OO.ui.mixin.IconElement );
7120 OO.mixinClass( OO.ui.DecoratedOptionWidget, OO.ui.mixin.IndicatorElement );
7121
7122 /**
7123 * MenuOptionWidget is an option widget that looks like a menu item. The class is used with
7124 * OO.ui.MenuSelectWidget to create a menu of mutually exclusive options. Please see
7125 * the [OOUI documentation on MediaWiki] [1] for more information.
7126 *
7127 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options#Menu_selects_and_options
7128 *
7129 * @class
7130 * @extends OO.ui.DecoratedOptionWidget
7131 *
7132 * @constructor
7133 * @param {Object} [config] Configuration options
7134 */
7135 OO.ui.MenuOptionWidget = function OoUiMenuOptionWidget( config ) {
7136 // Parent constructor
7137 OO.ui.MenuOptionWidget.parent.call( this, config );
7138
7139 // Properties
7140 this.checkIcon = new OO.ui.IconWidget( {
7141 icon: 'check',
7142 classes: [ 'oo-ui-menuOptionWidget-checkIcon' ]
7143 } );
7144
7145 // Initialization
7146 this.$element
7147 .prepend( this.checkIcon.$element )
7148 .addClass( 'oo-ui-menuOptionWidget' );
7149 };
7150
7151 /* Setup */
7152
7153 OO.inheritClass( OO.ui.MenuOptionWidget, OO.ui.DecoratedOptionWidget );
7154
7155 /* Static Properties */
7156
7157 /**
7158 * @static
7159 * @inheritdoc
7160 */
7161 OO.ui.MenuOptionWidget.static.scrollIntoViewOnSelect = true;
7162
7163 /**
7164 * MenuSectionOptionWidgets are used inside {@link OO.ui.MenuSelectWidget menu select widgets} to group one or more related
7165 * {@link OO.ui.MenuOptionWidget menu options}. MenuSectionOptionWidgets cannot be highlighted or selected.
7166 *
7167 * @example
7168 * var myDropdown = new OO.ui.DropdownWidget( {
7169 * menu: {
7170 * items: [
7171 * new OO.ui.MenuSectionOptionWidget( {
7172 * label: 'Dogs'
7173 * } ),
7174 * new OO.ui.MenuOptionWidget( {
7175 * data: 'corgi',
7176 * label: 'Welsh Corgi'
7177 * } ),
7178 * new OO.ui.MenuOptionWidget( {
7179 * data: 'poodle',
7180 * label: 'Standard Poodle'
7181 * } ),
7182 * new OO.ui.MenuSectionOptionWidget( {
7183 * label: 'Cats'
7184 * } ),
7185 * new OO.ui.MenuOptionWidget( {
7186 * data: 'lion',
7187 * label: 'Lion'
7188 * } )
7189 * ]
7190 * }
7191 * } );
7192 * $( 'body' ).append( myDropdown.$element );
7193 *
7194 * @class
7195 * @extends OO.ui.DecoratedOptionWidget
7196 *
7197 * @constructor
7198 * @param {Object} [config] Configuration options
7199 */
7200 OO.ui.MenuSectionOptionWidget = function OoUiMenuSectionOptionWidget( config ) {
7201 // Parent constructor
7202 OO.ui.MenuSectionOptionWidget.parent.call( this, config );
7203
7204 // Initialization
7205 this.$element.addClass( 'oo-ui-menuSectionOptionWidget' )
7206 .removeAttr( 'role aria-selected' );
7207 };
7208
7209 /* Setup */
7210
7211 OO.inheritClass( OO.ui.MenuSectionOptionWidget, OO.ui.DecoratedOptionWidget );
7212
7213 /* Static Properties */
7214
7215 /**
7216 * @static
7217 * @inheritdoc
7218 */
7219 OO.ui.MenuSectionOptionWidget.static.selectable = false;
7220
7221 /**
7222 * @static
7223 * @inheritdoc
7224 */
7225 OO.ui.MenuSectionOptionWidget.static.highlightable = false;
7226
7227 /**
7228 * MenuSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains options and
7229 * is used together with OO.ui.MenuOptionWidget. It is designed be used as part of another widget.
7230 * See {@link OO.ui.DropdownWidget DropdownWidget}, {@link OO.ui.ComboBoxInputWidget ComboBoxInputWidget},
7231 * and {@link OO.ui.mixin.LookupElement LookupElement} for examples of widgets that contain menus.
7232 * MenuSelectWidgets themselves are not instantiated directly, rather subclassed
7233 * and customized to be opened, closed, and displayed as needed.
7234 *
7235 * By default, menus are clipped to the visible viewport and are not visible when a user presses the
7236 * mouse outside the menu.
7237 *
7238 * Menus also have support for keyboard interaction:
7239 *
7240 * - Enter/Return key: choose and select a menu option
7241 * - Up-arrow key: highlight the previous menu option
7242 * - Down-arrow key: highlight the next menu option
7243 * - Esc key: hide the menu
7244 *
7245 * Unlike most widgets, MenuSelectWidget is initially hidden and must be shown by calling #toggle.
7246 *
7247 * Please see the [OOUI documentation on MediaWiki][1] for more information.
7248 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options
7249 *
7250 * @class
7251 * @extends OO.ui.SelectWidget
7252 * @mixins OO.ui.mixin.ClippableElement
7253 * @mixins OO.ui.mixin.FloatableElement
7254 *
7255 * @constructor
7256 * @param {Object} [config] Configuration options
7257 * @cfg {OO.ui.TextInputWidget} [input] Text input used to implement option highlighting for menu items that match
7258 * the text the user types. This config is used by {@link OO.ui.ComboBoxInputWidget ComboBoxInputWidget}
7259 * and {@link OO.ui.mixin.LookupElement LookupElement}
7260 * @cfg {jQuery} [$input] Text input used to implement option highlighting for menu items that match
7261 * the text the user types. This config is used by {@link OO.ui.CapsuleMultiselectWidget CapsuleMultiselectWidget}
7262 * @cfg {OO.ui.Widget} [widget] Widget associated with the menu's active state. If the user clicks the mouse
7263 * anywhere on the page outside of this widget, the menu is hidden. For example, if there is a button
7264 * that toggles the menu's visibility on click, the menu will be hidden then re-shown when the user clicks
7265 * that button, unless the button (or its parent widget) is passed in here.
7266 * @cfg {boolean} [autoHide=true] Hide the menu when the mouse is pressed outside the menu.
7267 * @cfg {jQuery} [$autoCloseIgnore] If these elements are clicked, don't auto-hide the menu.
7268 * @cfg {boolean} [hideOnChoose=true] Hide the menu when the user chooses an option.
7269 * @cfg {boolean} [filterFromInput=false] Filter the displayed options from the input
7270 * @cfg {boolean} [highlightOnFilter] Highlight the first result when filtering
7271 * @cfg {number} [width] Width of the menu
7272 */
7273 OO.ui.MenuSelectWidget = function OoUiMenuSelectWidget( config ) {
7274 // Configuration initialization
7275 config = config || {};
7276
7277 // Parent constructor
7278 OO.ui.MenuSelectWidget.parent.call( this, config );
7279
7280 // Mixin constructors
7281 OO.ui.mixin.ClippableElement.call( this, $.extend( {}, config, { $clippable: this.$group } ) );
7282 OO.ui.mixin.FloatableElement.call( this, config );
7283
7284 // Properties
7285 this.autoHide = config.autoHide === undefined || !!config.autoHide;
7286 this.hideOnChoose = config.hideOnChoose === undefined || !!config.hideOnChoose;
7287 this.filterFromInput = !!config.filterFromInput;
7288 this.$input = config.$input ? config.$input : config.input ? config.input.$input : null;
7289 this.$widget = config.widget ? config.widget.$element : null;
7290 this.$autoCloseIgnore = config.$autoCloseIgnore || $( [] );
7291 this.onDocumentMouseDownHandler = this.onDocumentMouseDown.bind( this );
7292 this.onInputEditHandler = OO.ui.debounce( this.updateItemVisibility.bind( this ), 100 );
7293 this.highlightOnFilter = !!config.highlightOnFilter;
7294 this.width = config.width;
7295
7296 // Initialization
7297 this.$element.addClass( 'oo-ui-menuSelectWidget' );
7298 if ( config.widget ) {
7299 this.setFocusOwner( config.widget.$tabIndexed );
7300 }
7301
7302 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
7303 // that reference properties not initialized at that time of parent class construction
7304 // TODO: Find a better way to handle post-constructor setup
7305 this.visible = false;
7306 this.$element.addClass( 'oo-ui-element-hidden' );
7307 };
7308
7309 /* Setup */
7310
7311 OO.inheritClass( OO.ui.MenuSelectWidget, OO.ui.SelectWidget );
7312 OO.mixinClass( OO.ui.MenuSelectWidget, OO.ui.mixin.ClippableElement );
7313 OO.mixinClass( OO.ui.MenuSelectWidget, OO.ui.mixin.FloatableElement );
7314
7315 /* Events */
7316
7317 /**
7318 * @event ready
7319 *
7320 * The menu is ready: it is visible and has been positioned and clipped.
7321 */
7322
7323 /* Methods */
7324
7325 /**
7326 * Handles document mouse down events.
7327 *
7328 * @protected
7329 * @param {MouseEvent} e Mouse down event
7330 */
7331 OO.ui.MenuSelectWidget.prototype.onDocumentMouseDown = function ( e ) {
7332 if (
7333 this.isVisible() &&
7334 !OO.ui.contains(
7335 this.$element.add( this.$widget ).add( this.$autoCloseIgnore ).get(),
7336 e.target,
7337 true
7338 )
7339 ) {
7340 this.toggle( false );
7341 }
7342 };
7343
7344 /**
7345 * @inheritdoc
7346 */
7347 OO.ui.MenuSelectWidget.prototype.onKeyDown = function ( e ) {
7348 var currentItem = this.findHighlightedItem() || this.findSelectedItem();
7349
7350 if ( !this.isDisabled() && this.isVisible() ) {
7351 switch ( e.keyCode ) {
7352 case OO.ui.Keys.LEFT:
7353 case OO.ui.Keys.RIGHT:
7354 // Do nothing if a text field is associated, arrow keys will be handled natively
7355 if ( !this.$input ) {
7356 OO.ui.MenuSelectWidget.parent.prototype.onKeyDown.call( this, e );
7357 }
7358 break;
7359 case OO.ui.Keys.ESCAPE:
7360 case OO.ui.Keys.TAB:
7361 if ( currentItem ) {
7362 currentItem.setHighlighted( false );
7363 }
7364 this.toggle( false );
7365 // Don't prevent tabbing away, prevent defocusing
7366 if ( e.keyCode === OO.ui.Keys.ESCAPE ) {
7367 e.preventDefault();
7368 e.stopPropagation();
7369 }
7370 break;
7371 default:
7372 OO.ui.MenuSelectWidget.parent.prototype.onKeyDown.call( this, e );
7373 return;
7374 }
7375 }
7376 };
7377
7378 /**
7379 * Update menu item visibility and clipping after input changes (if filterFromInput is enabled)
7380 * or after items were added/removed (always).
7381 *
7382 * @protected
7383 */
7384 OO.ui.MenuSelectWidget.prototype.updateItemVisibility = function () {
7385 var i, item, visible, section, sectionEmpty, filter, exactFilter,
7386 firstItemFound = false,
7387 anyVisible = false,
7388 len = this.items.length,
7389 showAll = !this.isVisible(),
7390 exactMatch = false;
7391
7392 if ( this.$input && this.filterFromInput ) {
7393 filter = showAll ? null : this.getItemMatcher( this.$input.val() );
7394 exactFilter = this.getItemMatcher( this.$input.val(), true );
7395
7396 // Hide non-matching options, and also hide section headers if all options
7397 // in their section are hidden.
7398 for ( i = 0; i < len; i++ ) {
7399 item = this.items[ i ];
7400 if ( item instanceof OO.ui.MenuSectionOptionWidget ) {
7401 if ( section ) {
7402 // If the previous section was empty, hide its header
7403 section.toggle( showAll || !sectionEmpty );
7404 }
7405 section = item;
7406 sectionEmpty = true;
7407 } else if ( item instanceof OO.ui.OptionWidget ) {
7408 visible = showAll || filter( item );
7409 exactMatch = exactMatch || exactFilter( item );
7410 anyVisible = anyVisible || visible;
7411 sectionEmpty = sectionEmpty && !visible;
7412 item.toggle( visible );
7413 if ( this.highlightOnFilter && visible && !firstItemFound ) {
7414 // Highlight the first item in the list
7415 this.highlightItem( item );
7416 firstItemFound = true;
7417 }
7418 }
7419 }
7420 // Process the final section
7421 if ( section ) {
7422 section.toggle( showAll || !sectionEmpty );
7423 }
7424
7425 if ( anyVisible && this.items.length && !exactMatch ) {
7426 this.scrollItemIntoView( this.items[ 0 ] );
7427 }
7428
7429 this.$element.toggleClass( 'oo-ui-menuSelectWidget-invisible', !anyVisible );
7430 }
7431
7432 // Reevaluate clipping
7433 this.clip();
7434 };
7435
7436 /**
7437 * @inheritdoc
7438 */
7439 OO.ui.MenuSelectWidget.prototype.bindKeyDownListener = function () {
7440 if ( this.$input ) {
7441 this.$input.on( 'keydown', this.onKeyDownHandler );
7442 } else {
7443 OO.ui.MenuSelectWidget.parent.prototype.bindKeyDownListener.call( this );
7444 }
7445 };
7446
7447 /**
7448 * @inheritdoc
7449 */
7450 OO.ui.MenuSelectWidget.prototype.unbindKeyDownListener = function () {
7451 if ( this.$input ) {
7452 this.$input.off( 'keydown', this.onKeyDownHandler );
7453 } else {
7454 OO.ui.MenuSelectWidget.parent.prototype.unbindKeyDownListener.call( this );
7455 }
7456 };
7457
7458 /**
7459 * @inheritdoc
7460 */
7461 OO.ui.MenuSelectWidget.prototype.bindKeyPressListener = function () {
7462 if ( this.$input ) {
7463 if ( this.filterFromInput ) {
7464 this.$input.on( 'keydown mouseup cut paste change input select', this.onInputEditHandler );
7465 this.updateItemVisibility();
7466 }
7467 } else {
7468 OO.ui.MenuSelectWidget.parent.prototype.bindKeyPressListener.call( this );
7469 }
7470 };
7471
7472 /**
7473 * @inheritdoc
7474 */
7475 OO.ui.MenuSelectWidget.prototype.unbindKeyPressListener = function () {
7476 if ( this.$input ) {
7477 if ( this.filterFromInput ) {
7478 this.$input.off( 'keydown mouseup cut paste change input select', this.onInputEditHandler );
7479 this.updateItemVisibility();
7480 }
7481 } else {
7482 OO.ui.MenuSelectWidget.parent.prototype.unbindKeyPressListener.call( this );
7483 }
7484 };
7485
7486 /**
7487 * Choose an item.
7488 *
7489 * When a user chooses an item, the menu is closed, unless the hideOnChoose config option is set to false.
7490 *
7491 * Note that ‘choose’ should never be modified programmatically. A user can choose an option with the keyboard
7492 * or mouse and it becomes selected. To select an item programmatically, use the #selectItem method.
7493 *
7494 * @param {OO.ui.OptionWidget} item Item to choose
7495 * @chainable
7496 */
7497 OO.ui.MenuSelectWidget.prototype.chooseItem = function ( item ) {
7498 OO.ui.MenuSelectWidget.parent.prototype.chooseItem.call( this, item );
7499 if ( this.hideOnChoose ) {
7500 this.toggle( false );
7501 }
7502 return this;
7503 };
7504
7505 /**
7506 * @inheritdoc
7507 */
7508 OO.ui.MenuSelectWidget.prototype.addItems = function ( items, index ) {
7509 // Parent method
7510 OO.ui.MenuSelectWidget.parent.prototype.addItems.call( this, items, index );
7511
7512 this.updateItemVisibility();
7513
7514 return this;
7515 };
7516
7517 /**
7518 * @inheritdoc
7519 */
7520 OO.ui.MenuSelectWidget.prototype.removeItems = function ( items ) {
7521 // Parent method
7522 OO.ui.MenuSelectWidget.parent.prototype.removeItems.call( this, items );
7523
7524 this.updateItemVisibility();
7525
7526 return this;
7527 };
7528
7529 /**
7530 * @inheritdoc
7531 */
7532 OO.ui.MenuSelectWidget.prototype.clearItems = function () {
7533 // Parent method
7534 OO.ui.MenuSelectWidget.parent.prototype.clearItems.call( this );
7535
7536 this.updateItemVisibility();
7537
7538 return this;
7539 };
7540
7541 /**
7542 * Toggle visibility of the menu. The menu is initially hidden and must be shown by calling
7543 * `.toggle( true )` after its #$element is attached to the DOM.
7544 *
7545 * Do not show the menu while it is not attached to the DOM. The calculations required to display
7546 * it in the right place and with the right dimensions only work correctly while it is attached.
7547 * Side-effects may include broken interface and exceptions being thrown. This wasn't always
7548 * strictly enforced, so currently it only generates a warning in the browser console.
7549 *
7550 * @fires ready
7551 * @inheritdoc
7552 */
7553 OO.ui.MenuSelectWidget.prototype.toggle = function ( visible ) {
7554 var change, belowHeight, aboveHeight;
7555
7556 visible = ( visible === undefined ? !this.visible : !!visible ) && !!this.items.length;
7557 change = visible !== this.isVisible();
7558
7559 if ( visible && !this.warnedUnattached && !this.isElementAttached() ) {
7560 OO.ui.warnDeprecation( 'MenuSelectWidget#toggle: Before calling this method, the menu must be attached to the DOM.' );
7561 this.warnedUnattached = true;
7562 }
7563
7564 if ( change && visible ) {
7565 // Reset position before showing the popup again. It's possible we no longer need to flip
7566 // (e.g. if the user scrolled).
7567 this.setVerticalPosition( 'below' );
7568 }
7569
7570 // Parent method
7571 OO.ui.MenuSelectWidget.parent.prototype.toggle.call( this, visible );
7572
7573 if ( change ) {
7574 if ( visible ) {
7575
7576 if ( this.width ) {
7577 this.setIdealSize( this.width );
7578 } else if ( this.$floatableContainer ) {
7579 this.$clippable.css( 'width', 'auto' );
7580 this.setIdealSize(
7581 this.$floatableContainer[ 0 ].offsetWidth > this.$clippable[ 0 ].offsetWidth ?
7582 // Dropdown is smaller than handle so expand to width
7583 this.$floatableContainer[ 0 ].offsetWidth :
7584 // Dropdown is larger than handle so auto size
7585 'auto'
7586 );
7587 this.$clippable.css( 'width', '' );
7588 }
7589
7590 this.togglePositioning( !!this.$floatableContainer );
7591 this.toggleClipping( true );
7592
7593 this.bindKeyDownListener();
7594 this.bindKeyPressListener();
7595
7596 if ( this.isClippedVertically() || this.isFloatableOutOfView() ) {
7597 // If opening the menu downwards causes it to be clipped, flip it to open upwards instead
7598 belowHeight = this.$element.height();
7599 this.setVerticalPosition( 'above' );
7600 if ( this.isClippedVertically() || this.isFloatableOutOfView() ) {
7601 // If opening upwards also causes it to be clipped, flip it to open in whichever direction
7602 // we have more space
7603 aboveHeight = this.$element.height();
7604 if ( aboveHeight < belowHeight ) {
7605 this.setVerticalPosition( 'below' );
7606 }
7607 }
7608 }
7609 // Note that we do not flip the menu's opening direction if the clipping changes
7610 // later (e.g. after the user scrolls), that seems like it would be annoying
7611
7612 this.$focusOwner.attr( 'aria-expanded', 'true' );
7613
7614 if ( this.findSelectedItem() ) {
7615 this.$focusOwner.attr( 'aria-activedescendant', this.findSelectedItem().getElementId() );
7616 this.findSelectedItem().scrollElementIntoView( { duration: 0 } );
7617 }
7618
7619 // Auto-hide
7620 if ( this.autoHide ) {
7621 this.getElementDocument().addEventListener( 'mousedown', this.onDocumentMouseDownHandler, true );
7622 }
7623
7624 this.emit( 'ready' );
7625 } else {
7626 this.$focusOwner.removeAttr( 'aria-activedescendant' );
7627 this.unbindKeyDownListener();
7628 this.unbindKeyPressListener();
7629 this.$focusOwner.attr( 'aria-expanded', 'false' );
7630 this.getElementDocument().removeEventListener( 'mousedown', this.onDocumentMouseDownHandler, true );
7631 this.togglePositioning( false );
7632 this.toggleClipping( false );
7633 }
7634 }
7635
7636 return this;
7637 };
7638
7639 /**
7640 * DropdownWidgets are not menus themselves, rather they contain a menu of options created with
7641 * OO.ui.MenuOptionWidget. The DropdownWidget takes care of opening and displaying the menu so that
7642 * users can interact with it.
7643 *
7644 * If you want to use this within an HTML form, such as a OO.ui.FormLayout, use
7645 * OO.ui.DropdownInputWidget instead.
7646 *
7647 * @example
7648 * // Example: A DropdownWidget with a menu that contains three options
7649 * var dropDown = new OO.ui.DropdownWidget( {
7650 * label: 'Dropdown menu: Select a menu option',
7651 * menu: {
7652 * items: [
7653 * new OO.ui.MenuOptionWidget( {
7654 * data: 'a',
7655 * label: 'First'
7656 * } ),
7657 * new OO.ui.MenuOptionWidget( {
7658 * data: 'b',
7659 * label: 'Second'
7660 * } ),
7661 * new OO.ui.MenuOptionWidget( {
7662 * data: 'c',
7663 * label: 'Third'
7664 * } )
7665 * ]
7666 * }
7667 * } );
7668 *
7669 * $( 'body' ).append( dropDown.$element );
7670 *
7671 * dropDown.getMenu().selectItemByData( 'b' );
7672 *
7673 * dropDown.getMenu().findSelectedItem().getData(); // returns 'b'
7674 *
7675 * For more information, please see the [OOUI documentation on MediaWiki] [1].
7676 *
7677 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options#Menu_selects_and_options
7678 *
7679 * @class
7680 * @extends OO.ui.Widget
7681 * @mixins OO.ui.mixin.IconElement
7682 * @mixins OO.ui.mixin.IndicatorElement
7683 * @mixins OO.ui.mixin.LabelElement
7684 * @mixins OO.ui.mixin.TitledElement
7685 * @mixins OO.ui.mixin.TabIndexedElement
7686 *
7687 * @constructor
7688 * @param {Object} [config] Configuration options
7689 * @cfg {Object} [menu] Configuration options to pass to {@link OO.ui.MenuSelectWidget menu select widget}
7690 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
7691 * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
7692 * containing `<div>` and has a larger area. By default, the menu uses relative positioning.
7693 * See <https://www.mediawiki.org/wiki/OOUI/Concepts#Overlays>.
7694 */
7695 OO.ui.DropdownWidget = function OoUiDropdownWidget( config ) {
7696 // Configuration initialization
7697 config = $.extend( { indicator: 'down' }, config );
7698
7699 // Parent constructor
7700 OO.ui.DropdownWidget.parent.call( this, config );
7701
7702 // Properties (must be set before TabIndexedElement constructor call)
7703 this.$handle = $( '<span>' );
7704 this.$overlay = ( config.$overlay === true ? OO.ui.getDefaultOverlay() : config.$overlay ) || this.$element;
7705
7706 // Mixin constructors
7707 OO.ui.mixin.IconElement.call( this, config );
7708 OO.ui.mixin.IndicatorElement.call( this, config );
7709 OO.ui.mixin.LabelElement.call( this, config );
7710 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$label } ) );
7711 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$handle } ) );
7712
7713 // Properties
7714 this.menu = new OO.ui.MenuSelectWidget( $.extend( {
7715 widget: this,
7716 $floatableContainer: this.$element
7717 }, config.menu ) );
7718
7719 // Events
7720 this.$handle.on( {
7721 click: this.onClick.bind( this ),
7722 keydown: this.onKeyDown.bind( this ),
7723 // Hack? Handle type-to-search when menu is not expanded and not handling its own events
7724 keypress: this.menu.onKeyPressHandler,
7725 blur: this.menu.clearKeyPressBuffer.bind( this.menu )
7726 } );
7727 this.menu.connect( this, {
7728 select: 'onMenuSelect',
7729 toggle: 'onMenuToggle'
7730 } );
7731
7732 // Initialization
7733 this.$handle
7734 .addClass( 'oo-ui-dropdownWidget-handle' )
7735 .attr( {
7736 role: 'combobox',
7737 'aria-owns': this.menu.getElementId(),
7738 'aria-autocomplete': 'list'
7739 } )
7740 .append( this.$icon, this.$label, this.$indicator );
7741 this.$element
7742 .addClass( 'oo-ui-dropdownWidget' )
7743 .append( this.$handle );
7744 this.$overlay.append( this.menu.$element );
7745 };
7746
7747 /* Setup */
7748
7749 OO.inheritClass( OO.ui.DropdownWidget, OO.ui.Widget );
7750 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.IconElement );
7751 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.IndicatorElement );
7752 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.LabelElement );
7753 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.TitledElement );
7754 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.TabIndexedElement );
7755
7756 /* Methods */
7757
7758 /**
7759 * Get the menu.
7760 *
7761 * @return {OO.ui.MenuSelectWidget} Menu of widget
7762 */
7763 OO.ui.DropdownWidget.prototype.getMenu = function () {
7764 return this.menu;
7765 };
7766
7767 /**
7768 * Handles menu select events.
7769 *
7770 * @private
7771 * @param {OO.ui.MenuOptionWidget} item Selected menu item
7772 */
7773 OO.ui.DropdownWidget.prototype.onMenuSelect = function ( item ) {
7774 var selectedLabel;
7775
7776 if ( !item ) {
7777 this.setLabel( null );
7778 return;
7779 }
7780
7781 selectedLabel = item.getLabel();
7782
7783 // If the label is a DOM element, clone it, because setLabel will append() it
7784 if ( selectedLabel instanceof jQuery ) {
7785 selectedLabel = selectedLabel.clone();
7786 }
7787
7788 this.setLabel( selectedLabel );
7789 };
7790
7791 /**
7792 * Handle menu toggle events.
7793 *
7794 * @private
7795 * @param {boolean} isVisible Open state of the menu
7796 */
7797 OO.ui.DropdownWidget.prototype.onMenuToggle = function ( isVisible ) {
7798 this.$element.toggleClass( 'oo-ui-dropdownWidget-open', isVisible );
7799 this.$handle.attr(
7800 'aria-expanded',
7801 this.$element.hasClass( 'oo-ui-dropdownWidget-open' ).toString()
7802 );
7803 };
7804
7805 /**
7806 * Handle mouse click events.
7807 *
7808 * @private
7809 * @param {jQuery.Event} e Mouse click event
7810 */
7811 OO.ui.DropdownWidget.prototype.onClick = function ( e ) {
7812 if ( !this.isDisabled() && e.which === OO.ui.MouseButtons.LEFT ) {
7813 this.menu.toggle();
7814 }
7815 return false;
7816 };
7817
7818 /**
7819 * Handle key down events.
7820 *
7821 * @private
7822 * @param {jQuery.Event} e Key down event
7823 */
7824 OO.ui.DropdownWidget.prototype.onKeyDown = function ( e ) {
7825 if (
7826 !this.isDisabled() &&
7827 (
7828 e.which === OO.ui.Keys.ENTER ||
7829 (
7830 e.which === OO.ui.Keys.SPACE &&
7831 // Avoid conflicts with type-to-search, see SelectWidget#onKeyPress.
7832 // Space only closes the menu is the user is not typing to search.
7833 this.menu.keyPressBuffer === ''
7834 ) ||
7835 (
7836 !this.menu.isVisible() &&
7837 (
7838 e.which === OO.ui.Keys.UP ||
7839 e.which === OO.ui.Keys.DOWN
7840 )
7841 )
7842 )
7843 ) {
7844 this.menu.toggle();
7845 return false;
7846 }
7847 };
7848
7849 /**
7850 * RadioOptionWidget is an option widget that looks like a radio button.
7851 * The class is used with OO.ui.RadioSelectWidget to create a selection of radio options.
7852 * Please see the [OOUI documentation on MediaWiki] [1] for more information.
7853 *
7854 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options#Button_selects_and_option
7855 *
7856 * @class
7857 * @extends OO.ui.OptionWidget
7858 *
7859 * @constructor
7860 * @param {Object} [config] Configuration options
7861 */
7862 OO.ui.RadioOptionWidget = function OoUiRadioOptionWidget( config ) {
7863 // Configuration initialization
7864 config = config || {};
7865
7866 // Properties (must be done before parent constructor which calls #setDisabled)
7867 this.radio = new OO.ui.RadioInputWidget( { value: config.data, tabIndex: -1 } );
7868
7869 // Parent constructor
7870 OO.ui.RadioOptionWidget.parent.call( this, config );
7871
7872 // Initialization
7873 // Remove implicit role, we're handling it ourselves
7874 this.radio.$input.attr( 'role', 'presentation' );
7875 this.$element
7876 .addClass( 'oo-ui-radioOptionWidget' )
7877 .attr( 'role', 'radio' )
7878 .attr( 'aria-checked', 'false' )
7879 .removeAttr( 'aria-selected' )
7880 .prepend( this.radio.$element );
7881 };
7882
7883 /* Setup */
7884
7885 OO.inheritClass( OO.ui.RadioOptionWidget, OO.ui.OptionWidget );
7886
7887 /* Static Properties */
7888
7889 /**
7890 * @static
7891 * @inheritdoc
7892 */
7893 OO.ui.RadioOptionWidget.static.highlightable = false;
7894
7895 /**
7896 * @static
7897 * @inheritdoc
7898 */
7899 OO.ui.RadioOptionWidget.static.scrollIntoViewOnSelect = true;
7900
7901 /**
7902 * @static
7903 * @inheritdoc
7904 */
7905 OO.ui.RadioOptionWidget.static.pressable = false;
7906
7907 /**
7908 * @static
7909 * @inheritdoc
7910 */
7911 OO.ui.RadioOptionWidget.static.tagName = 'label';
7912
7913 /* Methods */
7914
7915 /**
7916 * @inheritdoc
7917 */
7918 OO.ui.RadioOptionWidget.prototype.setSelected = function ( state ) {
7919 OO.ui.RadioOptionWidget.parent.prototype.setSelected.call( this, state );
7920
7921 this.radio.setSelected( state );
7922 this.$element
7923 .attr( 'aria-checked', state.toString() )
7924 .removeAttr( 'aria-selected' );
7925
7926 return this;
7927 };
7928
7929 /**
7930 * @inheritdoc
7931 */
7932 OO.ui.RadioOptionWidget.prototype.setDisabled = function ( disabled ) {
7933 OO.ui.RadioOptionWidget.parent.prototype.setDisabled.call( this, disabled );
7934
7935 this.radio.setDisabled( this.isDisabled() );
7936
7937 return this;
7938 };
7939
7940 /**
7941 * RadioSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains radio
7942 * options and is used together with OO.ui.RadioOptionWidget. The RadioSelectWidget provides
7943 * an interface for adding, removing and selecting options.
7944 * Please see the [OOUI documentation on MediaWiki][1] for more information.
7945 *
7946 * If you want to use this within an HTML form, such as a OO.ui.FormLayout, use
7947 * OO.ui.RadioSelectInputWidget instead.
7948 *
7949 * @example
7950 * // A RadioSelectWidget with RadioOptions.
7951 * var option1 = new OO.ui.RadioOptionWidget( {
7952 * data: 'a',
7953 * label: 'Selected radio option'
7954 * } );
7955 *
7956 * var option2 = new OO.ui.RadioOptionWidget( {
7957 * data: 'b',
7958 * label: 'Unselected radio option'
7959 * } );
7960 *
7961 * var radioSelect=new OO.ui.RadioSelectWidget( {
7962 * items: [ option1, option2 ]
7963 * } );
7964 *
7965 * // Select 'option 1' using the RadioSelectWidget's selectItem() method.
7966 * radioSelect.selectItem( option1 );
7967 *
7968 * $( 'body' ).append( radioSelect.$element );
7969 *
7970 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options
7971
7972 *
7973 * @class
7974 * @extends OO.ui.SelectWidget
7975 * @mixins OO.ui.mixin.TabIndexedElement
7976 *
7977 * @constructor
7978 * @param {Object} [config] Configuration options
7979 */
7980 OO.ui.RadioSelectWidget = function OoUiRadioSelectWidget( config ) {
7981 // Parent constructor
7982 OO.ui.RadioSelectWidget.parent.call( this, config );
7983
7984 // Mixin constructors
7985 OO.ui.mixin.TabIndexedElement.call( this, config );
7986
7987 // Events
7988 this.$element.on( {
7989 focus: this.bindKeyDownListener.bind( this ),
7990 blur: this.unbindKeyDownListener.bind( this )
7991 } );
7992
7993 // Initialization
7994 this.$element
7995 .addClass( 'oo-ui-radioSelectWidget' )
7996 .attr( 'role', 'radiogroup' );
7997 };
7998
7999 /* Setup */
8000
8001 OO.inheritClass( OO.ui.RadioSelectWidget, OO.ui.SelectWidget );
8002 OO.mixinClass( OO.ui.RadioSelectWidget, OO.ui.mixin.TabIndexedElement );
8003
8004 /**
8005 * MultioptionWidgets are special elements that can be selected and configured with data. The
8006 * data is often unique for each option, but it does not have to be. MultioptionWidgets are used
8007 * with OO.ui.SelectWidget to create a selection of mutually exclusive options. For more information
8008 * and examples, please see the [OOUI documentation on MediaWiki][1].
8009 *
8010 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Multioptions
8011 *
8012 * @class
8013 * @extends OO.ui.Widget
8014 * @mixins OO.ui.mixin.ItemWidget
8015 * @mixins OO.ui.mixin.LabelElement
8016 *
8017 * @constructor
8018 * @param {Object} [config] Configuration options
8019 * @cfg {boolean} [selected=false] Whether the option is initially selected
8020 */
8021 OO.ui.MultioptionWidget = function OoUiMultioptionWidget( config ) {
8022 // Configuration initialization
8023 config = config || {};
8024
8025 // Parent constructor
8026 OO.ui.MultioptionWidget.parent.call( this, config );
8027
8028 // Mixin constructors
8029 OO.ui.mixin.ItemWidget.call( this );
8030 OO.ui.mixin.LabelElement.call( this, config );
8031
8032 // Properties
8033 this.selected = null;
8034
8035 // Initialization
8036 this.$element
8037 .addClass( 'oo-ui-multioptionWidget' )
8038 .append( this.$label );
8039 this.setSelected( config.selected );
8040 };
8041
8042 /* Setup */
8043
8044 OO.inheritClass( OO.ui.MultioptionWidget, OO.ui.Widget );
8045 OO.mixinClass( OO.ui.MultioptionWidget, OO.ui.mixin.ItemWidget );
8046 OO.mixinClass( OO.ui.MultioptionWidget, OO.ui.mixin.LabelElement );
8047
8048 /* Events */
8049
8050 /**
8051 * @event change
8052 *
8053 * A change event is emitted when the selected state of the option changes.
8054 *
8055 * @param {boolean} selected Whether the option is now selected
8056 */
8057
8058 /* Methods */
8059
8060 /**
8061 * Check if the option is selected.
8062 *
8063 * @return {boolean} Item is selected
8064 */
8065 OO.ui.MultioptionWidget.prototype.isSelected = function () {
8066 return this.selected;
8067 };
8068
8069 /**
8070 * Set the option’s selected state. In general, all modifications to the selection
8071 * should be handled by the SelectWidget’s {@link OO.ui.SelectWidget#selectItem selectItem( [item] )}
8072 * method instead of this method.
8073 *
8074 * @param {boolean} [state=false] Select option
8075 * @chainable
8076 */
8077 OO.ui.MultioptionWidget.prototype.setSelected = function ( state ) {
8078 state = !!state;
8079 if ( this.selected !== state ) {
8080 this.selected = state;
8081 this.emit( 'change', state );
8082 this.$element.toggleClass( 'oo-ui-multioptionWidget-selected', state );
8083 }
8084 return this;
8085 };
8086
8087 /**
8088 * MultiselectWidget allows selecting multiple options from a list.
8089 *
8090 * For more information about menus and options, please see the [OOUI documentation on MediaWiki][1].
8091 *
8092 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options#Menu_selects_and_options
8093 *
8094 * @class
8095 * @abstract
8096 * @extends OO.ui.Widget
8097 * @mixins OO.ui.mixin.GroupWidget
8098 *
8099 * @constructor
8100 * @param {Object} [config] Configuration options
8101 * @cfg {OO.ui.MultioptionWidget[]} [items] An array of options to add to the multiselect.
8102 */
8103 OO.ui.MultiselectWidget = function OoUiMultiselectWidget( config ) {
8104 // Parent constructor
8105 OO.ui.MultiselectWidget.parent.call( this, config );
8106
8107 // Configuration initialization
8108 config = config || {};
8109
8110 // Mixin constructors
8111 OO.ui.mixin.GroupWidget.call( this, config );
8112
8113 // Events
8114 this.aggregate( { change: 'select' } );
8115 // This is mostly for compatibility with CapsuleMultiselectWidget... normally, 'change' is emitted
8116 // by GroupElement only when items are added/removed
8117 this.connect( this, { select: [ 'emit', 'change' ] } );
8118
8119 // Initialization
8120 if ( config.items ) {
8121 this.addItems( config.items );
8122 }
8123 this.$group.addClass( 'oo-ui-multiselectWidget-group' );
8124 this.$element.addClass( 'oo-ui-multiselectWidget' )
8125 .append( this.$group );
8126 };
8127
8128 /* Setup */
8129
8130 OO.inheritClass( OO.ui.MultiselectWidget, OO.ui.Widget );
8131 OO.mixinClass( OO.ui.MultiselectWidget, OO.ui.mixin.GroupWidget );
8132
8133 /* Events */
8134
8135 /**
8136 * @event change
8137 *
8138 * A change event is emitted when the set of items changes, or an item is selected or deselected.
8139 */
8140
8141 /**
8142 * @event select
8143 *
8144 * A select event is emitted when an item is selected or deselected.
8145 */
8146
8147 /* Methods */
8148
8149 /**
8150 * Find options that are selected.
8151 *
8152 * @return {OO.ui.MultioptionWidget[]} Selected options
8153 */
8154 OO.ui.MultiselectWidget.prototype.findSelectedItems = function () {
8155 return this.items.filter( function ( item ) {
8156 return item.isSelected();
8157 } );
8158 };
8159
8160 /**
8161 * Find the data of options that are selected.
8162 *
8163 * @return {Object[]|string[]} Values of selected options
8164 */
8165 OO.ui.MultiselectWidget.prototype.findSelectedItemsData = function () {
8166 return this.findSelectedItems().map( function ( item ) {
8167 return item.data;
8168 } );
8169 };
8170
8171 /**
8172 * Select options by reference. Options not mentioned in the `items` array will be deselected.
8173 *
8174 * @param {OO.ui.MultioptionWidget[]} items Items to select
8175 * @chainable
8176 */
8177 OO.ui.MultiselectWidget.prototype.selectItems = function ( items ) {
8178 this.items.forEach( function ( item ) {
8179 var selected = items.indexOf( item ) !== -1;
8180 item.setSelected( selected );
8181 } );
8182 return this;
8183 };
8184
8185 /**
8186 * Select items by their data. Options not mentioned in the `datas` array will be deselected.
8187 *
8188 * @param {Object[]|string[]} datas Values of items to select
8189 * @chainable
8190 */
8191 OO.ui.MultiselectWidget.prototype.selectItemsByData = function ( datas ) {
8192 var items,
8193 widget = this;
8194 items = datas.map( function ( data ) {
8195 return widget.findItemFromData( data );
8196 } );
8197 this.selectItems( items );
8198 return this;
8199 };
8200
8201 /**
8202 * CheckboxMultioptionWidget is an option widget that looks like a checkbox.
8203 * The class is used with OO.ui.CheckboxMultiselectWidget to create a selection of checkbox options.
8204 * Please see the [OOUI documentation on MediaWiki] [1] for more information.
8205 *
8206 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options#Button_selects_and_option
8207 *
8208 * @class
8209 * @extends OO.ui.MultioptionWidget
8210 *
8211 * @constructor
8212 * @param {Object} [config] Configuration options
8213 */
8214 OO.ui.CheckboxMultioptionWidget = function OoUiCheckboxMultioptionWidget( config ) {
8215 // Configuration initialization
8216 config = config || {};
8217
8218 // Properties (must be done before parent constructor which calls #setDisabled)
8219 this.checkbox = new OO.ui.CheckboxInputWidget();
8220
8221 // Parent constructor
8222 OO.ui.CheckboxMultioptionWidget.parent.call( this, config );
8223
8224 // Events
8225 this.checkbox.on( 'change', this.onCheckboxChange.bind( this ) );
8226 this.$element.on( 'keydown', this.onKeyDown.bind( this ) );
8227
8228 // Initialization
8229 this.$element
8230 .addClass( 'oo-ui-checkboxMultioptionWidget' )
8231 .prepend( this.checkbox.$element );
8232 };
8233
8234 /* Setup */
8235
8236 OO.inheritClass( OO.ui.CheckboxMultioptionWidget, OO.ui.MultioptionWidget );
8237
8238 /* Static Properties */
8239
8240 /**
8241 * @static
8242 * @inheritdoc
8243 */
8244 OO.ui.CheckboxMultioptionWidget.static.tagName = 'label';
8245
8246 /* Methods */
8247
8248 /**
8249 * Handle checkbox selected state change.
8250 *
8251 * @private
8252 */
8253 OO.ui.CheckboxMultioptionWidget.prototype.onCheckboxChange = function () {
8254 this.setSelected( this.checkbox.isSelected() );
8255 };
8256
8257 /**
8258 * @inheritdoc
8259 */
8260 OO.ui.CheckboxMultioptionWidget.prototype.setSelected = function ( state ) {
8261 OO.ui.CheckboxMultioptionWidget.parent.prototype.setSelected.call( this, state );
8262 this.checkbox.setSelected( state );
8263 return this;
8264 };
8265
8266 /**
8267 * @inheritdoc
8268 */
8269 OO.ui.CheckboxMultioptionWidget.prototype.setDisabled = function ( disabled ) {
8270 OO.ui.CheckboxMultioptionWidget.parent.prototype.setDisabled.call( this, disabled );
8271 this.checkbox.setDisabled( this.isDisabled() );
8272 return this;
8273 };
8274
8275 /**
8276 * Focus the widget.
8277 */
8278 OO.ui.CheckboxMultioptionWidget.prototype.focus = function () {
8279 this.checkbox.focus();
8280 };
8281
8282 /**
8283 * Handle key down events.
8284 *
8285 * @protected
8286 * @param {jQuery.Event} e
8287 */
8288 OO.ui.CheckboxMultioptionWidget.prototype.onKeyDown = function ( e ) {
8289 var
8290 element = this.getElementGroup(),
8291 nextItem;
8292
8293 if ( e.keyCode === OO.ui.Keys.LEFT || e.keyCode === OO.ui.Keys.UP ) {
8294 nextItem = element.getRelativeFocusableItem( this, -1 );
8295 } else if ( e.keyCode === OO.ui.Keys.RIGHT || e.keyCode === OO.ui.Keys.DOWN ) {
8296 nextItem = element.getRelativeFocusableItem( this, 1 );
8297 }
8298
8299 if ( nextItem ) {
8300 e.preventDefault();
8301 nextItem.focus();
8302 }
8303 };
8304
8305 /**
8306 * CheckboxMultiselectWidget is a {@link OO.ui.MultiselectWidget multiselect widget} that contains
8307 * checkboxes and is used together with OO.ui.CheckboxMultioptionWidget. The
8308 * CheckboxMultiselectWidget provides an interface for adding, removing and selecting options.
8309 * Please see the [OOUI documentation on MediaWiki][1] for more information.
8310 *
8311 * If you want to use this within an HTML form, such as a OO.ui.FormLayout, use
8312 * OO.ui.CheckboxMultiselectInputWidget instead.
8313 *
8314 * @example
8315 * // A CheckboxMultiselectWidget with CheckboxMultioptions.
8316 * var option1 = new OO.ui.CheckboxMultioptionWidget( {
8317 * data: 'a',
8318 * selected: true,
8319 * label: 'Selected checkbox'
8320 * } );
8321 *
8322 * var option2 = new OO.ui.CheckboxMultioptionWidget( {
8323 * data: 'b',
8324 * label: 'Unselected checkbox'
8325 * } );
8326 *
8327 * var multiselect=new OO.ui.CheckboxMultiselectWidget( {
8328 * items: [ option1, option2 ]
8329 * } );
8330 *
8331 * $( 'body' ).append( multiselect.$element );
8332 *
8333 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options
8334 *
8335 * @class
8336 * @extends OO.ui.MultiselectWidget
8337 *
8338 * @constructor
8339 * @param {Object} [config] Configuration options
8340 */
8341 OO.ui.CheckboxMultiselectWidget = function OoUiCheckboxMultiselectWidget( config ) {
8342 // Parent constructor
8343 OO.ui.CheckboxMultiselectWidget.parent.call( this, config );
8344
8345 // Properties
8346 this.$lastClicked = null;
8347
8348 // Events
8349 this.$group.on( 'click', this.onClick.bind( this ) );
8350
8351 // Initialization
8352 this.$element
8353 .addClass( 'oo-ui-checkboxMultiselectWidget' );
8354 };
8355
8356 /* Setup */
8357
8358 OO.inheritClass( OO.ui.CheckboxMultiselectWidget, OO.ui.MultiselectWidget );
8359
8360 /* Methods */
8361
8362 /**
8363 * Get an option by its position relative to the specified item (or to the start of the option array,
8364 * if item is `null`). The direction in which to search through the option array is specified with a
8365 * number: -1 for reverse (the default) or 1 for forward. The method will return an option, or
8366 * `null` if there are no options in the array.
8367 *
8368 * @param {OO.ui.CheckboxMultioptionWidget|null} item Item to describe the start position, or `null` to start at the beginning of the array.
8369 * @param {number} direction Direction to move in: -1 to move backward, 1 to move forward
8370 * @return {OO.ui.CheckboxMultioptionWidget|null} Item at position, `null` if there are no items in the select
8371 */
8372 OO.ui.CheckboxMultiselectWidget.prototype.getRelativeFocusableItem = function ( item, direction ) {
8373 var currentIndex, nextIndex, i,
8374 increase = direction > 0 ? 1 : -1,
8375 len = this.items.length;
8376
8377 if ( item ) {
8378 currentIndex = this.items.indexOf( item );
8379 nextIndex = ( currentIndex + increase + len ) % len;
8380 } else {
8381 // If no item is selected and moving forward, start at the beginning.
8382 // If moving backward, start at the end.
8383 nextIndex = direction > 0 ? 0 : len - 1;
8384 }
8385
8386 for ( i = 0; i < len; i++ ) {
8387 item = this.items[ nextIndex ];
8388 if ( item && !item.isDisabled() ) {
8389 return item;
8390 }
8391 nextIndex = ( nextIndex + increase + len ) % len;
8392 }
8393 return null;
8394 };
8395
8396 /**
8397 * Handle click events on checkboxes.
8398 *
8399 * @param {jQuery.Event} e
8400 */
8401 OO.ui.CheckboxMultiselectWidget.prototype.onClick = function ( e ) {
8402 var $options, lastClickedIndex, nowClickedIndex, i, direction, wasSelected, items,
8403 $lastClicked = this.$lastClicked,
8404 $nowClicked = $( e.target ).closest( '.oo-ui-checkboxMultioptionWidget' )
8405 .not( '.oo-ui-widget-disabled' );
8406
8407 // Allow selecting multiple options at once by Shift-clicking them
8408 if ( $lastClicked && $nowClicked.length && e.shiftKey ) {
8409 $options = this.$group.find( '.oo-ui-checkboxMultioptionWidget' );
8410 lastClickedIndex = $options.index( $lastClicked );
8411 nowClickedIndex = $options.index( $nowClicked );
8412 // If it's the same item, either the user is being silly, or it's a fake event generated by the
8413 // browser. In either case we don't need custom handling.
8414 if ( nowClickedIndex !== lastClickedIndex ) {
8415 items = this.items;
8416 wasSelected = items[ nowClickedIndex ].isSelected();
8417 direction = nowClickedIndex > lastClickedIndex ? 1 : -1;
8418
8419 // This depends on the DOM order of the items and the order of the .items array being the same.
8420 for ( i = lastClickedIndex; i !== nowClickedIndex; i += direction ) {
8421 if ( !items[ i ].isDisabled() ) {
8422 items[ i ].setSelected( !wasSelected );
8423 }
8424 }
8425 // For the now-clicked element, use immediate timeout to allow the browser to do its own
8426 // handling first, then set our value. The order in which events happen is different for
8427 // clicks on the <input> and on the <label> and there are additional fake clicks fired for
8428 // non-click actions that change the checkboxes.
8429 e.preventDefault();
8430 setTimeout( function () {
8431 if ( !items[ nowClickedIndex ].isDisabled() ) {
8432 items[ nowClickedIndex ].setSelected( !wasSelected );
8433 }
8434 } );
8435 }
8436 }
8437
8438 if ( $nowClicked.length ) {
8439 this.$lastClicked = $nowClicked;
8440 }
8441 };
8442
8443 /**
8444 * Focus the widget
8445 *
8446 * @chainable
8447 */
8448 OO.ui.CheckboxMultiselectWidget.prototype.focus = function () {
8449 var item;
8450 if ( !this.isDisabled() ) {
8451 item = this.getRelativeFocusableItem( null, 1 );
8452 if ( item ) {
8453 item.focus();
8454 }
8455 }
8456 return this;
8457 };
8458
8459 /**
8460 * @inheritdoc
8461 */
8462 OO.ui.CheckboxMultiselectWidget.prototype.simulateLabelClick = function () {
8463 this.focus();
8464 };
8465
8466 /**
8467 * Progress bars visually display the status of an operation, such as a download,
8468 * and can be either determinate or indeterminate:
8469 *
8470 * - **determinate** process bars show the percent of an operation that is complete.
8471 *
8472 * - **indeterminate** process bars use a visual display of motion to indicate that an operation
8473 * is taking place. Because the extent of an indeterminate operation is unknown, the bar does
8474 * not use percentages.
8475 *
8476 * The value of the `progress` configuration determines whether the bar is determinate or indeterminate.
8477 *
8478 * @example
8479 * // Examples of determinate and indeterminate progress bars.
8480 * var progressBar1 = new OO.ui.ProgressBarWidget( {
8481 * progress: 33
8482 * } );
8483 * var progressBar2 = new OO.ui.ProgressBarWidget();
8484 *
8485 * // Create a FieldsetLayout to layout progress bars
8486 * var fieldset = new OO.ui.FieldsetLayout;
8487 * fieldset.addItems( [
8488 * new OO.ui.FieldLayout( progressBar1, {label: 'Determinate', align: 'top'}),
8489 * new OO.ui.FieldLayout( progressBar2, {label: 'Indeterminate', align: 'top'})
8490 * ] );
8491 * $( 'body' ).append( fieldset.$element );
8492 *
8493 * @class
8494 * @extends OO.ui.Widget
8495 *
8496 * @constructor
8497 * @param {Object} [config] Configuration options
8498 * @cfg {number|boolean} [progress=false] The type of progress bar (determinate or indeterminate).
8499 * To create a determinate progress bar, specify a number that reflects the initial percent complete.
8500 * By default, the progress bar is indeterminate.
8501 */
8502 OO.ui.ProgressBarWidget = function OoUiProgressBarWidget( config ) {
8503 // Configuration initialization
8504 config = config || {};
8505
8506 // Parent constructor
8507 OO.ui.ProgressBarWidget.parent.call( this, config );
8508
8509 // Properties
8510 this.$bar = $( '<div>' );
8511 this.progress = null;
8512
8513 // Initialization
8514 this.setProgress( config.progress !== undefined ? config.progress : false );
8515 this.$bar.addClass( 'oo-ui-progressBarWidget-bar' );
8516 this.$element
8517 .attr( {
8518 role: 'progressbar',
8519 'aria-valuemin': 0,
8520 'aria-valuemax': 100
8521 } )
8522 .addClass( 'oo-ui-progressBarWidget' )
8523 .append( this.$bar );
8524 };
8525
8526 /* Setup */
8527
8528 OO.inheritClass( OO.ui.ProgressBarWidget, OO.ui.Widget );
8529
8530 /* Static Properties */
8531
8532 /**
8533 * @static
8534 * @inheritdoc
8535 */
8536 OO.ui.ProgressBarWidget.static.tagName = 'div';
8537
8538 /* Methods */
8539
8540 /**
8541 * Get the percent of the progress that has been completed. Indeterminate progresses will return `false`.
8542 *
8543 * @return {number|boolean} Progress percent
8544 */
8545 OO.ui.ProgressBarWidget.prototype.getProgress = function () {
8546 return this.progress;
8547 };
8548
8549 /**
8550 * Set the percent of the process completed or `false` for an indeterminate process.
8551 *
8552 * @param {number|boolean} progress Progress percent or `false` for indeterminate
8553 */
8554 OO.ui.ProgressBarWidget.prototype.setProgress = function ( progress ) {
8555 this.progress = progress;
8556
8557 if ( progress !== false ) {
8558 this.$bar.css( 'width', this.progress + '%' );
8559 this.$element.attr( 'aria-valuenow', this.progress );
8560 } else {
8561 this.$bar.css( 'width', '' );
8562 this.$element.removeAttr( 'aria-valuenow' );
8563 }
8564 this.$element.toggleClass( 'oo-ui-progressBarWidget-indeterminate', progress === false );
8565 };
8566
8567 /**
8568 * InputWidget is the base class for all input widgets, which
8569 * include {@link OO.ui.TextInputWidget text inputs}, {@link OO.ui.CheckboxInputWidget checkbox inputs},
8570 * {@link OO.ui.RadioInputWidget radio inputs}, and {@link OO.ui.ButtonInputWidget button inputs}.
8571 * See the [OOUI documentation on MediaWiki] [1] for more information and examples.
8572 *
8573 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
8574 *
8575 * @abstract
8576 * @class
8577 * @extends OO.ui.Widget
8578 * @mixins OO.ui.mixin.FlaggedElement
8579 * @mixins OO.ui.mixin.TabIndexedElement
8580 * @mixins OO.ui.mixin.TitledElement
8581 * @mixins OO.ui.mixin.AccessKeyedElement
8582 *
8583 * @constructor
8584 * @param {Object} [config] Configuration options
8585 * @cfg {string} [name=''] The value of the input’s HTML `name` attribute.
8586 * @cfg {string} [value=''] The value of the input.
8587 * @cfg {string} [dir] The directionality of the input (ltr/rtl).
8588 * @cfg {string} [inputId] The value of the input’s HTML `id` attribute.
8589 * @cfg {Function} [inputFilter] The name of an input filter function. Input filters modify the value of an input
8590 * before it is accepted.
8591 */
8592 OO.ui.InputWidget = function OoUiInputWidget( config ) {
8593 // Configuration initialization
8594 config = config || {};
8595
8596 // Parent constructor
8597 OO.ui.InputWidget.parent.call( this, config );
8598
8599 // Properties
8600 // See #reusePreInfuseDOM about config.$input
8601 this.$input = config.$input || this.getInputElement( config );
8602 this.value = '';
8603 this.inputFilter = config.inputFilter;
8604
8605 // Mixin constructors
8606 OO.ui.mixin.FlaggedElement.call( this, config );
8607 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$input } ) );
8608 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$input } ) );
8609 OO.ui.mixin.AccessKeyedElement.call( this, $.extend( {}, config, { $accessKeyed: this.$input } ) );
8610
8611 // Events
8612 this.$input.on( 'keydown mouseup cut paste change input select', this.onEdit.bind( this ) );
8613
8614 // Initialization
8615 this.$input
8616 .addClass( 'oo-ui-inputWidget-input' )
8617 .attr( 'name', config.name )
8618 .prop( 'disabled', this.isDisabled() );
8619 this.$element
8620 .addClass( 'oo-ui-inputWidget' )
8621 .append( this.$input );
8622 this.setValue( config.value );
8623 if ( config.dir ) {
8624 this.setDir( config.dir );
8625 }
8626 if ( config.inputId !== undefined ) {
8627 this.setInputId( config.inputId );
8628 }
8629 };
8630
8631 /* Setup */
8632
8633 OO.inheritClass( OO.ui.InputWidget, OO.ui.Widget );
8634 OO.mixinClass( OO.ui.InputWidget, OO.ui.mixin.FlaggedElement );
8635 OO.mixinClass( OO.ui.InputWidget, OO.ui.mixin.TabIndexedElement );
8636 OO.mixinClass( OO.ui.InputWidget, OO.ui.mixin.TitledElement );
8637 OO.mixinClass( OO.ui.InputWidget, OO.ui.mixin.AccessKeyedElement );
8638
8639 /* Static Methods */
8640
8641 /**
8642 * @inheritdoc
8643 */
8644 OO.ui.InputWidget.static.reusePreInfuseDOM = function ( node, config ) {
8645 config = OO.ui.InputWidget.parent.static.reusePreInfuseDOM( node, config );
8646 // Reusing `$input` lets browsers preserve inputted values across page reloads, see T114134.
8647 config.$input = $( node ).find( '.oo-ui-inputWidget-input' );
8648 return config;
8649 };
8650
8651 /**
8652 * @inheritdoc
8653 */
8654 OO.ui.InputWidget.static.gatherPreInfuseState = function ( node, config ) {
8655 var state = OO.ui.InputWidget.parent.static.gatherPreInfuseState( node, config );
8656 if ( config.$input && config.$input.length ) {
8657 state.value = config.$input.val();
8658 // Might be better in TabIndexedElement, but it's awkward to do there because mixins are awkward
8659 state.focus = config.$input.is( ':focus' );
8660 }
8661 return state;
8662 };
8663
8664 /* Events */
8665
8666 /**
8667 * @event change
8668 *
8669 * A change event is emitted when the value of the input changes.
8670 *
8671 * @param {string} value
8672 */
8673
8674 /* Methods */
8675
8676 /**
8677 * Get input element.
8678 *
8679 * Subclasses of OO.ui.InputWidget use the `config` parameter to produce different elements in
8680 * different circumstances. The element must have a `value` property (like form elements).
8681 *
8682 * @protected
8683 * @param {Object} config Configuration options
8684 * @return {jQuery} Input element
8685 */
8686 OO.ui.InputWidget.prototype.getInputElement = function () {
8687 return $( '<input>' );
8688 };
8689
8690 /**
8691 * Handle potentially value-changing events.
8692 *
8693 * @private
8694 * @param {jQuery.Event} e Key down, mouse up, cut, paste, change, input, or select event
8695 */
8696 OO.ui.InputWidget.prototype.onEdit = function () {
8697 var widget = this;
8698 if ( !this.isDisabled() ) {
8699 // Allow the stack to clear so the value will be updated
8700 setTimeout( function () {
8701 widget.setValue( widget.$input.val() );
8702 } );
8703 }
8704 };
8705
8706 /**
8707 * Get the value of the input.
8708 *
8709 * @return {string} Input value
8710 */
8711 OO.ui.InputWidget.prototype.getValue = function () {
8712 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
8713 // it, and we won't know unless they're kind enough to trigger a 'change' event.
8714 var value = this.$input.val();
8715 if ( this.value !== value ) {
8716 this.setValue( value );
8717 }
8718 return this.value;
8719 };
8720
8721 /**
8722 * Set the directionality of the input.
8723 *
8724 * @param {string} dir Text directionality: 'ltr', 'rtl' or 'auto'
8725 * @chainable
8726 */
8727 OO.ui.InputWidget.prototype.setDir = function ( dir ) {
8728 this.$input.prop( 'dir', dir );
8729 return this;
8730 };
8731
8732 /**
8733 * Set the value of the input.
8734 *
8735 * @param {string} value New value
8736 * @fires change
8737 * @chainable
8738 */
8739 OO.ui.InputWidget.prototype.setValue = function ( value ) {
8740 value = this.cleanUpValue( value );
8741 // Update the DOM if it has changed. Note that with cleanUpValue, it
8742 // is possible for the DOM value to change without this.value changing.
8743 if ( this.$input.val() !== value ) {
8744 this.$input.val( value );
8745 }
8746 if ( this.value !== value ) {
8747 this.value = value;
8748 this.emit( 'change', this.value );
8749 }
8750 // The first time that the value is set (probably while constructing the widget),
8751 // remember it in defaultValue. This property can be later used to check whether
8752 // the value of the input has been changed since it was created.
8753 if ( this.defaultValue === undefined ) {
8754 this.defaultValue = this.value;
8755 this.$input[ 0 ].defaultValue = this.defaultValue;
8756 }
8757 return this;
8758 };
8759
8760 /**
8761 * Clean up incoming value.
8762 *
8763 * Ensures value is a string, and converts undefined and null to empty string.
8764 *
8765 * @private
8766 * @param {string} value Original value
8767 * @return {string} Cleaned up value
8768 */
8769 OO.ui.InputWidget.prototype.cleanUpValue = function ( value ) {
8770 if ( value === undefined || value === null ) {
8771 return '';
8772 } else if ( this.inputFilter ) {
8773 return this.inputFilter( String( value ) );
8774 } else {
8775 return String( value );
8776 }
8777 };
8778
8779 /**
8780 * @inheritdoc
8781 */
8782 OO.ui.InputWidget.prototype.setDisabled = function ( state ) {
8783 OO.ui.InputWidget.parent.prototype.setDisabled.call( this, state );
8784 if ( this.$input ) {
8785 this.$input.prop( 'disabled', this.isDisabled() );
8786 }
8787 return this;
8788 };
8789
8790 /**
8791 * Set the 'id' attribute of the `<input>` element.
8792 *
8793 * @param {string} id
8794 * @chainable
8795 */
8796 OO.ui.InputWidget.prototype.setInputId = function ( id ) {
8797 this.$input.attr( 'id', id );
8798 return this;
8799 };
8800
8801 /**
8802 * @inheritdoc
8803 */
8804 OO.ui.InputWidget.prototype.restorePreInfuseState = function ( state ) {
8805 OO.ui.InputWidget.parent.prototype.restorePreInfuseState.call( this, state );
8806 if ( state.value !== undefined && state.value !== this.getValue() ) {
8807 this.setValue( state.value );
8808 }
8809 if ( state.focus ) {
8810 this.focus();
8811 }
8812 };
8813
8814 /**
8815 * Data widget intended for creating 'hidden'-type inputs.
8816 *
8817 * @class
8818 * @extends OO.ui.Widget
8819 *
8820 * @constructor
8821 * @param {Object} [config] Configuration options
8822 * @cfg {string} [value=''] The value of the input.
8823 * @cfg {string} [name=''] The value of the input’s HTML `name` attribute.
8824 */
8825 OO.ui.HiddenInputWidget = function OoUiHiddenInputWidget( config ) {
8826 // Configuration initialization
8827 config = $.extend( { value: '', name: '' }, config );
8828
8829 // Parent constructor
8830 OO.ui.HiddenInputWidget.parent.call( this, config );
8831
8832 // Initialization
8833 this.$element.attr( {
8834 type: 'hidden',
8835 value: config.value,
8836 name: config.name
8837 } );
8838 this.$element.removeAttr( 'aria-disabled' );
8839 };
8840
8841 /* Setup */
8842
8843 OO.inheritClass( OO.ui.HiddenInputWidget, OO.ui.Widget );
8844
8845 /* Static Properties */
8846
8847 /**
8848 * @static
8849 * @inheritdoc
8850 */
8851 OO.ui.HiddenInputWidget.static.tagName = 'input';
8852
8853 /**
8854 * ButtonInputWidget is used to submit HTML forms and is intended to be used within
8855 * a OO.ui.FormLayout. If you do not need the button to work with HTML forms, you probably
8856 * want to use OO.ui.ButtonWidget instead. Button input widgets can be rendered as either an
8857 * HTML `<button>` (the default) or an HTML `<input>` tags. See the
8858 * [OOUI documentation on MediaWiki] [1] for more information.
8859 *
8860 * @example
8861 * // A ButtonInputWidget rendered as an HTML button, the default.
8862 * var button = new OO.ui.ButtonInputWidget( {
8863 * label: 'Input button',
8864 * icon: 'check',
8865 * value: 'check'
8866 * } );
8867 * $( 'body' ).append( button.$element );
8868 *
8869 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs#Button_inputs
8870 *
8871 * @class
8872 * @extends OO.ui.InputWidget
8873 * @mixins OO.ui.mixin.ButtonElement
8874 * @mixins OO.ui.mixin.IconElement
8875 * @mixins OO.ui.mixin.IndicatorElement
8876 * @mixins OO.ui.mixin.LabelElement
8877 * @mixins OO.ui.mixin.TitledElement
8878 *
8879 * @constructor
8880 * @param {Object} [config] Configuration options
8881 * @cfg {string} [type='button'] The value of the HTML `'type'` attribute: 'button', 'submit' or 'reset'.
8882 * @cfg {boolean} [useInputTag=false] Use an `<input>` tag instead of a `<button>` tag, the default.
8883 * Widgets configured to be an `<input>` do not support {@link #icon icons} and {@link #indicator indicators},
8884 * non-plaintext {@link #label labels}, or {@link #value values}. In general, useInputTag should only
8885 * be set to `true` when there’s need to support IE 6 in a form with multiple buttons.
8886 */
8887 OO.ui.ButtonInputWidget = function OoUiButtonInputWidget( config ) {
8888 // Configuration initialization
8889 config = $.extend( { type: 'button', useInputTag: false }, config );
8890
8891 // See InputWidget#reusePreInfuseDOM about config.$input
8892 if ( config.$input ) {
8893 config.$input.empty();
8894 }
8895
8896 // Properties (must be set before parent constructor, which calls #setValue)
8897 this.useInputTag = config.useInputTag;
8898
8899 // Parent constructor
8900 OO.ui.ButtonInputWidget.parent.call( this, config );
8901
8902 // Mixin constructors
8903 OO.ui.mixin.ButtonElement.call( this, $.extend( {}, config, { $button: this.$input } ) );
8904 OO.ui.mixin.IconElement.call( this, config );
8905 OO.ui.mixin.IndicatorElement.call( this, config );
8906 OO.ui.mixin.LabelElement.call( this, config );
8907 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$input } ) );
8908
8909 // Initialization
8910 if ( !config.useInputTag ) {
8911 this.$input.append( this.$icon, this.$label, this.$indicator );
8912 }
8913 this.$element.addClass( 'oo-ui-buttonInputWidget' );
8914 };
8915
8916 /* Setup */
8917
8918 OO.inheritClass( OO.ui.ButtonInputWidget, OO.ui.InputWidget );
8919 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.ButtonElement );
8920 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.IconElement );
8921 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.IndicatorElement );
8922 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.LabelElement );
8923 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.TitledElement );
8924
8925 /* Static Properties */
8926
8927 /**
8928 * @static
8929 * @inheritdoc
8930 */
8931 OO.ui.ButtonInputWidget.static.tagName = 'span';
8932
8933 /* Methods */
8934
8935 /**
8936 * @inheritdoc
8937 * @protected
8938 */
8939 OO.ui.ButtonInputWidget.prototype.getInputElement = function ( config ) {
8940 var type;
8941 type = [ 'button', 'submit', 'reset' ].indexOf( config.type ) !== -1 ? config.type : 'button';
8942 return $( '<' + ( config.useInputTag ? 'input' : 'button' ) + ' type="' + type + '">' );
8943 };
8944
8945 /**
8946 * Set label value.
8947 *
8948 * If #useInputTag is `true`, the label is set as the `value` of the `<input>` tag.
8949 *
8950 * @param {jQuery|string|Function|null} label Label nodes, text, a function that returns nodes or
8951 * text, or `null` for no label
8952 * @chainable
8953 */
8954 OO.ui.ButtonInputWidget.prototype.setLabel = function ( label ) {
8955 if ( typeof label === 'function' ) {
8956 label = OO.ui.resolveMsg( label );
8957 }
8958
8959 if ( this.useInputTag ) {
8960 // Discard non-plaintext labels
8961 if ( typeof label !== 'string' ) {
8962 label = '';
8963 }
8964
8965 this.$input.val( label );
8966 }
8967
8968 return OO.ui.mixin.LabelElement.prototype.setLabel.call( this, label );
8969 };
8970
8971 /**
8972 * Set the value of the input.
8973 *
8974 * This method is disabled for button inputs configured as {@link #useInputTag <input> tags}, as
8975 * they do not support {@link #value values}.
8976 *
8977 * @param {string} value New value
8978 * @chainable
8979 */
8980 OO.ui.ButtonInputWidget.prototype.setValue = function ( value ) {
8981 if ( !this.useInputTag ) {
8982 OO.ui.ButtonInputWidget.parent.prototype.setValue.call( this, value );
8983 }
8984 return this;
8985 };
8986
8987 /**
8988 * @inheritdoc
8989 */
8990 OO.ui.ButtonInputWidget.prototype.getInputId = function () {
8991 // Disable generating `<label>` elements for buttons. One would very rarely need additional label
8992 // for a button, and it's already a big clickable target, and it causes unexpected rendering.
8993 return null;
8994 };
8995
8996 /**
8997 * CheckboxInputWidgets, like HTML checkboxes, can be selected and/or configured with a value.
8998 * Note that these {@link OO.ui.InputWidget input widgets} are best laid out
8999 * in {@link OO.ui.FieldLayout field layouts} that use the {@link OO.ui.FieldLayout#align inline}
9000 * alignment. For more information, please see the [OOUI documentation on MediaWiki][1].
9001 *
9002 * This widget can be used inside an HTML form, such as a OO.ui.FormLayout.
9003 *
9004 * @example
9005 * // An example of selected, unselected, and disabled checkbox inputs
9006 * var checkbox1=new OO.ui.CheckboxInputWidget( {
9007 * value: 'a',
9008 * selected: true
9009 * } );
9010 * var checkbox2=new OO.ui.CheckboxInputWidget( {
9011 * value: 'b'
9012 * } );
9013 * var checkbox3=new OO.ui.CheckboxInputWidget( {
9014 * value:'c',
9015 * disabled: true
9016 * } );
9017 * // Create a fieldset layout with fields for each checkbox.
9018 * var fieldset = new OO.ui.FieldsetLayout( {
9019 * label: 'Checkboxes'
9020 * } );
9021 * fieldset.addItems( [
9022 * new OO.ui.FieldLayout( checkbox1, { label: 'Selected checkbox', align: 'inline' } ),
9023 * new OO.ui.FieldLayout( checkbox2, { label: 'Unselected checkbox', align: 'inline' } ),
9024 * new OO.ui.FieldLayout( checkbox3, { label: 'Disabled checkbox', align: 'inline' } ),
9025 * ] );
9026 * $( 'body' ).append( fieldset.$element );
9027 *
9028 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
9029 *
9030 * @class
9031 * @extends OO.ui.InputWidget
9032 *
9033 * @constructor
9034 * @param {Object} [config] Configuration options
9035 * @cfg {boolean} [selected=false] Select the checkbox initially. By default, the checkbox is not selected.
9036 */
9037 OO.ui.CheckboxInputWidget = function OoUiCheckboxInputWidget( config ) {
9038 // Configuration initialization
9039 config = config || {};
9040
9041 // Parent constructor
9042 OO.ui.CheckboxInputWidget.parent.call( this, config );
9043
9044 // Properties
9045 this.checkIcon = new OO.ui.IconWidget( {
9046 icon: 'check',
9047 classes: [ 'oo-ui-checkboxInputWidget-checkIcon' ]
9048 } );
9049
9050 // Initialization
9051 this.$element
9052 .addClass( 'oo-ui-checkboxInputWidget' )
9053 // Required for pretty styling in WikimediaUI theme
9054 .append( this.checkIcon.$element );
9055 this.setSelected( config.selected !== undefined ? config.selected : false );
9056 };
9057
9058 /* Setup */
9059
9060 OO.inheritClass( OO.ui.CheckboxInputWidget, OO.ui.InputWidget );
9061
9062 /* Static Properties */
9063
9064 /**
9065 * @static
9066 * @inheritdoc
9067 */
9068 OO.ui.CheckboxInputWidget.static.tagName = 'span';
9069
9070 /* Static Methods */
9071
9072 /**
9073 * @inheritdoc
9074 */
9075 OO.ui.CheckboxInputWidget.static.gatherPreInfuseState = function ( node, config ) {
9076 var state = OO.ui.CheckboxInputWidget.parent.static.gatherPreInfuseState( node, config );
9077 state.checked = config.$input.prop( 'checked' );
9078 return state;
9079 };
9080
9081 /* Methods */
9082
9083 /**
9084 * @inheritdoc
9085 * @protected
9086 */
9087 OO.ui.CheckboxInputWidget.prototype.getInputElement = function () {
9088 return $( '<input>' ).attr( 'type', 'checkbox' );
9089 };
9090
9091 /**
9092 * @inheritdoc
9093 */
9094 OO.ui.CheckboxInputWidget.prototype.onEdit = function () {
9095 var widget = this;
9096 if ( !this.isDisabled() ) {
9097 // Allow the stack to clear so the value will be updated
9098 setTimeout( function () {
9099 widget.setSelected( widget.$input.prop( 'checked' ) );
9100 } );
9101 }
9102 };
9103
9104 /**
9105 * Set selection state of this checkbox.
9106 *
9107 * @param {boolean} state `true` for selected
9108 * @chainable
9109 */
9110 OO.ui.CheckboxInputWidget.prototype.setSelected = function ( state ) {
9111 state = !!state;
9112 if ( this.selected !== state ) {
9113 this.selected = state;
9114 this.$input.prop( 'checked', this.selected );
9115 this.emit( 'change', this.selected );
9116 }
9117 // The first time that the selection state is set (probably while constructing the widget),
9118 // remember it in defaultSelected. This property can be later used to check whether
9119 // the selection state of the input has been changed since it was created.
9120 if ( this.defaultSelected === undefined ) {
9121 this.defaultSelected = this.selected;
9122 this.$input[ 0 ].defaultChecked = this.defaultSelected;
9123 }
9124 return this;
9125 };
9126
9127 /**
9128 * Check if this checkbox is selected.
9129 *
9130 * @return {boolean} Checkbox is selected
9131 */
9132 OO.ui.CheckboxInputWidget.prototype.isSelected = function () {
9133 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
9134 // it, and we won't know unless they're kind enough to trigger a 'change' event.
9135 var selected = this.$input.prop( 'checked' );
9136 if ( this.selected !== selected ) {
9137 this.setSelected( selected );
9138 }
9139 return this.selected;
9140 };
9141
9142 /**
9143 * @inheritdoc
9144 */
9145 OO.ui.CheckboxInputWidget.prototype.simulateLabelClick = function () {
9146 if ( !this.isDisabled() ) {
9147 this.$input.click();
9148 }
9149 this.focus();
9150 };
9151
9152 /**
9153 * @inheritdoc
9154 */
9155 OO.ui.CheckboxInputWidget.prototype.restorePreInfuseState = function ( state ) {
9156 OO.ui.CheckboxInputWidget.parent.prototype.restorePreInfuseState.call( this, state );
9157 if ( state.checked !== undefined && state.checked !== this.isSelected() ) {
9158 this.setSelected( state.checked );
9159 }
9160 };
9161
9162 /**
9163 * DropdownInputWidget is a {@link OO.ui.DropdownWidget DropdownWidget} intended to be used
9164 * within an HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with the value
9165 * of a hidden HTML `input` tag. Please see the [OOUI documentation on MediaWiki][1] for
9166 * more information about input widgets.
9167 *
9168 * A DropdownInputWidget always has a value (one of the options is always selected), unless there
9169 * are no options. If no `value` configuration option is provided, the first option is selected.
9170 * If you need a state representing no value (no option being selected), use a DropdownWidget.
9171 *
9172 * This and OO.ui.RadioSelectInputWidget support the same configuration options.
9173 *
9174 * @example
9175 * // Example: A DropdownInputWidget with three options
9176 * var dropdownInput = new OO.ui.DropdownInputWidget( {
9177 * options: [
9178 * { data: 'a', label: 'First' },
9179 * { data: 'b', label: 'Second'},
9180 * { data: 'c', label: 'Third' }
9181 * ]
9182 * } );
9183 * $( 'body' ).append( dropdownInput.$element );
9184 *
9185 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
9186 *
9187 * @class
9188 * @extends OO.ui.InputWidget
9189 *
9190 * @constructor
9191 * @param {Object} [config] Configuration options
9192 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
9193 * @cfg {Object} [dropdown] Configuration options for {@link OO.ui.DropdownWidget DropdownWidget}
9194 */
9195 OO.ui.DropdownInputWidget = function OoUiDropdownInputWidget( config ) {
9196 // Configuration initialization
9197 config = config || {};
9198
9199 // Properties (must be done before parent constructor which calls #setDisabled)
9200 this.dropdownWidget = new OO.ui.DropdownWidget( config.dropdown );
9201 // Set up the options before parent constructor, which uses them to validate config.value.
9202 // Use this instead of setOptions() because this.$input is not set up yet.
9203 this.setOptionsData( config.options || [] );
9204
9205 // Parent constructor
9206 OO.ui.DropdownInputWidget.parent.call( this, config );
9207
9208 // Events
9209 this.dropdownWidget.getMenu().connect( this, { select: 'onMenuSelect' } );
9210
9211 // Initialization
9212 this.$element
9213 .addClass( 'oo-ui-dropdownInputWidget' )
9214 .append( this.dropdownWidget.$element );
9215 this.setTabIndexedElement( this.dropdownWidget.$tabIndexed );
9216 };
9217
9218 /* Setup */
9219
9220 OO.inheritClass( OO.ui.DropdownInputWidget, OO.ui.InputWidget );
9221
9222 /* Methods */
9223
9224 /**
9225 * @inheritdoc
9226 * @protected
9227 */
9228 OO.ui.DropdownInputWidget.prototype.getInputElement = function () {
9229 return $( '<select>' );
9230 };
9231
9232 /**
9233 * Handles menu select events.
9234 *
9235 * @private
9236 * @param {OO.ui.MenuOptionWidget|null} item Selected menu item
9237 */
9238 OO.ui.DropdownInputWidget.prototype.onMenuSelect = function ( item ) {
9239 this.setValue( item ? item.getData() : '' );
9240 };
9241
9242 /**
9243 * @inheritdoc
9244 */
9245 OO.ui.DropdownInputWidget.prototype.setValue = function ( value ) {
9246 var selected;
9247 value = this.cleanUpValue( value );
9248 // Only allow setting values that are actually present in the dropdown
9249 selected = this.dropdownWidget.getMenu().findItemFromData( value ) ||
9250 this.dropdownWidget.getMenu().findFirstSelectableItem();
9251 this.dropdownWidget.getMenu().selectItem( selected );
9252 value = selected ? selected.getData() : '';
9253 OO.ui.DropdownInputWidget.parent.prototype.setValue.call( this, value );
9254 if ( this.optionsDirty ) {
9255 // We reached this from the constructor or from #setOptions.
9256 // We have to update the <select> element.
9257 this.updateOptionsInterface();
9258 }
9259 return this;
9260 };
9261
9262 /**
9263 * @inheritdoc
9264 */
9265 OO.ui.DropdownInputWidget.prototype.setDisabled = function ( state ) {
9266 this.dropdownWidget.setDisabled( state );
9267 OO.ui.DropdownInputWidget.parent.prototype.setDisabled.call( this, state );
9268 return this;
9269 };
9270
9271 /**
9272 * Set the options available for this input.
9273 *
9274 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
9275 * @chainable
9276 */
9277 OO.ui.DropdownInputWidget.prototype.setOptions = function ( options ) {
9278 var value = this.getValue();
9279
9280 this.setOptionsData( options );
9281
9282 // Re-set the value to update the visible interface (DropdownWidget and <select>).
9283 // In case the previous value is no longer an available option, select the first valid one.
9284 this.setValue( value );
9285
9286 return this;
9287 };
9288
9289 /**
9290 * Set the internal list of options, used e.g. by setValue() to see which options are allowed.
9291 *
9292 * This method may be called before the parent constructor, so various properties may not be
9293 * intialized yet.
9294 *
9295 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
9296 * @private
9297 */
9298 OO.ui.DropdownInputWidget.prototype.setOptionsData = function ( options ) {
9299 var
9300 optionWidgets,
9301 widget = this;
9302
9303 this.optionsDirty = true;
9304
9305 optionWidgets = options.map( function ( opt ) {
9306 var optValue;
9307
9308 if ( opt.optgroup !== undefined ) {
9309 return widget.createMenuSectionOptionWidget( opt.optgroup );
9310 }
9311
9312 optValue = widget.cleanUpValue( opt.data );
9313 return widget.createMenuOptionWidget(
9314 optValue,
9315 opt.label !== undefined ? opt.label : optValue
9316 );
9317
9318 } );
9319
9320 this.dropdownWidget.getMenu().clearItems().addItems( optionWidgets );
9321 };
9322
9323 /**
9324 * Create a menu option widget.
9325 *
9326 * @protected
9327 * @param {string} data Item data
9328 * @param {string} label Item label
9329 * @return {OO.ui.MenuOptionWidget} Option widget
9330 */
9331 OO.ui.DropdownInputWidget.prototype.createMenuOptionWidget = function ( data, label ) {
9332 return new OO.ui.MenuOptionWidget( {
9333 data: data,
9334 label: label
9335 } );
9336 };
9337
9338 /**
9339 * Create a menu section option widget.
9340 *
9341 * @protected
9342 * @param {string} label Section item label
9343 * @return {OO.ui.MenuSectionOptionWidget} Menu section option widget
9344 */
9345 OO.ui.DropdownInputWidget.prototype.createMenuSectionOptionWidget = function ( label ) {
9346 return new OO.ui.MenuSectionOptionWidget( {
9347 label: label
9348 } );
9349 };
9350
9351 /**
9352 * Update the user-visible interface to match the internal list of options and value.
9353 *
9354 * This method must only be called after the parent constructor.
9355 *
9356 * @private
9357 */
9358 OO.ui.DropdownInputWidget.prototype.updateOptionsInterface = function () {
9359 var
9360 $optionsContainer = this.$input,
9361 defaultValue = this.defaultValue,
9362 widget = this;
9363
9364 this.$input.empty();
9365
9366 this.dropdownWidget.getMenu().getItems().forEach( function ( optionWidget ) {
9367 var $optionNode;
9368
9369 if ( !( optionWidget instanceof OO.ui.MenuSectionOptionWidget ) ) {
9370 $optionNode = $( '<option>' )
9371 .attr( 'value', optionWidget.getData() )
9372 .text( optionWidget.getLabel() );
9373
9374 // Remember original selection state. This property can be later used to check whether
9375 // the selection state of the input has been changed since it was created.
9376 $optionNode[ 0 ].defaultSelected = ( optionWidget.getData() === defaultValue );
9377
9378 $optionsContainer.append( $optionNode );
9379 } else {
9380 $optionNode = $( '<optgroup>' )
9381 .attr( 'label', optionWidget.getLabel() );
9382 widget.$input.append( $optionNode );
9383 $optionsContainer = $optionNode;
9384 }
9385 } );
9386
9387 this.optionsDirty = false;
9388 };
9389
9390 /**
9391 * @inheritdoc
9392 */
9393 OO.ui.DropdownInputWidget.prototype.focus = function () {
9394 this.dropdownWidget.focus();
9395 return this;
9396 };
9397
9398 /**
9399 * @inheritdoc
9400 */
9401 OO.ui.DropdownInputWidget.prototype.blur = function () {
9402 this.dropdownWidget.blur();
9403 return this;
9404 };
9405
9406 /**
9407 * RadioInputWidget creates a single radio button. Because radio buttons are usually used as a set,
9408 * in most cases you will want to use a {@link OO.ui.RadioSelectWidget radio select}
9409 * with {@link OO.ui.RadioOptionWidget radio options} instead of this class. For more information,
9410 * please see the [OOUI documentation on MediaWiki][1].
9411 *
9412 * This widget can be used inside an HTML form, such as a OO.ui.FormLayout.
9413 *
9414 * @example
9415 * // An example of selected, unselected, and disabled radio inputs
9416 * var radio1 = new OO.ui.RadioInputWidget( {
9417 * value: 'a',
9418 * selected: true
9419 * } );
9420 * var radio2 = new OO.ui.RadioInputWidget( {
9421 * value: 'b'
9422 * } );
9423 * var radio3 = new OO.ui.RadioInputWidget( {
9424 * value: 'c',
9425 * disabled: true
9426 * } );
9427 * // Create a fieldset layout with fields for each radio button.
9428 * var fieldset = new OO.ui.FieldsetLayout( {
9429 * label: 'Radio inputs'
9430 * } );
9431 * fieldset.addItems( [
9432 * new OO.ui.FieldLayout( radio1, { label: 'Selected', align: 'inline' } ),
9433 * new OO.ui.FieldLayout( radio2, { label: 'Unselected', align: 'inline' } ),
9434 * new OO.ui.FieldLayout( radio3, { label: 'Disabled', align: 'inline' } ),
9435 * ] );
9436 * $( 'body' ).append( fieldset.$element );
9437 *
9438 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
9439 *
9440 * @class
9441 * @extends OO.ui.InputWidget
9442 *
9443 * @constructor
9444 * @param {Object} [config] Configuration options
9445 * @cfg {boolean} [selected=false] Select the radio button initially. By default, the radio button is not selected.
9446 */
9447 OO.ui.RadioInputWidget = function OoUiRadioInputWidget( config ) {
9448 // Configuration initialization
9449 config = config || {};
9450
9451 // Parent constructor
9452 OO.ui.RadioInputWidget.parent.call( this, config );
9453
9454 // Initialization
9455 this.$element
9456 .addClass( 'oo-ui-radioInputWidget' )
9457 // Required for pretty styling in WikimediaUI theme
9458 .append( $( '<span>' ) );
9459 this.setSelected( config.selected !== undefined ? config.selected : false );
9460 };
9461
9462 /* Setup */
9463
9464 OO.inheritClass( OO.ui.RadioInputWidget, OO.ui.InputWidget );
9465
9466 /* Static Properties */
9467
9468 /**
9469 * @static
9470 * @inheritdoc
9471 */
9472 OO.ui.RadioInputWidget.static.tagName = 'span';
9473
9474 /* Static Methods */
9475
9476 /**
9477 * @inheritdoc
9478 */
9479 OO.ui.RadioInputWidget.static.gatherPreInfuseState = function ( node, config ) {
9480 var state = OO.ui.RadioInputWidget.parent.static.gatherPreInfuseState( node, config );
9481 state.checked = config.$input.prop( 'checked' );
9482 return state;
9483 };
9484
9485 /* Methods */
9486
9487 /**
9488 * @inheritdoc
9489 * @protected
9490 */
9491 OO.ui.RadioInputWidget.prototype.getInputElement = function () {
9492 return $( '<input>' ).attr( 'type', 'radio' );
9493 };
9494
9495 /**
9496 * @inheritdoc
9497 */
9498 OO.ui.RadioInputWidget.prototype.onEdit = function () {
9499 // RadioInputWidget doesn't track its state.
9500 };
9501
9502 /**
9503 * Set selection state of this radio button.
9504 *
9505 * @param {boolean} state `true` for selected
9506 * @chainable
9507 */
9508 OO.ui.RadioInputWidget.prototype.setSelected = function ( state ) {
9509 // RadioInputWidget doesn't track its state.
9510 this.$input.prop( 'checked', state );
9511 // The first time that the selection state is set (probably while constructing the widget),
9512 // remember it in defaultSelected. This property can be later used to check whether
9513 // the selection state of the input has been changed since it was created.
9514 if ( this.defaultSelected === undefined ) {
9515 this.defaultSelected = state;
9516 this.$input[ 0 ].defaultChecked = this.defaultSelected;
9517 }
9518 return this;
9519 };
9520
9521 /**
9522 * Check if this radio button is selected.
9523 *
9524 * @return {boolean} Radio is selected
9525 */
9526 OO.ui.RadioInputWidget.prototype.isSelected = function () {
9527 return this.$input.prop( 'checked' );
9528 };
9529
9530 /**
9531 * @inheritdoc
9532 */
9533 OO.ui.RadioInputWidget.prototype.simulateLabelClick = function () {
9534 if ( !this.isDisabled() ) {
9535 this.$input.click();
9536 }
9537 this.focus();
9538 };
9539
9540 /**
9541 * @inheritdoc
9542 */
9543 OO.ui.RadioInputWidget.prototype.restorePreInfuseState = function ( state ) {
9544 OO.ui.RadioInputWidget.parent.prototype.restorePreInfuseState.call( this, state );
9545 if ( state.checked !== undefined && state.checked !== this.isSelected() ) {
9546 this.setSelected( state.checked );
9547 }
9548 };
9549
9550 /**
9551 * RadioSelectInputWidget is a {@link OO.ui.RadioSelectWidget RadioSelectWidget} intended to be used
9552 * within an HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with the value
9553 * of a hidden HTML `input` tag. Please see the [OOUI documentation on MediaWiki][1] for
9554 * more information about input widgets.
9555 *
9556 * This and OO.ui.DropdownInputWidget support the same configuration options.
9557 *
9558 * @example
9559 * // Example: A RadioSelectInputWidget with three options
9560 * var radioSelectInput = new OO.ui.RadioSelectInputWidget( {
9561 * options: [
9562 * { data: 'a', label: 'First' },
9563 * { data: 'b', label: 'Second'},
9564 * { data: 'c', label: 'Third' }
9565 * ]
9566 * } );
9567 * $( 'body' ).append( radioSelectInput.$element );
9568 *
9569 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
9570 *
9571 * @class
9572 * @extends OO.ui.InputWidget
9573 *
9574 * @constructor
9575 * @param {Object} [config] Configuration options
9576 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
9577 */
9578 OO.ui.RadioSelectInputWidget = function OoUiRadioSelectInputWidget( config ) {
9579 // Configuration initialization
9580 config = config || {};
9581
9582 // Properties (must be done before parent constructor which calls #setDisabled)
9583 this.radioSelectWidget = new OO.ui.RadioSelectWidget();
9584 // Set up the options before parent constructor, which uses them to validate config.value.
9585 // Use this instead of setOptions() because this.$input is not set up yet
9586 this.setOptionsData( config.options || [] );
9587
9588 // Parent constructor
9589 OO.ui.RadioSelectInputWidget.parent.call( this, config );
9590
9591 // Events
9592 this.radioSelectWidget.connect( this, { select: 'onMenuSelect' } );
9593
9594 // Initialization
9595 this.$element
9596 .addClass( 'oo-ui-radioSelectInputWidget' )
9597 .append( this.radioSelectWidget.$element );
9598 this.setTabIndexedElement( this.radioSelectWidget.$tabIndexed );
9599 };
9600
9601 /* Setup */
9602
9603 OO.inheritClass( OO.ui.RadioSelectInputWidget, OO.ui.InputWidget );
9604
9605 /* Static Methods */
9606
9607 /**
9608 * @inheritdoc
9609 */
9610 OO.ui.RadioSelectInputWidget.static.gatherPreInfuseState = function ( node, config ) {
9611 var state = OO.ui.RadioSelectInputWidget.parent.static.gatherPreInfuseState( node, config );
9612 state.value = $( node ).find( '.oo-ui-radioInputWidget .oo-ui-inputWidget-input:checked' ).val();
9613 return state;
9614 };
9615
9616 /**
9617 * @inheritdoc
9618 */
9619 OO.ui.RadioSelectInputWidget.static.reusePreInfuseDOM = function ( node, config ) {
9620 config = OO.ui.RadioSelectInputWidget.parent.static.reusePreInfuseDOM( node, config );
9621 // Cannot reuse the `<input type=radio>` set
9622 delete config.$input;
9623 return config;
9624 };
9625
9626 /* Methods */
9627
9628 /**
9629 * @inheritdoc
9630 * @protected
9631 */
9632 OO.ui.RadioSelectInputWidget.prototype.getInputElement = function () {
9633 // Use this instead of <input type="hidden">, because hidden inputs do not have separate
9634 // 'value' and 'defaultValue' properties, and InputWidget wants to handle 'defaultValue'.
9635 return $( '<input>' ).addClass( 'oo-ui-element-hidden' );
9636 };
9637
9638 /**
9639 * Handles menu select events.
9640 *
9641 * @private
9642 * @param {OO.ui.RadioOptionWidget} item Selected menu item
9643 */
9644 OO.ui.RadioSelectInputWidget.prototype.onMenuSelect = function ( item ) {
9645 this.setValue( item.getData() );
9646 };
9647
9648 /**
9649 * @inheritdoc
9650 */
9651 OO.ui.RadioSelectInputWidget.prototype.setValue = function ( value ) {
9652 var selected;
9653 value = this.cleanUpValue( value );
9654 // Only allow setting values that are actually present in the dropdown
9655 selected = this.radioSelectWidget.findItemFromData( value ) ||
9656 this.radioSelectWidget.findFirstSelectableItem();
9657 this.radioSelectWidget.selectItem( selected );
9658 value = selected ? selected.getData() : '';
9659 OO.ui.RadioSelectInputWidget.parent.prototype.setValue.call( this, value );
9660 return this;
9661 };
9662
9663 /**
9664 * @inheritdoc
9665 */
9666 OO.ui.RadioSelectInputWidget.prototype.setDisabled = function ( state ) {
9667 this.radioSelectWidget.setDisabled( state );
9668 OO.ui.RadioSelectInputWidget.parent.prototype.setDisabled.call( this, state );
9669 return this;
9670 };
9671
9672 /**
9673 * Set the options available for this input.
9674 *
9675 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
9676 * @chainable
9677 */
9678 OO.ui.RadioSelectInputWidget.prototype.setOptions = function ( options ) {
9679 var value = this.getValue();
9680
9681 this.setOptionsData( options );
9682
9683 // Re-set the value to update the visible interface (RadioSelectWidget).
9684 // In case the previous value is no longer an available option, select the first valid one.
9685 this.setValue( value );
9686
9687 return this;
9688 };
9689
9690 /**
9691 * Set the internal list of options, used e.g. by setValue() to see which options are allowed.
9692 *
9693 * This method may be called before the parent constructor, so various properties may not be
9694 * intialized yet.
9695 *
9696 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
9697 * @private
9698 */
9699 OO.ui.RadioSelectInputWidget.prototype.setOptionsData = function ( options ) {
9700 var widget = this;
9701
9702 this.radioSelectWidget
9703 .clearItems()
9704 .addItems( options.map( function ( opt ) {
9705 var optValue = widget.cleanUpValue( opt.data );
9706 return new OO.ui.RadioOptionWidget( {
9707 data: optValue,
9708 label: opt.label !== undefined ? opt.label : optValue
9709 } );
9710 } ) );
9711 };
9712
9713 /**
9714 * @inheritdoc
9715 */
9716 OO.ui.RadioSelectInputWidget.prototype.focus = function () {
9717 this.radioSelectWidget.focus();
9718 return this;
9719 };
9720
9721 /**
9722 * @inheritdoc
9723 */
9724 OO.ui.RadioSelectInputWidget.prototype.blur = function () {
9725 this.radioSelectWidget.blur();
9726 return this;
9727 };
9728
9729 /**
9730 * CheckboxMultiselectInputWidget is a
9731 * {@link OO.ui.CheckboxMultiselectWidget CheckboxMultiselectWidget} intended to be used within a
9732 * HTML form, such as a OO.ui.FormLayout. The selected values are synchronized with the value of
9733 * HTML `<input type=checkbox>` tags. Please see the [OOUI documentation on MediaWiki][1] for
9734 * more information about input widgets.
9735 *
9736 * @example
9737 * // Example: A CheckboxMultiselectInputWidget with three options
9738 * var multiselectInput = new OO.ui.CheckboxMultiselectInputWidget( {
9739 * options: [
9740 * { data: 'a', label: 'First' },
9741 * { data: 'b', label: 'Second'},
9742 * { data: 'c', label: 'Third' }
9743 * ]
9744 * } );
9745 * $( 'body' ).append( multiselectInput.$element );
9746 *
9747 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
9748 *
9749 * @class
9750 * @extends OO.ui.InputWidget
9751 *
9752 * @constructor
9753 * @param {Object} [config] Configuration options
9754 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: …, disabled: … }`
9755 */
9756 OO.ui.CheckboxMultiselectInputWidget = function OoUiCheckboxMultiselectInputWidget( config ) {
9757 // Configuration initialization
9758 config = config || {};
9759
9760 // Properties (must be done before parent constructor which calls #setDisabled)
9761 this.checkboxMultiselectWidget = new OO.ui.CheckboxMultiselectWidget();
9762 // Must be set before the #setOptionsData call below
9763 this.inputName = config.name;
9764 // Set up the options before parent constructor, which uses them to validate config.value.
9765 // Use this instead of setOptions() because this.$input is not set up yet
9766 this.setOptionsData( config.options || [] );
9767
9768 // Parent constructor
9769 OO.ui.CheckboxMultiselectInputWidget.parent.call( this, config );
9770
9771 // Events
9772 this.checkboxMultiselectWidget.connect( this, { select: 'onCheckboxesSelect' } );
9773
9774 // Initialization
9775 this.$element
9776 .addClass( 'oo-ui-checkboxMultiselectInputWidget' )
9777 .append( this.checkboxMultiselectWidget.$element );
9778 // We don't use this.$input, but rather the CheckboxInputWidgets inside each option
9779 this.$input.detach();
9780 };
9781
9782 /* Setup */
9783
9784 OO.inheritClass( OO.ui.CheckboxMultiselectInputWidget, OO.ui.InputWidget );
9785
9786 /* Static Methods */
9787
9788 /**
9789 * @inheritdoc
9790 */
9791 OO.ui.CheckboxMultiselectInputWidget.static.gatherPreInfuseState = function ( node, config ) {
9792 var state = OO.ui.CheckboxMultiselectInputWidget.parent.static.gatherPreInfuseState( node, config );
9793 state.value = $( node ).find( '.oo-ui-checkboxInputWidget .oo-ui-inputWidget-input:checked' )
9794 .toArray().map( function ( el ) { return el.value; } );
9795 return state;
9796 };
9797
9798 /**
9799 * @inheritdoc
9800 */
9801 OO.ui.CheckboxMultiselectInputWidget.static.reusePreInfuseDOM = function ( node, config ) {
9802 config = OO.ui.CheckboxMultiselectInputWidget.parent.static.reusePreInfuseDOM( node, config );
9803 // Cannot reuse the `<input type=checkbox>` set
9804 delete config.$input;
9805 return config;
9806 };
9807
9808 /* Methods */
9809
9810 /**
9811 * @inheritdoc
9812 * @protected
9813 */
9814 OO.ui.CheckboxMultiselectInputWidget.prototype.getInputElement = function () {
9815 // Actually unused
9816 return $( '<unused>' );
9817 };
9818
9819 /**
9820 * Handles CheckboxMultiselectWidget select events.
9821 *
9822 * @private
9823 */
9824 OO.ui.CheckboxMultiselectInputWidget.prototype.onCheckboxesSelect = function () {
9825 this.setValue( this.checkboxMultiselectWidget.findSelectedItemsData() );
9826 };
9827
9828 /**
9829 * @inheritdoc
9830 */
9831 OO.ui.CheckboxMultiselectInputWidget.prototype.getValue = function () {
9832 var value = this.$element.find( '.oo-ui-checkboxInputWidget .oo-ui-inputWidget-input:checked' )
9833 .toArray().map( function ( el ) { return el.value; } );
9834 if ( this.value !== value ) {
9835 this.setValue( value );
9836 }
9837 return this.value;
9838 };
9839
9840 /**
9841 * @inheritdoc
9842 */
9843 OO.ui.CheckboxMultiselectInputWidget.prototype.setValue = function ( value ) {
9844 value = this.cleanUpValue( value );
9845 this.checkboxMultiselectWidget.selectItemsByData( value );
9846 OO.ui.CheckboxMultiselectInputWidget.parent.prototype.setValue.call( this, value );
9847 if ( this.optionsDirty ) {
9848 // We reached this from the constructor or from #setOptions.
9849 // We have to update the <select> element.
9850 this.updateOptionsInterface();
9851 }
9852 return this;
9853 };
9854
9855 /**
9856 * Clean up incoming value.
9857 *
9858 * @param {string[]} value Original value
9859 * @return {string[]} Cleaned up value
9860 */
9861 OO.ui.CheckboxMultiselectInputWidget.prototype.cleanUpValue = function ( value ) {
9862 var i, singleValue,
9863 cleanValue = [];
9864 if ( !Array.isArray( value ) ) {
9865 return cleanValue;
9866 }
9867 for ( i = 0; i < value.length; i++ ) {
9868 singleValue =
9869 OO.ui.CheckboxMultiselectInputWidget.parent.prototype.cleanUpValue.call( this, value[ i ] );
9870 // Remove options that we don't have here
9871 if ( !this.checkboxMultiselectWidget.findItemFromData( singleValue ) ) {
9872 continue;
9873 }
9874 cleanValue.push( singleValue );
9875 }
9876 return cleanValue;
9877 };
9878
9879 /**
9880 * @inheritdoc
9881 */
9882 OO.ui.CheckboxMultiselectInputWidget.prototype.setDisabled = function ( state ) {
9883 this.checkboxMultiselectWidget.setDisabled( state );
9884 OO.ui.CheckboxMultiselectInputWidget.parent.prototype.setDisabled.call( this, state );
9885 return this;
9886 };
9887
9888 /**
9889 * Set the options available for this input.
9890 *
9891 * @param {Object[]} options Array of menu options in the format `{ data: …, label: …, disabled: … }`
9892 * @chainable
9893 */
9894 OO.ui.CheckboxMultiselectInputWidget.prototype.setOptions = function ( options ) {
9895 var value = this.getValue();
9896
9897 this.setOptionsData( options );
9898
9899 // Re-set the value to update the visible interface (CheckboxMultiselectWidget).
9900 // This will also get rid of any stale options that we just removed.
9901 this.setValue( value );
9902
9903 return this;
9904 };
9905
9906 /**
9907 * Set the internal list of options, used e.g. by setValue() to see which options are allowed.
9908 *
9909 * This method may be called before the parent constructor, so various properties may not be
9910 * intialized yet.
9911 *
9912 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
9913 * @private
9914 */
9915 OO.ui.CheckboxMultiselectInputWidget.prototype.setOptionsData = function ( options ) {
9916 var widget = this;
9917
9918 this.optionsDirty = true;
9919
9920 this.checkboxMultiselectWidget
9921 .clearItems()
9922 .addItems( options.map( function ( opt ) {
9923 var optValue, item, optDisabled;
9924 optValue =
9925 OO.ui.CheckboxMultiselectInputWidget.parent.prototype.cleanUpValue.call( widget, opt.data );
9926 optDisabled = opt.disabled !== undefined ? opt.disabled : false;
9927 item = new OO.ui.CheckboxMultioptionWidget( {
9928 data: optValue,
9929 label: opt.label !== undefined ? opt.label : optValue,
9930 disabled: optDisabled
9931 } );
9932 // Set the 'name' and 'value' for form submission
9933 item.checkbox.$input.attr( 'name', widget.inputName );
9934 item.checkbox.setValue( optValue );
9935 return item;
9936 } ) );
9937 };
9938
9939 /**
9940 * Update the user-visible interface to match the internal list of options and value.
9941 *
9942 * This method must only be called after the parent constructor.
9943 *
9944 * @private
9945 */
9946 OO.ui.CheckboxMultiselectInputWidget.prototype.updateOptionsInterface = function () {
9947 var defaultValue = this.defaultValue;
9948
9949 this.checkboxMultiselectWidget.getItems().forEach( function ( item ) {
9950 // Remember original selection state. This property can be later used to check whether
9951 // the selection state of the input has been changed since it was created.
9952 var isDefault = defaultValue.indexOf( item.getData() ) !== -1;
9953 item.checkbox.defaultSelected = isDefault;
9954 item.checkbox.$input[ 0 ].defaultChecked = isDefault;
9955 } );
9956
9957 this.optionsDirty = false;
9958 };
9959
9960 /**
9961 * @inheritdoc
9962 */
9963 OO.ui.CheckboxMultiselectInputWidget.prototype.focus = function () {
9964 this.checkboxMultiselectWidget.focus();
9965 return this;
9966 };
9967
9968 /**
9969 * TextInputWidgets, like HTML text inputs, can be configured with options that customize the
9970 * size of the field as well as its presentation. In addition, these widgets can be configured
9971 * with {@link OO.ui.mixin.IconElement icons}, {@link OO.ui.mixin.IndicatorElement indicators}, an optional
9972 * validation-pattern (used to determine if an input value is valid or not) and an input filter,
9973 * which modifies incoming values rather than validating them.
9974 * Please see the [OOUI documentation on MediaWiki] [1] for more information and examples.
9975 *
9976 * This widget can be used inside an HTML form, such as a OO.ui.FormLayout.
9977 *
9978 * @example
9979 * // Example of a text input widget
9980 * var textInput = new OO.ui.TextInputWidget( {
9981 * value: 'Text input'
9982 * } )
9983 * $( 'body' ).append( textInput.$element );
9984 *
9985 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
9986 *
9987 * @class
9988 * @extends OO.ui.InputWidget
9989 * @mixins OO.ui.mixin.IconElement
9990 * @mixins OO.ui.mixin.IndicatorElement
9991 * @mixins OO.ui.mixin.PendingElement
9992 * @mixins OO.ui.mixin.LabelElement
9993 *
9994 * @constructor
9995 * @param {Object} [config] Configuration options
9996 * @cfg {string} [type='text'] The value of the HTML `type` attribute: 'text', 'password'
9997 * 'email', 'url' or 'number'.
9998 * @cfg {string} [placeholder] Placeholder text
9999 * @cfg {boolean} [autofocus=false] Use an HTML `autofocus` attribute to
10000 * instruct the browser to focus this widget.
10001 * @cfg {boolean} [readOnly=false] Prevent changes to the value of the text input.
10002 * @cfg {number} [maxLength] Maximum number of characters allowed in the input.
10003 *
10004 * For unfortunate historical reasons, this counts the number of UTF-16 code units rather than
10005 * Unicode codepoints, which means that codepoints outside the Basic Multilingual Plane (e.g.
10006 * many emojis) count as 2 characters each.
10007 * @cfg {string} [labelPosition='after'] The position of the inline label relative to that of
10008 * the value or placeholder text: `'before'` or `'after'`
10009 * @cfg {boolean} [required=false] Mark the field as required with `true`. Implies `indicator: 'required'`.
10010 * Note that `false` & setting `indicator: 'required' will result in no indicator shown.
10011 * @cfg {boolean} [autocomplete=true] Should the browser support autocomplete for this field
10012 * @cfg {boolean} [spellcheck] Should the browser support spellcheck for this field (`undefined` means
10013 * leaving it up to the browser).
10014 * @cfg {RegExp|Function|string} [validate] Validation pattern: when string, a symbolic name of a
10015 * pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer'
10016 * (the value must contain only numbers); when RegExp, a regular expression that must match the
10017 * value for it to be considered valid; when Function, a function receiving the value as parameter
10018 * that must return true, or promise resolving to true, for it to be considered valid.
10019 */
10020 OO.ui.TextInputWidget = function OoUiTextInputWidget( config ) {
10021 // Configuration initialization
10022 config = $.extend( {
10023 type: 'text',
10024 labelPosition: 'after'
10025 }, config );
10026
10027 if ( config.multiline ) {
10028 OO.ui.warnDeprecation( 'TextInputWidget: config.multiline is deprecated. Use the MultilineTextInputWidget instead. See T130434.' );
10029 return new OO.ui.MultilineTextInputWidget( config );
10030 }
10031
10032 // Parent constructor
10033 OO.ui.TextInputWidget.parent.call( this, config );
10034
10035 // Mixin constructors
10036 OO.ui.mixin.IconElement.call( this, config );
10037 OO.ui.mixin.IndicatorElement.call( this, config );
10038 OO.ui.mixin.PendingElement.call( this, $.extend( {}, config, { $pending: this.$input } ) );
10039 OO.ui.mixin.LabelElement.call( this, config );
10040
10041 // Properties
10042 this.type = this.getSaneType( config );
10043 this.readOnly = false;
10044 this.required = false;
10045 this.validate = null;
10046 this.styleHeight = null;
10047 this.scrollWidth = null;
10048
10049 this.setValidation( config.validate );
10050 this.setLabelPosition( config.labelPosition );
10051
10052 // Events
10053 this.$input.on( {
10054 keypress: this.onKeyPress.bind( this ),
10055 blur: this.onBlur.bind( this ),
10056 focus: this.onFocus.bind( this )
10057 } );
10058 this.$icon.on( 'mousedown', this.onIconMouseDown.bind( this ) );
10059 this.$indicator.on( 'mousedown', this.onIndicatorMouseDown.bind( this ) );
10060 this.on( 'labelChange', this.updatePosition.bind( this ) );
10061 this.on( 'change', OO.ui.debounce( this.onDebouncedChange.bind( this ), 250 ) );
10062
10063 // Initialization
10064 this.$element
10065 .addClass( 'oo-ui-textInputWidget oo-ui-textInputWidget-type-' + this.type )
10066 .append( this.$icon, this.$indicator );
10067 this.setReadOnly( !!config.readOnly );
10068 this.setRequired( !!config.required );
10069 if ( config.placeholder !== undefined ) {
10070 this.$input.attr( 'placeholder', config.placeholder );
10071 }
10072 if ( config.maxLength !== undefined ) {
10073 this.$input.attr( 'maxlength', config.maxLength );
10074 }
10075 if ( config.autofocus ) {
10076 this.$input.attr( 'autofocus', 'autofocus' );
10077 }
10078 if ( config.autocomplete === false ) {
10079 this.$input.attr( 'autocomplete', 'off' );
10080 // Turning off autocompletion also disables "form caching" when the user navigates to a
10081 // different page and then clicks "Back". Re-enable it when leaving. Borrowed from jQuery UI.
10082 $( window ).on( {
10083 beforeunload: function () {
10084 this.$input.removeAttr( 'autocomplete' );
10085 }.bind( this ),
10086 pageshow: function () {
10087 // Browsers don't seem to actually fire this event on "Back", they instead just reload the
10088 // whole page... it shouldn't hurt, though.
10089 this.$input.attr( 'autocomplete', 'off' );
10090 }.bind( this )
10091 } );
10092 }
10093 if ( config.spellcheck !== undefined ) {
10094 this.$input.attr( 'spellcheck', config.spellcheck ? 'true' : 'false' );
10095 }
10096 if ( this.label ) {
10097 this.isWaitingToBeAttached = true;
10098 this.installParentChangeDetector();
10099 }
10100 };
10101
10102 /* Setup */
10103
10104 OO.inheritClass( OO.ui.TextInputWidget, OO.ui.InputWidget );
10105 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.mixin.IconElement );
10106 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.mixin.IndicatorElement );
10107 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.mixin.PendingElement );
10108 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.mixin.LabelElement );
10109
10110 /* Static Properties */
10111
10112 OO.ui.TextInputWidget.static.validationPatterns = {
10113 'non-empty': /.+/,
10114 integer: /^\d+$/
10115 };
10116
10117 /* Events */
10118
10119 /**
10120 * An `enter` event is emitted when the user presses 'enter' inside the text box.
10121 *
10122 * @event enter
10123 */
10124
10125 /* Methods */
10126
10127 /**
10128 * Handle icon mouse down events.
10129 *
10130 * @private
10131 * @param {jQuery.Event} e Mouse down event
10132 */
10133 OO.ui.TextInputWidget.prototype.onIconMouseDown = function ( e ) {
10134 if ( e.which === OO.ui.MouseButtons.LEFT ) {
10135 this.focus();
10136 return false;
10137 }
10138 };
10139
10140 /**
10141 * Handle indicator mouse down events.
10142 *
10143 * @private
10144 * @param {jQuery.Event} e Mouse down event
10145 */
10146 OO.ui.TextInputWidget.prototype.onIndicatorMouseDown = function ( e ) {
10147 if ( e.which === OO.ui.MouseButtons.LEFT ) {
10148 this.focus();
10149 return false;
10150 }
10151 };
10152
10153 /**
10154 * Handle key press events.
10155 *
10156 * @private
10157 * @param {jQuery.Event} e Key press event
10158 * @fires enter If enter key is pressed
10159 */
10160 OO.ui.TextInputWidget.prototype.onKeyPress = function ( e ) {
10161 if ( e.which === OO.ui.Keys.ENTER ) {
10162 this.emit( 'enter', e );
10163 }
10164 };
10165
10166 /**
10167 * Handle blur events.
10168 *
10169 * @private
10170 * @param {jQuery.Event} e Blur event
10171 */
10172 OO.ui.TextInputWidget.prototype.onBlur = function () {
10173 this.setValidityFlag();
10174 };
10175
10176 /**
10177 * Handle focus events.
10178 *
10179 * @private
10180 * @param {jQuery.Event} e Focus event
10181 */
10182 OO.ui.TextInputWidget.prototype.onFocus = function () {
10183 if ( this.isWaitingToBeAttached ) {
10184 // If we've received focus, then we must be attached to the document, and if
10185 // isWaitingToBeAttached is still true, that means the handler never fired. Fire it now.
10186 this.onElementAttach();
10187 }
10188 this.setValidityFlag( true );
10189 };
10190
10191 /**
10192 * Handle element attach events.
10193 *
10194 * @private
10195 * @param {jQuery.Event} e Element attach event
10196 */
10197 OO.ui.TextInputWidget.prototype.onElementAttach = function () {
10198 this.isWaitingToBeAttached = false;
10199 // Any previously calculated size is now probably invalid if we reattached elsewhere
10200 this.valCache = null;
10201 this.positionLabel();
10202 };
10203
10204 /**
10205 * Handle debounced change events.
10206 *
10207 * @param {string} value
10208 * @private
10209 */
10210 OO.ui.TextInputWidget.prototype.onDebouncedChange = function () {
10211 this.setValidityFlag();
10212 };
10213
10214 /**
10215 * Check if the input is {@link #readOnly read-only}.
10216 *
10217 * @return {boolean}
10218 */
10219 OO.ui.TextInputWidget.prototype.isReadOnly = function () {
10220 return this.readOnly;
10221 };
10222
10223 /**
10224 * Set the {@link #readOnly read-only} state of the input.
10225 *
10226 * @param {boolean} state Make input read-only
10227 * @chainable
10228 */
10229 OO.ui.TextInputWidget.prototype.setReadOnly = function ( state ) {
10230 this.readOnly = !!state;
10231 this.$input.prop( 'readOnly', this.readOnly );
10232 return this;
10233 };
10234
10235 /**
10236 * Check if the input is {@link #required required}.
10237 *
10238 * @return {boolean}
10239 */
10240 OO.ui.TextInputWidget.prototype.isRequired = function () {
10241 return this.required;
10242 };
10243
10244 /**
10245 * Set the {@link #required required} state of the input.
10246 *
10247 * @param {boolean} state Make input required
10248 * @chainable
10249 */
10250 OO.ui.TextInputWidget.prototype.setRequired = function ( state ) {
10251 this.required = !!state;
10252 if ( this.required ) {
10253 this.$input
10254 .prop( 'required', true )
10255 .attr( 'aria-required', 'true' );
10256 if ( this.getIndicator() === null ) {
10257 this.setIndicator( 'required' );
10258 }
10259 } else {
10260 this.$input
10261 .prop( 'required', false )
10262 .removeAttr( 'aria-required' );
10263 if ( this.getIndicator() === 'required' ) {
10264 this.setIndicator( null );
10265 }
10266 }
10267 return this;
10268 };
10269
10270 /**
10271 * Support function for making #onElementAttach work across browsers.
10272 *
10273 * This whole function could be replaced with one line of code using the DOMNodeInsertedIntoDocument
10274 * event, but it's not supported by Firefox and allegedly deprecated, so we only use it as fallback.
10275 *
10276 * Due to MutationObserver performance woes, #onElementAttach is only somewhat reliably called the
10277 * first time that the element gets attached to the documented.
10278 */
10279 OO.ui.TextInputWidget.prototype.installParentChangeDetector = function () {
10280 var mutationObserver, onRemove, topmostNode, fakeParentNode,
10281 MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver,
10282 widget = this;
10283
10284 if ( MutationObserver ) {
10285 // The new way. If only it wasn't so ugly.
10286
10287 if ( this.isElementAttached() ) {
10288 // Widget is attached already, do nothing. This breaks the functionality of this function when
10289 // the widget is detached and reattached. Alas, doing this correctly with MutationObserver
10290 // would require observation of the whole document, which would hurt performance of other,
10291 // more important code.
10292 return;
10293 }
10294
10295 // Find topmost node in the tree
10296 topmostNode = this.$element[ 0 ];
10297 while ( topmostNode.parentNode ) {
10298 topmostNode = topmostNode.parentNode;
10299 }
10300
10301 // We have no way to detect the $element being attached somewhere without observing the entire
10302 // DOM with subtree modifications, which would hurt performance. So we cheat: we hook to the
10303 // parent node of $element, and instead detect when $element is removed from it (and thus
10304 // probably attached somewhere else). If there is no parent, we create a "fake" one. If it
10305 // doesn't get attached, we end up back here and create the parent.
10306
10307 mutationObserver = new MutationObserver( function ( mutations ) {
10308 var i, j, removedNodes;
10309 for ( i = 0; i < mutations.length; i++ ) {
10310 removedNodes = mutations[ i ].removedNodes;
10311 for ( j = 0; j < removedNodes.length; j++ ) {
10312 if ( removedNodes[ j ] === topmostNode ) {
10313 setTimeout( onRemove, 0 );
10314 return;
10315 }
10316 }
10317 }
10318 } );
10319
10320 onRemove = function () {
10321 // If the node was attached somewhere else, report it
10322 if ( widget.isElementAttached() ) {
10323 widget.onElementAttach();
10324 }
10325 mutationObserver.disconnect();
10326 widget.installParentChangeDetector();
10327 };
10328
10329 // Create a fake parent and observe it
10330 fakeParentNode = $( '<div>' ).append( topmostNode )[ 0 ];
10331 mutationObserver.observe( fakeParentNode, { childList: true } );
10332 } else {
10333 // Using the DOMNodeInsertedIntoDocument event is much nicer and less magical, and works for
10334 // detachment and reattachment, but it's not supported by Firefox and allegedly deprecated.
10335 this.$element.on( 'DOMNodeInsertedIntoDocument', this.onElementAttach.bind( this ) );
10336 }
10337 };
10338
10339 /**
10340 * @inheritdoc
10341 * @protected
10342 */
10343 OO.ui.TextInputWidget.prototype.getInputElement = function ( config ) {
10344 if ( this.getSaneType( config ) === 'number' ) {
10345 return $( '<input>' )
10346 .attr( 'step', 'any' )
10347 .attr( 'type', 'number' );
10348 } else {
10349 return $( '<input>' ).attr( 'type', this.getSaneType( config ) );
10350 }
10351 };
10352
10353 /**
10354 * Get sanitized value for 'type' for given config.
10355 *
10356 * @param {Object} config Configuration options
10357 * @return {string|null}
10358 * @protected
10359 */
10360 OO.ui.TextInputWidget.prototype.getSaneType = function ( config ) {
10361 var allowedTypes = [
10362 'text',
10363 'password',
10364 'email',
10365 'url',
10366 'number'
10367 ];
10368 return allowedTypes.indexOf( config.type ) !== -1 ? config.type : 'text';
10369 };
10370
10371 /**
10372 * Focus the input and select a specified range within the text.
10373 *
10374 * @param {number} from Select from offset
10375 * @param {number} [to] Select to offset, defaults to from
10376 * @chainable
10377 */
10378 OO.ui.TextInputWidget.prototype.selectRange = function ( from, to ) {
10379 var isBackwards, start, end,
10380 input = this.$input[ 0 ];
10381
10382 to = to || from;
10383
10384 isBackwards = to < from;
10385 start = isBackwards ? to : from;
10386 end = isBackwards ? from : to;
10387
10388 this.focus();
10389
10390 try {
10391 input.setSelectionRange( start, end, isBackwards ? 'backward' : 'forward' );
10392 } catch ( e ) {
10393 // IE throws an exception if you call setSelectionRange on a unattached DOM node.
10394 // Rather than expensively check if the input is attached every time, just check
10395 // if it was the cause of an error being thrown. If not, rethrow the error.
10396 if ( this.getElementDocument().body.contains( input ) ) {
10397 throw e;
10398 }
10399 }
10400 return this;
10401 };
10402
10403 /**
10404 * Get an object describing the current selection range in a directional manner
10405 *
10406 * @return {Object} Object containing 'from' and 'to' offsets
10407 */
10408 OO.ui.TextInputWidget.prototype.getRange = function () {
10409 var input = this.$input[ 0 ],
10410 start = input.selectionStart,
10411 end = input.selectionEnd,
10412 isBackwards = input.selectionDirection === 'backward';
10413
10414 return {
10415 from: isBackwards ? end : start,
10416 to: isBackwards ? start : end
10417 };
10418 };
10419
10420 /**
10421 * Get the length of the text input value.
10422 *
10423 * This could differ from the length of #getValue if the
10424 * value gets filtered
10425 *
10426 * @return {number} Input length
10427 */
10428 OO.ui.TextInputWidget.prototype.getInputLength = function () {
10429 return this.$input[ 0 ].value.length;
10430 };
10431
10432 /**
10433 * Focus the input and select the entire text.
10434 *
10435 * @chainable
10436 */
10437 OO.ui.TextInputWidget.prototype.select = function () {
10438 return this.selectRange( 0, this.getInputLength() );
10439 };
10440
10441 /**
10442 * Focus the input and move the cursor to the start.
10443 *
10444 * @chainable
10445 */
10446 OO.ui.TextInputWidget.prototype.moveCursorToStart = function () {
10447 return this.selectRange( 0 );
10448 };
10449
10450 /**
10451 * Focus the input and move the cursor to the end.
10452 *
10453 * @chainable
10454 */
10455 OO.ui.TextInputWidget.prototype.moveCursorToEnd = function () {
10456 return this.selectRange( this.getInputLength() );
10457 };
10458
10459 /**
10460 * Insert new content into the input.
10461 *
10462 * @param {string} content Content to be inserted
10463 * @chainable
10464 */
10465 OO.ui.TextInputWidget.prototype.insertContent = function ( content ) {
10466 var start, end,
10467 range = this.getRange(),
10468 value = this.getValue();
10469
10470 start = Math.min( range.from, range.to );
10471 end = Math.max( range.from, range.to );
10472
10473 this.setValue( value.slice( 0, start ) + content + value.slice( end ) );
10474 this.selectRange( start + content.length );
10475 return this;
10476 };
10477
10478 /**
10479 * Insert new content either side of a selection.
10480 *
10481 * @param {string} pre Content to be inserted before the selection
10482 * @param {string} post Content to be inserted after the selection
10483 * @chainable
10484 */
10485 OO.ui.TextInputWidget.prototype.encapsulateContent = function ( pre, post ) {
10486 var start, end,
10487 range = this.getRange(),
10488 offset = pre.length;
10489
10490 start = Math.min( range.from, range.to );
10491 end = Math.max( range.from, range.to );
10492
10493 this.selectRange( start ).insertContent( pre );
10494 this.selectRange( offset + end ).insertContent( post );
10495
10496 this.selectRange( offset + start, offset + end );
10497 return this;
10498 };
10499
10500 /**
10501 * Set the validation pattern.
10502 *
10503 * The validation pattern is either a regular expression, a function, or the symbolic name of a
10504 * pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer' (the
10505 * value must contain only numbers).
10506 *
10507 * @param {RegExp|Function|string|null} validate Regular expression, function, or the symbolic name
10508 * of a pattern (either ‘integer’ or ‘non-empty’) defined by the class.
10509 */
10510 OO.ui.TextInputWidget.prototype.setValidation = function ( validate ) {
10511 if ( validate instanceof RegExp || validate instanceof Function ) {
10512 this.validate = validate;
10513 } else {
10514 this.validate = this.constructor.static.validationPatterns[ validate ] || /.*/;
10515 }
10516 };
10517
10518 /**
10519 * Sets the 'invalid' flag appropriately.
10520 *
10521 * @param {boolean} [isValid] Optionally override validation result
10522 */
10523 OO.ui.TextInputWidget.prototype.setValidityFlag = function ( isValid ) {
10524 var widget = this,
10525 setFlag = function ( valid ) {
10526 if ( !valid ) {
10527 widget.$input.attr( 'aria-invalid', 'true' );
10528 } else {
10529 widget.$input.removeAttr( 'aria-invalid' );
10530 }
10531 widget.setFlags( { invalid: !valid } );
10532 };
10533
10534 if ( isValid !== undefined ) {
10535 setFlag( isValid );
10536 } else {
10537 this.getValidity().then( function () {
10538 setFlag( true );
10539 }, function () {
10540 setFlag( false );
10541 } );
10542 }
10543 };
10544
10545 /**
10546 * Get the validity of current value.
10547 *
10548 * This method returns a promise that resolves if the value is valid and rejects if
10549 * it isn't. Uses the {@link #validate validation pattern} to check for validity.
10550 *
10551 * @return {jQuery.Promise} A promise that resolves if the value is valid, rejects if not.
10552 */
10553 OO.ui.TextInputWidget.prototype.getValidity = function () {
10554 var result;
10555
10556 function rejectOrResolve( valid ) {
10557 if ( valid ) {
10558 return $.Deferred().resolve().promise();
10559 } else {
10560 return $.Deferred().reject().promise();
10561 }
10562 }
10563
10564 // Check browser validity and reject if it is invalid
10565 if (
10566 this.$input[ 0 ].checkValidity !== undefined &&
10567 this.$input[ 0 ].checkValidity() === false
10568 ) {
10569 return rejectOrResolve( false );
10570 }
10571
10572 // Run our checks if the browser thinks the field is valid
10573 if ( this.validate instanceof Function ) {
10574 result = this.validate( this.getValue() );
10575 if ( result && $.isFunction( result.promise ) ) {
10576 return result.promise().then( function ( valid ) {
10577 return rejectOrResolve( valid );
10578 } );
10579 } else {
10580 return rejectOrResolve( result );
10581 }
10582 } else {
10583 return rejectOrResolve( this.getValue().match( this.validate ) );
10584 }
10585 };
10586
10587 /**
10588 * Set the position of the inline label relative to that of the value: `‘before’` or `‘after’`.
10589 *
10590 * @param {string} labelPosition Label position, 'before' or 'after'
10591 * @chainable
10592 */
10593 OO.ui.TextInputWidget.prototype.setLabelPosition = function ( labelPosition ) {
10594 this.labelPosition = labelPosition;
10595 if ( this.label ) {
10596 // If there is no label and we only change the position, #updatePosition is a no-op,
10597 // but it takes really a lot of work to do nothing.
10598 this.updatePosition();
10599 }
10600 return this;
10601 };
10602
10603 /**
10604 * Update the position of the inline label.
10605 *
10606 * This method is called by #setLabelPosition, and can also be called on its own if
10607 * something causes the label to be mispositioned.
10608 *
10609 * @chainable
10610 */
10611 OO.ui.TextInputWidget.prototype.updatePosition = function () {
10612 var after = this.labelPosition === 'after';
10613
10614 this.$element
10615 .toggleClass( 'oo-ui-textInputWidget-labelPosition-after', !!this.label && after )
10616 .toggleClass( 'oo-ui-textInputWidget-labelPosition-before', !!this.label && !after );
10617
10618 this.valCache = null;
10619 this.scrollWidth = null;
10620 this.positionLabel();
10621
10622 return this;
10623 };
10624
10625 /**
10626 * Position the label by setting the correct padding on the input.
10627 *
10628 * @private
10629 * @chainable
10630 */
10631 OO.ui.TextInputWidget.prototype.positionLabel = function () {
10632 var after, rtl, property, newCss;
10633
10634 if ( this.isWaitingToBeAttached ) {
10635 // #onElementAttach will be called soon, which calls this method
10636 return this;
10637 }
10638
10639 newCss = {
10640 'padding-right': '',
10641 'padding-left': ''
10642 };
10643
10644 if ( this.label ) {
10645 this.$element.append( this.$label );
10646 } else {
10647 this.$label.detach();
10648 // Clear old values if present
10649 this.$input.css( newCss );
10650 return;
10651 }
10652
10653 after = this.labelPosition === 'after';
10654 rtl = this.$element.css( 'direction' ) === 'rtl';
10655 property = after === rtl ? 'padding-left' : 'padding-right';
10656
10657 newCss[ property ] = this.$label.outerWidth( true ) + ( after ? this.scrollWidth : 0 );
10658 // We have to clear the padding on the other side, in case the element direction changed
10659 this.$input.css( newCss );
10660
10661 return this;
10662 };
10663
10664 /**
10665 * @class
10666 * @extends OO.ui.TextInputWidget
10667 *
10668 * @constructor
10669 * @param {Object} [config] Configuration options
10670 */
10671 OO.ui.SearchInputWidget = function OoUiSearchInputWidget( config ) {
10672 config = $.extend( {
10673 icon: 'search'
10674 }, config );
10675
10676 // Parent constructor
10677 OO.ui.SearchInputWidget.parent.call( this, config );
10678
10679 // Events
10680 this.connect( this, {
10681 change: 'onChange'
10682 } );
10683
10684 // Initialization
10685 this.updateSearchIndicator();
10686 this.connect( this, {
10687 disable: 'onDisable'
10688 } );
10689 };
10690
10691 /* Setup */
10692
10693 OO.inheritClass( OO.ui.SearchInputWidget, OO.ui.TextInputWidget );
10694
10695 /* Methods */
10696
10697 /**
10698 * @inheritdoc
10699 * @protected
10700 */
10701 OO.ui.SearchInputWidget.prototype.getSaneType = function () {
10702 return 'search';
10703 };
10704
10705 /**
10706 * @inheritdoc
10707 */
10708 OO.ui.SearchInputWidget.prototype.onIndicatorMouseDown = function ( e ) {
10709 if ( e.which === OO.ui.MouseButtons.LEFT ) {
10710 // Clear the text field
10711 this.setValue( '' );
10712 this.focus();
10713 return false;
10714 }
10715 };
10716
10717 /**
10718 * Update the 'clear' indicator displayed on type: 'search' text
10719 * fields, hiding it when the field is already empty or when it's not
10720 * editable.
10721 */
10722 OO.ui.SearchInputWidget.prototype.updateSearchIndicator = function () {
10723 if ( this.getValue() === '' || this.isDisabled() || this.isReadOnly() ) {
10724 this.setIndicator( null );
10725 } else {
10726 this.setIndicator( 'clear' );
10727 }
10728 };
10729
10730 /**
10731 * Handle change events.
10732 *
10733 * @private
10734 */
10735 OO.ui.SearchInputWidget.prototype.onChange = function () {
10736 this.updateSearchIndicator();
10737 };
10738
10739 /**
10740 * Handle disable events.
10741 *
10742 * @param {boolean} disabled Element is disabled
10743 * @private
10744 */
10745 OO.ui.SearchInputWidget.prototype.onDisable = function () {
10746 this.updateSearchIndicator();
10747 };
10748
10749 /**
10750 * @inheritdoc
10751 */
10752 OO.ui.SearchInputWidget.prototype.setReadOnly = function ( state ) {
10753 OO.ui.SearchInputWidget.parent.prototype.setReadOnly.call( this, state );
10754 this.updateSearchIndicator();
10755 return this;
10756 };
10757
10758 /**
10759 * @class
10760 * @extends OO.ui.TextInputWidget
10761 *
10762 * @constructor
10763 * @param {Object} [config] Configuration options
10764 * @cfg {number} [rows] Number of visible lines in textarea. If used with `autosize`,
10765 * specifies minimum number of rows to display.
10766 * @cfg {boolean} [autosize=false] Automatically resize the text input to fit its content.
10767 * Use the #maxRows config to specify a maximum number of displayed rows.
10768 * @cfg {number} [maxRows] Maximum number of rows to display when #autosize is set to true.
10769 * Defaults to the maximum of `10` and `2 * rows`, or `10` if `rows` isn't provided.
10770 */
10771 OO.ui.MultilineTextInputWidget = function OoUiMultilineTextInputWidget( config ) {
10772 config = $.extend( {
10773 type: 'text'
10774 }, config );
10775 config.multiline = false;
10776 // Parent constructor
10777 OO.ui.MultilineTextInputWidget.parent.call( this, config );
10778
10779 // Properties
10780 this.multiline = true;
10781 this.autosize = !!config.autosize;
10782 this.minRows = config.rows !== undefined ? config.rows : '';
10783 this.maxRows = config.maxRows || Math.max( 2 * ( this.minRows || 0 ), 10 );
10784
10785 // Clone for resizing
10786 if ( this.autosize ) {
10787 this.$clone = this.$input
10788 .clone()
10789 .insertAfter( this.$input )
10790 .attr( 'aria-hidden', 'true' )
10791 .addClass( 'oo-ui-element-hidden' );
10792 }
10793
10794 // Events
10795 this.connect( this, {
10796 change: 'onChange'
10797 } );
10798
10799 // Initialization
10800 if ( this.multiline && config.rows ) {
10801 this.$input.attr( 'rows', config.rows );
10802 }
10803 if ( this.autosize ) {
10804 this.$input.addClass( 'oo-ui-textInputWidget-autosized' );
10805 this.isWaitingToBeAttached = true;
10806 this.installParentChangeDetector();
10807 }
10808 };
10809
10810 /* Setup */
10811
10812 OO.inheritClass( OO.ui.MultilineTextInputWidget, OO.ui.TextInputWidget );
10813
10814 /* Static Methods */
10815
10816 /**
10817 * @inheritdoc
10818 */
10819 OO.ui.MultilineTextInputWidget.static.gatherPreInfuseState = function ( node, config ) {
10820 var state = OO.ui.MultilineTextInputWidget.parent.static.gatherPreInfuseState( node, config );
10821 state.scrollTop = config.$input.scrollTop();
10822 return state;
10823 };
10824
10825 /* Methods */
10826
10827 /**
10828 * @inheritdoc
10829 */
10830 OO.ui.MultilineTextInputWidget.prototype.onElementAttach = function () {
10831 OO.ui.MultilineTextInputWidget.parent.prototype.onElementAttach.call( this );
10832 this.adjustSize();
10833 };
10834
10835 /**
10836 * Handle change events.
10837 *
10838 * @private
10839 */
10840 OO.ui.MultilineTextInputWidget.prototype.onChange = function () {
10841 this.adjustSize();
10842 };
10843
10844 /**
10845 * @inheritdoc
10846 */
10847 OO.ui.MultilineTextInputWidget.prototype.updatePosition = function () {
10848 OO.ui.MultilineTextInputWidget.parent.prototype.updatePosition.call( this );
10849 this.adjustSize();
10850 };
10851
10852 /**
10853 * @inheritdoc
10854 *
10855 * Modify to emit 'enter' on Ctrl/Meta+Enter, instead of plain Enter
10856 */
10857 OO.ui.MultilineTextInputWidget.prototype.onKeyPress = function ( e ) {
10858 if (
10859 ( e.which === OO.ui.Keys.ENTER && ( e.ctrlKey || e.metaKey ) ) ||
10860 // Some platforms emit keycode 10 for ctrl+enter in a textarea
10861 e.which === 10
10862 ) {
10863 this.emit( 'enter', e );
10864 }
10865 };
10866
10867 /**
10868 * Automatically adjust the size of the text input.
10869 *
10870 * This only affects multiline inputs that are {@link #autosize autosized}.
10871 *
10872 * @chainable
10873 * @fires resize
10874 */
10875 OO.ui.MultilineTextInputWidget.prototype.adjustSize = function () {
10876 var scrollHeight, innerHeight, outerHeight, maxInnerHeight, measurementError,
10877 idealHeight, newHeight, scrollWidth, property;
10878
10879 if ( this.$input.val() !== this.valCache ) {
10880 if ( this.autosize ) {
10881 this.$clone
10882 .val( this.$input.val() )
10883 .attr( 'rows', this.minRows )
10884 // Set inline height property to 0 to measure scroll height
10885 .css( 'height', 0 );
10886
10887 this.$clone.removeClass( 'oo-ui-element-hidden' );
10888
10889 this.valCache = this.$input.val();
10890
10891 scrollHeight = this.$clone[ 0 ].scrollHeight;
10892
10893 // Remove inline height property to measure natural heights
10894 this.$clone.css( 'height', '' );
10895 innerHeight = this.$clone.innerHeight();
10896 outerHeight = this.$clone.outerHeight();
10897
10898 // Measure max rows height
10899 this.$clone
10900 .attr( 'rows', this.maxRows )
10901 .css( 'height', 'auto' )
10902 .val( '' );
10903 maxInnerHeight = this.$clone.innerHeight();
10904
10905 // Difference between reported innerHeight and scrollHeight with no scrollbars present.
10906 // This is sometimes non-zero on Blink-based browsers, depending on zoom level.
10907 measurementError = maxInnerHeight - this.$clone[ 0 ].scrollHeight;
10908 idealHeight = Math.min( maxInnerHeight, scrollHeight + measurementError );
10909
10910 this.$clone.addClass( 'oo-ui-element-hidden' );
10911
10912 // Only apply inline height when expansion beyond natural height is needed
10913 // Use the difference between the inner and outer height as a buffer
10914 newHeight = idealHeight > innerHeight ? idealHeight + ( outerHeight - innerHeight ) : '';
10915 if ( newHeight !== this.styleHeight ) {
10916 this.$input.css( 'height', newHeight );
10917 this.styleHeight = newHeight;
10918 this.emit( 'resize' );
10919 }
10920 }
10921 scrollWidth = this.$input[ 0 ].offsetWidth - this.$input[ 0 ].clientWidth;
10922 if ( scrollWidth !== this.scrollWidth ) {
10923 property = this.$element.css( 'direction' ) === 'rtl' ? 'left' : 'right';
10924 // Reset
10925 this.$label.css( { right: '', left: '' } );
10926 this.$indicator.css( { right: '', left: '' } );
10927
10928 if ( scrollWidth ) {
10929 this.$indicator.css( property, scrollWidth );
10930 if ( this.labelPosition === 'after' ) {
10931 this.$label.css( property, scrollWidth );
10932 }
10933 }
10934
10935 this.scrollWidth = scrollWidth;
10936 this.positionLabel();
10937 }
10938 }
10939 return this;
10940 };
10941
10942 /**
10943 * @inheritdoc
10944 * @protected
10945 */
10946 OO.ui.MultilineTextInputWidget.prototype.getInputElement = function () {
10947 return $( '<textarea>' );
10948 };
10949
10950 /**
10951 * Check if the input supports multiple lines.
10952 *
10953 * @return {boolean}
10954 */
10955 OO.ui.MultilineTextInputWidget.prototype.isMultiline = function () {
10956 return !!this.multiline;
10957 };
10958
10959 /**
10960 * Check if the input automatically adjusts its size.
10961 *
10962 * @return {boolean}
10963 */
10964 OO.ui.MultilineTextInputWidget.prototype.isAutosizing = function () {
10965 return !!this.autosize;
10966 };
10967
10968 /**
10969 * @inheritdoc
10970 */
10971 OO.ui.MultilineTextInputWidget.prototype.restorePreInfuseState = function ( state ) {
10972 OO.ui.MultilineTextInputWidget.parent.prototype.restorePreInfuseState.call( this, state );
10973 if ( state.scrollTop !== undefined ) {
10974 this.$input.scrollTop( state.scrollTop );
10975 }
10976 };
10977
10978 /**
10979 * ComboBoxInputWidgets combine a {@link OO.ui.TextInputWidget text input} (where a value
10980 * can be entered manually) and a {@link OO.ui.MenuSelectWidget menu of options} (from which
10981 * a value can be chosen instead). Users can choose options from the combo box in one of two ways:
10982 *
10983 * - by typing a value in the text input field. If the value exactly matches the value of a menu
10984 * option, that option will appear to be selected.
10985 * - by choosing a value from the menu. The value of the chosen option will then appear in the text
10986 * input field.
10987 *
10988 * After the user chooses an option, its `data` will be used as a new value for the widget.
10989 * A `label` also can be specified for each option: if given, it will be shown instead of the
10990 * `data` in the dropdown menu.
10991 *
10992 * This widget can be used inside an HTML form, such as a OO.ui.FormLayout.
10993 *
10994 * For more information about menus and options, please see the [OOUI documentation on MediaWiki][1].
10995 *
10996 * @example
10997 * // Example: A ComboBoxInputWidget.
10998 * var comboBox = new OO.ui.ComboBoxInputWidget( {
10999 * value: 'Option 1',
11000 * options: [
11001 * { data: 'Option 1' },
11002 * { data: 'Option 2' },
11003 * { data: 'Option 3' }
11004 * ]
11005 * } );
11006 * $( 'body' ).append( comboBox.$element );
11007 *
11008 * @example
11009 * // Example: A ComboBoxInputWidget with additional option labels.
11010 * var comboBox = new OO.ui.ComboBoxInputWidget( {
11011 * value: 'Option 1',
11012 * options: [
11013 * {
11014 * data: 'Option 1',
11015 * label: 'Option One'
11016 * },
11017 * {
11018 * data: 'Option 2',
11019 * label: 'Option Two'
11020 * },
11021 * {
11022 * data: 'Option 3',
11023 * label: 'Option Three'
11024 * }
11025 * ]
11026 * } );
11027 * $( 'body' ).append( comboBox.$element );
11028 *
11029 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options#Menu_selects_and_options
11030 *
11031 * @class
11032 * @extends OO.ui.TextInputWidget
11033 *
11034 * @constructor
11035 * @param {Object} [config] Configuration options
11036 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
11037 * @cfg {Object} [menu] Configuration options to pass to the {@link OO.ui.MenuSelectWidget menu select widget}.
11038 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
11039 * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
11040 * containing `<div>` and has a larger area. By default, the menu uses relative positioning.
11041 * See <https://www.mediawiki.org/wiki/OOUI/Concepts#Overlays>.
11042 */
11043 OO.ui.ComboBoxInputWidget = function OoUiComboBoxInputWidget( config ) {
11044 // Configuration initialization
11045 config = $.extend( {
11046 autocomplete: false
11047 }, config );
11048
11049 // ComboBoxInputWidget shouldn't support `multiline`
11050 config.multiline = false;
11051
11052 // See InputWidget#reusePreInfuseDOM about `config.$input`
11053 if ( config.$input ) {
11054 config.$input.removeAttr( 'list' );
11055 }
11056
11057 // Parent constructor
11058 OO.ui.ComboBoxInputWidget.parent.call( this, config );
11059
11060 // Properties
11061 this.$overlay = ( config.$overlay === true ? OO.ui.getDefaultOverlay() : config.$overlay ) || this.$element;
11062 this.dropdownButton = new OO.ui.ButtonWidget( {
11063 classes: [ 'oo-ui-comboBoxInputWidget-dropdownButton' ],
11064 indicator: 'down',
11065 disabled: this.disabled
11066 } );
11067 this.menu = new OO.ui.MenuSelectWidget( $.extend(
11068 {
11069 widget: this,
11070 input: this,
11071 $floatableContainer: this.$element,
11072 disabled: this.isDisabled()
11073 },
11074 config.menu
11075 ) );
11076
11077 // Events
11078 this.connect( this, {
11079 change: 'onInputChange',
11080 enter: 'onInputEnter'
11081 } );
11082 this.dropdownButton.connect( this, {
11083 click: 'onDropdownButtonClick'
11084 } );
11085 this.menu.connect( this, {
11086 choose: 'onMenuChoose',
11087 add: 'onMenuItemsChange',
11088 remove: 'onMenuItemsChange',
11089 toggle: 'onMenuToggle'
11090 } );
11091
11092 // Initialization
11093 this.$input.attr( {
11094 role: 'combobox',
11095 'aria-owns': this.menu.getElementId(),
11096 'aria-autocomplete': 'list'
11097 } );
11098 // Do not override options set via config.menu.items
11099 if ( config.options !== undefined ) {
11100 this.setOptions( config.options );
11101 }
11102 this.$field = $( '<div>' )
11103 .addClass( 'oo-ui-comboBoxInputWidget-field' )
11104 .append( this.$input, this.dropdownButton.$element );
11105 this.$element
11106 .addClass( 'oo-ui-comboBoxInputWidget' )
11107 .append( this.$field );
11108 this.$overlay.append( this.menu.$element );
11109 this.onMenuItemsChange();
11110 };
11111
11112 /* Setup */
11113
11114 OO.inheritClass( OO.ui.ComboBoxInputWidget, OO.ui.TextInputWidget );
11115
11116 /* Methods */
11117
11118 /**
11119 * Get the combobox's menu.
11120 *
11121 * @return {OO.ui.MenuSelectWidget} Menu widget
11122 */
11123 OO.ui.ComboBoxInputWidget.prototype.getMenu = function () {
11124 return this.menu;
11125 };
11126
11127 /**
11128 * Get the combobox's text input widget.
11129 *
11130 * @return {OO.ui.TextInputWidget} Text input widget
11131 */
11132 OO.ui.ComboBoxInputWidget.prototype.getInput = function () {
11133 return this;
11134 };
11135
11136 /**
11137 * Handle input change events.
11138 *
11139 * @private
11140 * @param {string} value New value
11141 */
11142 OO.ui.ComboBoxInputWidget.prototype.onInputChange = function ( value ) {
11143 var match = this.menu.findItemFromData( value );
11144
11145 this.menu.selectItem( match );
11146 if ( this.menu.findHighlightedItem() ) {
11147 this.menu.highlightItem( match );
11148 }
11149
11150 if ( !this.isDisabled() ) {
11151 this.menu.toggle( true );
11152 }
11153 };
11154
11155 /**
11156 * Handle input enter events.
11157 *
11158 * @private
11159 */
11160 OO.ui.ComboBoxInputWidget.prototype.onInputEnter = function () {
11161 if ( !this.isDisabled() ) {
11162 this.menu.toggle( false );
11163 }
11164 };
11165
11166 /**
11167 * Handle button click events.
11168 *
11169 * @private
11170 */
11171 OO.ui.ComboBoxInputWidget.prototype.onDropdownButtonClick = function () {
11172 this.menu.toggle();
11173 this.focus();
11174 };
11175
11176 /**
11177 * Handle menu choose events.
11178 *
11179 * @private
11180 * @param {OO.ui.OptionWidget} item Chosen item
11181 */
11182 OO.ui.ComboBoxInputWidget.prototype.onMenuChoose = function ( item ) {
11183 this.setValue( item.getData() );
11184 };
11185
11186 /**
11187 * Handle menu item change events.
11188 *
11189 * @private
11190 */
11191 OO.ui.ComboBoxInputWidget.prototype.onMenuItemsChange = function () {
11192 var match = this.menu.findItemFromData( this.getValue() );
11193 this.menu.selectItem( match );
11194 if ( this.menu.findHighlightedItem() ) {
11195 this.menu.highlightItem( match );
11196 }
11197 this.$element.toggleClass( 'oo-ui-comboBoxInputWidget-empty', this.menu.isEmpty() );
11198 };
11199
11200 /**
11201 * Handle menu toggle events.
11202 *
11203 * @private
11204 * @param {boolean} isVisible Open state of the menu
11205 */
11206 OO.ui.ComboBoxInputWidget.prototype.onMenuToggle = function ( isVisible ) {
11207 this.$element.toggleClass( 'oo-ui-comboBoxInputWidget-open', isVisible );
11208 };
11209
11210 /**
11211 * @inheritdoc
11212 */
11213 OO.ui.ComboBoxInputWidget.prototype.setDisabled = function ( disabled ) {
11214 // Parent method
11215 OO.ui.ComboBoxInputWidget.parent.prototype.setDisabled.call( this, disabled );
11216
11217 if ( this.dropdownButton ) {
11218 this.dropdownButton.setDisabled( this.isDisabled() );
11219 }
11220 if ( this.menu ) {
11221 this.menu.setDisabled( this.isDisabled() );
11222 }
11223
11224 return this;
11225 };
11226
11227 /**
11228 * Set the options available for this input.
11229 *
11230 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
11231 * @chainable
11232 */
11233 OO.ui.ComboBoxInputWidget.prototype.setOptions = function ( options ) {
11234 this.getMenu()
11235 .clearItems()
11236 .addItems( options.map( function ( opt ) {
11237 return new OO.ui.MenuOptionWidget( {
11238 data: opt.data,
11239 label: opt.label !== undefined ? opt.label : opt.data
11240 } );
11241 } ) );
11242
11243 return this;
11244 };
11245
11246 /**
11247 * FieldLayouts are used with OO.ui.FieldsetLayout. Each FieldLayout requires a field-widget,
11248 * which is a widget that is specified by reference before any optional configuration settings.
11249 *
11250 * Field layouts can be configured with help text and/or labels. Labels are aligned in one of four ways:
11251 *
11252 * - **left**: The label is placed before the field-widget and aligned with the left margin.
11253 * A left-alignment is used for forms with many fields.
11254 * - **right**: The label is placed before the field-widget and aligned to the right margin.
11255 * A right-alignment is used for long but familiar forms which users tab through,
11256 * verifying the current field with a quick glance at the label.
11257 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
11258 * that users fill out from top to bottom.
11259 * - **inline**: The label is placed after the field-widget and aligned to the left.
11260 * An inline-alignment is best used with checkboxes or radio buttons.
11261 *
11262 * Help text is accessed via a help icon that appears in the upper right corner of the rendered field layout.
11263 * Please see the [OOUI documentation on MediaWiki] [1] for examples and more information.
11264 *
11265 * [1]: https://www.mediawiki.org/wiki/OOUI/Layouts/Fields_and_Fieldsets
11266 *
11267 * @class
11268 * @extends OO.ui.Layout
11269 * @mixins OO.ui.mixin.LabelElement
11270 * @mixins OO.ui.mixin.TitledElement
11271 *
11272 * @constructor
11273 * @param {OO.ui.Widget} fieldWidget Field widget
11274 * @param {Object} [config] Configuration options
11275 * @cfg {string} [align='left'] Alignment of the label: 'left', 'right', 'top' or 'inline'
11276 * @cfg {Array} [errors] Error messages about the widget, which will be displayed below the widget.
11277 * The array may contain strings or OO.ui.HtmlSnippet instances.
11278 * @cfg {Array} [notices] Notices about the widget, which will be displayed below the widget.
11279 * The array may contain strings or OO.ui.HtmlSnippet instances.
11280 * @cfg {string|OO.ui.HtmlSnippet} [help] Help text. When help text is specified, a "help" icon will appear
11281 * in the upper-right corner of the rendered field; clicking it will display the text in a popup.
11282 * For important messages, you are advised to use `notices`, as they are always shown.
11283 * @cfg {jQuery} [$overlay] Passed to OO.ui.PopupButtonWidget for help popup, if `help` is given.
11284 * See <https://www.mediawiki.org/wiki/OOUI/Concepts#Overlays>.
11285 *
11286 * @throws {Error} An error is thrown if no widget is specified
11287 */
11288 OO.ui.FieldLayout = function OoUiFieldLayout( fieldWidget, config ) {
11289 // Allow passing positional parameters inside the config object
11290 if ( OO.isPlainObject( fieldWidget ) && config === undefined ) {
11291 config = fieldWidget;
11292 fieldWidget = config.fieldWidget;
11293 }
11294
11295 // Make sure we have required constructor arguments
11296 if ( fieldWidget === undefined ) {
11297 throw new Error( 'Widget not found' );
11298 }
11299
11300 // Configuration initialization
11301 config = $.extend( { align: 'left' }, config );
11302
11303 // Parent constructor
11304 OO.ui.FieldLayout.parent.call( this, config );
11305
11306 // Mixin constructors
11307 OO.ui.mixin.LabelElement.call( this, $.extend( {}, config, {
11308 $label: $( '<label>' )
11309 } ) );
11310 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$label } ) );
11311
11312 // Properties
11313 this.fieldWidget = fieldWidget;
11314 this.errors = [];
11315 this.notices = [];
11316 this.$field = this.isFieldInline() ? $( '<span>' ) : $( '<div>' );
11317 this.$messages = $( '<ul>' );
11318 this.$header = $( '<span>' );
11319 this.$body = $( '<div>' );
11320 this.align = null;
11321 if ( config.help ) {
11322 this.popupButtonWidget = new OO.ui.PopupButtonWidget( {
11323 $overlay: config.$overlay,
11324 popup: {
11325 padded: true
11326 },
11327 classes: [ 'oo-ui-fieldLayout-help' ],
11328 framed: false,
11329 icon: 'info',
11330 label: OO.ui.msg( 'ooui-field-help' )
11331 } );
11332 if ( config.help instanceof OO.ui.HtmlSnippet ) {
11333 this.popupButtonWidget.getPopup().$body.html( config.help.toString() );
11334 } else {
11335 this.popupButtonWidget.getPopup().$body.text( config.help );
11336 }
11337 this.$help = this.popupButtonWidget.$element;
11338 } else {
11339 this.$help = $( [] );
11340 }
11341
11342 // Events
11343 this.fieldWidget.connect( this, { disable: 'onFieldDisable' } );
11344
11345 // Initialization
11346 if ( config.help ) {
11347 // Set the 'aria-describedby' attribute on the fieldWidget
11348 // Preference given to an input or a button
11349 (
11350 this.fieldWidget.$input ||
11351 this.fieldWidget.$button ||
11352 this.fieldWidget.$element
11353 ).attr(
11354 'aria-describedby',
11355 this.popupButtonWidget.getPopup().getBodyId()
11356 );
11357 }
11358 if ( this.fieldWidget.getInputId() ) {
11359 this.$label.attr( 'for', this.fieldWidget.getInputId() );
11360 } else {
11361 this.$label.on( 'click', function () {
11362 this.fieldWidget.simulateLabelClick();
11363 }.bind( this ) );
11364 }
11365 this.$element
11366 .addClass( 'oo-ui-fieldLayout' )
11367 .toggleClass( 'oo-ui-fieldLayout-disabled', this.fieldWidget.isDisabled() )
11368 .append( this.$body );
11369 this.$body.addClass( 'oo-ui-fieldLayout-body' );
11370 this.$header.addClass( 'oo-ui-fieldLayout-header' );
11371 this.$messages.addClass( 'oo-ui-fieldLayout-messages' );
11372 this.$field
11373 .addClass( 'oo-ui-fieldLayout-field' )
11374 .append( this.fieldWidget.$element );
11375
11376 this.setErrors( config.errors || [] );
11377 this.setNotices( config.notices || [] );
11378 this.setAlignment( config.align );
11379 // Call this again to take into account the widget's accessKey
11380 this.updateTitle();
11381 };
11382
11383 /* Setup */
11384
11385 OO.inheritClass( OO.ui.FieldLayout, OO.ui.Layout );
11386 OO.mixinClass( OO.ui.FieldLayout, OO.ui.mixin.LabelElement );
11387 OO.mixinClass( OO.ui.FieldLayout, OO.ui.mixin.TitledElement );
11388
11389 /* Methods */
11390
11391 /**
11392 * Handle field disable events.
11393 *
11394 * @private
11395 * @param {boolean} value Field is disabled
11396 */
11397 OO.ui.FieldLayout.prototype.onFieldDisable = function ( value ) {
11398 this.$element.toggleClass( 'oo-ui-fieldLayout-disabled', value );
11399 };
11400
11401 /**
11402 * Get the widget contained by the field.
11403 *
11404 * @return {OO.ui.Widget} Field widget
11405 */
11406 OO.ui.FieldLayout.prototype.getField = function () {
11407 return this.fieldWidget;
11408 };
11409
11410 /**
11411 * Return `true` if the given field widget can be used with `'inline'` alignment (see
11412 * #setAlignment). Return `false` if it can't or if this can't be determined.
11413 *
11414 * @return {boolean}
11415 */
11416 OO.ui.FieldLayout.prototype.isFieldInline = function () {
11417 // This is very simplistic, but should be good enough.
11418 return this.getField().$element.prop( 'tagName' ).toLowerCase() === 'span';
11419 };
11420
11421 /**
11422 * @protected
11423 * @param {string} kind 'error' or 'notice'
11424 * @param {string|OO.ui.HtmlSnippet} text
11425 * @return {jQuery}
11426 */
11427 OO.ui.FieldLayout.prototype.makeMessage = function ( kind, text ) {
11428 var $listItem, $icon, message;
11429 $listItem = $( '<li>' );
11430 if ( kind === 'error' ) {
11431 $icon = new OO.ui.IconWidget( { icon: 'alert', flags: [ 'warning' ] } ).$element;
11432 $listItem.attr( 'role', 'alert' );
11433 } else if ( kind === 'notice' ) {
11434 $icon = new OO.ui.IconWidget( { icon: 'notice' } ).$element;
11435 } else {
11436 $icon = '';
11437 }
11438 message = new OO.ui.LabelWidget( { label: text } );
11439 $listItem
11440 .append( $icon, message.$element )
11441 .addClass( 'oo-ui-fieldLayout-messages-' + kind );
11442 return $listItem;
11443 };
11444
11445 /**
11446 * Set the field alignment mode.
11447 *
11448 * @private
11449 * @param {string} value Alignment mode, either 'left', 'right', 'top' or 'inline'
11450 * @chainable
11451 */
11452 OO.ui.FieldLayout.prototype.setAlignment = function ( value ) {
11453 if ( value !== this.align ) {
11454 // Default to 'left'
11455 if ( [ 'left', 'right', 'top', 'inline' ].indexOf( value ) === -1 ) {
11456 value = 'left';
11457 }
11458 // Validate
11459 if ( value === 'inline' && !this.isFieldInline() ) {
11460 value = 'top';
11461 }
11462 // Reorder elements
11463 if ( value === 'top' ) {
11464 this.$header.append( this.$help, this.$label );
11465 this.$body.append( this.$header, this.$field );
11466 } else if ( value === 'inline' ) {
11467 this.$header.append( this.$help, this.$label );
11468 this.$body.append( this.$field, this.$header );
11469 } else {
11470 this.$header.append( this.$label );
11471 this.$body.append( this.$header, this.$help, this.$field );
11472 }
11473 // Set classes. The following classes can be used here:
11474 // * oo-ui-fieldLayout-align-left
11475 // * oo-ui-fieldLayout-align-right
11476 // * oo-ui-fieldLayout-align-top
11477 // * oo-ui-fieldLayout-align-inline
11478 if ( this.align ) {
11479 this.$element.removeClass( 'oo-ui-fieldLayout-align-' + this.align );
11480 }
11481 this.$element.addClass( 'oo-ui-fieldLayout-align-' + value );
11482 this.align = value;
11483 }
11484
11485 return this;
11486 };
11487
11488 /**
11489 * Set the list of error messages.
11490 *
11491 * @param {Array} errors Error messages about the widget, which will be displayed below the widget.
11492 * The array may contain strings or OO.ui.HtmlSnippet instances.
11493 * @chainable
11494 */
11495 OO.ui.FieldLayout.prototype.setErrors = function ( errors ) {
11496 this.errors = errors.slice();
11497 this.updateMessages();
11498 return this;
11499 };
11500
11501 /**
11502 * Set the list of notice messages.
11503 *
11504 * @param {Array} notices Notices about the widget, which will be displayed below the widget.
11505 * The array may contain strings or OO.ui.HtmlSnippet instances.
11506 * @chainable
11507 */
11508 OO.ui.FieldLayout.prototype.setNotices = function ( notices ) {
11509 this.notices = notices.slice();
11510 this.updateMessages();
11511 return this;
11512 };
11513
11514 /**
11515 * Update the rendering of error and notice messages.
11516 *
11517 * @private
11518 */
11519 OO.ui.FieldLayout.prototype.updateMessages = function () {
11520 var i;
11521 this.$messages.empty();
11522
11523 if ( this.errors.length || this.notices.length ) {
11524 this.$body.after( this.$messages );
11525 } else {
11526 this.$messages.remove();
11527 return;
11528 }
11529
11530 for ( i = 0; i < this.notices.length; i++ ) {
11531 this.$messages.append( this.makeMessage( 'notice', this.notices[ i ] ) );
11532 }
11533 for ( i = 0; i < this.errors.length; i++ ) {
11534 this.$messages.append( this.makeMessage( 'error', this.errors[ i ] ) );
11535 }
11536 };
11537
11538 /**
11539 * Include information about the widget's accessKey in our title. TitledElement calls this method.
11540 * (This is a bit of a hack.)
11541 *
11542 * @protected
11543 * @param {string} title Tooltip label for 'title' attribute
11544 * @return {string}
11545 */
11546 OO.ui.FieldLayout.prototype.formatTitleWithAccessKey = function ( title ) {
11547 if ( this.fieldWidget && this.fieldWidget.formatTitleWithAccessKey ) {
11548 return this.fieldWidget.formatTitleWithAccessKey( title );
11549 }
11550 return title;
11551 };
11552
11553 /**
11554 * ActionFieldLayouts are used with OO.ui.FieldsetLayout. The layout consists of a field-widget, a button,
11555 * and an optional label and/or help text. The field-widget (e.g., a {@link OO.ui.TextInputWidget TextInputWidget}),
11556 * is required and is specified before any optional configuration settings.
11557 *
11558 * Labels can be aligned in one of four ways:
11559 *
11560 * - **left**: The label is placed before the field-widget and aligned with the left margin.
11561 * A left-alignment is used for forms with many fields.
11562 * - **right**: The label is placed before the field-widget and aligned to the right margin.
11563 * A right-alignment is used for long but familiar forms which users tab through,
11564 * verifying the current field with a quick glance at the label.
11565 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
11566 * that users fill out from top to bottom.
11567 * - **inline**: The label is placed after the field-widget and aligned to the left.
11568 * An inline-alignment is best used with checkboxes or radio buttons.
11569 *
11570 * Help text is accessed via a help icon that appears in the upper right corner of the rendered field layout when help
11571 * text is specified.
11572 *
11573 * @example
11574 * // Example of an ActionFieldLayout
11575 * var actionFieldLayout = new OO.ui.ActionFieldLayout(
11576 * new OO.ui.TextInputWidget( {
11577 * placeholder: 'Field widget'
11578 * } ),
11579 * new OO.ui.ButtonWidget( {
11580 * label: 'Button'
11581 * } ),
11582 * {
11583 * label: 'An ActionFieldLayout. This label is aligned top',
11584 * align: 'top',
11585 * help: 'This is help text'
11586 * }
11587 * );
11588 *
11589 * $( 'body' ).append( actionFieldLayout.$element );
11590 *
11591 * @class
11592 * @extends OO.ui.FieldLayout
11593 *
11594 * @constructor
11595 * @param {OO.ui.Widget} fieldWidget Field widget
11596 * @param {OO.ui.ButtonWidget} buttonWidget Button widget
11597 * @param {Object} config
11598 */
11599 OO.ui.ActionFieldLayout = function OoUiActionFieldLayout( fieldWidget, buttonWidget, config ) {
11600 // Allow passing positional parameters inside the config object
11601 if ( OO.isPlainObject( fieldWidget ) && config === undefined ) {
11602 config = fieldWidget;
11603 fieldWidget = config.fieldWidget;
11604 buttonWidget = config.buttonWidget;
11605 }
11606
11607 // Parent constructor
11608 OO.ui.ActionFieldLayout.parent.call( this, fieldWidget, config );
11609
11610 // Properties
11611 this.buttonWidget = buttonWidget;
11612 this.$button = $( '<span>' );
11613 this.$input = this.isFieldInline() ? $( '<span>' ) : $( '<div>' );
11614
11615 // Initialization
11616 this.$element
11617 .addClass( 'oo-ui-actionFieldLayout' );
11618 this.$button
11619 .addClass( 'oo-ui-actionFieldLayout-button' )
11620 .append( this.buttonWidget.$element );
11621 this.$input
11622 .addClass( 'oo-ui-actionFieldLayout-input' )
11623 .append( this.fieldWidget.$element );
11624 this.$field
11625 .append( this.$input, this.$button );
11626 };
11627
11628 /* Setup */
11629
11630 OO.inheritClass( OO.ui.ActionFieldLayout, OO.ui.FieldLayout );
11631
11632 /**
11633 * FieldsetLayouts are composed of one or more {@link OO.ui.FieldLayout FieldLayouts},
11634 * which each contain an individual widget and, optionally, a label. Each Fieldset can be
11635 * configured with a label as well. For more information and examples,
11636 * please see the [OOUI documentation on MediaWiki][1].
11637 *
11638 * @example
11639 * // Example of a fieldset layout
11640 * var input1 = new OO.ui.TextInputWidget( {
11641 * placeholder: 'A text input field'
11642 * } );
11643 *
11644 * var input2 = new OO.ui.TextInputWidget( {
11645 * placeholder: 'A text input field'
11646 * } );
11647 *
11648 * var fieldset = new OO.ui.FieldsetLayout( {
11649 * label: 'Example of a fieldset layout'
11650 * } );
11651 *
11652 * fieldset.addItems( [
11653 * new OO.ui.FieldLayout( input1, {
11654 * label: 'Field One'
11655 * } ),
11656 * new OO.ui.FieldLayout( input2, {
11657 * label: 'Field Two'
11658 * } )
11659 * ] );
11660 * $( 'body' ).append( fieldset.$element );
11661 *
11662 * [1]: https://www.mediawiki.org/wiki/OOUI/Layouts/Fields_and_Fieldsets
11663 *
11664 * @class
11665 * @extends OO.ui.Layout
11666 * @mixins OO.ui.mixin.IconElement
11667 * @mixins OO.ui.mixin.LabelElement
11668 * @mixins OO.ui.mixin.GroupElement
11669 *
11670 * @constructor
11671 * @param {Object} [config] Configuration options
11672 * @cfg {OO.ui.FieldLayout[]} [items] An array of fields to add to the fieldset. See OO.ui.FieldLayout for more information about fields.
11673 * @cfg {string|OO.ui.HtmlSnippet} [help] Help text. When help text is specified, a "help" icon will appear
11674 * in the upper-right corner of the rendered field; clicking it will display the text in a popup.
11675 * For important messages, you are advised to use `notices`, as they are always shown.
11676 * @cfg {jQuery} [$overlay] Passed to OO.ui.PopupButtonWidget for help popup, if `help` is given.
11677 * See <https://www.mediawiki.org/wiki/OOUI/Concepts#Overlays>.
11678 */
11679 OO.ui.FieldsetLayout = function OoUiFieldsetLayout( config ) {
11680 // Configuration initialization
11681 config = config || {};
11682
11683 // Parent constructor
11684 OO.ui.FieldsetLayout.parent.call( this, config );
11685
11686 // Mixin constructors
11687 OO.ui.mixin.IconElement.call( this, config );
11688 OO.ui.mixin.LabelElement.call( this, config );
11689 OO.ui.mixin.GroupElement.call( this, config );
11690
11691 // Properties
11692 this.$header = $( '<legend>' );
11693 if ( config.help ) {
11694 this.popupButtonWidget = new OO.ui.PopupButtonWidget( {
11695 $overlay: config.$overlay,
11696 popup: {
11697 padded: true
11698 },
11699 classes: [ 'oo-ui-fieldsetLayout-help' ],
11700 framed: false,
11701 icon: 'info',
11702 label: OO.ui.msg( 'ooui-field-help' )
11703 } );
11704 if ( config.help instanceof OO.ui.HtmlSnippet ) {
11705 this.popupButtonWidget.getPopup().$body.html( config.help.toString() );
11706 } else {
11707 this.popupButtonWidget.getPopup().$body.text( config.help );
11708 }
11709 this.$help = this.popupButtonWidget.$element;
11710 } else {
11711 this.$help = $( [] );
11712 }
11713
11714 // Initialization
11715 this.$header
11716 .addClass( 'oo-ui-fieldsetLayout-header' )
11717 .append( this.$icon, this.$label, this.$help );
11718 this.$group.addClass( 'oo-ui-fieldsetLayout-group' );
11719 this.$element
11720 .addClass( 'oo-ui-fieldsetLayout' )
11721 .prepend( this.$header, this.$group );
11722 if ( Array.isArray( config.items ) ) {
11723 this.addItems( config.items );
11724 }
11725 };
11726
11727 /* Setup */
11728
11729 OO.inheritClass( OO.ui.FieldsetLayout, OO.ui.Layout );
11730 OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.mixin.IconElement );
11731 OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.mixin.LabelElement );
11732 OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.mixin.GroupElement );
11733
11734 /* Static Properties */
11735
11736 /**
11737 * @static
11738 * @inheritdoc
11739 */
11740 OO.ui.FieldsetLayout.static.tagName = 'fieldset';
11741
11742 /**
11743 * FormLayouts are used to wrap {@link OO.ui.FieldsetLayout FieldsetLayouts} when you intend to use browser-based
11744 * form submission for the fields instead of handling them in JavaScript. Form layouts can be configured with an
11745 * HTML form action, an encoding type, and a method using the #action, #enctype, and #method configs, respectively.
11746 * See the [OOUI documentation on MediaWiki] [1] for more information and examples.
11747 *
11748 * Only widgets from the {@link OO.ui.InputWidget InputWidget} family support form submission. It
11749 * includes standard form elements like {@link OO.ui.CheckboxInputWidget checkboxes}, {@link
11750 * OO.ui.RadioInputWidget radio buttons} and {@link OO.ui.TextInputWidget text fields}, as well as
11751 * some fancier controls. Some controls have both regular and InputWidget variants, for example
11752 * OO.ui.DropdownWidget and OO.ui.DropdownInputWidget – only the latter support form submission and
11753 * often have simplified APIs to match the capabilities of HTML forms.
11754 * See the [OOUI documentation on MediaWiki] [2] for more information about InputWidgets.
11755 *
11756 * [1]: https://www.mediawiki.org/wiki/OOUI/Layouts/Forms
11757 * [2]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
11758 *
11759 * @example
11760 * // Example of a form layout that wraps a fieldset layout
11761 * var input1 = new OO.ui.TextInputWidget( {
11762 * placeholder: 'Username'
11763 * } );
11764 * var input2 = new OO.ui.TextInputWidget( {
11765 * placeholder: 'Password',
11766 * type: 'password'
11767 * } );
11768 * var submit = new OO.ui.ButtonInputWidget( {
11769 * label: 'Submit'
11770 * } );
11771 *
11772 * var fieldset = new OO.ui.FieldsetLayout( {
11773 * label: 'A form layout'
11774 * } );
11775 * fieldset.addItems( [
11776 * new OO.ui.FieldLayout( input1, {
11777 * label: 'Username',
11778 * align: 'top'
11779 * } ),
11780 * new OO.ui.FieldLayout( input2, {
11781 * label: 'Password',
11782 * align: 'top'
11783 * } ),
11784 * new OO.ui.FieldLayout( submit )
11785 * ] );
11786 * var form = new OO.ui.FormLayout( {
11787 * items: [ fieldset ],
11788 * action: '/api/formhandler',
11789 * method: 'get'
11790 * } )
11791 * $( 'body' ).append( form.$element );
11792 *
11793 * @class
11794 * @extends OO.ui.Layout
11795 * @mixins OO.ui.mixin.GroupElement
11796 *
11797 * @constructor
11798 * @param {Object} [config] Configuration options
11799 * @cfg {string} [method] HTML form `method` attribute
11800 * @cfg {string} [action] HTML form `action` attribute
11801 * @cfg {string} [enctype] HTML form `enctype` attribute
11802 * @cfg {OO.ui.FieldsetLayout[]} [items] Fieldset layouts to add to the form layout.
11803 */
11804 OO.ui.FormLayout = function OoUiFormLayout( config ) {
11805 var action;
11806
11807 // Configuration initialization
11808 config = config || {};
11809
11810 // Parent constructor
11811 OO.ui.FormLayout.parent.call( this, config );
11812
11813 // Mixin constructors
11814 OO.ui.mixin.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) );
11815
11816 // Events
11817 this.$element.on( 'submit', this.onFormSubmit.bind( this ) );
11818
11819 // Make sure the action is safe
11820 action = config.action;
11821 if ( action !== undefined && !OO.ui.isSafeUrl( action ) ) {
11822 action = './' + action;
11823 }
11824
11825 // Initialization
11826 this.$element
11827 .addClass( 'oo-ui-formLayout' )
11828 .attr( {
11829 method: config.method,
11830 action: action,
11831 enctype: config.enctype
11832 } );
11833 if ( Array.isArray( config.items ) ) {
11834 this.addItems( config.items );
11835 }
11836 };
11837
11838 /* Setup */
11839
11840 OO.inheritClass( OO.ui.FormLayout, OO.ui.Layout );
11841 OO.mixinClass( OO.ui.FormLayout, OO.ui.mixin.GroupElement );
11842
11843 /* Events */
11844
11845 /**
11846 * A 'submit' event is emitted when the form is submitted.
11847 *
11848 * @event submit
11849 */
11850
11851 /* Static Properties */
11852
11853 /**
11854 * @static
11855 * @inheritdoc
11856 */
11857 OO.ui.FormLayout.static.tagName = 'form';
11858
11859 /* Methods */
11860
11861 /**
11862 * Handle form submit events.
11863 *
11864 * @private
11865 * @param {jQuery.Event} e Submit event
11866 * @fires submit
11867 */
11868 OO.ui.FormLayout.prototype.onFormSubmit = function () {
11869 if ( this.emit( 'submit' ) ) {
11870 return false;
11871 }
11872 };
11873
11874 /**
11875 * PanelLayouts expand to cover the entire area of their parent. They can be configured with scrolling, padding,
11876 * and a frame, and are often used together with {@link OO.ui.StackLayout StackLayouts}.
11877 *
11878 * @example
11879 * // Example of a panel layout
11880 * var panel = new OO.ui.PanelLayout( {
11881 * expanded: false,
11882 * framed: true,
11883 * padded: true,
11884 * $content: $( '<p>A panel layout with padding and a frame.</p>' )
11885 * } );
11886 * $( 'body' ).append( panel.$element );
11887 *
11888 * @class
11889 * @extends OO.ui.Layout
11890 *
11891 * @constructor
11892 * @param {Object} [config] Configuration options
11893 * @cfg {boolean} [scrollable=false] Allow vertical scrolling
11894 * @cfg {boolean} [padded=false] Add padding between the content and the edges of the panel.
11895 * @cfg {boolean} [expanded=true] Expand the panel to fill the entire parent element.
11896 * @cfg {boolean} [framed=false] Render the panel with a frame to visually separate it from outside content.
11897 */
11898 OO.ui.PanelLayout = function OoUiPanelLayout( config ) {
11899 // Configuration initialization
11900 config = $.extend( {
11901 scrollable: false,
11902 padded: false,
11903 expanded: true,
11904 framed: false
11905 }, config );
11906
11907 // Parent constructor
11908 OO.ui.PanelLayout.parent.call( this, config );
11909
11910 // Initialization
11911 this.$element.addClass( 'oo-ui-panelLayout' );
11912 if ( config.scrollable ) {
11913 this.$element.addClass( 'oo-ui-panelLayout-scrollable' );
11914 }
11915 if ( config.padded ) {
11916 this.$element.addClass( 'oo-ui-panelLayout-padded' );
11917 }
11918 if ( config.expanded ) {
11919 this.$element.addClass( 'oo-ui-panelLayout-expanded' );
11920 }
11921 if ( config.framed ) {
11922 this.$element.addClass( 'oo-ui-panelLayout-framed' );
11923 }
11924 };
11925
11926 /* Setup */
11927
11928 OO.inheritClass( OO.ui.PanelLayout, OO.ui.Layout );
11929
11930 /* Methods */
11931
11932 /**
11933 * Focus the panel layout
11934 *
11935 * The default implementation just focuses the first focusable element in the panel
11936 */
11937 OO.ui.PanelLayout.prototype.focus = function () {
11938 OO.ui.findFocusable( this.$element ).focus();
11939 };
11940
11941 /**
11942 * HorizontalLayout arranges its contents in a single line (using `display: inline-block` for its
11943 * items), with small margins between them. Convenient when you need to put a number of block-level
11944 * widgets on a single line next to each other.
11945 *
11946 * Note that inline elements, such as OO.ui.ButtonWidgets, do not need this wrapper.
11947 *
11948 * @example
11949 * // HorizontalLayout with a text input and a label
11950 * var layout = new OO.ui.HorizontalLayout( {
11951 * items: [
11952 * new OO.ui.LabelWidget( { label: 'Label' } ),
11953 * new OO.ui.TextInputWidget( { value: 'Text' } )
11954 * ]
11955 * } );
11956 * $( 'body' ).append( layout.$element );
11957 *
11958 * @class
11959 * @extends OO.ui.Layout
11960 * @mixins OO.ui.mixin.GroupElement
11961 *
11962 * @constructor
11963 * @param {Object} [config] Configuration options
11964 * @cfg {OO.ui.Widget[]|OO.ui.Layout[]} [items] Widgets or other layouts to add to the layout.
11965 */
11966 OO.ui.HorizontalLayout = function OoUiHorizontalLayout( config ) {
11967 // Configuration initialization
11968 config = config || {};
11969
11970 // Parent constructor
11971 OO.ui.HorizontalLayout.parent.call( this, config );
11972
11973 // Mixin constructors
11974 OO.ui.mixin.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) );
11975
11976 // Initialization
11977 this.$element.addClass( 'oo-ui-horizontalLayout' );
11978 if ( Array.isArray( config.items ) ) {
11979 this.addItems( config.items );
11980 }
11981 };
11982
11983 /* Setup */
11984
11985 OO.inheritClass( OO.ui.HorizontalLayout, OO.ui.Layout );
11986 OO.mixinClass( OO.ui.HorizontalLayout, OO.ui.mixin.GroupElement );
11987
11988 /**
11989 * NumberInputWidgets combine a {@link OO.ui.TextInputWidget text input} (where a value
11990 * can be entered manually) and two {@link OO.ui.ButtonWidget button widgets}
11991 * (to adjust the value in increments) to allow the user to enter a number.
11992 *
11993 * @example
11994 * // Example: A NumberInputWidget.
11995 * var numberInput = new OO.ui.NumberInputWidget( {
11996 * label: 'NumberInputWidget',
11997 * input: { value: 5 },
11998 * min: 1,
11999 * max: 10
12000 * } );
12001 * $( 'body' ).append( numberInput.$element );
12002 *
12003 * @class
12004 * @extends OO.ui.TextInputWidget
12005 *
12006 * @constructor
12007 * @param {Object} [config] Configuration options
12008 * @cfg {Object} [minusButton] Configuration options to pass to the {@link OO.ui.ButtonWidget decrementing button widget}.
12009 * @cfg {Object} [plusButton] Configuration options to pass to the {@link OO.ui.ButtonWidget incrementing button widget}.
12010 * @cfg {boolean} [allowInteger=false] Whether the field accepts only integer values.
12011 * @cfg {number} [min=-Infinity] Minimum allowed value
12012 * @cfg {number} [max=Infinity] Maximum allowed value
12013 * @cfg {number} [step=1] Delta when using the buttons or up/down arrow keys
12014 * @cfg {number|null} [pageStep] Delta when using the page-up/page-down keys. Defaults to 10 times #step.
12015 * @cfg {boolean} [showButtons=true] Whether to show the plus and minus buttons.
12016 */
12017 OO.ui.NumberInputWidget = function OoUiNumberInputWidget( config ) {
12018 var $field = $( '<div>' )
12019 .addClass( 'oo-ui-numberInputWidget-field' );
12020
12021 // Configuration initialization
12022 config = $.extend( {
12023 allowInteger: false,
12024 min: -Infinity,
12025 max: Infinity,
12026 step: 1,
12027 pageStep: null,
12028 showButtons: true
12029 }, config );
12030
12031 // For backward compatibility
12032 $.extend( config, config.input );
12033 this.input = this;
12034
12035 // Parent constructor
12036 OO.ui.NumberInputWidget.parent.call( this, $.extend( config, {
12037 type: 'number'
12038 } ) );
12039
12040 if ( config.showButtons ) {
12041 this.minusButton = new OO.ui.ButtonWidget( $.extend(
12042 {
12043 disabled: this.isDisabled(),
12044 tabIndex: -1,
12045 classes: [ 'oo-ui-numberInputWidget-minusButton' ],
12046 icon: 'subtract'
12047 },
12048 config.minusButton
12049 ) );
12050 this.minusButton.$element.attr( 'aria-hidden', 'true' );
12051 this.plusButton = new OO.ui.ButtonWidget( $.extend(
12052 {
12053 disabled: this.isDisabled(),
12054 tabIndex: -1,
12055 classes: [ 'oo-ui-numberInputWidget-plusButton' ],
12056 icon: 'add'
12057 },
12058 config.plusButton
12059 ) );
12060 this.plusButton.$element.attr( 'aria-hidden', 'true' );
12061 }
12062
12063 // Events
12064 this.$input.on( {
12065 keydown: this.onKeyDown.bind( this ),
12066 'wheel mousewheel DOMMouseScroll': this.onWheel.bind( this )
12067 } );
12068 if ( config.showButtons ) {
12069 this.plusButton.connect( this, {
12070 click: [ 'onButtonClick', +1 ]
12071 } );
12072 this.minusButton.connect( this, {
12073 click: [ 'onButtonClick', -1 ]
12074 } );
12075 }
12076
12077 // Build the field
12078 $field.append( this.$input );
12079 if ( config.showButtons ) {
12080 $field
12081 .prepend( this.minusButton.$element )
12082 .append( this.plusButton.$element );
12083 }
12084
12085 // Initialization
12086 this.setAllowInteger( config.allowInteger || config.isInteger );
12087 this.setRange( config.min, config.max );
12088 this.setStep( config.step, config.pageStep );
12089 // Set the validation method after we set allowInteger and range
12090 // so that it doesn't immediately call setValidityFlag
12091 this.setValidation( this.validateNumber.bind( this ) );
12092
12093 this.$element
12094 .addClass( 'oo-ui-numberInputWidget' )
12095 .toggleClass( 'oo-ui-numberInputWidget-buttoned', config.showButtons )
12096 .append( $field );
12097 };
12098
12099 /* Setup */
12100
12101 OO.inheritClass( OO.ui.NumberInputWidget, OO.ui.TextInputWidget );
12102
12103 /* Methods */
12104
12105 /**
12106 * Set whether only integers are allowed
12107 *
12108 * @param {boolean} flag
12109 */
12110 OO.ui.NumberInputWidget.prototype.setAllowInteger = function ( flag ) {
12111 this.allowInteger = !!flag;
12112 this.setValidityFlag();
12113 };
12114 // Backward compatibility
12115 OO.ui.NumberInputWidget.prototype.setIsInteger = OO.ui.NumberInputWidget.prototype.setAllowInteger;
12116
12117 /**
12118 * Get whether only integers are allowed
12119 *
12120 * @return {boolean} Flag value
12121 */
12122 OO.ui.NumberInputWidget.prototype.getAllowInteger = function () {
12123 return this.allowInteger;
12124 };
12125 // Backward compatibility
12126 OO.ui.NumberInputWidget.prototype.getIsInteger = OO.ui.NumberInputWidget.prototype.getAllowInteger;
12127
12128 /**
12129 * Set the range of allowed values
12130 *
12131 * @param {number} min Minimum allowed value
12132 * @param {number} max Maximum allowed value
12133 */
12134 OO.ui.NumberInputWidget.prototype.setRange = function ( min, max ) {
12135 if ( min > max ) {
12136 throw new Error( 'Minimum (' + min + ') must not be greater than maximum (' + max + ')' );
12137 }
12138 this.min = min;
12139 this.max = max;
12140 this.$input.attr( 'min', this.min );
12141 this.$input.attr( 'max', this.max );
12142 this.setValidityFlag();
12143 };
12144
12145 /**
12146 * Get the current range
12147 *
12148 * @return {number[]} Minimum and maximum values
12149 */
12150 OO.ui.NumberInputWidget.prototype.getRange = function () {
12151 return [ this.min, this.max ];
12152 };
12153
12154 /**
12155 * Set the stepping deltas
12156 *
12157 * @param {number} step Normal step
12158 * @param {number|null} pageStep Page step. If null, 10 * step will be used.
12159 */
12160 OO.ui.NumberInputWidget.prototype.setStep = function ( step, pageStep ) {
12161 if ( step <= 0 ) {
12162 throw new Error( 'Step value must be positive' );
12163 }
12164 if ( pageStep === null ) {
12165 pageStep = step * 10;
12166 } else if ( pageStep <= 0 ) {
12167 throw new Error( 'Page step value must be positive' );
12168 }
12169 this.step = step;
12170 this.pageStep = pageStep;
12171 this.$input.attr( 'step', this.step );
12172 };
12173
12174 /**
12175 * @inheritdoc
12176 */
12177 OO.ui.NumberInputWidget.prototype.setValue = function ( value ) {
12178 if ( value === '' ) {
12179 // Some browsers allow a value in the input even if there isn't one reported by $input.val()
12180 // so here we make sure an 'empty' value is actually displayed as such.
12181 this.$input.val( '' );
12182 }
12183 return OO.ui.NumberInputWidget.parent.prototype.setValue.call( this, value );
12184 };
12185
12186 /**
12187 * Get the current stepping values
12188 *
12189 * @return {number[]} Step and page step
12190 */
12191 OO.ui.NumberInputWidget.prototype.getStep = function () {
12192 return [ this.step, this.pageStep ];
12193 };
12194
12195 /**
12196 * Get the current value of the widget as a number
12197 *
12198 * @return {number} May be NaN, or an invalid number
12199 */
12200 OO.ui.NumberInputWidget.prototype.getNumericValue = function () {
12201 return +this.getValue();
12202 };
12203
12204 /**
12205 * Adjust the value of the widget
12206 *
12207 * @param {number} delta Adjustment amount
12208 */
12209 OO.ui.NumberInputWidget.prototype.adjustValue = function ( delta ) {
12210 var n, v = this.getNumericValue();
12211
12212 delta = +delta;
12213 if ( isNaN( delta ) || !isFinite( delta ) ) {
12214 throw new Error( 'Delta must be a finite number' );
12215 }
12216
12217 if ( isNaN( v ) ) {
12218 n = 0;
12219 } else {
12220 n = v + delta;
12221 n = Math.max( Math.min( n, this.max ), this.min );
12222 if ( this.allowInteger ) {
12223 n = Math.round( n );
12224 }
12225 }
12226
12227 if ( n !== v ) {
12228 this.setValue( n );
12229 }
12230 };
12231 /**
12232 * Validate input
12233 *
12234 * @private
12235 * @param {string} value Field value
12236 * @return {boolean}
12237 */
12238 OO.ui.NumberInputWidget.prototype.validateNumber = function ( value ) {
12239 var n = +value;
12240 if ( value === '' ) {
12241 return !this.isRequired();
12242 }
12243
12244 if ( isNaN( n ) || !isFinite( n ) ) {
12245 return false;
12246 }
12247
12248 if ( this.allowInteger && Math.floor( n ) !== n ) {
12249 return false;
12250 }
12251
12252 if ( n < this.min || n > this.max ) {
12253 return false;
12254 }
12255
12256 return true;
12257 };
12258
12259 /**
12260 * Handle mouse click events.
12261 *
12262 * @private
12263 * @param {number} dir +1 or -1
12264 */
12265 OO.ui.NumberInputWidget.prototype.onButtonClick = function ( dir ) {
12266 this.adjustValue( dir * this.step );
12267 };
12268
12269 /**
12270 * Handle mouse wheel events.
12271 *
12272 * @private
12273 * @param {jQuery.Event} event
12274 */
12275 OO.ui.NumberInputWidget.prototype.onWheel = function ( event ) {
12276 var delta = 0;
12277
12278 if ( !this.isDisabled() && this.$input.is( ':focus' ) ) {
12279 // Standard 'wheel' event
12280 if ( event.originalEvent.deltaMode !== undefined ) {
12281 this.sawWheelEvent = true;
12282 }
12283 if ( event.originalEvent.deltaY ) {
12284 delta = -event.originalEvent.deltaY;
12285 } else if ( event.originalEvent.deltaX ) {
12286 delta = event.originalEvent.deltaX;
12287 }
12288
12289 // Non-standard events
12290 if ( !this.sawWheelEvent ) {
12291 if ( event.originalEvent.wheelDeltaX ) {
12292 delta = -event.originalEvent.wheelDeltaX;
12293 } else if ( event.originalEvent.wheelDeltaY ) {
12294 delta = event.originalEvent.wheelDeltaY;
12295 } else if ( event.originalEvent.wheelDelta ) {
12296 delta = event.originalEvent.wheelDelta;
12297 } else if ( event.originalEvent.detail ) {
12298 delta = -event.originalEvent.detail;
12299 }
12300 }
12301
12302 if ( delta ) {
12303 delta = delta < 0 ? -1 : 1;
12304 this.adjustValue( delta * this.step );
12305 }
12306
12307 return false;
12308 }
12309 };
12310
12311 /**
12312 * Handle key down events.
12313 *
12314 * @private
12315 * @param {jQuery.Event} e Key down event
12316 */
12317 OO.ui.NumberInputWidget.prototype.onKeyDown = function ( e ) {
12318 if ( !this.isDisabled() ) {
12319 switch ( e.which ) {
12320 case OO.ui.Keys.UP:
12321 this.adjustValue( this.step );
12322 return false;
12323 case OO.ui.Keys.DOWN:
12324 this.adjustValue( -this.step );
12325 return false;
12326 case OO.ui.Keys.PAGEUP:
12327 this.adjustValue( this.pageStep );
12328 return false;
12329 case OO.ui.Keys.PAGEDOWN:
12330 this.adjustValue( -this.pageStep );
12331 return false;
12332 }
12333 }
12334 };
12335
12336 /**
12337 * @inheritdoc
12338 */
12339 OO.ui.NumberInputWidget.prototype.setDisabled = function ( disabled ) {
12340 // Parent method
12341 OO.ui.NumberInputWidget.parent.prototype.setDisabled.call( this, disabled );
12342
12343 if ( this.minusButton ) {
12344 this.minusButton.setDisabled( this.isDisabled() );
12345 }
12346 if ( this.plusButton ) {
12347 this.plusButton.setDisabled( this.isDisabled() );
12348 }
12349
12350 return this;
12351 };
12352
12353 }( OO ) );
12354
12355 //# sourceMappingURL=oojs-ui-core.js.map.json