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