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