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