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