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