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