Merge "Improve some timeout docs"
[lhc/web/wiklou.git] / resources / lib / oojs-ui / oojs-ui-core.js
1 /*!
2 * OOjs UI v0.22.5
3 * https://www.mediawiki.org/wiki/OOjs_UI
4 *
5 * Copyright 2011–2017 OOjs UI Team and other contributors.
6 * Released under the MIT license
7 * http://oojs.mit-license.org
8 *
9 * Date: 2017-08-22T21:37:37Z
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 'oojsui-' + 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 * // OOjs UI 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} Use is on a mobile device
537 */
538 OO.ui.isMobile = function () {
539 return false;
540 };
541
542 /*!
543 * Mixin namespace.
544 */
545
546 /**
547 * Namespace for OOjs UI mixins.
548 *
549 * Mixins are named according to the type of object they are intended to
550 * be mixed in to. For example, OO.ui.mixin.GroupElement is intended to be
551 * mixed in to an instance of OO.ui.Element, and OO.ui.mixin.GroupWidget
552 * is intended to be mixed in to an instance of OO.ui.Widget.
553 *
554 * @class
555 * @singleton
556 */
557 OO.ui.mixin = {};
558
559 /**
560 * Each Element represents a rendering in the DOM—a button or an icon, for example, or anything
561 * that is visible to a user. Unlike {@link OO.ui.Widget widgets}, plain elements usually do not have events
562 * connected to them and can't be interacted with.
563 *
564 * @abstract
565 * @class
566 *
567 * @constructor
568 * @param {Object} [config] Configuration options
569 * @cfg {string[]} [classes] The names of the CSS classes to apply to the element. CSS styles are added
570 * to the top level (e.g., the outermost div) of the element. See the [OOjs UI documentation on MediaWiki][2]
571 * for an example.
572 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#cssExample
573 * @cfg {string} [id] The HTML id attribute used in the rendered tag.
574 * @cfg {string} [text] Text to insert
575 * @cfg {Array} [content] An array of content elements to append (after #text).
576 * Strings will be html-escaped; use an OO.ui.HtmlSnippet to append raw HTML.
577 * Instances of OO.ui.Element will have their $element appended.
578 * @cfg {jQuery} [$content] Content elements to append (after #text).
579 * @cfg {jQuery} [$element] Wrapper element. Defaults to a new element with #getTagName.
580 * @cfg {Mixed} [data] Custom data of any type or combination of types (e.g., string, number, array, object).
581 * Data can also be specified with the #setData method.
582 */
583 OO.ui.Element = function OoUiElement( config ) {
584 this.initialConfig = config;
585 // Configuration initialization
586 config = config || {};
587
588 // Properties
589 this.$ = $;
590 this.elementId = null;
591 this.visible = true;
592 this.data = config.data;
593 this.$element = config.$element ||
594 $( document.createElement( this.getTagName() ) );
595 this.elementGroup = null;
596
597 // Initialization
598 if ( Array.isArray( config.classes ) ) {
599 this.$element.addClass( config.classes.join( ' ' ) );
600 }
601 if ( config.id ) {
602 this.setElementId( config.id );
603 }
604 if ( config.text ) {
605 this.$element.text( config.text );
606 }
607 if ( config.content ) {
608 // The `content` property treats plain strings as text; use an
609 // HtmlSnippet to append HTML content. `OO.ui.Element`s get their
610 // appropriate $element appended.
611 this.$element.append( config.content.map( function ( v ) {
612 if ( typeof v === 'string' ) {
613 // Escape string so it is properly represented in HTML.
614 return document.createTextNode( v );
615 } else if ( v instanceof OO.ui.HtmlSnippet ) {
616 // Bypass escaping.
617 return v.toString();
618 } else if ( v instanceof OO.ui.Element ) {
619 return v.$element;
620 }
621 return v;
622 } ) );
623 }
624 if ( config.$content ) {
625 // The `$content` property treats plain strings as HTML.
626 this.$element.append( config.$content );
627 }
628 };
629
630 /* Setup */
631
632 OO.initClass( OO.ui.Element );
633
634 /* Static Properties */
635
636 /**
637 * The name of the HTML tag used by the element.
638 *
639 * The static value may be ignored if the #getTagName method is overridden.
640 *
641 * @static
642 * @inheritable
643 * @property {string}
644 */
645 OO.ui.Element.static.tagName = 'div';
646
647 /* Static Methods */
648
649 /**
650 * Reconstitute a JavaScript object corresponding to a widget created
651 * by the PHP implementation.
652 *
653 * @param {string|HTMLElement|jQuery} idOrNode
654 * A DOM id (if a string) or node for the widget to infuse.
655 * @return {OO.ui.Element}
656 * The `OO.ui.Element` corresponding to this (infusable) document node.
657 * For `Tag` objects emitted on the HTML side (used occasionally for content)
658 * the value returned is a newly-created Element wrapping around the existing
659 * DOM node.
660 */
661 OO.ui.Element.static.infuse = function ( idOrNode ) {
662 var obj = OO.ui.Element.static.unsafeInfuse( idOrNode, false );
663 // Verify that the type matches up.
664 // FIXME: uncomment after T89721 is fixed, see T90929.
665 /*
666 if ( !( obj instanceof this['class'] ) ) {
667 throw new Error( 'Infusion type mismatch!' );
668 }
669 */
670 return obj;
671 };
672
673 /**
674 * Implementation helper for `infuse`; skips the type check and has an
675 * extra property so that only the top-level invocation touches the DOM.
676 *
677 * @private
678 * @param {string|HTMLElement|jQuery} idOrNode
679 * @param {jQuery.Promise|boolean} domPromise A promise that will be resolved
680 * when the top-level widget of this infusion is inserted into DOM,
681 * replacing the original node; or false for top-level invocation.
682 * @return {OO.ui.Element}
683 */
684 OO.ui.Element.static.unsafeInfuse = function ( idOrNode, domPromise ) {
685 // look for a cached result of a previous infusion.
686 var id, $elem, data, cls, parts, parent, obj, top, state, infusedChildren;
687 if ( typeof idOrNode === 'string' ) {
688 id = idOrNode;
689 $elem = $( document.getElementById( id ) );
690 } else {
691 $elem = $( idOrNode );
692 id = $elem.attr( 'id' );
693 }
694 if ( !$elem.length ) {
695 throw new Error( 'Widget not found: ' + id );
696 }
697 if ( $elem[ 0 ].oouiInfused ) {
698 $elem = $elem[ 0 ].oouiInfused;
699 }
700 data = $elem.data( 'ooui-infused' );
701 if ( data ) {
702 // cached!
703 if ( data === true ) {
704 throw new Error( 'Circular dependency! ' + id );
705 }
706 if ( domPromise ) {
707 // pick up dynamic state, like focus, value of form inputs, scroll position, etc.
708 state = data.constructor.static.gatherPreInfuseState( $elem, data );
709 // restore dynamic state after the new element is re-inserted into DOM under infused parent
710 domPromise.done( data.restorePreInfuseState.bind( data, state ) );
711 infusedChildren = $elem.data( 'ooui-infused-children' );
712 if ( infusedChildren && infusedChildren.length ) {
713 infusedChildren.forEach( function ( data ) {
714 var state = data.constructor.static.gatherPreInfuseState( $elem, data );
715 domPromise.done( data.restorePreInfuseState.bind( data, state ) );
716 } );
717 }
718 }
719 return data;
720 }
721 data = $elem.attr( 'data-ooui' );
722 if ( !data ) {
723 throw new Error( 'No infusion data found: ' + id );
724 }
725 try {
726 data = JSON.parse( data );
727 } catch ( _ ) {
728 data = null;
729 }
730 if ( !( data && data._ ) ) {
731 throw new Error( 'No valid infusion data found: ' + id );
732 }
733 if ( data._ === 'Tag' ) {
734 // Special case: this is a raw Tag; wrap existing node, don't rebuild.
735 return new OO.ui.Element( { $element: $elem } );
736 }
737 parts = data._.split( '.' );
738 cls = OO.getProp.apply( OO, [ window ].concat( parts ) );
739 if ( cls === undefined ) {
740 // The PHP output might be old and not including the "OO.ui" prefix
741 // TODO: Remove this back-compat after next major release
742 cls = OO.getProp.apply( OO, [ OO.ui ].concat( parts ) );
743 if ( cls === undefined ) {
744 throw new Error( 'Unknown widget type: id: ' + id + ', class: ' + data._ );
745 }
746 }
747
748 // Verify that we're creating an OO.ui.Element instance
749 parent = cls.parent;
750
751 while ( parent !== undefined ) {
752 if ( parent === OO.ui.Element ) {
753 // Safe
754 break;
755 }
756
757 parent = parent.parent;
758 }
759
760 if ( parent !== OO.ui.Element ) {
761 throw new Error( 'Unknown widget type: id: ' + id + ', class: ' + data._ );
762 }
763
764 if ( domPromise === false ) {
765 top = $.Deferred();
766 domPromise = top.promise();
767 }
768 $elem.data( 'ooui-infused', true ); // prevent loops
769 data.id = id; // implicit
770 infusedChildren = [];
771 data = OO.copy( data, null, function deserialize( value ) {
772 var infused;
773 if ( OO.isPlainObject( value ) ) {
774 if ( value.tag ) {
775 infused = OO.ui.Element.static.unsafeInfuse( value.tag, domPromise );
776 infusedChildren.push( infused );
777 // Flatten the structure
778 infusedChildren.push.apply( infusedChildren, infused.$element.data( 'ooui-infused-children' ) || [] );
779 infused.$element.removeData( 'ooui-infused-children' );
780 return infused;
781 }
782 if ( value.html !== undefined ) {
783 return new OO.ui.HtmlSnippet( value.html );
784 }
785 }
786 } );
787 // allow widgets to reuse parts of the DOM
788 data = cls.static.reusePreInfuseDOM( $elem[ 0 ], data );
789 // pick up dynamic state, like focus, value of form inputs, scroll position, etc.
790 state = cls.static.gatherPreInfuseState( $elem[ 0 ], data );
791 // rebuild widget
792 // eslint-disable-next-line new-cap
793 obj = new cls( data );
794 // now replace old DOM with this new DOM.
795 if ( top ) {
796 // An efficient constructor might be able to reuse the entire DOM tree of the original element,
797 // so only mutate the DOM if we need to.
798 if ( $elem[ 0 ] !== obj.$element[ 0 ] ) {
799 $elem.replaceWith( obj.$element );
800 // This element is now gone from the DOM, but if anyone is holding a reference to it,
801 // let's allow them to OO.ui.infuse() it and do what they expect, see T105828.
802 // Do not use jQuery.data(), as using it on detached nodes leaks memory in 1.x line by design.
803 $elem[ 0 ].oouiInfused = obj.$element;
804 }
805 top.resolve();
806 }
807 obj.$element.data( 'ooui-infused', obj );
808 obj.$element.data( 'ooui-infused-children', infusedChildren );
809 // set the 'data-ooui' attribute so we can identify infused widgets
810 obj.$element.attr( 'data-ooui', '' );
811 // restore dynamic state after the new element is inserted into DOM
812 domPromise.done( obj.restorePreInfuseState.bind( obj, state ) );
813 return obj;
814 };
815
816 /**
817 * Pick out parts of `node`'s DOM to be reused when infusing a widget.
818 *
819 * This method **must not** make any changes to the DOM, only find interesting pieces and add them
820 * to `config` (which should then be returned). Actual DOM juggling should then be done by the
821 * constructor, which will be given the enhanced config.
822 *
823 * @protected
824 * @param {HTMLElement} node
825 * @param {Object} config
826 * @return {Object}
827 */
828 OO.ui.Element.static.reusePreInfuseDOM = function ( node, config ) {
829 return config;
830 };
831
832 /**
833 * Gather the dynamic state (focus, value of form inputs, scroll position, etc.) of an HTML DOM node
834 * (and its children) that represent an Element of the same class and the given configuration,
835 * generated by the PHP implementation.
836 *
837 * This method is called just before `node` is detached from the DOM. The return value of this
838 * function will be passed to #restorePreInfuseState after the newly created widget's #$element
839 * is inserted into DOM to replace `node`.
840 *
841 * @protected
842 * @param {HTMLElement} node
843 * @param {Object} config
844 * @return {Object}
845 */
846 OO.ui.Element.static.gatherPreInfuseState = function () {
847 return {};
848 };
849
850 /**
851 * Get a jQuery function within a specific document.
852 *
853 * @static
854 * @param {jQuery|HTMLElement|HTMLDocument|Window} context Context to bind the function to
855 * @param {jQuery} [$iframe] HTML iframe element that contains the document, omit if document is
856 * not in an iframe
857 * @return {Function} Bound jQuery function
858 */
859 OO.ui.Element.static.getJQuery = function ( context, $iframe ) {
860 function wrapper( selector ) {
861 return $( selector, wrapper.context );
862 }
863
864 wrapper.context = this.getDocument( context );
865
866 if ( $iframe ) {
867 wrapper.$iframe = $iframe;
868 }
869
870 return wrapper;
871 };
872
873 /**
874 * Get the document of an element.
875 *
876 * @static
877 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Object to get the document for
878 * @return {HTMLDocument|null} Document object
879 */
880 OO.ui.Element.static.getDocument = function ( obj ) {
881 // jQuery - selections created "offscreen" won't have a context, so .context isn't reliable
882 return ( obj[ 0 ] && obj[ 0 ].ownerDocument ) ||
883 // Empty jQuery selections might have a context
884 obj.context ||
885 // HTMLElement
886 obj.ownerDocument ||
887 // Window
888 obj.document ||
889 // HTMLDocument
890 ( obj.nodeType === Node.DOCUMENT_NODE && obj ) ||
891 null;
892 };
893
894 /**
895 * Get the window of an element or document.
896 *
897 * @static
898 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the window for
899 * @return {Window} Window object
900 */
901 OO.ui.Element.static.getWindow = function ( obj ) {
902 var doc = this.getDocument( obj );
903 return doc.defaultView;
904 };
905
906 /**
907 * Get the direction of an element or document.
908 *
909 * @static
910 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the direction for
911 * @return {string} Text direction, either 'ltr' or 'rtl'
912 */
913 OO.ui.Element.static.getDir = function ( obj ) {
914 var isDoc, isWin;
915
916 if ( obj instanceof jQuery ) {
917 obj = obj[ 0 ];
918 }
919 isDoc = obj.nodeType === Node.DOCUMENT_NODE;
920 isWin = obj.document !== undefined;
921 if ( isDoc || isWin ) {
922 if ( isWin ) {
923 obj = obj.document;
924 }
925 obj = obj.body;
926 }
927 return $( obj ).css( 'direction' );
928 };
929
930 /**
931 * Get the offset between two frames.
932 *
933 * TODO: Make this function not use recursion.
934 *
935 * @static
936 * @param {Window} from Window of the child frame
937 * @param {Window} [to=window] Window of the parent frame
938 * @param {Object} [offset] Offset to start with, used internally
939 * @return {Object} Offset object, containing left and top properties
940 */
941 OO.ui.Element.static.getFrameOffset = function ( from, to, offset ) {
942 var i, len, frames, frame, rect;
943
944 if ( !to ) {
945 to = window;
946 }
947 if ( !offset ) {
948 offset = { top: 0, left: 0 };
949 }
950 if ( from.parent === from ) {
951 return offset;
952 }
953
954 // Get iframe element
955 frames = from.parent.document.getElementsByTagName( 'iframe' );
956 for ( i = 0, len = frames.length; i < len; i++ ) {
957 if ( frames[ i ].contentWindow === from ) {
958 frame = frames[ i ];
959 break;
960 }
961 }
962
963 // Recursively accumulate offset values
964 if ( frame ) {
965 rect = frame.getBoundingClientRect();
966 offset.left += rect.left;
967 offset.top += rect.top;
968 if ( from !== to ) {
969 this.getFrameOffset( from.parent, offset );
970 }
971 }
972 return offset;
973 };
974
975 /**
976 * Get the offset between two elements.
977 *
978 * The two elements may be in a different frame, but in that case the frame $element is in must
979 * be contained in the frame $anchor is in.
980 *
981 * @static
982 * @param {jQuery} $element Element whose position to get
983 * @param {jQuery} $anchor Element to get $element's position relative to
984 * @return {Object} Translated position coordinates, containing top and left properties
985 */
986 OO.ui.Element.static.getRelativePosition = function ( $element, $anchor ) {
987 var iframe, iframePos,
988 pos = $element.offset(),
989 anchorPos = $anchor.offset(),
990 elementDocument = this.getDocument( $element ),
991 anchorDocument = this.getDocument( $anchor );
992
993 // If $element isn't in the same document as $anchor, traverse up
994 while ( elementDocument !== anchorDocument ) {
995 iframe = elementDocument.defaultView.frameElement;
996 if ( !iframe ) {
997 throw new Error( '$element frame is not contained in $anchor frame' );
998 }
999 iframePos = $( iframe ).offset();
1000 pos.left += iframePos.left;
1001 pos.top += iframePos.top;
1002 elementDocument = iframe.ownerDocument;
1003 }
1004 pos.left -= anchorPos.left;
1005 pos.top -= anchorPos.top;
1006 return pos;
1007 };
1008
1009 /**
1010 * Get element border sizes.
1011 *
1012 * @static
1013 * @param {HTMLElement} el Element to measure
1014 * @return {Object} Dimensions object with `top`, `left`, `bottom` and `right` properties
1015 */
1016 OO.ui.Element.static.getBorders = function ( el ) {
1017 var doc = el.ownerDocument,
1018 win = doc.defaultView,
1019 style = win.getComputedStyle( el, null ),
1020 $el = $( el ),
1021 top = parseFloat( style ? style.borderTopWidth : $el.css( 'borderTopWidth' ) ) || 0,
1022 left = parseFloat( style ? style.borderLeftWidth : $el.css( 'borderLeftWidth' ) ) || 0,
1023 bottom = parseFloat( style ? style.borderBottomWidth : $el.css( 'borderBottomWidth' ) ) || 0,
1024 right = parseFloat( style ? style.borderRightWidth : $el.css( 'borderRightWidth' ) ) || 0;
1025
1026 return {
1027 top: top,
1028 left: left,
1029 bottom: bottom,
1030 right: right
1031 };
1032 };
1033
1034 /**
1035 * Get dimensions of an element or window.
1036 *
1037 * @static
1038 * @param {HTMLElement|Window} el Element to measure
1039 * @return {Object} Dimensions object with `borders`, `scroll`, `scrollbar` and `rect` properties
1040 */
1041 OO.ui.Element.static.getDimensions = function ( el ) {
1042 var $el, $win,
1043 doc = el.ownerDocument || el.document,
1044 win = doc.defaultView;
1045
1046 if ( win === el || el === doc.documentElement ) {
1047 $win = $( win );
1048 return {
1049 borders: { top: 0, left: 0, bottom: 0, right: 0 },
1050 scroll: {
1051 top: $win.scrollTop(),
1052 left: $win.scrollLeft()
1053 },
1054 scrollbar: { right: 0, bottom: 0 },
1055 rect: {
1056 top: 0,
1057 left: 0,
1058 bottom: $win.innerHeight(),
1059 right: $win.innerWidth()
1060 }
1061 };
1062 } else {
1063 $el = $( el );
1064 return {
1065 borders: this.getBorders( el ),
1066 scroll: {
1067 top: $el.scrollTop(),
1068 left: $el.scrollLeft()
1069 },
1070 scrollbar: {
1071 right: $el.innerWidth() - el.clientWidth,
1072 bottom: $el.innerHeight() - el.clientHeight
1073 },
1074 rect: el.getBoundingClientRect()
1075 };
1076 }
1077 };
1078
1079 /**
1080 * Get the number of pixels that an element's content is scrolled to the left.
1081 *
1082 * Adapted from <https://github.com/othree/jquery.rtl-scroll-type>.
1083 * Original code copyright 2012 Wei-Ko Kao, licensed under the MIT License.
1084 *
1085 * This function smooths out browser inconsistencies (nicely described in the README at
1086 * <https://github.com/othree/jquery.rtl-scroll-type>) and produces a result consistent
1087 * with Firefox's 'scrollLeft', which seems the sanest.
1088 *
1089 * @static
1090 * @method
1091 * @param {HTMLElement|Window} el Element to measure
1092 * @return {number} Scroll position from the left.
1093 * If the element's direction is LTR, this is a positive number between `0` (initial scroll position)
1094 * and `el.scrollWidth - el.clientWidth` (furthest possible scroll position).
1095 * If the element's direction is RTL, this is a negative number between `0` (initial scroll position)
1096 * and `-el.scrollWidth + el.clientWidth` (furthest possible scroll position).
1097 */
1098 OO.ui.Element.static.getScrollLeft = ( function () {
1099 var rtlScrollType = null;
1100
1101 function test() {
1102 var $definer = $( '<div dir="rtl" style="font-size: 14px; width: 1px; height: 1px; position: absolute; top: -1000px; overflow: scroll">A</div>' ),
1103 definer = $definer[ 0 ];
1104
1105 $definer.appendTo( 'body' );
1106 if ( definer.scrollLeft > 0 ) {
1107 // Safari, Chrome
1108 rtlScrollType = 'default';
1109 } else {
1110 definer.scrollLeft = 1;
1111 if ( definer.scrollLeft === 0 ) {
1112 // Firefox, old Opera
1113 rtlScrollType = 'negative';
1114 } else {
1115 // Internet Explorer, Edge
1116 rtlScrollType = 'reverse';
1117 }
1118 }
1119 $definer.remove();
1120 }
1121
1122 return function getScrollLeft( el ) {
1123 var isRoot = el.window === el ||
1124 el === el.ownerDocument.body ||
1125 el === el.ownerDocument.documentElement,
1126 scrollLeft = isRoot ? $( window ).scrollLeft() : el.scrollLeft,
1127 // All browsers use the correct scroll type ('negative') on the root, so don't
1128 // do any fixups when looking at the root element
1129 direction = isRoot ? 'ltr' : $( el ).css( 'direction' );
1130
1131 if ( direction === 'rtl' ) {
1132 if ( rtlScrollType === null ) {
1133 test();
1134 }
1135 if ( rtlScrollType === 'reverse' ) {
1136 scrollLeft = -scrollLeft;
1137 } else if ( rtlScrollType === 'default' ) {
1138 scrollLeft = scrollLeft - el.scrollWidth + el.clientWidth;
1139 }
1140 }
1141
1142 return scrollLeft;
1143 };
1144 }() );
1145
1146 /**
1147 * Get the root scrollable element of given element's document.
1148 *
1149 * On Blink-based browsers (Chrome etc.), `document.documentElement` can't be used to get or set
1150 * the scrollTop property; instead we have to use `document.body`. Changing and testing the value
1151 * lets us use 'body' or 'documentElement' based on what is working.
1152 *
1153 * https://code.google.com/p/chromium/issues/detail?id=303131
1154 *
1155 * @static
1156 * @param {HTMLElement} el Element to find root scrollable parent for
1157 * @return {HTMLElement} Scrollable parent, `document.body` or `document.documentElement`
1158 * depending on browser
1159 */
1160 OO.ui.Element.static.getRootScrollableElement = function ( el ) {
1161 var scrollTop, body;
1162
1163 if ( OO.ui.scrollableElement === undefined ) {
1164 body = el.ownerDocument.body;
1165 scrollTop = body.scrollTop;
1166 body.scrollTop = 1;
1167
1168 // In some browsers (observed in Chrome 56 on Linux Mint 18.1),
1169 // body.scrollTop doesn't become exactly 1, but a fractional value like 0.76
1170 if ( Math.round( body.scrollTop ) === 1 ) {
1171 body.scrollTop = scrollTop;
1172 OO.ui.scrollableElement = 'body';
1173 } else {
1174 OO.ui.scrollableElement = 'documentElement';
1175 }
1176 }
1177
1178 return el.ownerDocument[ OO.ui.scrollableElement ];
1179 };
1180
1181 /**
1182 * Get closest scrollable container.
1183 *
1184 * Traverses up until either a scrollable element or the root is reached, in which case the root
1185 * scrollable element will be returned (see #getRootScrollableElement).
1186 *
1187 * @static
1188 * @param {HTMLElement} el Element to find scrollable container for
1189 * @param {string} [dimension] Dimension of scrolling to look for; `x`, `y` or omit for either
1190 * @return {HTMLElement} Closest scrollable container
1191 */
1192 OO.ui.Element.static.getClosestScrollableContainer = function ( el, dimension ) {
1193 var i, val,
1194 // Browsers do not correctly return the computed value of 'overflow' when 'overflow-x' and
1195 // 'overflow-y' have different values, so we need to check the separate properties.
1196 props = [ 'overflow-x', 'overflow-y' ],
1197 $parent = $( el ).parent();
1198
1199 if ( dimension === 'x' || dimension === 'y' ) {
1200 props = [ 'overflow-' + dimension ];
1201 }
1202
1203 // Special case for the document root (which doesn't really have any scrollable container, since
1204 // it is the ultimate scrollable container, but this is probably saner than null or exception)
1205 if ( $( el ).is( 'html, body' ) ) {
1206 return this.getRootScrollableElement( el );
1207 }
1208
1209 while ( $parent.length ) {
1210 if ( $parent[ 0 ] === this.getRootScrollableElement( el ) ) {
1211 return $parent[ 0 ];
1212 }
1213 i = props.length;
1214 while ( i-- ) {
1215 val = $parent.css( props[ i ] );
1216 // We assume that elements with 'overflow' (in any direction) set to 'hidden' will never be
1217 // scrolled in that direction, but they can actually be scrolled programatically. The user can
1218 // unintentionally perform a scroll in such case even if the application doesn't scroll
1219 // programatically, e.g. when jumping to an anchor, or when using built-in find functionality.
1220 // This could cause funny issues...
1221 if ( val === 'auto' || val === 'scroll' ) {
1222 return $parent[ 0 ];
1223 }
1224 }
1225 $parent = $parent.parent();
1226 }
1227 // The element is unattached... return something mostly sane
1228 return this.getRootScrollableElement( el );
1229 };
1230
1231 /**
1232 * Scroll element into view.
1233 *
1234 * @static
1235 * @param {HTMLElement} el Element to scroll into view
1236 * @param {Object} [config] Configuration options
1237 * @param {string} [config.duration='fast'] jQuery animation duration value
1238 * @param {string} [config.direction] Scroll in only one direction, e.g. 'x' or 'y', omit
1239 * to scroll in both directions
1240 * @return {jQuery.Promise} Promise which resolves when the scroll is complete
1241 */
1242 OO.ui.Element.static.scrollIntoView = function ( el, config ) {
1243 var position, animations, container, $container, elementDimensions, containerDimensions, $window,
1244 deferred = $.Deferred();
1245
1246 // Configuration initialization
1247 config = config || {};
1248
1249 animations = {};
1250 container = this.getClosestScrollableContainer( el, config.direction );
1251 $container = $( container );
1252 elementDimensions = this.getDimensions( el );
1253 containerDimensions = this.getDimensions( container );
1254 $window = $( this.getWindow( el ) );
1255
1256 // Compute the element's position relative to the container
1257 if ( $container.is( 'html, body' ) ) {
1258 // If the scrollable container is the root, this is easy
1259 position = {
1260 top: elementDimensions.rect.top,
1261 bottom: $window.innerHeight() - elementDimensions.rect.bottom,
1262 left: elementDimensions.rect.left,
1263 right: $window.innerWidth() - elementDimensions.rect.right
1264 };
1265 } else {
1266 // Otherwise, we have to subtract el's coordinates from container's coordinates
1267 position = {
1268 top: elementDimensions.rect.top - ( containerDimensions.rect.top + containerDimensions.borders.top ),
1269 bottom: containerDimensions.rect.bottom - containerDimensions.borders.bottom - containerDimensions.scrollbar.bottom - elementDimensions.rect.bottom,
1270 left: elementDimensions.rect.left - ( containerDimensions.rect.left + containerDimensions.borders.left ),
1271 right: containerDimensions.rect.right - containerDimensions.borders.right - containerDimensions.scrollbar.right - elementDimensions.rect.right
1272 };
1273 }
1274
1275 if ( !config.direction || config.direction === 'y' ) {
1276 if ( position.top < 0 ) {
1277 animations.scrollTop = containerDimensions.scroll.top + position.top;
1278 } else if ( position.top > 0 && position.bottom < 0 ) {
1279 animations.scrollTop = containerDimensions.scroll.top + Math.min( position.top, -position.bottom );
1280 }
1281 }
1282 if ( !config.direction || config.direction === 'x' ) {
1283 if ( position.left < 0 ) {
1284 animations.scrollLeft = containerDimensions.scroll.left + position.left;
1285 } else if ( position.left > 0 && position.right < 0 ) {
1286 animations.scrollLeft = containerDimensions.scroll.left + Math.min( position.left, -position.right );
1287 }
1288 }
1289 if ( !$.isEmptyObject( animations ) ) {
1290 $container.stop( true ).animate( animations, config.duration === undefined ? 'fast' : config.duration );
1291 $container.queue( function ( next ) {
1292 deferred.resolve();
1293 next();
1294 } );
1295 } else {
1296 deferred.resolve();
1297 }
1298 return deferred.promise();
1299 };
1300
1301 /**
1302 * Force the browser to reconsider whether it really needs to render scrollbars inside the element
1303 * and reserve space for them, because it probably doesn't.
1304 *
1305 * Workaround primarily for <https://code.google.com/p/chromium/issues/detail?id=387290>, but also
1306 * similar bugs in other browsers. "Just" forcing a reflow is not sufficient in all cases, we need
1307 * to first actually detach (or hide, but detaching is simpler) all children, *then* force a reflow,
1308 * and then reattach (or show) them back.
1309 *
1310 * @static
1311 * @param {HTMLElement} el Element to reconsider the scrollbars on
1312 */
1313 OO.ui.Element.static.reconsiderScrollbars = function ( el ) {
1314 var i, len, scrollLeft, scrollTop, nodes = [];
1315 // Save scroll position
1316 scrollLeft = el.scrollLeft;
1317 scrollTop = el.scrollTop;
1318 // Detach all children
1319 while ( el.firstChild ) {
1320 nodes.push( el.firstChild );
1321 el.removeChild( el.firstChild );
1322 }
1323 // Force reflow
1324 void el.offsetHeight;
1325 // Reattach all children
1326 for ( i = 0, len = nodes.length; i < len; i++ ) {
1327 el.appendChild( nodes[ i ] );
1328 }
1329 // Restore scroll position (no-op if scrollbars disappeared)
1330 el.scrollLeft = scrollLeft;
1331 el.scrollTop = scrollTop;
1332 };
1333
1334 /* Methods */
1335
1336 /**
1337 * Toggle visibility of an element.
1338 *
1339 * @param {boolean} [show] Make element visible, omit to toggle visibility
1340 * @fires visible
1341 * @chainable
1342 */
1343 OO.ui.Element.prototype.toggle = function ( show ) {
1344 show = show === undefined ? !this.visible : !!show;
1345
1346 if ( show !== this.isVisible() ) {
1347 this.visible = show;
1348 this.$element.toggleClass( 'oo-ui-element-hidden', !this.visible );
1349 this.emit( 'toggle', show );
1350 }
1351
1352 return this;
1353 };
1354
1355 /**
1356 * Check if element is visible.
1357 *
1358 * @return {boolean} element is visible
1359 */
1360 OO.ui.Element.prototype.isVisible = function () {
1361 return this.visible;
1362 };
1363
1364 /**
1365 * Get element data.
1366 *
1367 * @return {Mixed} Element data
1368 */
1369 OO.ui.Element.prototype.getData = function () {
1370 return this.data;
1371 };
1372
1373 /**
1374 * Set element data.
1375 *
1376 * @param {Mixed} data Element data
1377 * @chainable
1378 */
1379 OO.ui.Element.prototype.setData = function ( data ) {
1380 this.data = data;
1381 return this;
1382 };
1383
1384 /**
1385 * Set the element has an 'id' attribute.
1386 *
1387 * @param {string} id
1388 * @chainable
1389 */
1390 OO.ui.Element.prototype.setElementId = function ( id ) {
1391 this.elementId = id;
1392 this.$element.attr( 'id', id );
1393 return this;
1394 };
1395
1396 /**
1397 * Ensure that the element has an 'id' attribute, setting it to an unique value if it's missing,
1398 * and return its value.
1399 *
1400 * @return {string}
1401 */
1402 OO.ui.Element.prototype.getElementId = function () {
1403 if ( this.elementId === null ) {
1404 this.setElementId( OO.ui.generateElementId() );
1405 }
1406 return this.elementId;
1407 };
1408
1409 /**
1410 * Check if element supports one or more methods.
1411 *
1412 * @param {string|string[]} methods Method or list of methods to check
1413 * @return {boolean} All methods are supported
1414 */
1415 OO.ui.Element.prototype.supports = function ( methods ) {
1416 var i, len,
1417 support = 0;
1418
1419 methods = Array.isArray( methods ) ? methods : [ methods ];
1420 for ( i = 0, len = methods.length; i < len; i++ ) {
1421 if ( $.isFunction( this[ methods[ i ] ] ) ) {
1422 support++;
1423 }
1424 }
1425
1426 return methods.length === support;
1427 };
1428
1429 /**
1430 * Update the theme-provided classes.
1431 *
1432 * @localdoc This is called in element mixins and widget classes any time state changes.
1433 * Updating is debounced, minimizing overhead of changing multiple attributes and
1434 * guaranteeing that theme updates do not occur within an element's constructor
1435 */
1436 OO.ui.Element.prototype.updateThemeClasses = function () {
1437 OO.ui.theme.queueUpdateElementClasses( this );
1438 };
1439
1440 /**
1441 * Get the HTML tag name.
1442 *
1443 * Override this method to base the result on instance information.
1444 *
1445 * @return {string} HTML tag name
1446 */
1447 OO.ui.Element.prototype.getTagName = function () {
1448 return this.constructor.static.tagName;
1449 };
1450
1451 /**
1452 * Check if the element is attached to the DOM
1453 *
1454 * @return {boolean} The element is attached to the DOM
1455 */
1456 OO.ui.Element.prototype.isElementAttached = function () {
1457 return $.contains( this.getElementDocument(), this.$element[ 0 ] );
1458 };
1459
1460 /**
1461 * Get the DOM document.
1462 *
1463 * @return {HTMLDocument} Document object
1464 */
1465 OO.ui.Element.prototype.getElementDocument = function () {
1466 // Don't cache this in other ways either because subclasses could can change this.$element
1467 return OO.ui.Element.static.getDocument( this.$element );
1468 };
1469
1470 /**
1471 * Get the DOM window.
1472 *
1473 * @return {Window} Window object
1474 */
1475 OO.ui.Element.prototype.getElementWindow = function () {
1476 return OO.ui.Element.static.getWindow( this.$element );
1477 };
1478
1479 /**
1480 * Get closest scrollable container.
1481 *
1482 * @return {HTMLElement} Closest scrollable container
1483 */
1484 OO.ui.Element.prototype.getClosestScrollableElementContainer = function () {
1485 return OO.ui.Element.static.getClosestScrollableContainer( this.$element[ 0 ] );
1486 };
1487
1488 /**
1489 * Get group element is in.
1490 *
1491 * @return {OO.ui.mixin.GroupElement|null} Group element, null if none
1492 */
1493 OO.ui.Element.prototype.getElementGroup = function () {
1494 return this.elementGroup;
1495 };
1496
1497 /**
1498 * Set group element is in.
1499 *
1500 * @param {OO.ui.mixin.GroupElement|null} group Group element, null if none
1501 * @chainable
1502 */
1503 OO.ui.Element.prototype.setElementGroup = function ( group ) {
1504 this.elementGroup = group;
1505 return this;
1506 };
1507
1508 /**
1509 * Scroll element into view.
1510 *
1511 * @param {Object} [config] Configuration options
1512 * @return {jQuery.Promise} Promise which resolves when the scroll is complete
1513 */
1514 OO.ui.Element.prototype.scrollElementIntoView = function ( config ) {
1515 if (
1516 !this.isElementAttached() ||
1517 !this.isVisible() ||
1518 ( this.getElementGroup() && !this.getElementGroup().isVisible() )
1519 ) {
1520 return $.Deferred().resolve();
1521 }
1522 return OO.ui.Element.static.scrollIntoView( this.$element[ 0 ], config );
1523 };
1524
1525 /**
1526 * Restore the pre-infusion dynamic state for this widget.
1527 *
1528 * This method is called after #$element has been inserted into DOM. The parameter is the return
1529 * value of #gatherPreInfuseState.
1530 *
1531 * @protected
1532 * @param {Object} state
1533 */
1534 OO.ui.Element.prototype.restorePreInfuseState = function () {
1535 };
1536
1537 /**
1538 * Wraps an HTML snippet for use with configuration values which default
1539 * to strings. This bypasses the default html-escaping done to string
1540 * values.
1541 *
1542 * @class
1543 *
1544 * @constructor
1545 * @param {string} [content] HTML content
1546 */
1547 OO.ui.HtmlSnippet = function OoUiHtmlSnippet( content ) {
1548 // Properties
1549 this.content = content;
1550 };
1551
1552 /* Setup */
1553
1554 OO.initClass( OO.ui.HtmlSnippet );
1555
1556 /* Methods */
1557
1558 /**
1559 * Render into HTML.
1560 *
1561 * @return {string} Unchanged HTML snippet.
1562 */
1563 OO.ui.HtmlSnippet.prototype.toString = function () {
1564 return this.content;
1565 };
1566
1567 /**
1568 * Layouts are containers for elements and are used to arrange other widgets of arbitrary type in a way
1569 * that is centrally controlled and can be updated dynamically. Layouts can be, and usually are, combined.
1570 * See {@link OO.ui.FieldsetLayout FieldsetLayout}, {@link OO.ui.FieldLayout FieldLayout}, {@link OO.ui.FormLayout FormLayout},
1571 * {@link OO.ui.PanelLayout PanelLayout}, {@link OO.ui.StackLayout StackLayout}, {@link OO.ui.PageLayout PageLayout},
1572 * {@link OO.ui.HorizontalLayout HorizontalLayout}, and {@link OO.ui.BookletLayout BookletLayout} for more information and examples.
1573 *
1574 * @abstract
1575 * @class
1576 * @extends OO.ui.Element
1577 * @mixins OO.EventEmitter
1578 *
1579 * @constructor
1580 * @param {Object} [config] Configuration options
1581 */
1582 OO.ui.Layout = function OoUiLayout( config ) {
1583 // Configuration initialization
1584 config = config || {};
1585
1586 // Parent constructor
1587 OO.ui.Layout.parent.call( this, config );
1588
1589 // Mixin constructors
1590 OO.EventEmitter.call( this );
1591
1592 // Initialization
1593 this.$element.addClass( 'oo-ui-layout' );
1594 };
1595
1596 /* Setup */
1597
1598 OO.inheritClass( OO.ui.Layout, OO.ui.Element );
1599 OO.mixinClass( OO.ui.Layout, OO.EventEmitter );
1600
1601 /**
1602 * Widgets are compositions of one or more OOjs UI elements that users can both view
1603 * and interact with. All widgets can be configured and modified via a standard API,
1604 * and their state can change dynamically according to a model.
1605 *
1606 * @abstract
1607 * @class
1608 * @extends OO.ui.Element
1609 * @mixins OO.EventEmitter
1610 *
1611 * @constructor
1612 * @param {Object} [config] Configuration options
1613 * @cfg {boolean} [disabled=false] Disable the widget. Disabled widgets cannot be used and their
1614 * appearance reflects this state.
1615 */
1616 OO.ui.Widget = function OoUiWidget( config ) {
1617 // Initialize config
1618 config = $.extend( { disabled: false }, config );
1619
1620 // Parent constructor
1621 OO.ui.Widget.parent.call( this, config );
1622
1623 // Mixin constructors
1624 OO.EventEmitter.call( this );
1625
1626 // Properties
1627 this.disabled = null;
1628 this.wasDisabled = null;
1629
1630 // Initialization
1631 this.$element.addClass( 'oo-ui-widget' );
1632 this.setDisabled( !!config.disabled );
1633 };
1634
1635 /* Setup */
1636
1637 OO.inheritClass( OO.ui.Widget, OO.ui.Element );
1638 OO.mixinClass( OO.ui.Widget, OO.EventEmitter );
1639
1640 /* Events */
1641
1642 /**
1643 * @event disable
1644 *
1645 * A 'disable' event is emitted when the disabled state of the widget changes
1646 * (i.e. on disable **and** enable).
1647 *
1648 * @param {boolean} disabled Widget is disabled
1649 */
1650
1651 /**
1652 * @event toggle
1653 *
1654 * A 'toggle' event is emitted when the visibility of the widget changes.
1655 *
1656 * @param {boolean} visible Widget is visible
1657 */
1658
1659 /* Methods */
1660
1661 /**
1662 * Check if the widget is disabled.
1663 *
1664 * @return {boolean} Widget is disabled
1665 */
1666 OO.ui.Widget.prototype.isDisabled = function () {
1667 return this.disabled;
1668 };
1669
1670 /**
1671 * Set the 'disabled' state of the widget.
1672 *
1673 * When a widget is disabled, it cannot be used and its appearance is updated to reflect this state.
1674 *
1675 * @param {boolean} disabled Disable widget
1676 * @chainable
1677 */
1678 OO.ui.Widget.prototype.setDisabled = function ( disabled ) {
1679 var isDisabled;
1680
1681 this.disabled = !!disabled;
1682 isDisabled = this.isDisabled();
1683 if ( isDisabled !== this.wasDisabled ) {
1684 this.$element.toggleClass( 'oo-ui-widget-disabled', isDisabled );
1685 this.$element.toggleClass( 'oo-ui-widget-enabled', !isDisabled );
1686 this.$element.attr( 'aria-disabled', isDisabled.toString() );
1687 this.emit( 'disable', isDisabled );
1688 this.updateThemeClasses();
1689 }
1690 this.wasDisabled = isDisabled;
1691
1692 return this;
1693 };
1694
1695 /**
1696 * Update the disabled state, in case of changes in parent widget.
1697 *
1698 * @chainable
1699 */
1700 OO.ui.Widget.prototype.updateDisabled = function () {
1701 this.setDisabled( this.disabled );
1702 return this;
1703 };
1704
1705 /**
1706 * Get an ID of a labelable node which is part of this widget, if any, to be used for `<label for>`
1707 * value.
1708 *
1709 * If this function returns null, the widget should have a meaningful #simulateLabelClick method
1710 * instead.
1711 *
1712 * @return {string|null} The ID of the labelable element
1713 */
1714 OO.ui.Widget.prototype.getInputId = function () {
1715 return null;
1716 };
1717
1718 /**
1719 * Simulate the behavior of clicking on a label (a HTML `<label>` element) bound to this input.
1720 * HTML only allows `<label>` to act on specific "labelable" elements; complex widgets might need to
1721 * override this method to provide intuitive, accessible behavior.
1722 *
1723 * By default, this does nothing. OO.ui.mixin.TabIndexedElement overrides it for focusable widgets.
1724 * Individual widgets may override it too.
1725 *
1726 * This method is called by OO.ui.LabelWidget and OO.ui.FieldLayout. It should not be called
1727 * directly.
1728 */
1729 OO.ui.Widget.prototype.simulateLabelClick = function () {
1730 };
1731
1732 /**
1733 * Theme logic.
1734 *
1735 * @abstract
1736 * @class
1737 *
1738 * @constructor
1739 */
1740 OO.ui.Theme = function OoUiTheme() {
1741 this.elementClassesQueue = [];
1742 this.debouncedUpdateQueuedElementClasses = OO.ui.debounce( this.updateQueuedElementClasses );
1743 };
1744
1745 /* Setup */
1746
1747 OO.initClass( OO.ui.Theme );
1748
1749 /* Methods */
1750
1751 /**
1752 * Get a list of classes to be applied to a widget.
1753 *
1754 * The 'on' and 'off' lists combined MUST contain keys for all classes the theme adds or removes,
1755 * otherwise state transitions will not work properly.
1756 *
1757 * @param {OO.ui.Element} element Element for which to get classes
1758 * @return {Object.<string,string[]>} Categorized class names with `on` and `off` lists
1759 */
1760 OO.ui.Theme.prototype.getElementClasses = function () {
1761 return { on: [], off: [] };
1762 };
1763
1764 /**
1765 * Update CSS classes provided by the theme.
1766 *
1767 * For elements with theme logic hooks, this should be called any time there's a state change.
1768 *
1769 * @param {OO.ui.Element} element Element for which to update classes
1770 */
1771 OO.ui.Theme.prototype.updateElementClasses = function ( element ) {
1772 var $elements = $( [] ),
1773 classes = this.getElementClasses( element );
1774
1775 if ( element.$icon ) {
1776 $elements = $elements.add( element.$icon );
1777 }
1778 if ( element.$indicator ) {
1779 $elements = $elements.add( element.$indicator );
1780 }
1781
1782 $elements
1783 .removeClass( classes.off.join( ' ' ) )
1784 .addClass( classes.on.join( ' ' ) );
1785 };
1786
1787 /**
1788 * @private
1789 */
1790 OO.ui.Theme.prototype.updateQueuedElementClasses = function () {
1791 var i;
1792 for ( i = 0; i < this.elementClassesQueue.length; i++ ) {
1793 this.updateElementClasses( this.elementClassesQueue[ i ] );
1794 }
1795 // Clear the queue
1796 this.elementClassesQueue = [];
1797 };
1798
1799 /**
1800 * Queue #updateElementClasses to be called for this element.
1801 *
1802 * @localdoc QUnit tests override this method to directly call #queueUpdateElementClasses,
1803 * to make them synchronous.
1804 *
1805 * @param {OO.ui.Element} element Element for which to update classes
1806 */
1807 OO.ui.Theme.prototype.queueUpdateElementClasses = function ( element ) {
1808 // Keep items in the queue unique. Use lastIndexOf to start checking from the end because that's
1809 // the most common case (this method is often called repeatedly for the same element).
1810 if ( this.elementClassesQueue.lastIndexOf( element ) !== -1 ) {
1811 return;
1812 }
1813 this.elementClassesQueue.push( element );
1814 this.debouncedUpdateQueuedElementClasses();
1815 };
1816
1817 /**
1818 * Get the transition duration in milliseconds for dialogs opening/closing
1819 *
1820 * The dialog should be fully rendered this many milliseconds after the
1821 * ready process has executed.
1822 *
1823 * @return {number} Transition duration in milliseconds
1824 */
1825 OO.ui.Theme.prototype.getDialogTransitionDuration = function () {
1826 return 0;
1827 };
1828
1829 /**
1830 * The TabIndexedElement class is an attribute mixin used to add additional functionality to an
1831 * element created by another class. The mixin provides a ‘tabIndex’ property, which specifies the
1832 * order in which users will navigate through the focusable elements via the "tab" key.
1833 *
1834 * @example
1835 * // TabIndexedElement is mixed into the ButtonWidget class
1836 * // to provide a tabIndex property.
1837 * var button1 = new OO.ui.ButtonWidget( {
1838 * label: 'fourth',
1839 * tabIndex: 4
1840 * } );
1841 * var button2 = new OO.ui.ButtonWidget( {
1842 * label: 'second',
1843 * tabIndex: 2
1844 * } );
1845 * var button3 = new OO.ui.ButtonWidget( {
1846 * label: 'third',
1847 * tabIndex: 3
1848 * } );
1849 * var button4 = new OO.ui.ButtonWidget( {
1850 * label: 'first',
1851 * tabIndex: 1
1852 * } );
1853 * $( 'body' ).append( button1.$element, button2.$element, button3.$element, button4.$element );
1854 *
1855 * @abstract
1856 * @class
1857 *
1858 * @constructor
1859 * @param {Object} [config] Configuration options
1860 * @cfg {jQuery} [$tabIndexed] The element that should use the tabindex functionality. By default,
1861 * the functionality is applied to the element created by the class ($element). If a different element is specified, the tabindex
1862 * functionality will be applied to it instead.
1863 * @cfg {string|number|null} [tabIndex=0] Number that specifies the element’s position in the tab-navigation
1864 * order (e.g., 1 for the first focusable element). Use 0 to use the default navigation order; use -1
1865 * to remove the element from the tab-navigation flow.
1866 */
1867 OO.ui.mixin.TabIndexedElement = function OoUiMixinTabIndexedElement( config ) {
1868 // Configuration initialization
1869 config = $.extend( { tabIndex: 0 }, config );
1870
1871 // Properties
1872 this.$tabIndexed = null;
1873 this.tabIndex = null;
1874
1875 // Events
1876 this.connect( this, { disable: 'onTabIndexedElementDisable' } );
1877
1878 // Initialization
1879 this.setTabIndex( config.tabIndex );
1880 this.setTabIndexedElement( config.$tabIndexed || this.$element );
1881 };
1882
1883 /* Setup */
1884
1885 OO.initClass( OO.ui.mixin.TabIndexedElement );
1886
1887 /* Methods */
1888
1889 /**
1890 * Set the element that should use the tabindex functionality.
1891 *
1892 * This method is used to retarget a tabindex mixin so that its functionality applies
1893 * to the specified element. If an element is currently using the functionality, the mixin’s
1894 * effect on that element is removed before the new element is set up.
1895 *
1896 * @param {jQuery} $tabIndexed Element that should use the tabindex functionality
1897 * @chainable
1898 */
1899 OO.ui.mixin.TabIndexedElement.prototype.setTabIndexedElement = function ( $tabIndexed ) {
1900 var tabIndex = this.tabIndex;
1901 // Remove attributes from old $tabIndexed
1902 this.setTabIndex( null );
1903 // Force update of new $tabIndexed
1904 this.$tabIndexed = $tabIndexed;
1905 this.tabIndex = tabIndex;
1906 return this.updateTabIndex();
1907 };
1908
1909 /**
1910 * Set the value of the tabindex.
1911 *
1912 * @param {string|number|null} tabIndex Tabindex value, or `null` for no tabindex
1913 * @chainable
1914 */
1915 OO.ui.mixin.TabIndexedElement.prototype.setTabIndex = function ( tabIndex ) {
1916 tabIndex = /^-?\d+$/.test( tabIndex ) ? Number( tabIndex ) : null;
1917
1918 if ( this.tabIndex !== tabIndex ) {
1919 this.tabIndex = tabIndex;
1920 this.updateTabIndex();
1921 }
1922
1923 return this;
1924 };
1925
1926 /**
1927 * Update the `tabindex` attribute, in case of changes to tab index or
1928 * disabled state.
1929 *
1930 * @private
1931 * @chainable
1932 */
1933 OO.ui.mixin.TabIndexedElement.prototype.updateTabIndex = function () {
1934 if ( this.$tabIndexed ) {
1935 if ( this.tabIndex !== null ) {
1936 // Do not index over disabled elements
1937 this.$tabIndexed.attr( {
1938 tabindex: this.isDisabled() ? -1 : this.tabIndex,
1939 // Support: ChromeVox and NVDA
1940 // These do not seem to inherit aria-disabled from parent elements
1941 'aria-disabled': this.isDisabled().toString()
1942 } );
1943 } else {
1944 this.$tabIndexed.removeAttr( 'tabindex aria-disabled' );
1945 }
1946 }
1947 return this;
1948 };
1949
1950 /**
1951 * Handle disable events.
1952 *
1953 * @private
1954 * @param {boolean} disabled Element is disabled
1955 */
1956 OO.ui.mixin.TabIndexedElement.prototype.onTabIndexedElementDisable = function () {
1957 this.updateTabIndex();
1958 };
1959
1960 /**
1961 * Get the value of the tabindex.
1962 *
1963 * @return {number|null} Tabindex value
1964 */
1965 OO.ui.mixin.TabIndexedElement.prototype.getTabIndex = function () {
1966 return this.tabIndex;
1967 };
1968
1969 /**
1970 * Get an ID of a focusable element of this widget, if any, to be used for `<label for>` value.
1971 *
1972 * If the element already has an ID then that is returned, otherwise unique ID is
1973 * generated, set on the element, and returned.
1974 *
1975 * @return {string|null} The ID of the focusable element
1976 */
1977 OO.ui.mixin.TabIndexedElement.prototype.getInputId = function () {
1978 var id;
1979
1980 if ( !this.$tabIndexed ) {
1981 return null;
1982 }
1983 if ( !this.isLabelableNode( this.$tabIndexed ) ) {
1984 return null;
1985 }
1986
1987 id = this.$tabIndexed.attr( 'id' );
1988 if ( id === undefined ) {
1989 id = OO.ui.generateElementId();
1990 this.$tabIndexed.attr( 'id', id );
1991 }
1992
1993 return id;
1994 };
1995
1996 /**
1997 * Whether the node is 'labelable' according to the HTML spec
1998 * (i.e., whether it can be interacted with through a `<label for="…">`).
1999 * See: <https://html.spec.whatwg.org/multipage/forms.html#category-label>.
2000 *
2001 * @private
2002 * @param {jQuery} $node
2003 * @return {boolean}
2004 */
2005 OO.ui.mixin.TabIndexedElement.prototype.isLabelableNode = function ( $node ) {
2006 var
2007 labelableTags = [ 'button', 'meter', 'output', 'progress', 'select', 'textarea' ],
2008 tagName = $node.prop( 'tagName' ).toLowerCase();
2009
2010 if ( tagName === 'input' && $node.attr( 'type' ) !== 'hidden' ) {
2011 return true;
2012 }
2013 if ( labelableTags.indexOf( tagName ) !== -1 ) {
2014 return true;
2015 }
2016 return false;
2017 };
2018
2019 /**
2020 * Focus this element.
2021 *
2022 * @chainable
2023 */
2024 OO.ui.mixin.TabIndexedElement.prototype.focus = function () {
2025 if ( !this.isDisabled() ) {
2026 this.$tabIndexed.focus();
2027 }
2028 return this;
2029 };
2030
2031 /**
2032 * Blur this element.
2033 *
2034 * @chainable
2035 */
2036 OO.ui.mixin.TabIndexedElement.prototype.blur = function () {
2037 this.$tabIndexed.blur();
2038 return this;
2039 };
2040
2041 /**
2042 * @inheritdoc OO.ui.Widget
2043 */
2044 OO.ui.mixin.TabIndexedElement.prototype.simulateLabelClick = function () {
2045 this.focus();
2046 };
2047
2048 /**
2049 * ButtonElement is often mixed into other classes to generate a button, which is a clickable
2050 * interface element that can be configured with access keys for accessibility.
2051 * See the [OOjs UI documentation on MediaWiki] [1] for examples.
2052 *
2053 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#Buttons
2054 *
2055 * @abstract
2056 * @class
2057 *
2058 * @constructor
2059 * @param {Object} [config] Configuration options
2060 * @cfg {jQuery} [$button] The button element created by the class.
2061 * If this configuration is omitted, the button element will use a generated `<a>`.
2062 * @cfg {boolean} [framed=true] Render the button with a frame
2063 */
2064 OO.ui.mixin.ButtonElement = function OoUiMixinButtonElement( config ) {
2065 // Configuration initialization
2066 config = config || {};
2067
2068 // Properties
2069 this.$button = null;
2070 this.framed = null;
2071 this.active = config.active !== undefined && config.active;
2072 this.onMouseUpHandler = this.onMouseUp.bind( this );
2073 this.onMouseDownHandler = this.onMouseDown.bind( this );
2074 this.onKeyDownHandler = this.onKeyDown.bind( this );
2075 this.onKeyUpHandler = this.onKeyUp.bind( this );
2076 this.onClickHandler = this.onClick.bind( this );
2077 this.onKeyPressHandler = this.onKeyPress.bind( this );
2078
2079 // Initialization
2080 this.$element.addClass( 'oo-ui-buttonElement' );
2081 this.toggleFramed( config.framed === undefined || config.framed );
2082 this.setButtonElement( config.$button || $( '<a>' ) );
2083 };
2084
2085 /* Setup */
2086
2087 OO.initClass( OO.ui.mixin.ButtonElement );
2088
2089 /* Static Properties */
2090
2091 /**
2092 * Cancel mouse down events.
2093 *
2094 * This property is usually set to `true` to prevent the focus from changing when the button is clicked.
2095 * Classes such as {@link OO.ui.mixin.DraggableElement DraggableElement} and {@link OO.ui.ButtonOptionWidget ButtonOptionWidget}
2096 * use a value of `false` so that dragging behavior is possible and mousedown events can be handled by a
2097 * parent widget.
2098 *
2099 * @static
2100 * @inheritable
2101 * @property {boolean}
2102 */
2103 OO.ui.mixin.ButtonElement.static.cancelButtonMouseDownEvents = true;
2104
2105 /* Events */
2106
2107 /**
2108 * A 'click' event is emitted when the button element is clicked.
2109 *
2110 * @event click
2111 */
2112
2113 /* Methods */
2114
2115 /**
2116 * Set the button element.
2117 *
2118 * This method is used to retarget a button mixin so that its functionality applies to
2119 * the specified button element instead of the one created by the class. If a button element
2120 * is already set, the method will remove the mixin’s effect on that element.
2121 *
2122 * @param {jQuery} $button Element to use as button
2123 */
2124 OO.ui.mixin.ButtonElement.prototype.setButtonElement = function ( $button ) {
2125 if ( this.$button ) {
2126 this.$button
2127 .removeClass( 'oo-ui-buttonElement-button' )
2128 .removeAttr( 'role accesskey' )
2129 .off( {
2130 mousedown: this.onMouseDownHandler,
2131 keydown: this.onKeyDownHandler,
2132 click: this.onClickHandler,
2133 keypress: this.onKeyPressHandler
2134 } );
2135 }
2136
2137 this.$button = $button
2138 .addClass( 'oo-ui-buttonElement-button' )
2139 .on( {
2140 mousedown: this.onMouseDownHandler,
2141 keydown: this.onKeyDownHandler,
2142 click: this.onClickHandler,
2143 keypress: this.onKeyPressHandler
2144 } );
2145
2146 // Add `role="button"` on `<a>` elements, where it's needed
2147 // `toUppercase()` is added for XHTML documents
2148 if ( this.$button.prop( 'tagName' ).toUpperCase() === 'A' ) {
2149 this.$button.attr( 'role', 'button' );
2150 }
2151 };
2152
2153 /**
2154 * Handles mouse down events.
2155 *
2156 * @protected
2157 * @param {jQuery.Event} e Mouse down event
2158 */
2159 OO.ui.mixin.ButtonElement.prototype.onMouseDown = function ( e ) {
2160 if ( this.isDisabled() || e.which !== OO.ui.MouseButtons.LEFT ) {
2161 return;
2162 }
2163 this.$element.addClass( 'oo-ui-buttonElement-pressed' );
2164 // Run the mouseup handler no matter where the mouse is when the button is let go, so we can
2165 // reliably remove the pressed class
2166 this.getElementDocument().addEventListener( 'mouseup', this.onMouseUpHandler, true );
2167 // Prevent change of focus unless specifically configured otherwise
2168 if ( this.constructor.static.cancelButtonMouseDownEvents ) {
2169 return false;
2170 }
2171 };
2172
2173 /**
2174 * Handles mouse up events.
2175 *
2176 * @protected
2177 * @param {MouseEvent} e Mouse up event
2178 */
2179 OO.ui.mixin.ButtonElement.prototype.onMouseUp = function ( e ) {
2180 if ( this.isDisabled() || e.which !== OO.ui.MouseButtons.LEFT ) {
2181 return;
2182 }
2183 this.$element.removeClass( 'oo-ui-buttonElement-pressed' );
2184 // Stop listening for mouseup, since we only needed this once
2185 this.getElementDocument().removeEventListener( 'mouseup', this.onMouseUpHandler, true );
2186 };
2187
2188 /**
2189 * Handles mouse click events.
2190 *
2191 * @protected
2192 * @param {jQuery.Event} e Mouse click event
2193 * @fires click
2194 */
2195 OO.ui.mixin.ButtonElement.prototype.onClick = function ( e ) {
2196 if ( !this.isDisabled() && e.which === OO.ui.MouseButtons.LEFT ) {
2197 if ( this.emit( 'click' ) ) {
2198 return false;
2199 }
2200 }
2201 };
2202
2203 /**
2204 * Handles key down events.
2205 *
2206 * @protected
2207 * @param {jQuery.Event} e Key down event
2208 */
2209 OO.ui.mixin.ButtonElement.prototype.onKeyDown = function ( e ) {
2210 if ( this.isDisabled() || ( e.which !== OO.ui.Keys.SPACE && e.which !== OO.ui.Keys.ENTER ) ) {
2211 return;
2212 }
2213 this.$element.addClass( 'oo-ui-buttonElement-pressed' );
2214 // Run the keyup handler no matter where the key is when the button is let go, so we can
2215 // reliably remove the pressed class
2216 this.getElementDocument().addEventListener( 'keyup', this.onKeyUpHandler, true );
2217 };
2218
2219 /**
2220 * Handles key up events.
2221 *
2222 * @protected
2223 * @param {KeyboardEvent} e Key up event
2224 */
2225 OO.ui.mixin.ButtonElement.prototype.onKeyUp = function ( e ) {
2226 if ( this.isDisabled() || ( e.which !== OO.ui.Keys.SPACE && e.which !== OO.ui.Keys.ENTER ) ) {
2227 return;
2228 }
2229 this.$element.removeClass( 'oo-ui-buttonElement-pressed' );
2230 // Stop listening for keyup, since we only needed this once
2231 this.getElementDocument().removeEventListener( 'keyup', this.onKeyUpHandler, true );
2232 };
2233
2234 /**
2235 * Handles key press events.
2236 *
2237 * @protected
2238 * @param {jQuery.Event} e Key press event
2239 * @fires click
2240 */
2241 OO.ui.mixin.ButtonElement.prototype.onKeyPress = function ( e ) {
2242 if ( !this.isDisabled() && ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER ) ) {
2243 if ( this.emit( 'click' ) ) {
2244 return false;
2245 }
2246 }
2247 };
2248
2249 /**
2250 * Check if button has a frame.
2251 *
2252 * @return {boolean} Button is framed
2253 */
2254 OO.ui.mixin.ButtonElement.prototype.isFramed = function () {
2255 return this.framed;
2256 };
2257
2258 /**
2259 * Render the button with or without a frame. Omit the `framed` parameter to toggle the button frame on and off.
2260 *
2261 * @param {boolean} [framed] Make button framed, omit to toggle
2262 * @chainable
2263 */
2264 OO.ui.mixin.ButtonElement.prototype.toggleFramed = function ( framed ) {
2265 framed = framed === undefined ? !this.framed : !!framed;
2266 if ( framed !== this.framed ) {
2267 this.framed = framed;
2268 this.$element
2269 .toggleClass( 'oo-ui-buttonElement-frameless', !framed )
2270 .toggleClass( 'oo-ui-buttonElement-framed', framed );
2271 this.updateThemeClasses();
2272 }
2273
2274 return this;
2275 };
2276
2277 /**
2278 * Set the button's active state.
2279 *
2280 * The active state can be set on:
2281 *
2282 * - {@link OO.ui.ButtonOptionWidget ButtonOptionWidget} when it is selected
2283 * - {@link OO.ui.ToggleButtonWidget ToggleButtonWidget} when it is toggle on
2284 * - {@link OO.ui.ButtonWidget ButtonWidget} when clicking the button would only refresh the page
2285 *
2286 * @protected
2287 * @param {boolean} value Make button active
2288 * @chainable
2289 */
2290 OO.ui.mixin.ButtonElement.prototype.setActive = function ( value ) {
2291 this.active = !!value;
2292 this.$element.toggleClass( 'oo-ui-buttonElement-active', this.active );
2293 this.updateThemeClasses();
2294 return this;
2295 };
2296
2297 /**
2298 * Check if the button is active
2299 *
2300 * @protected
2301 * @return {boolean} The button is active
2302 */
2303 OO.ui.mixin.ButtonElement.prototype.isActive = function () {
2304 return this.active;
2305 };
2306
2307 /**
2308 * Any OOjs UI widget that contains other widgets (such as {@link OO.ui.ButtonWidget buttons} or
2309 * {@link OO.ui.OptionWidget options}) mixes in GroupElement. Adding, removing, and clearing
2310 * items from the group is done through the interface the class provides.
2311 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
2312 *
2313 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Groups
2314 *
2315 * @abstract
2316 * @mixins OO.EmitterList
2317 * @class
2318 *
2319 * @constructor
2320 * @param {Object} [config] Configuration options
2321 * @cfg {jQuery} [$group] The container element created by the class. If this configuration
2322 * is omitted, the group element will use a generated `<div>`.
2323 */
2324 OO.ui.mixin.GroupElement = function OoUiMixinGroupElement( config ) {
2325 // Configuration initialization
2326 config = config || {};
2327
2328 // Mixin constructors
2329 OO.EmitterList.call( this, config );
2330
2331 // Properties
2332 this.$group = null;
2333
2334 // Initialization
2335 this.setGroupElement( config.$group || $( '<div>' ) );
2336 };
2337
2338 /* Setup */
2339
2340 OO.mixinClass( OO.ui.mixin.GroupElement, OO.EmitterList );
2341
2342 /* Events */
2343
2344 /**
2345 * @event change
2346 *
2347 * A change event is emitted when the set of selected items changes.
2348 *
2349 * @param {OO.ui.Element[]} items Items currently in the group
2350 */
2351
2352 /* Methods */
2353
2354 /**
2355 * Set the group element.
2356 *
2357 * If an element is already set, items will be moved to the new element.
2358 *
2359 * @param {jQuery} $group Element to use as group
2360 */
2361 OO.ui.mixin.GroupElement.prototype.setGroupElement = function ( $group ) {
2362 var i, len;
2363
2364 this.$group = $group;
2365 for ( i = 0, len = this.items.length; i < len; i++ ) {
2366 this.$group.append( this.items[ i ].$element );
2367 }
2368 };
2369
2370 /**
2371 * Get an item by its data.
2372 *
2373 * Only the first item with matching data will be returned. To return all matching items,
2374 * use the #getItemsFromData method.
2375 *
2376 * @param {Object} data Item data to search for
2377 * @return {OO.ui.Element|null} Item with equivalent data, `null` if none exists
2378 */
2379 OO.ui.mixin.GroupElement.prototype.getItemFromData = function ( data ) {
2380 var i, len, item,
2381 hash = OO.getHash( data );
2382
2383 for ( i = 0, len = this.items.length; i < len; i++ ) {
2384 item = this.items[ i ];
2385 if ( hash === OO.getHash( item.getData() ) ) {
2386 return item;
2387 }
2388 }
2389
2390 return null;
2391 };
2392
2393 /**
2394 * Get items by their data.
2395 *
2396 * All items with matching data will be returned. To return only the first match, use the #getItemFromData method instead.
2397 *
2398 * @param {Object} data Item data to search for
2399 * @return {OO.ui.Element[]} Items with equivalent data
2400 */
2401 OO.ui.mixin.GroupElement.prototype.getItemsFromData = function ( data ) {
2402 var i, len, item,
2403 hash = OO.getHash( data ),
2404 items = [];
2405
2406 for ( i = 0, len = this.items.length; i < len; i++ ) {
2407 item = this.items[ i ];
2408 if ( hash === OO.getHash( item.getData() ) ) {
2409 items.push( item );
2410 }
2411 }
2412
2413 return items;
2414 };
2415
2416 /**
2417 * Add items to the group.
2418 *
2419 * Items will be added to the end of the group array unless the optional `index` parameter specifies
2420 * a different insertion point. Adding an existing item will move it to the end of the array or the point specified by the `index`.
2421 *
2422 * @param {OO.ui.Element[]} items An array of items to add to the group
2423 * @param {number} [index] Index of the insertion point
2424 * @chainable
2425 */
2426 OO.ui.mixin.GroupElement.prototype.addItems = function ( items, index ) {
2427 // Mixin method
2428 OO.EmitterList.prototype.addItems.call( this, items, index );
2429
2430 this.emit( 'change', this.getItems() );
2431 return this;
2432 };
2433
2434 /**
2435 * @inheritdoc
2436 */
2437 OO.ui.mixin.GroupElement.prototype.moveItem = function ( items, newIndex ) {
2438 // insertItemElements expects this.items to not have been modified yet, so call before the mixin
2439 this.insertItemElements( items, newIndex );
2440
2441 // Mixin method
2442 newIndex = OO.EmitterList.prototype.moveItem.call( this, items, newIndex );
2443
2444 return newIndex;
2445 };
2446
2447 /**
2448 * @inheritdoc
2449 */
2450 OO.ui.mixin.GroupElement.prototype.insertItem = function ( item, index ) {
2451 item.setElementGroup( this );
2452 this.insertItemElements( item, index );
2453
2454 // Mixin method
2455 index = OO.EmitterList.prototype.insertItem.call( this, item, index );
2456
2457 return index;
2458 };
2459
2460 /**
2461 * Insert elements into the group
2462 *
2463 * @private
2464 * @param {OO.ui.Element} itemWidget Item to insert
2465 * @param {number} index Insertion index
2466 */
2467 OO.ui.mixin.GroupElement.prototype.insertItemElements = function ( itemWidget, index ) {
2468 if ( index === undefined || index < 0 || index >= this.items.length ) {
2469 this.$group.append( itemWidget.$element );
2470 } else if ( index === 0 ) {
2471 this.$group.prepend( itemWidget.$element );
2472 } else {
2473 this.items[ index ].$element.before( itemWidget.$element );
2474 }
2475 };
2476
2477 /**
2478 * Remove the specified items from a group.
2479 *
2480 * Removed items are detached (not removed) from the DOM so that they may be reused.
2481 * To remove all items from a group, you may wish to use the #clearItems method instead.
2482 *
2483 * @param {OO.ui.Element[]} items An array of items to remove
2484 * @chainable
2485 */
2486 OO.ui.mixin.GroupElement.prototype.removeItems = function ( items ) {
2487 var i, len, item, index;
2488
2489 // Remove specific items elements
2490 for ( i = 0, len = items.length; i < len; i++ ) {
2491 item = items[ i ];
2492 index = this.items.indexOf( item );
2493 if ( index !== -1 ) {
2494 item.setElementGroup( null );
2495 item.$element.detach();
2496 }
2497 }
2498
2499 // Mixin method
2500 OO.EmitterList.prototype.removeItems.call( this, items );
2501
2502 this.emit( 'change', this.getItems() );
2503 return this;
2504 };
2505
2506 /**
2507 * Clear all items from the group.
2508 *
2509 * Cleared items are detached from the DOM, not removed, so that they may be reused.
2510 * To remove only a subset of items from a group, use the #removeItems method.
2511 *
2512 * @chainable
2513 */
2514 OO.ui.mixin.GroupElement.prototype.clearItems = function () {
2515 var i, len;
2516
2517 // Remove all item elements
2518 for ( i = 0, len = this.items.length; i < len; i++ ) {
2519 this.items[ i ].setElementGroup( null );
2520 this.items[ i ].$element.detach();
2521 }
2522
2523 // Mixin method
2524 OO.EmitterList.prototype.clearItems.call( this );
2525
2526 this.emit( 'change', this.getItems() );
2527 return this;
2528 };
2529
2530 /**
2531 * IconElement is often mixed into other classes to generate an icon.
2532 * Icons are graphics, about the size of normal text. They are used to aid the user
2533 * in locating a control or to convey information in a space-efficient way. See the
2534 * [OOjs UI documentation on MediaWiki] [1] for a list of icons
2535 * included in the library.
2536 *
2537 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
2538 *
2539 * @abstract
2540 * @class
2541 *
2542 * @constructor
2543 * @param {Object} [config] Configuration options
2544 * @cfg {jQuery} [$icon] The icon element created by the class. If this configuration is omitted,
2545 * the icon element will use a generated `<span>`. To use a different HTML tag, or to specify that
2546 * the icon element be set to an existing icon instead of the one generated by this class, set a
2547 * value using a jQuery selection. For example:
2548 *
2549 * // Use a <div> tag instead of a <span>
2550 * $icon: $("<div>")
2551 * // Use an existing icon element instead of the one generated by the class
2552 * $icon: this.$element
2553 * // Use an icon element from a child widget
2554 * $icon: this.childwidget.$element
2555 * @cfg {Object|string} [icon=''] The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of
2556 * symbolic names. A map is used for i18n purposes and contains a `default` icon
2557 * name and additional names keyed by language code. The `default` name is used when no icon is keyed
2558 * by the user's language.
2559 *
2560 * Example of an i18n map:
2561 *
2562 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
2563 * See the [OOjs UI documentation on MediaWiki] [2] for a list of icons included in the library.
2564 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
2565 * @cfg {string|Function} [iconTitle] A text string used as the icon title, or a function that returns title
2566 * text. The icon title is displayed when users move the mouse over the icon.
2567 */
2568 OO.ui.mixin.IconElement = function OoUiMixinIconElement( config ) {
2569 // Configuration initialization
2570 config = config || {};
2571
2572 // Properties
2573 this.$icon = null;
2574 this.icon = null;
2575 this.iconTitle = null;
2576
2577 // Initialization
2578 this.setIcon( config.icon || this.constructor.static.icon );
2579 this.setIconTitle( config.iconTitle || this.constructor.static.iconTitle );
2580 this.setIconElement( config.$icon || $( '<span>' ) );
2581 };
2582
2583 /* Setup */
2584
2585 OO.initClass( OO.ui.mixin.IconElement );
2586
2587 /* Static Properties */
2588
2589 /**
2590 * The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of symbolic names. A map is used
2591 * for i18n purposes and contains a `default` icon name and additional names keyed by
2592 * language code. The `default` name is used when no icon is keyed by the user's language.
2593 *
2594 * Example of an i18n map:
2595 *
2596 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
2597 *
2598 * Note: the static property will be overridden if the #icon configuration is used.
2599 *
2600 * @static
2601 * @inheritable
2602 * @property {Object|string}
2603 */
2604 OO.ui.mixin.IconElement.static.icon = null;
2605
2606 /**
2607 * The icon title, displayed when users move the mouse over the icon. The value can be text, a
2608 * function that returns title text, or `null` for no title.
2609 *
2610 * The static property will be overridden if the #iconTitle configuration is used.
2611 *
2612 * @static
2613 * @inheritable
2614 * @property {string|Function|null}
2615 */
2616 OO.ui.mixin.IconElement.static.iconTitle = null;
2617
2618 /* Methods */
2619
2620 /**
2621 * Set the icon element. This method is used to retarget an icon mixin so that its functionality
2622 * applies to the specified icon element instead of the one created by the class. If an icon
2623 * element is already set, the mixin’s effect on that element is removed. Generated CSS classes
2624 * and mixin methods will no longer affect the element.
2625 *
2626 * @param {jQuery} $icon Element to use as icon
2627 */
2628 OO.ui.mixin.IconElement.prototype.setIconElement = function ( $icon ) {
2629 if ( this.$icon ) {
2630 this.$icon
2631 .removeClass( 'oo-ui-iconElement-icon oo-ui-icon-' + this.icon )
2632 .removeAttr( 'title' );
2633 }
2634
2635 this.$icon = $icon
2636 .addClass( 'oo-ui-iconElement-icon' )
2637 .toggleClass( 'oo-ui-icon-' + this.icon, !!this.icon );
2638 if ( this.iconTitle !== null ) {
2639 this.$icon.attr( 'title', this.iconTitle );
2640 }
2641
2642 this.updateThemeClasses();
2643 };
2644
2645 /**
2646 * Set icon by symbolic name (e.g., ‘remove’ or ‘menu’). Use `null` to remove an icon.
2647 * The icon parameter can also be set to a map of icon names. See the #icon config setting
2648 * for an example.
2649 *
2650 * @param {Object|string|null} icon A symbolic icon name, a {@link #icon map of icon names} keyed
2651 * by language code, or `null` to remove the icon.
2652 * @chainable
2653 */
2654 OO.ui.mixin.IconElement.prototype.setIcon = function ( icon ) {
2655 icon = OO.isPlainObject( icon ) ? OO.ui.getLocalValue( icon, null, 'default' ) : icon;
2656 icon = typeof icon === 'string' && icon.trim().length ? icon.trim() : null;
2657
2658 if ( this.icon !== icon ) {
2659 if ( this.$icon ) {
2660 if ( this.icon !== null ) {
2661 this.$icon.removeClass( 'oo-ui-icon-' + this.icon );
2662 }
2663 if ( icon !== null ) {
2664 this.$icon.addClass( 'oo-ui-icon-' + icon );
2665 }
2666 }
2667 this.icon = icon;
2668 }
2669
2670 this.$element.toggleClass( 'oo-ui-iconElement', !!this.icon );
2671 this.updateThemeClasses();
2672
2673 return this;
2674 };
2675
2676 /**
2677 * Set the icon title. Use `null` to remove the title.
2678 *
2679 * @param {string|Function|null} iconTitle A text string used as the icon title,
2680 * a function that returns title text, or `null` for no title.
2681 * @chainable
2682 */
2683 OO.ui.mixin.IconElement.prototype.setIconTitle = function ( iconTitle ) {
2684 iconTitle =
2685 ( typeof iconTitle === 'function' || ( typeof iconTitle === 'string' && iconTitle.length ) ) ?
2686 OO.ui.resolveMsg( iconTitle ) : null;
2687
2688 if ( this.iconTitle !== iconTitle ) {
2689 this.iconTitle = iconTitle;
2690 if ( this.$icon ) {
2691 if ( this.iconTitle !== null ) {
2692 this.$icon.attr( 'title', iconTitle );
2693 } else {
2694 this.$icon.removeAttr( 'title' );
2695 }
2696 }
2697 }
2698
2699 return this;
2700 };
2701
2702 /**
2703 * Get the symbolic name of the icon.
2704 *
2705 * @return {string} Icon name
2706 */
2707 OO.ui.mixin.IconElement.prototype.getIcon = function () {
2708 return this.icon;
2709 };
2710
2711 /**
2712 * Get the icon title. The title text is displayed when a user moves the mouse over the icon.
2713 *
2714 * @return {string} Icon title text
2715 */
2716 OO.ui.mixin.IconElement.prototype.getIconTitle = function () {
2717 return this.iconTitle;
2718 };
2719
2720 /**
2721 * IndicatorElement is often mixed into other classes to generate an indicator.
2722 * Indicators are small graphics that are generally used in two ways:
2723 *
2724 * - To draw attention to the status of an item. For example, an indicator might be
2725 * used to show that an item in a list has errors that need to be resolved.
2726 * - To clarify the function of a control that acts in an exceptional way (a button
2727 * that opens a menu instead of performing an action directly, for example).
2728 *
2729 * For a list of indicators included in the library, please see the
2730 * [OOjs UI documentation on MediaWiki] [1].
2731 *
2732 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
2733 *
2734 * @abstract
2735 * @class
2736 *
2737 * @constructor
2738 * @param {Object} [config] Configuration options
2739 * @cfg {jQuery} [$indicator] The indicator element created by the class. If this
2740 * configuration is omitted, the indicator element will use a generated `<span>`.
2741 * @cfg {string} [indicator] Symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
2742 * See the [OOjs UI documentation on MediaWiki][2] for a list of indicators included
2743 * in the library.
2744 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
2745 * @cfg {string|Function} [indicatorTitle] A text string used as the indicator title,
2746 * or a function that returns title text. The indicator title is displayed when users move
2747 * the mouse over the indicator.
2748 */
2749 OO.ui.mixin.IndicatorElement = function OoUiMixinIndicatorElement( config ) {
2750 // Configuration initialization
2751 config = config || {};
2752
2753 // Properties
2754 this.$indicator = null;
2755 this.indicator = null;
2756 this.indicatorTitle = null;
2757
2758 // Initialization
2759 this.setIndicator( config.indicator || this.constructor.static.indicator );
2760 this.setIndicatorTitle( config.indicatorTitle || this.constructor.static.indicatorTitle );
2761 this.setIndicatorElement( config.$indicator || $( '<span>' ) );
2762 };
2763
2764 /* Setup */
2765
2766 OO.initClass( OO.ui.mixin.IndicatorElement );
2767
2768 /* Static Properties */
2769
2770 /**
2771 * Symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
2772 * The static property will be overridden if the #indicator configuration is used.
2773 *
2774 * @static
2775 * @inheritable
2776 * @property {string|null}
2777 */
2778 OO.ui.mixin.IndicatorElement.static.indicator = null;
2779
2780 /**
2781 * A text string used as the indicator title, a function that returns title text, or `null`
2782 * for no title. The static property will be overridden if the #indicatorTitle configuration is used.
2783 *
2784 * @static
2785 * @inheritable
2786 * @property {string|Function|null}
2787 */
2788 OO.ui.mixin.IndicatorElement.static.indicatorTitle = null;
2789
2790 /* Methods */
2791
2792 /**
2793 * Set the indicator element.
2794 *
2795 * If an element is already set, it will be cleaned up before setting up the new element.
2796 *
2797 * @param {jQuery} $indicator Element to use as indicator
2798 */
2799 OO.ui.mixin.IndicatorElement.prototype.setIndicatorElement = function ( $indicator ) {
2800 if ( this.$indicator ) {
2801 this.$indicator
2802 .removeClass( 'oo-ui-indicatorElement-indicator oo-ui-indicator-' + this.indicator )
2803 .removeAttr( 'title' );
2804 }
2805
2806 this.$indicator = $indicator
2807 .addClass( 'oo-ui-indicatorElement-indicator' )
2808 .toggleClass( 'oo-ui-indicator-' + this.indicator, !!this.indicator );
2809 if ( this.indicatorTitle !== null ) {
2810 this.$indicator.attr( 'title', this.indicatorTitle );
2811 }
2812
2813 this.updateThemeClasses();
2814 };
2815
2816 /**
2817 * Set the indicator by its symbolic name: ‘alert’, ‘down’, ‘next’, ‘previous’, ‘required’, ‘up’. Use `null` to remove the indicator.
2818 *
2819 * @param {string|null} indicator Symbolic name of indicator, or `null` for no indicator
2820 * @chainable
2821 */
2822 OO.ui.mixin.IndicatorElement.prototype.setIndicator = function ( indicator ) {
2823 indicator = typeof indicator === 'string' && indicator.length ? indicator.trim() : null;
2824
2825 if ( this.indicator !== indicator ) {
2826 if ( this.$indicator ) {
2827 if ( this.indicator !== null ) {
2828 this.$indicator.removeClass( 'oo-ui-indicator-' + this.indicator );
2829 }
2830 if ( indicator !== null ) {
2831 this.$indicator.addClass( 'oo-ui-indicator-' + indicator );
2832 }
2833 }
2834 this.indicator = indicator;
2835 }
2836
2837 this.$element.toggleClass( 'oo-ui-indicatorElement', !!this.indicator );
2838 this.updateThemeClasses();
2839
2840 return this;
2841 };
2842
2843 /**
2844 * Set the indicator title.
2845 *
2846 * The title is displayed when a user moves the mouse over the indicator.
2847 *
2848 * @param {string|Function|null} indicatorTitle Indicator title text, a function that returns text, or
2849 * `null` for no indicator title
2850 * @chainable
2851 */
2852 OO.ui.mixin.IndicatorElement.prototype.setIndicatorTitle = function ( indicatorTitle ) {
2853 indicatorTitle =
2854 ( typeof indicatorTitle === 'function' || ( typeof indicatorTitle === 'string' && indicatorTitle.length ) ) ?
2855 OO.ui.resolveMsg( indicatorTitle ) : null;
2856
2857 if ( this.indicatorTitle !== indicatorTitle ) {
2858 this.indicatorTitle = indicatorTitle;
2859 if ( this.$indicator ) {
2860 if ( this.indicatorTitle !== null ) {
2861 this.$indicator.attr( 'title', indicatorTitle );
2862 } else {
2863 this.$indicator.removeAttr( 'title' );
2864 }
2865 }
2866 }
2867
2868 return this;
2869 };
2870
2871 /**
2872 * Get the symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
2873 *
2874 * @return {string} Symbolic name of indicator
2875 */
2876 OO.ui.mixin.IndicatorElement.prototype.getIndicator = function () {
2877 return this.indicator;
2878 };
2879
2880 /**
2881 * Get the indicator title.
2882 *
2883 * The title is displayed when a user moves the mouse over the indicator.
2884 *
2885 * @return {string} Indicator title text
2886 */
2887 OO.ui.mixin.IndicatorElement.prototype.getIndicatorTitle = function () {
2888 return this.indicatorTitle;
2889 };
2890
2891 /**
2892 * LabelElement is often mixed into other classes to generate a label, which
2893 * helps identify the function of an interface element.
2894 * See the [OOjs UI documentation on MediaWiki] [1] for more information.
2895 *
2896 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Labels
2897 *
2898 * @abstract
2899 * @class
2900 *
2901 * @constructor
2902 * @param {Object} [config] Configuration options
2903 * @cfg {jQuery} [$label] The label element created by the class. If this
2904 * configuration is omitted, the label element will use a generated `<span>`.
2905 * @cfg {jQuery|string|Function|OO.ui.HtmlSnippet} [label] The label text. The label can be specified
2906 * as a plaintext string, a jQuery selection of elements, or a function that will produce a string
2907 * in the future. See the [OOjs UI documentation on MediaWiki] [2] for examples.
2908 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Labels
2909 */
2910 OO.ui.mixin.LabelElement = function OoUiMixinLabelElement( config ) {
2911 // Configuration initialization
2912 config = config || {};
2913
2914 // Properties
2915 this.$label = null;
2916 this.label = null;
2917
2918 // Initialization
2919 this.setLabel( config.label || this.constructor.static.label );
2920 this.setLabelElement( config.$label || $( '<span>' ) );
2921 };
2922
2923 /* Setup */
2924
2925 OO.initClass( OO.ui.mixin.LabelElement );
2926
2927 /* Events */
2928
2929 /**
2930 * @event labelChange
2931 * @param {string} value
2932 */
2933
2934 /* Static Properties */
2935
2936 /**
2937 * The label text. The label can be specified as a plaintext string, a function that will
2938 * produce a string in the future, or `null` for no label. The static value will
2939 * be overridden if a label is specified with the #label config option.
2940 *
2941 * @static
2942 * @inheritable
2943 * @property {string|Function|null}
2944 */
2945 OO.ui.mixin.LabelElement.static.label = null;
2946
2947 /* Static methods */
2948
2949 /**
2950 * Highlight the first occurrence of the query in the given text
2951 *
2952 * @param {string} text Text
2953 * @param {string} query Query to find
2954 * @return {jQuery} Text with the first match of the query
2955 * sub-string wrapped in highlighted span
2956 */
2957 OO.ui.mixin.LabelElement.static.highlightQuery = function ( text, query ) {
2958 var $result = $( '<span>' ),
2959 offset = text.toLowerCase().indexOf( query.toLowerCase() );
2960
2961 if ( !query.length || offset === -1 ) {
2962 return $result.text( text );
2963 }
2964 $result.append(
2965 document.createTextNode( text.slice( 0, offset ) ),
2966 $( '<span>' )
2967 .addClass( 'oo-ui-labelElement-label-highlight' )
2968 .text( text.slice( offset, offset + query.length ) ),
2969 document.createTextNode( text.slice( offset + query.length ) )
2970 );
2971 return $result.contents();
2972 };
2973
2974 /* Methods */
2975
2976 /**
2977 * Set the label element.
2978 *
2979 * If an element is already set, it will be cleaned up before setting up the new element.
2980 *
2981 * @param {jQuery} $label Element to use as label
2982 */
2983 OO.ui.mixin.LabelElement.prototype.setLabelElement = function ( $label ) {
2984 if ( this.$label ) {
2985 this.$label.removeClass( 'oo-ui-labelElement-label' ).empty();
2986 }
2987
2988 this.$label = $label.addClass( 'oo-ui-labelElement-label' );
2989 this.setLabelContent( this.label );
2990 };
2991
2992 /**
2993 * Set the label.
2994 *
2995 * An empty string will result in the label being hidden. A string containing only whitespace will
2996 * be converted to a single `&nbsp;`.
2997 *
2998 * @param {jQuery|string|OO.ui.HtmlSnippet|Function|null} label Label nodes; text; a function that returns nodes or
2999 * text; or null for no label
3000 * @chainable
3001 */
3002 OO.ui.mixin.LabelElement.prototype.setLabel = function ( label ) {
3003 label = typeof label === 'function' ? OO.ui.resolveMsg( label ) : label;
3004 label = ( ( typeof label === 'string' || label instanceof jQuery ) && label.length ) || ( label instanceof OO.ui.HtmlSnippet && label.toString().length ) ? label : null;
3005
3006 if ( this.label !== label ) {
3007 if ( this.$label ) {
3008 this.setLabelContent( label );
3009 }
3010 this.label = label;
3011 this.emit( 'labelChange' );
3012 }
3013
3014 this.$element.toggleClass( 'oo-ui-labelElement', !!this.label );
3015
3016 return this;
3017 };
3018
3019 /**
3020 * Set the label as plain text with a highlighted query
3021 *
3022 * @param {string} text Text label to set
3023 * @param {string} query Substring of text to highlight
3024 * @chainable
3025 */
3026 OO.ui.mixin.LabelElement.prototype.setHighlightedQuery = function ( text, query ) {
3027 return this.setLabel( this.constructor.static.highlightQuery( text, query ) );
3028 };
3029
3030 /**
3031 * Get the label.
3032 *
3033 * @return {jQuery|string|Function|null} Label nodes; text; a function that returns nodes or
3034 * text; or null for no label
3035 */
3036 OO.ui.mixin.LabelElement.prototype.getLabel = function () {
3037 return this.label;
3038 };
3039
3040 /**
3041 * Set the content of the label.
3042 *
3043 * Do not call this method until after the label element has been set by #setLabelElement.
3044 *
3045 * @private
3046 * @param {jQuery|string|Function|null} label Label nodes; text; a function that returns nodes or
3047 * text; or null for no label
3048 */
3049 OO.ui.mixin.LabelElement.prototype.setLabelContent = function ( label ) {
3050 if ( typeof label === 'string' ) {
3051 if ( label.match( /^\s*$/ ) ) {
3052 // Convert whitespace only string to a single non-breaking space
3053 this.$label.html( '&nbsp;' );
3054 } else {
3055 this.$label.text( label );
3056 }
3057 } else if ( label instanceof OO.ui.HtmlSnippet ) {
3058 this.$label.html( label.toString() );
3059 } else if ( label instanceof jQuery ) {
3060 this.$label.empty().append( label );
3061 } else {
3062 this.$label.empty();
3063 }
3064 };
3065
3066 /**
3067 * The FlaggedElement class is an attribute mixin, meaning that it is used to add
3068 * additional functionality to an element created by another class. The class provides
3069 * a ‘flags’ property assigned the name (or an array of names) of styling flags,
3070 * which are used to customize the look and feel of a widget to better describe its
3071 * importance and functionality.
3072 *
3073 * The library currently contains the following styling flags for general use:
3074 *
3075 * - **progressive**: Progressive styling is applied to convey that the widget will move the user forward in a process.
3076 * - **destructive**: Destructive styling is applied to convey that the widget will remove something.
3077 * - **constructive**: Constructive styling is applied to convey that the widget will create something.
3078 *
3079 * The flags affect the appearance of the buttons:
3080 *
3081 * @example
3082 * // FlaggedElement is mixed into ButtonWidget to provide styling flags
3083 * var button1 = new OO.ui.ButtonWidget( {
3084 * label: 'Constructive',
3085 * flags: 'constructive'
3086 * } );
3087 * var button2 = new OO.ui.ButtonWidget( {
3088 * label: 'Destructive',
3089 * flags: 'destructive'
3090 * } );
3091 * var button3 = new OO.ui.ButtonWidget( {
3092 * label: 'Progressive',
3093 * flags: 'progressive'
3094 * } );
3095 * $( 'body' ).append( button1.$element, button2.$element, button3.$element );
3096 *
3097 * {@link OO.ui.ActionWidget ActionWidgets}, which are a special kind of button that execute an action, use these flags: **primary** and **safe**.
3098 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information.
3099 *
3100 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Flagged
3101 *
3102 * @abstract
3103 * @class
3104 *
3105 * @constructor
3106 * @param {Object} [config] Configuration options
3107 * @cfg {string|string[]} [flags] The name or names of the flags (e.g., 'constructive' or 'primary') to apply.
3108 * Please see the [OOjs UI documentation on MediaWiki] [2] for more information about available flags.
3109 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Flagged
3110 * @cfg {jQuery} [$flagged] The flagged element. By default,
3111 * the flagged functionality is applied to the element created by the class ($element).
3112 * If a different element is specified, the flagged functionality will be applied to it instead.
3113 */
3114 OO.ui.mixin.FlaggedElement = function OoUiMixinFlaggedElement( config ) {
3115 // Configuration initialization
3116 config = config || {};
3117
3118 // Properties
3119 this.flags = {};
3120 this.$flagged = null;
3121
3122 // Initialization
3123 this.setFlags( config.flags );
3124 this.setFlaggedElement( config.$flagged || this.$element );
3125 };
3126
3127 /* Events */
3128
3129 /**
3130 * @event flag
3131 * A flag event is emitted when the #clearFlags or #setFlags methods are used. The `changes`
3132 * parameter contains the name of each modified flag and indicates whether it was
3133 * added or removed.
3134 *
3135 * @param {Object.<string,boolean>} changes Object keyed by flag name. A Boolean `true` indicates
3136 * that the flag was added, `false` that the flag was removed.
3137 */
3138
3139 /* Methods */
3140
3141 /**
3142 * Set the flagged element.
3143 *
3144 * This method is used to retarget a flagged mixin so that its functionality applies to the specified element.
3145 * If an element is already set, the method will remove the mixin’s effect on that element.
3146 *
3147 * @param {jQuery} $flagged Element that should be flagged
3148 */
3149 OO.ui.mixin.FlaggedElement.prototype.setFlaggedElement = function ( $flagged ) {
3150 var classNames = Object.keys( this.flags ).map( function ( flag ) {
3151 return 'oo-ui-flaggedElement-' + flag;
3152 } ).join( ' ' );
3153
3154 if ( this.$flagged ) {
3155 this.$flagged.removeClass( classNames );
3156 }
3157
3158 this.$flagged = $flagged.addClass( classNames );
3159 };
3160
3161 /**
3162 * Check if the specified flag is set.
3163 *
3164 * @param {string} flag Name of flag
3165 * @return {boolean} The flag is set
3166 */
3167 OO.ui.mixin.FlaggedElement.prototype.hasFlag = function ( flag ) {
3168 // This may be called before the constructor, thus before this.flags is set
3169 return this.flags && ( flag in this.flags );
3170 };
3171
3172 /**
3173 * Get the names of all flags set.
3174 *
3175 * @return {string[]} Flag names
3176 */
3177 OO.ui.mixin.FlaggedElement.prototype.getFlags = function () {
3178 // This may be called before the constructor, thus before this.flags is set
3179 return Object.keys( this.flags || {} );
3180 };
3181
3182 /**
3183 * Clear all flags.
3184 *
3185 * @chainable
3186 * @fires flag
3187 */
3188 OO.ui.mixin.FlaggedElement.prototype.clearFlags = function () {
3189 var flag, className,
3190 changes = {},
3191 remove = [],
3192 classPrefix = 'oo-ui-flaggedElement-';
3193
3194 for ( flag in this.flags ) {
3195 className = classPrefix + flag;
3196 changes[ flag ] = false;
3197 delete this.flags[ flag ];
3198 remove.push( className );
3199 }
3200
3201 if ( this.$flagged ) {
3202 this.$flagged.removeClass( remove.join( ' ' ) );
3203 }
3204
3205 this.updateThemeClasses();
3206 this.emit( 'flag', changes );
3207
3208 return this;
3209 };
3210
3211 /**
3212 * Add one or more flags.
3213 *
3214 * @param {string|string[]|Object.<string, boolean>} flags A flag name, an array of flag names,
3215 * or an object keyed by flag name with a boolean value that indicates whether the flag should
3216 * be added (`true`) or removed (`false`).
3217 * @chainable
3218 * @fires flag
3219 */
3220 OO.ui.mixin.FlaggedElement.prototype.setFlags = function ( flags ) {
3221 var i, len, flag, className,
3222 changes = {},
3223 add = [],
3224 remove = [],
3225 classPrefix = 'oo-ui-flaggedElement-';
3226
3227 if ( typeof flags === 'string' ) {
3228 className = classPrefix + flags;
3229 // Set
3230 if ( !this.flags[ flags ] ) {
3231 this.flags[ flags ] = true;
3232 add.push( className );
3233 }
3234 } else if ( Array.isArray( flags ) ) {
3235 for ( i = 0, len = flags.length; i < len; i++ ) {
3236 flag = flags[ i ];
3237 className = classPrefix + flag;
3238 // Set
3239 if ( !this.flags[ flag ] ) {
3240 changes[ flag ] = true;
3241 this.flags[ flag ] = true;
3242 add.push( className );
3243 }
3244 }
3245 } else if ( OO.isPlainObject( flags ) ) {
3246 for ( flag in flags ) {
3247 className = classPrefix + flag;
3248 if ( flags[ flag ] ) {
3249 // Set
3250 if ( !this.flags[ flag ] ) {
3251 changes[ flag ] = true;
3252 this.flags[ flag ] = true;
3253 add.push( className );
3254 }
3255 } else {
3256 // Remove
3257 if ( this.flags[ flag ] ) {
3258 changes[ flag ] = false;
3259 delete this.flags[ flag ];
3260 remove.push( className );
3261 }
3262 }
3263 }
3264 }
3265
3266 if ( this.$flagged ) {
3267 this.$flagged
3268 .addClass( add.join( ' ' ) )
3269 .removeClass( remove.join( ' ' ) );
3270 }
3271
3272 this.updateThemeClasses();
3273 this.emit( 'flag', changes );
3274
3275 return this;
3276 };
3277
3278 /**
3279 * TitledElement is mixed into other classes to provide a `title` attribute.
3280 * Titles are rendered by the browser and are made visible when the user moves
3281 * the mouse over the element. Titles are not visible on touch devices.
3282 *
3283 * @example
3284 * // TitledElement provides a 'title' attribute to the
3285 * // ButtonWidget class
3286 * var button = new OO.ui.ButtonWidget( {
3287 * label: 'Button with Title',
3288 * title: 'I am a button'
3289 * } );
3290 * $( 'body' ).append( button.$element );
3291 *
3292 * @abstract
3293 * @class
3294 *
3295 * @constructor
3296 * @param {Object} [config] Configuration options
3297 * @cfg {jQuery} [$titled] The element to which the `title` attribute is applied.
3298 * If this config is omitted, the title functionality is applied to $element, the
3299 * element created by the class.
3300 * @cfg {string|Function} [title] The title text or a function that returns text. If
3301 * this config is omitted, the value of the {@link #static-title static title} property is used.
3302 */
3303 OO.ui.mixin.TitledElement = function OoUiMixinTitledElement( config ) {
3304 // Configuration initialization
3305 config = config || {};
3306
3307 // Properties
3308 this.$titled = null;
3309 this.title = null;
3310
3311 // Initialization
3312 this.setTitle( config.title !== undefined ? config.title : this.constructor.static.title );
3313 this.setTitledElement( config.$titled || this.$element );
3314 };
3315
3316 /* Setup */
3317
3318 OO.initClass( OO.ui.mixin.TitledElement );
3319
3320 /* Static Properties */
3321
3322 /**
3323 * The title text, a function that returns text, or `null` for no title. The value of the static property
3324 * is overridden if the #title config option is used.
3325 *
3326 * @static
3327 * @inheritable
3328 * @property {string|Function|null}
3329 */
3330 OO.ui.mixin.TitledElement.static.title = null;
3331
3332 /* Methods */
3333
3334 /**
3335 * Set the titled element.
3336 *
3337 * This method is used to retarget a titledElement mixin so that its functionality applies to the specified element.
3338 * If an element is already set, the mixin’s effect on that element is removed before the new element is set up.
3339 *
3340 * @param {jQuery} $titled Element that should use the 'titled' functionality
3341 */
3342 OO.ui.mixin.TitledElement.prototype.setTitledElement = function ( $titled ) {
3343 if ( this.$titled ) {
3344 this.$titled.removeAttr( 'title' );
3345 }
3346
3347 this.$titled = $titled;
3348 if ( this.title ) {
3349 this.updateTitle();
3350 }
3351 };
3352
3353 /**
3354 * Set title.
3355 *
3356 * @param {string|Function|null} title Title text, a function that returns text, or `null` for no title
3357 * @chainable
3358 */
3359 OO.ui.mixin.TitledElement.prototype.setTitle = function ( title ) {
3360 title = typeof title === 'function' ? OO.ui.resolveMsg( title ) : title;
3361 title = ( typeof title === 'string' && title.length ) ? title : null;
3362
3363 if ( this.title !== title ) {
3364 this.title = title;
3365 this.updateTitle();
3366 }
3367
3368 return this;
3369 };
3370
3371 /**
3372 * Update the title attribute, in case of changes to title or accessKey.
3373 *
3374 * @protected
3375 * @chainable
3376 */
3377 OO.ui.mixin.TitledElement.prototype.updateTitle = function () {
3378 var title = this.getTitle();
3379 if ( this.$titled ) {
3380 if ( title !== null ) {
3381 // Only if this is an AccessKeyedElement
3382 if ( this.formatTitleWithAccessKey ) {
3383 title = this.formatTitleWithAccessKey( title );
3384 }
3385 this.$titled.attr( 'title', title );
3386 } else {
3387 this.$titled.removeAttr( 'title' );
3388 }
3389 }
3390 return this;
3391 };
3392
3393 /**
3394 * Get title.
3395 *
3396 * @return {string} Title string
3397 */
3398 OO.ui.mixin.TitledElement.prototype.getTitle = function () {
3399 return this.title;
3400 };
3401
3402 /**
3403 * AccessKeyedElement is mixed into other classes to provide an `accesskey` attribute.
3404 * Accesskeys allow an user to go to a specific element by using
3405 * a shortcut combination of a browser specific keys + the key
3406 * set to the field.
3407 *
3408 * @example
3409 * // AccessKeyedElement provides an 'accesskey' attribute to the
3410 * // ButtonWidget class
3411 * var button = new OO.ui.ButtonWidget( {
3412 * label: 'Button with Accesskey',
3413 * accessKey: 'k'
3414 * } );
3415 * $( 'body' ).append( button.$element );
3416 *
3417 * @abstract
3418 * @class
3419 *
3420 * @constructor
3421 * @param {Object} [config] Configuration options
3422 * @cfg {jQuery} [$accessKeyed] The element to which the `accesskey` attribute is applied.
3423 * If this config is omitted, the accesskey functionality is applied to $element, the
3424 * element created by the class.
3425 * @cfg {string|Function} [accessKey] The key or a function that returns the key. If
3426 * this config is omitted, no accesskey will be added.
3427 */
3428 OO.ui.mixin.AccessKeyedElement = function OoUiMixinAccessKeyedElement( config ) {
3429 // Configuration initialization
3430 config = config || {};
3431
3432 // Properties
3433 this.$accessKeyed = null;
3434 this.accessKey = null;
3435
3436 // Initialization
3437 this.setAccessKey( config.accessKey || null );
3438 this.setAccessKeyedElement( config.$accessKeyed || this.$element );
3439
3440 // If this is also a TitledElement and it initialized before we did, we may have
3441 // to update the title with the access key
3442 if ( this.updateTitle ) {
3443 this.updateTitle();
3444 }
3445 };
3446
3447 /* Setup */
3448
3449 OO.initClass( OO.ui.mixin.AccessKeyedElement );
3450
3451 /* Static Properties */
3452
3453 /**
3454 * The access key, a function that returns a key, or `null` for no accesskey.
3455 *
3456 * @static
3457 * @inheritable
3458 * @property {string|Function|null}
3459 */
3460 OO.ui.mixin.AccessKeyedElement.static.accessKey = null;
3461
3462 /* Methods */
3463
3464 /**
3465 * Set the accesskeyed element.
3466 *
3467 * This method is used to retarget a AccessKeyedElement mixin so that its functionality applies to the specified element.
3468 * If an element is already set, the mixin's effect on that element is removed before the new element is set up.
3469 *
3470 * @param {jQuery} $accessKeyed Element that should use the 'accesskeyes' functionality
3471 */
3472 OO.ui.mixin.AccessKeyedElement.prototype.setAccessKeyedElement = function ( $accessKeyed ) {
3473 if ( this.$accessKeyed ) {
3474 this.$accessKeyed.removeAttr( 'accesskey' );
3475 }
3476
3477 this.$accessKeyed = $accessKeyed;
3478 if ( this.accessKey ) {
3479 this.$accessKeyed.attr( 'accesskey', this.accessKey );
3480 }
3481 };
3482
3483 /**
3484 * Set accesskey.
3485 *
3486 * @param {string|Function|null} accessKey Key, a function that returns a key, or `null` for no accesskey
3487 * @chainable
3488 */
3489 OO.ui.mixin.AccessKeyedElement.prototype.setAccessKey = function ( accessKey ) {
3490 accessKey = typeof accessKey === 'string' ? OO.ui.resolveMsg( accessKey ) : null;
3491
3492 if ( this.accessKey !== accessKey ) {
3493 if ( this.$accessKeyed ) {
3494 if ( accessKey !== null ) {
3495 this.$accessKeyed.attr( 'accesskey', accessKey );
3496 } else {
3497 this.$accessKeyed.removeAttr( 'accesskey' );
3498 }
3499 }
3500 this.accessKey = accessKey;
3501
3502 // Only if this is a TitledElement
3503 if ( this.updateTitle ) {
3504 this.updateTitle();
3505 }
3506 }
3507
3508 return this;
3509 };
3510
3511 /**
3512 * Get accesskey.
3513 *
3514 * @return {string} accessKey string
3515 */
3516 OO.ui.mixin.AccessKeyedElement.prototype.getAccessKey = function () {
3517 return this.accessKey;
3518 };
3519
3520 /**
3521 * Add information about the access key to the element's tooltip label.
3522 * (This is only public for hacky usage in FieldLayout.)
3523 *
3524 * @param {string} title Tooltip label for `title` attribute
3525 * @return {string}
3526 */
3527 OO.ui.mixin.AccessKeyedElement.prototype.formatTitleWithAccessKey = function ( title ) {
3528 var accessKey;
3529
3530 if ( !this.$accessKeyed ) {
3531 // Not initialized yet; the constructor will call updateTitle() which will rerun this function
3532 return title;
3533 }
3534 // Use jquery.accessKeyLabel if available to show modifiers, otherwise just display the single key
3535 if ( $.fn.updateTooltipAccessKeys && $.fn.updateTooltipAccessKeys.getAccessKeyLabel ) {
3536 accessKey = $.fn.updateTooltipAccessKeys.getAccessKeyLabel( this.$accessKeyed[ 0 ] );
3537 } else {
3538 accessKey = this.getAccessKey();
3539 }
3540 if ( accessKey ) {
3541 title += ' [' + accessKey + ']';
3542 }
3543 return title;
3544 };
3545
3546 /**
3547 * ButtonWidget is a generic widget for buttons. A wide variety of looks,
3548 * feels, and functionality can be customized via the class’s configuration options
3549 * and methods. Please see the [OOjs UI documentation on MediaWiki] [1] for more information
3550 * and examples.
3551 *
3552 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches
3553 *
3554 * @example
3555 * // A button widget
3556 * var button = new OO.ui.ButtonWidget( {
3557 * label: 'Button with Icon',
3558 * icon: 'trash',
3559 * iconTitle: 'Remove'
3560 * } );
3561 * $( 'body' ).append( button.$element );
3562 *
3563 * NOTE: HTML form buttons should use the OO.ui.ButtonInputWidget class.
3564 *
3565 * @class
3566 * @extends OO.ui.Widget
3567 * @mixins OO.ui.mixin.ButtonElement
3568 * @mixins OO.ui.mixin.IconElement
3569 * @mixins OO.ui.mixin.IndicatorElement
3570 * @mixins OO.ui.mixin.LabelElement
3571 * @mixins OO.ui.mixin.TitledElement
3572 * @mixins OO.ui.mixin.FlaggedElement
3573 * @mixins OO.ui.mixin.TabIndexedElement
3574 * @mixins OO.ui.mixin.AccessKeyedElement
3575 *
3576 * @constructor
3577 * @param {Object} [config] Configuration options
3578 * @cfg {boolean} [active=false] Whether button should be shown as active
3579 * @cfg {string} [href] Hyperlink to visit when the button is clicked.
3580 * @cfg {string} [target] The frame or window in which to open the hyperlink.
3581 * @cfg {boolean} [noFollow] Search engine traversal hint (default: true)
3582 */
3583 OO.ui.ButtonWidget = function OoUiButtonWidget( config ) {
3584 // Configuration initialization
3585 config = config || {};
3586
3587 // Parent constructor
3588 OO.ui.ButtonWidget.parent.call( this, config );
3589
3590 // Mixin constructors
3591 OO.ui.mixin.ButtonElement.call( this, config );
3592 OO.ui.mixin.IconElement.call( this, config );
3593 OO.ui.mixin.IndicatorElement.call( this, config );
3594 OO.ui.mixin.LabelElement.call( this, config );
3595 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$button } ) );
3596 OO.ui.mixin.FlaggedElement.call( this, config );
3597 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$button } ) );
3598 OO.ui.mixin.AccessKeyedElement.call( this, $.extend( {}, config, { $accessKeyed: this.$button } ) );
3599
3600 // Properties
3601 this.href = null;
3602 this.target = null;
3603 this.noFollow = false;
3604
3605 // Events
3606 this.connect( this, { disable: 'onDisable' } );
3607
3608 // Initialization
3609 this.$button.append( this.$icon, this.$label, this.$indicator );
3610 this.$element
3611 .addClass( 'oo-ui-buttonWidget' )
3612 .append( this.$button );
3613 this.setActive( config.active );
3614 this.setHref( config.href );
3615 this.setTarget( config.target );
3616 this.setNoFollow( config.noFollow );
3617 };
3618
3619 /* Setup */
3620
3621 OO.inheritClass( OO.ui.ButtonWidget, OO.ui.Widget );
3622 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.ButtonElement );
3623 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.IconElement );
3624 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.IndicatorElement );
3625 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.LabelElement );
3626 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.TitledElement );
3627 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.FlaggedElement );
3628 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.TabIndexedElement );
3629 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.AccessKeyedElement );
3630
3631 /* Static Properties */
3632
3633 /**
3634 * @static
3635 * @inheritdoc
3636 */
3637 OO.ui.ButtonWidget.static.cancelButtonMouseDownEvents = false;
3638
3639 /**
3640 * @static
3641 * @inheritdoc
3642 */
3643 OO.ui.ButtonWidget.static.tagName = 'span';
3644
3645 /* Methods */
3646
3647 /**
3648 * Get hyperlink location.
3649 *
3650 * @return {string} Hyperlink location
3651 */
3652 OO.ui.ButtonWidget.prototype.getHref = function () {
3653 return this.href;
3654 };
3655
3656 /**
3657 * Get hyperlink target.
3658 *
3659 * @return {string} Hyperlink target
3660 */
3661 OO.ui.ButtonWidget.prototype.getTarget = function () {
3662 return this.target;
3663 };
3664
3665 /**
3666 * Get search engine traversal hint.
3667 *
3668 * @return {boolean} Whether search engines should avoid traversing this hyperlink
3669 */
3670 OO.ui.ButtonWidget.prototype.getNoFollow = function () {
3671 return this.noFollow;
3672 };
3673
3674 /**
3675 * Set hyperlink location.
3676 *
3677 * @param {string|null} href Hyperlink location, null to remove
3678 */
3679 OO.ui.ButtonWidget.prototype.setHref = function ( href ) {
3680 href = typeof href === 'string' ? href : null;
3681 if ( href !== null && !OO.ui.isSafeUrl( href ) ) {
3682 href = './' + href;
3683 }
3684
3685 if ( href !== this.href ) {
3686 this.href = href;
3687 this.updateHref();
3688 }
3689
3690 return this;
3691 };
3692
3693 /**
3694 * Update the `href` attribute, in case of changes to href or
3695 * disabled state.
3696 *
3697 * @private
3698 * @chainable
3699 */
3700 OO.ui.ButtonWidget.prototype.updateHref = function () {
3701 if ( this.href !== null && !this.isDisabled() ) {
3702 this.$button.attr( 'href', this.href );
3703 } else {
3704 this.$button.removeAttr( 'href' );
3705 }
3706
3707 return this;
3708 };
3709
3710 /**
3711 * Handle disable events.
3712 *
3713 * @private
3714 * @param {boolean} disabled Element is disabled
3715 */
3716 OO.ui.ButtonWidget.prototype.onDisable = function () {
3717 this.updateHref();
3718 };
3719
3720 /**
3721 * Set hyperlink target.
3722 *
3723 * @param {string|null} target Hyperlink target, null to remove
3724 */
3725 OO.ui.ButtonWidget.prototype.setTarget = function ( target ) {
3726 target = typeof target === 'string' ? target : null;
3727
3728 if ( target !== this.target ) {
3729 this.target = target;
3730 if ( target !== null ) {
3731 this.$button.attr( 'target', target );
3732 } else {
3733 this.$button.removeAttr( 'target' );
3734 }
3735 }
3736
3737 return this;
3738 };
3739
3740 /**
3741 * Set search engine traversal hint.
3742 *
3743 * @param {boolean} noFollow True if search engines should avoid traversing this hyperlink
3744 */
3745 OO.ui.ButtonWidget.prototype.setNoFollow = function ( noFollow ) {
3746 noFollow = typeof noFollow === 'boolean' ? noFollow : true;
3747
3748 if ( noFollow !== this.noFollow ) {
3749 this.noFollow = noFollow;
3750 if ( noFollow ) {
3751 this.$button.attr( 'rel', 'nofollow' );
3752 } else {
3753 this.$button.removeAttr( 'rel' );
3754 }
3755 }
3756
3757 return this;
3758 };
3759
3760 // Override method visibility hints from ButtonElement
3761 /**
3762 * @method setActive
3763 * @inheritdoc
3764 */
3765 /**
3766 * @method isActive
3767 * @inheritdoc
3768 */
3769
3770 /**
3771 * A ButtonGroupWidget groups related buttons and is used together with OO.ui.ButtonWidget and
3772 * its subclasses. Each button in a group is addressed by a unique reference. Buttons can be added,
3773 * removed, and cleared from the group.
3774 *
3775 * @example
3776 * // Example: A ButtonGroupWidget with two buttons
3777 * var button1 = new OO.ui.PopupButtonWidget( {
3778 * label: 'Select a category',
3779 * icon: 'menu',
3780 * popup: {
3781 * $content: $( '<p>List of categories...</p>' ),
3782 * padded: true,
3783 * align: 'left'
3784 * }
3785 * } );
3786 * var button2 = new OO.ui.ButtonWidget( {
3787 * label: 'Add item'
3788 * });
3789 * var buttonGroup = new OO.ui.ButtonGroupWidget( {
3790 * items: [button1, button2]
3791 * } );
3792 * $( 'body' ).append( buttonGroup.$element );
3793 *
3794 * @class
3795 * @extends OO.ui.Widget
3796 * @mixins OO.ui.mixin.GroupElement
3797 *
3798 * @constructor
3799 * @param {Object} [config] Configuration options
3800 * @cfg {OO.ui.ButtonWidget[]} [items] Buttons to add
3801 */
3802 OO.ui.ButtonGroupWidget = function OoUiButtonGroupWidget( config ) {
3803 // Configuration initialization
3804 config = config || {};
3805
3806 // Parent constructor
3807 OO.ui.ButtonGroupWidget.parent.call( this, config );
3808
3809 // Mixin constructors
3810 OO.ui.mixin.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) );
3811
3812 // Initialization
3813 this.$element.addClass( 'oo-ui-buttonGroupWidget' );
3814 if ( Array.isArray( config.items ) ) {
3815 this.addItems( config.items );
3816 }
3817 };
3818
3819 /* Setup */
3820
3821 OO.inheritClass( OO.ui.ButtonGroupWidget, OO.ui.Widget );
3822 OO.mixinClass( OO.ui.ButtonGroupWidget, OO.ui.mixin.GroupElement );
3823
3824 /* Static Properties */
3825
3826 /**
3827 * @static
3828 * @inheritdoc
3829 */
3830 OO.ui.ButtonGroupWidget.static.tagName = 'span';
3831
3832 /* Methods */
3833
3834 /**
3835 * Focus the widget
3836 *
3837 * @chainable
3838 */
3839 OO.ui.ButtonGroupWidget.prototype.focus = function () {
3840 if ( !this.isDisabled() ) {
3841 if ( this.items[ 0 ] ) {
3842 this.items[ 0 ].focus();
3843 }
3844 }
3845 return this;
3846 };
3847
3848 /**
3849 * @inheritdoc
3850 */
3851 OO.ui.ButtonGroupWidget.prototype.simulateLabelClick = function () {
3852 this.focus();
3853 };
3854
3855 /**
3856 * IconWidget is a generic widget for {@link OO.ui.mixin.IconElement icons}. In general, IconWidgets should be used with OO.ui.LabelWidget,
3857 * which creates a label that identifies the icon’s function. See the [OOjs UI documentation on MediaWiki] [1]
3858 * for a list of icons included in the library.
3859 *
3860 * @example
3861 * // An icon widget with a label
3862 * var myIcon = new OO.ui.IconWidget( {
3863 * icon: 'help',
3864 * iconTitle: 'Help'
3865 * } );
3866 * // Create a label.
3867 * var iconLabel = new OO.ui.LabelWidget( {
3868 * label: 'Help'
3869 * } );
3870 * $( 'body' ).append( myIcon.$element, iconLabel.$element );
3871 *
3872 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
3873 *
3874 * @class
3875 * @extends OO.ui.Widget
3876 * @mixins OO.ui.mixin.IconElement
3877 * @mixins OO.ui.mixin.TitledElement
3878 * @mixins OO.ui.mixin.FlaggedElement
3879 *
3880 * @constructor
3881 * @param {Object} [config] Configuration options
3882 */
3883 OO.ui.IconWidget = function OoUiIconWidget( config ) {
3884 // Configuration initialization
3885 config = config || {};
3886
3887 // Parent constructor
3888 OO.ui.IconWidget.parent.call( this, config );
3889
3890 // Mixin constructors
3891 OO.ui.mixin.IconElement.call( this, $.extend( {}, config, { $icon: this.$element } ) );
3892 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$element } ) );
3893 OO.ui.mixin.FlaggedElement.call( this, $.extend( {}, config, { $flagged: this.$element } ) );
3894
3895 // Initialization
3896 this.$element.addClass( 'oo-ui-iconWidget' );
3897 };
3898
3899 /* Setup */
3900
3901 OO.inheritClass( OO.ui.IconWidget, OO.ui.Widget );
3902 OO.mixinClass( OO.ui.IconWidget, OO.ui.mixin.IconElement );
3903 OO.mixinClass( OO.ui.IconWidget, OO.ui.mixin.TitledElement );
3904 OO.mixinClass( OO.ui.IconWidget, OO.ui.mixin.FlaggedElement );
3905
3906 /* Static Properties */
3907
3908 /**
3909 * @static
3910 * @inheritdoc
3911 */
3912 OO.ui.IconWidget.static.tagName = 'span';
3913
3914 /**
3915 * IndicatorWidgets create indicators, which are small graphics that are generally used to draw
3916 * attention to the status of an item or to clarify the function of a control. For a list of
3917 * indicators included in the library, please see the [OOjs UI documentation on MediaWiki][1].
3918 *
3919 * @example
3920 * // Example of an indicator widget
3921 * var indicator1 = new OO.ui.IndicatorWidget( {
3922 * indicator: 'alert'
3923 * } );
3924 *
3925 * // Create a fieldset layout to add a label
3926 * var fieldset = new OO.ui.FieldsetLayout();
3927 * fieldset.addItems( [
3928 * new OO.ui.FieldLayout( indicator1, { label: 'An alert indicator:' } )
3929 * ] );
3930 * $( 'body' ).append( fieldset.$element );
3931 *
3932 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
3933 *
3934 * @class
3935 * @extends OO.ui.Widget
3936 * @mixins OO.ui.mixin.IndicatorElement
3937 * @mixins OO.ui.mixin.TitledElement
3938 *
3939 * @constructor
3940 * @param {Object} [config] Configuration options
3941 */
3942 OO.ui.IndicatorWidget = function OoUiIndicatorWidget( config ) {
3943 // Configuration initialization
3944 config = config || {};
3945
3946 // Parent constructor
3947 OO.ui.IndicatorWidget.parent.call( this, config );
3948
3949 // Mixin constructors
3950 OO.ui.mixin.IndicatorElement.call( this, $.extend( {}, config, { $indicator: this.$element } ) );
3951 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$element } ) );
3952
3953 // Initialization
3954 this.$element.addClass( 'oo-ui-indicatorWidget' );
3955 };
3956
3957 /* Setup */
3958
3959 OO.inheritClass( OO.ui.IndicatorWidget, OO.ui.Widget );
3960 OO.mixinClass( OO.ui.IndicatorWidget, OO.ui.mixin.IndicatorElement );
3961 OO.mixinClass( OO.ui.IndicatorWidget, OO.ui.mixin.TitledElement );
3962
3963 /* Static Properties */
3964
3965 /**
3966 * @static
3967 * @inheritdoc
3968 */
3969 OO.ui.IndicatorWidget.static.tagName = 'span';
3970
3971 /**
3972 * LabelWidgets help identify the function of interface elements. Each LabelWidget can
3973 * be configured with a `label` option that is set to a string, a label node, or a function:
3974 *
3975 * - String: a plaintext string
3976 * - jQuery selection: a jQuery selection, used for anything other than a plaintext label, e.g., a
3977 * label that includes a link or special styling, such as a gray color or additional graphical elements.
3978 * - Function: a function that will produce a string in the future. Functions are used
3979 * in cases where the value of the label is not currently defined.
3980 *
3981 * In addition, the LabelWidget can be associated with an {@link OO.ui.InputWidget input widget}, which
3982 * will come into focus when the label is clicked.
3983 *
3984 * @example
3985 * // Examples of LabelWidgets
3986 * var label1 = new OO.ui.LabelWidget( {
3987 * label: 'plaintext label'
3988 * } );
3989 * var label2 = new OO.ui.LabelWidget( {
3990 * label: $( '<a href="default.html">jQuery label</a>' )
3991 * } );
3992 * // Create a fieldset layout with fields for each example
3993 * var fieldset = new OO.ui.FieldsetLayout();
3994 * fieldset.addItems( [
3995 * new OO.ui.FieldLayout( label1 ),
3996 * new OO.ui.FieldLayout( label2 )
3997 * ] );
3998 * $( 'body' ).append( fieldset.$element );
3999 *
4000 * @class
4001 * @extends OO.ui.Widget
4002 * @mixins OO.ui.mixin.LabelElement
4003 * @mixins OO.ui.mixin.TitledElement
4004 *
4005 * @constructor
4006 * @param {Object} [config] Configuration options
4007 * @cfg {OO.ui.InputWidget} [input] {@link OO.ui.InputWidget Input widget} that uses the label.
4008 * Clicking the label will focus the specified input field.
4009 */
4010 OO.ui.LabelWidget = function OoUiLabelWidget( config ) {
4011 // Configuration initialization
4012 config = config || {};
4013
4014 // Parent constructor
4015 OO.ui.LabelWidget.parent.call( this, config );
4016
4017 // Mixin constructors
4018 OO.ui.mixin.LabelElement.call( this, $.extend( {}, config, { $label: this.$element } ) );
4019 OO.ui.mixin.TitledElement.call( this, config );
4020
4021 // Properties
4022 this.input = config.input;
4023
4024 // Initialization
4025 if ( this.input ) {
4026 if ( this.input.getInputId() ) {
4027 this.$element.attr( 'for', this.input.getInputId() );
4028 } else {
4029 this.$label.on( 'click', function () {
4030 this.input.simulateLabelClick();
4031 return false;
4032 }.bind( this ) );
4033 }
4034 }
4035 this.$element.addClass( 'oo-ui-labelWidget' );
4036 };
4037
4038 /* Setup */
4039
4040 OO.inheritClass( OO.ui.LabelWidget, OO.ui.Widget );
4041 OO.mixinClass( OO.ui.LabelWidget, OO.ui.mixin.LabelElement );
4042 OO.mixinClass( OO.ui.LabelWidget, OO.ui.mixin.TitledElement );
4043
4044 /* Static Properties */
4045
4046 /**
4047 * @static
4048 * @inheritdoc
4049 */
4050 OO.ui.LabelWidget.static.tagName = 'label';
4051
4052 /**
4053 * PendingElement is a mixin that is used to create elements that notify users that something is happening
4054 * and that they should wait before proceeding. The pending state is visually represented with a pending
4055 * texture that appears in the head of a pending {@link OO.ui.ProcessDialog process dialog} or in the input
4056 * field of a {@link OO.ui.TextInputWidget text input widget}.
4057 *
4058 * Currently, {@link OO.ui.ActionWidget Action widgets}, which mix in this class, can also be marked as pending, but only when
4059 * used in {@link OO.ui.MessageDialog message dialogs}. The behavior is not currently supported for action widgets used
4060 * in process dialogs.
4061 *
4062 * @example
4063 * function MessageDialog( config ) {
4064 * MessageDialog.parent.call( this, config );
4065 * }
4066 * OO.inheritClass( MessageDialog, OO.ui.MessageDialog );
4067 *
4068 * MessageDialog.static.name = 'myMessageDialog';
4069 * MessageDialog.static.actions = [
4070 * { action: 'save', label: 'Done', flags: 'primary' },
4071 * { label: 'Cancel', flags: 'safe' }
4072 * ];
4073 *
4074 * MessageDialog.prototype.initialize = function () {
4075 * MessageDialog.parent.prototype.initialize.apply( this, arguments );
4076 * this.content = new OO.ui.PanelLayout( { $: this.$, padded: true } );
4077 * 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>' );
4078 * this.$body.append( this.content.$element );
4079 * };
4080 * MessageDialog.prototype.getBodyHeight = function () {
4081 * return 100;
4082 * }
4083 * MessageDialog.prototype.getActionProcess = function ( action ) {
4084 * var dialog = this;
4085 * if ( action === 'save' ) {
4086 * dialog.getActions().get({actions: 'save'})[0].pushPending();
4087 * return new OO.ui.Process()
4088 * .next( 1000 )
4089 * .next( function () {
4090 * dialog.getActions().get({actions: 'save'})[0].popPending();
4091 * } );
4092 * }
4093 * return MessageDialog.parent.prototype.getActionProcess.call( this, action );
4094 * };
4095 *
4096 * var windowManager = new OO.ui.WindowManager();
4097 * $( 'body' ).append( windowManager.$element );
4098 *
4099 * var dialog = new MessageDialog();
4100 * windowManager.addWindows( [ dialog ] );
4101 * windowManager.openWindow( dialog );
4102 *
4103 * @abstract
4104 * @class
4105 *
4106 * @constructor
4107 * @param {Object} [config] Configuration options
4108 * @cfg {jQuery} [$pending] Element to mark as pending, defaults to this.$element
4109 */
4110 OO.ui.mixin.PendingElement = function OoUiMixinPendingElement( config ) {
4111 // Configuration initialization
4112 config = config || {};
4113
4114 // Properties
4115 this.pending = 0;
4116 this.$pending = null;
4117
4118 // Initialisation
4119 this.setPendingElement( config.$pending || this.$element );
4120 };
4121
4122 /* Setup */
4123
4124 OO.initClass( OO.ui.mixin.PendingElement );
4125
4126 /* Methods */
4127
4128 /**
4129 * Set the pending element (and clean up any existing one).
4130 *
4131 * @param {jQuery} $pending The element to set to pending.
4132 */
4133 OO.ui.mixin.PendingElement.prototype.setPendingElement = function ( $pending ) {
4134 if ( this.$pending ) {
4135 this.$pending.removeClass( 'oo-ui-pendingElement-pending' );
4136 }
4137
4138 this.$pending = $pending;
4139 if ( this.pending > 0 ) {
4140 this.$pending.addClass( 'oo-ui-pendingElement-pending' );
4141 }
4142 };
4143
4144 /**
4145 * Check if an element is pending.
4146 *
4147 * @return {boolean} Element is pending
4148 */
4149 OO.ui.mixin.PendingElement.prototype.isPending = function () {
4150 return !!this.pending;
4151 };
4152
4153 /**
4154 * Increase the pending counter. The pending state will remain active until the counter is zero
4155 * (i.e., the number of calls to #pushPending and #popPending is the same).
4156 *
4157 * @chainable
4158 */
4159 OO.ui.mixin.PendingElement.prototype.pushPending = function () {
4160 if ( this.pending === 0 ) {
4161 this.$pending.addClass( 'oo-ui-pendingElement-pending' );
4162 this.updateThemeClasses();
4163 }
4164 this.pending++;
4165
4166 return this;
4167 };
4168
4169 /**
4170 * Decrease the pending counter. The pending state will remain active until the counter is zero
4171 * (i.e., the number of calls to #pushPending and #popPending is the same).
4172 *
4173 * @chainable
4174 */
4175 OO.ui.mixin.PendingElement.prototype.popPending = function () {
4176 if ( this.pending === 1 ) {
4177 this.$pending.removeClass( 'oo-ui-pendingElement-pending' );
4178 this.updateThemeClasses();
4179 }
4180 this.pending = Math.max( 0, this.pending - 1 );
4181
4182 return this;
4183 };
4184
4185 /**
4186 * Element that will stick adjacent to a specified container, even when it is inserted elsewhere
4187 * in the document (for example, in an OO.ui.Window's $overlay).
4188 *
4189 * The elements's position is automatically calculated and maintained when window is resized or the
4190 * page is scrolled. If you reposition the container manually, you have to call #position to make
4191 * sure the element is still placed correctly.
4192 *
4193 * As positioning is only possible when both the element and the container are attached to the DOM
4194 * and visible, it's only done after you call #togglePositioning. You might want to do this inside
4195 * the #toggle method to display a floating popup, for example.
4196 *
4197 * @abstract
4198 * @class
4199 *
4200 * @constructor
4201 * @param {Object} [config] Configuration options
4202 * @cfg {jQuery} [$floatable] Node to position, assigned to #$floatable, omit to use #$element
4203 * @cfg {jQuery} [$floatableContainer] Node to position adjacent to
4204 * @cfg {string} [verticalPosition='below'] Where to position $floatable vertically:
4205 * 'below': Directly below $floatableContainer, aligning f's top edge with fC's bottom edge
4206 * 'above': Directly above $floatableContainer, aligning f's bottom edge with fC's top edge
4207 * 'top': Align the top edge with $floatableContainer's top edge
4208 * 'bottom': Align the bottom edge with $floatableContainer's bottom edge
4209 * 'center': Vertically align the center with $floatableContainer's center
4210 * @cfg {string} [horizontalPosition='start'] Where to position $floatable horizontally:
4211 * 'before': Directly before $floatableContainer, aligning f's end edge with fC's start edge
4212 * 'after': Directly after $floatableContainer, algining f's start edge with fC's end edge
4213 * 'start': Align the start (left in LTR, right in RTL) edge with $floatableContainer's start edge
4214 * 'end': Align the end (right in LTR, left in RTL) edge with $floatableContainer's end edge
4215 * 'center': Horizontally align the center with $floatableContainer's center
4216 * @cfg {boolean} [hideWhenOutOfView=true] Whether to hide the floatable element if the container
4217 * is out of view
4218 */
4219 OO.ui.mixin.FloatableElement = function OoUiMixinFloatableElement( config ) {
4220 // Configuration initialization
4221 config = config || {};
4222
4223 // Properties
4224 this.$floatable = null;
4225 this.$floatableContainer = null;
4226 this.$floatableWindow = null;
4227 this.$floatableClosestScrollable = null;
4228 this.onFloatableScrollHandler = this.position.bind( this );
4229 this.onFloatableWindowResizeHandler = this.position.bind( this );
4230
4231 // Initialization
4232 this.setFloatableContainer( config.$floatableContainer );
4233 this.setFloatableElement( config.$floatable || this.$element );
4234 this.setVerticalPosition( config.verticalPosition || 'below' );
4235 this.setHorizontalPosition( config.horizontalPosition || 'start' );
4236 this.hideWhenOutOfView = config.hideWhenOutOfView === undefined ? true : !!config.hideWhenOutOfView;
4237 };
4238
4239 /* Methods */
4240
4241 /**
4242 * Set floatable element.
4243 *
4244 * If an element is already set, it will be cleaned up before setting up the new element.
4245 *
4246 * @param {jQuery} $floatable Element to make floatable
4247 */
4248 OO.ui.mixin.FloatableElement.prototype.setFloatableElement = function ( $floatable ) {
4249 if ( this.$floatable ) {
4250 this.$floatable.removeClass( 'oo-ui-floatableElement-floatable' );
4251 this.$floatable.css( { left: '', top: '' } );
4252 }
4253
4254 this.$floatable = $floatable.addClass( 'oo-ui-floatableElement-floatable' );
4255 this.position();
4256 };
4257
4258 /**
4259 * Set floatable container.
4260 *
4261 * The element will be positioned relative to the specified container.
4262 *
4263 * @param {jQuery|null} $floatableContainer Container to keep visible, or null to unset
4264 */
4265 OO.ui.mixin.FloatableElement.prototype.setFloatableContainer = function ( $floatableContainer ) {
4266 this.$floatableContainer = $floatableContainer;
4267 if ( this.$floatable ) {
4268 this.position();
4269 }
4270 };
4271
4272 /**
4273 * Change how the element is positioned vertically.
4274 *
4275 * @param {string} position 'below', 'above', 'top', 'bottom' or 'center'
4276 */
4277 OO.ui.mixin.FloatableElement.prototype.setVerticalPosition = function ( position ) {
4278 if ( [ 'below', 'above', 'top', 'bottom', 'center' ].indexOf( position ) === -1 ) {
4279 throw new Error( 'Invalid value for vertical position: ' + position );
4280 }
4281 if ( this.verticalPosition !== position ) {
4282 this.verticalPosition = position;
4283 if ( this.$floatable ) {
4284 this.position();
4285 }
4286 }
4287 };
4288
4289 /**
4290 * Change how the element is positioned horizontally.
4291 *
4292 * @param {string} position 'before', 'after', 'start', 'end' or 'center'
4293 */
4294 OO.ui.mixin.FloatableElement.prototype.setHorizontalPosition = function ( position ) {
4295 if ( [ 'before', 'after', 'start', 'end', 'center' ].indexOf( position ) === -1 ) {
4296 throw new Error( 'Invalid value for horizontal position: ' + position );
4297 }
4298 if ( this.horizontalPosition !== position ) {
4299 this.horizontalPosition = position;
4300 if ( this.$floatable ) {
4301 this.position();
4302 }
4303 }
4304 };
4305
4306 /**
4307 * Toggle positioning.
4308 *
4309 * Do not turn positioning on until after the element is attached to the DOM and visible.
4310 *
4311 * @param {boolean} [positioning] Enable positioning, omit to toggle
4312 * @chainable
4313 */
4314 OO.ui.mixin.FloatableElement.prototype.togglePositioning = function ( positioning ) {
4315 var closestScrollableOfContainer;
4316
4317 if ( !this.$floatable || !this.$floatableContainer ) {
4318 return this;
4319 }
4320
4321 positioning = positioning === undefined ? !this.positioning : !!positioning;
4322
4323 if ( positioning && !this.warnedUnattached && !this.isElementAttached() ) {
4324 OO.ui.warnDeprecation( 'FloatableElement#togglePositioning: Before calling this method, the element must be attached to the DOM.' );
4325 this.warnedUnattached = true;
4326 }
4327
4328 if ( this.positioning !== positioning ) {
4329 this.positioning = positioning;
4330
4331 this.needsCustomPosition =
4332 this.verticalPostion !== 'below' ||
4333 this.horizontalPosition !== 'start' ||
4334 !OO.ui.contains( this.$floatableContainer[ 0 ], this.$floatable[ 0 ] );
4335
4336 closestScrollableOfContainer = OO.ui.Element.static.getClosestScrollableContainer( this.$floatableContainer[ 0 ] );
4337 // If the scrollable is the root, we have to listen to scroll events
4338 // on the window because of browser inconsistencies.
4339 if ( $( closestScrollableOfContainer ).is( 'html, body' ) ) {
4340 closestScrollableOfContainer = OO.ui.Element.static.getWindow( closestScrollableOfContainer );
4341 }
4342
4343 if ( positioning ) {
4344 this.$floatableWindow = $( this.getElementWindow() );
4345 this.$floatableWindow.on( 'resize', this.onFloatableWindowResizeHandler );
4346
4347 this.$floatableClosestScrollable = $( closestScrollableOfContainer );
4348 this.$floatableClosestScrollable.on( 'scroll', this.onFloatableScrollHandler );
4349
4350 // Initial position after visible
4351 this.position();
4352 } else {
4353 if ( this.$floatableWindow ) {
4354 this.$floatableWindow.off( 'resize', this.onFloatableWindowResizeHandler );
4355 this.$floatableWindow = null;
4356 }
4357
4358 if ( this.$floatableClosestScrollable ) {
4359 this.$floatableClosestScrollable.off( 'scroll', this.onFloatableScrollHandler );
4360 this.$floatableClosestScrollable = null;
4361 }
4362
4363 this.$floatable.css( { left: '', right: '', top: '' } );
4364 }
4365 }
4366
4367 return this;
4368 };
4369
4370 /**
4371 * Check whether the bottom edge of the given element is within the viewport of the given container.
4372 *
4373 * @private
4374 * @param {jQuery} $element
4375 * @param {jQuery} $container
4376 * @return {boolean}
4377 */
4378 OO.ui.mixin.FloatableElement.prototype.isElementInViewport = function ( $element, $container ) {
4379 var elemRect, contRect, topEdgeInBounds, bottomEdgeInBounds, leftEdgeInBounds, rightEdgeInBounds,
4380 startEdgeInBounds, endEdgeInBounds,
4381 direction = $element.css( 'direction' );
4382
4383 elemRect = $element[ 0 ].getBoundingClientRect();
4384 if ( $container[ 0 ] === window ) {
4385 contRect = {
4386 top: 0,
4387 left: 0,
4388 right: document.documentElement.clientWidth,
4389 bottom: document.documentElement.clientHeight
4390 };
4391 } else {
4392 contRect = $container[ 0 ].getBoundingClientRect();
4393 }
4394
4395 topEdgeInBounds = elemRect.top >= contRect.top && elemRect.top <= contRect.bottom;
4396 bottomEdgeInBounds = elemRect.bottom >= contRect.top && elemRect.bottom <= contRect.bottom;
4397 leftEdgeInBounds = elemRect.left >= contRect.left && elemRect.left <= contRect.right;
4398 rightEdgeInBounds = elemRect.right >= contRect.left && elemRect.right <= contRect.right;
4399 if ( direction === 'rtl' ) {
4400 startEdgeInBounds = rightEdgeInBounds;
4401 endEdgeInBounds = leftEdgeInBounds;
4402 } else {
4403 startEdgeInBounds = leftEdgeInBounds;
4404 endEdgeInBounds = rightEdgeInBounds;
4405 }
4406
4407 if ( this.verticalPosition === 'below' && !bottomEdgeInBounds ) {
4408 return false;
4409 }
4410 if ( this.verticalPosition === 'above' && !topEdgeInBounds ) {
4411 return false;
4412 }
4413 if ( this.horizontalPosition === 'before' && !startEdgeInBounds ) {
4414 return false;
4415 }
4416 if ( this.horizontalPosition === 'after' && !endEdgeInBounds ) {
4417 return false;
4418 }
4419
4420 // The other positioning values are all about being inside the container,
4421 // so in those cases all we care about is that any part of the container is visible.
4422 return elemRect.top <= contRect.bottom && elemRect.bottom >= contRect.top &&
4423 elemRect.left <= contRect.right && elemRect.right >= contRect.left;
4424 };
4425
4426 /**
4427 * Position the floatable below its container.
4428 *
4429 * This should only be done when both of them are attached to the DOM and visible.
4430 *
4431 * @chainable
4432 */
4433 OO.ui.mixin.FloatableElement.prototype.position = function () {
4434 if ( !this.positioning ) {
4435 return this;
4436 }
4437
4438 if ( !(
4439 // To continue, some things need to be true:
4440 // The element must actually be in the DOM
4441 this.isElementAttached() && (
4442 // The closest scrollable is the current window
4443 this.$floatableClosestScrollable[ 0 ] === this.getElementWindow() ||
4444 // OR is an element in the element's DOM
4445 $.contains( this.getElementDocument(), this.$floatableClosestScrollable[ 0 ] )
4446 )
4447 ) ) {
4448 // Abort early if important parts of the widget are no longer attached to the DOM
4449 return this;
4450 }
4451
4452 if ( this.hideWhenOutOfView && !this.isElementInViewport( this.$floatableContainer, this.$floatableClosestScrollable ) ) {
4453 this.$floatable.addClass( 'oo-ui-element-hidden' );
4454 return this;
4455 } else {
4456 this.$floatable.removeClass( 'oo-ui-element-hidden' );
4457 }
4458
4459 if ( !this.needsCustomPosition ) {
4460 return this;
4461 }
4462
4463 this.$floatable.css( this.computePosition() );
4464
4465 // We updated the position, so re-evaluate the clipping state.
4466 // (ClippableElement does not listen to 'scroll' events on $floatableContainer's parent, and so
4467 // will not notice the need to update itself.)
4468 // TODO: This is terrible, we shouldn't need to know about ClippableElement at all here. Why does
4469 // it not listen to the right events in the right places?
4470 if ( this.clip ) {
4471 this.clip();
4472 }
4473
4474 return this;
4475 };
4476
4477 /**
4478 * Compute how #$floatable should be positioned based on the position of #$floatableContainer
4479 * and the positioning settings. This is a helper for #position that shouldn't be called directly,
4480 * but may be overridden by subclasses if they want to change or add to the positioning logic.
4481 *
4482 * @return {Object} New position to apply with .css(). Keys are 'top', 'left', 'bottom' and 'right'.
4483 */
4484 OO.ui.mixin.FloatableElement.prototype.computePosition = function () {
4485 var isBody, scrollableX, scrollableY, containerPos,
4486 horizScrollbarHeight, vertScrollbarWidth, scrollTop, scrollLeft,
4487 newPos = { top: '', left: '', bottom: '', right: '' },
4488 direction = this.$floatableContainer.css( 'direction' ),
4489 $offsetParent = this.$floatable.offsetParent();
4490
4491 if ( $offsetParent.is( 'html' ) ) {
4492 // The innerHeight/Width and clientHeight/Width calculations don't work well on the
4493 // <html> element, but they do work on the <body>
4494 $offsetParent = $( $offsetParent[ 0 ].ownerDocument.body );
4495 }
4496 isBody = $offsetParent.is( 'body' );
4497 scrollableX = $offsetParent.css( 'overflow-x' ) === 'scroll' || $offsetParent.css( 'overflow-x' ) === 'auto';
4498 scrollableY = $offsetParent.css( 'overflow-y' ) === 'scroll' || $offsetParent.css( 'overflow-y' ) === 'auto';
4499
4500 vertScrollbarWidth = $offsetParent.innerWidth() - $offsetParent.prop( 'clientWidth' );
4501 horizScrollbarHeight = $offsetParent.innerHeight() - $offsetParent.prop( 'clientHeight' );
4502 // We don't need to compute and add scrollTop and scrollLeft if the scrollable container is the body,
4503 // or if it isn't scrollable
4504 scrollTop = scrollableY && !isBody ? $offsetParent.scrollTop() : 0;
4505 scrollLeft = scrollableX && !isBody ? OO.ui.Element.static.getScrollLeft( $offsetParent[ 0 ] ) : 0;
4506
4507 // Avoid passing the <body> to getRelativePosition(), because it won't return what we expect
4508 // if the <body> has a margin
4509 containerPos = isBody ?
4510 this.$floatableContainer.offset() :
4511 OO.ui.Element.static.getRelativePosition( this.$floatableContainer, $offsetParent );
4512 containerPos.bottom = containerPos.top + this.$floatableContainer.outerHeight();
4513 containerPos.right = containerPos.left + this.$floatableContainer.outerWidth();
4514 containerPos.start = direction === 'rtl' ? containerPos.right : containerPos.left;
4515 containerPos.end = direction === 'rtl' ? containerPos.left : containerPos.right;
4516
4517 if ( this.verticalPosition === 'below' ) {
4518 newPos.top = containerPos.bottom;
4519 } else if ( this.verticalPosition === 'above' ) {
4520 newPos.bottom = $offsetParent.outerHeight() - containerPos.top;
4521 } else if ( this.verticalPosition === 'top' ) {
4522 newPos.top = containerPos.top;
4523 } else if ( this.verticalPosition === 'bottom' ) {
4524 newPos.bottom = $offsetParent.outerHeight() - containerPos.bottom;
4525 } else if ( this.verticalPosition === 'center' ) {
4526 newPos.top = containerPos.top +
4527 ( this.$floatableContainer.height() - this.$floatable.height() ) / 2;
4528 }
4529
4530 if ( this.horizontalPosition === 'before' ) {
4531 newPos.end = containerPos.start;
4532 } else if ( this.horizontalPosition === 'after' ) {
4533 newPos.start = containerPos.end;
4534 } else if ( this.horizontalPosition === 'start' ) {
4535 newPos.start = containerPos.start;
4536 } else if ( this.horizontalPosition === 'end' ) {
4537 newPos.end = containerPos.end;
4538 } else if ( this.horizontalPosition === 'center' ) {
4539 newPos.left = containerPos.left +
4540 ( this.$floatableContainer.width() - this.$floatable.width() ) / 2;
4541 }
4542
4543 if ( newPos.start !== undefined ) {
4544 if ( direction === 'rtl' ) {
4545 newPos.right = ( isBody ? $( $offsetParent[ 0 ].ownerDocument.documentElement ) : $offsetParent ).outerWidth() - newPos.start;
4546 } else {
4547 newPos.left = newPos.start;
4548 }
4549 delete newPos.start;
4550 }
4551 if ( newPos.end !== undefined ) {
4552 if ( direction === 'rtl' ) {
4553 newPos.left = newPos.end;
4554 } else {
4555 newPos.right = ( isBody ? $( $offsetParent[ 0 ].ownerDocument.documentElement ) : $offsetParent ).outerWidth() - newPos.end;
4556 }
4557 delete newPos.end;
4558 }
4559
4560 // Account for scroll position
4561 if ( newPos.top !== '' ) {
4562 newPos.top += scrollTop;
4563 }
4564 if ( newPos.bottom !== '' ) {
4565 newPos.bottom -= scrollTop;
4566 }
4567 if ( newPos.left !== '' ) {
4568 newPos.left += scrollLeft;
4569 }
4570 if ( newPos.right !== '' ) {
4571 newPos.right -= scrollLeft;
4572 }
4573
4574 // Account for scrollbar gutter
4575 if ( newPos.bottom !== '' ) {
4576 newPos.bottom -= horizScrollbarHeight;
4577 }
4578 if ( direction === 'rtl' ) {
4579 if ( newPos.left !== '' ) {
4580 newPos.left -= vertScrollbarWidth;
4581 }
4582 } else {
4583 if ( newPos.right !== '' ) {
4584 newPos.right -= vertScrollbarWidth;
4585 }
4586 }
4587
4588 return newPos;
4589 };
4590
4591 /**
4592 * Element that can be automatically clipped to visible boundaries.
4593 *
4594 * Whenever the element's natural height changes, you have to call
4595 * {@link OO.ui.mixin.ClippableElement#clip} to make sure it's still
4596 * clipping correctly.
4597 *
4598 * The dimensions of #$clippableContainer will be compared to the boundaries of the
4599 * nearest scrollable container. If #$clippableContainer is too tall and/or too wide,
4600 * then #$clippable will be given a fixed reduced height and/or width and will be made
4601 * scrollable. By default, #$clippable and #$clippableContainer are the same element,
4602 * but you can build a static footer by setting #$clippableContainer to an element that contains
4603 * #$clippable and the footer.
4604 *
4605 * @abstract
4606 * @class
4607 *
4608 * @constructor
4609 * @param {Object} [config] Configuration options
4610 * @cfg {jQuery} [$clippable] Node to clip, assigned to #$clippable, omit to use #$element
4611 * @cfg {jQuery} [$clippableContainer] Node to keep visible, assigned to #$clippableContainer,
4612 * omit to use #$clippable
4613 */
4614 OO.ui.mixin.ClippableElement = function OoUiMixinClippableElement( config ) {
4615 // Configuration initialization
4616 config = config || {};
4617
4618 // Properties
4619 this.$clippable = null;
4620 this.$clippableContainer = null;
4621 this.clipping = false;
4622 this.clippedHorizontally = false;
4623 this.clippedVertically = false;
4624 this.$clippableScrollableContainer = null;
4625 this.$clippableScroller = null;
4626 this.$clippableWindow = null;
4627 this.idealWidth = null;
4628 this.idealHeight = null;
4629 this.onClippableScrollHandler = this.clip.bind( this );
4630 this.onClippableWindowResizeHandler = this.clip.bind( this );
4631
4632 // Initialization
4633 if ( config.$clippableContainer ) {
4634 this.setClippableContainer( config.$clippableContainer );
4635 }
4636 this.setClippableElement( config.$clippable || this.$element );
4637 };
4638
4639 /* Methods */
4640
4641 /**
4642 * Set clippable element.
4643 *
4644 * If an element is already set, it will be cleaned up before setting up the new element.
4645 *
4646 * @param {jQuery} $clippable Element to make clippable
4647 */
4648 OO.ui.mixin.ClippableElement.prototype.setClippableElement = function ( $clippable ) {
4649 if ( this.$clippable ) {
4650 this.$clippable.removeClass( 'oo-ui-clippableElement-clippable' );
4651 this.$clippable.css( { width: '', height: '', overflowX: '', overflowY: '' } );
4652 OO.ui.Element.static.reconsiderScrollbars( this.$clippable[ 0 ] );
4653 }
4654
4655 this.$clippable = $clippable.addClass( 'oo-ui-clippableElement-clippable' );
4656 this.clip();
4657 };
4658
4659 /**
4660 * Set clippable container.
4661 *
4662 * This is the container that will be measured when deciding whether to clip. When clipping,
4663 * #$clippable will be resized in order to keep the clippable container fully visible.
4664 *
4665 * If the clippable container is unset, #$clippable will be used.
4666 *
4667 * @param {jQuery|null} $clippableContainer Container to keep visible, or null to unset
4668 */
4669 OO.ui.mixin.ClippableElement.prototype.setClippableContainer = function ( $clippableContainer ) {
4670 this.$clippableContainer = $clippableContainer;
4671 if ( this.$clippable ) {
4672 this.clip();
4673 }
4674 };
4675
4676 /**
4677 * Toggle clipping.
4678 *
4679 * Do not turn clipping on until after the element is attached to the DOM and visible.
4680 *
4681 * @param {boolean} [clipping] Enable clipping, omit to toggle
4682 * @chainable
4683 */
4684 OO.ui.mixin.ClippableElement.prototype.toggleClipping = function ( clipping ) {
4685 clipping = clipping === undefined ? !this.clipping : !!clipping;
4686
4687 if ( clipping && !this.warnedUnattached && !this.isElementAttached() ) {
4688 OO.ui.warnDeprecation( 'ClippableElement#toggleClipping: Before calling this method, the element must be attached to the DOM.' );
4689 this.warnedUnattached = true;
4690 }
4691
4692 if ( this.clipping !== clipping ) {
4693 this.clipping = clipping;
4694 if ( clipping ) {
4695 this.$clippableScrollableContainer = $( this.getClosestScrollableElementContainer() );
4696 // If the clippable container is the root, we have to listen to scroll events and check
4697 // jQuery.scrollTop on the window because of browser inconsistencies
4698 this.$clippableScroller = this.$clippableScrollableContainer.is( 'html, body' ) ?
4699 $( OO.ui.Element.static.getWindow( this.$clippableScrollableContainer ) ) :
4700 this.$clippableScrollableContainer;
4701 this.$clippableScroller.on( 'scroll', this.onClippableScrollHandler );
4702 this.$clippableWindow = $( this.getElementWindow() )
4703 .on( 'resize', this.onClippableWindowResizeHandler );
4704 // Initial clip after visible
4705 this.clip();
4706 } else {
4707 this.$clippable.css( {
4708 width: '',
4709 height: '',
4710 maxWidth: '',
4711 maxHeight: '',
4712 overflowX: '',
4713 overflowY: ''
4714 } );
4715 OO.ui.Element.static.reconsiderScrollbars( this.$clippable[ 0 ] );
4716
4717 this.$clippableScrollableContainer = null;
4718 this.$clippableScroller.off( 'scroll', this.onClippableScrollHandler );
4719 this.$clippableScroller = null;
4720 this.$clippableWindow.off( 'resize', this.onClippableWindowResizeHandler );
4721 this.$clippableWindow = null;
4722 }
4723 }
4724
4725 return this;
4726 };
4727
4728 /**
4729 * Check if the element will be clipped to fit the visible area of the nearest scrollable container.
4730 *
4731 * @return {boolean} Element will be clipped to the visible area
4732 */
4733 OO.ui.mixin.ClippableElement.prototype.isClipping = function () {
4734 return this.clipping;
4735 };
4736
4737 /**
4738 * Check if the bottom or right of the element is being clipped by the nearest scrollable container.
4739 *
4740 * @return {boolean} Part of the element is being clipped
4741 */
4742 OO.ui.mixin.ClippableElement.prototype.isClipped = function () {
4743 return this.clippedHorizontally || this.clippedVertically;
4744 };
4745
4746 /**
4747 * Check if the right of the element is being clipped by the nearest scrollable container.
4748 *
4749 * @return {boolean} Part of the element is being clipped
4750 */
4751 OO.ui.mixin.ClippableElement.prototype.isClippedHorizontally = function () {
4752 return this.clippedHorizontally;
4753 };
4754
4755 /**
4756 * Check if the bottom of the element is being clipped by the nearest scrollable container.
4757 *
4758 * @return {boolean} Part of the element is being clipped
4759 */
4760 OO.ui.mixin.ClippableElement.prototype.isClippedVertically = function () {
4761 return this.clippedVertically;
4762 };
4763
4764 /**
4765 * Set the ideal size. These are the dimensions #$clippable will have when it's not being clipped.
4766 *
4767 * @param {number|string} [width] Width as a number of pixels or CSS string with unit suffix
4768 * @param {number|string} [height] Height as a number of pixels or CSS string with unit suffix
4769 */
4770 OO.ui.mixin.ClippableElement.prototype.setIdealSize = function ( width, height ) {
4771 this.idealWidth = width;
4772 this.idealHeight = height;
4773
4774 if ( !this.clipping ) {
4775 // Update dimensions
4776 this.$clippable.css( { width: width, height: height } );
4777 }
4778 // While clipping, idealWidth and idealHeight are not considered
4779 };
4780
4781 /**
4782 * Clip element to visible boundaries and allow scrolling when needed. You should call this method
4783 * when the element's natural height changes.
4784 *
4785 * Element will be clipped the bottom or right of the element is within 10px of the edge of, or
4786 * overlapped by, the visible area of the nearest scrollable container.
4787 *
4788 * Because calling clip() when the natural height changes isn't always possible, we also set
4789 * max-height when the element isn't being clipped. This means that if the element tries to grow
4790 * beyond the edge, something reasonable will happen before clip() is called.
4791 *
4792 * @chainable
4793 */
4794 OO.ui.mixin.ClippableElement.prototype.clip = function () {
4795 var $container, extraHeight, extraWidth, ccOffset,
4796 $scrollableContainer, scOffset, scHeight, scWidth,
4797 ccWidth, scrollerIsWindow, scrollTop, scrollLeft,
4798 desiredWidth, desiredHeight, allotedWidth, allotedHeight,
4799 naturalWidth, naturalHeight, clipWidth, clipHeight,
4800 buffer = 7; // Chosen by fair dice roll
4801
4802 if ( !this.clipping ) {
4803 // this.$clippableScrollableContainer and this.$clippableWindow are null, so the below will fail
4804 return this;
4805 }
4806
4807 $container = this.$clippableContainer || this.$clippable;
4808 extraHeight = $container.outerHeight() - this.$clippable.outerHeight();
4809 extraWidth = $container.outerWidth() - this.$clippable.outerWidth();
4810 ccOffset = $container.offset();
4811 if ( this.$clippableScrollableContainer.is( 'html, body' ) ) {
4812 $scrollableContainer = this.$clippableWindow;
4813 scOffset = { top: 0, left: 0 };
4814 } else {
4815 $scrollableContainer = this.$clippableScrollableContainer;
4816 scOffset = $scrollableContainer.offset();
4817 }
4818 scHeight = $scrollableContainer.innerHeight() - buffer;
4819 scWidth = $scrollableContainer.innerWidth() - buffer;
4820 ccWidth = $container.outerWidth() + buffer;
4821 scrollerIsWindow = this.$clippableScroller[ 0 ] === this.$clippableWindow[ 0 ];
4822 scrollTop = scrollerIsWindow ? this.$clippableScroller.scrollTop() : 0;
4823 scrollLeft = scrollerIsWindow ? this.$clippableScroller.scrollLeft() : 0;
4824 desiredWidth = ccOffset.left < 0 ?
4825 ccWidth + ccOffset.left :
4826 ( scOffset.left + scrollLeft + scWidth ) - ccOffset.left;
4827 desiredHeight = ( scOffset.top + scrollTop + scHeight ) - ccOffset.top;
4828 // It should never be desirable to exceed the dimensions of the browser viewport... right?
4829 desiredWidth = Math.min( desiredWidth, document.documentElement.clientWidth );
4830 desiredHeight = Math.min( desiredHeight, document.documentElement.clientHeight );
4831 allotedWidth = Math.ceil( desiredWidth - extraWidth );
4832 allotedHeight = Math.ceil( desiredHeight - extraHeight );
4833 naturalWidth = this.$clippable.prop( 'scrollWidth' );
4834 naturalHeight = this.$clippable.prop( 'scrollHeight' );
4835 clipWidth = allotedWidth < naturalWidth;
4836 clipHeight = allotedHeight < naturalHeight;
4837
4838 if ( clipWidth ) {
4839 // The order matters here. If overflow is not set first, Chrome displays bogus scrollbars. See T157672.
4840 // Forcing a reflow is a smaller workaround than calling reconsiderScrollbars() for this case.
4841 this.$clippable.css( 'overflowX', 'scroll' );
4842 void this.$clippable[ 0 ].offsetHeight; // Force reflow
4843 this.$clippable.css( {
4844 width: Math.max( 0, allotedWidth ),
4845 maxWidth: ''
4846 } );
4847 } else {
4848 this.$clippable.css( {
4849 overflowX: '',
4850 width: this.idealWidth || '',
4851 maxWidth: Math.max( 0, allotedWidth )
4852 } );
4853 }
4854 if ( clipHeight ) {
4855 // The order matters here. If overflow is not set first, Chrome displays bogus scrollbars. See T157672.
4856 // Forcing a reflow is a smaller workaround than calling reconsiderScrollbars() for this case.
4857 this.$clippable.css( 'overflowY', 'scroll' );
4858 void this.$clippable[ 0 ].offsetHeight; // Force reflow
4859 this.$clippable.css( {
4860 height: Math.max( 0, allotedHeight ),
4861 maxHeight: ''
4862 } );
4863 } else {
4864 this.$clippable.css( {
4865 overflowY: '',
4866 height: this.idealHeight || '',
4867 maxHeight: Math.max( 0, allotedHeight )
4868 } );
4869 }
4870
4871 // If we stopped clipping in at least one of the dimensions
4872 if ( ( this.clippedHorizontally && !clipWidth ) || ( this.clippedVertically && !clipHeight ) ) {
4873 OO.ui.Element.static.reconsiderScrollbars( this.$clippable[ 0 ] );
4874 }
4875
4876 this.clippedHorizontally = clipWidth;
4877 this.clippedVertically = clipHeight;
4878
4879 return this;
4880 };
4881
4882 /**
4883 * PopupWidget is a container for content. The popup is overlaid and positioned absolutely.
4884 * By default, each popup has an anchor that points toward its origin.
4885 * Please see the [OOjs UI documentation on Mediawiki] [1] for more information and examples.
4886 *
4887 * Unlike most widgets, PopupWidget is initially hidden and must be shown by calling #toggle.
4888 *
4889 * @example
4890 * // A popup widget.
4891 * var popup = new OO.ui.PopupWidget( {
4892 * $content: $( '<p>Hi there!</p>' ),
4893 * padded: true,
4894 * width: 300
4895 * } );
4896 *
4897 * $( 'body' ).append( popup.$element );
4898 * // To display the popup, toggle the visibility to 'true'.
4899 * popup.toggle( true );
4900 *
4901 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups
4902 *
4903 * @class
4904 * @extends OO.ui.Widget
4905 * @mixins OO.ui.mixin.LabelElement
4906 * @mixins OO.ui.mixin.ClippableElement
4907 * @mixins OO.ui.mixin.FloatableElement
4908 *
4909 * @constructor
4910 * @param {Object} [config] Configuration options
4911 * @cfg {number} [width=320] Width of popup in pixels
4912 * @cfg {number} [height] Height of popup in pixels. Omit to use the automatic height.
4913 * @cfg {boolean} [anchor=true] Show anchor pointing to origin of popup
4914 * @cfg {string} [position='below'] Where to position the popup relative to $floatableContainer
4915 * 'above': Put popup above $floatableContainer; anchor points down to the horizontal center
4916 * of $floatableContainer
4917 * 'below': Put popup below $floatableContainer; anchor points up to the horizontal center
4918 * of $floatableContainer
4919 * 'before': Put popup to the left (LTR) / right (RTL) of $floatableContainer; anchor points
4920 * endwards (right/left) to the vertical center of $floatableContainer
4921 * 'after': Put popup to the right (LTR) / left (RTL) of $floatableContainer; anchor points
4922 * startwards (left/right) to the vertical center of $floatableContainer
4923 * @cfg {string} [align='center'] How to align the popup to $floatableContainer
4924 * 'forwards': If position is above/below, move the popup as far endwards (right in LTR, left in RTL)
4925 * as possible while still keeping the anchor within the popup;
4926 * if position is before/after, move the popup as far downwards as possible.
4927 * 'backwards': If position is above/below, move the popup as far startwards (left in LTR, right in RTL)
4928 * as possible while still keeping the anchor within the popup;
4929 * if position in before/after, move the popup as far upwards as possible.
4930 * 'center': Horizontally (if position is above/below) or vertically (before/after) align the center
4931 * of the popup with the center of $floatableContainer.
4932 * 'force-left': Alias for 'forwards' in LTR and 'backwards' in RTL
4933 * 'force-right': Alias for 'backwards' in RTL and 'forwards' in LTR
4934 * @cfg {jQuery} [$container] Constrain the popup to the boundaries of the specified container.
4935 * See the [OOjs UI docs on MediaWiki][3] for an example.
4936 * [3]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups#containerExample
4937 * @cfg {number} [containerPadding=10] Padding between the popup and its container, specified as a number of pixels.
4938 * @cfg {jQuery} [$content] Content to append to the popup's body
4939 * @cfg {jQuery} [$footer] Content to append to the popup's footer
4940 * @cfg {boolean} [autoClose=false] Automatically close the popup when it loses focus.
4941 * @cfg {jQuery} [$autoCloseIgnore] Elements that will not close the popup when clicked.
4942 * This config option is only relevant if #autoClose is set to `true`. See the [OOjs UI docs on MediaWiki][2]
4943 * for an example.
4944 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups#autocloseExample
4945 * @cfg {boolean} [head=false] Show a popup header that contains a #label (if specified) and close
4946 * button.
4947 * @cfg {boolean} [padded=false] Add padding to the popup's body
4948 */
4949 OO.ui.PopupWidget = function OoUiPopupWidget( config ) {
4950 // Configuration initialization
4951 config = config || {};
4952
4953 // Parent constructor
4954 OO.ui.PopupWidget.parent.call( this, config );
4955
4956 // Properties (must be set before ClippableElement constructor call)
4957 this.$body = $( '<div>' );
4958 this.$popup = $( '<div>' );
4959
4960 // Mixin constructors
4961 OO.ui.mixin.LabelElement.call( this, config );
4962 OO.ui.mixin.ClippableElement.call( this, $.extend( {}, config, {
4963 $clippable: this.$body,
4964 $clippableContainer: this.$popup
4965 } ) );
4966 OO.ui.mixin.FloatableElement.call( this, config );
4967
4968 // Properties
4969 this.$anchor = $( '<div>' );
4970 // If undefined, will be computed lazily in computePosition()
4971 this.$container = config.$container;
4972 this.containerPadding = config.containerPadding !== undefined ? config.containerPadding : 10;
4973 this.autoClose = !!config.autoClose;
4974 this.$autoCloseIgnore = config.$autoCloseIgnore;
4975 this.transitionTimeout = null;
4976 this.anchored = false;
4977 this.width = config.width !== undefined ? config.width : 320;
4978 this.height = config.height !== undefined ? config.height : null;
4979 this.onMouseDownHandler = this.onMouseDown.bind( this );
4980 this.onDocumentKeyDownHandler = this.onDocumentKeyDown.bind( this );
4981
4982 // Initialization
4983 this.toggleAnchor( config.anchor === undefined || config.anchor );
4984 this.setAlignment( config.align || 'center' );
4985 this.setPosition( config.position || 'below' );
4986 this.$body.addClass( 'oo-ui-popupWidget-body' );
4987 this.$anchor.addClass( 'oo-ui-popupWidget-anchor' );
4988 this.$popup
4989 .addClass( 'oo-ui-popupWidget-popup' )
4990 .append( this.$body );
4991 this.$element
4992 .addClass( 'oo-ui-popupWidget' )
4993 .append( this.$popup, this.$anchor );
4994 // Move content, which was added to #$element by OO.ui.Widget, to the body
4995 // FIXME This is gross, we should use '$body' or something for the config
4996 if ( config.$content instanceof jQuery ) {
4997 this.$body.append( config.$content );
4998 }
4999
5000 if ( config.padded ) {
5001 this.$body.addClass( 'oo-ui-popupWidget-body-padded' );
5002 }
5003
5004 if ( config.head ) {
5005 this.closeButton = new OO.ui.ButtonWidget( { framed: false, icon: 'close' } );
5006 this.closeButton.connect( this, { click: 'onCloseButtonClick' } );
5007 this.$head = $( '<div>' )
5008 .addClass( 'oo-ui-popupWidget-head' )
5009 .append( this.$label, this.closeButton.$element );
5010 this.$popup.prepend( this.$head );
5011 }
5012
5013 if ( config.$footer ) {
5014 this.$footer = $( '<div>' )
5015 .addClass( 'oo-ui-popupWidget-footer' )
5016 .append( config.$footer );
5017 this.$popup.append( this.$footer );
5018 }
5019
5020 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
5021 // that reference properties not initialized at that time of parent class construction
5022 // TODO: Find a better way to handle post-constructor setup
5023 this.visible = false;
5024 this.$element.addClass( 'oo-ui-element-hidden' );
5025 };
5026
5027 /* Setup */
5028
5029 OO.inheritClass( OO.ui.PopupWidget, OO.ui.Widget );
5030 OO.mixinClass( OO.ui.PopupWidget, OO.ui.mixin.LabelElement );
5031 OO.mixinClass( OO.ui.PopupWidget, OO.ui.mixin.ClippableElement );
5032 OO.mixinClass( OO.ui.PopupWidget, OO.ui.mixin.FloatableElement );
5033
5034 /* Events */
5035
5036 /**
5037 * @event ready
5038 *
5039 * The popup is ready: it is visible and has been positioned and clipped.
5040 */
5041
5042 /* Methods */
5043
5044 /**
5045 * Handles mouse down events.
5046 *
5047 * @private
5048 * @param {MouseEvent} e Mouse down event
5049 */
5050 OO.ui.PopupWidget.prototype.onMouseDown = function ( e ) {
5051 if (
5052 this.isVisible() &&
5053 !OO.ui.contains( this.$element.add( this.$autoCloseIgnore ).get(), e.target, true )
5054 ) {
5055 this.toggle( false );
5056 }
5057 };
5058
5059 /**
5060 * Bind mouse down listener.
5061 *
5062 * @private
5063 */
5064 OO.ui.PopupWidget.prototype.bindMouseDownListener = function () {
5065 // Capture clicks outside popup
5066 this.getElementWindow().addEventListener( 'mousedown', this.onMouseDownHandler, true );
5067 };
5068
5069 /**
5070 * Handles close button click events.
5071 *
5072 * @private
5073 */
5074 OO.ui.PopupWidget.prototype.onCloseButtonClick = function () {
5075 if ( this.isVisible() ) {
5076 this.toggle( false );
5077 }
5078 };
5079
5080 /**
5081 * Unbind mouse down listener.
5082 *
5083 * @private
5084 */
5085 OO.ui.PopupWidget.prototype.unbindMouseDownListener = function () {
5086 this.getElementWindow().removeEventListener( 'mousedown', this.onMouseDownHandler, true );
5087 };
5088
5089 /**
5090 * Handles key down events.
5091 *
5092 * @private
5093 * @param {KeyboardEvent} e Key down event
5094 */
5095 OO.ui.PopupWidget.prototype.onDocumentKeyDown = function ( e ) {
5096 if (
5097 e.which === OO.ui.Keys.ESCAPE &&
5098 this.isVisible()
5099 ) {
5100 this.toggle( false );
5101 e.preventDefault();
5102 e.stopPropagation();
5103 }
5104 };
5105
5106 /**
5107 * Bind key down listener.
5108 *
5109 * @private
5110 */
5111 OO.ui.PopupWidget.prototype.bindKeyDownListener = function () {
5112 this.getElementWindow().addEventListener( 'keydown', this.onDocumentKeyDownHandler, true );
5113 };
5114
5115 /**
5116 * Unbind key down listener.
5117 *
5118 * @private
5119 */
5120 OO.ui.PopupWidget.prototype.unbindKeyDownListener = function () {
5121 this.getElementWindow().removeEventListener( 'keydown', this.onDocumentKeyDownHandler, true );
5122 };
5123
5124 /**
5125 * Show, hide, or toggle the visibility of the anchor.
5126 *
5127 * @param {boolean} [show] Show anchor, omit to toggle
5128 */
5129 OO.ui.PopupWidget.prototype.toggleAnchor = function ( show ) {
5130 show = show === undefined ? !this.anchored : !!show;
5131
5132 if ( this.anchored !== show ) {
5133 if ( show ) {
5134 this.$element.addClass( 'oo-ui-popupWidget-anchored' );
5135 this.$element.addClass( 'oo-ui-popupWidget-anchored-' + this.anchorEdge );
5136 } else {
5137 this.$element.removeClass( 'oo-ui-popupWidget-anchored' );
5138 this.$element.removeClass( 'oo-ui-popupWidget-anchored-' + this.anchorEdge );
5139 }
5140 this.anchored = show;
5141 }
5142 };
5143 /**
5144 * Change which edge the anchor appears on.
5145 *
5146 * @param {string} edge 'top', 'bottom', 'start' or 'end'
5147 */
5148 OO.ui.PopupWidget.prototype.setAnchorEdge = function ( edge ) {
5149 if ( [ 'top', 'bottom', 'start', 'end' ].indexOf( edge ) === -1 ) {
5150 throw new Error( 'Invalid value for edge: ' + edge );
5151 }
5152 if ( this.anchorEdge !== null ) {
5153 this.$element.removeClass( 'oo-ui-popupWidget-anchored-' + this.anchorEdge );
5154 }
5155 this.anchorEdge = edge;
5156 if ( this.anchored ) {
5157 this.$element.addClass( 'oo-ui-popupWidget-anchored-' + edge );
5158 }
5159 };
5160
5161 /**
5162 * Check if the anchor is visible.
5163 *
5164 * @return {boolean} Anchor is visible
5165 */
5166 OO.ui.PopupWidget.prototype.hasAnchor = function () {
5167 return this.anchored;
5168 };
5169
5170 /**
5171 * Toggle visibility of the popup. The popup is initially hidden and must be shown by calling
5172 * `.toggle( true )` after its #$element is attached to the DOM.
5173 *
5174 * Do not show the popup while it is not attached to the DOM. The calculations required to display
5175 * it in the right place and with the right dimensions only work correctly while it is attached.
5176 * Side-effects may include broken interface and exceptions being thrown. This wasn't always
5177 * strictly enforced, so currently it only generates a warning in the browser console.
5178 *
5179 * @fires ready
5180 * @inheritdoc
5181 */
5182 OO.ui.PopupWidget.prototype.toggle = function ( show ) {
5183 var change;
5184 show = show === undefined ? !this.isVisible() : !!show;
5185
5186 change = show !== this.isVisible();
5187
5188 if ( show && !this.warnedUnattached && !this.isElementAttached() ) {
5189 OO.ui.warnDeprecation( 'PopupWidget#toggle: Before calling this method, the popup must be attached to the DOM.' );
5190 this.warnedUnattached = true;
5191 }
5192 if ( show && !this.$floatableContainer && this.isElementAttached() ) {
5193 // Fall back to the parent node if the floatableContainer is not set
5194 this.setFloatableContainer( this.$element.parent() );
5195 }
5196
5197 // Parent method
5198 OO.ui.PopupWidget.parent.prototype.toggle.call( this, show );
5199
5200 if ( change ) {
5201 this.togglePositioning( show && !!this.$floatableContainer );
5202
5203 if ( show ) {
5204 if ( this.autoClose ) {
5205 this.bindMouseDownListener();
5206 this.bindKeyDownListener();
5207 }
5208 this.updateDimensions();
5209 this.toggleClipping( true );
5210 this.emit( 'ready' );
5211 } else {
5212 this.toggleClipping( false );
5213 if ( this.autoClose ) {
5214 this.unbindMouseDownListener();
5215 this.unbindKeyDownListener();
5216 }
5217 }
5218 }
5219
5220 return this;
5221 };
5222
5223 /**
5224 * Set the size of the popup.
5225 *
5226 * Changing the size may also change the popup's position depending on the alignment.
5227 *
5228 * @param {number} width Width in pixels
5229 * @param {number} height Height in pixels
5230 * @param {boolean} [transition=false] Use a smooth transition
5231 * @chainable
5232 */
5233 OO.ui.PopupWidget.prototype.setSize = function ( width, height, transition ) {
5234 this.width = width;
5235 this.height = height !== undefined ? height : null;
5236 if ( this.isVisible() ) {
5237 this.updateDimensions( transition );
5238 }
5239 };
5240
5241 /**
5242 * Update the size and position.
5243 *
5244 * Only use this to keep the popup properly anchored. Use #setSize to change the size, and this will
5245 * be called automatically.
5246 *
5247 * @param {boolean} [transition=false] Use a smooth transition
5248 * @chainable
5249 */
5250 OO.ui.PopupWidget.prototype.updateDimensions = function ( transition ) {
5251 var widget = this;
5252
5253 // Prevent transition from being interrupted
5254 clearTimeout( this.transitionTimeout );
5255 if ( transition ) {
5256 // Enable transition
5257 this.$element.addClass( 'oo-ui-popupWidget-transitioning' );
5258 }
5259
5260 this.position();
5261
5262 if ( transition ) {
5263 // Prevent transitioning after transition is complete
5264 this.transitionTimeout = setTimeout( function () {
5265 widget.$element.removeClass( 'oo-ui-popupWidget-transitioning' );
5266 }, 200 );
5267 } else {
5268 // Prevent transitioning immediately
5269 this.$element.removeClass( 'oo-ui-popupWidget-transitioning' );
5270 }
5271 };
5272
5273 /**
5274 * @inheritdoc
5275 */
5276 OO.ui.PopupWidget.prototype.computePosition = function () {
5277 var direction, align, vertical, start, end, near, far, sizeProp, popupSize, anchorSize, anchorPos,
5278 anchorOffset, anchorMargin, parentPosition, positionProp, positionAdjustment, floatablePos,
5279 offsetParentPos, containerPos,
5280 popupPos = {},
5281 anchorCss = { left: '', right: '', top: '', bottom: '' },
5282 alignMap = {
5283 ltr: {
5284 'force-left': 'backwards',
5285 'force-right': 'forwards'
5286 },
5287 rtl: {
5288 'force-left': 'forwards',
5289 'force-right': 'backwards'
5290 }
5291 },
5292 anchorEdgeMap = {
5293 above: 'bottom',
5294 below: 'top',
5295 before: 'end',
5296 after: 'start'
5297 },
5298 hPosMap = {
5299 forwards: 'start',
5300 center: 'center',
5301 backwards: this.anchored ? 'before' : 'end'
5302 },
5303 vPosMap = {
5304 forwards: 'top',
5305 center: 'center',
5306 backwards: 'bottom'
5307 };
5308
5309 if ( !this.$container ) {
5310 // Lazy-initialize $container if not specified in constructor
5311 this.$container = $( this.getClosestScrollableElementContainer() );
5312 }
5313 direction = this.$container.css( 'direction' );
5314
5315 // Set height and width before we do anything else, since it might cause our measurements
5316 // to change (e.g. due to scrollbars appearing or disappearing), and it also affects centering
5317 this.$popup.css( {
5318 width: this.width,
5319 height: this.height !== null ? this.height : 'auto'
5320 } );
5321
5322 align = alignMap[ direction ][ this.align ] || this.align;
5323 // If the popup is positioned before or after, then the anchor positioning is vertical, otherwise horizontal
5324 vertical = this.popupPosition === 'before' || this.popupPosition === 'after';
5325 start = vertical ? 'top' : ( direction === 'rtl' ? 'right' : 'left' );
5326 end = vertical ? 'bottom' : ( direction === 'rtl' ? 'left' : 'right' );
5327 near = vertical ? 'top' : 'left';
5328 far = vertical ? 'bottom' : 'right';
5329 sizeProp = vertical ? 'Height' : 'Width';
5330 popupSize = vertical ? ( this.height || this.$popup.height() ) : this.width;
5331
5332 this.setAnchorEdge( anchorEdgeMap[ this.popupPosition ] );
5333 this.horizontalPosition = vertical ? this.popupPosition : hPosMap[ align ];
5334 this.verticalPosition = vertical ? vPosMap[ align ] : this.popupPosition;
5335
5336 // Parent method
5337 parentPosition = OO.ui.mixin.FloatableElement.prototype.computePosition.call( this );
5338 // Find out which property FloatableElement used for positioning, and adjust that value
5339 positionProp = vertical ?
5340 ( parentPosition.top !== '' ? 'top' : 'bottom' ) :
5341 ( parentPosition.left !== '' ? 'left' : 'right' );
5342
5343 // Figure out where the near and far edges of the popup and $floatableContainer are
5344 floatablePos = this.$floatableContainer.offset();
5345 floatablePos[ far ] = floatablePos[ near ] + this.$floatableContainer[ 'outer' + sizeProp ]();
5346 // Measure where the offsetParent is and compute our position based on that and parentPosition
5347 offsetParentPos = this.$element.offsetParent().offset();
5348
5349 if ( positionProp === near ) {
5350 popupPos[ near ] = offsetParentPos[ near ] + parentPosition[ near ];
5351 popupPos[ far ] = popupPos[ near ] + popupSize;
5352 } else {
5353 popupPos[ far ] = offsetParentPos[ near ] +
5354 this.$element.offsetParent()[ 'inner' + sizeProp ]() - parentPosition[ far ];
5355 popupPos[ near ] = popupPos[ far ] - popupSize;
5356 }
5357
5358 if ( this.anchored ) {
5359 // Position the anchor (which is positioned relative to the popup) to point to $floatableContainer
5360 anchorPos = ( floatablePos[ start ] + floatablePos[ end ] ) / 2;
5361 anchorOffset = ( start === far ? -1 : 1 ) * ( anchorPos - popupPos[ start ] );
5362
5363 // If the anchor is less than 2*anchorSize from either edge, move the popup to make more space
5364 // this.$anchor.width()/height() returns 0 because of the CSS trickery we use, so use scrollWidth/Height
5365 anchorSize = this.$anchor[ 0 ][ 'scroll' + sizeProp ];
5366 anchorMargin = parseFloat( this.$anchor.css( 'margin-' + start ) );
5367 if ( anchorOffset + anchorMargin < 2 * anchorSize ) {
5368 // Not enough space for the anchor on the start side; pull the popup startwards
5369 positionAdjustment = ( positionProp === start ? -1 : 1 ) *
5370 ( 2 * anchorSize - ( anchorOffset + anchorMargin ) );
5371 } else if ( anchorOffset + anchorMargin > popupSize - 2 * anchorSize ) {
5372 // Not enough space for the anchor on the end side; pull the popup endwards
5373 positionAdjustment = ( positionProp === end ? -1 : 1 ) *
5374 ( anchorOffset + anchorMargin - ( popupSize - 2 * anchorSize ) );
5375 } else {
5376 positionAdjustment = 0;
5377 }
5378 } else {
5379 positionAdjustment = 0;
5380 }
5381
5382 // Check if the popup will go beyond the edge of this.$container
5383 containerPos = this.$container.offset();
5384 containerPos[ far ] = containerPos[ near ] + this.$container[ 'inner' + sizeProp ]();
5385 // Take into account how much the popup will move because of the adjustments we're going to make
5386 popupPos[ near ] += ( positionProp === near ? 1 : -1 ) * positionAdjustment;
5387 popupPos[ far ] += ( positionProp === near ? 1 : -1 ) * positionAdjustment;
5388 if ( containerPos[ near ] + this.containerPadding > popupPos[ near ] ) {
5389 // Popup goes beyond the near (left/top) edge, move it to the right/bottom
5390 positionAdjustment += ( positionProp === near ? 1 : -1 ) *
5391 ( containerPos[ near ] + this.containerPadding - popupPos[ near ] );
5392 } else if ( containerPos[ far ] - this.containerPadding < popupPos[ far ] ) {
5393 // Popup goes beyond the far (right/bottom) edge, move it to the left/top
5394 positionAdjustment += ( positionProp === far ? 1 : -1 ) *
5395 ( popupPos[ far ] - ( containerPos[ far ] - this.containerPadding ) );
5396 }
5397
5398 if ( this.anchored ) {
5399 // Adjust anchorOffset for positionAdjustment
5400 anchorOffset += ( positionProp === start ? -1 : 1 ) * positionAdjustment;
5401
5402 // Position the anchor
5403 anchorCss[ start ] = anchorOffset;
5404 this.$anchor.css( anchorCss );
5405 }
5406
5407 // Move the popup if needed
5408 parentPosition[ positionProp ] += positionAdjustment;
5409
5410 return parentPosition;
5411 };
5412
5413 /**
5414 * Set popup alignment
5415 *
5416 * @param {string} [align=center] Alignment of the popup, `center`, `force-left`, `force-right`,
5417 * `backwards` or `forwards`.
5418 */
5419 OO.ui.PopupWidget.prototype.setAlignment = function ( align ) {
5420 // Validate alignment
5421 if ( [ 'force-left', 'force-right', 'backwards', 'forwards', 'center' ].indexOf( align ) > -1 ) {
5422 this.align = align;
5423 } else {
5424 this.align = 'center';
5425 }
5426 this.position();
5427 };
5428
5429 /**
5430 * Get popup alignment
5431 *
5432 * @return {string} Alignment of the popup, `center`, `force-left`, `force-right`,
5433 * `backwards` or `forwards`.
5434 */
5435 OO.ui.PopupWidget.prototype.getAlignment = function () {
5436 return this.align;
5437 };
5438
5439 /**
5440 * Change the positioning of the popup.
5441 *
5442 * @param {string} position 'above', 'below', 'before' or 'after'
5443 */
5444 OO.ui.PopupWidget.prototype.setPosition = function ( position ) {
5445 if ( [ 'above', 'below', 'before', 'after' ].indexOf( position ) === -1 ) {
5446 position = 'below';
5447 }
5448 this.popupPosition = position;
5449 this.position();
5450 };
5451
5452 /**
5453 * Get popup positioning.
5454 *
5455 * @return {string} 'above', 'below', 'before' or 'after'
5456 */
5457 OO.ui.PopupWidget.prototype.getPosition = function () {
5458 return this.popupPosition;
5459 };
5460
5461 /**
5462 * Get an ID of the body element, this can be used as the
5463 * `aria-describedby` attribute for an input field.
5464 *
5465 * @return {string} The ID of the body element
5466 */
5467 OO.ui.PopupWidget.prototype.getBodyId = function () {
5468 var id = this.$body.attr( 'id' );
5469 if ( id === undefined ) {
5470 id = OO.ui.generateElementId();
5471 this.$body.attr( 'id', id );
5472 }
5473 return id;
5474 };
5475
5476 /**
5477 * PopupElement is mixed into other classes to generate a {@link OO.ui.PopupWidget popup widget}.
5478 * A popup is a container for content. It is overlaid and positioned absolutely. By default, each
5479 * popup has an anchor, which is an arrow-like protrusion that points toward the popup’s origin.
5480 * See {@link OO.ui.PopupWidget PopupWidget} for an example.
5481 *
5482 * @abstract
5483 * @class
5484 *
5485 * @constructor
5486 * @param {Object} [config] Configuration options
5487 * @cfg {Object} [popup] Configuration to pass to popup
5488 * @cfg {boolean} [popup.autoClose=true] Popup auto-closes when it loses focus
5489 */
5490 OO.ui.mixin.PopupElement = function OoUiMixinPopupElement( config ) {
5491 // Configuration initialization
5492 config = config || {};
5493
5494 // Properties
5495 this.popup = new OO.ui.PopupWidget( $.extend(
5496 {
5497 autoClose: true,
5498 $floatableContainer: this.$element
5499 },
5500 config.popup,
5501 {
5502 $autoCloseIgnore: this.$element.add( config.popup && config.popup.$autoCloseIgnore )
5503 }
5504 ) );
5505 };
5506
5507 /* Methods */
5508
5509 /**
5510 * Get popup.
5511 *
5512 * @return {OO.ui.PopupWidget} Popup widget
5513 */
5514 OO.ui.mixin.PopupElement.prototype.getPopup = function () {
5515 return this.popup;
5516 };
5517
5518 /**
5519 * PopupButtonWidgets toggle the visibility of a contained {@link OO.ui.PopupWidget PopupWidget},
5520 * which is used to display additional information or options.
5521 *
5522 * @example
5523 * // Example of a popup button.
5524 * var popupButton = new OO.ui.PopupButtonWidget( {
5525 * label: 'Popup button with options',
5526 * icon: 'menu',
5527 * popup: {
5528 * $content: $( '<p>Additional options here.</p>' ),
5529 * padded: true,
5530 * align: 'force-left'
5531 * }
5532 * } );
5533 * // Append the button to the DOM.
5534 * $( 'body' ).append( popupButton.$element );
5535 *
5536 * @class
5537 * @extends OO.ui.ButtonWidget
5538 * @mixins OO.ui.mixin.PopupElement
5539 *
5540 * @constructor
5541 * @param {Object} [config] Configuration options
5542 * @cfg {jQuery} [$overlay] Render the popup into a separate layer. This configuration is useful in cases where
5543 * the expanded popup is larger than its containing `<div>`. The specified overlay layer is usually on top of the
5544 * containing `<div>` and has a larger area. By default, the popup uses relative positioning.
5545 * See <https://www.mediawiki.org/wiki/OOjs_UI/Concepts#Overlays>.
5546 */
5547 OO.ui.PopupButtonWidget = function OoUiPopupButtonWidget( config ) {
5548 // Configuration initialization
5549 config = config || {};
5550
5551 // Parent constructor
5552 OO.ui.PopupButtonWidget.parent.call( this, config );
5553
5554 // Mixin constructors
5555 OO.ui.mixin.PopupElement.call( this, config );
5556
5557 // Properties
5558 this.$overlay = config.$overlay || this.$element;
5559
5560 // Events
5561 this.connect( this, { click: 'onAction' } );
5562
5563 // Initialization
5564 this.$element
5565 .addClass( 'oo-ui-popupButtonWidget' )
5566 .attr( 'aria-haspopup', 'true' );
5567 this.popup.$element
5568 .addClass( 'oo-ui-popupButtonWidget-popup' )
5569 .toggleClass( 'oo-ui-popupButtonWidget-framed-popup', this.isFramed() )
5570 .toggleClass( 'oo-ui-popupButtonWidget-frameless-popup', !this.isFramed() );
5571 this.$overlay.append( this.popup.$element );
5572 };
5573
5574 /* Setup */
5575
5576 OO.inheritClass( OO.ui.PopupButtonWidget, OO.ui.ButtonWidget );
5577 OO.mixinClass( OO.ui.PopupButtonWidget, OO.ui.mixin.PopupElement );
5578
5579 /* Methods */
5580
5581 /**
5582 * Handle the button action being triggered.
5583 *
5584 * @private
5585 */
5586 OO.ui.PopupButtonWidget.prototype.onAction = function () {
5587 this.popup.toggle();
5588 };
5589
5590 /**
5591 * Mixin for OO.ui.Widget subclasses to provide OO.ui.mixin.GroupElement.
5592 *
5593 * Use together with OO.ui.mixin.ItemWidget to make disabled state inheritable.
5594 *
5595 * @private
5596 * @abstract
5597 * @class
5598 * @mixins OO.ui.mixin.GroupElement
5599 *
5600 * @constructor
5601 * @param {Object} [config] Configuration options
5602 */
5603 OO.ui.mixin.GroupWidget = function OoUiMixinGroupWidget( config ) {
5604 // Mixin constructors
5605 OO.ui.mixin.GroupElement.call( this, config );
5606 };
5607
5608 /* Setup */
5609
5610 OO.mixinClass( OO.ui.mixin.GroupWidget, OO.ui.mixin.GroupElement );
5611
5612 /* Methods */
5613
5614 /**
5615 * Set the disabled state of the widget.
5616 *
5617 * This will also update the disabled state of child widgets.
5618 *
5619 * @param {boolean} disabled Disable widget
5620 * @chainable
5621 */
5622 OO.ui.mixin.GroupWidget.prototype.setDisabled = function ( disabled ) {
5623 var i, len;
5624
5625 // Parent method
5626 // Note: Calling #setDisabled this way assumes this is mixed into an OO.ui.Widget
5627 OO.ui.Widget.prototype.setDisabled.call( this, disabled );
5628
5629 // During construction, #setDisabled is called before the OO.ui.mixin.GroupElement constructor
5630 if ( this.items ) {
5631 for ( i = 0, len = this.items.length; i < len; i++ ) {
5632 this.items[ i ].updateDisabled();
5633 }
5634 }
5635
5636 return this;
5637 };
5638
5639 /**
5640 * Mixin for widgets used as items in widgets that mix in OO.ui.mixin.GroupWidget.
5641 *
5642 * Item widgets have a reference to a OO.ui.mixin.GroupWidget while they are attached to the group. This
5643 * allows bidirectional communication.
5644 *
5645 * Use together with OO.ui.mixin.GroupWidget to make disabled state inheritable.
5646 *
5647 * @private
5648 * @abstract
5649 * @class
5650 *
5651 * @constructor
5652 */
5653 OO.ui.mixin.ItemWidget = function OoUiMixinItemWidget() {
5654 //
5655 };
5656
5657 /* Methods */
5658
5659 /**
5660 * Check if widget is disabled.
5661 *
5662 * Checks parent if present, making disabled state inheritable.
5663 *
5664 * @return {boolean} Widget is disabled
5665 */
5666 OO.ui.mixin.ItemWidget.prototype.isDisabled = function () {
5667 return this.disabled ||
5668 ( this.elementGroup instanceof OO.ui.Widget && this.elementGroup.isDisabled() );
5669 };
5670
5671 /**
5672 * Set group element is in.
5673 *
5674 * @param {OO.ui.mixin.GroupElement|null} group Group element, null if none
5675 * @chainable
5676 */
5677 OO.ui.mixin.ItemWidget.prototype.setElementGroup = function ( group ) {
5678 // Parent method
5679 // Note: Calling #setElementGroup this way assumes this is mixed into an OO.ui.Element
5680 OO.ui.Element.prototype.setElementGroup.call( this, group );
5681
5682 // Initialize item disabled states
5683 this.updateDisabled();
5684
5685 return this;
5686 };
5687
5688 /**
5689 * OptionWidgets are special elements that can be selected and configured with data. The
5690 * data is often unique for each option, but it does not have to be. OptionWidgets are used
5691 * with OO.ui.SelectWidget to create a selection of mutually exclusive options. For more information
5692 * and examples, please see the [OOjs UI documentation on MediaWiki][1].
5693 *
5694 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
5695 *
5696 * @class
5697 * @extends OO.ui.Widget
5698 * @mixins OO.ui.mixin.ItemWidget
5699 * @mixins OO.ui.mixin.LabelElement
5700 * @mixins OO.ui.mixin.FlaggedElement
5701 * @mixins OO.ui.mixin.AccessKeyedElement
5702 *
5703 * @constructor
5704 * @param {Object} [config] Configuration options
5705 */
5706 OO.ui.OptionWidget = function OoUiOptionWidget( config ) {
5707 // Configuration initialization
5708 config = config || {};
5709
5710 // Parent constructor
5711 OO.ui.OptionWidget.parent.call( this, config );
5712
5713 // Mixin constructors
5714 OO.ui.mixin.ItemWidget.call( this );
5715 OO.ui.mixin.LabelElement.call( this, config );
5716 OO.ui.mixin.FlaggedElement.call( this, config );
5717 OO.ui.mixin.AccessKeyedElement.call( this, config );
5718
5719 // Properties
5720 this.selected = false;
5721 this.highlighted = false;
5722 this.pressed = false;
5723
5724 // Initialization
5725 this.$element
5726 .data( 'oo-ui-optionWidget', this )
5727 // Allow programmatic focussing (and by accesskey), but not tabbing
5728 .attr( 'tabindex', '-1' )
5729 .attr( 'role', 'option' )
5730 .attr( 'aria-selected', 'false' )
5731 .addClass( 'oo-ui-optionWidget' )
5732 .append( this.$label );
5733 };
5734
5735 /* Setup */
5736
5737 OO.inheritClass( OO.ui.OptionWidget, OO.ui.Widget );
5738 OO.mixinClass( OO.ui.OptionWidget, OO.ui.mixin.ItemWidget );
5739 OO.mixinClass( OO.ui.OptionWidget, OO.ui.mixin.LabelElement );
5740 OO.mixinClass( OO.ui.OptionWidget, OO.ui.mixin.FlaggedElement );
5741 OO.mixinClass( OO.ui.OptionWidget, OO.ui.mixin.AccessKeyedElement );
5742
5743 /* Static Properties */
5744
5745 /**
5746 * Whether this option can be selected. See #setSelected.
5747 *
5748 * @static
5749 * @inheritable
5750 * @property {boolean}
5751 */
5752 OO.ui.OptionWidget.static.selectable = true;
5753
5754 /**
5755 * Whether this option can be highlighted. See #setHighlighted.
5756 *
5757 * @static
5758 * @inheritable
5759 * @property {boolean}
5760 */
5761 OO.ui.OptionWidget.static.highlightable = true;
5762
5763 /**
5764 * Whether this option can be pressed. See #setPressed.
5765 *
5766 * @static
5767 * @inheritable
5768 * @property {boolean}
5769 */
5770 OO.ui.OptionWidget.static.pressable = true;
5771
5772 /**
5773 * Whether this option will be scrolled into view when it is selected.
5774 *
5775 * @static
5776 * @inheritable
5777 * @property {boolean}
5778 */
5779 OO.ui.OptionWidget.static.scrollIntoViewOnSelect = false;
5780
5781 /* Methods */
5782
5783 /**
5784 * Check if the option can be selected.
5785 *
5786 * @return {boolean} Item is selectable
5787 */
5788 OO.ui.OptionWidget.prototype.isSelectable = function () {
5789 return this.constructor.static.selectable && !this.isDisabled() && this.isVisible();
5790 };
5791
5792 /**
5793 * Check if the option can be highlighted. A highlight indicates that the option
5794 * may be selected when a user presses enter or clicks. Disabled items cannot
5795 * be highlighted.
5796 *
5797 * @return {boolean} Item is highlightable
5798 */
5799 OO.ui.OptionWidget.prototype.isHighlightable = function () {
5800 return this.constructor.static.highlightable && !this.isDisabled() && this.isVisible();
5801 };
5802
5803 /**
5804 * Check if the option can be pressed. The pressed state occurs when a user mouses
5805 * down on an item, but has not yet let go of the mouse.
5806 *
5807 * @return {boolean} Item is pressable
5808 */
5809 OO.ui.OptionWidget.prototype.isPressable = function () {
5810 return this.constructor.static.pressable && !this.isDisabled() && this.isVisible();
5811 };
5812
5813 /**
5814 * Check if the option is selected.
5815 *
5816 * @return {boolean} Item is selected
5817 */
5818 OO.ui.OptionWidget.prototype.isSelected = function () {
5819 return this.selected;
5820 };
5821
5822 /**
5823 * Check if the option is highlighted. A highlight indicates that the
5824 * item may be selected when a user presses enter or clicks.
5825 *
5826 * @return {boolean} Item is highlighted
5827 */
5828 OO.ui.OptionWidget.prototype.isHighlighted = function () {
5829 return this.highlighted;
5830 };
5831
5832 /**
5833 * Check if the option is pressed. The pressed state occurs when a user mouses
5834 * down on an item, but has not yet let go of the mouse. The item may appear
5835 * selected, but it will not be selected until the user releases the mouse.
5836 *
5837 * @return {boolean} Item is pressed
5838 */
5839 OO.ui.OptionWidget.prototype.isPressed = function () {
5840 return this.pressed;
5841 };
5842
5843 /**
5844 * Set the option’s selected state. In general, all modifications to the selection
5845 * should be handled by the SelectWidget’s {@link OO.ui.SelectWidget#selectItem selectItem( [item] )}
5846 * method instead of this method.
5847 *
5848 * @param {boolean} [state=false] Select option
5849 * @chainable
5850 */
5851 OO.ui.OptionWidget.prototype.setSelected = function ( state ) {
5852 if ( this.constructor.static.selectable ) {
5853 this.selected = !!state;
5854 this.$element
5855 .toggleClass( 'oo-ui-optionWidget-selected', state )
5856 .attr( 'aria-selected', state.toString() );
5857 if ( state && this.constructor.static.scrollIntoViewOnSelect ) {
5858 this.scrollElementIntoView();
5859 }
5860 this.updateThemeClasses();
5861 }
5862 return this;
5863 };
5864
5865 /**
5866 * Set the option’s highlighted state. In general, all programmatic
5867 * modifications to the highlight should be handled by the
5868 * SelectWidget’s {@link OO.ui.SelectWidget#highlightItem highlightItem( [item] )}
5869 * method instead of this method.
5870 *
5871 * @param {boolean} [state=false] Highlight option
5872 * @chainable
5873 */
5874 OO.ui.OptionWidget.prototype.setHighlighted = function ( state ) {
5875 if ( this.constructor.static.highlightable ) {
5876 this.highlighted = !!state;
5877 this.$element.toggleClass( 'oo-ui-optionWidget-highlighted', state );
5878 this.updateThemeClasses();
5879 }
5880 return this;
5881 };
5882
5883 /**
5884 * Set the option’s pressed state. In general, all
5885 * programmatic modifications to the pressed state should be handled by the
5886 * SelectWidget’s {@link OO.ui.SelectWidget#pressItem pressItem( [item] )}
5887 * method instead of this method.
5888 *
5889 * @param {boolean} [state=false] Press option
5890 * @chainable
5891 */
5892 OO.ui.OptionWidget.prototype.setPressed = function ( state ) {
5893 if ( this.constructor.static.pressable ) {
5894 this.pressed = !!state;
5895 this.$element.toggleClass( 'oo-ui-optionWidget-pressed', state );
5896 this.updateThemeClasses();
5897 }
5898 return this;
5899 };
5900
5901 /**
5902 * Get text to match search strings against.
5903 *
5904 * The default implementation returns the label text, but subclasses
5905 * can override this to provide more complex behavior.
5906 *
5907 * @return {string|boolean} String to match search string against
5908 */
5909 OO.ui.OptionWidget.prototype.getMatchText = function () {
5910 var label = this.getLabel();
5911 return typeof label === 'string' ? label : this.$label.text();
5912 };
5913
5914 /**
5915 * A SelectWidget is of a generic selection of options. The OOjs UI library contains several types of
5916 * select widgets, including {@link OO.ui.ButtonSelectWidget button selects},
5917 * {@link OO.ui.RadioSelectWidget radio selects}, and {@link OO.ui.MenuSelectWidget
5918 * menu selects}.
5919 *
5920 * This class should be used together with OO.ui.OptionWidget or OO.ui.DecoratedOptionWidget. For more
5921 * information, please see the [OOjs UI documentation on MediaWiki][1].
5922 *
5923 * @example
5924 * // Example of a select widget with three options
5925 * var select = new OO.ui.SelectWidget( {
5926 * items: [
5927 * new OO.ui.OptionWidget( {
5928 * data: 'a',
5929 * label: 'Option One',
5930 * } ),
5931 * new OO.ui.OptionWidget( {
5932 * data: 'b',
5933 * label: 'Option Two',
5934 * } ),
5935 * new OO.ui.OptionWidget( {
5936 * data: 'c',
5937 * label: 'Option Three',
5938 * } )
5939 * ]
5940 * } );
5941 * $( 'body' ).append( select.$element );
5942 *
5943 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
5944 *
5945 * @abstract
5946 * @class
5947 * @extends OO.ui.Widget
5948 * @mixins OO.ui.mixin.GroupWidget
5949 *
5950 * @constructor
5951 * @param {Object} [config] Configuration options
5952 * @cfg {OO.ui.OptionWidget[]} [items] An array of options to add to the select.
5953 * Options are created with {@link OO.ui.OptionWidget OptionWidget} classes. See
5954 * the [OOjs UI documentation on MediaWiki] [2] for examples.
5955 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
5956 */
5957 OO.ui.SelectWidget = function OoUiSelectWidget( config ) {
5958 // Configuration initialization
5959 config = config || {};
5960
5961 // Parent constructor
5962 OO.ui.SelectWidget.parent.call( this, config );
5963
5964 // Mixin constructors
5965 OO.ui.mixin.GroupWidget.call( this, $.extend( {}, config, { $group: this.$element } ) );
5966
5967 // Properties
5968 this.pressed = false;
5969 this.selecting = null;
5970 this.onMouseUpHandler = this.onMouseUp.bind( this );
5971 this.onMouseMoveHandler = this.onMouseMove.bind( this );
5972 this.onKeyDownHandler = this.onKeyDown.bind( this );
5973 this.onKeyPressHandler = this.onKeyPress.bind( this );
5974 this.keyPressBuffer = '';
5975 this.keyPressBufferTimer = null;
5976 this.blockMouseOverEvents = 0;
5977
5978 // Events
5979 this.connect( this, {
5980 toggle: 'onToggle'
5981 } );
5982 this.$element.on( {
5983 focusin: this.onFocus.bind( this ),
5984 mousedown: this.onMouseDown.bind( this ),
5985 mouseover: this.onMouseOver.bind( this ),
5986 mouseleave: this.onMouseLeave.bind( this )
5987 } );
5988
5989 // Initialization
5990 this.$element
5991 .addClass( 'oo-ui-selectWidget oo-ui-selectWidget-depressed' )
5992 .attr( 'role', 'listbox' );
5993 this.setFocusOwner( this.$element );
5994 if ( Array.isArray( config.items ) ) {
5995 this.addItems( config.items );
5996 }
5997 };
5998
5999 /* Setup */
6000
6001 OO.inheritClass( OO.ui.SelectWidget, OO.ui.Widget );
6002 OO.mixinClass( OO.ui.SelectWidget, OO.ui.mixin.GroupWidget );
6003
6004 /* Events */
6005
6006 /**
6007 * @event highlight
6008 *
6009 * A `highlight` event is emitted when the highlight is changed with the #highlightItem method.
6010 *
6011 * @param {OO.ui.OptionWidget|null} item Highlighted item
6012 */
6013
6014 /**
6015 * @event press
6016 *
6017 * A `press` event is emitted when the #pressItem method is used to programmatically modify the
6018 * pressed state of an option.
6019 *
6020 * @param {OO.ui.OptionWidget|null} item Pressed item
6021 */
6022
6023 /**
6024 * @event select
6025 *
6026 * A `select` event is emitted when the selection is modified programmatically with the #selectItem method.
6027 *
6028 * @param {OO.ui.OptionWidget|null} item Selected item
6029 */
6030
6031 /**
6032 * @event choose
6033 * A `choose` event is emitted when an item is chosen with the #chooseItem method.
6034 * @param {OO.ui.OptionWidget} item Chosen item
6035 */
6036
6037 /**
6038 * @event add
6039 *
6040 * An `add` event is emitted when options are added to the select with the #addItems method.
6041 *
6042 * @param {OO.ui.OptionWidget[]} items Added items
6043 * @param {number} index Index of insertion point
6044 */
6045
6046 /**
6047 * @event remove
6048 *
6049 * A `remove` event is emitted when options are removed from the select with the #clearItems
6050 * or #removeItems methods.
6051 *
6052 * @param {OO.ui.OptionWidget[]} items Removed items
6053 */
6054
6055 /* Methods */
6056
6057 /**
6058 * Handle focus events
6059 *
6060 * @private
6061 * @param {jQuery.Event} event
6062 */
6063 OO.ui.SelectWidget.prototype.onFocus = function ( event ) {
6064 var item;
6065 if ( event.target === this.$element[ 0 ] ) {
6066 // This widget was focussed, e.g. by the user tabbing to it.
6067 // The styles for focus state depend on one of the items being selected.
6068 if ( !this.getSelectedItem() ) {
6069 item = this.getFirstSelectableItem();
6070 }
6071 } else {
6072 // One of the options got focussed (and the event bubbled up here).
6073 // They can't be tabbed to, but they can be activated using accesskeys.
6074 item = this.getTargetItem( event );
6075 }
6076
6077 if ( item ) {
6078 if ( item.constructor.static.highlightable ) {
6079 this.highlightItem( item );
6080 } else {
6081 this.selectItem( item );
6082 }
6083 }
6084
6085 if ( event.target !== this.$element[ 0 ] ) {
6086 this.$focusOwner.focus();
6087 }
6088 };
6089
6090 /**
6091 * Handle mouse down events.
6092 *
6093 * @private
6094 * @param {jQuery.Event} e Mouse down event
6095 */
6096 OO.ui.SelectWidget.prototype.onMouseDown = function ( e ) {
6097 var item;
6098
6099 if ( !this.isDisabled() && e.which === OO.ui.MouseButtons.LEFT ) {
6100 this.togglePressed( true );
6101 item = this.getTargetItem( e );
6102 if ( item && item.isSelectable() ) {
6103 this.pressItem( item );
6104 this.selecting = item;
6105 this.getElementDocument().addEventListener( 'mouseup', this.onMouseUpHandler, true );
6106 this.getElementDocument().addEventListener( 'mousemove', this.onMouseMoveHandler, true );
6107 }
6108 }
6109 return false;
6110 };
6111
6112 /**
6113 * Handle mouse up events.
6114 *
6115 * @private
6116 * @param {MouseEvent} e Mouse up event
6117 */
6118 OO.ui.SelectWidget.prototype.onMouseUp = function ( e ) {
6119 var item;
6120
6121 this.togglePressed( false );
6122 if ( !this.selecting ) {
6123 item = this.getTargetItem( e );
6124 if ( item && item.isSelectable() ) {
6125 this.selecting = item;
6126 }
6127 }
6128 if ( !this.isDisabled() && e.which === OO.ui.MouseButtons.LEFT && this.selecting ) {
6129 this.pressItem( null );
6130 this.chooseItem( this.selecting );
6131 this.selecting = null;
6132 }
6133
6134 this.getElementDocument().removeEventListener( 'mouseup', this.onMouseUpHandler, true );
6135 this.getElementDocument().removeEventListener( 'mousemove', this.onMouseMoveHandler, true );
6136
6137 return false;
6138 };
6139
6140 /**
6141 * Handle mouse move events.
6142 *
6143 * @private
6144 * @param {MouseEvent} e Mouse move event
6145 */
6146 OO.ui.SelectWidget.prototype.onMouseMove = function ( e ) {
6147 var item;
6148
6149 if ( !this.isDisabled() && this.pressed ) {
6150 item = this.getTargetItem( e );
6151 if ( item && item !== this.selecting && item.isSelectable() ) {
6152 this.pressItem( item );
6153 this.selecting = item;
6154 }
6155 }
6156 };
6157
6158 /**
6159 * Handle mouse over events.
6160 *
6161 * @private
6162 * @param {jQuery.Event} e Mouse over event
6163 */
6164 OO.ui.SelectWidget.prototype.onMouseOver = function ( e ) {
6165 var item;
6166 if ( this.blockMouseOverEvents ) {
6167 return;
6168 }
6169 if ( !this.isDisabled() ) {
6170 item = this.getTargetItem( e );
6171 this.highlightItem( item && item.isHighlightable() ? item : null );
6172 }
6173 return false;
6174 };
6175
6176 /**
6177 * Handle mouse leave events.
6178 *
6179 * @private
6180 * @param {jQuery.Event} e Mouse over event
6181 */
6182 OO.ui.SelectWidget.prototype.onMouseLeave = function () {
6183 if ( !this.isDisabled() ) {
6184 this.highlightItem( null );
6185 }
6186 return false;
6187 };
6188
6189 /**
6190 * Handle key down events.
6191 *
6192 * @protected
6193 * @param {KeyboardEvent} e Key down event
6194 */
6195 OO.ui.SelectWidget.prototype.onKeyDown = function ( e ) {
6196 var nextItem,
6197 handled = false,
6198 currentItem = this.getHighlightedItem() || this.getSelectedItem();
6199
6200 if ( !this.isDisabled() && this.isVisible() ) {
6201 switch ( e.keyCode ) {
6202 case OO.ui.Keys.ENTER:
6203 if ( currentItem && currentItem.constructor.static.highlightable ) {
6204 // Was only highlighted, now let's select it. No-op if already selected.
6205 this.chooseItem( currentItem );
6206 handled = true;
6207 }
6208 break;
6209 case OO.ui.Keys.UP:
6210 case OO.ui.Keys.LEFT:
6211 this.clearKeyPressBuffer();
6212 nextItem = this.getRelativeSelectableItem( currentItem, -1 );
6213 handled = true;
6214 break;
6215 case OO.ui.Keys.DOWN:
6216 case OO.ui.Keys.RIGHT:
6217 this.clearKeyPressBuffer();
6218 nextItem = this.getRelativeSelectableItem( currentItem, 1 );
6219 handled = true;
6220 break;
6221 case OO.ui.Keys.ESCAPE:
6222 case OO.ui.Keys.TAB:
6223 if ( currentItem && currentItem.constructor.static.highlightable ) {
6224 currentItem.setHighlighted( false );
6225 }
6226 this.unbindKeyDownListener();
6227 this.unbindKeyPressListener();
6228 // Don't prevent tabbing away / defocusing
6229 handled = false;
6230 break;
6231 }
6232
6233 if ( nextItem ) {
6234 if ( nextItem.constructor.static.highlightable ) {
6235 this.highlightItem( nextItem );
6236 } else {
6237 this.chooseItem( nextItem );
6238 }
6239 this.scrollItemIntoView( nextItem );
6240 }
6241
6242 if ( handled ) {
6243 e.preventDefault();
6244 e.stopPropagation();
6245 }
6246 }
6247 };
6248
6249 /**
6250 * Bind key down listener.
6251 *
6252 * @protected
6253 */
6254 OO.ui.SelectWidget.prototype.bindKeyDownListener = function () {
6255 this.getElementWindow().addEventListener( 'keydown', this.onKeyDownHandler, true );
6256 };
6257
6258 /**
6259 * Unbind key down listener.
6260 *
6261 * @protected
6262 */
6263 OO.ui.SelectWidget.prototype.unbindKeyDownListener = function () {
6264 this.getElementWindow().removeEventListener( 'keydown', this.onKeyDownHandler, true );
6265 };
6266
6267 /**
6268 * Scroll item into view, preventing spurious mouse highlight actions from happening.
6269 *
6270 * @param {OO.ui.OptionWidget} item Item to scroll into view
6271 */
6272 OO.ui.SelectWidget.prototype.scrollItemIntoView = function ( item ) {
6273 var widget = this;
6274 // Chromium's Blink engine will generate spurious 'mouseover' events during programmatic scrolling
6275 // and around 100-150 ms after it is finished.
6276 this.blockMouseOverEvents++;
6277 item.scrollElementIntoView().done( function () {
6278 setTimeout( function () {
6279 widget.blockMouseOverEvents--;
6280 }, 200 );
6281 } );
6282 };
6283
6284 /**
6285 * Clear the key-press buffer
6286 *
6287 * @protected
6288 */
6289 OO.ui.SelectWidget.prototype.clearKeyPressBuffer = function () {
6290 if ( this.keyPressBufferTimer ) {
6291 clearTimeout( this.keyPressBufferTimer );
6292 this.keyPressBufferTimer = null;
6293 }
6294 this.keyPressBuffer = '';
6295 };
6296
6297 /**
6298 * Handle key press events.
6299 *
6300 * @protected
6301 * @param {KeyboardEvent} e Key press event
6302 */
6303 OO.ui.SelectWidget.prototype.onKeyPress = function ( e ) {
6304 var c, filter, item;
6305
6306 if ( !e.charCode ) {
6307 if ( e.keyCode === OO.ui.Keys.BACKSPACE && this.keyPressBuffer !== '' ) {
6308 this.keyPressBuffer = this.keyPressBuffer.substr( 0, this.keyPressBuffer.length - 1 );
6309 return false;
6310 }
6311 return;
6312 }
6313 if ( String.fromCodePoint ) {
6314 c = String.fromCodePoint( e.charCode );
6315 } else {
6316 c = String.fromCharCode( e.charCode );
6317 }
6318
6319 if ( this.keyPressBufferTimer ) {
6320 clearTimeout( this.keyPressBufferTimer );
6321 }
6322 this.keyPressBufferTimer = setTimeout( this.clearKeyPressBuffer.bind( this ), 1500 );
6323
6324 item = this.getHighlightedItem() || this.getSelectedItem();
6325
6326 if ( this.keyPressBuffer === c ) {
6327 // Common (if weird) special case: typing "xxxx" will cycle through all
6328 // the items beginning with "x".
6329 if ( item ) {
6330 item = this.getRelativeSelectableItem( item, 1 );
6331 }
6332 } else {
6333 this.keyPressBuffer += c;
6334 }
6335
6336 filter = this.getItemMatcher( this.keyPressBuffer, false );
6337 if ( !item || !filter( item ) ) {
6338 item = this.getRelativeSelectableItem( item, 1, filter );
6339 }
6340 if ( item ) {
6341 if ( this.isVisible() && item.constructor.static.highlightable ) {
6342 this.highlightItem( item );
6343 } else {
6344 this.chooseItem( item );
6345 }
6346 this.scrollItemIntoView( item );
6347 }
6348
6349 e.preventDefault();
6350 e.stopPropagation();
6351 };
6352
6353 /**
6354 * Get a matcher for the specific string
6355 *
6356 * @protected
6357 * @param {string} s String to match against items
6358 * @param {boolean} [exact=false] Only accept exact matches
6359 * @return {Function} function ( OO.ui.OptionWidget ) => boolean
6360 */
6361 OO.ui.SelectWidget.prototype.getItemMatcher = function ( s, exact ) {
6362 var re;
6363
6364 if ( s.normalize ) {
6365 s = s.normalize();
6366 }
6367 s = exact ? s.trim() : s.replace( /^\s+/, '' );
6368 re = '^\\s*' + s.replace( /([\\{}()|.?*+\-^$[\]])/g, '\\$1' ).replace( /\s+/g, '\\s+' );
6369 if ( exact ) {
6370 re += '\\s*$';
6371 }
6372 re = new RegExp( re, 'i' );
6373 return function ( item ) {
6374 var matchText = item.getMatchText();
6375 if ( matchText.normalize ) {
6376 matchText = matchText.normalize();
6377 }
6378 return re.test( matchText );
6379 };
6380 };
6381
6382 /**
6383 * Bind key press listener.
6384 *
6385 * @protected
6386 */
6387 OO.ui.SelectWidget.prototype.bindKeyPressListener = function () {
6388 this.getElementWindow().addEventListener( 'keypress', this.onKeyPressHandler, true );
6389 };
6390
6391 /**
6392 * Unbind key down listener.
6393 *
6394 * If you override this, be sure to call this.clearKeyPressBuffer() from your
6395 * implementation.
6396 *
6397 * @protected
6398 */
6399 OO.ui.SelectWidget.prototype.unbindKeyPressListener = function () {
6400 this.getElementWindow().removeEventListener( 'keypress', this.onKeyPressHandler, true );
6401 this.clearKeyPressBuffer();
6402 };
6403
6404 /**
6405 * Visibility change handler
6406 *
6407 * @protected
6408 * @param {boolean} visible
6409 */
6410 OO.ui.SelectWidget.prototype.onToggle = function ( visible ) {
6411 if ( !visible ) {
6412 this.clearKeyPressBuffer();
6413 }
6414 };
6415
6416 /**
6417 * Get the closest item to a jQuery.Event.
6418 *
6419 * @private
6420 * @param {jQuery.Event} e
6421 * @return {OO.ui.OptionWidget|null} Outline item widget, `null` if none was found
6422 */
6423 OO.ui.SelectWidget.prototype.getTargetItem = function ( e ) {
6424 return $( e.target ).closest( '.oo-ui-optionWidget' ).data( 'oo-ui-optionWidget' ) || null;
6425 };
6426
6427 /**
6428 * Get selected item.
6429 *
6430 * @return {OO.ui.OptionWidget|null} Selected item, `null` if no item is selected
6431 */
6432 OO.ui.SelectWidget.prototype.getSelectedItem = function () {
6433 var i, len;
6434
6435 for ( i = 0, len = this.items.length; i < len; i++ ) {
6436 if ( this.items[ i ].isSelected() ) {
6437 return this.items[ i ];
6438 }
6439 }
6440 return null;
6441 };
6442
6443 /**
6444 * Get highlighted item.
6445 *
6446 * @return {OO.ui.OptionWidget|null} Highlighted item, `null` if no item is highlighted
6447 */
6448 OO.ui.SelectWidget.prototype.getHighlightedItem = function () {
6449 var i, len;
6450
6451 for ( i = 0, len = this.items.length; i < len; i++ ) {
6452 if ( this.items[ i ].isHighlighted() ) {
6453 return this.items[ i ];
6454 }
6455 }
6456 return null;
6457 };
6458
6459 /**
6460 * Toggle pressed state.
6461 *
6462 * Press is a state that occurs when a user mouses down on an item, but
6463 * has not yet let go of the mouse. The item may appear selected, but it will not be selected
6464 * until the user releases the mouse.
6465 *
6466 * @param {boolean} pressed An option is being pressed
6467 */
6468 OO.ui.SelectWidget.prototype.togglePressed = function ( pressed ) {
6469 if ( pressed === undefined ) {
6470 pressed = !this.pressed;
6471 }
6472 if ( pressed !== this.pressed ) {
6473 this.$element
6474 .toggleClass( 'oo-ui-selectWidget-pressed', pressed )
6475 .toggleClass( 'oo-ui-selectWidget-depressed', !pressed );
6476 this.pressed = pressed;
6477 }
6478 };
6479
6480 /**
6481 * Highlight an option. If the `item` param is omitted, no options will be highlighted
6482 * and any existing highlight will be removed. The highlight is mutually exclusive.
6483 *
6484 * @param {OO.ui.OptionWidget} [item] Item to highlight, omit for no highlight
6485 * @fires highlight
6486 * @chainable
6487 */
6488 OO.ui.SelectWidget.prototype.highlightItem = function ( item ) {
6489 var i, len, highlighted,
6490 changed = false;
6491
6492 for ( i = 0, len = this.items.length; i < len; i++ ) {
6493 highlighted = this.items[ i ] === item;
6494 if ( this.items[ i ].isHighlighted() !== highlighted ) {
6495 this.items[ i ].setHighlighted( highlighted );
6496 changed = true;
6497 }
6498 }
6499 if ( changed ) {
6500 if ( item ) {
6501 this.$focusOwner.attr( 'aria-activedescendant', item.getElementId() );
6502 } else {
6503 this.$focusOwner.removeAttr( 'aria-activedescendant' );
6504 }
6505 this.emit( 'highlight', item );
6506 }
6507
6508 return this;
6509 };
6510
6511 /**
6512 * Fetch an item by its label.
6513 *
6514 * @param {string} label Label of the item to select.
6515 * @param {boolean} [prefix=false] Allow a prefix match, if only a single item matches
6516 * @return {OO.ui.Element|null} Item with equivalent label, `null` if none exists
6517 */
6518 OO.ui.SelectWidget.prototype.getItemFromLabel = function ( label, prefix ) {
6519 var i, item, found,
6520 len = this.items.length,
6521 filter = this.getItemMatcher( label, true );
6522
6523 for ( i = 0; i < len; i++ ) {
6524 item = this.items[ i ];
6525 if ( item instanceof OO.ui.OptionWidget && item.isSelectable() && filter( item ) ) {
6526 return item;
6527 }
6528 }
6529
6530 if ( prefix ) {
6531 found = null;
6532 filter = this.getItemMatcher( label, false );
6533 for ( i = 0; i < len; i++ ) {
6534 item = this.items[ i ];
6535 if ( item instanceof OO.ui.OptionWidget && item.isSelectable() && filter( item ) ) {
6536 if ( found ) {
6537 return null;
6538 }
6539 found = item;
6540 }
6541 }
6542 if ( found ) {
6543 return found;
6544 }
6545 }
6546
6547 return null;
6548 };
6549
6550 /**
6551 * Programmatically select an option by its label. If the item does not exist,
6552 * all options will be deselected.
6553 *
6554 * @param {string} [label] Label of the item to select.
6555 * @param {boolean} [prefix=false] Allow a prefix match, if only a single item matches
6556 * @fires select
6557 * @chainable
6558 */
6559 OO.ui.SelectWidget.prototype.selectItemByLabel = function ( label, prefix ) {
6560 var itemFromLabel = this.getItemFromLabel( label, !!prefix );
6561 if ( label === undefined || !itemFromLabel ) {
6562 return this.selectItem();
6563 }
6564 return this.selectItem( itemFromLabel );
6565 };
6566
6567 /**
6568 * Programmatically select an option by its data. If the `data` parameter is omitted,
6569 * or if the item does not exist, all options will be deselected.
6570 *
6571 * @param {Object|string} [data] Value of the item to select, omit to deselect all
6572 * @fires select
6573 * @chainable
6574 */
6575 OO.ui.SelectWidget.prototype.selectItemByData = function ( data ) {
6576 var itemFromData = this.getItemFromData( data );
6577 if ( data === undefined || !itemFromData ) {
6578 return this.selectItem();
6579 }
6580 return this.selectItem( itemFromData );
6581 };
6582
6583 /**
6584 * Programmatically select an option by its reference. If the `item` parameter is omitted,
6585 * all options will be deselected.
6586 *
6587 * @param {OO.ui.OptionWidget} [item] Item to select, omit to deselect all
6588 * @fires select
6589 * @chainable
6590 */
6591 OO.ui.SelectWidget.prototype.selectItem = function ( item ) {
6592 var i, len, selected,
6593 changed = false;
6594
6595 for ( i = 0, len = this.items.length; i < len; i++ ) {
6596 selected = this.items[ i ] === item;
6597 if ( this.items[ i ].isSelected() !== selected ) {
6598 this.items[ i ].setSelected( selected );
6599 changed = true;
6600 }
6601 }
6602 if ( changed ) {
6603 if ( item && !item.constructor.static.highlightable ) {
6604 if ( item ) {
6605 this.$focusOwner.attr( 'aria-activedescendant', item.getElementId() );
6606 } else {
6607 this.$focusOwner.removeAttr( 'aria-activedescendant' );
6608 }
6609 }
6610 this.emit( 'select', item );
6611 }
6612
6613 return this;
6614 };
6615
6616 /**
6617 * Press an item.
6618 *
6619 * Press is a state that occurs when a user mouses down on an item, but has not
6620 * yet let go of the mouse. The item may appear selected, but it will not be selected until the user
6621 * releases the mouse.
6622 *
6623 * @param {OO.ui.OptionWidget} [item] Item to press, omit to depress all
6624 * @fires press
6625 * @chainable
6626 */
6627 OO.ui.SelectWidget.prototype.pressItem = function ( item ) {
6628 var i, len, pressed,
6629 changed = false;
6630
6631 for ( i = 0, len = this.items.length; i < len; i++ ) {
6632 pressed = this.items[ i ] === item;
6633 if ( this.items[ i ].isPressed() !== pressed ) {
6634 this.items[ i ].setPressed( pressed );
6635 changed = true;
6636 }
6637 }
6638 if ( changed ) {
6639 this.emit( 'press', item );
6640 }
6641
6642 return this;
6643 };
6644
6645 /**
6646 * Choose an item.
6647 *
6648 * Note that ‘choose’ should never be modified programmatically. A user can choose
6649 * an option with the keyboard or mouse and it becomes selected. To select an item programmatically,
6650 * use the #selectItem method.
6651 *
6652 * This method is identical to #selectItem, but may vary in subclasses that take additional action
6653 * when users choose an item with the keyboard or mouse.
6654 *
6655 * @param {OO.ui.OptionWidget} item Item to choose
6656 * @fires choose
6657 * @chainable
6658 */
6659 OO.ui.SelectWidget.prototype.chooseItem = function ( item ) {
6660 if ( item ) {
6661 this.selectItem( item );
6662 this.emit( 'choose', item );
6663 }
6664
6665 return this;
6666 };
6667
6668 /**
6669 * Get an option by its position relative to the specified item (or to the start of the option array,
6670 * if item is `null`). The direction in which to search through the option array is specified with a
6671 * number: -1 for reverse (the default) or 1 for forward. The method will return an option, or
6672 * `null` if there are no options in the array.
6673 *
6674 * @param {OO.ui.OptionWidget|null} item Item to describe the start position, or `null` to start at the beginning of the array.
6675 * @param {number} direction Direction to move in: -1 to move backward, 1 to move forward
6676 * @param {Function} [filter] Only consider items for which this function returns
6677 * true. Function takes an OO.ui.OptionWidget and returns a boolean.
6678 * @return {OO.ui.OptionWidget|null} Item at position, `null` if there are no items in the select
6679 */
6680 OO.ui.SelectWidget.prototype.getRelativeSelectableItem = function ( item, direction, filter ) {
6681 var currentIndex, nextIndex, i,
6682 increase = direction > 0 ? 1 : -1,
6683 len = this.items.length;
6684
6685 if ( item instanceof OO.ui.OptionWidget ) {
6686 currentIndex = this.items.indexOf( item );
6687 nextIndex = ( currentIndex + increase + len ) % len;
6688 } else {
6689 // If no item is selected and moving forward, start at the beginning.
6690 // If moving backward, start at the end.
6691 nextIndex = direction > 0 ? 0 : len - 1;
6692 }
6693
6694 for ( i = 0; i < len; i++ ) {
6695 item = this.items[ nextIndex ];
6696 if (
6697 item instanceof OO.ui.OptionWidget && item.isSelectable() &&
6698 ( !filter || filter( item ) )
6699 ) {
6700 return item;
6701 }
6702 nextIndex = ( nextIndex + increase + len ) % len;
6703 }
6704 return null;
6705 };
6706
6707 /**
6708 * Get the next selectable item or `null` if there are no selectable items.
6709 * Disabled options and menu-section markers and breaks are not selectable.
6710 *
6711 * @return {OO.ui.OptionWidget|null} Item, `null` if there aren't any selectable items
6712 */
6713 OO.ui.SelectWidget.prototype.getFirstSelectableItem = function () {
6714 return this.getRelativeSelectableItem( null, 1 );
6715 };
6716
6717 /**
6718 * Add an array of options to the select. Optionally, an index number can be used to
6719 * specify an insertion point.
6720 *
6721 * @param {OO.ui.OptionWidget[]} items Items to add
6722 * @param {number} [index] Index to insert items after
6723 * @fires add
6724 * @chainable
6725 */
6726 OO.ui.SelectWidget.prototype.addItems = function ( items, index ) {
6727 // Mixin method
6728 OO.ui.mixin.GroupWidget.prototype.addItems.call( this, items, index );
6729
6730 // Always provide an index, even if it was omitted
6731 this.emit( 'add', items, index === undefined ? this.items.length - items.length - 1 : index );
6732
6733 return this;
6734 };
6735
6736 /**
6737 * Remove the specified array of options from the select. Options will be detached
6738 * from the DOM, not removed, so they can be reused later. To remove all options from
6739 * the select, you may wish to use the #clearItems method instead.
6740 *
6741 * @param {OO.ui.OptionWidget[]} items Items to remove
6742 * @fires remove
6743 * @chainable
6744 */
6745 OO.ui.SelectWidget.prototype.removeItems = function ( items ) {
6746 var i, len, item;
6747
6748 // Deselect items being removed
6749 for ( i = 0, len = items.length; i < len; i++ ) {
6750 item = items[ i ];
6751 if ( item.isSelected() ) {
6752 this.selectItem( null );
6753 }
6754 }
6755
6756 // Mixin method
6757 OO.ui.mixin.GroupWidget.prototype.removeItems.call( this, items );
6758
6759 this.emit( 'remove', items );
6760
6761 return this;
6762 };
6763
6764 /**
6765 * Clear all options from the select. Options will be detached from the DOM, not removed,
6766 * so that they can be reused later. To remove a subset of options from the select, use
6767 * the #removeItems method.
6768 *
6769 * @fires remove
6770 * @chainable
6771 */
6772 OO.ui.SelectWidget.prototype.clearItems = function () {
6773 var items = this.items.slice();
6774
6775 // Mixin method
6776 OO.ui.mixin.GroupWidget.prototype.clearItems.call( this );
6777
6778 // Clear selection
6779 this.selectItem( null );
6780
6781 this.emit( 'remove', items );
6782
6783 return this;
6784 };
6785
6786 /**
6787 * Set the DOM element which has focus while the user is interacting with this SelectWidget.
6788 *
6789 * Currently this is just used to set `aria-activedescendant` on it.
6790 *
6791 * @protected
6792 * @param {jQuery} $focusOwner
6793 */
6794 OO.ui.SelectWidget.prototype.setFocusOwner = function ( $focusOwner ) {
6795 this.$focusOwner = $focusOwner;
6796 };
6797
6798 /**
6799 * DecoratedOptionWidgets are {@link OO.ui.OptionWidget options} that can be configured
6800 * with an {@link OO.ui.mixin.IconElement icon} and/or {@link OO.ui.mixin.IndicatorElement indicator}.
6801 * This class is used with OO.ui.SelectWidget to create a selection of mutually exclusive
6802 * options. For more information about options and selects, please see the
6803 * [OOjs UI documentation on MediaWiki][1].
6804 *
6805 * @example
6806 * // Decorated options in a select widget
6807 * var select = new OO.ui.SelectWidget( {
6808 * items: [
6809 * new OO.ui.DecoratedOptionWidget( {
6810 * data: 'a',
6811 * label: 'Option with icon',
6812 * icon: 'help'
6813 * } ),
6814 * new OO.ui.DecoratedOptionWidget( {
6815 * data: 'b',
6816 * label: 'Option with indicator',
6817 * indicator: 'next'
6818 * } )
6819 * ]
6820 * } );
6821 * $( 'body' ).append( select.$element );
6822 *
6823 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
6824 *
6825 * @class
6826 * @extends OO.ui.OptionWidget
6827 * @mixins OO.ui.mixin.IconElement
6828 * @mixins OO.ui.mixin.IndicatorElement
6829 *
6830 * @constructor
6831 * @param {Object} [config] Configuration options
6832 */
6833 OO.ui.DecoratedOptionWidget = function OoUiDecoratedOptionWidget( config ) {
6834 // Parent constructor
6835 OO.ui.DecoratedOptionWidget.parent.call( this, config );
6836
6837 // Mixin constructors
6838 OO.ui.mixin.IconElement.call( this, config );
6839 OO.ui.mixin.IndicatorElement.call( this, config );
6840
6841 // Initialization
6842 this.$element
6843 .addClass( 'oo-ui-decoratedOptionWidget' )
6844 .prepend( this.$icon )
6845 .append( this.$indicator );
6846 };
6847
6848 /* Setup */
6849
6850 OO.inheritClass( OO.ui.DecoratedOptionWidget, OO.ui.OptionWidget );
6851 OO.mixinClass( OO.ui.DecoratedOptionWidget, OO.ui.mixin.IconElement );
6852 OO.mixinClass( OO.ui.DecoratedOptionWidget, OO.ui.mixin.IndicatorElement );
6853
6854 /**
6855 * MenuOptionWidget is an option widget that looks like a menu item. The class is used with
6856 * OO.ui.MenuSelectWidget to create a menu of mutually exclusive options. Please see
6857 * the [OOjs UI documentation on MediaWiki] [1] for more information.
6858 *
6859 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
6860 *
6861 * @class
6862 * @extends OO.ui.DecoratedOptionWidget
6863 *
6864 * @constructor
6865 * @param {Object} [config] Configuration options
6866 */
6867 OO.ui.MenuOptionWidget = function OoUiMenuOptionWidget( config ) {
6868 // Parent constructor
6869 OO.ui.MenuOptionWidget.parent.call( this, config );
6870
6871 // Initialization
6872 this.$element.addClass( 'oo-ui-menuOptionWidget' );
6873 };
6874
6875 /* Setup */
6876
6877 OO.inheritClass( OO.ui.MenuOptionWidget, OO.ui.DecoratedOptionWidget );
6878
6879 /* Static Properties */
6880
6881 /**
6882 * @static
6883 * @inheritdoc
6884 */
6885 OO.ui.MenuOptionWidget.static.scrollIntoViewOnSelect = true;
6886
6887 /**
6888 * MenuSectionOptionWidgets are used inside {@link OO.ui.MenuSelectWidget menu select widgets} to group one or more related
6889 * {@link OO.ui.MenuOptionWidget menu options}. MenuSectionOptionWidgets cannot be highlighted or selected.
6890 *
6891 * @example
6892 * var myDropdown = new OO.ui.DropdownWidget( {
6893 * menu: {
6894 * items: [
6895 * new OO.ui.MenuSectionOptionWidget( {
6896 * label: 'Dogs'
6897 * } ),
6898 * new OO.ui.MenuOptionWidget( {
6899 * data: 'corgi',
6900 * label: 'Welsh Corgi'
6901 * } ),
6902 * new OO.ui.MenuOptionWidget( {
6903 * data: 'poodle',
6904 * label: 'Standard Poodle'
6905 * } ),
6906 * new OO.ui.MenuSectionOptionWidget( {
6907 * label: 'Cats'
6908 * } ),
6909 * new OO.ui.MenuOptionWidget( {
6910 * data: 'lion',
6911 * label: 'Lion'
6912 * } )
6913 * ]
6914 * }
6915 * } );
6916 * $( 'body' ).append( myDropdown.$element );
6917 *
6918 * @class
6919 * @extends OO.ui.DecoratedOptionWidget
6920 *
6921 * @constructor
6922 * @param {Object} [config] Configuration options
6923 */
6924 OO.ui.MenuSectionOptionWidget = function OoUiMenuSectionOptionWidget( config ) {
6925 // Parent constructor
6926 OO.ui.MenuSectionOptionWidget.parent.call( this, config );
6927
6928 // Initialization
6929 this.$element.addClass( 'oo-ui-menuSectionOptionWidget' )
6930 .removeAttr( 'role aria-selected' );
6931 };
6932
6933 /* Setup */
6934
6935 OO.inheritClass( OO.ui.MenuSectionOptionWidget, OO.ui.DecoratedOptionWidget );
6936
6937 /* Static Properties */
6938
6939 /**
6940 * @static
6941 * @inheritdoc
6942 */
6943 OO.ui.MenuSectionOptionWidget.static.selectable = false;
6944
6945 /**
6946 * @static
6947 * @inheritdoc
6948 */
6949 OO.ui.MenuSectionOptionWidget.static.highlightable = false;
6950
6951 /**
6952 * MenuSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains options and
6953 * is used together with OO.ui.MenuOptionWidget. It is designed be used as part of another widget.
6954 * See {@link OO.ui.DropdownWidget DropdownWidget}, {@link OO.ui.ComboBoxInputWidget ComboBoxInputWidget},
6955 * and {@link OO.ui.mixin.LookupElement LookupElement} for examples of widgets that contain menus.
6956 * MenuSelectWidgets themselves are not instantiated directly, rather subclassed
6957 * and customized to be opened, closed, and displayed as needed.
6958 *
6959 * By default, menus are clipped to the visible viewport and are not visible when a user presses the
6960 * mouse outside the menu.
6961 *
6962 * Menus also have support for keyboard interaction:
6963 *
6964 * - Enter/Return key: choose and select a menu option
6965 * - Up-arrow key: highlight the previous menu option
6966 * - Down-arrow key: highlight the next menu option
6967 * - Esc key: hide the menu
6968 *
6969 * Unlike most widgets, MenuSelectWidget is initially hidden and must be shown by calling #toggle.
6970 *
6971 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
6972 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
6973 *
6974 * @class
6975 * @extends OO.ui.SelectWidget
6976 * @mixins OO.ui.mixin.ClippableElement
6977 * @mixins OO.ui.mixin.FloatableElement
6978 *
6979 * @constructor
6980 * @param {Object} [config] Configuration options
6981 * @cfg {OO.ui.TextInputWidget} [input] Text input used to implement option highlighting for menu items that match
6982 * the text the user types. This config is used by {@link OO.ui.ComboBoxInputWidget ComboBoxInputWidget}
6983 * and {@link OO.ui.mixin.LookupElement LookupElement}
6984 * @cfg {jQuery} [$input] Text input used to implement option highlighting for menu items that match
6985 * the text the user types. This config is used by {@link OO.ui.CapsuleMultiselectWidget CapsuleMultiselectWidget}
6986 * @cfg {OO.ui.Widget} [widget] Widget associated with the menu's active state. If the user clicks the mouse
6987 * anywhere on the page outside of this widget, the menu is hidden. For example, if there is a button
6988 * that toggles the menu's visibility on click, the menu will be hidden then re-shown when the user clicks
6989 * that button, unless the button (or its parent widget) is passed in here.
6990 * @cfg {boolean} [autoHide=true] Hide the menu when the mouse is pressed outside the menu.
6991 * @cfg {jQuery} [$autoCloseIgnore] If these elements are clicked, don't auto-hide the menu.
6992 * @cfg {boolean} [hideOnChoose=true] Hide the menu when the user chooses an option.
6993 * @cfg {boolean} [filterFromInput=false] Filter the displayed options from the input
6994 * @cfg {boolean} [highlightOnFilter] Highlight the first result when filtering
6995 * @cfg {number} [width] Width of the menu
6996 */
6997 OO.ui.MenuSelectWidget = function OoUiMenuSelectWidget( config ) {
6998 // Configuration initialization
6999 config = config || {};
7000
7001 // Parent constructor
7002 OO.ui.MenuSelectWidget.parent.call( this, config );
7003
7004 // Mixin constructors
7005 OO.ui.mixin.ClippableElement.call( this, $.extend( {}, config, { $clippable: this.$group } ) );
7006 OO.ui.mixin.FloatableElement.call( this, config );
7007
7008 // Properties
7009 this.autoHide = config.autoHide === undefined || !!config.autoHide;
7010 this.hideOnChoose = config.hideOnChoose === undefined || !!config.hideOnChoose;
7011 this.filterFromInput = !!config.filterFromInput;
7012 this.$input = config.$input ? config.$input : config.input ? config.input.$input : null;
7013 this.$widget = config.widget ? config.widget.$element : null;
7014 this.$autoCloseIgnore = config.$autoCloseIgnore || $( [] );
7015 this.onDocumentMouseDownHandler = this.onDocumentMouseDown.bind( this );
7016 this.onInputEditHandler = OO.ui.debounce( this.updateItemVisibility.bind( this ), 100 );
7017 this.highlightOnFilter = !!config.highlightOnFilter;
7018 this.width = config.width;
7019
7020 // Initialization
7021 this.$element.addClass( 'oo-ui-menuSelectWidget' );
7022 if ( config.widget ) {
7023 this.setFocusOwner( config.widget.$tabIndexed );
7024 }
7025
7026 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
7027 // that reference properties not initialized at that time of parent class construction
7028 // TODO: Find a better way to handle post-constructor setup
7029 this.visible = false;
7030 this.$element.addClass( 'oo-ui-element-hidden' );
7031 };
7032
7033 /* Setup */
7034
7035 OO.inheritClass( OO.ui.MenuSelectWidget, OO.ui.SelectWidget );
7036 OO.mixinClass( OO.ui.MenuSelectWidget, OO.ui.mixin.ClippableElement );
7037 OO.mixinClass( OO.ui.MenuSelectWidget, OO.ui.mixin.FloatableElement );
7038
7039 /* Events */
7040
7041 /**
7042 * @event ready
7043 *
7044 * The menu is ready: it is visible and has been positioned and clipped.
7045 */
7046
7047 /* Methods */
7048
7049 /**
7050 * Handles document mouse down events.
7051 *
7052 * @protected
7053 * @param {MouseEvent} e Mouse down event
7054 */
7055 OO.ui.MenuSelectWidget.prototype.onDocumentMouseDown = function ( e ) {
7056 if (
7057 this.isVisible() &&
7058 !OO.ui.contains(
7059 this.$element.add( this.$widget ).add( this.$autoCloseIgnore ).get(),
7060 e.target,
7061 true
7062 )
7063 ) {
7064 this.toggle( false );
7065 }
7066 };
7067
7068 /**
7069 * @inheritdoc
7070 */
7071 OO.ui.MenuSelectWidget.prototype.onKeyDown = function ( e ) {
7072 var currentItem = this.getHighlightedItem() || this.getSelectedItem();
7073
7074 if ( !this.isDisabled() && this.isVisible() ) {
7075 switch ( e.keyCode ) {
7076 case OO.ui.Keys.LEFT:
7077 case OO.ui.Keys.RIGHT:
7078 // Do nothing if a text field is associated, arrow keys will be handled natively
7079 if ( !this.$input ) {
7080 OO.ui.MenuSelectWidget.parent.prototype.onKeyDown.call( this, e );
7081 }
7082 break;
7083 case OO.ui.Keys.ESCAPE:
7084 case OO.ui.Keys.TAB:
7085 if ( currentItem ) {
7086 currentItem.setHighlighted( false );
7087 }
7088 this.toggle( false );
7089 // Don't prevent tabbing away, prevent defocusing
7090 if ( e.keyCode === OO.ui.Keys.ESCAPE ) {
7091 e.preventDefault();
7092 e.stopPropagation();
7093 }
7094 break;
7095 default:
7096 OO.ui.MenuSelectWidget.parent.prototype.onKeyDown.call( this, e );
7097 return;
7098 }
7099 }
7100 };
7101
7102 /**
7103 * Update menu item visibility and clipping after input changes (if filterFromInput is enabled)
7104 * or after items were added/removed (always).
7105 *
7106 * @protected
7107 */
7108 OO.ui.MenuSelectWidget.prototype.updateItemVisibility = function () {
7109 var i, item, visible, section, sectionEmpty, filter, exactFilter,
7110 firstItemFound = false,
7111 anyVisible = false,
7112 len = this.items.length,
7113 showAll = !this.isVisible(),
7114 exactMatch = false;
7115
7116 if ( this.$input && this.filterFromInput ) {
7117 filter = showAll ? null : this.getItemMatcher( this.$input.val() );
7118 exactFilter = this.getItemMatcher( this.$input.val(), true );
7119
7120 // Hide non-matching options, and also hide section headers if all options
7121 // in their section are hidden.
7122 for ( i = 0; i < len; i++ ) {
7123 item = this.items[ i ];
7124 if ( item instanceof OO.ui.MenuSectionOptionWidget ) {
7125 if ( section ) {
7126 // If the previous section was empty, hide its header
7127 section.toggle( showAll || !sectionEmpty );
7128 }
7129 section = item;
7130 sectionEmpty = true;
7131 } else if ( item instanceof OO.ui.OptionWidget ) {
7132 visible = showAll || filter( item );
7133 exactMatch = exactMatch || exactFilter( item );
7134 anyVisible = anyVisible || visible;
7135 sectionEmpty = sectionEmpty && !visible;
7136 item.toggle( visible );
7137 if ( this.highlightOnFilter && visible && !firstItemFound ) {
7138 // Highlight the first item in the list
7139 this.highlightItem( item );
7140 firstItemFound = true;
7141 }
7142 }
7143 }
7144 // Process the final section
7145 if ( section ) {
7146 section.toggle( showAll || !sectionEmpty );
7147 }
7148
7149 if ( anyVisible && this.items.length && !exactMatch ) {
7150 this.scrollItemIntoView( this.items[ 0 ] );
7151 }
7152
7153 this.$element.toggleClass( 'oo-ui-menuSelectWidget-invisible', !anyVisible );
7154 }
7155
7156 // Reevaluate clipping
7157 this.clip();
7158 };
7159
7160 /**
7161 * @inheritdoc
7162 */
7163 OO.ui.MenuSelectWidget.prototype.bindKeyDownListener = function () {
7164 if ( this.$input ) {
7165 this.$input.on( 'keydown', this.onKeyDownHandler );
7166 } else {
7167 OO.ui.MenuSelectWidget.parent.prototype.bindKeyDownListener.call( this );
7168 }
7169 };
7170
7171 /**
7172 * @inheritdoc
7173 */
7174 OO.ui.MenuSelectWidget.prototype.unbindKeyDownListener = function () {
7175 if ( this.$input ) {
7176 this.$input.off( 'keydown', this.onKeyDownHandler );
7177 } else {
7178 OO.ui.MenuSelectWidget.parent.prototype.unbindKeyDownListener.call( this );
7179 }
7180 };
7181
7182 /**
7183 * @inheritdoc
7184 */
7185 OO.ui.MenuSelectWidget.prototype.bindKeyPressListener = function () {
7186 if ( this.$input ) {
7187 if ( this.filterFromInput ) {
7188 this.$input.on( 'keydown mouseup cut paste change input select', this.onInputEditHandler );
7189 this.updateItemVisibility();
7190 }
7191 } else {
7192 OO.ui.MenuSelectWidget.parent.prototype.bindKeyPressListener.call( this );
7193 }
7194 };
7195
7196 /**
7197 * @inheritdoc
7198 */
7199 OO.ui.MenuSelectWidget.prototype.unbindKeyPressListener = function () {
7200 if ( this.$input ) {
7201 if ( this.filterFromInput ) {
7202 this.$input.off( 'keydown mouseup cut paste change input select', this.onInputEditHandler );
7203 this.updateItemVisibility();
7204 }
7205 } else {
7206 OO.ui.MenuSelectWidget.parent.prototype.unbindKeyPressListener.call( this );
7207 }
7208 };
7209
7210 /**
7211 * Choose an item.
7212 *
7213 * When a user chooses an item, the menu is closed, unless the hideOnChoose config option is set to false.
7214 *
7215 * Note that ‘choose’ should never be modified programmatically. A user can choose an option with the keyboard
7216 * or mouse and it becomes selected. To select an item programmatically, use the #selectItem method.
7217 *
7218 * @param {OO.ui.OptionWidget} item Item to choose
7219 * @chainable
7220 */
7221 OO.ui.MenuSelectWidget.prototype.chooseItem = function ( item ) {
7222 OO.ui.MenuSelectWidget.parent.prototype.chooseItem.call( this, item );
7223 if ( this.hideOnChoose ) {
7224 this.toggle( false );
7225 }
7226 return this;
7227 };
7228
7229 /**
7230 * @inheritdoc
7231 */
7232 OO.ui.MenuSelectWidget.prototype.addItems = function ( items, index ) {
7233 // Parent method
7234 OO.ui.MenuSelectWidget.parent.prototype.addItems.call( this, items, index );
7235
7236 this.updateItemVisibility();
7237
7238 return this;
7239 };
7240
7241 /**
7242 * @inheritdoc
7243 */
7244 OO.ui.MenuSelectWidget.prototype.removeItems = function ( items ) {
7245 // Parent method
7246 OO.ui.MenuSelectWidget.parent.prototype.removeItems.call( this, items );
7247
7248 this.updateItemVisibility();
7249
7250 return this;
7251 };
7252
7253 /**
7254 * @inheritdoc
7255 */
7256 OO.ui.MenuSelectWidget.prototype.clearItems = function () {
7257 // Parent method
7258 OO.ui.MenuSelectWidget.parent.prototype.clearItems.call( this );
7259
7260 this.updateItemVisibility();
7261
7262 return this;
7263 };
7264
7265 /**
7266 * Toggle visibility of the menu. The menu is initially hidden and must be shown by calling
7267 * `.toggle( true )` after its #$element is attached to the DOM.
7268 *
7269 * Do not show the menu while it is not attached to the DOM. The calculations required to display
7270 * it in the right place and with the right dimensions only work correctly while it is attached.
7271 * Side-effects may include broken interface and exceptions being thrown. This wasn't always
7272 * strictly enforced, so currently it only generates a warning in the browser console.
7273 *
7274 * @fires ready
7275 * @inheritdoc
7276 */
7277 OO.ui.MenuSelectWidget.prototype.toggle = function ( visible ) {
7278 var change;
7279
7280 visible = ( visible === undefined ? !this.visible : !!visible ) && !!this.items.length;
7281 change = visible !== this.isVisible();
7282
7283 if ( visible && !this.warnedUnattached && !this.isElementAttached() ) {
7284 OO.ui.warnDeprecation( 'MenuSelectWidget#toggle: Before calling this method, the menu must be attached to the DOM.' );
7285 this.warnedUnattached = true;
7286 }
7287
7288 if ( change && visible && ( this.width || this.$floatableContainer ) ) {
7289 this.setIdealSize( this.width || this.$floatableContainer.width() );
7290 }
7291
7292 // Parent method
7293 OO.ui.MenuSelectWidget.parent.prototype.toggle.call( this, visible );
7294
7295 if ( change ) {
7296 if ( visible ) {
7297 this.bindKeyDownListener();
7298 this.bindKeyPressListener();
7299
7300 this.togglePositioning( !!this.$floatableContainer );
7301 this.toggleClipping( true );
7302
7303 this.$focusOwner.attr( 'aria-expanded', 'true' );
7304
7305 if ( this.getSelectedItem() ) {
7306 this.$focusOwner.attr( 'aria-activedescendant', this.getSelectedItem().getElementId() );
7307 this.getSelectedItem().scrollElementIntoView( { duration: 0 } );
7308 }
7309
7310 // Auto-hide
7311 if ( this.autoHide ) {
7312 this.getElementDocument().addEventListener( 'mousedown', this.onDocumentMouseDownHandler, true );
7313 }
7314
7315 this.emit( 'ready' );
7316 } else {
7317 this.$focusOwner.removeAttr( 'aria-activedescendant' );
7318 this.unbindKeyDownListener();
7319 this.unbindKeyPressListener();
7320 this.$focusOwner.attr( 'aria-expanded', 'false' );
7321 this.getElementDocument().removeEventListener( 'mousedown', this.onDocumentMouseDownHandler, true );
7322 this.togglePositioning( false );
7323 this.toggleClipping( false );
7324 }
7325 }
7326
7327 return this;
7328 };
7329
7330 /**
7331 * DropdownWidgets are not menus themselves, rather they contain a menu of options created with
7332 * OO.ui.MenuOptionWidget. The DropdownWidget takes care of opening and displaying the menu so that
7333 * users can interact with it.
7334 *
7335 * If you want to use this within an HTML form, such as a OO.ui.FormLayout, use
7336 * OO.ui.DropdownInputWidget instead.
7337 *
7338 * @example
7339 * // Example: A DropdownWidget with a menu that contains three options
7340 * var dropDown = new OO.ui.DropdownWidget( {
7341 * label: 'Dropdown menu: Select a menu option',
7342 * menu: {
7343 * items: [
7344 * new OO.ui.MenuOptionWidget( {
7345 * data: 'a',
7346 * label: 'First'
7347 * } ),
7348 * new OO.ui.MenuOptionWidget( {
7349 * data: 'b',
7350 * label: 'Second'
7351 * } ),
7352 * new OO.ui.MenuOptionWidget( {
7353 * data: 'c',
7354 * label: 'Third'
7355 * } )
7356 * ]
7357 * }
7358 * } );
7359 *
7360 * $( 'body' ).append( dropDown.$element );
7361 *
7362 * dropDown.getMenu().selectItemByData( 'b' );
7363 *
7364 * dropDown.getMenu().getSelectedItem().getData(); // returns 'b'
7365 *
7366 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
7367 *
7368 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
7369 *
7370 * @class
7371 * @extends OO.ui.Widget
7372 * @mixins OO.ui.mixin.IconElement
7373 * @mixins OO.ui.mixin.IndicatorElement
7374 * @mixins OO.ui.mixin.LabelElement
7375 * @mixins OO.ui.mixin.TitledElement
7376 * @mixins OO.ui.mixin.TabIndexedElement
7377 *
7378 * @constructor
7379 * @param {Object} [config] Configuration options
7380 * @cfg {Object} [menu] Configuration options to pass to {@link OO.ui.MenuSelectWidget menu select widget}
7381 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
7382 * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
7383 * containing `<div>` and has a larger area. By default, the menu uses relative positioning.
7384 * See <https://www.mediawiki.org/wiki/OOjs_UI/Concepts#Overlays>.
7385 */
7386 OO.ui.DropdownWidget = function OoUiDropdownWidget( config ) {
7387 // Configuration initialization
7388 config = $.extend( { indicator: 'down' }, config );
7389
7390 // Parent constructor
7391 OO.ui.DropdownWidget.parent.call( this, config );
7392
7393 // Properties (must be set before TabIndexedElement constructor call)
7394 this.$handle = this.$( '<span>' );
7395 this.$overlay = config.$overlay || this.$element;
7396
7397 // Mixin constructors
7398 OO.ui.mixin.IconElement.call( this, config );
7399 OO.ui.mixin.IndicatorElement.call( this, config );
7400 OO.ui.mixin.LabelElement.call( this, config );
7401 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$label } ) );
7402 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$handle } ) );
7403
7404 // Properties
7405 this.menu = new OO.ui.MenuSelectWidget( $.extend( {
7406 widget: this,
7407 $floatableContainer: this.$element
7408 }, config.menu ) );
7409
7410 // Events
7411 this.$handle.on( {
7412 click: this.onClick.bind( this ),
7413 keydown: this.onKeyDown.bind( this ),
7414 // Hack? Handle type-to-search when menu is not expanded and not handling its own events
7415 keypress: this.menu.onKeyPressHandler,
7416 blur: this.menu.clearKeyPressBuffer.bind( this.menu )
7417 } );
7418 this.menu.connect( this, {
7419 select: 'onMenuSelect',
7420 toggle: 'onMenuToggle'
7421 } );
7422
7423 // Initialization
7424 this.$handle
7425 .addClass( 'oo-ui-dropdownWidget-handle' )
7426 .attr( {
7427 role: 'combobox',
7428 'aria-owns': this.menu.getElementId(),
7429 'aria-autocomplete': 'list'
7430 } )
7431 .append( this.$icon, this.$label, this.$indicator );
7432 this.$element
7433 .addClass( 'oo-ui-dropdownWidget' )
7434 .append( this.$handle );
7435 this.$overlay.append( this.menu.$element );
7436 };
7437
7438 /* Setup */
7439
7440 OO.inheritClass( OO.ui.DropdownWidget, OO.ui.Widget );
7441 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.IconElement );
7442 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.IndicatorElement );
7443 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.LabelElement );
7444 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.TitledElement );
7445 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.TabIndexedElement );
7446
7447 /* Methods */
7448
7449 /**
7450 * Get the menu.
7451 *
7452 * @return {OO.ui.MenuSelectWidget} Menu of widget
7453 */
7454 OO.ui.DropdownWidget.prototype.getMenu = function () {
7455 return this.menu;
7456 };
7457
7458 /**
7459 * Handles menu select events.
7460 *
7461 * @private
7462 * @param {OO.ui.MenuOptionWidget} item Selected menu item
7463 */
7464 OO.ui.DropdownWidget.prototype.onMenuSelect = function ( item ) {
7465 var selectedLabel;
7466
7467 if ( !item ) {
7468 this.setLabel( null );
7469 return;
7470 }
7471
7472 selectedLabel = item.getLabel();
7473
7474 // If the label is a DOM element, clone it, because setLabel will append() it
7475 if ( selectedLabel instanceof jQuery ) {
7476 selectedLabel = selectedLabel.clone();
7477 }
7478
7479 this.setLabel( selectedLabel );
7480 };
7481
7482 /**
7483 * Handle menu toggle events.
7484 *
7485 * @private
7486 * @param {boolean} isVisible Menu toggle event
7487 */
7488 OO.ui.DropdownWidget.prototype.onMenuToggle = function ( isVisible ) {
7489 this.$element.toggleClass( 'oo-ui-dropdownWidget-open', isVisible );
7490 this.$handle.attr(
7491 'aria-expanded',
7492 this.$element.hasClass( 'oo-ui-dropdownWidget-open' ).toString()
7493 );
7494 };
7495
7496 /**
7497 * Handle mouse click events.
7498 *
7499 * @private
7500 * @param {jQuery.Event} e Mouse click event
7501 */
7502 OO.ui.DropdownWidget.prototype.onClick = function ( e ) {
7503 if ( !this.isDisabled() && e.which === OO.ui.MouseButtons.LEFT ) {
7504 this.menu.toggle();
7505 }
7506 return false;
7507 };
7508
7509 /**
7510 * Handle key down events.
7511 *
7512 * @private
7513 * @param {jQuery.Event} e Key down event
7514 */
7515 OO.ui.DropdownWidget.prototype.onKeyDown = function ( e ) {
7516 if (
7517 !this.isDisabled() &&
7518 (
7519 e.which === OO.ui.Keys.ENTER ||
7520 (
7521 !this.menu.isVisible() &&
7522 (
7523 e.which === OO.ui.Keys.SPACE ||
7524 e.which === OO.ui.Keys.UP ||
7525 e.which === OO.ui.Keys.DOWN
7526 )
7527 )
7528 )
7529 ) {
7530 this.menu.toggle();
7531 return false;
7532 }
7533 };
7534
7535 /**
7536 * RadioOptionWidget is an option widget that looks like a radio button.
7537 * The class is used with OO.ui.RadioSelectWidget to create a selection of radio options.
7538 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information.
7539 *
7540 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Button_selects_and_option
7541 *
7542 * @class
7543 * @extends OO.ui.OptionWidget
7544 *
7545 * @constructor
7546 * @param {Object} [config] Configuration options
7547 */
7548 OO.ui.RadioOptionWidget = function OoUiRadioOptionWidget( config ) {
7549 // Configuration initialization
7550 config = config || {};
7551
7552 // Properties (must be done before parent constructor which calls #setDisabled)
7553 this.radio = new OO.ui.RadioInputWidget( { value: config.data, tabIndex: -1 } );
7554
7555 // Parent constructor
7556 OO.ui.RadioOptionWidget.parent.call( this, config );
7557
7558 // Initialization
7559 // Remove implicit role, we're handling it ourselves
7560 this.radio.$input.attr( 'role', 'presentation' );
7561 this.$element
7562 .addClass( 'oo-ui-radioOptionWidget' )
7563 .attr( 'role', 'radio' )
7564 .attr( 'aria-checked', 'false' )
7565 .removeAttr( 'aria-selected' )
7566 .prepend( this.radio.$element );
7567 };
7568
7569 /* Setup */
7570
7571 OO.inheritClass( OO.ui.RadioOptionWidget, OO.ui.OptionWidget );
7572
7573 /* Static Properties */
7574
7575 /**
7576 * @static
7577 * @inheritdoc
7578 */
7579 OO.ui.RadioOptionWidget.static.highlightable = false;
7580
7581 /**
7582 * @static
7583 * @inheritdoc
7584 */
7585 OO.ui.RadioOptionWidget.static.scrollIntoViewOnSelect = true;
7586
7587 /**
7588 * @static
7589 * @inheritdoc
7590 */
7591 OO.ui.RadioOptionWidget.static.pressable = false;
7592
7593 /**
7594 * @static
7595 * @inheritdoc
7596 */
7597 OO.ui.RadioOptionWidget.static.tagName = 'label';
7598
7599 /* Methods */
7600
7601 /**
7602 * @inheritdoc
7603 */
7604 OO.ui.RadioOptionWidget.prototype.setSelected = function ( state ) {
7605 OO.ui.RadioOptionWidget.parent.prototype.setSelected.call( this, state );
7606
7607 this.radio.setSelected( state );
7608 this.$element
7609 .attr( 'aria-checked', state.toString() )
7610 .removeAttr( 'aria-selected' );
7611
7612 return this;
7613 };
7614
7615 /**
7616 * @inheritdoc
7617 */
7618 OO.ui.RadioOptionWidget.prototype.setDisabled = function ( disabled ) {
7619 OO.ui.RadioOptionWidget.parent.prototype.setDisabled.call( this, disabled );
7620
7621 this.radio.setDisabled( this.isDisabled() );
7622
7623 return this;
7624 };
7625
7626 /**
7627 * RadioSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains radio
7628 * options and is used together with OO.ui.RadioOptionWidget. The RadioSelectWidget provides
7629 * an interface for adding, removing and selecting options.
7630 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
7631 *
7632 * If you want to use this within an HTML form, such as a OO.ui.FormLayout, use
7633 * OO.ui.RadioSelectInputWidget instead.
7634 *
7635 * @example
7636 * // A RadioSelectWidget with RadioOptions.
7637 * var option1 = new OO.ui.RadioOptionWidget( {
7638 * data: 'a',
7639 * label: 'Selected radio option'
7640 * } );
7641 *
7642 * var option2 = new OO.ui.RadioOptionWidget( {
7643 * data: 'b',
7644 * label: 'Unselected radio option'
7645 * } );
7646 *
7647 * var radioSelect=new OO.ui.RadioSelectWidget( {
7648 * items: [ option1, option2 ]
7649 * } );
7650 *
7651 * // Select 'option 1' using the RadioSelectWidget's selectItem() method.
7652 * radioSelect.selectItem( option1 );
7653 *
7654 * $( 'body' ).append( radioSelect.$element );
7655 *
7656 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
7657
7658 *
7659 * @class
7660 * @extends OO.ui.SelectWidget
7661 * @mixins OO.ui.mixin.TabIndexedElement
7662 *
7663 * @constructor
7664 * @param {Object} [config] Configuration options
7665 */
7666 OO.ui.RadioSelectWidget = function OoUiRadioSelectWidget( config ) {
7667 // Parent constructor
7668 OO.ui.RadioSelectWidget.parent.call( this, config );
7669
7670 // Mixin constructors
7671 OO.ui.mixin.TabIndexedElement.call( this, config );
7672
7673 // Events
7674 this.$element.on( {
7675 focus: this.bindKeyDownListener.bind( this ),
7676 blur: this.unbindKeyDownListener.bind( this )
7677 } );
7678
7679 // Initialization
7680 this.$element
7681 .addClass( 'oo-ui-radioSelectWidget' )
7682 .attr( 'role', 'radiogroup' );
7683 };
7684
7685 /* Setup */
7686
7687 OO.inheritClass( OO.ui.RadioSelectWidget, OO.ui.SelectWidget );
7688 OO.mixinClass( OO.ui.RadioSelectWidget, OO.ui.mixin.TabIndexedElement );
7689
7690 /**
7691 * MultioptionWidgets are special elements that can be selected and configured with data. The
7692 * data is often unique for each option, but it does not have to be. MultioptionWidgets are used
7693 * with OO.ui.SelectWidget to create a selection of mutually exclusive options. For more information
7694 * and examples, please see the [OOjs UI documentation on MediaWiki][1].
7695 *
7696 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Multioptions
7697 *
7698 * @class
7699 * @extends OO.ui.Widget
7700 * @mixins OO.ui.mixin.ItemWidget
7701 * @mixins OO.ui.mixin.LabelElement
7702 *
7703 * @constructor
7704 * @param {Object} [config] Configuration options
7705 * @cfg {boolean} [selected=false] Whether the option is initially selected
7706 */
7707 OO.ui.MultioptionWidget = function OoUiMultioptionWidget( config ) {
7708 // Configuration initialization
7709 config = config || {};
7710
7711 // Parent constructor
7712 OO.ui.MultioptionWidget.parent.call( this, config );
7713
7714 // Mixin constructors
7715 OO.ui.mixin.ItemWidget.call( this );
7716 OO.ui.mixin.LabelElement.call( this, config );
7717
7718 // Properties
7719 this.selected = null;
7720
7721 // Initialization
7722 this.$element
7723 .addClass( 'oo-ui-multioptionWidget' )
7724 .append( this.$label );
7725 this.setSelected( config.selected );
7726 };
7727
7728 /* Setup */
7729
7730 OO.inheritClass( OO.ui.MultioptionWidget, OO.ui.Widget );
7731 OO.mixinClass( OO.ui.MultioptionWidget, OO.ui.mixin.ItemWidget );
7732 OO.mixinClass( OO.ui.MultioptionWidget, OO.ui.mixin.LabelElement );
7733
7734 /* Events */
7735
7736 /**
7737 * @event change
7738 *
7739 * A change event is emitted when the selected state of the option changes.
7740 *
7741 * @param {boolean} selected Whether the option is now selected
7742 */
7743
7744 /* Methods */
7745
7746 /**
7747 * Check if the option is selected.
7748 *
7749 * @return {boolean} Item is selected
7750 */
7751 OO.ui.MultioptionWidget.prototype.isSelected = function () {
7752 return this.selected;
7753 };
7754
7755 /**
7756 * Set the option’s selected state. In general, all modifications to the selection
7757 * should be handled by the SelectWidget’s {@link OO.ui.SelectWidget#selectItem selectItem( [item] )}
7758 * method instead of this method.
7759 *
7760 * @param {boolean} [state=false] Select option
7761 * @chainable
7762 */
7763 OO.ui.MultioptionWidget.prototype.setSelected = function ( state ) {
7764 state = !!state;
7765 if ( this.selected !== state ) {
7766 this.selected = state;
7767 this.emit( 'change', state );
7768 this.$element.toggleClass( 'oo-ui-multioptionWidget-selected', state );
7769 }
7770 return this;
7771 };
7772
7773 /**
7774 * MultiselectWidget allows selecting multiple options from a list.
7775 *
7776 * For more information about menus and options, please see the [OOjs UI documentation on MediaWiki][1].
7777 *
7778 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
7779 *
7780 * @class
7781 * @abstract
7782 * @extends OO.ui.Widget
7783 * @mixins OO.ui.mixin.GroupWidget
7784 *
7785 * @constructor
7786 * @param {Object} [config] Configuration options
7787 * @cfg {OO.ui.MultioptionWidget[]} [items] An array of options to add to the multiselect.
7788 */
7789 OO.ui.MultiselectWidget = function OoUiMultiselectWidget( config ) {
7790 // Parent constructor
7791 OO.ui.MultiselectWidget.parent.call( this, config );
7792
7793 // Configuration initialization
7794 config = config || {};
7795
7796 // Mixin constructors
7797 OO.ui.mixin.GroupWidget.call( this, config );
7798
7799 // Events
7800 this.aggregate( { change: 'select' } );
7801 // This is mostly for compatibility with CapsuleMultiselectWidget... normally, 'change' is emitted
7802 // by GroupElement only when items are added/removed
7803 this.connect( this, { select: [ 'emit', 'change' ] } );
7804
7805 // Initialization
7806 if ( config.items ) {
7807 this.addItems( config.items );
7808 }
7809 this.$group.addClass( 'oo-ui-multiselectWidget-group' );
7810 this.$element.addClass( 'oo-ui-multiselectWidget' )
7811 .append( this.$group );
7812 };
7813
7814 /* Setup */
7815
7816 OO.inheritClass( OO.ui.MultiselectWidget, OO.ui.Widget );
7817 OO.mixinClass( OO.ui.MultiselectWidget, OO.ui.mixin.GroupWidget );
7818
7819 /* Events */
7820
7821 /**
7822 * @event change
7823 *
7824 * A change event is emitted when the set of items changes, or an item is selected or deselected.
7825 */
7826
7827 /**
7828 * @event select
7829 *
7830 * A select event is emitted when an item is selected or deselected.
7831 */
7832
7833 /* Methods */
7834
7835 /**
7836 * Get options that are selected.
7837 *
7838 * @return {OO.ui.MultioptionWidget[]} Selected options
7839 */
7840 OO.ui.MultiselectWidget.prototype.getSelectedItems = function () {
7841 return this.items.filter( function ( item ) {
7842 return item.isSelected();
7843 } );
7844 };
7845
7846 /**
7847 * Get the data of options that are selected.
7848 *
7849 * @return {Object[]|string[]} Values of selected options
7850 */
7851 OO.ui.MultiselectWidget.prototype.getSelectedItemsData = function () {
7852 return this.getSelectedItems().map( function ( item ) {
7853 return item.data;
7854 } );
7855 };
7856
7857 /**
7858 * Select options by reference. Options not mentioned in the `items` array will be deselected.
7859 *
7860 * @param {OO.ui.MultioptionWidget[]} items Items to select
7861 * @chainable
7862 */
7863 OO.ui.MultiselectWidget.prototype.selectItems = function ( items ) {
7864 this.items.forEach( function ( item ) {
7865 var selected = items.indexOf( item ) !== -1;
7866 item.setSelected( selected );
7867 } );
7868 return this;
7869 };
7870
7871 /**
7872 * Select items by their data. Options not mentioned in the `datas` array will be deselected.
7873 *
7874 * @param {Object[]|string[]} datas Values of items to select
7875 * @chainable
7876 */
7877 OO.ui.MultiselectWidget.prototype.selectItemsByData = function ( datas ) {
7878 var items,
7879 widget = this;
7880 items = datas.map( function ( data ) {
7881 return widget.getItemFromData( data );
7882 } );
7883 this.selectItems( items );
7884 return this;
7885 };
7886
7887 /**
7888 * CheckboxMultioptionWidget is an option widget that looks like a checkbox.
7889 * The class is used with OO.ui.CheckboxMultiselectWidget to create a selection of checkbox options.
7890 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information.
7891 *
7892 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Button_selects_and_option
7893 *
7894 * @class
7895 * @extends OO.ui.MultioptionWidget
7896 *
7897 * @constructor
7898 * @param {Object} [config] Configuration options
7899 */
7900 OO.ui.CheckboxMultioptionWidget = function OoUiCheckboxMultioptionWidget( config ) {
7901 // Configuration initialization
7902 config = config || {};
7903
7904 // Properties (must be done before parent constructor which calls #setDisabled)
7905 this.checkbox = new OO.ui.CheckboxInputWidget();
7906
7907 // Parent constructor
7908 OO.ui.CheckboxMultioptionWidget.parent.call( this, config );
7909
7910 // Events
7911 this.checkbox.on( 'change', this.onCheckboxChange.bind( this ) );
7912 this.$element.on( 'keydown', this.onKeyDown.bind( this ) );
7913
7914 // Initialization
7915 this.$element
7916 .addClass( 'oo-ui-checkboxMultioptionWidget' )
7917 .prepend( this.checkbox.$element );
7918 };
7919
7920 /* Setup */
7921
7922 OO.inheritClass( OO.ui.CheckboxMultioptionWidget, OO.ui.MultioptionWidget );
7923
7924 /* Static Properties */
7925
7926 /**
7927 * @static
7928 * @inheritdoc
7929 */
7930 OO.ui.CheckboxMultioptionWidget.static.tagName = 'label';
7931
7932 /* Methods */
7933
7934 /**
7935 * Handle checkbox selected state change.
7936 *
7937 * @private
7938 */
7939 OO.ui.CheckboxMultioptionWidget.prototype.onCheckboxChange = function () {
7940 this.setSelected( this.checkbox.isSelected() );
7941 };
7942
7943 /**
7944 * @inheritdoc
7945 */
7946 OO.ui.CheckboxMultioptionWidget.prototype.setSelected = function ( state ) {
7947 OO.ui.CheckboxMultioptionWidget.parent.prototype.setSelected.call( this, state );
7948 this.checkbox.setSelected( state );
7949 return this;
7950 };
7951
7952 /**
7953 * @inheritdoc
7954 */
7955 OO.ui.CheckboxMultioptionWidget.prototype.setDisabled = function ( disabled ) {
7956 OO.ui.CheckboxMultioptionWidget.parent.prototype.setDisabled.call( this, disabled );
7957 this.checkbox.setDisabled( this.isDisabled() );
7958 return this;
7959 };
7960
7961 /**
7962 * Focus the widget.
7963 */
7964 OO.ui.CheckboxMultioptionWidget.prototype.focus = function () {
7965 this.checkbox.focus();
7966 };
7967
7968 /**
7969 * Handle key down events.
7970 *
7971 * @protected
7972 * @param {jQuery.Event} e
7973 */
7974 OO.ui.CheckboxMultioptionWidget.prototype.onKeyDown = function ( e ) {
7975 var
7976 element = this.getElementGroup(),
7977 nextItem;
7978
7979 if ( e.keyCode === OO.ui.Keys.LEFT || e.keyCode === OO.ui.Keys.UP ) {
7980 nextItem = element.getRelativeFocusableItem( this, -1 );
7981 } else if ( e.keyCode === OO.ui.Keys.RIGHT || e.keyCode === OO.ui.Keys.DOWN ) {
7982 nextItem = element.getRelativeFocusableItem( this, 1 );
7983 }
7984
7985 if ( nextItem ) {
7986 e.preventDefault();
7987 nextItem.focus();
7988 }
7989 };
7990
7991 /**
7992 * CheckboxMultiselectWidget is a {@link OO.ui.MultiselectWidget multiselect widget} that contains
7993 * checkboxes and is used together with OO.ui.CheckboxMultioptionWidget. The
7994 * CheckboxMultiselectWidget provides an interface for adding, removing and selecting options.
7995 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
7996 *
7997 * If you want to use this within an HTML form, such as a OO.ui.FormLayout, use
7998 * OO.ui.CheckboxMultiselectInputWidget instead.
7999 *
8000 * @example
8001 * // A CheckboxMultiselectWidget with CheckboxMultioptions.
8002 * var option1 = new OO.ui.CheckboxMultioptionWidget( {
8003 * data: 'a',
8004 * selected: true,
8005 * label: 'Selected checkbox'
8006 * } );
8007 *
8008 * var option2 = new OO.ui.CheckboxMultioptionWidget( {
8009 * data: 'b',
8010 * label: 'Unselected checkbox'
8011 * } );
8012 *
8013 * var multiselect=new OO.ui.CheckboxMultiselectWidget( {
8014 * items: [ option1, option2 ]
8015 * } );
8016 *
8017 * $( 'body' ).append( multiselect.$element );
8018 *
8019 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
8020 *
8021 * @class
8022 * @extends OO.ui.MultiselectWidget
8023 *
8024 * @constructor
8025 * @param {Object} [config] Configuration options
8026 */
8027 OO.ui.CheckboxMultiselectWidget = function OoUiCheckboxMultiselectWidget( config ) {
8028 // Parent constructor
8029 OO.ui.CheckboxMultiselectWidget.parent.call( this, config );
8030
8031 // Properties
8032 this.$lastClicked = null;
8033
8034 // Events
8035 this.$group.on( 'click', this.onClick.bind( this ) );
8036
8037 // Initialization
8038 this.$element
8039 .addClass( 'oo-ui-checkboxMultiselectWidget' );
8040 };
8041
8042 /* Setup */
8043
8044 OO.inheritClass( OO.ui.CheckboxMultiselectWidget, OO.ui.MultiselectWidget );
8045
8046 /* Methods */
8047
8048 /**
8049 * Get an option by its position relative to the specified item (or to the start of the option array,
8050 * if item is `null`). The direction in which to search through the option array is specified with a
8051 * number: -1 for reverse (the default) or 1 for forward. The method will return an option, or
8052 * `null` if there are no options in the array.
8053 *
8054 * @param {OO.ui.CheckboxMultioptionWidget|null} item Item to describe the start position, or `null` to start at the beginning of the array.
8055 * @param {number} direction Direction to move in: -1 to move backward, 1 to move forward
8056 * @return {OO.ui.CheckboxMultioptionWidget|null} Item at position, `null` if there are no items in the select
8057 */
8058 OO.ui.CheckboxMultiselectWidget.prototype.getRelativeFocusableItem = function ( item, direction ) {
8059 var currentIndex, nextIndex, i,
8060 increase = direction > 0 ? 1 : -1,
8061 len = this.items.length;
8062
8063 if ( item ) {
8064 currentIndex = this.items.indexOf( item );
8065 nextIndex = ( currentIndex + increase + len ) % len;
8066 } else {
8067 // If no item is selected and moving forward, start at the beginning.
8068 // If moving backward, start at the end.
8069 nextIndex = direction > 0 ? 0 : len - 1;
8070 }
8071
8072 for ( i = 0; i < len; i++ ) {
8073 item = this.items[ nextIndex ];
8074 if ( item && !item.isDisabled() ) {
8075 return item;
8076 }
8077 nextIndex = ( nextIndex + increase + len ) % len;
8078 }
8079 return null;
8080 };
8081
8082 /**
8083 * Handle click events on checkboxes.
8084 *
8085 * @param {jQuery.Event} e
8086 */
8087 OO.ui.CheckboxMultiselectWidget.prototype.onClick = function ( e ) {
8088 var $options, lastClickedIndex, nowClickedIndex, i, direction, wasSelected, items,
8089 $lastClicked = this.$lastClicked,
8090 $nowClicked = $( e.target ).closest( '.oo-ui-checkboxMultioptionWidget' )
8091 .not( '.oo-ui-widget-disabled' );
8092
8093 // Allow selecting multiple options at once by Shift-clicking them
8094 if ( $lastClicked && $nowClicked.length && e.shiftKey ) {
8095 $options = this.$group.find( '.oo-ui-checkboxMultioptionWidget' );
8096 lastClickedIndex = $options.index( $lastClicked );
8097 nowClickedIndex = $options.index( $nowClicked );
8098 // If it's the same item, either the user is being silly, or it's a fake event generated by the
8099 // browser. In either case we don't need custom handling.
8100 if ( nowClickedIndex !== lastClickedIndex ) {
8101 items = this.items;
8102 wasSelected = items[ nowClickedIndex ].isSelected();
8103 direction = nowClickedIndex > lastClickedIndex ? 1 : -1;
8104
8105 // This depends on the DOM order of the items and the order of the .items array being the same.
8106 for ( i = lastClickedIndex; i !== nowClickedIndex; i += direction ) {
8107 if ( !items[ i ].isDisabled() ) {
8108 items[ i ].setSelected( !wasSelected );
8109 }
8110 }
8111 // For the now-clicked element, use immediate timeout to allow the browser to do its own
8112 // handling first, then set our value. The order in which events happen is different for
8113 // clicks on the <input> and on the <label> and there are additional fake clicks fired for
8114 // non-click actions that change the checkboxes.
8115 e.preventDefault();
8116 setTimeout( function () {
8117 if ( !items[ nowClickedIndex ].isDisabled() ) {
8118 items[ nowClickedIndex ].setSelected( !wasSelected );
8119 }
8120 } );
8121 }
8122 }
8123
8124 if ( $nowClicked.length ) {
8125 this.$lastClicked = $nowClicked;
8126 }
8127 };
8128
8129 /**
8130 * Focus the widget
8131 *
8132 * @chainable
8133 */
8134 OO.ui.CheckboxMultiselectWidget.prototype.focus = function () {
8135 var item;
8136 if ( !this.isDisabled() ) {
8137 item = this.getRelativeFocusableItem( null, 1 );
8138 if ( item ) {
8139 item.focus();
8140 }
8141 }
8142 return this;
8143 };
8144
8145 /**
8146 * @inheritdoc
8147 */
8148 OO.ui.CheckboxMultiselectWidget.prototype.simulateLabelClick = function () {
8149 this.focus();
8150 };
8151
8152 /**
8153 * FloatingMenuSelectWidget was a menu that would stick under a specified
8154 * container, even when it is inserted elsewhere in the document.
8155 * This functionality is now included in MenuSelectWidget, and FloatingMenuSelectWidget
8156 * is preserved for backwards-compatibility.
8157 *
8158 * @class
8159 * @extends OO.ui.MenuSelectWidget
8160 * @deprecated since v0.21.3, use MenuSelectWidget instead.
8161 *
8162 * @constructor
8163 * @param {OO.ui.Widget} [inputWidget] Widget to provide the menu for.
8164 * Deprecated, omit this parameter and specify `$container` instead.
8165 * @param {Object} [config] Configuration options
8166 * @cfg {jQuery} [$container=inputWidget.$element] Element to render menu under
8167 */
8168 OO.ui.FloatingMenuSelectWidget = function OoUiFloatingMenuSelectWidget( inputWidget, config ) {
8169 OO.ui.warnDeprecation( 'FloatingMenuSelectWidget is deprecated. Use the MenuSelectWidget instead.' );
8170
8171 // Allow 'inputWidget' parameter and config for backwards compatibility
8172 if ( OO.isPlainObject( inputWidget ) && config === undefined ) {
8173 config = inputWidget;
8174 inputWidget = config.inputWidget;
8175 }
8176
8177 // Configuration initialization
8178 config = config || {};
8179
8180 // Properties
8181 this.inputWidget = inputWidget; // For backwards compatibility
8182 this.$container = config.$floatableContainer || config.$container || this.inputWidget.$element;
8183
8184 // Parent constructor
8185 OO.ui.FloatingMenuSelectWidget.parent.call( this, $.extend( {}, config, { $floatableContainer: this.$container } ) );
8186
8187 // Initialization
8188 this.$element.addClass( 'oo-ui-floatingMenuSelectWidget' );
8189 // For backwards compatibility
8190 this.$element.addClass( 'oo-ui-textInputMenuSelectWidget' );
8191 };
8192
8193 /* Setup */
8194
8195 OO.inheritClass( OO.ui.FloatingMenuSelectWidget, OO.ui.MenuSelectWidget );
8196
8197 /**
8198 * Progress bars visually display the status of an operation, such as a download,
8199 * and can be either determinate or indeterminate:
8200 *
8201 * - **determinate** process bars show the percent of an operation that is complete.
8202 *
8203 * - **indeterminate** process bars use a visual display of motion to indicate that an operation
8204 * is taking place. Because the extent of an indeterminate operation is unknown, the bar does
8205 * not use percentages.
8206 *
8207 * The value of the `progress` configuration determines whether the bar is determinate or indeterminate.
8208 *
8209 * @example
8210 * // Examples of determinate and indeterminate progress bars.
8211 * var progressBar1 = new OO.ui.ProgressBarWidget( {
8212 * progress: 33
8213 * } );
8214 * var progressBar2 = new OO.ui.ProgressBarWidget();
8215 *
8216 * // Create a FieldsetLayout to layout progress bars
8217 * var fieldset = new OO.ui.FieldsetLayout;
8218 * fieldset.addItems( [
8219 * new OO.ui.FieldLayout( progressBar1, {label: 'Determinate', align: 'top'}),
8220 * new OO.ui.FieldLayout( progressBar2, {label: 'Indeterminate', align: 'top'})
8221 * ] );
8222 * $( 'body' ).append( fieldset.$element );
8223 *
8224 * @class
8225 * @extends OO.ui.Widget
8226 *
8227 * @constructor
8228 * @param {Object} [config] Configuration options
8229 * @cfg {number|boolean} [progress=false] The type of progress bar (determinate or indeterminate).
8230 * To create a determinate progress bar, specify a number that reflects the initial percent complete.
8231 * By default, the progress bar is indeterminate.
8232 */
8233 OO.ui.ProgressBarWidget = function OoUiProgressBarWidget( config ) {
8234 // Configuration initialization
8235 config = config || {};
8236
8237 // Parent constructor
8238 OO.ui.ProgressBarWidget.parent.call( this, config );
8239
8240 // Properties
8241 this.$bar = $( '<div>' );
8242 this.progress = null;
8243
8244 // Initialization
8245 this.setProgress( config.progress !== undefined ? config.progress : false );
8246 this.$bar.addClass( 'oo-ui-progressBarWidget-bar' );
8247 this.$element
8248 .attr( {
8249 role: 'progressbar',
8250 'aria-valuemin': 0,
8251 'aria-valuemax': 100
8252 } )
8253 .addClass( 'oo-ui-progressBarWidget' )
8254 .append( this.$bar );
8255 };
8256
8257 /* Setup */
8258
8259 OO.inheritClass( OO.ui.ProgressBarWidget, OO.ui.Widget );
8260
8261 /* Static Properties */
8262
8263 /**
8264 * @static
8265 * @inheritdoc
8266 */
8267 OO.ui.ProgressBarWidget.static.tagName = 'div';
8268
8269 /* Methods */
8270
8271 /**
8272 * Get the percent of the progress that has been completed. Indeterminate progresses will return `false`.
8273 *
8274 * @return {number|boolean} Progress percent
8275 */
8276 OO.ui.ProgressBarWidget.prototype.getProgress = function () {
8277 return this.progress;
8278 };
8279
8280 /**
8281 * Set the percent of the process completed or `false` for an indeterminate process.
8282 *
8283 * @param {number|boolean} progress Progress percent or `false` for indeterminate
8284 */
8285 OO.ui.ProgressBarWidget.prototype.setProgress = function ( progress ) {
8286 this.progress = progress;
8287
8288 if ( progress !== false ) {
8289 this.$bar.css( 'width', this.progress + '%' );
8290 this.$element.attr( 'aria-valuenow', this.progress );
8291 } else {
8292 this.$bar.css( 'width', '' );
8293 this.$element.removeAttr( 'aria-valuenow' );
8294 }
8295 this.$element.toggleClass( 'oo-ui-progressBarWidget-indeterminate', progress === false );
8296 };
8297
8298 /**
8299 * InputWidget is the base class for all input widgets, which
8300 * include {@link OO.ui.TextInputWidget text inputs}, {@link OO.ui.CheckboxInputWidget checkbox inputs},
8301 * {@link OO.ui.RadioInputWidget radio inputs}, and {@link OO.ui.ButtonInputWidget button inputs}.
8302 * See the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
8303 *
8304 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
8305 *
8306 * @abstract
8307 * @class
8308 * @extends OO.ui.Widget
8309 * @mixins OO.ui.mixin.FlaggedElement
8310 * @mixins OO.ui.mixin.TabIndexedElement
8311 * @mixins OO.ui.mixin.TitledElement
8312 * @mixins OO.ui.mixin.AccessKeyedElement
8313 *
8314 * @constructor
8315 * @param {Object} [config] Configuration options
8316 * @cfg {string} [name=''] The value of the input’s HTML `name` attribute.
8317 * @cfg {string} [value=''] The value of the input.
8318 * @cfg {string} [dir] The directionality of the input (ltr/rtl).
8319 * @cfg {string} [inputId] The value of the input’s HTML `id` attribute.
8320 * @cfg {Function} [inputFilter] The name of an input filter function. Input filters modify the value of an input
8321 * before it is accepted.
8322 */
8323 OO.ui.InputWidget = function OoUiInputWidget( config ) {
8324 // Configuration initialization
8325 config = config || {};
8326
8327 // Parent constructor
8328 OO.ui.InputWidget.parent.call( this, config );
8329
8330 // Properties
8331 // See #reusePreInfuseDOM about config.$input
8332 this.$input = config.$input || this.getInputElement( config );
8333 this.value = '';
8334 this.inputFilter = config.inputFilter;
8335
8336 // Mixin constructors
8337 OO.ui.mixin.FlaggedElement.call( this, config );
8338 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$input } ) );
8339 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$input } ) );
8340 OO.ui.mixin.AccessKeyedElement.call( this, $.extend( {}, config, { $accessKeyed: this.$input } ) );
8341
8342 // Events
8343 this.$input.on( 'keydown mouseup cut paste change input select', this.onEdit.bind( this ) );
8344
8345 // Initialization
8346 this.$input
8347 .addClass( 'oo-ui-inputWidget-input' )
8348 .attr( 'name', config.name )
8349 .prop( 'disabled', this.isDisabled() );
8350 this.$element
8351 .addClass( 'oo-ui-inputWidget' )
8352 .append( this.$input );
8353 this.setValue( config.value );
8354 if ( config.dir ) {
8355 this.setDir( config.dir );
8356 }
8357 if ( config.inputId !== undefined ) {
8358 this.setInputId( config.inputId );
8359 }
8360 };
8361
8362 /* Setup */
8363
8364 OO.inheritClass( OO.ui.InputWidget, OO.ui.Widget );
8365 OO.mixinClass( OO.ui.InputWidget, OO.ui.mixin.FlaggedElement );
8366 OO.mixinClass( OO.ui.InputWidget, OO.ui.mixin.TabIndexedElement );
8367 OO.mixinClass( OO.ui.InputWidget, OO.ui.mixin.TitledElement );
8368 OO.mixinClass( OO.ui.InputWidget, OO.ui.mixin.AccessKeyedElement );
8369
8370 /* Static Methods */
8371
8372 /**
8373 * @inheritdoc
8374 */
8375 OO.ui.InputWidget.static.reusePreInfuseDOM = function ( node, config ) {
8376 config = OO.ui.InputWidget.parent.static.reusePreInfuseDOM( node, config );
8377 // Reusing `$input` lets browsers preserve inputted values across page reloads, see T114134.
8378 config.$input = $( node ).find( '.oo-ui-inputWidget-input' );
8379 return config;
8380 };
8381
8382 /**
8383 * @inheritdoc
8384 */
8385 OO.ui.InputWidget.static.gatherPreInfuseState = function ( node, config ) {
8386 var state = OO.ui.InputWidget.parent.static.gatherPreInfuseState( node, config );
8387 if ( config.$input && config.$input.length ) {
8388 state.value = config.$input.val();
8389 // Might be better in TabIndexedElement, but it's awkward to do there because mixins are awkward
8390 state.focus = config.$input.is( ':focus' );
8391 }
8392 return state;
8393 };
8394
8395 /* Events */
8396
8397 /**
8398 * @event change
8399 *
8400 * A change event is emitted when the value of the input changes.
8401 *
8402 * @param {string} value
8403 */
8404
8405 /* Methods */
8406
8407 /**
8408 * Get input element.
8409 *
8410 * Subclasses of OO.ui.InputWidget use the `config` parameter to produce different elements in
8411 * different circumstances. The element must have a `value` property (like form elements).
8412 *
8413 * @protected
8414 * @param {Object} config Configuration options
8415 * @return {jQuery} Input element
8416 */
8417 OO.ui.InputWidget.prototype.getInputElement = function () {
8418 return $( '<input>' );
8419 };
8420
8421 /**
8422 * Handle potentially value-changing events.
8423 *
8424 * @private
8425 * @param {jQuery.Event} e Key down, mouse up, cut, paste, change, input, or select event
8426 */
8427 OO.ui.InputWidget.prototype.onEdit = function () {
8428 var widget = this;
8429 if ( !this.isDisabled() ) {
8430 // Allow the stack to clear so the value will be updated
8431 setTimeout( function () {
8432 widget.setValue( widget.$input.val() );
8433 } );
8434 }
8435 };
8436
8437 /**
8438 * Get the value of the input.
8439 *
8440 * @return {string} Input value
8441 */
8442 OO.ui.InputWidget.prototype.getValue = function () {
8443 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
8444 // it, and we won't know unless they're kind enough to trigger a 'change' event.
8445 var value = this.$input.val();
8446 if ( this.value !== value ) {
8447 this.setValue( value );
8448 }
8449 return this.value;
8450 };
8451
8452 /**
8453 * Set the directionality of the input.
8454 *
8455 * @param {string} dir Text directionality: 'ltr', 'rtl' or 'auto'
8456 * @chainable
8457 */
8458 OO.ui.InputWidget.prototype.setDir = function ( dir ) {
8459 this.$input.prop( 'dir', dir );
8460 return this;
8461 };
8462
8463 /**
8464 * Set the value of the input.
8465 *
8466 * @param {string} value New value
8467 * @fires change
8468 * @chainable
8469 */
8470 OO.ui.InputWidget.prototype.setValue = function ( value ) {
8471 value = this.cleanUpValue( value );
8472 // Update the DOM if it has changed. Note that with cleanUpValue, it
8473 // is possible for the DOM value to change without this.value changing.
8474 if ( this.$input.val() !== value ) {
8475 this.$input.val( value );
8476 }
8477 if ( this.value !== value ) {
8478 this.value = value;
8479 this.emit( 'change', this.value );
8480 }
8481 return this;
8482 };
8483
8484 /**
8485 * Clean up incoming value.
8486 *
8487 * Ensures value is a string, and converts undefined and null to empty string.
8488 *
8489 * @private
8490 * @param {string} value Original value
8491 * @return {string} Cleaned up value
8492 */
8493 OO.ui.InputWidget.prototype.cleanUpValue = function ( value ) {
8494 if ( value === undefined || value === null ) {
8495 return '';
8496 } else if ( this.inputFilter ) {
8497 return this.inputFilter( String( value ) );
8498 } else {
8499 return String( value );
8500 }
8501 };
8502
8503 /**
8504 * @inheritdoc
8505 */
8506 OO.ui.InputWidget.prototype.setDisabled = function ( state ) {
8507 OO.ui.InputWidget.parent.prototype.setDisabled.call( this, state );
8508 if ( this.$input ) {
8509 this.$input.prop( 'disabled', this.isDisabled() );
8510 }
8511 return this;
8512 };
8513
8514 /**
8515 * Set the 'id' attribute of the `<input>` element.
8516 *
8517 * @param {string} id
8518 * @chainable
8519 */
8520 OO.ui.InputWidget.prototype.setInputId = function ( id ) {
8521 this.$input.attr( 'id', id );
8522 return this;
8523 };
8524
8525 /**
8526 * @inheritdoc
8527 */
8528 OO.ui.InputWidget.prototype.restorePreInfuseState = function ( state ) {
8529 OO.ui.InputWidget.parent.prototype.restorePreInfuseState.call( this, state );
8530 if ( state.value !== undefined && state.value !== this.getValue() ) {
8531 this.setValue( state.value );
8532 }
8533 if ( state.focus ) {
8534 this.focus();
8535 }
8536 };
8537
8538 /**
8539 * Data widget intended for creating 'hidden'-type inputs.
8540 *
8541 * @class
8542 * @extends OO.ui.Widget
8543 *
8544 * @constructor
8545 * @param {Object} [config] Configuration options
8546 * @cfg {string} [value=''] The value of the input.
8547 * @cfg {string} [name=''] The value of the input’s HTML `name` attribute.
8548 */
8549 OO.ui.HiddenInputWidget = function OoUiHiddenInputWidget( config ) {
8550 // Configuration initialization
8551 config = $.extend( { value: '', name: '' }, config );
8552
8553 // Parent constructor
8554 OO.ui.HiddenInputWidget.parent.call( this, config );
8555
8556 // Initialization
8557 this.$element.attr( {
8558 type: 'hidden',
8559 value: config.value,
8560 name: config.name
8561 } );
8562 this.$element.removeAttr( 'aria-disabled' );
8563 };
8564
8565 /* Setup */
8566
8567 OO.inheritClass( OO.ui.HiddenInputWidget, OO.ui.Widget );
8568
8569 /* Static Properties */
8570
8571 /**
8572 * @static
8573 * @inheritdoc
8574 */
8575 OO.ui.HiddenInputWidget.static.tagName = 'input';
8576
8577 /**
8578 * ButtonInputWidget is used to submit HTML forms and is intended to be used within
8579 * a OO.ui.FormLayout. If you do not need the button to work with HTML forms, you probably
8580 * want to use OO.ui.ButtonWidget instead. Button input widgets can be rendered as either an
8581 * HTML `<button>` (the default) or an HTML `<input>` tags. See the
8582 * [OOjs UI documentation on MediaWiki] [1] for more information.
8583 *
8584 * @example
8585 * // A ButtonInputWidget rendered as an HTML button, the default.
8586 * var button = new OO.ui.ButtonInputWidget( {
8587 * label: 'Input button',
8588 * icon: 'check',
8589 * value: 'check'
8590 * } );
8591 * $( 'body' ).append( button.$element );
8592 *
8593 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs#Button_inputs
8594 *
8595 * @class
8596 * @extends OO.ui.InputWidget
8597 * @mixins OO.ui.mixin.ButtonElement
8598 * @mixins OO.ui.mixin.IconElement
8599 * @mixins OO.ui.mixin.IndicatorElement
8600 * @mixins OO.ui.mixin.LabelElement
8601 * @mixins OO.ui.mixin.TitledElement
8602 *
8603 * @constructor
8604 * @param {Object} [config] Configuration options
8605 * @cfg {string} [type='button'] The value of the HTML `'type'` attribute: 'button', 'submit' or 'reset'.
8606 * @cfg {boolean} [useInputTag=false] Use an `<input>` tag instead of a `<button>` tag, the default.
8607 * Widgets configured to be an `<input>` do not support {@link #icon icons} and {@link #indicator indicators},
8608 * non-plaintext {@link #label labels}, or {@link #value values}. In general, useInputTag should only
8609 * be set to `true` when there’s need to support IE 6 in a form with multiple buttons.
8610 */
8611 OO.ui.ButtonInputWidget = function OoUiButtonInputWidget( config ) {
8612 // Configuration initialization
8613 config = $.extend( { type: 'button', useInputTag: false }, config );
8614
8615 // See InputWidget#reusePreInfuseDOM about config.$input
8616 if ( config.$input ) {
8617 config.$input.empty();
8618 }
8619
8620 // Properties (must be set before parent constructor, which calls #setValue)
8621 this.useInputTag = config.useInputTag;
8622
8623 // Parent constructor
8624 OO.ui.ButtonInputWidget.parent.call( this, config );
8625
8626 // Mixin constructors
8627 OO.ui.mixin.ButtonElement.call( this, $.extend( {}, config, { $button: this.$input } ) );
8628 OO.ui.mixin.IconElement.call( this, config );
8629 OO.ui.mixin.IndicatorElement.call( this, config );
8630 OO.ui.mixin.LabelElement.call( this, config );
8631 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$input } ) );
8632
8633 // Initialization
8634 if ( !config.useInputTag ) {
8635 this.$input.append( this.$icon, this.$label, this.$indicator );
8636 }
8637 this.$element.addClass( 'oo-ui-buttonInputWidget' );
8638 };
8639
8640 /* Setup */
8641
8642 OO.inheritClass( OO.ui.ButtonInputWidget, OO.ui.InputWidget );
8643 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.ButtonElement );
8644 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.IconElement );
8645 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.IndicatorElement );
8646 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.LabelElement );
8647 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.TitledElement );
8648
8649 /* Static Properties */
8650
8651 /**
8652 * @static
8653 * @inheritdoc
8654 */
8655 OO.ui.ButtonInputWidget.static.tagName = 'span';
8656
8657 /* Methods */
8658
8659 /**
8660 * @inheritdoc
8661 * @protected
8662 */
8663 OO.ui.ButtonInputWidget.prototype.getInputElement = function ( config ) {
8664 var type;
8665 type = [ 'button', 'submit', 'reset' ].indexOf( config.type ) !== -1 ? config.type : 'button';
8666 return $( '<' + ( config.useInputTag ? 'input' : 'button' ) + ' type="' + type + '">' );
8667 };
8668
8669 /**
8670 * Set label value.
8671 *
8672 * If #useInputTag is `true`, the label is set as the `value` of the `<input>` tag.
8673 *
8674 * @param {jQuery|string|Function|null} label Label nodes, text, a function that returns nodes or
8675 * text, or `null` for no label
8676 * @chainable
8677 */
8678 OO.ui.ButtonInputWidget.prototype.setLabel = function ( label ) {
8679 if ( typeof label === 'function' ) {
8680 label = OO.ui.resolveMsg( label );
8681 }
8682
8683 if ( this.useInputTag ) {
8684 // Discard non-plaintext labels
8685 if ( typeof label !== 'string' ) {
8686 label = '';
8687 }
8688
8689 this.$input.val( label );
8690 }
8691
8692 return OO.ui.mixin.LabelElement.prototype.setLabel.call( this, label );
8693 };
8694
8695 /**
8696 * Set the value of the input.
8697 *
8698 * This method is disabled for button inputs configured as {@link #useInputTag <input> tags}, as
8699 * they do not support {@link #value values}.
8700 *
8701 * @param {string} value New value
8702 * @chainable
8703 */
8704 OO.ui.ButtonInputWidget.prototype.setValue = function ( value ) {
8705 if ( !this.useInputTag ) {
8706 OO.ui.ButtonInputWidget.parent.prototype.setValue.call( this, value );
8707 }
8708 return this;
8709 };
8710
8711 /**
8712 * @inheritdoc
8713 */
8714 OO.ui.ButtonInputWidget.prototype.getInputId = function () {
8715 // Disable generating `<label>` elements for buttons. One would very rarely need additional label
8716 // for a button, and it's already a big clickable target, and it causes unexpected rendering.
8717 return null;
8718 };
8719
8720 /**
8721 * CheckboxInputWidgets, like HTML checkboxes, can be selected and/or configured with a value.
8722 * Note that these {@link OO.ui.InputWidget input widgets} are best laid out
8723 * in {@link OO.ui.FieldLayout field layouts} that use the {@link OO.ui.FieldLayout#align inline}
8724 * alignment. For more information, please see the [OOjs UI documentation on MediaWiki][1].
8725 *
8726 * This widget can be used inside an HTML form, such as a OO.ui.FormLayout.
8727 *
8728 * @example
8729 * // An example of selected, unselected, and disabled checkbox inputs
8730 * var checkbox1=new OO.ui.CheckboxInputWidget( {
8731 * value: 'a',
8732 * selected: true
8733 * } );
8734 * var checkbox2=new OO.ui.CheckboxInputWidget( {
8735 * value: 'b'
8736 * } );
8737 * var checkbox3=new OO.ui.CheckboxInputWidget( {
8738 * value:'c',
8739 * disabled: true
8740 * } );
8741 * // Create a fieldset layout with fields for each checkbox.
8742 * var fieldset = new OO.ui.FieldsetLayout( {
8743 * label: 'Checkboxes'
8744 * } );
8745 * fieldset.addItems( [
8746 * new OO.ui.FieldLayout( checkbox1, { label: 'Selected checkbox', align: 'inline' } ),
8747 * new OO.ui.FieldLayout( checkbox2, { label: 'Unselected checkbox', align: 'inline' } ),
8748 * new OO.ui.FieldLayout( checkbox3, { label: 'Disabled checkbox', align: 'inline' } ),
8749 * ] );
8750 * $( 'body' ).append( fieldset.$element );
8751 *
8752 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
8753 *
8754 * @class
8755 * @extends OO.ui.InputWidget
8756 *
8757 * @constructor
8758 * @param {Object} [config] Configuration options
8759 * @cfg {boolean} [selected=false] Select the checkbox initially. By default, the checkbox is not selected.
8760 */
8761 OO.ui.CheckboxInputWidget = function OoUiCheckboxInputWidget( config ) {
8762 // Configuration initialization
8763 config = config || {};
8764
8765 // Parent constructor
8766 OO.ui.CheckboxInputWidget.parent.call( this, config );
8767
8768 // Initialization
8769 this.$element
8770 .addClass( 'oo-ui-checkboxInputWidget' )
8771 // Required for pretty styling in WikimediaUI theme
8772 .append( $( '<span>' ) );
8773 this.setSelected( config.selected !== undefined ? config.selected : false );
8774 };
8775
8776 /* Setup */
8777
8778 OO.inheritClass( OO.ui.CheckboxInputWidget, OO.ui.InputWidget );
8779
8780 /* Static Properties */
8781
8782 /**
8783 * @static
8784 * @inheritdoc
8785 */
8786 OO.ui.CheckboxInputWidget.static.tagName = 'span';
8787
8788 /* Static Methods */
8789
8790 /**
8791 * @inheritdoc
8792 */
8793 OO.ui.CheckboxInputWidget.static.gatherPreInfuseState = function ( node, config ) {
8794 var state = OO.ui.CheckboxInputWidget.parent.static.gatherPreInfuseState( node, config );
8795 state.checked = config.$input.prop( 'checked' );
8796 return state;
8797 };
8798
8799 /* Methods */
8800
8801 /**
8802 * @inheritdoc
8803 * @protected
8804 */
8805 OO.ui.CheckboxInputWidget.prototype.getInputElement = function () {
8806 return $( '<input>' ).attr( 'type', 'checkbox' );
8807 };
8808
8809 /**
8810 * @inheritdoc
8811 */
8812 OO.ui.CheckboxInputWidget.prototype.onEdit = function () {
8813 var widget = this;
8814 if ( !this.isDisabled() ) {
8815 // Allow the stack to clear so the value will be updated
8816 setTimeout( function () {
8817 widget.setSelected( widget.$input.prop( 'checked' ) );
8818 } );
8819 }
8820 };
8821
8822 /**
8823 * Set selection state of this checkbox.
8824 *
8825 * @param {boolean} state `true` for selected
8826 * @chainable
8827 */
8828 OO.ui.CheckboxInputWidget.prototype.setSelected = function ( state ) {
8829 state = !!state;
8830 if ( this.selected !== state ) {
8831 this.selected = state;
8832 this.$input.prop( 'checked', this.selected );
8833 this.emit( 'change', this.selected );
8834 }
8835 return this;
8836 };
8837
8838 /**
8839 * Check if this checkbox is selected.
8840 *
8841 * @return {boolean} Checkbox is selected
8842 */
8843 OO.ui.CheckboxInputWidget.prototype.isSelected = function () {
8844 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
8845 // it, and we won't know unless they're kind enough to trigger a 'change' event.
8846 var selected = this.$input.prop( 'checked' );
8847 if ( this.selected !== selected ) {
8848 this.setSelected( selected );
8849 }
8850 return this.selected;
8851 };
8852
8853 /**
8854 * @inheritdoc
8855 */
8856 OO.ui.CheckboxInputWidget.prototype.simulateLabelClick = function () {
8857 if ( !this.isDisabled() ) {
8858 this.$input.click();
8859 }
8860 this.focus();
8861 };
8862
8863 /**
8864 * @inheritdoc
8865 */
8866 OO.ui.CheckboxInputWidget.prototype.restorePreInfuseState = function ( state ) {
8867 OO.ui.CheckboxInputWidget.parent.prototype.restorePreInfuseState.call( this, state );
8868 if ( state.checked !== undefined && state.checked !== this.isSelected() ) {
8869 this.setSelected( state.checked );
8870 }
8871 };
8872
8873 /**
8874 * DropdownInputWidget is a {@link OO.ui.DropdownWidget DropdownWidget} intended to be used
8875 * within an HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with the value
8876 * of a hidden HTML `input` tag. Please see the [OOjs UI documentation on MediaWiki][1] for
8877 * more information about input widgets.
8878 *
8879 * A DropdownInputWidget always has a value (one of the options is always selected), unless there
8880 * are no options. If no `value` configuration option is provided, the first option is selected.
8881 * If you need a state representing no value (no option being selected), use a DropdownWidget.
8882 *
8883 * This and OO.ui.RadioSelectInputWidget support the same configuration options.
8884 *
8885 * @example
8886 * // Example: A DropdownInputWidget with three options
8887 * var dropdownInput = new OO.ui.DropdownInputWidget( {
8888 * options: [
8889 * { data: 'a', label: 'First' },
8890 * { data: 'b', label: 'Second'},
8891 * { data: 'c', label: 'Third' }
8892 * ]
8893 * } );
8894 * $( 'body' ).append( dropdownInput.$element );
8895 *
8896 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
8897 *
8898 * @class
8899 * @extends OO.ui.InputWidget
8900 * @mixins OO.ui.mixin.TitledElement
8901 *
8902 * @constructor
8903 * @param {Object} [config] Configuration options
8904 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
8905 * @cfg {Object} [dropdown] Configuration options for {@link OO.ui.DropdownWidget DropdownWidget}
8906 */
8907 OO.ui.DropdownInputWidget = function OoUiDropdownInputWidget( config ) {
8908 // Configuration initialization
8909 config = config || {};
8910
8911 // See InputWidget#reusePreInfuseDOM about config.$input
8912 if ( config.$input ) {
8913 config.$input.addClass( 'oo-ui-element-hidden' );
8914 }
8915
8916 // Properties (must be done before parent constructor which calls #setDisabled)
8917 this.dropdownWidget = new OO.ui.DropdownWidget( config.dropdown );
8918
8919 // Parent constructor
8920 OO.ui.DropdownInputWidget.parent.call( this, config );
8921
8922 // Mixin constructors
8923 OO.ui.mixin.TitledElement.call( this, config );
8924
8925 // Events
8926 this.dropdownWidget.getMenu().connect( this, { select: 'onMenuSelect' } );
8927
8928 // Initialization
8929 this.setOptions( config.options || [] );
8930 // Set the value again, after we did setOptions(). The call from parent doesn't work because the
8931 // widget has no valid options when it happens.
8932 this.setValue( config.value );
8933 this.$element
8934 .addClass( 'oo-ui-dropdownInputWidget' )
8935 .append( this.dropdownWidget.$element );
8936 this.setTabIndexedElement( null );
8937 };
8938
8939 /* Setup */
8940
8941 OO.inheritClass( OO.ui.DropdownInputWidget, OO.ui.InputWidget );
8942 OO.mixinClass( OO.ui.DropdownInputWidget, OO.ui.mixin.TitledElement );
8943
8944 /* Methods */
8945
8946 /**
8947 * @inheritdoc
8948 * @protected
8949 */
8950 OO.ui.DropdownInputWidget.prototype.getInputElement = function () {
8951 return $( '<input>' ).attr( 'type', 'hidden' );
8952 };
8953
8954 /**
8955 * Handles menu select events.
8956 *
8957 * @private
8958 * @param {OO.ui.MenuOptionWidget|null} item Selected menu item
8959 */
8960 OO.ui.DropdownInputWidget.prototype.onMenuSelect = function ( item ) {
8961 this.setValue( item ? item.getData() : '' );
8962 };
8963
8964 /**
8965 * @inheritdoc
8966 */
8967 OO.ui.DropdownInputWidget.prototype.setValue = function ( value ) {
8968 var selected;
8969 value = this.cleanUpValue( value );
8970 // Only allow setting values that are actually present in the dropdown
8971 selected = this.dropdownWidget.getMenu().getItemFromData( value ) ||
8972 this.dropdownWidget.getMenu().getFirstSelectableItem();
8973 this.dropdownWidget.getMenu().selectItem( selected );
8974 value = selected ? selected.getData() : '';
8975 OO.ui.DropdownInputWidget.parent.prototype.setValue.call( this, value );
8976 return this;
8977 };
8978
8979 /**
8980 * @inheritdoc
8981 */
8982 OO.ui.DropdownInputWidget.prototype.setDisabled = function ( state ) {
8983 this.dropdownWidget.setDisabled( state );
8984 OO.ui.DropdownInputWidget.parent.prototype.setDisabled.call( this, state );
8985 return this;
8986 };
8987
8988 /**
8989 * Set the options available for this input.
8990 *
8991 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
8992 * @chainable
8993 */
8994 OO.ui.DropdownInputWidget.prototype.setOptions = function ( options ) {
8995 var
8996 value = this.getValue(),
8997 widget = this;
8998
8999 // Rebuild the dropdown menu
9000 this.dropdownWidget.getMenu()
9001 .clearItems()
9002 .addItems( options.map( function ( opt ) {
9003 var optValue = widget.cleanUpValue( opt.data );
9004
9005 if ( opt.optgroup === undefined ) {
9006 return new OO.ui.MenuOptionWidget( {
9007 data: optValue,
9008 label: opt.label !== undefined ? opt.label : optValue
9009 } );
9010 } else {
9011 return new OO.ui.MenuSectionOptionWidget( {
9012 label: opt.optgroup
9013 } );
9014 }
9015 } ) );
9016
9017 // Restore the previous value, or reset to something sensible
9018 if ( this.dropdownWidget.getMenu().getItemFromData( value ) ) {
9019 // Previous value is still available, ensure consistency with the dropdown
9020 this.setValue( value );
9021 } else {
9022 // No longer valid, reset
9023 if ( options.length ) {
9024 this.setValue( options[ 0 ].data );
9025 }
9026 }
9027
9028 return this;
9029 };
9030
9031 /**
9032 * @inheritdoc
9033 */
9034 OO.ui.DropdownInputWidget.prototype.focus = function () {
9035 this.dropdownWidget.focus();
9036 return this;
9037 };
9038
9039 /**
9040 * @inheritdoc
9041 */
9042 OO.ui.DropdownInputWidget.prototype.blur = function () {
9043 this.dropdownWidget.blur();
9044 return this;
9045 };
9046
9047 /**
9048 * RadioInputWidget creates a single radio button. Because radio buttons are usually used as a set,
9049 * in most cases you will want to use a {@link OO.ui.RadioSelectWidget radio select}
9050 * with {@link OO.ui.RadioOptionWidget radio options} instead of this class. For more information,
9051 * please see the [OOjs UI documentation on MediaWiki][1].
9052 *
9053 * This widget can be used inside an HTML form, such as a OO.ui.FormLayout.
9054 *
9055 * @example
9056 * // An example of selected, unselected, and disabled radio inputs
9057 * var radio1 = new OO.ui.RadioInputWidget( {
9058 * value: 'a',
9059 * selected: true
9060 * } );
9061 * var radio2 = new OO.ui.RadioInputWidget( {
9062 * value: 'b'
9063 * } );
9064 * var radio3 = new OO.ui.RadioInputWidget( {
9065 * value: 'c',
9066 * disabled: true
9067 * } );
9068 * // Create a fieldset layout with fields for each radio button.
9069 * var fieldset = new OO.ui.FieldsetLayout( {
9070 * label: 'Radio inputs'
9071 * } );
9072 * fieldset.addItems( [
9073 * new OO.ui.FieldLayout( radio1, { label: 'Selected', align: 'inline' } ),
9074 * new OO.ui.FieldLayout( radio2, { label: 'Unselected', align: 'inline' } ),
9075 * new OO.ui.FieldLayout( radio3, { label: 'Disabled', align: 'inline' } ),
9076 * ] );
9077 * $( 'body' ).append( fieldset.$element );
9078 *
9079 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
9080 *
9081 * @class
9082 * @extends OO.ui.InputWidget
9083 *
9084 * @constructor
9085 * @param {Object} [config] Configuration options
9086 * @cfg {boolean} [selected=false] Select the radio button initially. By default, the radio button is not selected.
9087 */
9088 OO.ui.RadioInputWidget = function OoUiRadioInputWidget( config ) {
9089 // Configuration initialization
9090 config = config || {};
9091
9092 // Parent constructor
9093 OO.ui.RadioInputWidget.parent.call( this, config );
9094
9095 // Initialization
9096 this.$element
9097 .addClass( 'oo-ui-radioInputWidget' )
9098 // Required for pretty styling in WikimediaUI theme
9099 .append( $( '<span>' ) );
9100 this.setSelected( config.selected !== undefined ? config.selected : false );
9101 };
9102
9103 /* Setup */
9104
9105 OO.inheritClass( OO.ui.RadioInputWidget, OO.ui.InputWidget );
9106
9107 /* Static Properties */
9108
9109 /**
9110 * @static
9111 * @inheritdoc
9112 */
9113 OO.ui.RadioInputWidget.static.tagName = 'span';
9114
9115 /* Static Methods */
9116
9117 /**
9118 * @inheritdoc
9119 */
9120 OO.ui.RadioInputWidget.static.gatherPreInfuseState = function ( node, config ) {
9121 var state = OO.ui.RadioInputWidget.parent.static.gatherPreInfuseState( node, config );
9122 state.checked = config.$input.prop( 'checked' );
9123 return state;
9124 };
9125
9126 /* Methods */
9127
9128 /**
9129 * @inheritdoc
9130 * @protected
9131 */
9132 OO.ui.RadioInputWidget.prototype.getInputElement = function () {
9133 return $( '<input>' ).attr( 'type', 'radio' );
9134 };
9135
9136 /**
9137 * @inheritdoc
9138 */
9139 OO.ui.RadioInputWidget.prototype.onEdit = function () {
9140 // RadioInputWidget doesn't track its state.
9141 };
9142
9143 /**
9144 * Set selection state of this radio button.
9145 *
9146 * @param {boolean} state `true` for selected
9147 * @chainable
9148 */
9149 OO.ui.RadioInputWidget.prototype.setSelected = function ( state ) {
9150 // RadioInputWidget doesn't track its state.
9151 this.$input.prop( 'checked', state );
9152 return this;
9153 };
9154
9155 /**
9156 * Check if this radio button is selected.
9157 *
9158 * @return {boolean} Radio is selected
9159 */
9160 OO.ui.RadioInputWidget.prototype.isSelected = function () {
9161 return this.$input.prop( 'checked' );
9162 };
9163
9164 /**
9165 * @inheritdoc
9166 */
9167 OO.ui.RadioInputWidget.prototype.simulateLabelClick = function () {
9168 if ( !this.isDisabled() ) {
9169 this.$input.click();
9170 }
9171 this.focus();
9172 };
9173
9174 /**
9175 * @inheritdoc
9176 */
9177 OO.ui.RadioInputWidget.prototype.restorePreInfuseState = function ( state ) {
9178 OO.ui.RadioInputWidget.parent.prototype.restorePreInfuseState.call( this, state );
9179 if ( state.checked !== undefined && state.checked !== this.isSelected() ) {
9180 this.setSelected( state.checked );
9181 }
9182 };
9183
9184 /**
9185 * RadioSelectInputWidget is a {@link OO.ui.RadioSelectWidget RadioSelectWidget} intended to be used
9186 * within an HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with the value
9187 * of a hidden HTML `input` tag. Please see the [OOjs UI documentation on MediaWiki][1] for
9188 * more information about input widgets.
9189 *
9190 * This and OO.ui.DropdownInputWidget support the same configuration options.
9191 *
9192 * @example
9193 * // Example: A RadioSelectInputWidget with three options
9194 * var radioSelectInput = new OO.ui.RadioSelectInputWidget( {
9195 * options: [
9196 * { data: 'a', label: 'First' },
9197 * { data: 'b', label: 'Second'},
9198 * { data: 'c', label: 'Third' }
9199 * ]
9200 * } );
9201 * $( 'body' ).append( radioSelectInput.$element );
9202 *
9203 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
9204 *
9205 * @class
9206 * @extends OO.ui.InputWidget
9207 *
9208 * @constructor
9209 * @param {Object} [config] Configuration options
9210 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
9211 */
9212 OO.ui.RadioSelectInputWidget = function OoUiRadioSelectInputWidget( config ) {
9213 // Configuration initialization
9214 config = config || {};
9215
9216 // Properties (must be done before parent constructor which calls #setDisabled)
9217 this.radioSelectWidget = new OO.ui.RadioSelectWidget();
9218
9219 // Parent constructor
9220 OO.ui.RadioSelectInputWidget.parent.call( this, config );
9221
9222 // Events
9223 this.radioSelectWidget.connect( this, { select: 'onMenuSelect' } );
9224
9225 // Initialization
9226 this.setOptions( config.options || [] );
9227 this.$element
9228 .addClass( 'oo-ui-radioSelectInputWidget' )
9229 .append( this.radioSelectWidget.$element );
9230 this.setTabIndexedElement( null );
9231 };
9232
9233 /* Setup */
9234
9235 OO.inheritClass( OO.ui.RadioSelectInputWidget, OO.ui.InputWidget );
9236
9237 /* Static Methods */
9238
9239 /**
9240 * @inheritdoc
9241 */
9242 OO.ui.RadioSelectInputWidget.static.gatherPreInfuseState = function ( node, config ) {
9243 var state = OO.ui.RadioSelectInputWidget.parent.static.gatherPreInfuseState( node, config );
9244 state.value = $( node ).find( '.oo-ui-radioInputWidget .oo-ui-inputWidget-input:checked' ).val();
9245 return state;
9246 };
9247
9248 /**
9249 * @inheritdoc
9250 */
9251 OO.ui.RadioSelectInputWidget.static.reusePreInfuseDOM = function ( node, config ) {
9252 config = OO.ui.RadioSelectInputWidget.parent.static.reusePreInfuseDOM( node, config );
9253 // Cannot reuse the `<input type=radio>` set
9254 delete config.$input;
9255 return config;
9256 };
9257
9258 /* Methods */
9259
9260 /**
9261 * @inheritdoc
9262 * @protected
9263 */
9264 OO.ui.RadioSelectInputWidget.prototype.getInputElement = function () {
9265 return $( '<input>' ).attr( 'type', 'hidden' );
9266 };
9267
9268 /**
9269 * Handles menu select events.
9270 *
9271 * @private
9272 * @param {OO.ui.RadioOptionWidget} item Selected menu item
9273 */
9274 OO.ui.RadioSelectInputWidget.prototype.onMenuSelect = function ( item ) {
9275 this.setValue( item.getData() );
9276 };
9277
9278 /**
9279 * @inheritdoc
9280 */
9281 OO.ui.RadioSelectInputWidget.prototype.setValue = function ( value ) {
9282 value = this.cleanUpValue( value );
9283 this.radioSelectWidget.selectItemByData( value );
9284 OO.ui.RadioSelectInputWidget.parent.prototype.setValue.call( this, value );
9285 return this;
9286 };
9287
9288 /**
9289 * @inheritdoc
9290 */
9291 OO.ui.RadioSelectInputWidget.prototype.setDisabled = function ( state ) {
9292 this.radioSelectWidget.setDisabled( state );
9293 OO.ui.RadioSelectInputWidget.parent.prototype.setDisabled.call( this, state );
9294 return this;
9295 };
9296
9297 /**
9298 * Set the options available for this input.
9299 *
9300 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
9301 * @chainable
9302 */
9303 OO.ui.RadioSelectInputWidget.prototype.setOptions = function ( options ) {
9304 var
9305 value = this.getValue(),
9306 widget = this;
9307
9308 // Rebuild the radioSelect menu
9309 this.radioSelectWidget
9310 .clearItems()
9311 .addItems( options.map( function ( opt ) {
9312 var optValue = widget.cleanUpValue( opt.data );
9313 return new OO.ui.RadioOptionWidget( {
9314 data: optValue,
9315 label: opt.label !== undefined ? opt.label : optValue
9316 } );
9317 } ) );
9318
9319 // Restore the previous value, or reset to something sensible
9320 if ( this.radioSelectWidget.getItemFromData( value ) ) {
9321 // Previous value is still available, ensure consistency with the radioSelect
9322 this.setValue( value );
9323 } else {
9324 // No longer valid, reset
9325 if ( options.length ) {
9326 this.setValue( options[ 0 ].data );
9327 }
9328 }
9329
9330 return this;
9331 };
9332
9333 /**
9334 * @inheritdoc
9335 */
9336 OO.ui.RadioSelectInputWidget.prototype.focus = function () {
9337 this.radioSelectWidget.focus();
9338 return this;
9339 };
9340
9341 /**
9342 * @inheritdoc
9343 */
9344 OO.ui.RadioSelectInputWidget.prototype.blur = function () {
9345 this.radioSelectWidget.blur();
9346 return this;
9347 };
9348
9349 /**
9350 * CheckboxMultiselectInputWidget is a
9351 * {@link OO.ui.CheckboxMultiselectWidget CheckboxMultiselectWidget} intended to be used within a
9352 * HTML form, such as a OO.ui.FormLayout. The selected values are synchronized with the value of
9353 * HTML `<input type=checkbox>` tags. Please see the [OOjs UI documentation on MediaWiki][1] for
9354 * more information about input widgets.
9355 *
9356 * @example
9357 * // Example: A CheckboxMultiselectInputWidget with three options
9358 * var multiselectInput = new OO.ui.CheckboxMultiselectInputWidget( {
9359 * options: [
9360 * { data: 'a', label: 'First' },
9361 * { data: 'b', label: 'Second'},
9362 * { data: 'c', label: 'Third' }
9363 * ]
9364 * } );
9365 * $( 'body' ).append( multiselectInput.$element );
9366 *
9367 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
9368 *
9369 * @class
9370 * @extends OO.ui.InputWidget
9371 *
9372 * @constructor
9373 * @param {Object} [config] Configuration options
9374 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: …, disabled: … }`
9375 */
9376 OO.ui.CheckboxMultiselectInputWidget = function OoUiCheckboxMultiselectInputWidget( config ) {
9377 // Configuration initialization
9378 config = config || {};
9379
9380 // Properties (must be done before parent constructor which calls #setDisabled)
9381 this.checkboxMultiselectWidget = new OO.ui.CheckboxMultiselectWidget();
9382
9383 // Parent constructor
9384 OO.ui.CheckboxMultiselectInputWidget.parent.call( this, config );
9385
9386 // Properties
9387 this.inputName = config.name;
9388
9389 // Initialization
9390 this.$element
9391 .addClass( 'oo-ui-checkboxMultiselectInputWidget' )
9392 .append( this.checkboxMultiselectWidget.$element );
9393 // We don't use this.$input, but rather the CheckboxInputWidgets inside each option
9394 this.$input.detach();
9395 this.setOptions( config.options || [] );
9396 // Have to repeat this from parent, as we need options to be set up for this to make sense
9397 this.setValue( config.value );
9398
9399 // setValue when checkboxMultiselectWidget changes
9400 this.checkboxMultiselectWidget.on( 'change', function () {
9401 this.setValue( this.checkboxMultiselectWidget.getSelectedItemsData() );
9402 }.bind( this ) );
9403 };
9404
9405 /* Setup */
9406
9407 OO.inheritClass( OO.ui.CheckboxMultiselectInputWidget, OO.ui.InputWidget );
9408
9409 /* Static Methods */
9410
9411 /**
9412 * @inheritdoc
9413 */
9414 OO.ui.CheckboxMultiselectInputWidget.static.gatherPreInfuseState = function ( node, config ) {
9415 var state = OO.ui.CheckboxMultiselectInputWidget.parent.static.gatherPreInfuseState( node, config );
9416 state.value = $( node ).find( '.oo-ui-checkboxInputWidget .oo-ui-inputWidget-input:checked' )
9417 .toArray().map( function ( el ) { return el.value; } );
9418 return state;
9419 };
9420
9421 /**
9422 * @inheritdoc
9423 */
9424 OO.ui.CheckboxMultiselectInputWidget.static.reusePreInfuseDOM = function ( node, config ) {
9425 config = OO.ui.CheckboxMultiselectInputWidget.parent.static.reusePreInfuseDOM( node, config );
9426 // Cannot reuse the `<input type=checkbox>` set
9427 delete config.$input;
9428 return config;
9429 };
9430
9431 /* Methods */
9432
9433 /**
9434 * @inheritdoc
9435 * @protected
9436 */
9437 OO.ui.CheckboxMultiselectInputWidget.prototype.getInputElement = function () {
9438 // Actually unused
9439 return $( '<unused>' );
9440 };
9441
9442 /**
9443 * @inheritdoc
9444 */
9445 OO.ui.CheckboxMultiselectInputWidget.prototype.getValue = function () {
9446 var value = this.$element.find( '.oo-ui-checkboxInputWidget .oo-ui-inputWidget-input:checked' )
9447 .toArray().map( function ( el ) { return el.value; } );
9448 if ( this.value !== value ) {
9449 this.setValue( value );
9450 }
9451 return this.value;
9452 };
9453
9454 /**
9455 * @inheritdoc
9456 */
9457 OO.ui.CheckboxMultiselectInputWidget.prototype.setValue = function ( value ) {
9458 value = this.cleanUpValue( value );
9459 this.checkboxMultiselectWidget.selectItemsByData( value );
9460 OO.ui.CheckboxMultiselectInputWidget.parent.prototype.setValue.call( this, value );
9461 return this;
9462 };
9463
9464 /**
9465 * Clean up incoming value.
9466 *
9467 * @param {string[]} value Original value
9468 * @return {string[]} Cleaned up value
9469 */
9470 OO.ui.CheckboxMultiselectInputWidget.prototype.cleanUpValue = function ( value ) {
9471 var i, singleValue,
9472 cleanValue = [];
9473 if ( !Array.isArray( value ) ) {
9474 return cleanValue;
9475 }
9476 for ( i = 0; i < value.length; i++ ) {
9477 singleValue =
9478 OO.ui.CheckboxMultiselectInputWidget.parent.prototype.cleanUpValue.call( this, value[ i ] );
9479 // Remove options that we don't have here
9480 if ( !this.checkboxMultiselectWidget.getItemFromData( singleValue ) ) {
9481 continue;
9482 }
9483 cleanValue.push( singleValue );
9484 }
9485 return cleanValue;
9486 };
9487
9488 /**
9489 * @inheritdoc
9490 */
9491 OO.ui.CheckboxMultiselectInputWidget.prototype.setDisabled = function ( state ) {
9492 this.checkboxMultiselectWidget.setDisabled( state );
9493 OO.ui.CheckboxMultiselectInputWidget.parent.prototype.setDisabled.call( this, state );
9494 return this;
9495 };
9496
9497 /**
9498 * Set the options available for this input.
9499 *
9500 * @param {Object[]} options Array of menu options in the format `{ data: …, label: …, disabled: … }`
9501 * @chainable
9502 */
9503 OO.ui.CheckboxMultiselectInputWidget.prototype.setOptions = function ( options ) {
9504 var widget = this;
9505
9506 // Rebuild the checkboxMultiselectWidget menu
9507 this.checkboxMultiselectWidget
9508 .clearItems()
9509 .addItems( options.map( function ( opt ) {
9510 var optValue, item, optDisabled;
9511 optValue =
9512 OO.ui.CheckboxMultiselectInputWidget.parent.prototype.cleanUpValue.call( widget, opt.data );
9513 optDisabled = opt.disabled !== undefined ? opt.disabled : false;
9514 item = new OO.ui.CheckboxMultioptionWidget( {
9515 data: optValue,
9516 label: opt.label !== undefined ? opt.label : optValue,
9517 disabled: optDisabled
9518 } );
9519 // Set the 'name' and 'value' for form submission
9520 item.checkbox.$input.attr( 'name', widget.inputName );
9521 item.checkbox.setValue( optValue );
9522 return item;
9523 } ) );
9524
9525 // Re-set the value, checking the checkboxes as needed.
9526 // This will also get rid of any stale options that we just removed.
9527 this.setValue( this.getValue() );
9528
9529 return this;
9530 };
9531
9532 /**
9533 * @inheritdoc
9534 */
9535 OO.ui.CheckboxMultiselectInputWidget.prototype.focus = function () {
9536 this.checkboxMultiselectWidget.focus();
9537 return this;
9538 };
9539
9540 /**
9541 * TextInputWidgets, like HTML text inputs, can be configured with options that customize the
9542 * size of the field as well as its presentation. In addition, these widgets can be configured
9543 * with {@link OO.ui.mixin.IconElement icons}, {@link OO.ui.mixin.IndicatorElement indicators}, an optional
9544 * validation-pattern (used to determine if an input value is valid or not) and an input filter,
9545 * which modifies incoming values rather than validating them.
9546 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
9547 *
9548 * This widget can be used inside an HTML form, such as a OO.ui.FormLayout.
9549 *
9550 * @example
9551 * // Example of a text input widget
9552 * var textInput = new OO.ui.TextInputWidget( {
9553 * value: 'Text input'
9554 * } )
9555 * $( 'body' ).append( textInput.$element );
9556 *
9557 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
9558 *
9559 * @class
9560 * @extends OO.ui.InputWidget
9561 * @mixins OO.ui.mixin.IconElement
9562 * @mixins OO.ui.mixin.IndicatorElement
9563 * @mixins OO.ui.mixin.PendingElement
9564 * @mixins OO.ui.mixin.LabelElement
9565 *
9566 * @constructor
9567 * @param {Object} [config] Configuration options
9568 * @cfg {string} [type='text'] The value of the HTML `type` attribute: 'text', 'password'
9569 * 'email', 'url' or 'number'.
9570 * @cfg {string} [placeholder] Placeholder text
9571 * @cfg {boolean} [autofocus=false] Use an HTML `autofocus` attribute to
9572 * instruct the browser to focus this widget.
9573 * @cfg {boolean} [readOnly=false] Prevent changes to the value of the text input.
9574 * @cfg {number} [maxLength] Maximum number of characters allowed in the input.
9575 * @cfg {string} [labelPosition='after'] The position of the inline label relative to that of
9576 * the value or placeholder text: `'before'` or `'after'`
9577 * @cfg {boolean} [required=false] Mark the field as required. Implies `indicator: 'required'`.
9578 * @cfg {boolean} [autocomplete=true] Should the browser support autocomplete for this field
9579 * @cfg {RegExp|Function|string} [validate] Validation pattern: when string, a symbolic name of a
9580 * pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer'
9581 * (the value must contain only numbers); when RegExp, a regular expression that must match the
9582 * value for it to be considered valid; when Function, a function receiving the value as parameter
9583 * that must return true, or promise resolving to true, for it to be considered valid.
9584 */
9585 OO.ui.TextInputWidget = function OoUiTextInputWidget( config ) {
9586 // Configuration initialization
9587 config = $.extend( {
9588 type: 'text',
9589 labelPosition: 'after'
9590 }, config );
9591
9592 if ( config.multiline ) {
9593 OO.ui.warnDeprecation( 'TextInputWidget: config.multiline is deprecated. Use the MultilineTextInputWidget instead. See T130434.' );
9594 return new OO.ui.MultilineTextInputWidget( config );
9595 }
9596
9597 // Parent constructor
9598 OO.ui.TextInputWidget.parent.call( this, config );
9599
9600 // Mixin constructors
9601 OO.ui.mixin.IconElement.call( this, config );
9602 OO.ui.mixin.IndicatorElement.call( this, config );
9603 OO.ui.mixin.PendingElement.call( this, $.extend( {}, config, { $pending: this.$input } ) );
9604 OO.ui.mixin.LabelElement.call( this, config );
9605
9606 // Properties
9607 this.type = this.getSaneType( config );
9608 this.readOnly = false;
9609 this.required = false;
9610 this.validate = null;
9611 this.styleHeight = null;
9612 this.scrollWidth = null;
9613
9614 this.setValidation( config.validate );
9615 this.setLabelPosition( config.labelPosition );
9616
9617 // Events
9618 this.$input.on( {
9619 keypress: this.onKeyPress.bind( this ),
9620 blur: this.onBlur.bind( this ),
9621 focus: this.onFocus.bind( this )
9622 } );
9623 this.$icon.on( 'mousedown', this.onIconMouseDown.bind( this ) );
9624 this.$indicator.on( 'mousedown', this.onIndicatorMouseDown.bind( this ) );
9625 this.on( 'labelChange', this.updatePosition.bind( this ) );
9626 this.on( 'change', OO.ui.debounce( this.onDebouncedChange.bind( this ), 250 ) );
9627
9628 // Initialization
9629 this.$element
9630 .addClass( 'oo-ui-textInputWidget oo-ui-textInputWidget-type-' + this.type )
9631 .append( this.$icon, this.$indicator );
9632 this.setReadOnly( !!config.readOnly );
9633 this.setRequired( !!config.required );
9634 if ( config.placeholder !== undefined ) {
9635 this.$input.attr( 'placeholder', config.placeholder );
9636 }
9637 if ( config.maxLength !== undefined ) {
9638 this.$input.attr( 'maxlength', config.maxLength );
9639 }
9640 if ( config.autofocus ) {
9641 this.$input.attr( 'autofocus', 'autofocus' );
9642 }
9643 if ( config.autocomplete === false ) {
9644 this.$input.attr( 'autocomplete', 'off' );
9645 // Turning off autocompletion also disables "form caching" when the user navigates to a
9646 // different page and then clicks "Back". Re-enable it when leaving. Borrowed from jQuery UI.
9647 $( window ).on( {
9648 beforeunload: function () {
9649 this.$input.removeAttr( 'autocomplete' );
9650 }.bind( this ),
9651 pageshow: function () {
9652 // Browsers don't seem to actually fire this event on "Back", they instead just reload the
9653 // whole page... it shouldn't hurt, though.
9654 this.$input.attr( 'autocomplete', 'off' );
9655 }.bind( this )
9656 } );
9657 }
9658 if ( this.label ) {
9659 this.isWaitingToBeAttached = true;
9660 this.installParentChangeDetector();
9661 }
9662 };
9663
9664 /* Setup */
9665
9666 OO.inheritClass( OO.ui.TextInputWidget, OO.ui.InputWidget );
9667 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.mixin.IconElement );
9668 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.mixin.IndicatorElement );
9669 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.mixin.PendingElement );
9670 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.mixin.LabelElement );
9671
9672 /* Static Properties */
9673
9674 OO.ui.TextInputWidget.static.validationPatterns = {
9675 'non-empty': /.+/,
9676 integer: /^\d+$/
9677 };
9678
9679 /* Static Methods */
9680
9681 /**
9682 * @inheritdoc
9683 */
9684 OO.ui.TextInputWidget.static.gatherPreInfuseState = function ( node, config ) {
9685 var state = OO.ui.TextInputWidget.parent.static.gatherPreInfuseState( node, config );
9686 return state;
9687 };
9688
9689 /* Events */
9690
9691 /**
9692 * An `enter` event is emitted when the user presses 'enter' inside the text box.
9693 *
9694 * @event enter
9695 */
9696
9697 /* Methods */
9698
9699 /**
9700 * Handle icon mouse down events.
9701 *
9702 * @private
9703 * @param {jQuery.Event} e Mouse down event
9704 */
9705 OO.ui.TextInputWidget.prototype.onIconMouseDown = function ( e ) {
9706 if ( e.which === OO.ui.MouseButtons.LEFT ) {
9707 this.focus();
9708 return false;
9709 }
9710 };
9711
9712 /**
9713 * Handle indicator mouse down events.
9714 *
9715 * @private
9716 * @param {jQuery.Event} e Mouse down event
9717 */
9718 OO.ui.TextInputWidget.prototype.onIndicatorMouseDown = function ( e ) {
9719 if ( e.which === OO.ui.MouseButtons.LEFT ) {
9720 this.focus();
9721 return false;
9722 }
9723 };
9724
9725 /**
9726 * Handle key press events.
9727 *
9728 * @private
9729 * @param {jQuery.Event} e Key press event
9730 * @fires enter If enter key is pressed
9731 */
9732 OO.ui.TextInputWidget.prototype.onKeyPress = function ( e ) {
9733 if ( e.which === OO.ui.Keys.ENTER ) {
9734 this.emit( 'enter', e );
9735 }
9736 };
9737
9738 /**
9739 * Handle blur events.
9740 *
9741 * @private
9742 * @param {jQuery.Event} e Blur event
9743 */
9744 OO.ui.TextInputWidget.prototype.onBlur = function () {
9745 this.setValidityFlag();
9746 };
9747
9748 /**
9749 * Handle focus events.
9750 *
9751 * @private
9752 * @param {jQuery.Event} e Focus event
9753 */
9754 OO.ui.TextInputWidget.prototype.onFocus = function () {
9755 if ( this.isWaitingToBeAttached ) {
9756 // If we've received focus, then we must be attached to the document, and if
9757 // isWaitingToBeAttached is still true, that means the handler never fired. Fire it now.
9758 this.onElementAttach();
9759 }
9760 this.setValidityFlag( true );
9761 };
9762
9763 /**
9764 * Handle element attach events.
9765 *
9766 * @private
9767 * @param {jQuery.Event} e Element attach event
9768 */
9769 OO.ui.TextInputWidget.prototype.onElementAttach = function () {
9770 this.isWaitingToBeAttached = false;
9771 // Any previously calculated size is now probably invalid if we reattached elsewhere
9772 this.valCache = null;
9773 this.positionLabel();
9774 };
9775
9776 /**
9777 * Handle debounced change events.
9778 *
9779 * @param {string} value
9780 * @private
9781 */
9782 OO.ui.TextInputWidget.prototype.onDebouncedChange = function () {
9783 this.setValidityFlag();
9784 };
9785
9786 /**
9787 * Check if the input is {@link #readOnly read-only}.
9788 *
9789 * @return {boolean}
9790 */
9791 OO.ui.TextInputWidget.prototype.isReadOnly = function () {
9792 return this.readOnly;
9793 };
9794
9795 /**
9796 * Set the {@link #readOnly read-only} state of the input.
9797 *
9798 * @param {boolean} state Make input read-only
9799 * @chainable
9800 */
9801 OO.ui.TextInputWidget.prototype.setReadOnly = function ( state ) {
9802 this.readOnly = !!state;
9803 this.$input.prop( 'readOnly', this.readOnly );
9804 return this;
9805 };
9806
9807 /**
9808 * Check if the input is {@link #required required}.
9809 *
9810 * @return {boolean}
9811 */
9812 OO.ui.TextInputWidget.prototype.isRequired = function () {
9813 return this.required;
9814 };
9815
9816 /**
9817 * Set the {@link #required required} state of the input.
9818 *
9819 * @param {boolean} state Make input required
9820 * @chainable
9821 */
9822 OO.ui.TextInputWidget.prototype.setRequired = function ( state ) {
9823 this.required = !!state;
9824 if ( this.required ) {
9825 this.$input
9826 .prop( 'required', true )
9827 .attr( 'aria-required', 'true' );
9828 if ( this.getIndicator() === null ) {
9829 this.setIndicator( 'required' );
9830 }
9831 } else {
9832 this.$input
9833 .prop( 'required', false )
9834 .removeAttr( 'aria-required' );
9835 if ( this.getIndicator() === 'required' ) {
9836 this.setIndicator( null );
9837 }
9838 }
9839 return this;
9840 };
9841
9842 /**
9843 * Support function for making #onElementAttach work across browsers.
9844 *
9845 * This whole function could be replaced with one line of code using the DOMNodeInsertedIntoDocument
9846 * event, but it's not supported by Firefox and allegedly deprecated, so we only use it as fallback.
9847 *
9848 * Due to MutationObserver performance woes, #onElementAttach is only somewhat reliably called the
9849 * first time that the element gets attached to the documented.
9850 */
9851 OO.ui.TextInputWidget.prototype.installParentChangeDetector = function () {
9852 var mutationObserver, onRemove, topmostNode, fakeParentNode,
9853 MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver,
9854 widget = this;
9855
9856 if ( MutationObserver ) {
9857 // The new way. If only it wasn't so ugly.
9858
9859 if ( this.isElementAttached() ) {
9860 // Widget is attached already, do nothing. This breaks the functionality of this function when
9861 // the widget is detached and reattached. Alas, doing this correctly with MutationObserver
9862 // would require observation of the whole document, which would hurt performance of other,
9863 // more important code.
9864 return;
9865 }
9866
9867 // Find topmost node in the tree
9868 topmostNode = this.$element[ 0 ];
9869 while ( topmostNode.parentNode ) {
9870 topmostNode = topmostNode.parentNode;
9871 }
9872
9873 // We have no way to detect the $element being attached somewhere without observing the entire
9874 // DOM with subtree modifications, which would hurt performance. So we cheat: we hook to the
9875 // parent node of $element, and instead detect when $element is removed from it (and thus
9876 // probably attached somewhere else). If there is no parent, we create a "fake" one. If it
9877 // doesn't get attached, we end up back here and create the parent.
9878
9879 mutationObserver = new MutationObserver( function ( mutations ) {
9880 var i, j, removedNodes;
9881 for ( i = 0; i < mutations.length; i++ ) {
9882 removedNodes = mutations[ i ].removedNodes;
9883 for ( j = 0; j < removedNodes.length; j++ ) {
9884 if ( removedNodes[ j ] === topmostNode ) {
9885 setTimeout( onRemove, 0 );
9886 return;
9887 }
9888 }
9889 }
9890 } );
9891
9892 onRemove = function () {
9893 // If the node was attached somewhere else, report it
9894 if ( widget.isElementAttached() ) {
9895 widget.onElementAttach();
9896 }
9897 mutationObserver.disconnect();
9898 widget.installParentChangeDetector();
9899 };
9900
9901 // Create a fake parent and observe it
9902 fakeParentNode = $( '<div>' ).append( topmostNode )[ 0 ];
9903 mutationObserver.observe( fakeParentNode, { childList: true } );
9904 } else {
9905 // Using the DOMNodeInsertedIntoDocument event is much nicer and less magical, and works for
9906 // detachment and reattachment, but it's not supported by Firefox and allegedly deprecated.
9907 this.$element.on( 'DOMNodeInsertedIntoDocument', this.onElementAttach.bind( this ) );
9908 }
9909 };
9910
9911 /**
9912 * @inheritdoc
9913 * @protected
9914 */
9915 OO.ui.TextInputWidget.prototype.getInputElement = function ( config ) {
9916 if ( this.getSaneType( config ) === 'number' ) {
9917 return $( '<input>' )
9918 .attr( 'step', 'any' )
9919 .attr( 'type', 'number' );
9920 } else {
9921 return $( '<input>' ).attr( 'type', this.getSaneType( config ) );
9922 }
9923 };
9924
9925 /**
9926 * Get sanitized value for 'type' for given config.
9927 *
9928 * @param {Object} config Configuration options
9929 * @return {string|null}
9930 * @private
9931 */
9932 OO.ui.TextInputWidget.prototype.getSaneType = function ( config ) {
9933 var allowedTypes = [
9934 'text',
9935 'password',
9936 'email',
9937 'url',
9938 'number'
9939 ];
9940 return allowedTypes.indexOf( config.type ) !== -1 ? config.type : 'text';
9941 };
9942
9943 /**
9944 * Focus the input and select a specified range within the text.
9945 *
9946 * @param {number} from Select from offset
9947 * @param {number} [to] Select to offset, defaults to from
9948 * @chainable
9949 */
9950 OO.ui.TextInputWidget.prototype.selectRange = function ( from, to ) {
9951 var isBackwards, start, end,
9952 input = this.$input[ 0 ];
9953
9954 to = to || from;
9955
9956 isBackwards = to < from;
9957 start = isBackwards ? to : from;
9958 end = isBackwards ? from : to;
9959
9960 this.focus();
9961
9962 try {
9963 input.setSelectionRange( start, end, isBackwards ? 'backward' : 'forward' );
9964 } catch ( e ) {
9965 // IE throws an exception if you call setSelectionRange on a unattached DOM node.
9966 // Rather than expensively check if the input is attached every time, just check
9967 // if it was the cause of an error being thrown. If not, rethrow the error.
9968 if ( this.getElementDocument().body.contains( input ) ) {
9969 throw e;
9970 }
9971 }
9972 return this;
9973 };
9974
9975 /**
9976 * Get an object describing the current selection range in a directional manner
9977 *
9978 * @return {Object} Object containing 'from' and 'to' offsets
9979 */
9980 OO.ui.TextInputWidget.prototype.getRange = function () {
9981 var input = this.$input[ 0 ],
9982 start = input.selectionStart,
9983 end = input.selectionEnd,
9984 isBackwards = input.selectionDirection === 'backward';
9985
9986 return {
9987 from: isBackwards ? end : start,
9988 to: isBackwards ? start : end
9989 };
9990 };
9991
9992 /**
9993 * Get the length of the text input value.
9994 *
9995 * This could differ from the length of #getValue if the
9996 * value gets filtered
9997 *
9998 * @return {number} Input length
9999 */
10000 OO.ui.TextInputWidget.prototype.getInputLength = function () {
10001 return this.$input[ 0 ].value.length;
10002 };
10003
10004 /**
10005 * Focus the input and select the entire text.
10006 *
10007 * @chainable
10008 */
10009 OO.ui.TextInputWidget.prototype.select = function () {
10010 return this.selectRange( 0, this.getInputLength() );
10011 };
10012
10013 /**
10014 * Focus the input and move the cursor to the start.
10015 *
10016 * @chainable
10017 */
10018 OO.ui.TextInputWidget.prototype.moveCursorToStart = function () {
10019 return this.selectRange( 0 );
10020 };
10021
10022 /**
10023 * Focus the input and move the cursor to the end.
10024 *
10025 * @chainable
10026 */
10027 OO.ui.TextInputWidget.prototype.moveCursorToEnd = function () {
10028 return this.selectRange( this.getInputLength() );
10029 };
10030
10031 /**
10032 * Insert new content into the input.
10033 *
10034 * @param {string} content Content to be inserted
10035 * @chainable
10036 */
10037 OO.ui.TextInputWidget.prototype.insertContent = function ( content ) {
10038 var start, end,
10039 range = this.getRange(),
10040 value = this.getValue();
10041
10042 start = Math.min( range.from, range.to );
10043 end = Math.max( range.from, range.to );
10044
10045 this.setValue( value.slice( 0, start ) + content + value.slice( end ) );
10046 this.selectRange( start + content.length );
10047 return this;
10048 };
10049
10050 /**
10051 * Insert new content either side of a selection.
10052 *
10053 * @param {string} pre Content to be inserted before the selection
10054 * @param {string} post Content to be inserted after the selection
10055 * @chainable
10056 */
10057 OO.ui.TextInputWidget.prototype.encapsulateContent = function ( pre, post ) {
10058 var start, end,
10059 range = this.getRange(),
10060 offset = pre.length;
10061
10062 start = Math.min( range.from, range.to );
10063 end = Math.max( range.from, range.to );
10064
10065 this.selectRange( start ).insertContent( pre );
10066 this.selectRange( offset + end ).insertContent( post );
10067
10068 this.selectRange( offset + start, offset + end );
10069 return this;
10070 };
10071
10072 /**
10073 * Set the validation pattern.
10074 *
10075 * The validation pattern is either a regular expression, a function, or the symbolic name of a
10076 * pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer' (the
10077 * value must contain only numbers).
10078 *
10079 * @param {RegExp|Function|string|null} validate Regular expression, function, or the symbolic name
10080 * of a pattern (either ‘integer’ or ‘non-empty’) defined by the class.
10081 */
10082 OO.ui.TextInputWidget.prototype.setValidation = function ( validate ) {
10083 if ( validate instanceof RegExp || validate instanceof Function ) {
10084 this.validate = validate;
10085 } else {
10086 this.validate = this.constructor.static.validationPatterns[ validate ] || /.*/;
10087 }
10088 };
10089
10090 /**
10091 * Sets the 'invalid' flag appropriately.
10092 *
10093 * @param {boolean} [isValid] Optionally override validation result
10094 */
10095 OO.ui.TextInputWidget.prototype.setValidityFlag = function ( isValid ) {
10096 var widget = this,
10097 setFlag = function ( valid ) {
10098 if ( !valid ) {
10099 widget.$input.attr( 'aria-invalid', 'true' );
10100 } else {
10101 widget.$input.removeAttr( 'aria-invalid' );
10102 }
10103 widget.setFlags( { invalid: !valid } );
10104 };
10105
10106 if ( isValid !== undefined ) {
10107 setFlag( isValid );
10108 } else {
10109 this.getValidity().then( function () {
10110 setFlag( true );
10111 }, function () {
10112 setFlag( false );
10113 } );
10114 }
10115 };
10116
10117 /**
10118 * Get the validity of current value.
10119 *
10120 * This method returns a promise that resolves if the value is valid and rejects if
10121 * it isn't. Uses the {@link #validate validation pattern} to check for validity.
10122 *
10123 * @return {jQuery.Promise} A promise that resolves if the value is valid, rejects if not.
10124 */
10125 OO.ui.TextInputWidget.prototype.getValidity = function () {
10126 var result;
10127
10128 function rejectOrResolve( valid ) {
10129 if ( valid ) {
10130 return $.Deferred().resolve().promise();
10131 } else {
10132 return $.Deferred().reject().promise();
10133 }
10134 }
10135
10136 // Check browser validity and reject if it is invalid
10137 if (
10138 this.$input[ 0 ].checkValidity !== undefined &&
10139 this.$input[ 0 ].checkValidity() === false
10140 ) {
10141 return rejectOrResolve( false );
10142 }
10143
10144 // Run our checks if the browser thinks the field is valid
10145 if ( this.validate instanceof Function ) {
10146 result = this.validate( this.getValue() );
10147 if ( result && $.isFunction( result.promise ) ) {
10148 return result.promise().then( function ( valid ) {
10149 return rejectOrResolve( valid );
10150 } );
10151 } else {
10152 return rejectOrResolve( result );
10153 }
10154 } else {
10155 return rejectOrResolve( this.getValue().match( this.validate ) );
10156 }
10157 };
10158
10159 /**
10160 * Set the position of the inline label relative to that of the value: `‘before’` or `‘after’`.
10161 *
10162 * @param {string} labelPosition Label position, 'before' or 'after'
10163 * @chainable
10164 */
10165 OO.ui.TextInputWidget.prototype.setLabelPosition = function ( labelPosition ) {
10166 this.labelPosition = labelPosition;
10167 if ( this.label ) {
10168 // If there is no label and we only change the position, #updatePosition is a no-op,
10169 // but it takes really a lot of work to do nothing.
10170 this.updatePosition();
10171 }
10172 return this;
10173 };
10174
10175 /**
10176 * Update the position of the inline label.
10177 *
10178 * This method is called by #setLabelPosition, and can also be called on its own if
10179 * something causes the label to be mispositioned.
10180 *
10181 * @chainable
10182 */
10183 OO.ui.TextInputWidget.prototype.updatePosition = function () {
10184 var after = this.labelPosition === 'after';
10185
10186 this.$element
10187 .toggleClass( 'oo-ui-textInputWidget-labelPosition-after', !!this.label && after )
10188 .toggleClass( 'oo-ui-textInputWidget-labelPosition-before', !!this.label && !after );
10189
10190 this.valCache = null;
10191 this.scrollWidth = null;
10192 this.positionLabel();
10193
10194 return this;
10195 };
10196
10197 /**
10198 * Position the label by setting the correct padding on the input.
10199 *
10200 * @private
10201 * @chainable
10202 */
10203 OO.ui.TextInputWidget.prototype.positionLabel = function () {
10204 var after, rtl, property, newCss;
10205
10206 if ( this.isWaitingToBeAttached ) {
10207 // #onElementAttach will be called soon, which calls this method
10208 return this;
10209 }
10210
10211 newCss = {
10212 'padding-right': '',
10213 'padding-left': ''
10214 };
10215
10216 if ( this.label ) {
10217 this.$element.append( this.$label );
10218 } else {
10219 this.$label.detach();
10220 // Clear old values if present
10221 this.$input.css( newCss );
10222 return;
10223 }
10224
10225 after = this.labelPosition === 'after';
10226 rtl = this.$element.css( 'direction' ) === 'rtl';
10227 property = after === rtl ? 'padding-left' : 'padding-right';
10228
10229 newCss[ property ] = this.$label.outerWidth( true ) + ( after ? this.scrollWidth : 0 );
10230 // We have to clear the padding on the other side, in case the element direction changed
10231 this.$input.css( newCss );
10232
10233 return this;
10234 };
10235
10236 /**
10237 * @inheritdoc
10238 */
10239 OO.ui.TextInputWidget.prototype.restorePreInfuseState = function ( state ) {
10240 OO.ui.TextInputWidget.parent.prototype.restorePreInfuseState.call( this, state );
10241 if ( state.scrollTop !== undefined ) {
10242 this.$input.scrollTop( state.scrollTop );
10243 }
10244 };
10245
10246 /**
10247 * @class
10248 * @extends OO.ui.TextInputWidget
10249 *
10250 * @constructor
10251 * @param {Object} [config] Configuration options
10252 */
10253 OO.ui.SearchInputWidget = function OoUiSearchInputWidget( config ) {
10254 config = $.extend( {
10255 icon: 'search'
10256 }, config );
10257
10258 // Set type to text so that TextInputWidget doesn't
10259 // get stuck in an infinite loop.
10260 config.type = 'text';
10261
10262 // Parent constructor
10263 OO.ui.SearchInputWidget.parent.call( this, config );
10264
10265 // Events
10266 this.connect( this, {
10267 change: 'onChange'
10268 } );
10269
10270 // Initialization
10271 this.$element.addClass( 'oo-ui-textInputWidget-type-search' );
10272 this.updateSearchIndicator();
10273 this.connect( this, {
10274 disable: 'onDisable'
10275 } );
10276 };
10277
10278 /* Setup */
10279
10280 OO.inheritClass( OO.ui.SearchInputWidget, OO.ui.TextInputWidget );
10281
10282 /* Methods */
10283
10284 /**
10285 * @inheritdoc
10286 * @protected
10287 */
10288 OO.ui.SearchInputWidget.prototype.getInputElement = function () {
10289 return $( '<input>' ).attr( 'type', 'search' );
10290 };
10291
10292 /**
10293 * @inheritdoc
10294 */
10295 OO.ui.SearchInputWidget.prototype.onIndicatorMouseDown = function ( e ) {
10296 if ( e.which === OO.ui.MouseButtons.LEFT ) {
10297 // Clear the text field
10298 this.setValue( '' );
10299 this.focus();
10300 return false;
10301 }
10302 };
10303
10304 /**
10305 * Update the 'clear' indicator displayed on type: 'search' text
10306 * fields, hiding it when the field is already empty or when it's not
10307 * editable.
10308 */
10309 OO.ui.SearchInputWidget.prototype.updateSearchIndicator = function () {
10310 if ( this.getValue() === '' || this.isDisabled() || this.isReadOnly() ) {
10311 this.setIndicator( null );
10312 } else {
10313 this.setIndicator( 'clear' );
10314 }
10315 };
10316
10317 /**
10318 * Handle change events.
10319 *
10320 * @private
10321 */
10322 OO.ui.SearchInputWidget.prototype.onChange = function () {
10323 this.updateSearchIndicator();
10324 };
10325
10326 /**
10327 * Handle disable events.
10328 *
10329 * @param {boolean} disabled Element is disabled
10330 * @private
10331 */
10332 OO.ui.SearchInputWidget.prototype.onDisable = function () {
10333 this.updateSearchIndicator();
10334 };
10335
10336 /**
10337 * @inheritdoc
10338 */
10339 OO.ui.SearchInputWidget.prototype.setReadOnly = function ( state ) {
10340 OO.ui.SearchInputWidget.parent.prototype.setReadOnly.call( this, state );
10341 this.updateSearchIndicator();
10342 return this;
10343 };
10344
10345 /**
10346 * @class
10347 * @extends OO.ui.TextInputWidget
10348 *
10349 * @constructor
10350 * @param {Object} [config] Configuration options
10351 * @cfg {number} [rows] Number of visible lines in textarea. If used with `autosize`,
10352 * specifies minimum number of rows to display.
10353 * @cfg {string} [labelPosition='after'] The position of the inline label relative to that of
10354 * @cfg {boolean} [autosize=false] Automatically resize the text input to fit its content.
10355 * Use the #maxRows config to specify a maximum number of displayed rows.
10356 * @cfg {boolean} [maxRows] Maximum number of rows to display when #autosize is set to true.
10357 * Defaults to the maximum of `10` and `2 * rows`, or `10` if `rows` isn't provided.
10358 */
10359 OO.ui.MultilineTextInputWidget = function OoUiMultilineTextInputWidget( config ) {
10360 config = $.extend( {
10361 type: 'text'
10362 }, config );
10363 config.multiline = false;
10364 // Parent constructor
10365 OO.ui.MultilineTextInputWidget.parent.call( this, config );
10366
10367 // Properties
10368 this.multiline = true;
10369 this.autosize = !!config.autosize;
10370 this.minRows = config.rows !== undefined ? config.rows : '';
10371 this.maxRows = config.maxRows || Math.max( 2 * ( this.minRows || 0 ), 10 );
10372
10373 // Clone for resizing
10374 if ( this.autosize ) {
10375 this.$clone = this.$input
10376 .clone()
10377 .insertAfter( this.$input )
10378 .attr( 'aria-hidden', 'true' )
10379 .addClass( 'oo-ui-element-hidden' );
10380 }
10381
10382 // Events
10383 this.connect( this, {
10384 change: 'onChange'
10385 } );
10386
10387 // Initialization
10388 if ( this.multiline && config.rows ) {
10389 this.$input.attr( 'rows', config.rows );
10390 }
10391 if ( this.autosize ) {
10392 this.isWaitingToBeAttached = true;
10393 this.installParentChangeDetector();
10394 }
10395 };
10396
10397 /* Setup */
10398
10399 OO.inheritClass( OO.ui.MultilineTextInputWidget, OO.ui.TextInputWidget );
10400
10401 /* Static Methods */
10402
10403 /**
10404 * @inheritdoc
10405 */
10406 OO.ui.MultilineTextInputWidget.static.gatherPreInfuseState = function ( node, config ) {
10407 var state = OO.ui.MultilineTextInputWidget.parent.static.gatherPreInfuseState( node, config );
10408 state.scrollTop = config.$input.scrollTop();
10409 return state;
10410 };
10411
10412 /* Methods */
10413
10414 /**
10415 * @inheritdoc
10416 */
10417 OO.ui.MultilineTextInputWidget.prototype.onElementAttach = function () {
10418 OO.ui.MultilineTextInputWidget.parent.prototype.onElementAttach.call( this );
10419 this.adjustSize();
10420 };
10421
10422 /**
10423 * Handle change events.
10424 *
10425 * @private
10426 */
10427 OO.ui.MultilineTextInputWidget.prototype.onChange = function () {
10428 this.adjustSize();
10429 };
10430
10431 /**
10432 * @inheritdoc
10433 */
10434 OO.ui.MultilineTextInputWidget.prototype.updatePosition = function () {
10435 OO.ui.MultilineTextInputWidget.parent.prototype.updatePosition.call( this );
10436 this.adjustSize();
10437 };
10438
10439 /**
10440 * Override TextInputWidget so it doesn't emit the 'enter' event.
10441 *
10442 * @private
10443 * @param {jQuery.Event} e Key press event
10444 */
10445 OO.ui.MultilineTextInputWidget.prototype.onKeyPress = function () {
10446 return;
10447 };
10448
10449 /**
10450 * Automatically adjust the size of the text input.
10451 *
10452 * This only affects multiline inputs that are {@link #autosize autosized}.
10453 *
10454 * @chainable
10455 * @fires resize
10456 */
10457 OO.ui.MultilineTextInputWidget.prototype.adjustSize = function () {
10458 var scrollHeight, innerHeight, outerHeight, maxInnerHeight, measurementError,
10459 idealHeight, newHeight, scrollWidth, property;
10460
10461 if ( this.$input.val() !== this.valCache ) {
10462 if ( this.autosize ) {
10463 this.$clone
10464 .val( this.$input.val() )
10465 .attr( 'rows', this.minRows )
10466 // Set inline height property to 0 to measure scroll height
10467 .css( 'height', 0 );
10468
10469 this.$clone.removeClass( 'oo-ui-element-hidden' );
10470
10471 this.valCache = this.$input.val();
10472
10473 scrollHeight = this.$clone[ 0 ].scrollHeight;
10474
10475 // Remove inline height property to measure natural heights
10476 this.$clone.css( 'height', '' );
10477 innerHeight = this.$clone.innerHeight();
10478 outerHeight = this.$clone.outerHeight();
10479
10480 // Measure max rows height
10481 this.$clone
10482 .attr( 'rows', this.maxRows )
10483 .css( 'height', 'auto' )
10484 .val( '' );
10485 maxInnerHeight = this.$clone.innerHeight();
10486
10487 // Difference between reported innerHeight and scrollHeight with no scrollbars present.
10488 // This is sometimes non-zero on Blink-based browsers, depending on zoom level.
10489 measurementError = maxInnerHeight - this.$clone[ 0 ].scrollHeight;
10490 idealHeight = Math.min( maxInnerHeight, scrollHeight + measurementError );
10491
10492 this.$clone.addClass( 'oo-ui-element-hidden' );
10493
10494 // Only apply inline height when expansion beyond natural height is needed
10495 // Use the difference between the inner and outer height as a buffer
10496 newHeight = idealHeight > innerHeight ? idealHeight + ( outerHeight - innerHeight ) : '';
10497 if ( newHeight !== this.styleHeight ) {
10498 this.$input.css( 'height', newHeight );
10499 this.styleHeight = newHeight;
10500 this.emit( 'resize' );
10501 }
10502 }
10503 scrollWidth = this.$input[ 0 ].offsetWidth - this.$input[ 0 ].clientWidth;
10504 if ( scrollWidth !== this.scrollWidth ) {
10505 property = this.$element.css( 'direction' ) === 'rtl' ? 'left' : 'right';
10506 // Reset
10507 this.$label.css( { right: '', left: '' } );
10508 this.$indicator.css( { right: '', left: '' } );
10509
10510 if ( scrollWidth ) {
10511 this.$indicator.css( property, scrollWidth );
10512 if ( this.labelPosition === 'after' ) {
10513 this.$label.css( property, scrollWidth );
10514 }
10515 }
10516
10517 this.scrollWidth = scrollWidth;
10518 this.positionLabel();
10519 }
10520 }
10521 return this;
10522 };
10523
10524 /**
10525 * @inheritdoc
10526 * @protected
10527 */
10528 OO.ui.MultilineTextInputWidget.prototype.getInputElement = function () {
10529 return $( '<textarea>' );
10530 };
10531
10532 /**
10533 * Check if the input supports multiple lines.
10534 *
10535 * @return {boolean}
10536 */
10537 OO.ui.MultilineTextInputWidget.prototype.isMultiline = function () {
10538 return !!this.multiline;
10539 };
10540
10541 /**
10542 * Check if the input automatically adjusts its size.
10543 *
10544 * @return {boolean}
10545 */
10546 OO.ui.MultilineTextInputWidget.prototype.isAutosizing = function () {
10547 return !!this.autosize;
10548 };
10549
10550 /**
10551 * ComboBoxInputWidgets combine a {@link OO.ui.TextInputWidget text input} (where a value
10552 * can be entered manually) and a {@link OO.ui.MenuSelectWidget menu of options} (from which
10553 * a value can be chosen instead). Users can choose options from the combo box in one of two ways:
10554 *
10555 * - by typing a value in the text input field. If the value exactly matches the value of a menu
10556 * option, that option will appear to be selected.
10557 * - by choosing a value from the menu. The value of the chosen option will then appear in the text
10558 * input field.
10559 *
10560 * After the user chooses an option, its `data` will be used as a new value for the widget.
10561 * A `label` also can be specified for each option: if given, it will be shown instead of the
10562 * `data` in the dropdown menu.
10563 *
10564 * This widget can be used inside an HTML form, such as a OO.ui.FormLayout.
10565 *
10566 * For more information about menus and options, please see the [OOjs UI documentation on MediaWiki][1].
10567 *
10568 * @example
10569 * // Example: A ComboBoxInputWidget.
10570 * var comboBox = new OO.ui.ComboBoxInputWidget( {
10571 * value: 'Option 1',
10572 * options: [
10573 * { data: 'Option 1' },
10574 * { data: 'Option 2' },
10575 * { data: 'Option 3' }
10576 * ]
10577 * } );
10578 * $( 'body' ).append( comboBox.$element );
10579 *
10580 * @example
10581 * // Example: A ComboBoxInputWidget with additional option labels.
10582 * var comboBox = new OO.ui.ComboBoxInputWidget( {
10583 * value: 'Option 1',
10584 * options: [
10585 * {
10586 * data: 'Option 1',
10587 * label: 'Option One'
10588 * },
10589 * {
10590 * data: 'Option 2',
10591 * label: 'Option Two'
10592 * },
10593 * {
10594 * data: 'Option 3',
10595 * label: 'Option Three'
10596 * }
10597 * ]
10598 * } );
10599 * $( 'body' ).append( comboBox.$element );
10600 *
10601 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
10602 *
10603 * @class
10604 * @extends OO.ui.TextInputWidget
10605 *
10606 * @constructor
10607 * @param {Object} [config] Configuration options
10608 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
10609 * @cfg {Object} [menu] Configuration options to pass to the {@link OO.ui.MenuSelectWidget menu select widget}.
10610 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
10611 * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
10612 * containing `<div>` and has a larger area. By default, the menu uses relative positioning.
10613 * See <https://www.mediawiki.org/wiki/OOjs_UI/Concepts#Overlays>.
10614 */
10615 OO.ui.ComboBoxInputWidget = function OoUiComboBoxInputWidget( config ) {
10616 // Configuration initialization
10617 config = $.extend( {
10618 autocomplete: false
10619 }, config );
10620
10621 // ComboBoxInputWidget shouldn't support `multiline`
10622 config.multiline = false;
10623
10624 // See InputWidget#reusePreInfuseDOM about `config.$input`
10625 if ( config.$input ) {
10626 config.$input.removeAttr( 'list' );
10627 }
10628
10629 // Parent constructor
10630 OO.ui.ComboBoxInputWidget.parent.call( this, config );
10631
10632 // Properties
10633 this.$overlay = config.$overlay || this.$element;
10634 this.dropdownButton = new OO.ui.ButtonWidget( {
10635 classes: [ 'oo-ui-comboBoxInputWidget-dropdownButton' ],
10636 indicator: 'down',
10637 disabled: this.disabled
10638 } );
10639 this.menu = new OO.ui.MenuSelectWidget( $.extend(
10640 {
10641 widget: this,
10642 input: this,
10643 $floatableContainer: this.$element,
10644 disabled: this.isDisabled()
10645 },
10646 config.menu
10647 ) );
10648
10649 // Events
10650 this.connect( this, {
10651 change: 'onInputChange',
10652 enter: 'onInputEnter'
10653 } );
10654 this.dropdownButton.connect( this, {
10655 click: 'onDropdownButtonClick'
10656 } );
10657 this.menu.connect( this, {
10658 choose: 'onMenuChoose',
10659 add: 'onMenuItemsChange',
10660 remove: 'onMenuItemsChange'
10661 } );
10662
10663 // Initialization
10664 this.$input.attr( {
10665 role: 'combobox',
10666 'aria-owns': this.menu.getElementId(),
10667 'aria-autocomplete': 'list'
10668 } );
10669 // Do not override options set via config.menu.items
10670 if ( config.options !== undefined ) {
10671 this.setOptions( config.options );
10672 }
10673 this.$field = $( '<div>' )
10674 .addClass( 'oo-ui-comboBoxInputWidget-field' )
10675 .append( this.$input, this.dropdownButton.$element );
10676 this.$element
10677 .addClass( 'oo-ui-comboBoxInputWidget' )
10678 .append( this.$field );
10679 this.$overlay.append( this.menu.$element );
10680 this.onMenuItemsChange();
10681 };
10682
10683 /* Setup */
10684
10685 OO.inheritClass( OO.ui.ComboBoxInputWidget, OO.ui.TextInputWidget );
10686
10687 /* Methods */
10688
10689 /**
10690 * Get the combobox's menu.
10691 *
10692 * @return {OO.ui.MenuSelectWidget} Menu widget
10693 */
10694 OO.ui.ComboBoxInputWidget.prototype.getMenu = function () {
10695 return this.menu;
10696 };
10697
10698 /**
10699 * Get the combobox's text input widget.
10700 *
10701 * @return {OO.ui.TextInputWidget} Text input widget
10702 */
10703 OO.ui.ComboBoxInputWidget.prototype.getInput = function () {
10704 return this;
10705 };
10706
10707 /**
10708 * Handle input change events.
10709 *
10710 * @private
10711 * @param {string} value New value
10712 */
10713 OO.ui.ComboBoxInputWidget.prototype.onInputChange = function ( value ) {
10714 var match = this.menu.getItemFromData( value );
10715
10716 this.menu.selectItem( match );
10717 if ( this.menu.getHighlightedItem() ) {
10718 this.menu.highlightItem( match );
10719 }
10720
10721 if ( !this.isDisabled() ) {
10722 this.menu.toggle( true );
10723 }
10724 };
10725
10726 /**
10727 * Handle input enter events.
10728 *
10729 * @private
10730 */
10731 OO.ui.ComboBoxInputWidget.prototype.onInputEnter = function () {
10732 if ( !this.isDisabled() ) {
10733 this.menu.toggle( false );
10734 }
10735 };
10736
10737 /**
10738 * Handle button click events.
10739 *
10740 * @private
10741 */
10742 OO.ui.ComboBoxInputWidget.prototype.onDropdownButtonClick = function () {
10743 this.menu.toggle();
10744 this.focus();
10745 };
10746
10747 /**
10748 * Handle menu choose events.
10749 *
10750 * @private
10751 * @param {OO.ui.OptionWidget} item Chosen item
10752 */
10753 OO.ui.ComboBoxInputWidget.prototype.onMenuChoose = function ( item ) {
10754 this.setValue( item.getData() );
10755 };
10756
10757 /**
10758 * Handle menu item change events.
10759 *
10760 * @private
10761 */
10762 OO.ui.ComboBoxInputWidget.prototype.onMenuItemsChange = function () {
10763 var match = this.menu.getItemFromData( this.getValue() );
10764 this.menu.selectItem( match );
10765 if ( this.menu.getHighlightedItem() ) {
10766 this.menu.highlightItem( match );
10767 }
10768 this.$element.toggleClass( 'oo-ui-comboBoxInputWidget-empty', this.menu.isEmpty() );
10769 };
10770
10771 /**
10772 * @inheritdoc
10773 */
10774 OO.ui.ComboBoxInputWidget.prototype.setDisabled = function ( disabled ) {
10775 // Parent method
10776 OO.ui.ComboBoxInputWidget.parent.prototype.setDisabled.call( this, disabled );
10777
10778 if ( this.dropdownButton ) {
10779 this.dropdownButton.setDisabled( this.isDisabled() );
10780 }
10781 if ( this.menu ) {
10782 this.menu.setDisabled( this.isDisabled() );
10783 }
10784
10785 return this;
10786 };
10787
10788 /**
10789 * Set the options available for this input.
10790 *
10791 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
10792 * @chainable
10793 */
10794 OO.ui.ComboBoxInputWidget.prototype.setOptions = function ( options ) {
10795 this.getMenu()
10796 .clearItems()
10797 .addItems( options.map( function ( opt ) {
10798 return new OO.ui.MenuOptionWidget( {
10799 data: opt.data,
10800 label: opt.label !== undefined ? opt.label : opt.data
10801 } );
10802 } ) );
10803
10804 return this;
10805 };
10806
10807 /**
10808 * FieldLayouts are used with OO.ui.FieldsetLayout. Each FieldLayout requires a field-widget,
10809 * which is a widget that is specified by reference before any optional configuration settings.
10810 *
10811 * Field layouts can be configured with help text and/or labels. Labels are aligned in one of four ways:
10812 *
10813 * - **left**: The label is placed before the field-widget and aligned with the left margin.
10814 * A left-alignment is used for forms with many fields.
10815 * - **right**: The label is placed before the field-widget and aligned to the right margin.
10816 * A right-alignment is used for long but familiar forms which users tab through,
10817 * verifying the current field with a quick glance at the label.
10818 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
10819 * that users fill out from top to bottom.
10820 * - **inline**: The label is placed after the field-widget and aligned to the left.
10821 * An inline-alignment is best used with checkboxes or radio buttons.
10822 *
10823 * Help text is accessed via a help icon that appears in the upper right corner of the rendered field layout.
10824 * Please see the [OOjs UI documentation on MediaWiki] [1] for examples and more information.
10825 *
10826 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Fields_and_Fieldsets
10827 *
10828 * @class
10829 * @extends OO.ui.Layout
10830 * @mixins OO.ui.mixin.LabelElement
10831 * @mixins OO.ui.mixin.TitledElement
10832 *
10833 * @constructor
10834 * @param {OO.ui.Widget} fieldWidget Field widget
10835 * @param {Object} [config] Configuration options
10836 * @cfg {string} [align='left'] Alignment of the label: 'left', 'right', 'top' or 'inline'
10837 * @cfg {Array} [errors] Error messages about the widget, which will be displayed below the widget.
10838 * The array may contain strings or OO.ui.HtmlSnippet instances.
10839 * @cfg {Array} [notices] Notices about the widget, which will be displayed below the widget.
10840 * The array may contain strings or OO.ui.HtmlSnippet instances.
10841 * @cfg {string|OO.ui.HtmlSnippet} [help] Help text. When help text is specified, a "help" icon will appear
10842 * in the upper-right corner of the rendered field; clicking it will display the text in a popup.
10843 * For important messages, you are advised to use `notices`, as they are always shown.
10844 * @cfg {jQuery} [$overlay] Passed to OO.ui.PopupButtonWidget for help popup, if `help` is given.
10845 * See <https://www.mediawiki.org/wiki/OOjs_UI/Concepts#Overlays>.
10846 *
10847 * @throws {Error} An error is thrown if no widget is specified
10848 */
10849 OO.ui.FieldLayout = function OoUiFieldLayout( fieldWidget, config ) {
10850 // Allow passing positional parameters inside the config object
10851 if ( OO.isPlainObject( fieldWidget ) && config === undefined ) {
10852 config = fieldWidget;
10853 fieldWidget = config.fieldWidget;
10854 }
10855
10856 // Make sure we have required constructor arguments
10857 if ( fieldWidget === undefined ) {
10858 throw new Error( 'Widget not found' );
10859 }
10860
10861 // Configuration initialization
10862 config = $.extend( { align: 'left' }, config );
10863
10864 // Parent constructor
10865 OO.ui.FieldLayout.parent.call( this, config );
10866
10867 // Mixin constructors
10868 OO.ui.mixin.LabelElement.call( this, $.extend( {}, config, {
10869 $label: $( '<label>' )
10870 } ) );
10871 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$label } ) );
10872
10873 // Properties
10874 this.fieldWidget = fieldWidget;
10875 this.errors = [];
10876 this.notices = [];
10877 this.$field = this.isFieldInline() ? $( '<span>' ) : $( '<div>' );
10878 this.$messages = $( '<ul>' );
10879 this.$header = $( '<span>' );
10880 this.$body = $( '<div>' );
10881 this.align = null;
10882 if ( config.help ) {
10883 this.popupButtonWidget = new OO.ui.PopupButtonWidget( {
10884 $overlay: config.$overlay,
10885 popup: {
10886 padded: true
10887 },
10888 classes: [ 'oo-ui-fieldLayout-help' ],
10889 framed: false,
10890 icon: 'info'
10891 } );
10892 if ( config.help instanceof OO.ui.HtmlSnippet ) {
10893 this.popupButtonWidget.getPopup().$body.html( config.help.toString() );
10894 } else {
10895 this.popupButtonWidget.getPopup().$body.text( config.help );
10896 }
10897 this.$help = this.popupButtonWidget.$element;
10898 } else {
10899 this.$help = $( [] );
10900 }
10901
10902 // Events
10903 this.fieldWidget.connect( this, { disable: 'onFieldDisable' } );
10904
10905 // Initialization
10906 if ( config.help ) {
10907 // Set the 'aria-describedby' attribute on the fieldWidget
10908 // Preference given to an input or a button
10909 (
10910 this.fieldWidget.$input ||
10911 this.fieldWidget.$button ||
10912 this.fieldWidget.$element
10913 ).attr(
10914 'aria-describedby',
10915 this.popupButtonWidget.getPopup().getBodyId()
10916 );
10917 }
10918 if ( this.fieldWidget.getInputId() ) {
10919 this.$label.attr( 'for', this.fieldWidget.getInputId() );
10920 } else {
10921 this.$label.on( 'click', function () {
10922 this.fieldWidget.simulateLabelClick();
10923 return false;
10924 }.bind( this ) );
10925 }
10926 this.$element
10927 .addClass( 'oo-ui-fieldLayout' )
10928 .toggleClass( 'oo-ui-fieldLayout-disabled', this.fieldWidget.isDisabled() )
10929 .append( this.$body );
10930 this.$body.addClass( 'oo-ui-fieldLayout-body' );
10931 this.$header.addClass( 'oo-ui-fieldLayout-header' );
10932 this.$messages.addClass( 'oo-ui-fieldLayout-messages' );
10933 this.$field
10934 .addClass( 'oo-ui-fieldLayout-field' )
10935 .append( this.fieldWidget.$element );
10936
10937 this.setErrors( config.errors || [] );
10938 this.setNotices( config.notices || [] );
10939 this.setAlignment( config.align );
10940 // Call this again to take into account the widget's accessKey
10941 this.updateTitle();
10942 };
10943
10944 /* Setup */
10945
10946 OO.inheritClass( OO.ui.FieldLayout, OO.ui.Layout );
10947 OO.mixinClass( OO.ui.FieldLayout, OO.ui.mixin.LabelElement );
10948 OO.mixinClass( OO.ui.FieldLayout, OO.ui.mixin.TitledElement );
10949
10950 /* Methods */
10951
10952 /**
10953 * Handle field disable events.
10954 *
10955 * @private
10956 * @param {boolean} value Field is disabled
10957 */
10958 OO.ui.FieldLayout.prototype.onFieldDisable = function ( value ) {
10959 this.$element.toggleClass( 'oo-ui-fieldLayout-disabled', value );
10960 };
10961
10962 /**
10963 * Get the widget contained by the field.
10964 *
10965 * @return {OO.ui.Widget} Field widget
10966 */
10967 OO.ui.FieldLayout.prototype.getField = function () {
10968 return this.fieldWidget;
10969 };
10970
10971 /**
10972 * Return `true` if the given field widget can be used with `'inline'` alignment (see
10973 * #setAlignment). Return `false` if it can't or if this can't be determined.
10974 *
10975 * @return {boolean}
10976 */
10977 OO.ui.FieldLayout.prototype.isFieldInline = function () {
10978 // This is very simplistic, but should be good enough.
10979 return this.getField().$element.prop( 'tagName' ).toLowerCase() === 'span';
10980 };
10981
10982 /**
10983 * @protected
10984 * @param {string} kind 'error' or 'notice'
10985 * @param {string|OO.ui.HtmlSnippet} text
10986 * @return {jQuery}
10987 */
10988 OO.ui.FieldLayout.prototype.makeMessage = function ( kind, text ) {
10989 var $listItem, $icon, message;
10990 $listItem = $( '<li>' );
10991 if ( kind === 'error' ) {
10992 $icon = new OO.ui.IconWidget( { icon: 'alert', flags: [ 'warning' ] } ).$element;
10993 $listItem.attr( 'role', 'alert' );
10994 } else if ( kind === 'notice' ) {
10995 $icon = new OO.ui.IconWidget( { icon: 'info' } ).$element;
10996 } else {
10997 $icon = '';
10998 }
10999 message = new OO.ui.LabelWidget( { label: text } );
11000 $listItem
11001 .append( $icon, message.$element )
11002 .addClass( 'oo-ui-fieldLayout-messages-' + kind );
11003 return $listItem;
11004 };
11005
11006 /**
11007 * Set the field alignment mode.
11008 *
11009 * @private
11010 * @param {string} value Alignment mode, either 'left', 'right', 'top' or 'inline'
11011 * @chainable
11012 */
11013 OO.ui.FieldLayout.prototype.setAlignment = function ( value ) {
11014 if ( value !== this.align ) {
11015 // Default to 'left'
11016 if ( [ 'left', 'right', 'top', 'inline' ].indexOf( value ) === -1 ) {
11017 value = 'left';
11018 }
11019 // Validate
11020 if ( value === 'inline' && !this.isFieldInline() ) {
11021 value = 'top';
11022 }
11023 // Reorder elements
11024 if ( value === 'top' ) {
11025 this.$header.append( this.$label, this.$help );
11026 this.$body.append( this.$header, this.$field );
11027 } else if ( value === 'inline' ) {
11028 this.$header.append( this.$label, this.$help );
11029 this.$body.append( this.$field, this.$header );
11030 } else {
11031 this.$header.append( this.$label );
11032 this.$body.append( this.$header, this.$help, this.$field );
11033 }
11034 // Set classes. The following classes can be used here:
11035 // * oo-ui-fieldLayout-align-left
11036 // * oo-ui-fieldLayout-align-right
11037 // * oo-ui-fieldLayout-align-top
11038 // * oo-ui-fieldLayout-align-inline
11039 if ( this.align ) {
11040 this.$element.removeClass( 'oo-ui-fieldLayout-align-' + this.align );
11041 }
11042 this.$element.addClass( 'oo-ui-fieldLayout-align-' + value );
11043 this.align = value;
11044 }
11045
11046 return this;
11047 };
11048
11049 /**
11050 * Set the list of error messages.
11051 *
11052 * @param {Array} errors Error messages about the widget, which will be displayed below the widget.
11053 * The array may contain strings or OO.ui.HtmlSnippet instances.
11054 * @chainable
11055 */
11056 OO.ui.FieldLayout.prototype.setErrors = function ( errors ) {
11057 this.errors = errors.slice();
11058 this.updateMessages();
11059 return this;
11060 };
11061
11062 /**
11063 * Set the list of notice messages.
11064 *
11065 * @param {Array} notices Notices about the widget, which will be displayed below the widget.
11066 * The array may contain strings or OO.ui.HtmlSnippet instances.
11067 * @chainable
11068 */
11069 OO.ui.FieldLayout.prototype.setNotices = function ( notices ) {
11070 this.notices = notices.slice();
11071 this.updateMessages();
11072 return this;
11073 };
11074
11075 /**
11076 * Update the rendering of error and notice messages.
11077 *
11078 * @private
11079 */
11080 OO.ui.FieldLayout.prototype.updateMessages = function () {
11081 var i;
11082 this.$messages.empty();
11083
11084 if ( this.errors.length || this.notices.length ) {
11085 this.$body.after( this.$messages );
11086 } else {
11087 this.$messages.remove();
11088 return;
11089 }
11090
11091 for ( i = 0; i < this.notices.length; i++ ) {
11092 this.$messages.append( this.makeMessage( 'notice', this.notices[ i ] ) );
11093 }
11094 for ( i = 0; i < this.errors.length; i++ ) {
11095 this.$messages.append( this.makeMessage( 'error', this.errors[ i ] ) );
11096 }
11097 };
11098
11099 /**
11100 * Include information about the widget's accessKey in our title. TitledElement calls this method.
11101 * (This is a bit of a hack.)
11102 *
11103 * @protected
11104 * @param {string} title Tooltip label for 'title' attribute
11105 * @return {string}
11106 */
11107 OO.ui.FieldLayout.prototype.formatTitleWithAccessKey = function ( title ) {
11108 if ( this.fieldWidget && this.fieldWidget.formatTitleWithAccessKey ) {
11109 return this.fieldWidget.formatTitleWithAccessKey( title );
11110 }
11111 return title;
11112 };
11113
11114 /**
11115 * ActionFieldLayouts are used with OO.ui.FieldsetLayout. The layout consists of a field-widget, a button,
11116 * and an optional label and/or help text. The field-widget (e.g., a {@link OO.ui.TextInputWidget TextInputWidget}),
11117 * is required and is specified before any optional configuration settings.
11118 *
11119 * Labels can be aligned in one of four ways:
11120 *
11121 * - **left**: The label is placed before the field-widget and aligned with the left margin.
11122 * A left-alignment is used for forms with many fields.
11123 * - **right**: The label is placed before the field-widget and aligned to the right margin.
11124 * A right-alignment is used for long but familiar forms which users tab through,
11125 * verifying the current field with a quick glance at the label.
11126 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
11127 * that users fill out from top to bottom.
11128 * - **inline**: The label is placed after the field-widget and aligned to the left.
11129 * An inline-alignment is best used with checkboxes or radio buttons.
11130 *
11131 * Help text is accessed via a help icon that appears in the upper right corner of the rendered field layout when help
11132 * text is specified.
11133 *
11134 * @example
11135 * // Example of an ActionFieldLayout
11136 * var actionFieldLayout = new OO.ui.ActionFieldLayout(
11137 * new OO.ui.TextInputWidget( {
11138 * placeholder: 'Field widget'
11139 * } ),
11140 * new OO.ui.ButtonWidget( {
11141 * label: 'Button'
11142 * } ),
11143 * {
11144 * label: 'An ActionFieldLayout. This label is aligned top',
11145 * align: 'top',
11146 * help: 'This is help text'
11147 * }
11148 * );
11149 *
11150 * $( 'body' ).append( actionFieldLayout.$element );
11151 *
11152 * @class
11153 * @extends OO.ui.FieldLayout
11154 *
11155 * @constructor
11156 * @param {OO.ui.Widget} fieldWidget Field widget
11157 * @param {OO.ui.ButtonWidget} buttonWidget Button widget
11158 * @param {Object} config
11159 */
11160 OO.ui.ActionFieldLayout = function OoUiActionFieldLayout( fieldWidget, buttonWidget, config ) {
11161 // Allow passing positional parameters inside the config object
11162 if ( OO.isPlainObject( fieldWidget ) && config === undefined ) {
11163 config = fieldWidget;
11164 fieldWidget = config.fieldWidget;
11165 buttonWidget = config.buttonWidget;
11166 }
11167
11168 // Parent constructor
11169 OO.ui.ActionFieldLayout.parent.call( this, fieldWidget, config );
11170
11171 // Properties
11172 this.buttonWidget = buttonWidget;
11173 this.$button = $( '<span>' );
11174 this.$input = this.isFieldInline() ? $( '<span>' ) : $( '<div>' );
11175
11176 // Initialization
11177 this.$element
11178 .addClass( 'oo-ui-actionFieldLayout' );
11179 this.$button
11180 .addClass( 'oo-ui-actionFieldLayout-button' )
11181 .append( this.buttonWidget.$element );
11182 this.$input
11183 .addClass( 'oo-ui-actionFieldLayout-input' )
11184 .append( this.fieldWidget.$element );
11185 this.$field
11186 .append( this.$input, this.$button );
11187 };
11188
11189 /* Setup */
11190
11191 OO.inheritClass( OO.ui.ActionFieldLayout, OO.ui.FieldLayout );
11192
11193 /**
11194 * FieldsetLayouts are composed of one or more {@link OO.ui.FieldLayout FieldLayouts},
11195 * which each contain an individual widget and, optionally, a label. Each Fieldset can be
11196 * configured with a label as well. For more information and examples,
11197 * please see the [OOjs UI documentation on MediaWiki][1].
11198 *
11199 * @example
11200 * // Example of a fieldset layout
11201 * var input1 = new OO.ui.TextInputWidget( {
11202 * placeholder: 'A text input field'
11203 * } );
11204 *
11205 * var input2 = new OO.ui.TextInputWidget( {
11206 * placeholder: 'A text input field'
11207 * } );
11208 *
11209 * var fieldset = new OO.ui.FieldsetLayout( {
11210 * label: 'Example of a fieldset layout'
11211 * } );
11212 *
11213 * fieldset.addItems( [
11214 * new OO.ui.FieldLayout( input1, {
11215 * label: 'Field One'
11216 * } ),
11217 * new OO.ui.FieldLayout( input2, {
11218 * label: 'Field Two'
11219 * } )
11220 * ] );
11221 * $( 'body' ).append( fieldset.$element );
11222 *
11223 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Fields_and_Fieldsets
11224 *
11225 * @class
11226 * @extends OO.ui.Layout
11227 * @mixins OO.ui.mixin.IconElement
11228 * @mixins OO.ui.mixin.LabelElement
11229 * @mixins OO.ui.mixin.GroupElement
11230 *
11231 * @constructor
11232 * @param {Object} [config] Configuration options
11233 * @cfg {OO.ui.FieldLayout[]} [items] An array of fields to add to the fieldset. See OO.ui.FieldLayout for more information about fields.
11234 * @cfg {string|OO.ui.HtmlSnippet} [help] Help text. When help text is specified, a "help" icon will appear
11235 * in the upper-right corner of the rendered field; clicking it will display the text in a popup.
11236 * For important messages, you are advised to use `notices`, as they are always shown.
11237 * @cfg {jQuery} [$overlay] Passed to OO.ui.PopupButtonWidget for help popup, if `help` is given.
11238 * See <https://www.mediawiki.org/wiki/OOjs_UI/Concepts#Overlays>.
11239 */
11240 OO.ui.FieldsetLayout = function OoUiFieldsetLayout( config ) {
11241 // Configuration initialization
11242 config = config || {};
11243
11244 // Parent constructor
11245 OO.ui.FieldsetLayout.parent.call( this, config );
11246
11247 // Mixin constructors
11248 OO.ui.mixin.IconElement.call( this, config );
11249 OO.ui.mixin.LabelElement.call( this, config );
11250 OO.ui.mixin.GroupElement.call( this, config );
11251
11252 // Properties
11253 this.$header = $( '<legend>' );
11254 if ( config.help ) {
11255 this.popupButtonWidget = new OO.ui.PopupButtonWidget( {
11256 $overlay: config.$overlay,
11257 popup: {
11258 padded: true
11259 },
11260 classes: [ 'oo-ui-fieldsetLayout-help' ],
11261 framed: false,
11262 icon: 'info'
11263 } );
11264 if ( config.help instanceof OO.ui.HtmlSnippet ) {
11265 this.popupButtonWidget.getPopup().$body.html( config.help.toString() );
11266 } else {
11267 this.popupButtonWidget.getPopup().$body.text( config.help );
11268 }
11269 this.$help = this.popupButtonWidget.$element;
11270 } else {
11271 this.$help = $( [] );
11272 }
11273
11274 // Initialization
11275 this.$header
11276 .addClass( 'oo-ui-fieldsetLayout-header' )
11277 .append( this.$icon, this.$label, this.$help );
11278 this.$group.addClass( 'oo-ui-fieldsetLayout-group' );
11279 this.$element
11280 .addClass( 'oo-ui-fieldsetLayout' )
11281 .prepend( this.$header, this.$group );
11282 if ( Array.isArray( config.items ) ) {
11283 this.addItems( config.items );
11284 }
11285 };
11286
11287 /* Setup */
11288
11289 OO.inheritClass( OO.ui.FieldsetLayout, OO.ui.Layout );
11290 OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.mixin.IconElement );
11291 OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.mixin.LabelElement );
11292 OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.mixin.GroupElement );
11293
11294 /* Static Properties */
11295
11296 /**
11297 * @static
11298 * @inheritdoc
11299 */
11300 OO.ui.FieldsetLayout.static.tagName = 'fieldset';
11301
11302 /**
11303 * FormLayouts are used to wrap {@link OO.ui.FieldsetLayout FieldsetLayouts} when you intend to use browser-based
11304 * form submission for the fields instead of handling them in JavaScript. Form layouts can be configured with an
11305 * HTML form action, an encoding type, and a method using the #action, #enctype, and #method configs, respectively.
11306 * See the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
11307 *
11308 * Only widgets from the {@link OO.ui.InputWidget InputWidget} family support form submission. It
11309 * includes standard form elements like {@link OO.ui.CheckboxInputWidget checkboxes}, {@link
11310 * OO.ui.RadioInputWidget radio buttons} and {@link OO.ui.TextInputWidget text fields}, as well as
11311 * some fancier controls. Some controls have both regular and InputWidget variants, for example
11312 * OO.ui.DropdownWidget and OO.ui.DropdownInputWidget – only the latter support form submission and
11313 * often have simplified APIs to match the capabilities of HTML forms.
11314 * See the [OOjs UI Inputs documentation on MediaWiki] [2] for more information about InputWidgets.
11315 *
11316 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Forms
11317 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
11318 *
11319 * @example
11320 * // Example of a form layout that wraps a fieldset layout
11321 * var input1 = new OO.ui.TextInputWidget( {
11322 * placeholder: 'Username'
11323 * } );
11324 * var input2 = new OO.ui.TextInputWidget( {
11325 * placeholder: 'Password',
11326 * type: 'password'
11327 * } );
11328 * var submit = new OO.ui.ButtonInputWidget( {
11329 * label: 'Submit'
11330 * } );
11331 *
11332 * var fieldset = new OO.ui.FieldsetLayout( {
11333 * label: 'A form layout'
11334 * } );
11335 * fieldset.addItems( [
11336 * new OO.ui.FieldLayout( input1, {
11337 * label: 'Username',
11338 * align: 'top'
11339 * } ),
11340 * new OO.ui.FieldLayout( input2, {
11341 * label: 'Password',
11342 * align: 'top'
11343 * } ),
11344 * new OO.ui.FieldLayout( submit )
11345 * ] );
11346 * var form = new OO.ui.FormLayout( {
11347 * items: [ fieldset ],
11348 * action: '/api/formhandler',
11349 * method: 'get'
11350 * } )
11351 * $( 'body' ).append( form.$element );
11352 *
11353 * @class
11354 * @extends OO.ui.Layout
11355 * @mixins OO.ui.mixin.GroupElement
11356 *
11357 * @constructor
11358 * @param {Object} [config] Configuration options
11359 * @cfg {string} [method] HTML form `method` attribute
11360 * @cfg {string} [action] HTML form `action` attribute
11361 * @cfg {string} [enctype] HTML form `enctype` attribute
11362 * @cfg {OO.ui.FieldsetLayout[]} [items] Fieldset layouts to add to the form layout.
11363 */
11364 OO.ui.FormLayout = function OoUiFormLayout( config ) {
11365 var action;
11366
11367 // Configuration initialization
11368 config = config || {};
11369
11370 // Parent constructor
11371 OO.ui.FormLayout.parent.call( this, config );
11372
11373 // Mixin constructors
11374 OO.ui.mixin.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) );
11375
11376 // Events
11377 this.$element.on( 'submit', this.onFormSubmit.bind( this ) );
11378
11379 // Make sure the action is safe
11380 action = config.action;
11381 if ( action !== undefined && !OO.ui.isSafeUrl( action ) ) {
11382 action = './' + action;
11383 }
11384
11385 // Initialization
11386 this.$element
11387 .addClass( 'oo-ui-formLayout' )
11388 .attr( {
11389 method: config.method,
11390 action: action,
11391 enctype: config.enctype
11392 } );
11393 if ( Array.isArray( config.items ) ) {
11394 this.addItems( config.items );
11395 }
11396 };
11397
11398 /* Setup */
11399
11400 OO.inheritClass( OO.ui.FormLayout, OO.ui.Layout );
11401 OO.mixinClass( OO.ui.FormLayout, OO.ui.mixin.GroupElement );
11402
11403 /* Events */
11404
11405 /**
11406 * A 'submit' event is emitted when the form is submitted.
11407 *
11408 * @event submit
11409 */
11410
11411 /* Static Properties */
11412
11413 /**
11414 * @static
11415 * @inheritdoc
11416 */
11417 OO.ui.FormLayout.static.tagName = 'form';
11418
11419 /* Methods */
11420
11421 /**
11422 * Handle form submit events.
11423 *
11424 * @private
11425 * @param {jQuery.Event} e Submit event
11426 * @fires submit
11427 */
11428 OO.ui.FormLayout.prototype.onFormSubmit = function () {
11429 if ( this.emit( 'submit' ) ) {
11430 return false;
11431 }
11432 };
11433
11434 /**
11435 * PanelLayouts expand to cover the entire area of their parent. They can be configured with scrolling, padding,
11436 * and a frame, and are often used together with {@link OO.ui.StackLayout StackLayouts}.
11437 *
11438 * @example
11439 * // Example of a panel layout
11440 * var panel = new OO.ui.PanelLayout( {
11441 * expanded: false,
11442 * framed: true,
11443 * padded: true,
11444 * $content: $( '<p>A panel layout with padding and a frame.</p>' )
11445 * } );
11446 * $( 'body' ).append( panel.$element );
11447 *
11448 * @class
11449 * @extends OO.ui.Layout
11450 *
11451 * @constructor
11452 * @param {Object} [config] Configuration options
11453 * @cfg {boolean} [scrollable=false] Allow vertical scrolling
11454 * @cfg {boolean} [padded=false] Add padding between the content and the edges of the panel.
11455 * @cfg {boolean} [expanded=true] Expand the panel to fill the entire parent element.
11456 * @cfg {boolean} [framed=false] Render the panel with a frame to visually separate it from outside content.
11457 */
11458 OO.ui.PanelLayout = function OoUiPanelLayout( config ) {
11459 // Configuration initialization
11460 config = $.extend( {
11461 scrollable: false,
11462 padded: false,
11463 expanded: true,
11464 framed: false
11465 }, config );
11466
11467 // Parent constructor
11468 OO.ui.PanelLayout.parent.call( this, config );
11469
11470 // Initialization
11471 this.$element.addClass( 'oo-ui-panelLayout' );
11472 if ( config.scrollable ) {
11473 this.$element.addClass( 'oo-ui-panelLayout-scrollable' );
11474 }
11475 if ( config.padded ) {
11476 this.$element.addClass( 'oo-ui-panelLayout-padded' );
11477 }
11478 if ( config.expanded ) {
11479 this.$element.addClass( 'oo-ui-panelLayout-expanded' );
11480 }
11481 if ( config.framed ) {
11482 this.$element.addClass( 'oo-ui-panelLayout-framed' );
11483 }
11484 };
11485
11486 /* Setup */
11487
11488 OO.inheritClass( OO.ui.PanelLayout, OO.ui.Layout );
11489
11490 /* Methods */
11491
11492 /**
11493 * Focus the panel layout
11494 *
11495 * The default implementation just focuses the first focusable element in the panel
11496 */
11497 OO.ui.PanelLayout.prototype.focus = function () {
11498 OO.ui.findFocusable( this.$element ).focus();
11499 };
11500
11501 /**
11502 * HorizontalLayout arranges its contents in a single line (using `display: inline-block` for its
11503 * items), with small margins between them. Convenient when you need to put a number of block-level
11504 * widgets on a single line next to each other.
11505 *
11506 * Note that inline elements, such as OO.ui.ButtonWidgets, do not need this wrapper.
11507 *
11508 * @example
11509 * // HorizontalLayout with a text input and a label
11510 * var layout = new OO.ui.HorizontalLayout( {
11511 * items: [
11512 * new OO.ui.LabelWidget( { label: 'Label' } ),
11513 * new OO.ui.TextInputWidget( { value: 'Text' } )
11514 * ]
11515 * } );
11516 * $( 'body' ).append( layout.$element );
11517 *
11518 * @class
11519 * @extends OO.ui.Layout
11520 * @mixins OO.ui.mixin.GroupElement
11521 *
11522 * @constructor
11523 * @param {Object} [config] Configuration options
11524 * @cfg {OO.ui.Widget[]|OO.ui.Layout[]} [items] Widgets or other layouts to add to the layout.
11525 */
11526 OO.ui.HorizontalLayout = function OoUiHorizontalLayout( config ) {
11527 // Configuration initialization
11528 config = config || {};
11529
11530 // Parent constructor
11531 OO.ui.HorizontalLayout.parent.call( this, config );
11532
11533 // Mixin constructors
11534 OO.ui.mixin.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) );
11535
11536 // Initialization
11537 this.$element.addClass( 'oo-ui-horizontalLayout' );
11538 if ( Array.isArray( config.items ) ) {
11539 this.addItems( config.items );
11540 }
11541 };
11542
11543 /* Setup */
11544
11545 OO.inheritClass( OO.ui.HorizontalLayout, OO.ui.Layout );
11546 OO.mixinClass( OO.ui.HorizontalLayout, OO.ui.mixin.GroupElement );
11547
11548 }( OO ) );
11549
11550 //# sourceMappingURL=oojs-ui-core.js.map