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