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