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