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