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