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