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