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