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