Update OOjs UI to v0.13.2
[lhc/web/wiklou.git] / resources / lib / oojs-ui / oojs-ui.js
1 /*!
2 * OOjs UI v0.13.2
3 * https://www.mediawiki.org/wiki/OOjs_UI
4 *
5 * Copyright 2011–2015 OOjs UI Team and other contributors.
6 * Released under the MIT license
7 * http://oojs.mit-license.org
8 *
9 * Date: 2015-11-10T23:32:59Z
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 * @property {Number}
49 */
50 OO.ui.elementId = 0;
51
52 /**
53 * Generate a unique ID for element
54 *
55 * @return {String} [id]
56 */
57 OO.ui.generateElementId = function () {
58 OO.ui.elementId += 1;
59 return 'oojsui-' + OO.ui.elementId;
60 };
61
62 /**
63 * Check if an element is focusable.
64 * Inspired from :focusable in jQueryUI v1.11.4 - 2015-04-14
65 *
66 * @param {jQuery} element Element to test
67 * @return {boolean}
68 */
69 OO.ui.isFocusableElement = function ( $element ) {
70 var nodeName,
71 element = $element[ 0 ];
72
73 // Anything disabled is not focusable
74 if ( element.disabled ) {
75 return false;
76 }
77
78 // Check if the element is visible
79 if ( !(
80 // This is quicker than calling $element.is( ':visible' )
81 $.expr.filters.visible( element ) &&
82 // Check that all parents are visible
83 !$element.parents().addBack().filter( function () {
84 return $.css( this, 'visibility' ) === 'hidden';
85 } ).length
86 ) ) {
87 return false;
88 }
89
90 // Check if the element is ContentEditable, which is the string 'true'
91 if ( element.contentEditable === 'true' ) {
92 return true;
93 }
94
95 // Anything with a non-negative numeric tabIndex is focusable.
96 // Use .prop to avoid browser bugs
97 if ( $element.prop( 'tabIndex' ) >= 0 ) {
98 return true;
99 }
100
101 // Some element types are naturally focusable
102 // (indexOf is much faster than regex in Chrome and about the
103 // same in FF: https://jsperf.com/regex-vs-indexof-array2)
104 nodeName = element.nodeName.toLowerCase();
105 if ( [ 'input', 'select', 'textarea', 'button', 'object' ].indexOf( nodeName ) !== -1 ) {
106 return true;
107 }
108
109 // Links and areas are focusable if they have an href
110 if ( ( nodeName === 'a' || nodeName === 'area' ) && $element.attr( 'href' ) !== undefined ) {
111 return true;
112 }
113
114 return false;
115 };
116
117 /**
118 * Find a focusable child
119 *
120 * @param {jQuery} $container Container to search in
121 * @param {boolean} [backwards] Search backwards
122 * @return {jQuery} Focusable child, an empty jQuery object if none found
123 */
124 OO.ui.findFocusable = function ( $container, backwards ) {
125 var $focusable = $( [] ),
126 // $focusableCandidates is a superset of things that
127 // could get matched by isFocusableElement
128 $focusableCandidates = $container
129 .find( 'input, select, textarea, button, object, a, area, [contenteditable], [tabindex]' );
130
131 if ( backwards ) {
132 $focusableCandidates = Array.prototype.reverse.call( $focusableCandidates );
133 }
134
135 $focusableCandidates.each( function () {
136 var $this = $( this );
137 if ( OO.ui.isFocusableElement( $this ) ) {
138 $focusable = $this;
139 return false;
140 }
141 } );
142 return $focusable;
143 };
144
145 /**
146 * Get the user's language and any fallback languages.
147 *
148 * These language codes are used to localize user interface elements in the user's language.
149 *
150 * In environments that provide a localization system, this function should be overridden to
151 * return the user's language(s). The default implementation returns English (en) only.
152 *
153 * @return {string[]} Language codes, in descending order of priority
154 */
155 OO.ui.getUserLanguages = function () {
156 return [ 'en' ];
157 };
158
159 /**
160 * Get a value in an object keyed by language code.
161 *
162 * @param {Object.<string,Mixed>} obj Object keyed by language code
163 * @param {string|null} [lang] Language code, if omitted or null defaults to any user language
164 * @param {string} [fallback] Fallback code, used if no matching language can be found
165 * @return {Mixed} Local value
166 */
167 OO.ui.getLocalValue = function ( obj, lang, fallback ) {
168 var i, len, langs;
169
170 // Requested language
171 if ( obj[ lang ] ) {
172 return obj[ lang ];
173 }
174 // Known user language
175 langs = OO.ui.getUserLanguages();
176 for ( i = 0, len = langs.length; i < len; i++ ) {
177 lang = langs[ i ];
178 if ( obj[ lang ] ) {
179 return obj[ lang ];
180 }
181 }
182 // Fallback language
183 if ( obj[ fallback ] ) {
184 return obj[ fallback ];
185 }
186 // First existing language
187 for ( lang in obj ) {
188 return obj[ lang ];
189 }
190
191 return undefined;
192 };
193
194 /**
195 * Check if a node is contained within another node
196 *
197 * Similar to jQuery#contains except a list of containers can be supplied
198 * and a boolean argument allows you to include the container in the match list
199 *
200 * @param {HTMLElement|HTMLElement[]} containers Container node(s) to search in
201 * @param {HTMLElement} contained Node to find
202 * @param {boolean} [matchContainers] Include the container(s) in the list of nodes to match, otherwise only match descendants
203 * @return {boolean} The node is in the list of target nodes
204 */
205 OO.ui.contains = function ( containers, contained, matchContainers ) {
206 var i;
207 if ( !Array.isArray( containers ) ) {
208 containers = [ containers ];
209 }
210 for ( i = containers.length - 1; i >= 0; i-- ) {
211 if ( ( matchContainers && contained === containers[ i ] ) || $.contains( containers[ i ], contained ) ) {
212 return true;
213 }
214 }
215 return false;
216 };
217
218 /**
219 * Return a function, that, as long as it continues to be invoked, will not
220 * be triggered. The function will be called after it stops being called for
221 * N milliseconds. If `immediate` is passed, trigger the function on the
222 * leading edge, instead of the trailing.
223 *
224 * Ported from: http://underscorejs.org/underscore.js
225 *
226 * @param {Function} func
227 * @param {number} wait
228 * @param {boolean} immediate
229 * @return {Function}
230 */
231 OO.ui.debounce = function ( func, wait, immediate ) {
232 var timeout;
233 return function () {
234 var context = this,
235 args = arguments,
236 later = function () {
237 timeout = null;
238 if ( !immediate ) {
239 func.apply( context, args );
240 }
241 };
242 if ( immediate && !timeout ) {
243 func.apply( context, args );
244 }
245 clearTimeout( timeout );
246 timeout = setTimeout( later, wait );
247 };
248 };
249
250 /**
251 * Proxy for `node.addEventListener( eventName, handler, true )`, if the browser supports it.
252 * Otherwise falls back to non-capturing event listeners.
253 *
254 * @param {HTMLElement} node
255 * @param {string} eventName
256 * @param {Function} handler
257 */
258 OO.ui.addCaptureEventListener = function ( node, eventName, handler ) {
259 if ( node.addEventListener ) {
260 node.addEventListener( eventName, handler, true );
261 } else {
262 node.attachEvent( 'on' + eventName, handler );
263 }
264 };
265
266 /**
267 * Proxy for `node.removeEventListener( eventName, handler, true )`, if the browser supports it.
268 * Otherwise falls back to non-capturing event listeners.
269 *
270 * @param {HTMLElement} node
271 * @param {string} eventName
272 * @param {Function} handler
273 */
274 OO.ui.removeCaptureEventListener = function ( node, eventName, handler ) {
275 if ( node.addEventListener ) {
276 node.removeEventListener( eventName, handler, true );
277 } else {
278 node.detachEvent( 'on' + eventName, handler );
279 }
280 };
281
282 /**
283 * Reconstitute a JavaScript object corresponding to a widget created by
284 * the PHP implementation.
285 *
286 * This is an alias for `OO.ui.Element.static.infuse()`.
287 *
288 * @param {string|HTMLElement|jQuery} idOrNode
289 * A DOM id (if a string) or node for the widget to infuse.
290 * @return {OO.ui.Element}
291 * The `OO.ui.Element` corresponding to this (infusable) document node.
292 */
293 OO.ui.infuse = function ( idOrNode ) {
294 return OO.ui.Element.static.infuse( idOrNode );
295 };
296
297 ( function () {
298 /**
299 * Message store for the default implementation of OO.ui.msg
300 *
301 * Environments that provide a localization system should not use this, but should override
302 * OO.ui.msg altogether.
303 *
304 * @private
305 */
306 var messages = {
307 // Tool tip for a button that moves items in a list down one place
308 'ooui-outline-control-move-down': 'Move item down',
309 // Tool tip for a button that moves items in a list up one place
310 'ooui-outline-control-move-up': 'Move item up',
311 // Tool tip for a button that removes items from a list
312 'ooui-outline-control-remove': 'Remove item',
313 // Label for the toolbar group that contains a list of all other available tools
314 'ooui-toolbar-more': 'More',
315 // Label for the fake tool that expands the full list of tools in a toolbar group
316 'ooui-toolgroup-expand': 'More',
317 // Label for the fake tool that collapses the full list of tools in a toolbar group
318 'ooui-toolgroup-collapse': 'Fewer',
319 // Default label for the accept button of a confirmation dialog
320 'ooui-dialog-message-accept': 'OK',
321 // Default label for the reject button of a confirmation dialog
322 'ooui-dialog-message-reject': 'Cancel',
323 // Title for process dialog error description
324 'ooui-dialog-process-error': 'Something went wrong',
325 // Label for process dialog dismiss error button, visible when describing errors
326 'ooui-dialog-process-dismiss': 'Dismiss',
327 // Label for process dialog retry action button, visible when describing only recoverable errors
328 'ooui-dialog-process-retry': 'Try again',
329 // Label for process dialog retry action button, visible when describing only warnings
330 'ooui-dialog-process-continue': 'Continue',
331 // Label for the file selection widget's select file button
332 'ooui-selectfile-button-select': 'Select a file',
333 // Label for the file selection widget if file selection is not supported
334 'ooui-selectfile-not-supported': 'File selection is not supported',
335 // Label for the file selection widget when no file is currently selected
336 'ooui-selectfile-placeholder': 'No file is selected',
337 // Label for the file selection widget's drop target
338 'ooui-selectfile-dragdrop-placeholder': 'Drop file here'
339 };
340
341 /**
342 * Get a localized message.
343 *
344 * In environments that provide a localization system, this function should be overridden to
345 * return the message translated in the user's language. The default implementation always returns
346 * English messages.
347 *
348 * After the message key, message parameters may optionally be passed. In the default implementation,
349 * any occurrences of $1 are replaced with the first parameter, $2 with the second parameter, etc.
350 * Alternative implementations of OO.ui.msg may use any substitution system they like, as long as
351 * they support unnamed, ordered message parameters.
352 *
353 * @abstract
354 * @param {string} key Message key
355 * @param {Mixed...} [params] Message parameters
356 * @return {string} Translated message with parameters substituted
357 */
358 OO.ui.msg = function ( key ) {
359 var message = messages[ key ],
360 params = Array.prototype.slice.call( arguments, 1 );
361 if ( typeof message === 'string' ) {
362 // Perform $1 substitution
363 message = message.replace( /\$(\d+)/g, function ( unused, n ) {
364 var i = parseInt( n, 10 );
365 return params[ i - 1 ] !== undefined ? params[ i - 1 ] : '$' + n;
366 } );
367 } else {
368 // Return placeholder if message not found
369 message = '[' + key + ']';
370 }
371 return message;
372 };
373
374 /**
375 * Package a message and arguments for deferred resolution.
376 *
377 * Use this when you are statically specifying a message and the message may not yet be present.
378 *
379 * @param {string} key Message key
380 * @param {Mixed...} [params] Message parameters
381 * @return {Function} Function that returns the resolved message when executed
382 */
383 OO.ui.deferMsg = function () {
384 var args = arguments;
385 return function () {
386 return OO.ui.msg.apply( OO.ui, args );
387 };
388 };
389
390 /**
391 * Resolve a message.
392 *
393 * If the message is a function it will be executed, otherwise it will pass through directly.
394 *
395 * @param {Function|string} msg Deferred message, or message text
396 * @return {string} Resolved message
397 */
398 OO.ui.resolveMsg = function ( msg ) {
399 if ( $.isFunction( msg ) ) {
400 return msg();
401 }
402 return msg;
403 };
404
405 /**
406 * @param {string} url
407 * @return {boolean}
408 */
409 OO.ui.isSafeUrl = function ( url ) {
410 var protocol,
411 // Keep in sync with php/Tag.php
412 whitelist = [
413 'bitcoin:', 'ftp:', 'ftps:', 'geo:', 'git:', 'gopher:', 'http:', 'https:', 'irc:', 'ircs:',
414 'magnet:', 'mailto:', 'mms:', 'news:', 'nntp:', 'redis:', 'sftp:', 'sip:', 'sips:', 'sms:', 'ssh:',
415 'svn:', 'tel:', 'telnet:', 'urn:', 'worldwind:', 'xmpp:'
416 ];
417
418 if ( url.indexOf( ':' ) === -1 ) {
419 // No protocol, safe
420 return true;
421 }
422
423 protocol = url.split( ':', 1 )[ 0 ] + ':';
424 if ( !protocol.match( /^([A-za-z0-9\+\.\-])+:/ ) ) {
425 // Not a valid protocol, safe
426 return true;
427 }
428
429 // Safe if in the whitelist
430 return whitelist.indexOf( protocol ) !== -1;
431 };
432
433 } )();
434
435 /*!
436 * Mixin namespace.
437 */
438
439 /**
440 * Namespace for OOjs UI mixins.
441 *
442 * Mixins are named according to the type of object they are intended to
443 * be mixed in to. For example, OO.ui.mixin.GroupElement is intended to be
444 * mixed in to an instance of OO.ui.Element, and OO.ui.mixin.GroupWidget
445 * is intended to be mixed in to an instance of OO.ui.Widget.
446 *
447 * @class
448 * @singleton
449 */
450 OO.ui.mixin = {};
451
452 /**
453 * PendingElement is a mixin that is used to create elements that notify users that something is happening
454 * and that they should wait before proceeding. The pending state is visually represented with a pending
455 * texture that appears in the head of a pending {@link OO.ui.ProcessDialog process dialog} or in the input
456 * field of a {@link OO.ui.TextInputWidget text input widget}.
457 *
458 * Currently, {@link OO.ui.ActionWidget Action widgets}, which mix in this class, can also be marked as pending, but only when
459 * used in {@link OO.ui.MessageDialog message dialogs}. The behavior is not currently supported for action widgets used
460 * in process dialogs.
461 *
462 * @example
463 * function MessageDialog( config ) {
464 * MessageDialog.parent.call( this, config );
465 * }
466 * OO.inheritClass( MessageDialog, OO.ui.MessageDialog );
467 *
468 * MessageDialog.static.actions = [
469 * { action: 'save', label: 'Done', flags: 'primary' },
470 * { label: 'Cancel', flags: 'safe' }
471 * ];
472 *
473 * MessageDialog.prototype.initialize = function () {
474 * MessageDialog.parent.prototype.initialize.apply( this, arguments );
475 * this.content = new OO.ui.PanelLayout( { $: this.$, padded: true } );
476 * 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>' );
477 * this.$body.append( this.content.$element );
478 * };
479 * MessageDialog.prototype.getBodyHeight = function () {
480 * return 100;
481 * }
482 * MessageDialog.prototype.getActionProcess = function ( action ) {
483 * var dialog = this;
484 * if ( action === 'save' ) {
485 * dialog.getActions().get({actions: 'save'})[0].pushPending();
486 * return new OO.ui.Process()
487 * .next( 1000 )
488 * .next( function () {
489 * dialog.getActions().get({actions: 'save'})[0].popPending();
490 * } );
491 * }
492 * return MessageDialog.parent.prototype.getActionProcess.call( this, action );
493 * };
494 *
495 * var windowManager = new OO.ui.WindowManager();
496 * $( 'body' ).append( windowManager.$element );
497 *
498 * var dialog = new MessageDialog();
499 * windowManager.addWindows( [ dialog ] );
500 * windowManager.openWindow( dialog );
501 *
502 * @abstract
503 * @class
504 *
505 * @constructor
506 * @param {Object} [config] Configuration options
507 * @cfg {jQuery} [$pending] Element to mark as pending, defaults to this.$element
508 */
509 OO.ui.mixin.PendingElement = function OoUiMixinPendingElement( config ) {
510 // Configuration initialization
511 config = config || {};
512
513 // Properties
514 this.pending = 0;
515 this.$pending = null;
516
517 // Initialisation
518 this.setPendingElement( config.$pending || this.$element );
519 };
520
521 /* Setup */
522
523 OO.initClass( OO.ui.mixin.PendingElement );
524
525 /* Methods */
526
527 /**
528 * Set the pending element (and clean up any existing one).
529 *
530 * @param {jQuery} $pending The element to set to pending.
531 */
532 OO.ui.mixin.PendingElement.prototype.setPendingElement = function ( $pending ) {
533 if ( this.$pending ) {
534 this.$pending.removeClass( 'oo-ui-pendingElement-pending' );
535 }
536
537 this.$pending = $pending;
538 if ( this.pending > 0 ) {
539 this.$pending.addClass( 'oo-ui-pendingElement-pending' );
540 }
541 };
542
543 /**
544 * Check if an element is pending.
545 *
546 * @return {boolean} Element is pending
547 */
548 OO.ui.mixin.PendingElement.prototype.isPending = function () {
549 return !!this.pending;
550 };
551
552 /**
553 * Increase the pending counter. The pending state will remain active until the counter is zero
554 * (i.e., the number of calls to #pushPending and #popPending is the same).
555 *
556 * @chainable
557 */
558 OO.ui.mixin.PendingElement.prototype.pushPending = function () {
559 if ( this.pending === 0 ) {
560 this.$pending.addClass( 'oo-ui-pendingElement-pending' );
561 this.updateThemeClasses();
562 }
563 this.pending++;
564
565 return this;
566 };
567
568 /**
569 * Decrease the pending counter. The pending state will remain active until the counter is zero
570 * (i.e., the number of calls to #pushPending and #popPending is the same).
571 *
572 * @chainable
573 */
574 OO.ui.mixin.PendingElement.prototype.popPending = function () {
575 if ( this.pending === 1 ) {
576 this.$pending.removeClass( 'oo-ui-pendingElement-pending' );
577 this.updateThemeClasses();
578 }
579 this.pending = Math.max( 0, this.pending - 1 );
580
581 return this;
582 };
583
584 /**
585 * ActionSets manage the behavior of the {@link OO.ui.ActionWidget action widgets} that comprise them.
586 * Actions can be made available for specific contexts (modes) and circumstances
587 * (abilities). Action sets are primarily used with {@link OO.ui.Dialog Dialogs}.
588 *
589 * ActionSets contain two types of actions:
590 *
591 * - Special: Special actions are the first visible actions with special flags, such as 'safe' and 'primary', the default special flags. Additional special flags can be configured in subclasses with the static #specialFlags property.
592 * - Other: Other actions include all non-special visible actions.
593 *
594 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
595 *
596 * @example
597 * // Example: An action set used in a process dialog
598 * function MyProcessDialog( config ) {
599 * MyProcessDialog.parent.call( this, config );
600 * }
601 * OO.inheritClass( MyProcessDialog, OO.ui.ProcessDialog );
602 * MyProcessDialog.static.title = 'An action set in a process dialog';
603 * // An action set that uses modes ('edit' and 'help' mode, in this example).
604 * MyProcessDialog.static.actions = [
605 * { action: 'continue', modes: 'edit', label: 'Continue', flags: [ 'primary', 'constructive' ] },
606 * { action: 'help', modes: 'edit', label: 'Help' },
607 * { modes: 'edit', label: 'Cancel', flags: 'safe' },
608 * { action: 'back', modes: 'help', label: 'Back', flags: 'safe' }
609 * ];
610 *
611 * MyProcessDialog.prototype.initialize = function () {
612 * MyProcessDialog.parent.prototype.initialize.apply( this, arguments );
613 * this.panel1 = new OO.ui.PanelLayout( { padded: true, expanded: false } );
614 * this.panel1.$element.append( '<p>This dialog uses an action set (continue, help, cancel, back) configured with modes. This is edit mode. Click \'help\' to see help mode.</p>' );
615 * this.panel2 = new OO.ui.PanelLayout( { padded: true, expanded: false } );
616 * this.panel2.$element.append( '<p>This is help mode. Only the \'back\' action widget is configured to be visible here. Click \'back\' to return to \'edit\' mode.</p>' );
617 * this.stackLayout = new OO.ui.StackLayout( {
618 * items: [ this.panel1, this.panel2 ]
619 * } );
620 * this.$body.append( this.stackLayout.$element );
621 * };
622 * MyProcessDialog.prototype.getSetupProcess = function ( data ) {
623 * return MyProcessDialog.parent.prototype.getSetupProcess.call( this, data )
624 * .next( function () {
625 * this.actions.setMode( 'edit' );
626 * }, this );
627 * };
628 * MyProcessDialog.prototype.getActionProcess = function ( action ) {
629 * if ( action === 'help' ) {
630 * this.actions.setMode( 'help' );
631 * this.stackLayout.setItem( this.panel2 );
632 * } else if ( action === 'back' ) {
633 * this.actions.setMode( 'edit' );
634 * this.stackLayout.setItem( this.panel1 );
635 * } else if ( action === 'continue' ) {
636 * var dialog = this;
637 * return new OO.ui.Process( function () {
638 * dialog.close();
639 * } );
640 * }
641 * return MyProcessDialog.parent.prototype.getActionProcess.call( this, action );
642 * };
643 * MyProcessDialog.prototype.getBodyHeight = function () {
644 * return this.panel1.$element.outerHeight( true );
645 * };
646 * var windowManager = new OO.ui.WindowManager();
647 * $( 'body' ).append( windowManager.$element );
648 * var dialog = new MyProcessDialog( {
649 * size: 'medium'
650 * } );
651 * windowManager.addWindows( [ dialog ] );
652 * windowManager.openWindow( dialog );
653 *
654 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Action_sets
655 *
656 * @abstract
657 * @class
658 * @mixins OO.EventEmitter
659 *
660 * @constructor
661 * @param {Object} [config] Configuration options
662 */
663 OO.ui.ActionSet = function OoUiActionSet( config ) {
664 // Configuration initialization
665 config = config || {};
666
667 // Mixin constructors
668 OO.EventEmitter.call( this );
669
670 // Properties
671 this.list = [];
672 this.categories = {
673 actions: 'getAction',
674 flags: 'getFlags',
675 modes: 'getModes'
676 };
677 this.categorized = {};
678 this.special = {};
679 this.others = [];
680 this.organized = false;
681 this.changing = false;
682 this.changed = false;
683 };
684
685 /* Setup */
686
687 OO.mixinClass( OO.ui.ActionSet, OO.EventEmitter );
688
689 /* Static Properties */
690
691 /**
692 * Symbolic name of the flags used to identify special actions. Special actions are displayed in the
693 * header of a {@link OO.ui.ProcessDialog process dialog}.
694 * See the [OOjs UI documentation on MediaWiki][2] for more information and examples.
695 *
696 * [2]:https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs
697 *
698 * @abstract
699 * @static
700 * @inheritable
701 * @property {string}
702 */
703 OO.ui.ActionSet.static.specialFlags = [ 'safe', 'primary' ];
704
705 /* Events */
706
707 /**
708 * @event click
709 *
710 * A 'click' event is emitted when an action is clicked.
711 *
712 * @param {OO.ui.ActionWidget} action Action that was clicked
713 */
714
715 /**
716 * @event resize
717 *
718 * A 'resize' event is emitted when an action widget is resized.
719 *
720 * @param {OO.ui.ActionWidget} action Action that was resized
721 */
722
723 /**
724 * @event add
725 *
726 * An 'add' event is emitted when actions are {@link #method-add added} to the action set.
727 *
728 * @param {OO.ui.ActionWidget[]} added Actions added
729 */
730
731 /**
732 * @event remove
733 *
734 * A 'remove' event is emitted when actions are {@link #method-remove removed}
735 * or {@link #clear cleared}.
736 *
737 * @param {OO.ui.ActionWidget[]} added Actions removed
738 */
739
740 /**
741 * @event change
742 *
743 * A 'change' event is emitted when actions are {@link #method-add added}, {@link #clear cleared},
744 * or {@link #method-remove removed} from the action set or when the {@link #setMode mode} is changed.
745 *
746 */
747
748 /* Methods */
749
750 /**
751 * Handle action change events.
752 *
753 * @private
754 * @fires change
755 */
756 OO.ui.ActionSet.prototype.onActionChange = function () {
757 this.organized = false;
758 if ( this.changing ) {
759 this.changed = true;
760 } else {
761 this.emit( 'change' );
762 }
763 };
764
765 /**
766 * Check if an action is one of the special actions.
767 *
768 * @param {OO.ui.ActionWidget} action Action to check
769 * @return {boolean} Action is special
770 */
771 OO.ui.ActionSet.prototype.isSpecial = function ( action ) {
772 var flag;
773
774 for ( flag in this.special ) {
775 if ( action === this.special[ flag ] ) {
776 return true;
777 }
778 }
779
780 return false;
781 };
782
783 /**
784 * Get action widgets based on the specified filter: ‘actions’, ‘flags’, ‘modes’, ‘visible’,
785 * or ‘disabled’.
786 *
787 * @param {Object} [filters] Filters to use, omit to get all actions
788 * @param {string|string[]} [filters.actions] Actions that action widgets must have
789 * @param {string|string[]} [filters.flags] Flags that action widgets must have (e.g., 'safe')
790 * @param {string|string[]} [filters.modes] Modes that action widgets must have
791 * @param {boolean} [filters.visible] Action widgets must be visible
792 * @param {boolean} [filters.disabled] Action widgets must be disabled
793 * @return {OO.ui.ActionWidget[]} Action widgets matching all criteria
794 */
795 OO.ui.ActionSet.prototype.get = function ( filters ) {
796 var i, len, list, category, actions, index, match, matches;
797
798 if ( filters ) {
799 this.organize();
800
801 // Collect category candidates
802 matches = [];
803 for ( category in this.categorized ) {
804 list = filters[ category ];
805 if ( list ) {
806 if ( !Array.isArray( list ) ) {
807 list = [ list ];
808 }
809 for ( i = 0, len = list.length; i < len; i++ ) {
810 actions = this.categorized[ category ][ list[ i ] ];
811 if ( Array.isArray( actions ) ) {
812 matches.push.apply( matches, actions );
813 }
814 }
815 }
816 }
817 // Remove by boolean filters
818 for ( i = 0, len = matches.length; i < len; i++ ) {
819 match = matches[ i ];
820 if (
821 ( filters.visible !== undefined && match.isVisible() !== filters.visible ) ||
822 ( filters.disabled !== undefined && match.isDisabled() !== filters.disabled )
823 ) {
824 matches.splice( i, 1 );
825 len--;
826 i--;
827 }
828 }
829 // Remove duplicates
830 for ( i = 0, len = matches.length; i < len; i++ ) {
831 match = matches[ i ];
832 index = matches.lastIndexOf( match );
833 while ( index !== i ) {
834 matches.splice( index, 1 );
835 len--;
836 index = matches.lastIndexOf( match );
837 }
838 }
839 return matches;
840 }
841 return this.list.slice();
842 };
843
844 /**
845 * Get 'special' actions.
846 *
847 * Special actions are the first visible action widgets with special flags, such as 'safe' and 'primary'.
848 * Special flags can be configured in subclasses by changing the static #specialFlags property.
849 *
850 * @return {OO.ui.ActionWidget[]|null} 'Special' action widgets.
851 */
852 OO.ui.ActionSet.prototype.getSpecial = function () {
853 this.organize();
854 return $.extend( {}, this.special );
855 };
856
857 /**
858 * Get 'other' actions.
859 *
860 * Other actions include all non-special visible action widgets.
861 *
862 * @return {OO.ui.ActionWidget[]} 'Other' action widgets
863 */
864 OO.ui.ActionSet.prototype.getOthers = function () {
865 this.organize();
866 return this.others.slice();
867 };
868
869 /**
870 * Set the mode (e.g., ‘edit’ or ‘view’). Only {@link OO.ui.ActionWidget#modes actions} configured
871 * to be available in the specified mode will be made visible. All other actions will be hidden.
872 *
873 * @param {string} mode The mode. Only actions configured to be available in the specified
874 * mode will be made visible.
875 * @chainable
876 * @fires toggle
877 * @fires change
878 */
879 OO.ui.ActionSet.prototype.setMode = function ( mode ) {
880 var i, len, action;
881
882 this.changing = true;
883 for ( i = 0, len = this.list.length; i < len; i++ ) {
884 action = this.list[ i ];
885 action.toggle( action.hasMode( mode ) );
886 }
887
888 this.organized = false;
889 this.changing = false;
890 this.emit( 'change' );
891
892 return this;
893 };
894
895 /**
896 * Set the abilities of the specified actions.
897 *
898 * Action widgets that are configured with the specified actions will be enabled
899 * or disabled based on the boolean values specified in the `actions`
900 * parameter.
901 *
902 * @param {Object.<string,boolean>} actions A list keyed by action name with boolean
903 * values that indicate whether or not the action should be enabled.
904 * @chainable
905 */
906 OO.ui.ActionSet.prototype.setAbilities = function ( actions ) {
907 var i, len, action, item;
908
909 for ( i = 0, len = this.list.length; i < len; i++ ) {
910 item = this.list[ i ];
911 action = item.getAction();
912 if ( actions[ action ] !== undefined ) {
913 item.setDisabled( !actions[ action ] );
914 }
915 }
916
917 return this;
918 };
919
920 /**
921 * Executes a function once per action.
922 *
923 * When making changes to multiple actions, use this method instead of iterating over the actions
924 * manually to defer emitting a #change event until after all actions have been changed.
925 *
926 * @param {Object|null} actions Filters to use to determine which actions to iterate over; see #get
927 * @param {Function} callback Callback to run for each action; callback is invoked with three
928 * arguments: the action, the action's index, the list of actions being iterated over
929 * @chainable
930 */
931 OO.ui.ActionSet.prototype.forEach = function ( filter, callback ) {
932 this.changed = false;
933 this.changing = true;
934 this.get( filter ).forEach( callback );
935 this.changing = false;
936 if ( this.changed ) {
937 this.emit( 'change' );
938 }
939
940 return this;
941 };
942
943 /**
944 * Add action widgets to the action set.
945 *
946 * @param {OO.ui.ActionWidget[]} actions Action widgets to add
947 * @chainable
948 * @fires add
949 * @fires change
950 */
951 OO.ui.ActionSet.prototype.add = function ( actions ) {
952 var i, len, action;
953
954 this.changing = true;
955 for ( i = 0, len = actions.length; i < len; i++ ) {
956 action = actions[ i ];
957 action.connect( this, {
958 click: [ 'emit', 'click', action ],
959 resize: [ 'emit', 'resize', action ],
960 toggle: [ 'onActionChange' ]
961 } );
962 this.list.push( action );
963 }
964 this.organized = false;
965 this.emit( 'add', actions );
966 this.changing = false;
967 this.emit( 'change' );
968
969 return this;
970 };
971
972 /**
973 * Remove action widgets from the set.
974 *
975 * To remove all actions, you may wish to use the #clear method instead.
976 *
977 * @param {OO.ui.ActionWidget[]} actions Action widgets to remove
978 * @chainable
979 * @fires remove
980 * @fires change
981 */
982 OO.ui.ActionSet.prototype.remove = function ( actions ) {
983 var i, len, index, action;
984
985 this.changing = true;
986 for ( i = 0, len = actions.length; i < len; i++ ) {
987 action = actions[ i ];
988 index = this.list.indexOf( action );
989 if ( index !== -1 ) {
990 action.disconnect( this );
991 this.list.splice( index, 1 );
992 }
993 }
994 this.organized = false;
995 this.emit( 'remove', actions );
996 this.changing = false;
997 this.emit( 'change' );
998
999 return this;
1000 };
1001
1002 /**
1003 * Remove all action widets from the set.
1004 *
1005 * To remove only specified actions, use the {@link #method-remove remove} method instead.
1006 *
1007 * @chainable
1008 * @fires remove
1009 * @fires change
1010 */
1011 OO.ui.ActionSet.prototype.clear = function () {
1012 var i, len, action,
1013 removed = this.list.slice();
1014
1015 this.changing = true;
1016 for ( i = 0, len = this.list.length; i < len; i++ ) {
1017 action = this.list[ i ];
1018 action.disconnect( this );
1019 }
1020
1021 this.list = [];
1022
1023 this.organized = false;
1024 this.emit( 'remove', removed );
1025 this.changing = false;
1026 this.emit( 'change' );
1027
1028 return this;
1029 };
1030
1031 /**
1032 * Organize actions.
1033 *
1034 * This is called whenever organized information is requested. It will only reorganize the actions
1035 * if something has changed since the last time it ran.
1036 *
1037 * @private
1038 * @chainable
1039 */
1040 OO.ui.ActionSet.prototype.organize = function () {
1041 var i, iLen, j, jLen, flag, action, category, list, item, special,
1042 specialFlags = this.constructor.static.specialFlags;
1043
1044 if ( !this.organized ) {
1045 this.categorized = {};
1046 this.special = {};
1047 this.others = [];
1048 for ( i = 0, iLen = this.list.length; i < iLen; i++ ) {
1049 action = this.list[ i ];
1050 if ( action.isVisible() ) {
1051 // Populate categories
1052 for ( category in this.categories ) {
1053 if ( !this.categorized[ category ] ) {
1054 this.categorized[ category ] = {};
1055 }
1056 list = action[ this.categories[ category ] ]();
1057 if ( !Array.isArray( list ) ) {
1058 list = [ list ];
1059 }
1060 for ( j = 0, jLen = list.length; j < jLen; j++ ) {
1061 item = list[ j ];
1062 if ( !this.categorized[ category ][ item ] ) {
1063 this.categorized[ category ][ item ] = [];
1064 }
1065 this.categorized[ category ][ item ].push( action );
1066 }
1067 }
1068 // Populate special/others
1069 special = false;
1070 for ( j = 0, jLen = specialFlags.length; j < jLen; j++ ) {
1071 flag = specialFlags[ j ];
1072 if ( !this.special[ flag ] && action.hasFlag( flag ) ) {
1073 this.special[ flag ] = action;
1074 special = true;
1075 break;
1076 }
1077 }
1078 if ( !special ) {
1079 this.others.push( action );
1080 }
1081 }
1082 }
1083 this.organized = true;
1084 }
1085
1086 return this;
1087 };
1088
1089 /**
1090 * Each Element represents a rendering in the DOM—a button or an icon, for example, or anything
1091 * that is visible to a user. Unlike {@link OO.ui.Widget widgets}, plain elements usually do not have events
1092 * connected to them and can't be interacted with.
1093 *
1094 * @abstract
1095 * @class
1096 *
1097 * @constructor
1098 * @param {Object} [config] Configuration options
1099 * @cfg {string[]} [classes] The names of the CSS classes to apply to the element. CSS styles are added
1100 * to the top level (e.g., the outermost div) of the element. See the [OOjs UI documentation on MediaWiki][2]
1101 * for an example.
1102 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#cssExample
1103 * @cfg {string} [id] The HTML id attribute used in the rendered tag.
1104 * @cfg {string} [text] Text to insert
1105 * @cfg {Array} [content] An array of content elements to append (after #text).
1106 * Strings will be html-escaped; use an OO.ui.HtmlSnippet to append raw HTML.
1107 * Instances of OO.ui.Element will have their $element appended.
1108 * @cfg {jQuery} [$content] Content elements to append (after #text).
1109 * @cfg {jQuery} [$element] Wrapper element. Defaults to a new element with #getTagName.
1110 * @cfg {Mixed} [data] Custom data of any type or combination of types (e.g., string, number, array, object).
1111 * Data can also be specified with the #setData method.
1112 */
1113 OO.ui.Element = function OoUiElement( config ) {
1114 // Configuration initialization
1115 config = config || {};
1116
1117 // Properties
1118 this.$ = $;
1119 this.visible = true;
1120 this.data = config.data;
1121 this.$element = config.$element ||
1122 $( document.createElement( this.getTagName() ) );
1123 this.elementGroup = null;
1124 this.debouncedUpdateThemeClassesHandler = OO.ui.debounce( this.debouncedUpdateThemeClasses );
1125
1126 // Initialization
1127 if ( Array.isArray( config.classes ) ) {
1128 this.$element.addClass( config.classes.join( ' ' ) );
1129 }
1130 if ( config.id ) {
1131 this.$element.attr( 'id', config.id );
1132 }
1133 if ( config.text ) {
1134 this.$element.text( config.text );
1135 }
1136 if ( config.content ) {
1137 // The `content` property treats plain strings as text; use an
1138 // HtmlSnippet to append HTML content. `OO.ui.Element`s get their
1139 // appropriate $element appended.
1140 this.$element.append( config.content.map( function ( v ) {
1141 if ( typeof v === 'string' ) {
1142 // Escape string so it is properly represented in HTML.
1143 return document.createTextNode( v );
1144 } else if ( v instanceof OO.ui.HtmlSnippet ) {
1145 // Bypass escaping.
1146 return v.toString();
1147 } else if ( v instanceof OO.ui.Element ) {
1148 return v.$element;
1149 }
1150 return v;
1151 } ) );
1152 }
1153 if ( config.$content ) {
1154 // The `$content` property treats plain strings as HTML.
1155 this.$element.append( config.$content );
1156 }
1157 };
1158
1159 /* Setup */
1160
1161 OO.initClass( OO.ui.Element );
1162
1163 /* Static Properties */
1164
1165 /**
1166 * The name of the HTML tag used by the element.
1167 *
1168 * The static value may be ignored if the #getTagName method is overridden.
1169 *
1170 * @static
1171 * @inheritable
1172 * @property {string}
1173 */
1174 OO.ui.Element.static.tagName = 'div';
1175
1176 /* Static Methods */
1177
1178 /**
1179 * Reconstitute a JavaScript object corresponding to a widget created
1180 * by the PHP implementation.
1181 *
1182 * @param {string|HTMLElement|jQuery} idOrNode
1183 * A DOM id (if a string) or node for the widget to infuse.
1184 * @return {OO.ui.Element}
1185 * The `OO.ui.Element` corresponding to this (infusable) document node.
1186 * For `Tag` objects emitted on the HTML side (used occasionally for content)
1187 * the value returned is a newly-created Element wrapping around the existing
1188 * DOM node.
1189 */
1190 OO.ui.Element.static.infuse = function ( idOrNode ) {
1191 var obj = OO.ui.Element.static.unsafeInfuse( idOrNode, false );
1192 // Verify that the type matches up.
1193 // FIXME: uncomment after T89721 is fixed (see T90929)
1194 /*
1195 if ( !( obj instanceof this['class'] ) ) {
1196 throw new Error( 'Infusion type mismatch!' );
1197 }
1198 */
1199 return obj;
1200 };
1201
1202 /**
1203 * Implementation helper for `infuse`; skips the type check and has an
1204 * extra property so that only the top-level invocation touches the DOM.
1205 * @private
1206 * @param {string|HTMLElement|jQuery} idOrNode
1207 * @param {jQuery.Promise|boolean} domPromise A promise that will be resolved
1208 * when the top-level widget of this infusion is inserted into DOM,
1209 * replacing the original node; or false for top-level invocation.
1210 * @return {OO.ui.Element}
1211 */
1212 OO.ui.Element.static.unsafeInfuse = function ( idOrNode, domPromise ) {
1213 // look for a cached result of a previous infusion.
1214 var id, $elem, data, cls, parts, parent, obj, top, state;
1215 if ( typeof idOrNode === 'string' ) {
1216 id = idOrNode;
1217 $elem = $( document.getElementById( id ) );
1218 } else {
1219 $elem = $( idOrNode );
1220 id = $elem.attr( 'id' );
1221 }
1222 if ( !$elem.length ) {
1223 throw new Error( 'Widget not found: ' + id );
1224 }
1225 data = $elem.data( 'ooui-infused' ) || $elem[ 0 ].oouiInfused;
1226 if ( data ) {
1227 // cached!
1228 if ( data === true ) {
1229 throw new Error( 'Circular dependency! ' + id );
1230 }
1231 return data;
1232 }
1233 data = $elem.attr( 'data-ooui' );
1234 if ( !data ) {
1235 throw new Error( 'No infusion data found: ' + id );
1236 }
1237 try {
1238 data = $.parseJSON( data );
1239 } catch ( _ ) {
1240 data = null;
1241 }
1242 if ( !( data && data._ ) ) {
1243 throw new Error( 'No valid infusion data found: ' + id );
1244 }
1245 if ( data._ === 'Tag' ) {
1246 // Special case: this is a raw Tag; wrap existing node, don't rebuild.
1247 return new OO.ui.Element( { $element: $elem } );
1248 }
1249 parts = data._.split( '.' );
1250 cls = OO.getProp.apply( OO, [ window ].concat( parts ) );
1251 if ( cls === undefined ) {
1252 // The PHP output might be old and not including the "OO.ui" prefix
1253 // TODO: Remove this back-compat after next major release
1254 cls = OO.getProp.apply( OO, [ OO.ui ].concat( parts ) );
1255 if ( cls === undefined ) {
1256 throw new Error( 'Unknown widget type: id: ' + id + ', class: ' + data._ );
1257 }
1258 }
1259
1260 // Verify that we're creating an OO.ui.Element instance
1261 parent = cls.parent;
1262
1263 while ( parent !== undefined ) {
1264 if ( parent === OO.ui.Element ) {
1265 // Safe
1266 break;
1267 }
1268
1269 parent = parent.parent;
1270 }
1271
1272 if ( parent !== OO.ui.Element ) {
1273 throw new Error( 'Unknown widget type: id: ' + id + ', class: ' + data._ );
1274 }
1275
1276 if ( domPromise === false ) {
1277 top = $.Deferred();
1278 domPromise = top.promise();
1279 }
1280 $elem.data( 'ooui-infused', true ); // prevent loops
1281 data.id = id; // implicit
1282 data = OO.copy( data, null, function deserialize( value ) {
1283 if ( OO.isPlainObject( value ) ) {
1284 if ( value.tag ) {
1285 return OO.ui.Element.static.unsafeInfuse( value.tag, domPromise );
1286 }
1287 if ( value.html ) {
1288 return new OO.ui.HtmlSnippet( value.html );
1289 }
1290 }
1291 } );
1292 // allow widgets to reuse parts of the DOM
1293 data = cls.static.reusePreInfuseDOM( $elem[ 0 ], data );
1294 // pick up dynamic state, like focus, value of form inputs, scroll position, etc.
1295 state = cls.static.gatherPreInfuseState( $elem[ 0 ], data );
1296 // rebuild widget
1297 // jscs:disable requireCapitalizedConstructors
1298 obj = new cls( data );
1299 // jscs:enable requireCapitalizedConstructors
1300 // now replace old DOM with this new DOM.
1301 if ( top ) {
1302 // An efficient constructor might be able to reuse the entire DOM tree of the original element,
1303 // so only mutate the DOM if we need to.
1304 if ( $elem[ 0 ] !== obj.$element[ 0 ] ) {
1305 $elem.replaceWith( obj.$element );
1306 // This element is now gone from the DOM, but if anyone is holding a reference to it,
1307 // let's allow them to OO.ui.infuse() it and do what they expect (T105828).
1308 // Do not use jQuery.data(), as using it on detached nodes leaks memory in 1.x line by design.
1309 $elem[ 0 ].oouiInfused = obj;
1310 }
1311 top.resolve();
1312 }
1313 obj.$element.data( 'ooui-infused', obj );
1314 // set the 'data-ooui' attribute so we can identify infused widgets
1315 obj.$element.attr( 'data-ooui', '' );
1316 // restore dynamic state after the new element is inserted into DOM
1317 domPromise.done( obj.restorePreInfuseState.bind( obj, state ) );
1318 return obj;
1319 };
1320
1321 /**
1322 * Pick out parts of `node`'s DOM to be reused when infusing a widget.
1323 *
1324 * This method **must not** make any changes to the DOM, only find interesting pieces and add them
1325 * to `config` (which should then be returned). Actual DOM juggling should then be done by the
1326 * constructor, which will be given the enhanced config.
1327 *
1328 * @protected
1329 * @param {HTMLElement} node
1330 * @param {Object} config
1331 * @return {Object}
1332 */
1333 OO.ui.Element.static.reusePreInfuseDOM = function ( node, config ) {
1334 return config;
1335 };
1336
1337 /**
1338 * Gather the dynamic state (focus, value of form inputs, scroll position, etc.) of a HTML DOM node
1339 * (and its children) that represent an Element of the same class and the given configuration,
1340 * generated by the PHP implementation.
1341 *
1342 * This method is called just before `node` is detached from the DOM. The return value of this
1343 * function will be passed to #restorePreInfuseState after the newly created widget's #$element
1344 * is inserted into DOM to replace `node`.
1345 *
1346 * @protected
1347 * @param {HTMLElement} node
1348 * @param {Object} config
1349 * @return {Object}
1350 */
1351 OO.ui.Element.static.gatherPreInfuseState = function () {
1352 return {};
1353 };
1354
1355 /**
1356 * Get a jQuery function within a specific document.
1357 *
1358 * @static
1359 * @param {jQuery|HTMLElement|HTMLDocument|Window} context Context to bind the function to
1360 * @param {jQuery} [$iframe] HTML iframe element that contains the document, omit if document is
1361 * not in an iframe
1362 * @return {Function} Bound jQuery function
1363 */
1364 OO.ui.Element.static.getJQuery = function ( context, $iframe ) {
1365 function wrapper( selector ) {
1366 return $( selector, wrapper.context );
1367 }
1368
1369 wrapper.context = this.getDocument( context );
1370
1371 if ( $iframe ) {
1372 wrapper.$iframe = $iframe;
1373 }
1374
1375 return wrapper;
1376 };
1377
1378 /**
1379 * Get the document of an element.
1380 *
1381 * @static
1382 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Object to get the document for
1383 * @return {HTMLDocument|null} Document object
1384 */
1385 OO.ui.Element.static.getDocument = function ( obj ) {
1386 // jQuery - selections created "offscreen" won't have a context, so .context isn't reliable
1387 return ( obj[ 0 ] && obj[ 0 ].ownerDocument ) ||
1388 // Empty jQuery selections might have a context
1389 obj.context ||
1390 // HTMLElement
1391 obj.ownerDocument ||
1392 // Window
1393 obj.document ||
1394 // HTMLDocument
1395 ( obj.nodeType === 9 && obj ) ||
1396 null;
1397 };
1398
1399 /**
1400 * Get the window of an element or document.
1401 *
1402 * @static
1403 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the window for
1404 * @return {Window} Window object
1405 */
1406 OO.ui.Element.static.getWindow = function ( obj ) {
1407 var doc = this.getDocument( obj );
1408 // Support: IE 8
1409 // Standard Document.defaultView is IE9+
1410 return doc.parentWindow || doc.defaultView;
1411 };
1412
1413 /**
1414 * Get the direction of an element or document.
1415 *
1416 * @static
1417 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the direction for
1418 * @return {string} Text direction, either 'ltr' or 'rtl'
1419 */
1420 OO.ui.Element.static.getDir = function ( obj ) {
1421 var isDoc, isWin;
1422
1423 if ( obj instanceof jQuery ) {
1424 obj = obj[ 0 ];
1425 }
1426 isDoc = obj.nodeType === 9;
1427 isWin = obj.document !== undefined;
1428 if ( isDoc || isWin ) {
1429 if ( isWin ) {
1430 obj = obj.document;
1431 }
1432 obj = obj.body;
1433 }
1434 return $( obj ).css( 'direction' );
1435 };
1436
1437 /**
1438 * Get the offset between two frames.
1439 *
1440 * TODO: Make this function not use recursion.
1441 *
1442 * @static
1443 * @param {Window} from Window of the child frame
1444 * @param {Window} [to=window] Window of the parent frame
1445 * @param {Object} [offset] Offset to start with, used internally
1446 * @return {Object} Offset object, containing left and top properties
1447 */
1448 OO.ui.Element.static.getFrameOffset = function ( from, to, offset ) {
1449 var i, len, frames, frame, rect;
1450
1451 if ( !to ) {
1452 to = window;
1453 }
1454 if ( !offset ) {
1455 offset = { top: 0, left: 0 };
1456 }
1457 if ( from.parent === from ) {
1458 return offset;
1459 }
1460
1461 // Get iframe element
1462 frames = from.parent.document.getElementsByTagName( 'iframe' );
1463 for ( i = 0, len = frames.length; i < len; i++ ) {
1464 if ( frames[ i ].contentWindow === from ) {
1465 frame = frames[ i ];
1466 break;
1467 }
1468 }
1469
1470 // Recursively accumulate offset values
1471 if ( frame ) {
1472 rect = frame.getBoundingClientRect();
1473 offset.left += rect.left;
1474 offset.top += rect.top;
1475 if ( from !== to ) {
1476 this.getFrameOffset( from.parent, offset );
1477 }
1478 }
1479 return offset;
1480 };
1481
1482 /**
1483 * Get the offset between two elements.
1484 *
1485 * The two elements may be in a different frame, but in that case the frame $element is in must
1486 * be contained in the frame $anchor is in.
1487 *
1488 * @static
1489 * @param {jQuery} $element Element whose position to get
1490 * @param {jQuery} $anchor Element to get $element's position relative to
1491 * @return {Object} Translated position coordinates, containing top and left properties
1492 */
1493 OO.ui.Element.static.getRelativePosition = function ( $element, $anchor ) {
1494 var iframe, iframePos,
1495 pos = $element.offset(),
1496 anchorPos = $anchor.offset(),
1497 elementDocument = this.getDocument( $element ),
1498 anchorDocument = this.getDocument( $anchor );
1499
1500 // If $element isn't in the same document as $anchor, traverse up
1501 while ( elementDocument !== anchorDocument ) {
1502 iframe = elementDocument.defaultView.frameElement;
1503 if ( !iframe ) {
1504 throw new Error( '$element frame is not contained in $anchor frame' );
1505 }
1506 iframePos = $( iframe ).offset();
1507 pos.left += iframePos.left;
1508 pos.top += iframePos.top;
1509 elementDocument = iframe.ownerDocument;
1510 }
1511 pos.left -= anchorPos.left;
1512 pos.top -= anchorPos.top;
1513 return pos;
1514 };
1515
1516 /**
1517 * Get element border sizes.
1518 *
1519 * @static
1520 * @param {HTMLElement} el Element to measure
1521 * @return {Object} Dimensions object with `top`, `left`, `bottom` and `right` properties
1522 */
1523 OO.ui.Element.static.getBorders = function ( el ) {
1524 var doc = el.ownerDocument,
1525 // Support: IE 8
1526 // Standard Document.defaultView is IE9+
1527 win = doc.parentWindow || doc.defaultView,
1528 style = win && win.getComputedStyle ?
1529 win.getComputedStyle( el, null ) :
1530 // Support: IE 8
1531 // Standard getComputedStyle() is IE9+
1532 el.currentStyle,
1533 $el = $( el ),
1534 top = parseFloat( style ? style.borderTopWidth : $el.css( 'borderTopWidth' ) ) || 0,
1535 left = parseFloat( style ? style.borderLeftWidth : $el.css( 'borderLeftWidth' ) ) || 0,
1536 bottom = parseFloat( style ? style.borderBottomWidth : $el.css( 'borderBottomWidth' ) ) || 0,
1537 right = parseFloat( style ? style.borderRightWidth : $el.css( 'borderRightWidth' ) ) || 0;
1538
1539 return {
1540 top: top,
1541 left: left,
1542 bottom: bottom,
1543 right: right
1544 };
1545 };
1546
1547 /**
1548 * Get dimensions of an element or window.
1549 *
1550 * @static
1551 * @param {HTMLElement|Window} el Element to measure
1552 * @return {Object} Dimensions object with `borders`, `scroll`, `scrollbar` and `rect` properties
1553 */
1554 OO.ui.Element.static.getDimensions = function ( el ) {
1555 var $el, $win,
1556 doc = el.ownerDocument || el.document,
1557 // Support: IE 8
1558 // Standard Document.defaultView is IE9+
1559 win = doc.parentWindow || doc.defaultView;
1560
1561 if ( win === el || el === doc.documentElement ) {
1562 $win = $( win );
1563 return {
1564 borders: { top: 0, left: 0, bottom: 0, right: 0 },
1565 scroll: {
1566 top: $win.scrollTop(),
1567 left: $win.scrollLeft()
1568 },
1569 scrollbar: { right: 0, bottom: 0 },
1570 rect: {
1571 top: 0,
1572 left: 0,
1573 bottom: $win.innerHeight(),
1574 right: $win.innerWidth()
1575 }
1576 };
1577 } else {
1578 $el = $( el );
1579 return {
1580 borders: this.getBorders( el ),
1581 scroll: {
1582 top: $el.scrollTop(),
1583 left: $el.scrollLeft()
1584 },
1585 scrollbar: {
1586 right: $el.innerWidth() - el.clientWidth,
1587 bottom: $el.innerHeight() - el.clientHeight
1588 },
1589 rect: el.getBoundingClientRect()
1590 };
1591 }
1592 };
1593
1594 /**
1595 * Get scrollable object parent
1596 *
1597 * documentElement can't be used to get or set the scrollTop
1598 * property on Blink. Changing and testing its value lets us
1599 * use 'body' or 'documentElement' based on what is working.
1600 *
1601 * https://code.google.com/p/chromium/issues/detail?id=303131
1602 *
1603 * @static
1604 * @param {HTMLElement} el Element to find scrollable parent for
1605 * @return {HTMLElement} Scrollable parent
1606 */
1607 OO.ui.Element.static.getRootScrollableElement = function ( el ) {
1608 var scrollTop, body;
1609
1610 if ( OO.ui.scrollableElement === undefined ) {
1611 body = el.ownerDocument.body;
1612 scrollTop = body.scrollTop;
1613 body.scrollTop = 1;
1614
1615 if ( body.scrollTop === 1 ) {
1616 body.scrollTop = scrollTop;
1617 OO.ui.scrollableElement = 'body';
1618 } else {
1619 OO.ui.scrollableElement = 'documentElement';
1620 }
1621 }
1622
1623 return el.ownerDocument[ OO.ui.scrollableElement ];
1624 };
1625
1626 /**
1627 * Get closest scrollable container.
1628 *
1629 * Traverses up until either a scrollable element or the root is reached, in which case the window
1630 * will be returned.
1631 *
1632 * @static
1633 * @param {HTMLElement} el Element to find scrollable container for
1634 * @param {string} [dimension] Dimension of scrolling to look for; `x`, `y` or omit for either
1635 * @return {HTMLElement} Closest scrollable container
1636 */
1637 OO.ui.Element.static.getClosestScrollableContainer = function ( el, dimension ) {
1638 var i, val,
1639 // props = [ 'overflow' ] doesn't work due to https://bugzilla.mozilla.org/show_bug.cgi?id=889091
1640 props = [ 'overflow-x', 'overflow-y' ],
1641 $parent = $( el ).parent();
1642
1643 if ( dimension === 'x' || dimension === 'y' ) {
1644 props = [ 'overflow-' + dimension ];
1645 }
1646
1647 while ( $parent.length ) {
1648 if ( $parent[ 0 ] === this.getRootScrollableElement( el ) ) {
1649 return $parent[ 0 ];
1650 }
1651 i = props.length;
1652 while ( i-- ) {
1653 val = $parent.css( props[ i ] );
1654 if ( val === 'auto' || val === 'scroll' ) {
1655 return $parent[ 0 ];
1656 }
1657 }
1658 $parent = $parent.parent();
1659 }
1660 return this.getDocument( el ).body;
1661 };
1662
1663 /**
1664 * Scroll element into view.
1665 *
1666 * @static
1667 * @param {HTMLElement} el Element to scroll into view
1668 * @param {Object} [config] Configuration options
1669 * @param {string} [config.duration] jQuery animation duration value
1670 * @param {string} [config.direction] Scroll in only one direction, e.g. 'x' or 'y', omit
1671 * to scroll in both directions
1672 * @param {Function} [config.complete] Function to call when scrolling completes
1673 */
1674 OO.ui.Element.static.scrollIntoView = function ( el, config ) {
1675 var rel, anim, callback, sc, $sc, eld, scd, $win;
1676
1677 // Configuration initialization
1678 config = config || {};
1679
1680 anim = {};
1681 callback = typeof config.complete === 'function' && config.complete;
1682 sc = this.getClosestScrollableContainer( el, config.direction );
1683 $sc = $( sc );
1684 eld = this.getDimensions( el );
1685 scd = this.getDimensions( sc );
1686 $win = $( this.getWindow( el ) );
1687
1688 // Compute the distances between the edges of el and the edges of the scroll viewport
1689 if ( $sc.is( 'html, body' ) ) {
1690 // If the scrollable container is the root, this is easy
1691 rel = {
1692 top: eld.rect.top,
1693 bottom: $win.innerHeight() - eld.rect.bottom,
1694 left: eld.rect.left,
1695 right: $win.innerWidth() - eld.rect.right
1696 };
1697 } else {
1698 // Otherwise, we have to subtract el's coordinates from sc's coordinates
1699 rel = {
1700 top: eld.rect.top - ( scd.rect.top + scd.borders.top ),
1701 bottom: scd.rect.bottom - scd.borders.bottom - scd.scrollbar.bottom - eld.rect.bottom,
1702 left: eld.rect.left - ( scd.rect.left + scd.borders.left ),
1703 right: scd.rect.right - scd.borders.right - scd.scrollbar.right - eld.rect.right
1704 };
1705 }
1706
1707 if ( !config.direction || config.direction === 'y' ) {
1708 if ( rel.top < 0 ) {
1709 anim.scrollTop = scd.scroll.top + rel.top;
1710 } else if ( rel.top > 0 && rel.bottom < 0 ) {
1711 anim.scrollTop = scd.scroll.top + Math.min( rel.top, -rel.bottom );
1712 }
1713 }
1714 if ( !config.direction || config.direction === 'x' ) {
1715 if ( rel.left < 0 ) {
1716 anim.scrollLeft = scd.scroll.left + rel.left;
1717 } else if ( rel.left > 0 && rel.right < 0 ) {
1718 anim.scrollLeft = scd.scroll.left + Math.min( rel.left, -rel.right );
1719 }
1720 }
1721 if ( !$.isEmptyObject( anim ) ) {
1722 $sc.stop( true ).animate( anim, config.duration || 'fast' );
1723 if ( callback ) {
1724 $sc.queue( function ( next ) {
1725 callback();
1726 next();
1727 } );
1728 }
1729 } else {
1730 if ( callback ) {
1731 callback();
1732 }
1733 }
1734 };
1735
1736 /**
1737 * Force the browser to reconsider whether it really needs to render scrollbars inside the element
1738 * and reserve space for them, because it probably doesn't.
1739 *
1740 * Workaround primarily for <https://code.google.com/p/chromium/issues/detail?id=387290>, but also
1741 * similar bugs in other browsers. "Just" forcing a reflow is not sufficient in all cases, we need
1742 * to first actually detach (or hide, but detaching is simpler) all children, *then* force a reflow,
1743 * and then reattach (or show) them back.
1744 *
1745 * @static
1746 * @param {HTMLElement} el Element to reconsider the scrollbars on
1747 */
1748 OO.ui.Element.static.reconsiderScrollbars = function ( el ) {
1749 var i, len, scrollLeft, scrollTop, nodes = [];
1750 // Save scroll position
1751 scrollLeft = el.scrollLeft;
1752 scrollTop = el.scrollTop;
1753 // Detach all children
1754 while ( el.firstChild ) {
1755 nodes.push( el.firstChild );
1756 el.removeChild( el.firstChild );
1757 }
1758 // Force reflow
1759 void el.offsetHeight;
1760 // Reattach all children
1761 for ( i = 0, len = nodes.length; i < len; i++ ) {
1762 el.appendChild( nodes[ i ] );
1763 }
1764 // Restore scroll position (no-op if scrollbars disappeared)
1765 el.scrollLeft = scrollLeft;
1766 el.scrollTop = scrollTop;
1767 };
1768
1769 /* Methods */
1770
1771 /**
1772 * Toggle visibility of an element.
1773 *
1774 * @param {boolean} [show] Make element visible, omit to toggle visibility
1775 * @fires visible
1776 * @chainable
1777 */
1778 OO.ui.Element.prototype.toggle = function ( show ) {
1779 show = show === undefined ? !this.visible : !!show;
1780
1781 if ( show !== this.isVisible() ) {
1782 this.visible = show;
1783 this.$element.toggleClass( 'oo-ui-element-hidden', !this.visible );
1784 this.emit( 'toggle', show );
1785 }
1786
1787 return this;
1788 };
1789
1790 /**
1791 * Check if element is visible.
1792 *
1793 * @return {boolean} element is visible
1794 */
1795 OO.ui.Element.prototype.isVisible = function () {
1796 return this.visible;
1797 };
1798
1799 /**
1800 * Get element data.
1801 *
1802 * @return {Mixed} Element data
1803 */
1804 OO.ui.Element.prototype.getData = function () {
1805 return this.data;
1806 };
1807
1808 /**
1809 * Set element data.
1810 *
1811 * @param {Mixed} Element data
1812 * @chainable
1813 */
1814 OO.ui.Element.prototype.setData = function ( data ) {
1815 this.data = data;
1816 return this;
1817 };
1818
1819 /**
1820 * Check if element supports one or more methods.
1821 *
1822 * @param {string|string[]} methods Method or list of methods to check
1823 * @return {boolean} All methods are supported
1824 */
1825 OO.ui.Element.prototype.supports = function ( methods ) {
1826 var i, len,
1827 support = 0;
1828
1829 methods = Array.isArray( methods ) ? methods : [ methods ];
1830 for ( i = 0, len = methods.length; i < len; i++ ) {
1831 if ( $.isFunction( this[ methods[ i ] ] ) ) {
1832 support++;
1833 }
1834 }
1835
1836 return methods.length === support;
1837 };
1838
1839 /**
1840 * Update the theme-provided classes.
1841 *
1842 * @localdoc This is called in element mixins and widget classes any time state changes.
1843 * Updating is debounced, minimizing overhead of changing multiple attributes and
1844 * guaranteeing that theme updates do not occur within an element's constructor
1845 */
1846 OO.ui.Element.prototype.updateThemeClasses = function () {
1847 this.debouncedUpdateThemeClassesHandler();
1848 };
1849
1850 /**
1851 * @private
1852 * @localdoc This method is called directly from the QUnit tests instead of #updateThemeClasses, to
1853 * make them synchronous.
1854 */
1855 OO.ui.Element.prototype.debouncedUpdateThemeClasses = function () {
1856 OO.ui.theme.updateElementClasses( this );
1857 };
1858
1859 /**
1860 * Get the HTML tag name.
1861 *
1862 * Override this method to base the result on instance information.
1863 *
1864 * @return {string} HTML tag name
1865 */
1866 OO.ui.Element.prototype.getTagName = function () {
1867 return this.constructor.static.tagName;
1868 };
1869
1870 /**
1871 * Check if the element is attached to the DOM
1872 * @return {boolean} The element is attached to the DOM
1873 */
1874 OO.ui.Element.prototype.isElementAttached = function () {
1875 return $.contains( this.getElementDocument(), this.$element[ 0 ] );
1876 };
1877
1878 /**
1879 * Get the DOM document.
1880 *
1881 * @return {HTMLDocument} Document object
1882 */
1883 OO.ui.Element.prototype.getElementDocument = function () {
1884 // Don't cache this in other ways either because subclasses could can change this.$element
1885 return OO.ui.Element.static.getDocument( this.$element );
1886 };
1887
1888 /**
1889 * Get the DOM window.
1890 *
1891 * @return {Window} Window object
1892 */
1893 OO.ui.Element.prototype.getElementWindow = function () {
1894 return OO.ui.Element.static.getWindow( this.$element );
1895 };
1896
1897 /**
1898 * Get closest scrollable container.
1899 */
1900 OO.ui.Element.prototype.getClosestScrollableElementContainer = function () {
1901 return OO.ui.Element.static.getClosestScrollableContainer( this.$element[ 0 ] );
1902 };
1903
1904 /**
1905 * Get group element is in.
1906 *
1907 * @return {OO.ui.mixin.GroupElement|null} Group element, null if none
1908 */
1909 OO.ui.Element.prototype.getElementGroup = function () {
1910 return this.elementGroup;
1911 };
1912
1913 /**
1914 * Set group element is in.
1915 *
1916 * @param {OO.ui.mixin.GroupElement|null} group Group element, null if none
1917 * @chainable
1918 */
1919 OO.ui.Element.prototype.setElementGroup = function ( group ) {
1920 this.elementGroup = group;
1921 return this;
1922 };
1923
1924 /**
1925 * Scroll element into view.
1926 *
1927 * @param {Object} [config] Configuration options
1928 */
1929 OO.ui.Element.prototype.scrollElementIntoView = function ( config ) {
1930 return OO.ui.Element.static.scrollIntoView( this.$element[ 0 ], config );
1931 };
1932
1933 /**
1934 * Restore the pre-infusion dynamic state for this widget.
1935 *
1936 * This method is called after #$element has been inserted into DOM. The parameter is the return
1937 * value of #gatherPreInfuseState.
1938 *
1939 * @protected
1940 * @param {Object} state
1941 */
1942 OO.ui.Element.prototype.restorePreInfuseState = function () {
1943 };
1944
1945 /**
1946 * Layouts are containers for elements and are used to arrange other widgets of arbitrary type in a way
1947 * that is centrally controlled and can be updated dynamically. Layouts can be, and usually are, combined.
1948 * See {@link OO.ui.FieldsetLayout FieldsetLayout}, {@link OO.ui.FieldLayout FieldLayout}, {@link OO.ui.FormLayout FormLayout},
1949 * {@link OO.ui.PanelLayout PanelLayout}, {@link OO.ui.StackLayout StackLayout}, {@link OO.ui.PageLayout PageLayout},
1950 * {@link OO.ui.HorizontalLayout HorizontalLayout}, and {@link OO.ui.BookletLayout BookletLayout} for more information and examples.
1951 *
1952 * @abstract
1953 * @class
1954 * @extends OO.ui.Element
1955 * @mixins OO.EventEmitter
1956 *
1957 * @constructor
1958 * @param {Object} [config] Configuration options
1959 */
1960 OO.ui.Layout = function OoUiLayout( config ) {
1961 // Configuration initialization
1962 config = config || {};
1963
1964 // Parent constructor
1965 OO.ui.Layout.parent.call( this, config );
1966
1967 // Mixin constructors
1968 OO.EventEmitter.call( this );
1969
1970 // Initialization
1971 this.$element.addClass( 'oo-ui-layout' );
1972 };
1973
1974 /* Setup */
1975
1976 OO.inheritClass( OO.ui.Layout, OO.ui.Element );
1977 OO.mixinClass( OO.ui.Layout, OO.EventEmitter );
1978
1979 /**
1980 * Widgets are compositions of one or more OOjs UI elements that users can both view
1981 * and interact with. All widgets can be configured and modified via a standard API,
1982 * and their state can change dynamically according to a model.
1983 *
1984 * @abstract
1985 * @class
1986 * @extends OO.ui.Element
1987 * @mixins OO.EventEmitter
1988 *
1989 * @constructor
1990 * @param {Object} [config] Configuration options
1991 * @cfg {boolean} [disabled=false] Disable the widget. Disabled widgets cannot be used and their
1992 * appearance reflects this state.
1993 */
1994 OO.ui.Widget = function OoUiWidget( config ) {
1995 // Initialize config
1996 config = $.extend( { disabled: false }, config );
1997
1998 // Parent constructor
1999 OO.ui.Widget.parent.call( this, config );
2000
2001 // Mixin constructors
2002 OO.EventEmitter.call( this );
2003
2004 // Properties
2005 this.disabled = null;
2006 this.wasDisabled = null;
2007
2008 // Initialization
2009 this.$element.addClass( 'oo-ui-widget' );
2010 this.setDisabled( !!config.disabled );
2011 };
2012
2013 /* Setup */
2014
2015 OO.inheritClass( OO.ui.Widget, OO.ui.Element );
2016 OO.mixinClass( OO.ui.Widget, OO.EventEmitter );
2017
2018 /* Static Properties */
2019
2020 /**
2021 * Whether this widget will behave reasonably when wrapped in a HTML `<label>`. If this is true,
2022 * wrappers such as OO.ui.FieldLayout may use a `<label>` instead of implementing own label click
2023 * handling.
2024 *
2025 * @static
2026 * @inheritable
2027 * @property {boolean}
2028 */
2029 OO.ui.Widget.static.supportsSimpleLabel = false;
2030
2031 /* Events */
2032
2033 /**
2034 * @event disable
2035 *
2036 * A 'disable' event is emitted when the disabled state of the widget changes
2037 * (i.e. on disable **and** enable).
2038 *
2039 * @param {boolean} disabled Widget is disabled
2040 */
2041
2042 /**
2043 * @event toggle
2044 *
2045 * A 'toggle' event is emitted when the visibility of the widget changes.
2046 *
2047 * @param {boolean} visible Widget is visible
2048 */
2049
2050 /* Methods */
2051
2052 /**
2053 * Check if the widget is disabled.
2054 *
2055 * @return {boolean} Widget is disabled
2056 */
2057 OO.ui.Widget.prototype.isDisabled = function () {
2058 return this.disabled;
2059 };
2060
2061 /**
2062 * Set the 'disabled' state of the widget.
2063 *
2064 * When a widget is disabled, it cannot be used and its appearance is updated to reflect this state.
2065 *
2066 * @param {boolean} disabled Disable widget
2067 * @chainable
2068 */
2069 OO.ui.Widget.prototype.setDisabled = function ( disabled ) {
2070 var isDisabled;
2071
2072 this.disabled = !!disabled;
2073 isDisabled = this.isDisabled();
2074 if ( isDisabled !== this.wasDisabled ) {
2075 this.$element.toggleClass( 'oo-ui-widget-disabled', isDisabled );
2076 this.$element.toggleClass( 'oo-ui-widget-enabled', !isDisabled );
2077 this.$element.attr( 'aria-disabled', isDisabled.toString() );
2078 this.emit( 'disable', isDisabled );
2079 this.updateThemeClasses();
2080 }
2081 this.wasDisabled = isDisabled;
2082
2083 return this;
2084 };
2085
2086 /**
2087 * Update the disabled state, in case of changes in parent widget.
2088 *
2089 * @chainable
2090 */
2091 OO.ui.Widget.prototype.updateDisabled = function () {
2092 this.setDisabled( this.disabled );
2093 return this;
2094 };
2095
2096 /**
2097 * A window is a container for elements that are in a child frame. They are used with
2098 * a window manager (OO.ui.WindowManager), which is used to open and close the window and control
2099 * its presentation. The size of a window is specified using a symbolic name (e.g., ‘small’, ‘medium’,
2100 * ‘large’), which is interpreted by the window manager. If the requested size is not recognized,
2101 * the window manager will choose a sensible fallback.
2102 *
2103 * The lifecycle of a window has three primary stages (opening, opened, and closing) in which
2104 * different processes are executed:
2105 *
2106 * **opening**: The opening stage begins when the window manager's {@link OO.ui.WindowManager#openWindow
2107 * openWindow} or the window's {@link #open open} methods are used, and the window manager begins to open
2108 * the window.
2109 *
2110 * - {@link #getSetupProcess} method is called and its result executed
2111 * - {@link #getReadyProcess} method is called and its result executed
2112 *
2113 * **opened**: The window is now open
2114 *
2115 * **closing**: The closing stage begins when the window manager's
2116 * {@link OO.ui.WindowManager#closeWindow closeWindow}
2117 * or the window's {@link #close} methods are used, and the window manager begins to close the window.
2118 *
2119 * - {@link #getHoldProcess} method is called and its result executed
2120 * - {@link #getTeardownProcess} method is called and its result executed. The window is now closed
2121 *
2122 * Each of the window's processes (setup, ready, hold, and teardown) can be extended in subclasses
2123 * by overriding the window's #getSetupProcess, #getReadyProcess, #getHoldProcess and #getTeardownProcess
2124 * methods. Note that each {@link OO.ui.Process process} is executed in series, so asynchronous
2125 * processing can complete. Always assume window processes are executed asynchronously.
2126 *
2127 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
2128 *
2129 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows
2130 *
2131 * @abstract
2132 * @class
2133 * @extends OO.ui.Element
2134 * @mixins OO.EventEmitter
2135 *
2136 * @constructor
2137 * @param {Object} [config] Configuration options
2138 * @cfg {string} [size] Symbolic name of the dialog size: `small`, `medium`, `large`, `larger` or
2139 * `full`. If omitted, the value of the {@link #static-size static size} property will be used.
2140 */
2141 OO.ui.Window = function OoUiWindow( config ) {
2142 // Configuration initialization
2143 config = config || {};
2144
2145 // Parent constructor
2146 OO.ui.Window.parent.call( this, config );
2147
2148 // Mixin constructors
2149 OO.EventEmitter.call( this );
2150
2151 // Properties
2152 this.manager = null;
2153 this.size = config.size || this.constructor.static.size;
2154 this.$frame = $( '<div>' );
2155 this.$overlay = $( '<div>' );
2156 this.$content = $( '<div>' );
2157
2158 this.$focusTrapBefore = $( '<div>' ).prop( 'tabIndex', 0 );
2159 this.$focusTrapAfter = $( '<div>' ).prop( 'tabIndex', 0 );
2160 this.$focusTraps = this.$focusTrapBefore.add( this.$focusTrapAfter );
2161
2162 // Initialization
2163 this.$overlay.addClass( 'oo-ui-window-overlay' );
2164 this.$content
2165 .addClass( 'oo-ui-window-content' )
2166 .attr( 'tabindex', 0 );
2167 this.$frame
2168 .addClass( 'oo-ui-window-frame' )
2169 .append( this.$focusTrapBefore, this.$content, this.$focusTrapAfter );
2170
2171 this.$element
2172 .addClass( 'oo-ui-window' )
2173 .append( this.$frame, this.$overlay );
2174
2175 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
2176 // that reference properties not initialized at that time of parent class construction
2177 // TODO: Find a better way to handle post-constructor setup
2178 this.visible = false;
2179 this.$element.addClass( 'oo-ui-element-hidden' );
2180 };
2181
2182 /* Setup */
2183
2184 OO.inheritClass( OO.ui.Window, OO.ui.Element );
2185 OO.mixinClass( OO.ui.Window, OO.EventEmitter );
2186
2187 /* Static Properties */
2188
2189 /**
2190 * Symbolic name of the window size: `small`, `medium`, `large`, `larger` or `full`.
2191 *
2192 * The static size is used if no #size is configured during construction.
2193 *
2194 * @static
2195 * @inheritable
2196 * @property {string}
2197 */
2198 OO.ui.Window.static.size = 'medium';
2199
2200 /* Methods */
2201
2202 /**
2203 * Handle mouse down events.
2204 *
2205 * @private
2206 * @param {jQuery.Event} e Mouse down event
2207 */
2208 OO.ui.Window.prototype.onMouseDown = function ( e ) {
2209 // Prevent clicking on the click-block from stealing focus
2210 if ( e.target === this.$element[ 0 ] ) {
2211 return false;
2212 }
2213 };
2214
2215 /**
2216 * Check if the window has been initialized.
2217 *
2218 * Initialization occurs when a window is added to a manager.
2219 *
2220 * @return {boolean} Window has been initialized
2221 */
2222 OO.ui.Window.prototype.isInitialized = function () {
2223 return !!this.manager;
2224 };
2225
2226 /**
2227 * Check if the window is visible.
2228 *
2229 * @return {boolean} Window is visible
2230 */
2231 OO.ui.Window.prototype.isVisible = function () {
2232 return this.visible;
2233 };
2234
2235 /**
2236 * Check if the window is opening.
2237 *
2238 * This method is a wrapper around the window manager's {@link OO.ui.WindowManager#isOpening isOpening}
2239 * method.
2240 *
2241 * @return {boolean} Window is opening
2242 */
2243 OO.ui.Window.prototype.isOpening = function () {
2244 return this.manager.isOpening( this );
2245 };
2246
2247 /**
2248 * Check if the window is closing.
2249 *
2250 * This method is a wrapper around the window manager's {@link OO.ui.WindowManager#isClosing isClosing} method.
2251 *
2252 * @return {boolean} Window is closing
2253 */
2254 OO.ui.Window.prototype.isClosing = function () {
2255 return this.manager.isClosing( this );
2256 };
2257
2258 /**
2259 * Check if the window is opened.
2260 *
2261 * This method is a wrapper around the window manager's {@link OO.ui.WindowManager#isOpened isOpened} method.
2262 *
2263 * @return {boolean} Window is opened
2264 */
2265 OO.ui.Window.prototype.isOpened = function () {
2266 return this.manager.isOpened( this );
2267 };
2268
2269 /**
2270 * Get the window manager.
2271 *
2272 * All windows must be attached to a window manager, which is used to open
2273 * and close the window and control its presentation.
2274 *
2275 * @return {OO.ui.WindowManager} Manager of window
2276 */
2277 OO.ui.Window.prototype.getManager = function () {
2278 return this.manager;
2279 };
2280
2281 /**
2282 * Get the symbolic name of the window size (e.g., `small` or `medium`).
2283 *
2284 * @return {string} Symbolic name of the size: `small`, `medium`, `large`, `larger`, `full`
2285 */
2286 OO.ui.Window.prototype.getSize = function () {
2287 var viewport = OO.ui.Element.static.getDimensions( this.getElementWindow() ),
2288 sizes = this.manager.constructor.static.sizes,
2289 size = this.size;
2290
2291 if ( !sizes[ size ] ) {
2292 size = this.manager.constructor.static.defaultSize;
2293 }
2294 if ( size !== 'full' && viewport.rect.right - viewport.rect.left < sizes[ size ].width ) {
2295 size = 'full';
2296 }
2297
2298 return size;
2299 };
2300
2301 /**
2302 * Get the size properties associated with the current window size
2303 *
2304 * @return {Object} Size properties
2305 */
2306 OO.ui.Window.prototype.getSizeProperties = function () {
2307 return this.manager.constructor.static.sizes[ this.getSize() ];
2308 };
2309
2310 /**
2311 * Disable transitions on window's frame for the duration of the callback function, then enable them
2312 * back.
2313 *
2314 * @private
2315 * @param {Function} callback Function to call while transitions are disabled
2316 */
2317 OO.ui.Window.prototype.withoutSizeTransitions = function ( callback ) {
2318 // Temporarily resize the frame so getBodyHeight() can use scrollHeight measurements.
2319 // Disable transitions first, otherwise we'll get values from when the window was animating.
2320 var oldTransition,
2321 styleObj = this.$frame[ 0 ].style;
2322 oldTransition = styleObj.transition || styleObj.OTransition || styleObj.MsTransition ||
2323 styleObj.MozTransition || styleObj.WebkitTransition;
2324 styleObj.transition = styleObj.OTransition = styleObj.MsTransition =
2325 styleObj.MozTransition = styleObj.WebkitTransition = 'none';
2326 callback();
2327 // Force reflow to make sure the style changes done inside callback really are not transitioned
2328 this.$frame.height();
2329 styleObj.transition = styleObj.OTransition = styleObj.MsTransition =
2330 styleObj.MozTransition = styleObj.WebkitTransition = oldTransition;
2331 };
2332
2333 /**
2334 * Get the height of the full window contents (i.e., the window head, body and foot together).
2335 *
2336 * What consistitutes the head, body, and foot varies depending on the window type.
2337 * A {@link OO.ui.MessageDialog message dialog} displays a title and message in its body,
2338 * and any actions in the foot. A {@link OO.ui.ProcessDialog process dialog} displays a title
2339 * and special actions in the head, and dialog content in the body.
2340 *
2341 * To get just the height of the dialog body, use the #getBodyHeight method.
2342 *
2343 * @return {number} The height of the window contents (the dialog head, body and foot) in pixels
2344 */
2345 OO.ui.Window.prototype.getContentHeight = function () {
2346 var bodyHeight,
2347 win = this,
2348 bodyStyleObj = this.$body[ 0 ].style,
2349 frameStyleObj = this.$frame[ 0 ].style;
2350
2351 // Temporarily resize the frame so getBodyHeight() can use scrollHeight measurements.
2352 // Disable transitions first, otherwise we'll get values from when the window was animating.
2353 this.withoutSizeTransitions( function () {
2354 var oldHeight = frameStyleObj.height,
2355 oldPosition = bodyStyleObj.position;
2356 frameStyleObj.height = '1px';
2357 // Force body to resize to new width
2358 bodyStyleObj.position = 'relative';
2359 bodyHeight = win.getBodyHeight();
2360 frameStyleObj.height = oldHeight;
2361 bodyStyleObj.position = oldPosition;
2362 } );
2363
2364 return (
2365 // Add buffer for border
2366 ( this.$frame.outerHeight() - this.$frame.innerHeight() ) +
2367 // Use combined heights of children
2368 ( this.$head.outerHeight( true ) + bodyHeight + this.$foot.outerHeight( true ) )
2369 );
2370 };
2371
2372 /**
2373 * Get the height of the window body.
2374 *
2375 * To get the height of the full window contents (the window body, head, and foot together),
2376 * use #getContentHeight.
2377 *
2378 * When this function is called, the window will temporarily have been resized
2379 * to height=1px, so .scrollHeight measurements can be taken accurately.
2380 *
2381 * @return {number} Height of the window body in pixels
2382 */
2383 OO.ui.Window.prototype.getBodyHeight = function () {
2384 return this.$body[ 0 ].scrollHeight;
2385 };
2386
2387 /**
2388 * Get the directionality of the frame (right-to-left or left-to-right).
2389 *
2390 * @return {string} Directionality: `'ltr'` or `'rtl'`
2391 */
2392 OO.ui.Window.prototype.getDir = function () {
2393 return OO.ui.Element.static.getDir( this.$content ) || 'ltr';
2394 };
2395
2396 /**
2397 * Get the 'setup' process.
2398 *
2399 * The setup process is used to set up a window for use in a particular context,
2400 * based on the `data` argument. This method is called during the opening phase of the window’s
2401 * lifecycle.
2402 *
2403 * Override this method to add additional steps to the ‘setup’ process the parent method provides
2404 * using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next} methods
2405 * of OO.ui.Process.
2406 *
2407 * To add window content that persists between openings, you may wish to use the #initialize method
2408 * instead.
2409 *
2410 * @abstract
2411 * @param {Object} [data] Window opening data
2412 * @return {OO.ui.Process} Setup process
2413 */
2414 OO.ui.Window.prototype.getSetupProcess = function () {
2415 return new OO.ui.Process();
2416 };
2417
2418 /**
2419 * Get the ‘ready’ process.
2420 *
2421 * The ready process is used to ready a window for use in a particular
2422 * context, based on the `data` argument. This method is called during the opening phase of
2423 * the window’s lifecycle, after the window has been {@link #getSetupProcess setup}.
2424 *
2425 * Override this method to add additional steps to the ‘ready’ process the parent method
2426 * provides using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next}
2427 * methods of OO.ui.Process.
2428 *
2429 * @abstract
2430 * @param {Object} [data] Window opening data
2431 * @return {OO.ui.Process} Ready process
2432 */
2433 OO.ui.Window.prototype.getReadyProcess = function () {
2434 return new OO.ui.Process();
2435 };
2436
2437 /**
2438 * Get the 'hold' process.
2439 *
2440 * The hold proccess is used to keep a window from being used in a particular context,
2441 * based on the `data` argument. This method is called during the closing phase of the window’s
2442 * lifecycle.
2443 *
2444 * Override this method to add additional steps to the 'hold' process the parent method provides
2445 * using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next} methods
2446 * of OO.ui.Process.
2447 *
2448 * @abstract
2449 * @param {Object} [data] Window closing data
2450 * @return {OO.ui.Process} Hold process
2451 */
2452 OO.ui.Window.prototype.getHoldProcess = function () {
2453 return new OO.ui.Process();
2454 };
2455
2456 /**
2457 * Get the ‘teardown’ process.
2458 *
2459 * The teardown process is used to teardown a window after use. During teardown,
2460 * user interactions within the window are conveyed and the window is closed, based on the `data`
2461 * argument. This method is called during the closing phase of the window’s lifecycle.
2462 *
2463 * Override this method to add additional steps to the ‘teardown’ process the parent method provides
2464 * using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next} methods
2465 * of OO.ui.Process.
2466 *
2467 * @abstract
2468 * @param {Object} [data] Window closing data
2469 * @return {OO.ui.Process} Teardown process
2470 */
2471 OO.ui.Window.prototype.getTeardownProcess = function () {
2472 return new OO.ui.Process();
2473 };
2474
2475 /**
2476 * Set the window manager.
2477 *
2478 * This will cause the window to initialize. Calling it more than once will cause an error.
2479 *
2480 * @param {OO.ui.WindowManager} manager Manager for this window
2481 * @throws {Error} An error is thrown if the method is called more than once
2482 * @chainable
2483 */
2484 OO.ui.Window.prototype.setManager = function ( manager ) {
2485 if ( this.manager ) {
2486 throw new Error( 'Cannot set window manager, window already has a manager' );
2487 }
2488
2489 this.manager = manager;
2490 this.initialize();
2491
2492 return this;
2493 };
2494
2495 /**
2496 * Set the window size by symbolic name (e.g., 'small' or 'medium')
2497 *
2498 * @param {string} size Symbolic name of size: `small`, `medium`, `large`, `larger` or
2499 * `full`
2500 * @chainable
2501 */
2502 OO.ui.Window.prototype.setSize = function ( size ) {
2503 this.size = size;
2504 this.updateSize();
2505 return this;
2506 };
2507
2508 /**
2509 * Update the window size.
2510 *
2511 * @throws {Error} An error is thrown if the window is not attached to a window manager
2512 * @chainable
2513 */
2514 OO.ui.Window.prototype.updateSize = function () {
2515 if ( !this.manager ) {
2516 throw new Error( 'Cannot update window size, must be attached to a manager' );
2517 }
2518
2519 this.manager.updateWindowSize( this );
2520
2521 return this;
2522 };
2523
2524 /**
2525 * Set window dimensions. This method is called by the {@link OO.ui.WindowManager window manager}
2526 * when the window is opening. In general, setDimensions should not be called directly.
2527 *
2528 * To set the size of the window, use the #setSize method.
2529 *
2530 * @param {Object} dim CSS dimension properties
2531 * @param {string|number} [dim.width] Width
2532 * @param {string|number} [dim.minWidth] Minimum width
2533 * @param {string|number} [dim.maxWidth] Maximum width
2534 * @param {string|number} [dim.width] Height, omit to set based on height of contents
2535 * @param {string|number} [dim.minWidth] Minimum height
2536 * @param {string|number} [dim.maxWidth] Maximum height
2537 * @chainable
2538 */
2539 OO.ui.Window.prototype.setDimensions = function ( dim ) {
2540 var height,
2541 win = this,
2542 styleObj = this.$frame[ 0 ].style;
2543
2544 // Calculate the height we need to set using the correct width
2545 if ( dim.height === undefined ) {
2546 this.withoutSizeTransitions( function () {
2547 var oldWidth = styleObj.width;
2548 win.$frame.css( 'width', dim.width || '' );
2549 height = win.getContentHeight();
2550 styleObj.width = oldWidth;
2551 } );
2552 } else {
2553 height = dim.height;
2554 }
2555
2556 this.$frame.css( {
2557 width: dim.width || '',
2558 minWidth: dim.minWidth || '',
2559 maxWidth: dim.maxWidth || '',
2560 height: height || '',
2561 minHeight: dim.minHeight || '',
2562 maxHeight: dim.maxHeight || ''
2563 } );
2564
2565 return this;
2566 };
2567
2568 /**
2569 * Initialize window contents.
2570 *
2571 * Before the window is opened for the first time, #initialize is called so that content that
2572 * persists between openings can be added to the window.
2573 *
2574 * To set up a window with new content each time the window opens, use #getSetupProcess.
2575 *
2576 * @throws {Error} An error is thrown if the window is not attached to a window manager
2577 * @chainable
2578 */
2579 OO.ui.Window.prototype.initialize = function () {
2580 if ( !this.manager ) {
2581 throw new Error( 'Cannot initialize window, must be attached to a manager' );
2582 }
2583
2584 // Properties
2585 this.$head = $( '<div>' );
2586 this.$body = $( '<div>' );
2587 this.$foot = $( '<div>' );
2588 this.$document = $( this.getElementDocument() );
2589
2590 // Events
2591 this.$element.on( 'mousedown', this.onMouseDown.bind( this ) );
2592
2593 // Initialization
2594 this.$head.addClass( 'oo-ui-window-head' );
2595 this.$body.addClass( 'oo-ui-window-body' );
2596 this.$foot.addClass( 'oo-ui-window-foot' );
2597 this.$content.append( this.$head, this.$body, this.$foot );
2598
2599 return this;
2600 };
2601
2602 /**
2603 * Called when someone tries to focus the hidden element at the end of the dialog.
2604 * Sends focus back to the start of the dialog.
2605 *
2606 * @param {jQuery.Event} event Focus event
2607 */
2608 OO.ui.Window.prototype.onFocusTrapFocused = function ( event ) {
2609 if ( this.$focusTrapBefore.is( event.target ) ) {
2610 OO.ui.findFocusable( this.$content, true ).focus();
2611 } else {
2612 // this.$content is the part of the focus cycle, and is the first focusable element
2613 this.$content.focus();
2614 }
2615 };
2616
2617 /**
2618 * Open the window.
2619 *
2620 * This method is a wrapper around a call to the window manager’s {@link OO.ui.WindowManager#openWindow openWindow}
2621 * method, which returns a promise resolved when the window is done opening.
2622 *
2623 * To customize the window each time it opens, use #getSetupProcess or #getReadyProcess.
2624 *
2625 * @param {Object} [data] Window opening data
2626 * @return {jQuery.Promise} Promise resolved with a value when the window is opened, or rejected
2627 * if the window fails to open. When the promise is resolved successfully, the first argument of the
2628 * value is a new promise, which is resolved when the window begins closing.
2629 * @throws {Error} An error is thrown if the window is not attached to a window manager
2630 */
2631 OO.ui.Window.prototype.open = function ( data ) {
2632 if ( !this.manager ) {
2633 throw new Error( 'Cannot open window, must be attached to a manager' );
2634 }
2635
2636 return this.manager.openWindow( this, data );
2637 };
2638
2639 /**
2640 * Close the window.
2641 *
2642 * This method is a wrapper around a call to the window
2643 * manager’s {@link OO.ui.WindowManager#closeWindow closeWindow} method,
2644 * which returns a closing promise resolved when the window is done closing.
2645 *
2646 * The window's #getHoldProcess and #getTeardownProcess methods are called during the closing
2647 * phase of the window’s lifecycle and can be used to specify closing behavior each time
2648 * the window closes.
2649 *
2650 * @param {Object} [data] Window closing data
2651 * @return {jQuery.Promise} Promise resolved when window is closed
2652 * @throws {Error} An error is thrown if the window is not attached to a window manager
2653 */
2654 OO.ui.Window.prototype.close = function ( data ) {
2655 if ( !this.manager ) {
2656 throw new Error( 'Cannot close window, must be attached to a manager' );
2657 }
2658
2659 return this.manager.closeWindow( this, data );
2660 };
2661
2662 /**
2663 * Setup window.
2664 *
2665 * This is called by OO.ui.WindowManager during window opening, and should not be called directly
2666 * by other systems.
2667 *
2668 * @param {Object} [data] Window opening data
2669 * @return {jQuery.Promise} Promise resolved when window is setup
2670 */
2671 OO.ui.Window.prototype.setup = function ( data ) {
2672 var win = this,
2673 deferred = $.Deferred();
2674
2675 this.toggle( true );
2676
2677 this.focusTrapHandler = OO.ui.bind( this.onFocusTrapFocused, this );
2678 this.$focusTraps.on( 'focus', this.focusTrapHandler );
2679
2680 this.getSetupProcess( data ).execute().done( function () {
2681 // Force redraw by asking the browser to measure the elements' widths
2682 win.$element.addClass( 'oo-ui-window-active oo-ui-window-setup' ).width();
2683 win.$content.addClass( 'oo-ui-window-content-setup' ).width();
2684 deferred.resolve();
2685 } );
2686
2687 return deferred.promise();
2688 };
2689
2690 /**
2691 * Ready window.
2692 *
2693 * This is called by OO.ui.WindowManager during window opening, and should not be called directly
2694 * by other systems.
2695 *
2696 * @param {Object} [data] Window opening data
2697 * @return {jQuery.Promise} Promise resolved when window is ready
2698 */
2699 OO.ui.Window.prototype.ready = function ( data ) {
2700 var win = this,
2701 deferred = $.Deferred();
2702
2703 this.$content.focus();
2704 this.getReadyProcess( data ).execute().done( function () {
2705 // Force redraw by asking the browser to measure the elements' widths
2706 win.$element.addClass( 'oo-ui-window-ready' ).width();
2707 win.$content.addClass( 'oo-ui-window-content-ready' ).width();
2708 deferred.resolve();
2709 } );
2710
2711 return deferred.promise();
2712 };
2713
2714 /**
2715 * Hold window.
2716 *
2717 * This is called by OO.ui.WindowManager during window closing, and should not be called directly
2718 * by other systems.
2719 *
2720 * @param {Object} [data] Window closing data
2721 * @return {jQuery.Promise} Promise resolved when window is held
2722 */
2723 OO.ui.Window.prototype.hold = function ( data ) {
2724 var win = this,
2725 deferred = $.Deferred();
2726
2727 this.getHoldProcess( data ).execute().done( function () {
2728 // Get the focused element within the window's content
2729 var $focus = win.$content.find( OO.ui.Element.static.getDocument( win.$content ).activeElement );
2730
2731 // Blur the focused element
2732 if ( $focus.length ) {
2733 $focus[ 0 ].blur();
2734 }
2735
2736 // Force redraw by asking the browser to measure the elements' widths
2737 win.$element.removeClass( 'oo-ui-window-ready' ).width();
2738 win.$content.removeClass( 'oo-ui-window-content-ready' ).width();
2739 deferred.resolve();
2740 } );
2741
2742 return deferred.promise();
2743 };
2744
2745 /**
2746 * Teardown window.
2747 *
2748 * This is called by OO.ui.WindowManager during window closing, and should not be called directly
2749 * by other systems.
2750 *
2751 * @param {Object} [data] Window closing data
2752 * @return {jQuery.Promise} Promise resolved when window is torn down
2753 */
2754 OO.ui.Window.prototype.teardown = function ( data ) {
2755 var win = this;
2756
2757 return this.getTeardownProcess( data ).execute()
2758 .done( function () {
2759 // Force redraw by asking the browser to measure the elements' widths
2760 win.$element.removeClass( 'oo-ui-window-active oo-ui-window-setup' ).width();
2761 win.$content.removeClass( 'oo-ui-window-content-setup' ).width();
2762 win.$focusTraps.off( 'focus', win.focusTrapHandler );
2763 win.toggle( false );
2764 } );
2765 };
2766
2767 /**
2768 * The Dialog class serves as the base class for the other types of dialogs.
2769 * Unless extended to include controls, the rendered dialog box is a simple window
2770 * that users can close by hitting the ‘Esc’ key. Dialog windows are used with OO.ui.WindowManager,
2771 * which opens, closes, and controls the presentation of the window. See the
2772 * [OOjs UI documentation on MediaWiki] [1] for more information.
2773 *
2774 * @example
2775 * // A simple dialog window.
2776 * function MyDialog( config ) {
2777 * MyDialog.parent.call( this, config );
2778 * }
2779 * OO.inheritClass( MyDialog, OO.ui.Dialog );
2780 * MyDialog.prototype.initialize = function () {
2781 * MyDialog.parent.prototype.initialize.call( this );
2782 * this.content = new OO.ui.PanelLayout( { padded: true, expanded: false } );
2783 * this.content.$element.append( '<p>A simple dialog window. Press \'Esc\' to close.</p>' );
2784 * this.$body.append( this.content.$element );
2785 * };
2786 * MyDialog.prototype.getBodyHeight = function () {
2787 * return this.content.$element.outerHeight( true );
2788 * };
2789 * var myDialog = new MyDialog( {
2790 * size: 'medium'
2791 * } );
2792 * // Create and append a window manager, which opens and closes the window.
2793 * var windowManager = new OO.ui.WindowManager();
2794 * $( 'body' ).append( windowManager.$element );
2795 * windowManager.addWindows( [ myDialog ] );
2796 * // Open the window!
2797 * windowManager.openWindow( myDialog );
2798 *
2799 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Dialogs
2800 *
2801 * @abstract
2802 * @class
2803 * @extends OO.ui.Window
2804 * @mixins OO.ui.mixin.PendingElement
2805 *
2806 * @constructor
2807 * @param {Object} [config] Configuration options
2808 */
2809 OO.ui.Dialog = function OoUiDialog( config ) {
2810 // Parent constructor
2811 OO.ui.Dialog.parent.call( this, config );
2812
2813 // Mixin constructors
2814 OO.ui.mixin.PendingElement.call( this );
2815
2816 // Properties
2817 this.actions = new OO.ui.ActionSet();
2818 this.attachedActions = [];
2819 this.currentAction = null;
2820 this.onDialogKeyDownHandler = this.onDialogKeyDown.bind( this );
2821
2822 // Events
2823 this.actions.connect( this, {
2824 click: 'onActionClick',
2825 resize: 'onActionResize',
2826 change: 'onActionsChange'
2827 } );
2828
2829 // Initialization
2830 this.$element
2831 .addClass( 'oo-ui-dialog' )
2832 .attr( 'role', 'dialog' );
2833 };
2834
2835 /* Setup */
2836
2837 OO.inheritClass( OO.ui.Dialog, OO.ui.Window );
2838 OO.mixinClass( OO.ui.Dialog, OO.ui.mixin.PendingElement );
2839
2840 /* Static Properties */
2841
2842 /**
2843 * Symbolic name of dialog.
2844 *
2845 * The dialog class must have a symbolic name in order to be registered with OO.Factory.
2846 * Please see the [OOjs UI documentation on MediaWiki] [3] for more information.
2847 *
2848 * [3]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
2849 *
2850 * @abstract
2851 * @static
2852 * @inheritable
2853 * @property {string}
2854 */
2855 OO.ui.Dialog.static.name = '';
2856
2857 /**
2858 * The dialog title.
2859 *
2860 * The title can be specified as a plaintext string, a {@link OO.ui.mixin.LabelElement Label} node, or a function
2861 * that will produce a Label node or string. The title can also be specified with data passed to the
2862 * constructor (see #getSetupProcess). In this case, the static value will be overriden.
2863 *
2864 * @abstract
2865 * @static
2866 * @inheritable
2867 * @property {jQuery|string|Function}
2868 */
2869 OO.ui.Dialog.static.title = '';
2870
2871 /**
2872 * An array of configured {@link OO.ui.ActionWidget action widgets}.
2873 *
2874 * Actions can also be specified with data passed to the constructor (see #getSetupProcess). In this case, the static
2875 * value will be overriden.
2876 *
2877 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Action_sets
2878 *
2879 * @static
2880 * @inheritable
2881 * @property {Object[]}
2882 */
2883 OO.ui.Dialog.static.actions = [];
2884
2885 /**
2886 * Close the dialog when the 'Esc' key is pressed.
2887 *
2888 * @static
2889 * @abstract
2890 * @inheritable
2891 * @property {boolean}
2892 */
2893 OO.ui.Dialog.static.escapable = true;
2894
2895 /* Methods */
2896
2897 /**
2898 * Handle frame document key down events.
2899 *
2900 * @private
2901 * @param {jQuery.Event} e Key down event
2902 */
2903 OO.ui.Dialog.prototype.onDialogKeyDown = function ( e ) {
2904 if ( e.which === OO.ui.Keys.ESCAPE ) {
2905 this.close();
2906 e.preventDefault();
2907 e.stopPropagation();
2908 }
2909 };
2910
2911 /**
2912 * Handle action resized events.
2913 *
2914 * @private
2915 * @param {OO.ui.ActionWidget} action Action that was resized
2916 */
2917 OO.ui.Dialog.prototype.onActionResize = function () {
2918 // Override in subclass
2919 };
2920
2921 /**
2922 * Handle action click events.
2923 *
2924 * @private
2925 * @param {OO.ui.ActionWidget} action Action that was clicked
2926 */
2927 OO.ui.Dialog.prototype.onActionClick = function ( action ) {
2928 if ( !this.isPending() ) {
2929 this.executeAction( action.getAction() );
2930 }
2931 };
2932
2933 /**
2934 * Handle actions change event.
2935 *
2936 * @private
2937 */
2938 OO.ui.Dialog.prototype.onActionsChange = function () {
2939 this.detachActions();
2940 if ( !this.isClosing() ) {
2941 this.attachActions();
2942 }
2943 };
2944
2945 /**
2946 * Get the set of actions used by the dialog.
2947 *
2948 * @return {OO.ui.ActionSet}
2949 */
2950 OO.ui.Dialog.prototype.getActions = function () {
2951 return this.actions;
2952 };
2953
2954 /**
2955 * Get a process for taking action.
2956 *
2957 * When you override this method, you can create a new OO.ui.Process and return it, or add additional
2958 * accept steps to the process the parent method provides using the {@link OO.ui.Process#first 'first'}
2959 * and {@link OO.ui.Process#next 'next'} methods of OO.ui.Process.
2960 *
2961 * @abstract
2962 * @param {string} [action] Symbolic name of action
2963 * @return {OO.ui.Process} Action process
2964 */
2965 OO.ui.Dialog.prototype.getActionProcess = function ( action ) {
2966 return new OO.ui.Process()
2967 .next( function () {
2968 if ( !action ) {
2969 // An empty action always closes the dialog without data, which should always be
2970 // safe and make no changes
2971 this.close();
2972 }
2973 }, this );
2974 };
2975
2976 /**
2977 * @inheritdoc
2978 *
2979 * @param {Object} [data] Dialog opening data
2980 * @param {jQuery|string|Function|null} [data.title] Dialog title, omit to use
2981 * the {@link #static-title static title}
2982 * @param {Object[]} [data.actions] List of configuration options for each
2983 * {@link OO.ui.ActionWidget action widget}, omit to use {@link #static-actions static actions}.
2984 */
2985 OO.ui.Dialog.prototype.getSetupProcess = function ( data ) {
2986 data = data || {};
2987
2988 // Parent method
2989 return OO.ui.Dialog.parent.prototype.getSetupProcess.call( this, data )
2990 .next( function () {
2991 var config = this.constructor.static,
2992 actions = data.actions !== undefined ? data.actions : config.actions;
2993
2994 this.title.setLabel(
2995 data.title !== undefined ? data.title : this.constructor.static.title
2996 );
2997 this.actions.add( this.getActionWidgets( actions ) );
2998
2999 if ( this.constructor.static.escapable ) {
3000 this.$element.on( 'keydown', this.onDialogKeyDownHandler );
3001 }
3002 }, this );
3003 };
3004
3005 /**
3006 * @inheritdoc
3007 */
3008 OO.ui.Dialog.prototype.getTeardownProcess = function ( data ) {
3009 // Parent method
3010 return OO.ui.Dialog.parent.prototype.getTeardownProcess.call( this, data )
3011 .first( function () {
3012 if ( this.constructor.static.escapable ) {
3013 this.$element.off( 'keydown', this.onDialogKeyDownHandler );
3014 }
3015
3016 this.actions.clear();
3017 this.currentAction = null;
3018 }, this );
3019 };
3020
3021 /**
3022 * @inheritdoc
3023 */
3024 OO.ui.Dialog.prototype.initialize = function () {
3025 var titleId;
3026
3027 // Parent method
3028 OO.ui.Dialog.parent.prototype.initialize.call( this );
3029
3030 titleId = OO.ui.generateElementId();
3031
3032 // Properties
3033 this.title = new OO.ui.LabelWidget( {
3034 id: titleId
3035 } );
3036
3037 // Initialization
3038 this.$content.addClass( 'oo-ui-dialog-content' );
3039 this.$element.attr( 'aria-labelledby', titleId );
3040 this.setPendingElement( this.$head );
3041 };
3042
3043 /**
3044 * Get action widgets from a list of configs
3045 *
3046 * @param {Object[]} actions Action widget configs
3047 * @return {OO.ui.ActionWidget[]} Action widgets
3048 */
3049 OO.ui.Dialog.prototype.getActionWidgets = function ( actions ) {
3050 var i, len, widgets = [];
3051 for ( i = 0, len = actions.length; i < len; i++ ) {
3052 widgets.push(
3053 new OO.ui.ActionWidget( actions[ i ] )
3054 );
3055 }
3056 return widgets;
3057 };
3058
3059 /**
3060 * Attach action actions.
3061 *
3062 * @protected
3063 */
3064 OO.ui.Dialog.prototype.attachActions = function () {
3065 // Remember the list of potentially attached actions
3066 this.attachedActions = this.actions.get();
3067 };
3068
3069 /**
3070 * Detach action actions.
3071 *
3072 * @protected
3073 * @chainable
3074 */
3075 OO.ui.Dialog.prototype.detachActions = function () {
3076 var i, len;
3077
3078 // Detach all actions that may have been previously attached
3079 for ( i = 0, len = this.attachedActions.length; i < len; i++ ) {
3080 this.attachedActions[ i ].$element.detach();
3081 }
3082 this.attachedActions = [];
3083 };
3084
3085 /**
3086 * Execute an action.
3087 *
3088 * @param {string} action Symbolic name of action to execute
3089 * @return {jQuery.Promise} Promise resolved when action completes, rejected if it fails
3090 */
3091 OO.ui.Dialog.prototype.executeAction = function ( action ) {
3092 this.pushPending();
3093 this.currentAction = action;
3094 return this.getActionProcess( action ).execute()
3095 .always( this.popPending.bind( this ) );
3096 };
3097
3098 /**
3099 * Window managers are used to open and close {@link OO.ui.Window windows} and control their presentation.
3100 * Managed windows are mutually exclusive. If a new window is opened while a current window is opening
3101 * or is opened, the current window will be closed and any ongoing {@link OO.ui.Process process} will be cancelled. Windows
3102 * themselves are persistent and—rather than being torn down when closed—can be repopulated with the
3103 * pertinent data and reused.
3104 *
3105 * Over the lifecycle of a window, the window manager makes available three promises: `opening`,
3106 * `opened`, and `closing`, which represent the primary stages of the cycle:
3107 *
3108 * **Opening**: the opening stage begins when the window manager’s #openWindow or a window’s
3109 * {@link OO.ui.Window#open open} method is used, and the window manager begins to open the window.
3110 *
3111 * - an `opening` event is emitted with an `opening` promise
3112 * - the #getSetupDelay method is called and the returned value is used to time a pause in execution before
3113 * the window’s {@link OO.ui.Window#getSetupProcess getSetupProcess} method is called on the
3114 * window and its result executed
3115 * - a `setup` progress notification is emitted from the `opening` promise
3116 * - the #getReadyDelay method is called the returned value is used to time a pause in execution before
3117 * the window’s {@link OO.ui.Window#getReadyProcess getReadyProcess} method is called on the
3118 * window and its result executed
3119 * - a `ready` progress notification is emitted from the `opening` promise
3120 * - the `opening` promise is resolved with an `opened` promise
3121 *
3122 * **Opened**: the window is now open.
3123 *
3124 * **Closing**: the closing stage begins when the window manager's #closeWindow or the
3125 * window's {@link OO.ui.Window#close close} methods is used, and the window manager begins
3126 * to close the window.
3127 *
3128 * - the `opened` promise is resolved with `closing` promise and a `closing` event is emitted
3129 * - the #getHoldDelay method is called and the returned value is used to time a pause in execution before
3130 * the window's {@link OO.ui.Window#getHoldProcess getHoldProces} method is called on the
3131 * window and its result executed
3132 * - a `hold` progress notification is emitted from the `closing` promise
3133 * - the #getTeardownDelay() method is called and the returned value is used to time a pause in execution before
3134 * the window's {@link OO.ui.Window#getTeardownProcess getTeardownProcess} method is called on the
3135 * window and its result executed
3136 * - a `teardown` progress notification is emitted from the `closing` promise
3137 * - the `closing` promise is resolved. The window is now closed
3138 *
3139 * See the [OOjs UI documentation on MediaWiki][1] for more information.
3140 *
3141 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
3142 *
3143 * @class
3144 * @extends OO.ui.Element
3145 * @mixins OO.EventEmitter
3146 *
3147 * @constructor
3148 * @param {Object} [config] Configuration options
3149 * @cfg {OO.Factory} [factory] Window factory to use for automatic instantiation
3150 * Note that window classes that are instantiated with a factory must have
3151 * a {@link OO.ui.Dialog#static-name static name} property that specifies a symbolic name.
3152 * @cfg {boolean} [modal=true] Prevent interaction outside the dialog
3153 */
3154 OO.ui.WindowManager = function OoUiWindowManager( config ) {
3155 // Configuration initialization
3156 config = config || {};
3157
3158 // Parent constructor
3159 OO.ui.WindowManager.parent.call( this, config );
3160
3161 // Mixin constructors
3162 OO.EventEmitter.call( this );
3163
3164 // Properties
3165 this.factory = config.factory;
3166 this.modal = config.modal === undefined || !!config.modal;
3167 this.windows = {};
3168 this.opening = null;
3169 this.opened = null;
3170 this.closing = null;
3171 this.preparingToOpen = null;
3172 this.preparingToClose = null;
3173 this.currentWindow = null;
3174 this.globalEvents = false;
3175 this.$ariaHidden = null;
3176 this.onWindowResizeTimeout = null;
3177 this.onWindowResizeHandler = this.onWindowResize.bind( this );
3178 this.afterWindowResizeHandler = this.afterWindowResize.bind( this );
3179
3180 // Initialization
3181 this.$element
3182 .addClass( 'oo-ui-windowManager' )
3183 .toggleClass( 'oo-ui-windowManager-modal', this.modal );
3184 };
3185
3186 /* Setup */
3187
3188 OO.inheritClass( OO.ui.WindowManager, OO.ui.Element );
3189 OO.mixinClass( OO.ui.WindowManager, OO.EventEmitter );
3190
3191 /* Events */
3192
3193 /**
3194 * An 'opening' event is emitted when the window begins to be opened.
3195 *
3196 * @event opening
3197 * @param {OO.ui.Window} win Window that's being opened
3198 * @param {jQuery.Promise} opening An `opening` promise resolved with a value when the window is opened successfully.
3199 * When the `opening` promise is resolved, the first argument of the value is an 'opened' promise, the second argument
3200 * is the opening data. The `opening` promise emits `setup` and `ready` notifications when those processes are complete.
3201 * @param {Object} data Window opening data
3202 */
3203
3204 /**
3205 * A 'closing' event is emitted when the window begins to be closed.
3206 *
3207 * @event closing
3208 * @param {OO.ui.Window} win Window that's being closed
3209 * @param {jQuery.Promise} closing A `closing` promise is resolved with a value when the window
3210 * is closed successfully. The promise emits `hold` and `teardown` notifications when those
3211 * processes are complete. When the `closing` promise is resolved, the first argument of its value
3212 * is the closing data.
3213 * @param {Object} data Window closing data
3214 */
3215
3216 /**
3217 * A 'resize' event is emitted when a window is resized.
3218 *
3219 * @event resize
3220 * @param {OO.ui.Window} win Window that was resized
3221 */
3222
3223 /* Static Properties */
3224
3225 /**
3226 * Map of the symbolic name of each window size and its CSS properties.
3227 *
3228 * @static
3229 * @inheritable
3230 * @property {Object}
3231 */
3232 OO.ui.WindowManager.static.sizes = {
3233 small: {
3234 width: 300
3235 },
3236 medium: {
3237 width: 500
3238 },
3239 large: {
3240 width: 700
3241 },
3242 larger: {
3243 width: 900
3244 },
3245 full: {
3246 // These can be non-numeric because they are never used in calculations
3247 width: '100%',
3248 height: '100%'
3249 }
3250 };
3251
3252 /**
3253 * Symbolic name of the default window size.
3254 *
3255 * The default size is used if the window's requested size is not recognized.
3256 *
3257 * @static
3258 * @inheritable
3259 * @property {string}
3260 */
3261 OO.ui.WindowManager.static.defaultSize = 'medium';
3262
3263 /* Methods */
3264
3265 /**
3266 * Handle window resize events.
3267 *
3268 * @private
3269 * @param {jQuery.Event} e Window resize event
3270 */
3271 OO.ui.WindowManager.prototype.onWindowResize = function () {
3272 clearTimeout( this.onWindowResizeTimeout );
3273 this.onWindowResizeTimeout = setTimeout( this.afterWindowResizeHandler, 200 );
3274 };
3275
3276 /**
3277 * Handle window resize events.
3278 *
3279 * @private
3280 * @param {jQuery.Event} e Window resize event
3281 */
3282 OO.ui.WindowManager.prototype.afterWindowResize = function () {
3283 if ( this.currentWindow ) {
3284 this.updateWindowSize( this.currentWindow );
3285 }
3286 };
3287
3288 /**
3289 * Check if window is opening.
3290 *
3291 * @return {boolean} Window is opening
3292 */
3293 OO.ui.WindowManager.prototype.isOpening = function ( win ) {
3294 return win === this.currentWindow && !!this.opening && this.opening.state() === 'pending';
3295 };
3296
3297 /**
3298 * Check if window is closing.
3299 *
3300 * @return {boolean} Window is closing
3301 */
3302 OO.ui.WindowManager.prototype.isClosing = function ( win ) {
3303 return win === this.currentWindow && !!this.closing && this.closing.state() === 'pending';
3304 };
3305
3306 /**
3307 * Check if window is opened.
3308 *
3309 * @return {boolean} Window is opened
3310 */
3311 OO.ui.WindowManager.prototype.isOpened = function ( win ) {
3312 return win === this.currentWindow && !!this.opened && this.opened.state() === 'pending';
3313 };
3314
3315 /**
3316 * Check if a window is being managed.
3317 *
3318 * @param {OO.ui.Window} win Window to check
3319 * @return {boolean} Window is being managed
3320 */
3321 OO.ui.WindowManager.prototype.hasWindow = function ( win ) {
3322 var name;
3323
3324 for ( name in this.windows ) {
3325 if ( this.windows[ name ] === win ) {
3326 return true;
3327 }
3328 }
3329
3330 return false;
3331 };
3332
3333 /**
3334 * Get the number of milliseconds to wait after opening begins before executing the ‘setup’ process.
3335 *
3336 * @param {OO.ui.Window} win Window being opened
3337 * @param {Object} [data] Window opening data
3338 * @return {number} Milliseconds to wait
3339 */
3340 OO.ui.WindowManager.prototype.getSetupDelay = function () {
3341 return 0;
3342 };
3343
3344 /**
3345 * Get the number of milliseconds to wait after setup has finished before executing the ‘ready’ process.
3346 *
3347 * @param {OO.ui.Window} win Window being opened
3348 * @param {Object} [data] Window opening data
3349 * @return {number} Milliseconds to wait
3350 */
3351 OO.ui.WindowManager.prototype.getReadyDelay = function () {
3352 return 0;
3353 };
3354
3355 /**
3356 * Get the number of milliseconds to wait after closing has begun before executing the 'hold' process.
3357 *
3358 * @param {OO.ui.Window} win Window being closed
3359 * @param {Object} [data] Window closing data
3360 * @return {number} Milliseconds to wait
3361 */
3362 OO.ui.WindowManager.prototype.getHoldDelay = function () {
3363 return 0;
3364 };
3365
3366 /**
3367 * Get the number of milliseconds to wait after the ‘hold’ process has finished before
3368 * executing the ‘teardown’ process.
3369 *
3370 * @param {OO.ui.Window} win Window being closed
3371 * @param {Object} [data] Window closing data
3372 * @return {number} Milliseconds to wait
3373 */
3374 OO.ui.WindowManager.prototype.getTeardownDelay = function () {
3375 return this.modal ? 250 : 0;
3376 };
3377
3378 /**
3379 * Get a window by its symbolic name.
3380 *
3381 * If the window is not yet instantiated and its symbolic name is recognized by a factory, it will be
3382 * instantiated and added to the window manager automatically. Please see the [OOjs UI documentation on MediaWiki][3]
3383 * for more information about using factories.
3384 * [3]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
3385 *
3386 * @param {string} name Symbolic name of the window
3387 * @return {jQuery.Promise} Promise resolved with matching window, or rejected with an OO.ui.Error
3388 * @throws {Error} An error is thrown if the symbolic name is not recognized by the factory.
3389 * @throws {Error} An error is thrown if the named window is not recognized as a managed window.
3390 */
3391 OO.ui.WindowManager.prototype.getWindow = function ( name ) {
3392 var deferred = $.Deferred(),
3393 win = this.windows[ name ];
3394
3395 if ( !( win instanceof OO.ui.Window ) ) {
3396 if ( this.factory ) {
3397 if ( !this.factory.lookup( name ) ) {
3398 deferred.reject( new OO.ui.Error(
3399 'Cannot auto-instantiate window: symbolic name is unrecognized by the factory'
3400 ) );
3401 } else {
3402 win = this.factory.create( name );
3403 this.addWindows( [ win ] );
3404 deferred.resolve( win );
3405 }
3406 } else {
3407 deferred.reject( new OO.ui.Error(
3408 'Cannot get unmanaged window: symbolic name unrecognized as a managed window'
3409 ) );
3410 }
3411 } else {
3412 deferred.resolve( win );
3413 }
3414
3415 return deferred.promise();
3416 };
3417
3418 /**
3419 * Get current window.
3420 *
3421 * @return {OO.ui.Window|null} Currently opening/opened/closing window
3422 */
3423 OO.ui.WindowManager.prototype.getCurrentWindow = function () {
3424 return this.currentWindow;
3425 };
3426
3427 /**
3428 * Open a window.
3429 *
3430 * @param {OO.ui.Window|string} win Window object or symbolic name of window to open
3431 * @param {Object} [data] Window opening data
3432 * @return {jQuery.Promise} An `opening` promise resolved when the window is done opening.
3433 * See {@link #event-opening 'opening' event} for more information about `opening` promises.
3434 * @fires opening
3435 */
3436 OO.ui.WindowManager.prototype.openWindow = function ( win, data ) {
3437 var manager = this,
3438 opening = $.Deferred();
3439
3440 // Argument handling
3441 if ( typeof win === 'string' ) {
3442 return this.getWindow( win ).then( function ( win ) {
3443 return manager.openWindow( win, data );
3444 } );
3445 }
3446
3447 // Error handling
3448 if ( !this.hasWindow( win ) ) {
3449 opening.reject( new OO.ui.Error(
3450 'Cannot open window: window is not attached to manager'
3451 ) );
3452 } else if ( this.preparingToOpen || this.opening || this.opened ) {
3453 opening.reject( new OO.ui.Error(
3454 'Cannot open window: another window is opening or open'
3455 ) );
3456 }
3457
3458 // Window opening
3459 if ( opening.state() !== 'rejected' ) {
3460 // If a window is currently closing, wait for it to complete
3461 this.preparingToOpen = $.when( this.closing );
3462 // Ensure handlers get called after preparingToOpen is set
3463 this.preparingToOpen.done( function () {
3464 if ( manager.modal ) {
3465 manager.toggleGlobalEvents( true );
3466 manager.toggleAriaIsolation( true );
3467 }
3468 manager.currentWindow = win;
3469 manager.opening = opening;
3470 manager.preparingToOpen = null;
3471 manager.emit( 'opening', win, opening, data );
3472 setTimeout( function () {
3473 win.setup( data ).then( function () {
3474 manager.updateWindowSize( win );
3475 manager.opening.notify( { state: 'setup' } );
3476 setTimeout( function () {
3477 win.ready( data ).then( function () {
3478 manager.opening.notify( { state: 'ready' } );
3479 manager.opening = null;
3480 manager.opened = $.Deferred();
3481 opening.resolve( manager.opened.promise(), data );
3482 } );
3483 }, manager.getReadyDelay() );
3484 } );
3485 }, manager.getSetupDelay() );
3486 } );
3487 }
3488
3489 return opening.promise();
3490 };
3491
3492 /**
3493 * Close a window.
3494 *
3495 * @param {OO.ui.Window|string} win Window object or symbolic name of window to close
3496 * @param {Object} [data] Window closing data
3497 * @return {jQuery.Promise} A `closing` promise resolved when the window is done closing.
3498 * See {@link #event-closing 'closing' event} for more information about closing promises.
3499 * @throws {Error} An error is thrown if the window is not managed by the window manager.
3500 * @fires closing
3501 */
3502 OO.ui.WindowManager.prototype.closeWindow = function ( win, data ) {
3503 var manager = this,
3504 closing = $.Deferred(),
3505 opened;
3506
3507 // Argument handling
3508 if ( typeof win === 'string' ) {
3509 win = this.windows[ win ];
3510 } else if ( !this.hasWindow( win ) ) {
3511 win = null;
3512 }
3513
3514 // Error handling
3515 if ( !win ) {
3516 closing.reject( new OO.ui.Error(
3517 'Cannot close window: window is not attached to manager'
3518 ) );
3519 } else if ( win !== this.currentWindow ) {
3520 closing.reject( new OO.ui.Error(
3521 'Cannot close window: window already closed with different data'
3522 ) );
3523 } else if ( this.preparingToClose || this.closing ) {
3524 closing.reject( new OO.ui.Error(
3525 'Cannot close window: window already closing with different data'
3526 ) );
3527 }
3528
3529 // Window closing
3530 if ( closing.state() !== 'rejected' ) {
3531 // If the window is currently opening, close it when it's done
3532 this.preparingToClose = $.when( this.opening );
3533 // Ensure handlers get called after preparingToClose is set
3534 this.preparingToClose.done( function () {
3535 manager.closing = closing;
3536 manager.preparingToClose = null;
3537 manager.emit( 'closing', win, closing, data );
3538 opened = manager.opened;
3539 manager.opened = null;
3540 opened.resolve( closing.promise(), data );
3541 setTimeout( function () {
3542 win.hold( data ).then( function () {
3543 closing.notify( { state: 'hold' } );
3544 setTimeout( function () {
3545 win.teardown( data ).then( function () {
3546 closing.notify( { state: 'teardown' } );
3547 if ( manager.modal ) {
3548 manager.toggleGlobalEvents( false );
3549 manager.toggleAriaIsolation( false );
3550 }
3551 manager.closing = null;
3552 manager.currentWindow = null;
3553 closing.resolve( data );
3554 } );
3555 }, manager.getTeardownDelay() );
3556 } );
3557 }, manager.getHoldDelay() );
3558 } );
3559 }
3560
3561 return closing.promise();
3562 };
3563
3564 /**
3565 * Add windows to the window manager.
3566 *
3567 * Windows can be added by reference, symbolic name, or explicitly defined symbolic names.
3568 * See the [OOjs ui documentation on MediaWiki] [2] for examples.
3569 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
3570 *
3571 * @param {Object.<string,OO.ui.Window>|OO.ui.Window[]} windows An array of window objects specified
3572 * by reference, symbolic name, or explicitly defined symbolic names.
3573 * @throws {Error} An error is thrown if a window is added by symbolic name, but has neither an
3574 * explicit nor a statically configured symbolic name.
3575 */
3576 OO.ui.WindowManager.prototype.addWindows = function ( windows ) {
3577 var i, len, win, name, list;
3578
3579 if ( Array.isArray( windows ) ) {
3580 // Convert to map of windows by looking up symbolic names from static configuration
3581 list = {};
3582 for ( i = 0, len = windows.length; i < len; i++ ) {
3583 name = windows[ i ].constructor.static.name;
3584 if ( typeof name !== 'string' ) {
3585 throw new Error( 'Cannot add window' );
3586 }
3587 list[ name ] = windows[ i ];
3588 }
3589 } else if ( OO.isPlainObject( windows ) ) {
3590 list = windows;
3591 }
3592
3593 // Add windows
3594 for ( name in list ) {
3595 win = list[ name ];
3596 this.windows[ name ] = win.toggle( false );
3597 this.$element.append( win.$element );
3598 win.setManager( this );
3599 }
3600 };
3601
3602 /**
3603 * Remove the specified windows from the windows manager.
3604 *
3605 * Windows will be closed before they are removed. If you wish to remove all windows, you may wish to use
3606 * the #clearWindows method instead. If you no longer need the window manager and want to ensure that it no
3607 * longer listens to events, use the #destroy method.
3608 *
3609 * @param {string[]} names Symbolic names of windows to remove
3610 * @return {jQuery.Promise} Promise resolved when window is closed and removed
3611 * @throws {Error} An error is thrown if the named windows are not managed by the window manager.
3612 */
3613 OO.ui.WindowManager.prototype.removeWindows = function ( names ) {
3614 var i, len, win, name, cleanupWindow,
3615 manager = this,
3616 promises = [],
3617 cleanup = function ( name, win ) {
3618 delete manager.windows[ name ];
3619 win.$element.detach();
3620 };
3621
3622 for ( i = 0, len = names.length; i < len; i++ ) {
3623 name = names[ i ];
3624 win = this.windows[ name ];
3625 if ( !win ) {
3626 throw new Error( 'Cannot remove window' );
3627 }
3628 cleanupWindow = cleanup.bind( null, name, win );
3629 promises.push( this.closeWindow( name ).then( cleanupWindow, cleanupWindow ) );
3630 }
3631
3632 return $.when.apply( $, promises );
3633 };
3634
3635 /**
3636 * Remove all windows from the window manager.
3637 *
3638 * Windows will be closed before they are removed. Note that the window manager, though not in use, will still
3639 * listen to events. If the window manager will not be used again, you may wish to use the #destroy method instead.
3640 * To remove just a subset of windows, use the #removeWindows method.
3641 *
3642 * @return {jQuery.Promise} Promise resolved when all windows are closed and removed
3643 */
3644 OO.ui.WindowManager.prototype.clearWindows = function () {
3645 return this.removeWindows( Object.keys( this.windows ) );
3646 };
3647
3648 /**
3649 * Set dialog size. In general, this method should not be called directly.
3650 *
3651 * Fullscreen mode will be used if the dialog is too wide to fit in the screen.
3652 *
3653 * @chainable
3654 */
3655 OO.ui.WindowManager.prototype.updateWindowSize = function ( win ) {
3656 var isFullscreen;
3657
3658 // Bypass for non-current, and thus invisible, windows
3659 if ( win !== this.currentWindow ) {
3660 return;
3661 }
3662
3663 isFullscreen = win.getSize() === 'full';
3664
3665 this.$element.toggleClass( 'oo-ui-windowManager-fullscreen', isFullscreen );
3666 this.$element.toggleClass( 'oo-ui-windowManager-floating', !isFullscreen );
3667 win.setDimensions( win.getSizeProperties() );
3668
3669 this.emit( 'resize', win );
3670
3671 return this;
3672 };
3673
3674 /**
3675 * Bind or unbind global events for scrolling.
3676 *
3677 * @private
3678 * @param {boolean} [on] Bind global events
3679 * @chainable
3680 */
3681 OO.ui.WindowManager.prototype.toggleGlobalEvents = function ( on ) {
3682 var scrollWidth, bodyMargin,
3683 $body = $( this.getElementDocument().body ),
3684 // We could have multiple window managers open so only modify
3685 // the body css at the bottom of the stack
3686 stackDepth = $body.data( 'windowManagerGlobalEvents' ) || 0 ;
3687
3688 on = on === undefined ? !!this.globalEvents : !!on;
3689
3690 if ( on ) {
3691 if ( !this.globalEvents ) {
3692 $( this.getElementWindow() ).on( {
3693 // Start listening for top-level window dimension changes
3694 'orientationchange resize': this.onWindowResizeHandler
3695 } );
3696 if ( stackDepth === 0 ) {
3697 scrollWidth = window.innerWidth - document.documentElement.clientWidth;
3698 bodyMargin = parseFloat( $body.css( 'margin-right' ) ) || 0;
3699 $body.css( {
3700 overflow: 'hidden',
3701 'margin-right': bodyMargin + scrollWidth
3702 } );
3703 }
3704 stackDepth++;
3705 this.globalEvents = true;
3706 }
3707 } else if ( this.globalEvents ) {
3708 $( this.getElementWindow() ).off( {
3709 // Stop listening for top-level window dimension changes
3710 'orientationchange resize': this.onWindowResizeHandler
3711 } );
3712 stackDepth--;
3713 if ( stackDepth === 0 ) {
3714 $body.css( {
3715 overflow: '',
3716 'margin-right': ''
3717 } );
3718 }
3719 this.globalEvents = false;
3720 }
3721 $body.data( 'windowManagerGlobalEvents', stackDepth );
3722
3723 return this;
3724 };
3725
3726 /**
3727 * Toggle screen reader visibility of content other than the window manager.
3728 *
3729 * @private
3730 * @param {boolean} [isolate] Make only the window manager visible to screen readers
3731 * @chainable
3732 */
3733 OO.ui.WindowManager.prototype.toggleAriaIsolation = function ( isolate ) {
3734 isolate = isolate === undefined ? !this.$ariaHidden : !!isolate;
3735
3736 if ( isolate ) {
3737 if ( !this.$ariaHidden ) {
3738 // Hide everything other than the window manager from screen readers
3739 this.$ariaHidden = $( 'body' )
3740 .children()
3741 .not( this.$element.parentsUntil( 'body' ).last() )
3742 .attr( 'aria-hidden', '' );
3743 }
3744 } else if ( this.$ariaHidden ) {
3745 // Restore screen reader visibility
3746 this.$ariaHidden.removeAttr( 'aria-hidden' );
3747 this.$ariaHidden = null;
3748 }
3749
3750 return this;
3751 };
3752
3753 /**
3754 * Destroy the window manager.
3755 *
3756 * Destroying the window manager ensures that it will no longer listen to events. If you would like to
3757 * continue using the window manager, but wish to remove all windows from it, use the #clearWindows method
3758 * instead.
3759 */
3760 OO.ui.WindowManager.prototype.destroy = function () {
3761 this.toggleGlobalEvents( false );
3762 this.toggleAriaIsolation( false );
3763 this.clearWindows();
3764 this.$element.remove();
3765 };
3766
3767 /**
3768 * Errors contain a required message (either a string or jQuery selection) that is used to describe what went wrong
3769 * in a {@link OO.ui.Process process}. The error's #recoverable and #warning configurations are used to customize the
3770 * appearance and functionality of the error interface.
3771 *
3772 * The basic error interface contains a formatted error message as well as two buttons: 'Dismiss' and 'Try again' (i.e., the error
3773 * is 'recoverable' by default). If the error is not recoverable, the 'Try again' button will not be rendered and the widget
3774 * that initiated the failed process will be disabled.
3775 *
3776 * If the error is a warning, the error interface will include a 'Dismiss' and a 'Continue' button, which will try the
3777 * process again.
3778 *
3779 * For an example of error interfaces, please see the [OOjs UI documentation on MediaWiki][1].
3780 *
3781 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Processes_and_errors
3782 *
3783 * @class
3784 *
3785 * @constructor
3786 * @param {string|jQuery} message Description of error
3787 * @param {Object} [config] Configuration options
3788 * @cfg {boolean} [recoverable=true] Error is recoverable.
3789 * By default, errors are recoverable, and users can try the process again.
3790 * @cfg {boolean} [warning=false] Error is a warning.
3791 * If the error is a warning, the error interface will include a
3792 * 'Dismiss' and a 'Continue' button. It is the responsibility of the developer to ensure that the warning
3793 * is not triggered a second time if the user chooses to continue.
3794 */
3795 OO.ui.Error = function OoUiError( message, config ) {
3796 // Allow passing positional parameters inside the config object
3797 if ( OO.isPlainObject( message ) && config === undefined ) {
3798 config = message;
3799 message = config.message;
3800 }
3801
3802 // Configuration initialization
3803 config = config || {};
3804
3805 // Properties
3806 this.message = message instanceof jQuery ? message : String( message );
3807 this.recoverable = config.recoverable === undefined || !!config.recoverable;
3808 this.warning = !!config.warning;
3809 };
3810
3811 /* Setup */
3812
3813 OO.initClass( OO.ui.Error );
3814
3815 /* Methods */
3816
3817 /**
3818 * Check if the error is recoverable.
3819 *
3820 * If the error is recoverable, users are able to try the process again.
3821 *
3822 * @return {boolean} Error is recoverable
3823 */
3824 OO.ui.Error.prototype.isRecoverable = function () {
3825 return this.recoverable;
3826 };
3827
3828 /**
3829 * Check if the error is a warning.
3830 *
3831 * If the error is a warning, the error interface will include a 'Dismiss' and a 'Continue' button.
3832 *
3833 * @return {boolean} Error is warning
3834 */
3835 OO.ui.Error.prototype.isWarning = function () {
3836 return this.warning;
3837 };
3838
3839 /**
3840 * Get error message as DOM nodes.
3841 *
3842 * @return {jQuery} Error message in DOM nodes
3843 */
3844 OO.ui.Error.prototype.getMessage = function () {
3845 return this.message instanceof jQuery ?
3846 this.message.clone() :
3847 $( '<div>' ).text( this.message ).contents();
3848 };
3849
3850 /**
3851 * Get the error message text.
3852 *
3853 * @return {string} Error message
3854 */
3855 OO.ui.Error.prototype.getMessageText = function () {
3856 return this.message instanceof jQuery ? this.message.text() : this.message;
3857 };
3858
3859 /**
3860 * Wraps an HTML snippet for use with configuration values which default
3861 * to strings. This bypasses the default html-escaping done to string
3862 * values.
3863 *
3864 * @class
3865 *
3866 * @constructor
3867 * @param {string} [content] HTML content
3868 */
3869 OO.ui.HtmlSnippet = function OoUiHtmlSnippet( content ) {
3870 // Properties
3871 this.content = content;
3872 };
3873
3874 /* Setup */
3875
3876 OO.initClass( OO.ui.HtmlSnippet );
3877
3878 /* Methods */
3879
3880 /**
3881 * Render into HTML.
3882 *
3883 * @return {string} Unchanged HTML snippet.
3884 */
3885 OO.ui.HtmlSnippet.prototype.toString = function () {
3886 return this.content;
3887 };
3888
3889 /**
3890 * A Process is a list of steps that are called in sequence. The step can be a number, a jQuery promise,
3891 * or a function:
3892 *
3893 * - **number**: the process will wait for the specified number of milliseconds before proceeding.
3894 * - **promise**: the process will continue to the next step when the promise is successfully resolved
3895 * or stop if the promise is rejected.
3896 * - **function**: the process will execute the function. The process will stop if the function returns
3897 * either a boolean `false` or a promise that is rejected; if the function returns a number, the process
3898 * will wait for that number of milliseconds before proceeding.
3899 *
3900 * If the process fails, an {@link OO.ui.Error error} is generated. Depending on how the error is
3901 * configured, users can dismiss the error and try the process again, or not. If a process is stopped,
3902 * its remaining steps will not be performed.
3903 *
3904 * @class
3905 *
3906 * @constructor
3907 * @param {number|jQuery.Promise|Function} step Number of miliseconds to wait before proceeding, promise
3908 * that must be resolved before proceeding, or a function to execute. See #createStep for more information. see #createStep for more information
3909 * @param {Object} [context=null] Execution context of the function. The context is ignored if the step is
3910 * a number or promise.
3911 * @return {Object} Step object, with `callback` and `context` properties
3912 */
3913 OO.ui.Process = function ( step, context ) {
3914 // Properties
3915 this.steps = [];
3916
3917 // Initialization
3918 if ( step !== undefined ) {
3919 this.next( step, context );
3920 }
3921 };
3922
3923 /* Setup */
3924
3925 OO.initClass( OO.ui.Process );
3926
3927 /* Methods */
3928
3929 /**
3930 * Start the process.
3931 *
3932 * @return {jQuery.Promise} Promise that is resolved when all steps have successfully completed.
3933 * If any of the steps return a promise that is rejected or a boolean false, this promise is rejected
3934 * and any remaining steps are not performed.
3935 */
3936 OO.ui.Process.prototype.execute = function () {
3937 var i, len, promise;
3938
3939 /**
3940 * Continue execution.
3941 *
3942 * @ignore
3943 * @param {Array} step A function and the context it should be called in
3944 * @return {Function} Function that continues the process
3945 */
3946 function proceed( step ) {
3947 return function () {
3948 // Execute step in the correct context
3949 var deferred,
3950 result = step.callback.call( step.context );
3951
3952 if ( result === false ) {
3953 // Use rejected promise for boolean false results
3954 return $.Deferred().reject( [] ).promise();
3955 }
3956 if ( typeof result === 'number' ) {
3957 if ( result < 0 ) {
3958 throw new Error( 'Cannot go back in time: flux capacitor is out of service' );
3959 }
3960 // Use a delayed promise for numbers, expecting them to be in milliseconds
3961 deferred = $.Deferred();
3962 setTimeout( deferred.resolve, result );
3963 return deferred.promise();
3964 }
3965 if ( result instanceof OO.ui.Error ) {
3966 // Use rejected promise for error
3967 return $.Deferred().reject( [ result ] ).promise();
3968 }
3969 if ( Array.isArray( result ) && result.length && result[ 0 ] instanceof OO.ui.Error ) {
3970 // Use rejected promise for list of errors
3971 return $.Deferred().reject( result ).promise();
3972 }
3973 // Duck-type the object to see if it can produce a promise
3974 if ( result && $.isFunction( result.promise ) ) {
3975 // Use a promise generated from the result
3976 return result.promise();
3977 }
3978 // Use resolved promise for other results
3979 return $.Deferred().resolve().promise();
3980 };
3981 }
3982
3983 if ( this.steps.length ) {
3984 // Generate a chain reaction of promises
3985 promise = proceed( this.steps[ 0 ] )();
3986 for ( i = 1, len = this.steps.length; i < len; i++ ) {
3987 promise = promise.then( proceed( this.steps[ i ] ) );
3988 }
3989 } else {
3990 promise = $.Deferred().resolve().promise();
3991 }
3992
3993 return promise;
3994 };
3995
3996 /**
3997 * Create a process step.
3998 *
3999 * @private
4000 * @param {number|jQuery.Promise|Function} step
4001 *
4002 * - Number of milliseconds to wait before proceeding
4003 * - Promise that must be resolved before proceeding
4004 * - Function to execute
4005 * - If the function returns a boolean false the process will stop
4006 * - If the function returns a promise, the process will continue to the next
4007 * step when the promise is resolved or stop if the promise is rejected
4008 * - If the function returns a number, the process will wait for that number of
4009 * milliseconds before proceeding
4010 * @param {Object} [context=null] Execution context of the function. The context is
4011 * ignored if the step is a number or promise.
4012 * @return {Object} Step object, with `callback` and `context` properties
4013 */
4014 OO.ui.Process.prototype.createStep = function ( step, context ) {
4015 if ( typeof step === 'number' || $.isFunction( step.promise ) ) {
4016 return {
4017 callback: function () {
4018 return step;
4019 },
4020 context: null
4021 };
4022 }
4023 if ( $.isFunction( step ) ) {
4024 return {
4025 callback: step,
4026 context: context
4027 };
4028 }
4029 throw new Error( 'Cannot create process step: number, promise or function expected' );
4030 };
4031
4032 /**
4033 * Add step to the beginning of the process.
4034 *
4035 * @inheritdoc #createStep
4036 * @return {OO.ui.Process} this
4037 * @chainable
4038 */
4039 OO.ui.Process.prototype.first = function ( step, context ) {
4040 this.steps.unshift( this.createStep( step, context ) );
4041 return this;
4042 };
4043
4044 /**
4045 * Add step to the end of the process.
4046 *
4047 * @inheritdoc #createStep
4048 * @return {OO.ui.Process} this
4049 * @chainable
4050 */
4051 OO.ui.Process.prototype.next = function ( step, context ) {
4052 this.steps.push( this.createStep( step, context ) );
4053 return this;
4054 };
4055
4056 /**
4057 * A ToolFactory creates tools on demand. All tools ({@link OO.ui.Tool Tools}, {@link OO.ui.PopupTool PopupTools},
4058 * and {@link OO.ui.ToolGroupTool ToolGroupTools}) must be registered with a tool factory. Tools are
4059 * registered by their symbolic name. See {@link OO.ui.Toolbar toolbars} for an example.
4060 *
4061 * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki][1].
4062 *
4063 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
4064 *
4065 * @class
4066 * @extends OO.Factory
4067 * @constructor
4068 */
4069 OO.ui.ToolFactory = function OoUiToolFactory() {
4070 // Parent constructor
4071 OO.ui.ToolFactory.parent.call( this );
4072 };
4073
4074 /* Setup */
4075
4076 OO.inheritClass( OO.ui.ToolFactory, OO.Factory );
4077
4078 /* Methods */
4079
4080 /**
4081 * Get tools from the factory
4082 *
4083 * @param {Array} include Included tools
4084 * @param {Array} exclude Excluded tools
4085 * @param {Array} promote Promoted tools
4086 * @param {Array} demote Demoted tools
4087 * @return {string[]} List of tools
4088 */
4089 OO.ui.ToolFactory.prototype.getTools = function ( include, exclude, promote, demote ) {
4090 var i, len, included, promoted, demoted,
4091 auto = [],
4092 used = {};
4093
4094 // Collect included and not excluded tools
4095 included = OO.simpleArrayDifference( this.extract( include ), this.extract( exclude ) );
4096
4097 // Promotion
4098 promoted = this.extract( promote, used );
4099 demoted = this.extract( demote, used );
4100
4101 // Auto
4102 for ( i = 0, len = included.length; i < len; i++ ) {
4103 if ( !used[ included[ i ] ] ) {
4104 auto.push( included[ i ] );
4105 }
4106 }
4107
4108 return promoted.concat( auto ).concat( demoted );
4109 };
4110
4111 /**
4112 * Get a flat list of names from a list of names or groups.
4113 *
4114 * Tools can be specified in the following ways:
4115 *
4116 * - A specific tool: `{ name: 'tool-name' }` or `'tool-name'`
4117 * - All tools in a group: `{ group: 'group-name' }`
4118 * - All tools: `'*'`
4119 *
4120 * @private
4121 * @param {Array|string} collection List of tools
4122 * @param {Object} [used] Object with names that should be skipped as properties; extracted
4123 * names will be added as properties
4124 * @return {string[]} List of extracted names
4125 */
4126 OO.ui.ToolFactory.prototype.extract = function ( collection, used ) {
4127 var i, len, item, name, tool,
4128 names = [];
4129
4130 if ( collection === '*' ) {
4131 for ( name in this.registry ) {
4132 tool = this.registry[ name ];
4133 if (
4134 // Only add tools by group name when auto-add is enabled
4135 tool.static.autoAddToCatchall &&
4136 // Exclude already used tools
4137 ( !used || !used[ name ] )
4138 ) {
4139 names.push( name );
4140 if ( used ) {
4141 used[ name ] = true;
4142 }
4143 }
4144 }
4145 } else if ( Array.isArray( collection ) ) {
4146 for ( i = 0, len = collection.length; i < len; i++ ) {
4147 item = collection[ i ];
4148 // Allow plain strings as shorthand for named tools
4149 if ( typeof item === 'string' ) {
4150 item = { name: item };
4151 }
4152 if ( OO.isPlainObject( item ) ) {
4153 if ( item.group ) {
4154 for ( name in this.registry ) {
4155 tool = this.registry[ name ];
4156 if (
4157 // Include tools with matching group
4158 tool.static.group === item.group &&
4159 // Only add tools by group name when auto-add is enabled
4160 tool.static.autoAddToGroup &&
4161 // Exclude already used tools
4162 ( !used || !used[ name ] )
4163 ) {
4164 names.push( name );
4165 if ( used ) {
4166 used[ name ] = true;
4167 }
4168 }
4169 }
4170 // Include tools with matching name and exclude already used tools
4171 } else if ( item.name && ( !used || !used[ item.name ] ) ) {
4172 names.push( item.name );
4173 if ( used ) {
4174 used[ item.name ] = true;
4175 }
4176 }
4177 }
4178 }
4179 }
4180 return names;
4181 };
4182
4183 /**
4184 * ToolGroupFactories create {@link OO.ui.ToolGroup toolgroups} on demand. The toolgroup classes must
4185 * specify a symbolic name and be registered with the factory. The following classes are registered by
4186 * default:
4187 *
4188 * - {@link OO.ui.BarToolGroup BarToolGroups} (‘bar’)
4189 * - {@link OO.ui.MenuToolGroup MenuToolGroups} (‘menu’)
4190 * - {@link OO.ui.ListToolGroup ListToolGroups} (‘list’)
4191 *
4192 * See {@link OO.ui.Toolbar toolbars} for an example.
4193 *
4194 * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki][1].
4195 *
4196 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
4197 * @class
4198 * @extends OO.Factory
4199 * @constructor
4200 */
4201 OO.ui.ToolGroupFactory = function OoUiToolGroupFactory() {
4202 var i, l, defaultClasses;
4203 // Parent constructor
4204 OO.Factory.call( this );
4205
4206 defaultClasses = this.constructor.static.getDefaultClasses();
4207
4208 // Register default toolgroups
4209 for ( i = 0, l = defaultClasses.length; i < l; i++ ) {
4210 this.register( defaultClasses[ i ] );
4211 }
4212 };
4213
4214 /* Setup */
4215
4216 OO.inheritClass( OO.ui.ToolGroupFactory, OO.Factory );
4217
4218 /* Static Methods */
4219
4220 /**
4221 * Get a default set of classes to be registered on construction.
4222 *
4223 * @return {Function[]} Default classes
4224 */
4225 OO.ui.ToolGroupFactory.static.getDefaultClasses = function () {
4226 return [
4227 OO.ui.BarToolGroup,
4228 OO.ui.ListToolGroup,
4229 OO.ui.MenuToolGroup
4230 ];
4231 };
4232
4233 /**
4234 * Theme logic.
4235 *
4236 * @abstract
4237 * @class
4238 *
4239 * @constructor
4240 * @param {Object} [config] Configuration options
4241 */
4242 OO.ui.Theme = function OoUiTheme( config ) {
4243 // Configuration initialization
4244 config = config || {};
4245 };
4246
4247 /* Setup */
4248
4249 OO.initClass( OO.ui.Theme );
4250
4251 /* Methods */
4252
4253 /**
4254 * Get a list of classes to be applied to a widget.
4255 *
4256 * The 'on' and 'off' lists combined MUST contain keys for all classes the theme adds or removes,
4257 * otherwise state transitions will not work properly.
4258 *
4259 * @param {OO.ui.Element} element Element for which to get classes
4260 * @return {Object.<string,string[]>} Categorized class names with `on` and `off` lists
4261 */
4262 OO.ui.Theme.prototype.getElementClasses = function () {
4263 return { on: [], off: [] };
4264 };
4265
4266 /**
4267 * Update CSS classes provided by the theme.
4268 *
4269 * For elements with theme logic hooks, this should be called any time there's a state change.
4270 *
4271 * @param {OO.ui.Element} element Element for which to update classes
4272 * @return {Object.<string,string[]>} Categorized class names with `on` and `off` lists
4273 */
4274 OO.ui.Theme.prototype.updateElementClasses = function ( element ) {
4275 var $elements = $( [] ),
4276 classes = this.getElementClasses( element );
4277
4278 if ( element.$icon ) {
4279 $elements = $elements.add( element.$icon );
4280 }
4281 if ( element.$indicator ) {
4282 $elements = $elements.add( element.$indicator );
4283 }
4284
4285 $elements
4286 .removeClass( classes.off.join( ' ' ) )
4287 .addClass( classes.on.join( ' ' ) );
4288 };
4289
4290 /**
4291 * The TabIndexedElement class is an attribute mixin used to add additional functionality to an
4292 * element created by another class. The mixin provides a ‘tabIndex’ property, which specifies the
4293 * order in which users will navigate through the focusable elements via the "tab" key.
4294 *
4295 * @example
4296 * // TabIndexedElement is mixed into the ButtonWidget class
4297 * // to provide a tabIndex property.
4298 * var button1 = new OO.ui.ButtonWidget( {
4299 * label: 'fourth',
4300 * tabIndex: 4
4301 * } );
4302 * var button2 = new OO.ui.ButtonWidget( {
4303 * label: 'second',
4304 * tabIndex: 2
4305 * } );
4306 * var button3 = new OO.ui.ButtonWidget( {
4307 * label: 'third',
4308 * tabIndex: 3
4309 * } );
4310 * var button4 = new OO.ui.ButtonWidget( {
4311 * label: 'first',
4312 * tabIndex: 1
4313 * } );
4314 * $( 'body' ).append( button1.$element, button2.$element, button3.$element, button4.$element );
4315 *
4316 * @abstract
4317 * @class
4318 *
4319 * @constructor
4320 * @param {Object} [config] Configuration options
4321 * @cfg {jQuery} [$tabIndexed] The element that should use the tabindex functionality. By default,
4322 * the functionality is applied to the element created by the class ($element). If a different element is specified, the tabindex
4323 * functionality will be applied to it instead.
4324 * @cfg {number|null} [tabIndex=0] Number that specifies the element’s position in the tab-navigation
4325 * order (e.g., 1 for the first focusable element). Use 0 to use the default navigation order; use -1
4326 * to remove the element from the tab-navigation flow.
4327 */
4328 OO.ui.mixin.TabIndexedElement = function OoUiMixinTabIndexedElement( config ) {
4329 // Configuration initialization
4330 config = $.extend( { tabIndex: 0 }, config );
4331
4332 // Properties
4333 this.$tabIndexed = null;
4334 this.tabIndex = null;
4335
4336 // Events
4337 this.connect( this, { disable: 'onTabIndexedElementDisable' } );
4338
4339 // Initialization
4340 this.setTabIndex( config.tabIndex );
4341 this.setTabIndexedElement( config.$tabIndexed || this.$element );
4342 };
4343
4344 /* Setup */
4345
4346 OO.initClass( OO.ui.mixin.TabIndexedElement );
4347
4348 /* Methods */
4349
4350 /**
4351 * Set the element that should use the tabindex functionality.
4352 *
4353 * This method is used to retarget a tabindex mixin so that its functionality applies
4354 * to the specified element. If an element is currently using the functionality, the mixin’s
4355 * effect on that element is removed before the new element is set up.
4356 *
4357 * @param {jQuery} $tabIndexed Element that should use the tabindex functionality
4358 * @chainable
4359 */
4360 OO.ui.mixin.TabIndexedElement.prototype.setTabIndexedElement = function ( $tabIndexed ) {
4361 var tabIndex = this.tabIndex;
4362 // Remove attributes from old $tabIndexed
4363 this.setTabIndex( null );
4364 // Force update of new $tabIndexed
4365 this.$tabIndexed = $tabIndexed;
4366 this.tabIndex = tabIndex;
4367 return this.updateTabIndex();
4368 };
4369
4370 /**
4371 * Set the value of the tabindex.
4372 *
4373 * @param {number|null} tabIndex Tabindex value, or `null` for no tabindex
4374 * @chainable
4375 */
4376 OO.ui.mixin.TabIndexedElement.prototype.setTabIndex = function ( tabIndex ) {
4377 tabIndex = typeof tabIndex === 'number' ? tabIndex : null;
4378
4379 if ( this.tabIndex !== tabIndex ) {
4380 this.tabIndex = tabIndex;
4381 this.updateTabIndex();
4382 }
4383
4384 return this;
4385 };
4386
4387 /**
4388 * Update the `tabindex` attribute, in case of changes to tab index or
4389 * disabled state.
4390 *
4391 * @private
4392 * @chainable
4393 */
4394 OO.ui.mixin.TabIndexedElement.prototype.updateTabIndex = function () {
4395 if ( this.$tabIndexed ) {
4396 if ( this.tabIndex !== null ) {
4397 // Do not index over disabled elements
4398 this.$tabIndexed.attr( {
4399 tabindex: this.isDisabled() ? -1 : this.tabIndex,
4400 // Support: ChromeVox and NVDA
4401 // These do not seem to inherit aria-disabled from parent elements
4402 'aria-disabled': this.isDisabled().toString()
4403 } );
4404 } else {
4405 this.$tabIndexed.removeAttr( 'tabindex aria-disabled' );
4406 }
4407 }
4408 return this;
4409 };
4410
4411 /**
4412 * Handle disable events.
4413 *
4414 * @private
4415 * @param {boolean} disabled Element is disabled
4416 */
4417 OO.ui.mixin.TabIndexedElement.prototype.onTabIndexedElementDisable = function () {
4418 this.updateTabIndex();
4419 };
4420
4421 /**
4422 * Get the value of the tabindex.
4423 *
4424 * @return {number|null} Tabindex value
4425 */
4426 OO.ui.mixin.TabIndexedElement.prototype.getTabIndex = function () {
4427 return this.tabIndex;
4428 };
4429
4430 /**
4431 * ButtonElement is often mixed into other classes to generate a button, which is a clickable
4432 * interface element that can be configured with access keys for accessibility.
4433 * See the [OOjs UI documentation on MediaWiki] [1] for examples.
4434 *
4435 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#Buttons
4436 * @abstract
4437 * @class
4438 *
4439 * @constructor
4440 * @param {Object} [config] Configuration options
4441 * @cfg {jQuery} [$button] The button element created by the class.
4442 * If this configuration is omitted, the button element will use a generated `<a>`.
4443 * @cfg {boolean} [framed=true] Render the button with a frame
4444 */
4445 OO.ui.mixin.ButtonElement = function OoUiMixinButtonElement( config ) {
4446 // Configuration initialization
4447 config = config || {};
4448
4449 // Properties
4450 this.$button = null;
4451 this.framed = null;
4452 this.active = false;
4453 this.onMouseUpHandler = this.onMouseUp.bind( this );
4454 this.onMouseDownHandler = this.onMouseDown.bind( this );
4455 this.onKeyDownHandler = this.onKeyDown.bind( this );
4456 this.onKeyUpHandler = this.onKeyUp.bind( this );
4457 this.onClickHandler = this.onClick.bind( this );
4458 this.onKeyPressHandler = this.onKeyPress.bind( this );
4459
4460 // Initialization
4461 this.$element.addClass( 'oo-ui-buttonElement' );
4462 this.toggleFramed( config.framed === undefined || config.framed );
4463 this.setButtonElement( config.$button || $( '<a>' ) );
4464 };
4465
4466 /* Setup */
4467
4468 OO.initClass( OO.ui.mixin.ButtonElement );
4469
4470 /* Static Properties */
4471
4472 /**
4473 * Cancel mouse down events.
4474 *
4475 * This property is usually set to `true` to prevent the focus from changing when the button is clicked.
4476 * Classes such as {@link OO.ui.mixin.DraggableElement DraggableElement} and {@link OO.ui.ButtonOptionWidget ButtonOptionWidget}
4477 * use a value of `false` so that dragging behavior is possible and mousedown events can be handled by a
4478 * parent widget.
4479 *
4480 * @static
4481 * @inheritable
4482 * @property {boolean}
4483 */
4484 OO.ui.mixin.ButtonElement.static.cancelButtonMouseDownEvents = true;
4485
4486 /* Events */
4487
4488 /**
4489 * A 'click' event is emitted when the button element is clicked.
4490 *
4491 * @event click
4492 */
4493
4494 /* Methods */
4495
4496 /**
4497 * Set the button element.
4498 *
4499 * This method is used to retarget a button mixin so that its functionality applies to
4500 * the specified button element instead of the one created by the class. If a button element
4501 * is already set, the method will remove the mixin’s effect on that element.
4502 *
4503 * @param {jQuery} $button Element to use as button
4504 */
4505 OO.ui.mixin.ButtonElement.prototype.setButtonElement = function ( $button ) {
4506 if ( this.$button ) {
4507 this.$button
4508 .removeClass( 'oo-ui-buttonElement-button' )
4509 .removeAttr( 'role accesskey' )
4510 .off( {
4511 mousedown: this.onMouseDownHandler,
4512 keydown: this.onKeyDownHandler,
4513 click: this.onClickHandler,
4514 keypress: this.onKeyPressHandler
4515 } );
4516 }
4517
4518 this.$button = $button
4519 .addClass( 'oo-ui-buttonElement-button' )
4520 .attr( { role: 'button' } )
4521 .on( {
4522 mousedown: this.onMouseDownHandler,
4523 keydown: this.onKeyDownHandler,
4524 click: this.onClickHandler,
4525 keypress: this.onKeyPressHandler
4526 } );
4527 };
4528
4529 /**
4530 * Handles mouse down events.
4531 *
4532 * @protected
4533 * @param {jQuery.Event} e Mouse down event
4534 */
4535 OO.ui.mixin.ButtonElement.prototype.onMouseDown = function ( e ) {
4536 if ( this.isDisabled() || e.which !== 1 ) {
4537 return;
4538 }
4539 this.$element.addClass( 'oo-ui-buttonElement-pressed' );
4540 // Run the mouseup handler no matter where the mouse is when the button is let go, so we can
4541 // reliably remove the pressed class
4542 OO.ui.addCaptureEventListener( this.getElementDocument(), 'mouseup', this.onMouseUpHandler );
4543 // Prevent change of focus unless specifically configured otherwise
4544 if ( this.constructor.static.cancelButtonMouseDownEvents ) {
4545 return false;
4546 }
4547 };
4548
4549 /**
4550 * Handles mouse up events.
4551 *
4552 * @protected
4553 * @param {jQuery.Event} e Mouse up event
4554 */
4555 OO.ui.mixin.ButtonElement.prototype.onMouseUp = function ( e ) {
4556 if ( this.isDisabled() || e.which !== 1 ) {
4557 return;
4558 }
4559 this.$element.removeClass( 'oo-ui-buttonElement-pressed' );
4560 // Stop listening for mouseup, since we only needed this once
4561 OO.ui.removeCaptureEventListener( this.getElementDocument(), 'mouseup', this.onMouseUpHandler );
4562 };
4563
4564 /**
4565 * Handles mouse click events.
4566 *
4567 * @protected
4568 * @param {jQuery.Event} e Mouse click event
4569 * @fires click
4570 */
4571 OO.ui.mixin.ButtonElement.prototype.onClick = function ( e ) {
4572 if ( !this.isDisabled() && e.which === 1 ) {
4573 if ( this.emit( 'click' ) ) {
4574 return false;
4575 }
4576 }
4577 };
4578
4579 /**
4580 * Handles key down events.
4581 *
4582 * @protected
4583 * @param {jQuery.Event} e Key down event
4584 */
4585 OO.ui.mixin.ButtonElement.prototype.onKeyDown = function ( e ) {
4586 if ( this.isDisabled() || ( e.which !== OO.ui.Keys.SPACE && e.which !== OO.ui.Keys.ENTER ) ) {
4587 return;
4588 }
4589 this.$element.addClass( 'oo-ui-buttonElement-pressed' );
4590 // Run the keyup handler no matter where the key is when the button is let go, so we can
4591 // reliably remove the pressed class
4592 OO.ui.addCaptureEventListener( this.getElementDocument(), 'keyup', this.onKeyUpHandler );
4593 };
4594
4595 /**
4596 * Handles key up events.
4597 *
4598 * @protected
4599 * @param {jQuery.Event} e Key up event
4600 */
4601 OO.ui.mixin.ButtonElement.prototype.onKeyUp = function ( e ) {
4602 if ( this.isDisabled() || ( e.which !== OO.ui.Keys.SPACE && e.which !== OO.ui.Keys.ENTER ) ) {
4603 return;
4604 }
4605 this.$element.removeClass( 'oo-ui-buttonElement-pressed' );
4606 // Stop listening for keyup, since we only needed this once
4607 OO.ui.removeCaptureEventListener( this.getElementDocument(), 'keyup', this.onKeyUpHandler );
4608 };
4609
4610 /**
4611 * Handles key press events.
4612 *
4613 * @protected
4614 * @param {jQuery.Event} e Key press event
4615 * @fires click
4616 */
4617 OO.ui.mixin.ButtonElement.prototype.onKeyPress = function ( e ) {
4618 if ( !this.isDisabled() && ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER ) ) {
4619 if ( this.emit( 'click' ) ) {
4620 return false;
4621 }
4622 }
4623 };
4624
4625 /**
4626 * Check if button has a frame.
4627 *
4628 * @return {boolean} Button is framed
4629 */
4630 OO.ui.mixin.ButtonElement.prototype.isFramed = function () {
4631 return this.framed;
4632 };
4633
4634 /**
4635 * Render the button with or without a frame. Omit the `framed` parameter to toggle the button frame on and off.
4636 *
4637 * @param {boolean} [framed] Make button framed, omit to toggle
4638 * @chainable
4639 */
4640 OO.ui.mixin.ButtonElement.prototype.toggleFramed = function ( framed ) {
4641 framed = framed === undefined ? !this.framed : !!framed;
4642 if ( framed !== this.framed ) {
4643 this.framed = framed;
4644 this.$element
4645 .toggleClass( 'oo-ui-buttonElement-frameless', !framed )
4646 .toggleClass( 'oo-ui-buttonElement-framed', framed );
4647 this.updateThemeClasses();
4648 }
4649
4650 return this;
4651 };
4652
4653 /**
4654 * Set the button's active state.
4655 *
4656 * The active state occurs when a {@link OO.ui.ButtonOptionWidget ButtonOptionWidget} or
4657 * a {@link OO.ui.ToggleButtonWidget ToggleButtonWidget} is pressed. This method does nothing
4658 * for other button types.
4659 *
4660 * @param {boolean} value Make button active
4661 * @chainable
4662 */
4663 OO.ui.mixin.ButtonElement.prototype.setActive = function ( value ) {
4664 this.active = !!value;
4665 this.$element.toggleClass( 'oo-ui-buttonElement-active', this.active );
4666 return this;
4667 };
4668
4669 /**
4670 * Check if the button is active
4671 *
4672 * @return {boolean} The button is active
4673 */
4674 OO.ui.mixin.ButtonElement.prototype.isActive = function () {
4675 return this.active;
4676 };
4677
4678 /**
4679 * Any OOjs UI widget that contains other widgets (such as {@link OO.ui.ButtonWidget buttons} or
4680 * {@link OO.ui.OptionWidget options}) mixes in GroupElement. Adding, removing, and clearing
4681 * items from the group is done through the interface the class provides.
4682 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
4683 *
4684 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Groups
4685 *
4686 * @abstract
4687 * @class
4688 *
4689 * @constructor
4690 * @param {Object} [config] Configuration options
4691 * @cfg {jQuery} [$group] The container element created by the class. If this configuration
4692 * is omitted, the group element will use a generated `<div>`.
4693 */
4694 OO.ui.mixin.GroupElement = function OoUiMixinGroupElement( config ) {
4695 // Configuration initialization
4696 config = config || {};
4697
4698 // Properties
4699 this.$group = null;
4700 this.items = [];
4701 this.aggregateItemEvents = {};
4702
4703 // Initialization
4704 this.setGroupElement( config.$group || $( '<div>' ) );
4705 };
4706
4707 /* Methods */
4708
4709 /**
4710 * Set the group element.
4711 *
4712 * If an element is already set, items will be moved to the new element.
4713 *
4714 * @param {jQuery} $group Element to use as group
4715 */
4716 OO.ui.mixin.GroupElement.prototype.setGroupElement = function ( $group ) {
4717 var i, len;
4718
4719 this.$group = $group;
4720 for ( i = 0, len = this.items.length; i < len; i++ ) {
4721 this.$group.append( this.items[ i ].$element );
4722 }
4723 };
4724
4725 /**
4726 * Check if a group contains no items.
4727 *
4728 * @return {boolean} Group is empty
4729 */
4730 OO.ui.mixin.GroupElement.prototype.isEmpty = function () {
4731 return !this.items.length;
4732 };
4733
4734 /**
4735 * Get all items in the group.
4736 *
4737 * The method returns an array of item references (e.g., [button1, button2, button3]) and is useful
4738 * when synchronizing groups of items, or whenever the references are required (e.g., when removing items
4739 * from a group).
4740 *
4741 * @return {OO.ui.Element[]} An array of items.
4742 */
4743 OO.ui.mixin.GroupElement.prototype.getItems = function () {
4744 return this.items.slice( 0 );
4745 };
4746
4747 /**
4748 * Get an item by its data.
4749 *
4750 * Only the first item with matching data will be returned. To return all matching items,
4751 * use the #getItemsFromData method.
4752 *
4753 * @param {Object} data Item data to search for
4754 * @return {OO.ui.Element|null} Item with equivalent data, `null` if none exists
4755 */
4756 OO.ui.mixin.GroupElement.prototype.getItemFromData = function ( data ) {
4757 var i, len, item,
4758 hash = OO.getHash( data );
4759
4760 for ( i = 0, len = this.items.length; i < len; i++ ) {
4761 item = this.items[ i ];
4762 if ( hash === OO.getHash( item.getData() ) ) {
4763 return item;
4764 }
4765 }
4766
4767 return null;
4768 };
4769
4770 /**
4771 * Get items by their data.
4772 *
4773 * All items with matching data will be returned. To return only the first match, use the #getItemFromData method instead.
4774 *
4775 * @param {Object} data Item data to search for
4776 * @return {OO.ui.Element[]} Items with equivalent data
4777 */
4778 OO.ui.mixin.GroupElement.prototype.getItemsFromData = function ( data ) {
4779 var i, len, item,
4780 hash = OO.getHash( data ),
4781 items = [];
4782
4783 for ( i = 0, len = this.items.length; i < len; i++ ) {
4784 item = this.items[ i ];
4785 if ( hash === OO.getHash( item.getData() ) ) {
4786 items.push( item );
4787 }
4788 }
4789
4790 return items;
4791 };
4792
4793 /**
4794 * Aggregate the events emitted by the group.
4795 *
4796 * When events are aggregated, the group will listen to all contained items for the event,
4797 * and then emit the event under a new name. The new event will contain an additional leading
4798 * parameter containing the item that emitted the original event. Other arguments emitted from
4799 * the original event are passed through.
4800 *
4801 * @param {Object.<string,string|null>} events An object keyed by the name of the event that should be
4802 * aggregated (e.g., ‘click’) and the value of the new name to use (e.g., ‘groupClick’).
4803 * A `null` value will remove aggregated events.
4804
4805 * @throws {Error} An error is thrown if aggregation already exists.
4806 */
4807 OO.ui.mixin.GroupElement.prototype.aggregate = function ( events ) {
4808 var i, len, item, add, remove, itemEvent, groupEvent;
4809
4810 for ( itemEvent in events ) {
4811 groupEvent = events[ itemEvent ];
4812
4813 // Remove existing aggregated event
4814 if ( Object.prototype.hasOwnProperty.call( this.aggregateItemEvents, itemEvent ) ) {
4815 // Don't allow duplicate aggregations
4816 if ( groupEvent ) {
4817 throw new Error( 'Duplicate item event aggregation for ' + itemEvent );
4818 }
4819 // Remove event aggregation from existing items
4820 for ( i = 0, len = this.items.length; i < len; i++ ) {
4821 item = this.items[ i ];
4822 if ( item.connect && item.disconnect ) {
4823 remove = {};
4824 remove[ itemEvent ] = [ 'emit', this.aggregateItemEvents[ itemEvent ], item ];
4825 item.disconnect( this, remove );
4826 }
4827 }
4828 // Prevent future items from aggregating event
4829 delete this.aggregateItemEvents[ itemEvent ];
4830 }
4831
4832 // Add new aggregate event
4833 if ( groupEvent ) {
4834 // Make future items aggregate event
4835 this.aggregateItemEvents[ itemEvent ] = groupEvent;
4836 // Add event aggregation to existing items
4837 for ( i = 0, len = this.items.length; i < len; i++ ) {
4838 item = this.items[ i ];
4839 if ( item.connect && item.disconnect ) {
4840 add = {};
4841 add[ itemEvent ] = [ 'emit', groupEvent, item ];
4842 item.connect( this, add );
4843 }
4844 }
4845 }
4846 }
4847 };
4848
4849 /**
4850 * Add items to the group.
4851 *
4852 * Items will be added to the end of the group array unless the optional `index` parameter specifies
4853 * a different insertion point. Adding an existing item will move it to the end of the array or the point specified by the `index`.
4854 *
4855 * @param {OO.ui.Element[]} items An array of items to add to the group
4856 * @param {number} [index] Index of the insertion point
4857 * @chainable
4858 */
4859 OO.ui.mixin.GroupElement.prototype.addItems = function ( items, index ) {
4860 var i, len, item, event, events, currentIndex,
4861 itemElements = [];
4862
4863 for ( i = 0, len = items.length; i < len; i++ ) {
4864 item = items[ i ];
4865
4866 // Check if item exists then remove it first, effectively "moving" it
4867 currentIndex = this.items.indexOf( item );
4868 if ( currentIndex >= 0 ) {
4869 this.removeItems( [ item ] );
4870 // Adjust index to compensate for removal
4871 if ( currentIndex < index ) {
4872 index--;
4873 }
4874 }
4875 // Add the item
4876 if ( item.connect && item.disconnect && !$.isEmptyObject( this.aggregateItemEvents ) ) {
4877 events = {};
4878 for ( event in this.aggregateItemEvents ) {
4879 events[ event ] = [ 'emit', this.aggregateItemEvents[ event ], item ];
4880 }
4881 item.connect( this, events );
4882 }
4883 item.setElementGroup( this );
4884 itemElements.push( item.$element.get( 0 ) );
4885 }
4886
4887 if ( index === undefined || index < 0 || index >= this.items.length ) {
4888 this.$group.append( itemElements );
4889 this.items.push.apply( this.items, items );
4890 } else if ( index === 0 ) {
4891 this.$group.prepend( itemElements );
4892 this.items.unshift.apply( this.items, items );
4893 } else {
4894 this.items[ index ].$element.before( itemElements );
4895 this.items.splice.apply( this.items, [ index, 0 ].concat( items ) );
4896 }
4897
4898 return this;
4899 };
4900
4901 /**
4902 * Remove the specified items from a group.
4903 *
4904 * Removed items are detached (not removed) from the DOM so that they may be reused.
4905 * To remove all items from a group, you may wish to use the #clearItems method instead.
4906 *
4907 * @param {OO.ui.Element[]} items An array of items to remove
4908 * @chainable
4909 */
4910 OO.ui.mixin.GroupElement.prototype.removeItems = function ( items ) {
4911 var i, len, item, index, remove, itemEvent;
4912
4913 // Remove specific items
4914 for ( i = 0, len = items.length; i < len; i++ ) {
4915 item = items[ i ];
4916 index = this.items.indexOf( item );
4917 if ( index !== -1 ) {
4918 if (
4919 item.connect && item.disconnect &&
4920 !$.isEmptyObject( this.aggregateItemEvents )
4921 ) {
4922 remove = {};
4923 if ( Object.prototype.hasOwnProperty.call( this.aggregateItemEvents, itemEvent ) ) {
4924 remove[ itemEvent ] = [ 'emit', this.aggregateItemEvents[ itemEvent ], item ];
4925 }
4926 item.disconnect( this, remove );
4927 }
4928 item.setElementGroup( null );
4929 this.items.splice( index, 1 );
4930 item.$element.detach();
4931 }
4932 }
4933
4934 return this;
4935 };
4936
4937 /**
4938 * Clear all items from the group.
4939 *
4940 * Cleared items are detached from the DOM, not removed, so that they may be reused.
4941 * To remove only a subset of items from a group, use the #removeItems method.
4942 *
4943 * @chainable
4944 */
4945 OO.ui.mixin.GroupElement.prototype.clearItems = function () {
4946 var i, len, item, remove, itemEvent;
4947
4948 // Remove all items
4949 for ( i = 0, len = this.items.length; i < len; i++ ) {
4950 item = this.items[ i ];
4951 if (
4952 item.connect && item.disconnect &&
4953 !$.isEmptyObject( this.aggregateItemEvents )
4954 ) {
4955 remove = {};
4956 if ( Object.prototype.hasOwnProperty.call( this.aggregateItemEvents, itemEvent ) ) {
4957 remove[ itemEvent ] = [ 'emit', this.aggregateItemEvents[ itemEvent ], item ];
4958 }
4959 item.disconnect( this, remove );
4960 }
4961 item.setElementGroup( null );
4962 item.$element.detach();
4963 }
4964
4965 this.items = [];
4966 return this;
4967 };
4968
4969 /**
4970 * DraggableElement is a mixin class used to create elements that can be clicked
4971 * and dragged by a mouse to a new position within a group. This class must be used
4972 * in conjunction with OO.ui.mixin.DraggableGroupElement, which provides a container for
4973 * the draggable elements.
4974 *
4975 * @abstract
4976 * @class
4977 *
4978 * @constructor
4979 */
4980 OO.ui.mixin.DraggableElement = function OoUiMixinDraggableElement() {
4981 // Properties
4982 this.index = null;
4983
4984 // Initialize and events
4985 this.$element
4986 .attr( 'draggable', true )
4987 .addClass( 'oo-ui-draggableElement' )
4988 .on( {
4989 dragstart: this.onDragStart.bind( this ),
4990 dragover: this.onDragOver.bind( this ),
4991 dragend: this.onDragEnd.bind( this ),
4992 drop: this.onDrop.bind( this )
4993 } );
4994 };
4995
4996 OO.initClass( OO.ui.mixin.DraggableElement );
4997
4998 /* Events */
4999
5000 /**
5001 * @event dragstart
5002 *
5003 * A dragstart event is emitted when the user clicks and begins dragging an item.
5004 * @param {OO.ui.mixin.DraggableElement} item The item the user has clicked and is dragging with the mouse.
5005 */
5006
5007 /**
5008 * @event dragend
5009 * A dragend event is emitted when the user drags an item and releases the mouse,
5010 * thus terminating the drag operation.
5011 */
5012
5013 /**
5014 * @event drop
5015 * A drop event is emitted when the user drags an item and then releases the mouse button
5016 * over a valid target.
5017 */
5018
5019 /* Static Properties */
5020
5021 /**
5022 * @inheritdoc OO.ui.mixin.ButtonElement
5023 */
5024 OO.ui.mixin.DraggableElement.static.cancelButtonMouseDownEvents = false;
5025
5026 /* Methods */
5027
5028 /**
5029 * Respond to dragstart event.
5030 *
5031 * @private
5032 * @param {jQuery.Event} event jQuery event
5033 * @fires dragstart
5034 */
5035 OO.ui.mixin.DraggableElement.prototype.onDragStart = function ( e ) {
5036 var dataTransfer = e.originalEvent.dataTransfer;
5037 // Define drop effect
5038 dataTransfer.dropEffect = 'none';
5039 dataTransfer.effectAllowed = 'move';
5040 // Support: Firefox
5041 // We must set up a dataTransfer data property or Firefox seems to
5042 // ignore the fact the element is draggable.
5043 try {
5044 dataTransfer.setData( 'application-x/OOjs-UI-draggable', this.getIndex() );
5045 } catch ( err ) {
5046 // The above is only for Firefox. Move on if it fails.
5047 }
5048 // Add dragging class
5049 this.$element.addClass( 'oo-ui-draggableElement-dragging' );
5050 // Emit event
5051 this.emit( 'dragstart', this );
5052 return true;
5053 };
5054
5055 /**
5056 * Respond to dragend event.
5057 *
5058 * @private
5059 * @fires dragend
5060 */
5061 OO.ui.mixin.DraggableElement.prototype.onDragEnd = function () {
5062 this.$element.removeClass( 'oo-ui-draggableElement-dragging' );
5063 this.emit( 'dragend' );
5064 };
5065
5066 /**
5067 * Handle drop event.
5068 *
5069 * @private
5070 * @param {jQuery.Event} event jQuery event
5071 * @fires drop
5072 */
5073 OO.ui.mixin.DraggableElement.prototype.onDrop = function ( e ) {
5074 e.preventDefault();
5075 this.emit( 'drop', e );
5076 };
5077
5078 /**
5079 * In order for drag/drop to work, the dragover event must
5080 * return false and stop propogation.
5081 *
5082 * @private
5083 */
5084 OO.ui.mixin.DraggableElement.prototype.onDragOver = function ( e ) {
5085 e.preventDefault();
5086 };
5087
5088 /**
5089 * Set item index.
5090 * Store it in the DOM so we can access from the widget drag event
5091 *
5092 * @private
5093 * @param {number} Item index
5094 */
5095 OO.ui.mixin.DraggableElement.prototype.setIndex = function ( index ) {
5096 if ( this.index !== index ) {
5097 this.index = index;
5098 this.$element.data( 'index', index );
5099 }
5100 };
5101
5102 /**
5103 * Get item index
5104 *
5105 * @private
5106 * @return {number} Item index
5107 */
5108 OO.ui.mixin.DraggableElement.prototype.getIndex = function () {
5109 return this.index;
5110 };
5111
5112 /**
5113 * DraggableGroupElement is a mixin class used to create a group element to
5114 * contain draggable elements, which are items that can be clicked and dragged by a mouse.
5115 * The class is used with OO.ui.mixin.DraggableElement.
5116 *
5117 * @abstract
5118 * @class
5119 * @mixins OO.ui.mixin.GroupElement
5120 *
5121 * @constructor
5122 * @param {Object} [config] Configuration options
5123 * @cfg {string} [orientation] Item orientation: 'horizontal' or 'vertical'. The orientation
5124 * should match the layout of the items. Items displayed in a single row
5125 * or in several rows should use horizontal orientation. The vertical orientation should only be
5126 * used when the items are displayed in a single column. Defaults to 'vertical'
5127 */
5128 OO.ui.mixin.DraggableGroupElement = function OoUiMixinDraggableGroupElement( config ) {
5129 // Configuration initialization
5130 config = config || {};
5131
5132 // Parent constructor
5133 OO.ui.mixin.GroupElement.call( this, config );
5134
5135 // Properties
5136 this.orientation = config.orientation || 'vertical';
5137 this.dragItem = null;
5138 this.itemDragOver = null;
5139 this.itemKeys = {};
5140 this.sideInsertion = '';
5141
5142 // Events
5143 this.aggregate( {
5144 dragstart: 'itemDragStart',
5145 dragend: 'itemDragEnd',
5146 drop: 'itemDrop'
5147 } );
5148 this.connect( this, {
5149 itemDragStart: 'onItemDragStart',
5150 itemDrop: 'onItemDrop',
5151 itemDragEnd: 'onItemDragEnd'
5152 } );
5153 this.$element.on( {
5154 dragover: this.onDragOver.bind( this ),
5155 dragleave: this.onDragLeave.bind( this )
5156 } );
5157
5158 // Initialize
5159 if ( Array.isArray( config.items ) ) {
5160 this.addItems( config.items );
5161 }
5162 this.$placeholder = $( '<div>' )
5163 .addClass( 'oo-ui-draggableGroupElement-placeholder' );
5164 this.$element
5165 .addClass( 'oo-ui-draggableGroupElement' )
5166 .append( this.$status )
5167 .toggleClass( 'oo-ui-draggableGroupElement-horizontal', this.orientation === 'horizontal' )
5168 .prepend( this.$placeholder );
5169 };
5170
5171 /* Setup */
5172 OO.mixinClass( OO.ui.mixin.DraggableGroupElement, OO.ui.mixin.GroupElement );
5173
5174 /* Events */
5175
5176 /**
5177 * A 'reorder' event is emitted when the order of items in the group changes.
5178 *
5179 * @event reorder
5180 * @param {OO.ui.mixin.DraggableElement} item Reordered item
5181 * @param {number} [newIndex] New index for the item
5182 */
5183
5184 /* Methods */
5185
5186 /**
5187 * Respond to item drag start event
5188 *
5189 * @private
5190 * @param {OO.ui.mixin.DraggableElement} item Dragged item
5191 */
5192 OO.ui.mixin.DraggableGroupElement.prototype.onItemDragStart = function ( item ) {
5193 var i, len;
5194
5195 // Map the index of each object
5196 for ( i = 0, len = this.items.length; i < len; i++ ) {
5197 this.items[ i ].setIndex( i );
5198 }
5199
5200 if ( this.orientation === 'horizontal' ) {
5201 // Set the height of the indicator
5202 this.$placeholder.css( {
5203 height: item.$element.outerHeight(),
5204 width: 2
5205 } );
5206 } else {
5207 // Set the width of the indicator
5208 this.$placeholder.css( {
5209 height: 2,
5210 width: item.$element.outerWidth()
5211 } );
5212 }
5213 this.setDragItem( item );
5214 };
5215
5216 /**
5217 * Respond to item drag end event
5218 *
5219 * @private
5220 */
5221 OO.ui.mixin.DraggableGroupElement.prototype.onItemDragEnd = function () {
5222 this.unsetDragItem();
5223 return false;
5224 };
5225
5226 /**
5227 * Handle drop event and switch the order of the items accordingly
5228 *
5229 * @private
5230 * @param {OO.ui.mixin.DraggableElement} item Dropped item
5231 * @fires reorder
5232 */
5233 OO.ui.mixin.DraggableGroupElement.prototype.onItemDrop = function ( item ) {
5234 var toIndex = item.getIndex();
5235 // Check if the dropped item is from the current group
5236 // TODO: Figure out a way to configure a list of legally droppable
5237 // elements even if they are not yet in the list
5238 if ( this.getDragItem() ) {
5239 // If the insertion point is 'after', the insertion index
5240 // is shifted to the right (or to the left in RTL, hence 'after')
5241 if ( this.sideInsertion === 'after' ) {
5242 toIndex++;
5243 }
5244 // Emit change event
5245 this.emit( 'reorder', this.getDragItem(), toIndex );
5246 }
5247 this.unsetDragItem();
5248 // Return false to prevent propogation
5249 return false;
5250 };
5251
5252 /**
5253 * Handle dragleave event.
5254 *
5255 * @private
5256 */
5257 OO.ui.mixin.DraggableGroupElement.prototype.onDragLeave = function () {
5258 // This means the item was dragged outside the widget
5259 this.$placeholder
5260 .css( 'left', 0 )
5261 .addClass( 'oo-ui-element-hidden' );
5262 };
5263
5264 /**
5265 * Respond to dragover event
5266 *
5267 * @private
5268 * @param {jQuery.Event} event Event details
5269 */
5270 OO.ui.mixin.DraggableGroupElement.prototype.onDragOver = function ( e ) {
5271 var dragOverObj, $optionWidget, itemOffset, itemMidpoint, itemBoundingRect,
5272 itemSize, cssOutput, dragPosition, itemIndex, itemPosition,
5273 clientX = e.originalEvent.clientX,
5274 clientY = e.originalEvent.clientY;
5275
5276 // Get the OptionWidget item we are dragging over
5277 dragOverObj = this.getElementDocument().elementFromPoint( clientX, clientY );
5278 $optionWidget = $( dragOverObj ).closest( '.oo-ui-draggableElement' );
5279 if ( $optionWidget[ 0 ] ) {
5280 itemOffset = $optionWidget.offset();
5281 itemBoundingRect = $optionWidget[ 0 ].getBoundingClientRect();
5282 itemPosition = $optionWidget.position();
5283 itemIndex = $optionWidget.data( 'index' );
5284 }
5285
5286 if (
5287 itemOffset &&
5288 this.isDragging() &&
5289 itemIndex !== this.getDragItem().getIndex()
5290 ) {
5291 if ( this.orientation === 'horizontal' ) {
5292 // Calculate where the mouse is relative to the item width
5293 itemSize = itemBoundingRect.width;
5294 itemMidpoint = itemBoundingRect.left + itemSize / 2;
5295 dragPosition = clientX;
5296 // Which side of the item we hover over will dictate
5297 // where the placeholder will appear, on the left or
5298 // on the right
5299 cssOutput = {
5300 left: dragPosition < itemMidpoint ? itemPosition.left : itemPosition.left + itemSize,
5301 top: itemPosition.top
5302 };
5303 } else {
5304 // Calculate where the mouse is relative to the item height
5305 itemSize = itemBoundingRect.height;
5306 itemMidpoint = itemBoundingRect.top + itemSize / 2;
5307 dragPosition = clientY;
5308 // Which side of the item we hover over will dictate
5309 // where the placeholder will appear, on the top or
5310 // on the bottom
5311 cssOutput = {
5312 top: dragPosition < itemMidpoint ? itemPosition.top : itemPosition.top + itemSize,
5313 left: itemPosition.left
5314 };
5315 }
5316 // Store whether we are before or after an item to rearrange
5317 // For horizontal layout, we need to account for RTL, as this is flipped
5318 if ( this.orientation === 'horizontal' && this.$element.css( 'direction' ) === 'rtl' ) {
5319 this.sideInsertion = dragPosition < itemMidpoint ? 'after' : 'before';
5320 } else {
5321 this.sideInsertion = dragPosition < itemMidpoint ? 'before' : 'after';
5322 }
5323 // Add drop indicator between objects
5324 this.$placeholder
5325 .css( cssOutput )
5326 .removeClass( 'oo-ui-element-hidden' );
5327 } else {
5328 // This means the item was dragged outside the widget
5329 this.$placeholder
5330 .css( 'left', 0 )
5331 .addClass( 'oo-ui-element-hidden' );
5332 }
5333 // Prevent default
5334 e.preventDefault();
5335 };
5336
5337 /**
5338 * Set a dragged item
5339 *
5340 * @param {OO.ui.mixin.DraggableElement} item Dragged item
5341 */
5342 OO.ui.mixin.DraggableGroupElement.prototype.setDragItem = function ( item ) {
5343 this.dragItem = item;
5344 };
5345
5346 /**
5347 * Unset the current dragged item
5348 */
5349 OO.ui.mixin.DraggableGroupElement.prototype.unsetDragItem = function () {
5350 this.dragItem = null;
5351 this.itemDragOver = null;
5352 this.$placeholder.addClass( 'oo-ui-element-hidden' );
5353 this.sideInsertion = '';
5354 };
5355
5356 /**
5357 * Get the item that is currently being dragged.
5358 *
5359 * @return {OO.ui.mixin.DraggableElement|null} The currently dragged item, or `null` if no item is being dragged
5360 */
5361 OO.ui.mixin.DraggableGroupElement.prototype.getDragItem = function () {
5362 return this.dragItem;
5363 };
5364
5365 /**
5366 * Check if an item in the group is currently being dragged.
5367 *
5368 * @return {Boolean} Item is being dragged
5369 */
5370 OO.ui.mixin.DraggableGroupElement.prototype.isDragging = function () {
5371 return this.getDragItem() !== null;
5372 };
5373
5374 /**
5375 * IconElement is often mixed into other classes to generate an icon.
5376 * Icons are graphics, about the size of normal text. They are used to aid the user
5377 * in locating a control or to convey information in a space-efficient way. See the
5378 * [OOjs UI documentation on MediaWiki] [1] for a list of icons
5379 * included in the library.
5380 *
5381 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
5382 *
5383 * @abstract
5384 * @class
5385 *
5386 * @constructor
5387 * @param {Object} [config] Configuration options
5388 * @cfg {jQuery} [$icon] The icon element created by the class. If this configuration is omitted,
5389 * the icon element will use a generated `<span>`. To use a different HTML tag, or to specify that
5390 * the icon element be set to an existing icon instead of the one generated by this class, set a
5391 * value using a jQuery selection. For example:
5392 *
5393 * // Use a <div> tag instead of a <span>
5394 * $icon: $("<div>")
5395 * // Use an existing icon element instead of the one generated by the class
5396 * $icon: this.$element
5397 * // Use an icon element from a child widget
5398 * $icon: this.childwidget.$element
5399 * @cfg {Object|string} [icon=''] The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of
5400 * symbolic names. A map is used for i18n purposes and contains a `default` icon
5401 * name and additional names keyed by language code. The `default` name is used when no icon is keyed
5402 * by the user's language.
5403 *
5404 * Example of an i18n map:
5405 *
5406 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
5407 * See the [OOjs UI documentation on MediaWiki] [2] for a list of icons included in the library.
5408 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
5409 * @cfg {string|Function} [iconTitle] A text string used as the icon title, or a function that returns title
5410 * text. The icon title is displayed when users move the mouse over the icon.
5411 */
5412 OO.ui.mixin.IconElement = function OoUiMixinIconElement( config ) {
5413 // Configuration initialization
5414 config = config || {};
5415
5416 // Properties
5417 this.$icon = null;
5418 this.icon = null;
5419 this.iconTitle = null;
5420
5421 // Initialization
5422 this.setIcon( config.icon || this.constructor.static.icon );
5423 this.setIconTitle( config.iconTitle || this.constructor.static.iconTitle );
5424 this.setIconElement( config.$icon || $( '<span>' ) );
5425 };
5426
5427 /* Setup */
5428
5429 OO.initClass( OO.ui.mixin.IconElement );
5430
5431 /* Static Properties */
5432
5433 /**
5434 * The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of symbolic names. A map is used
5435 * for i18n purposes and contains a `default` icon name and additional names keyed by
5436 * language code. The `default` name is used when no icon is keyed by the user's language.
5437 *
5438 * Example of an i18n map:
5439 *
5440 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
5441 *
5442 * Note: the static property will be overridden if the #icon configuration is used.
5443 *
5444 * @static
5445 * @inheritable
5446 * @property {Object|string}
5447 */
5448 OO.ui.mixin.IconElement.static.icon = null;
5449
5450 /**
5451 * The icon title, displayed when users move the mouse over the icon. The value can be text, a
5452 * function that returns title text, or `null` for no title.
5453 *
5454 * The static property will be overridden if the #iconTitle configuration is used.
5455 *
5456 * @static
5457 * @inheritable
5458 * @property {string|Function|null}
5459 */
5460 OO.ui.mixin.IconElement.static.iconTitle = null;
5461
5462 /* Methods */
5463
5464 /**
5465 * Set the icon element. This method is used to retarget an icon mixin so that its functionality
5466 * applies to the specified icon element instead of the one created by the class. If an icon
5467 * element is already set, the mixin’s effect on that element is removed. Generated CSS classes
5468 * and mixin methods will no longer affect the element.
5469 *
5470 * @param {jQuery} $icon Element to use as icon
5471 */
5472 OO.ui.mixin.IconElement.prototype.setIconElement = function ( $icon ) {
5473 if ( this.$icon ) {
5474 this.$icon
5475 .removeClass( 'oo-ui-iconElement-icon oo-ui-icon-' + this.icon )
5476 .removeAttr( 'title' );
5477 }
5478
5479 this.$icon = $icon
5480 .addClass( 'oo-ui-iconElement-icon' )
5481 .toggleClass( 'oo-ui-icon-' + this.icon, !!this.icon );
5482 if ( this.iconTitle !== null ) {
5483 this.$icon.attr( 'title', this.iconTitle );
5484 }
5485
5486 this.updateThemeClasses();
5487 };
5488
5489 /**
5490 * Set icon by symbolic name (e.g., ‘remove’ or ‘menu’). Use `null` to remove an icon.
5491 * The icon parameter can also be set to a map of icon names. See the #icon config setting
5492 * for an example.
5493 *
5494 * @param {Object|string|null} icon A symbolic icon name, a {@link #icon map of icon names} keyed
5495 * by language code, or `null` to remove the icon.
5496 * @chainable
5497 */
5498 OO.ui.mixin.IconElement.prototype.setIcon = function ( icon ) {
5499 icon = OO.isPlainObject( icon ) ? OO.ui.getLocalValue( icon, null, 'default' ) : icon;
5500 icon = typeof icon === 'string' && icon.trim().length ? icon.trim() : null;
5501
5502 if ( this.icon !== icon ) {
5503 if ( this.$icon ) {
5504 if ( this.icon !== null ) {
5505 this.$icon.removeClass( 'oo-ui-icon-' + this.icon );
5506 }
5507 if ( icon !== null ) {
5508 this.$icon.addClass( 'oo-ui-icon-' + icon );
5509 }
5510 }
5511 this.icon = icon;
5512 }
5513
5514 this.$element.toggleClass( 'oo-ui-iconElement', !!this.icon );
5515 this.updateThemeClasses();
5516
5517 return this;
5518 };
5519
5520 /**
5521 * Set the icon title. Use `null` to remove the title.
5522 *
5523 * @param {string|Function|null} iconTitle A text string used as the icon title,
5524 * a function that returns title text, or `null` for no title.
5525 * @chainable
5526 */
5527 OO.ui.mixin.IconElement.prototype.setIconTitle = function ( iconTitle ) {
5528 iconTitle = typeof iconTitle === 'function' ||
5529 ( typeof iconTitle === 'string' && iconTitle.length ) ?
5530 OO.ui.resolveMsg( iconTitle ) : null;
5531
5532 if ( this.iconTitle !== iconTitle ) {
5533 this.iconTitle = iconTitle;
5534 if ( this.$icon ) {
5535 if ( this.iconTitle !== null ) {
5536 this.$icon.attr( 'title', iconTitle );
5537 } else {
5538 this.$icon.removeAttr( 'title' );
5539 }
5540 }
5541 }
5542
5543 return this;
5544 };
5545
5546 /**
5547 * Get the symbolic name of the icon.
5548 *
5549 * @return {string} Icon name
5550 */
5551 OO.ui.mixin.IconElement.prototype.getIcon = function () {
5552 return this.icon;
5553 };
5554
5555 /**
5556 * Get the icon title. The title text is displayed when a user moves the mouse over the icon.
5557 *
5558 * @return {string} Icon title text
5559 */
5560 OO.ui.mixin.IconElement.prototype.getIconTitle = function () {
5561 return this.iconTitle;
5562 };
5563
5564 /**
5565 * IndicatorElement is often mixed into other classes to generate an indicator.
5566 * Indicators are small graphics that are generally used in two ways:
5567 *
5568 * - To draw attention to the status of an item. For example, an indicator might be
5569 * used to show that an item in a list has errors that need to be resolved.
5570 * - To clarify the function of a control that acts in an exceptional way (a button
5571 * that opens a menu instead of performing an action directly, for example).
5572 *
5573 * For a list of indicators included in the library, please see the
5574 * [OOjs UI documentation on MediaWiki] [1].
5575 *
5576 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
5577 *
5578 * @abstract
5579 * @class
5580 *
5581 * @constructor
5582 * @param {Object} [config] Configuration options
5583 * @cfg {jQuery} [$indicator] The indicator element created by the class. If this
5584 * configuration is omitted, the indicator element will use a generated `<span>`.
5585 * @cfg {string} [indicator] Symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
5586 * See the [OOjs UI documentation on MediaWiki][2] for a list of indicators included
5587 * in the library.
5588 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
5589 * @cfg {string|Function} [indicatorTitle] A text string used as the indicator title,
5590 * or a function that returns title text. The indicator title is displayed when users move
5591 * the mouse over the indicator.
5592 */
5593 OO.ui.mixin.IndicatorElement = function OoUiMixinIndicatorElement( config ) {
5594 // Configuration initialization
5595 config = config || {};
5596
5597 // Properties
5598 this.$indicator = null;
5599 this.indicator = null;
5600 this.indicatorTitle = null;
5601
5602 // Initialization
5603 this.setIndicator( config.indicator || this.constructor.static.indicator );
5604 this.setIndicatorTitle( config.indicatorTitle || this.constructor.static.indicatorTitle );
5605 this.setIndicatorElement( config.$indicator || $( '<span>' ) );
5606 };
5607
5608 /* Setup */
5609
5610 OO.initClass( OO.ui.mixin.IndicatorElement );
5611
5612 /* Static Properties */
5613
5614 /**
5615 * Symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
5616 * The static property will be overridden if the #indicator configuration is used.
5617 *
5618 * @static
5619 * @inheritable
5620 * @property {string|null}
5621 */
5622 OO.ui.mixin.IndicatorElement.static.indicator = null;
5623
5624 /**
5625 * A text string used as the indicator title, a function that returns title text, or `null`
5626 * for no title. The static property will be overridden if the #indicatorTitle configuration is used.
5627 *
5628 * @static
5629 * @inheritable
5630 * @property {string|Function|null}
5631 */
5632 OO.ui.mixin.IndicatorElement.static.indicatorTitle = null;
5633
5634 /* Methods */
5635
5636 /**
5637 * Set the indicator element.
5638 *
5639 * If an element is already set, it will be cleaned up before setting up the new element.
5640 *
5641 * @param {jQuery} $indicator Element to use as indicator
5642 */
5643 OO.ui.mixin.IndicatorElement.prototype.setIndicatorElement = function ( $indicator ) {
5644 if ( this.$indicator ) {
5645 this.$indicator
5646 .removeClass( 'oo-ui-indicatorElement-indicator oo-ui-indicator-' + this.indicator )
5647 .removeAttr( 'title' );
5648 }
5649
5650 this.$indicator = $indicator
5651 .addClass( 'oo-ui-indicatorElement-indicator' )
5652 .toggleClass( 'oo-ui-indicator-' + this.indicator, !!this.indicator );
5653 if ( this.indicatorTitle !== null ) {
5654 this.$indicator.attr( 'title', this.indicatorTitle );
5655 }
5656
5657 this.updateThemeClasses();
5658 };
5659
5660 /**
5661 * Set the indicator by its symbolic name: ‘alert’, ‘down’, ‘next’, ‘previous’, ‘required’, ‘up’. Use `null` to remove the indicator.
5662 *
5663 * @param {string|null} indicator Symbolic name of indicator, or `null` for no indicator
5664 * @chainable
5665 */
5666 OO.ui.mixin.IndicatorElement.prototype.setIndicator = function ( indicator ) {
5667 indicator = typeof indicator === 'string' && indicator.length ? indicator.trim() : null;
5668
5669 if ( this.indicator !== indicator ) {
5670 if ( this.$indicator ) {
5671 if ( this.indicator !== null ) {
5672 this.$indicator.removeClass( 'oo-ui-indicator-' + this.indicator );
5673 }
5674 if ( indicator !== null ) {
5675 this.$indicator.addClass( 'oo-ui-indicator-' + indicator );
5676 }
5677 }
5678 this.indicator = indicator;
5679 }
5680
5681 this.$element.toggleClass( 'oo-ui-indicatorElement', !!this.indicator );
5682 this.updateThemeClasses();
5683
5684 return this;
5685 };
5686
5687 /**
5688 * Set the indicator title.
5689 *
5690 * The title is displayed when a user moves the mouse over the indicator.
5691 *
5692 * @param {string|Function|null} indicator Indicator title text, a function that returns text, or
5693 * `null` for no indicator title
5694 * @chainable
5695 */
5696 OO.ui.mixin.IndicatorElement.prototype.setIndicatorTitle = function ( indicatorTitle ) {
5697 indicatorTitle = typeof indicatorTitle === 'function' ||
5698 ( typeof indicatorTitle === 'string' && indicatorTitle.length ) ?
5699 OO.ui.resolveMsg( indicatorTitle ) : null;
5700
5701 if ( this.indicatorTitle !== indicatorTitle ) {
5702 this.indicatorTitle = indicatorTitle;
5703 if ( this.$indicator ) {
5704 if ( this.indicatorTitle !== null ) {
5705 this.$indicator.attr( 'title', indicatorTitle );
5706 } else {
5707 this.$indicator.removeAttr( 'title' );
5708 }
5709 }
5710 }
5711
5712 return this;
5713 };
5714
5715 /**
5716 * Get the symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
5717 *
5718 * @return {string} Symbolic name of indicator
5719 */
5720 OO.ui.mixin.IndicatorElement.prototype.getIndicator = function () {
5721 return this.indicator;
5722 };
5723
5724 /**
5725 * Get the indicator title.
5726 *
5727 * The title is displayed when a user moves the mouse over the indicator.
5728 *
5729 * @return {string} Indicator title text
5730 */
5731 OO.ui.mixin.IndicatorElement.prototype.getIndicatorTitle = function () {
5732 return this.indicatorTitle;
5733 };
5734
5735 /**
5736 * LabelElement is often mixed into other classes to generate a label, which
5737 * helps identify the function of an interface element.
5738 * See the [OOjs UI documentation on MediaWiki] [1] for more information.
5739 *
5740 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Labels
5741 *
5742 * @abstract
5743 * @class
5744 *
5745 * @constructor
5746 * @param {Object} [config] Configuration options
5747 * @cfg {jQuery} [$label] The label element created by the class. If this
5748 * configuration is omitted, the label element will use a generated `<span>`.
5749 * @cfg {jQuery|string|Function|OO.ui.HtmlSnippet} [label] The label text. The label can be specified
5750 * as a plaintext string, a jQuery selection of elements, or a function that will produce a string
5751 * in the future. See the [OOjs UI documentation on MediaWiki] [2] for examples.
5752 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Labels
5753 * @cfg {boolean} [autoFitLabel=true] Fit the label to the width of the parent element.
5754 * The label will be truncated to fit if necessary.
5755 */
5756 OO.ui.mixin.LabelElement = function OoUiMixinLabelElement( config ) {
5757 // Configuration initialization
5758 config = config || {};
5759
5760 // Properties
5761 this.$label = null;
5762 this.label = null;
5763 this.autoFitLabel = config.autoFitLabel === undefined || !!config.autoFitLabel;
5764
5765 // Initialization
5766 this.setLabel( config.label || this.constructor.static.label );
5767 this.setLabelElement( config.$label || $( '<span>' ) );
5768 };
5769
5770 /* Setup */
5771
5772 OO.initClass( OO.ui.mixin.LabelElement );
5773
5774 /* Events */
5775
5776 /**
5777 * @event labelChange
5778 * @param {string} value
5779 */
5780
5781 /* Static Properties */
5782
5783 /**
5784 * The label text. The label can be specified as a plaintext string, a function that will
5785 * produce a string in the future, or `null` for no label. The static value will
5786 * be overridden if a label is specified with the #label config option.
5787 *
5788 * @static
5789 * @inheritable
5790 * @property {string|Function|null}
5791 */
5792 OO.ui.mixin.LabelElement.static.label = null;
5793
5794 /* Methods */
5795
5796 /**
5797 * Set the label element.
5798 *
5799 * If an element is already set, it will be cleaned up before setting up the new element.
5800 *
5801 * @param {jQuery} $label Element to use as label
5802 */
5803 OO.ui.mixin.LabelElement.prototype.setLabelElement = function ( $label ) {
5804 if ( this.$label ) {
5805 this.$label.removeClass( 'oo-ui-labelElement-label' ).empty();
5806 }
5807
5808 this.$label = $label.addClass( 'oo-ui-labelElement-label' );
5809 this.setLabelContent( this.label );
5810 };
5811
5812 /**
5813 * Set the label.
5814 *
5815 * An empty string will result in the label being hidden. A string containing only whitespace will
5816 * be converted to a single `&nbsp;`.
5817 *
5818 * @param {jQuery|string|OO.ui.HtmlSnippet|Function|null} label Label nodes; text; a function that returns nodes or
5819 * text; or null for no label
5820 * @chainable
5821 */
5822 OO.ui.mixin.LabelElement.prototype.setLabel = function ( label ) {
5823 label = typeof label === 'function' ? OO.ui.resolveMsg( label ) : label;
5824 label = ( ( typeof label === 'string' && label.length ) || label instanceof jQuery || label instanceof OO.ui.HtmlSnippet ) ? label : null;
5825
5826 this.$element.toggleClass( 'oo-ui-labelElement', !!label );
5827
5828 if ( this.label !== label ) {
5829 if ( this.$label ) {
5830 this.setLabelContent( label );
5831 }
5832 this.label = label;
5833 this.emit( 'labelChange' );
5834 }
5835
5836 return this;
5837 };
5838
5839 /**
5840 * Get the label.
5841 *
5842 * @return {jQuery|string|Function|null} Label nodes; text; a function that returns nodes or
5843 * text; or null for no label
5844 */
5845 OO.ui.mixin.LabelElement.prototype.getLabel = function () {
5846 return this.label;
5847 };
5848
5849 /**
5850 * Fit the label.
5851 *
5852 * @chainable
5853 */
5854 OO.ui.mixin.LabelElement.prototype.fitLabel = function () {
5855 if ( this.$label && this.$label.autoEllipsis && this.autoFitLabel ) {
5856 this.$label.autoEllipsis( { hasSpan: false, tooltip: true } );
5857 }
5858
5859 return this;
5860 };
5861
5862 /**
5863 * Set the content of the label.
5864 *
5865 * Do not call this method until after the label element has been set by #setLabelElement.
5866 *
5867 * @private
5868 * @param {jQuery|string|Function|null} label Label nodes; text; a function that returns nodes or
5869 * text; or null for no label
5870 */
5871 OO.ui.mixin.LabelElement.prototype.setLabelContent = function ( label ) {
5872 if ( typeof label === 'string' ) {
5873 if ( label.match( /^\s*$/ ) ) {
5874 // Convert whitespace only string to a single non-breaking space
5875 this.$label.html( '&nbsp;' );
5876 } else {
5877 this.$label.text( label );
5878 }
5879 } else if ( label instanceof OO.ui.HtmlSnippet ) {
5880 this.$label.html( label.toString() );
5881 } else if ( label instanceof jQuery ) {
5882 this.$label.empty().append( label );
5883 } else {
5884 this.$label.empty();
5885 }
5886 };
5887
5888 /**
5889 * LookupElement is a mixin that creates a {@link OO.ui.FloatingMenuSelectWidget menu} of suggested values for
5890 * a {@link OO.ui.TextInputWidget text input widget}. Suggested values are based on the characters the user types
5891 * into the text input field and, in general, the menu is only displayed when the user types. If a suggested value is chosen
5892 * from the lookup menu, that value becomes the value of the input field.
5893 *
5894 * Note that a new menu of suggested items is displayed when a value is chosen from the lookup menu. If this is
5895 * not the desired behavior, disable lookup menus with the #setLookupsDisabled method, then set the value, then
5896 * re-enable lookups.
5897 *
5898 * See the [OOjs UI demos][1] for an example.
5899 *
5900 * [1]: https://tools.wmflabs.org/oojs-ui/oojs-ui/demos/index.html#widgets-apex-vector-ltr
5901 *
5902 * @class
5903 * @abstract
5904 *
5905 * @constructor
5906 * @param {Object} [config] Configuration options
5907 * @cfg {jQuery} [$overlay] Overlay for the lookup menu; defaults to relative positioning
5908 * @cfg {jQuery} [$container=this.$element] The container element. The lookup menu is rendered beneath the specified element.
5909 * @cfg {boolean} [allowSuggestionsWhenEmpty=false] Request and display a lookup menu when the text input is empty.
5910 * By default, the lookup menu is not generated and displayed until the user begins to type.
5911 * @cfg {boolean} [highlightFirst=true] Whether the first lookup result should be highlighted (so, that the user can
5912 * take it over into the input with simply pressing return) automatically or not.
5913 */
5914 OO.ui.mixin.LookupElement = function OoUiMixinLookupElement( config ) {
5915 // Configuration initialization
5916 config = $.extend( { highlightFirst: true }, config );
5917
5918 // Properties
5919 this.$overlay = config.$overlay || this.$element;
5920 this.lookupMenu = new OO.ui.FloatingMenuSelectWidget( {
5921 widget: this,
5922 input: this,
5923 $container: config.$container || this.$element
5924 } );
5925
5926 this.allowSuggestionsWhenEmpty = config.allowSuggestionsWhenEmpty || false;
5927
5928 this.lookupCache = {};
5929 this.lookupQuery = null;
5930 this.lookupRequest = null;
5931 this.lookupsDisabled = false;
5932 this.lookupInputFocused = false;
5933 this.lookupHighlightFirstItem = config.highlightFirst;
5934
5935 // Events
5936 this.$input.on( {
5937 focus: this.onLookupInputFocus.bind( this ),
5938 blur: this.onLookupInputBlur.bind( this ),
5939 mousedown: this.onLookupInputMouseDown.bind( this )
5940 } );
5941 this.connect( this, { change: 'onLookupInputChange' } );
5942 this.lookupMenu.connect( this, {
5943 toggle: 'onLookupMenuToggle',
5944 choose: 'onLookupMenuItemChoose'
5945 } );
5946
5947 // Initialization
5948 this.$element.addClass( 'oo-ui-lookupElement' );
5949 this.lookupMenu.$element.addClass( 'oo-ui-lookupElement-menu' );
5950 this.$overlay.append( this.lookupMenu.$element );
5951 };
5952
5953 /* Methods */
5954
5955 /**
5956 * Handle input focus event.
5957 *
5958 * @protected
5959 * @param {jQuery.Event} e Input focus event
5960 */
5961 OO.ui.mixin.LookupElement.prototype.onLookupInputFocus = function () {
5962 this.lookupInputFocused = true;
5963 this.populateLookupMenu();
5964 };
5965
5966 /**
5967 * Handle input blur event.
5968 *
5969 * @protected
5970 * @param {jQuery.Event} e Input blur event
5971 */
5972 OO.ui.mixin.LookupElement.prototype.onLookupInputBlur = function () {
5973 this.closeLookupMenu();
5974 this.lookupInputFocused = false;
5975 };
5976
5977 /**
5978 * Handle input mouse down event.
5979 *
5980 * @protected
5981 * @param {jQuery.Event} e Input mouse down event
5982 */
5983 OO.ui.mixin.LookupElement.prototype.onLookupInputMouseDown = function () {
5984 // Only open the menu if the input was already focused.
5985 // This way we allow the user to open the menu again after closing it with Esc
5986 // by clicking in the input. Opening (and populating) the menu when initially
5987 // clicking into the input is handled by the focus handler.
5988 if ( this.lookupInputFocused && !this.lookupMenu.isVisible() ) {
5989 this.populateLookupMenu();
5990 }
5991 };
5992
5993 /**
5994 * Handle input change event.
5995 *
5996 * @protected
5997 * @param {string} value New input value
5998 */
5999 OO.ui.mixin.LookupElement.prototype.onLookupInputChange = function () {
6000 if ( this.lookupInputFocused ) {
6001 this.populateLookupMenu();
6002 }
6003 };
6004
6005 /**
6006 * Handle the lookup menu being shown/hidden.
6007 *
6008 * @protected
6009 * @param {boolean} visible Whether the lookup menu is now visible.
6010 */
6011 OO.ui.mixin.LookupElement.prototype.onLookupMenuToggle = function ( visible ) {
6012 if ( !visible ) {
6013 // When the menu is hidden, abort any active request and clear the menu.
6014 // This has to be done here in addition to closeLookupMenu(), because
6015 // MenuSelectWidget will close itself when the user presses Esc.
6016 this.abortLookupRequest();
6017 this.lookupMenu.clearItems();
6018 }
6019 };
6020
6021 /**
6022 * Handle menu item 'choose' event, updating the text input value to the value of the clicked item.
6023 *
6024 * @protected
6025 * @param {OO.ui.MenuOptionWidget} item Selected item
6026 */
6027 OO.ui.mixin.LookupElement.prototype.onLookupMenuItemChoose = function ( item ) {
6028 this.setValue( item.getData() );
6029 };
6030
6031 /**
6032 * Get lookup menu.
6033 *
6034 * @private
6035 * @return {OO.ui.FloatingMenuSelectWidget}
6036 */
6037 OO.ui.mixin.LookupElement.prototype.getLookupMenu = function () {
6038 return this.lookupMenu;
6039 };
6040
6041 /**
6042 * Disable or re-enable lookups.
6043 *
6044 * When lookups are disabled, calls to #populateLookupMenu will be ignored.
6045 *
6046 * @param {boolean} disabled Disable lookups
6047 */
6048 OO.ui.mixin.LookupElement.prototype.setLookupsDisabled = function ( disabled ) {
6049 this.lookupsDisabled = !!disabled;
6050 };
6051
6052 /**
6053 * Open the menu. If there are no entries in the menu, this does nothing.
6054 *
6055 * @private
6056 * @chainable
6057 */
6058 OO.ui.mixin.LookupElement.prototype.openLookupMenu = function () {
6059 if ( !this.lookupMenu.isEmpty() ) {
6060 this.lookupMenu.toggle( true );
6061 }
6062 return this;
6063 };
6064
6065 /**
6066 * Close the menu, empty it, and abort any pending request.
6067 *
6068 * @private
6069 * @chainable
6070 */
6071 OO.ui.mixin.LookupElement.prototype.closeLookupMenu = function () {
6072 this.lookupMenu.toggle( false );
6073 this.abortLookupRequest();
6074 this.lookupMenu.clearItems();
6075 return this;
6076 };
6077
6078 /**
6079 * Request menu items based on the input's current value, and when they arrive,
6080 * populate the menu with these items and show the menu.
6081 *
6082 * If lookups have been disabled with #setLookupsDisabled, this function does nothing.
6083 *
6084 * @private
6085 * @chainable
6086 */
6087 OO.ui.mixin.LookupElement.prototype.populateLookupMenu = function () {
6088 var widget = this,
6089 value = this.getValue();
6090
6091 if ( this.lookupsDisabled || this.isReadOnly() ) {
6092 return;
6093 }
6094
6095 // If the input is empty, clear the menu, unless suggestions when empty are allowed.
6096 if ( !this.allowSuggestionsWhenEmpty && value === '' ) {
6097 this.closeLookupMenu();
6098 // Skip population if there is already a request pending for the current value
6099 } else if ( value !== this.lookupQuery ) {
6100 this.getLookupMenuItems()
6101 .done( function ( items ) {
6102 widget.lookupMenu.clearItems();
6103 if ( items.length ) {
6104 widget.lookupMenu
6105 .addItems( items )
6106 .toggle( true );
6107 widget.initializeLookupMenuSelection();
6108 } else {
6109 widget.lookupMenu.toggle( false );
6110 }
6111 } )
6112 .fail( function () {
6113 widget.lookupMenu.clearItems();
6114 } );
6115 }
6116
6117 return this;
6118 };
6119
6120 /**
6121 * Highlight the first selectable item in the menu, if configured.
6122 *
6123 * @private
6124 * @chainable
6125 */
6126 OO.ui.mixin.LookupElement.prototype.initializeLookupMenuSelection = function () {
6127 if ( this.lookupHighlightFirstItem && !this.lookupMenu.getSelectedItem() ) {
6128 this.lookupMenu.highlightItem( this.lookupMenu.getFirstSelectableItem() );
6129 }
6130 };
6131
6132 /**
6133 * Get lookup menu items for the current query.
6134 *
6135 * @private
6136 * @return {jQuery.Promise} Promise object which will be passed menu items as the first argument of
6137 * the done event. If the request was aborted to make way for a subsequent request, this promise
6138 * will not be rejected: it will remain pending forever.
6139 */
6140 OO.ui.mixin.LookupElement.prototype.getLookupMenuItems = function () {
6141 var widget = this,
6142 value = this.getValue(),
6143 deferred = $.Deferred(),
6144 ourRequest;
6145
6146 this.abortLookupRequest();
6147 if ( Object.prototype.hasOwnProperty.call( this.lookupCache, value ) ) {
6148 deferred.resolve( this.getLookupMenuOptionsFromData( this.lookupCache[ value ] ) );
6149 } else {
6150 this.pushPending();
6151 this.lookupQuery = value;
6152 ourRequest = this.lookupRequest = this.getLookupRequest();
6153 ourRequest
6154 .always( function () {
6155 // We need to pop pending even if this is an old request, otherwise
6156 // the widget will remain pending forever.
6157 // TODO: this assumes that an aborted request will fail or succeed soon after
6158 // being aborted, or at least eventually. It would be nice if we could popPending()
6159 // at abort time, but only if we knew that we hadn't already called popPending()
6160 // for that request.
6161 widget.popPending();
6162 } )
6163 .done( function ( response ) {
6164 // If this is an old request (and aborting it somehow caused it to still succeed),
6165 // ignore its success completely
6166 if ( ourRequest === widget.lookupRequest ) {
6167 widget.lookupQuery = null;
6168 widget.lookupRequest = null;
6169 widget.lookupCache[ value ] = widget.getLookupCacheDataFromResponse( response );
6170 deferred.resolve( widget.getLookupMenuOptionsFromData( widget.lookupCache[ value ] ) );
6171 }
6172 } )
6173 .fail( function () {
6174 // If this is an old request (or a request failing because it's being aborted),
6175 // ignore its failure completely
6176 if ( ourRequest === widget.lookupRequest ) {
6177 widget.lookupQuery = null;
6178 widget.lookupRequest = null;
6179 deferred.reject();
6180 }
6181 } );
6182 }
6183 return deferred.promise();
6184 };
6185
6186 /**
6187 * Abort the currently pending lookup request, if any.
6188 *
6189 * @private
6190 */
6191 OO.ui.mixin.LookupElement.prototype.abortLookupRequest = function () {
6192 var oldRequest = this.lookupRequest;
6193 if ( oldRequest ) {
6194 // First unset this.lookupRequest to the fail handler will notice
6195 // that the request is no longer current
6196 this.lookupRequest = null;
6197 this.lookupQuery = null;
6198 oldRequest.abort();
6199 }
6200 };
6201
6202 /**
6203 * Get a new request object of the current lookup query value.
6204 *
6205 * @protected
6206 * @abstract
6207 * @return {jQuery.Promise} jQuery AJAX object, or promise object with an .abort() method
6208 */
6209 OO.ui.mixin.LookupElement.prototype.getLookupRequest = function () {
6210 // Stub, implemented in subclass
6211 return null;
6212 };
6213
6214 /**
6215 * Pre-process data returned by the request from #getLookupRequest.
6216 *
6217 * The return value of this function will be cached, and any further queries for the given value
6218 * will use the cache rather than doing API requests.
6219 *
6220 * @protected
6221 * @abstract
6222 * @param {Mixed} response Response from server
6223 * @return {Mixed} Cached result data
6224 */
6225 OO.ui.mixin.LookupElement.prototype.getLookupCacheDataFromResponse = function () {
6226 // Stub, implemented in subclass
6227 return [];
6228 };
6229
6230 /**
6231 * Get a list of menu option widgets from the (possibly cached) data returned by
6232 * #getLookupCacheDataFromResponse.
6233 *
6234 * @protected
6235 * @abstract
6236 * @param {Mixed} data Cached result data, usually an array
6237 * @return {OO.ui.MenuOptionWidget[]} Menu items
6238 */
6239 OO.ui.mixin.LookupElement.prototype.getLookupMenuOptionsFromData = function () {
6240 // Stub, implemented in subclass
6241 return [];
6242 };
6243
6244 /**
6245 * Set the read-only state of the widget.
6246 *
6247 * This will also disable/enable the lookups functionality.
6248 *
6249 * @param {boolean} readOnly Make input read-only
6250 * @chainable
6251 */
6252 OO.ui.mixin.LookupElement.prototype.setReadOnly = function ( readOnly ) {
6253 // Parent method
6254 // Note: Calling #setReadOnly this way assumes this is mixed into an OO.ui.TextInputWidget
6255 OO.ui.TextInputWidget.prototype.setReadOnly.call( this, readOnly );
6256
6257 // During construction, #setReadOnly is called before the OO.ui.mixin.LookupElement constructor
6258 if ( this.isReadOnly() && this.lookupMenu ) {
6259 this.closeLookupMenu();
6260 }
6261
6262 return this;
6263 };
6264
6265 /**
6266 * PopupElement is mixed into other classes to generate a {@link OO.ui.PopupWidget popup widget}.
6267 * A popup is a container for content. It is overlaid and positioned absolutely. By default, each
6268 * popup has an anchor, which is an arrow-like protrusion that points toward the popup’s origin.
6269 * See {@link OO.ui.PopupWidget PopupWidget} for an example.
6270 *
6271 * @abstract
6272 * @class
6273 *
6274 * @constructor
6275 * @param {Object} [config] Configuration options
6276 * @cfg {Object} [popup] Configuration to pass to popup
6277 * @cfg {boolean} [popup.autoClose=true] Popup auto-closes when it loses focus
6278 */
6279 OO.ui.mixin.PopupElement = function OoUiMixinPopupElement( config ) {
6280 // Configuration initialization
6281 config = config || {};
6282
6283 // Properties
6284 this.popup = new OO.ui.PopupWidget( $.extend(
6285 { autoClose: true },
6286 config.popup,
6287 { $autoCloseIgnore: this.$element }
6288 ) );
6289 };
6290
6291 /* Methods */
6292
6293 /**
6294 * Get popup.
6295 *
6296 * @return {OO.ui.PopupWidget} Popup widget
6297 */
6298 OO.ui.mixin.PopupElement.prototype.getPopup = function () {
6299 return this.popup;
6300 };
6301
6302 /**
6303 * The FlaggedElement class is an attribute mixin, meaning that it is used to add
6304 * additional functionality to an element created by another class. The class provides
6305 * a ‘flags’ property assigned the name (or an array of names) of styling flags,
6306 * which are used to customize the look and feel of a widget to better describe its
6307 * importance and functionality.
6308 *
6309 * The library currently contains the following styling flags for general use:
6310 *
6311 * - **progressive**: Progressive styling is applied to convey that the widget will move the user forward in a process.
6312 * - **destructive**: Destructive styling is applied to convey that the widget will remove something.
6313 * - **constructive**: Constructive styling is applied to convey that the widget will create something.
6314 *
6315 * The flags affect the appearance of the buttons:
6316 *
6317 * @example
6318 * // FlaggedElement is mixed into ButtonWidget to provide styling flags
6319 * var button1 = new OO.ui.ButtonWidget( {
6320 * label: 'Constructive',
6321 * flags: 'constructive'
6322 * } );
6323 * var button2 = new OO.ui.ButtonWidget( {
6324 * label: 'Destructive',
6325 * flags: 'destructive'
6326 * } );
6327 * var button3 = new OO.ui.ButtonWidget( {
6328 * label: 'Progressive',
6329 * flags: 'progressive'
6330 * } );
6331 * $( 'body' ).append( button1.$element, button2.$element, button3.$element );
6332 *
6333 * {@link OO.ui.ActionWidget ActionWidgets}, which are a special kind of button that execute an action, use these flags: **primary** and **safe**.
6334 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information.
6335 *
6336 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Flagged
6337 *
6338 * @abstract
6339 * @class
6340 *
6341 * @constructor
6342 * @param {Object} [config] Configuration options
6343 * @cfg {string|string[]} [flags] The name or names of the flags (e.g., 'constructive' or 'primary') to apply.
6344 * Please see the [OOjs UI documentation on MediaWiki] [2] for more information about available flags.
6345 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Flagged
6346 * @cfg {jQuery} [$flagged] The flagged element. By default,
6347 * the flagged functionality is applied to the element created by the class ($element).
6348 * If a different element is specified, the flagged functionality will be applied to it instead.
6349 */
6350 OO.ui.mixin.FlaggedElement = function OoUiMixinFlaggedElement( config ) {
6351 // Configuration initialization
6352 config = config || {};
6353
6354 // Properties
6355 this.flags = {};
6356 this.$flagged = null;
6357
6358 // Initialization
6359 this.setFlags( config.flags );
6360 this.setFlaggedElement( config.$flagged || this.$element );
6361 };
6362
6363 /* Events */
6364
6365 /**
6366 * @event flag
6367 * A flag event is emitted when the #clearFlags or #setFlags methods are used. The `changes`
6368 * parameter contains the name of each modified flag and indicates whether it was
6369 * added or removed.
6370 *
6371 * @param {Object.<string,boolean>} changes Object keyed by flag name. A Boolean `true` indicates
6372 * that the flag was added, `false` that the flag was removed.
6373 */
6374
6375 /* Methods */
6376
6377 /**
6378 * Set the flagged element.
6379 *
6380 * This method is used to retarget a flagged mixin so that its functionality applies to the specified element.
6381 * If an element is already set, the method will remove the mixin’s effect on that element.
6382 *
6383 * @param {jQuery} $flagged Element that should be flagged
6384 */
6385 OO.ui.mixin.FlaggedElement.prototype.setFlaggedElement = function ( $flagged ) {
6386 var classNames = Object.keys( this.flags ).map( function ( flag ) {
6387 return 'oo-ui-flaggedElement-' + flag;
6388 } ).join( ' ' );
6389
6390 if ( this.$flagged ) {
6391 this.$flagged.removeClass( classNames );
6392 }
6393
6394 this.$flagged = $flagged.addClass( classNames );
6395 };
6396
6397 /**
6398 * Check if the specified flag is set.
6399 *
6400 * @param {string} flag Name of flag
6401 * @return {boolean} The flag is set
6402 */
6403 OO.ui.mixin.FlaggedElement.prototype.hasFlag = function ( flag ) {
6404 // This may be called before the constructor, thus before this.flags is set
6405 return this.flags && ( flag in this.flags );
6406 };
6407
6408 /**
6409 * Get the names of all flags set.
6410 *
6411 * @return {string[]} Flag names
6412 */
6413 OO.ui.mixin.FlaggedElement.prototype.getFlags = function () {
6414 // This may be called before the constructor, thus before this.flags is set
6415 return Object.keys( this.flags || {} );
6416 };
6417
6418 /**
6419 * Clear all flags.
6420 *
6421 * @chainable
6422 * @fires flag
6423 */
6424 OO.ui.mixin.FlaggedElement.prototype.clearFlags = function () {
6425 var flag, className,
6426 changes = {},
6427 remove = [],
6428 classPrefix = 'oo-ui-flaggedElement-';
6429
6430 for ( flag in this.flags ) {
6431 className = classPrefix + flag;
6432 changes[ flag ] = false;
6433 delete this.flags[ flag ];
6434 remove.push( className );
6435 }
6436
6437 if ( this.$flagged ) {
6438 this.$flagged.removeClass( remove.join( ' ' ) );
6439 }
6440
6441 this.updateThemeClasses();
6442 this.emit( 'flag', changes );
6443
6444 return this;
6445 };
6446
6447 /**
6448 * Add one or more flags.
6449 *
6450 * @param {string|string[]|Object.<string, boolean>} flags A flag name, an array of flag names,
6451 * or an object keyed by flag name with a boolean value that indicates whether the flag should
6452 * be added (`true`) or removed (`false`).
6453 * @chainable
6454 * @fires flag
6455 */
6456 OO.ui.mixin.FlaggedElement.prototype.setFlags = function ( flags ) {
6457 var i, len, flag, className,
6458 changes = {},
6459 add = [],
6460 remove = [],
6461 classPrefix = 'oo-ui-flaggedElement-';
6462
6463 if ( typeof flags === 'string' ) {
6464 className = classPrefix + flags;
6465 // Set
6466 if ( !this.flags[ flags ] ) {
6467 this.flags[ flags ] = true;
6468 add.push( className );
6469 }
6470 } else if ( Array.isArray( flags ) ) {
6471 for ( i = 0, len = flags.length; i < len; i++ ) {
6472 flag = flags[ i ];
6473 className = classPrefix + flag;
6474 // Set
6475 if ( !this.flags[ flag ] ) {
6476 changes[ flag ] = true;
6477 this.flags[ flag ] = true;
6478 add.push( className );
6479 }
6480 }
6481 } else if ( OO.isPlainObject( flags ) ) {
6482 for ( flag in flags ) {
6483 className = classPrefix + flag;
6484 if ( flags[ flag ] ) {
6485 // Set
6486 if ( !this.flags[ flag ] ) {
6487 changes[ flag ] = true;
6488 this.flags[ flag ] = true;
6489 add.push( className );
6490 }
6491 } else {
6492 // Remove
6493 if ( this.flags[ flag ] ) {
6494 changes[ flag ] = false;
6495 delete this.flags[ flag ];
6496 remove.push( className );
6497 }
6498 }
6499 }
6500 }
6501
6502 if ( this.$flagged ) {
6503 this.$flagged
6504 .addClass( add.join( ' ' ) )
6505 .removeClass( remove.join( ' ' ) );
6506 }
6507
6508 this.updateThemeClasses();
6509 this.emit( 'flag', changes );
6510
6511 return this;
6512 };
6513
6514 /**
6515 * TitledElement is mixed into other classes to provide a `title` attribute.
6516 * Titles are rendered by the browser and are made visible when the user moves
6517 * the mouse over the element. Titles are not visible on touch devices.
6518 *
6519 * @example
6520 * // TitledElement provides a 'title' attribute to the
6521 * // ButtonWidget class
6522 * var button = new OO.ui.ButtonWidget( {
6523 * label: 'Button with Title',
6524 * title: 'I am a button'
6525 * } );
6526 * $( 'body' ).append( button.$element );
6527 *
6528 * @abstract
6529 * @class
6530 *
6531 * @constructor
6532 * @param {Object} [config] Configuration options
6533 * @cfg {jQuery} [$titled] The element to which the `title` attribute is applied.
6534 * If this config is omitted, the title functionality is applied to $element, the
6535 * element created by the class.
6536 * @cfg {string|Function} [title] The title text or a function that returns text. If
6537 * this config is omitted, the value of the {@link #static-title static title} property is used.
6538 */
6539 OO.ui.mixin.TitledElement = function OoUiMixinTitledElement( config ) {
6540 // Configuration initialization
6541 config = config || {};
6542
6543 // Properties
6544 this.$titled = null;
6545 this.title = null;
6546
6547 // Initialization
6548 this.setTitle( config.title || this.constructor.static.title );
6549 this.setTitledElement( config.$titled || this.$element );
6550 };
6551
6552 /* Setup */
6553
6554 OO.initClass( OO.ui.mixin.TitledElement );
6555
6556 /* Static Properties */
6557
6558 /**
6559 * The title text, a function that returns text, or `null` for no title. The value of the static property
6560 * is overridden if the #title config option is used.
6561 *
6562 * @static
6563 * @inheritable
6564 * @property {string|Function|null}
6565 */
6566 OO.ui.mixin.TitledElement.static.title = null;
6567
6568 /* Methods */
6569
6570 /**
6571 * Set the titled element.
6572 *
6573 * This method is used to retarget a titledElement mixin so that its functionality applies to the specified element.
6574 * If an element is already set, the mixin’s effect on that element is removed before the new element is set up.
6575 *
6576 * @param {jQuery} $titled Element that should use the 'titled' functionality
6577 */
6578 OO.ui.mixin.TitledElement.prototype.setTitledElement = function ( $titled ) {
6579 if ( this.$titled ) {
6580 this.$titled.removeAttr( 'title' );
6581 }
6582
6583 this.$titled = $titled;
6584 if ( this.title ) {
6585 this.$titled.attr( 'title', this.title );
6586 }
6587 };
6588
6589 /**
6590 * Set title.
6591 *
6592 * @param {string|Function|null} title Title text, a function that returns text, or `null` for no title
6593 * @chainable
6594 */
6595 OO.ui.mixin.TitledElement.prototype.setTitle = function ( title ) {
6596 title = typeof title === 'string' ? OO.ui.resolveMsg( title ) : null;
6597
6598 if ( this.title !== title ) {
6599 if ( this.$titled ) {
6600 if ( title !== null ) {
6601 this.$titled.attr( 'title', title );
6602 } else {
6603 this.$titled.removeAttr( 'title' );
6604 }
6605 }
6606 this.title = title;
6607 }
6608
6609 return this;
6610 };
6611
6612 /**
6613 * Get title.
6614 *
6615 * @return {string} Title string
6616 */
6617 OO.ui.mixin.TitledElement.prototype.getTitle = function () {
6618 return this.title;
6619 };
6620
6621 /**
6622 * Element that can be automatically clipped to visible boundaries.
6623 *
6624 * Whenever the element's natural height changes, you have to call
6625 * {@link OO.ui.mixin.ClippableElement#clip} to make sure it's still
6626 * clipping correctly.
6627 *
6628 * The dimensions of #$clippableContainer will be compared to the boundaries of the
6629 * nearest scrollable container. If #$clippableContainer is too tall and/or too wide,
6630 * then #$clippable will be given a fixed reduced height and/or width and will be made
6631 * scrollable. By default, #$clippable and #$clippableContainer are the same element,
6632 * but you can build a static footer by setting #$clippableContainer to an element that contains
6633 * #$clippable and the footer.
6634 *
6635 * @abstract
6636 * @class
6637 *
6638 * @constructor
6639 * @param {Object} [config] Configuration options
6640 * @cfg {jQuery} [$clippable] Node to clip, assigned to #$clippable, omit to use #$element
6641 * @cfg {jQuery} [$clippableContainer] Node to keep visible, assigned to #$clippableContainer,
6642 * omit to use #$clippable
6643 */
6644 OO.ui.mixin.ClippableElement = function OoUiMixinClippableElement( config ) {
6645 // Configuration initialization
6646 config = config || {};
6647
6648 // Properties
6649 this.$clippable = null;
6650 this.$clippableContainer = null;
6651 this.clipping = false;
6652 this.clippedHorizontally = false;
6653 this.clippedVertically = false;
6654 this.$clippableScrollableContainer = null;
6655 this.$clippableScroller = null;
6656 this.$clippableWindow = null;
6657 this.idealWidth = null;
6658 this.idealHeight = null;
6659 this.onClippableScrollHandler = this.clip.bind( this );
6660 this.onClippableWindowResizeHandler = this.clip.bind( this );
6661
6662 // Initialization
6663 if ( config.$clippableContainer ) {
6664 this.setClippableContainer( config.$clippableContainer );
6665 }
6666 this.setClippableElement( config.$clippable || this.$element );
6667 };
6668
6669 /* Methods */
6670
6671 /**
6672 * Set clippable element.
6673 *
6674 * If an element is already set, it will be cleaned up before setting up the new element.
6675 *
6676 * @param {jQuery} $clippable Element to make clippable
6677 */
6678 OO.ui.mixin.ClippableElement.prototype.setClippableElement = function ( $clippable ) {
6679 if ( this.$clippable ) {
6680 this.$clippable.removeClass( 'oo-ui-clippableElement-clippable' );
6681 this.$clippable.css( { width: '', height: '', overflowX: '', overflowY: '' } );
6682 OO.ui.Element.static.reconsiderScrollbars( this.$clippable[ 0 ] );
6683 }
6684
6685 this.$clippable = $clippable.addClass( 'oo-ui-clippableElement-clippable' );
6686 this.clip();
6687 };
6688
6689 /**
6690 * Set clippable container.
6691 *
6692 * This is the container that will be measured when deciding whether to clip. When clipping,
6693 * #$clippable will be resized in order to keep the clippable container fully visible.
6694 *
6695 * If the clippable container is unset, #$clippable will be used.
6696 *
6697 * @param {jQuery|null} $clippableContainer Container to keep visible, or null to unset
6698 */
6699 OO.ui.mixin.ClippableElement.prototype.setClippableContainer = function ( $clippableContainer ) {
6700 this.$clippableContainer = $clippableContainer;
6701 if ( this.$clippable ) {
6702 this.clip();
6703 }
6704 };
6705
6706 /**
6707 * Toggle clipping.
6708 *
6709 * Do not turn clipping on until after the element is attached to the DOM and visible.
6710 *
6711 * @param {boolean} [clipping] Enable clipping, omit to toggle
6712 * @chainable
6713 */
6714 OO.ui.mixin.ClippableElement.prototype.toggleClipping = function ( clipping ) {
6715 clipping = clipping === undefined ? !this.clipping : !!clipping;
6716
6717 if ( this.clipping !== clipping ) {
6718 this.clipping = clipping;
6719 if ( clipping ) {
6720 this.$clippableScrollableContainer = $( this.getClosestScrollableElementContainer() );
6721 // If the clippable container is the root, we have to listen to scroll events and check
6722 // jQuery.scrollTop on the window because of browser inconsistencies
6723 this.$clippableScroller = this.$clippableScrollableContainer.is( 'html, body' ) ?
6724 $( OO.ui.Element.static.getWindow( this.$clippableScrollableContainer ) ) :
6725 this.$clippableScrollableContainer;
6726 this.$clippableScroller.on( 'scroll', this.onClippableScrollHandler );
6727 this.$clippableWindow = $( this.getElementWindow() )
6728 .on( 'resize', this.onClippableWindowResizeHandler );
6729 // Initial clip after visible
6730 this.clip();
6731 } else {
6732 this.$clippable.css( { width: '', height: '', overflowX: '', overflowY: '' } );
6733 OO.ui.Element.static.reconsiderScrollbars( this.$clippable[ 0 ] );
6734
6735 this.$clippableScrollableContainer = null;
6736 this.$clippableScroller.off( 'scroll', this.onClippableScrollHandler );
6737 this.$clippableScroller = null;
6738 this.$clippableWindow.off( 'resize', this.onClippableWindowResizeHandler );
6739 this.$clippableWindow = null;
6740 }
6741 }
6742
6743 return this;
6744 };
6745
6746 /**
6747 * Check if the element will be clipped to fit the visible area of the nearest scrollable container.
6748 *
6749 * @return {boolean} Element will be clipped to the visible area
6750 */
6751 OO.ui.mixin.ClippableElement.prototype.isClipping = function () {
6752 return this.clipping;
6753 };
6754
6755 /**
6756 * Check if the bottom or right of the element is being clipped by the nearest scrollable container.
6757 *
6758 * @return {boolean} Part of the element is being clipped
6759 */
6760 OO.ui.mixin.ClippableElement.prototype.isClipped = function () {
6761 return this.clippedHorizontally || this.clippedVertically;
6762 };
6763
6764 /**
6765 * Check if the right of the element is being clipped by the nearest scrollable container.
6766 *
6767 * @return {boolean} Part of the element is being clipped
6768 */
6769 OO.ui.mixin.ClippableElement.prototype.isClippedHorizontally = function () {
6770 return this.clippedHorizontally;
6771 };
6772
6773 /**
6774 * Check if the bottom of the element is being clipped by the nearest scrollable container.
6775 *
6776 * @return {boolean} Part of the element is being clipped
6777 */
6778 OO.ui.mixin.ClippableElement.prototype.isClippedVertically = function () {
6779 return this.clippedVertically;
6780 };
6781
6782 /**
6783 * Set the ideal size. These are the dimensions the element will have when it's not being clipped.
6784 *
6785 * @param {number|string} [width] Width as a number of pixels or CSS string with unit suffix
6786 * @param {number|string} [height] Height as a number of pixels or CSS string with unit suffix
6787 */
6788 OO.ui.mixin.ClippableElement.prototype.setIdealSize = function ( width, height ) {
6789 this.idealWidth = width;
6790 this.idealHeight = height;
6791
6792 if ( !this.clipping ) {
6793 // Update dimensions
6794 this.$clippable.css( { width: width, height: height } );
6795 }
6796 // While clipping, idealWidth and idealHeight are not considered
6797 };
6798
6799 /**
6800 * Clip element to visible boundaries and allow scrolling when needed. Call this method when
6801 * the element's natural height changes.
6802 *
6803 * Element will be clipped the bottom or right of the element is within 10px of the edge of, or
6804 * overlapped by, the visible area of the nearest scrollable container.
6805 *
6806 * @chainable
6807 */
6808 OO.ui.mixin.ClippableElement.prototype.clip = function () {
6809 var $container, extraHeight, extraWidth, ccOffset,
6810 $scrollableContainer, scOffset, scHeight, scWidth,
6811 ccWidth, scrollerIsWindow, scrollTop, scrollLeft,
6812 desiredWidth, desiredHeight, allotedWidth, allotedHeight,
6813 naturalWidth, naturalHeight, clipWidth, clipHeight,
6814 buffer = 7; // Chosen by fair dice roll
6815
6816 if ( !this.clipping ) {
6817 // this.$clippableScrollableContainer and this.$clippableWindow are null, so the below will fail
6818 return this;
6819 }
6820
6821 $container = this.$clippableContainer || this.$clippable;
6822 extraHeight = $container.outerHeight() - this.$clippable.outerHeight();
6823 extraWidth = $container.outerWidth() - this.$clippable.outerWidth();
6824 ccOffset = $container.offset();
6825 $scrollableContainer = this.$clippableScrollableContainer.is( 'html, body' ) ?
6826 this.$clippableWindow : this.$clippableScrollableContainer;
6827 scOffset = $scrollableContainer.offset() || { top: 0, left: 0 };
6828 scHeight = $scrollableContainer.innerHeight() - buffer;
6829 scWidth = $scrollableContainer.innerWidth() - buffer;
6830 ccWidth = $container.outerWidth() + buffer;
6831 scrollerIsWindow = this.$clippableScroller[ 0 ] === this.$clippableWindow[ 0 ];
6832 scrollTop = scrollerIsWindow ? this.$clippableScroller.scrollTop() : 0;
6833 scrollLeft = scrollerIsWindow ? this.$clippableScroller.scrollLeft() : 0;
6834 desiredWidth = ccOffset.left < 0 ?
6835 ccWidth + ccOffset.left :
6836 ( scOffset.left + scrollLeft + scWidth ) - ccOffset.left;
6837 desiredHeight = ( scOffset.top + scrollTop + scHeight ) - ccOffset.top;
6838 allotedWidth = desiredWidth - extraWidth;
6839 allotedHeight = desiredHeight - extraHeight;
6840 naturalWidth = this.$clippable.prop( 'scrollWidth' );
6841 naturalHeight = this.$clippable.prop( 'scrollHeight' );
6842 clipWidth = allotedWidth < naturalWidth;
6843 clipHeight = allotedHeight < naturalHeight;
6844
6845 if ( clipWidth ) {
6846 this.$clippable.css( { overflowX: 'scroll', width: Math.max( 0, allotedWidth ) } );
6847 } else {
6848 this.$clippable.css( { width: this.idealWidth ? this.idealWidth - extraWidth : '', overflowX: '' } );
6849 }
6850 if ( clipHeight ) {
6851 this.$clippable.css( { overflowY: 'scroll', height: Math.max( 0, allotedHeight ) } );
6852 } else {
6853 this.$clippable.css( { height: this.idealHeight ? this.idealHeight - extraHeight : '', overflowY: '' } );
6854 }
6855
6856 // If we stopped clipping in at least one of the dimensions
6857 if ( ( this.clippedHorizontally && !clipWidth ) || ( this.clippedVertically && !clipHeight ) ) {
6858 OO.ui.Element.static.reconsiderScrollbars( this.$clippable[ 0 ] );
6859 }
6860
6861 this.clippedHorizontally = clipWidth;
6862 this.clippedVertically = clipHeight;
6863
6864 return this;
6865 };
6866
6867 /**
6868 * Element that will stick under a specified container, even when it is inserted elsewhere in the
6869 * document (for example, in a OO.ui.Window's $overlay).
6870 *
6871 * The elements's position is automatically calculated and maintained when window is resized or the
6872 * page is scrolled. If you reposition the container manually, you have to call #position to make
6873 * sure the element is still placed correctly.
6874 *
6875 * As positioning is only possible when both the element and the container are attached to the DOM
6876 * and visible, it's only done after you call #togglePositioning. You might want to do this inside
6877 * the #toggle method to display a floating popup, for example.
6878 *
6879 * @abstract
6880 * @class
6881 *
6882 * @constructor
6883 * @param {Object} [config] Configuration options
6884 * @cfg {jQuery} [$floatable] Node to position, assigned to #$floatable, omit to use #$element
6885 * @cfg {jQuery} [$floatableContainer] Node to position below
6886 */
6887 OO.ui.mixin.FloatableElement = function OoUiMixinFloatableElement( config ) {
6888 // Configuration initialization
6889 config = config || {};
6890
6891 // Properties
6892 this.$floatable = null;
6893 this.$floatableContainer = null;
6894 this.$floatableWindow = null;
6895 this.$floatableClosestScrollable = null;
6896 this.onFloatableScrollHandler = this.position.bind( this );
6897 this.onFloatableWindowResizeHandler = this.position.bind( this );
6898
6899 // Initialization
6900 this.setFloatableContainer( config.$floatableContainer );
6901 this.setFloatableElement( config.$floatable || this.$element );
6902 };
6903
6904 /* Methods */
6905
6906 /**
6907 * Set floatable element.
6908 *
6909 * If an element is already set, it will be cleaned up before setting up the new element.
6910 *
6911 * @param {jQuery} $floatable Element to make floatable
6912 */
6913 OO.ui.mixin.FloatableElement.prototype.setFloatableElement = function ( $floatable ) {
6914 if ( this.$floatable ) {
6915 this.$floatable.removeClass( 'oo-ui-floatableElement-floatable' );
6916 this.$floatable.css( { left: '', top: '' } );
6917 }
6918
6919 this.$floatable = $floatable.addClass( 'oo-ui-floatableElement-floatable' );
6920 this.position();
6921 };
6922
6923 /**
6924 * Set floatable container.
6925 *
6926 * The element will be always positioned under the specified container.
6927 *
6928 * @param {jQuery|null} $floatableContainer Container to keep visible, or null to unset
6929 */
6930 OO.ui.mixin.FloatableElement.prototype.setFloatableContainer = function ( $floatableContainer ) {
6931 this.$floatableContainer = $floatableContainer;
6932 if ( this.$floatable ) {
6933 this.position();
6934 }
6935 };
6936
6937 /**
6938 * Toggle positioning.
6939 *
6940 * Do not turn positioning on until after the element is attached to the DOM and visible.
6941 *
6942 * @param {boolean} [positioning] Enable positioning, omit to toggle
6943 * @chainable
6944 */
6945 OO.ui.mixin.FloatableElement.prototype.togglePositioning = function ( positioning ) {
6946 var closestScrollableOfContainer, closestScrollableOfFloatable;
6947
6948 positioning = positioning === undefined ? !this.positioning : !!positioning;
6949
6950 if ( this.positioning !== positioning ) {
6951 this.positioning = positioning;
6952
6953 closestScrollableOfContainer = OO.ui.Element.static.getClosestScrollableContainer( this.$floatableContainer[ 0 ] );
6954 closestScrollableOfFloatable = OO.ui.Element.static.getClosestScrollableContainer( this.$floatable[ 0 ] );
6955 if ( closestScrollableOfContainer !== closestScrollableOfFloatable ) {
6956 // If the scrollable is the root, we have to listen to scroll events
6957 // on the window because of browser inconsistencies (or do we? someone should verify this)
6958 if ( $( closestScrollableOfContainer ).is( 'html, body' ) ) {
6959 closestScrollableOfContainer = OO.ui.Element.static.getWindow( closestScrollableOfContainer );
6960 }
6961 }
6962
6963 if ( positioning ) {
6964 this.$floatableWindow = $( this.getElementWindow() );
6965 this.$floatableWindow.on( 'resize', this.onFloatableWindowResizeHandler );
6966
6967 if ( closestScrollableOfContainer !== closestScrollableOfFloatable ) {
6968 this.$floatableClosestScrollable = $( closestScrollableOfContainer );
6969 this.$floatableClosestScrollable.on( 'scroll', this.onFloatableScrollHandler );
6970 }
6971
6972 // Initial position after visible
6973 this.position();
6974 } else {
6975 if ( this.$floatableWindow ) {
6976 this.$floatableWindow.off( 'resize', this.onFloatableWindowResizeHandler );
6977 this.$floatableWindow = null;
6978 }
6979
6980 if ( this.$floatableClosestScrollable ) {
6981 this.$floatableClosestScrollable.off( 'scroll', this.onFloatableScrollHandler );
6982 this.$floatableClosestScrollable = null;
6983 }
6984
6985 this.$floatable.css( { left: '', top: '' } );
6986 }
6987 }
6988
6989 return this;
6990 };
6991
6992 /**
6993 * Position the floatable below its container.
6994 *
6995 * This should only be done when both of them are attached to the DOM and visible.
6996 *
6997 * @chainable
6998 */
6999 OO.ui.mixin.FloatableElement.prototype.position = function () {
7000 var pos;
7001
7002 if ( !this.positioning ) {
7003 return this;
7004 }
7005
7006 pos = OO.ui.Element.static.getRelativePosition( this.$floatableContainer, this.$floatable.offsetParent() );
7007
7008 // Position under container
7009 pos.top += this.$floatableContainer.height();
7010 this.$floatable.css( pos );
7011
7012 // We updated the position, so re-evaluate the clipping state.
7013 // (ClippableElement does not listen to 'scroll' events on $floatableContainer's parent, and so
7014 // will not notice the need to update itself.)
7015 // TODO: This is terrible, we shouldn't need to know about ClippableElement at all here. Why does
7016 // it not listen to the right events in the right places?
7017 if ( this.clip ) {
7018 this.clip();
7019 }
7020
7021 return this;
7022 };
7023
7024 /**
7025 * AccessKeyedElement is mixed into other classes to provide an `accesskey` attribute.
7026 * Accesskeys allow an user to go to a specific element by using
7027 * a shortcut combination of a browser specific keys + the key
7028 * set to the field.
7029 *
7030 * @example
7031 * // AccessKeyedElement provides an 'accesskey' attribute to the
7032 * // ButtonWidget class
7033 * var button = new OO.ui.ButtonWidget( {
7034 * label: 'Button with Accesskey',
7035 * accessKey: 'k'
7036 * } );
7037 * $( 'body' ).append( button.$element );
7038 *
7039 * @abstract
7040 * @class
7041 *
7042 * @constructor
7043 * @param {Object} [config] Configuration options
7044 * @cfg {jQuery} [$accessKeyed] The element to which the `accesskey` attribute is applied.
7045 * If this config is omitted, the accesskey functionality is applied to $element, the
7046 * element created by the class.
7047 * @cfg {string|Function} [accessKey] The key or a function that returns the key. If
7048 * this config is omitted, no accesskey will be added.
7049 */
7050 OO.ui.mixin.AccessKeyedElement = function OoUiMixinAccessKeyedElement( config ) {
7051 // Configuration initialization
7052 config = config || {};
7053
7054 // Properties
7055 this.$accessKeyed = null;
7056 this.accessKey = null;
7057
7058 // Initialization
7059 this.setAccessKey( config.accessKey || null );
7060 this.setAccessKeyedElement( config.$accessKeyed || this.$element );
7061 };
7062
7063 /* Setup */
7064
7065 OO.initClass( OO.ui.mixin.AccessKeyedElement );
7066
7067 /* Static Properties */
7068
7069 /**
7070 * The access key, a function that returns a key, or `null` for no accesskey.
7071 *
7072 * @static
7073 * @inheritable
7074 * @property {string|Function|null}
7075 */
7076 OO.ui.mixin.AccessKeyedElement.static.accessKey = null;
7077
7078 /* Methods */
7079
7080 /**
7081 * Set the accesskeyed element.
7082 *
7083 * This method is used to retarget a AccessKeyedElement mixin so that its functionality applies to the specified element.
7084 * If an element is already set, the mixin's effect on that element is removed before the new element is set up.
7085 *
7086 * @param {jQuery} $accessKeyed Element that should use the 'accesskeyes' functionality
7087 */
7088 OO.ui.mixin.AccessKeyedElement.prototype.setAccessKeyedElement = function ( $accessKeyed ) {
7089 if ( this.$accessKeyed ) {
7090 this.$accessKeyed.removeAttr( 'accesskey' );
7091 }
7092
7093 this.$accessKeyed = $accessKeyed;
7094 if ( this.accessKey ) {
7095 this.$accessKeyed.attr( 'accesskey', this.accessKey );
7096 }
7097 };
7098
7099 /**
7100 * Set accesskey.
7101 *
7102 * @param {string|Function|null} accesskey Key, a function that returns a key, or `null` for no accesskey
7103 * @chainable
7104 */
7105 OO.ui.mixin.AccessKeyedElement.prototype.setAccessKey = function ( accessKey ) {
7106 accessKey = typeof accessKey === 'string' ? OO.ui.resolveMsg( accessKey ) : null;
7107
7108 if ( this.accessKey !== accessKey ) {
7109 if ( this.$accessKeyed ) {
7110 if ( accessKey !== null ) {
7111 this.$accessKeyed.attr( 'accesskey', accessKey );
7112 } else {
7113 this.$accessKeyed.removeAttr( 'accesskey' );
7114 }
7115 }
7116 this.accessKey = accessKey;
7117 }
7118
7119 return this;
7120 };
7121
7122 /**
7123 * Get accesskey.
7124 *
7125 * @return {string} accessKey string
7126 */
7127 OO.ui.mixin.AccessKeyedElement.prototype.getAccessKey = function () {
7128 return this.accessKey;
7129 };
7130
7131 /**
7132 * Tools, together with {@link OO.ui.ToolGroup toolgroups}, constitute {@link OO.ui.Toolbar toolbars}.
7133 * Each tool is configured with a static name, title, and icon and is customized with the command to carry
7134 * out when the tool is selected. Tools must also be registered with a {@link OO.ui.ToolFactory tool factory},
7135 * which creates the tools on demand.
7136 *
7137 * Tools are added to toolgroups ({@link OO.ui.ListToolGroup ListToolGroup},
7138 * {@link OO.ui.BarToolGroup BarToolGroup}, or {@link OO.ui.MenuToolGroup MenuToolGroup}), which determine how
7139 * the tool is displayed in the toolbar. See {@link OO.ui.Toolbar toolbars} for an example.
7140 *
7141 * For more information, please see the [OOjs UI documentation on MediaWiki][1].
7142 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
7143 *
7144 * @abstract
7145 * @class
7146 * @extends OO.ui.Widget
7147 * @mixins OO.ui.mixin.IconElement
7148 * @mixins OO.ui.mixin.FlaggedElement
7149 * @mixins OO.ui.mixin.TabIndexedElement
7150 *
7151 * @constructor
7152 * @param {OO.ui.ToolGroup} toolGroup
7153 * @param {Object} [config] Configuration options
7154 * @cfg {string|Function} [title] Title text or a function that returns text. If this config is omitted, the value of
7155 * the {@link #static-title static title} property is used.
7156 *
7157 * The title is used in different ways depending on the type of toolgroup that contains the tool. The
7158 * title is used as a tooltip if the tool is part of a {@link OO.ui.BarToolGroup bar} toolgroup, or as the label text if the tool is
7159 * part of a {@link OO.ui.ListToolGroup list} or {@link OO.ui.MenuToolGroup menu} toolgroup.
7160 *
7161 * For bar toolgroups, a description of the accelerator key is appended to the title if an accelerator key
7162 * is associated with an action by the same name as the tool and accelerator functionality has been added to the application.
7163 * To add accelerator key functionality, you must subclass OO.ui.Toolbar and override the {@link OO.ui.Toolbar#getToolAccelerator getToolAccelerator} method.
7164 */
7165 OO.ui.Tool = function OoUiTool( toolGroup, config ) {
7166 // Allow passing positional parameters inside the config object
7167 if ( OO.isPlainObject( toolGroup ) && config === undefined ) {
7168 config = toolGroup;
7169 toolGroup = config.toolGroup;
7170 }
7171
7172 // Configuration initialization
7173 config = config || {};
7174
7175 // Parent constructor
7176 OO.ui.Tool.parent.call( this, config );
7177
7178 // Properties
7179 this.toolGroup = toolGroup;
7180 this.toolbar = this.toolGroup.getToolbar();
7181 this.active = false;
7182 this.$title = $( '<span>' );
7183 this.$accel = $( '<span>' );
7184 this.$link = $( '<a>' );
7185 this.title = null;
7186
7187 // Mixin constructors
7188 OO.ui.mixin.IconElement.call( this, config );
7189 OO.ui.mixin.FlaggedElement.call( this, config );
7190 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$link } ) );
7191
7192 // Events
7193 this.toolbar.connect( this, { updateState: 'onUpdateState' } );
7194
7195 // Initialization
7196 this.$title.addClass( 'oo-ui-tool-title' );
7197 this.$accel
7198 .addClass( 'oo-ui-tool-accel' )
7199 .prop( {
7200 // This may need to be changed if the key names are ever localized,
7201 // but for now they are essentially written in English
7202 dir: 'ltr',
7203 lang: 'en'
7204 } );
7205 this.$link
7206 .addClass( 'oo-ui-tool-link' )
7207 .append( this.$icon, this.$title, this.$accel )
7208 .attr( 'role', 'button' );
7209 this.$element
7210 .data( 'oo-ui-tool', this )
7211 .addClass(
7212 'oo-ui-tool ' + 'oo-ui-tool-name-' +
7213 this.constructor.static.name.replace( /^([^\/]+)\/([^\/]+).*$/, '$1-$2' )
7214 )
7215 .toggleClass( 'oo-ui-tool-with-label', this.constructor.static.displayBothIconAndLabel )
7216 .append( this.$link );
7217 this.setTitle( config.title || this.constructor.static.title );
7218 };
7219
7220 /* Setup */
7221
7222 OO.inheritClass( OO.ui.Tool, OO.ui.Widget );
7223 OO.mixinClass( OO.ui.Tool, OO.ui.mixin.IconElement );
7224 OO.mixinClass( OO.ui.Tool, OO.ui.mixin.FlaggedElement );
7225 OO.mixinClass( OO.ui.Tool, OO.ui.mixin.TabIndexedElement );
7226
7227 /* Static Properties */
7228
7229 /**
7230 * @static
7231 * @inheritdoc
7232 */
7233 OO.ui.Tool.static.tagName = 'span';
7234
7235 /**
7236 * Symbolic name of tool.
7237 *
7238 * The symbolic name is used internally to register the tool with a {@link OO.ui.ToolFactory ToolFactory}. It can
7239 * also be used when adding tools to toolgroups.
7240 *
7241 * @abstract
7242 * @static
7243 * @inheritable
7244 * @property {string}
7245 */
7246 OO.ui.Tool.static.name = '';
7247
7248 /**
7249 * Symbolic name of the group.
7250 *
7251 * The group name is used to associate tools with each other so that they can be selected later by
7252 * a {@link OO.ui.ToolGroup toolgroup}.
7253 *
7254 * @abstract
7255 * @static
7256 * @inheritable
7257 * @property {string}
7258 */
7259 OO.ui.Tool.static.group = '';
7260
7261 /**
7262 * Tool title text or a function that returns title text. The value of the static property is overridden if the #title config option is used.
7263 *
7264 * @abstract
7265 * @static
7266 * @inheritable
7267 * @property {string|Function}
7268 */
7269 OO.ui.Tool.static.title = '';
7270
7271 /**
7272 * Display both icon and label when the tool is used in a {@link OO.ui.BarToolGroup bar} toolgroup.
7273 * Normally only the icon is displayed, or only the label if no icon is given.
7274 *
7275 * @static
7276 * @inheritable
7277 * @property {boolean}
7278 */
7279 OO.ui.Tool.static.displayBothIconAndLabel = false;
7280
7281 /**
7282 * Add tool to catch-all groups automatically.
7283 *
7284 * A catch-all group, which contains all tools that do not currently belong to a toolgroup,
7285 * can be included in a toolgroup using the wildcard selector, an asterisk (*).
7286 *
7287 * @static
7288 * @inheritable
7289 * @property {boolean}
7290 */
7291 OO.ui.Tool.static.autoAddToCatchall = true;
7292
7293 /**
7294 * Add tool to named groups automatically.
7295 *
7296 * By default, tools that are configured with a static ‘group’ property are added
7297 * to that group and will be selected when the symbolic name of the group is specified (e.g., when
7298 * toolgroups include tools by group name).
7299 *
7300 * @static
7301 * @property {boolean}
7302 * @inheritable
7303 */
7304 OO.ui.Tool.static.autoAddToGroup = true;
7305
7306 /**
7307 * Check if this tool is compatible with given data.
7308 *
7309 * This is a stub that can be overriden to provide support for filtering tools based on an
7310 * arbitrary piece of information (e.g., where the cursor is in a document). The implementation
7311 * must also call this method so that the compatibility check can be performed.
7312 *
7313 * @static
7314 * @inheritable
7315 * @param {Mixed} data Data to check
7316 * @return {boolean} Tool can be used with data
7317 */
7318 OO.ui.Tool.static.isCompatibleWith = function () {
7319 return false;
7320 };
7321
7322 /* Methods */
7323
7324 /**
7325 * Handle the toolbar state being updated.
7326 *
7327 * This is an abstract method that must be overridden in a concrete subclass.
7328 *
7329 * @protected
7330 * @abstract
7331 */
7332 OO.ui.Tool.prototype.onUpdateState = function () {
7333 throw new Error(
7334 'OO.ui.Tool.onUpdateState not implemented in this subclass:' + this.constructor
7335 );
7336 };
7337
7338 /**
7339 * Handle the tool being selected.
7340 *
7341 * This is an abstract method that must be overridden in a concrete subclass.
7342 *
7343 * @protected
7344 * @abstract
7345 */
7346 OO.ui.Tool.prototype.onSelect = function () {
7347 throw new Error(
7348 'OO.ui.Tool.onSelect not implemented in this subclass:' + this.constructor
7349 );
7350 };
7351
7352 /**
7353 * Check if the tool is active.
7354 *
7355 * Tools become active when their #onSelect or #onUpdateState handlers change them to appear pressed
7356 * with the #setActive method. Additional CSS is applied to the tool to reflect the active state.
7357 *
7358 * @return {boolean} Tool is active
7359 */
7360 OO.ui.Tool.prototype.isActive = function () {
7361 return this.active;
7362 };
7363
7364 /**
7365 * Make the tool appear active or inactive.
7366 *
7367 * This method should be called within #onSelect or #onUpdateState event handlers to make the tool
7368 * appear pressed or not.
7369 *
7370 * @param {boolean} state Make tool appear active
7371 */
7372 OO.ui.Tool.prototype.setActive = function ( state ) {
7373 this.active = !!state;
7374 if ( this.active ) {
7375 this.$element.addClass( 'oo-ui-tool-active' );
7376 } else {
7377 this.$element.removeClass( 'oo-ui-tool-active' );
7378 }
7379 };
7380
7381 /**
7382 * Set the tool #title.
7383 *
7384 * @param {string|Function} title Title text or a function that returns text
7385 * @chainable
7386 */
7387 OO.ui.Tool.prototype.setTitle = function ( title ) {
7388 this.title = OO.ui.resolveMsg( title );
7389 this.updateTitle();
7390 return this;
7391 };
7392
7393 /**
7394 * Get the tool #title.
7395 *
7396 * @return {string} Title text
7397 */
7398 OO.ui.Tool.prototype.getTitle = function () {
7399 return this.title;
7400 };
7401
7402 /**
7403 * Get the tool's symbolic name.
7404 *
7405 * @return {string} Symbolic name of tool
7406 */
7407 OO.ui.Tool.prototype.getName = function () {
7408 return this.constructor.static.name;
7409 };
7410
7411 /**
7412 * Update the title.
7413 */
7414 OO.ui.Tool.prototype.updateTitle = function () {
7415 var titleTooltips = this.toolGroup.constructor.static.titleTooltips,
7416 accelTooltips = this.toolGroup.constructor.static.accelTooltips,
7417 accel = this.toolbar.getToolAccelerator( this.constructor.static.name ),
7418 tooltipParts = [];
7419
7420 this.$title.text( this.title );
7421 this.$accel.text( accel );
7422
7423 if ( titleTooltips && typeof this.title === 'string' && this.title.length ) {
7424 tooltipParts.push( this.title );
7425 }
7426 if ( accelTooltips && typeof accel === 'string' && accel.length ) {
7427 tooltipParts.push( accel );
7428 }
7429 if ( tooltipParts.length ) {
7430 this.$link.attr( 'title', tooltipParts.join( ' ' ) );
7431 } else {
7432 this.$link.removeAttr( 'title' );
7433 }
7434 };
7435
7436 /**
7437 * Destroy tool.
7438 *
7439 * Destroying the tool removes all event handlers and the tool’s DOM elements.
7440 * Call this method whenever you are done using a tool.
7441 */
7442 OO.ui.Tool.prototype.destroy = function () {
7443 this.toolbar.disconnect( this );
7444 this.$element.remove();
7445 };
7446
7447 /**
7448 * Toolbars are complex interface components that permit users to easily access a variety
7449 * of {@link OO.ui.Tool tools} (e.g., formatting commands) and actions, which are additional commands that are
7450 * part of the toolbar, but not configured as tools.
7451 *
7452 * Individual tools are customized and then registered with a {@link OO.ui.ToolFactory tool factory}, which creates
7453 * the tools on demand. Each tool has a symbolic name (used when registering the tool), a title (e.g., ‘Insert
7454 * picture’), and an icon.
7455 *
7456 * Individual tools are organized in {@link OO.ui.ToolGroup toolgroups}, which can be {@link OO.ui.MenuToolGroup menus}
7457 * of tools, {@link OO.ui.ListToolGroup lists} of tools, or a single {@link OO.ui.BarToolGroup bar} of tools.
7458 * The arrangement and order of the toolgroups is customized when the toolbar is set up. Tools can be presented in
7459 * any order, but each can only appear once in the toolbar.
7460 *
7461 * The following is an example of a basic toolbar.
7462 *
7463 * @example
7464 * // Example of a toolbar
7465 * // Create the toolbar
7466 * var toolFactory = new OO.ui.ToolFactory();
7467 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
7468 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
7469 *
7470 * // We will be placing status text in this element when tools are used
7471 * var $area = $( '<p>' ).text( 'Toolbar example' );
7472 *
7473 * // Define the tools that we're going to place in our toolbar
7474 *
7475 * // Create a class inheriting from OO.ui.Tool
7476 * function PictureTool() {
7477 * PictureTool.parent.apply( this, arguments );
7478 * }
7479 * OO.inheritClass( PictureTool, OO.ui.Tool );
7480 * // Each tool must have a 'name' (used as an internal identifier, see later) and at least one
7481 * // of 'icon' and 'title' (displayed icon and text).
7482 * PictureTool.static.name = 'picture';
7483 * PictureTool.static.icon = 'picture';
7484 * PictureTool.static.title = 'Insert picture';
7485 * // Defines the action that will happen when this tool is selected (clicked).
7486 * PictureTool.prototype.onSelect = function () {
7487 * $area.text( 'Picture tool clicked!' );
7488 * // Never display this tool as "active" (selected).
7489 * this.setActive( false );
7490 * };
7491 * // Make this tool available in our toolFactory and thus our toolbar
7492 * toolFactory.register( PictureTool );
7493 *
7494 * // Register two more tools, nothing interesting here
7495 * function SettingsTool() {
7496 * SettingsTool.parent.apply( this, arguments );
7497 * }
7498 * OO.inheritClass( SettingsTool, OO.ui.Tool );
7499 * SettingsTool.static.name = 'settings';
7500 * SettingsTool.static.icon = 'settings';
7501 * SettingsTool.static.title = 'Change settings';
7502 * SettingsTool.prototype.onSelect = function () {
7503 * $area.text( 'Settings tool clicked!' );
7504 * this.setActive( false );
7505 * };
7506 * toolFactory.register( SettingsTool );
7507 *
7508 * // Register two more tools, nothing interesting here
7509 * function StuffTool() {
7510 * StuffTool.parent.apply( this, arguments );
7511 * }
7512 * OO.inheritClass( StuffTool, OO.ui.Tool );
7513 * StuffTool.static.name = 'stuff';
7514 * StuffTool.static.icon = 'ellipsis';
7515 * StuffTool.static.title = 'More stuff';
7516 * StuffTool.prototype.onSelect = function () {
7517 * $area.text( 'More stuff tool clicked!' );
7518 * this.setActive( false );
7519 * };
7520 * toolFactory.register( StuffTool );
7521 *
7522 * // This is a PopupTool. Rather than having a custom 'onSelect' action, it will display a
7523 * // little popup window (a PopupWidget).
7524 * function HelpTool( toolGroup, config ) {
7525 * OO.ui.PopupTool.call( this, toolGroup, $.extend( { popup: {
7526 * padded: true,
7527 * label: 'Help',
7528 * head: true
7529 * } }, config ) );
7530 * this.popup.$body.append( '<p>I am helpful!</p>' );
7531 * }
7532 * OO.inheritClass( HelpTool, OO.ui.PopupTool );
7533 * HelpTool.static.name = 'help';
7534 * HelpTool.static.icon = 'help';
7535 * HelpTool.static.title = 'Help';
7536 * toolFactory.register( HelpTool );
7537 *
7538 * // Finally define which tools and in what order appear in the toolbar. Each tool may only be
7539 * // used once (but not all defined tools must be used).
7540 * toolbar.setup( [
7541 * {
7542 * // 'bar' tool groups display tools' icons only, side-by-side.
7543 * type: 'bar',
7544 * include: [ 'picture', 'help' ]
7545 * },
7546 * {
7547 * // 'list' tool groups display both the titles and icons, in a dropdown list.
7548 * type: 'list',
7549 * indicator: 'down',
7550 * label: 'More',
7551 * include: [ 'settings', 'stuff' ]
7552 * }
7553 * // Note how the tools themselves are toolgroup-agnostic - the same tool can be displayed
7554 * // either in a 'list' or a 'bar'. There is a 'menu' tool group too, not showcased here,
7555 * // since it's more complicated to use. (See the next example snippet on this page.)
7556 * ] );
7557 *
7558 * // Create some UI around the toolbar and place it in the document
7559 * var frame = new OO.ui.PanelLayout( {
7560 * expanded: false,
7561 * framed: true
7562 * } );
7563 * var contentFrame = new OO.ui.PanelLayout( {
7564 * expanded: false,
7565 * padded: true
7566 * } );
7567 * frame.$element.append(
7568 * toolbar.$element,
7569 * contentFrame.$element.append( $area )
7570 * );
7571 * $( 'body' ).append( frame.$element );
7572 *
7573 * // Here is where the toolbar is actually built. This must be done after inserting it into the
7574 * // document.
7575 * toolbar.initialize();
7576 *
7577 * The following example extends the previous one to illustrate 'menu' toolgroups and the usage of
7578 * 'updateState' event.
7579 *
7580 * @example
7581 * // Create the toolbar
7582 * var toolFactory = new OO.ui.ToolFactory();
7583 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
7584 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
7585 *
7586 * // We will be placing status text in this element when tools are used
7587 * var $area = $( '<p>' ).text( 'Toolbar example' );
7588 *
7589 * // Define the tools that we're going to place in our toolbar
7590 *
7591 * // Create a class inheriting from OO.ui.Tool
7592 * function PictureTool() {
7593 * PictureTool.parent.apply( this, arguments );
7594 * }
7595 * OO.inheritClass( PictureTool, OO.ui.Tool );
7596 * // Each tool must have a 'name' (used as an internal identifier, see later) and at least one
7597 * // of 'icon' and 'title' (displayed icon and text).
7598 * PictureTool.static.name = 'picture';
7599 * PictureTool.static.icon = 'picture';
7600 * PictureTool.static.title = 'Insert picture';
7601 * // Defines the action that will happen when this tool is selected (clicked).
7602 * PictureTool.prototype.onSelect = function () {
7603 * $area.text( 'Picture tool clicked!' );
7604 * // Never display this tool as "active" (selected).
7605 * this.setActive( false );
7606 * };
7607 * // The toolbar can be synchronized with the state of some external stuff, like a text
7608 * // editor's editing area, highlighting the tools (e.g. a 'bold' tool would be shown as active
7609 * // when the text cursor was inside bolded text). Here we simply disable this feature.
7610 * PictureTool.prototype.onUpdateState = function () {
7611 * };
7612 * // Make this tool available in our toolFactory and thus our toolbar
7613 * toolFactory.register( PictureTool );
7614 *
7615 * // Register two more tools, nothing interesting here
7616 * function SettingsTool() {
7617 * SettingsTool.parent.apply( this, arguments );
7618 * this.reallyActive = false;
7619 * }
7620 * OO.inheritClass( SettingsTool, OO.ui.Tool );
7621 * SettingsTool.static.name = 'settings';
7622 * SettingsTool.static.icon = 'settings';
7623 * SettingsTool.static.title = 'Change settings';
7624 * SettingsTool.prototype.onSelect = function () {
7625 * $area.text( 'Settings tool clicked!' );
7626 * // Toggle the active state on each click
7627 * this.reallyActive = !this.reallyActive;
7628 * this.setActive( this.reallyActive );
7629 * // To update the menu label
7630 * this.toolbar.emit( 'updateState' );
7631 * };
7632 * SettingsTool.prototype.onUpdateState = function () {
7633 * };
7634 * toolFactory.register( SettingsTool );
7635 *
7636 * // Register two more tools, nothing interesting here
7637 * function StuffTool() {
7638 * StuffTool.parent.apply( this, arguments );
7639 * this.reallyActive = false;
7640 * }
7641 * OO.inheritClass( StuffTool, OO.ui.Tool );
7642 * StuffTool.static.name = 'stuff';
7643 * StuffTool.static.icon = 'ellipsis';
7644 * StuffTool.static.title = 'More stuff';
7645 * StuffTool.prototype.onSelect = function () {
7646 * $area.text( 'More stuff tool clicked!' );
7647 * // Toggle the active state on each click
7648 * this.reallyActive = !this.reallyActive;
7649 * this.setActive( this.reallyActive );
7650 * // To update the menu label
7651 * this.toolbar.emit( 'updateState' );
7652 * };
7653 * StuffTool.prototype.onUpdateState = function () {
7654 * };
7655 * toolFactory.register( StuffTool );
7656 *
7657 * // This is a PopupTool. Rather than having a custom 'onSelect' action, it will display a
7658 * // little popup window (a PopupWidget). 'onUpdateState' is also already implemented.
7659 * function HelpTool( toolGroup, config ) {
7660 * OO.ui.PopupTool.call( this, toolGroup, $.extend( { popup: {
7661 * padded: true,
7662 * label: 'Help',
7663 * head: true
7664 * } }, config ) );
7665 * this.popup.$body.append( '<p>I am helpful!</p>' );
7666 * }
7667 * OO.inheritClass( HelpTool, OO.ui.PopupTool );
7668 * HelpTool.static.name = 'help';
7669 * HelpTool.static.icon = 'help';
7670 * HelpTool.static.title = 'Help';
7671 * toolFactory.register( HelpTool );
7672 *
7673 * // Finally define which tools and in what order appear in the toolbar. Each tool may only be
7674 * // used once (but not all defined tools must be used).
7675 * toolbar.setup( [
7676 * {
7677 * // 'bar' tool groups display tools' icons only, side-by-side.
7678 * type: 'bar',
7679 * include: [ 'picture', 'help' ]
7680 * },
7681 * {
7682 * // 'menu' tool groups display both the titles and icons, in a dropdown menu.
7683 * // Menu label indicates which items are selected.
7684 * type: 'menu',
7685 * indicator: 'down',
7686 * include: [ 'settings', 'stuff' ]
7687 * }
7688 * ] );
7689 *
7690 * // Create some UI around the toolbar and place it in the document
7691 * var frame = new OO.ui.PanelLayout( {
7692 * expanded: false,
7693 * framed: true
7694 * } );
7695 * var contentFrame = new OO.ui.PanelLayout( {
7696 * expanded: false,
7697 * padded: true
7698 * } );
7699 * frame.$element.append(
7700 * toolbar.$element,
7701 * contentFrame.$element.append( $area )
7702 * );
7703 * $( 'body' ).append( frame.$element );
7704 *
7705 * // Here is where the toolbar is actually built. This must be done after inserting it into the
7706 * // document.
7707 * toolbar.initialize();
7708 * toolbar.emit( 'updateState' );
7709 *
7710 * @class
7711 * @extends OO.ui.Element
7712 * @mixins OO.EventEmitter
7713 * @mixins OO.ui.mixin.GroupElement
7714 *
7715 * @constructor
7716 * @param {OO.ui.ToolFactory} toolFactory Factory for creating tools
7717 * @param {OO.ui.ToolGroupFactory} toolGroupFactory Factory for creating toolgroups
7718 * @param {Object} [config] Configuration options
7719 * @cfg {boolean} [actions] Add an actions section to the toolbar. Actions are commands that are included
7720 * in the toolbar, but are not configured as tools. By default, actions are displayed on the right side of
7721 * the toolbar.
7722 * @cfg {boolean} [shadow] Add a shadow below the toolbar.
7723 */
7724 OO.ui.Toolbar = function OoUiToolbar( toolFactory, toolGroupFactory, config ) {
7725 // Allow passing positional parameters inside the config object
7726 if ( OO.isPlainObject( toolFactory ) && config === undefined ) {
7727 config = toolFactory;
7728 toolFactory = config.toolFactory;
7729 toolGroupFactory = config.toolGroupFactory;
7730 }
7731
7732 // Configuration initialization
7733 config = config || {};
7734
7735 // Parent constructor
7736 OO.ui.Toolbar.parent.call( this, config );
7737
7738 // Mixin constructors
7739 OO.EventEmitter.call( this );
7740 OO.ui.mixin.GroupElement.call( this, config );
7741
7742 // Properties
7743 this.toolFactory = toolFactory;
7744 this.toolGroupFactory = toolGroupFactory;
7745 this.groups = [];
7746 this.tools = {};
7747 this.$bar = $( '<div>' );
7748 this.$actions = $( '<div>' );
7749 this.initialized = false;
7750 this.onWindowResizeHandler = this.onWindowResize.bind( this );
7751
7752 // Events
7753 this.$element
7754 .add( this.$bar ).add( this.$group ).add( this.$actions )
7755 .on( 'mousedown keydown', this.onPointerDown.bind( this ) );
7756
7757 // Initialization
7758 this.$group.addClass( 'oo-ui-toolbar-tools' );
7759 if ( config.actions ) {
7760 this.$bar.append( this.$actions.addClass( 'oo-ui-toolbar-actions' ) );
7761 }
7762 this.$bar
7763 .addClass( 'oo-ui-toolbar-bar' )
7764 .append( this.$group, '<div style="clear:both"></div>' );
7765 if ( config.shadow ) {
7766 this.$bar.append( '<div class="oo-ui-toolbar-shadow"></div>' );
7767 }
7768 this.$element.addClass( 'oo-ui-toolbar' ).append( this.$bar );
7769 };
7770
7771 /* Setup */
7772
7773 OO.inheritClass( OO.ui.Toolbar, OO.ui.Element );
7774 OO.mixinClass( OO.ui.Toolbar, OO.EventEmitter );
7775 OO.mixinClass( OO.ui.Toolbar, OO.ui.mixin.GroupElement );
7776
7777 /* Methods */
7778
7779 /**
7780 * Get the tool factory.
7781 *
7782 * @return {OO.ui.ToolFactory} Tool factory
7783 */
7784 OO.ui.Toolbar.prototype.getToolFactory = function () {
7785 return this.toolFactory;
7786 };
7787
7788 /**
7789 * Get the toolgroup factory.
7790 *
7791 * @return {OO.Factory} Toolgroup factory
7792 */
7793 OO.ui.Toolbar.prototype.getToolGroupFactory = function () {
7794 return this.toolGroupFactory;
7795 };
7796
7797 /**
7798 * Handles mouse down events.
7799 *
7800 * @private
7801 * @param {jQuery.Event} e Mouse down event
7802 */
7803 OO.ui.Toolbar.prototype.onPointerDown = function ( e ) {
7804 var $closestWidgetToEvent = $( e.target ).closest( '.oo-ui-widget' ),
7805 $closestWidgetToToolbar = this.$element.closest( '.oo-ui-widget' );
7806 if ( !$closestWidgetToEvent.length || $closestWidgetToEvent[ 0 ] === $closestWidgetToToolbar[ 0 ] ) {
7807 return false;
7808 }
7809 };
7810
7811 /**
7812 * Handle window resize event.
7813 *
7814 * @private
7815 * @param {jQuery.Event} e Window resize event
7816 */
7817 OO.ui.Toolbar.prototype.onWindowResize = function () {
7818 this.$element.toggleClass(
7819 'oo-ui-toolbar-narrow',
7820 this.$bar.width() <= this.narrowThreshold
7821 );
7822 };
7823
7824 /**
7825 * Sets up handles and preloads required information for the toolbar to work.
7826 * This must be called after it is attached to a visible document and before doing anything else.
7827 */
7828 OO.ui.Toolbar.prototype.initialize = function () {
7829 if ( !this.initialized ) {
7830 this.initialized = true;
7831 this.narrowThreshold = this.$group.width() + this.$actions.width();
7832 $( this.getElementWindow() ).on( 'resize', this.onWindowResizeHandler );
7833 this.onWindowResize();
7834 }
7835 };
7836
7837 /**
7838 * Set up the toolbar.
7839 *
7840 * The toolbar is set up with a list of toolgroup configurations that specify the type of
7841 * toolgroup ({@link OO.ui.BarToolGroup bar}, {@link OO.ui.MenuToolGroup menu}, or {@link OO.ui.ListToolGroup list})
7842 * to add and which tools to include, exclude, promote, or demote within that toolgroup. Please
7843 * see {@link OO.ui.ToolGroup toolgroups} for more information about including tools in toolgroups.
7844 *
7845 * @param {Object.<string,Array>} groups List of toolgroup configurations
7846 * @param {Array|string} [groups.include] Tools to include in the toolgroup
7847 * @param {Array|string} [groups.exclude] Tools to exclude from the toolgroup
7848 * @param {Array|string} [groups.promote] Tools to promote to the beginning of the toolgroup
7849 * @param {Array|string} [groups.demote] Tools to demote to the end of the toolgroup
7850 */
7851 OO.ui.Toolbar.prototype.setup = function ( groups ) {
7852 var i, len, type, group,
7853 items = [],
7854 defaultType = 'bar';
7855
7856 // Cleanup previous groups
7857 this.reset();
7858
7859 // Build out new groups
7860 for ( i = 0, len = groups.length; i < len; i++ ) {
7861 group = groups[ i ];
7862 if ( group.include === '*' ) {
7863 // Apply defaults to catch-all groups
7864 if ( group.type === undefined ) {
7865 group.type = 'list';
7866 }
7867 if ( group.label === undefined ) {
7868 group.label = OO.ui.msg( 'ooui-toolbar-more' );
7869 }
7870 }
7871 // Check type has been registered
7872 type = this.getToolGroupFactory().lookup( group.type ) ? group.type : defaultType;
7873 items.push(
7874 this.getToolGroupFactory().create( type, this, group )
7875 );
7876 }
7877 this.addItems( items );
7878 };
7879
7880 /**
7881 * Remove all tools and toolgroups from the toolbar.
7882 */
7883 OO.ui.Toolbar.prototype.reset = function () {
7884 var i, len;
7885
7886 this.groups = [];
7887 this.tools = {};
7888 for ( i = 0, len = this.items.length; i < len; i++ ) {
7889 this.items[ i ].destroy();
7890 }
7891 this.clearItems();
7892 };
7893
7894 /**
7895 * Destroy the toolbar.
7896 *
7897 * Destroying the toolbar removes all event handlers and DOM elements that constitute the toolbar. Call
7898 * this method whenever you are done using a toolbar.
7899 */
7900 OO.ui.Toolbar.prototype.destroy = function () {
7901 $( this.getElementWindow() ).off( 'resize', this.onWindowResizeHandler );
7902 this.reset();
7903 this.$element.remove();
7904 };
7905
7906 /**
7907 * Check if the tool is available.
7908 *
7909 * Available tools are ones that have not yet been added to the toolbar.
7910 *
7911 * @param {string} name Symbolic name of tool
7912 * @return {boolean} Tool is available
7913 */
7914 OO.ui.Toolbar.prototype.isToolAvailable = function ( name ) {
7915 return !this.tools[ name ];
7916 };
7917
7918 /**
7919 * Prevent tool from being used again.
7920 *
7921 * @param {OO.ui.Tool} tool Tool to reserve
7922 */
7923 OO.ui.Toolbar.prototype.reserveTool = function ( tool ) {
7924 this.tools[ tool.getName() ] = tool;
7925 };
7926
7927 /**
7928 * Allow tool to be used again.
7929 *
7930 * @param {OO.ui.Tool} tool Tool to release
7931 */
7932 OO.ui.Toolbar.prototype.releaseTool = function ( tool ) {
7933 delete this.tools[ tool.getName() ];
7934 };
7935
7936 /**
7937 * Get accelerator label for tool.
7938 *
7939 * The OOjs UI library does not contain an accelerator system, but this is the hook for one. To
7940 * use an accelerator system, subclass the toolbar and override this method, which is meant to return a label
7941 * that describes the accelerator keys for the tool passed (by symbolic name) to the method.
7942 *
7943 * @param {string} name Symbolic name of tool
7944 * @return {string|undefined} Tool accelerator label if available
7945 */
7946 OO.ui.Toolbar.prototype.getToolAccelerator = function () {
7947 return undefined;
7948 };
7949
7950 /**
7951 * ToolGroups are collections of {@link OO.ui.Tool tools} that are used in a {@link OO.ui.Toolbar toolbar}.
7952 * The type of toolgroup ({@link OO.ui.ListToolGroup list}, {@link OO.ui.BarToolGroup bar}, or {@link OO.ui.MenuToolGroup menu})
7953 * to which a tool belongs determines how the tool is arranged and displayed in the toolbar. Toolgroups
7954 * themselves are created on demand with a {@link OO.ui.ToolGroupFactory toolgroup factory}.
7955 *
7956 * Toolgroups can contain individual tools, groups of tools, or all available tools:
7957 *
7958 * To include an individual tool (or array of individual tools), specify tools by symbolic name:
7959 *
7960 * include: [ 'tool-name' ] or [ { name: 'tool-name' }]
7961 *
7962 * To include a group of tools, specify the group name. (The tool's static ‘group’ config is used to assign the tool to a group.)
7963 *
7964 * include: [ { group: 'group-name' } ]
7965 *
7966 * To include all tools that are not yet assigned to a toolgroup, use the catch-all selector, an asterisk (*):
7967 *
7968 * include: '*'
7969 *
7970 * See {@link OO.ui.Toolbar toolbars} for a full example. For more information about toolbars in general,
7971 * please see the [OOjs UI documentation on MediaWiki][1].
7972 *
7973 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
7974 *
7975 * @abstract
7976 * @class
7977 * @extends OO.ui.Widget
7978 * @mixins OO.ui.mixin.GroupElement
7979 *
7980 * @constructor
7981 * @param {OO.ui.Toolbar} toolbar
7982 * @param {Object} [config] Configuration options
7983 * @cfg {Array|string} [include=[]] List of tools to include in the toolgroup.
7984 * @cfg {Array|string} [exclude=[]] List of tools to exclude from the toolgroup.
7985 * @cfg {Array|string} [promote=[]] List of tools to promote to the beginning of the toolgroup.
7986 * @cfg {Array|string} [demote=[]] List of tools to demote to the end of the toolgroup.
7987 * This setting is particularly useful when tools have been added to the toolgroup
7988 * en masse (e.g., via the catch-all selector).
7989 */
7990 OO.ui.ToolGroup = function OoUiToolGroup( toolbar, config ) {
7991 // Allow passing positional parameters inside the config object
7992 if ( OO.isPlainObject( toolbar ) && config === undefined ) {
7993 config = toolbar;
7994 toolbar = config.toolbar;
7995 }
7996
7997 // Configuration initialization
7998 config = config || {};
7999
8000 // Parent constructor
8001 OO.ui.ToolGroup.parent.call( this, config );
8002
8003 // Mixin constructors
8004 OO.ui.mixin.GroupElement.call( this, config );
8005
8006 // Properties
8007 this.toolbar = toolbar;
8008 this.tools = {};
8009 this.pressed = null;
8010 this.autoDisabled = false;
8011 this.include = config.include || [];
8012 this.exclude = config.exclude || [];
8013 this.promote = config.promote || [];
8014 this.demote = config.demote || [];
8015 this.onCapturedMouseKeyUpHandler = this.onCapturedMouseKeyUp.bind( this );
8016
8017 // Events
8018 this.$element.on( {
8019 mousedown: this.onMouseKeyDown.bind( this ),
8020 mouseup: this.onMouseKeyUp.bind( this ),
8021 keydown: this.onMouseKeyDown.bind( this ),
8022 keyup: this.onMouseKeyUp.bind( this ),
8023 focus: this.onMouseOverFocus.bind( this ),
8024 blur: this.onMouseOutBlur.bind( this ),
8025 mouseover: this.onMouseOverFocus.bind( this ),
8026 mouseout: this.onMouseOutBlur.bind( this )
8027 } );
8028 this.toolbar.getToolFactory().connect( this, { register: 'onToolFactoryRegister' } );
8029 this.aggregate( { disable: 'itemDisable' } );
8030 this.connect( this, { itemDisable: 'updateDisabled' } );
8031
8032 // Initialization
8033 this.$group.addClass( 'oo-ui-toolGroup-tools' );
8034 this.$element
8035 .addClass( 'oo-ui-toolGroup' )
8036 .append( this.$group );
8037 this.populate();
8038 };
8039
8040 /* Setup */
8041
8042 OO.inheritClass( OO.ui.ToolGroup, OO.ui.Widget );
8043 OO.mixinClass( OO.ui.ToolGroup, OO.ui.mixin.GroupElement );
8044
8045 /* Events */
8046
8047 /**
8048 * @event update
8049 */
8050
8051 /* Static Properties */
8052
8053 /**
8054 * Show labels in tooltips.
8055 *
8056 * @static
8057 * @inheritable
8058 * @property {boolean}
8059 */
8060 OO.ui.ToolGroup.static.titleTooltips = false;
8061
8062 /**
8063 * Show acceleration labels in tooltips.
8064 *
8065 * Note: The OOjs UI library does not include an accelerator system, but does contain
8066 * a hook for one. To use an accelerator system, subclass the {@link OO.ui.Toolbar toolbar} and
8067 * override the {@link OO.ui.Toolbar#getToolAccelerator getToolAccelerator} method, which is
8068 * meant to return a label that describes the accelerator keys for a given tool (e.g., 'Ctrl + M').
8069 *
8070 * @static
8071 * @inheritable
8072 * @property {boolean}
8073 */
8074 OO.ui.ToolGroup.static.accelTooltips = false;
8075
8076 /**
8077 * Automatically disable the toolgroup when all tools are disabled
8078 *
8079 * @static
8080 * @inheritable
8081 * @property {boolean}
8082 */
8083 OO.ui.ToolGroup.static.autoDisable = true;
8084
8085 /* Methods */
8086
8087 /**
8088 * @inheritdoc
8089 */
8090 OO.ui.ToolGroup.prototype.isDisabled = function () {
8091 return this.autoDisabled || OO.ui.ToolGroup.parent.prototype.isDisabled.apply( this, arguments );
8092 };
8093
8094 /**
8095 * @inheritdoc
8096 */
8097 OO.ui.ToolGroup.prototype.updateDisabled = function () {
8098 var i, item, allDisabled = true;
8099
8100 if ( this.constructor.static.autoDisable ) {
8101 for ( i = this.items.length - 1; i >= 0; i-- ) {
8102 item = this.items[ i ];
8103 if ( !item.isDisabled() ) {
8104 allDisabled = false;
8105 break;
8106 }
8107 }
8108 this.autoDisabled = allDisabled;
8109 }
8110 OO.ui.ToolGroup.parent.prototype.updateDisabled.apply( this, arguments );
8111 };
8112
8113 /**
8114 * Handle mouse down and key down events.
8115 *
8116 * @protected
8117 * @param {jQuery.Event} e Mouse down or key down event
8118 */
8119 OO.ui.ToolGroup.prototype.onMouseKeyDown = function ( e ) {
8120 if (
8121 !this.isDisabled() &&
8122 ( e.which === 1 || e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
8123 ) {
8124 this.pressed = this.getTargetTool( e );
8125 if ( this.pressed ) {
8126 this.pressed.setActive( true );
8127 OO.ui.addCaptureEventListener( this.getElementDocument(), 'mouseup', this.onCapturedMouseKeyUpHandler );
8128 OO.ui.addCaptureEventListener( this.getElementDocument(), 'keyup', this.onCapturedMouseKeyUpHandler );
8129 }
8130 return false;
8131 }
8132 };
8133
8134 /**
8135 * Handle captured mouse up and key up events.
8136 *
8137 * @protected
8138 * @param {Event} e Mouse up or key up event
8139 */
8140 OO.ui.ToolGroup.prototype.onCapturedMouseKeyUp = function ( e ) {
8141 OO.ui.removeCaptureEventListener( this.getElementDocument(), 'mouseup', this.onCapturedMouseKeyUpHandler );
8142 OO.ui.removeCaptureEventListener( this.getElementDocument(), 'keyup', this.onCapturedMouseKeyUpHandler );
8143 // onMouseKeyUp may be called a second time, depending on where the mouse is when the button is
8144 // released, but since `this.pressed` will no longer be true, the second call will be ignored.
8145 this.onMouseKeyUp( e );
8146 };
8147
8148 /**
8149 * Handle mouse up and key up events.
8150 *
8151 * @protected
8152 * @param {jQuery.Event} e Mouse up or key up event
8153 */
8154 OO.ui.ToolGroup.prototype.onMouseKeyUp = function ( e ) {
8155 var tool = this.getTargetTool( e );
8156
8157 if (
8158 !this.isDisabled() && this.pressed && this.pressed === tool &&
8159 ( e.which === 1 || e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
8160 ) {
8161 this.pressed.onSelect();
8162 this.pressed = null;
8163 return false;
8164 }
8165
8166 this.pressed = null;
8167 };
8168
8169 /**
8170 * Handle mouse over and focus events.
8171 *
8172 * @protected
8173 * @param {jQuery.Event} e Mouse over or focus event
8174 */
8175 OO.ui.ToolGroup.prototype.onMouseOverFocus = function ( e ) {
8176 var tool = this.getTargetTool( e );
8177
8178 if ( this.pressed && this.pressed === tool ) {
8179 this.pressed.setActive( true );
8180 }
8181 };
8182
8183 /**
8184 * Handle mouse out and blur events.
8185 *
8186 * @protected
8187 * @param {jQuery.Event} e Mouse out or blur event
8188 */
8189 OO.ui.ToolGroup.prototype.onMouseOutBlur = function ( e ) {
8190 var tool = this.getTargetTool( e );
8191
8192 if ( this.pressed && this.pressed === tool ) {
8193 this.pressed.setActive( false );
8194 }
8195 };
8196
8197 /**
8198 * Get the closest tool to a jQuery.Event.
8199 *
8200 * Only tool links are considered, which prevents other elements in the tool such as popups from
8201 * triggering tool group interactions.
8202 *
8203 * @private
8204 * @param {jQuery.Event} e
8205 * @return {OO.ui.Tool|null} Tool, `null` if none was found
8206 */
8207 OO.ui.ToolGroup.prototype.getTargetTool = function ( e ) {
8208 var tool,
8209 $item = $( e.target ).closest( '.oo-ui-tool-link' );
8210
8211 if ( $item.length ) {
8212 tool = $item.parent().data( 'oo-ui-tool' );
8213 }
8214
8215 return tool && !tool.isDisabled() ? tool : null;
8216 };
8217
8218 /**
8219 * Handle tool registry register events.
8220 *
8221 * If a tool is registered after the group is created, we must repopulate the list to account for:
8222 *
8223 * - a tool being added that may be included
8224 * - a tool already included being overridden
8225 *
8226 * @protected
8227 * @param {string} name Symbolic name of tool
8228 */
8229 OO.ui.ToolGroup.prototype.onToolFactoryRegister = function () {
8230 this.populate();
8231 };
8232
8233 /**
8234 * Get the toolbar that contains the toolgroup.
8235 *
8236 * @return {OO.ui.Toolbar} Toolbar that contains the toolgroup
8237 */
8238 OO.ui.ToolGroup.prototype.getToolbar = function () {
8239 return this.toolbar;
8240 };
8241
8242 /**
8243 * Add and remove tools based on configuration.
8244 */
8245 OO.ui.ToolGroup.prototype.populate = function () {
8246 var i, len, name, tool,
8247 toolFactory = this.toolbar.getToolFactory(),
8248 names = {},
8249 add = [],
8250 remove = [],
8251 list = this.toolbar.getToolFactory().getTools(
8252 this.include, this.exclude, this.promote, this.demote
8253 );
8254
8255 // Build a list of needed tools
8256 for ( i = 0, len = list.length; i < len; i++ ) {
8257 name = list[ i ];
8258 if (
8259 // Tool exists
8260 toolFactory.lookup( name ) &&
8261 // Tool is available or is already in this group
8262 ( this.toolbar.isToolAvailable( name ) || this.tools[ name ] )
8263 ) {
8264 // Hack to prevent infinite recursion via ToolGroupTool. We need to reserve the tool before
8265 // creating it, but we can't call reserveTool() yet because we haven't created the tool.
8266 this.toolbar.tools[ name ] = true;
8267 tool = this.tools[ name ];
8268 if ( !tool ) {
8269 // Auto-initialize tools on first use
8270 this.tools[ name ] = tool = toolFactory.create( name, this );
8271 tool.updateTitle();
8272 }
8273 this.toolbar.reserveTool( tool );
8274 add.push( tool );
8275 names[ name ] = true;
8276 }
8277 }
8278 // Remove tools that are no longer needed
8279 for ( name in this.tools ) {
8280 if ( !names[ name ] ) {
8281 this.tools[ name ].destroy();
8282 this.toolbar.releaseTool( this.tools[ name ] );
8283 remove.push( this.tools[ name ] );
8284 delete this.tools[ name ];
8285 }
8286 }
8287 if ( remove.length ) {
8288 this.removeItems( remove );
8289 }
8290 // Update emptiness state
8291 if ( add.length ) {
8292 this.$element.removeClass( 'oo-ui-toolGroup-empty' );
8293 } else {
8294 this.$element.addClass( 'oo-ui-toolGroup-empty' );
8295 }
8296 // Re-add tools (moving existing ones to new locations)
8297 this.addItems( add );
8298 // Disabled state may depend on items
8299 this.updateDisabled();
8300 };
8301
8302 /**
8303 * Destroy toolgroup.
8304 */
8305 OO.ui.ToolGroup.prototype.destroy = function () {
8306 var name;
8307
8308 this.clearItems();
8309 this.toolbar.getToolFactory().disconnect( this );
8310 for ( name in this.tools ) {
8311 this.toolbar.releaseTool( this.tools[ name ] );
8312 this.tools[ name ].disconnect( this ).destroy();
8313 delete this.tools[ name ];
8314 }
8315 this.$element.remove();
8316 };
8317
8318 /**
8319 * MessageDialogs display a confirmation or alert message. By default, the rendered dialog box
8320 * consists of a header that contains the dialog title, a body with the message, and a footer that
8321 * contains any {@link OO.ui.ActionWidget action widgets}. The MessageDialog class is the only type
8322 * of {@link OO.ui.Dialog dialog} that is usually instantiated directly.
8323 *
8324 * There are two basic types of message dialogs, confirmation and alert:
8325 *
8326 * - **confirmation**: the dialog title describes what a progressive action will do and the message provides
8327 * more details about the consequences.
8328 * - **alert**: the dialog title describes which event occurred and the message provides more information
8329 * about why the event occurred.
8330 *
8331 * The MessageDialog class specifies two actions: ‘accept’, the primary
8332 * action (e.g., ‘ok’) and ‘reject,’ the safe action (e.g., ‘cancel’). Both will close the window,
8333 * passing along the selected action.
8334 *
8335 * For more information and examples, please see the [OOjs UI documentation on MediaWiki][1].
8336 *
8337 * @example
8338 * // Example: Creating and opening a message dialog window.
8339 * var messageDialog = new OO.ui.MessageDialog();
8340 *
8341 * // Create and append a window manager.
8342 * var windowManager = new OO.ui.WindowManager();
8343 * $( 'body' ).append( windowManager.$element );
8344 * windowManager.addWindows( [ messageDialog ] );
8345 * // Open the window.
8346 * windowManager.openWindow( messageDialog, {
8347 * title: 'Basic message dialog',
8348 * message: 'This is the message'
8349 * } );
8350 *
8351 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Message_Dialogs
8352 *
8353 * @class
8354 * @extends OO.ui.Dialog
8355 *
8356 * @constructor
8357 * @param {Object} [config] Configuration options
8358 */
8359 OO.ui.MessageDialog = function OoUiMessageDialog( config ) {
8360 // Parent constructor
8361 OO.ui.MessageDialog.parent.call( this, config );
8362
8363 // Properties
8364 this.verticalActionLayout = null;
8365
8366 // Initialization
8367 this.$element.addClass( 'oo-ui-messageDialog' );
8368 };
8369
8370 /* Setup */
8371
8372 OO.inheritClass( OO.ui.MessageDialog, OO.ui.Dialog );
8373
8374 /* Static Properties */
8375
8376 OO.ui.MessageDialog.static.name = 'message';
8377
8378 OO.ui.MessageDialog.static.size = 'small';
8379
8380 OO.ui.MessageDialog.static.verbose = false;
8381
8382 /**
8383 * Dialog title.
8384 *
8385 * The title of a confirmation dialog describes what a progressive action will do. The
8386 * title of an alert dialog describes which event occurred.
8387 *
8388 * @static
8389 * @inheritable
8390 * @property {jQuery|string|Function|null}
8391 */
8392 OO.ui.MessageDialog.static.title = null;
8393
8394 /**
8395 * The message displayed in the dialog body.
8396 *
8397 * A confirmation message describes the consequences of a progressive action. An alert
8398 * message describes why an event occurred.
8399 *
8400 * @static
8401 * @inheritable
8402 * @property {jQuery|string|Function|null}
8403 */
8404 OO.ui.MessageDialog.static.message = null;
8405
8406 OO.ui.MessageDialog.static.actions = [
8407 { action: 'accept', label: OO.ui.deferMsg( 'ooui-dialog-message-accept' ), flags: 'primary' },
8408 { action: 'reject', label: OO.ui.deferMsg( 'ooui-dialog-message-reject' ), flags: 'safe' }
8409 ];
8410
8411 /* Methods */
8412
8413 /**
8414 * @inheritdoc
8415 */
8416 OO.ui.MessageDialog.prototype.setManager = function ( manager ) {
8417 OO.ui.MessageDialog.parent.prototype.setManager.call( this, manager );
8418
8419 // Events
8420 this.manager.connect( this, {
8421 resize: 'onResize'
8422 } );
8423
8424 return this;
8425 };
8426
8427 /**
8428 * @inheritdoc
8429 */
8430 OO.ui.MessageDialog.prototype.onActionResize = function ( action ) {
8431 this.fitActions();
8432 return OO.ui.MessageDialog.parent.prototype.onActionResize.call( this, action );
8433 };
8434
8435 /**
8436 * Handle window resized events.
8437 *
8438 * @private
8439 */
8440 OO.ui.MessageDialog.prototype.onResize = function () {
8441 var dialog = this;
8442 dialog.fitActions();
8443 // Wait for CSS transition to finish and do it again :(
8444 setTimeout( function () {
8445 dialog.fitActions();
8446 }, 300 );
8447 };
8448
8449 /**
8450 * Toggle action layout between vertical and horizontal.
8451 *
8452 * @private
8453 * @param {boolean} [value] Layout actions vertically, omit to toggle
8454 * @chainable
8455 */
8456 OO.ui.MessageDialog.prototype.toggleVerticalActionLayout = function ( value ) {
8457 value = value === undefined ? !this.verticalActionLayout : !!value;
8458
8459 if ( value !== this.verticalActionLayout ) {
8460 this.verticalActionLayout = value;
8461 this.$actions
8462 .toggleClass( 'oo-ui-messageDialog-actions-vertical', value )
8463 .toggleClass( 'oo-ui-messageDialog-actions-horizontal', !value );
8464 }
8465
8466 return this;
8467 };
8468
8469 /**
8470 * @inheritdoc
8471 */
8472 OO.ui.MessageDialog.prototype.getActionProcess = function ( action ) {
8473 if ( action ) {
8474 return new OO.ui.Process( function () {
8475 this.close( { action: action } );
8476 }, this );
8477 }
8478 return OO.ui.MessageDialog.parent.prototype.getActionProcess.call( this, action );
8479 };
8480
8481 /**
8482 * @inheritdoc
8483 *
8484 * @param {Object} [data] Dialog opening data
8485 * @param {jQuery|string|Function|null} [data.title] Description of the action being confirmed
8486 * @param {jQuery|string|Function|null} [data.message] Description of the action's consequence
8487 * @param {boolean} [data.verbose] Message is verbose and should be styled as a long message
8488 * @param {Object[]} [data.actions] List of OO.ui.ActionOptionWidget configuration options for each
8489 * action item
8490 */
8491 OO.ui.MessageDialog.prototype.getSetupProcess = function ( data ) {
8492 data = data || {};
8493
8494 // Parent method
8495 return OO.ui.MessageDialog.parent.prototype.getSetupProcess.call( this, data )
8496 .next( function () {
8497 this.title.setLabel(
8498 data.title !== undefined ? data.title : this.constructor.static.title
8499 );
8500 this.message.setLabel(
8501 data.message !== undefined ? data.message : this.constructor.static.message
8502 );
8503 this.message.$element.toggleClass(
8504 'oo-ui-messageDialog-message-verbose',
8505 data.verbose !== undefined ? data.verbose : this.constructor.static.verbose
8506 );
8507 }, this );
8508 };
8509
8510 /**
8511 * @inheritdoc
8512 */
8513 OO.ui.MessageDialog.prototype.getReadyProcess = function ( data ) {
8514 data = data || {};
8515
8516 // Parent method
8517 return OO.ui.MessageDialog.parent.prototype.getReadyProcess.call( this, data )
8518 .next( function () {
8519 // Focus the primary action button
8520 var actions = this.actions.get();
8521 actions = actions.filter( function ( action ) {
8522 return action.getFlags().indexOf( 'primary' ) > -1;
8523 } );
8524 if ( actions.length > 0 ) {
8525 actions[ 0 ].$button.focus();
8526 }
8527 }, this );
8528 };
8529
8530 /**
8531 * @inheritdoc
8532 */
8533 OO.ui.MessageDialog.prototype.getBodyHeight = function () {
8534 var bodyHeight, oldOverflow,
8535 $scrollable = this.container.$element;
8536
8537 oldOverflow = $scrollable[ 0 ].style.overflow;
8538 $scrollable[ 0 ].style.overflow = 'hidden';
8539
8540 OO.ui.Element.static.reconsiderScrollbars( $scrollable[ 0 ] );
8541
8542 bodyHeight = this.text.$element.outerHeight( true );
8543 $scrollable[ 0 ].style.overflow = oldOverflow;
8544
8545 return bodyHeight;
8546 };
8547
8548 /**
8549 * @inheritdoc
8550 */
8551 OO.ui.MessageDialog.prototype.setDimensions = function ( dim ) {
8552 var $scrollable = this.container.$element;
8553 OO.ui.MessageDialog.parent.prototype.setDimensions.call( this, dim );
8554
8555 // Twiddle the overflow property, otherwise an unnecessary scrollbar will be produced.
8556 // Need to do it after transition completes (250ms), add 50ms just in case.
8557 setTimeout( function () {
8558 var oldOverflow = $scrollable[ 0 ].style.overflow;
8559 $scrollable[ 0 ].style.overflow = 'hidden';
8560
8561 OO.ui.Element.static.reconsiderScrollbars( $scrollable[ 0 ] );
8562
8563 $scrollable[ 0 ].style.overflow = oldOverflow;
8564 }, 300 );
8565
8566 return this;
8567 };
8568
8569 /**
8570 * @inheritdoc
8571 */
8572 OO.ui.MessageDialog.prototype.initialize = function () {
8573 // Parent method
8574 OO.ui.MessageDialog.parent.prototype.initialize.call( this );
8575
8576 // Properties
8577 this.$actions = $( '<div>' );
8578 this.container = new OO.ui.PanelLayout( {
8579 scrollable: true, classes: [ 'oo-ui-messageDialog-container' ]
8580 } );
8581 this.text = new OO.ui.PanelLayout( {
8582 padded: true, expanded: false, classes: [ 'oo-ui-messageDialog-text' ]
8583 } );
8584 this.message = new OO.ui.LabelWidget( {
8585 classes: [ 'oo-ui-messageDialog-message' ]
8586 } );
8587
8588 // Initialization
8589 this.title.$element.addClass( 'oo-ui-messageDialog-title' );
8590 this.$content.addClass( 'oo-ui-messageDialog-content' );
8591 this.container.$element.append( this.text.$element );
8592 this.text.$element.append( this.title.$element, this.message.$element );
8593 this.$body.append( this.container.$element );
8594 this.$actions.addClass( 'oo-ui-messageDialog-actions' );
8595 this.$foot.append( this.$actions );
8596 };
8597
8598 /**
8599 * @inheritdoc
8600 */
8601 OO.ui.MessageDialog.prototype.attachActions = function () {
8602 var i, len, other, special, others;
8603
8604 // Parent method
8605 OO.ui.MessageDialog.parent.prototype.attachActions.call( this );
8606
8607 special = this.actions.getSpecial();
8608 others = this.actions.getOthers();
8609
8610 if ( special.safe ) {
8611 this.$actions.append( special.safe.$element );
8612 special.safe.toggleFramed( false );
8613 }
8614 if ( others.length ) {
8615 for ( i = 0, len = others.length; i < len; i++ ) {
8616 other = others[ i ];
8617 this.$actions.append( other.$element );
8618 other.toggleFramed( false );
8619 }
8620 }
8621 if ( special.primary ) {
8622 this.$actions.append( special.primary.$element );
8623 special.primary.toggleFramed( false );
8624 }
8625
8626 if ( !this.isOpening() ) {
8627 // If the dialog is currently opening, this will be called automatically soon.
8628 // This also calls #fitActions.
8629 this.updateSize();
8630 }
8631 };
8632
8633 /**
8634 * Fit action actions into columns or rows.
8635 *
8636 * Columns will be used if all labels can fit without overflow, otherwise rows will be used.
8637 *
8638 * @private
8639 */
8640 OO.ui.MessageDialog.prototype.fitActions = function () {
8641 var i, len, action,
8642 previous = this.verticalActionLayout,
8643 actions = this.actions.get();
8644
8645 // Detect clipping
8646 this.toggleVerticalActionLayout( false );
8647 for ( i = 0, len = actions.length; i < len; i++ ) {
8648 action = actions[ i ];
8649 if ( action.$element.innerWidth() < action.$label.outerWidth( true ) ) {
8650 this.toggleVerticalActionLayout( true );
8651 break;
8652 }
8653 }
8654
8655 // Move the body out of the way of the foot
8656 this.$body.css( 'bottom', this.$foot.outerHeight( true ) );
8657
8658 if ( this.verticalActionLayout !== previous ) {
8659 // We changed the layout, window height might need to be updated.
8660 this.updateSize();
8661 }
8662 };
8663
8664 /**
8665 * ProcessDialog windows encapsulate a {@link OO.ui.Process process} and all of the code necessary
8666 * to complete it. If the process terminates with an error, a customizable {@link OO.ui.Error error
8667 * interface} alerts users to the trouble, permitting the user to dismiss the error and try again when
8668 * relevant. The ProcessDialog class is always extended and customized with the actions and content
8669 * required for each process.
8670 *
8671 * The process dialog box consists of a header that visually represents the ‘working’ state of long
8672 * processes with an animation. The header contains the dialog title as well as
8673 * two {@link OO.ui.ActionWidget action widgets}: a ‘safe’ action on the left (e.g., ‘Cancel’) and
8674 * a ‘primary’ action on the right (e.g., ‘Done’).
8675 *
8676 * Like other windows, the process dialog is managed by a {@link OO.ui.WindowManager window manager}.
8677 * Please see the [OOjs UI documentation on MediaWiki][1] for more information and examples.
8678 *
8679 * @example
8680 * // Example: Creating and opening a process dialog window.
8681 * function MyProcessDialog( config ) {
8682 * MyProcessDialog.parent.call( this, config );
8683 * }
8684 * OO.inheritClass( MyProcessDialog, OO.ui.ProcessDialog );
8685 *
8686 * MyProcessDialog.static.title = 'Process dialog';
8687 * MyProcessDialog.static.actions = [
8688 * { action: 'save', label: 'Done', flags: 'primary' },
8689 * { label: 'Cancel', flags: 'safe' }
8690 * ];
8691 *
8692 * MyProcessDialog.prototype.initialize = function () {
8693 * MyProcessDialog.parent.prototype.initialize.apply( this, arguments );
8694 * this.content = new OO.ui.PanelLayout( { padded: true, expanded: false } );
8695 * this.content.$element.append( '<p>This is a process dialog window. The header contains the title and two buttons: \'Cancel\' (a safe action) on the left and \'Done\' (a primary action) on the right.</p>' );
8696 * this.$body.append( this.content.$element );
8697 * };
8698 * MyProcessDialog.prototype.getActionProcess = function ( action ) {
8699 * var dialog = this;
8700 * if ( action ) {
8701 * return new OO.ui.Process( function () {
8702 * dialog.close( { action: action } );
8703 * } );
8704 * }
8705 * return MyProcessDialog.parent.prototype.getActionProcess.call( this, action );
8706 * };
8707 *
8708 * var windowManager = new OO.ui.WindowManager();
8709 * $( 'body' ).append( windowManager.$element );
8710 *
8711 * var dialog = new MyProcessDialog();
8712 * windowManager.addWindows( [ dialog ] );
8713 * windowManager.openWindow( dialog );
8714 *
8715 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs
8716 *
8717 * @abstract
8718 * @class
8719 * @extends OO.ui.Dialog
8720 *
8721 * @constructor
8722 * @param {Object} [config] Configuration options
8723 */
8724 OO.ui.ProcessDialog = function OoUiProcessDialog( config ) {
8725 // Parent constructor
8726 OO.ui.ProcessDialog.parent.call( this, config );
8727
8728 // Properties
8729 this.fitOnOpen = false;
8730
8731 // Initialization
8732 this.$element.addClass( 'oo-ui-processDialog' );
8733 };
8734
8735 /* Setup */
8736
8737 OO.inheritClass( OO.ui.ProcessDialog, OO.ui.Dialog );
8738
8739 /* Methods */
8740
8741 /**
8742 * Handle dismiss button click events.
8743 *
8744 * Hides errors.
8745 *
8746 * @private
8747 */
8748 OO.ui.ProcessDialog.prototype.onDismissErrorButtonClick = function () {
8749 this.hideErrors();
8750 };
8751
8752 /**
8753 * Handle retry button click events.
8754 *
8755 * Hides errors and then tries again.
8756 *
8757 * @private
8758 */
8759 OO.ui.ProcessDialog.prototype.onRetryButtonClick = function () {
8760 this.hideErrors();
8761 this.executeAction( this.currentAction );
8762 };
8763
8764 /**
8765 * @inheritdoc
8766 */
8767 OO.ui.ProcessDialog.prototype.onActionResize = function ( action ) {
8768 if ( this.actions.isSpecial( action ) ) {
8769 this.fitLabel();
8770 }
8771 return OO.ui.ProcessDialog.parent.prototype.onActionResize.call( this, action );
8772 };
8773
8774 /**
8775 * @inheritdoc
8776 */
8777 OO.ui.ProcessDialog.prototype.initialize = function () {
8778 // Parent method
8779 OO.ui.ProcessDialog.parent.prototype.initialize.call( this );
8780
8781 // Properties
8782 this.$navigation = $( '<div>' );
8783 this.$location = $( '<div>' );
8784 this.$safeActions = $( '<div>' );
8785 this.$primaryActions = $( '<div>' );
8786 this.$otherActions = $( '<div>' );
8787 this.dismissButton = new OO.ui.ButtonWidget( {
8788 label: OO.ui.msg( 'ooui-dialog-process-dismiss' )
8789 } );
8790 this.retryButton = new OO.ui.ButtonWidget();
8791 this.$errors = $( '<div>' );
8792 this.$errorsTitle = $( '<div>' );
8793
8794 // Events
8795 this.dismissButton.connect( this, { click: 'onDismissErrorButtonClick' } );
8796 this.retryButton.connect( this, { click: 'onRetryButtonClick' } );
8797
8798 // Initialization
8799 this.title.$element.addClass( 'oo-ui-processDialog-title' );
8800 this.$location
8801 .append( this.title.$element )
8802 .addClass( 'oo-ui-processDialog-location' );
8803 this.$safeActions.addClass( 'oo-ui-processDialog-actions-safe' );
8804 this.$primaryActions.addClass( 'oo-ui-processDialog-actions-primary' );
8805 this.$otherActions.addClass( 'oo-ui-processDialog-actions-other' );
8806 this.$errorsTitle
8807 .addClass( 'oo-ui-processDialog-errors-title' )
8808 .text( OO.ui.msg( 'ooui-dialog-process-error' ) );
8809 this.$errors
8810 .addClass( 'oo-ui-processDialog-errors oo-ui-element-hidden' )
8811 .append( this.$errorsTitle, this.dismissButton.$element, this.retryButton.$element );
8812 this.$content
8813 .addClass( 'oo-ui-processDialog-content' )
8814 .append( this.$errors );
8815 this.$navigation
8816 .addClass( 'oo-ui-processDialog-navigation' )
8817 .append( this.$safeActions, this.$location, this.$primaryActions );
8818 this.$head.append( this.$navigation );
8819 this.$foot.append( this.$otherActions );
8820 };
8821
8822 /**
8823 * @inheritdoc
8824 */
8825 OO.ui.ProcessDialog.prototype.getActionWidgets = function ( actions ) {
8826 var i, len, widgets = [];
8827 for ( i = 0, len = actions.length; i < len; i++ ) {
8828 widgets.push(
8829 new OO.ui.ActionWidget( $.extend( { framed: true }, actions[ i ] ) )
8830 );
8831 }
8832 return widgets;
8833 };
8834
8835 /**
8836 * @inheritdoc
8837 */
8838 OO.ui.ProcessDialog.prototype.attachActions = function () {
8839 var i, len, other, special, others;
8840
8841 // Parent method
8842 OO.ui.ProcessDialog.parent.prototype.attachActions.call( this );
8843
8844 special = this.actions.getSpecial();
8845 others = this.actions.getOthers();
8846 if ( special.primary ) {
8847 this.$primaryActions.append( special.primary.$element );
8848 }
8849 for ( i = 0, len = others.length; i < len; i++ ) {
8850 other = others[ i ];
8851 this.$otherActions.append( other.$element );
8852 }
8853 if ( special.safe ) {
8854 this.$safeActions.append( special.safe.$element );
8855 }
8856
8857 this.fitLabel();
8858 this.$body.css( 'bottom', this.$foot.outerHeight( true ) );
8859 };
8860
8861 /**
8862 * @inheritdoc
8863 */
8864 OO.ui.ProcessDialog.prototype.executeAction = function ( action ) {
8865 var process = this;
8866 return OO.ui.ProcessDialog.parent.prototype.executeAction.call( this, action )
8867 .fail( function ( errors ) {
8868 process.showErrors( errors || [] );
8869 } );
8870 };
8871
8872 /**
8873 * @inheritdoc
8874 */
8875 OO.ui.ProcessDialog.prototype.setDimensions = function () {
8876 // Parent method
8877 OO.ui.ProcessDialog.parent.prototype.setDimensions.apply( this, arguments );
8878
8879 this.fitLabel();
8880 };
8881
8882 /**
8883 * Fit label between actions.
8884 *
8885 * @private
8886 * @chainable
8887 */
8888 OO.ui.ProcessDialog.prototype.fitLabel = function () {
8889 var safeWidth, primaryWidth, biggerWidth, labelWidth, navigationWidth, leftWidth, rightWidth,
8890 size = this.getSizeProperties();
8891
8892 if ( typeof size.width !== 'number' ) {
8893 if ( this.isOpened() ) {
8894 navigationWidth = this.$head.width() - 20;
8895 } else if ( this.isOpening() ) {
8896 if ( !this.fitOnOpen ) {
8897 // Size is relative and the dialog isn't open yet, so wait.
8898 this.manager.opening.done( this.fitLabel.bind( this ) );
8899 this.fitOnOpen = true;
8900 }
8901 return;
8902 } else {
8903 return;
8904 }
8905 } else {
8906 navigationWidth = size.width - 20;
8907 }
8908
8909 safeWidth = this.$safeActions.is( ':visible' ) ? this.$safeActions.width() : 0;
8910 primaryWidth = this.$primaryActions.is( ':visible' ) ? this.$primaryActions.width() : 0;
8911 biggerWidth = Math.max( safeWidth, primaryWidth );
8912
8913 labelWidth = this.title.$element.width();
8914
8915 if ( 2 * biggerWidth + labelWidth < navigationWidth ) {
8916 // We have enough space to center the label
8917 leftWidth = rightWidth = biggerWidth;
8918 } else {
8919 // Let's hope we at least have enough space not to overlap, because we can't wrap the label…
8920 if ( this.getDir() === 'ltr' ) {
8921 leftWidth = safeWidth;
8922 rightWidth = primaryWidth;
8923 } else {
8924 leftWidth = primaryWidth;
8925 rightWidth = safeWidth;
8926 }
8927 }
8928
8929 this.$location.css( { paddingLeft: leftWidth, paddingRight: rightWidth } );
8930
8931 return this;
8932 };
8933
8934 /**
8935 * Handle errors that occurred during accept or reject processes.
8936 *
8937 * @private
8938 * @param {OO.ui.Error[]|OO.ui.Error} errors Errors to be handled
8939 */
8940 OO.ui.ProcessDialog.prototype.showErrors = function ( errors ) {
8941 var i, len, $item, actions,
8942 items = [],
8943 abilities = {},
8944 recoverable = true,
8945 warning = false;
8946
8947 if ( errors instanceof OO.ui.Error ) {
8948 errors = [ errors ];
8949 }
8950
8951 for ( i = 0, len = errors.length; i < len; i++ ) {
8952 if ( !errors[ i ].isRecoverable() ) {
8953 recoverable = false;
8954 }
8955 if ( errors[ i ].isWarning() ) {
8956 warning = true;
8957 }
8958 $item = $( '<div>' )
8959 .addClass( 'oo-ui-processDialog-error' )
8960 .append( errors[ i ].getMessage() );
8961 items.push( $item[ 0 ] );
8962 }
8963 this.$errorItems = $( items );
8964 if ( recoverable ) {
8965 abilities[ this.currentAction ] = true;
8966 // Copy the flags from the first matching action
8967 actions = this.actions.get( { actions: this.currentAction } );
8968 if ( actions.length ) {
8969 this.retryButton.clearFlags().setFlags( actions[ 0 ].getFlags() );
8970 }
8971 } else {
8972 abilities[ this.currentAction ] = false;
8973 this.actions.setAbilities( abilities );
8974 }
8975 if ( warning ) {
8976 this.retryButton.setLabel( OO.ui.msg( 'ooui-dialog-process-continue' ) );
8977 } else {
8978 this.retryButton.setLabel( OO.ui.msg( 'ooui-dialog-process-retry' ) );
8979 }
8980 this.retryButton.toggle( recoverable );
8981 this.$errorsTitle.after( this.$errorItems );
8982 this.$errors.removeClass( 'oo-ui-element-hidden' ).scrollTop( 0 );
8983 };
8984
8985 /**
8986 * Hide errors.
8987 *
8988 * @private
8989 */
8990 OO.ui.ProcessDialog.prototype.hideErrors = function () {
8991 this.$errors.addClass( 'oo-ui-element-hidden' );
8992 if ( this.$errorItems ) {
8993 this.$errorItems.remove();
8994 this.$errorItems = null;
8995 }
8996 };
8997
8998 /**
8999 * @inheritdoc
9000 */
9001 OO.ui.ProcessDialog.prototype.getTeardownProcess = function ( data ) {
9002 // Parent method
9003 return OO.ui.ProcessDialog.parent.prototype.getTeardownProcess.call( this, data )
9004 .first( function () {
9005 // Make sure to hide errors
9006 this.hideErrors();
9007 this.fitOnOpen = false;
9008 }, this );
9009 };
9010
9011 /**
9012 * FieldLayouts are used with OO.ui.FieldsetLayout. Each FieldLayout requires a field-widget,
9013 * which is a widget that is specified by reference before any optional configuration settings.
9014 *
9015 * Field layouts can be configured with help text and/or labels. Labels are aligned in one of four ways:
9016 *
9017 * - **left**: The label is placed before the field-widget and aligned with the left margin.
9018 * A left-alignment is used for forms with many fields.
9019 * - **right**: The label is placed before the field-widget and aligned to the right margin.
9020 * A right-alignment is used for long but familiar forms which users tab through,
9021 * verifying the current field with a quick glance at the label.
9022 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
9023 * that users fill out from top to bottom.
9024 * - **inline**: The label is placed after the field-widget and aligned to the left.
9025 * An inline-alignment is best used with checkboxes or radio buttons.
9026 *
9027 * Help text is accessed via a help icon that appears in the upper right corner of the rendered field layout.
9028 * Please see the [OOjs UI documentation on MediaWiki] [1] for examples and more information.
9029 *
9030 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Fields_and_Fieldsets
9031 * @class
9032 * @extends OO.ui.Layout
9033 * @mixins OO.ui.mixin.LabelElement
9034 * @mixins OO.ui.mixin.TitledElement
9035 *
9036 * @constructor
9037 * @param {OO.ui.Widget} fieldWidget Field widget
9038 * @param {Object} [config] Configuration options
9039 * @cfg {string} [align='left'] Alignment of the label: 'left', 'right', 'top' or 'inline'
9040 * @cfg {Array} [errors] Error messages about the widget, which will be displayed below the widget.
9041 * The array may contain strings or OO.ui.HtmlSnippet instances.
9042 * @cfg {Array} [notices] Notices about the widget, which will be displayed below the widget.
9043 * The array may contain strings or OO.ui.HtmlSnippet instances.
9044 * @cfg {string|OO.ui.HtmlSnippet} [help] Help text. When help text is specified, a "help" icon will appear
9045 * in the upper-right corner of the rendered field; clicking it will display the text in a popup.
9046 * For important messages, you are advised to use `notices`, as they are always shown.
9047 *
9048 * @throws {Error} An error is thrown if no widget is specified
9049 */
9050 OO.ui.FieldLayout = function OoUiFieldLayout( fieldWidget, config ) {
9051 var hasInputWidget, div;
9052
9053 // Allow passing positional parameters inside the config object
9054 if ( OO.isPlainObject( fieldWidget ) && config === undefined ) {
9055 config = fieldWidget;
9056 fieldWidget = config.fieldWidget;
9057 }
9058
9059 // Make sure we have required constructor arguments
9060 if ( fieldWidget === undefined ) {
9061 throw new Error( 'Widget not found' );
9062 }
9063
9064 hasInputWidget = fieldWidget.constructor.static.supportsSimpleLabel;
9065
9066 // Configuration initialization
9067 config = $.extend( { align: 'left' }, config );
9068
9069 // Parent constructor
9070 OO.ui.FieldLayout.parent.call( this, config );
9071
9072 // Mixin constructors
9073 OO.ui.mixin.LabelElement.call( this, config );
9074 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$label } ) );
9075
9076 // Properties
9077 this.fieldWidget = fieldWidget;
9078 this.errors = [];
9079 this.notices = [];
9080 this.$field = $( '<div>' );
9081 this.$messages = $( '<ul>' );
9082 this.$body = $( '<' + ( hasInputWidget ? 'label' : 'div' ) + '>' );
9083 this.align = null;
9084 if ( config.help ) {
9085 this.popupButtonWidget = new OO.ui.PopupButtonWidget( {
9086 classes: [ 'oo-ui-fieldLayout-help' ],
9087 framed: false,
9088 icon: 'info'
9089 } );
9090
9091 div = $( '<div>' );
9092 if ( config.help instanceof OO.ui.HtmlSnippet ) {
9093 div.html( config.help.toString() );
9094 } else {
9095 div.text( config.help );
9096 }
9097 this.popupButtonWidget.getPopup().$body.append(
9098 div.addClass( 'oo-ui-fieldLayout-help-content' )
9099 );
9100 this.$help = this.popupButtonWidget.$element;
9101 } else {
9102 this.$help = $( [] );
9103 }
9104
9105 // Events
9106 if ( hasInputWidget ) {
9107 this.$label.on( 'click', this.onLabelClick.bind( this ) );
9108 }
9109 this.fieldWidget.connect( this, { disable: 'onFieldDisable' } );
9110
9111 // Initialization
9112 this.$element
9113 .addClass( 'oo-ui-fieldLayout' )
9114 .append( this.$help, this.$body );
9115 this.$body.addClass( 'oo-ui-fieldLayout-body' );
9116 this.$messages.addClass( 'oo-ui-fieldLayout-messages' );
9117 this.$field
9118 .addClass( 'oo-ui-fieldLayout-field' )
9119 .toggleClass( 'oo-ui-fieldLayout-disable', this.fieldWidget.isDisabled() )
9120 .append( this.fieldWidget.$element );
9121
9122 this.setErrors( config.errors || [] );
9123 this.setNotices( config.notices || [] );
9124 this.setAlignment( config.align );
9125 };
9126
9127 /* Setup */
9128
9129 OO.inheritClass( OO.ui.FieldLayout, OO.ui.Layout );
9130 OO.mixinClass( OO.ui.FieldLayout, OO.ui.mixin.LabelElement );
9131 OO.mixinClass( OO.ui.FieldLayout, OO.ui.mixin.TitledElement );
9132
9133 /* Methods */
9134
9135 /**
9136 * Handle field disable events.
9137 *
9138 * @private
9139 * @param {boolean} value Field is disabled
9140 */
9141 OO.ui.FieldLayout.prototype.onFieldDisable = function ( value ) {
9142 this.$element.toggleClass( 'oo-ui-fieldLayout-disabled', value );
9143 };
9144
9145 /**
9146 * Handle label mouse click events.
9147 *
9148 * @private
9149 * @param {jQuery.Event} e Mouse click event
9150 */
9151 OO.ui.FieldLayout.prototype.onLabelClick = function () {
9152 this.fieldWidget.simulateLabelClick();
9153 return false;
9154 };
9155
9156 /**
9157 * Get the widget contained by the field.
9158 *
9159 * @return {OO.ui.Widget} Field widget
9160 */
9161 OO.ui.FieldLayout.prototype.getField = function () {
9162 return this.fieldWidget;
9163 };
9164
9165 /**
9166 * @protected
9167 * @param {string} kind 'error' or 'notice'
9168 * @param {string|OO.ui.HtmlSnippet} text
9169 * @return {jQuery}
9170 */
9171 OO.ui.FieldLayout.prototype.makeMessage = function ( kind, text ) {
9172 var $listItem, $icon, message;
9173 $listItem = $( '<li>' );
9174 if ( kind === 'error' ) {
9175 $icon = new OO.ui.IconWidget( { icon: 'alert', flags: [ 'warning' ] } ).$element;
9176 } else if ( kind === 'notice' ) {
9177 $icon = new OO.ui.IconWidget( { icon: 'info' } ).$element;
9178 } else {
9179 $icon = '';
9180 }
9181 message = new OO.ui.LabelWidget( { label: text } );
9182 $listItem
9183 .append( $icon, message.$element )
9184 .addClass( 'oo-ui-fieldLayout-messages-' + kind );
9185 return $listItem;
9186 };
9187
9188 /**
9189 * Set the field alignment mode.
9190 *
9191 * @private
9192 * @param {string} value Alignment mode, either 'left', 'right', 'top' or 'inline'
9193 * @chainable
9194 */
9195 OO.ui.FieldLayout.prototype.setAlignment = function ( value ) {
9196 if ( value !== this.align ) {
9197 // Default to 'left'
9198 if ( [ 'left', 'right', 'top', 'inline' ].indexOf( value ) === -1 ) {
9199 value = 'left';
9200 }
9201 // Reorder elements
9202 if ( value === 'inline' ) {
9203 this.$body.append( this.$field, this.$label );
9204 } else {
9205 this.$body.append( this.$label, this.$field );
9206 }
9207 // Set classes. The following classes can be used here:
9208 // * oo-ui-fieldLayout-align-left
9209 // * oo-ui-fieldLayout-align-right
9210 // * oo-ui-fieldLayout-align-top
9211 // * oo-ui-fieldLayout-align-inline
9212 if ( this.align ) {
9213 this.$element.removeClass( 'oo-ui-fieldLayout-align-' + this.align );
9214 }
9215 this.$element.addClass( 'oo-ui-fieldLayout-align-' + value );
9216 this.align = value;
9217 }
9218
9219 return this;
9220 };
9221
9222 /**
9223 * Set the list of error messages.
9224 *
9225 * @param {Array} errors Error messages about the widget, which will be displayed below the widget.
9226 * The array may contain strings or OO.ui.HtmlSnippet instances.
9227 * @chainable
9228 */
9229 OO.ui.FieldLayout.prototype.setErrors = function ( errors ) {
9230 this.errors = errors.slice();
9231 this.updateMessages();
9232 return this;
9233 };
9234
9235 /**
9236 * Set the list of notice messages.
9237 *
9238 * @param {Array} notices Notices about the widget, which will be displayed below the widget.
9239 * The array may contain strings or OO.ui.HtmlSnippet instances.
9240 * @chainable
9241 */
9242 OO.ui.FieldLayout.prototype.setNotices = function ( notices ) {
9243 this.notices = notices.slice();
9244 this.updateMessages();
9245 return this;
9246 };
9247
9248 /**
9249 * Update the rendering of error and notice messages.
9250 *
9251 * @private
9252 */
9253 OO.ui.FieldLayout.prototype.updateMessages = function () {
9254 var i;
9255 this.$messages.empty();
9256
9257 if ( this.errors.length || this.notices.length ) {
9258 this.$body.after( this.$messages );
9259 } else {
9260 this.$messages.remove();
9261 return;
9262 }
9263
9264 for ( i = 0; i < this.notices.length; i++ ) {
9265 this.$messages.append( this.makeMessage( 'notice', this.notices[ i ] ) );
9266 }
9267 for ( i = 0; i < this.errors.length; i++ ) {
9268 this.$messages.append( this.makeMessage( 'error', this.errors[ i ] ) );
9269 }
9270 };
9271
9272 /**
9273 * ActionFieldLayouts are used with OO.ui.FieldsetLayout. The layout consists of a field-widget, a button,
9274 * and an optional label and/or help text. The field-widget (e.g., a {@link OO.ui.TextInputWidget TextInputWidget}),
9275 * is required and is specified before any optional configuration settings.
9276 *
9277 * Labels can be aligned in one of four ways:
9278 *
9279 * - **left**: The label is placed before the field-widget and aligned with the left margin.
9280 * A left-alignment is used for forms with many fields.
9281 * - **right**: The label is placed before the field-widget and aligned to the right margin.
9282 * A right-alignment is used for long but familiar forms which users tab through,
9283 * verifying the current field with a quick glance at the label.
9284 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
9285 * that users fill out from top to bottom.
9286 * - **inline**: The label is placed after the field-widget and aligned to the left.
9287 * An inline-alignment is best used with checkboxes or radio buttons.
9288 *
9289 * Help text is accessed via a help icon that appears in the upper right corner of the rendered field layout when help
9290 * text is specified.
9291 *
9292 * @example
9293 * // Example of an ActionFieldLayout
9294 * var actionFieldLayout = new OO.ui.ActionFieldLayout(
9295 * new OO.ui.TextInputWidget( {
9296 * placeholder: 'Field widget'
9297 * } ),
9298 * new OO.ui.ButtonWidget( {
9299 * label: 'Button'
9300 * } ),
9301 * {
9302 * label: 'An ActionFieldLayout. This label is aligned top',
9303 * align: 'top',
9304 * help: 'This is help text'
9305 * }
9306 * );
9307 *
9308 * $( 'body' ).append( actionFieldLayout.$element );
9309 *
9310 * @class
9311 * @extends OO.ui.FieldLayout
9312 *
9313 * @constructor
9314 * @param {OO.ui.Widget} fieldWidget Field widget
9315 * @param {OO.ui.ButtonWidget} buttonWidget Button widget
9316 */
9317 OO.ui.ActionFieldLayout = function OoUiActionFieldLayout( fieldWidget, buttonWidget, config ) {
9318 // Allow passing positional parameters inside the config object
9319 if ( OO.isPlainObject( fieldWidget ) && config === undefined ) {
9320 config = fieldWidget;
9321 fieldWidget = config.fieldWidget;
9322 buttonWidget = config.buttonWidget;
9323 }
9324
9325 // Parent constructor
9326 OO.ui.ActionFieldLayout.parent.call( this, fieldWidget, config );
9327
9328 // Properties
9329 this.buttonWidget = buttonWidget;
9330 this.$button = $( '<div>' );
9331 this.$input = $( '<div>' );
9332
9333 // Initialization
9334 this.$element
9335 .addClass( 'oo-ui-actionFieldLayout' );
9336 this.$button
9337 .addClass( 'oo-ui-actionFieldLayout-button' )
9338 .append( this.buttonWidget.$element );
9339 this.$input
9340 .addClass( 'oo-ui-actionFieldLayout-input' )
9341 .append( this.fieldWidget.$element );
9342 this.$field
9343 .append( this.$input, this.$button );
9344 };
9345
9346 /* Setup */
9347
9348 OO.inheritClass( OO.ui.ActionFieldLayout, OO.ui.FieldLayout );
9349
9350 /**
9351 * FieldsetLayouts are composed of one or more {@link OO.ui.FieldLayout FieldLayouts},
9352 * which each contain an individual widget and, optionally, a label. Each Fieldset can be
9353 * configured with a label as well. For more information and examples,
9354 * please see the [OOjs UI documentation on MediaWiki][1].
9355 *
9356 * @example
9357 * // Example of a fieldset layout
9358 * var input1 = new OO.ui.TextInputWidget( {
9359 * placeholder: 'A text input field'
9360 * } );
9361 *
9362 * var input2 = new OO.ui.TextInputWidget( {
9363 * placeholder: 'A text input field'
9364 * } );
9365 *
9366 * var fieldset = new OO.ui.FieldsetLayout( {
9367 * label: 'Example of a fieldset layout'
9368 * } );
9369 *
9370 * fieldset.addItems( [
9371 * new OO.ui.FieldLayout( input1, {
9372 * label: 'Field One'
9373 * } ),
9374 * new OO.ui.FieldLayout( input2, {
9375 * label: 'Field Two'
9376 * } )
9377 * ] );
9378 * $( 'body' ).append( fieldset.$element );
9379 *
9380 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Fields_and_Fieldsets
9381 *
9382 * @class
9383 * @extends OO.ui.Layout
9384 * @mixins OO.ui.mixin.IconElement
9385 * @mixins OO.ui.mixin.LabelElement
9386 * @mixins OO.ui.mixin.GroupElement
9387 *
9388 * @constructor
9389 * @param {Object} [config] Configuration options
9390 * @cfg {OO.ui.FieldLayout[]} [items] An array of fields to add to the fieldset. See OO.ui.FieldLayout for more information about fields.
9391 */
9392 OO.ui.FieldsetLayout = function OoUiFieldsetLayout( config ) {
9393 // Configuration initialization
9394 config = config || {};
9395
9396 // Parent constructor
9397 OO.ui.FieldsetLayout.parent.call( this, config );
9398
9399 // Mixin constructors
9400 OO.ui.mixin.IconElement.call( this, config );
9401 OO.ui.mixin.LabelElement.call( this, config );
9402 OO.ui.mixin.GroupElement.call( this, config );
9403
9404 if ( config.help ) {
9405 this.popupButtonWidget = new OO.ui.PopupButtonWidget( {
9406 classes: [ 'oo-ui-fieldsetLayout-help' ],
9407 framed: false,
9408 icon: 'info'
9409 } );
9410
9411 this.popupButtonWidget.getPopup().$body.append(
9412 $( '<div>' )
9413 .text( config.help )
9414 .addClass( 'oo-ui-fieldsetLayout-help-content' )
9415 );
9416 this.$help = this.popupButtonWidget.$element;
9417 } else {
9418 this.$help = $( [] );
9419 }
9420
9421 // Initialization
9422 this.$element
9423 .addClass( 'oo-ui-fieldsetLayout' )
9424 .prepend( this.$help, this.$icon, this.$label, this.$group );
9425 if ( Array.isArray( config.items ) ) {
9426 this.addItems( config.items );
9427 }
9428 };
9429
9430 /* Setup */
9431
9432 OO.inheritClass( OO.ui.FieldsetLayout, OO.ui.Layout );
9433 OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.mixin.IconElement );
9434 OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.mixin.LabelElement );
9435 OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.mixin.GroupElement );
9436
9437 /**
9438 * FormLayouts are used to wrap {@link OO.ui.FieldsetLayout FieldsetLayouts} when you intend to use browser-based
9439 * form submission for the fields instead of handling them in JavaScript. Form layouts can be configured with an
9440 * HTML form action, an encoding type, and a method using the #action, #enctype, and #method configs, respectively.
9441 * See the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
9442 *
9443 * Only widgets from the {@link OO.ui.InputWidget InputWidget} family support form submission. It
9444 * includes standard form elements like {@link OO.ui.CheckboxInputWidget checkboxes}, {@link
9445 * OO.ui.RadioInputWidget radio buttons} and {@link OO.ui.TextInputWidget text fields}, as well as
9446 * some fancier controls. Some controls have both regular and InputWidget variants, for example
9447 * OO.ui.DropdownWidget and OO.ui.DropdownInputWidget – only the latter support form submission and
9448 * often have simplified APIs to match the capabilities of HTML forms.
9449 * See the [OOjs UI Inputs documentation on MediaWiki] [2] for more information about InputWidgets.
9450 *
9451 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Forms
9452 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
9453 *
9454 * @example
9455 * // Example of a form layout that wraps a fieldset layout
9456 * var input1 = new OO.ui.TextInputWidget( {
9457 * placeholder: 'Username'
9458 * } );
9459 * var input2 = new OO.ui.TextInputWidget( {
9460 * placeholder: 'Password',
9461 * type: 'password'
9462 * } );
9463 * var submit = new OO.ui.ButtonInputWidget( {
9464 * label: 'Submit'
9465 * } );
9466 *
9467 * var fieldset = new OO.ui.FieldsetLayout( {
9468 * label: 'A form layout'
9469 * } );
9470 * fieldset.addItems( [
9471 * new OO.ui.FieldLayout( input1, {
9472 * label: 'Username',
9473 * align: 'top'
9474 * } ),
9475 * new OO.ui.FieldLayout( input2, {
9476 * label: 'Password',
9477 * align: 'top'
9478 * } ),
9479 * new OO.ui.FieldLayout( submit )
9480 * ] );
9481 * var form = new OO.ui.FormLayout( {
9482 * items: [ fieldset ],
9483 * action: '/api/formhandler',
9484 * method: 'get'
9485 * } )
9486 * $( 'body' ).append( form.$element );
9487 *
9488 * @class
9489 * @extends OO.ui.Layout
9490 * @mixins OO.ui.mixin.GroupElement
9491 *
9492 * @constructor
9493 * @param {Object} [config] Configuration options
9494 * @cfg {string} [method] HTML form `method` attribute
9495 * @cfg {string} [action] HTML form `action` attribute
9496 * @cfg {string} [enctype] HTML form `enctype` attribute
9497 * @cfg {OO.ui.FieldsetLayout[]} [items] Fieldset layouts to add to the form layout.
9498 */
9499 OO.ui.FormLayout = function OoUiFormLayout( config ) {
9500 // Configuration initialization
9501 config = config || {};
9502
9503 // Parent constructor
9504 OO.ui.FormLayout.parent.call( this, config );
9505
9506 // Mixin constructors
9507 OO.ui.mixin.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) );
9508
9509 // Events
9510 this.$element.on( 'submit', this.onFormSubmit.bind( this ) );
9511
9512 // Make sure the action is safe
9513 if ( config.action !== undefined && !OO.ui.isSafeUrl( config.action ) ) {
9514 throw new Error( 'Potentially unsafe action provided: ' + config.action );
9515 }
9516
9517 // Initialization
9518 this.$element
9519 .addClass( 'oo-ui-formLayout' )
9520 .attr( {
9521 method: config.method,
9522 action: config.action,
9523 enctype: config.enctype
9524 } );
9525 if ( Array.isArray( config.items ) ) {
9526 this.addItems( config.items );
9527 }
9528 };
9529
9530 /* Setup */
9531
9532 OO.inheritClass( OO.ui.FormLayout, OO.ui.Layout );
9533 OO.mixinClass( OO.ui.FormLayout, OO.ui.mixin.GroupElement );
9534
9535 /* Events */
9536
9537 /**
9538 * A 'submit' event is emitted when the form is submitted.
9539 *
9540 * @event submit
9541 */
9542
9543 /* Static Properties */
9544
9545 OO.ui.FormLayout.static.tagName = 'form';
9546
9547 /* Methods */
9548
9549 /**
9550 * Handle form submit events.
9551 *
9552 * @private
9553 * @param {jQuery.Event} e Submit event
9554 * @fires submit
9555 */
9556 OO.ui.FormLayout.prototype.onFormSubmit = function () {
9557 if ( this.emit( 'submit' ) ) {
9558 return false;
9559 }
9560 };
9561
9562 /**
9563 * MenuLayouts combine a menu and a content {@link OO.ui.PanelLayout panel}. The menu is positioned relative to the content (after, before, top, or bottom)
9564 * and its size is customized with the #menuSize config. The content area will fill all remaining space.
9565 *
9566 * @example
9567 * var menuLayout = new OO.ui.MenuLayout( {
9568 * position: 'top'
9569 * } ),
9570 * menuPanel = new OO.ui.PanelLayout( { padded: true, expanded: true, scrollable: true } ),
9571 * contentPanel = new OO.ui.PanelLayout( { padded: true, expanded: true, scrollable: true } ),
9572 * select = new OO.ui.SelectWidget( {
9573 * items: [
9574 * new OO.ui.OptionWidget( {
9575 * data: 'before',
9576 * label: 'Before',
9577 * } ),
9578 * new OO.ui.OptionWidget( {
9579 * data: 'after',
9580 * label: 'After',
9581 * } ),
9582 * new OO.ui.OptionWidget( {
9583 * data: 'top',
9584 * label: 'Top',
9585 * } ),
9586 * new OO.ui.OptionWidget( {
9587 * data: 'bottom',
9588 * label: 'Bottom',
9589 * } )
9590 * ]
9591 * } ).on( 'select', function ( item ) {
9592 * menuLayout.setMenuPosition( item.getData() );
9593 * } );
9594 *
9595 * menuLayout.$menu.append(
9596 * menuPanel.$element.append( '<b>Menu panel</b>', select.$element )
9597 * );
9598 * menuLayout.$content.append(
9599 * contentPanel.$element.append( '<b>Content panel</b>', '<p>Note that the menu is positioned relative to the content panel: top, bottom, after, before.</p>')
9600 * );
9601 * $( 'body' ).append( menuLayout.$element );
9602 *
9603 * If menu size needs to be overridden, it can be accomplished using CSS similar to the snippet
9604 * below. MenuLayout's CSS will override the appropriate values with 'auto' or '0' to display the
9605 * menu correctly. If `menuPosition` is known beforehand, CSS rules corresponding to other positions
9606 * may be omitted.
9607 *
9608 * .oo-ui-menuLayout-menu {
9609 * height: 200px;
9610 * width: 200px;
9611 * }
9612 * .oo-ui-menuLayout-content {
9613 * top: 200px;
9614 * left: 200px;
9615 * right: 200px;
9616 * bottom: 200px;
9617 * }
9618 *
9619 * @class
9620 * @extends OO.ui.Layout
9621 *
9622 * @constructor
9623 * @param {Object} [config] Configuration options
9624 * @cfg {boolean} [showMenu=true] Show menu
9625 * @cfg {string} [menuPosition='before'] Position of menu: `top`, `after`, `bottom` or `before`
9626 */
9627 OO.ui.MenuLayout = function OoUiMenuLayout( config ) {
9628 // Configuration initialization
9629 config = $.extend( {
9630 showMenu: true,
9631 menuPosition: 'before'
9632 }, config );
9633
9634 // Parent constructor
9635 OO.ui.MenuLayout.parent.call( this, config );
9636
9637 /**
9638 * Menu DOM node
9639 *
9640 * @property {jQuery}
9641 */
9642 this.$menu = $( '<div>' );
9643 /**
9644 * Content DOM node
9645 *
9646 * @property {jQuery}
9647 */
9648 this.$content = $( '<div>' );
9649
9650 // Initialization
9651 this.$menu
9652 .addClass( 'oo-ui-menuLayout-menu' );
9653 this.$content.addClass( 'oo-ui-menuLayout-content' );
9654 this.$element
9655 .addClass( 'oo-ui-menuLayout' )
9656 .append( this.$content, this.$menu );
9657 this.setMenuPosition( config.menuPosition );
9658 this.toggleMenu( config.showMenu );
9659 };
9660
9661 /* Setup */
9662
9663 OO.inheritClass( OO.ui.MenuLayout, OO.ui.Layout );
9664
9665 /* Methods */
9666
9667 /**
9668 * Toggle menu.
9669 *
9670 * @param {boolean} showMenu Show menu, omit to toggle
9671 * @chainable
9672 */
9673 OO.ui.MenuLayout.prototype.toggleMenu = function ( showMenu ) {
9674 showMenu = showMenu === undefined ? !this.showMenu : !!showMenu;
9675
9676 if ( this.showMenu !== showMenu ) {
9677 this.showMenu = showMenu;
9678 this.$element
9679 .toggleClass( 'oo-ui-menuLayout-showMenu', this.showMenu )
9680 .toggleClass( 'oo-ui-menuLayout-hideMenu', !this.showMenu );
9681 }
9682
9683 return this;
9684 };
9685
9686 /**
9687 * Check if menu is visible
9688 *
9689 * @return {boolean} Menu is visible
9690 */
9691 OO.ui.MenuLayout.prototype.isMenuVisible = function () {
9692 return this.showMenu;
9693 };
9694
9695 /**
9696 * Set menu position.
9697 *
9698 * @param {string} position Position of menu, either `top`, `after`, `bottom` or `before`
9699 * @throws {Error} If position value is not supported
9700 * @chainable
9701 */
9702 OO.ui.MenuLayout.prototype.setMenuPosition = function ( position ) {
9703 this.$element.removeClass( 'oo-ui-menuLayout-' + this.menuPosition );
9704 this.menuPosition = position;
9705 this.$element.addClass( 'oo-ui-menuLayout-' + position );
9706
9707 return this;
9708 };
9709
9710 /**
9711 * Get menu position.
9712 *
9713 * @return {string} Menu position
9714 */
9715 OO.ui.MenuLayout.prototype.getMenuPosition = function () {
9716 return this.menuPosition;
9717 };
9718
9719 /**
9720 * BookletLayouts contain {@link OO.ui.PageLayout page layouts} as well as
9721 * an {@link OO.ui.OutlineSelectWidget outline} that allows users to easily navigate
9722 * through the pages and select which one to display. By default, only one page is
9723 * displayed at a time and the outline is hidden. When a user navigates to a new page,
9724 * the booklet layout automatically focuses on the first focusable element, unless the
9725 * default setting is changed. Optionally, booklets can be configured to show
9726 * {@link OO.ui.OutlineControlsWidget controls} for adding, moving, and removing items.
9727 *
9728 * @example
9729 * // Example of a BookletLayout that contains two PageLayouts.
9730 *
9731 * function PageOneLayout( name, config ) {
9732 * PageOneLayout.parent.call( this, name, config );
9733 * this.$element.append( '<p>First page</p><p>(This booklet has an outline, displayed on the left)</p>' );
9734 * }
9735 * OO.inheritClass( PageOneLayout, OO.ui.PageLayout );
9736 * PageOneLayout.prototype.setupOutlineItem = function () {
9737 * this.outlineItem.setLabel( 'Page One' );
9738 * };
9739 *
9740 * function PageTwoLayout( name, config ) {
9741 * PageTwoLayout.parent.call( this, name, config );
9742 * this.$element.append( '<p>Second page</p>' );
9743 * }
9744 * OO.inheritClass( PageTwoLayout, OO.ui.PageLayout );
9745 * PageTwoLayout.prototype.setupOutlineItem = function () {
9746 * this.outlineItem.setLabel( 'Page Two' );
9747 * };
9748 *
9749 * var page1 = new PageOneLayout( 'one' ),
9750 * page2 = new PageTwoLayout( 'two' );
9751 *
9752 * var booklet = new OO.ui.BookletLayout( {
9753 * outlined: true
9754 * } );
9755 *
9756 * booklet.addPages ( [ page1, page2 ] );
9757 * $( 'body' ).append( booklet.$element );
9758 *
9759 * @class
9760 * @extends OO.ui.MenuLayout
9761 *
9762 * @constructor
9763 * @param {Object} [config] Configuration options
9764 * @cfg {boolean} [continuous=false] Show all pages, one after another
9765 * @cfg {boolean} [autoFocus=true] Focus on the first focusable element when a new page is displayed.
9766 * @cfg {boolean} [outlined=false] Show the outline. The outline is used to navigate through the pages of the booklet.
9767 * @cfg {boolean} [editable=false] Show controls for adding, removing and reordering pages
9768 */
9769 OO.ui.BookletLayout = function OoUiBookletLayout( config ) {
9770 // Configuration initialization
9771 config = config || {};
9772
9773 // Parent constructor
9774 OO.ui.BookletLayout.parent.call( this, config );
9775
9776 // Properties
9777 this.currentPageName = null;
9778 this.pages = {};
9779 this.ignoreFocus = false;
9780 this.stackLayout = new OO.ui.StackLayout( { continuous: !!config.continuous } );
9781 this.$content.append( this.stackLayout.$element );
9782 this.autoFocus = config.autoFocus === undefined || !!config.autoFocus;
9783 this.outlineVisible = false;
9784 this.outlined = !!config.outlined;
9785 if ( this.outlined ) {
9786 this.editable = !!config.editable;
9787 this.outlineControlsWidget = null;
9788 this.outlineSelectWidget = new OO.ui.OutlineSelectWidget();
9789 this.outlinePanel = new OO.ui.PanelLayout( { scrollable: true } );
9790 this.$menu.append( this.outlinePanel.$element );
9791 this.outlineVisible = true;
9792 if ( this.editable ) {
9793 this.outlineControlsWidget = new OO.ui.OutlineControlsWidget(
9794 this.outlineSelectWidget
9795 );
9796 }
9797 }
9798 this.toggleMenu( this.outlined );
9799
9800 // Events
9801 this.stackLayout.connect( this, { set: 'onStackLayoutSet' } );
9802 if ( this.outlined ) {
9803 this.outlineSelectWidget.connect( this, { select: 'onOutlineSelectWidgetSelect' } );
9804 this.scrolling = false;
9805 this.stackLayout.connect( this, { visibleItemChange: 'onStackLayoutVisibleItemChange' } );
9806 }
9807 if ( this.autoFocus ) {
9808 // Event 'focus' does not bubble, but 'focusin' does
9809 this.stackLayout.$element.on( 'focusin', this.onStackLayoutFocus.bind( this ) );
9810 }
9811
9812 // Initialization
9813 this.$element.addClass( 'oo-ui-bookletLayout' );
9814 this.stackLayout.$element.addClass( 'oo-ui-bookletLayout-stackLayout' );
9815 if ( this.outlined ) {
9816 this.outlinePanel.$element
9817 .addClass( 'oo-ui-bookletLayout-outlinePanel' )
9818 .append( this.outlineSelectWidget.$element );
9819 if ( this.editable ) {
9820 this.outlinePanel.$element
9821 .addClass( 'oo-ui-bookletLayout-outlinePanel-editable' )
9822 .append( this.outlineControlsWidget.$element );
9823 }
9824 }
9825 };
9826
9827 /* Setup */
9828
9829 OO.inheritClass( OO.ui.BookletLayout, OO.ui.MenuLayout );
9830
9831 /* Events */
9832
9833 /**
9834 * A 'set' event is emitted when a page is {@link #setPage set} to be displayed by the booklet layout.
9835 * @event set
9836 * @param {OO.ui.PageLayout} page Current page
9837 */
9838
9839 /**
9840 * An 'add' event is emitted when pages are {@link #addPages added} to the booklet layout.
9841 *
9842 * @event add
9843 * @param {OO.ui.PageLayout[]} page Added pages
9844 * @param {number} index Index pages were added at
9845 */
9846
9847 /**
9848 * A 'remove' event is emitted when pages are {@link #clearPages cleared} or
9849 * {@link #removePages removed} from the booklet.
9850 *
9851 * @event remove
9852 * @param {OO.ui.PageLayout[]} pages Removed pages
9853 */
9854
9855 /* Methods */
9856
9857 /**
9858 * Handle stack layout focus.
9859 *
9860 * @private
9861 * @param {jQuery.Event} e Focusin event
9862 */
9863 OO.ui.BookletLayout.prototype.onStackLayoutFocus = function ( e ) {
9864 var name, $target;
9865
9866 // Find the page that an element was focused within
9867 $target = $( e.target ).closest( '.oo-ui-pageLayout' );
9868 for ( name in this.pages ) {
9869 // Check for page match, exclude current page to find only page changes
9870 if ( this.pages[ name ].$element[ 0 ] === $target[ 0 ] && name !== this.currentPageName ) {
9871 this.setPage( name );
9872 break;
9873 }
9874 }
9875 };
9876
9877 /**
9878 * Handle visibleItemChange events from the stackLayout
9879 *
9880 * The next visible page is set as the current page by selecting it
9881 * in the outline
9882 *
9883 * @param {OO.ui.PageLayout} page The next visible page in the layout
9884 */
9885 OO.ui.BookletLayout.prototype.onStackLayoutVisibleItemChange = function ( page ) {
9886 // Set a flag to so that the resulting call to #onStackLayoutSet doesn't
9887 // try and scroll the item into view again.
9888 this.scrolling = true;
9889 this.outlineSelectWidget.selectItemByData( page.getName() );
9890 this.scrolling = false;
9891 };
9892
9893 /**
9894 * Handle stack layout set events.
9895 *
9896 * @private
9897 * @param {OO.ui.PanelLayout|null} page The page panel that is now the current panel
9898 */
9899 OO.ui.BookletLayout.prototype.onStackLayoutSet = function ( page ) {
9900 var layout = this;
9901 if ( !this.scrolling && page ) {
9902 page.scrollElementIntoView( { complete: function () {
9903 if ( layout.autoFocus ) {
9904 layout.focus();
9905 }
9906 } } );
9907 }
9908 };
9909
9910 /**
9911 * Focus the first input in the current page.
9912 *
9913 * If no page is selected, the first selectable page will be selected.
9914 * If the focus is already in an element on the current page, nothing will happen.
9915 * @param {number} [itemIndex] A specific item to focus on
9916 */
9917 OO.ui.BookletLayout.prototype.focus = function ( itemIndex ) {
9918 var page,
9919 items = this.stackLayout.getItems();
9920
9921 if ( itemIndex !== undefined && items[ itemIndex ] ) {
9922 page = items[ itemIndex ];
9923 } else {
9924 page = this.stackLayout.getCurrentItem();
9925 }
9926
9927 if ( !page && this.outlined ) {
9928 this.selectFirstSelectablePage();
9929 page = this.stackLayout.getCurrentItem();
9930 }
9931 if ( !page ) {
9932 return;
9933 }
9934 // Only change the focus if is not already in the current page
9935 if ( !OO.ui.contains( page.$element[ 0 ], this.getElementDocument().activeElement, true ) ) {
9936 page.focus();
9937 }
9938 };
9939
9940 /**
9941 * Find the first focusable input in the booklet layout and focus
9942 * on it.
9943 */
9944 OO.ui.BookletLayout.prototype.focusFirstFocusable = function () {
9945 OO.ui.findFocusable( this.stackLayout.$element ).focus();
9946 };
9947
9948 /**
9949 * Handle outline widget select events.
9950 *
9951 * @private
9952 * @param {OO.ui.OptionWidget|null} item Selected item
9953 */
9954 OO.ui.BookletLayout.prototype.onOutlineSelectWidgetSelect = function ( item ) {
9955 if ( item ) {
9956 this.setPage( item.getData() );
9957 }
9958 };
9959
9960 /**
9961 * Check if booklet has an outline.
9962 *
9963 * @return {boolean} Booklet has an outline
9964 */
9965 OO.ui.BookletLayout.prototype.isOutlined = function () {
9966 return this.outlined;
9967 };
9968
9969 /**
9970 * Check if booklet has editing controls.
9971 *
9972 * @return {boolean} Booklet is editable
9973 */
9974 OO.ui.BookletLayout.prototype.isEditable = function () {
9975 return this.editable;
9976 };
9977
9978 /**
9979 * Check if booklet has a visible outline.
9980 *
9981 * @return {boolean} Outline is visible
9982 */
9983 OO.ui.BookletLayout.prototype.isOutlineVisible = function () {
9984 return this.outlined && this.outlineVisible;
9985 };
9986
9987 /**
9988 * Hide or show the outline.
9989 *
9990 * @param {boolean} [show] Show outline, omit to invert current state
9991 * @chainable
9992 */
9993 OO.ui.BookletLayout.prototype.toggleOutline = function ( show ) {
9994 if ( this.outlined ) {
9995 show = show === undefined ? !this.outlineVisible : !!show;
9996 this.outlineVisible = show;
9997 this.toggleMenu( show );
9998 }
9999
10000 return this;
10001 };
10002
10003 /**
10004 * Get the page closest to the specified page.
10005 *
10006 * @param {OO.ui.PageLayout} page Page to use as a reference point
10007 * @return {OO.ui.PageLayout|null} Page closest to the specified page
10008 */
10009 OO.ui.BookletLayout.prototype.getClosestPage = function ( page ) {
10010 var next, prev, level,
10011 pages = this.stackLayout.getItems(),
10012 index = pages.indexOf( page );
10013
10014 if ( index !== -1 ) {
10015 next = pages[ index + 1 ];
10016 prev = pages[ index - 1 ];
10017 // Prefer adjacent pages at the same level
10018 if ( this.outlined ) {
10019 level = this.outlineSelectWidget.getItemFromData( page.getName() ).getLevel();
10020 if (
10021 prev &&
10022 level === this.outlineSelectWidget.getItemFromData( prev.getName() ).getLevel()
10023 ) {
10024 return prev;
10025 }
10026 if (
10027 next &&
10028 level === this.outlineSelectWidget.getItemFromData( next.getName() ).getLevel()
10029 ) {
10030 return next;
10031 }
10032 }
10033 }
10034 return prev || next || null;
10035 };
10036
10037 /**
10038 * Get the outline widget.
10039 *
10040 * If the booklet is not outlined, the method will return `null`.
10041 *
10042 * @return {OO.ui.OutlineSelectWidget|null} Outline widget, or null if the booklet is not outlined
10043 */
10044 OO.ui.BookletLayout.prototype.getOutline = function () {
10045 return this.outlineSelectWidget;
10046 };
10047
10048 /**
10049 * Get the outline controls widget.
10050 *
10051 * If the outline is not editable, the method will return `null`.
10052 *
10053 * @return {OO.ui.OutlineControlsWidget|null} The outline controls widget.
10054 */
10055 OO.ui.BookletLayout.prototype.getOutlineControls = function () {
10056 return this.outlineControlsWidget;
10057 };
10058
10059 /**
10060 * Get a page by its symbolic name.
10061 *
10062 * @param {string} name Symbolic name of page
10063 * @return {OO.ui.PageLayout|undefined} Page, if found
10064 */
10065 OO.ui.BookletLayout.prototype.getPage = function ( name ) {
10066 return this.pages[ name ];
10067 };
10068
10069 /**
10070 * Get the current page.
10071 *
10072 * @return {OO.ui.PageLayout|undefined} Current page, if found
10073 */
10074 OO.ui.BookletLayout.prototype.getCurrentPage = function () {
10075 var name = this.getCurrentPageName();
10076 return name ? this.getPage( name ) : undefined;
10077 };
10078
10079 /**
10080 * Get the symbolic name of the current page.
10081 *
10082 * @return {string|null} Symbolic name of the current page
10083 */
10084 OO.ui.BookletLayout.prototype.getCurrentPageName = function () {
10085 return this.currentPageName;
10086 };
10087
10088 /**
10089 * Add pages to the booklet layout
10090 *
10091 * When pages are added with the same names as existing pages, the existing pages will be
10092 * automatically removed before the new pages are added.
10093 *
10094 * @param {OO.ui.PageLayout[]} pages Pages to add
10095 * @param {number} index Index of the insertion point
10096 * @fires add
10097 * @chainable
10098 */
10099 OO.ui.BookletLayout.prototype.addPages = function ( pages, index ) {
10100 var i, len, name, page, item, currentIndex,
10101 stackLayoutPages = this.stackLayout.getItems(),
10102 remove = [],
10103 items = [];
10104
10105 // Remove pages with same names
10106 for ( i = 0, len = pages.length; i < len; i++ ) {
10107 page = pages[ i ];
10108 name = page.getName();
10109
10110 if ( Object.prototype.hasOwnProperty.call( this.pages, name ) ) {
10111 // Correct the insertion index
10112 currentIndex = stackLayoutPages.indexOf( this.pages[ name ] );
10113 if ( currentIndex !== -1 && currentIndex + 1 < index ) {
10114 index--;
10115 }
10116 remove.push( this.pages[ name ] );
10117 }
10118 }
10119 if ( remove.length ) {
10120 this.removePages( remove );
10121 }
10122
10123 // Add new pages
10124 for ( i = 0, len = pages.length; i < len; i++ ) {
10125 page = pages[ i ];
10126 name = page.getName();
10127 this.pages[ page.getName() ] = page;
10128 if ( this.outlined ) {
10129 item = new OO.ui.OutlineOptionWidget( { data: name } );
10130 page.setOutlineItem( item );
10131 items.push( item );
10132 }
10133 }
10134
10135 if ( this.outlined && items.length ) {
10136 this.outlineSelectWidget.addItems( items, index );
10137 this.selectFirstSelectablePage();
10138 }
10139 this.stackLayout.addItems( pages, index );
10140 this.emit( 'add', pages, index );
10141
10142 return this;
10143 };
10144
10145 /**
10146 * Remove the specified pages from the booklet layout.
10147 *
10148 * To remove all pages from the booklet, you may wish to use the #clearPages method instead.
10149 *
10150 * @param {OO.ui.PageLayout[]} pages An array of pages to remove
10151 * @fires remove
10152 * @chainable
10153 */
10154 OO.ui.BookletLayout.prototype.removePages = function ( pages ) {
10155 var i, len, name, page,
10156 items = [];
10157
10158 for ( i = 0, len = pages.length; i < len; i++ ) {
10159 page = pages[ i ];
10160 name = page.getName();
10161 delete this.pages[ name ];
10162 if ( this.outlined ) {
10163 items.push( this.outlineSelectWidget.getItemFromData( name ) );
10164 page.setOutlineItem( null );
10165 }
10166 }
10167 if ( this.outlined && items.length ) {
10168 this.outlineSelectWidget.removeItems( items );
10169 this.selectFirstSelectablePage();
10170 }
10171 this.stackLayout.removeItems( pages );
10172 this.emit( 'remove', pages );
10173
10174 return this;
10175 };
10176
10177 /**
10178 * Clear all pages from the booklet layout.
10179 *
10180 * To remove only a subset of pages from the booklet, use the #removePages method.
10181 *
10182 * @fires remove
10183 * @chainable
10184 */
10185 OO.ui.BookletLayout.prototype.clearPages = function () {
10186 var i, len,
10187 pages = this.stackLayout.getItems();
10188
10189 this.pages = {};
10190 this.currentPageName = null;
10191 if ( this.outlined ) {
10192 this.outlineSelectWidget.clearItems();
10193 for ( i = 0, len = pages.length; i < len; i++ ) {
10194 pages[ i ].setOutlineItem( null );
10195 }
10196 }
10197 this.stackLayout.clearItems();
10198
10199 this.emit( 'remove', pages );
10200
10201 return this;
10202 };
10203
10204 /**
10205 * Set the current page by symbolic name.
10206 *
10207 * @fires set
10208 * @param {string} name Symbolic name of page
10209 */
10210 OO.ui.BookletLayout.prototype.setPage = function ( name ) {
10211 var selectedItem,
10212 $focused,
10213 page = this.pages[ name ],
10214 previousPage = this.currentPageName && this.pages[ this.currentPageName ];
10215
10216 if ( name !== this.currentPageName ) {
10217 if ( this.outlined ) {
10218 selectedItem = this.outlineSelectWidget.getSelectedItem();
10219 if ( selectedItem && selectedItem.getData() !== name ) {
10220 this.outlineSelectWidget.selectItemByData( name );
10221 }
10222 }
10223 if ( page ) {
10224 if ( previousPage ) {
10225 previousPage.setActive( false );
10226 // Blur anything focused if the next page doesn't have anything focusable.
10227 // This is not needed if the next page has something focusable (because once it is focused
10228 // this blur happens automatically). If the layout is non-continuous, this check is
10229 // meaningless because the next page is not visible yet and thus can't hold focus.
10230 if (
10231 this.autoFocus &&
10232 this.stackLayout.continuous &&
10233 OO.ui.findFocusable( page.$element ).length !== 0
10234 ) {
10235 $focused = previousPage.$element.find( ':focus' );
10236 if ( $focused.length ) {
10237 $focused[ 0 ].blur();
10238 }
10239 }
10240 }
10241 this.currentPageName = name;
10242 page.setActive( true );
10243 this.stackLayout.setItem( page );
10244 if ( !this.stackLayout.continuous && previousPage ) {
10245 // This should not be necessary, since any inputs on the previous page should have been
10246 // blurred when it was hidden, but browsers are not very consistent about this.
10247 $focused = previousPage.$element.find( ':focus' );
10248 if ( $focused.length ) {
10249 $focused[ 0 ].blur();
10250 }
10251 }
10252 this.emit( 'set', page );
10253 }
10254 }
10255 };
10256
10257 /**
10258 * Select the first selectable page.
10259 *
10260 * @chainable
10261 */
10262 OO.ui.BookletLayout.prototype.selectFirstSelectablePage = function () {
10263 if ( !this.outlineSelectWidget.getSelectedItem() ) {
10264 this.outlineSelectWidget.selectItem( this.outlineSelectWidget.getFirstSelectableItem() );
10265 }
10266
10267 return this;
10268 };
10269
10270 /**
10271 * IndexLayouts contain {@link OO.ui.CardLayout card layouts} as well as
10272 * {@link OO.ui.TabSelectWidget tabs} that allow users to easily navigate through the cards and
10273 * select which one to display. By default, only one card is displayed at a time. When a user
10274 * navigates to a new card, the index layout automatically focuses on the first focusable element,
10275 * unless the default setting is changed.
10276 *
10277 * TODO: This class is similar to BookletLayout, we may want to refactor to reduce duplication
10278 *
10279 * @example
10280 * // Example of a IndexLayout that contains two CardLayouts.
10281 *
10282 * function CardOneLayout( name, config ) {
10283 * CardOneLayout.parent.call( this, name, config );
10284 * this.$element.append( '<p>First card</p>' );
10285 * }
10286 * OO.inheritClass( CardOneLayout, OO.ui.CardLayout );
10287 * CardOneLayout.prototype.setupTabItem = function () {
10288 * this.tabItem.setLabel( 'Card one' );
10289 * };
10290 *
10291 * var card1 = new CardOneLayout( 'one' ),
10292 * card2 = new CardLayout( 'two', { label: 'Card two' } );
10293 *
10294 * card2.$element.append( '<p>Second card</p>' );
10295 *
10296 * var index = new OO.ui.IndexLayout();
10297 *
10298 * index.addCards ( [ card1, card2 ] );
10299 * $( 'body' ).append( index.$element );
10300 *
10301 * @class
10302 * @extends OO.ui.MenuLayout
10303 *
10304 * @constructor
10305 * @param {Object} [config] Configuration options
10306 * @cfg {boolean} [continuous=false] Show all cards, one after another
10307 * @cfg {boolean} [expanded=true] Expand the content panel to fill the entire parent element.
10308 * @cfg {boolean} [autoFocus=true] Focus on the first focusable element when a new card is displayed.
10309 */
10310 OO.ui.IndexLayout = function OoUiIndexLayout( config ) {
10311 // Configuration initialization
10312 config = $.extend( {}, config, { menuPosition: 'top' } );
10313
10314 // Parent constructor
10315 OO.ui.IndexLayout.parent.call( this, config );
10316
10317 // Properties
10318 this.currentCardName = null;
10319 this.cards = {};
10320 this.ignoreFocus = false;
10321 this.stackLayout = new OO.ui.StackLayout( {
10322 continuous: !!config.continuous,
10323 expanded: config.expanded
10324 } );
10325 this.$content.append( this.stackLayout.$element );
10326 this.autoFocus = config.autoFocus === undefined || !!config.autoFocus;
10327
10328 this.tabSelectWidget = new OO.ui.TabSelectWidget();
10329 this.tabPanel = new OO.ui.PanelLayout();
10330 this.$menu.append( this.tabPanel.$element );
10331
10332 this.toggleMenu( true );
10333
10334 // Events
10335 this.stackLayout.connect( this, { set: 'onStackLayoutSet' } );
10336 this.tabSelectWidget.connect( this, { select: 'onTabSelectWidgetSelect' } );
10337 if ( this.autoFocus ) {
10338 // Event 'focus' does not bubble, but 'focusin' does
10339 this.stackLayout.$element.on( 'focusin', this.onStackLayoutFocus.bind( this ) );
10340 }
10341
10342 // Initialization
10343 this.$element.addClass( 'oo-ui-indexLayout' );
10344 this.stackLayout.$element.addClass( 'oo-ui-indexLayout-stackLayout' );
10345 this.tabPanel.$element
10346 .addClass( 'oo-ui-indexLayout-tabPanel' )
10347 .append( this.tabSelectWidget.$element );
10348 };
10349
10350 /* Setup */
10351
10352 OO.inheritClass( OO.ui.IndexLayout, OO.ui.MenuLayout );
10353
10354 /* Events */
10355
10356 /**
10357 * A 'set' event is emitted when a card is {@link #setCard set} to be displayed by the index layout.
10358 * @event set
10359 * @param {OO.ui.CardLayout} card Current card
10360 */
10361
10362 /**
10363 * An 'add' event is emitted when cards are {@link #addCards added} to the index layout.
10364 *
10365 * @event add
10366 * @param {OO.ui.CardLayout[]} card Added cards
10367 * @param {number} index Index cards were added at
10368 */
10369
10370 /**
10371 * A 'remove' event is emitted when cards are {@link #clearCards cleared} or
10372 * {@link #removeCards removed} from the index.
10373 *
10374 * @event remove
10375 * @param {OO.ui.CardLayout[]} cards Removed cards
10376 */
10377
10378 /* Methods */
10379
10380 /**
10381 * Handle stack layout focus.
10382 *
10383 * @private
10384 * @param {jQuery.Event} e Focusin event
10385 */
10386 OO.ui.IndexLayout.prototype.onStackLayoutFocus = function ( e ) {
10387 var name, $target;
10388
10389 // Find the card that an element was focused within
10390 $target = $( e.target ).closest( '.oo-ui-cardLayout' );
10391 for ( name in this.cards ) {
10392 // Check for card match, exclude current card to find only card changes
10393 if ( this.cards[ name ].$element[ 0 ] === $target[ 0 ] && name !== this.currentCardName ) {
10394 this.setCard( name );
10395 break;
10396 }
10397 }
10398 };
10399
10400 /**
10401 * Handle stack layout set events.
10402 *
10403 * @private
10404 * @param {OO.ui.PanelLayout|null} card The card panel that is now the current panel
10405 */
10406 OO.ui.IndexLayout.prototype.onStackLayoutSet = function ( card ) {
10407 var layout = this;
10408 if ( card ) {
10409 card.scrollElementIntoView( { complete: function () {
10410 if ( layout.autoFocus ) {
10411 layout.focus();
10412 }
10413 } } );
10414 }
10415 };
10416
10417 /**
10418 * Focus the first input in the current card.
10419 *
10420 * If no card is selected, the first selectable card will be selected.
10421 * If the focus is already in an element on the current card, nothing will happen.
10422 * @param {number} [itemIndex] A specific item to focus on
10423 */
10424 OO.ui.IndexLayout.prototype.focus = function ( itemIndex ) {
10425 var card,
10426 items = this.stackLayout.getItems();
10427
10428 if ( itemIndex !== undefined && items[ itemIndex ] ) {
10429 card = items[ itemIndex ];
10430 } else {
10431 card = this.stackLayout.getCurrentItem();
10432 }
10433
10434 if ( !card ) {
10435 this.selectFirstSelectableCard();
10436 card = this.stackLayout.getCurrentItem();
10437 }
10438 if ( !card ) {
10439 return;
10440 }
10441 // Only change the focus if is not already in the current page
10442 if ( !OO.ui.contains( card.$element[ 0 ], this.getElementDocument().activeElement, true ) ) {
10443 card.focus();
10444 }
10445 };
10446
10447 /**
10448 * Find the first focusable input in the index layout and focus
10449 * on it.
10450 */
10451 OO.ui.IndexLayout.prototype.focusFirstFocusable = function () {
10452 OO.ui.findFocusable( this.stackLayout.$element ).focus();
10453 };
10454
10455 /**
10456 * Handle tab widget select events.
10457 *
10458 * @private
10459 * @param {OO.ui.OptionWidget|null} item Selected item
10460 */
10461 OO.ui.IndexLayout.prototype.onTabSelectWidgetSelect = function ( item ) {
10462 if ( item ) {
10463 this.setCard( item.getData() );
10464 }
10465 };
10466
10467 /**
10468 * Get the card closest to the specified card.
10469 *
10470 * @param {OO.ui.CardLayout} card Card to use as a reference point
10471 * @return {OO.ui.CardLayout|null} Card closest to the specified card
10472 */
10473 OO.ui.IndexLayout.prototype.getClosestCard = function ( card ) {
10474 var next, prev, level,
10475 cards = this.stackLayout.getItems(),
10476 index = cards.indexOf( card );
10477
10478 if ( index !== -1 ) {
10479 next = cards[ index + 1 ];
10480 prev = cards[ index - 1 ];
10481 // Prefer adjacent cards at the same level
10482 level = this.tabSelectWidget.getItemFromData( card.getName() ).getLevel();
10483 if (
10484 prev &&
10485 level === this.tabSelectWidget.getItemFromData( prev.getName() ).getLevel()
10486 ) {
10487 return prev;
10488 }
10489 if (
10490 next &&
10491 level === this.tabSelectWidget.getItemFromData( next.getName() ).getLevel()
10492 ) {
10493 return next;
10494 }
10495 }
10496 return prev || next || null;
10497 };
10498
10499 /**
10500 * Get the tabs widget.
10501 *
10502 * @return {OO.ui.TabSelectWidget} Tabs widget
10503 */
10504 OO.ui.IndexLayout.prototype.getTabs = function () {
10505 return this.tabSelectWidget;
10506 };
10507
10508 /**
10509 * Get a card by its symbolic name.
10510 *
10511 * @param {string} name Symbolic name of card
10512 * @return {OO.ui.CardLayout|undefined} Card, if found
10513 */
10514 OO.ui.IndexLayout.prototype.getCard = function ( name ) {
10515 return this.cards[ name ];
10516 };
10517
10518 /**
10519 * Get the current card.
10520 *
10521 * @return {OO.ui.CardLayout|undefined} Current card, if found
10522 */
10523 OO.ui.IndexLayout.prototype.getCurrentCard = function () {
10524 var name = this.getCurrentCardName();
10525 return name ? this.getCard( name ) : undefined;
10526 };
10527
10528 /**
10529 * Get the symbolic name of the current card.
10530 *
10531 * @return {string|null} Symbolic name of the current card
10532 */
10533 OO.ui.IndexLayout.prototype.getCurrentCardName = function () {
10534 return this.currentCardName;
10535 };
10536
10537 /**
10538 * Add cards to the index layout
10539 *
10540 * When cards are added with the same names as existing cards, the existing cards will be
10541 * automatically removed before the new cards are added.
10542 *
10543 * @param {OO.ui.CardLayout[]} cards Cards to add
10544 * @param {number} index Index of the insertion point
10545 * @fires add
10546 * @chainable
10547 */
10548 OO.ui.IndexLayout.prototype.addCards = function ( cards, index ) {
10549 var i, len, name, card, item, currentIndex,
10550 stackLayoutCards = this.stackLayout.getItems(),
10551 remove = [],
10552 items = [];
10553
10554 // Remove cards with same names
10555 for ( i = 0, len = cards.length; i < len; i++ ) {
10556 card = cards[ i ];
10557 name = card.getName();
10558
10559 if ( Object.prototype.hasOwnProperty.call( this.cards, name ) ) {
10560 // Correct the insertion index
10561 currentIndex = stackLayoutCards.indexOf( this.cards[ name ] );
10562 if ( currentIndex !== -1 && currentIndex + 1 < index ) {
10563 index--;
10564 }
10565 remove.push( this.cards[ name ] );
10566 }
10567 }
10568 if ( remove.length ) {
10569 this.removeCards( remove );
10570 }
10571
10572 // Add new cards
10573 for ( i = 0, len = cards.length; i < len; i++ ) {
10574 card = cards[ i ];
10575 name = card.getName();
10576 this.cards[ card.getName() ] = card;
10577 item = new OO.ui.TabOptionWidget( { data: name } );
10578 card.setTabItem( item );
10579 items.push( item );
10580 }
10581
10582 if ( items.length ) {
10583 this.tabSelectWidget.addItems( items, index );
10584 this.selectFirstSelectableCard();
10585 }
10586 this.stackLayout.addItems( cards, index );
10587 this.emit( 'add', cards, index );
10588
10589 return this;
10590 };
10591
10592 /**
10593 * Remove the specified cards from the index layout.
10594 *
10595 * To remove all cards from the index, you may wish to use the #clearCards method instead.
10596 *
10597 * @param {OO.ui.CardLayout[]} cards An array of cards to remove
10598 * @fires remove
10599 * @chainable
10600 */
10601 OO.ui.IndexLayout.prototype.removeCards = function ( cards ) {
10602 var i, len, name, card,
10603 items = [];
10604
10605 for ( i = 0, len = cards.length; i < len; i++ ) {
10606 card = cards[ i ];
10607 name = card.getName();
10608 delete this.cards[ name ];
10609 items.push( this.tabSelectWidget.getItemFromData( name ) );
10610 card.setTabItem( null );
10611 }
10612 if ( items.length ) {
10613 this.tabSelectWidget.removeItems( items );
10614 this.selectFirstSelectableCard();
10615 }
10616 this.stackLayout.removeItems( cards );
10617 this.emit( 'remove', cards );
10618
10619 return this;
10620 };
10621
10622 /**
10623 * Clear all cards from the index layout.
10624 *
10625 * To remove only a subset of cards from the index, use the #removeCards method.
10626 *
10627 * @fires remove
10628 * @chainable
10629 */
10630 OO.ui.IndexLayout.prototype.clearCards = function () {
10631 var i, len,
10632 cards = this.stackLayout.getItems();
10633
10634 this.cards = {};
10635 this.currentCardName = null;
10636 this.tabSelectWidget.clearItems();
10637 for ( i = 0, len = cards.length; i < len; i++ ) {
10638 cards[ i ].setTabItem( null );
10639 }
10640 this.stackLayout.clearItems();
10641
10642 this.emit( 'remove', cards );
10643
10644 return this;
10645 };
10646
10647 /**
10648 * Set the current card by symbolic name.
10649 *
10650 * @fires set
10651 * @param {string} name Symbolic name of card
10652 */
10653 OO.ui.IndexLayout.prototype.setCard = function ( name ) {
10654 var selectedItem,
10655 $focused,
10656 card = this.cards[ name ],
10657 previousCard = this.currentCardName && this.cards[ this.currentCardName ];
10658
10659 if ( name !== this.currentCardName ) {
10660 selectedItem = this.tabSelectWidget.getSelectedItem();
10661 if ( selectedItem && selectedItem.getData() !== name ) {
10662 this.tabSelectWidget.selectItemByData( name );
10663 }
10664 if ( card ) {
10665 if ( previousCard ) {
10666 previousCard.setActive( false );
10667 // Blur anything focused if the next card doesn't have anything focusable.
10668 // This is not needed if the next card has something focusable (because once it is focused
10669 // this blur happens automatically). If the layout is non-continuous, this check is
10670 // meaningless because the next card is not visible yet and thus can't hold focus.
10671 if (
10672 this.autoFocus &&
10673 this.stackLayout.continuous &&
10674 OO.ui.findFocusable( card.$element ).length !== 0
10675 ) {
10676 $focused = previousCard.$element.find( ':focus' );
10677 if ( $focused.length ) {
10678 $focused[ 0 ].blur();
10679 }
10680 }
10681 }
10682 this.currentCardName = name;
10683 card.setActive( true );
10684 this.stackLayout.setItem( card );
10685 if ( !this.stackLayout.continuous && previousCard ) {
10686 // This should not be necessary, since any inputs on the previous card should have been
10687 // blurred when it was hidden, but browsers are not very consistent about this.
10688 $focused = previousCard.$element.find( ':focus' );
10689 if ( $focused.length ) {
10690 $focused[ 0 ].blur();
10691 }
10692 }
10693 this.emit( 'set', card );
10694 }
10695 }
10696 };
10697
10698 /**
10699 * Select the first selectable card.
10700 *
10701 * @chainable
10702 */
10703 OO.ui.IndexLayout.prototype.selectFirstSelectableCard = function () {
10704 if ( !this.tabSelectWidget.getSelectedItem() ) {
10705 this.tabSelectWidget.selectItem( this.tabSelectWidget.getFirstSelectableItem() );
10706 }
10707
10708 return this;
10709 };
10710
10711 /**
10712 * PanelLayouts expand to cover the entire area of their parent. They can be configured with scrolling, padding,
10713 * and a frame, and are often used together with {@link OO.ui.StackLayout StackLayouts}.
10714 *
10715 * @example
10716 * // Example of a panel layout
10717 * var panel = new OO.ui.PanelLayout( {
10718 * expanded: false,
10719 * framed: true,
10720 * padded: true,
10721 * $content: $( '<p>A panel layout with padding and a frame.</p>' )
10722 * } );
10723 * $( 'body' ).append( panel.$element );
10724 *
10725 * @class
10726 * @extends OO.ui.Layout
10727 *
10728 * @constructor
10729 * @param {Object} [config] Configuration options
10730 * @cfg {boolean} [scrollable=false] Allow vertical scrolling
10731 * @cfg {boolean} [padded=false] Add padding between the content and the edges of the panel.
10732 * @cfg {boolean} [expanded=true] Expand the panel to fill the entire parent element.
10733 * @cfg {boolean} [framed=false] Render the panel with a frame to visually separate it from outside content.
10734 */
10735 OO.ui.PanelLayout = function OoUiPanelLayout( config ) {
10736 // Configuration initialization
10737 config = $.extend( {
10738 scrollable: false,
10739 padded: false,
10740 expanded: true,
10741 framed: false
10742 }, config );
10743
10744 // Parent constructor
10745 OO.ui.PanelLayout.parent.call( this, config );
10746
10747 // Initialization
10748 this.$element.addClass( 'oo-ui-panelLayout' );
10749 if ( config.scrollable ) {
10750 this.$element.addClass( 'oo-ui-panelLayout-scrollable' );
10751 }
10752 if ( config.padded ) {
10753 this.$element.addClass( 'oo-ui-panelLayout-padded' );
10754 }
10755 if ( config.expanded ) {
10756 this.$element.addClass( 'oo-ui-panelLayout-expanded' );
10757 }
10758 if ( config.framed ) {
10759 this.$element.addClass( 'oo-ui-panelLayout-framed' );
10760 }
10761 };
10762
10763 /* Setup */
10764
10765 OO.inheritClass( OO.ui.PanelLayout, OO.ui.Layout );
10766
10767 /* Methods */
10768
10769 /**
10770 * Focus the panel layout
10771 *
10772 * The default implementation just focuses the first focusable element in the panel
10773 */
10774 OO.ui.PanelLayout.prototype.focus = function () {
10775 OO.ui.findFocusable( this.$element ).focus();
10776 };
10777
10778 /**
10779 * CardLayouts are used within {@link OO.ui.IndexLayout index layouts} to create cards that users can select and display
10780 * from the index's optional {@link OO.ui.TabSelectWidget tab} navigation. Cards are usually not instantiated directly,
10781 * rather extended to include the required content and functionality.
10782 *
10783 * Each card must have a unique symbolic name, which is passed to the constructor. In addition, the card's tab
10784 * item is customized (with a label) using the #setupTabItem method. See
10785 * {@link OO.ui.IndexLayout IndexLayout} for an example.
10786 *
10787 * @class
10788 * @extends OO.ui.PanelLayout
10789 *
10790 * @constructor
10791 * @param {string} name Unique symbolic name of card
10792 * @param {Object} [config] Configuration options
10793 * @cfg {jQuery|string|Function|OO.ui.HtmlSnippet} [label] Label for card's tab
10794 */
10795 OO.ui.CardLayout = function OoUiCardLayout( name, config ) {
10796 // Allow passing positional parameters inside the config object
10797 if ( OO.isPlainObject( name ) && config === undefined ) {
10798 config = name;
10799 name = config.name;
10800 }
10801
10802 // Configuration initialization
10803 config = $.extend( { scrollable: true }, config );
10804
10805 // Parent constructor
10806 OO.ui.CardLayout.parent.call( this, config );
10807
10808 // Properties
10809 this.name = name;
10810 this.label = config.label;
10811 this.tabItem = null;
10812 this.active = false;
10813
10814 // Initialization
10815 this.$element.addClass( 'oo-ui-cardLayout' );
10816 };
10817
10818 /* Setup */
10819
10820 OO.inheritClass( OO.ui.CardLayout, OO.ui.PanelLayout );
10821
10822 /* Events */
10823
10824 /**
10825 * An 'active' event is emitted when the card becomes active. Cards become active when they are
10826 * shown in a index layout that is configured to display only one card at a time.
10827 *
10828 * @event active
10829 * @param {boolean} active Card is active
10830 */
10831
10832 /* Methods */
10833
10834 /**
10835 * Get the symbolic name of the card.
10836 *
10837 * @return {string} Symbolic name of card
10838 */
10839 OO.ui.CardLayout.prototype.getName = function () {
10840 return this.name;
10841 };
10842
10843 /**
10844 * Check if card is active.
10845 *
10846 * Cards become active when they are shown in a {@link OO.ui.IndexLayout index layout} that is configured to display
10847 * only one card at a time. Additional CSS is applied to the card's tab item to reflect the active state.
10848 *
10849 * @return {boolean} Card is active
10850 */
10851 OO.ui.CardLayout.prototype.isActive = function () {
10852 return this.active;
10853 };
10854
10855 /**
10856 * Get tab item.
10857 *
10858 * The tab item allows users to access the card from the index's tab
10859 * navigation. The tab item itself can be customized (with a label, level, etc.) using the #setupTabItem method.
10860 *
10861 * @return {OO.ui.TabOptionWidget|null} Tab option widget
10862 */
10863 OO.ui.CardLayout.prototype.getTabItem = function () {
10864 return this.tabItem;
10865 };
10866
10867 /**
10868 * Set or unset the tab item.
10869 *
10870 * Specify a {@link OO.ui.TabOptionWidget tab option} to set it,
10871 * or `null` to clear the tab item. To customize the tab item itself (e.g., to set a label or tab
10872 * level), use #setupTabItem instead of this method.
10873 *
10874 * @param {OO.ui.TabOptionWidget|null} tabItem Tab option widget, null to clear
10875 * @chainable
10876 */
10877 OO.ui.CardLayout.prototype.setTabItem = function ( tabItem ) {
10878 this.tabItem = tabItem || null;
10879 if ( tabItem ) {
10880 this.setupTabItem();
10881 }
10882 return this;
10883 };
10884
10885 /**
10886 * Set up the tab item.
10887 *
10888 * Use this method to customize the tab item (e.g., to add a label or tab level). To set or unset
10889 * the tab item itself (with a {@link OO.ui.TabOptionWidget tab option} or `null`), use
10890 * the #setTabItem method instead.
10891 *
10892 * @param {OO.ui.TabOptionWidget} tabItem Tab option widget to set up
10893 * @chainable
10894 */
10895 OO.ui.CardLayout.prototype.setupTabItem = function () {
10896 if ( this.label ) {
10897 this.tabItem.setLabel( this.label );
10898 }
10899 return this;
10900 };
10901
10902 /**
10903 * Set the card to its 'active' state.
10904 *
10905 * Cards become active when they are shown in a index layout that is configured to display only one card at a time. Additional
10906 * CSS is applied to the tab item to reflect the card's active state. Outside of the index
10907 * context, setting the active state on a card does nothing.
10908 *
10909 * @param {boolean} value Card is active
10910 * @fires active
10911 */
10912 OO.ui.CardLayout.prototype.setActive = function ( active ) {
10913 active = !!active;
10914
10915 if ( active !== this.active ) {
10916 this.active = active;
10917 this.$element.toggleClass( 'oo-ui-cardLayout-active', this.active );
10918 this.emit( 'active', this.active );
10919 }
10920 };
10921
10922 /**
10923 * PageLayouts are used within {@link OO.ui.BookletLayout booklet layouts} to create pages that users can select and display
10924 * from the booklet's optional {@link OO.ui.OutlineSelectWidget outline} navigation. Pages are usually not instantiated directly,
10925 * rather extended to include the required content and functionality.
10926 *
10927 * Each page must have a unique symbolic name, which is passed to the constructor. In addition, the page's outline
10928 * item is customized (with a label, outline level, etc.) using the #setupOutlineItem method. See
10929 * {@link OO.ui.BookletLayout BookletLayout} for an example.
10930 *
10931 * @class
10932 * @extends OO.ui.PanelLayout
10933 *
10934 * @constructor
10935 * @param {string} name Unique symbolic name of page
10936 * @param {Object} [config] Configuration options
10937 */
10938 OO.ui.PageLayout = function OoUiPageLayout( name, config ) {
10939 // Allow passing positional parameters inside the config object
10940 if ( OO.isPlainObject( name ) && config === undefined ) {
10941 config = name;
10942 name = config.name;
10943 }
10944
10945 // Configuration initialization
10946 config = $.extend( { scrollable: true }, config );
10947
10948 // Parent constructor
10949 OO.ui.PageLayout.parent.call( this, config );
10950
10951 // Properties
10952 this.name = name;
10953 this.outlineItem = null;
10954 this.active = false;
10955
10956 // Initialization
10957 this.$element.addClass( 'oo-ui-pageLayout' );
10958 };
10959
10960 /* Setup */
10961
10962 OO.inheritClass( OO.ui.PageLayout, OO.ui.PanelLayout );
10963
10964 /* Events */
10965
10966 /**
10967 * An 'active' event is emitted when the page becomes active. Pages become active when they are
10968 * shown in a booklet layout that is configured to display only one page at a time.
10969 *
10970 * @event active
10971 * @param {boolean} active Page is active
10972 */
10973
10974 /* Methods */
10975
10976 /**
10977 * Get the symbolic name of the page.
10978 *
10979 * @return {string} Symbolic name of page
10980 */
10981 OO.ui.PageLayout.prototype.getName = function () {
10982 return this.name;
10983 };
10984
10985 /**
10986 * Check if page is active.
10987 *
10988 * Pages become active when they are shown in a {@link OO.ui.BookletLayout booklet layout} that is configured to display
10989 * only one page at a time. Additional CSS is applied to the page's outline item to reflect the active state.
10990 *
10991 * @return {boolean} Page is active
10992 */
10993 OO.ui.PageLayout.prototype.isActive = function () {
10994 return this.active;
10995 };
10996
10997 /**
10998 * Get outline item.
10999 *
11000 * The outline item allows users to access the page from the booklet's outline
11001 * navigation. The outline item itself can be customized (with a label, level, etc.) using the #setupOutlineItem method.
11002 *
11003 * @return {OO.ui.OutlineOptionWidget|null} Outline option widget
11004 */
11005 OO.ui.PageLayout.prototype.getOutlineItem = function () {
11006 return this.outlineItem;
11007 };
11008
11009 /**
11010 * Set or unset the outline item.
11011 *
11012 * Specify an {@link OO.ui.OutlineOptionWidget outline option} to set it,
11013 * or `null` to clear the outline item. To customize the outline item itself (e.g., to set a label or outline
11014 * level), use #setupOutlineItem instead of this method.
11015 *
11016 * @param {OO.ui.OutlineOptionWidget|null} outlineItem Outline option widget, null to clear
11017 * @chainable
11018 */
11019 OO.ui.PageLayout.prototype.setOutlineItem = function ( outlineItem ) {
11020 this.outlineItem = outlineItem || null;
11021 if ( outlineItem ) {
11022 this.setupOutlineItem();
11023 }
11024 return this;
11025 };
11026
11027 /**
11028 * Set up the outline item.
11029 *
11030 * Use this method to customize the outline item (e.g., to add a label or outline level). To set or unset
11031 * the outline item itself (with an {@link OO.ui.OutlineOptionWidget outline option} or `null`), use
11032 * the #setOutlineItem method instead.
11033 *
11034 * @param {OO.ui.OutlineOptionWidget} outlineItem Outline option widget to set up
11035 * @chainable
11036 */
11037 OO.ui.PageLayout.prototype.setupOutlineItem = function () {
11038 return this;
11039 };
11040
11041 /**
11042 * Set the page to its 'active' state.
11043 *
11044 * Pages become active when they are shown in a booklet layout that is configured to display only one page at a time. Additional
11045 * CSS is applied to the outline item to reflect the page's active state. Outside of the booklet
11046 * context, setting the active state on a page does nothing.
11047 *
11048 * @param {boolean} value Page is active
11049 * @fires active
11050 */
11051 OO.ui.PageLayout.prototype.setActive = function ( active ) {
11052 active = !!active;
11053
11054 if ( active !== this.active ) {
11055 this.active = active;
11056 this.$element.toggleClass( 'oo-ui-pageLayout-active', active );
11057 this.emit( 'active', this.active );
11058 }
11059 };
11060
11061 /**
11062 * StackLayouts contain a series of {@link OO.ui.PanelLayout panel layouts}. By default, only one panel is displayed
11063 * at a time, though the stack layout can also be configured to show all contained panels, one after another,
11064 * by setting the #continuous option to 'true'.
11065 *
11066 * @example
11067 * // A stack layout with two panels, configured to be displayed continously
11068 * var myStack = new OO.ui.StackLayout( {
11069 * items: [
11070 * new OO.ui.PanelLayout( {
11071 * $content: $( '<p>Panel One</p>' ),
11072 * padded: true,
11073 * framed: true
11074 * } ),
11075 * new OO.ui.PanelLayout( {
11076 * $content: $( '<p>Panel Two</p>' ),
11077 * padded: true,
11078 * framed: true
11079 * } )
11080 * ],
11081 * continuous: true
11082 * } );
11083 * $( 'body' ).append( myStack.$element );
11084 *
11085 * @class
11086 * @extends OO.ui.PanelLayout
11087 * @mixins OO.ui.mixin.GroupElement
11088 *
11089 * @constructor
11090 * @param {Object} [config] Configuration options
11091 * @cfg {boolean} [continuous=false] Show all panels, one after another. By default, only one panel is displayed at a time.
11092 * @cfg {OO.ui.Layout[]} [items] Panel layouts to add to the stack layout.
11093 */
11094 OO.ui.StackLayout = function OoUiStackLayout( config ) {
11095 // Configuration initialization
11096 config = $.extend( { scrollable: true }, config );
11097
11098 // Parent constructor
11099 OO.ui.StackLayout.parent.call( this, config );
11100
11101 // Mixin constructors
11102 OO.ui.mixin.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) );
11103
11104 // Properties
11105 this.currentItem = null;
11106 this.continuous = !!config.continuous;
11107
11108 // Initialization
11109 this.$element.addClass( 'oo-ui-stackLayout' );
11110 if ( this.continuous ) {
11111 this.$element.addClass( 'oo-ui-stackLayout-continuous' );
11112 this.$element.on( 'scroll', OO.ui.debounce( this.onScroll.bind( this ), 250 ) );
11113 }
11114 if ( Array.isArray( config.items ) ) {
11115 this.addItems( config.items );
11116 }
11117 };
11118
11119 /* Setup */
11120
11121 OO.inheritClass( OO.ui.StackLayout, OO.ui.PanelLayout );
11122 OO.mixinClass( OO.ui.StackLayout, OO.ui.mixin.GroupElement );
11123
11124 /* Events */
11125
11126 /**
11127 * A 'set' event is emitted when panels are {@link #addItems added}, {@link #removeItems removed},
11128 * {@link #clearItems cleared} or {@link #setItem displayed}.
11129 *
11130 * @event set
11131 * @param {OO.ui.Layout|null} item Current panel or `null` if no panel is shown
11132 */
11133
11134 /**
11135 * When used in continuous mode, this event is emitted when the user scrolls down
11136 * far enough such that currentItem is no longer visible.
11137 *
11138 * @event visibleItemChange
11139 * @param {OO.ui.PanelLayout} panel The next visible item in the layout
11140 */
11141
11142 /* Methods */
11143
11144 /**
11145 * Handle scroll events from the layout element
11146 *
11147 * @param {jQuery.Event} e
11148 * @fires visibleItemChange
11149 */
11150 OO.ui.StackLayout.prototype.onScroll = function () {
11151 var currentRect,
11152 len = this.items.length,
11153 currentIndex = this.items.indexOf( this.currentItem ),
11154 newIndex = currentIndex,
11155 containerRect = this.$element[ 0 ].getBoundingClientRect();
11156
11157 if ( !containerRect || ( !containerRect.top && !containerRect.bottom ) ) {
11158 // Can't get bounding rect, possibly not attached.
11159 return;
11160 }
11161
11162 function getRect( item ) {
11163 return item.$element[ 0 ].getBoundingClientRect();
11164 }
11165
11166 function isVisible( item ) {
11167 var rect = getRect( item );
11168 return rect.bottom > containerRect.top && rect.top < containerRect.bottom;
11169 }
11170
11171 currentRect = getRect( this.currentItem );
11172
11173 if ( currentRect.bottom < containerRect.top ) {
11174 // Scrolled down past current item
11175 while ( ++newIndex < len ) {
11176 if ( isVisible( this.items[ newIndex ] ) ) {
11177 break;
11178 }
11179 }
11180 } else if ( currentRect.top > containerRect.bottom ) {
11181 // Scrolled up past current item
11182 while ( --newIndex >= 0 ) {
11183 if ( isVisible( this.items[ newIndex ] ) ) {
11184 break;
11185 }
11186 }
11187 }
11188
11189 if ( newIndex !== currentIndex ) {
11190 this.emit( 'visibleItemChange', this.items[ newIndex ] );
11191 }
11192 };
11193
11194 /**
11195 * Get the current panel.
11196 *
11197 * @return {OO.ui.Layout|null}
11198 */
11199 OO.ui.StackLayout.prototype.getCurrentItem = function () {
11200 return this.currentItem;
11201 };
11202
11203 /**
11204 * Unset the current item.
11205 *
11206 * @private
11207 * @param {OO.ui.StackLayout} layout
11208 * @fires set
11209 */
11210 OO.ui.StackLayout.prototype.unsetCurrentItem = function () {
11211 var prevItem = this.currentItem;
11212 if ( prevItem === null ) {
11213 return;
11214 }
11215
11216 this.currentItem = null;
11217 this.emit( 'set', null );
11218 };
11219
11220 /**
11221 * Add panel layouts to the stack layout.
11222 *
11223 * Panels will be added to the end of the stack layout array unless the optional index parameter specifies a different
11224 * insertion point. Adding a panel that is already in the stack will move it to the end of the array or the point specified
11225 * by the index.
11226 *
11227 * @param {OO.ui.Layout[]} items Panels to add
11228 * @param {number} [index] Index of the insertion point
11229 * @chainable
11230 */
11231 OO.ui.StackLayout.prototype.addItems = function ( items, index ) {
11232 // Update the visibility
11233 this.updateHiddenState( items, this.currentItem );
11234
11235 // Mixin method
11236 OO.ui.mixin.GroupElement.prototype.addItems.call( this, items, index );
11237
11238 if ( !this.currentItem && items.length ) {
11239 this.setItem( items[ 0 ] );
11240 }
11241
11242 return this;
11243 };
11244
11245 /**
11246 * Remove the specified panels from the stack layout.
11247 *
11248 * Removed panels are detached from the DOM, not removed, so that they may be reused. To remove all panels,
11249 * you may wish to use the #clearItems method instead.
11250 *
11251 * @param {OO.ui.Layout[]} items Panels to remove
11252 * @chainable
11253 * @fires set
11254 */
11255 OO.ui.StackLayout.prototype.removeItems = function ( items ) {
11256 // Mixin method
11257 OO.ui.mixin.GroupElement.prototype.removeItems.call( this, items );
11258
11259 if ( items.indexOf( this.currentItem ) !== -1 ) {
11260 if ( this.items.length ) {
11261 this.setItem( this.items[ 0 ] );
11262 } else {
11263 this.unsetCurrentItem();
11264 }
11265 }
11266
11267 return this;
11268 };
11269
11270 /**
11271 * Clear all panels from the stack layout.
11272 *
11273 * Cleared panels are detached from the DOM, not removed, so that they may be reused. To remove only
11274 * a subset of panels, use the #removeItems method.
11275 *
11276 * @chainable
11277 * @fires set
11278 */
11279 OO.ui.StackLayout.prototype.clearItems = function () {
11280 this.unsetCurrentItem();
11281 OO.ui.mixin.GroupElement.prototype.clearItems.call( this );
11282
11283 return this;
11284 };
11285
11286 /**
11287 * Show the specified panel.
11288 *
11289 * If another panel is currently displayed, it will be hidden.
11290 *
11291 * @param {OO.ui.Layout} item Panel to show
11292 * @chainable
11293 * @fires set
11294 */
11295 OO.ui.StackLayout.prototype.setItem = function ( item ) {
11296 if ( item !== this.currentItem ) {
11297 this.updateHiddenState( this.items, item );
11298
11299 if ( this.items.indexOf( item ) !== -1 ) {
11300 this.currentItem = item;
11301 this.emit( 'set', item );
11302 } else {
11303 this.unsetCurrentItem();
11304 }
11305 }
11306
11307 return this;
11308 };
11309
11310 /**
11311 * Update the visibility of all items in case of non-continuous view.
11312 *
11313 * Ensure all items are hidden except for the selected one.
11314 * This method does nothing when the stack is continuous.
11315 *
11316 * @private
11317 * @param {OO.ui.Layout[]} items Item list iterate over
11318 * @param {OO.ui.Layout} [selectedItem] Selected item to show
11319 */
11320 OO.ui.StackLayout.prototype.updateHiddenState = function ( items, selectedItem ) {
11321 var i, len;
11322
11323 if ( !this.continuous ) {
11324 for ( i = 0, len = items.length; i < len; i++ ) {
11325 if ( !selectedItem || selectedItem !== items[ i ] ) {
11326 items[ i ].$element.addClass( 'oo-ui-element-hidden' );
11327 }
11328 }
11329 if ( selectedItem ) {
11330 selectedItem.$element.removeClass( 'oo-ui-element-hidden' );
11331 }
11332 }
11333 };
11334
11335 /**
11336 * HorizontalLayout arranges its contents in a single line (using `display: inline-block` for its
11337 * items), with small margins between them. Convenient when you need to put a number of block-level
11338 * widgets on a single line next to each other.
11339 *
11340 * Note that inline elements, such as OO.ui.ButtonWidgets, do not need this wrapper.
11341 *
11342 * @example
11343 * // HorizontalLayout with a text input and a label
11344 * var layout = new OO.ui.HorizontalLayout( {
11345 * items: [
11346 * new OO.ui.LabelWidget( { label: 'Label' } ),
11347 * new OO.ui.TextInputWidget( { value: 'Text' } )
11348 * ]
11349 * } );
11350 * $( 'body' ).append( layout.$element );
11351 *
11352 * @class
11353 * @extends OO.ui.Layout
11354 * @mixins OO.ui.mixin.GroupElement
11355 *
11356 * @constructor
11357 * @param {Object} [config] Configuration options
11358 * @cfg {OO.ui.Widget[]|OO.ui.Layout[]} [items] Widgets or other layouts to add to the layout.
11359 */
11360 OO.ui.HorizontalLayout = function OoUiHorizontalLayout( config ) {
11361 // Configuration initialization
11362 config = config || {};
11363
11364 // Parent constructor
11365 OO.ui.HorizontalLayout.parent.call( this, config );
11366
11367 // Mixin constructors
11368 OO.ui.mixin.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) );
11369
11370 // Initialization
11371 this.$element.addClass( 'oo-ui-horizontalLayout' );
11372 if ( Array.isArray( config.items ) ) {
11373 this.addItems( config.items );
11374 }
11375 };
11376
11377 /* Setup */
11378
11379 OO.inheritClass( OO.ui.HorizontalLayout, OO.ui.Layout );
11380 OO.mixinClass( OO.ui.HorizontalLayout, OO.ui.mixin.GroupElement );
11381
11382 /**
11383 * BarToolGroups are one of three types of {@link OO.ui.ToolGroup toolgroups} that are used to
11384 * create {@link OO.ui.Toolbar toolbars} (the other types of groups are {@link OO.ui.MenuToolGroup MenuToolGroup}
11385 * and {@link OO.ui.ListToolGroup ListToolGroup}). The {@link OO.ui.Tool tools} in a BarToolGroup are
11386 * displayed by icon in a single row. The title of the tool is displayed when users move the mouse over
11387 * the tool.
11388 *
11389 * BarToolGroups are created by a {@link OO.ui.ToolGroupFactory tool group factory} when the toolbar is
11390 * set up.
11391 *
11392 * @example
11393 * // Example of a BarToolGroup with two tools
11394 * var toolFactory = new OO.ui.ToolFactory();
11395 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
11396 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
11397 *
11398 * // We will be placing status text in this element when tools are used
11399 * var $area = $( '<p>' ).text( 'Example of a BarToolGroup with two tools.' );
11400 *
11401 * // Define the tools that we're going to place in our toolbar
11402 *
11403 * // Create a class inheriting from OO.ui.Tool
11404 * function PictureTool() {
11405 * PictureTool.parent.apply( this, arguments );
11406 * }
11407 * OO.inheritClass( PictureTool, OO.ui.Tool );
11408 * // Each tool must have a 'name' (used as an internal identifier, see later) and at least one
11409 * // of 'icon' and 'title' (displayed icon and text).
11410 * PictureTool.static.name = 'picture';
11411 * PictureTool.static.icon = 'picture';
11412 * PictureTool.static.title = 'Insert picture';
11413 * // Defines the action that will happen when this tool is selected (clicked).
11414 * PictureTool.prototype.onSelect = function () {
11415 * $area.text( 'Picture tool clicked!' );
11416 * // Never display this tool as "active" (selected).
11417 * this.setActive( false );
11418 * };
11419 * // Make this tool available in our toolFactory and thus our toolbar
11420 * toolFactory.register( PictureTool );
11421 *
11422 * // This is a PopupTool. Rather than having a custom 'onSelect' action, it will display a
11423 * // little popup window (a PopupWidget).
11424 * function HelpTool( toolGroup, config ) {
11425 * OO.ui.PopupTool.call( this, toolGroup, $.extend( { popup: {
11426 * padded: true,
11427 * label: 'Help',
11428 * head: true
11429 * } }, config ) );
11430 * this.popup.$body.append( '<p>I am helpful!</p>' );
11431 * }
11432 * OO.inheritClass( HelpTool, OO.ui.PopupTool );
11433 * HelpTool.static.name = 'help';
11434 * HelpTool.static.icon = 'help';
11435 * HelpTool.static.title = 'Help';
11436 * toolFactory.register( HelpTool );
11437 *
11438 * // Finally define which tools and in what order appear in the toolbar. Each tool may only be
11439 * // used once (but not all defined tools must be used).
11440 * toolbar.setup( [
11441 * {
11442 * // 'bar' tool groups display tools by icon only
11443 * type: 'bar',
11444 * include: [ 'picture', 'help' ]
11445 * }
11446 * ] );
11447 *
11448 * // Create some UI around the toolbar and place it in the document
11449 * var frame = new OO.ui.PanelLayout( {
11450 * expanded: false,
11451 * framed: true
11452 * } );
11453 * var contentFrame = new OO.ui.PanelLayout( {
11454 * expanded: false,
11455 * padded: true
11456 * } );
11457 * frame.$element.append(
11458 * toolbar.$element,
11459 * contentFrame.$element.append( $area )
11460 * );
11461 * $( 'body' ).append( frame.$element );
11462 *
11463 * // Here is where the toolbar is actually built. This must be done after inserting it into the
11464 * // document.
11465 * toolbar.initialize();
11466 *
11467 * For more information about how to add tools to a bar tool group, please see {@link OO.ui.ToolGroup toolgroup}.
11468 * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki][1].
11469 *
11470 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
11471 *
11472 * @class
11473 * @extends OO.ui.ToolGroup
11474 *
11475 * @constructor
11476 * @param {OO.ui.Toolbar} toolbar
11477 * @param {Object} [config] Configuration options
11478 */
11479 OO.ui.BarToolGroup = function OoUiBarToolGroup( toolbar, config ) {
11480 // Allow passing positional parameters inside the config object
11481 if ( OO.isPlainObject( toolbar ) && config === undefined ) {
11482 config = toolbar;
11483 toolbar = config.toolbar;
11484 }
11485
11486 // Parent constructor
11487 OO.ui.BarToolGroup.parent.call( this, toolbar, config );
11488
11489 // Initialization
11490 this.$element.addClass( 'oo-ui-barToolGroup' );
11491 };
11492
11493 /* Setup */
11494
11495 OO.inheritClass( OO.ui.BarToolGroup, OO.ui.ToolGroup );
11496
11497 /* Static Properties */
11498
11499 OO.ui.BarToolGroup.static.titleTooltips = true;
11500
11501 OO.ui.BarToolGroup.static.accelTooltips = true;
11502
11503 OO.ui.BarToolGroup.static.name = 'bar';
11504
11505 /**
11506 * PopupToolGroup is an abstract base class used by both {@link OO.ui.MenuToolGroup MenuToolGroup}
11507 * and {@link OO.ui.ListToolGroup ListToolGroup} to provide a popup--an overlaid menu or list of tools with an
11508 * optional icon and label. This class can be used for other base classes that also use this functionality.
11509 *
11510 * @abstract
11511 * @class
11512 * @extends OO.ui.ToolGroup
11513 * @mixins OO.ui.mixin.IconElement
11514 * @mixins OO.ui.mixin.IndicatorElement
11515 * @mixins OO.ui.mixin.LabelElement
11516 * @mixins OO.ui.mixin.TitledElement
11517 * @mixins OO.ui.mixin.ClippableElement
11518 * @mixins OO.ui.mixin.TabIndexedElement
11519 *
11520 * @constructor
11521 * @param {OO.ui.Toolbar} toolbar
11522 * @param {Object} [config] Configuration options
11523 * @cfg {string} [header] Text to display at the top of the popup
11524 */
11525 OO.ui.PopupToolGroup = function OoUiPopupToolGroup( toolbar, config ) {
11526 // Allow passing positional parameters inside the config object
11527 if ( OO.isPlainObject( toolbar ) && config === undefined ) {
11528 config = toolbar;
11529 toolbar = config.toolbar;
11530 }
11531
11532 // Configuration initialization
11533 config = config || {};
11534
11535 // Parent constructor
11536 OO.ui.PopupToolGroup.parent.call( this, toolbar, config );
11537
11538 // Properties
11539 this.active = false;
11540 this.dragging = false;
11541 this.onBlurHandler = this.onBlur.bind( this );
11542 this.$handle = $( '<span>' );
11543
11544 // Mixin constructors
11545 OO.ui.mixin.IconElement.call( this, config );
11546 OO.ui.mixin.IndicatorElement.call( this, config );
11547 OO.ui.mixin.LabelElement.call( this, config );
11548 OO.ui.mixin.TitledElement.call( this, config );
11549 OO.ui.mixin.ClippableElement.call( this, $.extend( {}, config, { $clippable: this.$group } ) );
11550 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$handle } ) );
11551
11552 // Events
11553 this.$handle.on( {
11554 keydown: this.onHandleMouseKeyDown.bind( this ),
11555 keyup: this.onHandleMouseKeyUp.bind( this ),
11556 mousedown: this.onHandleMouseKeyDown.bind( this ),
11557 mouseup: this.onHandleMouseKeyUp.bind( this )
11558 } );
11559
11560 // Initialization
11561 this.$handle
11562 .addClass( 'oo-ui-popupToolGroup-handle' )
11563 .append( this.$icon, this.$label, this.$indicator );
11564 // If the pop-up should have a header, add it to the top of the toolGroup.
11565 // Note: If this feature is useful for other widgets, we could abstract it into an
11566 // OO.ui.HeaderedElement mixin constructor.
11567 if ( config.header !== undefined ) {
11568 this.$group
11569 .prepend( $( '<span>' )
11570 .addClass( 'oo-ui-popupToolGroup-header' )
11571 .text( config.header )
11572 );
11573 }
11574 this.$element
11575 .addClass( 'oo-ui-popupToolGroup' )
11576 .prepend( this.$handle );
11577 };
11578
11579 /* Setup */
11580
11581 OO.inheritClass( OO.ui.PopupToolGroup, OO.ui.ToolGroup );
11582 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.mixin.IconElement );
11583 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.mixin.IndicatorElement );
11584 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.mixin.LabelElement );
11585 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.mixin.TitledElement );
11586 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.mixin.ClippableElement );
11587 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.mixin.TabIndexedElement );
11588
11589 /* Methods */
11590
11591 /**
11592 * @inheritdoc
11593 */
11594 OO.ui.PopupToolGroup.prototype.setDisabled = function () {
11595 // Parent method
11596 OO.ui.PopupToolGroup.parent.prototype.setDisabled.apply( this, arguments );
11597
11598 if ( this.isDisabled() && this.isElementAttached() ) {
11599 this.setActive( false );
11600 }
11601 };
11602
11603 /**
11604 * Handle focus being lost.
11605 *
11606 * The event is actually generated from a mouseup/keyup, so it is not a normal blur event object.
11607 *
11608 * @protected
11609 * @param {jQuery.Event} e Mouse up or key up event
11610 */
11611 OO.ui.PopupToolGroup.prototype.onBlur = function ( e ) {
11612 // Only deactivate when clicking outside the dropdown element
11613 if ( $( e.target ).closest( '.oo-ui-popupToolGroup' )[ 0 ] !== this.$element[ 0 ] ) {
11614 this.setActive( false );
11615 }
11616 };
11617
11618 /**
11619 * @inheritdoc
11620 */
11621 OO.ui.PopupToolGroup.prototype.onMouseKeyUp = function ( e ) {
11622 // Only close toolgroup when a tool was actually selected
11623 if (
11624 !this.isDisabled() && this.pressed && this.pressed === this.getTargetTool( e ) &&
11625 ( e.which === 1 || e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
11626 ) {
11627 this.setActive( false );
11628 }
11629 return OO.ui.PopupToolGroup.parent.prototype.onMouseKeyUp.call( this, e );
11630 };
11631
11632 /**
11633 * Handle mouse up and key up events.
11634 *
11635 * @protected
11636 * @param {jQuery.Event} e Mouse up or key up event
11637 */
11638 OO.ui.PopupToolGroup.prototype.onHandleMouseKeyUp = function ( e ) {
11639 if (
11640 !this.isDisabled() &&
11641 ( e.which === 1 || e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
11642 ) {
11643 return false;
11644 }
11645 };
11646
11647 /**
11648 * Handle mouse down and key down events.
11649 *
11650 * @protected
11651 * @param {jQuery.Event} e Mouse down or key down event
11652 */
11653 OO.ui.PopupToolGroup.prototype.onHandleMouseKeyDown = function ( e ) {
11654 if (
11655 !this.isDisabled() &&
11656 ( e.which === 1 || e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
11657 ) {
11658 this.setActive( !this.active );
11659 return false;
11660 }
11661 };
11662
11663 /**
11664 * Switch into 'active' mode.
11665 *
11666 * When active, the popup is visible. A mouseup event anywhere in the document will trigger
11667 * deactivation.
11668 */
11669 OO.ui.PopupToolGroup.prototype.setActive = function ( value ) {
11670 var containerWidth, containerLeft;
11671 value = !!value;
11672 if ( this.active !== value ) {
11673 this.active = value;
11674 if ( value ) {
11675 OO.ui.addCaptureEventListener( this.getElementDocument(), 'mouseup', this.onBlurHandler );
11676 OO.ui.addCaptureEventListener( this.getElementDocument(), 'keyup', this.onBlurHandler );
11677
11678 this.$clippable.css( 'left', '' );
11679 // Try anchoring the popup to the left first
11680 this.$element.addClass( 'oo-ui-popupToolGroup-active oo-ui-popupToolGroup-left' );
11681 this.toggleClipping( true );
11682 if ( this.isClippedHorizontally() ) {
11683 // Anchoring to the left caused the popup to clip, so anchor it to the right instead
11684 this.toggleClipping( false );
11685 this.$element
11686 .removeClass( 'oo-ui-popupToolGroup-left' )
11687 .addClass( 'oo-ui-popupToolGroup-right' );
11688 this.toggleClipping( true );
11689 }
11690 if ( this.isClippedHorizontally() ) {
11691 // Anchoring to the right also caused the popup to clip, so just make it fill the container
11692 containerWidth = this.$clippableScrollableContainer.width();
11693 containerLeft = this.$clippableScrollableContainer.offset().left;
11694
11695 this.toggleClipping( false );
11696 this.$element.removeClass( 'oo-ui-popupToolGroup-right' );
11697
11698 this.$clippable.css( {
11699 left: -( this.$element.offset().left - containerLeft ),
11700 width: containerWidth
11701 } );
11702 }
11703 } else {
11704 OO.ui.removeCaptureEventListener( this.getElementDocument(), 'mouseup', this.onBlurHandler );
11705 OO.ui.removeCaptureEventListener( this.getElementDocument(), 'keyup', this.onBlurHandler );
11706 this.$element.removeClass(
11707 'oo-ui-popupToolGroup-active oo-ui-popupToolGroup-left oo-ui-popupToolGroup-right'
11708 );
11709 this.toggleClipping( false );
11710 }
11711 }
11712 };
11713
11714 /**
11715 * ListToolGroups are one of three types of {@link OO.ui.ToolGroup toolgroups} that are used to
11716 * create {@link OO.ui.Toolbar toolbars} (the other types of groups are {@link OO.ui.MenuToolGroup MenuToolGroup}
11717 * and {@link OO.ui.BarToolGroup BarToolGroup}). The {@link OO.ui.Tool tools} in a ListToolGroup are displayed
11718 * by label in a dropdown menu. The title of the tool is used as the label text. The menu itself can be configured
11719 * with a label, icon, indicator, header, and title.
11720 *
11721 * ListToolGroups can be configured to be expanded and collapsed. Collapsed lists will have a ‘More’ option that
11722 * users can select to see the full list of tools. If a collapsed toolgroup is expanded, a ‘Fewer’ option permits
11723 * users to collapse the list again.
11724 *
11725 * ListToolGroups are created by a {@link OO.ui.ToolGroupFactory toolgroup factory} when the toolbar is set up. The factory
11726 * requires the ListToolGroup's symbolic name, 'list', which is specified along with the other configurations. For more
11727 * information about how to add tools to a ListToolGroup, please see {@link OO.ui.ToolGroup toolgroup}.
11728 *
11729 * @example
11730 * // Example of a ListToolGroup
11731 * var toolFactory = new OO.ui.ToolFactory();
11732 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
11733 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
11734 *
11735 * // Configure and register two tools
11736 * function SettingsTool() {
11737 * SettingsTool.parent.apply( this, arguments );
11738 * }
11739 * OO.inheritClass( SettingsTool, OO.ui.Tool );
11740 * SettingsTool.static.name = 'settings';
11741 * SettingsTool.static.icon = 'settings';
11742 * SettingsTool.static.title = 'Change settings';
11743 * SettingsTool.prototype.onSelect = function () {
11744 * this.setActive( false );
11745 * };
11746 * toolFactory.register( SettingsTool );
11747 * // Register two more tools, nothing interesting here
11748 * function StuffTool() {
11749 * StuffTool.parent.apply( this, arguments );
11750 * }
11751 * OO.inheritClass( StuffTool, OO.ui.Tool );
11752 * StuffTool.static.name = 'stuff';
11753 * StuffTool.static.icon = 'ellipsis';
11754 * StuffTool.static.title = 'Change the world';
11755 * StuffTool.prototype.onSelect = function () {
11756 * this.setActive( false );
11757 * };
11758 * toolFactory.register( StuffTool );
11759 * toolbar.setup( [
11760 * {
11761 * // Configurations for list toolgroup.
11762 * type: 'list',
11763 * label: 'ListToolGroup',
11764 * indicator: 'down',
11765 * icon: 'picture',
11766 * title: 'This is the title, displayed when user moves the mouse over the list toolgroup',
11767 * header: 'This is the header',
11768 * include: [ 'settings', 'stuff' ],
11769 * allowCollapse: ['stuff']
11770 * }
11771 * ] );
11772 *
11773 * // Create some UI around the toolbar and place it in the document
11774 * var frame = new OO.ui.PanelLayout( {
11775 * expanded: false,
11776 * framed: true
11777 * } );
11778 * frame.$element.append(
11779 * toolbar.$element
11780 * );
11781 * $( 'body' ).append( frame.$element );
11782 * // Build the toolbar. This must be done after the toolbar has been appended to the document.
11783 * toolbar.initialize();
11784 *
11785 * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki][1].
11786 *
11787 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
11788 *
11789 * @class
11790 * @extends OO.ui.PopupToolGroup
11791 *
11792 * @constructor
11793 * @param {OO.ui.Toolbar} toolbar
11794 * @param {Object} [config] Configuration options
11795 * @cfg {Array} [allowCollapse] Allow the specified tools to be collapsed. By default, collapsible tools
11796 * will only be displayed if users click the ‘More’ option displayed at the bottom of the list. If
11797 * the list is expanded, a ‘Fewer’ option permits users to collapse the list again. Any tools that
11798 * are included in the toolgroup, but are not designated as collapsible, will always be displayed.
11799 * To open a collapsible list in its expanded state, set #expanded to 'true'.
11800 * @cfg {Array} [forceExpand] Expand the specified tools. All other tools will be designated as collapsible.
11801 * Unless #expanded is set to true, the collapsible tools will be collapsed when the list is first opened.
11802 * @cfg {boolean} [expanded=false] Expand collapsible tools. This config is only relevant if tools have
11803 * been designated as collapsible. When expanded is set to true, all tools in the group will be displayed
11804 * when the list is first opened. Users can collapse the list with a ‘Fewer’ option at the bottom.
11805 */
11806 OO.ui.ListToolGroup = function OoUiListToolGroup( toolbar, config ) {
11807 // Allow passing positional parameters inside the config object
11808 if ( OO.isPlainObject( toolbar ) && config === undefined ) {
11809 config = toolbar;
11810 toolbar = config.toolbar;
11811 }
11812
11813 // Configuration initialization
11814 config = config || {};
11815
11816 // Properties (must be set before parent constructor, which calls #populate)
11817 this.allowCollapse = config.allowCollapse;
11818 this.forceExpand = config.forceExpand;
11819 this.expanded = config.expanded !== undefined ? config.expanded : false;
11820 this.collapsibleTools = [];
11821
11822 // Parent constructor
11823 OO.ui.ListToolGroup.parent.call( this, toolbar, config );
11824
11825 // Initialization
11826 this.$element.addClass( 'oo-ui-listToolGroup' );
11827 };
11828
11829 /* Setup */
11830
11831 OO.inheritClass( OO.ui.ListToolGroup, OO.ui.PopupToolGroup );
11832
11833 /* Static Properties */
11834
11835 OO.ui.ListToolGroup.static.name = 'list';
11836
11837 /* Methods */
11838
11839 /**
11840 * @inheritdoc
11841 */
11842 OO.ui.ListToolGroup.prototype.populate = function () {
11843 var i, len, allowCollapse = [];
11844
11845 OO.ui.ListToolGroup.parent.prototype.populate.call( this );
11846
11847 // Update the list of collapsible tools
11848 if ( this.allowCollapse !== undefined ) {
11849 allowCollapse = this.allowCollapse;
11850 } else if ( this.forceExpand !== undefined ) {
11851 allowCollapse = OO.simpleArrayDifference( Object.keys( this.tools ), this.forceExpand );
11852 }
11853
11854 this.collapsibleTools = [];
11855 for ( i = 0, len = allowCollapse.length; i < len; i++ ) {
11856 if ( this.tools[ allowCollapse[ i ] ] !== undefined ) {
11857 this.collapsibleTools.push( this.tools[ allowCollapse[ i ] ] );
11858 }
11859 }
11860
11861 // Keep at the end, even when tools are added
11862 this.$group.append( this.getExpandCollapseTool().$element );
11863
11864 this.getExpandCollapseTool().toggle( this.collapsibleTools.length !== 0 );
11865 this.updateCollapsibleState();
11866 };
11867
11868 OO.ui.ListToolGroup.prototype.getExpandCollapseTool = function () {
11869 var ExpandCollapseTool;
11870 if ( this.expandCollapseTool === undefined ) {
11871 ExpandCollapseTool = function () {
11872 ExpandCollapseTool.parent.apply( this, arguments );
11873 };
11874
11875 OO.inheritClass( ExpandCollapseTool, OO.ui.Tool );
11876
11877 ExpandCollapseTool.prototype.onSelect = function () {
11878 this.toolGroup.expanded = !this.toolGroup.expanded;
11879 this.toolGroup.updateCollapsibleState();
11880 this.setActive( false );
11881 };
11882 ExpandCollapseTool.prototype.onUpdateState = function () {
11883 // Do nothing. Tool interface requires an implementation of this function.
11884 };
11885
11886 ExpandCollapseTool.static.name = 'more-fewer';
11887
11888 this.expandCollapseTool = new ExpandCollapseTool( this );
11889 }
11890 return this.expandCollapseTool;
11891 };
11892
11893 /**
11894 * @inheritdoc
11895 */
11896 OO.ui.ListToolGroup.prototype.onMouseKeyUp = function ( e ) {
11897 // Do not close the popup when the user wants to show more/fewer tools
11898 if (
11899 $( e.target ).closest( '.oo-ui-tool-name-more-fewer' ).length &&
11900 ( e.which === 1 || e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
11901 ) {
11902 // HACK: Prevent the popup list from being hidden. Skip the PopupToolGroup implementation (which
11903 // hides the popup list when a tool is selected) and call ToolGroup's implementation directly.
11904 return OO.ui.ListToolGroup.parent.parent.prototype.onMouseKeyUp.call( this, e );
11905 } else {
11906 return OO.ui.ListToolGroup.parent.prototype.onMouseKeyUp.call( this, e );
11907 }
11908 };
11909
11910 OO.ui.ListToolGroup.prototype.updateCollapsibleState = function () {
11911 var i, len;
11912
11913 this.getExpandCollapseTool()
11914 .setIcon( this.expanded ? 'collapse' : 'expand' )
11915 .setTitle( OO.ui.msg( this.expanded ? 'ooui-toolgroup-collapse' : 'ooui-toolgroup-expand' ) );
11916
11917 for ( i = 0, len = this.collapsibleTools.length; i < len; i++ ) {
11918 this.collapsibleTools[ i ].toggle( this.expanded );
11919 }
11920 };
11921
11922 /**
11923 * MenuToolGroups are one of three types of {@link OO.ui.ToolGroup toolgroups} that are used to
11924 * create {@link OO.ui.Toolbar toolbars} (the other types of groups are {@link OO.ui.BarToolGroup BarToolGroup}
11925 * and {@link OO.ui.ListToolGroup ListToolGroup}). MenuToolGroups contain selectable {@link OO.ui.Tool tools},
11926 * which are displayed by label in a dropdown menu. The tool's title is used as the label text, and the
11927 * menu label is updated to reflect which tool or tools are currently selected. If no tools are selected,
11928 * the menu label is empty. The menu can be configured with an indicator, icon, title, and/or header.
11929 *
11930 * MenuToolGroups are created by a {@link OO.ui.ToolGroupFactory tool group factory} when the toolbar
11931 * is set up. Note that all tools must define an {@link OO.ui.Tool#onUpdateState onUpdateState} method if
11932 * a MenuToolGroup is used.
11933 *
11934 * @example
11935 * // Example of a MenuToolGroup
11936 * var toolFactory = new OO.ui.ToolFactory();
11937 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
11938 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
11939 *
11940 * // We will be placing status text in this element when tools are used
11941 * var $area = $( '<p>' ).text( 'An example of a MenuToolGroup. Select a tool from the dropdown menu.' );
11942 *
11943 * // Define the tools that we're going to place in our toolbar
11944 *
11945 * function SettingsTool() {
11946 * SettingsTool.parent.apply( this, arguments );
11947 * this.reallyActive = false;
11948 * }
11949 * OO.inheritClass( SettingsTool, OO.ui.Tool );
11950 * SettingsTool.static.name = 'settings';
11951 * SettingsTool.static.icon = 'settings';
11952 * SettingsTool.static.title = 'Change settings';
11953 * SettingsTool.prototype.onSelect = function () {
11954 * $area.text( 'Settings tool clicked!' );
11955 * // Toggle the active state on each click
11956 * this.reallyActive = !this.reallyActive;
11957 * this.setActive( this.reallyActive );
11958 * // To update the menu label
11959 * this.toolbar.emit( 'updateState' );
11960 * };
11961 * SettingsTool.prototype.onUpdateState = function () {
11962 * };
11963 * toolFactory.register( SettingsTool );
11964 *
11965 * function StuffTool() {
11966 * StuffTool.parent.apply( this, arguments );
11967 * this.reallyActive = false;
11968 * }
11969 * OO.inheritClass( StuffTool, OO.ui.Tool );
11970 * StuffTool.static.name = 'stuff';
11971 * StuffTool.static.icon = 'ellipsis';
11972 * StuffTool.static.title = 'More stuff';
11973 * StuffTool.prototype.onSelect = function () {
11974 * $area.text( 'More stuff tool clicked!' );
11975 * // Toggle the active state on each click
11976 * this.reallyActive = !this.reallyActive;
11977 * this.setActive( this.reallyActive );
11978 * // To update the menu label
11979 * this.toolbar.emit( 'updateState' );
11980 * };
11981 * StuffTool.prototype.onUpdateState = function () {
11982 * };
11983 * toolFactory.register( StuffTool );
11984 *
11985 * // Finally define which tools and in what order appear in the toolbar. Each tool may only be
11986 * // used once (but not all defined tools must be used).
11987 * toolbar.setup( [
11988 * {
11989 * type: 'menu',
11990 * header: 'This is the (optional) header',
11991 * title: 'This is the (optional) title',
11992 * indicator: 'down',
11993 * include: [ 'settings', 'stuff' ]
11994 * }
11995 * ] );
11996 *
11997 * // Create some UI around the toolbar and place it in the document
11998 * var frame = new OO.ui.PanelLayout( {
11999 * expanded: false,
12000 * framed: true
12001 * } );
12002 * var contentFrame = new OO.ui.PanelLayout( {
12003 * expanded: false,
12004 * padded: true
12005 * } );
12006 * frame.$element.append(
12007 * toolbar.$element,
12008 * contentFrame.$element.append( $area )
12009 * );
12010 * $( 'body' ).append( frame.$element );
12011 *
12012 * // Here is where the toolbar is actually built. This must be done after inserting it into the
12013 * // document.
12014 * toolbar.initialize();
12015 * toolbar.emit( 'updateState' );
12016 *
12017 * For more information about how to add tools to a MenuToolGroup, please see {@link OO.ui.ToolGroup toolgroup}.
12018 * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki] [1].
12019 *
12020 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
12021 *
12022 * @class
12023 * @extends OO.ui.PopupToolGroup
12024 *
12025 * @constructor
12026 * @param {OO.ui.Toolbar} toolbar
12027 * @param {Object} [config] Configuration options
12028 */
12029 OO.ui.MenuToolGroup = function OoUiMenuToolGroup( toolbar, config ) {
12030 // Allow passing positional parameters inside the config object
12031 if ( OO.isPlainObject( toolbar ) && config === undefined ) {
12032 config = toolbar;
12033 toolbar = config.toolbar;
12034 }
12035
12036 // Configuration initialization
12037 config = config || {};
12038
12039 // Parent constructor
12040 OO.ui.MenuToolGroup.parent.call( this, toolbar, config );
12041
12042 // Events
12043 this.toolbar.connect( this, { updateState: 'onUpdateState' } );
12044
12045 // Initialization
12046 this.$element.addClass( 'oo-ui-menuToolGroup' );
12047 };
12048
12049 /* Setup */
12050
12051 OO.inheritClass( OO.ui.MenuToolGroup, OO.ui.PopupToolGroup );
12052
12053 /* Static Properties */
12054
12055 OO.ui.MenuToolGroup.static.name = 'menu';
12056
12057 /* Methods */
12058
12059 /**
12060 * Handle the toolbar state being updated.
12061 *
12062 * When the state changes, the title of each active item in the menu will be joined together and
12063 * used as a label for the group. The label will be empty if none of the items are active.
12064 *
12065 * @private
12066 */
12067 OO.ui.MenuToolGroup.prototype.onUpdateState = function () {
12068 var name,
12069 labelTexts = [];
12070
12071 for ( name in this.tools ) {
12072 if ( this.tools[ name ].isActive() ) {
12073 labelTexts.push( this.tools[ name ].getTitle() );
12074 }
12075 }
12076
12077 this.setLabel( labelTexts.join( ', ' ) || ' ' );
12078 };
12079
12080 /**
12081 * Popup tools open a popup window when they are selected from the {@link OO.ui.Toolbar toolbar}. Each popup tool is configured
12082 * with a static name, title, and icon, as well with as any popup configurations. Unlike other tools, popup tools do not require that developers specify
12083 * an #onSelect or #onUpdateState method, as these methods have been implemented already.
12084 *
12085 * // Example of a popup tool. When selected, a popup tool displays
12086 * // a popup window.
12087 * function HelpTool( toolGroup, config ) {
12088 * OO.ui.PopupTool.call( this, toolGroup, $.extend( { popup: {
12089 * padded: true,
12090 * label: 'Help',
12091 * head: true
12092 * } }, config ) );
12093 * this.popup.$body.append( '<p>I am helpful!</p>' );
12094 * };
12095 * OO.inheritClass( HelpTool, OO.ui.PopupTool );
12096 * HelpTool.static.name = 'help';
12097 * HelpTool.static.icon = 'help';
12098 * HelpTool.static.title = 'Help';
12099 * toolFactory.register( HelpTool );
12100 *
12101 * For an example of a toolbar that contains a popup tool, see {@link OO.ui.Toolbar toolbars}. For more information about
12102 * toolbars in genreral, please see the [OOjs UI documentation on MediaWiki][1].
12103 *
12104 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
12105 *
12106 * @abstract
12107 * @class
12108 * @extends OO.ui.Tool
12109 * @mixins OO.ui.mixin.PopupElement
12110 *
12111 * @constructor
12112 * @param {OO.ui.ToolGroup} toolGroup
12113 * @param {Object} [config] Configuration options
12114 */
12115 OO.ui.PopupTool = function OoUiPopupTool( toolGroup, config ) {
12116 // Allow passing positional parameters inside the config object
12117 if ( OO.isPlainObject( toolGroup ) && config === undefined ) {
12118 config = toolGroup;
12119 toolGroup = config.toolGroup;
12120 }
12121
12122 // Parent constructor
12123 OO.ui.PopupTool.parent.call( this, toolGroup, config );
12124
12125 // Mixin constructors
12126 OO.ui.mixin.PopupElement.call( this, config );
12127
12128 // Initialization
12129 this.$element
12130 .addClass( 'oo-ui-popupTool' )
12131 .append( this.popup.$element );
12132 };
12133
12134 /* Setup */
12135
12136 OO.inheritClass( OO.ui.PopupTool, OO.ui.Tool );
12137 OO.mixinClass( OO.ui.PopupTool, OO.ui.mixin.PopupElement );
12138
12139 /* Methods */
12140
12141 /**
12142 * Handle the tool being selected.
12143 *
12144 * @inheritdoc
12145 */
12146 OO.ui.PopupTool.prototype.onSelect = function () {
12147 if ( !this.isDisabled() ) {
12148 this.popup.toggle();
12149 }
12150 this.setActive( false );
12151 return false;
12152 };
12153
12154 /**
12155 * Handle the toolbar state being updated.
12156 *
12157 * @inheritdoc
12158 */
12159 OO.ui.PopupTool.prototype.onUpdateState = function () {
12160 this.setActive( false );
12161 };
12162
12163 /**
12164 * A ToolGroupTool is a special sort of tool that can contain other {@link OO.ui.Tool tools}
12165 * and {@link OO.ui.ToolGroup toolgroups}. The ToolGroupTool was specifically designed to be used
12166 * inside a {@link OO.ui.BarToolGroup bar} toolgroup to provide access to additional tools from
12167 * the bar item. Included tools will be displayed in a dropdown {@link OO.ui.ListToolGroup list}
12168 * when the ToolGroupTool is selected.
12169 *
12170 * // Example: ToolGroupTool with two nested tools, 'setting1' and 'setting2', defined elsewhere.
12171 *
12172 * function SettingsTool() {
12173 * SettingsTool.parent.apply( this, arguments );
12174 * };
12175 * OO.inheritClass( SettingsTool, OO.ui.ToolGroupTool );
12176 * SettingsTool.static.name = 'settings';
12177 * SettingsTool.static.title = 'Change settings';
12178 * SettingsTool.static.groupConfig = {
12179 * icon: 'settings',
12180 * label: 'ToolGroupTool',
12181 * include: [ 'setting1', 'setting2' ]
12182 * };
12183 * toolFactory.register( SettingsTool );
12184 *
12185 * For more information, please see the [OOjs UI documentation on MediaWiki][1].
12186 *
12187 * Please note that this implementation is subject to change per [T74159] [2].
12188 *
12189 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars#ToolGroupTool
12190 * [2]: https://phabricator.wikimedia.org/T74159
12191 *
12192 * @abstract
12193 * @class
12194 * @extends OO.ui.Tool
12195 *
12196 * @constructor
12197 * @param {OO.ui.ToolGroup} toolGroup
12198 * @param {Object} [config] Configuration options
12199 */
12200 OO.ui.ToolGroupTool = function OoUiToolGroupTool( toolGroup, config ) {
12201 // Allow passing positional parameters inside the config object
12202 if ( OO.isPlainObject( toolGroup ) && config === undefined ) {
12203 config = toolGroup;
12204 toolGroup = config.toolGroup;
12205 }
12206
12207 // Parent constructor
12208 OO.ui.ToolGroupTool.parent.call( this, toolGroup, config );
12209
12210 // Properties
12211 this.innerToolGroup = this.createGroup( this.constructor.static.groupConfig );
12212
12213 // Events
12214 this.innerToolGroup.connect( this, { disable: 'onToolGroupDisable' } );
12215
12216 // Initialization
12217 this.$link.remove();
12218 this.$element
12219 .addClass( 'oo-ui-toolGroupTool' )
12220 .append( this.innerToolGroup.$element );
12221 };
12222
12223 /* Setup */
12224
12225 OO.inheritClass( OO.ui.ToolGroupTool, OO.ui.Tool );
12226
12227 /* Static Properties */
12228
12229 /**
12230 * Toolgroup configuration.
12231 *
12232 * The toolgroup configuration consists of the tools to include, as well as an icon and label
12233 * to use for the bar item. Tools can be included by symbolic name, group, or with the
12234 * wildcard selector. Please see {@link OO.ui.ToolGroup toolgroup} for more information.
12235 *
12236 * @property {Object.<string,Array>}
12237 */
12238 OO.ui.ToolGroupTool.static.groupConfig = {};
12239
12240 /* Methods */
12241
12242 /**
12243 * Handle the tool being selected.
12244 *
12245 * @inheritdoc
12246 */
12247 OO.ui.ToolGroupTool.prototype.onSelect = function () {
12248 this.innerToolGroup.setActive( !this.innerToolGroup.active );
12249 return false;
12250 };
12251
12252 /**
12253 * Synchronize disabledness state of the tool with the inner toolgroup.
12254 *
12255 * @private
12256 * @param {boolean} disabled Element is disabled
12257 */
12258 OO.ui.ToolGroupTool.prototype.onToolGroupDisable = function ( disabled ) {
12259 this.setDisabled( disabled );
12260 };
12261
12262 /**
12263 * Handle the toolbar state being updated.
12264 *
12265 * @inheritdoc
12266 */
12267 OO.ui.ToolGroupTool.prototype.onUpdateState = function () {
12268 this.setActive( false );
12269 };
12270
12271 /**
12272 * Build a {@link OO.ui.ToolGroup toolgroup} from the specified configuration.
12273 *
12274 * @param {Object.<string,Array>} group Toolgroup configuration. Please see {@link OO.ui.ToolGroup toolgroup} for
12275 * more information.
12276 * @return {OO.ui.ListToolGroup}
12277 */
12278 OO.ui.ToolGroupTool.prototype.createGroup = function ( group ) {
12279 if ( group.include === '*' ) {
12280 // Apply defaults to catch-all groups
12281 if ( group.label === undefined ) {
12282 group.label = OO.ui.msg( 'ooui-toolbar-more' );
12283 }
12284 }
12285
12286 return this.toolbar.getToolGroupFactory().create( 'list', this.toolbar, group );
12287 };
12288
12289 /**
12290 * Mixin for OO.ui.Widget subclasses to provide OO.ui.mixin.GroupElement.
12291 *
12292 * Use together with OO.ui.mixin.ItemWidget to make disabled state inheritable.
12293 *
12294 * @private
12295 * @abstract
12296 * @class
12297 * @extends OO.ui.mixin.GroupElement
12298 *
12299 * @constructor
12300 * @param {Object} [config] Configuration options
12301 */
12302 OO.ui.mixin.GroupWidget = function OoUiMixinGroupWidget( config ) {
12303 // Parent constructor
12304 OO.ui.mixin.GroupWidget.parent.call( this, config );
12305 };
12306
12307 /* Setup */
12308
12309 OO.inheritClass( OO.ui.mixin.GroupWidget, OO.ui.mixin.GroupElement );
12310
12311 /* Methods */
12312
12313 /**
12314 * Set the disabled state of the widget.
12315 *
12316 * This will also update the disabled state of child widgets.
12317 *
12318 * @param {boolean} disabled Disable widget
12319 * @chainable
12320 */
12321 OO.ui.mixin.GroupWidget.prototype.setDisabled = function ( disabled ) {
12322 var i, len;
12323
12324 // Parent method
12325 // Note: Calling #setDisabled this way assumes this is mixed into an OO.ui.Widget
12326 OO.ui.Widget.prototype.setDisabled.call( this, disabled );
12327
12328 // During construction, #setDisabled is called before the OO.ui.mixin.GroupElement constructor
12329 if ( this.items ) {
12330 for ( i = 0, len = this.items.length; i < len; i++ ) {
12331 this.items[ i ].updateDisabled();
12332 }
12333 }
12334
12335 return this;
12336 };
12337
12338 /**
12339 * Mixin for widgets used as items in widgets that mix in OO.ui.mixin.GroupWidget.
12340 *
12341 * Item widgets have a reference to a OO.ui.mixin.GroupWidget while they are attached to the group. This
12342 * allows bidirectional communication.
12343 *
12344 * Use together with OO.ui.mixin.GroupWidget to make disabled state inheritable.
12345 *
12346 * @private
12347 * @abstract
12348 * @class
12349 *
12350 * @constructor
12351 */
12352 OO.ui.mixin.ItemWidget = function OoUiMixinItemWidget() {
12353 //
12354 };
12355
12356 /* Methods */
12357
12358 /**
12359 * Check if widget is disabled.
12360 *
12361 * Checks parent if present, making disabled state inheritable.
12362 *
12363 * @return {boolean} Widget is disabled
12364 */
12365 OO.ui.mixin.ItemWidget.prototype.isDisabled = function () {
12366 return this.disabled ||
12367 ( this.elementGroup instanceof OO.ui.Widget && this.elementGroup.isDisabled() );
12368 };
12369
12370 /**
12371 * Set group element is in.
12372 *
12373 * @param {OO.ui.mixin.GroupElement|null} group Group element, null if none
12374 * @chainable
12375 */
12376 OO.ui.mixin.ItemWidget.prototype.setElementGroup = function ( group ) {
12377 // Parent method
12378 // Note: Calling #setElementGroup this way assumes this is mixed into an OO.ui.Element
12379 OO.ui.Element.prototype.setElementGroup.call( this, group );
12380
12381 // Initialize item disabled states
12382 this.updateDisabled();
12383
12384 return this;
12385 };
12386
12387 /**
12388 * OutlineControlsWidget is a set of controls for an {@link OO.ui.OutlineSelectWidget outline select widget}.
12389 * Controls include moving items up and down, removing items, and adding different kinds of items.
12390 *
12391 * **Currently, this class is only used by {@link OO.ui.BookletLayout booklet layouts}.**
12392 *
12393 * @class
12394 * @extends OO.ui.Widget
12395 * @mixins OO.ui.mixin.GroupElement
12396 * @mixins OO.ui.mixin.IconElement
12397 *
12398 * @constructor
12399 * @param {OO.ui.OutlineSelectWidget} outline Outline to control
12400 * @param {Object} [config] Configuration options
12401 * @cfg {Object} [abilities] List of abilties
12402 * @cfg {boolean} [abilities.move=true] Allow moving movable items
12403 * @cfg {boolean} [abilities.remove=true] Allow removing removable items
12404 */
12405 OO.ui.OutlineControlsWidget = function OoUiOutlineControlsWidget( outline, config ) {
12406 // Allow passing positional parameters inside the config object
12407 if ( OO.isPlainObject( outline ) && config === undefined ) {
12408 config = outline;
12409 outline = config.outline;
12410 }
12411
12412 // Configuration initialization
12413 config = $.extend( { icon: 'add' }, config );
12414
12415 // Parent constructor
12416 OO.ui.OutlineControlsWidget.parent.call( this, config );
12417
12418 // Mixin constructors
12419 OO.ui.mixin.GroupElement.call( this, config );
12420 OO.ui.mixin.IconElement.call( this, config );
12421
12422 // Properties
12423 this.outline = outline;
12424 this.$movers = $( '<div>' );
12425 this.upButton = new OO.ui.ButtonWidget( {
12426 framed: false,
12427 icon: 'collapse',
12428 title: OO.ui.msg( 'ooui-outline-control-move-up' )
12429 } );
12430 this.downButton = new OO.ui.ButtonWidget( {
12431 framed: false,
12432 icon: 'expand',
12433 title: OO.ui.msg( 'ooui-outline-control-move-down' )
12434 } );
12435 this.removeButton = new OO.ui.ButtonWidget( {
12436 framed: false,
12437 icon: 'remove',
12438 title: OO.ui.msg( 'ooui-outline-control-remove' )
12439 } );
12440 this.abilities = { move: true, remove: true };
12441
12442 // Events
12443 outline.connect( this, {
12444 select: 'onOutlineChange',
12445 add: 'onOutlineChange',
12446 remove: 'onOutlineChange'
12447 } );
12448 this.upButton.connect( this, { click: [ 'emit', 'move', -1 ] } );
12449 this.downButton.connect( this, { click: [ 'emit', 'move', 1 ] } );
12450 this.removeButton.connect( this, { click: [ 'emit', 'remove' ] } );
12451
12452 // Initialization
12453 this.$element.addClass( 'oo-ui-outlineControlsWidget' );
12454 this.$group.addClass( 'oo-ui-outlineControlsWidget-items' );
12455 this.$movers
12456 .addClass( 'oo-ui-outlineControlsWidget-movers' )
12457 .append( this.removeButton.$element, this.upButton.$element, this.downButton.$element );
12458 this.$element.append( this.$icon, this.$group, this.$movers );
12459 this.setAbilities( config.abilities || {} );
12460 };
12461
12462 /* Setup */
12463
12464 OO.inheritClass( OO.ui.OutlineControlsWidget, OO.ui.Widget );
12465 OO.mixinClass( OO.ui.OutlineControlsWidget, OO.ui.mixin.GroupElement );
12466 OO.mixinClass( OO.ui.OutlineControlsWidget, OO.ui.mixin.IconElement );
12467
12468 /* Events */
12469
12470 /**
12471 * @event move
12472 * @param {number} places Number of places to move
12473 */
12474
12475 /**
12476 * @event remove
12477 */
12478
12479 /* Methods */
12480
12481 /**
12482 * Set abilities.
12483 *
12484 * @param {Object} abilities List of abilties
12485 * @param {boolean} [abilities.move] Allow moving movable items
12486 * @param {boolean} [abilities.remove] Allow removing removable items
12487 */
12488 OO.ui.OutlineControlsWidget.prototype.setAbilities = function ( abilities ) {
12489 var ability;
12490
12491 for ( ability in this.abilities ) {
12492 if ( abilities[ ability ] !== undefined ) {
12493 this.abilities[ ability ] = !!abilities[ ability ];
12494 }
12495 }
12496
12497 this.onOutlineChange();
12498 };
12499
12500 /**
12501 * @private
12502 * Handle outline change events.
12503 */
12504 OO.ui.OutlineControlsWidget.prototype.onOutlineChange = function () {
12505 var i, len, firstMovable, lastMovable,
12506 items = this.outline.getItems(),
12507 selectedItem = this.outline.getSelectedItem(),
12508 movable = this.abilities.move && selectedItem && selectedItem.isMovable(),
12509 removable = this.abilities.remove && selectedItem && selectedItem.isRemovable();
12510
12511 if ( movable ) {
12512 i = -1;
12513 len = items.length;
12514 while ( ++i < len ) {
12515 if ( items[ i ].isMovable() ) {
12516 firstMovable = items[ i ];
12517 break;
12518 }
12519 }
12520 i = len;
12521 while ( i-- ) {
12522 if ( items[ i ].isMovable() ) {
12523 lastMovable = items[ i ];
12524 break;
12525 }
12526 }
12527 }
12528 this.upButton.setDisabled( !movable || selectedItem === firstMovable );
12529 this.downButton.setDisabled( !movable || selectedItem === lastMovable );
12530 this.removeButton.setDisabled( !removable );
12531 };
12532
12533 /**
12534 * ToggleWidget implements basic behavior of widgets with an on/off state.
12535 * Please see OO.ui.ToggleButtonWidget and OO.ui.ToggleSwitchWidget for examples.
12536 *
12537 * @abstract
12538 * @class
12539 * @extends OO.ui.Widget
12540 *
12541 * @constructor
12542 * @param {Object} [config] Configuration options
12543 * @cfg {boolean} [value=false] The toggle’s initial on/off state.
12544 * By default, the toggle is in the 'off' state.
12545 */
12546 OO.ui.ToggleWidget = function OoUiToggleWidget( config ) {
12547 // Configuration initialization
12548 config = config || {};
12549
12550 // Parent constructor
12551 OO.ui.ToggleWidget.parent.call( this, config );
12552
12553 // Properties
12554 this.value = null;
12555
12556 // Initialization
12557 this.$element.addClass( 'oo-ui-toggleWidget' );
12558 this.setValue( !!config.value );
12559 };
12560
12561 /* Setup */
12562
12563 OO.inheritClass( OO.ui.ToggleWidget, OO.ui.Widget );
12564
12565 /* Events */
12566
12567 /**
12568 * @event change
12569 *
12570 * A change event is emitted when the on/off state of the toggle changes.
12571 *
12572 * @param {boolean} value Value representing the new state of the toggle
12573 */
12574
12575 /* Methods */
12576
12577 /**
12578 * Get the value representing the toggle’s state.
12579 *
12580 * @return {boolean} The on/off state of the toggle
12581 */
12582 OO.ui.ToggleWidget.prototype.getValue = function () {
12583 return this.value;
12584 };
12585
12586 /**
12587 * Set the state of the toggle: `true` for 'on', `false' for 'off'.
12588 *
12589 * @param {boolean} value The state of the toggle
12590 * @fires change
12591 * @chainable
12592 */
12593 OO.ui.ToggleWidget.prototype.setValue = function ( value ) {
12594 value = !!value;
12595 if ( this.value !== value ) {
12596 this.value = value;
12597 this.emit( 'change', value );
12598 this.$element.toggleClass( 'oo-ui-toggleWidget-on', value );
12599 this.$element.toggleClass( 'oo-ui-toggleWidget-off', !value );
12600 this.$element.attr( 'aria-checked', value.toString() );
12601 }
12602 return this;
12603 };
12604
12605 /**
12606 * A ButtonGroupWidget groups related buttons and is used together with OO.ui.ButtonWidget and
12607 * its subclasses. Each button in a group is addressed by a unique reference. Buttons can be added,
12608 * removed, and cleared from the group.
12609 *
12610 * @example
12611 * // Example: A ButtonGroupWidget with two buttons
12612 * var button1 = new OO.ui.PopupButtonWidget( {
12613 * label: 'Select a category',
12614 * icon: 'menu',
12615 * popup: {
12616 * $content: $( '<p>List of categories...</p>' ),
12617 * padded: true,
12618 * align: 'left'
12619 * }
12620 * } );
12621 * var button2 = new OO.ui.ButtonWidget( {
12622 * label: 'Add item'
12623 * });
12624 * var buttonGroup = new OO.ui.ButtonGroupWidget( {
12625 * items: [button1, button2]
12626 * } );
12627 * $( 'body' ).append( buttonGroup.$element );
12628 *
12629 * @class
12630 * @extends OO.ui.Widget
12631 * @mixins OO.ui.mixin.GroupElement
12632 *
12633 * @constructor
12634 * @param {Object} [config] Configuration options
12635 * @cfg {OO.ui.ButtonWidget[]} [items] Buttons to add
12636 */
12637 OO.ui.ButtonGroupWidget = function OoUiButtonGroupWidget( config ) {
12638 // Configuration initialization
12639 config = config || {};
12640
12641 // Parent constructor
12642 OO.ui.ButtonGroupWidget.parent.call( this, config );
12643
12644 // Mixin constructors
12645 OO.ui.mixin.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) );
12646
12647 // Initialization
12648 this.$element.addClass( 'oo-ui-buttonGroupWidget' );
12649 if ( Array.isArray( config.items ) ) {
12650 this.addItems( config.items );
12651 }
12652 };
12653
12654 /* Setup */
12655
12656 OO.inheritClass( OO.ui.ButtonGroupWidget, OO.ui.Widget );
12657 OO.mixinClass( OO.ui.ButtonGroupWidget, OO.ui.mixin.GroupElement );
12658
12659 /**
12660 * ButtonWidget is a generic widget for buttons. A wide variety of looks,
12661 * feels, and functionality can be customized via the class’s configuration options
12662 * and methods. Please see the [OOjs UI documentation on MediaWiki] [1] for more information
12663 * and examples.
12664 *
12665 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches
12666 *
12667 * @example
12668 * // A button widget
12669 * var button = new OO.ui.ButtonWidget( {
12670 * label: 'Button with Icon',
12671 * icon: 'remove',
12672 * iconTitle: 'Remove'
12673 * } );
12674 * $( 'body' ).append( button.$element );
12675 *
12676 * NOTE: HTML form buttons should use the OO.ui.ButtonInputWidget class.
12677 *
12678 * @class
12679 * @extends OO.ui.Widget
12680 * @mixins OO.ui.mixin.ButtonElement
12681 * @mixins OO.ui.mixin.IconElement
12682 * @mixins OO.ui.mixin.IndicatorElement
12683 * @mixins OO.ui.mixin.LabelElement
12684 * @mixins OO.ui.mixin.TitledElement
12685 * @mixins OO.ui.mixin.FlaggedElement
12686 * @mixins OO.ui.mixin.TabIndexedElement
12687 * @mixins OO.ui.mixin.AccessKeyedElement
12688 *
12689 * @constructor
12690 * @param {Object} [config] Configuration options
12691 * @cfg {string} [href] Hyperlink to visit when the button is clicked.
12692 * @cfg {string} [target] The frame or window in which to open the hyperlink.
12693 * @cfg {boolean} [noFollow] Search engine traversal hint (default: true)
12694 */
12695 OO.ui.ButtonWidget = function OoUiButtonWidget( config ) {
12696 // Configuration initialization
12697 config = config || {};
12698
12699 // Parent constructor
12700 OO.ui.ButtonWidget.parent.call( this, config );
12701
12702 // Mixin constructors
12703 OO.ui.mixin.ButtonElement.call( this, config );
12704 OO.ui.mixin.IconElement.call( this, config );
12705 OO.ui.mixin.IndicatorElement.call( this, config );
12706 OO.ui.mixin.LabelElement.call( this, config );
12707 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$button } ) );
12708 OO.ui.mixin.FlaggedElement.call( this, config );
12709 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$button } ) );
12710 OO.ui.mixin.AccessKeyedElement.call( this, $.extend( {}, config, { $accessKeyed: this.$button } ) );
12711
12712 // Properties
12713 this.href = null;
12714 this.target = null;
12715 this.noFollow = false;
12716
12717 // Events
12718 this.connect( this, { disable: 'onDisable' } );
12719
12720 // Initialization
12721 this.$button.append( this.$icon, this.$label, this.$indicator );
12722 this.$element
12723 .addClass( 'oo-ui-buttonWidget' )
12724 .append( this.$button );
12725 this.setHref( config.href );
12726 this.setTarget( config.target );
12727 this.setNoFollow( config.noFollow );
12728 };
12729
12730 /* Setup */
12731
12732 OO.inheritClass( OO.ui.ButtonWidget, OO.ui.Widget );
12733 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.ButtonElement );
12734 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.IconElement );
12735 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.IndicatorElement );
12736 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.LabelElement );
12737 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.TitledElement );
12738 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.FlaggedElement );
12739 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.TabIndexedElement );
12740 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.AccessKeyedElement );
12741
12742 /* Methods */
12743
12744 /**
12745 * @inheritdoc
12746 */
12747 OO.ui.ButtonWidget.prototype.onMouseDown = function ( e ) {
12748 if ( !this.isDisabled() ) {
12749 // Remove the tab-index while the button is down to prevent the button from stealing focus
12750 this.$button.removeAttr( 'tabindex' );
12751 }
12752
12753 return OO.ui.mixin.ButtonElement.prototype.onMouseDown.call( this, e );
12754 };
12755
12756 /**
12757 * @inheritdoc
12758 */
12759 OO.ui.ButtonWidget.prototype.onMouseUp = function ( e ) {
12760 if ( !this.isDisabled() ) {
12761 // Restore the tab-index after the button is up to restore the button's accessibility
12762 this.$button.attr( 'tabindex', this.tabIndex );
12763 }
12764
12765 return OO.ui.mixin.ButtonElement.prototype.onMouseUp.call( this, e );
12766 };
12767
12768 /**
12769 * Get hyperlink location.
12770 *
12771 * @return {string} Hyperlink location
12772 */
12773 OO.ui.ButtonWidget.prototype.getHref = function () {
12774 return this.href;
12775 };
12776
12777 /**
12778 * Get hyperlink target.
12779 *
12780 * @return {string} Hyperlink target
12781 */
12782 OO.ui.ButtonWidget.prototype.getTarget = function () {
12783 return this.target;
12784 };
12785
12786 /**
12787 * Get search engine traversal hint.
12788 *
12789 * @return {boolean} Whether search engines should avoid traversing this hyperlink
12790 */
12791 OO.ui.ButtonWidget.prototype.getNoFollow = function () {
12792 return this.noFollow;
12793 };
12794
12795 /**
12796 * Set hyperlink location.
12797 *
12798 * @param {string|null} href Hyperlink location, null to remove
12799 */
12800 OO.ui.ButtonWidget.prototype.setHref = function ( href ) {
12801 href = typeof href === 'string' ? href : null;
12802 if ( href !== null ) {
12803 if ( !OO.ui.isSafeUrl( href ) ) {
12804 throw new Error( 'Potentially unsafe href provided: ' + href );
12805 }
12806
12807 }
12808
12809 if ( href !== this.href ) {
12810 this.href = href;
12811 this.updateHref();
12812 }
12813
12814 return this;
12815 };
12816
12817 /**
12818 * Update the `href` attribute, in case of changes to href or
12819 * disabled state.
12820 *
12821 * @private
12822 * @chainable
12823 */
12824 OO.ui.ButtonWidget.prototype.updateHref = function () {
12825 if ( this.href !== null && !this.isDisabled() ) {
12826 this.$button.attr( 'href', this.href );
12827 } else {
12828 this.$button.removeAttr( 'href' );
12829 }
12830
12831 return this;
12832 };
12833
12834 /**
12835 * Handle disable events.
12836 *
12837 * @private
12838 * @param {boolean} disabled Element is disabled
12839 */
12840 OO.ui.ButtonWidget.prototype.onDisable = function () {
12841 this.updateHref();
12842 };
12843
12844 /**
12845 * Set hyperlink target.
12846 *
12847 * @param {string|null} target Hyperlink target, null to remove
12848 */
12849 OO.ui.ButtonWidget.prototype.setTarget = function ( target ) {
12850 target = typeof target === 'string' ? target : null;
12851
12852 if ( target !== this.target ) {
12853 this.target = target;
12854 if ( target !== null ) {
12855 this.$button.attr( 'target', target );
12856 } else {
12857 this.$button.removeAttr( 'target' );
12858 }
12859 }
12860
12861 return this;
12862 };
12863
12864 /**
12865 * Set search engine traversal hint.
12866 *
12867 * @param {boolean} noFollow True if search engines should avoid traversing this hyperlink
12868 */
12869 OO.ui.ButtonWidget.prototype.setNoFollow = function ( noFollow ) {
12870 noFollow = typeof noFollow === 'boolean' ? noFollow : true;
12871
12872 if ( noFollow !== this.noFollow ) {
12873 this.noFollow = noFollow;
12874 if ( noFollow ) {
12875 this.$button.attr( 'rel', 'nofollow' );
12876 } else {
12877 this.$button.removeAttr( 'rel' );
12878 }
12879 }
12880
12881 return this;
12882 };
12883
12884 /**
12885 * An ActionWidget is a {@link OO.ui.ButtonWidget button widget} that executes an action.
12886 * Action widgets are used with OO.ui.ActionSet, which manages the behavior and availability
12887 * of the actions.
12888 *
12889 * Both actions and action sets are primarily used with {@link OO.ui.Dialog Dialogs}.
12890 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information
12891 * and examples.
12892 *
12893 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Action_sets
12894 *
12895 * @class
12896 * @extends OO.ui.ButtonWidget
12897 * @mixins OO.ui.mixin.PendingElement
12898 *
12899 * @constructor
12900 * @param {Object} [config] Configuration options
12901 * @cfg {string} [action] Symbolic name of the action (e.g., ‘continue’ or ‘cancel’).
12902 * @cfg {string[]} [modes] Symbolic names of the modes (e.g., ‘edit’ or ‘read’) in which the action
12903 * should be made available. See the action set's {@link OO.ui.ActionSet#setMode setMode} method
12904 * for more information about setting modes.
12905 * @cfg {boolean} [framed=false] Render the action button with a frame
12906 */
12907 OO.ui.ActionWidget = function OoUiActionWidget( config ) {
12908 // Configuration initialization
12909 config = $.extend( { framed: false }, config );
12910
12911 // Parent constructor
12912 OO.ui.ActionWidget.parent.call( this, config );
12913
12914 // Mixin constructors
12915 OO.ui.mixin.PendingElement.call( this, config );
12916
12917 // Properties
12918 this.action = config.action || '';
12919 this.modes = config.modes || [];
12920 this.width = 0;
12921 this.height = 0;
12922
12923 // Initialization
12924 this.$element.addClass( 'oo-ui-actionWidget' );
12925 };
12926
12927 /* Setup */
12928
12929 OO.inheritClass( OO.ui.ActionWidget, OO.ui.ButtonWidget );
12930 OO.mixinClass( OO.ui.ActionWidget, OO.ui.mixin.PendingElement );
12931
12932 /* Events */
12933
12934 /**
12935 * A resize event is emitted when the size of the widget changes.
12936 *
12937 * @event resize
12938 */
12939
12940 /* Methods */
12941
12942 /**
12943 * Check if the action is configured to be available in the specified `mode`.
12944 *
12945 * @param {string} mode Name of mode
12946 * @return {boolean} The action is configured with the mode
12947 */
12948 OO.ui.ActionWidget.prototype.hasMode = function ( mode ) {
12949 return this.modes.indexOf( mode ) !== -1;
12950 };
12951
12952 /**
12953 * Get the symbolic name of the action (e.g., ‘continue’ or ‘cancel’).
12954 *
12955 * @return {string}
12956 */
12957 OO.ui.ActionWidget.prototype.getAction = function () {
12958 return this.action;
12959 };
12960
12961 /**
12962 * Get the symbolic name of the mode or modes for which the action is configured to be available.
12963 *
12964 * The current mode is set with the action set's {@link OO.ui.ActionSet#setMode setMode} method.
12965 * Only actions that are configured to be avaiable in the current mode will be visible. All other actions
12966 * are hidden.
12967 *
12968 * @return {string[]}
12969 */
12970 OO.ui.ActionWidget.prototype.getModes = function () {
12971 return this.modes.slice();
12972 };
12973
12974 /**
12975 * Emit a resize event if the size has changed.
12976 *
12977 * @private
12978 * @chainable
12979 */
12980 OO.ui.ActionWidget.prototype.propagateResize = function () {
12981 var width, height;
12982
12983 if ( this.isElementAttached() ) {
12984 width = this.$element.width();
12985 height = this.$element.height();
12986
12987 if ( width !== this.width || height !== this.height ) {
12988 this.width = width;
12989 this.height = height;
12990 this.emit( 'resize' );
12991 }
12992 }
12993
12994 return this;
12995 };
12996
12997 /**
12998 * @inheritdoc
12999 */
13000 OO.ui.ActionWidget.prototype.setIcon = function () {
13001 // Mixin method
13002 OO.ui.mixin.IconElement.prototype.setIcon.apply( this, arguments );
13003 this.propagateResize();
13004
13005 return this;
13006 };
13007
13008 /**
13009 * @inheritdoc
13010 */
13011 OO.ui.ActionWidget.prototype.setLabel = function () {
13012 // Mixin method
13013 OO.ui.mixin.LabelElement.prototype.setLabel.apply( this, arguments );
13014 this.propagateResize();
13015
13016 return this;
13017 };
13018
13019 /**
13020 * @inheritdoc
13021 */
13022 OO.ui.ActionWidget.prototype.setFlags = function () {
13023 // Mixin method
13024 OO.ui.mixin.FlaggedElement.prototype.setFlags.apply( this, arguments );
13025 this.propagateResize();
13026
13027 return this;
13028 };
13029
13030 /**
13031 * @inheritdoc
13032 */
13033 OO.ui.ActionWidget.prototype.clearFlags = function () {
13034 // Mixin method
13035 OO.ui.mixin.FlaggedElement.prototype.clearFlags.apply( this, arguments );
13036 this.propagateResize();
13037
13038 return this;
13039 };
13040
13041 /**
13042 * Toggle the visibility of the action button.
13043 *
13044 * @param {boolean} [show] Show button, omit to toggle visibility
13045 * @chainable
13046 */
13047 OO.ui.ActionWidget.prototype.toggle = function () {
13048 // Parent method
13049 OO.ui.ActionWidget.parent.prototype.toggle.apply( this, arguments );
13050 this.propagateResize();
13051
13052 return this;
13053 };
13054
13055 /**
13056 * PopupButtonWidgets toggle the visibility of a contained {@link OO.ui.PopupWidget PopupWidget},
13057 * which is used to display additional information or options.
13058 *
13059 * @example
13060 * // Example of a popup button.
13061 * var popupButton = new OO.ui.PopupButtonWidget( {
13062 * label: 'Popup button with options',
13063 * icon: 'menu',
13064 * popup: {
13065 * $content: $( '<p>Additional options here.</p>' ),
13066 * padded: true,
13067 * align: 'force-left'
13068 * }
13069 * } );
13070 * // Append the button to the DOM.
13071 * $( 'body' ).append( popupButton.$element );
13072 *
13073 * @class
13074 * @extends OO.ui.ButtonWidget
13075 * @mixins OO.ui.mixin.PopupElement
13076 *
13077 * @constructor
13078 * @param {Object} [config] Configuration options
13079 */
13080 OO.ui.PopupButtonWidget = function OoUiPopupButtonWidget( config ) {
13081 // Parent constructor
13082 OO.ui.PopupButtonWidget.parent.call( this, config );
13083
13084 // Mixin constructors
13085 OO.ui.mixin.PopupElement.call( this, config );
13086
13087 // Events
13088 this.connect( this, { click: 'onAction' } );
13089
13090 // Initialization
13091 this.$element
13092 .addClass( 'oo-ui-popupButtonWidget' )
13093 .attr( 'aria-haspopup', 'true' )
13094 .append( this.popup.$element );
13095 };
13096
13097 /* Setup */
13098
13099 OO.inheritClass( OO.ui.PopupButtonWidget, OO.ui.ButtonWidget );
13100 OO.mixinClass( OO.ui.PopupButtonWidget, OO.ui.mixin.PopupElement );
13101
13102 /* Methods */
13103
13104 /**
13105 * Handle the button action being triggered.
13106 *
13107 * @private
13108 */
13109 OO.ui.PopupButtonWidget.prototype.onAction = function () {
13110 this.popup.toggle();
13111 };
13112
13113 /**
13114 * ToggleButtons are buttons that have a state (‘on’ or ‘off’) that is represented by a
13115 * Boolean value. Like other {@link OO.ui.ButtonWidget buttons}, toggle buttons can be
13116 * configured with {@link OO.ui.mixin.IconElement icons}, {@link OO.ui.mixin.IndicatorElement indicators},
13117 * {@link OO.ui.mixin.TitledElement titles}, {@link OO.ui.mixin.FlaggedElement styling flags},
13118 * and {@link OO.ui.mixin.LabelElement labels}. Please see
13119 * the [OOjs UI documentation][1] on MediaWiki for more information.
13120 *
13121 * @example
13122 * // Toggle buttons in the 'off' and 'on' state.
13123 * var toggleButton1 = new OO.ui.ToggleButtonWidget( {
13124 * label: 'Toggle Button off'
13125 * } );
13126 * var toggleButton2 = new OO.ui.ToggleButtonWidget( {
13127 * label: 'Toggle Button on',
13128 * value: true
13129 * } );
13130 * // Append the buttons to the DOM.
13131 * $( 'body' ).append( toggleButton1.$element, toggleButton2.$element );
13132 *
13133 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#Toggle_buttons
13134 *
13135 * @class
13136 * @extends OO.ui.ToggleWidget
13137 * @mixins OO.ui.mixin.ButtonElement
13138 * @mixins OO.ui.mixin.IconElement
13139 * @mixins OO.ui.mixin.IndicatorElement
13140 * @mixins OO.ui.mixin.LabelElement
13141 * @mixins OO.ui.mixin.TitledElement
13142 * @mixins OO.ui.mixin.FlaggedElement
13143 * @mixins OO.ui.mixin.TabIndexedElement
13144 *
13145 * @constructor
13146 * @param {Object} [config] Configuration options
13147 * @cfg {boolean} [value=false] The toggle button’s initial on/off
13148 * state. By default, the button is in the 'off' state.
13149 */
13150 OO.ui.ToggleButtonWidget = function OoUiToggleButtonWidget( config ) {
13151 // Configuration initialization
13152 config = config || {};
13153
13154 // Parent constructor
13155 OO.ui.ToggleButtonWidget.parent.call( this, config );
13156
13157 // Mixin constructors
13158 OO.ui.mixin.ButtonElement.call( this, config );
13159 OO.ui.mixin.IconElement.call( this, config );
13160 OO.ui.mixin.IndicatorElement.call( this, config );
13161 OO.ui.mixin.LabelElement.call( this, config );
13162 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$button } ) );
13163 OO.ui.mixin.FlaggedElement.call( this, config );
13164 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$button } ) );
13165
13166 // Events
13167 this.connect( this, { click: 'onAction' } );
13168
13169 // Initialization
13170 this.$button.append( this.$icon, this.$label, this.$indicator );
13171 this.$element
13172 .addClass( 'oo-ui-toggleButtonWidget' )
13173 .append( this.$button );
13174 };
13175
13176 /* Setup */
13177
13178 OO.inheritClass( OO.ui.ToggleButtonWidget, OO.ui.ToggleWidget );
13179 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.ButtonElement );
13180 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.IconElement );
13181 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.IndicatorElement );
13182 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.LabelElement );
13183 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.TitledElement );
13184 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.FlaggedElement );
13185 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.TabIndexedElement );
13186
13187 /* Methods */
13188
13189 /**
13190 * Handle the button action being triggered.
13191 *
13192 * @private
13193 */
13194 OO.ui.ToggleButtonWidget.prototype.onAction = function () {
13195 this.setValue( !this.value );
13196 };
13197
13198 /**
13199 * @inheritdoc
13200 */
13201 OO.ui.ToggleButtonWidget.prototype.setValue = function ( value ) {
13202 value = !!value;
13203 if ( value !== this.value ) {
13204 // Might be called from parent constructor before ButtonElement constructor
13205 if ( this.$button ) {
13206 this.$button.attr( 'aria-pressed', value.toString() );
13207 }
13208 this.setActive( value );
13209 }
13210
13211 // Parent method
13212 OO.ui.ToggleButtonWidget.parent.prototype.setValue.call( this, value );
13213
13214 return this;
13215 };
13216
13217 /**
13218 * @inheritdoc
13219 */
13220 OO.ui.ToggleButtonWidget.prototype.setButtonElement = function ( $button ) {
13221 if ( this.$button ) {
13222 this.$button.removeAttr( 'aria-pressed' );
13223 }
13224 OO.ui.mixin.ButtonElement.prototype.setButtonElement.call( this, $button );
13225 this.$button.attr( 'aria-pressed', this.value.toString() );
13226 };
13227
13228 /**
13229 * CapsuleMultiSelectWidgets are something like a {@link OO.ui.ComboBoxInputWidget combo box widget}
13230 * that allows for selecting multiple values.
13231 *
13232 * For more information about menus and options, please see the [OOjs UI documentation on MediaWiki][1].
13233 *
13234 * @example
13235 * // Example: A CapsuleMultiSelectWidget.
13236 * var capsule = new OO.ui.CapsuleMultiSelectWidget( {
13237 * label: 'CapsuleMultiSelectWidget',
13238 * selected: [ 'Option 1', 'Option 3' ],
13239 * menu: {
13240 * items: [
13241 * new OO.ui.MenuOptionWidget( {
13242 * data: 'Option 1',
13243 * label: 'Option One'
13244 * } ),
13245 * new OO.ui.MenuOptionWidget( {
13246 * data: 'Option 2',
13247 * label: 'Option Two'
13248 * } ),
13249 * new OO.ui.MenuOptionWidget( {
13250 * data: 'Option 3',
13251 * label: 'Option Three'
13252 * } ),
13253 * new OO.ui.MenuOptionWidget( {
13254 * data: 'Option 4',
13255 * label: 'Option Four'
13256 * } ),
13257 * new OO.ui.MenuOptionWidget( {
13258 * data: 'Option 5',
13259 * label: 'Option Five'
13260 * } )
13261 * ]
13262 * }
13263 * } );
13264 * $( 'body' ).append( capsule.$element );
13265 *
13266 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
13267 *
13268 * @class
13269 * @extends OO.ui.Widget
13270 * @mixins OO.ui.mixin.TabIndexedElement
13271 * @mixins OO.ui.mixin.GroupElement
13272 *
13273 * @constructor
13274 * @param {Object} [config] Configuration options
13275 * @cfg {boolean} [allowArbitrary=false] Allow data items to be added even if not present in the menu.
13276 * @cfg {Object} [menu] Configuration options to pass to the {@link OO.ui.MenuSelectWidget menu select widget}.
13277 * @cfg {Object} [popup] Configuration options to pass to the {@link OO.ui.PopupWidget popup widget}.
13278 * If specified, this popup will be shown instead of the menu (but the menu
13279 * will still be used for item labels and allowArbitrary=false). The widgets
13280 * in the popup should use this.addItemsFromData() or this.addItems() as necessary.
13281 * @cfg {jQuery} [$overlay] Render the menu or popup into a separate layer.
13282 * This configuration is useful in cases where the expanded menu is larger than
13283 * its containing `<div>`. The specified overlay layer is usually on top of
13284 * the containing `<div>` and has a larger area. By default, the menu uses
13285 * relative positioning.
13286 */
13287 OO.ui.CapsuleMultiSelectWidget = function OoUiCapsuleMultiSelectWidget( config ) {
13288 var $tabFocus;
13289
13290 // Configuration initialization
13291 config = config || {};
13292
13293 // Parent constructor
13294 OO.ui.CapsuleMultiSelectWidget.parent.call( this, config );
13295
13296 // Properties (must be set before mixin constructor calls)
13297 this.$input = config.popup ? null : $( '<input>' );
13298 this.$handle = $( '<div>' );
13299
13300 // Mixin constructors
13301 OO.ui.mixin.GroupElement.call( this, config );
13302 if ( config.popup ) {
13303 config.popup = $.extend( {}, config.popup, {
13304 align: 'forwards',
13305 anchor: false
13306 } );
13307 OO.ui.mixin.PopupElement.call( this, config );
13308 $tabFocus = $( '<span>' );
13309 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: $tabFocus } ) );
13310 } else {
13311 this.popup = null;
13312 $tabFocus = null;
13313 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$input } ) );
13314 }
13315 OO.ui.mixin.IndicatorElement.call( this, config );
13316 OO.ui.mixin.IconElement.call( this, config );
13317
13318 // Properties
13319 this.allowArbitrary = !!config.allowArbitrary;
13320 this.$overlay = config.$overlay || this.$element;
13321 this.menu = new OO.ui.FloatingMenuSelectWidget( $.extend(
13322 {
13323 widget: this,
13324 $input: this.$input,
13325 $container: this.$element,
13326 filterFromInput: true,
13327 disabled: this.isDisabled()
13328 },
13329 config.menu
13330 ) );
13331
13332 // Events
13333 if ( this.popup ) {
13334 $tabFocus.on( {
13335 focus: this.onFocusForPopup.bind( this )
13336 } );
13337 this.popup.$element.on( 'focusout', this.onPopupFocusOut.bind( this ) );
13338 if ( this.popup.$autoCloseIgnore ) {
13339 this.popup.$autoCloseIgnore.on( 'focusout', this.onPopupFocusOut.bind( this ) );
13340 }
13341 this.popup.connect( this, {
13342 toggle: function ( visible ) {
13343 $tabFocus.toggle( !visible );
13344 }
13345 } );
13346 } else {
13347 this.$input.on( {
13348 focus: this.onInputFocus.bind( this ),
13349 blur: this.onInputBlur.bind( this ),
13350 'propertychange change click mouseup keydown keyup input cut paste select': this.onInputChange.bind( this ),
13351 keydown: this.onKeyDown.bind( this ),
13352 keypress: this.onKeyPress.bind( this )
13353 } );
13354 }
13355 this.menu.connect( this, {
13356 choose: 'onMenuChoose',
13357 add: 'onMenuItemsChange',
13358 remove: 'onMenuItemsChange'
13359 } );
13360 this.$handle.on( {
13361 click: this.onClick.bind( this )
13362 } );
13363
13364 // Initialization
13365 if ( this.$input ) {
13366 this.$input.prop( 'disabled', this.isDisabled() );
13367 this.$input.attr( {
13368 role: 'combobox',
13369 'aria-autocomplete': 'list'
13370 } );
13371 this.$input.width( '1em' );
13372 }
13373 if ( config.data ) {
13374 this.setItemsFromData( config.data );
13375 }
13376 this.$group.addClass( 'oo-ui-capsuleMultiSelectWidget-group' );
13377 this.$handle.addClass( 'oo-ui-capsuleMultiSelectWidget-handle' )
13378 .append( this.$indicator, this.$icon, this.$group );
13379 this.$element.addClass( 'oo-ui-capsuleMultiSelectWidget' )
13380 .append( this.$handle );
13381 if ( this.popup ) {
13382 this.$handle.append( $tabFocus );
13383 this.$overlay.append( this.popup.$element );
13384 } else {
13385 this.$handle.append( this.$input );
13386 this.$overlay.append( this.menu.$element );
13387 }
13388 this.onMenuItemsChange();
13389 };
13390
13391 /* Setup */
13392
13393 OO.inheritClass( OO.ui.CapsuleMultiSelectWidget, OO.ui.Widget );
13394 OO.mixinClass( OO.ui.CapsuleMultiSelectWidget, OO.ui.mixin.GroupElement );
13395 OO.mixinClass( OO.ui.CapsuleMultiSelectWidget, OO.ui.mixin.PopupElement );
13396 OO.mixinClass( OO.ui.CapsuleMultiSelectWidget, OO.ui.mixin.TabIndexedElement );
13397 OO.mixinClass( OO.ui.CapsuleMultiSelectWidget, OO.ui.mixin.IndicatorElement );
13398 OO.mixinClass( OO.ui.CapsuleMultiSelectWidget, OO.ui.mixin.IconElement );
13399
13400 /* Events */
13401
13402 /**
13403 * @event change
13404 *
13405 * A change event is emitted when the set of selected items changes.
13406 *
13407 * @param {Mixed[]} datas Data of the now-selected items
13408 */
13409
13410 /* Methods */
13411
13412 /**
13413 * Construct a OO.ui.CapsuleItemWidget (or a subclass thereof) from given label and data.
13414 *
13415 * @protected
13416 * @param {Mixed} data Custom data of any type.
13417 * @param {string} label The label text.
13418 * @return {OO.ui.CapsuleItemWidget}
13419 */
13420 OO.ui.CapsuleMultiSelectWidget.prototype.createItemWidget = function ( data, label ) {
13421 return new OO.ui.CapsuleItemWidget( { data: data, label: label } );
13422 };
13423
13424 /**
13425 * Get the data of the items in the capsule
13426 * @return {Mixed[]}
13427 */
13428 OO.ui.CapsuleMultiSelectWidget.prototype.getItemsData = function () {
13429 return $.map( this.getItems(), function ( e ) { return e.data; } );
13430 };
13431
13432 /**
13433 * Set the items in the capsule by providing data
13434 * @chainable
13435 * @param {Mixed[]} datas
13436 * @return {OO.ui.CapsuleMultiSelectWidget}
13437 */
13438 OO.ui.CapsuleMultiSelectWidget.prototype.setItemsFromData = function ( datas ) {
13439 var widget = this,
13440 menu = this.menu,
13441 items = this.getItems();
13442
13443 $.each( datas, function ( i, data ) {
13444 var j, label,
13445 item = menu.getItemFromData( data );
13446
13447 if ( item ) {
13448 label = item.label;
13449 } else if ( widget.allowArbitrary ) {
13450 label = String( data );
13451 } else {
13452 return;
13453 }
13454
13455 item = null;
13456 for ( j = 0; j < items.length; j++ ) {
13457 if ( items[ j ].data === data && items[ j ].label === label ) {
13458 item = items[ j ];
13459 items.splice( j, 1 );
13460 break;
13461 }
13462 }
13463 if ( !item ) {
13464 item = widget.createItemWidget( data, label );
13465 }
13466 widget.addItems( [ item ], i );
13467 } );
13468
13469 if ( items.length ) {
13470 widget.removeItems( items );
13471 }
13472
13473 return this;
13474 };
13475
13476 /**
13477 * Add items to the capsule by providing their data
13478 * @chainable
13479 * @param {Mixed[]} datas
13480 * @return {OO.ui.CapsuleMultiSelectWidget}
13481 */
13482 OO.ui.CapsuleMultiSelectWidget.prototype.addItemsFromData = function ( datas ) {
13483 var widget = this,
13484 menu = this.menu,
13485 items = [];
13486
13487 $.each( datas, function ( i, data ) {
13488 var item;
13489
13490 if ( !widget.getItemFromData( data ) ) {
13491 item = menu.getItemFromData( data );
13492 if ( item ) {
13493 items.push( widget.createItemWidget( data, item.label ) );
13494 } else if ( widget.allowArbitrary ) {
13495 items.push( widget.createItemWidget( data, String( data ) ) );
13496 }
13497 }
13498 } );
13499
13500 if ( items.length ) {
13501 this.addItems( items );
13502 }
13503
13504 return this;
13505 };
13506
13507 /**
13508 * Remove items by data
13509 * @chainable
13510 * @param {Mixed[]} datas
13511 * @return {OO.ui.CapsuleMultiSelectWidget}
13512 */
13513 OO.ui.CapsuleMultiSelectWidget.prototype.removeItemsFromData = function ( datas ) {
13514 var widget = this,
13515 items = [];
13516
13517 $.each( datas, function ( i, data ) {
13518 var item = widget.getItemFromData( data );
13519 if ( item ) {
13520 items.push( item );
13521 }
13522 } );
13523
13524 if ( items.length ) {
13525 this.removeItems( items );
13526 }
13527
13528 return this;
13529 };
13530
13531 /**
13532 * @inheritdoc
13533 */
13534 OO.ui.CapsuleMultiSelectWidget.prototype.addItems = function ( items ) {
13535 var same, i, l,
13536 oldItems = this.items.slice();
13537
13538 OO.ui.mixin.GroupElement.prototype.addItems.call( this, items );
13539
13540 if ( this.items.length !== oldItems.length ) {
13541 same = false;
13542 } else {
13543 same = true;
13544 for ( i = 0, l = oldItems.length; same && i < l; i++ ) {
13545 same = same && this.items[ i ] === oldItems[ i ];
13546 }
13547 }
13548 if ( !same ) {
13549 this.emit( 'change', this.getItemsData() );
13550 }
13551
13552 return this;
13553 };
13554
13555 /**
13556 * @inheritdoc
13557 */
13558 OO.ui.CapsuleMultiSelectWidget.prototype.removeItems = function ( items ) {
13559 var same, i, l,
13560 oldItems = this.items.slice();
13561
13562 OO.ui.mixin.GroupElement.prototype.removeItems.call( this, items );
13563
13564 if ( this.items.length !== oldItems.length ) {
13565 same = false;
13566 } else {
13567 same = true;
13568 for ( i = 0, l = oldItems.length; same && i < l; i++ ) {
13569 same = same && this.items[ i ] === oldItems[ i ];
13570 }
13571 }
13572 if ( !same ) {
13573 this.emit( 'change', this.getItemsData() );
13574 }
13575
13576 return this;
13577 };
13578
13579 /**
13580 * @inheritdoc
13581 */
13582 OO.ui.CapsuleMultiSelectWidget.prototype.clearItems = function () {
13583 if ( this.items.length ) {
13584 OO.ui.mixin.GroupElement.prototype.clearItems.call( this );
13585 this.emit( 'change', this.getItemsData() );
13586 }
13587 return this;
13588 };
13589
13590 /**
13591 * Get the capsule widget's menu.
13592 * @return {OO.ui.MenuSelectWidget} Menu widget
13593 */
13594 OO.ui.CapsuleMultiSelectWidget.prototype.getMenu = function () {
13595 return this.menu;
13596 };
13597
13598 /**
13599 * Handle focus events
13600 *
13601 * @private
13602 * @param {jQuery.Event} event
13603 */
13604 OO.ui.CapsuleMultiSelectWidget.prototype.onInputFocus = function () {
13605 if ( !this.isDisabled() ) {
13606 this.menu.toggle( true );
13607 }
13608 };
13609
13610 /**
13611 * Handle blur events
13612 *
13613 * @private
13614 * @param {jQuery.Event} event
13615 */
13616 OO.ui.CapsuleMultiSelectWidget.prototype.onInputBlur = function () {
13617 if ( this.allowArbitrary && this.$input.val().trim() !== '' ) {
13618 this.addItemsFromData( [ this.$input.val() ] );
13619 }
13620 this.clearInput();
13621 };
13622
13623 /**
13624 * Handle focus events
13625 *
13626 * @private
13627 * @param {jQuery.Event} event
13628 */
13629 OO.ui.CapsuleMultiSelectWidget.prototype.onFocusForPopup = function () {
13630 if ( !this.isDisabled() ) {
13631 this.popup.setSize( this.$handle.width() );
13632 this.popup.toggle( true );
13633 this.popup.$element.find( '*' )
13634 .filter( function () { return OO.ui.isFocusableElement( $( this ), true ); } )
13635 .first()
13636 .focus();
13637 }
13638 };
13639
13640 /**
13641 * Handles popup focus out events.
13642 *
13643 * @private
13644 * @param {Event} e Focus out event
13645 */
13646 OO.ui.CapsuleMultiSelectWidget.prototype.onPopupFocusOut = function () {
13647 var widget = this.popup;
13648
13649 setTimeout( function () {
13650 if (
13651 widget.isVisible() &&
13652 !OO.ui.contains( widget.$element[ 0 ], document.activeElement, true ) &&
13653 ( !widget.$autoCloseIgnore || !widget.$autoCloseIgnore.has( document.activeElement ).length )
13654 ) {
13655 widget.toggle( false );
13656 }
13657 } );
13658 };
13659
13660 /**
13661 * Handle mouse click events.
13662 *
13663 * @private
13664 * @param {jQuery.Event} e Mouse click event
13665 */
13666 OO.ui.CapsuleMultiSelectWidget.prototype.onClick = function ( e ) {
13667 if ( e.which === 1 ) {
13668 this.focus();
13669 return false;
13670 }
13671 };
13672
13673 /**
13674 * Handle key press events.
13675 *
13676 * @private
13677 * @param {jQuery.Event} e Key press event
13678 */
13679 OO.ui.CapsuleMultiSelectWidget.prototype.onKeyPress = function ( e ) {
13680 var item;
13681
13682 if ( !this.isDisabled() ) {
13683 if ( e.which === OO.ui.Keys.ESCAPE ) {
13684 this.clearInput();
13685 return false;
13686 }
13687
13688 if ( !this.popup ) {
13689 this.menu.toggle( true );
13690 if ( e.which === OO.ui.Keys.ENTER ) {
13691 item = this.menu.getItemFromLabel( this.$input.val(), true );
13692 if ( item ) {
13693 this.addItemsFromData( [ item.data ] );
13694 this.clearInput();
13695 } else if ( this.allowArbitrary && this.$input.val().trim() !== '' ) {
13696 this.addItemsFromData( [ this.$input.val() ] );
13697 this.clearInput();
13698 }
13699 return false;
13700 }
13701
13702 // Make sure the input gets resized.
13703 setTimeout( this.onInputChange.bind( this ), 0 );
13704 }
13705 }
13706 };
13707
13708 /**
13709 * Handle key down events.
13710 *
13711 * @private
13712 * @param {jQuery.Event} e Key down event
13713 */
13714 OO.ui.CapsuleMultiSelectWidget.prototype.onKeyDown = function ( e ) {
13715 if ( !this.isDisabled() ) {
13716 // 'keypress' event is not triggered for Backspace
13717 if ( e.keyCode === OO.ui.Keys.BACKSPACE && this.$input.val() === '' ) {
13718 if ( this.items.length ) {
13719 this.removeItems( this.items.slice( -1 ) );
13720 }
13721 return false;
13722 }
13723 }
13724 };
13725
13726 /**
13727 * Handle input change events.
13728 *
13729 * @private
13730 * @param {jQuery.Event} e Event of some sort
13731 */
13732 OO.ui.CapsuleMultiSelectWidget.prototype.onInputChange = function () {
13733 if ( !this.isDisabled() ) {
13734 this.$input.width( this.$input.val().length + 'em' );
13735 }
13736 };
13737
13738 /**
13739 * Handle menu choose events.
13740 *
13741 * @private
13742 * @param {OO.ui.OptionWidget} item Chosen item
13743 */
13744 OO.ui.CapsuleMultiSelectWidget.prototype.onMenuChoose = function ( item ) {
13745 if ( item && item.isVisible() ) {
13746 this.addItemsFromData( [ item.getData() ] );
13747 this.clearInput();
13748 }
13749 };
13750
13751 /**
13752 * Handle menu item change events.
13753 *
13754 * @private
13755 */
13756 OO.ui.CapsuleMultiSelectWidget.prototype.onMenuItemsChange = function () {
13757 this.setItemsFromData( this.getItemsData() );
13758 this.$element.toggleClass( 'oo-ui-capsuleMultiSelectWidget-empty', this.menu.isEmpty() );
13759 };
13760
13761 /**
13762 * Clear the input field
13763 * @private
13764 */
13765 OO.ui.CapsuleMultiSelectWidget.prototype.clearInput = function () {
13766 if ( this.$input ) {
13767 this.$input.val( '' );
13768 this.$input.width( '1em' );
13769 }
13770 if ( this.popup ) {
13771 this.popup.toggle( false );
13772 }
13773 this.menu.toggle( false );
13774 this.menu.selectItem();
13775 this.menu.highlightItem();
13776 };
13777
13778 /**
13779 * @inheritdoc
13780 */
13781 OO.ui.CapsuleMultiSelectWidget.prototype.setDisabled = function ( disabled ) {
13782 var i, len;
13783
13784 // Parent method
13785 OO.ui.CapsuleMultiSelectWidget.parent.prototype.setDisabled.call( this, disabled );
13786
13787 if ( this.$input ) {
13788 this.$input.prop( 'disabled', this.isDisabled() );
13789 }
13790 if ( this.menu ) {
13791 this.menu.setDisabled( this.isDisabled() );
13792 }
13793 if ( this.popup ) {
13794 this.popup.setDisabled( this.isDisabled() );
13795 }
13796
13797 if ( this.items ) {
13798 for ( i = 0, len = this.items.length; i < len; i++ ) {
13799 this.items[ i ].updateDisabled();
13800 }
13801 }
13802
13803 return this;
13804 };
13805
13806 /**
13807 * Focus the widget
13808 * @chainable
13809 * @return {OO.ui.CapsuleMultiSelectWidget}
13810 */
13811 OO.ui.CapsuleMultiSelectWidget.prototype.focus = function () {
13812 if ( !this.isDisabled() ) {
13813 if ( this.popup ) {
13814 this.popup.setSize( this.$handle.width() );
13815 this.popup.toggle( true );
13816 this.popup.$element.find( '*' )
13817 .filter( function () { return OO.ui.isFocusableElement( $( this ), true ); } )
13818 .first()
13819 .focus();
13820 } else {
13821 this.menu.toggle( true );
13822 this.$input.focus();
13823 }
13824 }
13825 return this;
13826 };
13827
13828 /**
13829 * CapsuleItemWidgets are used within a {@link OO.ui.CapsuleMultiSelectWidget
13830 * CapsuleMultiSelectWidget} to display the selected items.
13831 *
13832 * @class
13833 * @extends OO.ui.Widget
13834 * @mixins OO.ui.mixin.ItemWidget
13835 * @mixins OO.ui.mixin.IndicatorElement
13836 * @mixins OO.ui.mixin.LabelElement
13837 * @mixins OO.ui.mixin.FlaggedElement
13838 * @mixins OO.ui.mixin.TabIndexedElement
13839 *
13840 * @constructor
13841 * @param {Object} [config] Configuration options
13842 */
13843 OO.ui.CapsuleItemWidget = function OoUiCapsuleItemWidget( config ) {
13844 // Configuration initialization
13845 config = config || {};
13846
13847 // Parent constructor
13848 OO.ui.CapsuleItemWidget.parent.call( this, config );
13849
13850 // Properties (must be set before mixin constructor calls)
13851 this.$indicator = $( '<span>' );
13852
13853 // Mixin constructors
13854 OO.ui.mixin.ItemWidget.call( this );
13855 OO.ui.mixin.IndicatorElement.call( this, $.extend( {}, config, { $indicator: this.$indicator, indicator: 'clear' } ) );
13856 OO.ui.mixin.LabelElement.call( this, config );
13857 OO.ui.mixin.FlaggedElement.call( this, config );
13858 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$indicator } ) );
13859
13860 // Events
13861 this.$indicator.on( {
13862 keydown: this.onCloseKeyDown.bind( this ),
13863 click: this.onCloseClick.bind( this )
13864 } );
13865
13866 // Initialization
13867 this.$element
13868 .addClass( 'oo-ui-capsuleItemWidget' )
13869 .append( this.$indicator, this.$label );
13870 };
13871
13872 /* Setup */
13873
13874 OO.inheritClass( OO.ui.CapsuleItemWidget, OO.ui.Widget );
13875 OO.mixinClass( OO.ui.CapsuleItemWidget, OO.ui.mixin.ItemWidget );
13876 OO.mixinClass( OO.ui.CapsuleItemWidget, OO.ui.mixin.IndicatorElement );
13877 OO.mixinClass( OO.ui.CapsuleItemWidget, OO.ui.mixin.LabelElement );
13878 OO.mixinClass( OO.ui.CapsuleItemWidget, OO.ui.mixin.FlaggedElement );
13879 OO.mixinClass( OO.ui.CapsuleItemWidget, OO.ui.mixin.TabIndexedElement );
13880
13881 /* Methods */
13882
13883 /**
13884 * Handle close icon clicks
13885 * @param {jQuery.Event} event
13886 */
13887 OO.ui.CapsuleItemWidget.prototype.onCloseClick = function () {
13888 var element = this.getElementGroup();
13889
13890 if ( !this.isDisabled() && element && $.isFunction( element.removeItems ) ) {
13891 element.removeItems( [ this ] );
13892 element.focus();
13893 }
13894 };
13895
13896 /**
13897 * Handle close keyboard events
13898 * @param {jQuery.Event} event Key down event
13899 */
13900 OO.ui.CapsuleItemWidget.prototype.onCloseKeyDown = function ( e ) {
13901 if ( !this.isDisabled() && $.isFunction( this.getElementGroup().removeItems ) ) {
13902 switch ( e.which ) {
13903 case OO.ui.Keys.ENTER:
13904 case OO.ui.Keys.BACKSPACE:
13905 case OO.ui.Keys.SPACE:
13906 this.getElementGroup().removeItems( [ this ] );
13907 return false;
13908 }
13909 }
13910 };
13911
13912 /**
13913 * DropdownWidgets are not menus themselves, rather they contain a menu of options created with
13914 * OO.ui.MenuOptionWidget. The DropdownWidget takes care of opening and displaying the menu so that
13915 * users can interact with it.
13916 *
13917 * If you want to use this within a HTML form, such as a OO.ui.FormLayout, use
13918 * OO.ui.DropdownInputWidget instead.
13919 *
13920 * @example
13921 * // Example: A DropdownWidget with a menu that contains three options
13922 * var dropDown = new OO.ui.DropdownWidget( {
13923 * label: 'Dropdown menu: Select a menu option',
13924 * menu: {
13925 * items: [
13926 * new OO.ui.MenuOptionWidget( {
13927 * data: 'a',
13928 * label: 'First'
13929 * } ),
13930 * new OO.ui.MenuOptionWidget( {
13931 * data: 'b',
13932 * label: 'Second'
13933 * } ),
13934 * new OO.ui.MenuOptionWidget( {
13935 * data: 'c',
13936 * label: 'Third'
13937 * } )
13938 * ]
13939 * }
13940 * } );
13941 *
13942 * $( 'body' ).append( dropDown.$element );
13943 *
13944 * dropDown.getMenu().selectItemByData( 'b' );
13945 *
13946 * dropDown.getMenu().getSelectedItem().getData(); // returns 'b'
13947 *
13948 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
13949 *
13950 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
13951 *
13952 * @class
13953 * @extends OO.ui.Widget
13954 * @mixins OO.ui.mixin.IconElement
13955 * @mixins OO.ui.mixin.IndicatorElement
13956 * @mixins OO.ui.mixin.LabelElement
13957 * @mixins OO.ui.mixin.TitledElement
13958 * @mixins OO.ui.mixin.TabIndexedElement
13959 *
13960 * @constructor
13961 * @param {Object} [config] Configuration options
13962 * @cfg {Object} [menu] Configuration options to pass to {@link OO.ui.FloatingMenuSelectWidget menu select widget}
13963 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
13964 * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
13965 * containing `<div>` and has a larger area. By default, the menu uses relative positioning.
13966 */
13967 OO.ui.DropdownWidget = function OoUiDropdownWidget( config ) {
13968 // Configuration initialization
13969 config = $.extend( { indicator: 'down' }, config );
13970
13971 // Parent constructor
13972 OO.ui.DropdownWidget.parent.call( this, config );
13973
13974 // Properties (must be set before TabIndexedElement constructor call)
13975 this.$handle = this.$( '<span>' );
13976 this.$overlay = config.$overlay || this.$element;
13977
13978 // Mixin constructors
13979 OO.ui.mixin.IconElement.call( this, config );
13980 OO.ui.mixin.IndicatorElement.call( this, config );
13981 OO.ui.mixin.LabelElement.call( this, config );
13982 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$label } ) );
13983 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$handle } ) );
13984
13985 // Properties
13986 this.menu = new OO.ui.FloatingMenuSelectWidget( $.extend( {
13987 widget: this,
13988 $container: this.$element
13989 }, config.menu ) );
13990
13991 // Events
13992 this.$handle.on( {
13993 click: this.onClick.bind( this ),
13994 keypress: this.onKeyPress.bind( this )
13995 } );
13996 this.menu.connect( this, { select: 'onMenuSelect' } );
13997
13998 // Initialization
13999 this.$handle
14000 .addClass( 'oo-ui-dropdownWidget-handle' )
14001 .append( this.$icon, this.$label, this.$indicator );
14002 this.$element
14003 .addClass( 'oo-ui-dropdownWidget' )
14004 .append( this.$handle );
14005 this.$overlay.append( this.menu.$element );
14006 };
14007
14008 /* Setup */
14009
14010 OO.inheritClass( OO.ui.DropdownWidget, OO.ui.Widget );
14011 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.IconElement );
14012 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.IndicatorElement );
14013 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.LabelElement );
14014 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.TitledElement );
14015 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.TabIndexedElement );
14016
14017 /* Methods */
14018
14019 /**
14020 * Get the menu.
14021 *
14022 * @return {OO.ui.MenuSelectWidget} Menu of widget
14023 */
14024 OO.ui.DropdownWidget.prototype.getMenu = function () {
14025 return this.menu;
14026 };
14027
14028 /**
14029 * Handles menu select events.
14030 *
14031 * @private
14032 * @param {OO.ui.MenuOptionWidget} item Selected menu item
14033 */
14034 OO.ui.DropdownWidget.prototype.onMenuSelect = function ( item ) {
14035 var selectedLabel;
14036
14037 if ( !item ) {
14038 this.setLabel( null );
14039 return;
14040 }
14041
14042 selectedLabel = item.getLabel();
14043
14044 // If the label is a DOM element, clone it, because setLabel will append() it
14045 if ( selectedLabel instanceof jQuery ) {
14046 selectedLabel = selectedLabel.clone();
14047 }
14048
14049 this.setLabel( selectedLabel );
14050 };
14051
14052 /**
14053 * Handle mouse click events.
14054 *
14055 * @private
14056 * @param {jQuery.Event} e Mouse click event
14057 */
14058 OO.ui.DropdownWidget.prototype.onClick = function ( e ) {
14059 if ( !this.isDisabled() && e.which === 1 ) {
14060 this.menu.toggle();
14061 }
14062 return false;
14063 };
14064
14065 /**
14066 * Handle key press events.
14067 *
14068 * @private
14069 * @param {jQuery.Event} e Key press event
14070 */
14071 OO.ui.DropdownWidget.prototype.onKeyPress = function ( e ) {
14072 if ( !this.isDisabled() &&
14073 ( ( e.which === OO.ui.Keys.SPACE && !this.menu.isVisible() ) || e.which === OO.ui.Keys.ENTER )
14074 ) {
14075 this.menu.toggle();
14076 return false;
14077 }
14078 };
14079
14080 /**
14081 * SelectFileWidgets allow for selecting files, using the HTML5 File API. These
14082 * widgets can be configured with {@link OO.ui.mixin.IconElement icons} and {@link
14083 * OO.ui.mixin.IndicatorElement indicators}.
14084 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
14085 *
14086 * @example
14087 * // Example of a file select widget
14088 * var selectFile = new OO.ui.SelectFileWidget();
14089 * $( 'body' ).append( selectFile.$element );
14090 *
14091 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets
14092 *
14093 * @class
14094 * @extends OO.ui.Widget
14095 * @mixins OO.ui.mixin.IconElement
14096 * @mixins OO.ui.mixin.IndicatorElement
14097 * @mixins OO.ui.mixin.PendingElement
14098 * @mixins OO.ui.mixin.LabelElement
14099 *
14100 * @constructor
14101 * @param {Object} [config] Configuration options
14102 * @cfg {string[]|null} [accept=null] MIME types to accept. null accepts all types.
14103 * @cfg {string} [placeholder] Text to display when no file is selected.
14104 * @cfg {string} [notsupported] Text to display when file support is missing in the browser.
14105 * @cfg {boolean} [droppable=true] Whether to accept files by drag and drop.
14106 * @cfg {boolean} [showDropTarget=false] Whether to show a drop target. Requires droppable to be true.
14107 * @cfg {boolean} [dragDropUI=false] Deprecated alias for showDropTarget
14108 */
14109 OO.ui.SelectFileWidget = function OoUiSelectFileWidget( config ) {
14110 var dragHandler;
14111
14112 // TODO: Remove in next release
14113 if ( config && config.dragDropUI ) {
14114 config.showDropTarget = true;
14115 }
14116
14117 // Configuration initialization
14118 config = $.extend( {
14119 accept: null,
14120 placeholder: OO.ui.msg( 'ooui-selectfile-placeholder' ),
14121 notsupported: OO.ui.msg( 'ooui-selectfile-not-supported' ),
14122 droppable: true,
14123 showDropTarget: false
14124 }, config );
14125
14126 // Parent constructor
14127 OO.ui.SelectFileWidget.parent.call( this, config );
14128
14129 // Mixin constructors
14130 OO.ui.mixin.IconElement.call( this, config );
14131 OO.ui.mixin.IndicatorElement.call( this, config );
14132 OO.ui.mixin.PendingElement.call( this, $.extend( {}, config, { $pending: this.$info } ) );
14133 OO.ui.mixin.LabelElement.call( this, $.extend( {}, config, { autoFitLabel: true } ) );
14134
14135 // Properties
14136 this.$info = $( '<span>' );
14137
14138 // Properties
14139 this.showDropTarget = config.showDropTarget;
14140 this.isSupported = this.constructor.static.isSupported();
14141 this.currentFile = null;
14142 if ( Array.isArray( config.accept ) ) {
14143 this.accept = config.accept;
14144 } else {
14145 this.accept = null;
14146 }
14147 this.placeholder = config.placeholder;
14148 this.notsupported = config.notsupported;
14149 this.onFileSelectedHandler = this.onFileSelected.bind( this );
14150
14151 this.selectButton = new OO.ui.ButtonWidget( {
14152 classes: [ 'oo-ui-selectFileWidget-selectButton' ],
14153 label: 'Select a file',
14154 disabled: this.disabled || !this.isSupported
14155 } );
14156
14157 this.clearButton = new OO.ui.ButtonWidget( {
14158 classes: [ 'oo-ui-selectFileWidget-clearButton' ],
14159 framed: false,
14160 icon: 'remove',
14161 disabled: this.disabled
14162 } );
14163
14164 // Events
14165 this.selectButton.$button.on( {
14166 keypress: this.onKeyPress.bind( this )
14167 } );
14168 this.clearButton.connect( this, {
14169 click: 'onClearClick'
14170 } );
14171 if ( config.droppable ) {
14172 dragHandler = this.onDragEnterOrOver.bind( this );
14173 this.$element.on( {
14174 dragenter: dragHandler,
14175 dragover: dragHandler,
14176 dragleave: this.onDragLeave.bind( this ),
14177 drop: this.onDrop.bind( this )
14178 } );
14179 }
14180
14181 // Initialization
14182 this.addInput();
14183 this.updateUI();
14184 this.$label.addClass( 'oo-ui-selectFileWidget-label' );
14185 this.$info
14186 .addClass( 'oo-ui-selectFileWidget-info' )
14187 .append( this.$icon, this.$label, this.clearButton.$element, this.$indicator );
14188 this.$element
14189 .addClass( 'oo-ui-selectFileWidget' )
14190 .append( this.$info, this.selectButton.$element );
14191 if ( config.droppable && config.showDropTarget ) {
14192 this.$dropTarget = $( '<div>' )
14193 .addClass( 'oo-ui-selectFileWidget-dropTarget' )
14194 .text( OO.ui.msg( 'ooui-selectfile-dragdrop-placeholder' ) )
14195 .on( {
14196 click: this.onDropTargetClick.bind( this )
14197 } );
14198 this.$element.prepend( this.$dropTarget );
14199 }
14200 };
14201
14202 /* Setup */
14203
14204 OO.inheritClass( OO.ui.SelectFileWidget, OO.ui.Widget );
14205 OO.mixinClass( OO.ui.SelectFileWidget, OO.ui.mixin.IconElement );
14206 OO.mixinClass( OO.ui.SelectFileWidget, OO.ui.mixin.IndicatorElement );
14207 OO.mixinClass( OO.ui.SelectFileWidget, OO.ui.mixin.PendingElement );
14208 OO.mixinClass( OO.ui.SelectFileWidget, OO.ui.mixin.LabelElement );
14209
14210 /* Static Properties */
14211
14212 /**
14213 * Check if this widget is supported
14214 *
14215 * @static
14216 * @return {boolean}
14217 */
14218 OO.ui.SelectFileWidget.static.isSupported = function () {
14219 var $input;
14220 if ( OO.ui.SelectFileWidget.static.isSupportedCache === null ) {
14221 $input = $( '<input type="file">' );
14222 OO.ui.SelectFileWidget.static.isSupportedCache = $input[ 0 ].files !== undefined;
14223 }
14224 return OO.ui.SelectFileWidget.static.isSupportedCache;
14225 };
14226
14227 OO.ui.SelectFileWidget.static.isSupportedCache = null;
14228
14229 /* Events */
14230
14231 /**
14232 * @event change
14233 *
14234 * A change event is emitted when the on/off state of the toggle changes.
14235 *
14236 * @param {File|null} value New value
14237 */
14238
14239 /* Methods */
14240
14241 /**
14242 * Get the current value of the field
14243 *
14244 * @return {File|null}
14245 */
14246 OO.ui.SelectFileWidget.prototype.getValue = function () {
14247 return this.currentFile;
14248 };
14249
14250 /**
14251 * Set the current value of the field
14252 *
14253 * @param {File|null} file File to select
14254 */
14255 OO.ui.SelectFileWidget.prototype.setValue = function ( file ) {
14256 if ( this.currentFile !== file ) {
14257 this.currentFile = file;
14258 this.updateUI();
14259 this.emit( 'change', this.currentFile );
14260 }
14261 };
14262
14263 /**
14264 * Focus the widget.
14265 *
14266 * Focusses the select file button.
14267 *
14268 * @chainable
14269 */
14270 OO.ui.SelectFileWidget.prototype.focus = function () {
14271 this.selectButton.$button[ 0 ].focus();
14272 return this;
14273 };
14274
14275 /**
14276 * Update the user interface when a file is selected or unselected
14277 *
14278 * @protected
14279 */
14280 OO.ui.SelectFileWidget.prototype.updateUI = function () {
14281 var $label;
14282 if ( !this.isSupported ) {
14283 this.$element.addClass( 'oo-ui-selectFileWidget-notsupported' );
14284 this.$element.removeClass( 'oo-ui-selectFileWidget-empty' );
14285 this.setLabel( this.notsupported );
14286 } else {
14287 this.$element.addClass( 'oo-ui-selectFileWidget-supported' );
14288 if ( this.currentFile ) {
14289 this.$element.removeClass( 'oo-ui-selectFileWidget-empty' );
14290 $label = $( [] );
14291 if ( this.currentFile.type !== '' ) {
14292 $label = $label.add( $( '<span>' ).addClass( 'oo-ui-selectFileWidget-fileType' ).text( this.currentFile.type ) );
14293 }
14294 $label = $label.add( $( '<span>' ).text( this.currentFile.name ) );
14295 this.setLabel( $label );
14296 } else {
14297 this.$element.addClass( 'oo-ui-selectFileWidget-empty' );
14298 this.setLabel( this.placeholder );
14299 }
14300 }
14301
14302 if ( this.$input ) {
14303 this.$input.attr( 'title', this.getLabel() );
14304 }
14305 };
14306
14307 /**
14308 * Add the input to the widget
14309 *
14310 * @private
14311 */
14312 OO.ui.SelectFileWidget.prototype.addInput = function () {
14313 if ( this.$input ) {
14314 this.$input.remove();
14315 }
14316
14317 if ( !this.isSupported ) {
14318 this.$input = null;
14319 return;
14320 }
14321
14322 this.$input = $( '<input type="file">' );
14323 this.$input.on( 'change', this.onFileSelectedHandler );
14324 this.$input.attr( {
14325 tabindex: -1,
14326 title: this.getLabel()
14327 } );
14328 if ( this.accept ) {
14329 this.$input.attr( 'accept', this.accept.join( ', ' ) );
14330 }
14331 this.selectButton.$button.append( this.$input );
14332 };
14333
14334 /**
14335 * Determine if we should accept this file
14336 *
14337 * @private
14338 * @param {string} File MIME type
14339 * @return {boolean}
14340 */
14341 OO.ui.SelectFileWidget.prototype.isAllowedType = function ( mimeType ) {
14342 var i, mimeTest;
14343
14344 if ( !this.accept || !mimeType ) {
14345 return true;
14346 }
14347
14348 for ( i = 0; i < this.accept.length; i++ ) {
14349 mimeTest = this.accept[ i ];
14350 if ( mimeTest === mimeType ) {
14351 return true;
14352 } else if ( mimeTest.substr( -2 ) === '/*' ) {
14353 mimeTest = mimeTest.substr( 0, mimeTest.length - 1 );
14354 if ( mimeType.substr( 0, mimeTest.length ) === mimeTest ) {
14355 return true;
14356 }
14357 }
14358 }
14359
14360 return false;
14361 };
14362
14363 /**
14364 * Handle file selection from the input
14365 *
14366 * @private
14367 * @param {jQuery.Event} e
14368 */
14369 OO.ui.SelectFileWidget.prototype.onFileSelected = function ( e ) {
14370 var file = OO.getProp( e.target, 'files', 0 ) || null;
14371
14372 if ( file && !this.isAllowedType( file.type ) ) {
14373 file = null;
14374 }
14375
14376 this.setValue( file );
14377 this.addInput();
14378 };
14379
14380 /**
14381 * Handle clear button click events.
14382 *
14383 * @private
14384 */
14385 OO.ui.SelectFileWidget.prototype.onClearClick = function () {
14386 this.setValue( null );
14387 return false;
14388 };
14389
14390 /**
14391 * Handle key press events.
14392 *
14393 * @private
14394 * @param {jQuery.Event} e Key press event
14395 */
14396 OO.ui.SelectFileWidget.prototype.onKeyPress = function ( e ) {
14397 if ( this.isSupported && !this.isDisabled() && this.$input &&
14398 ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
14399 ) {
14400 this.$input.click();
14401 return false;
14402 }
14403 };
14404
14405 /**
14406 * Handle drop target click events.
14407 *
14408 * @private
14409 * @param {jQuery.Event} e Key press event
14410 */
14411 OO.ui.SelectFileWidget.prototype.onDropTargetClick = function () {
14412 if ( this.isSupported && !this.isDisabled() && this.$input ) {
14413 this.$input.click();
14414 return false;
14415 }
14416 };
14417
14418 /**
14419 * Handle drag enter and over events
14420 *
14421 * @private
14422 * @param {jQuery.Event} e Drag event
14423 */
14424 OO.ui.SelectFileWidget.prototype.onDragEnterOrOver = function ( e ) {
14425 var itemOrFile,
14426 droppableFile = false,
14427 dt = e.originalEvent.dataTransfer;
14428
14429 e.preventDefault();
14430 e.stopPropagation();
14431
14432 if ( this.isDisabled() || !this.isSupported ) {
14433 this.$element.removeClass( 'oo-ui-selectFileWidget-canDrop' );
14434 dt.dropEffect = 'none';
14435 return false;
14436 }
14437
14438 // DataTransferItem and File both have a type property, but in Chrome files
14439 // have no information at this point.
14440 itemOrFile = OO.getProp( dt, 'items', 0 ) || OO.getProp( dt, 'files', 0 );
14441 if ( itemOrFile ) {
14442 if ( this.isAllowedType( itemOrFile.type ) ) {
14443 droppableFile = true;
14444 }
14445 // dt.types is Array-like, but not an Array
14446 } else if ( Array.prototype.indexOf.call( OO.getProp( dt, 'types' ) || [], 'Files' ) !== -1 ) {
14447 // File information is not available at this point for security so just assume
14448 // it is acceptable for now.
14449 // https://bugzilla.mozilla.org/show_bug.cgi?id=640534
14450 droppableFile = true;
14451 }
14452
14453 this.$element.toggleClass( 'oo-ui-selectFileWidget-canDrop', droppableFile );
14454 if ( !droppableFile ) {
14455 dt.dropEffect = 'none';
14456 }
14457
14458 return false;
14459 };
14460
14461 /**
14462 * Handle drag leave events
14463 *
14464 * @private
14465 * @param {jQuery.Event} e Drag event
14466 */
14467 OO.ui.SelectFileWidget.prototype.onDragLeave = function () {
14468 this.$element.removeClass( 'oo-ui-selectFileWidget-canDrop' );
14469 };
14470
14471 /**
14472 * Handle drop events
14473 *
14474 * @private
14475 * @param {jQuery.Event} e Drop event
14476 */
14477 OO.ui.SelectFileWidget.prototype.onDrop = function ( e ) {
14478 var file = null,
14479 dt = e.originalEvent.dataTransfer;
14480
14481 e.preventDefault();
14482 e.stopPropagation();
14483 this.$element.removeClass( 'oo-ui-selectFileWidget-canDrop' );
14484
14485 if ( this.isDisabled() || !this.isSupported ) {
14486 return false;
14487 }
14488
14489 file = OO.getProp( dt, 'files', 0 );
14490 if ( file && !this.isAllowedType( file.type ) ) {
14491 file = null;
14492 }
14493 if ( file ) {
14494 this.setValue( file );
14495 }
14496
14497 return false;
14498 };
14499
14500 /**
14501 * @inheritdoc
14502 */
14503 OO.ui.SelectFileWidget.prototype.setDisabled = function ( disabled ) {
14504 OO.ui.SelectFileWidget.parent.prototype.setDisabled.call( this, disabled );
14505 if ( this.selectButton ) {
14506 this.selectButton.setDisabled( disabled );
14507 }
14508 if ( this.clearButton ) {
14509 this.clearButton.setDisabled( disabled );
14510 }
14511 return this;
14512 };
14513
14514 /**
14515 * IconWidget is a generic widget for {@link OO.ui.mixin.IconElement icons}. In general, IconWidgets should be used with OO.ui.LabelWidget,
14516 * which creates a label that identifies the icon’s function. See the [OOjs UI documentation on MediaWiki] [1]
14517 * for a list of icons included in the library.
14518 *
14519 * @example
14520 * // An icon widget with a label
14521 * var myIcon = new OO.ui.IconWidget( {
14522 * icon: 'help',
14523 * iconTitle: 'Help'
14524 * } );
14525 * // Create a label.
14526 * var iconLabel = new OO.ui.LabelWidget( {
14527 * label: 'Help'
14528 * } );
14529 * $( 'body' ).append( myIcon.$element, iconLabel.$element );
14530 *
14531 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
14532 *
14533 * @class
14534 * @extends OO.ui.Widget
14535 * @mixins OO.ui.mixin.IconElement
14536 * @mixins OO.ui.mixin.TitledElement
14537 * @mixins OO.ui.mixin.FlaggedElement
14538 *
14539 * @constructor
14540 * @param {Object} [config] Configuration options
14541 */
14542 OO.ui.IconWidget = function OoUiIconWidget( config ) {
14543 // Configuration initialization
14544 config = config || {};
14545
14546 // Parent constructor
14547 OO.ui.IconWidget.parent.call( this, config );
14548
14549 // Mixin constructors
14550 OO.ui.mixin.IconElement.call( this, $.extend( {}, config, { $icon: this.$element } ) );
14551 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$element } ) );
14552 OO.ui.mixin.FlaggedElement.call( this, $.extend( {}, config, { $flagged: this.$element } ) );
14553
14554 // Initialization
14555 this.$element.addClass( 'oo-ui-iconWidget' );
14556 };
14557
14558 /* Setup */
14559
14560 OO.inheritClass( OO.ui.IconWidget, OO.ui.Widget );
14561 OO.mixinClass( OO.ui.IconWidget, OO.ui.mixin.IconElement );
14562 OO.mixinClass( OO.ui.IconWidget, OO.ui.mixin.TitledElement );
14563 OO.mixinClass( OO.ui.IconWidget, OO.ui.mixin.FlaggedElement );
14564
14565 /* Static Properties */
14566
14567 OO.ui.IconWidget.static.tagName = 'span';
14568
14569 /**
14570 * IndicatorWidgets create indicators, which are small graphics that are generally used to draw
14571 * attention to the status of an item or to clarify the function of a control. For a list of
14572 * indicators included in the library, please see the [OOjs UI documentation on MediaWiki][1].
14573 *
14574 * @example
14575 * // Example of an indicator widget
14576 * var indicator1 = new OO.ui.IndicatorWidget( {
14577 * indicator: 'alert'
14578 * } );
14579 *
14580 * // Create a fieldset layout to add a label
14581 * var fieldset = new OO.ui.FieldsetLayout();
14582 * fieldset.addItems( [
14583 * new OO.ui.FieldLayout( indicator1, { label: 'An alert indicator:' } )
14584 * ] );
14585 * $( 'body' ).append( fieldset.$element );
14586 *
14587 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
14588 *
14589 * @class
14590 * @extends OO.ui.Widget
14591 * @mixins OO.ui.mixin.IndicatorElement
14592 * @mixins OO.ui.mixin.TitledElement
14593 *
14594 * @constructor
14595 * @param {Object} [config] Configuration options
14596 */
14597 OO.ui.IndicatorWidget = function OoUiIndicatorWidget( config ) {
14598 // Configuration initialization
14599 config = config || {};
14600
14601 // Parent constructor
14602 OO.ui.IndicatorWidget.parent.call( this, config );
14603
14604 // Mixin constructors
14605 OO.ui.mixin.IndicatorElement.call( this, $.extend( {}, config, { $indicator: this.$element } ) );
14606 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$element } ) );
14607
14608 // Initialization
14609 this.$element.addClass( 'oo-ui-indicatorWidget' );
14610 };
14611
14612 /* Setup */
14613
14614 OO.inheritClass( OO.ui.IndicatorWidget, OO.ui.Widget );
14615 OO.mixinClass( OO.ui.IndicatorWidget, OO.ui.mixin.IndicatorElement );
14616 OO.mixinClass( OO.ui.IndicatorWidget, OO.ui.mixin.TitledElement );
14617
14618 /* Static Properties */
14619
14620 OO.ui.IndicatorWidget.static.tagName = 'span';
14621
14622 /**
14623 * InputWidget is the base class for all input widgets, which
14624 * include {@link OO.ui.TextInputWidget text inputs}, {@link OO.ui.CheckboxInputWidget checkbox inputs},
14625 * {@link OO.ui.RadioInputWidget radio inputs}, and {@link OO.ui.ButtonInputWidget button inputs}.
14626 * See the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
14627 *
14628 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
14629 *
14630 * @abstract
14631 * @class
14632 * @extends OO.ui.Widget
14633 * @mixins OO.ui.mixin.FlaggedElement
14634 * @mixins OO.ui.mixin.TabIndexedElement
14635 * @mixins OO.ui.mixin.TitledElement
14636 * @mixins OO.ui.mixin.AccessKeyedElement
14637 *
14638 * @constructor
14639 * @param {Object} [config] Configuration options
14640 * @cfg {string} [name=''] The value of the input’s HTML `name` attribute.
14641 * @cfg {string} [value=''] The value of the input.
14642 * @cfg {string} [dir] The directionality of the input (ltr/rtl).
14643 * @cfg {Function} [inputFilter] The name of an input filter function. Input filters modify the value of an input
14644 * before it is accepted.
14645 */
14646 OO.ui.InputWidget = function OoUiInputWidget( config ) {
14647 // Configuration initialization
14648 config = config || {};
14649
14650 // Parent constructor
14651 OO.ui.InputWidget.parent.call( this, config );
14652
14653 // Properties
14654 this.$input = this.getInputElement( config );
14655 this.value = '';
14656 this.inputFilter = config.inputFilter;
14657
14658 // Mixin constructors
14659 OO.ui.mixin.FlaggedElement.call( this, config );
14660 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$input } ) );
14661 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$input } ) );
14662 OO.ui.mixin.AccessKeyedElement.call( this, $.extend( {}, config, { $accessKeyed: this.$input } ) );
14663
14664 // Events
14665 this.$input.on( 'keydown mouseup cut paste change input select', this.onEdit.bind( this ) );
14666
14667 // Initialization
14668 this.$input
14669 .addClass( 'oo-ui-inputWidget-input' )
14670 .attr( 'name', config.name )
14671 .prop( 'disabled', this.isDisabled() );
14672 this.$element
14673 .addClass( 'oo-ui-inputWidget' )
14674 .append( this.$input );
14675 this.setValue( config.value );
14676 this.setAccessKey( config.accessKey );
14677 if ( config.dir ) {
14678 this.setDir( config.dir );
14679 }
14680 };
14681
14682 /* Setup */
14683
14684 OO.inheritClass( OO.ui.InputWidget, OO.ui.Widget );
14685 OO.mixinClass( OO.ui.InputWidget, OO.ui.mixin.FlaggedElement );
14686 OO.mixinClass( OO.ui.InputWidget, OO.ui.mixin.TabIndexedElement );
14687 OO.mixinClass( OO.ui.InputWidget, OO.ui.mixin.TitledElement );
14688 OO.mixinClass( OO.ui.InputWidget, OO.ui.mixin.AccessKeyedElement );
14689
14690 /* Static Properties */
14691
14692 OO.ui.InputWidget.static.supportsSimpleLabel = true;
14693
14694 /* Static Methods */
14695
14696 /**
14697 * @inheritdoc
14698 */
14699 OO.ui.InputWidget.static.reusePreInfuseDOM = function ( node, config ) {
14700 config = OO.ui.InputWidget.parent.static.reusePreInfuseDOM( node, config );
14701 // Reusing $input lets browsers preserve inputted values across page reloads (T114134)
14702 config.$input = $( node ).find( '.oo-ui-inputWidget-input' );
14703 return config;
14704 };
14705
14706 /**
14707 * @inheritdoc
14708 */
14709 OO.ui.InputWidget.static.gatherPreInfuseState = function ( node, config ) {
14710 var state = OO.ui.InputWidget.parent.static.gatherPreInfuseState( node, config );
14711 state.value = config.$input.val();
14712 // Might be better in TabIndexedElement, but it's awkward to do there because mixins are awkward
14713 state.focus = config.$input.is( ':focus' );
14714 return state;
14715 };
14716
14717 /* Events */
14718
14719 /**
14720 * @event change
14721 *
14722 * A change event is emitted when the value of the input changes.
14723 *
14724 * @param {string} value
14725 */
14726
14727 /* Methods */
14728
14729 /**
14730 * Get input element.
14731 *
14732 * Subclasses of OO.ui.InputWidget use the `config` parameter to produce different elements in
14733 * different circumstances. The element must have a `value` property (like form elements).
14734 *
14735 * @protected
14736 * @param {Object} config Configuration options
14737 * @return {jQuery} Input element
14738 */
14739 OO.ui.InputWidget.prototype.getInputElement = function ( config ) {
14740 // See #reusePreInfuseDOM about config.$input
14741 return config.$input || $( '<input>' );
14742 };
14743
14744 /**
14745 * Handle potentially value-changing events.
14746 *
14747 * @private
14748 * @param {jQuery.Event} e Key down, mouse up, cut, paste, change, input, or select event
14749 */
14750 OO.ui.InputWidget.prototype.onEdit = function () {
14751 var widget = this;
14752 if ( !this.isDisabled() ) {
14753 // Allow the stack to clear so the value will be updated
14754 setTimeout( function () {
14755 widget.setValue( widget.$input.val() );
14756 } );
14757 }
14758 };
14759
14760 /**
14761 * Get the value of the input.
14762 *
14763 * @return {string} Input value
14764 */
14765 OO.ui.InputWidget.prototype.getValue = function () {
14766 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
14767 // it, and we won't know unless they're kind enough to trigger a 'change' event.
14768 var value = this.$input.val();
14769 if ( this.value !== value ) {
14770 this.setValue( value );
14771 }
14772 return this.value;
14773 };
14774
14775 /**
14776 * Set the directionality of the input, either RTL (right-to-left) or LTR (left-to-right).
14777 *
14778 * @deprecated since v0.13.1, use #setDir directly
14779 * @param {boolean} isRTL Directionality is right-to-left
14780 * @chainable
14781 */
14782 OO.ui.InputWidget.prototype.setRTL = function ( isRTL ) {
14783 this.setDir( isRTL ? 'rtl' : 'ltr' );
14784 return this;
14785 };
14786
14787 /**
14788 * Set the directionality of the input.
14789 *
14790 * @param {string} dir Text directionality: 'ltr', 'rtl' or 'auto'
14791 * @chainable
14792 */
14793 OO.ui.InputWidget.prototype.setDir = function ( dir ) {
14794 this.$input.prop( 'dir', dir );
14795 return this;
14796 };
14797
14798 /**
14799 * Set the value of the input.
14800 *
14801 * @param {string} value New value
14802 * @fires change
14803 * @chainable
14804 */
14805 OO.ui.InputWidget.prototype.setValue = function ( value ) {
14806 value = this.cleanUpValue( value );
14807 // Update the DOM if it has changed. Note that with cleanUpValue, it
14808 // is possible for the DOM value to change without this.value changing.
14809 if ( this.$input.val() !== value ) {
14810 this.$input.val( value );
14811 }
14812 if ( this.value !== value ) {
14813 this.value = value;
14814 this.emit( 'change', this.value );
14815 }
14816 return this;
14817 };
14818
14819 /**
14820 * Set the input's access key.
14821 * FIXME: This is the same code as in OO.ui.mixin.ButtonElement, maybe find a better place for it?
14822 *
14823 * @param {string} accessKey Input's access key, use empty string to remove
14824 * @chainable
14825 */
14826 OO.ui.InputWidget.prototype.setAccessKey = function ( accessKey ) {
14827 accessKey = typeof accessKey === 'string' && accessKey.length ? accessKey : null;
14828
14829 if ( this.accessKey !== accessKey ) {
14830 if ( this.$input ) {
14831 if ( accessKey !== null ) {
14832 this.$input.attr( 'accesskey', accessKey );
14833 } else {
14834 this.$input.removeAttr( 'accesskey' );
14835 }
14836 }
14837 this.accessKey = accessKey;
14838 }
14839
14840 return this;
14841 };
14842
14843 /**
14844 * Clean up incoming value.
14845 *
14846 * Ensures value is a string, and converts undefined and null to empty string.
14847 *
14848 * @private
14849 * @param {string} value Original value
14850 * @return {string} Cleaned up value
14851 */
14852 OO.ui.InputWidget.prototype.cleanUpValue = function ( value ) {
14853 if ( value === undefined || value === null ) {
14854 return '';
14855 } else if ( this.inputFilter ) {
14856 return this.inputFilter( String( value ) );
14857 } else {
14858 return String( value );
14859 }
14860 };
14861
14862 /**
14863 * Simulate the behavior of clicking on a label bound to this input. This method is only called by
14864 * {@link OO.ui.LabelWidget LabelWidget} and {@link OO.ui.FieldLayout FieldLayout}. It should not be
14865 * called directly.
14866 */
14867 OO.ui.InputWidget.prototype.simulateLabelClick = function () {
14868 if ( !this.isDisabled() ) {
14869 if ( this.$input.is( ':checkbox, :radio' ) ) {
14870 this.$input.click();
14871 }
14872 if ( this.$input.is( ':input' ) ) {
14873 this.$input[ 0 ].focus();
14874 }
14875 }
14876 };
14877
14878 /**
14879 * @inheritdoc
14880 */
14881 OO.ui.InputWidget.prototype.setDisabled = function ( state ) {
14882 OO.ui.InputWidget.parent.prototype.setDisabled.call( this, state );
14883 if ( this.$input ) {
14884 this.$input.prop( 'disabled', this.isDisabled() );
14885 }
14886 return this;
14887 };
14888
14889 /**
14890 * Focus the input.
14891 *
14892 * @chainable
14893 */
14894 OO.ui.InputWidget.prototype.focus = function () {
14895 this.$input[ 0 ].focus();
14896 return this;
14897 };
14898
14899 /**
14900 * Blur the input.
14901 *
14902 * @chainable
14903 */
14904 OO.ui.InputWidget.prototype.blur = function () {
14905 this.$input[ 0 ].blur();
14906 return this;
14907 };
14908
14909 /**
14910 * @inheritdoc
14911 */
14912 OO.ui.InputWidget.prototype.restorePreInfuseState = function ( state ) {
14913 OO.ui.InputWidget.parent.prototype.restorePreInfuseState.call( this, state );
14914 if ( state.value !== undefined && state.value !== this.getValue() ) {
14915 this.setValue( state.value );
14916 }
14917 if ( state.focus ) {
14918 this.focus();
14919 }
14920 };
14921
14922 /**
14923 * ButtonInputWidget is used to submit HTML forms and is intended to be used within
14924 * a OO.ui.FormLayout. If you do not need the button to work with HTML forms, you probably
14925 * want to use OO.ui.ButtonWidget instead. Button input widgets can be rendered as either an
14926 * HTML `<button/>` (the default) or an HTML `<input/>` tags. See the
14927 * [OOjs UI documentation on MediaWiki] [1] for more information.
14928 *
14929 * @example
14930 * // A ButtonInputWidget rendered as an HTML button, the default.
14931 * var button = new OO.ui.ButtonInputWidget( {
14932 * label: 'Input button',
14933 * icon: 'check',
14934 * value: 'check'
14935 * } );
14936 * $( 'body' ).append( button.$element );
14937 *
14938 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs#Button_inputs
14939 *
14940 * @class
14941 * @extends OO.ui.InputWidget
14942 * @mixins OO.ui.mixin.ButtonElement
14943 * @mixins OO.ui.mixin.IconElement
14944 * @mixins OO.ui.mixin.IndicatorElement
14945 * @mixins OO.ui.mixin.LabelElement
14946 * @mixins OO.ui.mixin.TitledElement
14947 *
14948 * @constructor
14949 * @param {Object} [config] Configuration options
14950 * @cfg {string} [type='button'] The value of the HTML `'type'` attribute: 'button', 'submit' or 'reset'.
14951 * @cfg {boolean} [useInputTag=false] Use an `<input/>` tag instead of a `<button/>` tag, the default.
14952 * Widgets configured to be an `<input/>` do not support {@link #icon icons} and {@link #indicator indicators},
14953 * non-plaintext {@link #label labels}, or {@link #value values}. In general, useInputTag should only
14954 * be set to `true` when there’s need to support IE6 in a form with multiple buttons.
14955 */
14956 OO.ui.ButtonInputWidget = function OoUiButtonInputWidget( config ) {
14957 // Configuration initialization
14958 config = $.extend( { type: 'button', useInputTag: false }, config );
14959
14960 // Properties (must be set before parent constructor, which calls #setValue)
14961 this.useInputTag = config.useInputTag;
14962
14963 // Parent constructor
14964 OO.ui.ButtonInputWidget.parent.call( this, config );
14965
14966 // Mixin constructors
14967 OO.ui.mixin.ButtonElement.call( this, $.extend( {}, config, { $button: this.$input } ) );
14968 OO.ui.mixin.IconElement.call( this, config );
14969 OO.ui.mixin.IndicatorElement.call( this, config );
14970 OO.ui.mixin.LabelElement.call( this, config );
14971 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$input } ) );
14972
14973 // Initialization
14974 if ( !config.useInputTag ) {
14975 this.$input.append( this.$icon, this.$label, this.$indicator );
14976 }
14977 this.$element.addClass( 'oo-ui-buttonInputWidget' );
14978 };
14979
14980 /* Setup */
14981
14982 OO.inheritClass( OO.ui.ButtonInputWidget, OO.ui.InputWidget );
14983 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.ButtonElement );
14984 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.IconElement );
14985 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.IndicatorElement );
14986 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.LabelElement );
14987 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.TitledElement );
14988
14989 /* Static Properties */
14990
14991 /**
14992 * Disable generating `<label>` elements for buttons. One would very rarely need additional label
14993 * for a button, and it's already a big clickable target, and it causes unexpected rendering.
14994 */
14995 OO.ui.ButtonInputWidget.static.supportsSimpleLabel = false;
14996
14997 /* Methods */
14998
14999 /**
15000 * @inheritdoc
15001 * @protected
15002 */
15003 OO.ui.ButtonInputWidget.prototype.getInputElement = function ( config ) {
15004 var type;
15005 // See InputWidget#reusePreInfuseDOM about config.$input
15006 if ( config.$input ) {
15007 return config.$input.empty();
15008 }
15009 type = [ 'button', 'submit', 'reset' ].indexOf( config.type ) !== -1 ? config.type : 'button';
15010 return $( '<' + ( config.useInputTag ? 'input' : 'button' ) + ' type="' + type + '">' );
15011 };
15012
15013 /**
15014 * Set label value.
15015 *
15016 * If #useInputTag is `true`, the label is set as the `value` of the `<input/>` tag.
15017 *
15018 * @param {jQuery|string|Function|null} label Label nodes, text, a function that returns nodes or
15019 * text, or `null` for no label
15020 * @chainable
15021 */
15022 OO.ui.ButtonInputWidget.prototype.setLabel = function ( label ) {
15023 OO.ui.mixin.LabelElement.prototype.setLabel.call( this, label );
15024
15025 if ( this.useInputTag ) {
15026 if ( typeof label === 'function' ) {
15027 label = OO.ui.resolveMsg( label );
15028 }
15029 if ( label instanceof jQuery ) {
15030 label = label.text();
15031 }
15032 if ( !label ) {
15033 label = '';
15034 }
15035 this.$input.val( label );
15036 }
15037
15038 return this;
15039 };
15040
15041 /**
15042 * Set the value of the input.
15043 *
15044 * This method is disabled for button inputs configured as {@link #useInputTag <input/> tags}, as
15045 * they do not support {@link #value values}.
15046 *
15047 * @param {string} value New value
15048 * @chainable
15049 */
15050 OO.ui.ButtonInputWidget.prototype.setValue = function ( value ) {
15051 if ( !this.useInputTag ) {
15052 OO.ui.ButtonInputWidget.parent.prototype.setValue.call( this, value );
15053 }
15054 return this;
15055 };
15056
15057 /**
15058 * CheckboxInputWidgets, like HTML checkboxes, can be selected and/or configured with a value.
15059 * Note that these {@link OO.ui.InputWidget input widgets} are best laid out
15060 * in {@link OO.ui.FieldLayout field layouts} that use the {@link OO.ui.FieldLayout#align inline}
15061 * alignment. For more information, please see the [OOjs UI documentation on MediaWiki][1].
15062 *
15063 * This widget can be used inside a HTML form, such as a OO.ui.FormLayout.
15064 *
15065 * @example
15066 * // An example of selected, unselected, and disabled checkbox inputs
15067 * var checkbox1=new OO.ui.CheckboxInputWidget( {
15068 * value: 'a',
15069 * selected: true
15070 * } );
15071 * var checkbox2=new OO.ui.CheckboxInputWidget( {
15072 * value: 'b'
15073 * } );
15074 * var checkbox3=new OO.ui.CheckboxInputWidget( {
15075 * value:'c',
15076 * disabled: true
15077 * } );
15078 * // Create a fieldset layout with fields for each checkbox.
15079 * var fieldset = new OO.ui.FieldsetLayout( {
15080 * label: 'Checkboxes'
15081 * } );
15082 * fieldset.addItems( [
15083 * new OO.ui.FieldLayout( checkbox1, { label: 'Selected checkbox', align: 'inline' } ),
15084 * new OO.ui.FieldLayout( checkbox2, { label: 'Unselected checkbox', align: 'inline' } ),
15085 * new OO.ui.FieldLayout( checkbox3, { label: 'Disabled checkbox', align: 'inline' } ),
15086 * ] );
15087 * $( 'body' ).append( fieldset.$element );
15088 *
15089 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
15090 *
15091 * @class
15092 * @extends OO.ui.InputWidget
15093 *
15094 * @constructor
15095 * @param {Object} [config] Configuration options
15096 * @cfg {boolean} [selected=false] Select the checkbox initially. By default, the checkbox is not selected.
15097 */
15098 OO.ui.CheckboxInputWidget = function OoUiCheckboxInputWidget( config ) {
15099 // Configuration initialization
15100 config = config || {};
15101
15102 // Parent constructor
15103 OO.ui.CheckboxInputWidget.parent.call( this, config );
15104
15105 // Initialization
15106 this.$element
15107 .addClass( 'oo-ui-checkboxInputWidget' )
15108 // Required for pretty styling in MediaWiki theme
15109 .append( $( '<span>' ) );
15110 this.setSelected( config.selected !== undefined ? config.selected : false );
15111 };
15112
15113 /* Setup */
15114
15115 OO.inheritClass( OO.ui.CheckboxInputWidget, OO.ui.InputWidget );
15116
15117 /* Static Methods */
15118
15119 /**
15120 * @inheritdoc
15121 */
15122 OO.ui.CheckboxInputWidget.static.gatherPreInfuseState = function ( node, config ) {
15123 var state = OO.ui.CheckboxInputWidget.parent.static.gatherPreInfuseState( node, config );
15124 state.checked = config.$input.prop( 'checked' );
15125 return state;
15126 };
15127
15128 /* Methods */
15129
15130 /**
15131 * @inheritdoc
15132 * @protected
15133 */
15134 OO.ui.CheckboxInputWidget.prototype.getInputElement = function () {
15135 return $( '<input type="checkbox" />' );
15136 };
15137
15138 /**
15139 * @inheritdoc
15140 */
15141 OO.ui.CheckboxInputWidget.prototype.onEdit = function () {
15142 var widget = this;
15143 if ( !this.isDisabled() ) {
15144 // Allow the stack to clear so the value will be updated
15145 setTimeout( function () {
15146 widget.setSelected( widget.$input.prop( 'checked' ) );
15147 } );
15148 }
15149 };
15150
15151 /**
15152 * Set selection state of this checkbox.
15153 *
15154 * @param {boolean} state `true` for selected
15155 * @chainable
15156 */
15157 OO.ui.CheckboxInputWidget.prototype.setSelected = function ( state ) {
15158 state = !!state;
15159 if ( this.selected !== state ) {
15160 this.selected = state;
15161 this.$input.prop( 'checked', this.selected );
15162 this.emit( 'change', this.selected );
15163 }
15164 return this;
15165 };
15166
15167 /**
15168 * Check if this checkbox is selected.
15169 *
15170 * @return {boolean} Checkbox is selected
15171 */
15172 OO.ui.CheckboxInputWidget.prototype.isSelected = function () {
15173 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
15174 // it, and we won't know unless they're kind enough to trigger a 'change' event.
15175 var selected = this.$input.prop( 'checked' );
15176 if ( this.selected !== selected ) {
15177 this.setSelected( selected );
15178 }
15179 return this.selected;
15180 };
15181
15182 /**
15183 * @inheritdoc
15184 */
15185 OO.ui.CheckboxInputWidget.prototype.restorePreInfuseState = function ( state ) {
15186 OO.ui.CheckboxInputWidget.parent.prototype.restorePreInfuseState.call( this, state );
15187 if ( state.checked !== undefined && state.checked !== this.isSelected() ) {
15188 this.setSelected( state.checked );
15189 }
15190 };
15191
15192 /**
15193 * DropdownInputWidget is a {@link OO.ui.DropdownWidget DropdownWidget} intended to be used
15194 * within a HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with the value
15195 * of a hidden HTML `input` tag. Please see the [OOjs UI documentation on MediaWiki][1] for
15196 * more information about input widgets.
15197 *
15198 * A DropdownInputWidget always has a value (one of the options is always selected), unless there
15199 * are no options. If no `value` configuration option is provided, the first option is selected.
15200 * If you need a state representing no value (no option being selected), use a DropdownWidget.
15201 *
15202 * This and OO.ui.RadioSelectInputWidget support the same configuration options.
15203 *
15204 * @example
15205 * // Example: A DropdownInputWidget with three options
15206 * var dropdownInput = new OO.ui.DropdownInputWidget( {
15207 * options: [
15208 * { data: 'a', label: 'First' },
15209 * { data: 'b', label: 'Second'},
15210 * { data: 'c', label: 'Third' }
15211 * ]
15212 * } );
15213 * $( 'body' ).append( dropdownInput.$element );
15214 *
15215 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
15216 *
15217 * @class
15218 * @extends OO.ui.InputWidget
15219 * @mixins OO.ui.mixin.TitledElement
15220 *
15221 * @constructor
15222 * @param {Object} [config] Configuration options
15223 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
15224 * @cfg {Object} [dropdown] Configuration options for {@link OO.ui.DropdownWidget DropdownWidget}
15225 */
15226 OO.ui.DropdownInputWidget = function OoUiDropdownInputWidget( config ) {
15227 // Configuration initialization
15228 config = config || {};
15229
15230 // Properties (must be done before parent constructor which calls #setDisabled)
15231 this.dropdownWidget = new OO.ui.DropdownWidget( config.dropdown );
15232
15233 // Parent constructor
15234 OO.ui.DropdownInputWidget.parent.call( this, config );
15235
15236 // Mixin constructors
15237 OO.ui.mixin.TitledElement.call( this, config );
15238
15239 // Events
15240 this.dropdownWidget.getMenu().connect( this, { select: 'onMenuSelect' } );
15241
15242 // Initialization
15243 this.setOptions( config.options || [] );
15244 this.$element
15245 .addClass( 'oo-ui-dropdownInputWidget' )
15246 .append( this.dropdownWidget.$element );
15247 };
15248
15249 /* Setup */
15250
15251 OO.inheritClass( OO.ui.DropdownInputWidget, OO.ui.InputWidget );
15252 OO.mixinClass( OO.ui.DropdownInputWidget, OO.ui.mixin.TitledElement );
15253
15254 /* Methods */
15255
15256 /**
15257 * @inheritdoc
15258 * @protected
15259 */
15260 OO.ui.DropdownInputWidget.prototype.getInputElement = function ( config ) {
15261 // See InputWidget#reusePreInfuseDOM about config.$input
15262 if ( config.$input ) {
15263 return config.$input.addClass( 'oo-ui-element-hidden' );
15264 }
15265 return $( '<input type="hidden">' );
15266 };
15267
15268 /**
15269 * Handles menu select events.
15270 *
15271 * @private
15272 * @param {OO.ui.MenuOptionWidget} item Selected menu item
15273 */
15274 OO.ui.DropdownInputWidget.prototype.onMenuSelect = function ( item ) {
15275 this.setValue( item.getData() );
15276 };
15277
15278 /**
15279 * @inheritdoc
15280 */
15281 OO.ui.DropdownInputWidget.prototype.setValue = function ( value ) {
15282 value = this.cleanUpValue( value );
15283 this.dropdownWidget.getMenu().selectItemByData( value );
15284 OO.ui.DropdownInputWidget.parent.prototype.setValue.call( this, value );
15285 return this;
15286 };
15287
15288 /**
15289 * @inheritdoc
15290 */
15291 OO.ui.DropdownInputWidget.prototype.setDisabled = function ( state ) {
15292 this.dropdownWidget.setDisabled( state );
15293 OO.ui.DropdownInputWidget.parent.prototype.setDisabled.call( this, state );
15294 return this;
15295 };
15296
15297 /**
15298 * Set the options available for this input.
15299 *
15300 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
15301 * @chainable
15302 */
15303 OO.ui.DropdownInputWidget.prototype.setOptions = function ( options ) {
15304 var
15305 value = this.getValue(),
15306 widget = this;
15307
15308 // Rebuild the dropdown menu
15309 this.dropdownWidget.getMenu()
15310 .clearItems()
15311 .addItems( options.map( function ( opt ) {
15312 var optValue = widget.cleanUpValue( opt.data );
15313 return new OO.ui.MenuOptionWidget( {
15314 data: optValue,
15315 label: opt.label !== undefined ? opt.label : optValue
15316 } );
15317 } ) );
15318
15319 // Restore the previous value, or reset to something sensible
15320 if ( this.dropdownWidget.getMenu().getItemFromData( value ) ) {
15321 // Previous value is still available, ensure consistency with the dropdown
15322 this.setValue( value );
15323 } else {
15324 // No longer valid, reset
15325 if ( options.length ) {
15326 this.setValue( options[ 0 ].data );
15327 }
15328 }
15329
15330 return this;
15331 };
15332
15333 /**
15334 * @inheritdoc
15335 */
15336 OO.ui.DropdownInputWidget.prototype.focus = function () {
15337 this.dropdownWidget.getMenu().toggle( true );
15338 return this;
15339 };
15340
15341 /**
15342 * @inheritdoc
15343 */
15344 OO.ui.DropdownInputWidget.prototype.blur = function () {
15345 this.dropdownWidget.getMenu().toggle( false );
15346 return this;
15347 };
15348
15349 /**
15350 * RadioInputWidget creates a single radio button. Because radio buttons are usually used as a set,
15351 * in most cases you will want to use a {@link OO.ui.RadioSelectWidget radio select}
15352 * with {@link OO.ui.RadioOptionWidget radio options} instead of this class. For more information,
15353 * please see the [OOjs UI documentation on MediaWiki][1].
15354 *
15355 * This widget can be used inside a HTML form, such as a OO.ui.FormLayout.
15356 *
15357 * @example
15358 * // An example of selected, unselected, and disabled radio inputs
15359 * var radio1 = new OO.ui.RadioInputWidget( {
15360 * value: 'a',
15361 * selected: true
15362 * } );
15363 * var radio2 = new OO.ui.RadioInputWidget( {
15364 * value: 'b'
15365 * } );
15366 * var radio3 = new OO.ui.RadioInputWidget( {
15367 * value: 'c',
15368 * disabled: true
15369 * } );
15370 * // Create a fieldset layout with fields for each radio button.
15371 * var fieldset = new OO.ui.FieldsetLayout( {
15372 * label: 'Radio inputs'
15373 * } );
15374 * fieldset.addItems( [
15375 * new OO.ui.FieldLayout( radio1, { label: 'Selected', align: 'inline' } ),
15376 * new OO.ui.FieldLayout( radio2, { label: 'Unselected', align: 'inline' } ),
15377 * new OO.ui.FieldLayout( radio3, { label: 'Disabled', align: 'inline' } ),
15378 * ] );
15379 * $( 'body' ).append( fieldset.$element );
15380 *
15381 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
15382 *
15383 * @class
15384 * @extends OO.ui.InputWidget
15385 *
15386 * @constructor
15387 * @param {Object} [config] Configuration options
15388 * @cfg {boolean} [selected=false] Select the radio button initially. By default, the radio button is not selected.
15389 */
15390 OO.ui.RadioInputWidget = function OoUiRadioInputWidget( config ) {
15391 // Configuration initialization
15392 config = config || {};
15393
15394 // Parent constructor
15395 OO.ui.RadioInputWidget.parent.call( this, config );
15396
15397 // Initialization
15398 this.$element
15399 .addClass( 'oo-ui-radioInputWidget' )
15400 // Required for pretty styling in MediaWiki theme
15401 .append( $( '<span>' ) );
15402 this.setSelected( config.selected !== undefined ? config.selected : false );
15403 };
15404
15405 /* Setup */
15406
15407 OO.inheritClass( OO.ui.RadioInputWidget, OO.ui.InputWidget );
15408
15409 /* Static Methods */
15410
15411 /**
15412 * @inheritdoc
15413 */
15414 OO.ui.RadioInputWidget.static.gatherPreInfuseState = function ( node, config ) {
15415 var state = OO.ui.RadioInputWidget.parent.static.gatherPreInfuseState( node, config );
15416 state.checked = config.$input.prop( 'checked' );
15417 return state;
15418 };
15419
15420 /* Methods */
15421
15422 /**
15423 * @inheritdoc
15424 * @protected
15425 */
15426 OO.ui.RadioInputWidget.prototype.getInputElement = function () {
15427 return $( '<input type="radio" />' );
15428 };
15429
15430 /**
15431 * @inheritdoc
15432 */
15433 OO.ui.RadioInputWidget.prototype.onEdit = function () {
15434 // RadioInputWidget doesn't track its state.
15435 };
15436
15437 /**
15438 * Set selection state of this radio button.
15439 *
15440 * @param {boolean} state `true` for selected
15441 * @chainable
15442 */
15443 OO.ui.RadioInputWidget.prototype.setSelected = function ( state ) {
15444 // RadioInputWidget doesn't track its state.
15445 this.$input.prop( 'checked', state );
15446 return this;
15447 };
15448
15449 /**
15450 * Check if this radio button is selected.
15451 *
15452 * @return {boolean} Radio is selected
15453 */
15454 OO.ui.RadioInputWidget.prototype.isSelected = function () {
15455 return this.$input.prop( 'checked' );
15456 };
15457
15458 /**
15459 * @inheritdoc
15460 */
15461 OO.ui.RadioInputWidget.prototype.restorePreInfuseState = function ( state ) {
15462 OO.ui.RadioInputWidget.parent.prototype.restorePreInfuseState.call( this, state );
15463 if ( state.checked !== undefined && state.checked !== this.isSelected() ) {
15464 this.setSelected( state.checked );
15465 }
15466 };
15467
15468 /**
15469 * RadioSelectInputWidget is a {@link OO.ui.RadioSelectWidget RadioSelectWidget} intended to be used
15470 * within a HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with the value
15471 * of a hidden HTML `input` tag. Please see the [OOjs UI documentation on MediaWiki][1] for
15472 * more information about input widgets.
15473 *
15474 * This and OO.ui.DropdownInputWidget support the same configuration options.
15475 *
15476 * @example
15477 * // Example: A RadioSelectInputWidget with three options
15478 * var radioSelectInput = new OO.ui.RadioSelectInputWidget( {
15479 * options: [
15480 * { data: 'a', label: 'First' },
15481 * { data: 'b', label: 'Second'},
15482 * { data: 'c', label: 'Third' }
15483 * ]
15484 * } );
15485 * $( 'body' ).append( radioSelectInput.$element );
15486 *
15487 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
15488 *
15489 * @class
15490 * @extends OO.ui.InputWidget
15491 *
15492 * @constructor
15493 * @param {Object} [config] Configuration options
15494 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
15495 */
15496 OO.ui.RadioSelectInputWidget = function OoUiRadioSelectInputWidget( config ) {
15497 // Configuration initialization
15498 config = config || {};
15499
15500 // Properties (must be done before parent constructor which calls #setDisabled)
15501 this.radioSelectWidget = new OO.ui.RadioSelectWidget();
15502
15503 // Parent constructor
15504 OO.ui.RadioSelectInputWidget.parent.call( this, config );
15505
15506 // Events
15507 this.radioSelectWidget.connect( this, { select: 'onMenuSelect' } );
15508
15509 // Initialization
15510 this.setOptions( config.options || [] );
15511 this.$element
15512 .addClass( 'oo-ui-radioSelectInputWidget' )
15513 .append( this.radioSelectWidget.$element );
15514 };
15515
15516 /* Setup */
15517
15518 OO.inheritClass( OO.ui.RadioSelectInputWidget, OO.ui.InputWidget );
15519
15520 /* Static Properties */
15521
15522 OO.ui.RadioSelectInputWidget.static.supportsSimpleLabel = false;
15523
15524 /* Static Methods */
15525
15526 /**
15527 * @inheritdoc
15528 */
15529 OO.ui.RadioSelectInputWidget.static.gatherPreInfuseState = function ( node, config ) {
15530 var state = OO.ui.RadioSelectInputWidget.parent.static.gatherPreInfuseState( node, config );
15531 state.value = $( node ).find( '.oo-ui-radioInputWidget .oo-ui-inputWidget-input:checked' ).val();
15532 return state;
15533 };
15534
15535 /* Methods */
15536
15537 /**
15538 * @inheritdoc
15539 * @protected
15540 */
15541 OO.ui.RadioSelectInputWidget.prototype.getInputElement = function () {
15542 return $( '<input type="hidden">' );
15543 };
15544
15545 /**
15546 * Handles menu select events.
15547 *
15548 * @private
15549 * @param {OO.ui.RadioOptionWidget} item Selected menu item
15550 */
15551 OO.ui.RadioSelectInputWidget.prototype.onMenuSelect = function ( item ) {
15552 this.setValue( item.getData() );
15553 };
15554
15555 /**
15556 * @inheritdoc
15557 */
15558 OO.ui.RadioSelectInputWidget.prototype.setValue = function ( value ) {
15559 value = this.cleanUpValue( value );
15560 this.radioSelectWidget.selectItemByData( value );
15561 OO.ui.RadioSelectInputWidget.parent.prototype.setValue.call( this, value );
15562 return this;
15563 };
15564
15565 /**
15566 * @inheritdoc
15567 */
15568 OO.ui.RadioSelectInputWidget.prototype.setDisabled = function ( state ) {
15569 this.radioSelectWidget.setDisabled( state );
15570 OO.ui.RadioSelectInputWidget.parent.prototype.setDisabled.call( this, state );
15571 return this;
15572 };
15573
15574 /**
15575 * Set the options available for this input.
15576 *
15577 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
15578 * @chainable
15579 */
15580 OO.ui.RadioSelectInputWidget.prototype.setOptions = function ( options ) {
15581 var
15582 value = this.getValue(),
15583 widget = this;
15584
15585 // Rebuild the radioSelect menu
15586 this.radioSelectWidget
15587 .clearItems()
15588 .addItems( options.map( function ( opt ) {
15589 var optValue = widget.cleanUpValue( opt.data );
15590 return new OO.ui.RadioOptionWidget( {
15591 data: optValue,
15592 label: opt.label !== undefined ? opt.label : optValue
15593 } );
15594 } ) );
15595
15596 // Restore the previous value, or reset to something sensible
15597 if ( this.radioSelectWidget.getItemFromData( value ) ) {
15598 // Previous value is still available, ensure consistency with the radioSelect
15599 this.setValue( value );
15600 } else {
15601 // No longer valid, reset
15602 if ( options.length ) {
15603 this.setValue( options[ 0 ].data );
15604 }
15605 }
15606
15607 return this;
15608 };
15609
15610 /**
15611 * TextInputWidgets, like HTML text inputs, can be configured with options that customize the
15612 * size of the field as well as its presentation. In addition, these widgets can be configured
15613 * with {@link OO.ui.mixin.IconElement icons}, {@link OO.ui.mixin.IndicatorElement indicators}, an optional
15614 * validation-pattern (used to determine if an input value is valid or not) and an input filter,
15615 * which modifies incoming values rather than validating them.
15616 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
15617 *
15618 * This widget can be used inside a HTML form, such as a OO.ui.FormLayout.
15619 *
15620 * @example
15621 * // Example of a text input widget
15622 * var textInput = new OO.ui.TextInputWidget( {
15623 * value: 'Text input'
15624 * } )
15625 * $( 'body' ).append( textInput.$element );
15626 *
15627 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
15628 *
15629 * @class
15630 * @extends OO.ui.InputWidget
15631 * @mixins OO.ui.mixin.IconElement
15632 * @mixins OO.ui.mixin.IndicatorElement
15633 * @mixins OO.ui.mixin.PendingElement
15634 * @mixins OO.ui.mixin.LabelElement
15635 *
15636 * @constructor
15637 * @param {Object} [config] Configuration options
15638 * @cfg {string} [type='text'] The value of the HTML `type` attribute: 'text', 'password', 'search',
15639 * 'email' or 'url'. Ignored if `multiline` is true.
15640 *
15641 * Some values of `type` result in additional behaviors:
15642 *
15643 * - `search`: implies `icon: 'search'` and `indicator: 'clear'`; when clicked, the indicator
15644 * empties the text field
15645 * @cfg {string} [placeholder] Placeholder text
15646 * @cfg {boolean} [autofocus=false] Use an HTML `autofocus` attribute to
15647 * instruct the browser to focus this widget.
15648 * @cfg {boolean} [readOnly=false] Prevent changes to the value of the text input.
15649 * @cfg {number} [maxLength] Maximum number of characters allowed in the input.
15650 * @cfg {boolean} [multiline=false] Allow multiple lines of text
15651 * @cfg {number} [rows] If multiline, number of visible lines in textarea. If used with `autosize`,
15652 * specifies minimum number of rows to display.
15653 * @cfg {boolean} [autosize=false] Automatically resize the text input to fit its content.
15654 * Use the #maxRows config to specify a maximum number of displayed rows.
15655 * @cfg {boolean} [maxRows] Maximum number of rows to display when #autosize is set to true.
15656 * Defaults to the maximum of `10` and `2 * rows`, or `10` if `rows` isn't provided.
15657 * @cfg {string} [labelPosition='after'] The position of the inline label relative to that of
15658 * the value or placeholder text: `'before'` or `'after'`
15659 * @cfg {boolean} [required=false] Mark the field as required. Implies `indicator: 'required'`.
15660 * @cfg {boolean} [autocomplete=true] Should the browser support autocomplete for this field
15661 * @cfg {RegExp|Function|string} [validate] Validation pattern: when string, a symbolic name of a
15662 * pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer'
15663 * (the value must contain only numbers); when RegExp, a regular expression that must match the
15664 * value for it to be considered valid; when Function, a function receiving the value as parameter
15665 * that must return true, or promise resolving to true, for it to be considered valid.
15666 */
15667 OO.ui.TextInputWidget = function OoUiTextInputWidget( config ) {
15668 // Configuration initialization
15669 config = $.extend( {
15670 type: 'text',
15671 labelPosition: 'after'
15672 }, config );
15673 if ( config.type === 'search' ) {
15674 if ( config.icon === undefined ) {
15675 config.icon = 'search';
15676 }
15677 // indicator: 'clear' is set dynamically later, depending on value
15678 }
15679 if ( config.required ) {
15680 if ( config.indicator === undefined ) {
15681 config.indicator = 'required';
15682 }
15683 }
15684
15685 // Parent constructor
15686 OO.ui.TextInputWidget.parent.call( this, config );
15687
15688 // Mixin constructors
15689 OO.ui.mixin.IconElement.call( this, config );
15690 OO.ui.mixin.IndicatorElement.call( this, config );
15691 OO.ui.mixin.PendingElement.call( this, $.extend( {}, config, { $pending: this.$input } ) );
15692 OO.ui.mixin.LabelElement.call( this, config );
15693
15694 // Properties
15695 this.type = this.getSaneType( config );
15696 this.readOnly = false;
15697 this.multiline = !!config.multiline;
15698 this.autosize = !!config.autosize;
15699 this.minRows = config.rows !== undefined ? config.rows : '';
15700 this.maxRows = config.maxRows || Math.max( 2 * ( this.minRows || 0 ), 10 );
15701 this.validate = null;
15702 this.styleHeight = null;
15703 this.scrollWidth = null;
15704
15705 // Clone for resizing
15706 if ( this.autosize ) {
15707 this.$clone = this.$input
15708 .clone()
15709 .insertAfter( this.$input )
15710 .attr( 'aria-hidden', 'true' )
15711 .addClass( 'oo-ui-element-hidden' );
15712 }
15713
15714 this.setValidation( config.validate );
15715 this.setLabelPosition( config.labelPosition );
15716
15717 // Events
15718 this.$input.on( {
15719 keypress: this.onKeyPress.bind( this ),
15720 blur: this.onBlur.bind( this )
15721 } );
15722 this.$input.one( {
15723 focus: this.onElementAttach.bind( this )
15724 } );
15725 this.$icon.on( 'mousedown', this.onIconMouseDown.bind( this ) );
15726 this.$indicator.on( 'mousedown', this.onIndicatorMouseDown.bind( this ) );
15727 this.on( 'labelChange', this.updatePosition.bind( this ) );
15728 this.connect( this, {
15729 change: 'onChange',
15730 disable: 'onDisable'
15731 } );
15732
15733 // Initialization
15734 this.$element
15735 .addClass( 'oo-ui-textInputWidget oo-ui-textInputWidget-type-' + this.type )
15736 .append( this.$icon, this.$indicator );
15737 this.setReadOnly( !!config.readOnly );
15738 this.updateSearchIndicator();
15739 if ( config.placeholder ) {
15740 this.$input.attr( 'placeholder', config.placeholder );
15741 }
15742 if ( config.maxLength !== undefined ) {
15743 this.$input.attr( 'maxlength', config.maxLength );
15744 }
15745 if ( config.autofocus ) {
15746 this.$input.attr( 'autofocus', 'autofocus' );
15747 }
15748 if ( config.required ) {
15749 this.$input.attr( 'required', 'required' );
15750 this.$input.attr( 'aria-required', 'true' );
15751 }
15752 if ( config.autocomplete === false ) {
15753 this.$input.attr( 'autocomplete', 'off' );
15754 // Turning off autocompletion also disables "form caching" when the user navigates to a
15755 // different page and then clicks "Back". Re-enable it when leaving. Borrowed from jQuery UI.
15756 $( window ).on( {
15757 beforeunload: function () {
15758 this.$input.removeAttr( 'autocomplete' );
15759 }.bind( this ),
15760 pageshow: function () {
15761 // Browsers don't seem to actually fire this event on "Back", they instead just reload the
15762 // whole page... it shouldn't hurt, though.
15763 this.$input.attr( 'autocomplete', 'off' );
15764 }.bind( this )
15765 } );
15766 }
15767 if ( this.multiline && config.rows ) {
15768 this.$input.attr( 'rows', config.rows );
15769 }
15770 if ( this.label || config.autosize ) {
15771 this.installParentChangeDetector();
15772 }
15773 };
15774
15775 /* Setup */
15776
15777 OO.inheritClass( OO.ui.TextInputWidget, OO.ui.InputWidget );
15778 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.mixin.IconElement );
15779 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.mixin.IndicatorElement );
15780 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.mixin.PendingElement );
15781 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.mixin.LabelElement );
15782
15783 /* Static Properties */
15784
15785 OO.ui.TextInputWidget.static.validationPatterns = {
15786 'non-empty': /.+/,
15787 integer: /^\d+$/
15788 };
15789
15790 /* Static Methods */
15791
15792 /**
15793 * @inheritdoc
15794 */
15795 OO.ui.TextInputWidget.static.gatherPreInfuseState = function ( node, config ) {
15796 var state = OO.ui.TextInputWidget.parent.static.gatherPreInfuseState( node, config );
15797 if ( config.multiline ) {
15798 state.scrollTop = config.$input.scrollTop();
15799 }
15800 return state;
15801 };
15802
15803 /* Events */
15804
15805 /**
15806 * An `enter` event is emitted when the user presses 'enter' inside the text box.
15807 *
15808 * Not emitted if the input is multiline.
15809 *
15810 * @event enter
15811 */
15812
15813 /**
15814 * A `resize` event is emitted when autosize is set and the widget resizes
15815 *
15816 * @event resize
15817 */
15818
15819 /* Methods */
15820
15821 /**
15822 * Handle icon mouse down events.
15823 *
15824 * @private
15825 * @param {jQuery.Event} e Mouse down event
15826 * @fires icon
15827 */
15828 OO.ui.TextInputWidget.prototype.onIconMouseDown = function ( e ) {
15829 if ( e.which === 1 ) {
15830 this.$input[ 0 ].focus();
15831 return false;
15832 }
15833 };
15834
15835 /**
15836 * Handle indicator mouse down events.
15837 *
15838 * @private
15839 * @param {jQuery.Event} e Mouse down event
15840 * @fires indicator
15841 */
15842 OO.ui.TextInputWidget.prototype.onIndicatorMouseDown = function ( e ) {
15843 if ( e.which === 1 ) {
15844 if ( this.type === 'search' ) {
15845 // Clear the text field
15846 this.setValue( '' );
15847 }
15848 this.$input[ 0 ].focus();
15849 return false;
15850 }
15851 };
15852
15853 /**
15854 * Handle key press events.
15855 *
15856 * @private
15857 * @param {jQuery.Event} e Key press event
15858 * @fires enter If enter key is pressed and input is not multiline
15859 */
15860 OO.ui.TextInputWidget.prototype.onKeyPress = function ( e ) {
15861 if ( e.which === OO.ui.Keys.ENTER && !this.multiline ) {
15862 this.emit( 'enter', e );
15863 }
15864 };
15865
15866 /**
15867 * Handle blur events.
15868 *
15869 * @private
15870 * @param {jQuery.Event} e Blur event
15871 */
15872 OO.ui.TextInputWidget.prototype.onBlur = function () {
15873 this.setValidityFlag();
15874 };
15875
15876 /**
15877 * Handle element attach events.
15878 *
15879 * @private
15880 * @param {jQuery.Event} e Element attach event
15881 */
15882 OO.ui.TextInputWidget.prototype.onElementAttach = function () {
15883 // Any previously calculated size is now probably invalid if we reattached elsewhere
15884 this.valCache = null;
15885 this.adjustSize();
15886 this.positionLabel();
15887 };
15888
15889 /**
15890 * Handle change events.
15891 *
15892 * @param {string} value
15893 * @private
15894 */
15895 OO.ui.TextInputWidget.prototype.onChange = function () {
15896 this.updateSearchIndicator();
15897 this.setValidityFlag();
15898 this.adjustSize();
15899 };
15900
15901 /**
15902 * Handle disable events.
15903 *
15904 * @param {boolean} disabled Element is disabled
15905 * @private
15906 */
15907 OO.ui.TextInputWidget.prototype.onDisable = function () {
15908 this.updateSearchIndicator();
15909 };
15910
15911 /**
15912 * Check if the input is {@link #readOnly read-only}.
15913 *
15914 * @return {boolean}
15915 */
15916 OO.ui.TextInputWidget.prototype.isReadOnly = function () {
15917 return this.readOnly;
15918 };
15919
15920 /**
15921 * Set the {@link #readOnly read-only} state of the input.
15922 *
15923 * @param {boolean} state Make input read-only
15924 * @chainable
15925 */
15926 OO.ui.TextInputWidget.prototype.setReadOnly = function ( state ) {
15927 this.readOnly = !!state;
15928 this.$input.prop( 'readOnly', this.readOnly );
15929 this.updateSearchIndicator();
15930 return this;
15931 };
15932
15933 /**
15934 * Support function for making #onElementAttach work across browsers.
15935 *
15936 * This whole function could be replaced with one line of code using the DOMNodeInsertedIntoDocument
15937 * event, but it's not supported by Firefox and allegedly deprecated, so we only use it as fallback.
15938 *
15939 * Due to MutationObserver performance woes, #onElementAttach is only somewhat reliably called the
15940 * first time that the element gets attached to the documented.
15941 */
15942 OO.ui.TextInputWidget.prototype.installParentChangeDetector = function () {
15943 var mutationObserver, onRemove, topmostNode, fakeParentNode,
15944 MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver,
15945 widget = this;
15946
15947 if ( MutationObserver ) {
15948 // The new way. If only it wasn't so ugly.
15949
15950 if ( this.$element.closest( 'html' ).length ) {
15951 // Widget is attached already, do nothing. This breaks the functionality of this function when
15952 // the widget is detached and reattached. Alas, doing this correctly with MutationObserver
15953 // would require observation of the whole document, which would hurt performance of other,
15954 // more important code.
15955 return;
15956 }
15957
15958 // Find topmost node in the tree
15959 topmostNode = this.$element[ 0 ];
15960 while ( topmostNode.parentNode ) {
15961 topmostNode = topmostNode.parentNode;
15962 }
15963
15964 // We have no way to detect the $element being attached somewhere without observing the entire
15965 // DOM with subtree modifications, which would hurt performance. So we cheat: we hook to the
15966 // parent node of $element, and instead detect when $element is removed from it (and thus
15967 // probably attached somewhere else). If there is no parent, we create a "fake" one. If it
15968 // doesn't get attached, we end up back here and create the parent.
15969
15970 mutationObserver = new MutationObserver( function ( mutations ) {
15971 var i, j, removedNodes;
15972 for ( i = 0; i < mutations.length; i++ ) {
15973 removedNodes = mutations[ i ].removedNodes;
15974 for ( j = 0; j < removedNodes.length; j++ ) {
15975 if ( removedNodes[ j ] === topmostNode ) {
15976 setTimeout( onRemove, 0 );
15977 return;
15978 }
15979 }
15980 }
15981 } );
15982
15983 onRemove = function () {
15984 // If the node was attached somewhere else, report it
15985 if ( widget.$element.closest( 'html' ).length ) {
15986 widget.onElementAttach();
15987 }
15988 mutationObserver.disconnect();
15989 widget.installParentChangeDetector();
15990 };
15991
15992 // Create a fake parent and observe it
15993 fakeParentNode = $( '<div>' ).append( topmostNode )[ 0 ];
15994 mutationObserver.observe( fakeParentNode, { childList: true } );
15995 } else {
15996 // Using the DOMNodeInsertedIntoDocument event is much nicer and less magical, and works for
15997 // detachment and reattachment, but it's not supported by Firefox and allegedly deprecated.
15998 this.$element.on( 'DOMNodeInsertedIntoDocument', this.onElementAttach.bind( this ) );
15999 }
16000 };
16001
16002 /**
16003 * Automatically adjust the size of the text input.
16004 *
16005 * This only affects #multiline inputs that are {@link #autosize autosized}.
16006 *
16007 * @chainable
16008 * @fires resize
16009 */
16010 OO.ui.TextInputWidget.prototype.adjustSize = function () {
16011 var scrollHeight, innerHeight, outerHeight, maxInnerHeight, measurementError,
16012 idealHeight, newHeight, scrollWidth, property;
16013
16014 if ( this.multiline && this.$input.val() !== this.valCache ) {
16015 if ( this.autosize ) {
16016 this.$clone
16017 .val( this.$input.val() )
16018 .attr( 'rows', this.minRows )
16019 // Set inline height property to 0 to measure scroll height
16020 .css( 'height', 0 );
16021
16022 this.$clone.removeClass( 'oo-ui-element-hidden' );
16023
16024 this.valCache = this.$input.val();
16025
16026 scrollHeight = this.$clone[ 0 ].scrollHeight;
16027
16028 // Remove inline height property to measure natural heights
16029 this.$clone.css( 'height', '' );
16030 innerHeight = this.$clone.innerHeight();
16031 outerHeight = this.$clone.outerHeight();
16032
16033 // Measure max rows height
16034 this.$clone
16035 .attr( 'rows', this.maxRows )
16036 .css( 'height', 'auto' )
16037 .val( '' );
16038 maxInnerHeight = this.$clone.innerHeight();
16039
16040 // Difference between reported innerHeight and scrollHeight with no scrollbars present
16041 // Equals 1 on Blink-based browsers and 0 everywhere else
16042 measurementError = maxInnerHeight - this.$clone[ 0 ].scrollHeight;
16043 idealHeight = Math.min( maxInnerHeight, scrollHeight + measurementError );
16044
16045 this.$clone.addClass( 'oo-ui-element-hidden' );
16046
16047 // Only apply inline height when expansion beyond natural height is needed
16048 // Use the difference between the inner and outer height as a buffer
16049 newHeight = idealHeight > innerHeight ? idealHeight + ( outerHeight - innerHeight ) : '';
16050 if ( newHeight !== this.styleHeight ) {
16051 this.$input.css( 'height', newHeight );
16052 this.styleHeight = newHeight;
16053 this.emit( 'resize' );
16054 }
16055 }
16056 scrollWidth = this.$input[ 0 ].offsetWidth - this.$input[ 0 ].clientWidth;
16057 if ( scrollWidth !== this.scrollWidth ) {
16058 property = this.$element.css( 'direction' ) === 'rtl' ? 'left' : 'right';
16059 // Reset
16060 this.$label.css( { right: '', left: '' } );
16061 this.$indicator.css( { right: '', left: '' } );
16062
16063 if ( scrollWidth ) {
16064 this.$indicator.css( property, scrollWidth );
16065 if ( this.labelPosition === 'after' ) {
16066 this.$label.css( property, scrollWidth );
16067 }
16068 }
16069
16070 this.scrollWidth = scrollWidth;
16071 this.positionLabel();
16072 }
16073 }
16074 return this;
16075 };
16076
16077 /**
16078 * @inheritdoc
16079 * @protected
16080 */
16081 OO.ui.TextInputWidget.prototype.getInputElement = function ( config ) {
16082 return config.multiline ?
16083 $( '<textarea>' ) :
16084 $( '<input type="' + this.getSaneType( config ) + '" />' );
16085 };
16086
16087 /**
16088 * Get sanitized value for 'type' for given config.
16089 *
16090 * @param {Object} config Configuration options
16091 * @return {string|null}
16092 * @private
16093 */
16094 OO.ui.TextInputWidget.prototype.getSaneType = function ( config ) {
16095 var type = [ 'text', 'password', 'search', 'email', 'url' ].indexOf( config.type ) !== -1 ?
16096 config.type :
16097 'text';
16098 return config.multiline ? 'multiline' : type;
16099 };
16100
16101 /**
16102 * Check if the input supports multiple lines.
16103 *
16104 * @return {boolean}
16105 */
16106 OO.ui.TextInputWidget.prototype.isMultiline = function () {
16107 return !!this.multiline;
16108 };
16109
16110 /**
16111 * Check if the input automatically adjusts its size.
16112 *
16113 * @return {boolean}
16114 */
16115 OO.ui.TextInputWidget.prototype.isAutosizing = function () {
16116 return !!this.autosize;
16117 };
16118
16119 /**
16120 * Focus the input and select a specified range within the text.
16121 *
16122 * @param {number} from Select from offset
16123 * @param {number} [to] Select to offset, defaults to from
16124 * @chainable
16125 */
16126 OO.ui.TextInputWidget.prototype.selectRange = function ( from, to ) {
16127 var textRange, isBackwards, start, end,
16128 element = this.$input[ 0 ];
16129
16130 to = to || from;
16131
16132 isBackwards = to < from;
16133 start = isBackwards ? to : from;
16134 end = isBackwards ? from : to;
16135
16136 this.focus();
16137
16138 if ( element.setSelectionRange ) {
16139 element.setSelectionRange( start, end, isBackwards ? 'backward' : 'forward' );
16140 } else if ( element.createTextRange ) {
16141 // IE 8 and below
16142 textRange = element.createTextRange();
16143 textRange.collapse( true );
16144 textRange.moveStart( 'character', start );
16145 textRange.moveEnd( 'character', end - start );
16146 textRange.select();
16147 }
16148 return this;
16149 };
16150
16151 /**
16152 * Get the length of the text input value.
16153 *
16154 * This could differ from the length of #getValue if the
16155 * value gets filtered
16156 *
16157 * @return {number} Input length
16158 */
16159 OO.ui.TextInputWidget.prototype.getInputLength = function () {
16160 return this.$input[ 0 ].value.length;
16161 };
16162
16163 /**
16164 * Focus the input and select the entire text.
16165 *
16166 * @chainable
16167 */
16168 OO.ui.TextInputWidget.prototype.select = function () {
16169 return this.selectRange( 0, this.getInputLength() );
16170 };
16171
16172 /**
16173 * Focus the input and move the cursor to the start.
16174 *
16175 * @chainable
16176 */
16177 OO.ui.TextInputWidget.prototype.moveCursorToStart = function () {
16178 return this.selectRange( 0 );
16179 };
16180
16181 /**
16182 * Focus the input and move the cursor to the end.
16183 *
16184 * @chainable
16185 */
16186 OO.ui.TextInputWidget.prototype.moveCursorToEnd = function () {
16187 return this.selectRange( this.getInputLength() );
16188 };
16189
16190 /**
16191 * Set the validation pattern.
16192 *
16193 * The validation pattern is either a regular expression, a function, or the symbolic name of a
16194 * pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer' (the
16195 * value must contain only numbers).
16196 *
16197 * @param {RegExp|Function|string|null} validate Regular expression, function, or the symbolic name
16198 * of a pattern (either ‘integer’ or ‘non-empty’) defined by the class.
16199 */
16200 OO.ui.TextInputWidget.prototype.setValidation = function ( validate ) {
16201 if ( validate instanceof RegExp || validate instanceof Function ) {
16202 this.validate = validate;
16203 } else {
16204 this.validate = this.constructor.static.validationPatterns[ validate ] || /.*/;
16205 }
16206 };
16207
16208 /**
16209 * Sets the 'invalid' flag appropriately.
16210 *
16211 * @param {boolean} [isValid] Optionally override validation result
16212 */
16213 OO.ui.TextInputWidget.prototype.setValidityFlag = function ( isValid ) {
16214 var widget = this,
16215 setFlag = function ( valid ) {
16216 if ( !valid ) {
16217 widget.$input.attr( 'aria-invalid', 'true' );
16218 } else {
16219 widget.$input.removeAttr( 'aria-invalid' );
16220 }
16221 widget.setFlags( { invalid: !valid } );
16222 };
16223
16224 if ( isValid !== undefined ) {
16225 setFlag( isValid );
16226 } else {
16227 this.getValidity().then( function () {
16228 setFlag( true );
16229 }, function () {
16230 setFlag( false );
16231 } );
16232 }
16233 };
16234
16235 /**
16236 * Check if a value is valid.
16237 *
16238 * This method returns a promise that resolves with a boolean `true` if the current value is
16239 * considered valid according to the supplied {@link #validate validation pattern}.
16240 *
16241 * @deprecated
16242 * @return {jQuery.Promise} A promise that resolves to a boolean `true` if the value is valid.
16243 */
16244 OO.ui.TextInputWidget.prototype.isValid = function () {
16245 var result;
16246
16247 if ( this.validate instanceof Function ) {
16248 result = this.validate( this.getValue() );
16249 if ( $.isFunction( result.promise ) ) {
16250 return result.promise();
16251 } else {
16252 return $.Deferred().resolve( !!result ).promise();
16253 }
16254 } else {
16255 return $.Deferred().resolve( !!this.getValue().match( this.validate ) ).promise();
16256 }
16257 };
16258
16259 /**
16260 * Get the validity of current value.
16261 *
16262 * This method returns a promise that resolves if the value is valid and rejects if
16263 * it isn't. Uses the {@link #validate validation pattern} to check for validity.
16264 *
16265 * @return {jQuery.Promise} A promise that resolves if the value is valid, rejects if not.
16266 */
16267 OO.ui.TextInputWidget.prototype.getValidity = function () {
16268 var result, promise;
16269
16270 function rejectOrResolve( valid ) {
16271 if ( valid ) {
16272 return $.Deferred().resolve().promise();
16273 } else {
16274 return $.Deferred().reject().promise();
16275 }
16276 }
16277
16278 if ( this.validate instanceof Function ) {
16279 result = this.validate( this.getValue() );
16280
16281 if ( $.isFunction( result.promise ) ) {
16282 promise = $.Deferred();
16283
16284 result.then( function ( valid ) {
16285 if ( valid ) {
16286 promise.resolve();
16287 } else {
16288 promise.reject();
16289 }
16290 }, function () {
16291 promise.reject();
16292 } );
16293
16294 return promise.promise();
16295 } else {
16296 return rejectOrResolve( result );
16297 }
16298 } else {
16299 return rejectOrResolve( this.getValue().match( this.validate ) );
16300 }
16301 };
16302
16303 /**
16304 * Set the position of the inline label relative to that of the value: `‘before’` or `‘after’`.
16305 *
16306 * @param {string} labelPosition Label position, 'before' or 'after'
16307 * @chainable
16308 */
16309 OO.ui.TextInputWidget.prototype.setLabelPosition = function ( labelPosition ) {
16310 this.labelPosition = labelPosition;
16311 this.updatePosition();
16312 return this;
16313 };
16314
16315 /**
16316 * Deprecated alias of #setLabelPosition
16317 *
16318 * @deprecated Use setLabelPosition instead.
16319 */
16320 OO.ui.TextInputWidget.prototype.setPosition =
16321 OO.ui.TextInputWidget.prototype.setLabelPosition;
16322
16323 /**
16324 * Update the position of the inline label.
16325 *
16326 * This method is called by #setLabelPosition, and can also be called on its own if
16327 * something causes the label to be mispositioned.
16328 *
16329 * @chainable
16330 */
16331 OO.ui.TextInputWidget.prototype.updatePosition = function () {
16332 var after = this.labelPosition === 'after';
16333
16334 this.$element
16335 .toggleClass( 'oo-ui-textInputWidget-labelPosition-after', !!this.label && after )
16336 .toggleClass( 'oo-ui-textInputWidget-labelPosition-before', !!this.label && !after );
16337
16338 this.valCache = null;
16339 this.scrollWidth = null;
16340 this.adjustSize();
16341 this.positionLabel();
16342
16343 return this;
16344 };
16345
16346 /**
16347 * Update the 'clear' indicator displayed on type: 'search' text fields, hiding it when the field is
16348 * already empty or when it's not editable.
16349 */
16350 OO.ui.TextInputWidget.prototype.updateSearchIndicator = function () {
16351 if ( this.type === 'search' ) {
16352 if ( this.getValue() === '' || this.isDisabled() || this.isReadOnly() ) {
16353 this.setIndicator( null );
16354 } else {
16355 this.setIndicator( 'clear' );
16356 }
16357 }
16358 };
16359
16360 /**
16361 * Position the label by setting the correct padding on the input.
16362 *
16363 * @private
16364 * @chainable
16365 */
16366 OO.ui.TextInputWidget.prototype.positionLabel = function () {
16367 var after, rtl, property;
16368 // Clear old values
16369 this.$input
16370 // Clear old values if present
16371 .css( {
16372 'padding-right': '',
16373 'padding-left': ''
16374 } );
16375
16376 if ( this.label ) {
16377 this.$element.append( this.$label );
16378 } else {
16379 this.$label.detach();
16380 return;
16381 }
16382
16383 after = this.labelPosition === 'after';
16384 rtl = this.$element.css( 'direction' ) === 'rtl';
16385 property = after === rtl ? 'padding-left' : 'padding-right';
16386
16387 this.$input.css( property, this.$label.outerWidth( true ) + ( after ? this.scrollWidth : 0 ) );
16388
16389 return this;
16390 };
16391
16392 /**
16393 * @inheritdoc
16394 */
16395 OO.ui.TextInputWidget.prototype.restorePreInfuseState = function ( state ) {
16396 OO.ui.TextInputWidget.parent.prototype.restorePreInfuseState.call( this, state );
16397 if ( state.scrollTop !== undefined ) {
16398 this.$input.scrollTop( state.scrollTop );
16399 }
16400 };
16401
16402 /**
16403 * ComboBoxInputWidgets combine a {@link OO.ui.TextInputWidget text input} (where a value
16404 * can be entered manually) and a {@link OO.ui.MenuSelectWidget menu of options} (from which
16405 * a value can be chosen instead). Users can choose options from the combo box in one of two ways:
16406 *
16407 * - by typing a value in the text input field. If the value exactly matches the value of a menu
16408 * option, that option will appear to be selected.
16409 * - by choosing a value from the menu. The value of the chosen option will then appear in the text
16410 * input field.
16411 *
16412 * This widget can be used inside a HTML form, such as a OO.ui.FormLayout.
16413 *
16414 * For more information about menus and options, please see the [OOjs UI documentation on MediaWiki][1].
16415 *
16416 * @example
16417 * // Example: A ComboBoxInputWidget.
16418 * var comboBox = new OO.ui.ComboBoxInputWidget( {
16419 * label: 'ComboBoxInputWidget',
16420 * value: 'Option 1',
16421 * menu: {
16422 * items: [
16423 * new OO.ui.MenuOptionWidget( {
16424 * data: 'Option 1',
16425 * label: 'Option One'
16426 * } ),
16427 * new OO.ui.MenuOptionWidget( {
16428 * data: 'Option 2',
16429 * label: 'Option Two'
16430 * } ),
16431 * new OO.ui.MenuOptionWidget( {
16432 * data: 'Option 3',
16433 * label: 'Option Three'
16434 * } ),
16435 * new OO.ui.MenuOptionWidget( {
16436 * data: 'Option 4',
16437 * label: 'Option Four'
16438 * } ),
16439 * new OO.ui.MenuOptionWidget( {
16440 * data: 'Option 5',
16441 * label: 'Option Five'
16442 * } )
16443 * ]
16444 * }
16445 * } );
16446 * $( 'body' ).append( comboBox.$element );
16447 *
16448 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
16449 *
16450 * @class
16451 * @extends OO.ui.TextInputWidget
16452 *
16453 * @constructor
16454 * @param {Object} [config] Configuration options
16455 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
16456 * @cfg {Object} [menu] Configuration options to pass to the {@link OO.ui.FloatingMenuSelectWidget menu select widget}.
16457 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
16458 * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
16459 * containing `<div>` and has a larger area. By default, the menu uses relative positioning.
16460 */
16461 OO.ui.ComboBoxInputWidget = function OoUiComboBoxInputWidget( config ) {
16462 // Configuration initialization
16463 config = $.extend( {
16464 indicator: 'down'
16465 }, config );
16466 // For backwards-compatibility with ComboBoxWidget config
16467 $.extend( config, config.input );
16468
16469 // Parent constructor
16470 OO.ui.ComboBoxInputWidget.parent.call( this, config );
16471
16472 // Properties
16473 this.$overlay = config.$overlay || this.$element;
16474 this.menu = new OO.ui.FloatingMenuSelectWidget( $.extend(
16475 {
16476 widget: this,
16477 input: this,
16478 $container: this.$element,
16479 disabled: this.isDisabled()
16480 },
16481 config.menu
16482 ) );
16483 // For backwards-compatibility with ComboBoxWidget
16484 this.input = this;
16485
16486 // Events
16487 this.$indicator.on( {
16488 click: this.onIndicatorClick.bind( this ),
16489 keypress: this.onIndicatorKeyPress.bind( this )
16490 } );
16491 this.connect( this, {
16492 change: 'onInputChange',
16493 enter: 'onInputEnter'
16494 } );
16495 this.menu.connect( this, {
16496 choose: 'onMenuChoose',
16497 add: 'onMenuItemsChange',
16498 remove: 'onMenuItemsChange'
16499 } );
16500
16501 // Initialization
16502 this.$input.attr( {
16503 role: 'combobox',
16504 'aria-autocomplete': 'list'
16505 } );
16506 // Do not override options set via config.menu.items
16507 if ( config.options !== undefined ) {
16508 this.setOptions( config.options );
16509 }
16510 // Extra class for backwards-compatibility with ComboBoxWidget
16511 this.$element.addClass( 'oo-ui-comboBoxInputWidget oo-ui-comboBoxWidget' );
16512 this.$overlay.append( this.menu.$element );
16513 this.onMenuItemsChange();
16514 };
16515
16516 /* Setup */
16517
16518 OO.inheritClass( OO.ui.ComboBoxInputWidget, OO.ui.TextInputWidget );
16519
16520 /* Methods */
16521
16522 /**
16523 * Get the combobox's menu.
16524 * @return {OO.ui.FloatingMenuSelectWidget} Menu widget
16525 */
16526 OO.ui.ComboBoxInputWidget.prototype.getMenu = function () {
16527 return this.menu;
16528 };
16529
16530 /**
16531 * Get the combobox's text input widget.
16532 * @return {OO.ui.TextInputWidget} Text input widget
16533 */
16534 OO.ui.ComboBoxInputWidget.prototype.getInput = function () {
16535 return this;
16536 };
16537
16538 /**
16539 * Handle input change events.
16540 *
16541 * @private
16542 * @param {string} value New value
16543 */
16544 OO.ui.ComboBoxInputWidget.prototype.onInputChange = function ( value ) {
16545 var match = this.menu.getItemFromData( value );
16546
16547 this.menu.selectItem( match );
16548 if ( this.menu.getHighlightedItem() ) {
16549 this.menu.highlightItem( match );
16550 }
16551
16552 if ( !this.isDisabled() ) {
16553 this.menu.toggle( true );
16554 }
16555 };
16556
16557 /**
16558 * Handle mouse click events.
16559 *
16560 * @private
16561 * @param {jQuery.Event} e Mouse click event
16562 */
16563 OO.ui.ComboBoxInputWidget.prototype.onIndicatorClick = function ( e ) {
16564 if ( !this.isDisabled() && e.which === 1 ) {
16565 this.menu.toggle();
16566 this.$input[ 0 ].focus();
16567 }
16568 return false;
16569 };
16570
16571 /**
16572 * Handle key press events.
16573 *
16574 * @private
16575 * @param {jQuery.Event} e Key press event
16576 */
16577 OO.ui.ComboBoxInputWidget.prototype.onIndicatorKeyPress = function ( e ) {
16578 if ( !this.isDisabled() && ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER ) ) {
16579 this.menu.toggle();
16580 this.$input[ 0 ].focus();
16581 return false;
16582 }
16583 };
16584
16585 /**
16586 * Handle input enter events.
16587 *
16588 * @private
16589 */
16590 OO.ui.ComboBoxInputWidget.prototype.onInputEnter = function () {
16591 if ( !this.isDisabled() ) {
16592 this.menu.toggle( false );
16593 }
16594 };
16595
16596 /**
16597 * Handle menu choose events.
16598 *
16599 * @private
16600 * @param {OO.ui.OptionWidget} item Chosen item
16601 */
16602 OO.ui.ComboBoxInputWidget.prototype.onMenuChoose = function ( item ) {
16603 this.setValue( item.getData() );
16604 };
16605
16606 /**
16607 * Handle menu item change events.
16608 *
16609 * @private
16610 */
16611 OO.ui.ComboBoxInputWidget.prototype.onMenuItemsChange = function () {
16612 var match = this.menu.getItemFromData( this.getValue() );
16613 this.menu.selectItem( match );
16614 if ( this.menu.getHighlightedItem() ) {
16615 this.menu.highlightItem( match );
16616 }
16617 this.$element.toggleClass( 'oo-ui-comboBoxInputWidget-empty', this.menu.isEmpty() );
16618 };
16619
16620 /**
16621 * @inheritdoc
16622 */
16623 OO.ui.ComboBoxInputWidget.prototype.setDisabled = function ( disabled ) {
16624 // Parent method
16625 OO.ui.ComboBoxInputWidget.parent.prototype.setDisabled.call( this, disabled );
16626
16627 if ( this.menu ) {
16628 this.menu.setDisabled( this.isDisabled() );
16629 }
16630
16631 return this;
16632 };
16633
16634 /**
16635 * Set the options available for this input.
16636 *
16637 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
16638 * @chainable
16639 */
16640 OO.ui.ComboBoxInputWidget.prototype.setOptions = function ( options ) {
16641 this.getMenu()
16642 .clearItems()
16643 .addItems( options.map( function ( opt ) {
16644 return new OO.ui.MenuOptionWidget( {
16645 data: opt.data,
16646 label: opt.label !== undefined ? opt.label : opt.data
16647 } );
16648 } ) );
16649
16650 return this;
16651 };
16652
16653 /**
16654 * @class
16655 * @deprecated Use OO.ui.ComboBoxInputWidget instead.
16656 */
16657 OO.ui.ComboBoxWidget = OO.ui.ComboBoxInputWidget;
16658
16659 /**
16660 * LabelWidgets help identify the function of interface elements. Each LabelWidget can
16661 * be configured with a `label` option that is set to a string, a label node, or a function:
16662 *
16663 * - String: a plaintext string
16664 * - jQuery selection: a jQuery selection, used for anything other than a plaintext label, e.g., a
16665 * label that includes a link or special styling, such as a gray color or additional graphical elements.
16666 * - Function: a function that will produce a string in the future. Functions are used
16667 * in cases where the value of the label is not currently defined.
16668 *
16669 * In addition, the LabelWidget can be associated with an {@link OO.ui.InputWidget input widget}, which
16670 * will come into focus when the label is clicked.
16671 *
16672 * @example
16673 * // Examples of LabelWidgets
16674 * var label1 = new OO.ui.LabelWidget( {
16675 * label: 'plaintext label'
16676 * } );
16677 * var label2 = new OO.ui.LabelWidget( {
16678 * label: $( '<a href="default.html">jQuery label</a>' )
16679 * } );
16680 * // Create a fieldset layout with fields for each example
16681 * var fieldset = new OO.ui.FieldsetLayout();
16682 * fieldset.addItems( [
16683 * new OO.ui.FieldLayout( label1 ),
16684 * new OO.ui.FieldLayout( label2 )
16685 * ] );
16686 * $( 'body' ).append( fieldset.$element );
16687 *
16688 * @class
16689 * @extends OO.ui.Widget
16690 * @mixins OO.ui.mixin.LabelElement
16691 *
16692 * @constructor
16693 * @param {Object} [config] Configuration options
16694 * @cfg {OO.ui.InputWidget} [input] {@link OO.ui.InputWidget Input widget} that uses the label.
16695 * Clicking the label will focus the specified input field.
16696 */
16697 OO.ui.LabelWidget = function OoUiLabelWidget( config ) {
16698 // Configuration initialization
16699 config = config || {};
16700
16701 // Parent constructor
16702 OO.ui.LabelWidget.parent.call( this, config );
16703
16704 // Mixin constructors
16705 OO.ui.mixin.LabelElement.call( this, $.extend( {}, config, { $label: this.$element } ) );
16706 OO.ui.mixin.TitledElement.call( this, config );
16707
16708 // Properties
16709 this.input = config.input;
16710
16711 // Events
16712 if ( this.input instanceof OO.ui.InputWidget ) {
16713 this.$element.on( 'click', this.onClick.bind( this ) );
16714 }
16715
16716 // Initialization
16717 this.$element.addClass( 'oo-ui-labelWidget' );
16718 };
16719
16720 /* Setup */
16721
16722 OO.inheritClass( OO.ui.LabelWidget, OO.ui.Widget );
16723 OO.mixinClass( OO.ui.LabelWidget, OO.ui.mixin.LabelElement );
16724 OO.mixinClass( OO.ui.LabelWidget, OO.ui.mixin.TitledElement );
16725
16726 /* Static Properties */
16727
16728 OO.ui.LabelWidget.static.tagName = 'span';
16729
16730 /* Methods */
16731
16732 /**
16733 * Handles label mouse click events.
16734 *
16735 * @private
16736 * @param {jQuery.Event} e Mouse click event
16737 */
16738 OO.ui.LabelWidget.prototype.onClick = function () {
16739 this.input.simulateLabelClick();
16740 return false;
16741 };
16742
16743 /**
16744 * OptionWidgets are special elements that can be selected and configured with data. The
16745 * data is often unique for each option, but it does not have to be. OptionWidgets are used
16746 * with OO.ui.SelectWidget to create a selection of mutually exclusive options. For more information
16747 * and examples, please see the [OOjs UI documentation on MediaWiki][1].
16748 *
16749 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
16750 *
16751 * @class
16752 * @extends OO.ui.Widget
16753 * @mixins OO.ui.mixin.LabelElement
16754 * @mixins OO.ui.mixin.FlaggedElement
16755 *
16756 * @constructor
16757 * @param {Object} [config] Configuration options
16758 */
16759 OO.ui.OptionWidget = function OoUiOptionWidget( config ) {
16760 // Configuration initialization
16761 config = config || {};
16762
16763 // Parent constructor
16764 OO.ui.OptionWidget.parent.call( this, config );
16765
16766 // Mixin constructors
16767 OO.ui.mixin.ItemWidget.call( this );
16768 OO.ui.mixin.LabelElement.call( this, config );
16769 OO.ui.mixin.FlaggedElement.call( this, config );
16770
16771 // Properties
16772 this.selected = false;
16773 this.highlighted = false;
16774 this.pressed = false;
16775
16776 // Initialization
16777 this.$element
16778 .data( 'oo-ui-optionWidget', this )
16779 .attr( 'role', 'option' )
16780 .attr( 'aria-selected', 'false' )
16781 .addClass( 'oo-ui-optionWidget' )
16782 .append( this.$label );
16783 };
16784
16785 /* Setup */
16786
16787 OO.inheritClass( OO.ui.OptionWidget, OO.ui.Widget );
16788 OO.mixinClass( OO.ui.OptionWidget, OO.ui.mixin.ItemWidget );
16789 OO.mixinClass( OO.ui.OptionWidget, OO.ui.mixin.LabelElement );
16790 OO.mixinClass( OO.ui.OptionWidget, OO.ui.mixin.FlaggedElement );
16791
16792 /* Static Properties */
16793
16794 OO.ui.OptionWidget.static.selectable = true;
16795
16796 OO.ui.OptionWidget.static.highlightable = true;
16797
16798 OO.ui.OptionWidget.static.pressable = true;
16799
16800 OO.ui.OptionWidget.static.scrollIntoViewOnSelect = false;
16801
16802 /* Methods */
16803
16804 /**
16805 * Check if the option can be selected.
16806 *
16807 * @return {boolean} Item is selectable
16808 */
16809 OO.ui.OptionWidget.prototype.isSelectable = function () {
16810 return this.constructor.static.selectable && !this.isDisabled() && this.isVisible();
16811 };
16812
16813 /**
16814 * Check if the option can be highlighted. A highlight indicates that the option
16815 * may be selected when a user presses enter or clicks. Disabled items cannot
16816 * be highlighted.
16817 *
16818 * @return {boolean} Item is highlightable
16819 */
16820 OO.ui.OptionWidget.prototype.isHighlightable = function () {
16821 return this.constructor.static.highlightable && !this.isDisabled() && this.isVisible();
16822 };
16823
16824 /**
16825 * Check if the option can be pressed. The pressed state occurs when a user mouses
16826 * down on an item, but has not yet let go of the mouse.
16827 *
16828 * @return {boolean} Item is pressable
16829 */
16830 OO.ui.OptionWidget.prototype.isPressable = function () {
16831 return this.constructor.static.pressable && !this.isDisabled() && this.isVisible();
16832 };
16833
16834 /**
16835 * Check if the option is selected.
16836 *
16837 * @return {boolean} Item is selected
16838 */
16839 OO.ui.OptionWidget.prototype.isSelected = function () {
16840 return this.selected;
16841 };
16842
16843 /**
16844 * Check if the option is highlighted. A highlight indicates that the
16845 * item may be selected when a user presses enter or clicks.
16846 *
16847 * @return {boolean} Item is highlighted
16848 */
16849 OO.ui.OptionWidget.prototype.isHighlighted = function () {
16850 return this.highlighted;
16851 };
16852
16853 /**
16854 * Check if the option is pressed. The pressed state occurs when a user mouses
16855 * down on an item, but has not yet let go of the mouse. The item may appear
16856 * selected, but it will not be selected until the user releases the mouse.
16857 *
16858 * @return {boolean} Item is pressed
16859 */
16860 OO.ui.OptionWidget.prototype.isPressed = function () {
16861 return this.pressed;
16862 };
16863
16864 /**
16865 * Set the option’s selected state. In general, all modifications to the selection
16866 * should be handled by the SelectWidget’s {@link OO.ui.SelectWidget#selectItem selectItem( [item] )}
16867 * method instead of this method.
16868 *
16869 * @param {boolean} [state=false] Select option
16870 * @chainable
16871 */
16872 OO.ui.OptionWidget.prototype.setSelected = function ( state ) {
16873 if ( this.constructor.static.selectable ) {
16874 this.selected = !!state;
16875 this.$element
16876 .toggleClass( 'oo-ui-optionWidget-selected', state )
16877 .attr( 'aria-selected', state.toString() );
16878 if ( state && this.constructor.static.scrollIntoViewOnSelect ) {
16879 this.scrollElementIntoView();
16880 }
16881 this.updateThemeClasses();
16882 }
16883 return this;
16884 };
16885
16886 /**
16887 * Set the option’s highlighted state. In general, all programmatic
16888 * modifications to the highlight should be handled by the
16889 * SelectWidget’s {@link OO.ui.SelectWidget#highlightItem highlightItem( [item] )}
16890 * method instead of this method.
16891 *
16892 * @param {boolean} [state=false] Highlight option
16893 * @chainable
16894 */
16895 OO.ui.OptionWidget.prototype.setHighlighted = function ( state ) {
16896 if ( this.constructor.static.highlightable ) {
16897 this.highlighted = !!state;
16898 this.$element.toggleClass( 'oo-ui-optionWidget-highlighted', state );
16899 this.updateThemeClasses();
16900 }
16901 return this;
16902 };
16903
16904 /**
16905 * Set the option’s pressed state. In general, all
16906 * programmatic modifications to the pressed state should be handled by the
16907 * SelectWidget’s {@link OO.ui.SelectWidget#pressItem pressItem( [item] )}
16908 * method instead of this method.
16909 *
16910 * @param {boolean} [state=false] Press option
16911 * @chainable
16912 */
16913 OO.ui.OptionWidget.prototype.setPressed = function ( state ) {
16914 if ( this.constructor.static.pressable ) {
16915 this.pressed = !!state;
16916 this.$element.toggleClass( 'oo-ui-optionWidget-pressed', state );
16917 this.updateThemeClasses();
16918 }
16919 return this;
16920 };
16921
16922 /**
16923 * DecoratedOptionWidgets are {@link OO.ui.OptionWidget options} that can be configured
16924 * with an {@link OO.ui.mixin.IconElement icon} and/or {@link OO.ui.mixin.IndicatorElement indicator}.
16925 * This class is used with OO.ui.SelectWidget to create a selection of mutually exclusive
16926 * options. For more information about options and selects, please see the
16927 * [OOjs UI documentation on MediaWiki][1].
16928 *
16929 * @example
16930 * // Decorated options in a select widget
16931 * var select = new OO.ui.SelectWidget( {
16932 * items: [
16933 * new OO.ui.DecoratedOptionWidget( {
16934 * data: 'a',
16935 * label: 'Option with icon',
16936 * icon: 'help'
16937 * } ),
16938 * new OO.ui.DecoratedOptionWidget( {
16939 * data: 'b',
16940 * label: 'Option with indicator',
16941 * indicator: 'next'
16942 * } )
16943 * ]
16944 * } );
16945 * $( 'body' ).append( select.$element );
16946 *
16947 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
16948 *
16949 * @class
16950 * @extends OO.ui.OptionWidget
16951 * @mixins OO.ui.mixin.IconElement
16952 * @mixins OO.ui.mixin.IndicatorElement
16953 *
16954 * @constructor
16955 * @param {Object} [config] Configuration options
16956 */
16957 OO.ui.DecoratedOptionWidget = function OoUiDecoratedOptionWidget( config ) {
16958 // Parent constructor
16959 OO.ui.DecoratedOptionWidget.parent.call( this, config );
16960
16961 // Mixin constructors
16962 OO.ui.mixin.IconElement.call( this, config );
16963 OO.ui.mixin.IndicatorElement.call( this, config );
16964
16965 // Initialization
16966 this.$element
16967 .addClass( 'oo-ui-decoratedOptionWidget' )
16968 .prepend( this.$icon )
16969 .append( this.$indicator );
16970 };
16971
16972 /* Setup */
16973
16974 OO.inheritClass( OO.ui.DecoratedOptionWidget, OO.ui.OptionWidget );
16975 OO.mixinClass( OO.ui.DecoratedOptionWidget, OO.ui.mixin.IconElement );
16976 OO.mixinClass( OO.ui.DecoratedOptionWidget, OO.ui.mixin.IndicatorElement );
16977
16978 /**
16979 * ButtonOptionWidget is a special type of {@link OO.ui.mixin.ButtonElement button element} that
16980 * can be selected and configured with data. The class is
16981 * used with OO.ui.ButtonSelectWidget to create a selection of button options. Please see the
16982 * [OOjs UI documentation on MediaWiki] [1] for more information.
16983 *
16984 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Button_selects_and_options
16985 *
16986 * @class
16987 * @extends OO.ui.DecoratedOptionWidget
16988 * @mixins OO.ui.mixin.ButtonElement
16989 * @mixins OO.ui.mixin.TabIndexedElement
16990 * @mixins OO.ui.mixin.TitledElement
16991 *
16992 * @constructor
16993 * @param {Object} [config] Configuration options
16994 */
16995 OO.ui.ButtonOptionWidget = function OoUiButtonOptionWidget( config ) {
16996 // Configuration initialization
16997 config = config || {};
16998
16999 // Parent constructor
17000 OO.ui.ButtonOptionWidget.parent.call( this, config );
17001
17002 // Mixin constructors
17003 OO.ui.mixin.ButtonElement.call( this, config );
17004 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$button } ) );
17005 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, {
17006 $tabIndexed: this.$button,
17007 tabIndex: -1
17008 } ) );
17009
17010 // Initialization
17011 this.$element.addClass( 'oo-ui-buttonOptionWidget' );
17012 this.$button.append( this.$element.contents() );
17013 this.$element.append( this.$button );
17014 };
17015
17016 /* Setup */
17017
17018 OO.inheritClass( OO.ui.ButtonOptionWidget, OO.ui.DecoratedOptionWidget );
17019 OO.mixinClass( OO.ui.ButtonOptionWidget, OO.ui.mixin.ButtonElement );
17020 OO.mixinClass( OO.ui.ButtonOptionWidget, OO.ui.mixin.TitledElement );
17021 OO.mixinClass( OO.ui.ButtonOptionWidget, OO.ui.mixin.TabIndexedElement );
17022
17023 /* Static Properties */
17024
17025 // Allow button mouse down events to pass through so they can be handled by the parent select widget
17026 OO.ui.ButtonOptionWidget.static.cancelButtonMouseDownEvents = false;
17027
17028 OO.ui.ButtonOptionWidget.static.highlightable = false;
17029
17030 /* Methods */
17031
17032 /**
17033 * @inheritdoc
17034 */
17035 OO.ui.ButtonOptionWidget.prototype.setSelected = function ( state ) {
17036 OO.ui.ButtonOptionWidget.parent.prototype.setSelected.call( this, state );
17037
17038 if ( this.constructor.static.selectable ) {
17039 this.setActive( state );
17040 }
17041
17042 return this;
17043 };
17044
17045 /**
17046 * RadioOptionWidget is an option widget that looks like a radio button.
17047 * The class is used with OO.ui.RadioSelectWidget to create a selection of radio options.
17048 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information.
17049 *
17050 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Button_selects_and_option
17051 *
17052 * @class
17053 * @extends OO.ui.OptionWidget
17054 *
17055 * @constructor
17056 * @param {Object} [config] Configuration options
17057 */
17058 OO.ui.RadioOptionWidget = function OoUiRadioOptionWidget( config ) {
17059 // Configuration initialization
17060 config = config || {};
17061
17062 // Properties (must be done before parent constructor which calls #setDisabled)
17063 this.radio = new OO.ui.RadioInputWidget( { value: config.data, tabIndex: -1 } );
17064
17065 // Parent constructor
17066 OO.ui.RadioOptionWidget.parent.call( this, config );
17067
17068 // Events
17069 this.radio.$input.on( 'focus', this.onInputFocus.bind( this ) );
17070
17071 // Initialization
17072 // Remove implicit role, we're handling it ourselves
17073 this.radio.$input.attr( 'role', 'presentation' );
17074 this.$element
17075 .addClass( 'oo-ui-radioOptionWidget' )
17076 .attr( 'role', 'radio' )
17077 .attr( 'aria-checked', 'false' )
17078 .removeAttr( 'aria-selected' )
17079 .prepend( this.radio.$element );
17080 };
17081
17082 /* Setup */
17083
17084 OO.inheritClass( OO.ui.RadioOptionWidget, OO.ui.OptionWidget );
17085
17086 /* Static Properties */
17087
17088 OO.ui.RadioOptionWidget.static.highlightable = false;
17089
17090 OO.ui.RadioOptionWidget.static.scrollIntoViewOnSelect = true;
17091
17092 OO.ui.RadioOptionWidget.static.pressable = false;
17093
17094 OO.ui.RadioOptionWidget.static.tagName = 'label';
17095
17096 /* Methods */
17097
17098 /**
17099 * @param {jQuery.Event} e Focus event
17100 * @private
17101 */
17102 OO.ui.RadioOptionWidget.prototype.onInputFocus = function () {
17103 this.radio.$input.blur();
17104 this.$element.parent().focus();
17105 };
17106
17107 /**
17108 * @inheritdoc
17109 */
17110 OO.ui.RadioOptionWidget.prototype.setSelected = function ( state ) {
17111 OO.ui.RadioOptionWidget.parent.prototype.setSelected.call( this, state );
17112
17113 this.radio.setSelected( state );
17114 this.$element
17115 .attr( 'aria-checked', state.toString() )
17116 .removeAttr( 'aria-selected' );
17117
17118 return this;
17119 };
17120
17121 /**
17122 * @inheritdoc
17123 */
17124 OO.ui.RadioOptionWidget.prototype.setDisabled = function ( disabled ) {
17125 OO.ui.RadioOptionWidget.parent.prototype.setDisabled.call( this, disabled );
17126
17127 this.radio.setDisabled( this.isDisabled() );
17128
17129 return this;
17130 };
17131
17132 /**
17133 * MenuOptionWidget is an option widget that looks like a menu item. The class is used with
17134 * OO.ui.MenuSelectWidget to create a menu of mutually exclusive options. Please see
17135 * the [OOjs UI documentation on MediaWiki] [1] for more information.
17136 *
17137 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
17138 *
17139 * @class
17140 * @extends OO.ui.DecoratedOptionWidget
17141 *
17142 * @constructor
17143 * @param {Object} [config] Configuration options
17144 */
17145 OO.ui.MenuOptionWidget = function OoUiMenuOptionWidget( config ) {
17146 // Configuration initialization
17147 config = $.extend( { icon: 'check' }, config );
17148
17149 // Parent constructor
17150 OO.ui.MenuOptionWidget.parent.call( this, config );
17151
17152 // Initialization
17153 this.$element
17154 .attr( 'role', 'menuitem' )
17155 .addClass( 'oo-ui-menuOptionWidget' );
17156 };
17157
17158 /* Setup */
17159
17160 OO.inheritClass( OO.ui.MenuOptionWidget, OO.ui.DecoratedOptionWidget );
17161
17162 /* Static Properties */
17163
17164 OO.ui.MenuOptionWidget.static.scrollIntoViewOnSelect = true;
17165
17166 /**
17167 * MenuSectionOptionWidgets are used inside {@link OO.ui.MenuSelectWidget menu select widgets} to group one or more related
17168 * {@link OO.ui.MenuOptionWidget menu options}. MenuSectionOptionWidgets cannot be highlighted or selected.
17169 *
17170 * @example
17171 * var myDropdown = new OO.ui.DropdownWidget( {
17172 * menu: {
17173 * items: [
17174 * new OO.ui.MenuSectionOptionWidget( {
17175 * label: 'Dogs'
17176 * } ),
17177 * new OO.ui.MenuOptionWidget( {
17178 * data: 'corgi',
17179 * label: 'Welsh Corgi'
17180 * } ),
17181 * new OO.ui.MenuOptionWidget( {
17182 * data: 'poodle',
17183 * label: 'Standard Poodle'
17184 * } ),
17185 * new OO.ui.MenuSectionOptionWidget( {
17186 * label: 'Cats'
17187 * } ),
17188 * new OO.ui.MenuOptionWidget( {
17189 * data: 'lion',
17190 * label: 'Lion'
17191 * } )
17192 * ]
17193 * }
17194 * } );
17195 * $( 'body' ).append( myDropdown.$element );
17196 *
17197 * @class
17198 * @extends OO.ui.DecoratedOptionWidget
17199 *
17200 * @constructor
17201 * @param {Object} [config] Configuration options
17202 */
17203 OO.ui.MenuSectionOptionWidget = function OoUiMenuSectionOptionWidget( config ) {
17204 // Parent constructor
17205 OO.ui.MenuSectionOptionWidget.parent.call( this, config );
17206
17207 // Initialization
17208 this.$element.addClass( 'oo-ui-menuSectionOptionWidget' );
17209 };
17210
17211 /* Setup */
17212
17213 OO.inheritClass( OO.ui.MenuSectionOptionWidget, OO.ui.DecoratedOptionWidget );
17214
17215 /* Static Properties */
17216
17217 OO.ui.MenuSectionOptionWidget.static.selectable = false;
17218
17219 OO.ui.MenuSectionOptionWidget.static.highlightable = false;
17220
17221 /**
17222 * OutlineOptionWidget is an item in an {@link OO.ui.OutlineSelectWidget OutlineSelectWidget}.
17223 *
17224 * Currently, this class is only used by {@link OO.ui.BookletLayout booklet layouts}, which contain
17225 * {@link OO.ui.PageLayout page layouts}. See {@link OO.ui.BookletLayout BookletLayout}
17226 * for an example.
17227 *
17228 * @class
17229 * @extends OO.ui.DecoratedOptionWidget
17230 *
17231 * @constructor
17232 * @param {Object} [config] Configuration options
17233 * @cfg {number} [level] Indentation level
17234 * @cfg {boolean} [movable] Allow modification from {@link OO.ui.OutlineControlsWidget outline controls}.
17235 */
17236 OO.ui.OutlineOptionWidget = function OoUiOutlineOptionWidget( config ) {
17237 // Configuration initialization
17238 config = config || {};
17239
17240 // Parent constructor
17241 OO.ui.OutlineOptionWidget.parent.call( this, config );
17242
17243 // Properties
17244 this.level = 0;
17245 this.movable = !!config.movable;
17246 this.removable = !!config.removable;
17247
17248 // Initialization
17249 this.$element.addClass( 'oo-ui-outlineOptionWidget' );
17250 this.setLevel( config.level );
17251 };
17252
17253 /* Setup */
17254
17255 OO.inheritClass( OO.ui.OutlineOptionWidget, OO.ui.DecoratedOptionWidget );
17256
17257 /* Static Properties */
17258
17259 OO.ui.OutlineOptionWidget.static.highlightable = false;
17260
17261 OO.ui.OutlineOptionWidget.static.scrollIntoViewOnSelect = true;
17262
17263 OO.ui.OutlineOptionWidget.static.levelClass = 'oo-ui-outlineOptionWidget-level-';
17264
17265 OO.ui.OutlineOptionWidget.static.levels = 3;
17266
17267 /* Methods */
17268
17269 /**
17270 * Check if item is movable.
17271 *
17272 * Movability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
17273 *
17274 * @return {boolean} Item is movable
17275 */
17276 OO.ui.OutlineOptionWidget.prototype.isMovable = function () {
17277 return this.movable;
17278 };
17279
17280 /**
17281 * Check if item is removable.
17282 *
17283 * Removability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
17284 *
17285 * @return {boolean} Item is removable
17286 */
17287 OO.ui.OutlineOptionWidget.prototype.isRemovable = function () {
17288 return this.removable;
17289 };
17290
17291 /**
17292 * Get indentation level.
17293 *
17294 * @return {number} Indentation level
17295 */
17296 OO.ui.OutlineOptionWidget.prototype.getLevel = function () {
17297 return this.level;
17298 };
17299
17300 /**
17301 * Set movability.
17302 *
17303 * Movability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
17304 *
17305 * @param {boolean} movable Item is movable
17306 * @chainable
17307 */
17308 OO.ui.OutlineOptionWidget.prototype.setMovable = function ( movable ) {
17309 this.movable = !!movable;
17310 this.updateThemeClasses();
17311 return this;
17312 };
17313
17314 /**
17315 * Set removability.
17316 *
17317 * Removability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
17318 *
17319 * @param {boolean} movable Item is removable
17320 * @chainable
17321 */
17322 OO.ui.OutlineOptionWidget.prototype.setRemovable = function ( removable ) {
17323 this.removable = !!removable;
17324 this.updateThemeClasses();
17325 return this;
17326 };
17327
17328 /**
17329 * Set indentation level.
17330 *
17331 * @param {number} [level=0] Indentation level, in the range of [0,#maxLevel]
17332 * @chainable
17333 */
17334 OO.ui.OutlineOptionWidget.prototype.setLevel = function ( level ) {
17335 var levels = this.constructor.static.levels,
17336 levelClass = this.constructor.static.levelClass,
17337 i = levels;
17338
17339 this.level = level ? Math.max( 0, Math.min( levels - 1, level ) ) : 0;
17340 while ( i-- ) {
17341 if ( this.level === i ) {
17342 this.$element.addClass( levelClass + i );
17343 } else {
17344 this.$element.removeClass( levelClass + i );
17345 }
17346 }
17347 this.updateThemeClasses();
17348
17349 return this;
17350 };
17351
17352 /**
17353 * TabOptionWidget is an item in a {@link OO.ui.TabSelectWidget TabSelectWidget}.
17354 *
17355 * Currently, this class is only used by {@link OO.ui.IndexLayout index layouts}, which contain
17356 * {@link OO.ui.CardLayout card layouts}. See {@link OO.ui.IndexLayout IndexLayout}
17357 * for an example.
17358 *
17359 * @class
17360 * @extends OO.ui.OptionWidget
17361 *
17362 * @constructor
17363 * @param {Object} [config] Configuration options
17364 */
17365 OO.ui.TabOptionWidget = function OoUiTabOptionWidget( config ) {
17366 // Configuration initialization
17367 config = config || {};
17368
17369 // Parent constructor
17370 OO.ui.TabOptionWidget.parent.call( this, config );
17371
17372 // Initialization
17373 this.$element.addClass( 'oo-ui-tabOptionWidget' );
17374 };
17375
17376 /* Setup */
17377
17378 OO.inheritClass( OO.ui.TabOptionWidget, OO.ui.OptionWidget );
17379
17380 /* Static Properties */
17381
17382 OO.ui.TabOptionWidget.static.highlightable = false;
17383
17384 /**
17385 * PopupWidget is a container for content. The popup is overlaid and positioned absolutely.
17386 * By default, each popup has an anchor that points toward its origin.
17387 * Please see the [OOjs UI documentation on Mediawiki] [1] for more information and examples.
17388 *
17389 * @example
17390 * // A popup widget.
17391 * var popup = new OO.ui.PopupWidget( {
17392 * $content: $( '<p>Hi there!</p>' ),
17393 * padded: true,
17394 * width: 300
17395 * } );
17396 *
17397 * $( 'body' ).append( popup.$element );
17398 * // To display the popup, toggle the visibility to 'true'.
17399 * popup.toggle( true );
17400 *
17401 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups
17402 *
17403 * @class
17404 * @extends OO.ui.Widget
17405 * @mixins OO.ui.mixin.LabelElement
17406 * @mixins OO.ui.mixin.ClippableElement
17407 *
17408 * @constructor
17409 * @param {Object} [config] Configuration options
17410 * @cfg {number} [width=320] Width of popup in pixels
17411 * @cfg {number} [height] Height of popup in pixels. Omit to use the automatic height.
17412 * @cfg {boolean} [anchor=true] Show anchor pointing to origin of popup
17413 * @cfg {string} [align='center'] Alignment of the popup: `center`, `force-left`, `force-right`, `backwards` or `forwards`.
17414 * If the popup is forced-left the popup body is leaning towards the left. For force-right alignment, the body of the
17415 * popup is leaning towards the right of the screen.
17416 * Using 'backwards' is a logical direction which will result in the popup leaning towards the beginning of the sentence
17417 * in the given language, which means it will flip to the correct positioning in right-to-left languages.
17418 * Using 'forward' will also result in a logical alignment where the body of the popup leans towards the end of the
17419 * sentence in the given language.
17420 * @cfg {jQuery} [$container] Constrain the popup to the boundaries of the specified container.
17421 * See the [OOjs UI docs on MediaWiki][3] for an example.
17422 * [3]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups#containerExample
17423 * @cfg {number} [containerPadding=10] Padding between the popup and its container, specified as a number of pixels.
17424 * @cfg {jQuery} [$content] Content to append to the popup's body
17425 * @cfg {jQuery} [$footer] Content to append to the popup's footer
17426 * @cfg {boolean} [autoClose=false] Automatically close the popup when it loses focus.
17427 * @cfg {jQuery} [$autoCloseIgnore] Elements that will not close the popup when clicked.
17428 * This config option is only relevant if #autoClose is set to `true`. See the [OOjs UI docs on MediaWiki][2]
17429 * for an example.
17430 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups#autocloseExample
17431 * @cfg {boolean} [head] Show a popup header that contains a #label (if specified) and close
17432 * button.
17433 * @cfg {boolean} [padded] Add padding to the popup's body
17434 */
17435 OO.ui.PopupWidget = function OoUiPopupWidget( config ) {
17436 // Configuration initialization
17437 config = config || {};
17438
17439 // Parent constructor
17440 OO.ui.PopupWidget.parent.call( this, config );
17441
17442 // Properties (must be set before ClippableElement constructor call)
17443 this.$body = $( '<div>' );
17444 this.$popup = $( '<div>' );
17445
17446 // Mixin constructors
17447 OO.ui.mixin.LabelElement.call( this, config );
17448 OO.ui.mixin.ClippableElement.call( this, $.extend( {}, config, {
17449 $clippable: this.$body,
17450 $clippableContainer: this.$popup
17451 } ) );
17452
17453 // Properties
17454 this.$head = $( '<div>' );
17455 this.$footer = $( '<div>' );
17456 this.$anchor = $( '<div>' );
17457 // If undefined, will be computed lazily in updateDimensions()
17458 this.$container = config.$container;
17459 this.containerPadding = config.containerPadding !== undefined ? config.containerPadding : 10;
17460 this.autoClose = !!config.autoClose;
17461 this.$autoCloseIgnore = config.$autoCloseIgnore;
17462 this.transitionTimeout = null;
17463 this.anchor = null;
17464 this.width = config.width !== undefined ? config.width : 320;
17465 this.height = config.height !== undefined ? config.height : null;
17466 this.setAlignment( config.align );
17467 this.closeButton = new OO.ui.ButtonWidget( { framed: false, icon: 'close' } );
17468 this.onMouseDownHandler = this.onMouseDown.bind( this );
17469 this.onDocumentKeyDownHandler = this.onDocumentKeyDown.bind( this );
17470
17471 // Events
17472 this.closeButton.connect( this, { click: 'onCloseButtonClick' } );
17473
17474 // Initialization
17475 this.toggleAnchor( config.anchor === undefined || config.anchor );
17476 this.$body.addClass( 'oo-ui-popupWidget-body' );
17477 this.$anchor.addClass( 'oo-ui-popupWidget-anchor' );
17478 this.$head
17479 .addClass( 'oo-ui-popupWidget-head' )
17480 .append( this.$label, this.closeButton.$element );
17481 this.$footer.addClass( 'oo-ui-popupWidget-footer' );
17482 if ( !config.head ) {
17483 this.$head.addClass( 'oo-ui-element-hidden' );
17484 }
17485 if ( !config.$footer ) {
17486 this.$footer.addClass( 'oo-ui-element-hidden' );
17487 }
17488 this.$popup
17489 .addClass( 'oo-ui-popupWidget-popup' )
17490 .append( this.$head, this.$body, this.$footer );
17491 this.$element
17492 .addClass( 'oo-ui-popupWidget' )
17493 .append( this.$popup, this.$anchor );
17494 // Move content, which was added to #$element by OO.ui.Widget, to the body
17495 if ( config.$content instanceof jQuery ) {
17496 this.$body.append( config.$content );
17497 }
17498 if ( config.$footer instanceof jQuery ) {
17499 this.$footer.append( config.$footer );
17500 }
17501 if ( config.padded ) {
17502 this.$body.addClass( 'oo-ui-popupWidget-body-padded' );
17503 }
17504
17505 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
17506 // that reference properties not initialized at that time of parent class construction
17507 // TODO: Find a better way to handle post-constructor setup
17508 this.visible = false;
17509 this.$element.addClass( 'oo-ui-element-hidden' );
17510 };
17511
17512 /* Setup */
17513
17514 OO.inheritClass( OO.ui.PopupWidget, OO.ui.Widget );
17515 OO.mixinClass( OO.ui.PopupWidget, OO.ui.mixin.LabelElement );
17516 OO.mixinClass( OO.ui.PopupWidget, OO.ui.mixin.ClippableElement );
17517
17518 /* Methods */
17519
17520 /**
17521 * Handles mouse down events.
17522 *
17523 * @private
17524 * @param {MouseEvent} e Mouse down event
17525 */
17526 OO.ui.PopupWidget.prototype.onMouseDown = function ( e ) {
17527 if (
17528 this.isVisible() &&
17529 !$.contains( this.$element[ 0 ], e.target ) &&
17530 ( !this.$autoCloseIgnore || !this.$autoCloseIgnore.has( e.target ).length )
17531 ) {
17532 this.toggle( false );
17533 }
17534 };
17535
17536 /**
17537 * Bind mouse down listener.
17538 *
17539 * @private
17540 */
17541 OO.ui.PopupWidget.prototype.bindMouseDownListener = function () {
17542 // Capture clicks outside popup
17543 OO.ui.addCaptureEventListener( this.getElementWindow(), 'mousedown', this.onMouseDownHandler );
17544 };
17545
17546 /**
17547 * Handles close button click events.
17548 *
17549 * @private
17550 */
17551 OO.ui.PopupWidget.prototype.onCloseButtonClick = function () {
17552 if ( this.isVisible() ) {
17553 this.toggle( false );
17554 }
17555 };
17556
17557 /**
17558 * Unbind mouse down listener.
17559 *
17560 * @private
17561 */
17562 OO.ui.PopupWidget.prototype.unbindMouseDownListener = function () {
17563 OO.ui.removeCaptureEventListener( this.getElementWindow(), 'mousedown', this.onMouseDownHandler );
17564 };
17565
17566 /**
17567 * Handles key down events.
17568 *
17569 * @private
17570 * @param {KeyboardEvent} e Key down event
17571 */
17572 OO.ui.PopupWidget.prototype.onDocumentKeyDown = function ( e ) {
17573 if (
17574 e.which === OO.ui.Keys.ESCAPE &&
17575 this.isVisible()
17576 ) {
17577 this.toggle( false );
17578 e.preventDefault();
17579 e.stopPropagation();
17580 }
17581 };
17582
17583 /**
17584 * Bind key down listener.
17585 *
17586 * @private
17587 */
17588 OO.ui.PopupWidget.prototype.bindKeyDownListener = function () {
17589 OO.ui.addCaptureEventListener( this.getElementWindow(), 'keydown', this.onDocumentKeyDownHandler );
17590 };
17591
17592 /**
17593 * Unbind key down listener.
17594 *
17595 * @private
17596 */
17597 OO.ui.PopupWidget.prototype.unbindKeyDownListener = function () {
17598 OO.ui.removeCaptureEventListener( this.getElementWindow(), 'keydown', this.onDocumentKeyDownHandler );
17599 };
17600
17601 /**
17602 * Show, hide, or toggle the visibility of the anchor.
17603 *
17604 * @param {boolean} [show] Show anchor, omit to toggle
17605 */
17606 OO.ui.PopupWidget.prototype.toggleAnchor = function ( show ) {
17607 show = show === undefined ? !this.anchored : !!show;
17608
17609 if ( this.anchored !== show ) {
17610 if ( show ) {
17611 this.$element.addClass( 'oo-ui-popupWidget-anchored' );
17612 } else {
17613 this.$element.removeClass( 'oo-ui-popupWidget-anchored' );
17614 }
17615 this.anchored = show;
17616 }
17617 };
17618
17619 /**
17620 * Check if the anchor is visible.
17621 *
17622 * @return {boolean} Anchor is visible
17623 */
17624 OO.ui.PopupWidget.prototype.hasAnchor = function () {
17625 return this.anchor;
17626 };
17627
17628 /**
17629 * @inheritdoc
17630 */
17631 OO.ui.PopupWidget.prototype.toggle = function ( show ) {
17632 var change;
17633 show = show === undefined ? !this.isVisible() : !!show;
17634
17635 change = show !== this.isVisible();
17636
17637 // Parent method
17638 OO.ui.PopupWidget.parent.prototype.toggle.call( this, show );
17639
17640 if ( change ) {
17641 if ( show ) {
17642 if ( this.autoClose ) {
17643 this.bindMouseDownListener();
17644 this.bindKeyDownListener();
17645 }
17646 this.updateDimensions();
17647 this.toggleClipping( true );
17648 } else {
17649 this.toggleClipping( false );
17650 if ( this.autoClose ) {
17651 this.unbindMouseDownListener();
17652 this.unbindKeyDownListener();
17653 }
17654 }
17655 }
17656
17657 return this;
17658 };
17659
17660 /**
17661 * Set the size of the popup.
17662 *
17663 * Changing the size may also change the popup's position depending on the alignment.
17664 *
17665 * @param {number} width Width in pixels
17666 * @param {number} height Height in pixels
17667 * @param {boolean} [transition=false] Use a smooth transition
17668 * @chainable
17669 */
17670 OO.ui.PopupWidget.prototype.setSize = function ( width, height, transition ) {
17671 this.width = width;
17672 this.height = height !== undefined ? height : null;
17673 if ( this.isVisible() ) {
17674 this.updateDimensions( transition );
17675 }
17676 };
17677
17678 /**
17679 * Update the size and position.
17680 *
17681 * Only use this to keep the popup properly anchored. Use #setSize to change the size, and this will
17682 * be called automatically.
17683 *
17684 * @param {boolean} [transition=false] Use a smooth transition
17685 * @chainable
17686 */
17687 OO.ui.PopupWidget.prototype.updateDimensions = function ( transition ) {
17688 var popupOffset, originOffset, containerLeft, containerWidth, containerRight,
17689 popupLeft, popupRight, overlapLeft, overlapRight, anchorWidth,
17690 align = this.align,
17691 widget = this;
17692
17693 if ( !this.$container ) {
17694 // Lazy-initialize $container if not specified in constructor
17695 this.$container = $( this.getClosestScrollableElementContainer() );
17696 }
17697
17698 // Set height and width before measuring things, since it might cause our measurements
17699 // to change (e.g. due to scrollbars appearing or disappearing)
17700 this.$popup.css( {
17701 width: this.width,
17702 height: this.height !== null ? this.height : 'auto'
17703 } );
17704
17705 // If we are in RTL, we need to flip the alignment, unless it is center
17706 if ( align === 'forwards' || align === 'backwards' ) {
17707 if ( this.$container.css( 'direction' ) === 'rtl' ) {
17708 align = ( { forwards: 'force-left', backwards: 'force-right' } )[ this.align ];
17709 } else {
17710 align = ( { forwards: 'force-right', backwards: 'force-left' } )[ this.align ];
17711 }
17712
17713 }
17714
17715 // Compute initial popupOffset based on alignment
17716 popupOffset = this.width * ( { 'force-left': -1, center: -0.5, 'force-right': 0 } )[ align ];
17717
17718 // Figure out if this will cause the popup to go beyond the edge of the container
17719 originOffset = this.$element.offset().left;
17720 containerLeft = this.$container.offset().left;
17721 containerWidth = this.$container.innerWidth();
17722 containerRight = containerLeft + containerWidth;
17723 popupLeft = popupOffset - this.containerPadding;
17724 popupRight = popupOffset + this.containerPadding + this.width + this.containerPadding;
17725 overlapLeft = ( originOffset + popupLeft ) - containerLeft;
17726 overlapRight = containerRight - ( originOffset + popupRight );
17727
17728 // Adjust offset to make the popup not go beyond the edge, if needed
17729 if ( overlapRight < 0 ) {
17730 popupOffset += overlapRight;
17731 } else if ( overlapLeft < 0 ) {
17732 popupOffset -= overlapLeft;
17733 }
17734
17735 // Adjust offset to avoid anchor being rendered too close to the edge
17736 // $anchor.width() doesn't work with the pure CSS anchor (returns 0)
17737 // TODO: Find a measurement that works for CSS anchors and image anchors
17738 anchorWidth = this.$anchor[ 0 ].scrollWidth * 2;
17739 if ( popupOffset + this.width < anchorWidth ) {
17740 popupOffset = anchorWidth - this.width;
17741 } else if ( -popupOffset < anchorWidth ) {
17742 popupOffset = -anchorWidth;
17743 }
17744
17745 // Prevent transition from being interrupted
17746 clearTimeout( this.transitionTimeout );
17747 if ( transition ) {
17748 // Enable transition
17749 this.$element.addClass( 'oo-ui-popupWidget-transitioning' );
17750 }
17751
17752 // Position body relative to anchor
17753 this.$popup.css( 'margin-left', popupOffset );
17754
17755 if ( transition ) {
17756 // Prevent transitioning after transition is complete
17757 this.transitionTimeout = setTimeout( function () {
17758 widget.$element.removeClass( 'oo-ui-popupWidget-transitioning' );
17759 }, 200 );
17760 } else {
17761 // Prevent transitioning immediately
17762 this.$element.removeClass( 'oo-ui-popupWidget-transitioning' );
17763 }
17764
17765 // Reevaluate clipping state since we've relocated and resized the popup
17766 this.clip();
17767
17768 return this;
17769 };
17770
17771 /**
17772 * Set popup alignment
17773 * @param {string} align Alignment of the popup, `center`, `force-left`, `force-right`,
17774 * `backwards` or `forwards`.
17775 */
17776 OO.ui.PopupWidget.prototype.setAlignment = function ( align ) {
17777 // Validate alignment and transform deprecated values
17778 if ( [ 'left', 'right', 'force-left', 'force-right', 'backwards', 'forwards', 'center' ].indexOf( align ) > -1 ) {
17779 this.align = { left: 'force-right', right: 'force-left' }[ align ] || align;
17780 } else {
17781 this.align = 'center';
17782 }
17783 };
17784
17785 /**
17786 * Get popup alignment
17787 * @return {string} align Alignment of the popup, `center`, `force-left`, `force-right`,
17788 * `backwards` or `forwards`.
17789 */
17790 OO.ui.PopupWidget.prototype.getAlignment = function () {
17791 return this.align;
17792 };
17793
17794 /**
17795 * Progress bars visually display the status of an operation, such as a download,
17796 * and can be either determinate or indeterminate:
17797 *
17798 * - **determinate** process bars show the percent of an operation that is complete.
17799 *
17800 * - **indeterminate** process bars use a visual display of motion to indicate that an operation
17801 * is taking place. Because the extent of an indeterminate operation is unknown, the bar does
17802 * not use percentages.
17803 *
17804 * The value of the `progress` configuration determines whether the bar is determinate or indeterminate.
17805 *
17806 * @example
17807 * // Examples of determinate and indeterminate progress bars.
17808 * var progressBar1 = new OO.ui.ProgressBarWidget( {
17809 * progress: 33
17810 * } );
17811 * var progressBar2 = new OO.ui.ProgressBarWidget();
17812 *
17813 * // Create a FieldsetLayout to layout progress bars
17814 * var fieldset = new OO.ui.FieldsetLayout;
17815 * fieldset.addItems( [
17816 * new OO.ui.FieldLayout( progressBar1, {label: 'Determinate', align: 'top'}),
17817 * new OO.ui.FieldLayout( progressBar2, {label: 'Indeterminate', align: 'top'})
17818 * ] );
17819 * $( 'body' ).append( fieldset.$element );
17820 *
17821 * @class
17822 * @extends OO.ui.Widget
17823 *
17824 * @constructor
17825 * @param {Object} [config] Configuration options
17826 * @cfg {number|boolean} [progress=false] The type of progress bar (determinate or indeterminate).
17827 * To create a determinate progress bar, specify a number that reflects the initial percent complete.
17828 * By default, the progress bar is indeterminate.
17829 */
17830 OO.ui.ProgressBarWidget = function OoUiProgressBarWidget( config ) {
17831 // Configuration initialization
17832 config = config || {};
17833
17834 // Parent constructor
17835 OO.ui.ProgressBarWidget.parent.call( this, config );
17836
17837 // Properties
17838 this.$bar = $( '<div>' );
17839 this.progress = null;
17840
17841 // Initialization
17842 this.setProgress( config.progress !== undefined ? config.progress : false );
17843 this.$bar.addClass( 'oo-ui-progressBarWidget-bar' );
17844 this.$element
17845 .attr( {
17846 role: 'progressbar',
17847 'aria-valuemin': 0,
17848 'aria-valuemax': 100
17849 } )
17850 .addClass( 'oo-ui-progressBarWidget' )
17851 .append( this.$bar );
17852 };
17853
17854 /* Setup */
17855
17856 OO.inheritClass( OO.ui.ProgressBarWidget, OO.ui.Widget );
17857
17858 /* Static Properties */
17859
17860 OO.ui.ProgressBarWidget.static.tagName = 'div';
17861
17862 /* Methods */
17863
17864 /**
17865 * Get the percent of the progress that has been completed. Indeterminate progresses will return `false`.
17866 *
17867 * @return {number|boolean} Progress percent
17868 */
17869 OO.ui.ProgressBarWidget.prototype.getProgress = function () {
17870 return this.progress;
17871 };
17872
17873 /**
17874 * Set the percent of the process completed or `false` for an indeterminate process.
17875 *
17876 * @param {number|boolean} progress Progress percent or `false` for indeterminate
17877 */
17878 OO.ui.ProgressBarWidget.prototype.setProgress = function ( progress ) {
17879 this.progress = progress;
17880
17881 if ( progress !== false ) {
17882 this.$bar.css( 'width', this.progress + '%' );
17883 this.$element.attr( 'aria-valuenow', this.progress );
17884 } else {
17885 this.$bar.css( 'width', '' );
17886 this.$element.removeAttr( 'aria-valuenow' );
17887 }
17888 this.$element.toggleClass( 'oo-ui-progressBarWidget-indeterminate', !progress );
17889 };
17890
17891 /**
17892 * SearchWidgets combine a {@link OO.ui.TextInputWidget text input field}, where users can type a search query,
17893 * and a menu of search results, which is displayed beneath the query
17894 * field. Unlike {@link OO.ui.mixin.LookupElement lookup menus}, search result menus are always visible to the user.
17895 * Users can choose an item from the menu or type a query into the text field to search for a matching result item.
17896 * In general, search widgets are used inside a separate {@link OO.ui.Dialog dialog} window.
17897 *
17898 * Each time the query is changed, the search result menu is cleared and repopulated. Please see
17899 * the [OOjs UI demos][1] for an example.
17900 *
17901 * [1]: https://tools.wmflabs.org/oojs-ui/oojs-ui/demos/#dialogs-mediawiki-vector-ltr
17902 *
17903 * @class
17904 * @extends OO.ui.Widget
17905 *
17906 * @constructor
17907 * @param {Object} [config] Configuration options
17908 * @cfg {string|jQuery} [placeholder] Placeholder text for query input
17909 * @cfg {string} [value] Initial query value
17910 */
17911 OO.ui.SearchWidget = function OoUiSearchWidget( config ) {
17912 // Configuration initialization
17913 config = config || {};
17914
17915 // Parent constructor
17916 OO.ui.SearchWidget.parent.call( this, config );
17917
17918 // Properties
17919 this.query = new OO.ui.TextInputWidget( {
17920 icon: 'search',
17921 placeholder: config.placeholder,
17922 value: config.value
17923 } );
17924 this.results = new OO.ui.SelectWidget();
17925 this.$query = $( '<div>' );
17926 this.$results = $( '<div>' );
17927
17928 // Events
17929 this.query.connect( this, {
17930 change: 'onQueryChange',
17931 enter: 'onQueryEnter'
17932 } );
17933 this.query.$input.on( 'keydown', this.onQueryKeydown.bind( this ) );
17934
17935 // Initialization
17936 this.$query
17937 .addClass( 'oo-ui-searchWidget-query' )
17938 .append( this.query.$element );
17939 this.$results
17940 .addClass( 'oo-ui-searchWidget-results' )
17941 .append( this.results.$element );
17942 this.$element
17943 .addClass( 'oo-ui-searchWidget' )
17944 .append( this.$results, this.$query );
17945 };
17946
17947 /* Setup */
17948
17949 OO.inheritClass( OO.ui.SearchWidget, OO.ui.Widget );
17950
17951 /* Methods */
17952
17953 /**
17954 * Handle query key down events.
17955 *
17956 * @private
17957 * @param {jQuery.Event} e Key down event
17958 */
17959 OO.ui.SearchWidget.prototype.onQueryKeydown = function ( e ) {
17960 var highlightedItem, nextItem,
17961 dir = e.which === OO.ui.Keys.DOWN ? 1 : ( e.which === OO.ui.Keys.UP ? -1 : 0 );
17962
17963 if ( dir ) {
17964 highlightedItem = this.results.getHighlightedItem();
17965 if ( !highlightedItem ) {
17966 highlightedItem = this.results.getSelectedItem();
17967 }
17968 nextItem = this.results.getRelativeSelectableItem( highlightedItem, dir );
17969 this.results.highlightItem( nextItem );
17970 nextItem.scrollElementIntoView();
17971 }
17972 };
17973
17974 /**
17975 * Handle select widget select events.
17976 *
17977 * Clears existing results. Subclasses should repopulate items according to new query.
17978 *
17979 * @private
17980 * @param {string} value New value
17981 */
17982 OO.ui.SearchWidget.prototype.onQueryChange = function () {
17983 // Reset
17984 this.results.clearItems();
17985 };
17986
17987 /**
17988 * Handle select widget enter key events.
17989 *
17990 * Chooses highlighted item.
17991 *
17992 * @private
17993 * @param {string} value New value
17994 */
17995 OO.ui.SearchWidget.prototype.onQueryEnter = function () {
17996 var highlightedItem = this.results.getHighlightedItem();
17997 if ( highlightedItem ) {
17998 this.results.chooseItem( highlightedItem );
17999 }
18000 };
18001
18002 /**
18003 * Get the query input.
18004 *
18005 * @return {OO.ui.TextInputWidget} Query input
18006 */
18007 OO.ui.SearchWidget.prototype.getQuery = function () {
18008 return this.query;
18009 };
18010
18011 /**
18012 * Get the search results menu.
18013 *
18014 * @return {OO.ui.SelectWidget} Menu of search results
18015 */
18016 OO.ui.SearchWidget.prototype.getResults = function () {
18017 return this.results;
18018 };
18019
18020 /**
18021 * A SelectWidget is of a generic selection of options. The OOjs UI library contains several types of
18022 * select widgets, including {@link OO.ui.ButtonSelectWidget button selects},
18023 * {@link OO.ui.RadioSelectWidget radio selects}, and {@link OO.ui.MenuSelectWidget
18024 * menu selects}.
18025 *
18026 * This class should be used together with OO.ui.OptionWidget or OO.ui.DecoratedOptionWidget. For more
18027 * information, please see the [OOjs UI documentation on MediaWiki][1].
18028 *
18029 * @example
18030 * // Example of a select widget with three options
18031 * var select = new OO.ui.SelectWidget( {
18032 * items: [
18033 * new OO.ui.OptionWidget( {
18034 * data: 'a',
18035 * label: 'Option One',
18036 * } ),
18037 * new OO.ui.OptionWidget( {
18038 * data: 'b',
18039 * label: 'Option Two',
18040 * } ),
18041 * new OO.ui.OptionWidget( {
18042 * data: 'c',
18043 * label: 'Option Three',
18044 * } )
18045 * ]
18046 * } );
18047 * $( 'body' ).append( select.$element );
18048 *
18049 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
18050 *
18051 * @abstract
18052 * @class
18053 * @extends OO.ui.Widget
18054 * @mixins OO.ui.mixin.GroupWidget
18055 *
18056 * @constructor
18057 * @param {Object} [config] Configuration options
18058 * @cfg {OO.ui.OptionWidget[]} [items] An array of options to add to the select.
18059 * Options are created with {@link OO.ui.OptionWidget OptionWidget} classes. See
18060 * the [OOjs UI documentation on MediaWiki] [2] for examples.
18061 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
18062 */
18063 OO.ui.SelectWidget = function OoUiSelectWidget( config ) {
18064 // Configuration initialization
18065 config = config || {};
18066
18067 // Parent constructor
18068 OO.ui.SelectWidget.parent.call( this, config );
18069
18070 // Mixin constructors
18071 OO.ui.mixin.GroupWidget.call( this, $.extend( {}, config, { $group: this.$element } ) );
18072
18073 // Properties
18074 this.pressed = false;
18075 this.selecting = null;
18076 this.onMouseUpHandler = this.onMouseUp.bind( this );
18077 this.onMouseMoveHandler = this.onMouseMove.bind( this );
18078 this.onKeyDownHandler = this.onKeyDown.bind( this );
18079 this.onKeyPressHandler = this.onKeyPress.bind( this );
18080 this.keyPressBuffer = '';
18081 this.keyPressBufferTimer = null;
18082
18083 // Events
18084 this.connect( this, {
18085 toggle: 'onToggle'
18086 } );
18087 this.$element.on( {
18088 mousedown: this.onMouseDown.bind( this ),
18089 mouseover: this.onMouseOver.bind( this ),
18090 mouseleave: this.onMouseLeave.bind( this )
18091 } );
18092
18093 // Initialization
18094 this.$element
18095 .addClass( 'oo-ui-selectWidget oo-ui-selectWidget-depressed' )
18096 .attr( 'role', 'listbox' );
18097 if ( Array.isArray( config.items ) ) {
18098 this.addItems( config.items );
18099 }
18100 };
18101
18102 /* Setup */
18103
18104 OO.inheritClass( OO.ui.SelectWidget, OO.ui.Widget );
18105
18106 // Need to mixin base class as well
18107 OO.mixinClass( OO.ui.SelectWidget, OO.ui.mixin.GroupElement );
18108 OO.mixinClass( OO.ui.SelectWidget, OO.ui.mixin.GroupWidget );
18109
18110 /* Static */
18111 OO.ui.SelectWidget.static.passAllFilter = function () {
18112 return true;
18113 };
18114
18115 /* Events */
18116
18117 /**
18118 * @event highlight
18119 *
18120 * A `highlight` event is emitted when the highlight is changed with the #highlightItem method.
18121 *
18122 * @param {OO.ui.OptionWidget|null} item Highlighted item
18123 */
18124
18125 /**
18126 * @event press
18127 *
18128 * A `press` event is emitted when the #pressItem method is used to programmatically modify the
18129 * pressed state of an option.
18130 *
18131 * @param {OO.ui.OptionWidget|null} item Pressed item
18132 */
18133
18134 /**
18135 * @event select
18136 *
18137 * A `select` event is emitted when the selection is modified programmatically with the #selectItem method.
18138 *
18139 * @param {OO.ui.OptionWidget|null} item Selected item
18140 */
18141
18142 /**
18143 * @event choose
18144 * A `choose` event is emitted when an item is chosen with the #chooseItem method.
18145 * @param {OO.ui.OptionWidget} item Chosen item
18146 */
18147
18148 /**
18149 * @event add
18150 *
18151 * An `add` event is emitted when options are added to the select with the #addItems method.
18152 *
18153 * @param {OO.ui.OptionWidget[]} items Added items
18154 * @param {number} index Index of insertion point
18155 */
18156
18157 /**
18158 * @event remove
18159 *
18160 * A `remove` event is emitted when options are removed from the select with the #clearItems
18161 * or #removeItems methods.
18162 *
18163 * @param {OO.ui.OptionWidget[]} items Removed items
18164 */
18165
18166 /* Methods */
18167
18168 /**
18169 * Handle mouse down events.
18170 *
18171 * @private
18172 * @param {jQuery.Event} e Mouse down event
18173 */
18174 OO.ui.SelectWidget.prototype.onMouseDown = function ( e ) {
18175 var item;
18176
18177 if ( !this.isDisabled() && e.which === 1 ) {
18178 this.togglePressed( true );
18179 item = this.getTargetItem( e );
18180 if ( item && item.isSelectable() ) {
18181 this.pressItem( item );
18182 this.selecting = item;
18183 OO.ui.addCaptureEventListener(
18184 this.getElementDocument(),
18185 'mouseup',
18186 this.onMouseUpHandler
18187 );
18188 OO.ui.addCaptureEventListener(
18189 this.getElementDocument(),
18190 'mousemove',
18191 this.onMouseMoveHandler
18192 );
18193 }
18194 }
18195 return false;
18196 };
18197
18198 /**
18199 * Handle mouse up events.
18200 *
18201 * @private
18202 * @param {jQuery.Event} e Mouse up event
18203 */
18204 OO.ui.SelectWidget.prototype.onMouseUp = function ( e ) {
18205 var item;
18206
18207 this.togglePressed( false );
18208 if ( !this.selecting ) {
18209 item = this.getTargetItem( e );
18210 if ( item && item.isSelectable() ) {
18211 this.selecting = item;
18212 }
18213 }
18214 if ( !this.isDisabled() && e.which === 1 && this.selecting ) {
18215 this.pressItem( null );
18216 this.chooseItem( this.selecting );
18217 this.selecting = null;
18218 }
18219
18220 OO.ui.removeCaptureEventListener( this.getElementDocument(), 'mouseup',
18221 this.onMouseUpHandler );
18222 OO.ui.removeCaptureEventListener( this.getElementDocument(), 'mousemove',
18223 this.onMouseMoveHandler );
18224
18225 return false;
18226 };
18227
18228 /**
18229 * Handle mouse move events.
18230 *
18231 * @private
18232 * @param {jQuery.Event} e Mouse move event
18233 */
18234 OO.ui.SelectWidget.prototype.onMouseMove = function ( e ) {
18235 var item;
18236
18237 if ( !this.isDisabled() && this.pressed ) {
18238 item = this.getTargetItem( e );
18239 if ( item && item !== this.selecting && item.isSelectable() ) {
18240 this.pressItem( item );
18241 this.selecting = item;
18242 }
18243 }
18244 return false;
18245 };
18246
18247 /**
18248 * Handle mouse over events.
18249 *
18250 * @private
18251 * @param {jQuery.Event} e Mouse over event
18252 */
18253 OO.ui.SelectWidget.prototype.onMouseOver = function ( e ) {
18254 var item;
18255
18256 if ( !this.isDisabled() ) {
18257 item = this.getTargetItem( e );
18258 this.highlightItem( item && item.isHighlightable() ? item : null );
18259 }
18260 return false;
18261 };
18262
18263 /**
18264 * Handle mouse leave events.
18265 *
18266 * @private
18267 * @param {jQuery.Event} e Mouse over event
18268 */
18269 OO.ui.SelectWidget.prototype.onMouseLeave = function () {
18270 if ( !this.isDisabled() ) {
18271 this.highlightItem( null );
18272 }
18273 return false;
18274 };
18275
18276 /**
18277 * Handle key down events.
18278 *
18279 * @protected
18280 * @param {jQuery.Event} e Key down event
18281 */
18282 OO.ui.SelectWidget.prototype.onKeyDown = function ( e ) {
18283 var nextItem,
18284 handled = false,
18285 currentItem = this.getHighlightedItem() || this.getSelectedItem();
18286
18287 if ( !this.isDisabled() && this.isVisible() ) {
18288 switch ( e.keyCode ) {
18289 case OO.ui.Keys.ENTER:
18290 if ( currentItem && currentItem.constructor.static.highlightable ) {
18291 // Was only highlighted, now let's select it. No-op if already selected.
18292 this.chooseItem( currentItem );
18293 handled = true;
18294 }
18295 break;
18296 case OO.ui.Keys.UP:
18297 case OO.ui.Keys.LEFT:
18298 this.clearKeyPressBuffer();
18299 nextItem = this.getRelativeSelectableItem( currentItem, -1 );
18300 handled = true;
18301 break;
18302 case OO.ui.Keys.DOWN:
18303 case OO.ui.Keys.RIGHT:
18304 this.clearKeyPressBuffer();
18305 nextItem = this.getRelativeSelectableItem( currentItem, 1 );
18306 handled = true;
18307 break;
18308 case OO.ui.Keys.ESCAPE:
18309 case OO.ui.Keys.TAB:
18310 if ( currentItem && currentItem.constructor.static.highlightable ) {
18311 currentItem.setHighlighted( false );
18312 }
18313 this.unbindKeyDownListener();
18314 this.unbindKeyPressListener();
18315 // Don't prevent tabbing away / defocusing
18316 handled = false;
18317 break;
18318 }
18319
18320 if ( nextItem ) {
18321 if ( nextItem.constructor.static.highlightable ) {
18322 this.highlightItem( nextItem );
18323 } else {
18324 this.chooseItem( nextItem );
18325 }
18326 nextItem.scrollElementIntoView();
18327 }
18328
18329 if ( handled ) {
18330 // Can't just return false, because e is not always a jQuery event
18331 e.preventDefault();
18332 e.stopPropagation();
18333 }
18334 }
18335 };
18336
18337 /**
18338 * Bind key down listener.
18339 *
18340 * @protected
18341 */
18342 OO.ui.SelectWidget.prototype.bindKeyDownListener = function () {
18343 OO.ui.addCaptureEventListener( this.getElementWindow(), 'keydown', this.onKeyDownHandler );
18344 };
18345
18346 /**
18347 * Unbind key down listener.
18348 *
18349 * @protected
18350 */
18351 OO.ui.SelectWidget.prototype.unbindKeyDownListener = function () {
18352 OO.ui.removeCaptureEventListener( this.getElementWindow(), 'keydown', this.onKeyDownHandler );
18353 };
18354
18355 /**
18356 * Clear the key-press buffer
18357 *
18358 * @protected
18359 */
18360 OO.ui.SelectWidget.prototype.clearKeyPressBuffer = function () {
18361 if ( this.keyPressBufferTimer ) {
18362 clearTimeout( this.keyPressBufferTimer );
18363 this.keyPressBufferTimer = null;
18364 }
18365 this.keyPressBuffer = '';
18366 };
18367
18368 /**
18369 * Handle key press events.
18370 *
18371 * @protected
18372 * @param {jQuery.Event} e Key press event
18373 */
18374 OO.ui.SelectWidget.prototype.onKeyPress = function ( e ) {
18375 var c, filter, item;
18376
18377 if ( !e.charCode ) {
18378 if ( e.keyCode === OO.ui.Keys.BACKSPACE && this.keyPressBuffer !== '' ) {
18379 this.keyPressBuffer = this.keyPressBuffer.substr( 0, this.keyPressBuffer.length - 1 );
18380 return false;
18381 }
18382 return;
18383 }
18384 if ( String.fromCodePoint ) {
18385 c = String.fromCodePoint( e.charCode );
18386 } else {
18387 c = String.fromCharCode( e.charCode );
18388 }
18389
18390 if ( this.keyPressBufferTimer ) {
18391 clearTimeout( this.keyPressBufferTimer );
18392 }
18393 this.keyPressBufferTimer = setTimeout( this.clearKeyPressBuffer.bind( this ), 1500 );
18394
18395 item = this.getHighlightedItem() || this.getSelectedItem();
18396
18397 if ( this.keyPressBuffer === c ) {
18398 // Common (if weird) special case: typing "xxxx" will cycle through all
18399 // the items beginning with "x".
18400 if ( item ) {
18401 item = this.getRelativeSelectableItem( item, 1 );
18402 }
18403 } else {
18404 this.keyPressBuffer += c;
18405 }
18406
18407 filter = this.getItemMatcher( this.keyPressBuffer, false );
18408 if ( !item || !filter( item ) ) {
18409 item = this.getRelativeSelectableItem( item, 1, filter );
18410 }
18411 if ( item ) {
18412 if ( item.constructor.static.highlightable ) {
18413 this.highlightItem( item );
18414 } else {
18415 this.chooseItem( item );
18416 }
18417 item.scrollElementIntoView();
18418 }
18419
18420 return false;
18421 };
18422
18423 /**
18424 * Get a matcher for the specific string
18425 *
18426 * @protected
18427 * @param {string} s String to match against items
18428 * @param {boolean} [exact=false] Only accept exact matches
18429 * @return {Function} function ( OO.ui.OptionItem ) => boolean
18430 */
18431 OO.ui.SelectWidget.prototype.getItemMatcher = function ( s, exact ) {
18432 var re;
18433
18434 if ( s.normalize ) {
18435 s = s.normalize();
18436 }
18437 s = exact ? s.trim() : s.replace( /^\s+/, '' );
18438 re = '^\\s*' + s.replace( /([\\{}()|.?*+\-\^$\[\]])/g, '\\$1' ).replace( /\s+/g, '\\s+' );
18439 if ( exact ) {
18440 re += '\\s*$';
18441 }
18442 re = new RegExp( re, 'i' );
18443 return function ( item ) {
18444 var l = item.getLabel();
18445 if ( typeof l !== 'string' ) {
18446 l = item.$label.text();
18447 }
18448 if ( l.normalize ) {
18449 l = l.normalize();
18450 }
18451 return re.test( l );
18452 };
18453 };
18454
18455 /**
18456 * Bind key press listener.
18457 *
18458 * @protected
18459 */
18460 OO.ui.SelectWidget.prototype.bindKeyPressListener = function () {
18461 OO.ui.addCaptureEventListener( this.getElementWindow(), 'keypress', this.onKeyPressHandler );
18462 };
18463
18464 /**
18465 * Unbind key down listener.
18466 *
18467 * If you override this, be sure to call this.clearKeyPressBuffer() from your
18468 * implementation.
18469 *
18470 * @protected
18471 */
18472 OO.ui.SelectWidget.prototype.unbindKeyPressListener = function () {
18473 OO.ui.removeCaptureEventListener( this.getElementWindow(), 'keypress', this.onKeyPressHandler );
18474 this.clearKeyPressBuffer();
18475 };
18476
18477 /**
18478 * Visibility change handler
18479 *
18480 * @protected
18481 * @param {boolean} visible
18482 */
18483 OO.ui.SelectWidget.prototype.onToggle = function ( visible ) {
18484 if ( !visible ) {
18485 this.clearKeyPressBuffer();
18486 }
18487 };
18488
18489 /**
18490 * Get the closest item to a jQuery.Event.
18491 *
18492 * @private
18493 * @param {jQuery.Event} e
18494 * @return {OO.ui.OptionWidget|null} Outline item widget, `null` if none was found
18495 */
18496 OO.ui.SelectWidget.prototype.getTargetItem = function ( e ) {
18497 return $( e.target ).closest( '.oo-ui-optionWidget' ).data( 'oo-ui-optionWidget' ) || null;
18498 };
18499
18500 /**
18501 * Get selected item.
18502 *
18503 * @return {OO.ui.OptionWidget|null} Selected item, `null` if no item is selected
18504 */
18505 OO.ui.SelectWidget.prototype.getSelectedItem = function () {
18506 var i, len;
18507
18508 for ( i = 0, len = this.items.length; i < len; i++ ) {
18509 if ( this.items[ i ].isSelected() ) {
18510 return this.items[ i ];
18511 }
18512 }
18513 return null;
18514 };
18515
18516 /**
18517 * Get highlighted item.
18518 *
18519 * @return {OO.ui.OptionWidget|null} Highlighted item, `null` if no item is highlighted
18520 */
18521 OO.ui.SelectWidget.prototype.getHighlightedItem = function () {
18522 var i, len;
18523
18524 for ( i = 0, len = this.items.length; i < len; i++ ) {
18525 if ( this.items[ i ].isHighlighted() ) {
18526 return this.items[ i ];
18527 }
18528 }
18529 return null;
18530 };
18531
18532 /**
18533 * Toggle pressed state.
18534 *
18535 * Press is a state that occurs when a user mouses down on an item, but
18536 * has not yet let go of the mouse. The item may appear selected, but it will not be selected
18537 * until the user releases the mouse.
18538 *
18539 * @param {boolean} pressed An option is being pressed
18540 */
18541 OO.ui.SelectWidget.prototype.togglePressed = function ( pressed ) {
18542 if ( pressed === undefined ) {
18543 pressed = !this.pressed;
18544 }
18545 if ( pressed !== this.pressed ) {
18546 this.$element
18547 .toggleClass( 'oo-ui-selectWidget-pressed', pressed )
18548 .toggleClass( 'oo-ui-selectWidget-depressed', !pressed );
18549 this.pressed = pressed;
18550 }
18551 };
18552
18553 /**
18554 * Highlight an option. If the `item` param is omitted, no options will be highlighted
18555 * and any existing highlight will be removed. The highlight is mutually exclusive.
18556 *
18557 * @param {OO.ui.OptionWidget} [item] Item to highlight, omit for no highlight
18558 * @fires highlight
18559 * @chainable
18560 */
18561 OO.ui.SelectWidget.prototype.highlightItem = function ( item ) {
18562 var i, len, highlighted,
18563 changed = false;
18564
18565 for ( i = 0, len = this.items.length; i < len; i++ ) {
18566 highlighted = this.items[ i ] === item;
18567 if ( this.items[ i ].isHighlighted() !== highlighted ) {
18568 this.items[ i ].setHighlighted( highlighted );
18569 changed = true;
18570 }
18571 }
18572 if ( changed ) {
18573 this.emit( 'highlight', item );
18574 }
18575
18576 return this;
18577 };
18578
18579 /**
18580 * Fetch an item by its label.
18581 *
18582 * @param {string} label Label of the item to select.
18583 * @param {boolean} [prefix=false] Allow a prefix match, if only a single item matches
18584 * @return {OO.ui.Element|null} Item with equivalent label, `null` if none exists
18585 */
18586 OO.ui.SelectWidget.prototype.getItemFromLabel = function ( label, prefix ) {
18587 var i, item, found,
18588 len = this.items.length,
18589 filter = this.getItemMatcher( label, true );
18590
18591 for ( i = 0; i < len; i++ ) {
18592 item = this.items[ i ];
18593 if ( item instanceof OO.ui.OptionWidget && item.isSelectable() && filter( item ) ) {
18594 return item;
18595 }
18596 }
18597
18598 if ( prefix ) {
18599 found = null;
18600 filter = this.getItemMatcher( label, false );
18601 for ( i = 0; i < len; i++ ) {
18602 item = this.items[ i ];
18603 if ( item instanceof OO.ui.OptionWidget && item.isSelectable() && filter( item ) ) {
18604 if ( found ) {
18605 return null;
18606 }
18607 found = item;
18608 }
18609 }
18610 if ( found ) {
18611 return found;
18612 }
18613 }
18614
18615 return null;
18616 };
18617
18618 /**
18619 * Programmatically select an option by its label. If the item does not exist,
18620 * all options will be deselected.
18621 *
18622 * @param {string} [label] Label of the item to select.
18623 * @param {boolean} [prefix=false] Allow a prefix match, if only a single item matches
18624 * @fires select
18625 * @chainable
18626 */
18627 OO.ui.SelectWidget.prototype.selectItemByLabel = function ( label, prefix ) {
18628 var itemFromLabel = this.getItemFromLabel( label, !!prefix );
18629 if ( label === undefined || !itemFromLabel ) {
18630 return this.selectItem();
18631 }
18632 return this.selectItem( itemFromLabel );
18633 };
18634
18635 /**
18636 * Programmatically select an option by its data. If the `data` parameter is omitted,
18637 * or if the item does not exist, all options will be deselected.
18638 *
18639 * @param {Object|string} [data] Value of the item to select, omit to deselect all
18640 * @fires select
18641 * @chainable
18642 */
18643 OO.ui.SelectWidget.prototype.selectItemByData = function ( data ) {
18644 var itemFromData = this.getItemFromData( data );
18645 if ( data === undefined || !itemFromData ) {
18646 return this.selectItem();
18647 }
18648 return this.selectItem( itemFromData );
18649 };
18650
18651 /**
18652 * Programmatically select an option by its reference. If the `item` parameter is omitted,
18653 * all options will be deselected.
18654 *
18655 * @param {OO.ui.OptionWidget} [item] Item to select, omit to deselect all
18656 * @fires select
18657 * @chainable
18658 */
18659 OO.ui.SelectWidget.prototype.selectItem = function ( item ) {
18660 var i, len, selected,
18661 changed = false;
18662
18663 for ( i = 0, len = this.items.length; i < len; i++ ) {
18664 selected = this.items[ i ] === item;
18665 if ( this.items[ i ].isSelected() !== selected ) {
18666 this.items[ i ].setSelected( selected );
18667 changed = true;
18668 }
18669 }
18670 if ( changed ) {
18671 this.emit( 'select', item );
18672 }
18673
18674 return this;
18675 };
18676
18677 /**
18678 * Press an item.
18679 *
18680 * Press is a state that occurs when a user mouses down on an item, but has not
18681 * yet let go of the mouse. The item may appear selected, but it will not be selected until the user
18682 * releases the mouse.
18683 *
18684 * @param {OO.ui.OptionWidget} [item] Item to press, omit to depress all
18685 * @fires press
18686 * @chainable
18687 */
18688 OO.ui.SelectWidget.prototype.pressItem = function ( item ) {
18689 var i, len, pressed,
18690 changed = false;
18691
18692 for ( i = 0, len = this.items.length; i < len; i++ ) {
18693 pressed = this.items[ i ] === item;
18694 if ( this.items[ i ].isPressed() !== pressed ) {
18695 this.items[ i ].setPressed( pressed );
18696 changed = true;
18697 }
18698 }
18699 if ( changed ) {
18700 this.emit( 'press', item );
18701 }
18702
18703 return this;
18704 };
18705
18706 /**
18707 * Choose an item.
18708 *
18709 * Note that ‘choose’ should never be modified programmatically. A user can choose
18710 * an option with the keyboard or mouse and it becomes selected. To select an item programmatically,
18711 * use the #selectItem method.
18712 *
18713 * This method is identical to #selectItem, but may vary in subclasses that take additional action
18714 * when users choose an item with the keyboard or mouse.
18715 *
18716 * @param {OO.ui.OptionWidget} item Item to choose
18717 * @fires choose
18718 * @chainable
18719 */
18720 OO.ui.SelectWidget.prototype.chooseItem = function ( item ) {
18721 if ( item ) {
18722 this.selectItem( item );
18723 this.emit( 'choose', item );
18724 }
18725
18726 return this;
18727 };
18728
18729 /**
18730 * Get an option by its position relative to the specified item (or to the start of the option array,
18731 * if item is `null`). The direction in which to search through the option array is specified with a
18732 * number: -1 for reverse (the default) or 1 for forward. The method will return an option, or
18733 * `null` if there are no options in the array.
18734 *
18735 * @param {OO.ui.OptionWidget|null} item Item to describe the start position, or `null` to start at the beginning of the array.
18736 * @param {number} direction Direction to move in: -1 to move backward, 1 to move forward
18737 * @param {Function} filter Only consider items for which this function returns
18738 * true. Function takes an OO.ui.OptionWidget and returns a boolean.
18739 * @return {OO.ui.OptionWidget|null} Item at position, `null` if there are no items in the select
18740 */
18741 OO.ui.SelectWidget.prototype.getRelativeSelectableItem = function ( item, direction, filter ) {
18742 var currentIndex, nextIndex, i,
18743 increase = direction > 0 ? 1 : -1,
18744 len = this.items.length;
18745
18746 if ( !$.isFunction( filter ) ) {
18747 filter = OO.ui.SelectWidget.static.passAllFilter;
18748 }
18749
18750 if ( item instanceof OO.ui.OptionWidget ) {
18751 currentIndex = this.items.indexOf( item );
18752 nextIndex = ( currentIndex + increase + len ) % len;
18753 } else {
18754 // If no item is selected and moving forward, start at the beginning.
18755 // If moving backward, start at the end.
18756 nextIndex = direction > 0 ? 0 : len - 1;
18757 }
18758
18759 for ( i = 0; i < len; i++ ) {
18760 item = this.items[ nextIndex ];
18761 if ( item instanceof OO.ui.OptionWidget && item.isSelectable() && filter( item ) ) {
18762 return item;
18763 }
18764 nextIndex = ( nextIndex + increase + len ) % len;
18765 }
18766 return null;
18767 };
18768
18769 /**
18770 * Get the next selectable item or `null` if there are no selectable items.
18771 * Disabled options and menu-section markers and breaks are not selectable.
18772 *
18773 * @return {OO.ui.OptionWidget|null} Item, `null` if there aren't any selectable items
18774 */
18775 OO.ui.SelectWidget.prototype.getFirstSelectableItem = function () {
18776 var i, len, item;
18777
18778 for ( i = 0, len = this.items.length; i < len; i++ ) {
18779 item = this.items[ i ];
18780 if ( item instanceof OO.ui.OptionWidget && item.isSelectable() ) {
18781 return item;
18782 }
18783 }
18784
18785 return null;
18786 };
18787
18788 /**
18789 * Add an array of options to the select. Optionally, an index number can be used to
18790 * specify an insertion point.
18791 *
18792 * @param {OO.ui.OptionWidget[]} items Items to add
18793 * @param {number} [index] Index to insert items after
18794 * @fires add
18795 * @chainable
18796 */
18797 OO.ui.SelectWidget.prototype.addItems = function ( items, index ) {
18798 // Mixin method
18799 OO.ui.mixin.GroupWidget.prototype.addItems.call( this, items, index );
18800
18801 // Always provide an index, even if it was omitted
18802 this.emit( 'add', items, index === undefined ? this.items.length - items.length - 1 : index );
18803
18804 return this;
18805 };
18806
18807 /**
18808 * Remove the specified array of options from the select. Options will be detached
18809 * from the DOM, not removed, so they can be reused later. To remove all options from
18810 * the select, you may wish to use the #clearItems method instead.
18811 *
18812 * @param {OO.ui.OptionWidget[]} items Items to remove
18813 * @fires remove
18814 * @chainable
18815 */
18816 OO.ui.SelectWidget.prototype.removeItems = function ( items ) {
18817 var i, len, item;
18818
18819 // Deselect items being removed
18820 for ( i = 0, len = items.length; i < len; i++ ) {
18821 item = items[ i ];
18822 if ( item.isSelected() ) {
18823 this.selectItem( null );
18824 }
18825 }
18826
18827 // Mixin method
18828 OO.ui.mixin.GroupWidget.prototype.removeItems.call( this, items );
18829
18830 this.emit( 'remove', items );
18831
18832 return this;
18833 };
18834
18835 /**
18836 * Clear all options from the select. Options will be detached from the DOM, not removed,
18837 * so that they can be reused later. To remove a subset of options from the select, use
18838 * the #removeItems method.
18839 *
18840 * @fires remove
18841 * @chainable
18842 */
18843 OO.ui.SelectWidget.prototype.clearItems = function () {
18844 var items = this.items.slice();
18845
18846 // Mixin method
18847 OO.ui.mixin.GroupWidget.prototype.clearItems.call( this );
18848
18849 // Clear selection
18850 this.selectItem( null );
18851
18852 this.emit( 'remove', items );
18853
18854 return this;
18855 };
18856
18857 /**
18858 * ButtonSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains
18859 * button options and is used together with
18860 * OO.ui.ButtonOptionWidget. The ButtonSelectWidget provides an interface for
18861 * highlighting, choosing, and selecting mutually exclusive options. Please see
18862 * the [OOjs UI documentation on MediaWiki] [1] for more information.
18863 *
18864 * @example
18865 * // Example: A ButtonSelectWidget that contains three ButtonOptionWidgets
18866 * var option1 = new OO.ui.ButtonOptionWidget( {
18867 * data: 1,
18868 * label: 'Option 1',
18869 * title: 'Button option 1'
18870 * } );
18871 *
18872 * var option2 = new OO.ui.ButtonOptionWidget( {
18873 * data: 2,
18874 * label: 'Option 2',
18875 * title: 'Button option 2'
18876 * } );
18877 *
18878 * var option3 = new OO.ui.ButtonOptionWidget( {
18879 * data: 3,
18880 * label: 'Option 3',
18881 * title: 'Button option 3'
18882 * } );
18883 *
18884 * var buttonSelect=new OO.ui.ButtonSelectWidget( {
18885 * items: [ option1, option2, option3 ]
18886 * } );
18887 * $( 'body' ).append( buttonSelect.$element );
18888 *
18889 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
18890 *
18891 * @class
18892 * @extends OO.ui.SelectWidget
18893 * @mixins OO.ui.mixin.TabIndexedElement
18894 *
18895 * @constructor
18896 * @param {Object} [config] Configuration options
18897 */
18898 OO.ui.ButtonSelectWidget = function OoUiButtonSelectWidget( config ) {
18899 // Parent constructor
18900 OO.ui.ButtonSelectWidget.parent.call( this, config );
18901
18902 // Mixin constructors
18903 OO.ui.mixin.TabIndexedElement.call( this, config );
18904
18905 // Events
18906 this.$element.on( {
18907 focus: this.bindKeyDownListener.bind( this ),
18908 blur: this.unbindKeyDownListener.bind( this )
18909 } );
18910
18911 // Initialization
18912 this.$element.addClass( 'oo-ui-buttonSelectWidget' );
18913 };
18914
18915 /* Setup */
18916
18917 OO.inheritClass( OO.ui.ButtonSelectWidget, OO.ui.SelectWidget );
18918 OO.mixinClass( OO.ui.ButtonSelectWidget, OO.ui.mixin.TabIndexedElement );
18919
18920 /**
18921 * RadioSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains radio
18922 * options and is used together with OO.ui.RadioOptionWidget. The RadioSelectWidget provides
18923 * an interface for adding, removing and selecting options.
18924 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
18925 *
18926 * If you want to use this within a HTML form, such as a OO.ui.FormLayout, use
18927 * OO.ui.RadioSelectInputWidget instead.
18928 *
18929 * @example
18930 * // A RadioSelectWidget with RadioOptions.
18931 * var option1 = new OO.ui.RadioOptionWidget( {
18932 * data: 'a',
18933 * label: 'Selected radio option'
18934 * } );
18935 *
18936 * var option2 = new OO.ui.RadioOptionWidget( {
18937 * data: 'b',
18938 * label: 'Unselected radio option'
18939 * } );
18940 *
18941 * var radioSelect=new OO.ui.RadioSelectWidget( {
18942 * items: [ option1, option2 ]
18943 * } );
18944 *
18945 * // Select 'option 1' using the RadioSelectWidget's selectItem() method.
18946 * radioSelect.selectItem( option1 );
18947 *
18948 * $( 'body' ).append( radioSelect.$element );
18949 *
18950 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
18951
18952 *
18953 * @class
18954 * @extends OO.ui.SelectWidget
18955 * @mixins OO.ui.mixin.TabIndexedElement
18956 *
18957 * @constructor
18958 * @param {Object} [config] Configuration options
18959 */
18960 OO.ui.RadioSelectWidget = function OoUiRadioSelectWidget( config ) {
18961 // Parent constructor
18962 OO.ui.RadioSelectWidget.parent.call( this, config );
18963
18964 // Mixin constructors
18965 OO.ui.mixin.TabIndexedElement.call( this, config );
18966
18967 // Events
18968 this.$element.on( {
18969 focus: this.bindKeyDownListener.bind( this ),
18970 blur: this.unbindKeyDownListener.bind( this )
18971 } );
18972
18973 // Initialization
18974 this.$element
18975 .addClass( 'oo-ui-radioSelectWidget' )
18976 .attr( 'role', 'radiogroup' );
18977 };
18978
18979 /* Setup */
18980
18981 OO.inheritClass( OO.ui.RadioSelectWidget, OO.ui.SelectWidget );
18982 OO.mixinClass( OO.ui.RadioSelectWidget, OO.ui.mixin.TabIndexedElement );
18983
18984 /**
18985 * MenuSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains options and
18986 * is used together with OO.ui.MenuOptionWidget. It is designed be used as part of another widget.
18987 * See {@link OO.ui.DropdownWidget DropdownWidget}, {@link OO.ui.ComboBoxInputWidget ComboBoxInputWidget},
18988 * and {@link OO.ui.mixin.LookupElement LookupElement} for examples of widgets that contain menus.
18989 * MenuSelectWidgets themselves are not instantiated directly, rather subclassed
18990 * and customized to be opened, closed, and displayed as needed.
18991 *
18992 * By default, menus are clipped to the visible viewport and are not visible when a user presses the
18993 * mouse outside the menu.
18994 *
18995 * Menus also have support for keyboard interaction:
18996 *
18997 * - Enter/Return key: choose and select a menu option
18998 * - Up-arrow key: highlight the previous menu option
18999 * - Down-arrow key: highlight the next menu option
19000 * - Esc key: hide the menu
19001 *
19002 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
19003 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
19004 *
19005 * @class
19006 * @extends OO.ui.SelectWidget
19007 * @mixins OO.ui.mixin.ClippableElement
19008 *
19009 * @constructor
19010 * @param {Object} [config] Configuration options
19011 * @cfg {OO.ui.TextInputWidget} [input] Text input used to implement option highlighting for menu items that match
19012 * the text the user types. This config is used by {@link OO.ui.ComboBoxInputWidget ComboBoxInputWidget}
19013 * and {@link OO.ui.mixin.LookupElement LookupElement}
19014 * @cfg {jQuery} [$input] Text input used to implement option highlighting for menu items that match
19015 * the text the user types. This config is used by {@link OO.ui.CapsuleMultiSelectWidget CapsuleMultiSelectWidget}
19016 * @cfg {OO.ui.Widget} [widget] Widget associated with the menu's active state. If the user clicks the mouse
19017 * anywhere on the page outside of this widget, the menu is hidden. For example, if there is a button
19018 * that toggles the menu's visibility on click, the menu will be hidden then re-shown when the user clicks
19019 * that button, unless the button (or its parent widget) is passed in here.
19020 * @cfg {boolean} [autoHide=true] Hide the menu when the mouse is pressed outside the menu.
19021 * @cfg {boolean} [filterFromInput=false] Filter the displayed options from the input
19022 */
19023 OO.ui.MenuSelectWidget = function OoUiMenuSelectWidget( config ) {
19024 // Configuration initialization
19025 config = config || {};
19026
19027 // Parent constructor
19028 OO.ui.MenuSelectWidget.parent.call( this, config );
19029
19030 // Mixin constructors
19031 OO.ui.mixin.ClippableElement.call( this, $.extend( {}, config, { $clippable: this.$group } ) );
19032
19033 // Properties
19034 this.newItems = null;
19035 this.autoHide = config.autoHide === undefined || !!config.autoHide;
19036 this.filterFromInput = !!config.filterFromInput;
19037 this.$input = config.$input ? config.$input : config.input ? config.input.$input : null;
19038 this.$widget = config.widget ? config.widget.$element : null;
19039 this.onDocumentMouseDownHandler = this.onDocumentMouseDown.bind( this );
19040 this.onInputEditHandler = OO.ui.debounce( this.updateItemVisibility.bind( this ), 100 );
19041
19042 // Initialization
19043 this.$element
19044 .addClass( 'oo-ui-menuSelectWidget' )
19045 .attr( 'role', 'menu' );
19046
19047 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
19048 // that reference properties not initialized at that time of parent class construction
19049 // TODO: Find a better way to handle post-constructor setup
19050 this.visible = false;
19051 this.$element.addClass( 'oo-ui-element-hidden' );
19052 };
19053
19054 /* Setup */
19055
19056 OO.inheritClass( OO.ui.MenuSelectWidget, OO.ui.SelectWidget );
19057 OO.mixinClass( OO.ui.MenuSelectWidget, OO.ui.mixin.ClippableElement );
19058
19059 /* Methods */
19060
19061 /**
19062 * Handles document mouse down events.
19063 *
19064 * @protected
19065 * @param {jQuery.Event} e Key down event
19066 */
19067 OO.ui.MenuSelectWidget.prototype.onDocumentMouseDown = function ( e ) {
19068 if (
19069 !OO.ui.contains( this.$element[ 0 ], e.target, true ) &&
19070 ( !this.$widget || !OO.ui.contains( this.$widget[ 0 ], e.target, true ) )
19071 ) {
19072 this.toggle( false );
19073 }
19074 };
19075
19076 /**
19077 * @inheritdoc
19078 */
19079 OO.ui.MenuSelectWidget.prototype.onKeyDown = function ( e ) {
19080 var currentItem = this.getHighlightedItem() || this.getSelectedItem();
19081
19082 if ( !this.isDisabled() && this.isVisible() ) {
19083 switch ( e.keyCode ) {
19084 case OO.ui.Keys.LEFT:
19085 case OO.ui.Keys.RIGHT:
19086 // Do nothing if a text field is associated, arrow keys will be handled natively
19087 if ( !this.$input ) {
19088 OO.ui.MenuSelectWidget.parent.prototype.onKeyDown.call( this, e );
19089 }
19090 break;
19091 case OO.ui.Keys.ESCAPE:
19092 case OO.ui.Keys.TAB:
19093 if ( currentItem ) {
19094 currentItem.setHighlighted( false );
19095 }
19096 this.toggle( false );
19097 // Don't prevent tabbing away, prevent defocusing
19098 if ( e.keyCode === OO.ui.Keys.ESCAPE ) {
19099 e.preventDefault();
19100 e.stopPropagation();
19101 }
19102 break;
19103 default:
19104 OO.ui.MenuSelectWidget.parent.prototype.onKeyDown.call( this, e );
19105 return;
19106 }
19107 }
19108 };
19109
19110 /**
19111 * Update menu item visibility after input changes.
19112 * @protected
19113 */
19114 OO.ui.MenuSelectWidget.prototype.updateItemVisibility = function () {
19115 var i, item,
19116 len = this.items.length,
19117 showAll = !this.isVisible(),
19118 filter = showAll ? null : this.getItemMatcher( this.$input.val() );
19119
19120 for ( i = 0; i < len; i++ ) {
19121 item = this.items[ i ];
19122 if ( item instanceof OO.ui.OptionWidget ) {
19123 item.toggle( showAll || filter( item ) );
19124 }
19125 }
19126
19127 // Reevaluate clipping
19128 this.clip();
19129 };
19130
19131 /**
19132 * @inheritdoc
19133 */
19134 OO.ui.MenuSelectWidget.prototype.bindKeyDownListener = function () {
19135 if ( this.$input ) {
19136 this.$input.on( 'keydown', this.onKeyDownHandler );
19137 } else {
19138 OO.ui.MenuSelectWidget.parent.prototype.bindKeyDownListener.call( this );
19139 }
19140 };
19141
19142 /**
19143 * @inheritdoc
19144 */
19145 OO.ui.MenuSelectWidget.prototype.unbindKeyDownListener = function () {
19146 if ( this.$input ) {
19147 this.$input.off( 'keydown', this.onKeyDownHandler );
19148 } else {
19149 OO.ui.MenuSelectWidget.parent.prototype.unbindKeyDownListener.call( this );
19150 }
19151 };
19152
19153 /**
19154 * @inheritdoc
19155 */
19156 OO.ui.MenuSelectWidget.prototype.bindKeyPressListener = function () {
19157 if ( this.$input ) {
19158 if ( this.filterFromInput ) {
19159 this.$input.on( 'keydown mouseup cut paste change input select', this.onInputEditHandler );
19160 }
19161 } else {
19162 OO.ui.MenuSelectWidget.parent.prototype.bindKeyPressListener.call( this );
19163 }
19164 };
19165
19166 /**
19167 * @inheritdoc
19168 */
19169 OO.ui.MenuSelectWidget.prototype.unbindKeyPressListener = function () {
19170 if ( this.$input ) {
19171 if ( this.filterFromInput ) {
19172 this.$input.off( 'keydown mouseup cut paste change input select', this.onInputEditHandler );
19173 this.updateItemVisibility();
19174 }
19175 } else {
19176 OO.ui.MenuSelectWidget.parent.prototype.unbindKeyPressListener.call( this );
19177 }
19178 };
19179
19180 /**
19181 * Choose an item.
19182 *
19183 * When a user chooses an item, the menu is closed.
19184 *
19185 * Note that ‘choose’ should never be modified programmatically. A user can choose an option with the keyboard
19186 * or mouse and it becomes selected. To select an item programmatically, use the #selectItem method.
19187 * @param {OO.ui.OptionWidget} item Item to choose
19188 * @chainable
19189 */
19190 OO.ui.MenuSelectWidget.prototype.chooseItem = function ( item ) {
19191 OO.ui.MenuSelectWidget.parent.prototype.chooseItem.call( this, item );
19192 this.toggle( false );
19193 return this;
19194 };
19195
19196 /**
19197 * @inheritdoc
19198 */
19199 OO.ui.MenuSelectWidget.prototype.addItems = function ( items, index ) {
19200 var i, len, item;
19201
19202 // Parent method
19203 OO.ui.MenuSelectWidget.parent.prototype.addItems.call( this, items, index );
19204
19205 // Auto-initialize
19206 if ( !this.newItems ) {
19207 this.newItems = [];
19208 }
19209
19210 for ( i = 0, len = items.length; i < len; i++ ) {
19211 item = items[ i ];
19212 if ( this.isVisible() ) {
19213 // Defer fitting label until item has been attached
19214 item.fitLabel();
19215 } else {
19216 this.newItems.push( item );
19217 }
19218 }
19219
19220 // Reevaluate clipping
19221 this.clip();
19222
19223 return this;
19224 };
19225
19226 /**
19227 * @inheritdoc
19228 */
19229 OO.ui.MenuSelectWidget.prototype.removeItems = function ( items ) {
19230 // Parent method
19231 OO.ui.MenuSelectWidget.parent.prototype.removeItems.call( this, items );
19232
19233 // Reevaluate clipping
19234 this.clip();
19235
19236 return this;
19237 };
19238
19239 /**
19240 * @inheritdoc
19241 */
19242 OO.ui.MenuSelectWidget.prototype.clearItems = function () {
19243 // Parent method
19244 OO.ui.MenuSelectWidget.parent.prototype.clearItems.call( this );
19245
19246 // Reevaluate clipping
19247 this.clip();
19248
19249 return this;
19250 };
19251
19252 /**
19253 * @inheritdoc
19254 */
19255 OO.ui.MenuSelectWidget.prototype.toggle = function ( visible ) {
19256 var i, len, change;
19257
19258 visible = ( visible === undefined ? !this.visible : !!visible ) && !!this.items.length;
19259 change = visible !== this.isVisible();
19260
19261 // Parent method
19262 OO.ui.MenuSelectWidget.parent.prototype.toggle.call( this, visible );
19263
19264 if ( change ) {
19265 if ( visible ) {
19266 this.bindKeyDownListener();
19267 this.bindKeyPressListener();
19268
19269 if ( this.newItems && this.newItems.length ) {
19270 for ( i = 0, len = this.newItems.length; i < len; i++ ) {
19271 this.newItems[ i ].fitLabel();
19272 }
19273 this.newItems = null;
19274 }
19275 this.toggleClipping( true );
19276
19277 // Auto-hide
19278 if ( this.autoHide ) {
19279 OO.ui.addCaptureEventListener( this.getElementDocument(), 'mousedown', this.onDocumentMouseDownHandler );
19280 }
19281 } else {
19282 this.unbindKeyDownListener();
19283 this.unbindKeyPressListener();
19284 OO.ui.removeCaptureEventListener( this.getElementDocument(), 'mousedown', this.onDocumentMouseDownHandler );
19285 this.toggleClipping( false );
19286 }
19287 }
19288
19289 return this;
19290 };
19291
19292 /**
19293 * FloatingMenuSelectWidget is a menu that will stick under a specified
19294 * container, even when it is inserted elsewhere in the document (for example,
19295 * in a OO.ui.Window's $overlay). This is sometimes necessary to prevent the
19296 * menu from being clipped too aggresively.
19297 *
19298 * The menu's position is automatically calculated and maintained when the menu
19299 * is toggled or the window is resized.
19300 *
19301 * See OO.ui.ComboBoxInputWidget for an example of a widget that uses this class.
19302 *
19303 * @class
19304 * @extends OO.ui.MenuSelectWidget
19305 * @mixins OO.ui.mixin.FloatableElement
19306 *
19307 * @constructor
19308 * @param {OO.ui.Widget} [inputWidget] Widget to provide the menu for.
19309 * Deprecated, omit this parameter and specify `$container` instead.
19310 * @param {Object} [config] Configuration options
19311 * @cfg {jQuery} [$container=inputWidget.$element] Element to render menu under
19312 */
19313 OO.ui.FloatingMenuSelectWidget = function OoUiFloatingMenuSelectWidget( inputWidget, config ) {
19314 // Allow 'inputWidget' parameter and config for backwards compatibility
19315 if ( OO.isPlainObject( inputWidget ) && config === undefined ) {
19316 config = inputWidget;
19317 inputWidget = config.inputWidget;
19318 }
19319
19320 // Configuration initialization
19321 config = config || {};
19322
19323 // Parent constructor
19324 OO.ui.FloatingMenuSelectWidget.parent.call( this, config );
19325
19326 // Properties (must be set before mixin constructors)
19327 this.inputWidget = inputWidget; // For backwards compatibility
19328 this.$container = config.$container || this.inputWidget.$element;
19329
19330 // Mixins constructors
19331 OO.ui.mixin.FloatableElement.call( this, $.extend( {}, config, { $floatableContainer: this.$container } ) );
19332
19333 // Initialization
19334 this.$element.addClass( 'oo-ui-floatingMenuSelectWidget' );
19335 // For backwards compatibility
19336 this.$element.addClass( 'oo-ui-textInputMenuSelectWidget' );
19337 };
19338
19339 /* Setup */
19340
19341 OO.inheritClass( OO.ui.FloatingMenuSelectWidget, OO.ui.MenuSelectWidget );
19342 OO.mixinClass( OO.ui.FloatingMenuSelectWidget, OO.ui.mixin.FloatableElement );
19343
19344 // For backwards compatibility
19345 OO.ui.TextInputMenuSelectWidget = OO.ui.FloatingMenuSelectWidget;
19346
19347 /* Methods */
19348
19349 /**
19350 * @inheritdoc
19351 */
19352 OO.ui.FloatingMenuSelectWidget.prototype.toggle = function ( visible ) {
19353 var change;
19354 visible = visible === undefined ? !this.isVisible() : !!visible;
19355 change = visible !== this.isVisible();
19356
19357 if ( change && visible ) {
19358 // Make sure the width is set before the parent method runs.
19359 this.setIdealSize( this.$container.width() );
19360 }
19361
19362 // Parent method
19363 // This will call this.clip(), which is nonsensical since we're not positioned yet...
19364 OO.ui.FloatingMenuSelectWidget.parent.prototype.toggle.call( this, visible );
19365
19366 if ( change ) {
19367 this.togglePositioning( this.isVisible() );
19368 }
19369
19370 return this;
19371 };
19372
19373 /**
19374 * OutlineSelectWidget is a structured list that contains {@link OO.ui.OutlineOptionWidget outline options}
19375 * A set of controls can be provided with an {@link OO.ui.OutlineControlsWidget outline controls} widget.
19376 *
19377 * **Currently, this class is only used by {@link OO.ui.BookletLayout booklet layouts}.**
19378 *
19379 * @class
19380 * @extends OO.ui.SelectWidget
19381 * @mixins OO.ui.mixin.TabIndexedElement
19382 *
19383 * @constructor
19384 * @param {Object} [config] Configuration options
19385 */
19386 OO.ui.OutlineSelectWidget = function OoUiOutlineSelectWidget( config ) {
19387 // Parent constructor
19388 OO.ui.OutlineSelectWidget.parent.call( this, config );
19389
19390 // Mixin constructors
19391 OO.ui.mixin.TabIndexedElement.call( this, config );
19392
19393 // Events
19394 this.$element.on( {
19395 focus: this.bindKeyDownListener.bind( this ),
19396 blur: this.unbindKeyDownListener.bind( this )
19397 } );
19398
19399 // Initialization
19400 this.$element.addClass( 'oo-ui-outlineSelectWidget' );
19401 };
19402
19403 /* Setup */
19404
19405 OO.inheritClass( OO.ui.OutlineSelectWidget, OO.ui.SelectWidget );
19406 OO.mixinClass( OO.ui.OutlineSelectWidget, OO.ui.mixin.TabIndexedElement );
19407
19408 /**
19409 * TabSelectWidget is a list that contains {@link OO.ui.TabOptionWidget tab options}
19410 *
19411 * **Currently, this class is only used by {@link OO.ui.IndexLayout index layouts}.**
19412 *
19413 * @class
19414 * @extends OO.ui.SelectWidget
19415 * @mixins OO.ui.mixin.TabIndexedElement
19416 *
19417 * @constructor
19418 * @param {Object} [config] Configuration options
19419 */
19420 OO.ui.TabSelectWidget = function OoUiTabSelectWidget( config ) {
19421 // Parent constructor
19422 OO.ui.TabSelectWidget.parent.call( this, config );
19423
19424 // Mixin constructors
19425 OO.ui.mixin.TabIndexedElement.call( this, config );
19426
19427 // Events
19428 this.$element.on( {
19429 focus: this.bindKeyDownListener.bind( this ),
19430 blur: this.unbindKeyDownListener.bind( this )
19431 } );
19432
19433 // Initialization
19434 this.$element.addClass( 'oo-ui-tabSelectWidget' );
19435 };
19436
19437 /* Setup */
19438
19439 OO.inheritClass( OO.ui.TabSelectWidget, OO.ui.SelectWidget );
19440 OO.mixinClass( OO.ui.TabSelectWidget, OO.ui.mixin.TabIndexedElement );
19441
19442 /**
19443 * NumberInputWidgets combine a {@link OO.ui.TextInputWidget text input} (where a value
19444 * can be entered manually) and two {@link OO.ui.ButtonWidget button widgets}
19445 * (to adjust the value in increments) to allow the user to enter a number.
19446 *
19447 * @example
19448 * // Example: A NumberInputWidget.
19449 * var numberInput = new OO.ui.NumberInputWidget( {
19450 * label: 'NumberInputWidget',
19451 * input: { value: 5, min: 1, max: 10 }
19452 * } );
19453 * $( 'body' ).append( numberInput.$element );
19454 *
19455 * @class
19456 * @extends OO.ui.Widget
19457 *
19458 * @constructor
19459 * @param {Object} [config] Configuration options
19460 * @cfg {Object} [input] Configuration options to pass to the {@link OO.ui.TextInputWidget text input widget}.
19461 * @cfg {Object} [minusButton] Configuration options to pass to the {@link OO.ui.ButtonWidget decrementing button widget}.
19462 * @cfg {Object} [plusButton] Configuration options to pass to the {@link OO.ui.ButtonWidget incrementing button widget}.
19463 * @cfg {boolean} [isInteger=false] Whether the field accepts only integer values.
19464 * @cfg {number} [min=-Infinity] Minimum allowed value
19465 * @cfg {number} [max=Infinity] Maximum allowed value
19466 * @cfg {number} [step=1] Delta when using the buttons or up/down arrow keys
19467 * @cfg {number|null} [pageStep] Delta when using the page-up/page-down keys. Defaults to 10 times #step.
19468 */
19469 OO.ui.NumberInputWidget = function OoUiNumberInputWidget( config ) {
19470 // Configuration initialization
19471 config = $.extend( {
19472 isInteger: false,
19473 min: -Infinity,
19474 max: Infinity,
19475 step: 1,
19476 pageStep: null
19477 }, config );
19478
19479 // Parent constructor
19480 OO.ui.NumberInputWidget.parent.call( this, config );
19481
19482 // Properties
19483 this.input = new OO.ui.TextInputWidget( $.extend(
19484 {
19485 disabled: this.isDisabled()
19486 },
19487 config.input
19488 ) );
19489 this.minusButton = new OO.ui.ButtonWidget( $.extend(
19490 {
19491 disabled: this.isDisabled(),
19492 tabIndex: -1
19493 },
19494 config.minusButton,
19495 {
19496 classes: [ 'oo-ui-numberInputWidget-minusButton' ],
19497 label: '−'
19498 }
19499 ) );
19500 this.plusButton = new OO.ui.ButtonWidget( $.extend(
19501 {
19502 disabled: this.isDisabled(),
19503 tabIndex: -1
19504 },
19505 config.plusButton,
19506 {
19507 classes: [ 'oo-ui-numberInputWidget-plusButton' ],
19508 label: '+'
19509 }
19510 ) );
19511
19512 // Events
19513 this.input.connect( this, {
19514 change: this.emit.bind( this, 'change' ),
19515 enter: this.emit.bind( this, 'enter' )
19516 } );
19517 this.input.$input.on( {
19518 keydown: this.onKeyDown.bind( this ),
19519 'wheel mousewheel DOMMouseScroll': this.onWheel.bind( this )
19520 } );
19521 this.plusButton.connect( this, {
19522 click: [ 'onButtonClick', +1 ]
19523 } );
19524 this.minusButton.connect( this, {
19525 click: [ 'onButtonClick', -1 ]
19526 } );
19527
19528 // Initialization
19529 this.setIsInteger( !!config.isInteger );
19530 this.setRange( config.min, config.max );
19531 this.setStep( config.step, config.pageStep );
19532
19533 this.$field = $( '<div>' ).addClass( 'oo-ui-numberInputWidget-field' )
19534 .append(
19535 this.minusButton.$element,
19536 this.input.$element,
19537 this.plusButton.$element
19538 );
19539 this.$element.addClass( 'oo-ui-numberInputWidget' ).append( this.$field );
19540 this.input.setValidation( this.validateNumber.bind( this ) );
19541 };
19542
19543 /* Setup */
19544
19545 OO.inheritClass( OO.ui.NumberInputWidget, OO.ui.Widget );
19546
19547 /* Events */
19548
19549 /**
19550 * A `change` event is emitted when the value of the input changes.
19551 *
19552 * @event change
19553 */
19554
19555 /**
19556 * An `enter` event is emitted when the user presses 'enter' inside the text box.
19557 *
19558 * @event enter
19559 */
19560
19561 /* Methods */
19562
19563 /**
19564 * Set whether only integers are allowed
19565 * @param {boolean} flag
19566 */
19567 OO.ui.NumberInputWidget.prototype.setIsInteger = function ( flag ) {
19568 this.isInteger = !!flag;
19569 this.input.setValidityFlag();
19570 };
19571
19572 /**
19573 * Get whether only integers are allowed
19574 * @return {boolean} Flag value
19575 */
19576 OO.ui.NumberInputWidget.prototype.getIsInteger = function () {
19577 return this.isInteger;
19578 };
19579
19580 /**
19581 * Set the range of allowed values
19582 * @param {number} min Minimum allowed value
19583 * @param {number} max Maximum allowed value
19584 */
19585 OO.ui.NumberInputWidget.prototype.setRange = function ( min, max ) {
19586 if ( min > max ) {
19587 throw new Error( 'Minimum (' + min + ') must not be greater than maximum (' + max + ')' );
19588 }
19589 this.min = min;
19590 this.max = max;
19591 this.input.setValidityFlag();
19592 };
19593
19594 /**
19595 * Get the current range
19596 * @return {number[]} Minimum and maximum values
19597 */
19598 OO.ui.NumberInputWidget.prototype.getRange = function () {
19599 return [ this.min, this.max ];
19600 };
19601
19602 /**
19603 * Set the stepping deltas
19604 * @param {number} step Normal step
19605 * @param {number|null} pageStep Page step. If null, 10 * step will be used.
19606 */
19607 OO.ui.NumberInputWidget.prototype.setStep = function ( step, pageStep ) {
19608 if ( step <= 0 ) {
19609 throw new Error( 'Step value must be positive' );
19610 }
19611 if ( pageStep === null ) {
19612 pageStep = step * 10;
19613 } else if ( pageStep <= 0 ) {
19614 throw new Error( 'Page step value must be positive' );
19615 }
19616 this.step = step;
19617 this.pageStep = pageStep;
19618 };
19619
19620 /**
19621 * Get the current stepping values
19622 * @return {number[]} Step and page step
19623 */
19624 OO.ui.NumberInputWidget.prototype.getStep = function () {
19625 return [ this.step, this.pageStep ];
19626 };
19627
19628 /**
19629 * Get the current value of the widget
19630 * @return {string}
19631 */
19632 OO.ui.NumberInputWidget.prototype.getValue = function () {
19633 return this.input.getValue();
19634 };
19635
19636 /**
19637 * Get the current value of the widget as a number
19638 * @return {number} May be NaN, or an invalid number
19639 */
19640 OO.ui.NumberInputWidget.prototype.getNumericValue = function () {
19641 return +this.input.getValue();
19642 };
19643
19644 /**
19645 * Set the value of the widget
19646 * @param {string} value Invalid values are allowed
19647 */
19648 OO.ui.NumberInputWidget.prototype.setValue = function ( value ) {
19649 this.input.setValue( value );
19650 };
19651
19652 /**
19653 * Adjust the value of the widget
19654 * @param {number} delta Adjustment amount
19655 */
19656 OO.ui.NumberInputWidget.prototype.adjustValue = function ( delta ) {
19657 var n, v = this.getNumericValue();
19658
19659 delta = +delta;
19660 if ( isNaN( delta ) || !isFinite( delta ) ) {
19661 throw new Error( 'Delta must be a finite number' );
19662 }
19663
19664 if ( isNaN( v ) ) {
19665 n = 0;
19666 } else {
19667 n = v + delta;
19668 n = Math.max( Math.min( n, this.max ), this.min );
19669 if ( this.isInteger ) {
19670 n = Math.round( n );
19671 }
19672 }
19673
19674 if ( n !== v ) {
19675 this.setValue( n );
19676 }
19677 };
19678
19679 /**
19680 * Validate input
19681 * @private
19682 * @param {string} value Field value
19683 * @return {boolean}
19684 */
19685 OO.ui.NumberInputWidget.prototype.validateNumber = function ( value ) {
19686 var n = +value;
19687 if ( isNaN( n ) || !isFinite( n ) ) {
19688 return false;
19689 }
19690
19691 /*jshint bitwise: false */
19692 if ( this.isInteger && ( n | 0 ) !== n ) {
19693 return false;
19694 }
19695 /*jshint bitwise: true */
19696
19697 if ( n < this.min || n > this.max ) {
19698 return false;
19699 }
19700
19701 return true;
19702 };
19703
19704 /**
19705 * Handle mouse click events.
19706 *
19707 * @private
19708 * @param {number} dir +1 or -1
19709 */
19710 OO.ui.NumberInputWidget.prototype.onButtonClick = function ( dir ) {
19711 this.adjustValue( dir * this.step );
19712 };
19713
19714 /**
19715 * Handle mouse wheel events.
19716 *
19717 * @private
19718 * @param {jQuery.Event} event
19719 */
19720 OO.ui.NumberInputWidget.prototype.onWheel = function ( event ) {
19721 var delta = 0;
19722
19723 // Standard 'wheel' event
19724 if ( event.originalEvent.deltaMode !== undefined ) {
19725 this.sawWheelEvent = true;
19726 }
19727 if ( event.originalEvent.deltaY ) {
19728 delta = -event.originalEvent.deltaY;
19729 } else if ( event.originalEvent.deltaX ) {
19730 delta = event.originalEvent.deltaX;
19731 }
19732
19733 // Non-standard events
19734 if ( !this.sawWheelEvent ) {
19735 if ( event.originalEvent.wheelDeltaX ) {
19736 delta = -event.originalEvent.wheelDeltaX;
19737 } else if ( event.originalEvent.wheelDeltaY ) {
19738 delta = event.originalEvent.wheelDeltaY;
19739 } else if ( event.originalEvent.wheelDelta ) {
19740 delta = event.originalEvent.wheelDelta;
19741 } else if ( event.originalEvent.detail ) {
19742 delta = -event.originalEvent.detail;
19743 }
19744 }
19745
19746 if ( delta ) {
19747 delta = delta < 0 ? -1 : 1;
19748 this.adjustValue( delta * this.step );
19749 }
19750
19751 return false;
19752 };
19753
19754 /**
19755 * Handle key down events.
19756 *
19757 * @private
19758 * @param {jQuery.Event} e Key down event
19759 */
19760 OO.ui.NumberInputWidget.prototype.onKeyDown = function ( e ) {
19761 if ( !this.isDisabled() ) {
19762 switch ( e.which ) {
19763 case OO.ui.Keys.UP:
19764 this.adjustValue( this.step );
19765 return false;
19766 case OO.ui.Keys.DOWN:
19767 this.adjustValue( -this.step );
19768 return false;
19769 case OO.ui.Keys.PAGEUP:
19770 this.adjustValue( this.pageStep );
19771 return false;
19772 case OO.ui.Keys.PAGEDOWN:
19773 this.adjustValue( -this.pageStep );
19774 return false;
19775 }
19776 }
19777 };
19778
19779 /**
19780 * @inheritdoc
19781 */
19782 OO.ui.NumberInputWidget.prototype.setDisabled = function ( disabled ) {
19783 // Parent method
19784 OO.ui.NumberInputWidget.parent.prototype.setDisabled.call( this, disabled );
19785
19786 if ( this.input ) {
19787 this.input.setDisabled( this.isDisabled() );
19788 }
19789 if ( this.minusButton ) {
19790 this.minusButton.setDisabled( this.isDisabled() );
19791 }
19792 if ( this.plusButton ) {
19793 this.plusButton.setDisabled( this.isDisabled() );
19794 }
19795
19796 return this;
19797 };
19798
19799 /**
19800 * ToggleSwitches are switches that slide on and off. Their state is represented by a Boolean
19801 * value (`true` for ‘on’, and `false` otherwise, the default). The ‘off’ state is represented
19802 * visually by a slider in the leftmost position.
19803 *
19804 * @example
19805 * // Toggle switches in the 'off' and 'on' position.
19806 * var toggleSwitch1 = new OO.ui.ToggleSwitchWidget();
19807 * var toggleSwitch2 = new OO.ui.ToggleSwitchWidget( {
19808 * value: true
19809 * } );
19810 *
19811 * // Create a FieldsetLayout to layout and label switches
19812 * var fieldset = new OO.ui.FieldsetLayout( {
19813 * label: 'Toggle switches'
19814 * } );
19815 * fieldset.addItems( [
19816 * new OO.ui.FieldLayout( toggleSwitch1, { label: 'Off', align: 'top' } ),
19817 * new OO.ui.FieldLayout( toggleSwitch2, { label: 'On', align: 'top' } )
19818 * ] );
19819 * $( 'body' ).append( fieldset.$element );
19820 *
19821 * @class
19822 * @extends OO.ui.ToggleWidget
19823 * @mixins OO.ui.mixin.TabIndexedElement
19824 *
19825 * @constructor
19826 * @param {Object} [config] Configuration options
19827 * @cfg {boolean} [value=false] The toggle switch’s initial on/off state.
19828 * By default, the toggle switch is in the 'off' position.
19829 */
19830 OO.ui.ToggleSwitchWidget = function OoUiToggleSwitchWidget( config ) {
19831 // Parent constructor
19832 OO.ui.ToggleSwitchWidget.parent.call( this, config );
19833
19834 // Mixin constructors
19835 OO.ui.mixin.TabIndexedElement.call( this, config );
19836
19837 // Properties
19838 this.dragging = false;
19839 this.dragStart = null;
19840 this.sliding = false;
19841 this.$glow = $( '<span>' );
19842 this.$grip = $( '<span>' );
19843
19844 // Events
19845 this.$element.on( {
19846 click: this.onClick.bind( this ),
19847 keypress: this.onKeyPress.bind( this )
19848 } );
19849
19850 // Initialization
19851 this.$glow.addClass( 'oo-ui-toggleSwitchWidget-glow' );
19852 this.$grip.addClass( 'oo-ui-toggleSwitchWidget-grip' );
19853 this.$element
19854 .addClass( 'oo-ui-toggleSwitchWidget' )
19855 .attr( 'role', 'checkbox' )
19856 .append( this.$glow, this.$grip );
19857 };
19858
19859 /* Setup */
19860
19861 OO.inheritClass( OO.ui.ToggleSwitchWidget, OO.ui.ToggleWidget );
19862 OO.mixinClass( OO.ui.ToggleSwitchWidget, OO.ui.mixin.TabIndexedElement );
19863
19864 /* Methods */
19865
19866 /**
19867 * Handle mouse click events.
19868 *
19869 * @private
19870 * @param {jQuery.Event} e Mouse click event
19871 */
19872 OO.ui.ToggleSwitchWidget.prototype.onClick = function ( e ) {
19873 if ( !this.isDisabled() && e.which === 1 ) {
19874 this.setValue( !this.value );
19875 }
19876 return false;
19877 };
19878
19879 /**
19880 * Handle key press events.
19881 *
19882 * @private
19883 * @param {jQuery.Event} e Key press event
19884 */
19885 OO.ui.ToggleSwitchWidget.prototype.onKeyPress = function ( e ) {
19886 if ( !this.isDisabled() && ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER ) ) {
19887 this.setValue( !this.value );
19888 return false;
19889 }
19890 };
19891
19892 }( OO ) );