Update OOjs UI to v0.17.1
[lhc/web/wiklou.git] / resources / lib / oojs-ui / oojs-ui-core.js
1 /*!
2 * OOjs UI v0.17.1
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-05-03T22:58:02Z
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 /* Events */
2056
2057 /**
2058 * @event change
2059 *
2060 * A change event is emitted when the set of selected items changes.
2061 *
2062 * @param {OO.ui.Element[]} items Items currently in the group
2063 */
2064
2065 /* Methods */
2066
2067 /**
2068 * Set the group element.
2069 *
2070 * If an element is already set, items will be moved to the new element.
2071 *
2072 * @param {jQuery} $group Element to use as group
2073 */
2074 OO.ui.mixin.GroupElement.prototype.setGroupElement = function ( $group ) {
2075 var i, len;
2076
2077 this.$group = $group;
2078 for ( i = 0, len = this.items.length; i < len; i++ ) {
2079 this.$group.append( this.items[ i ].$element );
2080 }
2081 };
2082
2083 /**
2084 * Check if a group contains no items.
2085 *
2086 * @return {boolean} Group is empty
2087 */
2088 OO.ui.mixin.GroupElement.prototype.isEmpty = function () {
2089 return !this.items.length;
2090 };
2091
2092 /**
2093 * Get all items in the group.
2094 *
2095 * The method returns an array of item references (e.g., [button1, button2, button3]) and is useful
2096 * when synchronizing groups of items, or whenever the references are required (e.g., when removing items
2097 * from a group).
2098 *
2099 * @return {OO.ui.Element[]} An array of items.
2100 */
2101 OO.ui.mixin.GroupElement.prototype.getItems = function () {
2102 return this.items.slice( 0 );
2103 };
2104
2105 /**
2106 * Get an item by its data.
2107 *
2108 * Only the first item with matching data will be returned. To return all matching items,
2109 * use the #getItemsFromData method.
2110 *
2111 * @param {Object} data Item data to search for
2112 * @return {OO.ui.Element|null} Item with equivalent data, `null` if none exists
2113 */
2114 OO.ui.mixin.GroupElement.prototype.getItemFromData = function ( data ) {
2115 var i, len, item,
2116 hash = OO.getHash( data );
2117
2118 for ( i = 0, len = this.items.length; i < len; i++ ) {
2119 item = this.items[ i ];
2120 if ( hash === OO.getHash( item.getData() ) ) {
2121 return item;
2122 }
2123 }
2124
2125 return null;
2126 };
2127
2128 /**
2129 * Get items by their data.
2130 *
2131 * All items with matching data will be returned. To return only the first match, use the #getItemFromData method instead.
2132 *
2133 * @param {Object} data Item data to search for
2134 * @return {OO.ui.Element[]} Items with equivalent data
2135 */
2136 OO.ui.mixin.GroupElement.prototype.getItemsFromData = function ( data ) {
2137 var i, len, item,
2138 hash = OO.getHash( data ),
2139 items = [];
2140
2141 for ( i = 0, len = this.items.length; i < len; i++ ) {
2142 item = this.items[ i ];
2143 if ( hash === OO.getHash( item.getData() ) ) {
2144 items.push( item );
2145 }
2146 }
2147
2148 return items;
2149 };
2150
2151 /**
2152 * Aggregate the events emitted by the group.
2153 *
2154 * When events are aggregated, the group will listen to all contained items for the event,
2155 * and then emit the event under a new name. The new event will contain an additional leading
2156 * parameter containing the item that emitted the original event. Other arguments emitted from
2157 * the original event are passed through.
2158 *
2159 * @param {Object.<string,string|null>} events An object keyed by the name of the event that should be
2160 * aggregated (e.g., ‘click’) and the value of the new name to use (e.g., ‘groupClick’).
2161 * A `null` value will remove aggregated events.
2162
2163 * @throws {Error} An error is thrown if aggregation already exists.
2164 */
2165 OO.ui.mixin.GroupElement.prototype.aggregate = function ( events ) {
2166 var i, len, item, add, remove, itemEvent, groupEvent;
2167
2168 for ( itemEvent in events ) {
2169 groupEvent = events[ itemEvent ];
2170
2171 // Remove existing aggregated event
2172 if ( Object.prototype.hasOwnProperty.call( this.aggregateItemEvents, itemEvent ) ) {
2173 // Don't allow duplicate aggregations
2174 if ( groupEvent ) {
2175 throw new Error( 'Duplicate item event aggregation for ' + itemEvent );
2176 }
2177 // Remove event aggregation from existing items
2178 for ( i = 0, len = this.items.length; i < len; i++ ) {
2179 item = this.items[ i ];
2180 if ( item.connect && item.disconnect ) {
2181 remove = {};
2182 remove[ itemEvent ] = [ 'emit', this.aggregateItemEvents[ itemEvent ], item ];
2183 item.disconnect( this, remove );
2184 }
2185 }
2186 // Prevent future items from aggregating event
2187 delete this.aggregateItemEvents[ itemEvent ];
2188 }
2189
2190 // Add new aggregate event
2191 if ( groupEvent ) {
2192 // Make future items aggregate event
2193 this.aggregateItemEvents[ itemEvent ] = groupEvent;
2194 // Add event aggregation to existing items
2195 for ( i = 0, len = this.items.length; i < len; i++ ) {
2196 item = this.items[ i ];
2197 if ( item.connect && item.disconnect ) {
2198 add = {};
2199 add[ itemEvent ] = [ 'emit', groupEvent, item ];
2200 item.connect( this, add );
2201 }
2202 }
2203 }
2204 }
2205 };
2206
2207 /**
2208 * Add items to the group.
2209 *
2210 * Items will be added to the end of the group array unless the optional `index` parameter specifies
2211 * a different insertion point. Adding an existing item will move it to the end of the array or the point specified by the `index`.
2212 *
2213 * @param {OO.ui.Element[]} items An array of items to add to the group
2214 * @param {number} [index] Index of the insertion point
2215 * @chainable
2216 */
2217 OO.ui.mixin.GroupElement.prototype.addItems = function ( items, index ) {
2218 var i, len, item, event, events, currentIndex,
2219 itemElements = [];
2220
2221 for ( i = 0, len = items.length; i < len; i++ ) {
2222 item = items[ i ];
2223
2224 // Check if item exists then remove it first, effectively "moving" it
2225 currentIndex = this.items.indexOf( item );
2226 if ( currentIndex >= 0 ) {
2227 this.removeItems( [ item ] );
2228 // Adjust index to compensate for removal
2229 if ( currentIndex < index ) {
2230 index--;
2231 }
2232 }
2233 // Add the item
2234 if ( item.connect && item.disconnect && !$.isEmptyObject( this.aggregateItemEvents ) ) {
2235 events = {};
2236 for ( event in this.aggregateItemEvents ) {
2237 events[ event ] = [ 'emit', this.aggregateItemEvents[ event ], item ];
2238 }
2239 item.connect( this, events );
2240 }
2241 item.setElementGroup( this );
2242 itemElements.push( item.$element.get( 0 ) );
2243 }
2244
2245 if ( index === undefined || index < 0 || index >= this.items.length ) {
2246 this.$group.append( itemElements );
2247 this.items.push.apply( this.items, items );
2248 } else if ( index === 0 ) {
2249 this.$group.prepend( itemElements );
2250 this.items.unshift.apply( this.items, items );
2251 } else {
2252 this.items[ index ].$element.before( itemElements );
2253 this.items.splice.apply( this.items, [ index, 0 ].concat( items ) );
2254 }
2255
2256 this.emit( 'change', this.getItems() );
2257 return this;
2258 };
2259
2260 /**
2261 * Remove the specified items from a group.
2262 *
2263 * Removed items are detached (not removed) from the DOM so that they may be reused.
2264 * To remove all items from a group, you may wish to use the #clearItems method instead.
2265 *
2266 * @param {OO.ui.Element[]} items An array of items to remove
2267 * @chainable
2268 */
2269 OO.ui.mixin.GroupElement.prototype.removeItems = function ( items ) {
2270 var i, len, item, index, remove, itemEvent;
2271
2272 // Remove specific items
2273 for ( i = 0, len = items.length; i < len; i++ ) {
2274 item = items[ i ];
2275 index = this.items.indexOf( item );
2276 if ( index !== -1 ) {
2277 if (
2278 item.connect && item.disconnect &&
2279 !$.isEmptyObject( this.aggregateItemEvents )
2280 ) {
2281 remove = {};
2282 if ( Object.prototype.hasOwnProperty.call( this.aggregateItemEvents, itemEvent ) ) {
2283 remove[ itemEvent ] = [ 'emit', this.aggregateItemEvents[ itemEvent ], item ];
2284 }
2285 item.disconnect( this, remove );
2286 }
2287 item.setElementGroup( null );
2288 this.items.splice( index, 1 );
2289 item.$element.detach();
2290 }
2291 }
2292
2293 this.emit( 'change', this.getItems() );
2294 return this;
2295 };
2296
2297 /**
2298 * Clear all items from the group.
2299 *
2300 * Cleared items are detached from the DOM, not removed, so that they may be reused.
2301 * To remove only a subset of items from a group, use the #removeItems method.
2302 *
2303 * @chainable
2304 */
2305 OO.ui.mixin.GroupElement.prototype.clearItems = function () {
2306 var i, len, item, remove, itemEvent;
2307
2308 // Remove all items
2309 for ( i = 0, len = this.items.length; i < len; i++ ) {
2310 item = this.items[ i ];
2311 if (
2312 item.connect && item.disconnect &&
2313 !$.isEmptyObject( this.aggregateItemEvents )
2314 ) {
2315 remove = {};
2316 if ( Object.prototype.hasOwnProperty.call( this.aggregateItemEvents, itemEvent ) ) {
2317 remove[ itemEvent ] = [ 'emit', this.aggregateItemEvents[ itemEvent ], item ];
2318 }
2319 item.disconnect( this, remove );
2320 }
2321 item.setElementGroup( null );
2322 item.$element.detach();
2323 }
2324
2325 this.emit( 'change', this.getItems() );
2326 this.items = [];
2327 return this;
2328 };
2329
2330 /**
2331 * IconElement is often mixed into other classes to generate an icon.
2332 * Icons are graphics, about the size of normal text. They are used to aid the user
2333 * in locating a control or to convey information in a space-efficient way. See the
2334 * [OOjs UI documentation on MediaWiki] [1] for a list of icons
2335 * included in the library.
2336 *
2337 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
2338 *
2339 * @abstract
2340 * @class
2341 *
2342 * @constructor
2343 * @param {Object} [config] Configuration options
2344 * @cfg {jQuery} [$icon] The icon element created by the class. If this configuration is omitted,
2345 * the icon element will use a generated `<span>`. To use a different HTML tag, or to specify that
2346 * the icon element be set to an existing icon instead of the one generated by this class, set a
2347 * value using a jQuery selection. For example:
2348 *
2349 * // Use a <div> tag instead of a <span>
2350 * $icon: $("<div>")
2351 * // Use an existing icon element instead of the one generated by the class
2352 * $icon: this.$element
2353 * // Use an icon element from a child widget
2354 * $icon: this.childwidget.$element
2355 * @cfg {Object|string} [icon=''] The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of
2356 * symbolic names. A map is used for i18n purposes and contains a `default` icon
2357 * name and additional names keyed by language code. The `default` name is used when no icon is keyed
2358 * by the user's language.
2359 *
2360 * Example of an i18n map:
2361 *
2362 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
2363 * See the [OOjs UI documentation on MediaWiki] [2] for a list of icons included in the library.
2364 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
2365 * @cfg {string|Function} [iconTitle] A text string used as the icon title, or a function that returns title
2366 * text. The icon title is displayed when users move the mouse over the icon.
2367 */
2368 OO.ui.mixin.IconElement = function OoUiMixinIconElement( config ) {
2369 // Configuration initialization
2370 config = config || {};
2371
2372 // Properties
2373 this.$icon = null;
2374 this.icon = null;
2375 this.iconTitle = null;
2376
2377 // Initialization
2378 this.setIcon( config.icon || this.constructor.static.icon );
2379 this.setIconTitle( config.iconTitle || this.constructor.static.iconTitle );
2380 this.setIconElement( config.$icon || $( '<span>' ) );
2381 };
2382
2383 /* Setup */
2384
2385 OO.initClass( OO.ui.mixin.IconElement );
2386
2387 /* Static Properties */
2388
2389 /**
2390 * The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of symbolic names. A map is used
2391 * for i18n purposes and contains a `default` icon name and additional names keyed by
2392 * language code. The `default` name is used when no icon is keyed by the user's language.
2393 *
2394 * Example of an i18n map:
2395 *
2396 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
2397 *
2398 * Note: the static property will be overridden if the #icon configuration is used.
2399 *
2400 * @static
2401 * @inheritable
2402 * @property {Object|string}
2403 */
2404 OO.ui.mixin.IconElement.static.icon = null;
2405
2406 /**
2407 * The icon title, displayed when users move the mouse over the icon. The value can be text, a
2408 * function that returns title text, or `null` for no title.
2409 *
2410 * The static property will be overridden if the #iconTitle configuration is used.
2411 *
2412 * @static
2413 * @inheritable
2414 * @property {string|Function|null}
2415 */
2416 OO.ui.mixin.IconElement.static.iconTitle = null;
2417
2418 /* Methods */
2419
2420 /**
2421 * Set the icon element. This method is used to retarget an icon mixin so that its functionality
2422 * applies to the specified icon element instead of the one created by the class. If an icon
2423 * element is already set, the mixin’s effect on that element is removed. Generated CSS classes
2424 * and mixin methods will no longer affect the element.
2425 *
2426 * @param {jQuery} $icon Element to use as icon
2427 */
2428 OO.ui.mixin.IconElement.prototype.setIconElement = function ( $icon ) {
2429 if ( this.$icon ) {
2430 this.$icon
2431 .removeClass( 'oo-ui-iconElement-icon oo-ui-icon-' + this.icon )
2432 .removeAttr( 'title' );
2433 }
2434
2435 this.$icon = $icon
2436 .addClass( 'oo-ui-iconElement-icon' )
2437 .toggleClass( 'oo-ui-icon-' + this.icon, !!this.icon );
2438 if ( this.iconTitle !== null ) {
2439 this.$icon.attr( 'title', this.iconTitle );
2440 }
2441
2442 this.updateThemeClasses();
2443 };
2444
2445 /**
2446 * Set icon by symbolic name (e.g., ‘remove’ or ‘menu’). Use `null` to remove an icon.
2447 * The icon parameter can also be set to a map of icon names. See the #icon config setting
2448 * for an example.
2449 *
2450 * @param {Object|string|null} icon A symbolic icon name, a {@link #icon map of icon names} keyed
2451 * by language code, or `null` to remove the icon.
2452 * @chainable
2453 */
2454 OO.ui.mixin.IconElement.prototype.setIcon = function ( icon ) {
2455 icon = OO.isPlainObject( icon ) ? OO.ui.getLocalValue( icon, null, 'default' ) : icon;
2456 icon = typeof icon === 'string' && icon.trim().length ? icon.trim() : null;
2457
2458 if ( this.icon !== icon ) {
2459 if ( this.$icon ) {
2460 if ( this.icon !== null ) {
2461 this.$icon.removeClass( 'oo-ui-icon-' + this.icon );
2462 }
2463 if ( icon !== null ) {
2464 this.$icon.addClass( 'oo-ui-icon-' + icon );
2465 }
2466 }
2467 this.icon = icon;
2468 }
2469
2470 this.$element.toggleClass( 'oo-ui-iconElement', !!this.icon );
2471 this.updateThemeClasses();
2472
2473 return this;
2474 };
2475
2476 /**
2477 * Set the icon title. Use `null` to remove the title.
2478 *
2479 * @param {string|Function|null} iconTitle A text string used as the icon title,
2480 * a function that returns title text, or `null` for no title.
2481 * @chainable
2482 */
2483 OO.ui.mixin.IconElement.prototype.setIconTitle = function ( iconTitle ) {
2484 iconTitle = typeof iconTitle === 'function' ||
2485 ( typeof iconTitle === 'string' && iconTitle.length ) ?
2486 OO.ui.resolveMsg( iconTitle ) : null;
2487
2488 if ( this.iconTitle !== iconTitle ) {
2489 this.iconTitle = iconTitle;
2490 if ( this.$icon ) {
2491 if ( this.iconTitle !== null ) {
2492 this.$icon.attr( 'title', iconTitle );
2493 } else {
2494 this.$icon.removeAttr( 'title' );
2495 }
2496 }
2497 }
2498
2499 return this;
2500 };
2501
2502 /**
2503 * Get the symbolic name of the icon.
2504 *
2505 * @return {string} Icon name
2506 */
2507 OO.ui.mixin.IconElement.prototype.getIcon = function () {
2508 return this.icon;
2509 };
2510
2511 /**
2512 * Get the icon title. The title text is displayed when a user moves the mouse over the icon.
2513 *
2514 * @return {string} Icon title text
2515 */
2516 OO.ui.mixin.IconElement.prototype.getIconTitle = function () {
2517 return this.iconTitle;
2518 };
2519
2520 /**
2521 * IndicatorElement is often mixed into other classes to generate an indicator.
2522 * Indicators are small graphics that are generally used in two ways:
2523 *
2524 * - To draw attention to the status of an item. For example, an indicator might be
2525 * used to show that an item in a list has errors that need to be resolved.
2526 * - To clarify the function of a control that acts in an exceptional way (a button
2527 * that opens a menu instead of performing an action directly, for example).
2528 *
2529 * For a list of indicators included in the library, please see the
2530 * [OOjs UI documentation on MediaWiki] [1].
2531 *
2532 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
2533 *
2534 * @abstract
2535 * @class
2536 *
2537 * @constructor
2538 * @param {Object} [config] Configuration options
2539 * @cfg {jQuery} [$indicator] The indicator element created by the class. If this
2540 * configuration is omitted, the indicator element will use a generated `<span>`.
2541 * @cfg {string} [indicator] Symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
2542 * See the [OOjs UI documentation on MediaWiki][2] for a list of indicators included
2543 * in the library.
2544 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
2545 * @cfg {string|Function} [indicatorTitle] A text string used as the indicator title,
2546 * or a function that returns title text. The indicator title is displayed when users move
2547 * the mouse over the indicator.
2548 */
2549 OO.ui.mixin.IndicatorElement = function OoUiMixinIndicatorElement( config ) {
2550 // Configuration initialization
2551 config = config || {};
2552
2553 // Properties
2554 this.$indicator = null;
2555 this.indicator = null;
2556 this.indicatorTitle = null;
2557
2558 // Initialization
2559 this.setIndicator( config.indicator || this.constructor.static.indicator );
2560 this.setIndicatorTitle( config.indicatorTitle || this.constructor.static.indicatorTitle );
2561 this.setIndicatorElement( config.$indicator || $( '<span>' ) );
2562 };
2563
2564 /* Setup */
2565
2566 OO.initClass( OO.ui.mixin.IndicatorElement );
2567
2568 /* Static Properties */
2569
2570 /**
2571 * Symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
2572 * The static property will be overridden if the #indicator configuration is used.
2573 *
2574 * @static
2575 * @inheritable
2576 * @property {string|null}
2577 */
2578 OO.ui.mixin.IndicatorElement.static.indicator = null;
2579
2580 /**
2581 * A text string used as the indicator title, a function that returns title text, or `null`
2582 * for no title. The static property will be overridden if the #indicatorTitle configuration is used.
2583 *
2584 * @static
2585 * @inheritable
2586 * @property {string|Function|null}
2587 */
2588 OO.ui.mixin.IndicatorElement.static.indicatorTitle = null;
2589
2590 /* Methods */
2591
2592 /**
2593 * Set the indicator element.
2594 *
2595 * If an element is already set, it will be cleaned up before setting up the new element.
2596 *
2597 * @param {jQuery} $indicator Element to use as indicator
2598 */
2599 OO.ui.mixin.IndicatorElement.prototype.setIndicatorElement = function ( $indicator ) {
2600 if ( this.$indicator ) {
2601 this.$indicator
2602 .removeClass( 'oo-ui-indicatorElement-indicator oo-ui-indicator-' + this.indicator )
2603 .removeAttr( 'title' );
2604 }
2605
2606 this.$indicator = $indicator
2607 .addClass( 'oo-ui-indicatorElement-indicator' )
2608 .toggleClass( 'oo-ui-indicator-' + this.indicator, !!this.indicator );
2609 if ( this.indicatorTitle !== null ) {
2610 this.$indicator.attr( 'title', this.indicatorTitle );
2611 }
2612
2613 this.updateThemeClasses();
2614 };
2615
2616 /**
2617 * Set the indicator by its symbolic name: ‘alert’, ‘down’, ‘next’, ‘previous’, ‘required’, ‘up’. Use `null` to remove the indicator.
2618 *
2619 * @param {string|null} indicator Symbolic name of indicator, or `null` for no indicator
2620 * @chainable
2621 */
2622 OO.ui.mixin.IndicatorElement.prototype.setIndicator = function ( indicator ) {
2623 indicator = typeof indicator === 'string' && indicator.length ? indicator.trim() : null;
2624
2625 if ( this.indicator !== indicator ) {
2626 if ( this.$indicator ) {
2627 if ( this.indicator !== null ) {
2628 this.$indicator.removeClass( 'oo-ui-indicator-' + this.indicator );
2629 }
2630 if ( indicator !== null ) {
2631 this.$indicator.addClass( 'oo-ui-indicator-' + indicator );
2632 }
2633 }
2634 this.indicator = indicator;
2635 }
2636
2637 this.$element.toggleClass( 'oo-ui-indicatorElement', !!this.indicator );
2638 this.updateThemeClasses();
2639
2640 return this;
2641 };
2642
2643 /**
2644 * Set the indicator title.
2645 *
2646 * The title is displayed when a user moves the mouse over the indicator.
2647 *
2648 * @param {string|Function|null} indicatorTitle Indicator title text, a function that returns text, or
2649 * `null` for no indicator title
2650 * @chainable
2651 */
2652 OO.ui.mixin.IndicatorElement.prototype.setIndicatorTitle = function ( indicatorTitle ) {
2653 indicatorTitle = typeof indicatorTitle === 'function' ||
2654 ( typeof indicatorTitle === 'string' && indicatorTitle.length ) ?
2655 OO.ui.resolveMsg( indicatorTitle ) : null;
2656
2657 if ( this.indicatorTitle !== indicatorTitle ) {
2658 this.indicatorTitle = indicatorTitle;
2659 if ( this.$indicator ) {
2660 if ( this.indicatorTitle !== null ) {
2661 this.$indicator.attr( 'title', indicatorTitle );
2662 } else {
2663 this.$indicator.removeAttr( 'title' );
2664 }
2665 }
2666 }
2667
2668 return this;
2669 };
2670
2671 /**
2672 * Get the symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
2673 *
2674 * @return {string} Symbolic name of indicator
2675 */
2676 OO.ui.mixin.IndicatorElement.prototype.getIndicator = function () {
2677 return this.indicator;
2678 };
2679
2680 /**
2681 * Get the indicator title.
2682 *
2683 * The title is displayed when a user moves the mouse over the indicator.
2684 *
2685 * @return {string} Indicator title text
2686 */
2687 OO.ui.mixin.IndicatorElement.prototype.getIndicatorTitle = function () {
2688 return this.indicatorTitle;
2689 };
2690
2691 /**
2692 * LabelElement is often mixed into other classes to generate a label, which
2693 * helps identify the function of an interface element.
2694 * See the [OOjs UI documentation on MediaWiki] [1] for more information.
2695 *
2696 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Labels
2697 *
2698 * @abstract
2699 * @class
2700 *
2701 * @constructor
2702 * @param {Object} [config] Configuration options
2703 * @cfg {jQuery} [$label] The label element created by the class. If this
2704 * configuration is omitted, the label element will use a generated `<span>`.
2705 * @cfg {jQuery|string|Function|OO.ui.HtmlSnippet} [label] The label text. The label can be specified
2706 * as a plaintext string, a jQuery selection of elements, or a function that will produce a string
2707 * in the future. See the [OOjs UI documentation on MediaWiki] [2] for examples.
2708 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Labels
2709 */
2710 OO.ui.mixin.LabelElement = function OoUiMixinLabelElement( config ) {
2711 // Configuration initialization
2712 config = config || {};
2713
2714 // Properties
2715 this.$label = null;
2716 this.label = null;
2717
2718 // Initialization
2719 this.setLabel( config.label || this.constructor.static.label );
2720 this.setLabelElement( config.$label || $( '<span>' ) );
2721 };
2722
2723 /* Setup */
2724
2725 OO.initClass( OO.ui.mixin.LabelElement );
2726
2727 /* Events */
2728
2729 /**
2730 * @event labelChange
2731 * @param {string} value
2732 */
2733
2734 /* Static Properties */
2735
2736 /**
2737 * The label text. The label can be specified as a plaintext string, a function that will
2738 * produce a string in the future, or `null` for no label. The static value will
2739 * be overridden if a label is specified with the #label config option.
2740 *
2741 * @static
2742 * @inheritable
2743 * @property {string|Function|null}
2744 */
2745 OO.ui.mixin.LabelElement.static.label = null;
2746
2747 /* Static methods */
2748
2749 /**
2750 * Highlight the first occurrence of the query in the given text
2751 *
2752 * @param {string} text Text
2753 * @param {string} query Query to find
2754 * @return {jQuery} Text with the first match of the query
2755 * sub-string wrapped in highlighted span
2756 */
2757 OO.ui.mixin.LabelElement.static.highlightQuery = function ( text, query ) {
2758 var $result = $( '<span>' ),
2759 offset = text.toLowerCase().indexOf( query.toLowerCase() );
2760
2761 if ( !query.length || offset === -1 ) {
2762 return $result.text( text );
2763 }
2764 $result.append(
2765 document.createTextNode( text.slice( 0, offset ) ),
2766 $( '<span>' )
2767 .addClass( 'oo-ui-labelElement-label-highlight' )
2768 .text( text.slice( offset, offset + query.length ) ),
2769 document.createTextNode( text.slice( offset + query.length ) )
2770 );
2771 return $result.contents();
2772 };
2773
2774 /* Methods */
2775
2776 /**
2777 * Set the label element.
2778 *
2779 * If an element is already set, it will be cleaned up before setting up the new element.
2780 *
2781 * @param {jQuery} $label Element to use as label
2782 */
2783 OO.ui.mixin.LabelElement.prototype.setLabelElement = function ( $label ) {
2784 if ( this.$label ) {
2785 this.$label.removeClass( 'oo-ui-labelElement-label' ).empty();
2786 }
2787
2788 this.$label = $label.addClass( 'oo-ui-labelElement-label' );
2789 this.setLabelContent( this.label );
2790 };
2791
2792 /**
2793 * Set the label.
2794 *
2795 * An empty string will result in the label being hidden. A string containing only whitespace will
2796 * be converted to a single `&nbsp;`.
2797 *
2798 * @param {jQuery|string|OO.ui.HtmlSnippet|Function|null} label Label nodes; text; a function that returns nodes or
2799 * text; or null for no label
2800 * @chainable
2801 */
2802 OO.ui.mixin.LabelElement.prototype.setLabel = function ( label ) {
2803 label = typeof label === 'function' ? OO.ui.resolveMsg( label ) : label;
2804 label = ( ( typeof label === 'string' || label instanceof jQuery ) && label.length ) || ( label instanceof OO.ui.HtmlSnippet && label.toString().length ) ? label : null;
2805
2806 if ( this.label !== label ) {
2807 if ( this.$label ) {
2808 this.setLabelContent( label );
2809 }
2810 this.label = label;
2811 this.emit( 'labelChange' );
2812 }
2813
2814 this.$element.toggleClass( 'oo-ui-labelElement', !!this.label );
2815
2816 return this;
2817 };
2818
2819 /**
2820 * Set the label as plain text with a highlighted query
2821 *
2822 * @param {string} text Text label to set
2823 * @param {string} query Substring of text to highlight
2824 * @chainable
2825 */
2826 OO.ui.mixin.LabelElement.prototype.setHighlightedQuery = function ( text, query ) {
2827 return this.setLabel( this.constructor.static.highlightQuery( text, query ) );
2828 };
2829
2830 /**
2831 * Get the label.
2832 *
2833 * @return {jQuery|string|Function|null} Label nodes; text; a function that returns nodes or
2834 * text; or null for no label
2835 */
2836 OO.ui.mixin.LabelElement.prototype.getLabel = function () {
2837 return this.label;
2838 };
2839
2840 /**
2841 * Fit the label.
2842 *
2843 * @chainable
2844 * @deprecated since 0.16.0
2845 */
2846 OO.ui.mixin.LabelElement.prototype.fitLabel = function () {
2847 return this;
2848 };
2849
2850 /**
2851 * Set the content of the label.
2852 *
2853 * Do not call this method until after the label element has been set by #setLabelElement.
2854 *
2855 * @private
2856 * @param {jQuery|string|Function|null} label Label nodes; text; a function that returns nodes or
2857 * text; or null for no label
2858 */
2859 OO.ui.mixin.LabelElement.prototype.setLabelContent = function ( label ) {
2860 if ( typeof label === 'string' ) {
2861 if ( label.match( /^\s*$/ ) ) {
2862 // Convert whitespace only string to a single non-breaking space
2863 this.$label.html( '&nbsp;' );
2864 } else {
2865 this.$label.text( label );
2866 }
2867 } else if ( label instanceof OO.ui.HtmlSnippet ) {
2868 this.$label.html( label.toString() );
2869 } else if ( label instanceof jQuery ) {
2870 this.$label.empty().append( label );
2871 } else {
2872 this.$label.empty();
2873 }
2874 };
2875
2876 /**
2877 * The FlaggedElement class is an attribute mixin, meaning that it is used to add
2878 * additional functionality to an element created by another class. The class provides
2879 * a ‘flags’ property assigned the name (or an array of names) of styling flags,
2880 * which are used to customize the look and feel of a widget to better describe its
2881 * importance and functionality.
2882 *
2883 * The library currently contains the following styling flags for general use:
2884 *
2885 * - **progressive**: Progressive styling is applied to convey that the widget will move the user forward in a process.
2886 * - **destructive**: Destructive styling is applied to convey that the widget will remove something.
2887 * - **constructive**: Constructive styling is applied to convey that the widget will create something.
2888 *
2889 * The flags affect the appearance of the buttons:
2890 *
2891 * @example
2892 * // FlaggedElement is mixed into ButtonWidget to provide styling flags
2893 * var button1 = new OO.ui.ButtonWidget( {
2894 * label: 'Constructive',
2895 * flags: 'constructive'
2896 * } );
2897 * var button2 = new OO.ui.ButtonWidget( {
2898 * label: 'Destructive',
2899 * flags: 'destructive'
2900 * } );
2901 * var button3 = new OO.ui.ButtonWidget( {
2902 * label: 'Progressive',
2903 * flags: 'progressive'
2904 * } );
2905 * $( 'body' ).append( button1.$element, button2.$element, button3.$element );
2906 *
2907 * {@link OO.ui.ActionWidget ActionWidgets}, which are a special kind of button that execute an action, use these flags: **primary** and **safe**.
2908 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information.
2909 *
2910 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Flagged
2911 *
2912 * @abstract
2913 * @class
2914 *
2915 * @constructor
2916 * @param {Object} [config] Configuration options
2917 * @cfg {string|string[]} [flags] The name or names of the flags (e.g., 'constructive' or 'primary') to apply.
2918 * Please see the [OOjs UI documentation on MediaWiki] [2] for more information about available flags.
2919 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Flagged
2920 * @cfg {jQuery} [$flagged] The flagged element. By default,
2921 * the flagged functionality is applied to the element created by the class ($element).
2922 * If a different element is specified, the flagged functionality will be applied to it instead.
2923 */
2924 OO.ui.mixin.FlaggedElement = function OoUiMixinFlaggedElement( config ) {
2925 // Configuration initialization
2926 config = config || {};
2927
2928 // Properties
2929 this.flags = {};
2930 this.$flagged = null;
2931
2932 // Initialization
2933 this.setFlags( config.flags );
2934 this.setFlaggedElement( config.$flagged || this.$element );
2935 };
2936
2937 /* Events */
2938
2939 /**
2940 * @event flag
2941 * A flag event is emitted when the #clearFlags or #setFlags methods are used. The `changes`
2942 * parameter contains the name of each modified flag and indicates whether it was
2943 * added or removed.
2944 *
2945 * @param {Object.<string,boolean>} changes Object keyed by flag name. A Boolean `true` indicates
2946 * that the flag was added, `false` that the flag was removed.
2947 */
2948
2949 /* Methods */
2950
2951 /**
2952 * Set the flagged element.
2953 *
2954 * This method is used to retarget a flagged mixin so that its functionality applies to the specified element.
2955 * If an element is already set, the method will remove the mixin’s effect on that element.
2956 *
2957 * @param {jQuery} $flagged Element that should be flagged
2958 */
2959 OO.ui.mixin.FlaggedElement.prototype.setFlaggedElement = function ( $flagged ) {
2960 var classNames = Object.keys( this.flags ).map( function ( flag ) {
2961 return 'oo-ui-flaggedElement-' + flag;
2962 } ).join( ' ' );
2963
2964 if ( this.$flagged ) {
2965 this.$flagged.removeClass( classNames );
2966 }
2967
2968 this.$flagged = $flagged.addClass( classNames );
2969 };
2970
2971 /**
2972 * Check if the specified flag is set.
2973 *
2974 * @param {string} flag Name of flag
2975 * @return {boolean} The flag is set
2976 */
2977 OO.ui.mixin.FlaggedElement.prototype.hasFlag = function ( flag ) {
2978 // This may be called before the constructor, thus before this.flags is set
2979 return this.flags && ( flag in this.flags );
2980 };
2981
2982 /**
2983 * Get the names of all flags set.
2984 *
2985 * @return {string[]} Flag names
2986 */
2987 OO.ui.mixin.FlaggedElement.prototype.getFlags = function () {
2988 // This may be called before the constructor, thus before this.flags is set
2989 return Object.keys( this.flags || {} );
2990 };
2991
2992 /**
2993 * Clear all flags.
2994 *
2995 * @chainable
2996 * @fires flag
2997 */
2998 OO.ui.mixin.FlaggedElement.prototype.clearFlags = function () {
2999 var flag, className,
3000 changes = {},
3001 remove = [],
3002 classPrefix = 'oo-ui-flaggedElement-';
3003
3004 for ( flag in this.flags ) {
3005 className = classPrefix + flag;
3006 changes[ flag ] = false;
3007 delete this.flags[ flag ];
3008 remove.push( className );
3009 }
3010
3011 if ( this.$flagged ) {
3012 this.$flagged.removeClass( remove.join( ' ' ) );
3013 }
3014
3015 this.updateThemeClasses();
3016 this.emit( 'flag', changes );
3017
3018 return this;
3019 };
3020
3021 /**
3022 * Add one or more flags.
3023 *
3024 * @param {string|string[]|Object.<string, boolean>} flags A flag name, an array of flag names,
3025 * or an object keyed by flag name with a boolean value that indicates whether the flag should
3026 * be added (`true`) or removed (`false`).
3027 * @chainable
3028 * @fires flag
3029 */
3030 OO.ui.mixin.FlaggedElement.prototype.setFlags = function ( flags ) {
3031 var i, len, flag, className,
3032 changes = {},
3033 add = [],
3034 remove = [],
3035 classPrefix = 'oo-ui-flaggedElement-';
3036
3037 if ( typeof flags === 'string' ) {
3038 className = classPrefix + flags;
3039 // Set
3040 if ( !this.flags[ flags ] ) {
3041 this.flags[ flags ] = true;
3042 add.push( className );
3043 }
3044 } else if ( Array.isArray( flags ) ) {
3045 for ( i = 0, len = flags.length; i < len; i++ ) {
3046 flag = flags[ i ];
3047 className = classPrefix + flag;
3048 // Set
3049 if ( !this.flags[ flag ] ) {
3050 changes[ flag ] = true;
3051 this.flags[ flag ] = true;
3052 add.push( className );
3053 }
3054 }
3055 } else if ( OO.isPlainObject( flags ) ) {
3056 for ( flag in flags ) {
3057 className = classPrefix + flag;
3058 if ( flags[ flag ] ) {
3059 // Set
3060 if ( !this.flags[ flag ] ) {
3061 changes[ flag ] = true;
3062 this.flags[ flag ] = true;
3063 add.push( className );
3064 }
3065 } else {
3066 // Remove
3067 if ( this.flags[ flag ] ) {
3068 changes[ flag ] = false;
3069 delete this.flags[ flag ];
3070 remove.push( className );
3071 }
3072 }
3073 }
3074 }
3075
3076 if ( this.$flagged ) {
3077 this.$flagged
3078 .addClass( add.join( ' ' ) )
3079 .removeClass( remove.join( ' ' ) );
3080 }
3081
3082 this.updateThemeClasses();
3083 this.emit( 'flag', changes );
3084
3085 return this;
3086 };
3087
3088 /**
3089 * TitledElement is mixed into other classes to provide a `title` attribute.
3090 * Titles are rendered by the browser and are made visible when the user moves
3091 * the mouse over the element. Titles are not visible on touch devices.
3092 *
3093 * @example
3094 * // TitledElement provides a 'title' attribute to the
3095 * // ButtonWidget class
3096 * var button = new OO.ui.ButtonWidget( {
3097 * label: 'Button with Title',
3098 * title: 'I am a button'
3099 * } );
3100 * $( 'body' ).append( button.$element );
3101 *
3102 * @abstract
3103 * @class
3104 *
3105 * @constructor
3106 * @param {Object} [config] Configuration options
3107 * @cfg {jQuery} [$titled] The element to which the `title` attribute is applied.
3108 * If this config is omitted, the title functionality is applied to $element, the
3109 * element created by the class.
3110 * @cfg {string|Function} [title] The title text or a function that returns text. If
3111 * this config is omitted, the value of the {@link #static-title static title} property is used.
3112 */
3113 OO.ui.mixin.TitledElement = function OoUiMixinTitledElement( config ) {
3114 // Configuration initialization
3115 config = config || {};
3116
3117 // Properties
3118 this.$titled = null;
3119 this.title = null;
3120
3121 // Initialization
3122 this.setTitle( config.title !== undefined ? config.title : this.constructor.static.title );
3123 this.setTitledElement( config.$titled || this.$element );
3124 };
3125
3126 /* Setup */
3127
3128 OO.initClass( OO.ui.mixin.TitledElement );
3129
3130 /* Static Properties */
3131
3132 /**
3133 * The title text, a function that returns text, or `null` for no title. The value of the static property
3134 * is overridden if the #title config option is used.
3135 *
3136 * @static
3137 * @inheritable
3138 * @property {string|Function|null}
3139 */
3140 OO.ui.mixin.TitledElement.static.title = null;
3141
3142 /* Methods */
3143
3144 /**
3145 * Set the titled element.
3146 *
3147 * This method is used to retarget a titledElement mixin so that its functionality applies to the specified element.
3148 * If an element is already set, the mixin’s effect on that element is removed before the new element is set up.
3149 *
3150 * @param {jQuery} $titled Element that should use the 'titled' functionality
3151 */
3152 OO.ui.mixin.TitledElement.prototype.setTitledElement = function ( $titled ) {
3153 if ( this.$titled ) {
3154 this.$titled.removeAttr( 'title' );
3155 }
3156
3157 this.$titled = $titled;
3158 if ( this.title ) {
3159 this.$titled.attr( 'title', this.title );
3160 }
3161 };
3162
3163 /**
3164 * Set title.
3165 *
3166 * @param {string|Function|null} title Title text, a function that returns text, or `null` for no title
3167 * @chainable
3168 */
3169 OO.ui.mixin.TitledElement.prototype.setTitle = function ( title ) {
3170 title = typeof title === 'function' ? OO.ui.resolveMsg( title ) : title;
3171 title = ( typeof title === 'string' && title.length ) ? title : null;
3172
3173 if ( this.title !== title ) {
3174 if ( this.$titled ) {
3175 if ( title !== null ) {
3176 this.$titled.attr( 'title', title );
3177 } else {
3178 this.$titled.removeAttr( 'title' );
3179 }
3180 }
3181 this.title = title;
3182 }
3183
3184 return this;
3185 };
3186
3187 /**
3188 * Get title.
3189 *
3190 * @return {string} Title string
3191 */
3192 OO.ui.mixin.TitledElement.prototype.getTitle = function () {
3193 return this.title;
3194 };
3195
3196 /**
3197 * AccessKeyedElement is mixed into other classes to provide an `accesskey` attribute.
3198 * Accesskeys allow an user to go to a specific element by using
3199 * a shortcut combination of a browser specific keys + the key
3200 * set to the field.
3201 *
3202 * @example
3203 * // AccessKeyedElement provides an 'accesskey' attribute to the
3204 * // ButtonWidget class
3205 * var button = new OO.ui.ButtonWidget( {
3206 * label: 'Button with Accesskey',
3207 * accessKey: 'k'
3208 * } );
3209 * $( 'body' ).append( button.$element );
3210 *
3211 * @abstract
3212 * @class
3213 *
3214 * @constructor
3215 * @param {Object} [config] Configuration options
3216 * @cfg {jQuery} [$accessKeyed] The element to which the `accesskey` attribute is applied.
3217 * If this config is omitted, the accesskey functionality is applied to $element, the
3218 * element created by the class.
3219 * @cfg {string|Function} [accessKey] The key or a function that returns the key. If
3220 * this config is omitted, no accesskey will be added.
3221 */
3222 OO.ui.mixin.AccessKeyedElement = function OoUiMixinAccessKeyedElement( config ) {
3223 // Configuration initialization
3224 config = config || {};
3225
3226 // Properties
3227 this.$accessKeyed = null;
3228 this.accessKey = null;
3229
3230 // Initialization
3231 this.setAccessKey( config.accessKey || null );
3232 this.setAccessKeyedElement( config.$accessKeyed || this.$element );
3233 };
3234
3235 /* Setup */
3236
3237 OO.initClass( OO.ui.mixin.AccessKeyedElement );
3238
3239 /* Static Properties */
3240
3241 /**
3242 * The access key, a function that returns a key, or `null` for no accesskey.
3243 *
3244 * @static
3245 * @inheritable
3246 * @property {string|Function|null}
3247 */
3248 OO.ui.mixin.AccessKeyedElement.static.accessKey = null;
3249
3250 /* Methods */
3251
3252 /**
3253 * Set the accesskeyed element.
3254 *
3255 * This method is used to retarget a AccessKeyedElement mixin so that its functionality applies to the specified element.
3256 * If an element is already set, the mixin's effect on that element is removed before the new element is set up.
3257 *
3258 * @param {jQuery} $accessKeyed Element that should use the 'accesskeyes' functionality
3259 */
3260 OO.ui.mixin.AccessKeyedElement.prototype.setAccessKeyedElement = function ( $accessKeyed ) {
3261 if ( this.$accessKeyed ) {
3262 this.$accessKeyed.removeAttr( 'accesskey' );
3263 }
3264
3265 this.$accessKeyed = $accessKeyed;
3266 if ( this.accessKey ) {
3267 this.$accessKeyed.attr( 'accesskey', this.accessKey );
3268 }
3269 };
3270
3271 /**
3272 * Set accesskey.
3273 *
3274 * @param {string|Function|null} accessKey Key, a function that returns a key, or `null` for no accesskey
3275 * @chainable
3276 */
3277 OO.ui.mixin.AccessKeyedElement.prototype.setAccessKey = function ( accessKey ) {
3278 accessKey = typeof accessKey === 'string' ? OO.ui.resolveMsg( accessKey ) : null;
3279
3280 if ( this.accessKey !== accessKey ) {
3281 if ( this.$accessKeyed ) {
3282 if ( accessKey !== null ) {
3283 this.$accessKeyed.attr( 'accesskey', accessKey );
3284 } else {
3285 this.$accessKeyed.removeAttr( 'accesskey' );
3286 }
3287 }
3288 this.accessKey = accessKey;
3289 }
3290
3291 return this;
3292 };
3293
3294 /**
3295 * Get accesskey.
3296 *
3297 * @return {string} accessKey string
3298 */
3299 OO.ui.mixin.AccessKeyedElement.prototype.getAccessKey = function () {
3300 return this.accessKey;
3301 };
3302
3303 /**
3304 * ButtonWidget is a generic widget for buttons. A wide variety of looks,
3305 * feels, and functionality can be customized via the class’s configuration options
3306 * and methods. Please see the [OOjs UI documentation on MediaWiki] [1] for more information
3307 * and examples.
3308 *
3309 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches
3310 *
3311 * @example
3312 * // A button widget
3313 * var button = new OO.ui.ButtonWidget( {
3314 * label: 'Button with Icon',
3315 * icon: 'remove',
3316 * iconTitle: 'Remove'
3317 * } );
3318 * $( 'body' ).append( button.$element );
3319 *
3320 * NOTE: HTML form buttons should use the OO.ui.ButtonInputWidget class.
3321 *
3322 * @class
3323 * @extends OO.ui.Widget
3324 * @mixins OO.ui.mixin.ButtonElement
3325 * @mixins OO.ui.mixin.IconElement
3326 * @mixins OO.ui.mixin.IndicatorElement
3327 * @mixins OO.ui.mixin.LabelElement
3328 * @mixins OO.ui.mixin.TitledElement
3329 * @mixins OO.ui.mixin.FlaggedElement
3330 * @mixins OO.ui.mixin.TabIndexedElement
3331 * @mixins OO.ui.mixin.AccessKeyedElement
3332 *
3333 * @constructor
3334 * @param {Object} [config] Configuration options
3335 * @cfg {string} [href] Hyperlink to visit when the button is clicked.
3336 * @cfg {string} [target] The frame or window in which to open the hyperlink.
3337 * @cfg {boolean} [noFollow] Search engine traversal hint (default: true)
3338 */
3339 OO.ui.ButtonWidget = function OoUiButtonWidget( config ) {
3340 // Configuration initialization
3341 config = config || {};
3342
3343 // Parent constructor
3344 OO.ui.ButtonWidget.parent.call( this, config );
3345
3346 // Mixin constructors
3347 OO.ui.mixin.ButtonElement.call( this, config );
3348 OO.ui.mixin.IconElement.call( this, config );
3349 OO.ui.mixin.IndicatorElement.call( this, config );
3350 OO.ui.mixin.LabelElement.call( this, config );
3351 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$button } ) );
3352 OO.ui.mixin.FlaggedElement.call( this, config );
3353 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$button } ) );
3354 OO.ui.mixin.AccessKeyedElement.call( this, $.extend( {}, config, { $accessKeyed: this.$button } ) );
3355
3356 // Properties
3357 this.href = null;
3358 this.target = null;
3359 this.noFollow = false;
3360
3361 // Events
3362 this.connect( this, { disable: 'onDisable' } );
3363
3364 // Initialization
3365 this.$button.append( this.$icon, this.$label, this.$indicator );
3366 this.$element
3367 .addClass( 'oo-ui-buttonWidget' )
3368 .append( this.$button );
3369 this.setHref( config.href );
3370 this.setTarget( config.target );
3371 this.setNoFollow( config.noFollow );
3372 };
3373
3374 /* Setup */
3375
3376 OO.inheritClass( OO.ui.ButtonWidget, OO.ui.Widget );
3377 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.ButtonElement );
3378 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.IconElement );
3379 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.IndicatorElement );
3380 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.LabelElement );
3381 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.TitledElement );
3382 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.FlaggedElement );
3383 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.TabIndexedElement );
3384 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.AccessKeyedElement );
3385
3386 /* Methods */
3387
3388 /**
3389 * @inheritdoc
3390 */
3391 OO.ui.ButtonWidget.prototype.onMouseDown = function ( e ) {
3392 if ( !this.isDisabled() ) {
3393 // Remove the tab-index while the button is down to prevent the button from stealing focus
3394 this.$button.removeAttr( 'tabindex' );
3395 }
3396
3397 return OO.ui.mixin.ButtonElement.prototype.onMouseDown.call( this, e );
3398 };
3399
3400 /**
3401 * @inheritdoc
3402 */
3403 OO.ui.ButtonWidget.prototype.onMouseUp = function ( e ) {
3404 if ( !this.isDisabled() ) {
3405 // Restore the tab-index after the button is up to restore the button's accessibility
3406 this.$button.attr( 'tabindex', this.tabIndex );
3407 }
3408
3409 return OO.ui.mixin.ButtonElement.prototype.onMouseUp.call( this, e );
3410 };
3411
3412 /**
3413 * Get hyperlink location.
3414 *
3415 * @return {string} Hyperlink location
3416 */
3417 OO.ui.ButtonWidget.prototype.getHref = function () {
3418 return this.href;
3419 };
3420
3421 /**
3422 * Get hyperlink target.
3423 *
3424 * @return {string} Hyperlink target
3425 */
3426 OO.ui.ButtonWidget.prototype.getTarget = function () {
3427 return this.target;
3428 };
3429
3430 /**
3431 * Get search engine traversal hint.
3432 *
3433 * @return {boolean} Whether search engines should avoid traversing this hyperlink
3434 */
3435 OO.ui.ButtonWidget.prototype.getNoFollow = function () {
3436 return this.noFollow;
3437 };
3438
3439 /**
3440 * Set hyperlink location.
3441 *
3442 * @param {string|null} href Hyperlink location, null to remove
3443 */
3444 OO.ui.ButtonWidget.prototype.setHref = function ( href ) {
3445 href = typeof href === 'string' ? href : null;
3446 if ( href !== null && !OO.ui.isSafeUrl( href ) ) {
3447 href = './' + href;
3448 }
3449
3450 if ( href !== this.href ) {
3451 this.href = href;
3452 this.updateHref();
3453 }
3454
3455 return this;
3456 };
3457
3458 /**
3459 * Update the `href` attribute, in case of changes to href or
3460 * disabled state.
3461 *
3462 * @private
3463 * @chainable
3464 */
3465 OO.ui.ButtonWidget.prototype.updateHref = function () {
3466 if ( this.href !== null && !this.isDisabled() ) {
3467 this.$button.attr( 'href', this.href );
3468 } else {
3469 this.$button.removeAttr( 'href' );
3470 }
3471
3472 return this;
3473 };
3474
3475 /**
3476 * Handle disable events.
3477 *
3478 * @private
3479 * @param {boolean} disabled Element is disabled
3480 */
3481 OO.ui.ButtonWidget.prototype.onDisable = function () {
3482 this.updateHref();
3483 };
3484
3485 /**
3486 * Set hyperlink target.
3487 *
3488 * @param {string|null} target Hyperlink target, null to remove
3489 */
3490 OO.ui.ButtonWidget.prototype.setTarget = function ( target ) {
3491 target = typeof target === 'string' ? target : null;
3492
3493 if ( target !== this.target ) {
3494 this.target = target;
3495 if ( target !== null ) {
3496 this.$button.attr( 'target', target );
3497 } else {
3498 this.$button.removeAttr( 'target' );
3499 }
3500 }
3501
3502 return this;
3503 };
3504
3505 /**
3506 * Set search engine traversal hint.
3507 *
3508 * @param {boolean} noFollow True if search engines should avoid traversing this hyperlink
3509 */
3510 OO.ui.ButtonWidget.prototype.setNoFollow = function ( noFollow ) {
3511 noFollow = typeof noFollow === 'boolean' ? noFollow : true;
3512
3513 if ( noFollow !== this.noFollow ) {
3514 this.noFollow = noFollow;
3515 if ( noFollow ) {
3516 this.$button.attr( 'rel', 'nofollow' );
3517 } else {
3518 this.$button.removeAttr( 'rel' );
3519 }
3520 }
3521
3522 return this;
3523 };
3524
3525 /**
3526 * A ButtonGroupWidget groups related buttons and is used together with OO.ui.ButtonWidget and
3527 * its subclasses. Each button in a group is addressed by a unique reference. Buttons can be added,
3528 * removed, and cleared from the group.
3529 *
3530 * @example
3531 * // Example: A ButtonGroupWidget with two buttons
3532 * var button1 = new OO.ui.PopupButtonWidget( {
3533 * label: 'Select a category',
3534 * icon: 'menu',
3535 * popup: {
3536 * $content: $( '<p>List of categories...</p>' ),
3537 * padded: true,
3538 * align: 'left'
3539 * }
3540 * } );
3541 * var button2 = new OO.ui.ButtonWidget( {
3542 * label: 'Add item'
3543 * });
3544 * var buttonGroup = new OO.ui.ButtonGroupWidget( {
3545 * items: [button1, button2]
3546 * } );
3547 * $( 'body' ).append( buttonGroup.$element );
3548 *
3549 * @class
3550 * @extends OO.ui.Widget
3551 * @mixins OO.ui.mixin.GroupElement
3552 *
3553 * @constructor
3554 * @param {Object} [config] Configuration options
3555 * @cfg {OO.ui.ButtonWidget[]} [items] Buttons to add
3556 */
3557 OO.ui.ButtonGroupWidget = function OoUiButtonGroupWidget( config ) {
3558 // Configuration initialization
3559 config = config || {};
3560
3561 // Parent constructor
3562 OO.ui.ButtonGroupWidget.parent.call( this, config );
3563
3564 // Mixin constructors
3565 OO.ui.mixin.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) );
3566
3567 // Initialization
3568 this.$element.addClass( 'oo-ui-buttonGroupWidget' );
3569 if ( Array.isArray( config.items ) ) {
3570 this.addItems( config.items );
3571 }
3572 };
3573
3574 /* Setup */
3575
3576 OO.inheritClass( OO.ui.ButtonGroupWidget, OO.ui.Widget );
3577 OO.mixinClass( OO.ui.ButtonGroupWidget, OO.ui.mixin.GroupElement );
3578
3579 /**
3580 * IconWidget is a generic widget for {@link OO.ui.mixin.IconElement icons}. In general, IconWidgets should be used with OO.ui.LabelWidget,
3581 * which creates a label that identifies the icon’s function. See the [OOjs UI documentation on MediaWiki] [1]
3582 * for a list of icons included in the library.
3583 *
3584 * @example
3585 * // An icon widget with a label
3586 * var myIcon = new OO.ui.IconWidget( {
3587 * icon: 'help',
3588 * iconTitle: 'Help'
3589 * } );
3590 * // Create a label.
3591 * var iconLabel = new OO.ui.LabelWidget( {
3592 * label: 'Help'
3593 * } );
3594 * $( 'body' ).append( myIcon.$element, iconLabel.$element );
3595 *
3596 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
3597 *
3598 * @class
3599 * @extends OO.ui.Widget
3600 * @mixins OO.ui.mixin.IconElement
3601 * @mixins OO.ui.mixin.TitledElement
3602 * @mixins OO.ui.mixin.FlaggedElement
3603 *
3604 * @constructor
3605 * @param {Object} [config] Configuration options
3606 */
3607 OO.ui.IconWidget = function OoUiIconWidget( config ) {
3608 // Configuration initialization
3609 config = config || {};
3610
3611 // Parent constructor
3612 OO.ui.IconWidget.parent.call( this, config );
3613
3614 // Mixin constructors
3615 OO.ui.mixin.IconElement.call( this, $.extend( {}, config, { $icon: this.$element } ) );
3616 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$element } ) );
3617 OO.ui.mixin.FlaggedElement.call( this, $.extend( {}, config, { $flagged: this.$element } ) );
3618
3619 // Initialization
3620 this.$element.addClass( 'oo-ui-iconWidget' );
3621 };
3622
3623 /* Setup */
3624
3625 OO.inheritClass( OO.ui.IconWidget, OO.ui.Widget );
3626 OO.mixinClass( OO.ui.IconWidget, OO.ui.mixin.IconElement );
3627 OO.mixinClass( OO.ui.IconWidget, OO.ui.mixin.TitledElement );
3628 OO.mixinClass( OO.ui.IconWidget, OO.ui.mixin.FlaggedElement );
3629
3630 /* Static Properties */
3631
3632 OO.ui.IconWidget.static.tagName = 'span';
3633
3634 /**
3635 * IndicatorWidgets create indicators, which are small graphics that are generally used to draw
3636 * attention to the status of an item or to clarify the function of a control. For a list of
3637 * indicators included in the library, please see the [OOjs UI documentation on MediaWiki][1].
3638 *
3639 * @example
3640 * // Example of an indicator widget
3641 * var indicator1 = new OO.ui.IndicatorWidget( {
3642 * indicator: 'alert'
3643 * } );
3644 *
3645 * // Create a fieldset layout to add a label
3646 * var fieldset = new OO.ui.FieldsetLayout();
3647 * fieldset.addItems( [
3648 * new OO.ui.FieldLayout( indicator1, { label: 'An alert indicator:' } )
3649 * ] );
3650 * $( 'body' ).append( fieldset.$element );
3651 *
3652 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
3653 *
3654 * @class
3655 * @extends OO.ui.Widget
3656 * @mixins OO.ui.mixin.IndicatorElement
3657 * @mixins OO.ui.mixin.TitledElement
3658 *
3659 * @constructor
3660 * @param {Object} [config] Configuration options
3661 */
3662 OO.ui.IndicatorWidget = function OoUiIndicatorWidget( config ) {
3663 // Configuration initialization
3664 config = config || {};
3665
3666 // Parent constructor
3667 OO.ui.IndicatorWidget.parent.call( this, config );
3668
3669 // Mixin constructors
3670 OO.ui.mixin.IndicatorElement.call( this, $.extend( {}, config, { $indicator: this.$element } ) );
3671 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$element } ) );
3672
3673 // Initialization
3674 this.$element.addClass( 'oo-ui-indicatorWidget' );
3675 };
3676
3677 /* Setup */
3678
3679 OO.inheritClass( OO.ui.IndicatorWidget, OO.ui.Widget );
3680 OO.mixinClass( OO.ui.IndicatorWidget, OO.ui.mixin.IndicatorElement );
3681 OO.mixinClass( OO.ui.IndicatorWidget, OO.ui.mixin.TitledElement );
3682
3683 /* Static Properties */
3684
3685 OO.ui.IndicatorWidget.static.tagName = 'span';
3686
3687 /**
3688 * LabelWidgets help identify the function of interface elements. Each LabelWidget can
3689 * be configured with a `label` option that is set to a string, a label node, or a function:
3690 *
3691 * - String: a plaintext string
3692 * - jQuery selection: a jQuery selection, used for anything other than a plaintext label, e.g., a
3693 * label that includes a link or special styling, such as a gray color or additional graphical elements.
3694 * - Function: a function that will produce a string in the future. Functions are used
3695 * in cases where the value of the label is not currently defined.
3696 *
3697 * In addition, the LabelWidget can be associated with an {@link OO.ui.InputWidget input widget}, which
3698 * will come into focus when the label is clicked.
3699 *
3700 * @example
3701 * // Examples of LabelWidgets
3702 * var label1 = new OO.ui.LabelWidget( {
3703 * label: 'plaintext label'
3704 * } );
3705 * var label2 = new OO.ui.LabelWidget( {
3706 * label: $( '<a href="default.html">jQuery label</a>' )
3707 * } );
3708 * // Create a fieldset layout with fields for each example
3709 * var fieldset = new OO.ui.FieldsetLayout();
3710 * fieldset.addItems( [
3711 * new OO.ui.FieldLayout( label1 ),
3712 * new OO.ui.FieldLayout( label2 )
3713 * ] );
3714 * $( 'body' ).append( fieldset.$element );
3715 *
3716 * @class
3717 * @extends OO.ui.Widget
3718 * @mixins OO.ui.mixin.LabelElement
3719 *
3720 * @constructor
3721 * @param {Object} [config] Configuration options
3722 * @cfg {OO.ui.InputWidget} [input] {@link OO.ui.InputWidget Input widget} that uses the label.
3723 * Clicking the label will focus the specified input field.
3724 */
3725 OO.ui.LabelWidget = function OoUiLabelWidget( config ) {
3726 // Configuration initialization
3727 config = config || {};
3728
3729 // Parent constructor
3730 OO.ui.LabelWidget.parent.call( this, config );
3731
3732 // Mixin constructors
3733 OO.ui.mixin.LabelElement.call( this, $.extend( {}, config, { $label: this.$element } ) );
3734 OO.ui.mixin.TitledElement.call( this, config );
3735
3736 // Properties
3737 this.input = config.input;
3738
3739 // Events
3740 if ( this.input instanceof OO.ui.InputWidget ) {
3741 this.$element.on( 'click', this.onClick.bind( this ) );
3742 }
3743
3744 // Initialization
3745 this.$element.addClass( 'oo-ui-labelWidget' );
3746 };
3747
3748 /* Setup */
3749
3750 OO.inheritClass( OO.ui.LabelWidget, OO.ui.Widget );
3751 OO.mixinClass( OO.ui.LabelWidget, OO.ui.mixin.LabelElement );
3752 OO.mixinClass( OO.ui.LabelWidget, OO.ui.mixin.TitledElement );
3753
3754 /* Static Properties */
3755
3756 OO.ui.LabelWidget.static.tagName = 'span';
3757
3758 /* Methods */
3759
3760 /**
3761 * Handles label mouse click events.
3762 *
3763 * @private
3764 * @param {jQuery.Event} e Mouse click event
3765 */
3766 OO.ui.LabelWidget.prototype.onClick = function () {
3767 this.input.simulateLabelClick();
3768 return false;
3769 };
3770
3771 /**
3772 * PendingElement is a mixin that is used to create elements that notify users that something is happening
3773 * and that they should wait before proceeding. The pending state is visually represented with a pending
3774 * texture that appears in the head of a pending {@link OO.ui.ProcessDialog process dialog} or in the input
3775 * field of a {@link OO.ui.TextInputWidget text input widget}.
3776 *
3777 * Currently, {@link OO.ui.ActionWidget Action widgets}, which mix in this class, can also be marked as pending, but only when
3778 * used in {@link OO.ui.MessageDialog message dialogs}. The behavior is not currently supported for action widgets used
3779 * in process dialogs.
3780 *
3781 * @example
3782 * function MessageDialog( config ) {
3783 * MessageDialog.parent.call( this, config );
3784 * }
3785 * OO.inheritClass( MessageDialog, OO.ui.MessageDialog );
3786 *
3787 * MessageDialog.static.actions = [
3788 * { action: 'save', label: 'Done', flags: 'primary' },
3789 * { label: 'Cancel', flags: 'safe' }
3790 * ];
3791 *
3792 * MessageDialog.prototype.initialize = function () {
3793 * MessageDialog.parent.prototype.initialize.apply( this, arguments );
3794 * this.content = new OO.ui.PanelLayout( { $: this.$, padded: true } );
3795 * 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>' );
3796 * this.$body.append( this.content.$element );
3797 * };
3798 * MessageDialog.prototype.getBodyHeight = function () {
3799 * return 100;
3800 * }
3801 * MessageDialog.prototype.getActionProcess = function ( action ) {
3802 * var dialog = this;
3803 * if ( action === 'save' ) {
3804 * dialog.getActions().get({actions: 'save'})[0].pushPending();
3805 * return new OO.ui.Process()
3806 * .next( 1000 )
3807 * .next( function () {
3808 * dialog.getActions().get({actions: 'save'})[0].popPending();
3809 * } );
3810 * }
3811 * return MessageDialog.parent.prototype.getActionProcess.call( this, action );
3812 * };
3813 *
3814 * var windowManager = new OO.ui.WindowManager();
3815 * $( 'body' ).append( windowManager.$element );
3816 *
3817 * var dialog = new MessageDialog();
3818 * windowManager.addWindows( [ dialog ] );
3819 * windowManager.openWindow( dialog );
3820 *
3821 * @abstract
3822 * @class
3823 *
3824 * @constructor
3825 * @param {Object} [config] Configuration options
3826 * @cfg {jQuery} [$pending] Element to mark as pending, defaults to this.$element
3827 */
3828 OO.ui.mixin.PendingElement = function OoUiMixinPendingElement( config ) {
3829 // Configuration initialization
3830 config = config || {};
3831
3832 // Properties
3833 this.pending = 0;
3834 this.$pending = null;
3835
3836 // Initialisation
3837 this.setPendingElement( config.$pending || this.$element );
3838 };
3839
3840 /* Setup */
3841
3842 OO.initClass( OO.ui.mixin.PendingElement );
3843
3844 /* Methods */
3845
3846 /**
3847 * Set the pending element (and clean up any existing one).
3848 *
3849 * @param {jQuery} $pending The element to set to pending.
3850 */
3851 OO.ui.mixin.PendingElement.prototype.setPendingElement = function ( $pending ) {
3852 if ( this.$pending ) {
3853 this.$pending.removeClass( 'oo-ui-pendingElement-pending' );
3854 }
3855
3856 this.$pending = $pending;
3857 if ( this.pending > 0 ) {
3858 this.$pending.addClass( 'oo-ui-pendingElement-pending' );
3859 }
3860 };
3861
3862 /**
3863 * Check if an element is pending.
3864 *
3865 * @return {boolean} Element is pending
3866 */
3867 OO.ui.mixin.PendingElement.prototype.isPending = function () {
3868 return !!this.pending;
3869 };
3870
3871 /**
3872 * Increase the pending counter. The pending state will remain active until the counter is zero
3873 * (i.e., the number of calls to #pushPending and #popPending is the same).
3874 *
3875 * @chainable
3876 */
3877 OO.ui.mixin.PendingElement.prototype.pushPending = function () {
3878 if ( this.pending === 0 ) {
3879 this.$pending.addClass( 'oo-ui-pendingElement-pending' );
3880 this.updateThemeClasses();
3881 }
3882 this.pending++;
3883
3884 return this;
3885 };
3886
3887 /**
3888 * Decrease the pending counter. The pending state will remain active until the counter is zero
3889 * (i.e., the number of calls to #pushPending and #popPending is the same).
3890 *
3891 * @chainable
3892 */
3893 OO.ui.mixin.PendingElement.prototype.popPending = function () {
3894 if ( this.pending === 1 ) {
3895 this.$pending.removeClass( 'oo-ui-pendingElement-pending' );
3896 this.updateThemeClasses();
3897 }
3898 this.pending = Math.max( 0, this.pending - 1 );
3899
3900 return this;
3901 };
3902
3903 /**
3904 * Element that can be automatically clipped to visible boundaries.
3905 *
3906 * Whenever the element's natural height changes, you have to call
3907 * {@link OO.ui.mixin.ClippableElement#clip} to make sure it's still
3908 * clipping correctly.
3909 *
3910 * The dimensions of #$clippableContainer will be compared to the boundaries of the
3911 * nearest scrollable container. If #$clippableContainer is too tall and/or too wide,
3912 * then #$clippable will be given a fixed reduced height and/or width and will be made
3913 * scrollable. By default, #$clippable and #$clippableContainer are the same element,
3914 * but you can build a static footer by setting #$clippableContainer to an element that contains
3915 * #$clippable and the footer.
3916 *
3917 * @abstract
3918 * @class
3919 *
3920 * @constructor
3921 * @param {Object} [config] Configuration options
3922 * @cfg {jQuery} [$clippable] Node to clip, assigned to #$clippable, omit to use #$element
3923 * @cfg {jQuery} [$clippableContainer] Node to keep visible, assigned to #$clippableContainer,
3924 * omit to use #$clippable
3925 */
3926 OO.ui.mixin.ClippableElement = function OoUiMixinClippableElement( config ) {
3927 // Configuration initialization
3928 config = config || {};
3929
3930 // Properties
3931 this.$clippable = null;
3932 this.$clippableContainer = null;
3933 this.clipping = false;
3934 this.clippedHorizontally = false;
3935 this.clippedVertically = false;
3936 this.$clippableScrollableContainer = null;
3937 this.$clippableScroller = null;
3938 this.$clippableWindow = null;
3939 this.idealWidth = null;
3940 this.idealHeight = null;
3941 this.onClippableScrollHandler = this.clip.bind( this );
3942 this.onClippableWindowResizeHandler = this.clip.bind( this );
3943
3944 // Initialization
3945 if ( config.$clippableContainer ) {
3946 this.setClippableContainer( config.$clippableContainer );
3947 }
3948 this.setClippableElement( config.$clippable || this.$element );
3949 };
3950
3951 /* Methods */
3952
3953 /**
3954 * Set clippable element.
3955 *
3956 * If an element is already set, it will be cleaned up before setting up the new element.
3957 *
3958 * @param {jQuery} $clippable Element to make clippable
3959 */
3960 OO.ui.mixin.ClippableElement.prototype.setClippableElement = function ( $clippable ) {
3961 if ( this.$clippable ) {
3962 this.$clippable.removeClass( 'oo-ui-clippableElement-clippable' );
3963 this.$clippable.css( { width: '', height: '', overflowX: '', overflowY: '' } );
3964 OO.ui.Element.static.reconsiderScrollbars( this.$clippable[ 0 ] );
3965 }
3966
3967 this.$clippable = $clippable.addClass( 'oo-ui-clippableElement-clippable' );
3968 this.clip();
3969 };
3970
3971 /**
3972 * Set clippable container.
3973 *
3974 * This is the container that will be measured when deciding whether to clip. When clipping,
3975 * #$clippable will be resized in order to keep the clippable container fully visible.
3976 *
3977 * If the clippable container is unset, #$clippable will be used.
3978 *
3979 * @param {jQuery|null} $clippableContainer Container to keep visible, or null to unset
3980 */
3981 OO.ui.mixin.ClippableElement.prototype.setClippableContainer = function ( $clippableContainer ) {
3982 this.$clippableContainer = $clippableContainer;
3983 if ( this.$clippable ) {
3984 this.clip();
3985 }
3986 };
3987
3988 /**
3989 * Toggle clipping.
3990 *
3991 * Do not turn clipping on until after the element is attached to the DOM and visible.
3992 *
3993 * @param {boolean} [clipping] Enable clipping, omit to toggle
3994 * @chainable
3995 */
3996 OO.ui.mixin.ClippableElement.prototype.toggleClipping = function ( clipping ) {
3997 clipping = clipping === undefined ? !this.clipping : !!clipping;
3998
3999 if ( this.clipping !== clipping ) {
4000 this.clipping = clipping;
4001 if ( clipping ) {
4002 this.$clippableScrollableContainer = $( this.getClosestScrollableElementContainer() );
4003 // If the clippable container is the root, we have to listen to scroll events and check
4004 // jQuery.scrollTop on the window because of browser inconsistencies
4005 this.$clippableScroller = this.$clippableScrollableContainer.is( 'html, body' ) ?
4006 $( OO.ui.Element.static.getWindow( this.$clippableScrollableContainer ) ) :
4007 this.$clippableScrollableContainer;
4008 this.$clippableScroller.on( 'scroll', this.onClippableScrollHandler );
4009 this.$clippableWindow = $( this.getElementWindow() )
4010 .on( 'resize', this.onClippableWindowResizeHandler );
4011 // Initial clip after visible
4012 this.clip();
4013 } else {
4014 this.$clippable.css( { width: '', height: '', overflowX: '', overflowY: '' } );
4015 OO.ui.Element.static.reconsiderScrollbars( this.$clippable[ 0 ] );
4016
4017 this.$clippableScrollableContainer = null;
4018 this.$clippableScroller.off( 'scroll', this.onClippableScrollHandler );
4019 this.$clippableScroller = null;
4020 this.$clippableWindow.off( 'resize', this.onClippableWindowResizeHandler );
4021 this.$clippableWindow = null;
4022 }
4023 }
4024
4025 return this;
4026 };
4027
4028 /**
4029 * Check if the element will be clipped to fit the visible area of the nearest scrollable container.
4030 *
4031 * @return {boolean} Element will be clipped to the visible area
4032 */
4033 OO.ui.mixin.ClippableElement.prototype.isClipping = function () {
4034 return this.clipping;
4035 };
4036
4037 /**
4038 * Check if the bottom or right of the element is being clipped by the nearest scrollable container.
4039 *
4040 * @return {boolean} Part of the element is being clipped
4041 */
4042 OO.ui.mixin.ClippableElement.prototype.isClipped = function () {
4043 return this.clippedHorizontally || this.clippedVertically;
4044 };
4045
4046 /**
4047 * Check if the right of the element is being clipped by the nearest scrollable container.
4048 *
4049 * @return {boolean} Part of the element is being clipped
4050 */
4051 OO.ui.mixin.ClippableElement.prototype.isClippedHorizontally = function () {
4052 return this.clippedHorizontally;
4053 };
4054
4055 /**
4056 * Check if the bottom of the element is being clipped by the nearest scrollable container.
4057 *
4058 * @return {boolean} Part of the element is being clipped
4059 */
4060 OO.ui.mixin.ClippableElement.prototype.isClippedVertically = function () {
4061 return this.clippedVertically;
4062 };
4063
4064 /**
4065 * Set the ideal size. These are the dimensions the element will have when it's not being clipped.
4066 *
4067 * @param {number|string} [width] Width as a number of pixels or CSS string with unit suffix
4068 * @param {number|string} [height] Height as a number of pixels or CSS string with unit suffix
4069 */
4070 OO.ui.mixin.ClippableElement.prototype.setIdealSize = function ( width, height ) {
4071 this.idealWidth = width;
4072 this.idealHeight = height;
4073
4074 if ( !this.clipping ) {
4075 // Update dimensions
4076 this.$clippable.css( { width: width, height: height } );
4077 }
4078 // While clipping, idealWidth and idealHeight are not considered
4079 };
4080
4081 /**
4082 * Clip element to visible boundaries and allow scrolling when needed. You should call this method
4083 * when the element's natural height changes.
4084 *
4085 * Element will be clipped the bottom or right of the element is within 10px of the edge of, or
4086 * overlapped by, the visible area of the nearest scrollable container.
4087 *
4088 * Because calling clip() when the natural height changes isn't always possible, we also set
4089 * max-height when the element isn't being clipped. This means that if the element tries to grow
4090 * beyond the edge, something reasonable will happen before clip() is called.
4091 *
4092 * @chainable
4093 */
4094 OO.ui.mixin.ClippableElement.prototype.clip = function () {
4095 var $container, extraHeight, extraWidth, ccOffset,
4096 $scrollableContainer, scOffset, scHeight, scWidth,
4097 ccWidth, scrollerIsWindow, scrollTop, scrollLeft,
4098 desiredWidth, desiredHeight, allotedWidth, allotedHeight,
4099 naturalWidth, naturalHeight, clipWidth, clipHeight,
4100 buffer = 7; // Chosen by fair dice roll
4101
4102 if ( !this.clipping ) {
4103 // this.$clippableScrollableContainer and this.$clippableWindow are null, so the below will fail
4104 return this;
4105 }
4106
4107 $container = this.$clippableContainer || this.$clippable;
4108 extraHeight = $container.outerHeight() - this.$clippable.outerHeight();
4109 extraWidth = $container.outerWidth() - this.$clippable.outerWidth();
4110 ccOffset = $container.offset();
4111 $scrollableContainer = this.$clippableScrollableContainer.is( 'html, body' ) ?
4112 this.$clippableWindow : this.$clippableScrollableContainer;
4113 scOffset = $scrollableContainer.offset() || { top: 0, left: 0 };
4114 scHeight = $scrollableContainer.innerHeight() - buffer;
4115 scWidth = $scrollableContainer.innerWidth() - buffer;
4116 ccWidth = $container.outerWidth() + buffer;
4117 scrollerIsWindow = this.$clippableScroller[ 0 ] === this.$clippableWindow[ 0 ];
4118 scrollTop = scrollerIsWindow ? this.$clippableScroller.scrollTop() : 0;
4119 scrollLeft = scrollerIsWindow ? this.$clippableScroller.scrollLeft() : 0;
4120 desiredWidth = ccOffset.left < 0 ?
4121 ccWidth + ccOffset.left :
4122 ( scOffset.left + scrollLeft + scWidth ) - ccOffset.left;
4123 desiredHeight = ( scOffset.top + scrollTop + scHeight ) - ccOffset.top;
4124 // It should never be desirable to exceed the dimensions of the browser viewport... right?
4125 desiredWidth = Math.min( desiredWidth, document.documentElement.clientWidth );
4126 desiredHeight = Math.min( desiredHeight, document.documentElement.clientHeight );
4127 allotedWidth = Math.ceil( desiredWidth - extraWidth );
4128 allotedHeight = Math.ceil( desiredHeight - extraHeight );
4129 naturalWidth = this.$clippable.prop( 'scrollWidth' );
4130 naturalHeight = this.$clippable.prop( 'scrollHeight' );
4131 clipWidth = allotedWidth < naturalWidth;
4132 clipHeight = allotedHeight < naturalHeight;
4133
4134 if ( clipWidth ) {
4135 this.$clippable.css( {
4136 overflowX: 'scroll',
4137 width: Math.max( 0, allotedWidth ),
4138 maxWidth: ''
4139 } );
4140 } else {
4141 this.$clippable.css( {
4142 overflowX: '',
4143 width: this.idealWidth ? this.idealWidth - extraWidth : '',
4144 maxWidth: Math.max( 0, allotedWidth )
4145 } );
4146 }
4147 if ( clipHeight ) {
4148 this.$clippable.css( {
4149 overflowY: 'scroll',
4150 height: Math.max( 0, allotedHeight ),
4151 maxHeight: ''
4152 } );
4153 } else {
4154 this.$clippable.css( {
4155 overflowY: '',
4156 height: this.idealHeight ? this.idealHeight - extraHeight : '',
4157 maxHeight: Math.max( 0, allotedHeight )
4158 } );
4159 }
4160
4161 // If we stopped clipping in at least one of the dimensions
4162 if ( ( this.clippedHorizontally && !clipWidth ) || ( this.clippedVertically && !clipHeight ) ) {
4163 OO.ui.Element.static.reconsiderScrollbars( this.$clippable[ 0 ] );
4164 }
4165
4166 this.clippedHorizontally = clipWidth;
4167 this.clippedVertically = clipHeight;
4168
4169 return this;
4170 };
4171
4172 /**
4173 * PopupWidget is a container for content. The popup is overlaid and positioned absolutely.
4174 * By default, each popup has an anchor that points toward its origin.
4175 * Please see the [OOjs UI documentation on Mediawiki] [1] for more information and examples.
4176 *
4177 * @example
4178 * // A popup widget.
4179 * var popup = new OO.ui.PopupWidget( {
4180 * $content: $( '<p>Hi there!</p>' ),
4181 * padded: true,
4182 * width: 300
4183 * } );
4184 *
4185 * $( 'body' ).append( popup.$element );
4186 * // To display the popup, toggle the visibility to 'true'.
4187 * popup.toggle( true );
4188 *
4189 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups
4190 *
4191 * @class
4192 * @extends OO.ui.Widget
4193 * @mixins OO.ui.mixin.LabelElement
4194 * @mixins OO.ui.mixin.ClippableElement
4195 *
4196 * @constructor
4197 * @param {Object} [config] Configuration options
4198 * @cfg {number} [width=320] Width of popup in pixels
4199 * @cfg {number} [height] Height of popup in pixels. Omit to use the automatic height.
4200 * @cfg {boolean} [anchor=true] Show anchor pointing to origin of popup
4201 * @cfg {string} [align='center'] Alignment of the popup: `center`, `force-left`, `force-right`, `backwards` or `forwards`.
4202 * If the popup is forced-left the popup body is leaning towards the left. For force-right alignment, the body of the
4203 * popup is leaning towards the right of the screen.
4204 * Using 'backwards' is a logical direction which will result in the popup leaning towards the beginning of the sentence
4205 * in the given language, which means it will flip to the correct positioning in right-to-left languages.
4206 * Using 'forward' will also result in a logical alignment where the body of the popup leans towards the end of the
4207 * sentence in the given language.
4208 * @cfg {jQuery} [$container] Constrain the popup to the boundaries of the specified container.
4209 * See the [OOjs UI docs on MediaWiki][3] for an example.
4210 * [3]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups#containerExample
4211 * @cfg {number} [containerPadding=10] Padding between the popup and its container, specified as a number of pixels.
4212 * @cfg {jQuery} [$content] Content to append to the popup's body
4213 * @cfg {jQuery} [$footer] Content to append to the popup's footer
4214 * @cfg {boolean} [autoClose=false] Automatically close the popup when it loses focus.
4215 * @cfg {jQuery} [$autoCloseIgnore] Elements that will not close the popup when clicked.
4216 * This config option is only relevant if #autoClose is set to `true`. See the [OOjs UI docs on MediaWiki][2]
4217 * for an example.
4218 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups#autocloseExample
4219 * @cfg {boolean} [head=false] Show a popup header that contains a #label (if specified) and close
4220 * button.
4221 * @cfg {boolean} [padded=false] Add padding to the popup's body
4222 */
4223 OO.ui.PopupWidget = function OoUiPopupWidget( config ) {
4224 // Configuration initialization
4225 config = config || {};
4226
4227 // Parent constructor
4228 OO.ui.PopupWidget.parent.call( this, config );
4229
4230 // Properties (must be set before ClippableElement constructor call)
4231 this.$body = $( '<div>' );
4232 this.$popup = $( '<div>' );
4233
4234 // Mixin constructors
4235 OO.ui.mixin.LabelElement.call( this, config );
4236 OO.ui.mixin.ClippableElement.call( this, $.extend( {}, config, {
4237 $clippable: this.$body,
4238 $clippableContainer: this.$popup
4239 } ) );
4240
4241 // Properties
4242 this.$anchor = $( '<div>' );
4243 // If undefined, will be computed lazily in updateDimensions()
4244 this.$container = config.$container;
4245 this.containerPadding = config.containerPadding !== undefined ? config.containerPadding : 10;
4246 this.autoClose = !!config.autoClose;
4247 this.$autoCloseIgnore = config.$autoCloseIgnore;
4248 this.transitionTimeout = null;
4249 this.anchor = null;
4250 this.width = config.width !== undefined ? config.width : 320;
4251 this.height = config.height !== undefined ? config.height : null;
4252 this.setAlignment( config.align );
4253 this.onMouseDownHandler = this.onMouseDown.bind( this );
4254 this.onDocumentKeyDownHandler = this.onDocumentKeyDown.bind( this );
4255
4256 // Initialization
4257 this.toggleAnchor( config.anchor === undefined || config.anchor );
4258 this.$body.addClass( 'oo-ui-popupWidget-body' );
4259 this.$anchor.addClass( 'oo-ui-popupWidget-anchor' );
4260 this.$popup
4261 .addClass( 'oo-ui-popupWidget-popup' )
4262 .append( this.$body );
4263 this.$element
4264 .addClass( 'oo-ui-popupWidget' )
4265 .append( this.$popup, this.$anchor );
4266 // Move content, which was added to #$element by OO.ui.Widget, to the body
4267 // FIXME This is gross, we should use '$body' or something for the config
4268 if ( config.$content instanceof jQuery ) {
4269 this.$body.append( config.$content );
4270 }
4271
4272 if ( config.padded ) {
4273 this.$body.addClass( 'oo-ui-popupWidget-body-padded' );
4274 }
4275
4276 if ( config.head ) {
4277 this.closeButton = new OO.ui.ButtonWidget( { framed: false, icon: 'close' } );
4278 this.closeButton.connect( this, { click: 'onCloseButtonClick' } );
4279 this.$head = $( '<div>' )
4280 .addClass( 'oo-ui-popupWidget-head' )
4281 .append( this.$label, this.closeButton.$element );
4282 this.$popup.prepend( this.$head );
4283 }
4284
4285 if ( config.$footer ) {
4286 this.$footer = $( '<div>' )
4287 .addClass( 'oo-ui-popupWidget-footer' )
4288 .append( config.$footer );
4289 this.$popup.append( this.$footer );
4290 }
4291
4292 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
4293 // that reference properties not initialized at that time of parent class construction
4294 // TODO: Find a better way to handle post-constructor setup
4295 this.visible = false;
4296 this.$element.addClass( 'oo-ui-element-hidden' );
4297 };
4298
4299 /* Setup */
4300
4301 OO.inheritClass( OO.ui.PopupWidget, OO.ui.Widget );
4302 OO.mixinClass( OO.ui.PopupWidget, OO.ui.mixin.LabelElement );
4303 OO.mixinClass( OO.ui.PopupWidget, OO.ui.mixin.ClippableElement );
4304
4305 /* Methods */
4306
4307 /**
4308 * Handles mouse down events.
4309 *
4310 * @private
4311 * @param {MouseEvent} e Mouse down event
4312 */
4313 OO.ui.PopupWidget.prototype.onMouseDown = function ( e ) {
4314 if (
4315 this.isVisible() &&
4316 !$.contains( this.$element[ 0 ], e.target ) &&
4317 ( !this.$autoCloseIgnore || !this.$autoCloseIgnore.has( e.target ).length )
4318 ) {
4319 this.toggle( false );
4320 }
4321 };
4322
4323 /**
4324 * Bind mouse down listener.
4325 *
4326 * @private
4327 */
4328 OO.ui.PopupWidget.prototype.bindMouseDownListener = function () {
4329 // Capture clicks outside popup
4330 this.getElementWindow().addEventListener( 'mousedown', this.onMouseDownHandler, true );
4331 };
4332
4333 /**
4334 * Handles close button click events.
4335 *
4336 * @private
4337 */
4338 OO.ui.PopupWidget.prototype.onCloseButtonClick = function () {
4339 if ( this.isVisible() ) {
4340 this.toggle( false );
4341 }
4342 };
4343
4344 /**
4345 * Unbind mouse down listener.
4346 *
4347 * @private
4348 */
4349 OO.ui.PopupWidget.prototype.unbindMouseDownListener = function () {
4350 this.getElementWindow().removeEventListener( 'mousedown', this.onMouseDownHandler, true );
4351 };
4352
4353 /**
4354 * Handles key down events.
4355 *
4356 * @private
4357 * @param {KeyboardEvent} e Key down event
4358 */
4359 OO.ui.PopupWidget.prototype.onDocumentKeyDown = function ( e ) {
4360 if (
4361 e.which === OO.ui.Keys.ESCAPE &&
4362 this.isVisible()
4363 ) {
4364 this.toggle( false );
4365 e.preventDefault();
4366 e.stopPropagation();
4367 }
4368 };
4369
4370 /**
4371 * Bind key down listener.
4372 *
4373 * @private
4374 */
4375 OO.ui.PopupWidget.prototype.bindKeyDownListener = function () {
4376 this.getElementWindow().addEventListener( 'keydown', this.onDocumentKeyDownHandler, true );
4377 };
4378
4379 /**
4380 * Unbind key down listener.
4381 *
4382 * @private
4383 */
4384 OO.ui.PopupWidget.prototype.unbindKeyDownListener = function () {
4385 this.getElementWindow().removeEventListener( 'keydown', this.onDocumentKeyDownHandler, true );
4386 };
4387
4388 /**
4389 * Show, hide, or toggle the visibility of the anchor.
4390 *
4391 * @param {boolean} [show] Show anchor, omit to toggle
4392 */
4393 OO.ui.PopupWidget.prototype.toggleAnchor = function ( show ) {
4394 show = show === undefined ? !this.anchored : !!show;
4395
4396 if ( this.anchored !== show ) {
4397 if ( show ) {
4398 this.$element.addClass( 'oo-ui-popupWidget-anchored' );
4399 } else {
4400 this.$element.removeClass( 'oo-ui-popupWidget-anchored' );
4401 }
4402 this.anchored = show;
4403 }
4404 };
4405
4406 /**
4407 * Check if the anchor is visible.
4408 *
4409 * @return {boolean} Anchor is visible
4410 */
4411 OO.ui.PopupWidget.prototype.hasAnchor = function () {
4412 return this.anchor;
4413 };
4414
4415 /**
4416 * @inheritdoc
4417 */
4418 OO.ui.PopupWidget.prototype.toggle = function ( show ) {
4419 var change;
4420 show = show === undefined ? !this.isVisible() : !!show;
4421
4422 change = show !== this.isVisible();
4423
4424 // Parent method
4425 OO.ui.PopupWidget.parent.prototype.toggle.call( this, show );
4426
4427 if ( change ) {
4428 if ( show ) {
4429 if ( this.autoClose ) {
4430 this.bindMouseDownListener();
4431 this.bindKeyDownListener();
4432 }
4433 this.updateDimensions();
4434 this.toggleClipping( true );
4435 } else {
4436 this.toggleClipping( false );
4437 if ( this.autoClose ) {
4438 this.unbindMouseDownListener();
4439 this.unbindKeyDownListener();
4440 }
4441 }
4442 }
4443
4444 return this;
4445 };
4446
4447 /**
4448 * Set the size of the popup.
4449 *
4450 * Changing the size may also change the popup's position depending on the alignment.
4451 *
4452 * @param {number} width Width in pixels
4453 * @param {number} height Height in pixels
4454 * @param {boolean} [transition=false] Use a smooth transition
4455 * @chainable
4456 */
4457 OO.ui.PopupWidget.prototype.setSize = function ( width, height, transition ) {
4458 this.width = width;
4459 this.height = height !== undefined ? height : null;
4460 if ( this.isVisible() ) {
4461 this.updateDimensions( transition );
4462 }
4463 };
4464
4465 /**
4466 * Update the size and position.
4467 *
4468 * Only use this to keep the popup properly anchored. Use #setSize to change the size, and this will
4469 * be called automatically.
4470 *
4471 * @param {boolean} [transition=false] Use a smooth transition
4472 * @chainable
4473 */
4474 OO.ui.PopupWidget.prototype.updateDimensions = function ( transition ) {
4475 var popupOffset, originOffset, containerLeft, containerWidth, containerRight,
4476 popupLeft, popupRight, overlapLeft, overlapRight, anchorWidth,
4477 align = this.align,
4478 widget = this;
4479
4480 if ( !this.$container ) {
4481 // Lazy-initialize $container if not specified in constructor
4482 this.$container = $( this.getClosestScrollableElementContainer() );
4483 }
4484
4485 // Set height and width before measuring things, since it might cause our measurements
4486 // to change (e.g. due to scrollbars appearing or disappearing)
4487 this.$popup.css( {
4488 width: this.width,
4489 height: this.height !== null ? this.height : 'auto'
4490 } );
4491
4492 // If we are in RTL, we need to flip the alignment, unless it is center
4493 if ( align === 'forwards' || align === 'backwards' ) {
4494 if ( this.$container.css( 'direction' ) === 'rtl' ) {
4495 align = ( { forwards: 'force-left', backwards: 'force-right' } )[ this.align ];
4496 } else {
4497 align = ( { forwards: 'force-right', backwards: 'force-left' } )[ this.align ];
4498 }
4499
4500 }
4501
4502 // Compute initial popupOffset based on alignment
4503 popupOffset = this.width * ( { 'force-left': -1, center: -0.5, 'force-right': 0 } )[ align ];
4504
4505 // Figure out if this will cause the popup to go beyond the edge of the container
4506 originOffset = this.$element.offset().left;
4507 containerLeft = this.$container.offset().left;
4508 containerWidth = this.$container.innerWidth();
4509 containerRight = containerLeft + containerWidth;
4510 popupLeft = popupOffset - this.containerPadding;
4511 popupRight = popupOffset + this.containerPadding + this.width + this.containerPadding;
4512 overlapLeft = ( originOffset + popupLeft ) - containerLeft;
4513 overlapRight = containerRight - ( originOffset + popupRight );
4514
4515 // Adjust offset to make the popup not go beyond the edge, if needed
4516 if ( overlapRight < 0 ) {
4517 popupOffset += overlapRight;
4518 } else if ( overlapLeft < 0 ) {
4519 popupOffset -= overlapLeft;
4520 }
4521
4522 // Adjust offset to avoid anchor being rendered too close to the edge
4523 // $anchor.width() doesn't work with the pure CSS anchor (returns 0)
4524 // TODO: Find a measurement that works for CSS anchors and image anchors
4525 anchorWidth = this.$anchor[ 0 ].scrollWidth * 2;
4526 if ( popupOffset + this.width < anchorWidth ) {
4527 popupOffset = anchorWidth - this.width;
4528 } else if ( -popupOffset < anchorWidth ) {
4529 popupOffset = -anchorWidth;
4530 }
4531
4532 // Prevent transition from being interrupted
4533 clearTimeout( this.transitionTimeout );
4534 if ( transition ) {
4535 // Enable transition
4536 this.$element.addClass( 'oo-ui-popupWidget-transitioning' );
4537 }
4538
4539 // Position body relative to anchor
4540 this.$popup.css( 'margin-left', popupOffset );
4541
4542 if ( transition ) {
4543 // Prevent transitioning after transition is complete
4544 this.transitionTimeout = setTimeout( function () {
4545 widget.$element.removeClass( 'oo-ui-popupWidget-transitioning' );
4546 }, 200 );
4547 } else {
4548 // Prevent transitioning immediately
4549 this.$element.removeClass( 'oo-ui-popupWidget-transitioning' );
4550 }
4551
4552 // Reevaluate clipping state since we've relocated and resized the popup
4553 this.clip();
4554
4555 return this;
4556 };
4557
4558 /**
4559 * Set popup alignment
4560 *
4561 * @param {string} align Alignment of the popup, `center`, `force-left`, `force-right`,
4562 * `backwards` or `forwards`.
4563 */
4564 OO.ui.PopupWidget.prototype.setAlignment = function ( align ) {
4565 // Validate alignment and transform deprecated values
4566 if ( [ 'left', 'right', 'force-left', 'force-right', 'backwards', 'forwards', 'center' ].indexOf( align ) > -1 ) {
4567 this.align = { left: 'force-right', right: 'force-left' }[ align ] || align;
4568 } else {
4569 this.align = 'center';
4570 }
4571 };
4572
4573 /**
4574 * Get popup alignment
4575 *
4576 * @return {string} align Alignment of the popup, `center`, `force-left`, `force-right`,
4577 * `backwards` or `forwards`.
4578 */
4579 OO.ui.PopupWidget.prototype.getAlignment = function () {
4580 return this.align;
4581 };
4582
4583 /**
4584 * PopupElement is mixed into other classes to generate a {@link OO.ui.PopupWidget popup widget}.
4585 * A popup is a container for content. It is overlaid and positioned absolutely. By default, each
4586 * popup has an anchor, which is an arrow-like protrusion that points toward the popup’s origin.
4587 * See {@link OO.ui.PopupWidget PopupWidget} for an example.
4588 *
4589 * @abstract
4590 * @class
4591 *
4592 * @constructor
4593 * @param {Object} [config] Configuration options
4594 * @cfg {Object} [popup] Configuration to pass to popup
4595 * @cfg {boolean} [popup.autoClose=true] Popup auto-closes when it loses focus
4596 */
4597 OO.ui.mixin.PopupElement = function OoUiMixinPopupElement( config ) {
4598 // Configuration initialization
4599 config = config || {};
4600
4601 // Properties
4602 this.popup = new OO.ui.PopupWidget( $.extend(
4603 { autoClose: true },
4604 config.popup,
4605 { $autoCloseIgnore: this.$element }
4606 ) );
4607 };
4608
4609 /* Methods */
4610
4611 /**
4612 * Get popup.
4613 *
4614 * @return {OO.ui.PopupWidget} Popup widget
4615 */
4616 OO.ui.mixin.PopupElement.prototype.getPopup = function () {
4617 return this.popup;
4618 };
4619
4620 /**
4621 * PopupButtonWidgets toggle the visibility of a contained {@link OO.ui.PopupWidget PopupWidget},
4622 * which is used to display additional information or options.
4623 *
4624 * @example
4625 * // Example of a popup button.
4626 * var popupButton = new OO.ui.PopupButtonWidget( {
4627 * label: 'Popup button with options',
4628 * icon: 'menu',
4629 * popup: {
4630 * $content: $( '<p>Additional options here.</p>' ),
4631 * padded: true,
4632 * align: 'force-left'
4633 * }
4634 * } );
4635 * // Append the button to the DOM.
4636 * $( 'body' ).append( popupButton.$element );
4637 *
4638 * @class
4639 * @extends OO.ui.ButtonWidget
4640 * @mixins OO.ui.mixin.PopupElement
4641 *
4642 * @constructor
4643 * @param {Object} [config] Configuration options
4644 */
4645 OO.ui.PopupButtonWidget = function OoUiPopupButtonWidget( config ) {
4646 // Parent constructor
4647 OO.ui.PopupButtonWidget.parent.call( this, config );
4648
4649 // Mixin constructors
4650 OO.ui.mixin.PopupElement.call( this, config );
4651
4652 // Events
4653 this.connect( this, { click: 'onAction' } );
4654
4655 // Initialization
4656 this.$element
4657 .addClass( 'oo-ui-popupButtonWidget' )
4658 .attr( 'aria-haspopup', 'true' )
4659 .append( this.popup.$element );
4660 };
4661
4662 /* Setup */
4663
4664 OO.inheritClass( OO.ui.PopupButtonWidget, OO.ui.ButtonWidget );
4665 OO.mixinClass( OO.ui.PopupButtonWidget, OO.ui.mixin.PopupElement );
4666
4667 /* Methods */
4668
4669 /**
4670 * Handle the button action being triggered.
4671 *
4672 * @private
4673 */
4674 OO.ui.PopupButtonWidget.prototype.onAction = function () {
4675 this.popup.toggle();
4676 };
4677
4678 /**
4679 * Mixin for OO.ui.Widget subclasses to provide OO.ui.mixin.GroupElement.
4680 *
4681 * Use together with OO.ui.mixin.ItemWidget to make disabled state inheritable.
4682 *
4683 * @private
4684 * @abstract
4685 * @class
4686 * @extends OO.ui.mixin.GroupElement
4687 *
4688 * @constructor
4689 * @param {Object} [config] Configuration options
4690 */
4691 OO.ui.mixin.GroupWidget = function OoUiMixinGroupWidget( config ) {
4692 // Parent constructor
4693 OO.ui.mixin.GroupWidget.parent.call( this, config );
4694 };
4695
4696 /* Setup */
4697
4698 OO.inheritClass( OO.ui.mixin.GroupWidget, OO.ui.mixin.GroupElement );
4699
4700 /* Methods */
4701
4702 /**
4703 * Set the disabled state of the widget.
4704 *
4705 * This will also update the disabled state of child widgets.
4706 *
4707 * @param {boolean} disabled Disable widget
4708 * @chainable
4709 */
4710 OO.ui.mixin.GroupWidget.prototype.setDisabled = function ( disabled ) {
4711 var i, len;
4712
4713 // Parent method
4714 // Note: Calling #setDisabled this way assumes this is mixed into an OO.ui.Widget
4715 OO.ui.Widget.prototype.setDisabled.call( this, disabled );
4716
4717 // During construction, #setDisabled is called before the OO.ui.mixin.GroupElement constructor
4718 if ( this.items ) {
4719 for ( i = 0, len = this.items.length; i < len; i++ ) {
4720 this.items[ i ].updateDisabled();
4721 }
4722 }
4723
4724 return this;
4725 };
4726
4727 /**
4728 * Mixin for widgets used as items in widgets that mix in OO.ui.mixin.GroupWidget.
4729 *
4730 * Item widgets have a reference to a OO.ui.mixin.GroupWidget while they are attached to the group. This
4731 * allows bidirectional communication.
4732 *
4733 * Use together with OO.ui.mixin.GroupWidget to make disabled state inheritable.
4734 *
4735 * @private
4736 * @abstract
4737 * @class
4738 *
4739 * @constructor
4740 */
4741 OO.ui.mixin.ItemWidget = function OoUiMixinItemWidget() {
4742 //
4743 };
4744
4745 /* Methods */
4746
4747 /**
4748 * Check if widget is disabled.
4749 *
4750 * Checks parent if present, making disabled state inheritable.
4751 *
4752 * @return {boolean} Widget is disabled
4753 */
4754 OO.ui.mixin.ItemWidget.prototype.isDisabled = function () {
4755 return this.disabled ||
4756 ( this.elementGroup instanceof OO.ui.Widget && this.elementGroup.isDisabled() );
4757 };
4758
4759 /**
4760 * Set group element is in.
4761 *
4762 * @param {OO.ui.mixin.GroupElement|null} group Group element, null if none
4763 * @chainable
4764 */
4765 OO.ui.mixin.ItemWidget.prototype.setElementGroup = function ( group ) {
4766 // Parent method
4767 // Note: Calling #setElementGroup this way assumes this is mixed into an OO.ui.Element
4768 OO.ui.Element.prototype.setElementGroup.call( this, group );
4769
4770 // Initialize item disabled states
4771 this.updateDisabled();
4772
4773 return this;
4774 };
4775
4776 /**
4777 * OptionWidgets are special elements that can be selected and configured with data. The
4778 * data is often unique for each option, but it does not have to be. OptionWidgets are used
4779 * with OO.ui.SelectWidget to create a selection of mutually exclusive options. For more information
4780 * and examples, please see the [OOjs UI documentation on MediaWiki][1].
4781 *
4782 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
4783 *
4784 * @class
4785 * @extends OO.ui.Widget
4786 * @mixins OO.ui.mixin.LabelElement
4787 * @mixins OO.ui.mixin.FlaggedElement
4788 *
4789 * @constructor
4790 * @param {Object} [config] Configuration options
4791 */
4792 OO.ui.OptionWidget = function OoUiOptionWidget( config ) {
4793 // Configuration initialization
4794 config = config || {};
4795
4796 // Parent constructor
4797 OO.ui.OptionWidget.parent.call( this, config );
4798
4799 // Mixin constructors
4800 OO.ui.mixin.ItemWidget.call( this );
4801 OO.ui.mixin.LabelElement.call( this, config );
4802 OO.ui.mixin.FlaggedElement.call( this, config );
4803
4804 // Properties
4805 this.selected = false;
4806 this.highlighted = false;
4807 this.pressed = false;
4808
4809 // Initialization
4810 this.$element
4811 .data( 'oo-ui-optionWidget', this )
4812 .attr( 'role', 'option' )
4813 .attr( 'aria-selected', 'false' )
4814 .addClass( 'oo-ui-optionWidget' )
4815 .append( this.$label );
4816 };
4817
4818 /* Setup */
4819
4820 OO.inheritClass( OO.ui.OptionWidget, OO.ui.Widget );
4821 OO.mixinClass( OO.ui.OptionWidget, OO.ui.mixin.ItemWidget );
4822 OO.mixinClass( OO.ui.OptionWidget, OO.ui.mixin.LabelElement );
4823 OO.mixinClass( OO.ui.OptionWidget, OO.ui.mixin.FlaggedElement );
4824
4825 /* Static Properties */
4826
4827 OO.ui.OptionWidget.static.selectable = true;
4828
4829 OO.ui.OptionWidget.static.highlightable = true;
4830
4831 OO.ui.OptionWidget.static.pressable = true;
4832
4833 OO.ui.OptionWidget.static.scrollIntoViewOnSelect = false;
4834
4835 /* Methods */
4836
4837 /**
4838 * Check if the option can be selected.
4839 *
4840 * @return {boolean} Item is selectable
4841 */
4842 OO.ui.OptionWidget.prototype.isSelectable = function () {
4843 return this.constructor.static.selectable && !this.isDisabled() && this.isVisible();
4844 };
4845
4846 /**
4847 * Check if the option can be highlighted. A highlight indicates that the option
4848 * may be selected when a user presses enter or clicks. Disabled items cannot
4849 * be highlighted.
4850 *
4851 * @return {boolean} Item is highlightable
4852 */
4853 OO.ui.OptionWidget.prototype.isHighlightable = function () {
4854 return this.constructor.static.highlightable && !this.isDisabled() && this.isVisible();
4855 };
4856
4857 /**
4858 * Check if the option can be pressed. The pressed state occurs when a user mouses
4859 * down on an item, but has not yet let go of the mouse.
4860 *
4861 * @return {boolean} Item is pressable
4862 */
4863 OO.ui.OptionWidget.prototype.isPressable = function () {
4864 return this.constructor.static.pressable && !this.isDisabled() && this.isVisible();
4865 };
4866
4867 /**
4868 * Check if the option is selected.
4869 *
4870 * @return {boolean} Item is selected
4871 */
4872 OO.ui.OptionWidget.prototype.isSelected = function () {
4873 return this.selected;
4874 };
4875
4876 /**
4877 * Check if the option is highlighted. A highlight indicates that the
4878 * item may be selected when a user presses enter or clicks.
4879 *
4880 * @return {boolean} Item is highlighted
4881 */
4882 OO.ui.OptionWidget.prototype.isHighlighted = function () {
4883 return this.highlighted;
4884 };
4885
4886 /**
4887 * Check if the option is pressed. The pressed state occurs when a user mouses
4888 * down on an item, but has not yet let go of the mouse. The item may appear
4889 * selected, but it will not be selected until the user releases the mouse.
4890 *
4891 * @return {boolean} Item is pressed
4892 */
4893 OO.ui.OptionWidget.prototype.isPressed = function () {
4894 return this.pressed;
4895 };
4896
4897 /**
4898 * Set the option’s selected state. In general, all modifications to the selection
4899 * should be handled by the SelectWidget’s {@link OO.ui.SelectWidget#selectItem selectItem( [item] )}
4900 * method instead of this method.
4901 *
4902 * @param {boolean} [state=false] Select option
4903 * @chainable
4904 */
4905 OO.ui.OptionWidget.prototype.setSelected = function ( state ) {
4906 if ( this.constructor.static.selectable ) {
4907 this.selected = !!state;
4908 this.$element
4909 .toggleClass( 'oo-ui-optionWidget-selected', state )
4910 .attr( 'aria-selected', state.toString() );
4911 if ( state && this.constructor.static.scrollIntoViewOnSelect ) {
4912 this.scrollElementIntoView();
4913 }
4914 this.updateThemeClasses();
4915 }
4916 return this;
4917 };
4918
4919 /**
4920 * Set the option’s highlighted state. In general, all programmatic
4921 * modifications to the highlight should be handled by the
4922 * SelectWidget’s {@link OO.ui.SelectWidget#highlightItem highlightItem( [item] )}
4923 * method instead of this method.
4924 *
4925 * @param {boolean} [state=false] Highlight option
4926 * @chainable
4927 */
4928 OO.ui.OptionWidget.prototype.setHighlighted = function ( state ) {
4929 if ( this.constructor.static.highlightable ) {
4930 this.highlighted = !!state;
4931 this.$element.toggleClass( 'oo-ui-optionWidget-highlighted', state );
4932 this.updateThemeClasses();
4933 }
4934 return this;
4935 };
4936
4937 /**
4938 * Set the option’s pressed state. In general, all
4939 * programmatic modifications to the pressed state should be handled by the
4940 * SelectWidget’s {@link OO.ui.SelectWidget#pressItem pressItem( [item] )}
4941 * method instead of this method.
4942 *
4943 * @param {boolean} [state=false] Press option
4944 * @chainable
4945 */
4946 OO.ui.OptionWidget.prototype.setPressed = function ( state ) {
4947 if ( this.constructor.static.pressable ) {
4948 this.pressed = !!state;
4949 this.$element.toggleClass( 'oo-ui-optionWidget-pressed', state );
4950 this.updateThemeClasses();
4951 }
4952 return this;
4953 };
4954
4955 /**
4956 * A SelectWidget is of a generic selection of options. The OOjs UI library contains several types of
4957 * select widgets, including {@link OO.ui.ButtonSelectWidget button selects},
4958 * {@link OO.ui.RadioSelectWidget radio selects}, and {@link OO.ui.MenuSelectWidget
4959 * menu selects}.
4960 *
4961 * This class should be used together with OO.ui.OptionWidget or OO.ui.DecoratedOptionWidget. For more
4962 * information, please see the [OOjs UI documentation on MediaWiki][1].
4963 *
4964 * @example
4965 * // Example of a select widget with three options
4966 * var select = new OO.ui.SelectWidget( {
4967 * items: [
4968 * new OO.ui.OptionWidget( {
4969 * data: 'a',
4970 * label: 'Option One',
4971 * } ),
4972 * new OO.ui.OptionWidget( {
4973 * data: 'b',
4974 * label: 'Option Two',
4975 * } ),
4976 * new OO.ui.OptionWidget( {
4977 * data: 'c',
4978 * label: 'Option Three',
4979 * } )
4980 * ]
4981 * } );
4982 * $( 'body' ).append( select.$element );
4983 *
4984 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
4985 *
4986 * @abstract
4987 * @class
4988 * @extends OO.ui.Widget
4989 * @mixins OO.ui.mixin.GroupWidget
4990 *
4991 * @constructor
4992 * @param {Object} [config] Configuration options
4993 * @cfg {OO.ui.OptionWidget[]} [items] An array of options to add to the select.
4994 * Options are created with {@link OO.ui.OptionWidget OptionWidget} classes. See
4995 * the [OOjs UI documentation on MediaWiki] [2] for examples.
4996 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
4997 */
4998 OO.ui.SelectWidget = function OoUiSelectWidget( config ) {
4999 // Configuration initialization
5000 config = config || {};
5001
5002 // Parent constructor
5003 OO.ui.SelectWidget.parent.call( this, config );
5004
5005 // Mixin constructors
5006 OO.ui.mixin.GroupWidget.call( this, $.extend( {}, config, { $group: this.$element } ) );
5007
5008 // Properties
5009 this.pressed = false;
5010 this.selecting = null;
5011 this.onMouseUpHandler = this.onMouseUp.bind( this );
5012 this.onMouseMoveHandler = this.onMouseMove.bind( this );
5013 this.onKeyDownHandler = this.onKeyDown.bind( this );
5014 this.onKeyPressHandler = this.onKeyPress.bind( this );
5015 this.keyPressBuffer = '';
5016 this.keyPressBufferTimer = null;
5017 this.blockMouseOverEvents = 0;
5018
5019 // Events
5020 this.connect( this, {
5021 toggle: 'onToggle'
5022 } );
5023 this.$element.on( {
5024 focus: this.onFocus.bind( this ),
5025 mousedown: this.onMouseDown.bind( this ),
5026 mouseover: this.onMouseOver.bind( this ),
5027 mouseleave: this.onMouseLeave.bind( this )
5028 } );
5029
5030 // Initialization
5031 this.$element
5032 .addClass( 'oo-ui-selectWidget oo-ui-selectWidget-depressed' )
5033 .attr( 'role', 'listbox' );
5034 if ( Array.isArray( config.items ) ) {
5035 this.addItems( config.items );
5036 }
5037 };
5038
5039 /* Setup */
5040
5041 OO.inheritClass( OO.ui.SelectWidget, OO.ui.Widget );
5042
5043 // Need to mixin base class as well
5044 OO.mixinClass( OO.ui.SelectWidget, OO.ui.mixin.GroupElement );
5045 OO.mixinClass( OO.ui.SelectWidget, OO.ui.mixin.GroupWidget );
5046
5047 /* Static */
5048 OO.ui.SelectWidget.static.passAllFilter = function () {
5049 return true;
5050 };
5051
5052 /* Events */
5053
5054 /**
5055 * @event highlight
5056 *
5057 * A `highlight` event is emitted when the highlight is changed with the #highlightItem method.
5058 *
5059 * @param {OO.ui.OptionWidget|null} item Highlighted item
5060 */
5061
5062 /**
5063 * @event press
5064 *
5065 * A `press` event is emitted when the #pressItem method is used to programmatically modify the
5066 * pressed state of an option.
5067 *
5068 * @param {OO.ui.OptionWidget|null} item Pressed item
5069 */
5070
5071 /**
5072 * @event select
5073 *
5074 * A `select` event is emitted when the selection is modified programmatically with the #selectItem method.
5075 *
5076 * @param {OO.ui.OptionWidget|null} item Selected item
5077 */
5078
5079 /**
5080 * @event choose
5081 * A `choose` event is emitted when an item is chosen with the #chooseItem method.
5082 * @param {OO.ui.OptionWidget} item Chosen item
5083 */
5084
5085 /**
5086 * @event add
5087 *
5088 * An `add` event is emitted when options are added to the select with the #addItems method.
5089 *
5090 * @param {OO.ui.OptionWidget[]} items Added items
5091 * @param {number} index Index of insertion point
5092 */
5093
5094 /**
5095 * @event remove
5096 *
5097 * A `remove` event is emitted when options are removed from the select with the #clearItems
5098 * or #removeItems methods.
5099 *
5100 * @param {OO.ui.OptionWidget[]} items Removed items
5101 */
5102
5103 /* Methods */
5104
5105 /**
5106 * Handle focus events
5107 *
5108 * @private
5109 * @param {jQuery.Event} event
5110 */
5111 OO.ui.SelectWidget.prototype.onFocus = function () {
5112 // The styles for focus state depend on one of the items being selected.
5113 if ( !this.getSelectedItem() ) {
5114 this.selectItem( this.getFirstSelectableItem() );
5115 }
5116 };
5117
5118 /**
5119 * Handle mouse down events.
5120 *
5121 * @private
5122 * @param {jQuery.Event} e Mouse down event
5123 */
5124 OO.ui.SelectWidget.prototype.onMouseDown = function ( e ) {
5125 var item;
5126
5127 if ( !this.isDisabled() && e.which === OO.ui.MouseButtons.LEFT ) {
5128 this.togglePressed( true );
5129 item = this.getTargetItem( e );
5130 if ( item && item.isSelectable() ) {
5131 this.pressItem( item );
5132 this.selecting = item;
5133 this.getElementDocument().addEventListener( 'mouseup', this.onMouseUpHandler, true );
5134 this.getElementDocument().addEventListener( 'mousemove', this.onMouseMoveHandler, true );
5135 }
5136 }
5137 return false;
5138 };
5139
5140 /**
5141 * Handle mouse up events.
5142 *
5143 * @private
5144 * @param {MouseEvent} e Mouse up event
5145 */
5146 OO.ui.SelectWidget.prototype.onMouseUp = function ( e ) {
5147 var item;
5148
5149 this.togglePressed( false );
5150 if ( !this.selecting ) {
5151 item = this.getTargetItem( e );
5152 if ( item && item.isSelectable() ) {
5153 this.selecting = item;
5154 }
5155 }
5156 if ( !this.isDisabled() && e.which === OO.ui.MouseButtons.LEFT && this.selecting ) {
5157 this.pressItem( null );
5158 this.chooseItem( this.selecting );
5159 this.selecting = null;
5160 }
5161
5162 this.getElementDocument().removeEventListener( 'mouseup', this.onMouseUpHandler, true );
5163 this.getElementDocument().removeEventListener( 'mousemove', this.onMouseMoveHandler, true );
5164
5165 return false;
5166 };
5167
5168 /**
5169 * Handle mouse move events.
5170 *
5171 * @private
5172 * @param {MouseEvent} e Mouse move event
5173 */
5174 OO.ui.SelectWidget.prototype.onMouseMove = function ( e ) {
5175 var item;
5176
5177 if ( !this.isDisabled() && this.pressed ) {
5178 item = this.getTargetItem( e );
5179 if ( item && item !== this.selecting && item.isSelectable() ) {
5180 this.pressItem( item );
5181 this.selecting = item;
5182 }
5183 }
5184 };
5185
5186 /**
5187 * Handle mouse over events.
5188 *
5189 * @private
5190 * @param {jQuery.Event} e Mouse over event
5191 */
5192 OO.ui.SelectWidget.prototype.onMouseOver = function ( e ) {
5193 var item;
5194 if ( this.blockMouseOverEvents ) {
5195 return;
5196 }
5197 if ( !this.isDisabled() ) {
5198 item = this.getTargetItem( e );
5199 this.highlightItem( item && item.isHighlightable() ? item : null );
5200 }
5201 return false;
5202 };
5203
5204 /**
5205 * Handle mouse leave events.
5206 *
5207 * @private
5208 * @param {jQuery.Event} e Mouse over event
5209 */
5210 OO.ui.SelectWidget.prototype.onMouseLeave = function () {
5211 if ( !this.isDisabled() ) {
5212 this.highlightItem( null );
5213 }
5214 return false;
5215 };
5216
5217 /**
5218 * Handle key down events.
5219 *
5220 * @protected
5221 * @param {KeyboardEvent} e Key down event
5222 */
5223 OO.ui.SelectWidget.prototype.onKeyDown = function ( e ) {
5224 var nextItem,
5225 handled = false,
5226 currentItem = this.getHighlightedItem() || this.getSelectedItem();
5227
5228 if ( !this.isDisabled() && this.isVisible() ) {
5229 switch ( e.keyCode ) {
5230 case OO.ui.Keys.ENTER:
5231 if ( currentItem && currentItem.constructor.static.highlightable ) {
5232 // Was only highlighted, now let's select it. No-op if already selected.
5233 this.chooseItem( currentItem );
5234 handled = true;
5235 }
5236 break;
5237 case OO.ui.Keys.UP:
5238 case OO.ui.Keys.LEFT:
5239 this.clearKeyPressBuffer();
5240 nextItem = this.getRelativeSelectableItem( currentItem, -1 );
5241 handled = true;
5242 break;
5243 case OO.ui.Keys.DOWN:
5244 case OO.ui.Keys.RIGHT:
5245 this.clearKeyPressBuffer();
5246 nextItem = this.getRelativeSelectableItem( currentItem, 1 );
5247 handled = true;
5248 break;
5249 case OO.ui.Keys.ESCAPE:
5250 case OO.ui.Keys.TAB:
5251 if ( currentItem && currentItem.constructor.static.highlightable ) {
5252 currentItem.setHighlighted( false );
5253 }
5254 this.unbindKeyDownListener();
5255 this.unbindKeyPressListener();
5256 // Don't prevent tabbing away / defocusing
5257 handled = false;
5258 break;
5259 }
5260
5261 if ( nextItem ) {
5262 if ( nextItem.constructor.static.highlightable ) {
5263 this.highlightItem( nextItem );
5264 } else {
5265 this.chooseItem( nextItem );
5266 }
5267 this.scrollItemIntoView( nextItem );
5268 }
5269
5270 if ( handled ) {
5271 e.preventDefault();
5272 e.stopPropagation();
5273 }
5274 }
5275 };
5276
5277 /**
5278 * Bind key down listener.
5279 *
5280 * @protected
5281 */
5282 OO.ui.SelectWidget.prototype.bindKeyDownListener = function () {
5283 this.getElementWindow().addEventListener( 'keydown', this.onKeyDownHandler, true );
5284 };
5285
5286 /**
5287 * Unbind key down listener.
5288 *
5289 * @protected
5290 */
5291 OO.ui.SelectWidget.prototype.unbindKeyDownListener = function () {
5292 this.getElementWindow().removeEventListener( 'keydown', this.onKeyDownHandler, true );
5293 };
5294
5295 /**
5296 * Scroll item into view, preventing spurious mouse highlight actions from happening.
5297 *
5298 * @param {OO.ui.OptionWidget} item Item to scroll into view
5299 */
5300 OO.ui.SelectWidget.prototype.scrollItemIntoView = function ( item ) {
5301 var widget = this;
5302 // Chromium's Blink engine will generate spurious 'mouseover' events during programmatic scrolling
5303 // and around 100-150 ms after it is finished.
5304 this.blockMouseOverEvents++;
5305 item.scrollElementIntoView().done( function () {
5306 setTimeout( function () {
5307 widget.blockMouseOverEvents--;
5308 }, 200 );
5309 } );
5310 };
5311
5312 /**
5313 * Clear the key-press buffer
5314 *
5315 * @protected
5316 */
5317 OO.ui.SelectWidget.prototype.clearKeyPressBuffer = function () {
5318 if ( this.keyPressBufferTimer ) {
5319 clearTimeout( this.keyPressBufferTimer );
5320 this.keyPressBufferTimer = null;
5321 }
5322 this.keyPressBuffer = '';
5323 };
5324
5325 /**
5326 * Handle key press events.
5327 *
5328 * @protected
5329 * @param {KeyboardEvent} e Key press event
5330 */
5331 OO.ui.SelectWidget.prototype.onKeyPress = function ( e ) {
5332 var c, filter, item;
5333
5334 if ( !e.charCode ) {
5335 if ( e.keyCode === OO.ui.Keys.BACKSPACE && this.keyPressBuffer !== '' ) {
5336 this.keyPressBuffer = this.keyPressBuffer.substr( 0, this.keyPressBuffer.length - 1 );
5337 return false;
5338 }
5339 return;
5340 }
5341 if ( String.fromCodePoint ) {
5342 c = String.fromCodePoint( e.charCode );
5343 } else {
5344 c = String.fromCharCode( e.charCode );
5345 }
5346
5347 if ( this.keyPressBufferTimer ) {
5348 clearTimeout( this.keyPressBufferTimer );
5349 }
5350 this.keyPressBufferTimer = setTimeout( this.clearKeyPressBuffer.bind( this ), 1500 );
5351
5352 item = this.getHighlightedItem() || this.getSelectedItem();
5353
5354 if ( this.keyPressBuffer === c ) {
5355 // Common (if weird) special case: typing "xxxx" will cycle through all
5356 // the items beginning with "x".
5357 if ( item ) {
5358 item = this.getRelativeSelectableItem( item, 1 );
5359 }
5360 } else {
5361 this.keyPressBuffer += c;
5362 }
5363
5364 filter = this.getItemMatcher( this.keyPressBuffer, false );
5365 if ( !item || !filter( item ) ) {
5366 item = this.getRelativeSelectableItem( item, 1, filter );
5367 }
5368 if ( item ) {
5369 if ( item.constructor.static.highlightable ) {
5370 this.highlightItem( item );
5371 } else {
5372 this.chooseItem( item );
5373 }
5374 this.scrollItemIntoView( item );
5375 }
5376
5377 e.preventDefault();
5378 e.stopPropagation();
5379 };
5380
5381 /**
5382 * Get a matcher for the specific string
5383 *
5384 * @protected
5385 * @param {string} s String to match against items
5386 * @param {boolean} [exact=false] Only accept exact matches
5387 * @return {Function} function ( OO.ui.OptionItem ) => boolean
5388 */
5389 OO.ui.SelectWidget.prototype.getItemMatcher = function ( s, exact ) {
5390 var re;
5391
5392 if ( s.normalize ) {
5393 s = s.normalize();
5394 }
5395 s = exact ? s.trim() : s.replace( /^\s+/, '' );
5396 re = '^\\s*' + s.replace( /([\\{}()|.?*+\-\^$\[\]])/g, '\\$1' ).replace( /\s+/g, '\\s+' );
5397 if ( exact ) {
5398 re += '\\s*$';
5399 }
5400 re = new RegExp( re, 'i' );
5401 return function ( item ) {
5402 var l = item.getLabel();
5403 if ( typeof l !== 'string' ) {
5404 l = item.$label.text();
5405 }
5406 if ( l.normalize ) {
5407 l = l.normalize();
5408 }
5409 return re.test( l );
5410 };
5411 };
5412
5413 /**
5414 * Bind key press listener.
5415 *
5416 * @protected
5417 */
5418 OO.ui.SelectWidget.prototype.bindKeyPressListener = function () {
5419 this.getElementWindow().addEventListener( 'keypress', this.onKeyPressHandler, true );
5420 };
5421
5422 /**
5423 * Unbind key down listener.
5424 *
5425 * If you override this, be sure to call this.clearKeyPressBuffer() from your
5426 * implementation.
5427 *
5428 * @protected
5429 */
5430 OO.ui.SelectWidget.prototype.unbindKeyPressListener = function () {
5431 this.getElementWindow().removeEventListener( 'keypress', this.onKeyPressHandler, true );
5432 this.clearKeyPressBuffer();
5433 };
5434
5435 /**
5436 * Visibility change handler
5437 *
5438 * @protected
5439 * @param {boolean} visible
5440 */
5441 OO.ui.SelectWidget.prototype.onToggle = function ( visible ) {
5442 if ( !visible ) {
5443 this.clearKeyPressBuffer();
5444 }
5445 };
5446
5447 /**
5448 * Get the closest item to a jQuery.Event.
5449 *
5450 * @private
5451 * @param {jQuery.Event} e
5452 * @return {OO.ui.OptionWidget|null} Outline item widget, `null` if none was found
5453 */
5454 OO.ui.SelectWidget.prototype.getTargetItem = function ( e ) {
5455 return $( e.target ).closest( '.oo-ui-optionWidget' ).data( 'oo-ui-optionWidget' ) || null;
5456 };
5457
5458 /**
5459 * Get selected item.
5460 *
5461 * @return {OO.ui.OptionWidget|null} Selected item, `null` if no item is selected
5462 */
5463 OO.ui.SelectWidget.prototype.getSelectedItem = function () {
5464 var i, len;
5465
5466 for ( i = 0, len = this.items.length; i < len; i++ ) {
5467 if ( this.items[ i ].isSelected() ) {
5468 return this.items[ i ];
5469 }
5470 }
5471 return null;
5472 };
5473
5474 /**
5475 * Get highlighted item.
5476 *
5477 * @return {OO.ui.OptionWidget|null} Highlighted item, `null` if no item is highlighted
5478 */
5479 OO.ui.SelectWidget.prototype.getHighlightedItem = function () {
5480 var i, len;
5481
5482 for ( i = 0, len = this.items.length; i < len; i++ ) {
5483 if ( this.items[ i ].isHighlighted() ) {
5484 return this.items[ i ];
5485 }
5486 }
5487 return null;
5488 };
5489
5490 /**
5491 * Toggle pressed state.
5492 *
5493 * Press is a state that occurs when a user mouses down on an item, but
5494 * has not yet let go of the mouse. The item may appear selected, but it will not be selected
5495 * until the user releases the mouse.
5496 *
5497 * @param {boolean} pressed An option is being pressed
5498 */
5499 OO.ui.SelectWidget.prototype.togglePressed = function ( pressed ) {
5500 if ( pressed === undefined ) {
5501 pressed = !this.pressed;
5502 }
5503 if ( pressed !== this.pressed ) {
5504 this.$element
5505 .toggleClass( 'oo-ui-selectWidget-pressed', pressed )
5506 .toggleClass( 'oo-ui-selectWidget-depressed', !pressed );
5507 this.pressed = pressed;
5508 }
5509 };
5510
5511 /**
5512 * Highlight an option. If the `item` param is omitted, no options will be highlighted
5513 * and any existing highlight will be removed. The highlight is mutually exclusive.
5514 *
5515 * @param {OO.ui.OptionWidget} [item] Item to highlight, omit for no highlight
5516 * @fires highlight
5517 * @chainable
5518 */
5519 OO.ui.SelectWidget.prototype.highlightItem = function ( item ) {
5520 var i, len, highlighted,
5521 changed = false;
5522
5523 for ( i = 0, len = this.items.length; i < len; i++ ) {
5524 highlighted = this.items[ i ] === item;
5525 if ( this.items[ i ].isHighlighted() !== highlighted ) {
5526 this.items[ i ].setHighlighted( highlighted );
5527 changed = true;
5528 }
5529 }
5530 if ( changed ) {
5531 this.emit( 'highlight', item );
5532 }
5533
5534 return this;
5535 };
5536
5537 /**
5538 * Fetch an item by its label.
5539 *
5540 * @param {string} label Label of the item to select.
5541 * @param {boolean} [prefix=false] Allow a prefix match, if only a single item matches
5542 * @return {OO.ui.Element|null} Item with equivalent label, `null` if none exists
5543 */
5544 OO.ui.SelectWidget.prototype.getItemFromLabel = function ( label, prefix ) {
5545 var i, item, found,
5546 len = this.items.length,
5547 filter = this.getItemMatcher( label, true );
5548
5549 for ( i = 0; i < len; i++ ) {
5550 item = this.items[ i ];
5551 if ( item instanceof OO.ui.OptionWidget && item.isSelectable() && filter( item ) ) {
5552 return item;
5553 }
5554 }
5555
5556 if ( prefix ) {
5557 found = null;
5558 filter = this.getItemMatcher( label, false );
5559 for ( i = 0; i < len; i++ ) {
5560 item = this.items[ i ];
5561 if ( item instanceof OO.ui.OptionWidget && item.isSelectable() && filter( item ) ) {
5562 if ( found ) {
5563 return null;
5564 }
5565 found = item;
5566 }
5567 }
5568 if ( found ) {
5569 return found;
5570 }
5571 }
5572
5573 return null;
5574 };
5575
5576 /**
5577 * Programmatically select an option by its label. If the item does not exist,
5578 * all options will be deselected.
5579 *
5580 * @param {string} [label] Label of the item to select.
5581 * @param {boolean} [prefix=false] Allow a prefix match, if only a single item matches
5582 * @fires select
5583 * @chainable
5584 */
5585 OO.ui.SelectWidget.prototype.selectItemByLabel = function ( label, prefix ) {
5586 var itemFromLabel = this.getItemFromLabel( label, !!prefix );
5587 if ( label === undefined || !itemFromLabel ) {
5588 return this.selectItem();
5589 }
5590 return this.selectItem( itemFromLabel );
5591 };
5592
5593 /**
5594 * Programmatically select an option by its data. If the `data` parameter is omitted,
5595 * or if the item does not exist, all options will be deselected.
5596 *
5597 * @param {Object|string} [data] Value of the item to select, omit to deselect all
5598 * @fires select
5599 * @chainable
5600 */
5601 OO.ui.SelectWidget.prototype.selectItemByData = function ( data ) {
5602 var itemFromData = this.getItemFromData( data );
5603 if ( data === undefined || !itemFromData ) {
5604 return this.selectItem();
5605 }
5606 return this.selectItem( itemFromData );
5607 };
5608
5609 /**
5610 * Programmatically select an option by its reference. If the `item` parameter is omitted,
5611 * all options will be deselected.
5612 *
5613 * @param {OO.ui.OptionWidget} [item] Item to select, omit to deselect all
5614 * @fires select
5615 * @chainable
5616 */
5617 OO.ui.SelectWidget.prototype.selectItem = function ( item ) {
5618 var i, len, selected,
5619 changed = false;
5620
5621 for ( i = 0, len = this.items.length; i < len; i++ ) {
5622 selected = this.items[ i ] === item;
5623 if ( this.items[ i ].isSelected() !== selected ) {
5624 this.items[ i ].setSelected( selected );
5625 changed = true;
5626 }
5627 }
5628 if ( changed ) {
5629 this.emit( 'select', item );
5630 }
5631
5632 return this;
5633 };
5634
5635 /**
5636 * Press an item.
5637 *
5638 * Press is a state that occurs when a user mouses down on an item, but has not
5639 * yet let go of the mouse. The item may appear selected, but it will not be selected until the user
5640 * releases the mouse.
5641 *
5642 * @param {OO.ui.OptionWidget} [item] Item to press, omit to depress all
5643 * @fires press
5644 * @chainable
5645 */
5646 OO.ui.SelectWidget.prototype.pressItem = function ( item ) {
5647 var i, len, pressed,
5648 changed = false;
5649
5650 for ( i = 0, len = this.items.length; i < len; i++ ) {
5651 pressed = this.items[ i ] === item;
5652 if ( this.items[ i ].isPressed() !== pressed ) {
5653 this.items[ i ].setPressed( pressed );
5654 changed = true;
5655 }
5656 }
5657 if ( changed ) {
5658 this.emit( 'press', item );
5659 }
5660
5661 return this;
5662 };
5663
5664 /**
5665 * Choose an item.
5666 *
5667 * Note that ‘choose’ should never be modified programmatically. A user can choose
5668 * an option with the keyboard or mouse and it becomes selected. To select an item programmatically,
5669 * use the #selectItem method.
5670 *
5671 * This method is identical to #selectItem, but may vary in subclasses that take additional action
5672 * when users choose an item with the keyboard or mouse.
5673 *
5674 * @param {OO.ui.OptionWidget} item Item to choose
5675 * @fires choose
5676 * @chainable
5677 */
5678 OO.ui.SelectWidget.prototype.chooseItem = function ( item ) {
5679 if ( item ) {
5680 this.selectItem( item );
5681 this.emit( 'choose', item );
5682 }
5683
5684 return this;
5685 };
5686
5687 /**
5688 * Get an option by its position relative to the specified item (or to the start of the option array,
5689 * if item is `null`). The direction in which to search through the option array is specified with a
5690 * number: -1 for reverse (the default) or 1 for forward. The method will return an option, or
5691 * `null` if there are no options in the array.
5692 *
5693 * @param {OO.ui.OptionWidget|null} item Item to describe the start position, or `null` to start at the beginning of the array.
5694 * @param {number} direction Direction to move in: -1 to move backward, 1 to move forward
5695 * @param {Function} filter Only consider items for which this function returns
5696 * true. Function takes an OO.ui.OptionWidget and returns a boolean.
5697 * @return {OO.ui.OptionWidget|null} Item at position, `null` if there are no items in the select
5698 */
5699 OO.ui.SelectWidget.prototype.getRelativeSelectableItem = function ( item, direction, filter ) {
5700 var currentIndex, nextIndex, i,
5701 increase = direction > 0 ? 1 : -1,
5702 len = this.items.length;
5703
5704 if ( !$.isFunction( filter ) ) {
5705 filter = OO.ui.SelectWidget.static.passAllFilter;
5706 }
5707
5708 if ( item instanceof OO.ui.OptionWidget ) {
5709 currentIndex = this.items.indexOf( item );
5710 nextIndex = ( currentIndex + increase + len ) % len;
5711 } else {
5712 // If no item is selected and moving forward, start at the beginning.
5713 // If moving backward, start at the end.
5714 nextIndex = direction > 0 ? 0 : len - 1;
5715 }
5716
5717 for ( i = 0; i < len; i++ ) {
5718 item = this.items[ nextIndex ];
5719 if ( item instanceof OO.ui.OptionWidget && item.isSelectable() && filter( item ) ) {
5720 return item;
5721 }
5722 nextIndex = ( nextIndex + increase + len ) % len;
5723 }
5724 return null;
5725 };
5726
5727 /**
5728 * Get the next selectable item or `null` if there are no selectable items.
5729 * Disabled options and menu-section markers and breaks are not selectable.
5730 *
5731 * @return {OO.ui.OptionWidget|null} Item, `null` if there aren't any selectable items
5732 */
5733 OO.ui.SelectWidget.prototype.getFirstSelectableItem = function () {
5734 var i, len, item;
5735
5736 for ( i = 0, len = this.items.length; i < len; i++ ) {
5737 item = this.items[ i ];
5738 if ( item instanceof OO.ui.OptionWidget && item.isSelectable() ) {
5739 return item;
5740 }
5741 }
5742
5743 return null;
5744 };
5745
5746 /**
5747 * Add an array of options to the select. Optionally, an index number can be used to
5748 * specify an insertion point.
5749 *
5750 * @param {OO.ui.OptionWidget[]} items Items to add
5751 * @param {number} [index] Index to insert items after
5752 * @fires add
5753 * @chainable
5754 */
5755 OO.ui.SelectWidget.prototype.addItems = function ( items, index ) {
5756 // Mixin method
5757 OO.ui.mixin.GroupWidget.prototype.addItems.call( this, items, index );
5758
5759 // Always provide an index, even if it was omitted
5760 this.emit( 'add', items, index === undefined ? this.items.length - items.length - 1 : index );
5761
5762 return this;
5763 };
5764
5765 /**
5766 * Remove the specified array of options from the select. Options will be detached
5767 * from the DOM, not removed, so they can be reused later. To remove all options from
5768 * the select, you may wish to use the #clearItems method instead.
5769 *
5770 * @param {OO.ui.OptionWidget[]} items Items to remove
5771 * @fires remove
5772 * @chainable
5773 */
5774 OO.ui.SelectWidget.prototype.removeItems = function ( items ) {
5775 var i, len, item;
5776
5777 // Deselect items being removed
5778 for ( i = 0, len = items.length; i < len; i++ ) {
5779 item = items[ i ];
5780 if ( item.isSelected() ) {
5781 this.selectItem( null );
5782 }
5783 }
5784
5785 // Mixin method
5786 OO.ui.mixin.GroupWidget.prototype.removeItems.call( this, items );
5787
5788 this.emit( 'remove', items );
5789
5790 return this;
5791 };
5792
5793 /**
5794 * Clear all options from the select. Options will be detached from the DOM, not removed,
5795 * so that they can be reused later. To remove a subset of options from the select, use
5796 * the #removeItems method.
5797 *
5798 * @fires remove
5799 * @chainable
5800 */
5801 OO.ui.SelectWidget.prototype.clearItems = function () {
5802 var items = this.items.slice();
5803
5804 // Mixin method
5805 OO.ui.mixin.GroupWidget.prototype.clearItems.call( this );
5806
5807 // Clear selection
5808 this.selectItem( null );
5809
5810 this.emit( 'remove', items );
5811
5812 return this;
5813 };
5814
5815 /**
5816 * DecoratedOptionWidgets are {@link OO.ui.OptionWidget options} that can be configured
5817 * with an {@link OO.ui.mixin.IconElement icon} and/or {@link OO.ui.mixin.IndicatorElement indicator}.
5818 * This class is used with OO.ui.SelectWidget to create a selection of mutually exclusive
5819 * options. For more information about options and selects, please see the
5820 * [OOjs UI documentation on MediaWiki][1].
5821 *
5822 * @example
5823 * // Decorated options in a select widget
5824 * var select = new OO.ui.SelectWidget( {
5825 * items: [
5826 * new OO.ui.DecoratedOptionWidget( {
5827 * data: 'a',
5828 * label: 'Option with icon',
5829 * icon: 'help'
5830 * } ),
5831 * new OO.ui.DecoratedOptionWidget( {
5832 * data: 'b',
5833 * label: 'Option with indicator',
5834 * indicator: 'next'
5835 * } )
5836 * ]
5837 * } );
5838 * $( 'body' ).append( select.$element );
5839 *
5840 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
5841 *
5842 * @class
5843 * @extends OO.ui.OptionWidget
5844 * @mixins OO.ui.mixin.IconElement
5845 * @mixins OO.ui.mixin.IndicatorElement
5846 *
5847 * @constructor
5848 * @param {Object} [config] Configuration options
5849 */
5850 OO.ui.DecoratedOptionWidget = function OoUiDecoratedOptionWidget( config ) {
5851 // Parent constructor
5852 OO.ui.DecoratedOptionWidget.parent.call( this, config );
5853
5854 // Mixin constructors
5855 OO.ui.mixin.IconElement.call( this, config );
5856 OO.ui.mixin.IndicatorElement.call( this, config );
5857
5858 // Initialization
5859 this.$element
5860 .addClass( 'oo-ui-decoratedOptionWidget' )
5861 .prepend( this.$icon )
5862 .append( this.$indicator );
5863 };
5864
5865 /* Setup */
5866
5867 OO.inheritClass( OO.ui.DecoratedOptionWidget, OO.ui.OptionWidget );
5868 OO.mixinClass( OO.ui.DecoratedOptionWidget, OO.ui.mixin.IconElement );
5869 OO.mixinClass( OO.ui.DecoratedOptionWidget, OO.ui.mixin.IndicatorElement );
5870
5871 /**
5872 * MenuOptionWidget is an option widget that looks like a menu item. The class is used with
5873 * OO.ui.MenuSelectWidget to create a menu of mutually exclusive options. Please see
5874 * the [OOjs UI documentation on MediaWiki] [1] for more information.
5875 *
5876 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
5877 *
5878 * @class
5879 * @extends OO.ui.DecoratedOptionWidget
5880 *
5881 * @constructor
5882 * @param {Object} [config] Configuration options
5883 */
5884 OO.ui.MenuOptionWidget = function OoUiMenuOptionWidget( config ) {
5885 // Configuration initialization
5886 config = $.extend( { icon: 'check' }, config );
5887
5888 // Parent constructor
5889 OO.ui.MenuOptionWidget.parent.call( this, config );
5890
5891 // Initialization
5892 this.$element
5893 .attr( 'role', 'menuitem' )
5894 .addClass( 'oo-ui-menuOptionWidget' );
5895 };
5896
5897 /* Setup */
5898
5899 OO.inheritClass( OO.ui.MenuOptionWidget, OO.ui.DecoratedOptionWidget );
5900
5901 /* Static Properties */
5902
5903 OO.ui.MenuOptionWidget.static.scrollIntoViewOnSelect = true;
5904
5905 /**
5906 * MenuSectionOptionWidgets are used inside {@link OO.ui.MenuSelectWidget menu select widgets} to group one or more related
5907 * {@link OO.ui.MenuOptionWidget menu options}. MenuSectionOptionWidgets cannot be highlighted or selected.
5908 *
5909 * @example
5910 * var myDropdown = new OO.ui.DropdownWidget( {
5911 * menu: {
5912 * items: [
5913 * new OO.ui.MenuSectionOptionWidget( {
5914 * label: 'Dogs'
5915 * } ),
5916 * new OO.ui.MenuOptionWidget( {
5917 * data: 'corgi',
5918 * label: 'Welsh Corgi'
5919 * } ),
5920 * new OO.ui.MenuOptionWidget( {
5921 * data: 'poodle',
5922 * label: 'Standard Poodle'
5923 * } ),
5924 * new OO.ui.MenuSectionOptionWidget( {
5925 * label: 'Cats'
5926 * } ),
5927 * new OO.ui.MenuOptionWidget( {
5928 * data: 'lion',
5929 * label: 'Lion'
5930 * } )
5931 * ]
5932 * }
5933 * } );
5934 * $( 'body' ).append( myDropdown.$element );
5935 *
5936 * @class
5937 * @extends OO.ui.DecoratedOptionWidget
5938 *
5939 * @constructor
5940 * @param {Object} [config] Configuration options
5941 */
5942 OO.ui.MenuSectionOptionWidget = function OoUiMenuSectionOptionWidget( config ) {
5943 // Parent constructor
5944 OO.ui.MenuSectionOptionWidget.parent.call( this, config );
5945
5946 // Initialization
5947 this.$element.addClass( 'oo-ui-menuSectionOptionWidget' );
5948 };
5949
5950 /* Setup */
5951
5952 OO.inheritClass( OO.ui.MenuSectionOptionWidget, OO.ui.DecoratedOptionWidget );
5953
5954 /* Static Properties */
5955
5956 OO.ui.MenuSectionOptionWidget.static.selectable = false;
5957
5958 OO.ui.MenuSectionOptionWidget.static.highlightable = false;
5959
5960 /**
5961 * MenuSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains options and
5962 * is used together with OO.ui.MenuOptionWidget. It is designed be used as part of another widget.
5963 * See {@link OO.ui.DropdownWidget DropdownWidget}, {@link OO.ui.ComboBoxInputWidget ComboBoxInputWidget},
5964 * and {@link OO.ui.mixin.LookupElement LookupElement} for examples of widgets that contain menus.
5965 * MenuSelectWidgets themselves are not instantiated directly, rather subclassed
5966 * and customized to be opened, closed, and displayed as needed.
5967 *
5968 * By default, menus are clipped to the visible viewport and are not visible when a user presses the
5969 * mouse outside the menu.
5970 *
5971 * Menus also have support for keyboard interaction:
5972 *
5973 * - Enter/Return key: choose and select a menu option
5974 * - Up-arrow key: highlight the previous menu option
5975 * - Down-arrow key: highlight the next menu option
5976 * - Esc key: hide the menu
5977 *
5978 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
5979 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
5980 *
5981 * @class
5982 * @extends OO.ui.SelectWidget
5983 * @mixins OO.ui.mixin.ClippableElement
5984 *
5985 * @constructor
5986 * @param {Object} [config] Configuration options
5987 * @cfg {OO.ui.TextInputWidget} [input] Text input used to implement option highlighting for menu items that match
5988 * the text the user types. This config is used by {@link OO.ui.ComboBoxInputWidget ComboBoxInputWidget}
5989 * and {@link OO.ui.mixin.LookupElement LookupElement}
5990 * @cfg {jQuery} [$input] Text input used to implement option highlighting for menu items that match
5991 * the text the user types. This config is used by {@link OO.ui.CapsuleMultiSelectWidget CapsuleMultiSelectWidget}
5992 * @cfg {OO.ui.Widget} [widget] Widget associated with the menu's active state. If the user clicks the mouse
5993 * anywhere on the page outside of this widget, the menu is hidden. For example, if there is a button
5994 * that toggles the menu's visibility on click, the menu will be hidden then re-shown when the user clicks
5995 * that button, unless the button (or its parent widget) is passed in here.
5996 * @cfg {boolean} [autoHide=true] Hide the menu when the mouse is pressed outside the menu.
5997 * @cfg {boolean} [filterFromInput=false] Filter the displayed options from the input
5998 */
5999 OO.ui.MenuSelectWidget = function OoUiMenuSelectWidget( config ) {
6000 // Configuration initialization
6001 config = config || {};
6002
6003 // Parent constructor
6004 OO.ui.MenuSelectWidget.parent.call( this, config );
6005
6006 // Mixin constructors
6007 OO.ui.mixin.ClippableElement.call( this, $.extend( {}, config, { $clippable: this.$group } ) );
6008
6009 // Properties
6010 this.autoHide = config.autoHide === undefined || !!config.autoHide;
6011 this.filterFromInput = !!config.filterFromInput;
6012 this.$input = config.$input ? config.$input : config.input ? config.input.$input : null;
6013 this.$widget = config.widget ? config.widget.$element : null;
6014 this.onDocumentMouseDownHandler = this.onDocumentMouseDown.bind( this );
6015 this.onInputEditHandler = OO.ui.debounce( this.updateItemVisibility.bind( this ), 100 );
6016
6017 // Initialization
6018 this.$element
6019 .addClass( 'oo-ui-menuSelectWidget' )
6020 .attr( 'role', 'menu' );
6021
6022 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
6023 // that reference properties not initialized at that time of parent class construction
6024 // TODO: Find a better way to handle post-constructor setup
6025 this.visible = false;
6026 this.$element.addClass( 'oo-ui-element-hidden' );
6027 };
6028
6029 /* Setup */
6030
6031 OO.inheritClass( OO.ui.MenuSelectWidget, OO.ui.SelectWidget );
6032 OO.mixinClass( OO.ui.MenuSelectWidget, OO.ui.mixin.ClippableElement );
6033
6034 /* Methods */
6035
6036 /**
6037 * Handles document mouse down events.
6038 *
6039 * @protected
6040 * @param {MouseEvent} e Mouse down event
6041 */
6042 OO.ui.MenuSelectWidget.prototype.onDocumentMouseDown = function ( e ) {
6043 if (
6044 !OO.ui.contains( this.$element[ 0 ], e.target, true ) &&
6045 ( !this.$widget || !OO.ui.contains( this.$widget[ 0 ], e.target, true ) )
6046 ) {
6047 this.toggle( false );
6048 }
6049 };
6050
6051 /**
6052 * @inheritdoc
6053 */
6054 OO.ui.MenuSelectWidget.prototype.onKeyDown = function ( e ) {
6055 var currentItem = this.getHighlightedItem() || this.getSelectedItem();
6056
6057 if ( !this.isDisabled() && this.isVisible() ) {
6058 switch ( e.keyCode ) {
6059 case OO.ui.Keys.LEFT:
6060 case OO.ui.Keys.RIGHT:
6061 // Do nothing if a text field is associated, arrow keys will be handled natively
6062 if ( !this.$input ) {
6063 OO.ui.MenuSelectWidget.parent.prototype.onKeyDown.call( this, e );
6064 }
6065 break;
6066 case OO.ui.Keys.ESCAPE:
6067 case OO.ui.Keys.TAB:
6068 if ( currentItem ) {
6069 currentItem.setHighlighted( false );
6070 }
6071 this.toggle( false );
6072 // Don't prevent tabbing away, prevent defocusing
6073 if ( e.keyCode === OO.ui.Keys.ESCAPE ) {
6074 e.preventDefault();
6075 e.stopPropagation();
6076 }
6077 break;
6078 default:
6079 OO.ui.MenuSelectWidget.parent.prototype.onKeyDown.call( this, e );
6080 return;
6081 }
6082 }
6083 };
6084
6085 /**
6086 * Update menu item visibility after input changes.
6087 *
6088 * @protected
6089 */
6090 OO.ui.MenuSelectWidget.prototype.updateItemVisibility = function () {
6091 var i, item,
6092 len = this.items.length,
6093 showAll = !this.isVisible(),
6094 filter = showAll ? null : this.getItemMatcher( this.$input.val() );
6095
6096 for ( i = 0; i < len; i++ ) {
6097 item = this.items[ i ];
6098 if ( item instanceof OO.ui.OptionWidget ) {
6099 item.toggle( showAll || filter( item ) );
6100 }
6101 }
6102
6103 // Reevaluate clipping
6104 this.clip();
6105 };
6106
6107 /**
6108 * @inheritdoc
6109 */
6110 OO.ui.MenuSelectWidget.prototype.bindKeyDownListener = function () {
6111 if ( this.$input ) {
6112 this.$input.on( 'keydown', this.onKeyDownHandler );
6113 } else {
6114 OO.ui.MenuSelectWidget.parent.prototype.bindKeyDownListener.call( this );
6115 }
6116 };
6117
6118 /**
6119 * @inheritdoc
6120 */
6121 OO.ui.MenuSelectWidget.prototype.unbindKeyDownListener = function () {
6122 if ( this.$input ) {
6123 this.$input.off( 'keydown', this.onKeyDownHandler );
6124 } else {
6125 OO.ui.MenuSelectWidget.parent.prototype.unbindKeyDownListener.call( this );
6126 }
6127 };
6128
6129 /**
6130 * @inheritdoc
6131 */
6132 OO.ui.MenuSelectWidget.prototype.bindKeyPressListener = function () {
6133 if ( this.$input ) {
6134 if ( this.filterFromInput ) {
6135 this.$input.on( 'keydown mouseup cut paste change input select', this.onInputEditHandler );
6136 }
6137 } else {
6138 OO.ui.MenuSelectWidget.parent.prototype.bindKeyPressListener.call( this );
6139 }
6140 };
6141
6142 /**
6143 * @inheritdoc
6144 */
6145 OO.ui.MenuSelectWidget.prototype.unbindKeyPressListener = function () {
6146 if ( this.$input ) {
6147 if ( this.filterFromInput ) {
6148 this.$input.off( 'keydown mouseup cut paste change input select', this.onInputEditHandler );
6149 this.updateItemVisibility();
6150 }
6151 } else {
6152 OO.ui.MenuSelectWidget.parent.prototype.unbindKeyPressListener.call( this );
6153 }
6154 };
6155
6156 /**
6157 * Choose an item.
6158 *
6159 * When a user chooses an item, the menu is closed.
6160 *
6161 * Note that ‘choose’ should never be modified programmatically. A user can choose an option with the keyboard
6162 * or mouse and it becomes selected. To select an item programmatically, use the #selectItem method.
6163 *
6164 * @param {OO.ui.OptionWidget} item Item to choose
6165 * @chainable
6166 */
6167 OO.ui.MenuSelectWidget.prototype.chooseItem = function ( item ) {
6168 OO.ui.MenuSelectWidget.parent.prototype.chooseItem.call( this, item );
6169 this.toggle( false );
6170 return this;
6171 };
6172
6173 /**
6174 * @inheritdoc
6175 */
6176 OO.ui.MenuSelectWidget.prototype.addItems = function ( items, index ) {
6177 // Parent method
6178 OO.ui.MenuSelectWidget.parent.prototype.addItems.call( this, items, index );
6179
6180 // Reevaluate clipping
6181 this.clip();
6182
6183 return this;
6184 };
6185
6186 /**
6187 * @inheritdoc
6188 */
6189 OO.ui.MenuSelectWidget.prototype.removeItems = function ( items ) {
6190 // Parent method
6191 OO.ui.MenuSelectWidget.parent.prototype.removeItems.call( this, items );
6192
6193 // Reevaluate clipping
6194 this.clip();
6195
6196 return this;
6197 };
6198
6199 /**
6200 * @inheritdoc
6201 */
6202 OO.ui.MenuSelectWidget.prototype.clearItems = function () {
6203 // Parent method
6204 OO.ui.MenuSelectWidget.parent.prototype.clearItems.call( this );
6205
6206 // Reevaluate clipping
6207 this.clip();
6208
6209 return this;
6210 };
6211
6212 /**
6213 * @inheritdoc
6214 */
6215 OO.ui.MenuSelectWidget.prototype.toggle = function ( visible ) {
6216 var change;
6217
6218 visible = ( visible === undefined ? !this.visible : !!visible ) && !!this.items.length;
6219 change = visible !== this.isVisible();
6220
6221 // Parent method
6222 OO.ui.MenuSelectWidget.parent.prototype.toggle.call( this, visible );
6223
6224 if ( change ) {
6225 if ( visible ) {
6226 this.bindKeyDownListener();
6227 this.bindKeyPressListener();
6228
6229 this.toggleClipping( true );
6230
6231 if ( this.getSelectedItem() ) {
6232 this.getSelectedItem().scrollElementIntoView( { duration: 0 } );
6233 }
6234
6235 // Auto-hide
6236 if ( this.autoHide ) {
6237 this.getElementDocument().addEventListener( 'mousedown', this.onDocumentMouseDownHandler, true );
6238 }
6239 } else {
6240 this.unbindKeyDownListener();
6241 this.unbindKeyPressListener();
6242 this.getElementDocument().removeEventListener( 'mousedown', this.onDocumentMouseDownHandler, true );
6243 this.toggleClipping( false );
6244 }
6245 }
6246
6247 return this;
6248 };
6249
6250 /**
6251 * DropdownWidgets are not menus themselves, rather they contain a menu of options created with
6252 * OO.ui.MenuOptionWidget. The DropdownWidget takes care of opening and displaying the menu so that
6253 * users can interact with it.
6254 *
6255 * If you want to use this within a HTML form, such as a OO.ui.FormLayout, use
6256 * OO.ui.DropdownInputWidget instead.
6257 *
6258 * @example
6259 * // Example: A DropdownWidget with a menu that contains three options
6260 * var dropDown = new OO.ui.DropdownWidget( {
6261 * label: 'Dropdown menu: Select a menu option',
6262 * menu: {
6263 * items: [
6264 * new OO.ui.MenuOptionWidget( {
6265 * data: 'a',
6266 * label: 'First'
6267 * } ),
6268 * new OO.ui.MenuOptionWidget( {
6269 * data: 'b',
6270 * label: 'Second'
6271 * } ),
6272 * new OO.ui.MenuOptionWidget( {
6273 * data: 'c',
6274 * label: 'Third'
6275 * } )
6276 * ]
6277 * }
6278 * } );
6279 *
6280 * $( 'body' ).append( dropDown.$element );
6281 *
6282 * dropDown.getMenu().selectItemByData( 'b' );
6283 *
6284 * dropDown.getMenu().getSelectedItem().getData(); // returns 'b'
6285 *
6286 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
6287 *
6288 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
6289 *
6290 * @class
6291 * @extends OO.ui.Widget
6292 * @mixins OO.ui.mixin.IconElement
6293 * @mixins OO.ui.mixin.IndicatorElement
6294 * @mixins OO.ui.mixin.LabelElement
6295 * @mixins OO.ui.mixin.TitledElement
6296 * @mixins OO.ui.mixin.TabIndexedElement
6297 *
6298 * @constructor
6299 * @param {Object} [config] Configuration options
6300 * @cfg {Object} [menu] Configuration options to pass to {@link OO.ui.FloatingMenuSelectWidget menu select widget}
6301 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
6302 * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
6303 * containing `<div>` and has a larger area. By default, the menu uses relative positioning.
6304 */
6305 OO.ui.DropdownWidget = function OoUiDropdownWidget( config ) {
6306 // Configuration initialization
6307 config = $.extend( { indicator: 'down' }, config );
6308
6309 // Parent constructor
6310 OO.ui.DropdownWidget.parent.call( this, config );
6311
6312 // Properties (must be set before TabIndexedElement constructor call)
6313 this.$handle = this.$( '<span>' );
6314 this.$overlay = config.$overlay || this.$element;
6315
6316 // Mixin constructors
6317 OO.ui.mixin.IconElement.call( this, config );
6318 OO.ui.mixin.IndicatorElement.call( this, config );
6319 OO.ui.mixin.LabelElement.call( this, config );
6320 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$label } ) );
6321 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$handle } ) );
6322
6323 // Properties
6324 this.menu = new OO.ui.FloatingMenuSelectWidget( $.extend( {
6325 widget: this,
6326 $container: this.$element
6327 }, config.menu ) );
6328
6329 // Events
6330 this.$handle.on( {
6331 click: this.onClick.bind( this ),
6332 keydown: this.onKeyDown.bind( this )
6333 } );
6334 this.menu.connect( this, { select: 'onMenuSelect' } );
6335
6336 // Initialization
6337 this.$handle
6338 .addClass( 'oo-ui-dropdownWidget-handle' )
6339 .append( this.$icon, this.$label, this.$indicator );
6340 this.$element
6341 .addClass( 'oo-ui-dropdownWidget' )
6342 .append( this.$handle );
6343 this.$overlay.append( this.menu.$element );
6344 };
6345
6346 /* Setup */
6347
6348 OO.inheritClass( OO.ui.DropdownWidget, OO.ui.Widget );
6349 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.IconElement );
6350 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.IndicatorElement );
6351 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.LabelElement );
6352 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.TitledElement );
6353 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.TabIndexedElement );
6354
6355 /* Methods */
6356
6357 /**
6358 * Get the menu.
6359 *
6360 * @return {OO.ui.MenuSelectWidget} Menu of widget
6361 */
6362 OO.ui.DropdownWidget.prototype.getMenu = function () {
6363 return this.menu;
6364 };
6365
6366 /**
6367 * Handles menu select events.
6368 *
6369 * @private
6370 * @param {OO.ui.MenuOptionWidget} item Selected menu item
6371 */
6372 OO.ui.DropdownWidget.prototype.onMenuSelect = function ( item ) {
6373 var selectedLabel;
6374
6375 if ( !item ) {
6376 this.setLabel( null );
6377 return;
6378 }
6379
6380 selectedLabel = item.getLabel();
6381
6382 // If the label is a DOM element, clone it, because setLabel will append() it
6383 if ( selectedLabel instanceof jQuery ) {
6384 selectedLabel = selectedLabel.clone();
6385 }
6386
6387 this.setLabel( selectedLabel );
6388 };
6389
6390 /**
6391 * Handle mouse click events.
6392 *
6393 * @private
6394 * @param {jQuery.Event} e Mouse click event
6395 */
6396 OO.ui.DropdownWidget.prototype.onClick = function ( e ) {
6397 if ( !this.isDisabled() && e.which === OO.ui.MouseButtons.LEFT ) {
6398 this.menu.toggle();
6399 }
6400 return false;
6401 };
6402
6403 /**
6404 * Handle key down events.
6405 *
6406 * @private
6407 * @param {jQuery.Event} e Key down event
6408 */
6409 OO.ui.DropdownWidget.prototype.onKeyDown = function ( e ) {
6410 if (
6411 !this.isDisabled() &&
6412 (
6413 e.which === OO.ui.Keys.ENTER ||
6414 (
6415 !this.menu.isVisible() &&
6416 (
6417 e.which === OO.ui.Keys.SPACE ||
6418 e.which === OO.ui.Keys.UP ||
6419 e.which === OO.ui.Keys.DOWN
6420 )
6421 )
6422 )
6423 ) {
6424 this.menu.toggle();
6425 return false;
6426 }
6427 };
6428
6429 /**
6430 * RadioOptionWidget is an option widget that looks like a radio button.
6431 * The class is used with OO.ui.RadioSelectWidget to create a selection of radio options.
6432 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information.
6433 *
6434 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Button_selects_and_option
6435 *
6436 * @class
6437 * @extends OO.ui.OptionWidget
6438 *
6439 * @constructor
6440 * @param {Object} [config] Configuration options
6441 */
6442 OO.ui.RadioOptionWidget = function OoUiRadioOptionWidget( config ) {
6443 // Configuration initialization
6444 config = config || {};
6445
6446 // Properties (must be done before parent constructor which calls #setDisabled)
6447 this.radio = new OO.ui.RadioInputWidget( { value: config.data, tabIndex: -1 } );
6448
6449 // Parent constructor
6450 OO.ui.RadioOptionWidget.parent.call( this, config );
6451
6452 // Events
6453 this.radio.$input.on( 'focus', this.onInputFocus.bind( this ) );
6454
6455 // Initialization
6456 // Remove implicit role, we're handling it ourselves
6457 this.radio.$input.attr( 'role', 'presentation' );
6458 this.$element
6459 .addClass( 'oo-ui-radioOptionWidget' )
6460 .attr( 'role', 'radio' )
6461 .attr( 'aria-checked', 'false' )
6462 .removeAttr( 'aria-selected' )
6463 .prepend( this.radio.$element );
6464 };
6465
6466 /* Setup */
6467
6468 OO.inheritClass( OO.ui.RadioOptionWidget, OO.ui.OptionWidget );
6469
6470 /* Static Properties */
6471
6472 OO.ui.RadioOptionWidget.static.highlightable = false;
6473
6474 OO.ui.RadioOptionWidget.static.scrollIntoViewOnSelect = true;
6475
6476 OO.ui.RadioOptionWidget.static.pressable = false;
6477
6478 OO.ui.RadioOptionWidget.static.tagName = 'label';
6479
6480 /* Methods */
6481
6482 /**
6483 * @param {jQuery.Event} e Focus event
6484 * @private
6485 */
6486 OO.ui.RadioOptionWidget.prototype.onInputFocus = function () {
6487 this.radio.$input.blur();
6488 this.$element.parent().focus();
6489 };
6490
6491 /**
6492 * @inheritdoc
6493 */
6494 OO.ui.RadioOptionWidget.prototype.setSelected = function ( state ) {
6495 OO.ui.RadioOptionWidget.parent.prototype.setSelected.call( this, state );
6496
6497 this.radio.setSelected( state );
6498 this.$element
6499 .attr( 'aria-checked', state.toString() )
6500 .removeAttr( 'aria-selected' );
6501
6502 return this;
6503 };
6504
6505 /**
6506 * @inheritdoc
6507 */
6508 OO.ui.RadioOptionWidget.prototype.setDisabled = function ( disabled ) {
6509 OO.ui.RadioOptionWidget.parent.prototype.setDisabled.call( this, disabled );
6510
6511 this.radio.setDisabled( this.isDisabled() );
6512
6513 return this;
6514 };
6515
6516 /**
6517 * RadioSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains radio
6518 * options and is used together with OO.ui.RadioOptionWidget. The RadioSelectWidget provides
6519 * an interface for adding, removing and selecting options.
6520 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
6521 *
6522 * If you want to use this within a HTML form, such as a OO.ui.FormLayout, use
6523 * OO.ui.RadioSelectInputWidget instead.
6524 *
6525 * @example
6526 * // A RadioSelectWidget with RadioOptions.
6527 * var option1 = new OO.ui.RadioOptionWidget( {
6528 * data: 'a',
6529 * label: 'Selected radio option'
6530 * } );
6531 *
6532 * var option2 = new OO.ui.RadioOptionWidget( {
6533 * data: 'b',
6534 * label: 'Unselected radio option'
6535 * } );
6536 *
6537 * var radioSelect=new OO.ui.RadioSelectWidget( {
6538 * items: [ option1, option2 ]
6539 * } );
6540 *
6541 * // Select 'option 1' using the RadioSelectWidget's selectItem() method.
6542 * radioSelect.selectItem( option1 );
6543 *
6544 * $( 'body' ).append( radioSelect.$element );
6545 *
6546 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
6547
6548 *
6549 * @class
6550 * @extends OO.ui.SelectWidget
6551 * @mixins OO.ui.mixin.TabIndexedElement
6552 *
6553 * @constructor
6554 * @param {Object} [config] Configuration options
6555 */
6556 OO.ui.RadioSelectWidget = function OoUiRadioSelectWidget( config ) {
6557 // Parent constructor
6558 OO.ui.RadioSelectWidget.parent.call( this, config );
6559
6560 // Mixin constructors
6561 OO.ui.mixin.TabIndexedElement.call( this, config );
6562
6563 // Events
6564 this.$element.on( {
6565 focus: this.bindKeyDownListener.bind( this ),
6566 blur: this.unbindKeyDownListener.bind( this )
6567 } );
6568
6569 // Initialization
6570 this.$element
6571 .addClass( 'oo-ui-radioSelectWidget' )
6572 .attr( 'role', 'radiogroup' );
6573 };
6574
6575 /* Setup */
6576
6577 OO.inheritClass( OO.ui.RadioSelectWidget, OO.ui.SelectWidget );
6578 OO.mixinClass( OO.ui.RadioSelectWidget, OO.ui.mixin.TabIndexedElement );
6579
6580 /**
6581 * Element that will stick under a specified container, even when it is inserted elsewhere in the
6582 * document (for example, in a OO.ui.Window's $overlay).
6583 *
6584 * The elements's position is automatically calculated and maintained when window is resized or the
6585 * page is scrolled. If you reposition the container manually, you have to call #position to make
6586 * sure the element is still placed correctly.
6587 *
6588 * As positioning is only possible when both the element and the container are attached to the DOM
6589 * and visible, it's only done after you call #togglePositioning. You might want to do this inside
6590 * the #toggle method to display a floating popup, for example.
6591 *
6592 * @abstract
6593 * @class
6594 *
6595 * @constructor
6596 * @param {Object} [config] Configuration options
6597 * @cfg {jQuery} [$floatable] Node to position, assigned to #$floatable, omit to use #$element
6598 * @cfg {jQuery} [$floatableContainer] Node to position below
6599 */
6600 OO.ui.mixin.FloatableElement = function OoUiMixinFloatableElement( config ) {
6601 // Configuration initialization
6602 config = config || {};
6603
6604 // Properties
6605 this.$floatable = null;
6606 this.$floatableContainer = null;
6607 this.$floatableWindow = null;
6608 this.$floatableClosestScrollable = null;
6609 this.onFloatableScrollHandler = this.position.bind( this );
6610 this.onFloatableWindowResizeHandler = this.position.bind( this );
6611
6612 // Initialization
6613 this.setFloatableContainer( config.$floatableContainer );
6614 this.setFloatableElement( config.$floatable || this.$element );
6615 };
6616
6617 /* Methods */
6618
6619 /**
6620 * Set floatable element.
6621 *
6622 * If an element is already set, it will be cleaned up before setting up the new element.
6623 *
6624 * @param {jQuery} $floatable Element to make floatable
6625 */
6626 OO.ui.mixin.FloatableElement.prototype.setFloatableElement = function ( $floatable ) {
6627 if ( this.$floatable ) {
6628 this.$floatable.removeClass( 'oo-ui-floatableElement-floatable' );
6629 this.$floatable.css( { left: '', top: '' } );
6630 }
6631
6632 this.$floatable = $floatable.addClass( 'oo-ui-floatableElement-floatable' );
6633 this.position();
6634 };
6635
6636 /**
6637 * Set floatable container.
6638 *
6639 * The element will be always positioned under the specified container.
6640 *
6641 * @param {jQuery|null} $floatableContainer Container to keep visible, or null to unset
6642 */
6643 OO.ui.mixin.FloatableElement.prototype.setFloatableContainer = function ( $floatableContainer ) {
6644 this.$floatableContainer = $floatableContainer;
6645 if ( this.$floatable ) {
6646 this.position();
6647 }
6648 };
6649
6650 /**
6651 * Toggle positioning.
6652 *
6653 * Do not turn positioning on until after the element is attached to the DOM and visible.
6654 *
6655 * @param {boolean} [positioning] Enable positioning, omit to toggle
6656 * @chainable
6657 */
6658 OO.ui.mixin.FloatableElement.prototype.togglePositioning = function ( positioning ) {
6659 var closestScrollableOfContainer, closestScrollableOfFloatable;
6660
6661 positioning = positioning === undefined ? !this.positioning : !!positioning;
6662
6663 if ( this.positioning !== positioning ) {
6664 this.positioning = positioning;
6665
6666 closestScrollableOfContainer = OO.ui.Element.static.getClosestScrollableContainer( this.$floatableContainer[ 0 ] );
6667 closestScrollableOfFloatable = OO.ui.Element.static.getClosestScrollableContainer( this.$floatable[ 0 ] );
6668 this.needsCustomPosition = closestScrollableOfContainer !== closestScrollableOfFloatable;
6669 // If the scrollable is the root, we have to listen to scroll events
6670 // on the window because of browser inconsistencies.
6671 if ( $( closestScrollableOfContainer ).is( 'html, body' ) ) {
6672 closestScrollableOfContainer = OO.ui.Element.static.getWindow( closestScrollableOfContainer );
6673 }
6674
6675 if ( positioning ) {
6676 this.$floatableWindow = $( this.getElementWindow() );
6677 this.$floatableWindow.on( 'resize', this.onFloatableWindowResizeHandler );
6678
6679 this.$floatableClosestScrollable = $( closestScrollableOfContainer );
6680 this.$floatableClosestScrollable.on( 'scroll', this.onFloatableScrollHandler );
6681
6682 // Initial position after visible
6683 this.position();
6684 } else {
6685 if ( this.$floatableWindow ) {
6686 this.$floatableWindow.off( 'resize', this.onFloatableWindowResizeHandler );
6687 this.$floatableWindow = null;
6688 }
6689
6690 if ( this.$floatableClosestScrollable ) {
6691 this.$floatableClosestScrollable.off( 'scroll', this.onFloatableScrollHandler );
6692 this.$floatableClosestScrollable = null;
6693 }
6694
6695 this.$floatable.css( { left: '', top: '' } );
6696 }
6697 }
6698
6699 return this;
6700 };
6701
6702 /**
6703 * Check whether the bottom edge of the given element is within the viewport of the given container.
6704 *
6705 * @private
6706 * @param {jQuery} $element
6707 * @param {jQuery} $container
6708 * @return {boolean}
6709 */
6710 OO.ui.mixin.FloatableElement.prototype.isElementInViewport = function ( $element, $container ) {
6711 var elemRect, contRect,
6712 topEdgeInBounds = false,
6713 leftEdgeInBounds = false,
6714 bottomEdgeInBounds = false,
6715 rightEdgeInBounds = false;
6716
6717 elemRect = $element[ 0 ].getBoundingClientRect();
6718 if ( $container[ 0 ] === window ) {
6719 contRect = {
6720 top: 0,
6721 left: 0,
6722 right: document.documentElement.clientWidth,
6723 bottom: document.documentElement.clientHeight
6724 };
6725 } else {
6726 contRect = $container[ 0 ].getBoundingClientRect();
6727 }
6728
6729 if ( elemRect.top >= contRect.top && elemRect.top <= contRect.bottom ) {
6730 topEdgeInBounds = true;
6731 }
6732 if ( elemRect.left >= contRect.left && elemRect.left <= contRect.right ) {
6733 leftEdgeInBounds = true;
6734 }
6735 if ( elemRect.bottom >= contRect.top && elemRect.bottom <= contRect.bottom ) {
6736 bottomEdgeInBounds = true;
6737 }
6738 if ( elemRect.right >= contRect.left && elemRect.right <= contRect.right ) {
6739 rightEdgeInBounds = true;
6740 }
6741
6742 // We only care that any part of the bottom edge is visible
6743 return bottomEdgeInBounds && ( leftEdgeInBounds || rightEdgeInBounds );
6744 };
6745
6746 /**
6747 * Position the floatable below its container.
6748 *
6749 * This should only be done when both of them are attached to the DOM and visible.
6750 *
6751 * @chainable
6752 */
6753 OO.ui.mixin.FloatableElement.prototype.position = function () {
6754 var pos;
6755
6756 if ( !this.positioning ) {
6757 return this;
6758 }
6759
6760 if ( !this.isElementInViewport( this.$floatableContainer, this.$floatableClosestScrollable ) ) {
6761 this.$floatable.addClass( 'oo-ui-floatableElement-hidden' );
6762 return;
6763 } else {
6764 this.$floatable.removeClass( 'oo-ui-floatableElement-hidden' );
6765 }
6766
6767 if ( !this.needsCustomPosition ) {
6768 return;
6769 }
6770
6771 pos = OO.ui.Element.static.getRelativePosition( this.$floatableContainer, this.$floatable.offsetParent() );
6772
6773 // Position under container
6774 pos.top += this.$floatableContainer.height();
6775 this.$floatable.css( pos );
6776
6777 // We updated the position, so re-evaluate the clipping state.
6778 // (ClippableElement does not listen to 'scroll' events on $floatableContainer's parent, and so
6779 // will not notice the need to update itself.)
6780 // TODO: This is terrible, we shouldn't need to know about ClippableElement at all here. Why does
6781 // it not listen to the right events in the right places?
6782 if ( this.clip ) {
6783 this.clip();
6784 }
6785
6786 return this;
6787 };
6788
6789 /**
6790 * FloatingMenuSelectWidget is a menu that will stick under a specified
6791 * container, even when it is inserted elsewhere in the document (for example,
6792 * in a OO.ui.Window's $overlay). This is sometimes necessary to prevent the
6793 * menu from being clipped too aggresively.
6794 *
6795 * The menu's position is automatically calculated and maintained when the menu
6796 * is toggled or the window is resized.
6797 *
6798 * See OO.ui.ComboBoxInputWidget for an example of a widget that uses this class.
6799 *
6800 * @class
6801 * @extends OO.ui.MenuSelectWidget
6802 * @mixins OO.ui.mixin.FloatableElement
6803 *
6804 * @constructor
6805 * @param {OO.ui.Widget} [inputWidget] Widget to provide the menu for.
6806 * Deprecated, omit this parameter and specify `$container` instead.
6807 * @param {Object} [config] Configuration options
6808 * @cfg {jQuery} [$container=inputWidget.$element] Element to render menu under
6809 */
6810 OO.ui.FloatingMenuSelectWidget = function OoUiFloatingMenuSelectWidget( inputWidget, config ) {
6811 // Allow 'inputWidget' parameter and config for backwards compatibility
6812 if ( OO.isPlainObject( inputWidget ) && config === undefined ) {
6813 config = inputWidget;
6814 inputWidget = config.inputWidget;
6815 }
6816
6817 // Configuration initialization
6818 config = config || {};
6819
6820 // Parent constructor
6821 OO.ui.FloatingMenuSelectWidget.parent.call( this, config );
6822
6823 // Properties (must be set before mixin constructors)
6824 this.inputWidget = inputWidget; // For backwards compatibility
6825 this.$container = config.$container || this.inputWidget.$element;
6826
6827 // Mixins constructors
6828 OO.ui.mixin.FloatableElement.call( this, $.extend( {}, config, { $floatableContainer: this.$container } ) );
6829
6830 // Initialization
6831 this.$element.addClass( 'oo-ui-floatingMenuSelectWidget' );
6832 // For backwards compatibility
6833 this.$element.addClass( 'oo-ui-textInputMenuSelectWidget' );
6834 };
6835
6836 /* Setup */
6837
6838 OO.inheritClass( OO.ui.FloatingMenuSelectWidget, OO.ui.MenuSelectWidget );
6839 OO.mixinClass( OO.ui.FloatingMenuSelectWidget, OO.ui.mixin.FloatableElement );
6840
6841 // For backwards compatibility
6842 OO.ui.TextInputMenuSelectWidget = OO.ui.FloatingMenuSelectWidget;
6843
6844 /* Methods */
6845
6846 /**
6847 * @inheritdoc
6848 */
6849 OO.ui.FloatingMenuSelectWidget.prototype.toggle = function ( visible ) {
6850 var change;
6851 visible = visible === undefined ? !this.isVisible() : !!visible;
6852 change = visible !== this.isVisible();
6853
6854 if ( change && visible ) {
6855 // Make sure the width is set before the parent method runs.
6856 this.setIdealSize( this.$container.width() );
6857 }
6858
6859 // Parent method
6860 // This will call this.clip(), which is nonsensical since we're not positioned yet...
6861 OO.ui.FloatingMenuSelectWidget.parent.prototype.toggle.call( this, visible );
6862
6863 if ( change ) {
6864 this.togglePositioning( this.isVisible() );
6865 }
6866
6867 return this;
6868 };
6869
6870 /**
6871 * InputWidget is the base class for all input widgets, which
6872 * include {@link OO.ui.TextInputWidget text inputs}, {@link OO.ui.CheckboxInputWidget checkbox inputs},
6873 * {@link OO.ui.RadioInputWidget radio inputs}, and {@link OO.ui.ButtonInputWidget button inputs}.
6874 * See the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
6875 *
6876 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
6877 *
6878 * @abstract
6879 * @class
6880 * @extends OO.ui.Widget
6881 * @mixins OO.ui.mixin.FlaggedElement
6882 * @mixins OO.ui.mixin.TabIndexedElement
6883 * @mixins OO.ui.mixin.TitledElement
6884 * @mixins OO.ui.mixin.AccessKeyedElement
6885 *
6886 * @constructor
6887 * @param {Object} [config] Configuration options
6888 * @cfg {string} [name=''] The value of the input’s HTML `name` attribute.
6889 * @cfg {string} [value=''] The value of the input.
6890 * @cfg {string} [dir] The directionality of the input (ltr/rtl).
6891 * @cfg {Function} [inputFilter] The name of an input filter function. Input filters modify the value of an input
6892 * before it is accepted.
6893 */
6894 OO.ui.InputWidget = function OoUiInputWidget( config ) {
6895 // Configuration initialization
6896 config = config || {};
6897
6898 // Parent constructor
6899 OO.ui.InputWidget.parent.call( this, config );
6900
6901 // Properties
6902 // See #reusePreInfuseDOM about config.$input
6903 this.$input = config.$input || this.getInputElement( config );
6904 this.value = '';
6905 this.inputFilter = config.inputFilter;
6906
6907 // Mixin constructors
6908 OO.ui.mixin.FlaggedElement.call( this, config );
6909 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$input } ) );
6910 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$input } ) );
6911 OO.ui.mixin.AccessKeyedElement.call( this, $.extend( {}, config, { $accessKeyed: this.$input } ) );
6912
6913 // Events
6914 this.$input.on( 'keydown mouseup cut paste change input select', this.onEdit.bind( this ) );
6915
6916 // Initialization
6917 this.$input
6918 .addClass( 'oo-ui-inputWidget-input' )
6919 .attr( 'name', config.name )
6920 .prop( 'disabled', this.isDisabled() );
6921 this.$element
6922 .addClass( 'oo-ui-inputWidget' )
6923 .append( this.$input );
6924 this.setValue( config.value );
6925 if ( config.dir ) {
6926 this.setDir( config.dir );
6927 }
6928 };
6929
6930 /* Setup */
6931
6932 OO.inheritClass( OO.ui.InputWidget, OO.ui.Widget );
6933 OO.mixinClass( OO.ui.InputWidget, OO.ui.mixin.FlaggedElement );
6934 OO.mixinClass( OO.ui.InputWidget, OO.ui.mixin.TabIndexedElement );
6935 OO.mixinClass( OO.ui.InputWidget, OO.ui.mixin.TitledElement );
6936 OO.mixinClass( OO.ui.InputWidget, OO.ui.mixin.AccessKeyedElement );
6937
6938 /* Static Properties */
6939
6940 OO.ui.InputWidget.static.supportsSimpleLabel = true;
6941
6942 /* Static Methods */
6943
6944 /**
6945 * @inheritdoc
6946 */
6947 OO.ui.InputWidget.static.reusePreInfuseDOM = function ( node, config ) {
6948 config = OO.ui.InputWidget.parent.static.reusePreInfuseDOM( node, config );
6949 // Reusing $input lets browsers preserve inputted values across page reloads (T114134)
6950 config.$input = $( node ).find( '.oo-ui-inputWidget-input' );
6951 return config;
6952 };
6953
6954 /**
6955 * @inheritdoc
6956 */
6957 OO.ui.InputWidget.static.gatherPreInfuseState = function ( node, config ) {
6958 var state = OO.ui.InputWidget.parent.static.gatherPreInfuseState( node, config );
6959 if ( config.$input && config.$input.length ) {
6960 state.value = config.$input.val();
6961 // Might be better in TabIndexedElement, but it's awkward to do there because mixins are awkward
6962 state.focus = config.$input.is( ':focus' );
6963 }
6964 return state;
6965 };
6966
6967 /* Events */
6968
6969 /**
6970 * @event change
6971 *
6972 * A change event is emitted when the value of the input changes.
6973 *
6974 * @param {string} value
6975 */
6976
6977 /* Methods */
6978
6979 /**
6980 * Get input element.
6981 *
6982 * Subclasses of OO.ui.InputWidget use the `config` parameter to produce different elements in
6983 * different circumstances. The element must have a `value` property (like form elements).
6984 *
6985 * @protected
6986 * @param {Object} config Configuration options
6987 * @return {jQuery} Input element
6988 */
6989 OO.ui.InputWidget.prototype.getInputElement = function () {
6990 return $( '<input>' );
6991 };
6992
6993 /**
6994 * Handle potentially value-changing events.
6995 *
6996 * @private
6997 * @param {jQuery.Event} e Key down, mouse up, cut, paste, change, input, or select event
6998 */
6999 OO.ui.InputWidget.prototype.onEdit = function () {
7000 var widget = this;
7001 if ( !this.isDisabled() ) {
7002 // Allow the stack to clear so the value will be updated
7003 setTimeout( function () {
7004 widget.setValue( widget.$input.val() );
7005 } );
7006 }
7007 };
7008
7009 /**
7010 * Get the value of the input.
7011 *
7012 * @return {string} Input value
7013 */
7014 OO.ui.InputWidget.prototype.getValue = function () {
7015 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
7016 // it, and we won't know unless they're kind enough to trigger a 'change' event.
7017 var value = this.$input.val();
7018 if ( this.value !== value ) {
7019 this.setValue( value );
7020 }
7021 return this.value;
7022 };
7023
7024 /**
7025 * Set the directionality of the input, either RTL (right-to-left) or LTR (left-to-right).
7026 *
7027 * @deprecated since v0.13.1; use #setDir directly
7028 * @param {boolean} isRTL Directionality is right-to-left
7029 * @chainable
7030 */
7031 OO.ui.InputWidget.prototype.setRTL = function ( isRTL ) {
7032 this.setDir( isRTL ? 'rtl' : 'ltr' );
7033 return this;
7034 };
7035
7036 /**
7037 * Set the directionality of the input.
7038 *
7039 * @param {string} dir Text directionality: 'ltr', 'rtl' or 'auto'
7040 * @chainable
7041 */
7042 OO.ui.InputWidget.prototype.setDir = function ( dir ) {
7043 this.$input.prop( 'dir', dir );
7044 return this;
7045 };
7046
7047 /**
7048 * Set the value of the input.
7049 *
7050 * @param {string} value New value
7051 * @fires change
7052 * @chainable
7053 */
7054 OO.ui.InputWidget.prototype.setValue = function ( value ) {
7055 value = this.cleanUpValue( value );
7056 // Update the DOM if it has changed. Note that with cleanUpValue, it
7057 // is possible for the DOM value to change without this.value changing.
7058 if ( this.$input.val() !== value ) {
7059 this.$input.val( value );
7060 }
7061 if ( this.value !== value ) {
7062 this.value = value;
7063 this.emit( 'change', this.value );
7064 }
7065 return this;
7066 };
7067
7068 /**
7069 * Clean up incoming value.
7070 *
7071 * Ensures value is a string, and converts undefined and null to empty string.
7072 *
7073 * @private
7074 * @param {string} value Original value
7075 * @return {string} Cleaned up value
7076 */
7077 OO.ui.InputWidget.prototype.cleanUpValue = function ( value ) {
7078 if ( value === undefined || value === null ) {
7079 return '';
7080 } else if ( this.inputFilter ) {
7081 return this.inputFilter( String( value ) );
7082 } else {
7083 return String( value );
7084 }
7085 };
7086
7087 /**
7088 * Simulate the behavior of clicking on a label bound to this input. This method is only called by
7089 * {@link OO.ui.LabelWidget LabelWidget} and {@link OO.ui.FieldLayout FieldLayout}. It should not be
7090 * called directly.
7091 */
7092 OO.ui.InputWidget.prototype.simulateLabelClick = function () {
7093 if ( !this.isDisabled() ) {
7094 if ( this.$input.is( ':checkbox, :radio' ) ) {
7095 this.$input.click();
7096 }
7097 if ( this.$input.is( ':input' ) ) {
7098 this.$input[ 0 ].focus();
7099 }
7100 }
7101 };
7102
7103 /**
7104 * @inheritdoc
7105 */
7106 OO.ui.InputWidget.prototype.setDisabled = function ( state ) {
7107 OO.ui.InputWidget.parent.prototype.setDisabled.call( this, state );
7108 if ( this.$input ) {
7109 this.$input.prop( 'disabled', this.isDisabled() );
7110 }
7111 return this;
7112 };
7113
7114 /**
7115 * Focus the input.
7116 *
7117 * @chainable
7118 */
7119 OO.ui.InputWidget.prototype.focus = function () {
7120 this.$input[ 0 ].focus();
7121 return this;
7122 };
7123
7124 /**
7125 * Blur the input.
7126 *
7127 * @chainable
7128 */
7129 OO.ui.InputWidget.prototype.blur = function () {
7130 this.$input[ 0 ].blur();
7131 return this;
7132 };
7133
7134 /**
7135 * @inheritdoc
7136 */
7137 OO.ui.InputWidget.prototype.restorePreInfuseState = function ( state ) {
7138 OO.ui.InputWidget.parent.prototype.restorePreInfuseState.call( this, state );
7139 if ( state.value !== undefined && state.value !== this.getValue() ) {
7140 this.setValue( state.value );
7141 }
7142 if ( state.focus ) {
7143 this.focus();
7144 }
7145 };
7146
7147 /**
7148 * ButtonInputWidget is used to submit HTML forms and is intended to be used within
7149 * a OO.ui.FormLayout. If you do not need the button to work with HTML forms, you probably
7150 * want to use OO.ui.ButtonWidget instead. Button input widgets can be rendered as either an
7151 * HTML `<button/>` (the default) or an HTML `<input/>` tags. See the
7152 * [OOjs UI documentation on MediaWiki] [1] for more information.
7153 *
7154 * @example
7155 * // A ButtonInputWidget rendered as an HTML button, the default.
7156 * var button = new OO.ui.ButtonInputWidget( {
7157 * label: 'Input button',
7158 * icon: 'check',
7159 * value: 'check'
7160 * } );
7161 * $( 'body' ).append( button.$element );
7162 *
7163 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs#Button_inputs
7164 *
7165 * @class
7166 * @extends OO.ui.InputWidget
7167 * @mixins OO.ui.mixin.ButtonElement
7168 * @mixins OO.ui.mixin.IconElement
7169 * @mixins OO.ui.mixin.IndicatorElement
7170 * @mixins OO.ui.mixin.LabelElement
7171 * @mixins OO.ui.mixin.TitledElement
7172 *
7173 * @constructor
7174 * @param {Object} [config] Configuration options
7175 * @cfg {string} [type='button'] The value of the HTML `'type'` attribute: 'button', 'submit' or 'reset'.
7176 * @cfg {boolean} [useInputTag=false] Use an `<input/>` tag instead of a `<button/>` tag, the default.
7177 * Widgets configured to be an `<input/>` do not support {@link #icon icons} and {@link #indicator indicators},
7178 * non-plaintext {@link #label labels}, or {@link #value values}. In general, useInputTag should only
7179 * be set to `true` when there’s need to support IE 6 in a form with multiple buttons.
7180 */
7181 OO.ui.ButtonInputWidget = function OoUiButtonInputWidget( config ) {
7182 // Configuration initialization
7183 config = $.extend( { type: 'button', useInputTag: false }, config );
7184
7185 // See InputWidget#reusePreInfuseDOM about config.$input
7186 if ( config.$input ) {
7187 config.$input.empty();
7188 }
7189
7190 // Properties (must be set before parent constructor, which calls #setValue)
7191 this.useInputTag = config.useInputTag;
7192
7193 // Parent constructor
7194 OO.ui.ButtonInputWidget.parent.call( this, config );
7195
7196 // Mixin constructors
7197 OO.ui.mixin.ButtonElement.call( this, $.extend( {}, config, { $button: this.$input } ) );
7198 OO.ui.mixin.IconElement.call( this, config );
7199 OO.ui.mixin.IndicatorElement.call( this, config );
7200 OO.ui.mixin.LabelElement.call( this, config );
7201 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$input } ) );
7202
7203 // Initialization
7204 if ( !config.useInputTag ) {
7205 this.$input.append( this.$icon, this.$label, this.$indicator );
7206 }
7207 this.$element.addClass( 'oo-ui-buttonInputWidget' );
7208 };
7209
7210 /* Setup */
7211
7212 OO.inheritClass( OO.ui.ButtonInputWidget, OO.ui.InputWidget );
7213 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.ButtonElement );
7214 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.IconElement );
7215 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.IndicatorElement );
7216 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.LabelElement );
7217 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.TitledElement );
7218
7219 /* Static Properties */
7220
7221 /**
7222 * Disable generating `<label>` elements for buttons. One would very rarely need additional label
7223 * for a button, and it's already a big clickable target, and it causes unexpected rendering.
7224 */
7225 OO.ui.ButtonInputWidget.static.supportsSimpleLabel = false;
7226
7227 /* Methods */
7228
7229 /**
7230 * @inheritdoc
7231 * @protected
7232 */
7233 OO.ui.ButtonInputWidget.prototype.getInputElement = function ( config ) {
7234 var type;
7235 type = [ 'button', 'submit', 'reset' ].indexOf( config.type ) !== -1 ? config.type : 'button';
7236 return $( '<' + ( config.useInputTag ? 'input' : 'button' ) + ' type="' + type + '">' );
7237 };
7238
7239 /**
7240 * Set label value.
7241 *
7242 * If #useInputTag is `true`, the label is set as the `value` of the `<input/>` tag.
7243 *
7244 * @param {jQuery|string|Function|null} label Label nodes, text, a function that returns nodes or
7245 * text, or `null` for no label
7246 * @chainable
7247 */
7248 OO.ui.ButtonInputWidget.prototype.setLabel = function ( label ) {
7249 if ( typeof label === 'function' ) {
7250 label = OO.ui.resolveMsg( label );
7251 }
7252
7253 if ( this.useInputTag ) {
7254 // Discard non-plaintext labels
7255 if ( typeof label !== 'string' ) {
7256 label = '';
7257 }
7258
7259 this.$input.val( label );
7260 }
7261
7262 return OO.ui.mixin.LabelElement.prototype.setLabel.call( this, label );
7263 };
7264
7265 /**
7266 * Set the value of the input.
7267 *
7268 * This method is disabled for button inputs configured as {@link #useInputTag <input/> tags}, as
7269 * they do not support {@link #value values}.
7270 *
7271 * @param {string} value New value
7272 * @chainable
7273 */
7274 OO.ui.ButtonInputWidget.prototype.setValue = function ( value ) {
7275 if ( !this.useInputTag ) {
7276 OO.ui.ButtonInputWidget.parent.prototype.setValue.call( this, value );
7277 }
7278 return this;
7279 };
7280
7281 /**
7282 * CheckboxInputWidgets, like HTML checkboxes, can be selected and/or configured with a value.
7283 * Note that these {@link OO.ui.InputWidget input widgets} are best laid out
7284 * in {@link OO.ui.FieldLayout field layouts} that use the {@link OO.ui.FieldLayout#align inline}
7285 * alignment. For more information, please see the [OOjs UI documentation on MediaWiki][1].
7286 *
7287 * This widget can be used inside a HTML form, such as a OO.ui.FormLayout.
7288 *
7289 * @example
7290 * // An example of selected, unselected, and disabled checkbox inputs
7291 * var checkbox1=new OO.ui.CheckboxInputWidget( {
7292 * value: 'a',
7293 * selected: true
7294 * } );
7295 * var checkbox2=new OO.ui.CheckboxInputWidget( {
7296 * value: 'b'
7297 * } );
7298 * var checkbox3=new OO.ui.CheckboxInputWidget( {
7299 * value:'c',
7300 * disabled: true
7301 * } );
7302 * // Create a fieldset layout with fields for each checkbox.
7303 * var fieldset = new OO.ui.FieldsetLayout( {
7304 * label: 'Checkboxes'
7305 * } );
7306 * fieldset.addItems( [
7307 * new OO.ui.FieldLayout( checkbox1, { label: 'Selected checkbox', align: 'inline' } ),
7308 * new OO.ui.FieldLayout( checkbox2, { label: 'Unselected checkbox', align: 'inline' } ),
7309 * new OO.ui.FieldLayout( checkbox3, { label: 'Disabled checkbox', align: 'inline' } ),
7310 * ] );
7311 * $( 'body' ).append( fieldset.$element );
7312 *
7313 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
7314 *
7315 * @class
7316 * @extends OO.ui.InputWidget
7317 *
7318 * @constructor
7319 * @param {Object} [config] Configuration options
7320 * @cfg {boolean} [selected=false] Select the checkbox initially. By default, the checkbox is not selected.
7321 */
7322 OO.ui.CheckboxInputWidget = function OoUiCheckboxInputWidget( config ) {
7323 // Configuration initialization
7324 config = config || {};
7325
7326 // Parent constructor
7327 OO.ui.CheckboxInputWidget.parent.call( this, config );
7328
7329 // Initialization
7330 this.$element
7331 .addClass( 'oo-ui-checkboxInputWidget' )
7332 // Required for pretty styling in MediaWiki theme
7333 .append( $( '<span>' ) );
7334 this.setSelected( config.selected !== undefined ? config.selected : false );
7335 };
7336
7337 /* Setup */
7338
7339 OO.inheritClass( OO.ui.CheckboxInputWidget, OO.ui.InputWidget );
7340
7341 /* Static Methods */
7342
7343 /**
7344 * @inheritdoc
7345 */
7346 OO.ui.CheckboxInputWidget.static.gatherPreInfuseState = function ( node, config ) {
7347 var state = OO.ui.CheckboxInputWidget.parent.static.gatherPreInfuseState( node, config );
7348 state.checked = config.$input.prop( 'checked' );
7349 return state;
7350 };
7351
7352 /* Methods */
7353
7354 /**
7355 * @inheritdoc
7356 * @protected
7357 */
7358 OO.ui.CheckboxInputWidget.prototype.getInputElement = function () {
7359 return $( '<input>' ).attr( 'type', 'checkbox' );
7360 };
7361
7362 /**
7363 * @inheritdoc
7364 */
7365 OO.ui.CheckboxInputWidget.prototype.onEdit = function () {
7366 var widget = this;
7367 if ( !this.isDisabled() ) {
7368 // Allow the stack to clear so the value will be updated
7369 setTimeout( function () {
7370 widget.setSelected( widget.$input.prop( 'checked' ) );
7371 } );
7372 }
7373 };
7374
7375 /**
7376 * Set selection state of this checkbox.
7377 *
7378 * @param {boolean} state `true` for selected
7379 * @chainable
7380 */
7381 OO.ui.CheckboxInputWidget.prototype.setSelected = function ( state ) {
7382 state = !!state;
7383 if ( this.selected !== state ) {
7384 this.selected = state;
7385 this.$input.prop( 'checked', this.selected );
7386 this.emit( 'change', this.selected );
7387 }
7388 return this;
7389 };
7390
7391 /**
7392 * Check if this checkbox is selected.
7393 *
7394 * @return {boolean} Checkbox is selected
7395 */
7396 OO.ui.CheckboxInputWidget.prototype.isSelected = function () {
7397 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
7398 // it, and we won't know unless they're kind enough to trigger a 'change' event.
7399 var selected = this.$input.prop( 'checked' );
7400 if ( this.selected !== selected ) {
7401 this.setSelected( selected );
7402 }
7403 return this.selected;
7404 };
7405
7406 /**
7407 * @inheritdoc
7408 */
7409 OO.ui.CheckboxInputWidget.prototype.restorePreInfuseState = function ( state ) {
7410 OO.ui.CheckboxInputWidget.parent.prototype.restorePreInfuseState.call( this, state );
7411 if ( state.checked !== undefined && state.checked !== this.isSelected() ) {
7412 this.setSelected( state.checked );
7413 }
7414 };
7415
7416 /**
7417 * DropdownInputWidget is a {@link OO.ui.DropdownWidget DropdownWidget} intended to be used
7418 * within a HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with the value
7419 * of a hidden HTML `input` tag. Please see the [OOjs UI documentation on MediaWiki][1] for
7420 * more information about input widgets.
7421 *
7422 * A DropdownInputWidget always has a value (one of the options is always selected), unless there
7423 * are no options. If no `value` configuration option is provided, the first option is selected.
7424 * If you need a state representing no value (no option being selected), use a DropdownWidget.
7425 *
7426 * This and OO.ui.RadioSelectInputWidget support the same configuration options.
7427 *
7428 * @example
7429 * // Example: A DropdownInputWidget with three options
7430 * var dropdownInput = new OO.ui.DropdownInputWidget( {
7431 * options: [
7432 * { data: 'a', label: 'First' },
7433 * { data: 'b', label: 'Second'},
7434 * { data: 'c', label: 'Third' }
7435 * ]
7436 * } );
7437 * $( 'body' ).append( dropdownInput.$element );
7438 *
7439 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
7440 *
7441 * @class
7442 * @extends OO.ui.InputWidget
7443 * @mixins OO.ui.mixin.TitledElement
7444 *
7445 * @constructor
7446 * @param {Object} [config] Configuration options
7447 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
7448 * @cfg {Object} [dropdown] Configuration options for {@link OO.ui.DropdownWidget DropdownWidget}
7449 */
7450 OO.ui.DropdownInputWidget = function OoUiDropdownInputWidget( config ) {
7451 // Configuration initialization
7452 config = config || {};
7453
7454 // See InputWidget#reusePreInfuseDOM about config.$input
7455 if ( config.$input ) {
7456 config.$input.addClass( 'oo-ui-element-hidden' );
7457 }
7458
7459 // Properties (must be done before parent constructor which calls #setDisabled)
7460 this.dropdownWidget = new OO.ui.DropdownWidget( config.dropdown );
7461
7462 // Parent constructor
7463 OO.ui.DropdownInputWidget.parent.call( this, config );
7464
7465 // Mixin constructors
7466 OO.ui.mixin.TitledElement.call( this, config );
7467
7468 // Events
7469 this.dropdownWidget.getMenu().connect( this, { select: 'onMenuSelect' } );
7470
7471 // Initialization
7472 this.setOptions( config.options || [] );
7473 this.$element
7474 .addClass( 'oo-ui-dropdownInputWidget' )
7475 .append( this.dropdownWidget.$element );
7476 };
7477
7478 /* Setup */
7479
7480 OO.inheritClass( OO.ui.DropdownInputWidget, OO.ui.InputWidget );
7481 OO.mixinClass( OO.ui.DropdownInputWidget, OO.ui.mixin.TitledElement );
7482
7483 /* Methods */
7484
7485 /**
7486 * @inheritdoc
7487 * @protected
7488 */
7489 OO.ui.DropdownInputWidget.prototype.getInputElement = function () {
7490 return $( '<input>' ).attr( 'type', 'hidden' );
7491 };
7492
7493 /**
7494 * Handles menu select events.
7495 *
7496 * @private
7497 * @param {OO.ui.MenuOptionWidget} item Selected menu item
7498 */
7499 OO.ui.DropdownInputWidget.prototype.onMenuSelect = function ( item ) {
7500 this.setValue( item.getData() );
7501 };
7502
7503 /**
7504 * @inheritdoc
7505 */
7506 OO.ui.DropdownInputWidget.prototype.setValue = function ( value ) {
7507 value = this.cleanUpValue( value );
7508 this.dropdownWidget.getMenu().selectItemByData( value );
7509 OO.ui.DropdownInputWidget.parent.prototype.setValue.call( this, value );
7510 return this;
7511 };
7512
7513 /**
7514 * @inheritdoc
7515 */
7516 OO.ui.DropdownInputWidget.prototype.setDisabled = function ( state ) {
7517 this.dropdownWidget.setDisabled( state );
7518 OO.ui.DropdownInputWidget.parent.prototype.setDisabled.call( this, state );
7519 return this;
7520 };
7521
7522 /**
7523 * Set the options available for this input.
7524 *
7525 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
7526 * @chainable
7527 */
7528 OO.ui.DropdownInputWidget.prototype.setOptions = function ( options ) {
7529 var
7530 value = this.getValue(),
7531 widget = this;
7532
7533 // Rebuild the dropdown menu
7534 this.dropdownWidget.getMenu()
7535 .clearItems()
7536 .addItems( options.map( function ( opt ) {
7537 var optValue = widget.cleanUpValue( opt.data );
7538 return new OO.ui.MenuOptionWidget( {
7539 data: optValue,
7540 label: opt.label !== undefined ? opt.label : optValue
7541 } );
7542 } ) );
7543
7544 // Restore the previous value, or reset to something sensible
7545 if ( this.dropdownWidget.getMenu().getItemFromData( value ) ) {
7546 // Previous value is still available, ensure consistency with the dropdown
7547 this.setValue( value );
7548 } else {
7549 // No longer valid, reset
7550 if ( options.length ) {
7551 this.setValue( options[ 0 ].data );
7552 }
7553 }
7554
7555 return this;
7556 };
7557
7558 /**
7559 * @inheritdoc
7560 */
7561 OO.ui.DropdownInputWidget.prototype.focus = function () {
7562 this.dropdownWidget.getMenu().toggle( true );
7563 return this;
7564 };
7565
7566 /**
7567 * @inheritdoc
7568 */
7569 OO.ui.DropdownInputWidget.prototype.blur = function () {
7570 this.dropdownWidget.getMenu().toggle( false );
7571 return this;
7572 };
7573
7574 /**
7575 * RadioInputWidget creates a single radio button. Because radio buttons are usually used as a set,
7576 * in most cases you will want to use a {@link OO.ui.RadioSelectWidget radio select}
7577 * with {@link OO.ui.RadioOptionWidget radio options} instead of this class. For more information,
7578 * please see the [OOjs UI documentation on MediaWiki][1].
7579 *
7580 * This widget can be used inside a HTML form, such as a OO.ui.FormLayout.
7581 *
7582 * @example
7583 * // An example of selected, unselected, and disabled radio inputs
7584 * var radio1 = new OO.ui.RadioInputWidget( {
7585 * value: 'a',
7586 * selected: true
7587 * } );
7588 * var radio2 = new OO.ui.RadioInputWidget( {
7589 * value: 'b'
7590 * } );
7591 * var radio3 = new OO.ui.RadioInputWidget( {
7592 * value: 'c',
7593 * disabled: true
7594 * } );
7595 * // Create a fieldset layout with fields for each radio button.
7596 * var fieldset = new OO.ui.FieldsetLayout( {
7597 * label: 'Radio inputs'
7598 * } );
7599 * fieldset.addItems( [
7600 * new OO.ui.FieldLayout( radio1, { label: 'Selected', align: 'inline' } ),
7601 * new OO.ui.FieldLayout( radio2, { label: 'Unselected', align: 'inline' } ),
7602 * new OO.ui.FieldLayout( radio3, { label: 'Disabled', align: 'inline' } ),
7603 * ] );
7604 * $( 'body' ).append( fieldset.$element );
7605 *
7606 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
7607 *
7608 * @class
7609 * @extends OO.ui.InputWidget
7610 *
7611 * @constructor
7612 * @param {Object} [config] Configuration options
7613 * @cfg {boolean} [selected=false] Select the radio button initially. By default, the radio button is not selected.
7614 */
7615 OO.ui.RadioInputWidget = function OoUiRadioInputWidget( config ) {
7616 // Configuration initialization
7617 config = config || {};
7618
7619 // Parent constructor
7620 OO.ui.RadioInputWidget.parent.call( this, config );
7621
7622 // Initialization
7623 this.$element
7624 .addClass( 'oo-ui-radioInputWidget' )
7625 // Required for pretty styling in MediaWiki theme
7626 .append( $( '<span>' ) );
7627 this.setSelected( config.selected !== undefined ? config.selected : false );
7628 };
7629
7630 /* Setup */
7631
7632 OO.inheritClass( OO.ui.RadioInputWidget, OO.ui.InputWidget );
7633
7634 /* Static Methods */
7635
7636 /**
7637 * @inheritdoc
7638 */
7639 OO.ui.RadioInputWidget.static.gatherPreInfuseState = function ( node, config ) {
7640 var state = OO.ui.RadioInputWidget.parent.static.gatherPreInfuseState( node, config );
7641 state.checked = config.$input.prop( 'checked' );
7642 return state;
7643 };
7644
7645 /* Methods */
7646
7647 /**
7648 * @inheritdoc
7649 * @protected
7650 */
7651 OO.ui.RadioInputWidget.prototype.getInputElement = function () {
7652 return $( '<input>' ).attr( 'type', 'radio' );
7653 };
7654
7655 /**
7656 * @inheritdoc
7657 */
7658 OO.ui.RadioInputWidget.prototype.onEdit = function () {
7659 // RadioInputWidget doesn't track its state.
7660 };
7661
7662 /**
7663 * Set selection state of this radio button.
7664 *
7665 * @param {boolean} state `true` for selected
7666 * @chainable
7667 */
7668 OO.ui.RadioInputWidget.prototype.setSelected = function ( state ) {
7669 // RadioInputWidget doesn't track its state.
7670 this.$input.prop( 'checked', state );
7671 return this;
7672 };
7673
7674 /**
7675 * Check if this radio button is selected.
7676 *
7677 * @return {boolean} Radio is selected
7678 */
7679 OO.ui.RadioInputWidget.prototype.isSelected = function () {
7680 return this.$input.prop( 'checked' );
7681 };
7682
7683 /**
7684 * @inheritdoc
7685 */
7686 OO.ui.RadioInputWidget.prototype.restorePreInfuseState = function ( state ) {
7687 OO.ui.RadioInputWidget.parent.prototype.restorePreInfuseState.call( this, state );
7688 if ( state.checked !== undefined && state.checked !== this.isSelected() ) {
7689 this.setSelected( state.checked );
7690 }
7691 };
7692
7693 /**
7694 * RadioSelectInputWidget is a {@link OO.ui.RadioSelectWidget RadioSelectWidget} intended to be used
7695 * within a HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with the value
7696 * of a hidden HTML `input` tag. Please see the [OOjs UI documentation on MediaWiki][1] for
7697 * more information about input widgets.
7698 *
7699 * This and OO.ui.DropdownInputWidget support the same configuration options.
7700 *
7701 * @example
7702 * // Example: A RadioSelectInputWidget with three options
7703 * var radioSelectInput = new OO.ui.RadioSelectInputWidget( {
7704 * options: [
7705 * { data: 'a', label: 'First' },
7706 * { data: 'b', label: 'Second'},
7707 * { data: 'c', label: 'Third' }
7708 * ]
7709 * } );
7710 * $( 'body' ).append( radioSelectInput.$element );
7711 *
7712 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
7713 *
7714 * @class
7715 * @extends OO.ui.InputWidget
7716 *
7717 * @constructor
7718 * @param {Object} [config] Configuration options
7719 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
7720 */
7721 OO.ui.RadioSelectInputWidget = function OoUiRadioSelectInputWidget( config ) {
7722 // Configuration initialization
7723 config = config || {};
7724
7725 // Properties (must be done before parent constructor which calls #setDisabled)
7726 this.radioSelectWidget = new OO.ui.RadioSelectWidget();
7727
7728 // Parent constructor
7729 OO.ui.RadioSelectInputWidget.parent.call( this, config );
7730
7731 // Events
7732 this.radioSelectWidget.connect( this, { select: 'onMenuSelect' } );
7733
7734 // Initialization
7735 this.setOptions( config.options || [] );
7736 this.$element
7737 .addClass( 'oo-ui-radioSelectInputWidget' )
7738 .append( this.radioSelectWidget.$element );
7739 };
7740
7741 /* Setup */
7742
7743 OO.inheritClass( OO.ui.RadioSelectInputWidget, OO.ui.InputWidget );
7744
7745 /* Static Properties */
7746
7747 OO.ui.RadioSelectInputWidget.static.supportsSimpleLabel = false;
7748
7749 /* Static Methods */
7750
7751 /**
7752 * @inheritdoc
7753 */
7754 OO.ui.RadioSelectInputWidget.static.gatherPreInfuseState = function ( node, config ) {
7755 var state = OO.ui.RadioSelectInputWidget.parent.static.gatherPreInfuseState( node, config );
7756 state.value = $( node ).find( '.oo-ui-radioInputWidget .oo-ui-inputWidget-input:checked' ).val();
7757 return state;
7758 };
7759
7760 /**
7761 * @inheritdoc
7762 */
7763 OO.ui.RadioSelectInputWidget.static.reusePreInfuseDOM = function ( node, config ) {
7764 config = OO.ui.RadioSelectInputWidget.parent.static.reusePreInfuseDOM( node, config );
7765 // Cannot reuse the `<input type=radio>` set
7766 delete config.$input;
7767 return config;
7768 };
7769
7770 /* Methods */
7771
7772 /**
7773 * @inheritdoc
7774 * @protected
7775 */
7776 OO.ui.RadioSelectInputWidget.prototype.getInputElement = function () {
7777 return $( '<input>' ).attr( 'type', 'hidden' );
7778 };
7779
7780 /**
7781 * Handles menu select events.
7782 *
7783 * @private
7784 * @param {OO.ui.RadioOptionWidget} item Selected menu item
7785 */
7786 OO.ui.RadioSelectInputWidget.prototype.onMenuSelect = function ( item ) {
7787 this.setValue( item.getData() );
7788 };
7789
7790 /**
7791 * @inheritdoc
7792 */
7793 OO.ui.RadioSelectInputWidget.prototype.setValue = function ( value ) {
7794 value = this.cleanUpValue( value );
7795 this.radioSelectWidget.selectItemByData( value );
7796 OO.ui.RadioSelectInputWidget.parent.prototype.setValue.call( this, value );
7797 return this;
7798 };
7799
7800 /**
7801 * @inheritdoc
7802 */
7803 OO.ui.RadioSelectInputWidget.prototype.setDisabled = function ( state ) {
7804 this.radioSelectWidget.setDisabled( state );
7805 OO.ui.RadioSelectInputWidget.parent.prototype.setDisabled.call( this, state );
7806 return this;
7807 };
7808
7809 /**
7810 * Set the options available for this input.
7811 *
7812 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
7813 * @chainable
7814 */
7815 OO.ui.RadioSelectInputWidget.prototype.setOptions = function ( options ) {
7816 var
7817 value = this.getValue(),
7818 widget = this;
7819
7820 // Rebuild the radioSelect menu
7821 this.radioSelectWidget
7822 .clearItems()
7823 .addItems( options.map( function ( opt ) {
7824 var optValue = widget.cleanUpValue( opt.data );
7825 return new OO.ui.RadioOptionWidget( {
7826 data: optValue,
7827 label: opt.label !== undefined ? opt.label : optValue
7828 } );
7829 } ) );
7830
7831 // Restore the previous value, or reset to something sensible
7832 if ( this.radioSelectWidget.getItemFromData( value ) ) {
7833 // Previous value is still available, ensure consistency with the radioSelect
7834 this.setValue( value );
7835 } else {
7836 // No longer valid, reset
7837 if ( options.length ) {
7838 this.setValue( options[ 0 ].data );
7839 }
7840 }
7841
7842 return this;
7843 };
7844
7845 /**
7846 * TextInputWidgets, like HTML text inputs, can be configured with options that customize the
7847 * size of the field as well as its presentation. In addition, these widgets can be configured
7848 * with {@link OO.ui.mixin.IconElement icons}, {@link OO.ui.mixin.IndicatorElement indicators}, an optional
7849 * validation-pattern (used to determine if an input value is valid or not) and an input filter,
7850 * which modifies incoming values rather than validating them.
7851 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
7852 *
7853 * This widget can be used inside a HTML form, such as a OO.ui.FormLayout.
7854 *
7855 * @example
7856 * // Example of a text input widget
7857 * var textInput = new OO.ui.TextInputWidget( {
7858 * value: 'Text input'
7859 * } )
7860 * $( 'body' ).append( textInput.$element );
7861 *
7862 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
7863 *
7864 * @class
7865 * @extends OO.ui.InputWidget
7866 * @mixins OO.ui.mixin.IconElement
7867 * @mixins OO.ui.mixin.IndicatorElement
7868 * @mixins OO.ui.mixin.PendingElement
7869 * @mixins OO.ui.mixin.LabelElement
7870 *
7871 * @constructor
7872 * @param {Object} [config] Configuration options
7873 * @cfg {string} [type='text'] The value of the HTML `type` attribute: 'text', 'password', 'search',
7874 * 'email', 'url', 'date' or 'number'. Ignored if `multiline` is true.
7875 *
7876 * Some values of `type` result in additional behaviors:
7877 *
7878 * - `search`: implies `icon: 'search'` and `indicator: 'clear'`; when clicked, the indicator
7879 * empties the text field
7880 * @cfg {string} [placeholder] Placeholder text
7881 * @cfg {boolean} [autofocus=false] Use an HTML `autofocus` attribute to
7882 * instruct the browser to focus this widget.
7883 * @cfg {boolean} [readOnly=false] Prevent changes to the value of the text input.
7884 * @cfg {number} [maxLength] Maximum number of characters allowed in the input.
7885 * @cfg {boolean} [multiline=false] Allow multiple lines of text
7886 * @cfg {number} [rows] If multiline, number of visible lines in textarea. If used with `autosize`,
7887 * specifies minimum number of rows to display.
7888 * @cfg {boolean} [autosize=false] Automatically resize the text input to fit its content.
7889 * Use the #maxRows config to specify a maximum number of displayed rows.
7890 * @cfg {boolean} [maxRows] Maximum number of rows to display when #autosize is set to true.
7891 * Defaults to the maximum of `10` and `2 * rows`, or `10` if `rows` isn't provided.
7892 * @cfg {string} [labelPosition='after'] The position of the inline label relative to that of
7893 * the value or placeholder text: `'before'` or `'after'`
7894 * @cfg {boolean} [required=false] Mark the field as required. Implies `indicator: 'required'`.
7895 * @cfg {boolean} [autocomplete=true] Should the browser support autocomplete for this field
7896 * @cfg {RegExp|Function|string} [validate] Validation pattern: when string, a symbolic name of a
7897 * pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer'
7898 * (the value must contain only numbers); when RegExp, a regular expression that must match the
7899 * value for it to be considered valid; when Function, a function receiving the value as parameter
7900 * that must return true, or promise resolving to true, for it to be considered valid.
7901 */
7902 OO.ui.TextInputWidget = function OoUiTextInputWidget( config ) {
7903 // Configuration initialization
7904 config = $.extend( {
7905 type: 'text',
7906 labelPosition: 'after'
7907 }, config );
7908 if ( config.type === 'search' ) {
7909 if ( config.icon === undefined ) {
7910 config.icon = 'search';
7911 }
7912 // indicator: 'clear' is set dynamically later, depending on value
7913 }
7914 if ( config.required ) {
7915 if ( config.indicator === undefined ) {
7916 config.indicator = 'required';
7917 }
7918 }
7919
7920 // Parent constructor
7921 OO.ui.TextInputWidget.parent.call( this, config );
7922
7923 // Mixin constructors
7924 OO.ui.mixin.IconElement.call( this, config );
7925 OO.ui.mixin.IndicatorElement.call( this, config );
7926 OO.ui.mixin.PendingElement.call( this, $.extend( {}, config, { $pending: this.$input } ) );
7927 OO.ui.mixin.LabelElement.call( this, config );
7928
7929 // Properties
7930 this.type = this.getSaneType( config );
7931 this.readOnly = false;
7932 this.multiline = !!config.multiline;
7933 this.autosize = !!config.autosize;
7934 this.minRows = config.rows !== undefined ? config.rows : '';
7935 this.maxRows = config.maxRows || Math.max( 2 * ( this.minRows || 0 ), 10 );
7936 this.validate = null;
7937 this.styleHeight = null;
7938 this.scrollWidth = null;
7939
7940 // Clone for resizing
7941 if ( this.autosize ) {
7942 this.$clone = this.$input
7943 .clone()
7944 .insertAfter( this.$input )
7945 .attr( 'aria-hidden', 'true' )
7946 .addClass( 'oo-ui-element-hidden' );
7947 }
7948
7949 this.setValidation( config.validate );
7950 this.setLabelPosition( config.labelPosition );
7951
7952 // Events
7953 this.$input.on( {
7954 keypress: this.onKeyPress.bind( this ),
7955 blur: this.onBlur.bind( this )
7956 } );
7957 this.$input.one( {
7958 focus: this.onElementAttach.bind( this )
7959 } );
7960 this.$icon.on( 'mousedown', this.onIconMouseDown.bind( this ) );
7961 this.$indicator.on( 'mousedown', this.onIndicatorMouseDown.bind( this ) );
7962 this.on( 'labelChange', this.updatePosition.bind( this ) );
7963 this.connect( this, {
7964 change: 'onChange',
7965 disable: 'onDisable'
7966 } );
7967
7968 // Initialization
7969 this.$element
7970 .addClass( 'oo-ui-textInputWidget oo-ui-textInputWidget-type-' + this.type )
7971 .append( this.$icon, this.$indicator );
7972 this.setReadOnly( !!config.readOnly );
7973 this.updateSearchIndicator();
7974 if ( config.placeholder !== undefined ) {
7975 this.$input.attr( 'placeholder', config.placeholder );
7976 }
7977 if ( config.maxLength !== undefined ) {
7978 this.$input.attr( 'maxlength', config.maxLength );
7979 }
7980 if ( config.autofocus ) {
7981 this.$input.attr( 'autofocus', 'autofocus' );
7982 }
7983 if ( config.required ) {
7984 this.$input.attr( 'required', 'required' );
7985 this.$input.attr( 'aria-required', 'true' );
7986 }
7987 if ( config.autocomplete === false ) {
7988 this.$input.attr( 'autocomplete', 'off' );
7989 // Turning off autocompletion also disables "form caching" when the user navigates to a
7990 // different page and then clicks "Back". Re-enable it when leaving. Borrowed from jQuery UI.
7991 $( window ).on( {
7992 beforeunload: function () {
7993 this.$input.removeAttr( 'autocomplete' );
7994 }.bind( this ),
7995 pageshow: function () {
7996 // Browsers don't seem to actually fire this event on "Back", they instead just reload the
7997 // whole page... it shouldn't hurt, though.
7998 this.$input.attr( 'autocomplete', 'off' );
7999 }.bind( this )
8000 } );
8001 }
8002 if ( this.multiline && config.rows ) {
8003 this.$input.attr( 'rows', config.rows );
8004 }
8005 if ( this.label || config.autosize ) {
8006 this.installParentChangeDetector();
8007 }
8008 };
8009
8010 /* Setup */
8011
8012 OO.inheritClass( OO.ui.TextInputWidget, OO.ui.InputWidget );
8013 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.mixin.IconElement );
8014 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.mixin.IndicatorElement );
8015 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.mixin.PendingElement );
8016 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.mixin.LabelElement );
8017
8018 /* Static Properties */
8019
8020 OO.ui.TextInputWidget.static.validationPatterns = {
8021 'non-empty': /.+/,
8022 integer: /^\d+$/
8023 };
8024
8025 /* Static Methods */
8026
8027 /**
8028 * @inheritdoc
8029 */
8030 OO.ui.TextInputWidget.static.gatherPreInfuseState = function ( node, config ) {
8031 var state = OO.ui.TextInputWidget.parent.static.gatherPreInfuseState( node, config );
8032 if ( config.multiline ) {
8033 state.scrollTop = config.$input.scrollTop();
8034 }
8035 return state;
8036 };
8037
8038 /* Events */
8039
8040 /**
8041 * An `enter` event is emitted when the user presses 'enter' inside the text box.
8042 *
8043 * Not emitted if the input is multiline.
8044 *
8045 * @event enter
8046 */
8047
8048 /**
8049 * A `resize` event is emitted when autosize is set and the widget resizes
8050 *
8051 * @event resize
8052 */
8053
8054 /* Methods */
8055
8056 /**
8057 * Handle icon mouse down events.
8058 *
8059 * @private
8060 * @param {jQuery.Event} e Mouse down event
8061 */
8062 OO.ui.TextInputWidget.prototype.onIconMouseDown = function ( e ) {
8063 if ( e.which === OO.ui.MouseButtons.LEFT ) {
8064 this.$input[ 0 ].focus();
8065 return false;
8066 }
8067 };
8068
8069 /**
8070 * Handle indicator mouse down events.
8071 *
8072 * @private
8073 * @param {jQuery.Event} e Mouse down event
8074 */
8075 OO.ui.TextInputWidget.prototype.onIndicatorMouseDown = function ( e ) {
8076 if ( e.which === OO.ui.MouseButtons.LEFT ) {
8077 if ( this.type === 'search' ) {
8078 // Clear the text field
8079 this.setValue( '' );
8080 }
8081 this.$input[ 0 ].focus();
8082 return false;
8083 }
8084 };
8085
8086 /**
8087 * Handle key press events.
8088 *
8089 * @private
8090 * @param {jQuery.Event} e Key press event
8091 * @fires enter If enter key is pressed and input is not multiline
8092 */
8093 OO.ui.TextInputWidget.prototype.onKeyPress = function ( e ) {
8094 if ( e.which === OO.ui.Keys.ENTER && !this.multiline ) {
8095 this.emit( 'enter', e );
8096 }
8097 };
8098
8099 /**
8100 * Handle blur events.
8101 *
8102 * @private
8103 * @param {jQuery.Event} e Blur event
8104 */
8105 OO.ui.TextInputWidget.prototype.onBlur = function () {
8106 this.setValidityFlag();
8107 };
8108
8109 /**
8110 * Handle element attach events.
8111 *
8112 * @private
8113 * @param {jQuery.Event} e Element attach event
8114 */
8115 OO.ui.TextInputWidget.prototype.onElementAttach = function () {
8116 // Any previously calculated size is now probably invalid if we reattached elsewhere
8117 this.valCache = null;
8118 this.adjustSize();
8119 this.positionLabel();
8120 };
8121
8122 /**
8123 * Handle change events.
8124 *
8125 * @param {string} value
8126 * @private
8127 */
8128 OO.ui.TextInputWidget.prototype.onChange = function () {
8129 this.updateSearchIndicator();
8130 this.setValidityFlag();
8131 this.adjustSize();
8132 };
8133
8134 /**
8135 * Handle disable events.
8136 *
8137 * @param {boolean} disabled Element is disabled
8138 * @private
8139 */
8140 OO.ui.TextInputWidget.prototype.onDisable = function () {
8141 this.updateSearchIndicator();
8142 };
8143
8144 /**
8145 * Check if the input is {@link #readOnly read-only}.
8146 *
8147 * @return {boolean}
8148 */
8149 OO.ui.TextInputWidget.prototype.isReadOnly = function () {
8150 return this.readOnly;
8151 };
8152
8153 /**
8154 * Set the {@link #readOnly read-only} state of the input.
8155 *
8156 * @param {boolean} state Make input read-only
8157 * @chainable
8158 */
8159 OO.ui.TextInputWidget.prototype.setReadOnly = function ( state ) {
8160 this.readOnly = !!state;
8161 this.$input.prop( 'readOnly', this.readOnly );
8162 this.updateSearchIndicator();
8163 return this;
8164 };
8165
8166 /**
8167 * Support function for making #onElementAttach work across browsers.
8168 *
8169 * This whole function could be replaced with one line of code using the DOMNodeInsertedIntoDocument
8170 * event, but it's not supported by Firefox and allegedly deprecated, so we only use it as fallback.
8171 *
8172 * Due to MutationObserver performance woes, #onElementAttach is only somewhat reliably called the
8173 * first time that the element gets attached to the documented.
8174 */
8175 OO.ui.TextInputWidget.prototype.installParentChangeDetector = function () {
8176 var mutationObserver, onRemove, topmostNode, fakeParentNode,
8177 MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver,
8178 widget = this;
8179
8180 if ( MutationObserver ) {
8181 // The new way. If only it wasn't so ugly.
8182
8183 if ( this.$element.closest( 'html' ).length ) {
8184 // Widget is attached already, do nothing. This breaks the functionality of this function when
8185 // the widget is detached and reattached. Alas, doing this correctly with MutationObserver
8186 // would require observation of the whole document, which would hurt performance of other,
8187 // more important code.
8188 return;
8189 }
8190
8191 // Find topmost node in the tree
8192 topmostNode = this.$element[ 0 ];
8193 while ( topmostNode.parentNode ) {
8194 topmostNode = topmostNode.parentNode;
8195 }
8196
8197 // We have no way to detect the $element being attached somewhere without observing the entire
8198 // DOM with subtree modifications, which would hurt performance. So we cheat: we hook to the
8199 // parent node of $element, and instead detect when $element is removed from it (and thus
8200 // probably attached somewhere else). If there is no parent, we create a "fake" one. If it
8201 // doesn't get attached, we end up back here and create the parent.
8202
8203 mutationObserver = new MutationObserver( function ( mutations ) {
8204 var i, j, removedNodes;
8205 for ( i = 0; i < mutations.length; i++ ) {
8206 removedNodes = mutations[ i ].removedNodes;
8207 for ( j = 0; j < removedNodes.length; j++ ) {
8208 if ( removedNodes[ j ] === topmostNode ) {
8209 setTimeout( onRemove, 0 );
8210 return;
8211 }
8212 }
8213 }
8214 } );
8215
8216 onRemove = function () {
8217 // If the node was attached somewhere else, report it
8218 if ( widget.$element.closest( 'html' ).length ) {
8219 widget.onElementAttach();
8220 }
8221 mutationObserver.disconnect();
8222 widget.installParentChangeDetector();
8223 };
8224
8225 // Create a fake parent and observe it
8226 fakeParentNode = $( '<div>' ).append( topmostNode )[ 0 ];
8227 mutationObserver.observe( fakeParentNode, { childList: true } );
8228 } else {
8229 // Using the DOMNodeInsertedIntoDocument event is much nicer and less magical, and works for
8230 // detachment and reattachment, but it's not supported by Firefox and allegedly deprecated.
8231 this.$element.on( 'DOMNodeInsertedIntoDocument', this.onElementAttach.bind( this ) );
8232 }
8233 };
8234
8235 /**
8236 * Automatically adjust the size of the text input.
8237 *
8238 * This only affects #multiline inputs that are {@link #autosize autosized}.
8239 *
8240 * @chainable
8241 * @fires resize
8242 */
8243 OO.ui.TextInputWidget.prototype.adjustSize = function () {
8244 var scrollHeight, innerHeight, outerHeight, maxInnerHeight, measurementError,
8245 idealHeight, newHeight, scrollWidth, property;
8246
8247 if ( this.multiline && this.$input.val() !== this.valCache ) {
8248 if ( this.autosize ) {
8249 this.$clone
8250 .val( this.$input.val() )
8251 .attr( 'rows', this.minRows )
8252 // Set inline height property to 0 to measure scroll height
8253 .css( 'height', 0 );
8254
8255 this.$clone.removeClass( 'oo-ui-element-hidden' );
8256
8257 this.valCache = this.$input.val();
8258
8259 scrollHeight = this.$clone[ 0 ].scrollHeight;
8260
8261 // Remove inline height property to measure natural heights
8262 this.$clone.css( 'height', '' );
8263 innerHeight = this.$clone.innerHeight();
8264 outerHeight = this.$clone.outerHeight();
8265
8266 // Measure max rows height
8267 this.$clone
8268 .attr( 'rows', this.maxRows )
8269 .css( 'height', 'auto' )
8270 .val( '' );
8271 maxInnerHeight = this.$clone.innerHeight();
8272
8273 // Difference between reported innerHeight and scrollHeight with no scrollbars present.
8274 // This is sometimes non-zero on Blink-based browsers, depending on zoom level.
8275 measurementError = maxInnerHeight - this.$clone[ 0 ].scrollHeight;
8276 idealHeight = Math.min( maxInnerHeight, scrollHeight + measurementError );
8277
8278 this.$clone.addClass( 'oo-ui-element-hidden' );
8279
8280 // Only apply inline height when expansion beyond natural height is needed
8281 // Use the difference between the inner and outer height as a buffer
8282 newHeight = idealHeight > innerHeight ? idealHeight + ( outerHeight - innerHeight ) : '';
8283 if ( newHeight !== this.styleHeight ) {
8284 this.$input.css( 'height', newHeight );
8285 this.styleHeight = newHeight;
8286 this.emit( 'resize' );
8287 }
8288 }
8289 scrollWidth = this.$input[ 0 ].offsetWidth - this.$input[ 0 ].clientWidth;
8290 if ( scrollWidth !== this.scrollWidth ) {
8291 property = this.$element.css( 'direction' ) === 'rtl' ? 'left' : 'right';
8292 // Reset
8293 this.$label.css( { right: '', left: '' } );
8294 this.$indicator.css( { right: '', left: '' } );
8295
8296 if ( scrollWidth ) {
8297 this.$indicator.css( property, scrollWidth );
8298 if ( this.labelPosition === 'after' ) {
8299 this.$label.css( property, scrollWidth );
8300 }
8301 }
8302
8303 this.scrollWidth = scrollWidth;
8304 this.positionLabel();
8305 }
8306 }
8307 return this;
8308 };
8309
8310 /**
8311 * @inheritdoc
8312 * @protected
8313 */
8314 OO.ui.TextInputWidget.prototype.getInputElement = function ( config ) {
8315 if ( config.multiline ) {
8316 return $( '<textarea>' );
8317 } else if ( this.getSaneType( config ) === 'number' ) {
8318 return $( '<input>' )
8319 .attr( 'step', 'any' )
8320 .attr( 'type', 'number' );
8321 } else {
8322 return $( '<input>' ).attr( 'type', this.getSaneType( config ) );
8323 }
8324 };
8325
8326 /**
8327 * Get sanitized value for 'type' for given config.
8328 *
8329 * @param {Object} config Configuration options
8330 * @return {string|null}
8331 * @private
8332 */
8333 OO.ui.TextInputWidget.prototype.getSaneType = function ( config ) {
8334 var allowedTypes = [
8335 'text',
8336 'password',
8337 'search',
8338 'email',
8339 'url',
8340 'date',
8341 'number'
8342 ],
8343 type = allowedTypes.indexOf( config.type ) !== -1 ? config.type : 'text';
8344 return config.multiline ? 'multiline' : type;
8345 };
8346
8347 /**
8348 * Check if the input supports multiple lines.
8349 *
8350 * @return {boolean}
8351 */
8352 OO.ui.TextInputWidget.prototype.isMultiline = function () {
8353 return !!this.multiline;
8354 };
8355
8356 /**
8357 * Check if the input automatically adjusts its size.
8358 *
8359 * @return {boolean}
8360 */
8361 OO.ui.TextInputWidget.prototype.isAutosizing = function () {
8362 return !!this.autosize;
8363 };
8364
8365 /**
8366 * Focus the input and select a specified range within the text.
8367 *
8368 * @param {number} from Select from offset
8369 * @param {number} [to] Select to offset, defaults to from
8370 * @chainable
8371 */
8372 OO.ui.TextInputWidget.prototype.selectRange = function ( from, to ) {
8373 var isBackwards, start, end,
8374 input = this.$input[ 0 ];
8375
8376 to = to || from;
8377
8378 isBackwards = to < from;
8379 start = isBackwards ? to : from;
8380 end = isBackwards ? from : to;
8381
8382 this.focus();
8383
8384 try {
8385 input.setSelectionRange( start, end, isBackwards ? 'backward' : 'forward' );
8386 } catch ( e ) {
8387 // IE throws an exception if you call setSelectionRange on a unattached DOM node.
8388 // Rather than expensively check if the input is attached every time, just check
8389 // if it was the cause of an error being thrown. If not, rethrow the error.
8390 if ( this.getElementDocument().body.contains( input ) ) {
8391 throw e;
8392 }
8393 }
8394 return this;
8395 };
8396
8397 /**
8398 * Get an object describing the current selection range in a directional manner
8399 *
8400 * @return {Object} Object containing 'from' and 'to' offsets
8401 */
8402 OO.ui.TextInputWidget.prototype.getRange = function () {
8403 var input = this.$input[ 0 ],
8404 start = input.selectionStart,
8405 end = input.selectionEnd,
8406 isBackwards = input.selectionDirection === 'backward';
8407
8408 return {
8409 from: isBackwards ? end : start,
8410 to: isBackwards ? start : end
8411 };
8412 };
8413
8414 /**
8415 * Get the length of the text input value.
8416 *
8417 * This could differ from the length of #getValue if the
8418 * value gets filtered
8419 *
8420 * @return {number} Input length
8421 */
8422 OO.ui.TextInputWidget.prototype.getInputLength = function () {
8423 return this.$input[ 0 ].value.length;
8424 };
8425
8426 /**
8427 * Focus the input and select the entire text.
8428 *
8429 * @chainable
8430 */
8431 OO.ui.TextInputWidget.prototype.select = function () {
8432 return this.selectRange( 0, this.getInputLength() );
8433 };
8434
8435 /**
8436 * Focus the input and move the cursor to the start.
8437 *
8438 * @chainable
8439 */
8440 OO.ui.TextInputWidget.prototype.moveCursorToStart = function () {
8441 return this.selectRange( 0 );
8442 };
8443
8444 /**
8445 * Focus the input and move the cursor to the end.
8446 *
8447 * @chainable
8448 */
8449 OO.ui.TextInputWidget.prototype.moveCursorToEnd = function () {
8450 return this.selectRange( this.getInputLength() );
8451 };
8452
8453 /**
8454 * Insert new content into the input.
8455 *
8456 * @param {string} content Content to be inserted
8457 * @chainable
8458 */
8459 OO.ui.TextInputWidget.prototype.insertContent = function ( content ) {
8460 var start, end,
8461 range = this.getRange(),
8462 value = this.getValue();
8463
8464 start = Math.min( range.from, range.to );
8465 end = Math.max( range.from, range.to );
8466
8467 this.setValue( value.slice( 0, start ) + content + value.slice( end ) );
8468 this.selectRange( start + content.length );
8469 return this;
8470 };
8471
8472 /**
8473 * Insert new content either side of a selection.
8474 *
8475 * @param {string} pre Content to be inserted before the selection
8476 * @param {string} post Content to be inserted after the selection
8477 * @chainable
8478 */
8479 OO.ui.TextInputWidget.prototype.encapsulateContent = function ( pre, post ) {
8480 var start, end,
8481 range = this.getRange(),
8482 offset = pre.length;
8483
8484 start = Math.min( range.from, range.to );
8485 end = Math.max( range.from, range.to );
8486
8487 this.selectRange( start ).insertContent( pre );
8488 this.selectRange( offset + end ).insertContent( post );
8489
8490 this.selectRange( offset + start, offset + end );
8491 return this;
8492 };
8493
8494 /**
8495 * Set the validation pattern.
8496 *
8497 * The validation pattern is either a regular expression, a function, or the symbolic name of a
8498 * pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer' (the
8499 * value must contain only numbers).
8500 *
8501 * @param {RegExp|Function|string|null} validate Regular expression, function, or the symbolic name
8502 * of a pattern (either ‘integer’ or ‘non-empty’) defined by the class.
8503 */
8504 OO.ui.TextInputWidget.prototype.setValidation = function ( validate ) {
8505 if ( validate instanceof RegExp || validate instanceof Function ) {
8506 this.validate = validate;
8507 } else {
8508 this.validate = this.constructor.static.validationPatterns[ validate ] || /.*/;
8509 }
8510 };
8511
8512 /**
8513 * Sets the 'invalid' flag appropriately.
8514 *
8515 * @param {boolean} [isValid] Optionally override validation result
8516 */
8517 OO.ui.TextInputWidget.prototype.setValidityFlag = function ( isValid ) {
8518 var widget = this,
8519 setFlag = function ( valid ) {
8520 if ( !valid ) {
8521 widget.$input.attr( 'aria-invalid', 'true' );
8522 } else {
8523 widget.$input.removeAttr( 'aria-invalid' );
8524 }
8525 widget.setFlags( { invalid: !valid } );
8526 };
8527
8528 if ( isValid !== undefined ) {
8529 setFlag( isValid );
8530 } else {
8531 this.getValidity().then( function () {
8532 setFlag( true );
8533 }, function () {
8534 setFlag( false );
8535 } );
8536 }
8537 };
8538
8539 /**
8540 * Check if a value is valid.
8541 *
8542 * This method returns a promise that resolves with a boolean `true` if the current value is
8543 * considered valid according to the supplied {@link #validate validation pattern}.
8544 *
8545 * @deprecated since v0.12.3
8546 * @return {jQuery.Promise} A promise that resolves to a boolean `true` if the value is valid.
8547 */
8548 OO.ui.TextInputWidget.prototype.isValid = function () {
8549 var result;
8550
8551 if ( this.validate instanceof Function ) {
8552 result = this.validate( this.getValue() );
8553 if ( result && $.isFunction( result.promise ) ) {
8554 return result.promise();
8555 } else {
8556 return $.Deferred().resolve( !!result ).promise();
8557 }
8558 } else {
8559 return $.Deferred().resolve( !!this.getValue().match( this.validate ) ).promise();
8560 }
8561 };
8562
8563 /**
8564 * Get the validity of current value.
8565 *
8566 * This method returns a promise that resolves if the value is valid and rejects if
8567 * it isn't. Uses the {@link #validate validation pattern} to check for validity.
8568 *
8569 * @return {jQuery.Promise} A promise that resolves if the value is valid, rejects if not.
8570 */
8571 OO.ui.TextInputWidget.prototype.getValidity = function () {
8572 var result;
8573
8574 function rejectOrResolve( valid ) {
8575 if ( valid ) {
8576 return $.Deferred().resolve().promise();
8577 } else {
8578 return $.Deferred().reject().promise();
8579 }
8580 }
8581
8582 if ( this.validate instanceof Function ) {
8583 result = this.validate( this.getValue() );
8584 if ( result && $.isFunction( result.promise ) ) {
8585 return result.promise().then( function ( valid ) {
8586 return rejectOrResolve( valid );
8587 } );
8588 } else {
8589 return rejectOrResolve( result );
8590 }
8591 } else {
8592 return rejectOrResolve( this.getValue().match( this.validate ) );
8593 }
8594 };
8595
8596 /**
8597 * Set the position of the inline label relative to that of the value: `‘before’` or `‘after’`.
8598 *
8599 * @param {string} labelPosition Label position, 'before' or 'after'
8600 * @chainable
8601 */
8602 OO.ui.TextInputWidget.prototype.setLabelPosition = function ( labelPosition ) {
8603 this.labelPosition = labelPosition;
8604 if ( this.label ) {
8605 // If there is no label and we only change the position, #updatePosition is a no-op,
8606 // but it takes really a lot of work to do nothing.
8607 this.updatePosition();
8608 }
8609 return this;
8610 };
8611
8612 /**
8613 * Update the position of the inline label.
8614 *
8615 * This method is called by #setLabelPosition, and can also be called on its own if
8616 * something causes the label to be mispositioned.
8617 *
8618 * @chainable
8619 */
8620 OO.ui.TextInputWidget.prototype.updatePosition = function () {
8621 var after = this.labelPosition === 'after';
8622
8623 this.$element
8624 .toggleClass( 'oo-ui-textInputWidget-labelPosition-after', !!this.label && after )
8625 .toggleClass( 'oo-ui-textInputWidget-labelPosition-before', !!this.label && !after );
8626
8627 this.valCache = null;
8628 this.scrollWidth = null;
8629 this.adjustSize();
8630 this.positionLabel();
8631
8632 return this;
8633 };
8634
8635 /**
8636 * Update the 'clear' indicator displayed on type: 'search' text fields, hiding it when the field is
8637 * already empty or when it's not editable.
8638 */
8639 OO.ui.TextInputWidget.prototype.updateSearchIndicator = function () {
8640 if ( this.type === 'search' ) {
8641 if ( this.getValue() === '' || this.isDisabled() || this.isReadOnly() ) {
8642 this.setIndicator( null );
8643 } else {
8644 this.setIndicator( 'clear' );
8645 }
8646 }
8647 };
8648
8649 /**
8650 * Position the label by setting the correct padding on the input.
8651 *
8652 * @private
8653 * @chainable
8654 */
8655 OO.ui.TextInputWidget.prototype.positionLabel = function () {
8656 var after, rtl, property;
8657 // Clear old values
8658 this.$input
8659 // Clear old values if present
8660 .css( {
8661 'padding-right': '',
8662 'padding-left': ''
8663 } );
8664
8665 if ( this.label ) {
8666 this.$element.append( this.$label );
8667 } else {
8668 this.$label.detach();
8669 return;
8670 }
8671
8672 after = this.labelPosition === 'after';
8673 rtl = this.$element.css( 'direction' ) === 'rtl';
8674 property = after === rtl ? 'padding-left' : 'padding-right';
8675
8676 this.$input.css( property, this.$label.outerWidth( true ) + ( after ? this.scrollWidth : 0 ) );
8677
8678 return this;
8679 };
8680
8681 /**
8682 * @inheritdoc
8683 */
8684 OO.ui.TextInputWidget.prototype.restorePreInfuseState = function ( state ) {
8685 OO.ui.TextInputWidget.parent.prototype.restorePreInfuseState.call( this, state );
8686 if ( state.scrollTop !== undefined ) {
8687 this.$input.scrollTop( state.scrollTop );
8688 }
8689 };
8690
8691 /**
8692 * ComboBoxInputWidgets combine a {@link OO.ui.TextInputWidget text input} (where a value
8693 * can be entered manually) and a {@link OO.ui.MenuSelectWidget menu of options} (from which
8694 * a value can be chosen instead). Users can choose options from the combo box in one of two ways:
8695 *
8696 * - by typing a value in the text input field. If the value exactly matches the value of a menu
8697 * option, that option will appear to be selected.
8698 * - by choosing a value from the menu. The value of the chosen option will then appear in the text
8699 * input field.
8700 *
8701 * This widget can be used inside a HTML form, such as a OO.ui.FormLayout.
8702 *
8703 * For more information about menus and options, please see the [OOjs UI documentation on MediaWiki][1].
8704 *
8705 * @example
8706 * // Example: A ComboBoxInputWidget.
8707 * var comboBox = new OO.ui.ComboBoxInputWidget( {
8708 * label: 'ComboBoxInputWidget',
8709 * value: 'Option 1',
8710 * menu: {
8711 * items: [
8712 * new OO.ui.MenuOptionWidget( {
8713 * data: 'Option 1',
8714 * label: 'Option One'
8715 * } ),
8716 * new OO.ui.MenuOptionWidget( {
8717 * data: 'Option 2',
8718 * label: 'Option Two'
8719 * } ),
8720 * new OO.ui.MenuOptionWidget( {
8721 * data: 'Option 3',
8722 * label: 'Option Three'
8723 * } ),
8724 * new OO.ui.MenuOptionWidget( {
8725 * data: 'Option 4',
8726 * label: 'Option Four'
8727 * } ),
8728 * new OO.ui.MenuOptionWidget( {
8729 * data: 'Option 5',
8730 * label: 'Option Five'
8731 * } )
8732 * ]
8733 * }
8734 * } );
8735 * $( 'body' ).append( comboBox.$element );
8736 *
8737 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
8738 *
8739 * @class
8740 * @extends OO.ui.TextInputWidget
8741 *
8742 * @constructor
8743 * @param {Object} [config] Configuration options
8744 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
8745 * @cfg {Object} [menu] Configuration options to pass to the {@link OO.ui.FloatingMenuSelectWidget menu select widget}.
8746 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
8747 * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
8748 * containing `<div>` and has a larger area. By default, the menu uses relative positioning.
8749 */
8750 OO.ui.ComboBoxInputWidget = function OoUiComboBoxInputWidget( config ) {
8751 // Configuration initialization
8752 config = $.extend( {
8753 indicator: 'down',
8754 autocomplete: false
8755 }, config );
8756 // For backwards-compatibility with ComboBoxWidget config
8757 $.extend( config, config.input );
8758
8759 // Parent constructor
8760 OO.ui.ComboBoxInputWidget.parent.call( this, config );
8761
8762 // Properties
8763 this.$overlay = config.$overlay || this.$element;
8764 this.menu = new OO.ui.FloatingMenuSelectWidget( $.extend(
8765 {
8766 widget: this,
8767 input: this,
8768 $container: this.$element,
8769 disabled: this.isDisabled()
8770 },
8771 config.menu
8772 ) );
8773 // For backwards-compatibility with ComboBoxWidget
8774 this.input = this;
8775
8776 // Events
8777 this.$indicator.on( {
8778 click: this.onIndicatorClick.bind( this ),
8779 keypress: this.onIndicatorKeyPress.bind( this )
8780 } );
8781 this.connect( this, {
8782 change: 'onInputChange',
8783 enter: 'onInputEnter'
8784 } );
8785 this.menu.connect( this, {
8786 choose: 'onMenuChoose',
8787 add: 'onMenuItemsChange',
8788 remove: 'onMenuItemsChange'
8789 } );
8790
8791 // Initialization
8792 this.$input.attr( {
8793 role: 'combobox',
8794 'aria-autocomplete': 'list'
8795 } );
8796 // Do not override options set via config.menu.items
8797 if ( config.options !== undefined ) {
8798 this.setOptions( config.options );
8799 }
8800 // Extra class for backwards-compatibility with ComboBoxWidget
8801 this.$element.addClass( 'oo-ui-comboBoxInputWidget oo-ui-comboBoxWidget' );
8802 this.$overlay.append( this.menu.$element );
8803 this.onMenuItemsChange();
8804 };
8805
8806 /* Setup */
8807
8808 OO.inheritClass( OO.ui.ComboBoxInputWidget, OO.ui.TextInputWidget );
8809
8810 /* Methods */
8811
8812 /**
8813 * Get the combobox's menu.
8814 *
8815 * @return {OO.ui.FloatingMenuSelectWidget} Menu widget
8816 */
8817 OO.ui.ComboBoxInputWidget.prototype.getMenu = function () {
8818 return this.menu;
8819 };
8820
8821 /**
8822 * Get the combobox's text input widget.
8823 *
8824 * @return {OO.ui.TextInputWidget} Text input widget
8825 */
8826 OO.ui.ComboBoxInputWidget.prototype.getInput = function () {
8827 return this;
8828 };
8829
8830 /**
8831 * Handle input change events.
8832 *
8833 * @private
8834 * @param {string} value New value
8835 */
8836 OO.ui.ComboBoxInputWidget.prototype.onInputChange = function ( value ) {
8837 var match = this.menu.getItemFromData( value );
8838
8839 this.menu.selectItem( match );
8840 if ( this.menu.getHighlightedItem() ) {
8841 this.menu.highlightItem( match );
8842 }
8843
8844 if ( !this.isDisabled() ) {
8845 this.menu.toggle( true );
8846 }
8847 };
8848
8849 /**
8850 * Handle mouse click events.
8851 *
8852 * @private
8853 * @param {jQuery.Event} e Mouse click event
8854 */
8855 OO.ui.ComboBoxInputWidget.prototype.onIndicatorClick = function ( e ) {
8856 if ( !this.isDisabled() && e.which === OO.ui.MouseButtons.LEFT ) {
8857 this.menu.toggle();
8858 this.$input[ 0 ].focus();
8859 }
8860 return false;
8861 };
8862
8863 /**
8864 * Handle key press events.
8865 *
8866 * @private
8867 * @param {jQuery.Event} e Key press event
8868 */
8869 OO.ui.ComboBoxInputWidget.prototype.onIndicatorKeyPress = function ( e ) {
8870 if ( !this.isDisabled() && ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER ) ) {
8871 this.menu.toggle();
8872 this.$input[ 0 ].focus();
8873 return false;
8874 }
8875 };
8876
8877 /**
8878 * Handle input enter events.
8879 *
8880 * @private
8881 */
8882 OO.ui.ComboBoxInputWidget.prototype.onInputEnter = function () {
8883 if ( !this.isDisabled() ) {
8884 this.menu.toggle( false );
8885 }
8886 };
8887
8888 /**
8889 * Handle menu choose events.
8890 *
8891 * @private
8892 * @param {OO.ui.OptionWidget} item Chosen item
8893 */
8894 OO.ui.ComboBoxInputWidget.prototype.onMenuChoose = function ( item ) {
8895 this.setValue( item.getData() );
8896 };
8897
8898 /**
8899 * Handle menu item change events.
8900 *
8901 * @private
8902 */
8903 OO.ui.ComboBoxInputWidget.prototype.onMenuItemsChange = function () {
8904 var match = this.menu.getItemFromData( this.getValue() );
8905 this.menu.selectItem( match );
8906 if ( this.menu.getHighlightedItem() ) {
8907 this.menu.highlightItem( match );
8908 }
8909 this.$element.toggleClass( 'oo-ui-comboBoxInputWidget-empty', this.menu.isEmpty() );
8910 };
8911
8912 /**
8913 * @inheritdoc
8914 */
8915 OO.ui.ComboBoxInputWidget.prototype.setDisabled = function ( disabled ) {
8916 // Parent method
8917 OO.ui.ComboBoxInputWidget.parent.prototype.setDisabled.call( this, disabled );
8918
8919 if ( this.menu ) {
8920 this.menu.setDisabled( this.isDisabled() );
8921 }
8922
8923 return this;
8924 };
8925
8926 /**
8927 * Set the options available for this input.
8928 *
8929 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
8930 * @chainable
8931 */
8932 OO.ui.ComboBoxInputWidget.prototype.setOptions = function ( options ) {
8933 this.getMenu()
8934 .clearItems()
8935 .addItems( options.map( function ( opt ) {
8936 return new OO.ui.MenuOptionWidget( {
8937 data: opt.data,
8938 label: opt.label !== undefined ? opt.label : opt.data
8939 } );
8940 } ) );
8941
8942 return this;
8943 };
8944
8945 /**
8946 * @class
8947 * @deprecated since 0.13.2; use OO.ui.ComboBoxInputWidget instead
8948 */
8949 OO.ui.ComboBoxWidget = OO.ui.ComboBoxInputWidget;
8950
8951 /**
8952 * FieldLayouts are used with OO.ui.FieldsetLayout. Each FieldLayout requires a field-widget,
8953 * which is a widget that is specified by reference before any optional configuration settings.
8954 *
8955 * Field layouts can be configured with help text and/or labels. Labels are aligned in one of four ways:
8956 *
8957 * - **left**: The label is placed before the field-widget and aligned with the left margin.
8958 * A left-alignment is used for forms with many fields.
8959 * - **right**: The label is placed before the field-widget and aligned to the right margin.
8960 * A right-alignment is used for long but familiar forms which users tab through,
8961 * verifying the current field with a quick glance at the label.
8962 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
8963 * that users fill out from top to bottom.
8964 * - **inline**: The label is placed after the field-widget and aligned to the left.
8965 * An inline-alignment is best used with checkboxes or radio buttons.
8966 *
8967 * Help text is accessed via a help icon that appears in the upper right corner of the rendered field layout.
8968 * Please see the [OOjs UI documentation on MediaWiki] [1] for examples and more information.
8969 *
8970 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Fields_and_Fieldsets
8971 *
8972 * @class
8973 * @extends OO.ui.Layout
8974 * @mixins OO.ui.mixin.LabelElement
8975 * @mixins OO.ui.mixin.TitledElement
8976 *
8977 * @constructor
8978 * @param {OO.ui.Widget} fieldWidget Field widget
8979 * @param {Object} [config] Configuration options
8980 * @cfg {string} [align='left'] Alignment of the label: 'left', 'right', 'top' or 'inline'
8981 * @cfg {Array} [errors] Error messages about the widget, which will be displayed below the widget.
8982 * The array may contain strings or OO.ui.HtmlSnippet instances.
8983 * @cfg {Array} [notices] Notices about the widget, which will be displayed below the widget.
8984 * The array may contain strings or OO.ui.HtmlSnippet instances.
8985 * @cfg {string|OO.ui.HtmlSnippet} [help] Help text. When help text is specified, a "help" icon will appear
8986 * in the upper-right corner of the rendered field; clicking it will display the text in a popup.
8987 * For important messages, you are advised to use `notices`, as they are always shown.
8988 *
8989 * @throws {Error} An error is thrown if no widget is specified
8990 */
8991 OO.ui.FieldLayout = function OoUiFieldLayout( fieldWidget, config ) {
8992 var hasInputWidget, div;
8993
8994 // Allow passing positional parameters inside the config object
8995 if ( OO.isPlainObject( fieldWidget ) && config === undefined ) {
8996 config = fieldWidget;
8997 fieldWidget = config.fieldWidget;
8998 }
8999
9000 // Make sure we have required constructor arguments
9001 if ( fieldWidget === undefined ) {
9002 throw new Error( 'Widget not found' );
9003 }
9004
9005 hasInputWidget = fieldWidget.constructor.static.supportsSimpleLabel;
9006
9007 // Configuration initialization
9008 config = $.extend( { align: 'left' }, config );
9009
9010 // Parent constructor
9011 OO.ui.FieldLayout.parent.call( this, config );
9012
9013 // Mixin constructors
9014 OO.ui.mixin.LabelElement.call( this, config );
9015 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$label } ) );
9016
9017 // Properties
9018 this.fieldWidget = fieldWidget;
9019 this.errors = [];
9020 this.notices = [];
9021 this.$field = $( '<div>' );
9022 this.$messages = $( '<ul>' );
9023 this.$body = $( '<' + ( hasInputWidget ? 'label' : 'div' ) + '>' );
9024 this.align = null;
9025 if ( config.help ) {
9026 this.popupButtonWidget = new OO.ui.PopupButtonWidget( {
9027 classes: [ 'oo-ui-fieldLayout-help' ],
9028 framed: false,
9029 icon: 'info'
9030 } );
9031
9032 div = $( '<div>' );
9033 if ( config.help instanceof OO.ui.HtmlSnippet ) {
9034 div.html( config.help.toString() );
9035 } else {
9036 div.text( config.help );
9037 }
9038 this.popupButtonWidget.getPopup().$body.append(
9039 div.addClass( 'oo-ui-fieldLayout-help-content' )
9040 );
9041 this.$help = this.popupButtonWidget.$element;
9042 } else {
9043 this.$help = $( [] );
9044 }
9045
9046 // Events
9047 if ( hasInputWidget ) {
9048 this.$label.on( 'click', this.onLabelClick.bind( this ) );
9049 }
9050 this.fieldWidget.connect( this, { disable: 'onFieldDisable' } );
9051
9052 // Initialization
9053 this.$element
9054 .addClass( 'oo-ui-fieldLayout' )
9055 .append( this.$help, this.$body );
9056 this.$body.addClass( 'oo-ui-fieldLayout-body' );
9057 this.$messages.addClass( 'oo-ui-fieldLayout-messages' );
9058 this.$field
9059 .addClass( 'oo-ui-fieldLayout-field' )
9060 .toggleClass( 'oo-ui-fieldLayout-disable', this.fieldWidget.isDisabled() )
9061 .append( this.fieldWidget.$element );
9062
9063 this.setErrors( config.errors || [] );
9064 this.setNotices( config.notices || [] );
9065 this.setAlignment( config.align );
9066 };
9067
9068 /* Setup */
9069
9070 OO.inheritClass( OO.ui.FieldLayout, OO.ui.Layout );
9071 OO.mixinClass( OO.ui.FieldLayout, OO.ui.mixin.LabelElement );
9072 OO.mixinClass( OO.ui.FieldLayout, OO.ui.mixin.TitledElement );
9073
9074 /* Methods */
9075
9076 /**
9077 * Handle field disable events.
9078 *
9079 * @private
9080 * @param {boolean} value Field is disabled
9081 */
9082 OO.ui.FieldLayout.prototype.onFieldDisable = function ( value ) {
9083 this.$element.toggleClass( 'oo-ui-fieldLayout-disabled', value );
9084 };
9085
9086 /**
9087 * Handle label mouse click events.
9088 *
9089 * @private
9090 * @param {jQuery.Event} e Mouse click event
9091 */
9092 OO.ui.FieldLayout.prototype.onLabelClick = function () {
9093 this.fieldWidget.simulateLabelClick();
9094 return false;
9095 };
9096
9097 /**
9098 * Get the widget contained by the field.
9099 *
9100 * @return {OO.ui.Widget} Field widget
9101 */
9102 OO.ui.FieldLayout.prototype.getField = function () {
9103 return this.fieldWidget;
9104 };
9105
9106 /**
9107 * @protected
9108 * @param {string} kind 'error' or 'notice'
9109 * @param {string|OO.ui.HtmlSnippet} text
9110 * @return {jQuery}
9111 */
9112 OO.ui.FieldLayout.prototype.makeMessage = function ( kind, text ) {
9113 var $listItem, $icon, message;
9114 $listItem = $( '<li>' );
9115 if ( kind === 'error' ) {
9116 $icon = new OO.ui.IconWidget( { icon: 'alert', flags: [ 'warning' ] } ).$element;
9117 } else if ( kind === 'notice' ) {
9118 $icon = new OO.ui.IconWidget( { icon: 'info' } ).$element;
9119 } else {
9120 $icon = '';
9121 }
9122 message = new OO.ui.LabelWidget( { label: text } );
9123 $listItem
9124 .append( $icon, message.$element )
9125 .addClass( 'oo-ui-fieldLayout-messages-' + kind );
9126 return $listItem;
9127 };
9128
9129 /**
9130 * Set the field alignment mode.
9131 *
9132 * @private
9133 * @param {string} value Alignment mode, either 'left', 'right', 'top' or 'inline'
9134 * @chainable
9135 */
9136 OO.ui.FieldLayout.prototype.setAlignment = function ( value ) {
9137 if ( value !== this.align ) {
9138 // Default to 'left'
9139 if ( [ 'left', 'right', 'top', 'inline' ].indexOf( value ) === -1 ) {
9140 value = 'left';
9141 }
9142 // Reorder elements
9143 if ( value === 'inline' ) {
9144 this.$body.append( this.$field, this.$label );
9145 } else {
9146 this.$body.append( this.$label, this.$field );
9147 }
9148 // Set classes. The following classes can be used here:
9149 // * oo-ui-fieldLayout-align-left
9150 // * oo-ui-fieldLayout-align-right
9151 // * oo-ui-fieldLayout-align-top
9152 // * oo-ui-fieldLayout-align-inline
9153 if ( this.align ) {
9154 this.$element.removeClass( 'oo-ui-fieldLayout-align-' + this.align );
9155 }
9156 this.$element.addClass( 'oo-ui-fieldLayout-align-' + value );
9157 this.align = value;
9158 }
9159
9160 return this;
9161 };
9162
9163 /**
9164 * Set the list of error messages.
9165 *
9166 * @param {Array} errors Error messages about the widget, which will be displayed below the widget.
9167 * The array may contain strings or OO.ui.HtmlSnippet instances.
9168 * @chainable
9169 */
9170 OO.ui.FieldLayout.prototype.setErrors = function ( errors ) {
9171 this.errors = errors.slice();
9172 this.updateMessages();
9173 return this;
9174 };
9175
9176 /**
9177 * Set the list of notice messages.
9178 *
9179 * @param {Array} notices Notices about the widget, which will be displayed below the widget.
9180 * The array may contain strings or OO.ui.HtmlSnippet instances.
9181 * @chainable
9182 */
9183 OO.ui.FieldLayout.prototype.setNotices = function ( notices ) {
9184 this.notices = notices.slice();
9185 this.updateMessages();
9186 return this;
9187 };
9188
9189 /**
9190 * Update the rendering of error and notice messages.
9191 *
9192 * @private
9193 */
9194 OO.ui.FieldLayout.prototype.updateMessages = function () {
9195 var i;
9196 this.$messages.empty();
9197
9198 if ( this.errors.length || this.notices.length ) {
9199 this.$body.after( this.$messages );
9200 } else {
9201 this.$messages.remove();
9202 return;
9203 }
9204
9205 for ( i = 0; i < this.notices.length; i++ ) {
9206 this.$messages.append( this.makeMessage( 'notice', this.notices[ i ] ) );
9207 }
9208 for ( i = 0; i < this.errors.length; i++ ) {
9209 this.$messages.append( this.makeMessage( 'error', this.errors[ i ] ) );
9210 }
9211 };
9212
9213 /**
9214 * ActionFieldLayouts are used with OO.ui.FieldsetLayout. The layout consists of a field-widget, a button,
9215 * and an optional label and/or help text. The field-widget (e.g., a {@link OO.ui.TextInputWidget TextInputWidget}),
9216 * is required and is specified before any optional configuration settings.
9217 *
9218 * Labels can be aligned in one of four ways:
9219 *
9220 * - **left**: The label is placed before the field-widget and aligned with the left margin.
9221 * A left-alignment is used for forms with many fields.
9222 * - **right**: The label is placed before the field-widget and aligned to the right margin.
9223 * A right-alignment is used for long but familiar forms which users tab through,
9224 * verifying the current field with a quick glance at the label.
9225 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
9226 * that users fill out from top to bottom.
9227 * - **inline**: The label is placed after the field-widget and aligned to the left.
9228 * An inline-alignment is best used with checkboxes or radio buttons.
9229 *
9230 * Help text is accessed via a help icon that appears in the upper right corner of the rendered field layout when help
9231 * text is specified.
9232 *
9233 * @example
9234 * // Example of an ActionFieldLayout
9235 * var actionFieldLayout = new OO.ui.ActionFieldLayout(
9236 * new OO.ui.TextInputWidget( {
9237 * placeholder: 'Field widget'
9238 * } ),
9239 * new OO.ui.ButtonWidget( {
9240 * label: 'Button'
9241 * } ),
9242 * {
9243 * label: 'An ActionFieldLayout. This label is aligned top',
9244 * align: 'top',
9245 * help: 'This is help text'
9246 * }
9247 * );
9248 *
9249 * $( 'body' ).append( actionFieldLayout.$element );
9250 *
9251 * @class
9252 * @extends OO.ui.FieldLayout
9253 *
9254 * @constructor
9255 * @param {OO.ui.Widget} fieldWidget Field widget
9256 * @param {OO.ui.ButtonWidget} buttonWidget Button widget
9257 */
9258 OO.ui.ActionFieldLayout = function OoUiActionFieldLayout( fieldWidget, buttonWidget, config ) {
9259 // Allow passing positional parameters inside the config object
9260 if ( OO.isPlainObject( fieldWidget ) && config === undefined ) {
9261 config = fieldWidget;
9262 fieldWidget = config.fieldWidget;
9263 buttonWidget = config.buttonWidget;
9264 }
9265
9266 // Parent constructor
9267 OO.ui.ActionFieldLayout.parent.call( this, fieldWidget, config );
9268
9269 // Properties
9270 this.buttonWidget = buttonWidget;
9271 this.$button = $( '<div>' );
9272 this.$input = $( '<div>' );
9273
9274 // Initialization
9275 this.$element
9276 .addClass( 'oo-ui-actionFieldLayout' );
9277 this.$button
9278 .addClass( 'oo-ui-actionFieldLayout-button' )
9279 .append( this.buttonWidget.$element );
9280 this.$input
9281 .addClass( 'oo-ui-actionFieldLayout-input' )
9282 .append( this.fieldWidget.$element );
9283 this.$field
9284 .append( this.$input, this.$button );
9285 };
9286
9287 /* Setup */
9288
9289 OO.inheritClass( OO.ui.ActionFieldLayout, OO.ui.FieldLayout );
9290
9291 /**
9292 * FieldsetLayouts are composed of one or more {@link OO.ui.FieldLayout FieldLayouts},
9293 * which each contain an individual widget and, optionally, a label. Each Fieldset can be
9294 * configured with a label as well. For more information and examples,
9295 * please see the [OOjs UI documentation on MediaWiki][1].
9296 *
9297 * @example
9298 * // Example of a fieldset layout
9299 * var input1 = new OO.ui.TextInputWidget( {
9300 * placeholder: 'A text input field'
9301 * } );
9302 *
9303 * var input2 = new OO.ui.TextInputWidget( {
9304 * placeholder: 'A text input field'
9305 * } );
9306 *
9307 * var fieldset = new OO.ui.FieldsetLayout( {
9308 * label: 'Example of a fieldset layout'
9309 * } );
9310 *
9311 * fieldset.addItems( [
9312 * new OO.ui.FieldLayout( input1, {
9313 * label: 'Field One'
9314 * } ),
9315 * new OO.ui.FieldLayout( input2, {
9316 * label: 'Field Two'
9317 * } )
9318 * ] );
9319 * $( 'body' ).append( fieldset.$element );
9320 *
9321 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Fields_and_Fieldsets
9322 *
9323 * @class
9324 * @extends OO.ui.Layout
9325 * @mixins OO.ui.mixin.IconElement
9326 * @mixins OO.ui.mixin.LabelElement
9327 * @mixins OO.ui.mixin.GroupElement
9328 *
9329 * @constructor
9330 * @param {Object} [config] Configuration options
9331 * @cfg {OO.ui.FieldLayout[]} [items] An array of fields to add to the fieldset. See OO.ui.FieldLayout for more information about fields.
9332 */
9333 OO.ui.FieldsetLayout = function OoUiFieldsetLayout( config ) {
9334 // Configuration initialization
9335 config = config || {};
9336
9337 // Parent constructor
9338 OO.ui.FieldsetLayout.parent.call( this, config );
9339
9340 // Mixin constructors
9341 OO.ui.mixin.IconElement.call( this, config );
9342 OO.ui.mixin.LabelElement.call( this, config );
9343 OO.ui.mixin.GroupElement.call( this, config );
9344
9345 if ( config.help ) {
9346 this.popupButtonWidget = new OO.ui.PopupButtonWidget( {
9347 classes: [ 'oo-ui-fieldsetLayout-help' ],
9348 framed: false,
9349 icon: 'info'
9350 } );
9351
9352 this.popupButtonWidget.getPopup().$body.append(
9353 $( '<div>' )
9354 .text( config.help )
9355 .addClass( 'oo-ui-fieldsetLayout-help-content' )
9356 );
9357 this.$help = this.popupButtonWidget.$element;
9358 } else {
9359 this.$help = $( [] );
9360 }
9361
9362 // Initialization
9363 this.$element
9364 .addClass( 'oo-ui-fieldsetLayout' )
9365 .prepend( this.$help, this.$icon, this.$label, this.$group );
9366 if ( Array.isArray( config.items ) ) {
9367 this.addItems( config.items );
9368 }
9369 };
9370
9371 /* Setup */
9372
9373 OO.inheritClass( OO.ui.FieldsetLayout, OO.ui.Layout );
9374 OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.mixin.IconElement );
9375 OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.mixin.LabelElement );
9376 OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.mixin.GroupElement );
9377
9378 /**
9379 * FormLayouts are used to wrap {@link OO.ui.FieldsetLayout FieldsetLayouts} when you intend to use browser-based
9380 * form submission for the fields instead of handling them in JavaScript. Form layouts can be configured with an
9381 * HTML form action, an encoding type, and a method using the #action, #enctype, and #method configs, respectively.
9382 * See the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
9383 *
9384 * Only widgets from the {@link OO.ui.InputWidget InputWidget} family support form submission. It
9385 * includes standard form elements like {@link OO.ui.CheckboxInputWidget checkboxes}, {@link
9386 * OO.ui.RadioInputWidget radio buttons} and {@link OO.ui.TextInputWidget text fields}, as well as
9387 * some fancier controls. Some controls have both regular and InputWidget variants, for example
9388 * OO.ui.DropdownWidget and OO.ui.DropdownInputWidget – only the latter support form submission and
9389 * often have simplified APIs to match the capabilities of HTML forms.
9390 * See the [OOjs UI Inputs documentation on MediaWiki] [2] for more information about InputWidgets.
9391 *
9392 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Forms
9393 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
9394 *
9395 * @example
9396 * // Example of a form layout that wraps a fieldset layout
9397 * var input1 = new OO.ui.TextInputWidget( {
9398 * placeholder: 'Username'
9399 * } );
9400 * var input2 = new OO.ui.TextInputWidget( {
9401 * placeholder: 'Password',
9402 * type: 'password'
9403 * } );
9404 * var submit = new OO.ui.ButtonInputWidget( {
9405 * label: 'Submit'
9406 * } );
9407 *
9408 * var fieldset = new OO.ui.FieldsetLayout( {
9409 * label: 'A form layout'
9410 * } );
9411 * fieldset.addItems( [
9412 * new OO.ui.FieldLayout( input1, {
9413 * label: 'Username',
9414 * align: 'top'
9415 * } ),
9416 * new OO.ui.FieldLayout( input2, {
9417 * label: 'Password',
9418 * align: 'top'
9419 * } ),
9420 * new OO.ui.FieldLayout( submit )
9421 * ] );
9422 * var form = new OO.ui.FormLayout( {
9423 * items: [ fieldset ],
9424 * action: '/api/formhandler',
9425 * method: 'get'
9426 * } )
9427 * $( 'body' ).append( form.$element );
9428 *
9429 * @class
9430 * @extends OO.ui.Layout
9431 * @mixins OO.ui.mixin.GroupElement
9432 *
9433 * @constructor
9434 * @param {Object} [config] Configuration options
9435 * @cfg {string} [method] HTML form `method` attribute
9436 * @cfg {string} [action] HTML form `action` attribute
9437 * @cfg {string} [enctype] HTML form `enctype` attribute
9438 * @cfg {OO.ui.FieldsetLayout[]} [items] Fieldset layouts to add to the form layout.
9439 */
9440 OO.ui.FormLayout = function OoUiFormLayout( config ) {
9441 var action;
9442
9443 // Configuration initialization
9444 config = config || {};
9445
9446 // Parent constructor
9447 OO.ui.FormLayout.parent.call( this, config );
9448
9449 // Mixin constructors
9450 OO.ui.mixin.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) );
9451
9452 // Events
9453 this.$element.on( 'submit', this.onFormSubmit.bind( this ) );
9454
9455 // Make sure the action is safe
9456 action = config.action;
9457 if ( action !== undefined && !OO.ui.isSafeUrl( action ) ) {
9458 action = './' + action;
9459 }
9460
9461 // Initialization
9462 this.$element
9463 .addClass( 'oo-ui-formLayout' )
9464 .attr( {
9465 method: config.method,
9466 action: action,
9467 enctype: config.enctype
9468 } );
9469 if ( Array.isArray( config.items ) ) {
9470 this.addItems( config.items );
9471 }
9472 };
9473
9474 /* Setup */
9475
9476 OO.inheritClass( OO.ui.FormLayout, OO.ui.Layout );
9477 OO.mixinClass( OO.ui.FormLayout, OO.ui.mixin.GroupElement );
9478
9479 /* Events */
9480
9481 /**
9482 * A 'submit' event is emitted when the form is submitted.
9483 *
9484 * @event submit
9485 */
9486
9487 /* Static Properties */
9488
9489 OO.ui.FormLayout.static.tagName = 'form';
9490
9491 /* Methods */
9492
9493 /**
9494 * Handle form submit events.
9495 *
9496 * @private
9497 * @param {jQuery.Event} e Submit event
9498 * @fires submit
9499 */
9500 OO.ui.FormLayout.prototype.onFormSubmit = function () {
9501 if ( this.emit( 'submit' ) ) {
9502 return false;
9503 }
9504 };
9505
9506 /**
9507 * PanelLayouts expand to cover the entire area of their parent. They can be configured with scrolling, padding,
9508 * and a frame, and are often used together with {@link OO.ui.StackLayout StackLayouts}.
9509 *
9510 * @example
9511 * // Example of a panel layout
9512 * var panel = new OO.ui.PanelLayout( {
9513 * expanded: false,
9514 * framed: true,
9515 * padded: true,
9516 * $content: $( '<p>A panel layout with padding and a frame.</p>' )
9517 * } );
9518 * $( 'body' ).append( panel.$element );
9519 *
9520 * @class
9521 * @extends OO.ui.Layout
9522 *
9523 * @constructor
9524 * @param {Object} [config] Configuration options
9525 * @cfg {boolean} [scrollable=false] Allow vertical scrolling
9526 * @cfg {boolean} [padded=false] Add padding between the content and the edges of the panel.
9527 * @cfg {boolean} [expanded=true] Expand the panel to fill the entire parent element.
9528 * @cfg {boolean} [framed=false] Render the panel with a frame to visually separate it from outside content.
9529 */
9530 OO.ui.PanelLayout = function OoUiPanelLayout( config ) {
9531 // Configuration initialization
9532 config = $.extend( {
9533 scrollable: false,
9534 padded: false,
9535 expanded: true,
9536 framed: false
9537 }, config );
9538
9539 // Parent constructor
9540 OO.ui.PanelLayout.parent.call( this, config );
9541
9542 // Initialization
9543 this.$element.addClass( 'oo-ui-panelLayout' );
9544 if ( config.scrollable ) {
9545 this.$element.addClass( 'oo-ui-panelLayout-scrollable' );
9546 }
9547 if ( config.padded ) {
9548 this.$element.addClass( 'oo-ui-panelLayout-padded' );
9549 }
9550 if ( config.expanded ) {
9551 this.$element.addClass( 'oo-ui-panelLayout-expanded' );
9552 }
9553 if ( config.framed ) {
9554 this.$element.addClass( 'oo-ui-panelLayout-framed' );
9555 }
9556 };
9557
9558 /* Setup */
9559
9560 OO.inheritClass( OO.ui.PanelLayout, OO.ui.Layout );
9561
9562 /* Methods */
9563
9564 /**
9565 * Focus the panel layout
9566 *
9567 * The default implementation just focuses the first focusable element in the panel
9568 */
9569 OO.ui.PanelLayout.prototype.focus = function () {
9570 OO.ui.findFocusable( this.$element ).focus();
9571 };
9572
9573 /**
9574 * HorizontalLayout arranges its contents in a single line (using `display: inline-block` for its
9575 * items), with small margins between them. Convenient when you need to put a number of block-level
9576 * widgets on a single line next to each other.
9577 *
9578 * Note that inline elements, such as OO.ui.ButtonWidgets, do not need this wrapper.
9579 *
9580 * @example
9581 * // HorizontalLayout with a text input and a label
9582 * var layout = new OO.ui.HorizontalLayout( {
9583 * items: [
9584 * new OO.ui.LabelWidget( { label: 'Label' } ),
9585 * new OO.ui.TextInputWidget( { value: 'Text' } )
9586 * ]
9587 * } );
9588 * $( 'body' ).append( layout.$element );
9589 *
9590 * @class
9591 * @extends OO.ui.Layout
9592 * @mixins OO.ui.mixin.GroupElement
9593 *
9594 * @constructor
9595 * @param {Object} [config] Configuration options
9596 * @cfg {OO.ui.Widget[]|OO.ui.Layout[]} [items] Widgets or other layouts to add to the layout.
9597 */
9598 OO.ui.HorizontalLayout = function OoUiHorizontalLayout( config ) {
9599 // Configuration initialization
9600 config = config || {};
9601
9602 // Parent constructor
9603 OO.ui.HorizontalLayout.parent.call( this, config );
9604
9605 // Mixin constructors
9606 OO.ui.mixin.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) );
9607
9608 // Initialization
9609 this.$element.addClass( 'oo-ui-horizontalLayout' );
9610 if ( Array.isArray( config.items ) ) {
9611 this.addItems( config.items );
9612 }
9613 };
9614
9615 /* Setup */
9616
9617 OO.inheritClass( OO.ui.HorizontalLayout, OO.ui.Layout );
9618 OO.mixinClass( OO.ui.HorizontalLayout, OO.ui.mixin.GroupElement );
9619
9620 }( OO ) );