Merge "Actually declare the base LoadMonior::clearCaches"
[lhc/web/wiklou.git] / resources / lib / oojs-ui / oojs-ui.js
1 /*
2 * Local backports:
3 *
4 * - d190bc51e60195eed81f147e9324c9ec21c9e68c
5 * FloatableElement: Don't try unbinding events before we bind them
6 * Required for mw.widgets.DateInputWidget when used with '$overlay' config option.
7 */
8
9 /*!
10 * OOjs UI v0.12.9
11 * https://www.mediawiki.org/wiki/OOjs_UI
12 *
13 * Copyright 2011–2015 OOjs UI Team and other contributors.
14 * Released under the MIT license
15 * http://oojs.mit-license.org
16 *
17 * Date: 2015-09-22T20:09:51Z
18 */
19 ( function ( OO ) {
20
21 'use strict';
22
23 /**
24 * Namespace for all classes, static methods and static properties.
25 *
26 * @class
27 * @singleton
28 */
29 OO.ui = {};
30
31 OO.ui.bind = $.proxy;
32
33 /**
34 * @property {Object}
35 */
36 OO.ui.Keys = {
37 UNDEFINED: 0,
38 BACKSPACE: 8,
39 DELETE: 46,
40 LEFT: 37,
41 RIGHT: 39,
42 UP: 38,
43 DOWN: 40,
44 ENTER: 13,
45 END: 35,
46 HOME: 36,
47 TAB: 9,
48 PAGEUP: 33,
49 PAGEDOWN: 34,
50 ESCAPE: 27,
51 SHIFT: 16,
52 SPACE: 32
53 };
54
55 /**
56 * @property {Number}
57 */
58 OO.ui.elementId = 0;
59
60 /**
61 * Generate a unique ID for element
62 *
63 * @return {String} [id]
64 */
65 OO.ui.generateElementId = function () {
66 OO.ui.elementId += 1;
67 return 'oojsui-' + OO.ui.elementId;
68 };
69
70 /**
71 * Check if an element is focusable.
72 * Inspired from :focusable in jQueryUI v1.11.4 - 2015-04-14
73 *
74 * @param {jQuery} element Element to test
75 * @return {boolean}
76 */
77 OO.ui.isFocusableElement = function ( $element ) {
78 var nodeName,
79 element = $element[ 0 ];
80
81 // Anything disabled is not focusable
82 if ( element.disabled ) {
83 return false;
84 }
85
86 // Check if the element is visible
87 if ( !(
88 // This is quicker than calling $element.is( ':visible' )
89 $.expr.filters.visible( element ) &&
90 // Check that all parents are visible
91 !$element.parents().addBack().filter( function () {
92 return $.css( this, 'visibility' ) === 'hidden';
93 } ).length
94 ) ) {
95 return false;
96 }
97
98 // Check if the element is ContentEditable, which is the string 'true'
99 if ( element.contentEditable === 'true' ) {
100 return true;
101 }
102
103 // Anything with a non-negative numeric tabIndex is focusable.
104 // Use .prop to avoid browser bugs
105 if ( $element.prop( 'tabIndex' ) >= 0 ) {
106 return true;
107 }
108
109 // Some element types are naturally focusable
110 // (indexOf is much faster than regex in Chrome and about the
111 // same in FF: https://jsperf.com/regex-vs-indexof-array2)
112 nodeName = element.nodeName.toLowerCase();
113 if ( [ 'input', 'select', 'textarea', 'button', 'object' ].indexOf( nodeName ) !== -1 ) {
114 return true;
115 }
116
117 // Links and areas are focusable if they have an href
118 if ( ( nodeName === 'a' || nodeName === 'area' ) && $element.attr( 'href' ) !== undefined ) {
119 return true;
120 }
121
122 return false;
123 };
124
125 /**
126 * Find a focusable child
127 *
128 * @param {jQuery} $container Container to search in
129 * @param {boolean} [backwards] Search backwards
130 * @return {jQuery} Focusable child, an empty jQuery object if none found
131 */
132 OO.ui.findFocusable = function ( $container, backwards ) {
133 var $focusable = $( [] ),
134 // $focusableCandidates is a superset of things that
135 // could get matched by isFocusableElement
136 $focusableCandidates = $container
137 .find( 'input, select, textarea, button, object, a, area, [contenteditable], [tabindex]' );
138
139 if ( backwards ) {
140 $focusableCandidates = Array.prototype.reverse.call( $focusableCandidates );
141 }
142
143 $focusableCandidates.each( function () {
144 var $this = $( this );
145 if ( OO.ui.isFocusableElement( $this ) ) {
146 $focusable = $this;
147 return false;
148 }
149 } );
150 return $focusable;
151 };
152
153 /**
154 * Get the user's language and any fallback languages.
155 *
156 * These language codes are used to localize user interface elements in the user's language.
157 *
158 * In environments that provide a localization system, this function should be overridden to
159 * return the user's language(s). The default implementation returns English (en) only.
160 *
161 * @return {string[]} Language codes, in descending order of priority
162 */
163 OO.ui.getUserLanguages = function () {
164 return [ 'en' ];
165 };
166
167 /**
168 * Get a value in an object keyed by language code.
169 *
170 * @param {Object.<string,Mixed>} obj Object keyed by language code
171 * @param {string|null} [lang] Language code, if omitted or null defaults to any user language
172 * @param {string} [fallback] Fallback code, used if no matching language can be found
173 * @return {Mixed} Local value
174 */
175 OO.ui.getLocalValue = function ( obj, lang, fallback ) {
176 var i, len, langs;
177
178 // Requested language
179 if ( obj[ lang ] ) {
180 return obj[ lang ];
181 }
182 // Known user language
183 langs = OO.ui.getUserLanguages();
184 for ( i = 0, len = langs.length; i < len; i++ ) {
185 lang = langs[ i ];
186 if ( obj[ lang ] ) {
187 return obj[ lang ];
188 }
189 }
190 // Fallback language
191 if ( obj[ fallback ] ) {
192 return obj[ fallback ];
193 }
194 // First existing language
195 for ( lang in obj ) {
196 return obj[ lang ];
197 }
198
199 return undefined;
200 };
201
202 /**
203 * Check if a node is contained within another node
204 *
205 * Similar to jQuery#contains except a list of containers can be supplied
206 * and a boolean argument allows you to include the container in the match list
207 *
208 * @param {HTMLElement|HTMLElement[]} containers Container node(s) to search in
209 * @param {HTMLElement} contained Node to find
210 * @param {boolean} [matchContainers] Include the container(s) in the list of nodes to match, otherwise only match descendants
211 * @return {boolean} The node is in the list of target nodes
212 */
213 OO.ui.contains = function ( containers, contained, matchContainers ) {
214 var i;
215 if ( !Array.isArray( containers ) ) {
216 containers = [ containers ];
217 }
218 for ( i = containers.length - 1; i >= 0; i-- ) {
219 if ( ( matchContainers && contained === containers[ i ] ) || $.contains( containers[ i ], contained ) ) {
220 return true;
221 }
222 }
223 return false;
224 };
225
226 /**
227 * Return a function, that, as long as it continues to be invoked, will not
228 * be triggered. The function will be called after it stops being called for
229 * N milliseconds. If `immediate` is passed, trigger the function on the
230 * leading edge, instead of the trailing.
231 *
232 * Ported from: http://underscorejs.org/underscore.js
233 *
234 * @param {Function} func
235 * @param {number} wait
236 * @param {boolean} immediate
237 * @return {Function}
238 */
239 OO.ui.debounce = function ( func, wait, immediate ) {
240 var timeout;
241 return function () {
242 var context = this,
243 args = arguments,
244 later = function () {
245 timeout = null;
246 if ( !immediate ) {
247 func.apply( context, args );
248 }
249 };
250 if ( immediate && !timeout ) {
251 func.apply( context, args );
252 }
253 clearTimeout( timeout );
254 timeout = setTimeout( later, wait );
255 };
256 };
257
258 /**
259 * Proxy for `node.addEventListener( eventName, handler, true )`, if the browser supports it.
260 * Otherwise falls back to non-capturing event listeners.
261 *
262 * @param {HTMLElement} node
263 * @param {string} eventName
264 * @param {Function} handler
265 */
266 OO.ui.addCaptureEventListener = function ( node, eventName, handler ) {
267 if ( node.addEventListener ) {
268 node.addEventListener( eventName, handler, true );
269 } else {
270 node.attachEvent( 'on' + eventName, handler );
271 }
272 };
273
274 /**
275 * Proxy for `node.removeEventListener( eventName, handler, true )`, if the browser supports it.
276 * Otherwise falls back to non-capturing event listeners.
277 *
278 * @param {HTMLElement} node
279 * @param {string} eventName
280 * @param {Function} handler
281 */
282 OO.ui.removeCaptureEventListener = function ( node, eventName, handler ) {
283 if ( node.addEventListener ) {
284 node.removeEventListener( eventName, handler, true );
285 } else {
286 node.detachEvent( 'on' + eventName, handler );
287 }
288 };
289
290 /**
291 * Reconstitute a JavaScript object corresponding to a widget created by
292 * the PHP implementation.
293 *
294 * This is an alias for `OO.ui.Element.static.infuse()`.
295 *
296 * @param {string|HTMLElement|jQuery} idOrNode
297 * A DOM id (if a string) or node for the widget to infuse.
298 * @return {OO.ui.Element}
299 * The `OO.ui.Element` corresponding to this (infusable) document node.
300 */
301 OO.ui.infuse = function ( idOrNode ) {
302 return OO.ui.Element.static.infuse( idOrNode );
303 };
304
305 ( function () {
306 /**
307 * Message store for the default implementation of OO.ui.msg
308 *
309 * Environments that provide a localization system should not use this, but should override
310 * OO.ui.msg altogether.
311 *
312 * @private
313 */
314 var messages = {
315 // Tool tip for a button that moves items in a list down one place
316 'ooui-outline-control-move-down': 'Move item down',
317 // Tool tip for a button that moves items in a list up one place
318 'ooui-outline-control-move-up': 'Move item up',
319 // Tool tip for a button that removes items from a list
320 'ooui-outline-control-remove': 'Remove item',
321 // Label for the toolbar group that contains a list of all other available tools
322 'ooui-toolbar-more': 'More',
323 // Label for the fake tool that expands the full list of tools in a toolbar group
324 'ooui-toolgroup-expand': 'More',
325 // Label for the fake tool that collapses the full list of tools in a toolbar group
326 'ooui-toolgroup-collapse': 'Fewer',
327 // Default label for the accept button of a confirmation dialog
328 'ooui-dialog-message-accept': 'OK',
329 // Default label for the reject button of a confirmation dialog
330 'ooui-dialog-message-reject': 'Cancel',
331 // Title for process dialog error description
332 'ooui-dialog-process-error': 'Something went wrong',
333 // Label for process dialog dismiss error button, visible when describing errors
334 'ooui-dialog-process-dismiss': 'Dismiss',
335 // Label for process dialog retry action button, visible when describing only recoverable errors
336 'ooui-dialog-process-retry': 'Try again',
337 // Label for process dialog retry action button, visible when describing only warnings
338 'ooui-dialog-process-continue': 'Continue',
339 // Label for the file selection widget's select file button
340 'ooui-selectfile-button-select': 'Select a file',
341 // Label for the file selection widget if file selection is not supported
342 'ooui-selectfile-not-supported': 'File selection is not supported',
343 // Label for the file selection widget when no file is currently selected
344 'ooui-selectfile-placeholder': 'No file is selected',
345 // Label for the file selection widget's drop target
346 'ooui-selectfile-dragdrop-placeholder': 'Drop file here'
347 };
348
349 /**
350 * Get a localized message.
351 *
352 * In environments that provide a localization system, this function should be overridden to
353 * return the message translated in the user's language. The default implementation always returns
354 * English messages.
355 *
356 * After the message key, message parameters may optionally be passed. In the default implementation,
357 * any occurrences of $1 are replaced with the first parameter, $2 with the second parameter, etc.
358 * Alternative implementations of OO.ui.msg may use any substitution system they like, as long as
359 * they support unnamed, ordered message parameters.
360 *
361 * @abstract
362 * @param {string} key Message key
363 * @param {Mixed...} [params] Message parameters
364 * @return {string} Translated message with parameters substituted
365 */
366 OO.ui.msg = function ( key ) {
367 var message = messages[ key ],
368 params = Array.prototype.slice.call( arguments, 1 );
369 if ( typeof message === 'string' ) {
370 // Perform $1 substitution
371 message = message.replace( /\$(\d+)/g, function ( unused, n ) {
372 var i = parseInt( n, 10 );
373 return params[ i - 1 ] !== undefined ? params[ i - 1 ] : '$' + n;
374 } );
375 } else {
376 // Return placeholder if message not found
377 message = '[' + key + ']';
378 }
379 return message;
380 };
381
382 /**
383 * Package a message and arguments for deferred resolution.
384 *
385 * Use this when you are statically specifying a message and the message may not yet be present.
386 *
387 * @param {string} key Message key
388 * @param {Mixed...} [params] Message parameters
389 * @return {Function} Function that returns the resolved message when executed
390 */
391 OO.ui.deferMsg = function () {
392 var args = arguments;
393 return function () {
394 return OO.ui.msg.apply( OO.ui, args );
395 };
396 };
397
398 /**
399 * Resolve a message.
400 *
401 * If the message is a function it will be executed, otherwise it will pass through directly.
402 *
403 * @param {Function|string} msg Deferred message, or message text
404 * @return {string} Resolved message
405 */
406 OO.ui.resolveMsg = function ( msg ) {
407 if ( $.isFunction( msg ) ) {
408 return msg();
409 }
410 return msg;
411 };
412
413 /**
414 * @param {string} url
415 * @return {boolean}
416 */
417 OO.ui.isSafeUrl = function ( url ) {
418 var protocol,
419 // Keep in sync with php/Tag.php
420 whitelist = [
421 'bitcoin:', 'ftp:', 'ftps:', 'geo:', 'git:', 'gopher:', 'http:', 'https:', 'irc:', 'ircs:',
422 'magnet:', 'mailto:', 'mms:', 'news:', 'nntp:', 'redis:', 'sftp:', 'sip:', 'sips:', 'sms:', 'ssh:',
423 'svn:', 'tel:', 'telnet:', 'urn:', 'worldwind:', 'xmpp:'
424 ];
425
426 if ( url.indexOf( ':' ) === -1 ) {
427 // No protocol, safe
428 return true;
429 }
430
431 protocol = url.split( ':', 1 )[ 0 ] + ':';
432 if ( !protocol.match( /^([A-za-z0-9\+\.\-])+:/ ) ) {
433 // Not a valid protocol, safe
434 return true;
435 }
436
437 // Safe if in the whitelist
438 return whitelist.indexOf( protocol ) !== -1;
439 };
440
441 } )();
442
443 /*!
444 * Mixin namespace.
445 */
446
447 /**
448 * Namespace for OOjs UI mixins.
449 *
450 * Mixins are named according to the type of object they are intended to
451 * be mixed in to. For example, OO.ui.mixin.GroupElement is intended to be
452 * mixed in to an instance of OO.ui.Element, and OO.ui.mixin.GroupWidget
453 * is intended to be mixed in to an instance of OO.ui.Widget.
454 *
455 * @class
456 * @singleton
457 */
458 OO.ui.mixin = {};
459
460 /**
461 * PendingElement is a mixin that is used to create elements that notify users that something is happening
462 * and that they should wait before proceeding. The pending state is visually represented with a pending
463 * texture that appears in the head of a pending {@link OO.ui.ProcessDialog process dialog} or in the input
464 * field of a {@link OO.ui.TextInputWidget text input widget}.
465 *
466 * Currently, {@link OO.ui.ActionWidget Action widgets}, which mix in this class, can also be marked as pending, but only when
467 * used in {@link OO.ui.MessageDialog message dialogs}. The behavior is not currently supported for action widgets used
468 * in process dialogs.
469 *
470 * @example
471 * function MessageDialog( config ) {
472 * MessageDialog.parent.call( this, config );
473 * }
474 * OO.inheritClass( MessageDialog, OO.ui.MessageDialog );
475 *
476 * MessageDialog.static.actions = [
477 * { action: 'save', label: 'Done', flags: 'primary' },
478 * { label: 'Cancel', flags: 'safe' }
479 * ];
480 *
481 * MessageDialog.prototype.initialize = function () {
482 * MessageDialog.parent.prototype.initialize.apply( this, arguments );
483 * this.content = new OO.ui.PanelLayout( { $: this.$, padded: true } );
484 * 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>' );
485 * this.$body.append( this.content.$element );
486 * };
487 * MessageDialog.prototype.getBodyHeight = function () {
488 * return 100;
489 * }
490 * MessageDialog.prototype.getActionProcess = function ( action ) {
491 * var dialog = this;
492 * if ( action === 'save' ) {
493 * dialog.getActions().get({actions: 'save'})[0].pushPending();
494 * return new OO.ui.Process()
495 * .next( 1000 )
496 * .next( function () {
497 * dialog.getActions().get({actions: 'save'})[0].popPending();
498 * } );
499 * }
500 * return MessageDialog.parent.prototype.getActionProcess.call( this, action );
501 * };
502 *
503 * var windowManager = new OO.ui.WindowManager();
504 * $( 'body' ).append( windowManager.$element );
505 *
506 * var dialog = new MessageDialog();
507 * windowManager.addWindows( [ dialog ] );
508 * windowManager.openWindow( dialog );
509 *
510 * @abstract
511 * @class
512 *
513 * @constructor
514 * @param {Object} [config] Configuration options
515 * @cfg {jQuery} [$pending] Element to mark as pending, defaults to this.$element
516 */
517 OO.ui.mixin.PendingElement = function OoUiMixinPendingElement( config ) {
518 // Configuration initialization
519 config = config || {};
520
521 // Properties
522 this.pending = 0;
523 this.$pending = null;
524
525 // Initialisation
526 this.setPendingElement( config.$pending || this.$element );
527 };
528
529 /* Setup */
530
531 OO.initClass( OO.ui.mixin.PendingElement );
532
533 /* Methods */
534
535 /**
536 * Set the pending element (and clean up any existing one).
537 *
538 * @param {jQuery} $pending The element to set to pending.
539 */
540 OO.ui.mixin.PendingElement.prototype.setPendingElement = function ( $pending ) {
541 if ( this.$pending ) {
542 this.$pending.removeClass( 'oo-ui-pendingElement-pending' );
543 }
544
545 this.$pending = $pending;
546 if ( this.pending > 0 ) {
547 this.$pending.addClass( 'oo-ui-pendingElement-pending' );
548 }
549 };
550
551 /**
552 * Check if an element is pending.
553 *
554 * @return {boolean} Element is pending
555 */
556 OO.ui.mixin.PendingElement.prototype.isPending = function () {
557 return !!this.pending;
558 };
559
560 /**
561 * Increase the pending counter. The pending state will remain active until the counter is zero
562 * (i.e., the number of calls to #pushPending and #popPending is the same).
563 *
564 * @chainable
565 */
566 OO.ui.mixin.PendingElement.prototype.pushPending = function () {
567 if ( this.pending === 0 ) {
568 this.$pending.addClass( 'oo-ui-pendingElement-pending' );
569 this.updateThemeClasses();
570 }
571 this.pending++;
572
573 return this;
574 };
575
576 /**
577 * Decrease the pending counter. The pending state will remain active until the counter is zero
578 * (i.e., the number of calls to #pushPending and #popPending is the same).
579 *
580 * @chainable
581 */
582 OO.ui.mixin.PendingElement.prototype.popPending = function () {
583 if ( this.pending === 1 ) {
584 this.$pending.removeClass( 'oo-ui-pendingElement-pending' );
585 this.updateThemeClasses();
586 }
587 this.pending = Math.max( 0, this.pending - 1 );
588
589 return this;
590 };
591
592 /**
593 * ActionSets manage the behavior of the {@link OO.ui.ActionWidget action widgets} that comprise them.
594 * Actions can be made available for specific contexts (modes) and circumstances
595 * (abilities). Action sets are primarily used with {@link OO.ui.Dialog Dialogs}.
596 *
597 * ActionSets contain two types of actions:
598 *
599 * - 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.
600 * - Other: Other actions include all non-special visible actions.
601 *
602 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
603 *
604 * @example
605 * // Example: An action set used in a process dialog
606 * function MyProcessDialog( config ) {
607 * MyProcessDialog.parent.call( this, config );
608 * }
609 * OO.inheritClass( MyProcessDialog, OO.ui.ProcessDialog );
610 * MyProcessDialog.static.title = 'An action set in a process dialog';
611 * // An action set that uses modes ('edit' and 'help' mode, in this example).
612 * MyProcessDialog.static.actions = [
613 * { action: 'continue', modes: 'edit', label: 'Continue', flags: [ 'primary', 'constructive' ] },
614 * { action: 'help', modes: 'edit', label: 'Help' },
615 * { modes: 'edit', label: 'Cancel', flags: 'safe' },
616 * { action: 'back', modes: 'help', label: 'Back', flags: 'safe' }
617 * ];
618 *
619 * MyProcessDialog.prototype.initialize = function () {
620 * MyProcessDialog.parent.prototype.initialize.apply( this, arguments );
621 * this.panel1 = new OO.ui.PanelLayout( { padded: true, expanded: false } );
622 * 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>' );
623 * this.panel2 = new OO.ui.PanelLayout( { padded: true, expanded: false } );
624 * 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>' );
625 * this.stackLayout = new OO.ui.StackLayout( {
626 * items: [ this.panel1, this.panel2 ]
627 * } );
628 * this.$body.append( this.stackLayout.$element );
629 * };
630 * MyProcessDialog.prototype.getSetupProcess = function ( data ) {
631 * return MyProcessDialog.parent.prototype.getSetupProcess.call( this, data )
632 * .next( function () {
633 * this.actions.setMode( 'edit' );
634 * }, this );
635 * };
636 * MyProcessDialog.prototype.getActionProcess = function ( action ) {
637 * if ( action === 'help' ) {
638 * this.actions.setMode( 'help' );
639 * this.stackLayout.setItem( this.panel2 );
640 * } else if ( action === 'back' ) {
641 * this.actions.setMode( 'edit' );
642 * this.stackLayout.setItem( this.panel1 );
643 * } else if ( action === 'continue' ) {
644 * var dialog = this;
645 * return new OO.ui.Process( function () {
646 * dialog.close();
647 * } );
648 * }
649 * return MyProcessDialog.parent.prototype.getActionProcess.call( this, action );
650 * };
651 * MyProcessDialog.prototype.getBodyHeight = function () {
652 * return this.panel1.$element.outerHeight( true );
653 * };
654 * var windowManager = new OO.ui.WindowManager();
655 * $( 'body' ).append( windowManager.$element );
656 * var dialog = new MyProcessDialog( {
657 * size: 'medium'
658 * } );
659 * windowManager.addWindows( [ dialog ] );
660 * windowManager.openWindow( dialog );
661 *
662 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Action_sets
663 *
664 * @abstract
665 * @class
666 * @mixins OO.EventEmitter
667 *
668 * @constructor
669 * @param {Object} [config] Configuration options
670 */
671 OO.ui.ActionSet = function OoUiActionSet( config ) {
672 // Configuration initialization
673 config = config || {};
674
675 // Mixin constructors
676 OO.EventEmitter.call( this );
677
678 // Properties
679 this.list = [];
680 this.categories = {
681 actions: 'getAction',
682 flags: 'getFlags',
683 modes: 'getModes'
684 };
685 this.categorized = {};
686 this.special = {};
687 this.others = [];
688 this.organized = false;
689 this.changing = false;
690 this.changed = false;
691 };
692
693 /* Setup */
694
695 OO.mixinClass( OO.ui.ActionSet, OO.EventEmitter );
696
697 /* Static Properties */
698
699 /**
700 * Symbolic name of the flags used to identify special actions. Special actions are displayed in the
701 * header of a {@link OO.ui.ProcessDialog process dialog}.
702 * See the [OOjs UI documentation on MediaWiki][2] for more information and examples.
703 *
704 * [2]:https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs
705 *
706 * @abstract
707 * @static
708 * @inheritable
709 * @property {string}
710 */
711 OO.ui.ActionSet.static.specialFlags = [ 'safe', 'primary' ];
712
713 /* Events */
714
715 /**
716 * @event click
717 *
718 * A 'click' event is emitted when an action is clicked.
719 *
720 * @param {OO.ui.ActionWidget} action Action that was clicked
721 */
722
723 /**
724 * @event resize
725 *
726 * A 'resize' event is emitted when an action widget is resized.
727 *
728 * @param {OO.ui.ActionWidget} action Action that was resized
729 */
730
731 /**
732 * @event add
733 *
734 * An 'add' event is emitted when actions are {@link #method-add added} to the action set.
735 *
736 * @param {OO.ui.ActionWidget[]} added Actions added
737 */
738
739 /**
740 * @event remove
741 *
742 * A 'remove' event is emitted when actions are {@link #method-remove removed}
743 * or {@link #clear cleared}.
744 *
745 * @param {OO.ui.ActionWidget[]} added Actions removed
746 */
747
748 /**
749 * @event change
750 *
751 * A 'change' event is emitted when actions are {@link #method-add added}, {@link #clear cleared},
752 * or {@link #method-remove removed} from the action set or when the {@link #setMode mode} is changed.
753 *
754 */
755
756 /* Methods */
757
758 /**
759 * Handle action change events.
760 *
761 * @private
762 * @fires change
763 */
764 OO.ui.ActionSet.prototype.onActionChange = function () {
765 this.organized = false;
766 if ( this.changing ) {
767 this.changed = true;
768 } else {
769 this.emit( 'change' );
770 }
771 };
772
773 /**
774 * Check if an action is one of the special actions.
775 *
776 * @param {OO.ui.ActionWidget} action Action to check
777 * @return {boolean} Action is special
778 */
779 OO.ui.ActionSet.prototype.isSpecial = function ( action ) {
780 var flag;
781
782 for ( flag in this.special ) {
783 if ( action === this.special[ flag ] ) {
784 return true;
785 }
786 }
787
788 return false;
789 };
790
791 /**
792 * Get action widgets based on the specified filter: ‘actions’, ‘flags’, ‘modes’, ‘visible’,
793 * or ‘disabled’.
794 *
795 * @param {Object} [filters] Filters to use, omit to get all actions
796 * @param {string|string[]} [filters.actions] Actions that action widgets must have
797 * @param {string|string[]} [filters.flags] Flags that action widgets must have (e.g., 'safe')
798 * @param {string|string[]} [filters.modes] Modes that action widgets must have
799 * @param {boolean} [filters.visible] Action widgets must be visible
800 * @param {boolean} [filters.disabled] Action widgets must be disabled
801 * @return {OO.ui.ActionWidget[]} Action widgets matching all criteria
802 */
803 OO.ui.ActionSet.prototype.get = function ( filters ) {
804 var i, len, list, category, actions, index, match, matches;
805
806 if ( filters ) {
807 this.organize();
808
809 // Collect category candidates
810 matches = [];
811 for ( category in this.categorized ) {
812 list = filters[ category ];
813 if ( list ) {
814 if ( !Array.isArray( list ) ) {
815 list = [ list ];
816 }
817 for ( i = 0, len = list.length; i < len; i++ ) {
818 actions = this.categorized[ category ][ list[ i ] ];
819 if ( Array.isArray( actions ) ) {
820 matches.push.apply( matches, actions );
821 }
822 }
823 }
824 }
825 // Remove by boolean filters
826 for ( i = 0, len = matches.length; i < len; i++ ) {
827 match = matches[ i ];
828 if (
829 ( filters.visible !== undefined && match.isVisible() !== filters.visible ) ||
830 ( filters.disabled !== undefined && match.isDisabled() !== filters.disabled )
831 ) {
832 matches.splice( i, 1 );
833 len--;
834 i--;
835 }
836 }
837 // Remove duplicates
838 for ( i = 0, len = matches.length; i < len; i++ ) {
839 match = matches[ i ];
840 index = matches.lastIndexOf( match );
841 while ( index !== i ) {
842 matches.splice( index, 1 );
843 len--;
844 index = matches.lastIndexOf( match );
845 }
846 }
847 return matches;
848 }
849 return this.list.slice();
850 };
851
852 /**
853 * Get 'special' actions.
854 *
855 * Special actions are the first visible action widgets with special flags, such as 'safe' and 'primary'.
856 * Special flags can be configured in subclasses by changing the static #specialFlags property.
857 *
858 * @return {OO.ui.ActionWidget[]|null} 'Special' action widgets.
859 */
860 OO.ui.ActionSet.prototype.getSpecial = function () {
861 this.organize();
862 return $.extend( {}, this.special );
863 };
864
865 /**
866 * Get 'other' actions.
867 *
868 * Other actions include all non-special visible action widgets.
869 *
870 * @return {OO.ui.ActionWidget[]} 'Other' action widgets
871 */
872 OO.ui.ActionSet.prototype.getOthers = function () {
873 this.organize();
874 return this.others.slice();
875 };
876
877 /**
878 * Set the mode (e.g., ‘edit’ or ‘view’). Only {@link OO.ui.ActionWidget#modes actions} configured
879 * to be available in the specified mode will be made visible. All other actions will be hidden.
880 *
881 * @param {string} mode The mode. Only actions configured to be available in the specified
882 * mode will be made visible.
883 * @chainable
884 * @fires toggle
885 * @fires change
886 */
887 OO.ui.ActionSet.prototype.setMode = function ( mode ) {
888 var i, len, action;
889
890 this.changing = true;
891 for ( i = 0, len = this.list.length; i < len; i++ ) {
892 action = this.list[ i ];
893 action.toggle( action.hasMode( mode ) );
894 }
895
896 this.organized = false;
897 this.changing = false;
898 this.emit( 'change' );
899
900 return this;
901 };
902
903 /**
904 * Set the abilities of the specified actions.
905 *
906 * Action widgets that are configured with the specified actions will be enabled
907 * or disabled based on the boolean values specified in the `actions`
908 * parameter.
909 *
910 * @param {Object.<string,boolean>} actions A list keyed by action name with boolean
911 * values that indicate whether or not the action should be enabled.
912 * @chainable
913 */
914 OO.ui.ActionSet.prototype.setAbilities = function ( actions ) {
915 var i, len, action, item;
916
917 for ( i = 0, len = this.list.length; i < len; i++ ) {
918 item = this.list[ i ];
919 action = item.getAction();
920 if ( actions[ action ] !== undefined ) {
921 item.setDisabled( !actions[ action ] );
922 }
923 }
924
925 return this;
926 };
927
928 /**
929 * Executes a function once per action.
930 *
931 * When making changes to multiple actions, use this method instead of iterating over the actions
932 * manually to defer emitting a #change event until after all actions have been changed.
933 *
934 * @param {Object|null} actions Filters to use to determine which actions to iterate over; see #get
935 * @param {Function} callback Callback to run for each action; callback is invoked with three
936 * arguments: the action, the action's index, the list of actions being iterated over
937 * @chainable
938 */
939 OO.ui.ActionSet.prototype.forEach = function ( filter, callback ) {
940 this.changed = false;
941 this.changing = true;
942 this.get( filter ).forEach( callback );
943 this.changing = false;
944 if ( this.changed ) {
945 this.emit( 'change' );
946 }
947
948 return this;
949 };
950
951 /**
952 * Add action widgets to the action set.
953 *
954 * @param {OO.ui.ActionWidget[]} actions Action widgets to add
955 * @chainable
956 * @fires add
957 * @fires change
958 */
959 OO.ui.ActionSet.prototype.add = function ( actions ) {
960 var i, len, action;
961
962 this.changing = true;
963 for ( i = 0, len = actions.length; i < len; i++ ) {
964 action = actions[ i ];
965 action.connect( this, {
966 click: [ 'emit', 'click', action ],
967 resize: [ 'emit', 'resize', action ],
968 toggle: [ 'onActionChange' ]
969 } );
970 this.list.push( action );
971 }
972 this.organized = false;
973 this.emit( 'add', actions );
974 this.changing = false;
975 this.emit( 'change' );
976
977 return this;
978 };
979
980 /**
981 * Remove action widgets from the set.
982 *
983 * To remove all actions, you may wish to use the #clear method instead.
984 *
985 * @param {OO.ui.ActionWidget[]} actions Action widgets to remove
986 * @chainable
987 * @fires remove
988 * @fires change
989 */
990 OO.ui.ActionSet.prototype.remove = function ( actions ) {
991 var i, len, index, action;
992
993 this.changing = true;
994 for ( i = 0, len = actions.length; i < len; i++ ) {
995 action = actions[ i ];
996 index = this.list.indexOf( action );
997 if ( index !== -1 ) {
998 action.disconnect( this );
999 this.list.splice( index, 1 );
1000 }
1001 }
1002 this.organized = false;
1003 this.emit( 'remove', actions );
1004 this.changing = false;
1005 this.emit( 'change' );
1006
1007 return this;
1008 };
1009
1010 /**
1011 * Remove all action widets from the set.
1012 *
1013 * To remove only specified actions, use the {@link #method-remove remove} method instead.
1014 *
1015 * @chainable
1016 * @fires remove
1017 * @fires change
1018 */
1019 OO.ui.ActionSet.prototype.clear = function () {
1020 var i, len, action,
1021 removed = this.list.slice();
1022
1023 this.changing = true;
1024 for ( i = 0, len = this.list.length; i < len; i++ ) {
1025 action = this.list[ i ];
1026 action.disconnect( this );
1027 }
1028
1029 this.list = [];
1030
1031 this.organized = false;
1032 this.emit( 'remove', removed );
1033 this.changing = false;
1034 this.emit( 'change' );
1035
1036 return this;
1037 };
1038
1039 /**
1040 * Organize actions.
1041 *
1042 * This is called whenever organized information is requested. It will only reorganize the actions
1043 * if something has changed since the last time it ran.
1044 *
1045 * @private
1046 * @chainable
1047 */
1048 OO.ui.ActionSet.prototype.organize = function () {
1049 var i, iLen, j, jLen, flag, action, category, list, item, special,
1050 specialFlags = this.constructor.static.specialFlags;
1051
1052 if ( !this.organized ) {
1053 this.categorized = {};
1054 this.special = {};
1055 this.others = [];
1056 for ( i = 0, iLen = this.list.length; i < iLen; i++ ) {
1057 action = this.list[ i ];
1058 if ( action.isVisible() ) {
1059 // Populate categories
1060 for ( category in this.categories ) {
1061 if ( !this.categorized[ category ] ) {
1062 this.categorized[ category ] = {};
1063 }
1064 list = action[ this.categories[ category ] ]();
1065 if ( !Array.isArray( list ) ) {
1066 list = [ list ];
1067 }
1068 for ( j = 0, jLen = list.length; j < jLen; j++ ) {
1069 item = list[ j ];
1070 if ( !this.categorized[ category ][ item ] ) {
1071 this.categorized[ category ][ item ] = [];
1072 }
1073 this.categorized[ category ][ item ].push( action );
1074 }
1075 }
1076 // Populate special/others
1077 special = false;
1078 for ( j = 0, jLen = specialFlags.length; j < jLen; j++ ) {
1079 flag = specialFlags[ j ];
1080 if ( !this.special[ flag ] && action.hasFlag( flag ) ) {
1081 this.special[ flag ] = action;
1082 special = true;
1083 break;
1084 }
1085 }
1086 if ( !special ) {
1087 this.others.push( action );
1088 }
1089 }
1090 }
1091 this.organized = true;
1092 }
1093
1094 return this;
1095 };
1096
1097 /**
1098 * Each Element represents a rendering in the DOM—a button or an icon, for example, or anything
1099 * that is visible to a user. Unlike {@link OO.ui.Widget widgets}, plain elements usually do not have events
1100 * connected to them and can't be interacted with.
1101 *
1102 * @abstract
1103 * @class
1104 *
1105 * @constructor
1106 * @param {Object} [config] Configuration options
1107 * @cfg {string[]} [classes] The names of the CSS classes to apply to the element. CSS styles are added
1108 * to the top level (e.g., the outermost div) of the element. See the [OOjs UI documentation on MediaWiki][2]
1109 * for an example.
1110 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#cssExample
1111 * @cfg {string} [id] The HTML id attribute used in the rendered tag.
1112 * @cfg {string} [text] Text to insert
1113 * @cfg {Array} [content] An array of content elements to append (after #text).
1114 * Strings will be html-escaped; use an OO.ui.HtmlSnippet to append raw HTML.
1115 * Instances of OO.ui.Element will have their $element appended.
1116 * @cfg {jQuery} [$content] Content elements to append (after #text)
1117 * @cfg {Mixed} [data] Custom data of any type or combination of types (e.g., string, number, array, object).
1118 * Data can also be specified with the #setData method.
1119 */
1120 OO.ui.Element = function OoUiElement( config ) {
1121 // Configuration initialization
1122 config = config || {};
1123
1124 // Properties
1125 this.$ = $;
1126 this.visible = true;
1127 this.data = config.data;
1128 this.$element = config.$element ||
1129 $( document.createElement( this.getTagName() ) );
1130 this.elementGroup = null;
1131 this.debouncedUpdateThemeClassesHandler = OO.ui.debounce( this.debouncedUpdateThemeClasses );
1132
1133 // Initialization
1134 if ( Array.isArray( config.classes ) ) {
1135 this.$element.addClass( config.classes.join( ' ' ) );
1136 }
1137 if ( config.id ) {
1138 this.$element.attr( 'id', config.id );
1139 }
1140 if ( config.text ) {
1141 this.$element.text( config.text );
1142 }
1143 if ( config.content ) {
1144 // The `content` property treats plain strings as text; use an
1145 // HtmlSnippet to append HTML content. `OO.ui.Element`s get their
1146 // appropriate $element appended.
1147 this.$element.append( config.content.map( function ( v ) {
1148 if ( typeof v === 'string' ) {
1149 // Escape string so it is properly represented in HTML.
1150 return document.createTextNode( v );
1151 } else if ( v instanceof OO.ui.HtmlSnippet ) {
1152 // Bypass escaping.
1153 return v.toString();
1154 } else if ( v instanceof OO.ui.Element ) {
1155 return v.$element;
1156 }
1157 return v;
1158 } ) );
1159 }
1160 if ( config.$content ) {
1161 // The `$content` property treats plain strings as HTML.
1162 this.$element.append( config.$content );
1163 }
1164 };
1165
1166 /* Setup */
1167
1168 OO.initClass( OO.ui.Element );
1169
1170 /* Static Properties */
1171
1172 /**
1173 * The name of the HTML tag used by the element.
1174 *
1175 * The static value may be ignored if the #getTagName method is overridden.
1176 *
1177 * @static
1178 * @inheritable
1179 * @property {string}
1180 */
1181 OO.ui.Element.static.tagName = 'div';
1182
1183 /* Static Methods */
1184
1185 /**
1186 * Reconstitute a JavaScript object corresponding to a widget created
1187 * by the PHP implementation.
1188 *
1189 * @param {string|HTMLElement|jQuery} idOrNode
1190 * A DOM id (if a string) or node for the widget to infuse.
1191 * @return {OO.ui.Element}
1192 * The `OO.ui.Element` corresponding to this (infusable) document node.
1193 * For `Tag` objects emitted on the HTML side (used occasionally for content)
1194 * the value returned is a newly-created Element wrapping around the existing
1195 * DOM node.
1196 */
1197 OO.ui.Element.static.infuse = function ( idOrNode ) {
1198 var obj = OO.ui.Element.static.unsafeInfuse( idOrNode, false );
1199 // Verify that the type matches up.
1200 // FIXME: uncomment after T89721 is fixed (see T90929)
1201 /*
1202 if ( !( obj instanceof this['class'] ) ) {
1203 throw new Error( 'Infusion type mismatch!' );
1204 }
1205 */
1206 return obj;
1207 };
1208
1209 /**
1210 * Implementation helper for `infuse`; skips the type check and has an
1211 * extra property so that only the top-level invocation touches the DOM.
1212 * @private
1213 * @param {string|HTMLElement|jQuery} idOrNode
1214 * @param {jQuery.Promise|boolean} domPromise A promise that will be resolved
1215 * when the top-level widget of this infusion is inserted into DOM,
1216 * replacing the original node; or false for top-level invocation.
1217 * @return {OO.ui.Element}
1218 */
1219 OO.ui.Element.static.unsafeInfuse = function ( idOrNode, domPromise ) {
1220 // look for a cached result of a previous infusion.
1221 var id, $elem, data, cls, parts, parent, obj, top, state;
1222 if ( typeof idOrNode === 'string' ) {
1223 id = idOrNode;
1224 $elem = $( document.getElementById( id ) );
1225 } else {
1226 $elem = $( idOrNode );
1227 id = $elem.attr( 'id' );
1228 }
1229 if ( !$elem.length ) {
1230 throw new Error( 'Widget not found: ' + id );
1231 }
1232 data = $elem.data( 'ooui-infused' ) || $elem[ 0 ].oouiInfused;
1233 if ( data ) {
1234 // cached!
1235 if ( data === true ) {
1236 throw new Error( 'Circular dependency! ' + id );
1237 }
1238 return data;
1239 }
1240 data = $elem.attr( 'data-ooui' );
1241 if ( !data ) {
1242 throw new Error( 'No infusion data found: ' + id );
1243 }
1244 try {
1245 data = $.parseJSON( data );
1246 } catch ( _ ) {
1247 data = null;
1248 }
1249 if ( !( data && data._ ) ) {
1250 throw new Error( 'No valid infusion data found: ' + id );
1251 }
1252 if ( data._ === 'Tag' ) {
1253 // Special case: this is a raw Tag; wrap existing node, don't rebuild.
1254 return new OO.ui.Element( { $element: $elem } );
1255 }
1256 parts = data._.split( '.' );
1257 cls = OO.getProp.apply( OO, [ window ].concat( parts ) );
1258 if ( cls === undefined ) {
1259 // The PHP output might be old and not including the "OO.ui" prefix
1260 // TODO: Remove this back-compat after next major release
1261 cls = OO.getProp.apply( OO, [ OO.ui ].concat( parts ) );
1262 if ( cls === undefined ) {
1263 throw new Error( 'Unknown widget type: id: ' + id + ', class: ' + data._ );
1264 }
1265 }
1266
1267 // Verify that we're creating an OO.ui.Element instance
1268 parent = cls.parent;
1269
1270 while ( parent !== undefined ) {
1271 if ( parent === OO.ui.Element ) {
1272 // Safe
1273 break;
1274 }
1275
1276 parent = parent.parent;
1277 }
1278
1279 if ( parent !== OO.ui.Element ) {
1280 throw new Error( 'Unknown widget type: id: ' + id + ', class: ' + data._ );
1281 }
1282
1283 if ( domPromise === false ) {
1284 top = $.Deferred();
1285 domPromise = top.promise();
1286 }
1287 $elem.data( 'ooui-infused', true ); // prevent loops
1288 data.id = id; // implicit
1289 data = OO.copy( data, null, function deserialize( value ) {
1290 if ( OO.isPlainObject( value ) ) {
1291 if ( value.tag ) {
1292 return OO.ui.Element.static.unsafeInfuse( value.tag, domPromise );
1293 }
1294 if ( value.html ) {
1295 return new OO.ui.HtmlSnippet( value.html );
1296 }
1297 }
1298 } );
1299 // jscs:disable requireCapitalizedConstructors
1300 obj = new cls( data ); // rebuild widget
1301 // pick up dynamic state, like focus, value of form inputs, scroll position, etc.
1302 state = obj.gatherPreInfuseState( $elem );
1303 // now replace old DOM with this new DOM.
1304 if ( top ) {
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 top.resolve();
1311 }
1312 obj.$element.data( 'ooui-infused', obj );
1313 // set the 'data-ooui' attribute so we can identify infused widgets
1314 obj.$element.attr( 'data-ooui', '' );
1315 // restore dynamic state after the new element is inserted into DOM
1316 domPromise.done( obj.restorePreInfuseState.bind( obj, state ) );
1317 return obj;
1318 };
1319
1320 /**
1321 * Get a jQuery function within a specific document.
1322 *
1323 * @static
1324 * @param {jQuery|HTMLElement|HTMLDocument|Window} context Context to bind the function to
1325 * @param {jQuery} [$iframe] HTML iframe element that contains the document, omit if document is
1326 * not in an iframe
1327 * @return {Function} Bound jQuery function
1328 */
1329 OO.ui.Element.static.getJQuery = function ( context, $iframe ) {
1330 function wrapper( selector ) {
1331 return $( selector, wrapper.context );
1332 }
1333
1334 wrapper.context = this.getDocument( context );
1335
1336 if ( $iframe ) {
1337 wrapper.$iframe = $iframe;
1338 }
1339
1340 return wrapper;
1341 };
1342
1343 /**
1344 * Get the document of an element.
1345 *
1346 * @static
1347 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Object to get the document for
1348 * @return {HTMLDocument|null} Document object
1349 */
1350 OO.ui.Element.static.getDocument = function ( obj ) {
1351 // jQuery - selections created "offscreen" won't have a context, so .context isn't reliable
1352 return ( obj[ 0 ] && obj[ 0 ].ownerDocument ) ||
1353 // Empty jQuery selections might have a context
1354 obj.context ||
1355 // HTMLElement
1356 obj.ownerDocument ||
1357 // Window
1358 obj.document ||
1359 // HTMLDocument
1360 ( obj.nodeType === 9 && obj ) ||
1361 null;
1362 };
1363
1364 /**
1365 * Get the window of an element or document.
1366 *
1367 * @static
1368 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the window for
1369 * @return {Window} Window object
1370 */
1371 OO.ui.Element.static.getWindow = function ( obj ) {
1372 var doc = this.getDocument( obj );
1373 // Support: IE 8
1374 // Standard Document.defaultView is IE9+
1375 return doc.parentWindow || doc.defaultView;
1376 };
1377
1378 /**
1379 * Get the direction of an element or document.
1380 *
1381 * @static
1382 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the direction for
1383 * @return {string} Text direction, either 'ltr' or 'rtl'
1384 */
1385 OO.ui.Element.static.getDir = function ( obj ) {
1386 var isDoc, isWin;
1387
1388 if ( obj instanceof jQuery ) {
1389 obj = obj[ 0 ];
1390 }
1391 isDoc = obj.nodeType === 9;
1392 isWin = obj.document !== undefined;
1393 if ( isDoc || isWin ) {
1394 if ( isWin ) {
1395 obj = obj.document;
1396 }
1397 obj = obj.body;
1398 }
1399 return $( obj ).css( 'direction' );
1400 };
1401
1402 /**
1403 * Get the offset between two frames.
1404 *
1405 * TODO: Make this function not use recursion.
1406 *
1407 * @static
1408 * @param {Window} from Window of the child frame
1409 * @param {Window} [to=window] Window of the parent frame
1410 * @param {Object} [offset] Offset to start with, used internally
1411 * @return {Object} Offset object, containing left and top properties
1412 */
1413 OO.ui.Element.static.getFrameOffset = function ( from, to, offset ) {
1414 var i, len, frames, frame, rect;
1415
1416 if ( !to ) {
1417 to = window;
1418 }
1419 if ( !offset ) {
1420 offset = { top: 0, left: 0 };
1421 }
1422 if ( from.parent === from ) {
1423 return offset;
1424 }
1425
1426 // Get iframe element
1427 frames = from.parent.document.getElementsByTagName( 'iframe' );
1428 for ( i = 0, len = frames.length; i < len; i++ ) {
1429 if ( frames[ i ].contentWindow === from ) {
1430 frame = frames[ i ];
1431 break;
1432 }
1433 }
1434
1435 // Recursively accumulate offset values
1436 if ( frame ) {
1437 rect = frame.getBoundingClientRect();
1438 offset.left += rect.left;
1439 offset.top += rect.top;
1440 if ( from !== to ) {
1441 this.getFrameOffset( from.parent, offset );
1442 }
1443 }
1444 return offset;
1445 };
1446
1447 /**
1448 * Get the offset between two elements.
1449 *
1450 * The two elements may be in a different frame, but in that case the frame $element is in must
1451 * be contained in the frame $anchor is in.
1452 *
1453 * @static
1454 * @param {jQuery} $element Element whose position to get
1455 * @param {jQuery} $anchor Element to get $element's position relative to
1456 * @return {Object} Translated position coordinates, containing top and left properties
1457 */
1458 OO.ui.Element.static.getRelativePosition = function ( $element, $anchor ) {
1459 var iframe, iframePos,
1460 pos = $element.offset(),
1461 anchorPos = $anchor.offset(),
1462 elementDocument = this.getDocument( $element ),
1463 anchorDocument = this.getDocument( $anchor );
1464
1465 // If $element isn't in the same document as $anchor, traverse up
1466 while ( elementDocument !== anchorDocument ) {
1467 iframe = elementDocument.defaultView.frameElement;
1468 if ( !iframe ) {
1469 throw new Error( '$element frame is not contained in $anchor frame' );
1470 }
1471 iframePos = $( iframe ).offset();
1472 pos.left += iframePos.left;
1473 pos.top += iframePos.top;
1474 elementDocument = iframe.ownerDocument;
1475 }
1476 pos.left -= anchorPos.left;
1477 pos.top -= anchorPos.top;
1478 return pos;
1479 };
1480
1481 /**
1482 * Get element border sizes.
1483 *
1484 * @static
1485 * @param {HTMLElement} el Element to measure
1486 * @return {Object} Dimensions object with `top`, `left`, `bottom` and `right` properties
1487 */
1488 OO.ui.Element.static.getBorders = function ( el ) {
1489 var doc = el.ownerDocument,
1490 // Support: IE 8
1491 // Standard Document.defaultView is IE9+
1492 win = doc.parentWindow || doc.defaultView,
1493 style = win && win.getComputedStyle ?
1494 win.getComputedStyle( el, null ) :
1495 // Support: IE 8
1496 // Standard getComputedStyle() is IE9+
1497 el.currentStyle,
1498 $el = $( el ),
1499 top = parseFloat( style ? style.borderTopWidth : $el.css( 'borderTopWidth' ) ) || 0,
1500 left = parseFloat( style ? style.borderLeftWidth : $el.css( 'borderLeftWidth' ) ) || 0,
1501 bottom = parseFloat( style ? style.borderBottomWidth : $el.css( 'borderBottomWidth' ) ) || 0,
1502 right = parseFloat( style ? style.borderRightWidth : $el.css( 'borderRightWidth' ) ) || 0;
1503
1504 return {
1505 top: top,
1506 left: left,
1507 bottom: bottom,
1508 right: right
1509 };
1510 };
1511
1512 /**
1513 * Get dimensions of an element or window.
1514 *
1515 * @static
1516 * @param {HTMLElement|Window} el Element to measure
1517 * @return {Object} Dimensions object with `borders`, `scroll`, `scrollbar` and `rect` properties
1518 */
1519 OO.ui.Element.static.getDimensions = function ( el ) {
1520 var $el, $win,
1521 doc = el.ownerDocument || el.document,
1522 // Support: IE 8
1523 // Standard Document.defaultView is IE9+
1524 win = doc.parentWindow || doc.defaultView;
1525
1526 if ( win === el || el === doc.documentElement ) {
1527 $win = $( win );
1528 return {
1529 borders: { top: 0, left: 0, bottom: 0, right: 0 },
1530 scroll: {
1531 top: $win.scrollTop(),
1532 left: $win.scrollLeft()
1533 },
1534 scrollbar: { right: 0, bottom: 0 },
1535 rect: {
1536 top: 0,
1537 left: 0,
1538 bottom: $win.innerHeight(),
1539 right: $win.innerWidth()
1540 }
1541 };
1542 } else {
1543 $el = $( el );
1544 return {
1545 borders: this.getBorders( el ),
1546 scroll: {
1547 top: $el.scrollTop(),
1548 left: $el.scrollLeft()
1549 },
1550 scrollbar: {
1551 right: $el.innerWidth() - el.clientWidth,
1552 bottom: $el.innerHeight() - el.clientHeight
1553 },
1554 rect: el.getBoundingClientRect()
1555 };
1556 }
1557 };
1558
1559 /**
1560 * Get scrollable object parent
1561 *
1562 * documentElement can't be used to get or set the scrollTop
1563 * property on Blink. Changing and testing its value lets us
1564 * use 'body' or 'documentElement' based on what is working.
1565 *
1566 * https://code.google.com/p/chromium/issues/detail?id=303131
1567 *
1568 * @static
1569 * @param {HTMLElement} el Element to find scrollable parent for
1570 * @return {HTMLElement} Scrollable parent
1571 */
1572 OO.ui.Element.static.getRootScrollableElement = function ( el ) {
1573 var scrollTop, body;
1574
1575 if ( OO.ui.scrollableElement === undefined ) {
1576 body = el.ownerDocument.body;
1577 scrollTop = body.scrollTop;
1578 body.scrollTop = 1;
1579
1580 if ( body.scrollTop === 1 ) {
1581 body.scrollTop = scrollTop;
1582 OO.ui.scrollableElement = 'body';
1583 } else {
1584 OO.ui.scrollableElement = 'documentElement';
1585 }
1586 }
1587
1588 return el.ownerDocument[ OO.ui.scrollableElement ];
1589 };
1590
1591 /**
1592 * Get closest scrollable container.
1593 *
1594 * Traverses up until either a scrollable element or the root is reached, in which case the window
1595 * will be returned.
1596 *
1597 * @static
1598 * @param {HTMLElement} el Element to find scrollable container for
1599 * @param {string} [dimension] Dimension of scrolling to look for; `x`, `y` or omit for either
1600 * @return {HTMLElement} Closest scrollable container
1601 */
1602 OO.ui.Element.static.getClosestScrollableContainer = function ( el, dimension ) {
1603 var i, val,
1604 // props = [ 'overflow' ] doesn't work due to https://bugzilla.mozilla.org/show_bug.cgi?id=889091
1605 props = [ 'overflow-x', 'overflow-y' ],
1606 $parent = $( el ).parent();
1607
1608 if ( dimension === 'x' || dimension === 'y' ) {
1609 props = [ 'overflow-' + dimension ];
1610 }
1611
1612 while ( $parent.length ) {
1613 if ( $parent[ 0 ] === this.getRootScrollableElement( el ) ) {
1614 return $parent[ 0 ];
1615 }
1616 i = props.length;
1617 while ( i-- ) {
1618 val = $parent.css( props[ i ] );
1619 if ( val === 'auto' || val === 'scroll' ) {
1620 return $parent[ 0 ];
1621 }
1622 }
1623 $parent = $parent.parent();
1624 }
1625 return this.getDocument( el ).body;
1626 };
1627
1628 /**
1629 * Scroll element into view.
1630 *
1631 * @static
1632 * @param {HTMLElement} el Element to scroll into view
1633 * @param {Object} [config] Configuration options
1634 * @param {string} [config.duration] jQuery animation duration value
1635 * @param {string} [config.direction] Scroll in only one direction, e.g. 'x' or 'y', omit
1636 * to scroll in both directions
1637 * @param {Function} [config.complete] Function to call when scrolling completes
1638 */
1639 OO.ui.Element.static.scrollIntoView = function ( el, config ) {
1640 var rel, anim, callback, sc, $sc, eld, scd, $win;
1641
1642 // Configuration initialization
1643 config = config || {};
1644
1645 anim = {};
1646 callback = typeof config.complete === 'function' && config.complete;
1647 sc = this.getClosestScrollableContainer( el, config.direction );
1648 $sc = $( sc );
1649 eld = this.getDimensions( el );
1650 scd = this.getDimensions( sc );
1651 $win = $( this.getWindow( el ) );
1652
1653 // Compute the distances between the edges of el and the edges of the scroll viewport
1654 if ( $sc.is( 'html, body' ) ) {
1655 // If the scrollable container is the root, this is easy
1656 rel = {
1657 top: eld.rect.top,
1658 bottom: $win.innerHeight() - eld.rect.bottom,
1659 left: eld.rect.left,
1660 right: $win.innerWidth() - eld.rect.right
1661 };
1662 } else {
1663 // Otherwise, we have to subtract el's coordinates from sc's coordinates
1664 rel = {
1665 top: eld.rect.top - ( scd.rect.top + scd.borders.top ),
1666 bottom: scd.rect.bottom - scd.borders.bottom - scd.scrollbar.bottom - eld.rect.bottom,
1667 left: eld.rect.left - ( scd.rect.left + scd.borders.left ),
1668 right: scd.rect.right - scd.borders.right - scd.scrollbar.right - eld.rect.right
1669 };
1670 }
1671
1672 if ( !config.direction || config.direction === 'y' ) {
1673 if ( rel.top < 0 ) {
1674 anim.scrollTop = scd.scroll.top + rel.top;
1675 } else if ( rel.top > 0 && rel.bottom < 0 ) {
1676 anim.scrollTop = scd.scroll.top + Math.min( rel.top, -rel.bottom );
1677 }
1678 }
1679 if ( !config.direction || config.direction === 'x' ) {
1680 if ( rel.left < 0 ) {
1681 anim.scrollLeft = scd.scroll.left + rel.left;
1682 } else if ( rel.left > 0 && rel.right < 0 ) {
1683 anim.scrollLeft = scd.scroll.left + Math.min( rel.left, -rel.right );
1684 }
1685 }
1686 if ( !$.isEmptyObject( anim ) ) {
1687 $sc.stop( true ).animate( anim, config.duration || 'fast' );
1688 if ( callback ) {
1689 $sc.queue( function ( next ) {
1690 callback();
1691 next();
1692 } );
1693 }
1694 } else {
1695 if ( callback ) {
1696 callback();
1697 }
1698 }
1699 };
1700
1701 /**
1702 * Force the browser to reconsider whether it really needs to render scrollbars inside the element
1703 * and reserve space for them, because it probably doesn't.
1704 *
1705 * Workaround primarily for <https://code.google.com/p/chromium/issues/detail?id=387290>, but also
1706 * similar bugs in other browsers. "Just" forcing a reflow is not sufficient in all cases, we need
1707 * to first actually detach (or hide, but detaching is simpler) all children, *then* force a reflow,
1708 * and then reattach (or show) them back.
1709 *
1710 * @static
1711 * @param {HTMLElement} el Element to reconsider the scrollbars on
1712 */
1713 OO.ui.Element.static.reconsiderScrollbars = function ( el ) {
1714 var i, len, scrollLeft, scrollTop, nodes = [];
1715 // Save scroll position
1716 scrollLeft = el.scrollLeft;
1717 scrollTop = el.scrollTop;
1718 // Detach all children
1719 while ( el.firstChild ) {
1720 nodes.push( el.firstChild );
1721 el.removeChild( el.firstChild );
1722 }
1723 // Force reflow
1724 void el.offsetHeight;
1725 // Reattach all children
1726 for ( i = 0, len = nodes.length; i < len; i++ ) {
1727 el.appendChild( nodes[ i ] );
1728 }
1729 // Restore scroll position (no-op if scrollbars disappeared)
1730 el.scrollLeft = scrollLeft;
1731 el.scrollTop = scrollTop;
1732 };
1733
1734 /* Methods */
1735
1736 /**
1737 * Toggle visibility of an element.
1738 *
1739 * @param {boolean} [show] Make element visible, omit to toggle visibility
1740 * @fires visible
1741 * @chainable
1742 */
1743 OO.ui.Element.prototype.toggle = function ( show ) {
1744 show = show === undefined ? !this.visible : !!show;
1745
1746 if ( show !== this.isVisible() ) {
1747 this.visible = show;
1748 this.$element.toggleClass( 'oo-ui-element-hidden', !this.visible );
1749 this.emit( 'toggle', show );
1750 }
1751
1752 return this;
1753 };
1754
1755 /**
1756 * Check if element is visible.
1757 *
1758 * @return {boolean} element is visible
1759 */
1760 OO.ui.Element.prototype.isVisible = function () {
1761 return this.visible;
1762 };
1763
1764 /**
1765 * Get element data.
1766 *
1767 * @return {Mixed} Element data
1768 */
1769 OO.ui.Element.prototype.getData = function () {
1770 return this.data;
1771 };
1772
1773 /**
1774 * Set element data.
1775 *
1776 * @param {Mixed} Element data
1777 * @chainable
1778 */
1779 OO.ui.Element.prototype.setData = function ( data ) {
1780 this.data = data;
1781 return this;
1782 };
1783
1784 /**
1785 * Check if element supports one or more methods.
1786 *
1787 * @param {string|string[]} methods Method or list of methods to check
1788 * @return {boolean} All methods are supported
1789 */
1790 OO.ui.Element.prototype.supports = function ( methods ) {
1791 var i, len,
1792 support = 0;
1793
1794 methods = Array.isArray( methods ) ? methods : [ methods ];
1795 for ( i = 0, len = methods.length; i < len; i++ ) {
1796 if ( $.isFunction( this[ methods[ i ] ] ) ) {
1797 support++;
1798 }
1799 }
1800
1801 return methods.length === support;
1802 };
1803
1804 /**
1805 * Update the theme-provided classes.
1806 *
1807 * @localdoc This is called in element mixins and widget classes any time state changes.
1808 * Updating is debounced, minimizing overhead of changing multiple attributes and
1809 * guaranteeing that theme updates do not occur within an element's constructor
1810 */
1811 OO.ui.Element.prototype.updateThemeClasses = function () {
1812 this.debouncedUpdateThemeClassesHandler();
1813 };
1814
1815 /**
1816 * @private
1817 * @localdoc This method is called directly from the QUnit tests instead of #updateThemeClasses, to
1818 * make them synchronous.
1819 */
1820 OO.ui.Element.prototype.debouncedUpdateThemeClasses = function () {
1821 OO.ui.theme.updateElementClasses( this );
1822 };
1823
1824 /**
1825 * Get the HTML tag name.
1826 *
1827 * Override this method to base the result on instance information.
1828 *
1829 * @return {string} HTML tag name
1830 */
1831 OO.ui.Element.prototype.getTagName = function () {
1832 return this.constructor.static.tagName;
1833 };
1834
1835 /**
1836 * Check if the element is attached to the DOM
1837 * @return {boolean} The element is attached to the DOM
1838 */
1839 OO.ui.Element.prototype.isElementAttached = function () {
1840 return $.contains( this.getElementDocument(), this.$element[ 0 ] );
1841 };
1842
1843 /**
1844 * Get the DOM document.
1845 *
1846 * @return {HTMLDocument} Document object
1847 */
1848 OO.ui.Element.prototype.getElementDocument = function () {
1849 // Don't cache this in other ways either because subclasses could can change this.$element
1850 return OO.ui.Element.static.getDocument( this.$element );
1851 };
1852
1853 /**
1854 * Get the DOM window.
1855 *
1856 * @return {Window} Window object
1857 */
1858 OO.ui.Element.prototype.getElementWindow = function () {
1859 return OO.ui.Element.static.getWindow( this.$element );
1860 };
1861
1862 /**
1863 * Get closest scrollable container.
1864 */
1865 OO.ui.Element.prototype.getClosestScrollableElementContainer = function () {
1866 return OO.ui.Element.static.getClosestScrollableContainer( this.$element[ 0 ] );
1867 };
1868
1869 /**
1870 * Get group element is in.
1871 *
1872 * @return {OO.ui.mixin.GroupElement|null} Group element, null if none
1873 */
1874 OO.ui.Element.prototype.getElementGroup = function () {
1875 return this.elementGroup;
1876 };
1877
1878 /**
1879 * Set group element is in.
1880 *
1881 * @param {OO.ui.mixin.GroupElement|null} group Group element, null if none
1882 * @chainable
1883 */
1884 OO.ui.Element.prototype.setElementGroup = function ( group ) {
1885 this.elementGroup = group;
1886 return this;
1887 };
1888
1889 /**
1890 * Scroll element into view.
1891 *
1892 * @param {Object} [config] Configuration options
1893 */
1894 OO.ui.Element.prototype.scrollElementIntoView = function ( config ) {
1895 return OO.ui.Element.static.scrollIntoView( this.$element[ 0 ], config );
1896 };
1897
1898 /**
1899 * Gather the dynamic state (focus, value of form inputs, scroll position, etc.) of a HTML DOM node
1900 * (and its children) that represent an Element of the same type and configuration as the current
1901 * one, generated by the PHP implementation.
1902 *
1903 * This method is called just before `node` is detached from the DOM. The return value of this
1904 * function will be passed to #restorePreInfuseState after this widget's #$element is inserted into
1905 * DOM to replace `node`.
1906 *
1907 * @protected
1908 * @param {HTMLElement} node
1909 * @return {Object}
1910 */
1911 OO.ui.Element.prototype.gatherPreInfuseState = function () {
1912 return {};
1913 };
1914
1915 /**
1916 * Restore the pre-infusion dynamic state for this widget.
1917 *
1918 * This method is called after #$element has been inserted into DOM. The parameter is the return
1919 * value of #gatherPreInfuseState.
1920 *
1921 * @protected
1922 * @param {Object} state
1923 */
1924 OO.ui.Element.prototype.restorePreInfuseState = function () {
1925 };
1926
1927 /**
1928 * Layouts are containers for elements and are used to arrange other widgets of arbitrary type in a way
1929 * that is centrally controlled and can be updated dynamically. Layouts can be, and usually are, combined.
1930 * See {@link OO.ui.FieldsetLayout FieldsetLayout}, {@link OO.ui.FieldLayout FieldLayout}, {@link OO.ui.FormLayout FormLayout},
1931 * {@link OO.ui.PanelLayout PanelLayout}, {@link OO.ui.StackLayout StackLayout}, {@link OO.ui.PageLayout PageLayout},
1932 * {@link OO.ui.HorizontalLayout HorizontalLayout}, and {@link OO.ui.BookletLayout BookletLayout} for more information and examples.
1933 *
1934 * @abstract
1935 * @class
1936 * @extends OO.ui.Element
1937 * @mixins OO.EventEmitter
1938 *
1939 * @constructor
1940 * @param {Object} [config] Configuration options
1941 */
1942 OO.ui.Layout = function OoUiLayout( config ) {
1943 // Configuration initialization
1944 config = config || {};
1945
1946 // Parent constructor
1947 OO.ui.Layout.parent.call( this, config );
1948
1949 // Mixin constructors
1950 OO.EventEmitter.call( this );
1951
1952 // Initialization
1953 this.$element.addClass( 'oo-ui-layout' );
1954 };
1955
1956 /* Setup */
1957
1958 OO.inheritClass( OO.ui.Layout, OO.ui.Element );
1959 OO.mixinClass( OO.ui.Layout, OO.EventEmitter );
1960
1961 /**
1962 * Widgets are compositions of one or more OOjs UI elements that users can both view
1963 * and interact with. All widgets can be configured and modified via a standard API,
1964 * and their state can change dynamically according to a model.
1965 *
1966 * @abstract
1967 * @class
1968 * @extends OO.ui.Element
1969 * @mixins OO.EventEmitter
1970 *
1971 * @constructor
1972 * @param {Object} [config] Configuration options
1973 * @cfg {boolean} [disabled=false] Disable the widget. Disabled widgets cannot be used and their
1974 * appearance reflects this state.
1975 */
1976 OO.ui.Widget = function OoUiWidget( config ) {
1977 // Initialize config
1978 config = $.extend( { disabled: false }, config );
1979
1980 // Parent constructor
1981 OO.ui.Widget.parent.call( this, config );
1982
1983 // Mixin constructors
1984 OO.EventEmitter.call( this );
1985
1986 // Properties
1987 this.disabled = null;
1988 this.wasDisabled = null;
1989
1990 // Initialization
1991 this.$element.addClass( 'oo-ui-widget' );
1992 this.setDisabled( !!config.disabled );
1993 };
1994
1995 /* Setup */
1996
1997 OO.inheritClass( OO.ui.Widget, OO.ui.Element );
1998 OO.mixinClass( OO.ui.Widget, OO.EventEmitter );
1999
2000 /* Static Properties */
2001
2002 /**
2003 * Whether this widget will behave reasonably when wrapped in a HTML `<label>`. If this is true,
2004 * wrappers such as OO.ui.FieldLayout may use a `<label>` instead of implementing own label click
2005 * handling.
2006 *
2007 * @static
2008 * @inheritable
2009 * @property {boolean}
2010 */
2011 OO.ui.Widget.static.supportsSimpleLabel = false;
2012
2013 /* Events */
2014
2015 /**
2016 * @event disable
2017 *
2018 * A 'disable' event is emitted when the disabled state of the widget changes
2019 * (i.e. on disable **and** enable).
2020 *
2021 * @param {boolean} disabled Widget is disabled
2022 */
2023
2024 /**
2025 * @event toggle
2026 *
2027 * A 'toggle' event is emitted when the visibility of the widget changes.
2028 *
2029 * @param {boolean} visible Widget is visible
2030 */
2031
2032 /* Methods */
2033
2034 /**
2035 * Check if the widget is disabled.
2036 *
2037 * @return {boolean} Widget is disabled
2038 */
2039 OO.ui.Widget.prototype.isDisabled = function () {
2040 return this.disabled;
2041 };
2042
2043 /**
2044 * Set the 'disabled' state of the widget.
2045 *
2046 * When a widget is disabled, it cannot be used and its appearance is updated to reflect this state.
2047 *
2048 * @param {boolean} disabled Disable widget
2049 * @chainable
2050 */
2051 OO.ui.Widget.prototype.setDisabled = function ( disabled ) {
2052 var isDisabled;
2053
2054 this.disabled = !!disabled;
2055 isDisabled = this.isDisabled();
2056 if ( isDisabled !== this.wasDisabled ) {
2057 this.$element.toggleClass( 'oo-ui-widget-disabled', isDisabled );
2058 this.$element.toggleClass( 'oo-ui-widget-enabled', !isDisabled );
2059 this.$element.attr( 'aria-disabled', isDisabled.toString() );
2060 this.emit( 'disable', isDisabled );
2061 this.updateThemeClasses();
2062 }
2063 this.wasDisabled = isDisabled;
2064
2065 return this;
2066 };
2067
2068 /**
2069 * Update the disabled state, in case of changes in parent widget.
2070 *
2071 * @chainable
2072 */
2073 OO.ui.Widget.prototype.updateDisabled = function () {
2074 this.setDisabled( this.disabled );
2075 return this;
2076 };
2077
2078 /**
2079 * A window is a container for elements that are in a child frame. They are used with
2080 * a window manager (OO.ui.WindowManager), which is used to open and close the window and control
2081 * its presentation. The size of a window is specified using a symbolic name (e.g., ‘small’, ‘medium’,
2082 * ‘large’), which is interpreted by the window manager. If the requested size is not recognized,
2083 * the window manager will choose a sensible fallback.
2084 *
2085 * The lifecycle of a window has three primary stages (opening, opened, and closing) in which
2086 * different processes are executed:
2087 *
2088 * **opening**: The opening stage begins when the window manager's {@link OO.ui.WindowManager#openWindow
2089 * openWindow} or the window's {@link #open open} methods are used, and the window manager begins to open
2090 * the window.
2091 *
2092 * - {@link #getSetupProcess} method is called and its result executed
2093 * - {@link #getReadyProcess} method is called and its result executed
2094 *
2095 * **opened**: The window is now open
2096 *
2097 * **closing**: The closing stage begins when the window manager's
2098 * {@link OO.ui.WindowManager#closeWindow closeWindow}
2099 * or the window's {@link #close} methods are used, and the window manager begins to close the window.
2100 *
2101 * - {@link #getHoldProcess} method is called and its result executed
2102 * - {@link #getTeardownProcess} method is called and its result executed. The window is now closed
2103 *
2104 * Each of the window's processes (setup, ready, hold, and teardown) can be extended in subclasses
2105 * by overriding the window's #getSetupProcess, #getReadyProcess, #getHoldProcess and #getTeardownProcess
2106 * methods. Note that each {@link OO.ui.Process process} is executed in series, so asynchronous
2107 * processing can complete. Always assume window processes are executed asynchronously.
2108 *
2109 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
2110 *
2111 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows
2112 *
2113 * @abstract
2114 * @class
2115 * @extends OO.ui.Element
2116 * @mixins OO.EventEmitter
2117 *
2118 * @constructor
2119 * @param {Object} [config] Configuration options
2120 * @cfg {string} [size] Symbolic name of the dialog size: `small`, `medium`, `large`, `larger` or
2121 * `full`. If omitted, the value of the {@link #static-size static size} property will be used.
2122 */
2123 OO.ui.Window = function OoUiWindow( config ) {
2124 // Configuration initialization
2125 config = config || {};
2126
2127 // Parent constructor
2128 OO.ui.Window.parent.call( this, config );
2129
2130 // Mixin constructors
2131 OO.EventEmitter.call( this );
2132
2133 // Properties
2134 this.manager = null;
2135 this.size = config.size || this.constructor.static.size;
2136 this.$frame = $( '<div>' );
2137 this.$overlay = $( '<div>' );
2138 this.$content = $( '<div>' );
2139
2140 this.$focusTrapBefore = $( '<div>' ).prop( 'tabIndex', 0 );
2141 this.$focusTrapAfter = $( '<div>' ).prop( 'tabIndex', 0 );
2142 this.$focusTraps = this.$focusTrapBefore.add( this.$focusTrapAfter );
2143
2144 // Initialization
2145 this.$overlay.addClass( 'oo-ui-window-overlay' );
2146 this.$content
2147 .addClass( 'oo-ui-window-content' )
2148 .attr( 'tabindex', 0 );
2149 this.$frame
2150 .addClass( 'oo-ui-window-frame' )
2151 .append( this.$focusTrapBefore, this.$content, this.$focusTrapAfter );
2152
2153 this.$element
2154 .addClass( 'oo-ui-window' )
2155 .append( this.$frame, this.$overlay );
2156
2157 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
2158 // that reference properties not initialized at that time of parent class construction
2159 // TODO: Find a better way to handle post-constructor setup
2160 this.visible = false;
2161 this.$element.addClass( 'oo-ui-element-hidden' );
2162 };
2163
2164 /* Setup */
2165
2166 OO.inheritClass( OO.ui.Window, OO.ui.Element );
2167 OO.mixinClass( OO.ui.Window, OO.EventEmitter );
2168
2169 /* Static Properties */
2170
2171 /**
2172 * Symbolic name of the window size: `small`, `medium`, `large`, `larger` or `full`.
2173 *
2174 * The static size is used if no #size is configured during construction.
2175 *
2176 * @static
2177 * @inheritable
2178 * @property {string}
2179 */
2180 OO.ui.Window.static.size = 'medium';
2181
2182 /* Methods */
2183
2184 /**
2185 * Handle mouse down events.
2186 *
2187 * @private
2188 * @param {jQuery.Event} e Mouse down event
2189 */
2190 OO.ui.Window.prototype.onMouseDown = function ( e ) {
2191 // Prevent clicking on the click-block from stealing focus
2192 if ( e.target === this.$element[ 0 ] ) {
2193 return false;
2194 }
2195 };
2196
2197 /**
2198 * Check if the window has been initialized.
2199 *
2200 * Initialization occurs when a window is added to a manager.
2201 *
2202 * @return {boolean} Window has been initialized
2203 */
2204 OO.ui.Window.prototype.isInitialized = function () {
2205 return !!this.manager;
2206 };
2207
2208 /**
2209 * Check if the window is visible.
2210 *
2211 * @return {boolean} Window is visible
2212 */
2213 OO.ui.Window.prototype.isVisible = function () {
2214 return this.visible;
2215 };
2216
2217 /**
2218 * Check if the window is opening.
2219 *
2220 * This method is a wrapper around the window manager's {@link OO.ui.WindowManager#isOpening isOpening}
2221 * method.
2222 *
2223 * @return {boolean} Window is opening
2224 */
2225 OO.ui.Window.prototype.isOpening = function () {
2226 return this.manager.isOpening( this );
2227 };
2228
2229 /**
2230 * Check if the window is closing.
2231 *
2232 * This method is a wrapper around the window manager's {@link OO.ui.WindowManager#isClosing isClosing} method.
2233 *
2234 * @return {boolean} Window is closing
2235 */
2236 OO.ui.Window.prototype.isClosing = function () {
2237 return this.manager.isClosing( this );
2238 };
2239
2240 /**
2241 * Check if the window is opened.
2242 *
2243 * This method is a wrapper around the window manager's {@link OO.ui.WindowManager#isOpened isOpened} method.
2244 *
2245 * @return {boolean} Window is opened
2246 */
2247 OO.ui.Window.prototype.isOpened = function () {
2248 return this.manager.isOpened( this );
2249 };
2250
2251 /**
2252 * Get the window manager.
2253 *
2254 * All windows must be attached to a window manager, which is used to open
2255 * and close the window and control its presentation.
2256 *
2257 * @return {OO.ui.WindowManager} Manager of window
2258 */
2259 OO.ui.Window.prototype.getManager = function () {
2260 return this.manager;
2261 };
2262
2263 /**
2264 * Get the symbolic name of the window size (e.g., `small` or `medium`).
2265 *
2266 * @return {string} Symbolic name of the size: `small`, `medium`, `large`, `larger`, `full`
2267 */
2268 OO.ui.Window.prototype.getSize = function () {
2269 var viewport = OO.ui.Element.static.getDimensions( this.getElementWindow() ),
2270 sizes = this.manager.constructor.static.sizes,
2271 size = this.size;
2272
2273 if ( !sizes[ size ] ) {
2274 size = this.manager.constructor.static.defaultSize;
2275 }
2276 if ( size !== 'full' && viewport.rect.right - viewport.rect.left < sizes[ size ].width ) {
2277 size = 'full';
2278 }
2279
2280 return size;
2281 };
2282
2283 /**
2284 * Get the size properties associated with the current window size
2285 *
2286 * @return {Object} Size properties
2287 */
2288 OO.ui.Window.prototype.getSizeProperties = function () {
2289 return this.manager.constructor.static.sizes[ this.getSize() ];
2290 };
2291
2292 /**
2293 * Disable transitions on window's frame for the duration of the callback function, then enable them
2294 * back.
2295 *
2296 * @private
2297 * @param {Function} callback Function to call while transitions are disabled
2298 */
2299 OO.ui.Window.prototype.withoutSizeTransitions = function ( callback ) {
2300 // Temporarily resize the frame so getBodyHeight() can use scrollHeight measurements.
2301 // Disable transitions first, otherwise we'll get values from when the window was animating.
2302 var oldTransition,
2303 styleObj = this.$frame[ 0 ].style;
2304 oldTransition = styleObj.transition || styleObj.OTransition || styleObj.MsTransition ||
2305 styleObj.MozTransition || styleObj.WebkitTransition;
2306 styleObj.transition = styleObj.OTransition = styleObj.MsTransition =
2307 styleObj.MozTransition = styleObj.WebkitTransition = 'none';
2308 callback();
2309 // Force reflow to make sure the style changes done inside callback really are not transitioned
2310 this.$frame.height();
2311 styleObj.transition = styleObj.OTransition = styleObj.MsTransition =
2312 styleObj.MozTransition = styleObj.WebkitTransition = oldTransition;
2313 };
2314
2315 /**
2316 * Get the height of the full window contents (i.e., the window head, body and foot together).
2317 *
2318 * What consistitutes the head, body, and foot varies depending on the window type.
2319 * A {@link OO.ui.MessageDialog message dialog} displays a title and message in its body,
2320 * and any actions in the foot. A {@link OO.ui.ProcessDialog process dialog} displays a title
2321 * and special actions in the head, and dialog content in the body.
2322 *
2323 * To get just the height of the dialog body, use the #getBodyHeight method.
2324 *
2325 * @return {number} The height of the window contents (the dialog head, body and foot) in pixels
2326 */
2327 OO.ui.Window.prototype.getContentHeight = function () {
2328 var bodyHeight,
2329 win = this,
2330 bodyStyleObj = this.$body[ 0 ].style,
2331 frameStyleObj = this.$frame[ 0 ].style;
2332
2333 // Temporarily resize the frame so getBodyHeight() can use scrollHeight measurements.
2334 // Disable transitions first, otherwise we'll get values from when the window was animating.
2335 this.withoutSizeTransitions( function () {
2336 var oldHeight = frameStyleObj.height,
2337 oldPosition = bodyStyleObj.position;
2338 frameStyleObj.height = '1px';
2339 // Force body to resize to new width
2340 bodyStyleObj.position = 'relative';
2341 bodyHeight = win.getBodyHeight();
2342 frameStyleObj.height = oldHeight;
2343 bodyStyleObj.position = oldPosition;
2344 } );
2345
2346 return (
2347 // Add buffer for border
2348 ( this.$frame.outerHeight() - this.$frame.innerHeight() ) +
2349 // Use combined heights of children
2350 ( this.$head.outerHeight( true ) + bodyHeight + this.$foot.outerHeight( true ) )
2351 );
2352 };
2353
2354 /**
2355 * Get the height of the window body.
2356 *
2357 * To get the height of the full window contents (the window body, head, and foot together),
2358 * use #getContentHeight.
2359 *
2360 * When this function is called, the window will temporarily have been resized
2361 * to height=1px, so .scrollHeight measurements can be taken accurately.
2362 *
2363 * @return {number} Height of the window body in pixels
2364 */
2365 OO.ui.Window.prototype.getBodyHeight = function () {
2366 return this.$body[ 0 ].scrollHeight;
2367 };
2368
2369 /**
2370 * Get the directionality of the frame (right-to-left or left-to-right).
2371 *
2372 * @return {string} Directionality: `'ltr'` or `'rtl'`
2373 */
2374 OO.ui.Window.prototype.getDir = function () {
2375 return OO.ui.Element.static.getDir( this.$content ) || 'ltr';
2376 };
2377
2378 /**
2379 * Get the 'setup' process.
2380 *
2381 * The setup process is used to set up a window for use in a particular context,
2382 * based on the `data` argument. This method is called during the opening phase of the window’s
2383 * lifecycle.
2384 *
2385 * Override this method to add additional steps to the ‘setup’ process the parent method provides
2386 * using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next} methods
2387 * of OO.ui.Process.
2388 *
2389 * To add window content that persists between openings, you may wish to use the #initialize method
2390 * instead.
2391 *
2392 * @abstract
2393 * @param {Object} [data] Window opening data
2394 * @return {OO.ui.Process} Setup process
2395 */
2396 OO.ui.Window.prototype.getSetupProcess = function () {
2397 return new OO.ui.Process();
2398 };
2399
2400 /**
2401 * Get the ‘ready’ process.
2402 *
2403 * The ready process is used to ready a window for use in a particular
2404 * context, based on the `data` argument. This method is called during the opening phase of
2405 * the window’s lifecycle, after the window has been {@link #getSetupProcess setup}.
2406 *
2407 * Override this method to add additional steps to the ‘ready’ process the parent method
2408 * provides using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next}
2409 * methods of OO.ui.Process.
2410 *
2411 * @abstract
2412 * @param {Object} [data] Window opening data
2413 * @return {OO.ui.Process} Ready process
2414 */
2415 OO.ui.Window.prototype.getReadyProcess = function () {
2416 return new OO.ui.Process();
2417 };
2418
2419 /**
2420 * Get the 'hold' process.
2421 *
2422 * The hold proccess is used to keep a window from being used in a particular context,
2423 * based on the `data` argument. This method is called during the closing phase of the window’s
2424 * lifecycle.
2425 *
2426 * Override this method to add additional steps to the 'hold' process the parent method provides
2427 * using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next} methods
2428 * of OO.ui.Process.
2429 *
2430 * @abstract
2431 * @param {Object} [data] Window closing data
2432 * @return {OO.ui.Process} Hold process
2433 */
2434 OO.ui.Window.prototype.getHoldProcess = function () {
2435 return new OO.ui.Process();
2436 };
2437
2438 /**
2439 * Get the ‘teardown’ process.
2440 *
2441 * The teardown process is used to teardown a window after use. During teardown,
2442 * user interactions within the window are conveyed and the window is closed, based on the `data`
2443 * argument. This method is called during the closing phase of the window’s lifecycle.
2444 *
2445 * Override this method to add additional steps to the ‘teardown’ process the parent method provides
2446 * using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next} methods
2447 * of OO.ui.Process.
2448 *
2449 * @abstract
2450 * @param {Object} [data] Window closing data
2451 * @return {OO.ui.Process} Teardown process
2452 */
2453 OO.ui.Window.prototype.getTeardownProcess = function () {
2454 return new OO.ui.Process();
2455 };
2456
2457 /**
2458 * Set the window manager.
2459 *
2460 * This will cause the window to initialize. Calling it more than once will cause an error.
2461 *
2462 * @param {OO.ui.WindowManager} manager Manager for this window
2463 * @throws {Error} An error is thrown if the method is called more than once
2464 * @chainable
2465 */
2466 OO.ui.Window.prototype.setManager = function ( manager ) {
2467 if ( this.manager ) {
2468 throw new Error( 'Cannot set window manager, window already has a manager' );
2469 }
2470
2471 this.manager = manager;
2472 this.initialize();
2473
2474 return this;
2475 };
2476
2477 /**
2478 * Set the window size by symbolic name (e.g., 'small' or 'medium')
2479 *
2480 * @param {string} size Symbolic name of size: `small`, `medium`, `large`, `larger` or
2481 * `full`
2482 * @chainable
2483 */
2484 OO.ui.Window.prototype.setSize = function ( size ) {
2485 this.size = size;
2486 this.updateSize();
2487 return this;
2488 };
2489
2490 /**
2491 * Update the window size.
2492 *
2493 * @throws {Error} An error is thrown if the window is not attached to a window manager
2494 * @chainable
2495 */
2496 OO.ui.Window.prototype.updateSize = function () {
2497 if ( !this.manager ) {
2498 throw new Error( 'Cannot update window size, must be attached to a manager' );
2499 }
2500
2501 this.manager.updateWindowSize( this );
2502
2503 return this;
2504 };
2505
2506 /**
2507 * Set window dimensions. This method is called by the {@link OO.ui.WindowManager window manager}
2508 * when the window is opening. In general, setDimensions should not be called directly.
2509 *
2510 * To set the size of the window, use the #setSize method.
2511 *
2512 * @param {Object} dim CSS dimension properties
2513 * @param {string|number} [dim.width] Width
2514 * @param {string|number} [dim.minWidth] Minimum width
2515 * @param {string|number} [dim.maxWidth] Maximum width
2516 * @param {string|number} [dim.width] Height, omit to set based on height of contents
2517 * @param {string|number} [dim.minWidth] Minimum height
2518 * @param {string|number} [dim.maxWidth] Maximum height
2519 * @chainable
2520 */
2521 OO.ui.Window.prototype.setDimensions = function ( dim ) {
2522 var height,
2523 win = this,
2524 styleObj = this.$frame[ 0 ].style;
2525
2526 // Calculate the height we need to set using the correct width
2527 if ( dim.height === undefined ) {
2528 this.withoutSizeTransitions( function () {
2529 var oldWidth = styleObj.width;
2530 win.$frame.css( 'width', dim.width || '' );
2531 height = win.getContentHeight();
2532 styleObj.width = oldWidth;
2533 } );
2534 } else {
2535 height = dim.height;
2536 }
2537
2538 this.$frame.css( {
2539 width: dim.width || '',
2540 minWidth: dim.minWidth || '',
2541 maxWidth: dim.maxWidth || '',
2542 height: height || '',
2543 minHeight: dim.minHeight || '',
2544 maxHeight: dim.maxHeight || ''
2545 } );
2546
2547 return this;
2548 };
2549
2550 /**
2551 * Initialize window contents.
2552 *
2553 * Before the window is opened for the first time, #initialize is called so that content that
2554 * persists between openings can be added to the window.
2555 *
2556 * To set up a window with new content each time the window opens, use #getSetupProcess.
2557 *
2558 * @throws {Error} An error is thrown if the window is not attached to a window manager
2559 * @chainable
2560 */
2561 OO.ui.Window.prototype.initialize = function () {
2562 if ( !this.manager ) {
2563 throw new Error( 'Cannot initialize window, must be attached to a manager' );
2564 }
2565
2566 // Properties
2567 this.$head = $( '<div>' );
2568 this.$body = $( '<div>' );
2569 this.$foot = $( '<div>' );
2570 this.$document = $( this.getElementDocument() );
2571
2572 // Events
2573 this.$element.on( 'mousedown', this.onMouseDown.bind( this ) );
2574
2575 // Initialization
2576 this.$head.addClass( 'oo-ui-window-head' );
2577 this.$body.addClass( 'oo-ui-window-body' );
2578 this.$foot.addClass( 'oo-ui-window-foot' );
2579 this.$content.append( this.$head, this.$body, this.$foot );
2580
2581 return this;
2582 };
2583
2584 /**
2585 * Called when someone tries to focus the hidden element at the end of the dialog.
2586 * Sends focus back to the start of the dialog.
2587 *
2588 * @param {jQuery.Event} event Focus event
2589 */
2590 OO.ui.Window.prototype.onFocusTrapFocused = function ( event ) {
2591 if ( this.$focusTrapBefore.is( event.target ) ) {
2592 OO.ui.findFocusable( this.$content, true ).focus();
2593 } else {
2594 // this.$content is the part of the focus cycle, and is the first focusable element
2595 this.$content.focus();
2596 }
2597 };
2598
2599 /**
2600 * Open the window.
2601 *
2602 * This method is a wrapper around a call to the window manager’s {@link OO.ui.WindowManager#openWindow openWindow}
2603 * method, which returns a promise resolved when the window is done opening.
2604 *
2605 * To customize the window each time it opens, use #getSetupProcess or #getReadyProcess.
2606 *
2607 * @param {Object} [data] Window opening data
2608 * @return {jQuery.Promise} Promise resolved with a value when the window is opened, or rejected
2609 * if the window fails to open. When the promise is resolved successfully, the first argument of the
2610 * value is a new promise, which is resolved when the window begins closing.
2611 * @throws {Error} An error is thrown if the window is not attached to a window manager
2612 */
2613 OO.ui.Window.prototype.open = function ( data ) {
2614 if ( !this.manager ) {
2615 throw new Error( 'Cannot open window, must be attached to a manager' );
2616 }
2617
2618 return this.manager.openWindow( this, data );
2619 };
2620
2621 /**
2622 * Close the window.
2623 *
2624 * This method is a wrapper around a call to the window
2625 * manager’s {@link OO.ui.WindowManager#closeWindow closeWindow} method,
2626 * which returns a closing promise resolved when the window is done closing.
2627 *
2628 * The window's #getHoldProcess and #getTeardownProcess methods are called during the closing
2629 * phase of the window’s lifecycle and can be used to specify closing behavior each time
2630 * the window closes.
2631 *
2632 * @param {Object} [data] Window closing data
2633 * @return {jQuery.Promise} Promise resolved when window is closed
2634 * @throws {Error} An error is thrown if the window is not attached to a window manager
2635 */
2636 OO.ui.Window.prototype.close = function ( data ) {
2637 if ( !this.manager ) {
2638 throw new Error( 'Cannot close window, must be attached to a manager' );
2639 }
2640
2641 return this.manager.closeWindow( this, data );
2642 };
2643
2644 /**
2645 * Setup window.
2646 *
2647 * This is called by OO.ui.WindowManager during window opening, and should not be called directly
2648 * by other systems.
2649 *
2650 * @param {Object} [data] Window opening data
2651 * @return {jQuery.Promise} Promise resolved when window is setup
2652 */
2653 OO.ui.Window.prototype.setup = function ( data ) {
2654 var win = this,
2655 deferred = $.Deferred();
2656
2657 this.toggle( true );
2658
2659 this.focusTrapHandler = OO.ui.bind( this.onFocusTrapFocused, this );
2660 this.$focusTraps.on( 'focus', this.focusTrapHandler );
2661
2662 this.getSetupProcess( data ).execute().done( function () {
2663 // Force redraw by asking the browser to measure the elements' widths
2664 win.$element.addClass( 'oo-ui-window-active oo-ui-window-setup' ).width();
2665 win.$content.addClass( 'oo-ui-window-content-setup' ).width();
2666 deferred.resolve();
2667 } );
2668
2669 return deferred.promise();
2670 };
2671
2672 /**
2673 * Ready window.
2674 *
2675 * This is called by OO.ui.WindowManager during window opening, and should not be called directly
2676 * by other systems.
2677 *
2678 * @param {Object} [data] Window opening data
2679 * @return {jQuery.Promise} Promise resolved when window is ready
2680 */
2681 OO.ui.Window.prototype.ready = function ( data ) {
2682 var win = this,
2683 deferred = $.Deferred();
2684
2685 this.$content.focus();
2686 this.getReadyProcess( data ).execute().done( function () {
2687 // Force redraw by asking the browser to measure the elements' widths
2688 win.$element.addClass( 'oo-ui-window-ready' ).width();
2689 win.$content.addClass( 'oo-ui-window-content-ready' ).width();
2690 deferred.resolve();
2691 } );
2692
2693 return deferred.promise();
2694 };
2695
2696 /**
2697 * Hold window.
2698 *
2699 * This is called by OO.ui.WindowManager during window closing, and should not be called directly
2700 * by other systems.
2701 *
2702 * @param {Object} [data] Window closing data
2703 * @return {jQuery.Promise} Promise resolved when window is held
2704 */
2705 OO.ui.Window.prototype.hold = function ( data ) {
2706 var win = this,
2707 deferred = $.Deferred();
2708
2709 this.getHoldProcess( data ).execute().done( function () {
2710 // Get the focused element within the window's content
2711 var $focus = win.$content.find( OO.ui.Element.static.getDocument( win.$content ).activeElement );
2712
2713 // Blur the focused element
2714 if ( $focus.length ) {
2715 $focus[ 0 ].blur();
2716 }
2717
2718 // Force redraw by asking the browser to measure the elements' widths
2719 win.$element.removeClass( 'oo-ui-window-ready' ).width();
2720 win.$content.removeClass( 'oo-ui-window-content-ready' ).width();
2721 deferred.resolve();
2722 } );
2723
2724 return deferred.promise();
2725 };
2726
2727 /**
2728 * Teardown window.
2729 *
2730 * This is called by OO.ui.WindowManager during window closing, and should not be called directly
2731 * by other systems.
2732 *
2733 * @param {Object} [data] Window closing data
2734 * @return {jQuery.Promise} Promise resolved when window is torn down
2735 */
2736 OO.ui.Window.prototype.teardown = function ( data ) {
2737 var win = this;
2738
2739 return this.getTeardownProcess( data ).execute()
2740 .done( function () {
2741 // Force redraw by asking the browser to measure the elements' widths
2742 win.$element.removeClass( 'oo-ui-window-active oo-ui-window-setup' ).width();
2743 win.$content.removeClass( 'oo-ui-window-content-setup' ).width();
2744 win.$focusTraps.off( 'focus', win.focusTrapHandler );
2745 win.toggle( false );
2746 } );
2747 };
2748
2749 /**
2750 * The Dialog class serves as the base class for the other types of dialogs.
2751 * Unless extended to include controls, the rendered dialog box is a simple window
2752 * that users can close by hitting the ‘Esc’ key. Dialog windows are used with OO.ui.WindowManager,
2753 * which opens, closes, and controls the presentation of the window. See the
2754 * [OOjs UI documentation on MediaWiki] [1] for more information.
2755 *
2756 * @example
2757 * // A simple dialog window.
2758 * function MyDialog( config ) {
2759 * MyDialog.parent.call( this, config );
2760 * }
2761 * OO.inheritClass( MyDialog, OO.ui.Dialog );
2762 * MyDialog.prototype.initialize = function () {
2763 * MyDialog.parent.prototype.initialize.call( this );
2764 * this.content = new OO.ui.PanelLayout( { padded: true, expanded: false } );
2765 * this.content.$element.append( '<p>A simple dialog window. Press \'Esc\' to close.</p>' );
2766 * this.$body.append( this.content.$element );
2767 * };
2768 * MyDialog.prototype.getBodyHeight = function () {
2769 * return this.content.$element.outerHeight( true );
2770 * };
2771 * var myDialog = new MyDialog( {
2772 * size: 'medium'
2773 * } );
2774 * // Create and append a window manager, which opens and closes the window.
2775 * var windowManager = new OO.ui.WindowManager();
2776 * $( 'body' ).append( windowManager.$element );
2777 * windowManager.addWindows( [ myDialog ] );
2778 * // Open the window!
2779 * windowManager.openWindow( myDialog );
2780 *
2781 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Dialogs
2782 *
2783 * @abstract
2784 * @class
2785 * @extends OO.ui.Window
2786 * @mixins OO.ui.mixin.PendingElement
2787 *
2788 * @constructor
2789 * @param {Object} [config] Configuration options
2790 */
2791 OO.ui.Dialog = function OoUiDialog( config ) {
2792 // Parent constructor
2793 OO.ui.Dialog.parent.call( this, config );
2794
2795 // Mixin constructors
2796 OO.ui.mixin.PendingElement.call( this );
2797
2798 // Properties
2799 this.actions = new OO.ui.ActionSet();
2800 this.attachedActions = [];
2801 this.currentAction = null;
2802 this.onDialogKeyDownHandler = this.onDialogKeyDown.bind( this );
2803
2804 // Events
2805 this.actions.connect( this, {
2806 click: 'onActionClick',
2807 resize: 'onActionResize',
2808 change: 'onActionsChange'
2809 } );
2810
2811 // Initialization
2812 this.$element
2813 .addClass( 'oo-ui-dialog' )
2814 .attr( 'role', 'dialog' );
2815 };
2816
2817 /* Setup */
2818
2819 OO.inheritClass( OO.ui.Dialog, OO.ui.Window );
2820 OO.mixinClass( OO.ui.Dialog, OO.ui.mixin.PendingElement );
2821
2822 /* Static Properties */
2823
2824 /**
2825 * Symbolic name of dialog.
2826 *
2827 * The dialog class must have a symbolic name in order to be registered with OO.Factory.
2828 * Please see the [OOjs UI documentation on MediaWiki] [3] for more information.
2829 *
2830 * [3]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
2831 *
2832 * @abstract
2833 * @static
2834 * @inheritable
2835 * @property {string}
2836 */
2837 OO.ui.Dialog.static.name = '';
2838
2839 /**
2840 * The dialog title.
2841 *
2842 * The title can be specified as a plaintext string, a {@link OO.ui.mixin.LabelElement Label} node, or a function
2843 * that will produce a Label node or string. The title can also be specified with data passed to the
2844 * constructor (see #getSetupProcess). In this case, the static value will be overriden.
2845 *
2846 * @abstract
2847 * @static
2848 * @inheritable
2849 * @property {jQuery|string|Function}
2850 */
2851 OO.ui.Dialog.static.title = '';
2852
2853 /**
2854 * An array of configured {@link OO.ui.ActionWidget action widgets}.
2855 *
2856 * Actions can also be specified with data passed to the constructor (see #getSetupProcess). In this case, the static
2857 * value will be overriden.
2858 *
2859 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Action_sets
2860 *
2861 * @static
2862 * @inheritable
2863 * @property {Object[]}
2864 */
2865 OO.ui.Dialog.static.actions = [];
2866
2867 /**
2868 * Close the dialog when the 'Esc' key is pressed.
2869 *
2870 * @static
2871 * @abstract
2872 * @inheritable
2873 * @property {boolean}
2874 */
2875 OO.ui.Dialog.static.escapable = true;
2876
2877 /* Methods */
2878
2879 /**
2880 * Handle frame document key down events.
2881 *
2882 * @private
2883 * @param {jQuery.Event} e Key down event
2884 */
2885 OO.ui.Dialog.prototype.onDialogKeyDown = function ( e ) {
2886 if ( e.which === OO.ui.Keys.ESCAPE ) {
2887 this.close();
2888 e.preventDefault();
2889 e.stopPropagation();
2890 }
2891 };
2892
2893 /**
2894 * Handle action resized events.
2895 *
2896 * @private
2897 * @param {OO.ui.ActionWidget} action Action that was resized
2898 */
2899 OO.ui.Dialog.prototype.onActionResize = function () {
2900 // Override in subclass
2901 };
2902
2903 /**
2904 * Handle action click events.
2905 *
2906 * @private
2907 * @param {OO.ui.ActionWidget} action Action that was clicked
2908 */
2909 OO.ui.Dialog.prototype.onActionClick = function ( action ) {
2910 if ( !this.isPending() ) {
2911 this.executeAction( action.getAction() );
2912 }
2913 };
2914
2915 /**
2916 * Handle actions change event.
2917 *
2918 * @private
2919 */
2920 OO.ui.Dialog.prototype.onActionsChange = function () {
2921 this.detachActions();
2922 if ( !this.isClosing() ) {
2923 this.attachActions();
2924 }
2925 };
2926
2927 /**
2928 * Get the set of actions used by the dialog.
2929 *
2930 * @return {OO.ui.ActionSet}
2931 */
2932 OO.ui.Dialog.prototype.getActions = function () {
2933 return this.actions;
2934 };
2935
2936 /**
2937 * Get a process for taking action.
2938 *
2939 * When you override this method, you can create a new OO.ui.Process and return it, or add additional
2940 * accept steps to the process the parent method provides using the {@link OO.ui.Process#first 'first'}
2941 * and {@link OO.ui.Process#next 'next'} methods of OO.ui.Process.
2942 *
2943 * @abstract
2944 * @param {string} [action] Symbolic name of action
2945 * @return {OO.ui.Process} Action process
2946 */
2947 OO.ui.Dialog.prototype.getActionProcess = function ( action ) {
2948 return new OO.ui.Process()
2949 .next( function () {
2950 if ( !action ) {
2951 // An empty action always closes the dialog without data, which should always be
2952 // safe and make no changes
2953 this.close();
2954 }
2955 }, this );
2956 };
2957
2958 /**
2959 * @inheritdoc
2960 *
2961 * @param {Object} [data] Dialog opening data
2962 * @param {jQuery|string|Function|null} [data.title] Dialog title, omit to use
2963 * the {@link #static-title static title}
2964 * @param {Object[]} [data.actions] List of configuration options for each
2965 * {@link OO.ui.ActionWidget action widget}, omit to use {@link #static-actions static actions}.
2966 */
2967 OO.ui.Dialog.prototype.getSetupProcess = function ( data ) {
2968 data = data || {};
2969
2970 // Parent method
2971 return OO.ui.Dialog.parent.prototype.getSetupProcess.call( this, data )
2972 .next( function () {
2973 var config = this.constructor.static,
2974 actions = data.actions !== undefined ? data.actions : config.actions;
2975
2976 this.title.setLabel(
2977 data.title !== undefined ? data.title : this.constructor.static.title
2978 );
2979 this.actions.add( this.getActionWidgets( actions ) );
2980
2981 if ( this.constructor.static.escapable ) {
2982 this.$element.on( 'keydown', this.onDialogKeyDownHandler );
2983 }
2984 }, this );
2985 };
2986
2987 /**
2988 * @inheritdoc
2989 */
2990 OO.ui.Dialog.prototype.getTeardownProcess = function ( data ) {
2991 // Parent method
2992 return OO.ui.Dialog.parent.prototype.getTeardownProcess.call( this, data )
2993 .first( function () {
2994 if ( this.constructor.static.escapable ) {
2995 this.$element.off( 'keydown', this.onDialogKeyDownHandler );
2996 }
2997
2998 this.actions.clear();
2999 this.currentAction = null;
3000 }, this );
3001 };
3002
3003 /**
3004 * @inheritdoc
3005 */
3006 OO.ui.Dialog.prototype.initialize = function () {
3007 var titleId;
3008
3009 // Parent method
3010 OO.ui.Dialog.parent.prototype.initialize.call( this );
3011
3012 titleId = OO.ui.generateElementId();
3013
3014 // Properties
3015 this.title = new OO.ui.LabelWidget( {
3016 id: titleId
3017 } );
3018
3019 // Initialization
3020 this.$content.addClass( 'oo-ui-dialog-content' );
3021 this.$element.attr( 'aria-labelledby', titleId );
3022 this.setPendingElement( this.$head );
3023 };
3024
3025 /**
3026 * Get action widgets from a list of configs
3027 *
3028 * @param {Object[]} actions Action widget configs
3029 * @return {OO.ui.ActionWidget[]} Action widgets
3030 */
3031 OO.ui.Dialog.prototype.getActionWidgets = function ( actions ) {
3032 var i, len, widgets = [];
3033 for ( i = 0, len = actions.length; i < len; i++ ) {
3034 widgets.push(
3035 new OO.ui.ActionWidget( actions[ i ] )
3036 );
3037 }
3038 return widgets;
3039 };
3040
3041 /**
3042 * Attach action actions.
3043 *
3044 * @protected
3045 */
3046 OO.ui.Dialog.prototype.attachActions = function () {
3047 // Remember the list of potentially attached actions
3048 this.attachedActions = this.actions.get();
3049 };
3050
3051 /**
3052 * Detach action actions.
3053 *
3054 * @protected
3055 * @chainable
3056 */
3057 OO.ui.Dialog.prototype.detachActions = function () {
3058 var i, len;
3059
3060 // Detach all actions that may have been previously attached
3061 for ( i = 0, len = this.attachedActions.length; i < len; i++ ) {
3062 this.attachedActions[ i ].$element.detach();
3063 }
3064 this.attachedActions = [];
3065 };
3066
3067 /**
3068 * Execute an action.
3069 *
3070 * @param {string} action Symbolic name of action to execute
3071 * @return {jQuery.Promise} Promise resolved when action completes, rejected if it fails
3072 */
3073 OO.ui.Dialog.prototype.executeAction = function ( action ) {
3074 this.pushPending();
3075 this.currentAction = action;
3076 return this.getActionProcess( action ).execute()
3077 .always( this.popPending.bind( this ) );
3078 };
3079
3080 /**
3081 * Window managers are used to open and close {@link OO.ui.Window windows} and control their presentation.
3082 * Managed windows are mutually exclusive. If a new window is opened while a current window is opening
3083 * or is opened, the current window will be closed and any ongoing {@link OO.ui.Process process} will be cancelled. Windows
3084 * themselves are persistent and—rather than being torn down when closed—can be repopulated with the
3085 * pertinent data and reused.
3086 *
3087 * Over the lifecycle of a window, the window manager makes available three promises: `opening`,
3088 * `opened`, and `closing`, which represent the primary stages of the cycle:
3089 *
3090 * **Opening**: the opening stage begins when the window manager’s #openWindow or a window’s
3091 * {@link OO.ui.Window#open open} method is used, and the window manager begins to open the window.
3092 *
3093 * - an `opening` event is emitted with an `opening` promise
3094 * - the #getSetupDelay method is called and the returned value is used to time a pause in execution before
3095 * the window’s {@link OO.ui.Window#getSetupProcess getSetupProcess} method is called on the
3096 * window and its result executed
3097 * - a `setup` progress notification is emitted from the `opening` promise
3098 * - the #getReadyDelay method is called the returned value is used to time a pause in execution before
3099 * the window’s {@link OO.ui.Window#getReadyProcess getReadyProcess} method is called on the
3100 * window and its result executed
3101 * - a `ready` progress notification is emitted from the `opening` promise
3102 * - the `opening` promise is resolved with an `opened` promise
3103 *
3104 * **Opened**: the window is now open.
3105 *
3106 * **Closing**: the closing stage begins when the window manager's #closeWindow or the
3107 * window's {@link OO.ui.Window#close close} methods is used, and the window manager begins
3108 * to close the window.
3109 *
3110 * - the `opened` promise is resolved with `closing` promise and a `closing` event is emitted
3111 * - the #getHoldDelay method is called and the returned value is used to time a pause in execution before
3112 * the window's {@link OO.ui.Window#getHoldProcess getHoldProces} method is called on the
3113 * window and its result executed
3114 * - a `hold` progress notification is emitted from the `closing` promise
3115 * - the #getTeardownDelay() method is called and the returned value is used to time a pause in execution before
3116 * the window's {@link OO.ui.Window#getTeardownProcess getTeardownProcess} method is called on the
3117 * window and its result executed
3118 * - a `teardown` progress notification is emitted from the `closing` promise
3119 * - the `closing` promise is resolved. The window is now closed
3120 *
3121 * See the [OOjs UI documentation on MediaWiki][1] for more information.
3122 *
3123 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
3124 *
3125 * @class
3126 * @extends OO.ui.Element
3127 * @mixins OO.EventEmitter
3128 *
3129 * @constructor
3130 * @param {Object} [config] Configuration options
3131 * @cfg {OO.Factory} [factory] Window factory to use for automatic instantiation
3132 * Note that window classes that are instantiated with a factory must have
3133 * a {@link OO.ui.Dialog#static-name static name} property that specifies a symbolic name.
3134 * @cfg {boolean} [modal=true] Prevent interaction outside the dialog
3135 */
3136 OO.ui.WindowManager = function OoUiWindowManager( config ) {
3137 // Configuration initialization
3138 config = config || {};
3139
3140 // Parent constructor
3141 OO.ui.WindowManager.parent.call( this, config );
3142
3143 // Mixin constructors
3144 OO.EventEmitter.call( this );
3145
3146 // Properties
3147 this.factory = config.factory;
3148 this.modal = config.modal === undefined || !!config.modal;
3149 this.windows = {};
3150 this.opening = null;
3151 this.opened = null;
3152 this.closing = null;
3153 this.preparingToOpen = null;
3154 this.preparingToClose = null;
3155 this.currentWindow = null;
3156 this.globalEvents = false;
3157 this.$ariaHidden = null;
3158 this.onWindowResizeTimeout = null;
3159 this.onWindowResizeHandler = this.onWindowResize.bind( this );
3160 this.afterWindowResizeHandler = this.afterWindowResize.bind( this );
3161
3162 // Initialization
3163 this.$element
3164 .addClass( 'oo-ui-windowManager' )
3165 .toggleClass( 'oo-ui-windowManager-modal', this.modal );
3166 };
3167
3168 /* Setup */
3169
3170 OO.inheritClass( OO.ui.WindowManager, OO.ui.Element );
3171 OO.mixinClass( OO.ui.WindowManager, OO.EventEmitter );
3172
3173 /* Events */
3174
3175 /**
3176 * An 'opening' event is emitted when the window begins to be opened.
3177 *
3178 * @event opening
3179 * @param {OO.ui.Window} win Window that's being opened
3180 * @param {jQuery.Promise} opening An `opening` promise resolved with a value when the window is opened successfully.
3181 * When the `opening` promise is resolved, the first argument of the value is an 'opened' promise, the second argument
3182 * is the opening data. The `opening` promise emits `setup` and `ready` notifications when those processes are complete.
3183 * @param {Object} data Window opening data
3184 */
3185
3186 /**
3187 * A 'closing' event is emitted when the window begins to be closed.
3188 *
3189 * @event closing
3190 * @param {OO.ui.Window} win Window that's being closed
3191 * @param {jQuery.Promise} closing A `closing` promise is resolved with a value when the window
3192 * is closed successfully. The promise emits `hold` and `teardown` notifications when those
3193 * processes are complete. When the `closing` promise is resolved, the first argument of its value
3194 * is the closing data.
3195 * @param {Object} data Window closing data
3196 */
3197
3198 /**
3199 * A 'resize' event is emitted when a window is resized.
3200 *
3201 * @event resize
3202 * @param {OO.ui.Window} win Window that was resized
3203 */
3204
3205 /* Static Properties */
3206
3207 /**
3208 * Map of the symbolic name of each window size and its CSS properties.
3209 *
3210 * @static
3211 * @inheritable
3212 * @property {Object}
3213 */
3214 OO.ui.WindowManager.static.sizes = {
3215 small: {
3216 width: 300
3217 },
3218 medium: {
3219 width: 500
3220 },
3221 large: {
3222 width: 700
3223 },
3224 larger: {
3225 width: 900
3226 },
3227 full: {
3228 // These can be non-numeric because they are never used in calculations
3229 width: '100%',
3230 height: '100%'
3231 }
3232 };
3233
3234 /**
3235 * Symbolic name of the default window size.
3236 *
3237 * The default size is used if the window's requested size is not recognized.
3238 *
3239 * @static
3240 * @inheritable
3241 * @property {string}
3242 */
3243 OO.ui.WindowManager.static.defaultSize = 'medium';
3244
3245 /* Methods */
3246
3247 /**
3248 * Handle window resize events.
3249 *
3250 * @private
3251 * @param {jQuery.Event} e Window resize event
3252 */
3253 OO.ui.WindowManager.prototype.onWindowResize = function () {
3254 clearTimeout( this.onWindowResizeTimeout );
3255 this.onWindowResizeTimeout = setTimeout( this.afterWindowResizeHandler, 200 );
3256 };
3257
3258 /**
3259 * Handle window resize events.
3260 *
3261 * @private
3262 * @param {jQuery.Event} e Window resize event
3263 */
3264 OO.ui.WindowManager.prototype.afterWindowResize = function () {
3265 if ( this.currentWindow ) {
3266 this.updateWindowSize( this.currentWindow );
3267 }
3268 };
3269
3270 /**
3271 * Check if window is opening.
3272 *
3273 * @return {boolean} Window is opening
3274 */
3275 OO.ui.WindowManager.prototype.isOpening = function ( win ) {
3276 return win === this.currentWindow && !!this.opening && this.opening.state() === 'pending';
3277 };
3278
3279 /**
3280 * Check if window is closing.
3281 *
3282 * @return {boolean} Window is closing
3283 */
3284 OO.ui.WindowManager.prototype.isClosing = function ( win ) {
3285 return win === this.currentWindow && !!this.closing && this.closing.state() === 'pending';
3286 };
3287
3288 /**
3289 * Check if window is opened.
3290 *
3291 * @return {boolean} Window is opened
3292 */
3293 OO.ui.WindowManager.prototype.isOpened = function ( win ) {
3294 return win === this.currentWindow && !!this.opened && this.opened.state() === 'pending';
3295 };
3296
3297 /**
3298 * Check if a window is being managed.
3299 *
3300 * @param {OO.ui.Window} win Window to check
3301 * @return {boolean} Window is being managed
3302 */
3303 OO.ui.WindowManager.prototype.hasWindow = function ( win ) {
3304 var name;
3305
3306 for ( name in this.windows ) {
3307 if ( this.windows[ name ] === win ) {
3308 return true;
3309 }
3310 }
3311
3312 return false;
3313 };
3314
3315 /**
3316 * Get the number of milliseconds to wait after opening begins before executing the ‘setup’ process.
3317 *
3318 * @param {OO.ui.Window} win Window being opened
3319 * @param {Object} [data] Window opening data
3320 * @return {number} Milliseconds to wait
3321 */
3322 OO.ui.WindowManager.prototype.getSetupDelay = function () {
3323 return 0;
3324 };
3325
3326 /**
3327 * Get the number of milliseconds to wait after setup has finished before executing the ‘ready’ process.
3328 *
3329 * @param {OO.ui.Window} win Window being opened
3330 * @param {Object} [data] Window opening data
3331 * @return {number} Milliseconds to wait
3332 */
3333 OO.ui.WindowManager.prototype.getReadyDelay = function () {
3334 return 0;
3335 };
3336
3337 /**
3338 * Get the number of milliseconds to wait after closing has begun before executing the 'hold' process.
3339 *
3340 * @param {OO.ui.Window} win Window being closed
3341 * @param {Object} [data] Window closing data
3342 * @return {number} Milliseconds to wait
3343 */
3344 OO.ui.WindowManager.prototype.getHoldDelay = function () {
3345 return 0;
3346 };
3347
3348 /**
3349 * Get the number of milliseconds to wait after the ‘hold’ process has finished before
3350 * executing the ‘teardown’ process.
3351 *
3352 * @param {OO.ui.Window} win Window being closed
3353 * @param {Object} [data] Window closing data
3354 * @return {number} Milliseconds to wait
3355 */
3356 OO.ui.WindowManager.prototype.getTeardownDelay = function () {
3357 return this.modal ? 250 : 0;
3358 };
3359
3360 /**
3361 * Get a window by its symbolic name.
3362 *
3363 * If the window is not yet instantiated and its symbolic name is recognized by a factory, it will be
3364 * instantiated and added to the window manager automatically. Please see the [OOjs UI documentation on MediaWiki][3]
3365 * for more information about using factories.
3366 * [3]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
3367 *
3368 * @param {string} name Symbolic name of the window
3369 * @return {jQuery.Promise} Promise resolved with matching window, or rejected with an OO.ui.Error
3370 * @throws {Error} An error is thrown if the symbolic name is not recognized by the factory.
3371 * @throws {Error} An error is thrown if the named window is not recognized as a managed window.
3372 */
3373 OO.ui.WindowManager.prototype.getWindow = function ( name ) {
3374 var deferred = $.Deferred(),
3375 win = this.windows[ name ];
3376
3377 if ( !( win instanceof OO.ui.Window ) ) {
3378 if ( this.factory ) {
3379 if ( !this.factory.lookup( name ) ) {
3380 deferred.reject( new OO.ui.Error(
3381 'Cannot auto-instantiate window: symbolic name is unrecognized by the factory'
3382 ) );
3383 } else {
3384 win = this.factory.create( name );
3385 this.addWindows( [ win ] );
3386 deferred.resolve( win );
3387 }
3388 } else {
3389 deferred.reject( new OO.ui.Error(
3390 'Cannot get unmanaged window: symbolic name unrecognized as a managed window'
3391 ) );
3392 }
3393 } else {
3394 deferred.resolve( win );
3395 }
3396
3397 return deferred.promise();
3398 };
3399
3400 /**
3401 * Get current window.
3402 *
3403 * @return {OO.ui.Window|null} Currently opening/opened/closing window
3404 */
3405 OO.ui.WindowManager.prototype.getCurrentWindow = function () {
3406 return this.currentWindow;
3407 };
3408
3409 /**
3410 * Open a window.
3411 *
3412 * @param {OO.ui.Window|string} win Window object or symbolic name of window to open
3413 * @param {Object} [data] Window opening data
3414 * @return {jQuery.Promise} An `opening` promise resolved when the window is done opening.
3415 * See {@link #event-opening 'opening' event} for more information about `opening` promises.
3416 * @fires opening
3417 */
3418 OO.ui.WindowManager.prototype.openWindow = function ( win, data ) {
3419 var manager = this,
3420 opening = $.Deferred();
3421
3422 // Argument handling
3423 if ( typeof win === 'string' ) {
3424 return this.getWindow( win ).then( function ( win ) {
3425 return manager.openWindow( win, data );
3426 } );
3427 }
3428
3429 // Error handling
3430 if ( !this.hasWindow( win ) ) {
3431 opening.reject( new OO.ui.Error(
3432 'Cannot open window: window is not attached to manager'
3433 ) );
3434 } else if ( this.preparingToOpen || this.opening || this.opened ) {
3435 opening.reject( new OO.ui.Error(
3436 'Cannot open window: another window is opening or open'
3437 ) );
3438 }
3439
3440 // Window opening
3441 if ( opening.state() !== 'rejected' ) {
3442 // If a window is currently closing, wait for it to complete
3443 this.preparingToOpen = $.when( this.closing );
3444 // Ensure handlers get called after preparingToOpen is set
3445 this.preparingToOpen.done( function () {
3446 if ( manager.modal ) {
3447 manager.toggleGlobalEvents( true );
3448 manager.toggleAriaIsolation( true );
3449 }
3450 manager.currentWindow = win;
3451 manager.opening = opening;
3452 manager.preparingToOpen = null;
3453 manager.emit( 'opening', win, opening, data );
3454 setTimeout( function () {
3455 win.setup( data ).then( function () {
3456 manager.updateWindowSize( win );
3457 manager.opening.notify( { state: 'setup' } );
3458 setTimeout( function () {
3459 win.ready( data ).then( function () {
3460 manager.opening.notify( { state: 'ready' } );
3461 manager.opening = null;
3462 manager.opened = $.Deferred();
3463 opening.resolve( manager.opened.promise(), data );
3464 } );
3465 }, manager.getReadyDelay() );
3466 } );
3467 }, manager.getSetupDelay() );
3468 } );
3469 }
3470
3471 return opening.promise();
3472 };
3473
3474 /**
3475 * Close a window.
3476 *
3477 * @param {OO.ui.Window|string} win Window object or symbolic name of window to close
3478 * @param {Object} [data] Window closing data
3479 * @return {jQuery.Promise} A `closing` promise resolved when the window is done closing.
3480 * See {@link #event-closing 'closing' event} for more information about closing promises.
3481 * @throws {Error} An error is thrown if the window is not managed by the window manager.
3482 * @fires closing
3483 */
3484 OO.ui.WindowManager.prototype.closeWindow = function ( win, data ) {
3485 var manager = this,
3486 closing = $.Deferred(),
3487 opened;
3488
3489 // Argument handling
3490 if ( typeof win === 'string' ) {
3491 win = this.windows[ win ];
3492 } else if ( !this.hasWindow( win ) ) {
3493 win = null;
3494 }
3495
3496 // Error handling
3497 if ( !win ) {
3498 closing.reject( new OO.ui.Error(
3499 'Cannot close window: window is not attached to manager'
3500 ) );
3501 } else if ( win !== this.currentWindow ) {
3502 closing.reject( new OO.ui.Error(
3503 'Cannot close window: window already closed with different data'
3504 ) );
3505 } else if ( this.preparingToClose || this.closing ) {
3506 closing.reject( new OO.ui.Error(
3507 'Cannot close window: window already closing with different data'
3508 ) );
3509 }
3510
3511 // Window closing
3512 if ( closing.state() !== 'rejected' ) {
3513 // If the window is currently opening, close it when it's done
3514 this.preparingToClose = $.when( this.opening );
3515 // Ensure handlers get called after preparingToClose is set
3516 this.preparingToClose.done( function () {
3517 manager.closing = closing;
3518 manager.preparingToClose = null;
3519 manager.emit( 'closing', win, closing, data );
3520 opened = manager.opened;
3521 manager.opened = null;
3522 opened.resolve( closing.promise(), data );
3523 setTimeout( function () {
3524 win.hold( data ).then( function () {
3525 closing.notify( { state: 'hold' } );
3526 setTimeout( function () {
3527 win.teardown( data ).then( function () {
3528 closing.notify( { state: 'teardown' } );
3529 if ( manager.modal ) {
3530 manager.toggleGlobalEvents( false );
3531 manager.toggleAriaIsolation( false );
3532 }
3533 manager.closing = null;
3534 manager.currentWindow = null;
3535 closing.resolve( data );
3536 } );
3537 }, manager.getTeardownDelay() );
3538 } );
3539 }, manager.getHoldDelay() );
3540 } );
3541 }
3542
3543 return closing.promise();
3544 };
3545
3546 /**
3547 * Add windows to the window manager.
3548 *
3549 * Windows can be added by reference, symbolic name, or explicitly defined symbolic names.
3550 * See the [OOjs ui documentation on MediaWiki] [2] for examples.
3551 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
3552 *
3553 * @param {Object.<string,OO.ui.Window>|OO.ui.Window[]} windows An array of window objects specified
3554 * by reference, symbolic name, or explicitly defined symbolic names.
3555 * @throws {Error} An error is thrown if a window is added by symbolic name, but has neither an
3556 * explicit nor a statically configured symbolic name.
3557 */
3558 OO.ui.WindowManager.prototype.addWindows = function ( windows ) {
3559 var i, len, win, name, list;
3560
3561 if ( Array.isArray( windows ) ) {
3562 // Convert to map of windows by looking up symbolic names from static configuration
3563 list = {};
3564 for ( i = 0, len = windows.length; i < len; i++ ) {
3565 name = windows[ i ].constructor.static.name;
3566 if ( typeof name !== 'string' ) {
3567 throw new Error( 'Cannot add window' );
3568 }
3569 list[ name ] = windows[ i ];
3570 }
3571 } else if ( OO.isPlainObject( windows ) ) {
3572 list = windows;
3573 }
3574
3575 // Add windows
3576 for ( name in list ) {
3577 win = list[ name ];
3578 this.windows[ name ] = win.toggle( false );
3579 this.$element.append( win.$element );
3580 win.setManager( this );
3581 }
3582 };
3583
3584 /**
3585 * Remove the specified windows from the windows manager.
3586 *
3587 * Windows will be closed before they are removed. If you wish to remove all windows, you may wish to use
3588 * the #clearWindows method instead. If you no longer need the window manager and want to ensure that it no
3589 * longer listens to events, use the #destroy method.
3590 *
3591 * @param {string[]} names Symbolic names of windows to remove
3592 * @return {jQuery.Promise} Promise resolved when window is closed and removed
3593 * @throws {Error} An error is thrown if the named windows are not managed by the window manager.
3594 */
3595 OO.ui.WindowManager.prototype.removeWindows = function ( names ) {
3596 var i, len, win, name, cleanupWindow,
3597 manager = this,
3598 promises = [],
3599 cleanup = function ( name, win ) {
3600 delete manager.windows[ name ];
3601 win.$element.detach();
3602 };
3603
3604 for ( i = 0, len = names.length; i < len; i++ ) {
3605 name = names[ i ];
3606 win = this.windows[ name ];
3607 if ( !win ) {
3608 throw new Error( 'Cannot remove window' );
3609 }
3610 cleanupWindow = cleanup.bind( null, name, win );
3611 promises.push( this.closeWindow( name ).then( cleanupWindow, cleanupWindow ) );
3612 }
3613
3614 return $.when.apply( $, promises );
3615 };
3616
3617 /**
3618 * Remove all windows from the window manager.
3619 *
3620 * Windows will be closed before they are removed. Note that the window manager, though not in use, will still
3621 * listen to events. If the window manager will not be used again, you may wish to use the #destroy method instead.
3622 * To remove just a subset of windows, use the #removeWindows method.
3623 *
3624 * @return {jQuery.Promise} Promise resolved when all windows are closed and removed
3625 */
3626 OO.ui.WindowManager.prototype.clearWindows = function () {
3627 return this.removeWindows( Object.keys( this.windows ) );
3628 };
3629
3630 /**
3631 * Set dialog size. In general, this method should not be called directly.
3632 *
3633 * Fullscreen mode will be used if the dialog is too wide to fit in the screen.
3634 *
3635 * @chainable
3636 */
3637 OO.ui.WindowManager.prototype.updateWindowSize = function ( win ) {
3638 var isFullscreen;
3639
3640 // Bypass for non-current, and thus invisible, windows
3641 if ( win !== this.currentWindow ) {
3642 return;
3643 }
3644
3645 isFullscreen = win.getSize() === 'full';
3646
3647 this.$element.toggleClass( 'oo-ui-windowManager-fullscreen', isFullscreen );
3648 this.$element.toggleClass( 'oo-ui-windowManager-floating', !isFullscreen );
3649 win.setDimensions( win.getSizeProperties() );
3650
3651 this.emit( 'resize', win );
3652
3653 return this;
3654 };
3655
3656 /**
3657 * Bind or unbind global events for scrolling.
3658 *
3659 * @private
3660 * @param {boolean} [on] Bind global events
3661 * @chainable
3662 */
3663 OO.ui.WindowManager.prototype.toggleGlobalEvents = function ( on ) {
3664 var scrollWidth, bodyMargin,
3665 $body = $( this.getElementDocument().body ),
3666 // We could have multiple window managers open so only modify
3667 // the body css at the bottom of the stack
3668 stackDepth = $body.data( 'windowManagerGlobalEvents' ) || 0 ;
3669
3670 on = on === undefined ? !!this.globalEvents : !!on;
3671
3672 if ( on ) {
3673 if ( !this.globalEvents ) {
3674 $( this.getElementWindow() ).on( {
3675 // Start listening for top-level window dimension changes
3676 'orientationchange resize': this.onWindowResizeHandler
3677 } );
3678 if ( stackDepth === 0 ) {
3679 scrollWidth = window.innerWidth - document.documentElement.clientWidth;
3680 bodyMargin = parseFloat( $body.css( 'margin-right' ) ) || 0;
3681 $body.css( {
3682 overflow: 'hidden',
3683 'margin-right': bodyMargin + scrollWidth
3684 } );
3685 }
3686 stackDepth++;
3687 this.globalEvents = true;
3688 }
3689 } else if ( this.globalEvents ) {
3690 $( this.getElementWindow() ).off( {
3691 // Stop listening for top-level window dimension changes
3692 'orientationchange resize': this.onWindowResizeHandler
3693 } );
3694 stackDepth--;
3695 if ( stackDepth === 0 ) {
3696 $body.css( {
3697 overflow: '',
3698 'margin-right': ''
3699 } );
3700 }
3701 this.globalEvents = false;
3702 }
3703 $body.data( 'windowManagerGlobalEvents', stackDepth );
3704
3705 return this;
3706 };
3707
3708 /**
3709 * Toggle screen reader visibility of content other than the window manager.
3710 *
3711 * @private
3712 * @param {boolean} [isolate] Make only the window manager visible to screen readers
3713 * @chainable
3714 */
3715 OO.ui.WindowManager.prototype.toggleAriaIsolation = function ( isolate ) {
3716 isolate = isolate === undefined ? !this.$ariaHidden : !!isolate;
3717
3718 if ( isolate ) {
3719 if ( !this.$ariaHidden ) {
3720 // Hide everything other than the window manager from screen readers
3721 this.$ariaHidden = $( 'body' )
3722 .children()
3723 .not( this.$element.parentsUntil( 'body' ).last() )
3724 .attr( 'aria-hidden', '' );
3725 }
3726 } else if ( this.$ariaHidden ) {
3727 // Restore screen reader visibility
3728 this.$ariaHidden.removeAttr( 'aria-hidden' );
3729 this.$ariaHidden = null;
3730 }
3731
3732 return this;
3733 };
3734
3735 /**
3736 * Destroy the window manager.
3737 *
3738 * Destroying the window manager ensures that it will no longer listen to events. If you would like to
3739 * continue using the window manager, but wish to remove all windows from it, use the #clearWindows method
3740 * instead.
3741 */
3742 OO.ui.WindowManager.prototype.destroy = function () {
3743 this.toggleGlobalEvents( false );
3744 this.toggleAriaIsolation( false );
3745 this.clearWindows();
3746 this.$element.remove();
3747 };
3748
3749 /**
3750 * Errors contain a required message (either a string or jQuery selection) that is used to describe what went wrong
3751 * in a {@link OO.ui.Process process}. The error's #recoverable and #warning configurations are used to customize the
3752 * appearance and functionality of the error interface.
3753 *
3754 * The basic error interface contains a formatted error message as well as two buttons: 'Dismiss' and 'Try again' (i.e., the error
3755 * is 'recoverable' by default). If the error is not recoverable, the 'Try again' button will not be rendered and the widget
3756 * that initiated the failed process will be disabled.
3757 *
3758 * If the error is a warning, the error interface will include a 'Dismiss' and a 'Continue' button, which will try the
3759 * process again.
3760 *
3761 * For an example of error interfaces, please see the [OOjs UI documentation on MediaWiki][1].
3762 *
3763 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Processes_and_errors
3764 *
3765 * @class
3766 *
3767 * @constructor
3768 * @param {string|jQuery} message Description of error
3769 * @param {Object} [config] Configuration options
3770 * @cfg {boolean} [recoverable=true] Error is recoverable.
3771 * By default, errors are recoverable, and users can try the process again.
3772 * @cfg {boolean} [warning=false] Error is a warning.
3773 * If the error is a warning, the error interface will include a
3774 * 'Dismiss' and a 'Continue' button. It is the responsibility of the developer to ensure that the warning
3775 * is not triggered a second time if the user chooses to continue.
3776 */
3777 OO.ui.Error = function OoUiError( message, config ) {
3778 // Allow passing positional parameters inside the config object
3779 if ( OO.isPlainObject( message ) && config === undefined ) {
3780 config = message;
3781 message = config.message;
3782 }
3783
3784 // Configuration initialization
3785 config = config || {};
3786
3787 // Properties
3788 this.message = message instanceof jQuery ? message : String( message );
3789 this.recoverable = config.recoverable === undefined || !!config.recoverable;
3790 this.warning = !!config.warning;
3791 };
3792
3793 /* Setup */
3794
3795 OO.initClass( OO.ui.Error );
3796
3797 /* Methods */
3798
3799 /**
3800 * Check if the error is recoverable.
3801 *
3802 * If the error is recoverable, users are able to try the process again.
3803 *
3804 * @return {boolean} Error is recoverable
3805 */
3806 OO.ui.Error.prototype.isRecoverable = function () {
3807 return this.recoverable;
3808 };
3809
3810 /**
3811 * Check if the error is a warning.
3812 *
3813 * If the error is a warning, the error interface will include a 'Dismiss' and a 'Continue' button.
3814 *
3815 * @return {boolean} Error is warning
3816 */
3817 OO.ui.Error.prototype.isWarning = function () {
3818 return this.warning;
3819 };
3820
3821 /**
3822 * Get error message as DOM nodes.
3823 *
3824 * @return {jQuery} Error message in DOM nodes
3825 */
3826 OO.ui.Error.prototype.getMessage = function () {
3827 return this.message instanceof jQuery ?
3828 this.message.clone() :
3829 $( '<div>' ).text( this.message ).contents();
3830 };
3831
3832 /**
3833 * Get the error message text.
3834 *
3835 * @return {string} Error message
3836 */
3837 OO.ui.Error.prototype.getMessageText = function () {
3838 return this.message instanceof jQuery ? this.message.text() : this.message;
3839 };
3840
3841 /**
3842 * Wraps an HTML snippet for use with configuration values which default
3843 * to strings. This bypasses the default html-escaping done to string
3844 * values.
3845 *
3846 * @class
3847 *
3848 * @constructor
3849 * @param {string} [content] HTML content
3850 */
3851 OO.ui.HtmlSnippet = function OoUiHtmlSnippet( content ) {
3852 // Properties
3853 this.content = content;
3854 };
3855
3856 /* Setup */
3857
3858 OO.initClass( OO.ui.HtmlSnippet );
3859
3860 /* Methods */
3861
3862 /**
3863 * Render into HTML.
3864 *
3865 * @return {string} Unchanged HTML snippet.
3866 */
3867 OO.ui.HtmlSnippet.prototype.toString = function () {
3868 return this.content;
3869 };
3870
3871 /**
3872 * A Process is a list of steps that are called in sequence. The step can be a number, a jQuery promise,
3873 * or a function:
3874 *
3875 * - **number**: the process will wait for the specified number of milliseconds before proceeding.
3876 * - **promise**: the process will continue to the next step when the promise is successfully resolved
3877 * or stop if the promise is rejected.
3878 * - **function**: the process will execute the function. The process will stop if the function returns
3879 * either a boolean `false` or a promise that is rejected; if the function returns a number, the process
3880 * will wait for that number of milliseconds before proceeding.
3881 *
3882 * If the process fails, an {@link OO.ui.Error error} is generated. Depending on how the error is
3883 * configured, users can dismiss the error and try the process again, or not. If a process is stopped,
3884 * its remaining steps will not be performed.
3885 *
3886 * @class
3887 *
3888 * @constructor
3889 * @param {number|jQuery.Promise|Function} step Number of miliseconds to wait before proceeding, promise
3890 * that must be resolved before proceeding, or a function to execute. See #createStep for more information. see #createStep for more information
3891 * @param {Object} [context=null] Execution context of the function. The context is ignored if the step is
3892 * a number or promise.
3893 * @return {Object} Step object, with `callback` and `context` properties
3894 */
3895 OO.ui.Process = function ( step, context ) {
3896 // Properties
3897 this.steps = [];
3898
3899 // Initialization
3900 if ( step !== undefined ) {
3901 this.next( step, context );
3902 }
3903 };
3904
3905 /* Setup */
3906
3907 OO.initClass( OO.ui.Process );
3908
3909 /* Methods */
3910
3911 /**
3912 * Start the process.
3913 *
3914 * @return {jQuery.Promise} Promise that is resolved when all steps have successfully completed.
3915 * If any of the steps return a promise that is rejected or a boolean false, this promise is rejected
3916 * and any remaining steps are not performed.
3917 */
3918 OO.ui.Process.prototype.execute = function () {
3919 var i, len, promise;
3920
3921 /**
3922 * Continue execution.
3923 *
3924 * @ignore
3925 * @param {Array} step A function and the context it should be called in
3926 * @return {Function} Function that continues the process
3927 */
3928 function proceed( step ) {
3929 return function () {
3930 // Execute step in the correct context
3931 var deferred,
3932 result = step.callback.call( step.context );
3933
3934 if ( result === false ) {
3935 // Use rejected promise for boolean false results
3936 return $.Deferred().reject( [] ).promise();
3937 }
3938 if ( typeof result === 'number' ) {
3939 if ( result < 0 ) {
3940 throw new Error( 'Cannot go back in time: flux capacitor is out of service' );
3941 }
3942 // Use a delayed promise for numbers, expecting them to be in milliseconds
3943 deferred = $.Deferred();
3944 setTimeout( deferred.resolve, result );
3945 return deferred.promise();
3946 }
3947 if ( result instanceof OO.ui.Error ) {
3948 // Use rejected promise for error
3949 return $.Deferred().reject( [ result ] ).promise();
3950 }
3951 if ( Array.isArray( result ) && result.length && result[ 0 ] instanceof OO.ui.Error ) {
3952 // Use rejected promise for list of errors
3953 return $.Deferred().reject( result ).promise();
3954 }
3955 // Duck-type the object to see if it can produce a promise
3956 if ( result && $.isFunction( result.promise ) ) {
3957 // Use a promise generated from the result
3958 return result.promise();
3959 }
3960 // Use resolved promise for other results
3961 return $.Deferred().resolve().promise();
3962 };
3963 }
3964
3965 if ( this.steps.length ) {
3966 // Generate a chain reaction of promises
3967 promise = proceed( this.steps[ 0 ] )();
3968 for ( i = 1, len = this.steps.length; i < len; i++ ) {
3969 promise = promise.then( proceed( this.steps[ i ] ) );
3970 }
3971 } else {
3972 promise = $.Deferred().resolve().promise();
3973 }
3974
3975 return promise;
3976 };
3977
3978 /**
3979 * Create a process step.
3980 *
3981 * @private
3982 * @param {number|jQuery.Promise|Function} step
3983 *
3984 * - Number of milliseconds to wait before proceeding
3985 * - Promise that must be resolved before proceeding
3986 * - Function to execute
3987 * - If the function returns a boolean false the process will stop
3988 * - If the function returns a promise, the process will continue to the next
3989 * step when the promise is resolved or stop if the promise is rejected
3990 * - If the function returns a number, the process will wait for that number of
3991 * milliseconds before proceeding
3992 * @param {Object} [context=null] Execution context of the function. The context is
3993 * ignored if the step is a number or promise.
3994 * @return {Object} Step object, with `callback` and `context` properties
3995 */
3996 OO.ui.Process.prototype.createStep = function ( step, context ) {
3997 if ( typeof step === 'number' || $.isFunction( step.promise ) ) {
3998 return {
3999 callback: function () {
4000 return step;
4001 },
4002 context: null
4003 };
4004 }
4005 if ( $.isFunction( step ) ) {
4006 return {
4007 callback: step,
4008 context: context
4009 };
4010 }
4011 throw new Error( 'Cannot create process step: number, promise or function expected' );
4012 };
4013
4014 /**
4015 * Add step to the beginning of the process.
4016 *
4017 * @inheritdoc #createStep
4018 * @return {OO.ui.Process} this
4019 * @chainable
4020 */
4021 OO.ui.Process.prototype.first = function ( step, context ) {
4022 this.steps.unshift( this.createStep( step, context ) );
4023 return this;
4024 };
4025
4026 /**
4027 * Add step to the end of the process.
4028 *
4029 * @inheritdoc #createStep
4030 * @return {OO.ui.Process} this
4031 * @chainable
4032 */
4033 OO.ui.Process.prototype.next = function ( step, context ) {
4034 this.steps.push( this.createStep( step, context ) );
4035 return this;
4036 };
4037
4038 /**
4039 * A ToolFactory creates tools on demand. All tools ({@link OO.ui.Tool Tools}, {@link OO.ui.PopupTool PopupTools},
4040 * and {@link OO.ui.ToolGroupTool ToolGroupTools}) must be registered with a tool factory. Tools are
4041 * registered by their symbolic name. See {@link OO.ui.Toolbar toolbars} for an example.
4042 *
4043 * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki][1].
4044 *
4045 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
4046 *
4047 * @class
4048 * @extends OO.Factory
4049 * @constructor
4050 */
4051 OO.ui.ToolFactory = function OoUiToolFactory() {
4052 // Parent constructor
4053 OO.ui.ToolFactory.parent.call( this );
4054 };
4055
4056 /* Setup */
4057
4058 OO.inheritClass( OO.ui.ToolFactory, OO.Factory );
4059
4060 /* Methods */
4061
4062 /**
4063 * Get tools from the factory
4064 *
4065 * @param {Array} include Included tools
4066 * @param {Array} exclude Excluded tools
4067 * @param {Array} promote Promoted tools
4068 * @param {Array} demote Demoted tools
4069 * @return {string[]} List of tools
4070 */
4071 OO.ui.ToolFactory.prototype.getTools = function ( include, exclude, promote, demote ) {
4072 var i, len, included, promoted, demoted,
4073 auto = [],
4074 used = {};
4075
4076 // Collect included and not excluded tools
4077 included = OO.simpleArrayDifference( this.extract( include ), this.extract( exclude ) );
4078
4079 // Promotion
4080 promoted = this.extract( promote, used );
4081 demoted = this.extract( demote, used );
4082
4083 // Auto
4084 for ( i = 0, len = included.length; i < len; i++ ) {
4085 if ( !used[ included[ i ] ] ) {
4086 auto.push( included[ i ] );
4087 }
4088 }
4089
4090 return promoted.concat( auto ).concat( demoted );
4091 };
4092
4093 /**
4094 * Get a flat list of names from a list of names or groups.
4095 *
4096 * Tools can be specified in the following ways:
4097 *
4098 * - A specific tool: `{ name: 'tool-name' }` or `'tool-name'`
4099 * - All tools in a group: `{ group: 'group-name' }`
4100 * - All tools: `'*'`
4101 *
4102 * @private
4103 * @param {Array|string} collection List of tools
4104 * @param {Object} [used] Object with names that should be skipped as properties; extracted
4105 * names will be added as properties
4106 * @return {string[]} List of extracted names
4107 */
4108 OO.ui.ToolFactory.prototype.extract = function ( collection, used ) {
4109 var i, len, item, name, tool,
4110 names = [];
4111
4112 if ( collection === '*' ) {
4113 for ( name in this.registry ) {
4114 tool = this.registry[ name ];
4115 if (
4116 // Only add tools by group name when auto-add is enabled
4117 tool.static.autoAddToCatchall &&
4118 // Exclude already used tools
4119 ( !used || !used[ name ] )
4120 ) {
4121 names.push( name );
4122 if ( used ) {
4123 used[ name ] = true;
4124 }
4125 }
4126 }
4127 } else if ( Array.isArray( collection ) ) {
4128 for ( i = 0, len = collection.length; i < len; i++ ) {
4129 item = collection[ i ];
4130 // Allow plain strings as shorthand for named tools
4131 if ( typeof item === 'string' ) {
4132 item = { name: item };
4133 }
4134 if ( OO.isPlainObject( item ) ) {
4135 if ( item.group ) {
4136 for ( name in this.registry ) {
4137 tool = this.registry[ name ];
4138 if (
4139 // Include tools with matching group
4140 tool.static.group === item.group &&
4141 // Only add tools by group name when auto-add is enabled
4142 tool.static.autoAddToGroup &&
4143 // Exclude already used tools
4144 ( !used || !used[ name ] )
4145 ) {
4146 names.push( name );
4147 if ( used ) {
4148 used[ name ] = true;
4149 }
4150 }
4151 }
4152 // Include tools with matching name and exclude already used tools
4153 } else if ( item.name && ( !used || !used[ item.name ] ) ) {
4154 names.push( item.name );
4155 if ( used ) {
4156 used[ item.name ] = true;
4157 }
4158 }
4159 }
4160 }
4161 }
4162 return names;
4163 };
4164
4165 /**
4166 * ToolGroupFactories create {@link OO.ui.ToolGroup toolgroups} on demand. The toolgroup classes must
4167 * specify a symbolic name and be registered with the factory. The following classes are registered by
4168 * default:
4169 *
4170 * - {@link OO.ui.BarToolGroup BarToolGroups} (‘bar’)
4171 * - {@link OO.ui.MenuToolGroup MenuToolGroups} (‘menu’)
4172 * - {@link OO.ui.ListToolGroup ListToolGroups} (‘list’)
4173 *
4174 * See {@link OO.ui.Toolbar toolbars} for an example.
4175 *
4176 * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki][1].
4177 *
4178 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
4179 * @class
4180 * @extends OO.Factory
4181 * @constructor
4182 */
4183 OO.ui.ToolGroupFactory = function OoUiToolGroupFactory() {
4184 var i, l, defaultClasses;
4185 // Parent constructor
4186 OO.Factory.call( this );
4187
4188 defaultClasses = this.constructor.static.getDefaultClasses();
4189
4190 // Register default toolgroups
4191 for ( i = 0, l = defaultClasses.length; i < l; i++ ) {
4192 this.register( defaultClasses[ i ] );
4193 }
4194 };
4195
4196 /* Setup */
4197
4198 OO.inheritClass( OO.ui.ToolGroupFactory, OO.Factory );
4199
4200 /* Static Methods */
4201
4202 /**
4203 * Get a default set of classes to be registered on construction.
4204 *
4205 * @return {Function[]} Default classes
4206 */
4207 OO.ui.ToolGroupFactory.static.getDefaultClasses = function () {
4208 return [
4209 OO.ui.BarToolGroup,
4210 OO.ui.ListToolGroup,
4211 OO.ui.MenuToolGroup
4212 ];
4213 };
4214
4215 /**
4216 * Theme logic.
4217 *
4218 * @abstract
4219 * @class
4220 *
4221 * @constructor
4222 * @param {Object} [config] Configuration options
4223 */
4224 OO.ui.Theme = function OoUiTheme( config ) {
4225 // Configuration initialization
4226 config = config || {};
4227 };
4228
4229 /* Setup */
4230
4231 OO.initClass( OO.ui.Theme );
4232
4233 /* Methods */
4234
4235 /**
4236 * Get a list of classes to be applied to a widget.
4237 *
4238 * The 'on' and 'off' lists combined MUST contain keys for all classes the theme adds or removes,
4239 * otherwise state transitions will not work properly.
4240 *
4241 * @param {OO.ui.Element} element Element for which to get classes
4242 * @return {Object.<string,string[]>} Categorized class names with `on` and `off` lists
4243 */
4244 OO.ui.Theme.prototype.getElementClasses = function ( /* element */ ) {
4245 return { on: [], off: [] };
4246 };
4247
4248 /**
4249 * Update CSS classes provided by the theme.
4250 *
4251 * For elements with theme logic hooks, this should be called any time there's a state change.
4252 *
4253 * @param {OO.ui.Element} element Element for which to update classes
4254 * @return {Object.<string,string[]>} Categorized class names with `on` and `off` lists
4255 */
4256 OO.ui.Theme.prototype.updateElementClasses = function ( element ) {
4257 var $elements = $( [] ),
4258 classes = this.getElementClasses( element );
4259
4260 if ( element.$icon ) {
4261 $elements = $elements.add( element.$icon );
4262 }
4263 if ( element.$indicator ) {
4264 $elements = $elements.add( element.$indicator );
4265 }
4266
4267 $elements
4268 .removeClass( classes.off.join( ' ' ) )
4269 .addClass( classes.on.join( ' ' ) );
4270 };
4271
4272 /**
4273 * The TabIndexedElement class is an attribute mixin used to add additional functionality to an
4274 * element created by another class. The mixin provides a ‘tabIndex’ property, which specifies the
4275 * order in which users will navigate through the focusable elements via the "tab" key.
4276 *
4277 * @example
4278 * // TabIndexedElement is mixed into the ButtonWidget class
4279 * // to provide a tabIndex property.
4280 * var button1 = new OO.ui.ButtonWidget( {
4281 * label: 'fourth',
4282 * tabIndex: 4
4283 * } );
4284 * var button2 = new OO.ui.ButtonWidget( {
4285 * label: 'second',
4286 * tabIndex: 2
4287 * } );
4288 * var button3 = new OO.ui.ButtonWidget( {
4289 * label: 'third',
4290 * tabIndex: 3
4291 * } );
4292 * var button4 = new OO.ui.ButtonWidget( {
4293 * label: 'first',
4294 * tabIndex: 1
4295 * } );
4296 * $( 'body' ).append( button1.$element, button2.$element, button3.$element, button4.$element );
4297 *
4298 * @abstract
4299 * @class
4300 *
4301 * @constructor
4302 * @param {Object} [config] Configuration options
4303 * @cfg {jQuery} [$tabIndexed] The element that should use the tabindex functionality. By default,
4304 * the functionality is applied to the element created by the class ($element). If a different element is specified, the tabindex
4305 * functionality will be applied to it instead.
4306 * @cfg {number|null} [tabIndex=0] Number that specifies the element’s position in the tab-navigation
4307 * order (e.g., 1 for the first focusable element). Use 0 to use the default navigation order; use -1
4308 * to remove the element from the tab-navigation flow.
4309 */
4310 OO.ui.mixin.TabIndexedElement = function OoUiMixinTabIndexedElement( config ) {
4311 // Configuration initialization
4312 config = $.extend( { tabIndex: 0 }, config );
4313
4314 // Properties
4315 this.$tabIndexed = null;
4316 this.tabIndex = null;
4317
4318 // Events
4319 this.connect( this, { disable: 'onTabIndexedElementDisable' } );
4320
4321 // Initialization
4322 this.setTabIndex( config.tabIndex );
4323 this.setTabIndexedElement( config.$tabIndexed || this.$element );
4324 };
4325
4326 /* Setup */
4327
4328 OO.initClass( OO.ui.mixin.TabIndexedElement );
4329
4330 /* Methods */
4331
4332 /**
4333 * Set the element that should use the tabindex functionality.
4334 *
4335 * This method is used to retarget a tabindex mixin so that its functionality applies
4336 * to the specified element. If an element is currently using the functionality, the mixin’s
4337 * effect on that element is removed before the new element is set up.
4338 *
4339 * @param {jQuery} $tabIndexed Element that should use the tabindex functionality
4340 * @chainable
4341 */
4342 OO.ui.mixin.TabIndexedElement.prototype.setTabIndexedElement = function ( $tabIndexed ) {
4343 var tabIndex = this.tabIndex;
4344 // Remove attributes from old $tabIndexed
4345 this.setTabIndex( null );
4346 // Force update of new $tabIndexed
4347 this.$tabIndexed = $tabIndexed;
4348 this.tabIndex = tabIndex;
4349 return this.updateTabIndex();
4350 };
4351
4352 /**
4353 * Set the value of the tabindex.
4354 *
4355 * @param {number|null} tabIndex Tabindex value, or `null` for no tabindex
4356 * @chainable
4357 */
4358 OO.ui.mixin.TabIndexedElement.prototype.setTabIndex = function ( tabIndex ) {
4359 tabIndex = typeof tabIndex === 'number' ? tabIndex : null;
4360
4361 if ( this.tabIndex !== tabIndex ) {
4362 this.tabIndex = tabIndex;
4363 this.updateTabIndex();
4364 }
4365
4366 return this;
4367 };
4368
4369 /**
4370 * Update the `tabindex` attribute, in case of changes to tab index or
4371 * disabled state.
4372 *
4373 * @private
4374 * @chainable
4375 */
4376 OO.ui.mixin.TabIndexedElement.prototype.updateTabIndex = function () {
4377 if ( this.$tabIndexed ) {
4378 if ( this.tabIndex !== null ) {
4379 // Do not index over disabled elements
4380 this.$tabIndexed.attr( {
4381 tabindex: this.isDisabled() ? -1 : this.tabIndex,
4382 // Support: ChromeVox and NVDA
4383 // These do not seem to inherit aria-disabled from parent elements
4384 'aria-disabled': this.isDisabled().toString()
4385 } );
4386 } else {
4387 this.$tabIndexed.removeAttr( 'tabindex aria-disabled' );
4388 }
4389 }
4390 return this;
4391 };
4392
4393 /**
4394 * Handle disable events.
4395 *
4396 * @private
4397 * @param {boolean} disabled Element is disabled
4398 */
4399 OO.ui.mixin.TabIndexedElement.prototype.onTabIndexedElementDisable = function () {
4400 this.updateTabIndex();
4401 };
4402
4403 /**
4404 * Get the value of the tabindex.
4405 *
4406 * @return {number|null} Tabindex value
4407 */
4408 OO.ui.mixin.TabIndexedElement.prototype.getTabIndex = function () {
4409 return this.tabIndex;
4410 };
4411
4412 /**
4413 * ButtonElement is often mixed into other classes to generate a button, which is a clickable
4414 * interface element that can be configured with access keys for accessibility.
4415 * See the [OOjs UI documentation on MediaWiki] [1] for examples.
4416 *
4417 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#Buttons
4418 * @abstract
4419 * @class
4420 *
4421 * @constructor
4422 * @param {Object} [config] Configuration options
4423 * @cfg {jQuery} [$button] The button element created by the class.
4424 * If this configuration is omitted, the button element will use a generated `<a>`.
4425 * @cfg {boolean} [framed=true] Render the button with a frame
4426 */
4427 OO.ui.mixin.ButtonElement = function OoUiMixinButtonElement( config ) {
4428 // Configuration initialization
4429 config = config || {};
4430
4431 // Properties
4432 this.$button = null;
4433 this.framed = null;
4434 this.active = false;
4435 this.onMouseUpHandler = this.onMouseUp.bind( this );
4436 this.onMouseDownHandler = this.onMouseDown.bind( this );
4437 this.onKeyDownHandler = this.onKeyDown.bind( this );
4438 this.onKeyUpHandler = this.onKeyUp.bind( this );
4439 this.onClickHandler = this.onClick.bind( this );
4440 this.onKeyPressHandler = this.onKeyPress.bind( this );
4441
4442 // Initialization
4443 this.$element.addClass( 'oo-ui-buttonElement' );
4444 this.toggleFramed( config.framed === undefined || config.framed );
4445 this.setButtonElement( config.$button || $( '<a>' ) );
4446 };
4447
4448 /* Setup */
4449
4450 OO.initClass( OO.ui.mixin.ButtonElement );
4451
4452 /* Static Properties */
4453
4454 /**
4455 * Cancel mouse down events.
4456 *
4457 * This property is usually set to `true` to prevent the focus from changing when the button is clicked.
4458 * Classes such as {@link OO.ui.mixin.DraggableElement DraggableElement} and {@link OO.ui.ButtonOptionWidget ButtonOptionWidget}
4459 * use a value of `false` so that dragging behavior is possible and mousedown events can be handled by a
4460 * parent widget.
4461 *
4462 * @static
4463 * @inheritable
4464 * @property {boolean}
4465 */
4466 OO.ui.mixin.ButtonElement.static.cancelButtonMouseDownEvents = true;
4467
4468 /* Events */
4469
4470 /**
4471 * A 'click' event is emitted when the button element is clicked.
4472 *
4473 * @event click
4474 */
4475
4476 /* Methods */
4477
4478 /**
4479 * Set the button element.
4480 *
4481 * This method is used to retarget a button mixin so that its functionality applies to
4482 * the specified button element instead of the one created by the class. If a button element
4483 * is already set, the method will remove the mixin’s effect on that element.
4484 *
4485 * @param {jQuery} $button Element to use as button
4486 */
4487 OO.ui.mixin.ButtonElement.prototype.setButtonElement = function ( $button ) {
4488 if ( this.$button ) {
4489 this.$button
4490 .removeClass( 'oo-ui-buttonElement-button' )
4491 .removeAttr( 'role accesskey' )
4492 .off( {
4493 mousedown: this.onMouseDownHandler,
4494 keydown: this.onKeyDownHandler,
4495 click: this.onClickHandler,
4496 keypress: this.onKeyPressHandler
4497 } );
4498 }
4499
4500 this.$button = $button
4501 .addClass( 'oo-ui-buttonElement-button' )
4502 .attr( { role: 'button' } )
4503 .on( {
4504 mousedown: this.onMouseDownHandler,
4505 keydown: this.onKeyDownHandler,
4506 click: this.onClickHandler,
4507 keypress: this.onKeyPressHandler
4508 } );
4509 };
4510
4511 /**
4512 * Handles mouse down events.
4513 *
4514 * @protected
4515 * @param {jQuery.Event} e Mouse down event
4516 */
4517 OO.ui.mixin.ButtonElement.prototype.onMouseDown = function ( e ) {
4518 if ( this.isDisabled() || e.which !== 1 ) {
4519 return;
4520 }
4521 this.$element.addClass( 'oo-ui-buttonElement-pressed' );
4522 // Run the mouseup handler no matter where the mouse is when the button is let go, so we can
4523 // reliably remove the pressed class
4524 OO.ui.addCaptureEventListener( this.getElementDocument(), 'mouseup', this.onMouseUpHandler );
4525 // Prevent change of focus unless specifically configured otherwise
4526 if ( this.constructor.static.cancelButtonMouseDownEvents ) {
4527 return false;
4528 }
4529 };
4530
4531 /**
4532 * Handles mouse up events.
4533 *
4534 * @protected
4535 * @param {jQuery.Event} e Mouse up event
4536 */
4537 OO.ui.mixin.ButtonElement.prototype.onMouseUp = function ( e ) {
4538 if ( this.isDisabled() || e.which !== 1 ) {
4539 return;
4540 }
4541 this.$element.removeClass( 'oo-ui-buttonElement-pressed' );
4542 // Stop listening for mouseup, since we only needed this once
4543 OO.ui.removeCaptureEventListener( this.getElementDocument(), 'mouseup', this.onMouseUpHandler );
4544 };
4545
4546 /**
4547 * Handles mouse click events.
4548 *
4549 * @protected
4550 * @param {jQuery.Event} e Mouse click event
4551 * @fires click
4552 */
4553 OO.ui.mixin.ButtonElement.prototype.onClick = function ( e ) {
4554 if ( !this.isDisabled() && e.which === 1 ) {
4555 if ( this.emit( 'click' ) ) {
4556 return false;
4557 }
4558 }
4559 };
4560
4561 /**
4562 * Handles key down events.
4563 *
4564 * @protected
4565 * @param {jQuery.Event} e Key down event
4566 */
4567 OO.ui.mixin.ButtonElement.prototype.onKeyDown = function ( e ) {
4568 if ( this.isDisabled() || ( e.which !== OO.ui.Keys.SPACE && e.which !== OO.ui.Keys.ENTER ) ) {
4569 return;
4570 }
4571 this.$element.addClass( 'oo-ui-buttonElement-pressed' );
4572 // Run the keyup handler no matter where the key is when the button is let go, so we can
4573 // reliably remove the pressed class
4574 OO.ui.addCaptureEventListener( this.getElementDocument(), 'keyup', this.onKeyUpHandler );
4575 };
4576
4577 /**
4578 * Handles key up events.
4579 *
4580 * @protected
4581 * @param {jQuery.Event} e Key up event
4582 */
4583 OO.ui.mixin.ButtonElement.prototype.onKeyUp = function ( e ) {
4584 if ( this.isDisabled() || ( e.which !== OO.ui.Keys.SPACE && e.which !== OO.ui.Keys.ENTER ) ) {
4585 return;
4586 }
4587 this.$element.removeClass( 'oo-ui-buttonElement-pressed' );
4588 // Stop listening for keyup, since we only needed this once
4589 OO.ui.removeCaptureEventListener( this.getElementDocument(), 'keyup', this.onKeyUpHandler );
4590 };
4591
4592 /**
4593 * Handles key press events.
4594 *
4595 * @protected
4596 * @param {jQuery.Event} e Key press event
4597 * @fires click
4598 */
4599 OO.ui.mixin.ButtonElement.prototype.onKeyPress = function ( e ) {
4600 if ( !this.isDisabled() && ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER ) ) {
4601 if ( this.emit( 'click' ) ) {
4602 return false;
4603 }
4604 }
4605 };
4606
4607 /**
4608 * Check if button has a frame.
4609 *
4610 * @return {boolean} Button is framed
4611 */
4612 OO.ui.mixin.ButtonElement.prototype.isFramed = function () {
4613 return this.framed;
4614 };
4615
4616 /**
4617 * Render the button with or without a frame. Omit the `framed` parameter to toggle the button frame on and off.
4618 *
4619 * @param {boolean} [framed] Make button framed, omit to toggle
4620 * @chainable
4621 */
4622 OO.ui.mixin.ButtonElement.prototype.toggleFramed = function ( framed ) {
4623 framed = framed === undefined ? !this.framed : !!framed;
4624 if ( framed !== this.framed ) {
4625 this.framed = framed;
4626 this.$element
4627 .toggleClass( 'oo-ui-buttonElement-frameless', !framed )
4628 .toggleClass( 'oo-ui-buttonElement-framed', framed );
4629 this.updateThemeClasses();
4630 }
4631
4632 return this;
4633 };
4634
4635 /**
4636 * Set the button to its 'active' state.
4637 *
4638 * The active state occurs when a {@link OO.ui.ButtonOptionWidget ButtonOptionWidget} or
4639 * a {@link OO.ui.ToggleButtonWidget ToggleButtonWidget} is pressed. This method does nothing
4640 * for other button types.
4641 *
4642 * @param {boolean} [value] Make button active
4643 * @chainable
4644 */
4645 OO.ui.mixin.ButtonElement.prototype.setActive = function ( value ) {
4646 this.$element.toggleClass( 'oo-ui-buttonElement-active', !!value );
4647 return this;
4648 };
4649
4650 /**
4651 * Any OOjs UI widget that contains other widgets (such as {@link OO.ui.ButtonWidget buttons} or
4652 * {@link OO.ui.OptionWidget options}) mixes in GroupElement. Adding, removing, and clearing
4653 * items from the group is done through the interface the class provides.
4654 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
4655 *
4656 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Groups
4657 *
4658 * @abstract
4659 * @class
4660 *
4661 * @constructor
4662 * @param {Object} [config] Configuration options
4663 * @cfg {jQuery} [$group] The container element created by the class. If this configuration
4664 * is omitted, the group element will use a generated `<div>`.
4665 */
4666 OO.ui.mixin.GroupElement = function OoUiMixinGroupElement( config ) {
4667 // Configuration initialization
4668 config = config || {};
4669
4670 // Properties
4671 this.$group = null;
4672 this.items = [];
4673 this.aggregateItemEvents = {};
4674
4675 // Initialization
4676 this.setGroupElement( config.$group || $( '<div>' ) );
4677 };
4678
4679 /* Methods */
4680
4681 /**
4682 * Set the group element.
4683 *
4684 * If an element is already set, items will be moved to the new element.
4685 *
4686 * @param {jQuery} $group Element to use as group
4687 */
4688 OO.ui.mixin.GroupElement.prototype.setGroupElement = function ( $group ) {
4689 var i, len;
4690
4691 this.$group = $group;
4692 for ( i = 0, len = this.items.length; i < len; i++ ) {
4693 this.$group.append( this.items[ i ].$element );
4694 }
4695 };
4696
4697 /**
4698 * Check if a group contains no items.
4699 *
4700 * @return {boolean} Group is empty
4701 */
4702 OO.ui.mixin.GroupElement.prototype.isEmpty = function () {
4703 return !this.items.length;
4704 };
4705
4706 /**
4707 * Get all items in the group.
4708 *
4709 * The method returns an array of item references (e.g., [button1, button2, button3]) and is useful
4710 * when synchronizing groups of items, or whenever the references are required (e.g., when removing items
4711 * from a group).
4712 *
4713 * @return {OO.ui.Element[]} An array of items.
4714 */
4715 OO.ui.mixin.GroupElement.prototype.getItems = function () {
4716 return this.items.slice( 0 );
4717 };
4718
4719 /**
4720 * Get an item by its data.
4721 *
4722 * Only the first item with matching data will be returned. To return all matching items,
4723 * use the #getItemsFromData method.
4724 *
4725 * @param {Object} data Item data to search for
4726 * @return {OO.ui.Element|null} Item with equivalent data, `null` if none exists
4727 */
4728 OO.ui.mixin.GroupElement.prototype.getItemFromData = function ( data ) {
4729 var i, len, item,
4730 hash = OO.getHash( data );
4731
4732 for ( i = 0, len = this.items.length; i < len; i++ ) {
4733 item = this.items[ i ];
4734 if ( hash === OO.getHash( item.getData() ) ) {
4735 return item;
4736 }
4737 }
4738
4739 return null;
4740 };
4741
4742 /**
4743 * Get items by their data.
4744 *
4745 * All items with matching data will be returned. To return only the first match, use the #getItemFromData method instead.
4746 *
4747 * @param {Object} data Item data to search for
4748 * @return {OO.ui.Element[]} Items with equivalent data
4749 */
4750 OO.ui.mixin.GroupElement.prototype.getItemsFromData = function ( data ) {
4751 var i, len, item,
4752 hash = OO.getHash( data ),
4753 items = [];
4754
4755 for ( i = 0, len = this.items.length; i < len; i++ ) {
4756 item = this.items[ i ];
4757 if ( hash === OO.getHash( item.getData() ) ) {
4758 items.push( item );
4759 }
4760 }
4761
4762 return items;
4763 };
4764
4765 /**
4766 * Aggregate the events emitted by the group.
4767 *
4768 * When events are aggregated, the group will listen to all contained items for the event,
4769 * and then emit the event under a new name. The new event will contain an additional leading
4770 * parameter containing the item that emitted the original event. Other arguments emitted from
4771 * the original event are passed through.
4772 *
4773 * @param {Object.<string,string|null>} events An object keyed by the name of the event that should be
4774 * aggregated (e.g., ‘click’) and the value of the new name to use (e.g., ‘groupClick’).
4775 * A `null` value will remove aggregated events.
4776
4777 * @throws {Error} An error is thrown if aggregation already exists.
4778 */
4779 OO.ui.mixin.GroupElement.prototype.aggregate = function ( events ) {
4780 var i, len, item, add, remove, itemEvent, groupEvent;
4781
4782 for ( itemEvent in events ) {
4783 groupEvent = events[ itemEvent ];
4784
4785 // Remove existing aggregated event
4786 if ( Object.prototype.hasOwnProperty.call( this.aggregateItemEvents, itemEvent ) ) {
4787 // Don't allow duplicate aggregations
4788 if ( groupEvent ) {
4789 throw new Error( 'Duplicate item event aggregation for ' + itemEvent );
4790 }
4791 // Remove event aggregation from existing items
4792 for ( i = 0, len = this.items.length; i < len; i++ ) {
4793 item = this.items[ i ];
4794 if ( item.connect && item.disconnect ) {
4795 remove = {};
4796 remove[ itemEvent ] = [ 'emit', this.aggregateItemEvents[ itemEvent ], item ];
4797 item.disconnect( this, remove );
4798 }
4799 }
4800 // Prevent future items from aggregating event
4801 delete this.aggregateItemEvents[ itemEvent ];
4802 }
4803
4804 // Add new aggregate event
4805 if ( groupEvent ) {
4806 // Make future items aggregate event
4807 this.aggregateItemEvents[ itemEvent ] = groupEvent;
4808 // Add event aggregation to existing items
4809 for ( i = 0, len = this.items.length; i < len; i++ ) {
4810 item = this.items[ i ];
4811 if ( item.connect && item.disconnect ) {
4812 add = {};
4813 add[ itemEvent ] = [ 'emit', groupEvent, item ];
4814 item.connect( this, add );
4815 }
4816 }
4817 }
4818 }
4819 };
4820
4821 /**
4822 * Add items to the group.
4823 *
4824 * Items will be added to the end of the group array unless the optional `index` parameter specifies
4825 * a different insertion point. Adding an existing item will move it to the end of the array or the point specified by the `index`.
4826 *
4827 * @param {OO.ui.Element[]} items An array of items to add to the group
4828 * @param {number} [index] Index of the insertion point
4829 * @chainable
4830 */
4831 OO.ui.mixin.GroupElement.prototype.addItems = function ( items, index ) {
4832 var i, len, item, event, events, currentIndex,
4833 itemElements = [];
4834
4835 for ( i = 0, len = items.length; i < len; i++ ) {
4836 item = items[ i ];
4837
4838 // Check if item exists then remove it first, effectively "moving" it
4839 currentIndex = this.items.indexOf( item );
4840 if ( currentIndex >= 0 ) {
4841 this.removeItems( [ item ] );
4842 // Adjust index to compensate for removal
4843 if ( currentIndex < index ) {
4844 index--;
4845 }
4846 }
4847 // Add the item
4848 if ( item.connect && item.disconnect && !$.isEmptyObject( this.aggregateItemEvents ) ) {
4849 events = {};
4850 for ( event in this.aggregateItemEvents ) {
4851 events[ event ] = [ 'emit', this.aggregateItemEvents[ event ], item ];
4852 }
4853 item.connect( this, events );
4854 }
4855 item.setElementGroup( this );
4856 itemElements.push( item.$element.get( 0 ) );
4857 }
4858
4859 if ( index === undefined || index < 0 || index >= this.items.length ) {
4860 this.$group.append( itemElements );
4861 this.items.push.apply( this.items, items );
4862 } else if ( index === 0 ) {
4863 this.$group.prepend( itemElements );
4864 this.items.unshift.apply( this.items, items );
4865 } else {
4866 this.items[ index ].$element.before( itemElements );
4867 this.items.splice.apply( this.items, [ index, 0 ].concat( items ) );
4868 }
4869
4870 return this;
4871 };
4872
4873 /**
4874 * Remove the specified items from a group.
4875 *
4876 * Removed items are detached (not removed) from the DOM so that they may be reused.
4877 * To remove all items from a group, you may wish to use the #clearItems method instead.
4878 *
4879 * @param {OO.ui.Element[]} items An array of items to remove
4880 * @chainable
4881 */
4882 OO.ui.mixin.GroupElement.prototype.removeItems = function ( items ) {
4883 var i, len, item, index, remove, itemEvent;
4884
4885 // Remove specific items
4886 for ( i = 0, len = items.length; i < len; i++ ) {
4887 item = items[ i ];
4888 index = this.items.indexOf( item );
4889 if ( index !== -1 ) {
4890 if (
4891 item.connect && item.disconnect &&
4892 !$.isEmptyObject( this.aggregateItemEvents )
4893 ) {
4894 remove = {};
4895 if ( Object.prototype.hasOwnProperty.call( this.aggregateItemEvents, itemEvent ) ) {
4896 remove[ itemEvent ] = [ 'emit', this.aggregateItemEvents[ itemEvent ], item ];
4897 }
4898 item.disconnect( this, remove );
4899 }
4900 item.setElementGroup( null );
4901 this.items.splice( index, 1 );
4902 item.$element.detach();
4903 }
4904 }
4905
4906 return this;
4907 };
4908
4909 /**
4910 * Clear all items from the group.
4911 *
4912 * Cleared items are detached from the DOM, not removed, so that they may be reused.
4913 * To remove only a subset of items from a group, use the #removeItems method.
4914 *
4915 * @chainable
4916 */
4917 OO.ui.mixin.GroupElement.prototype.clearItems = function () {
4918 var i, len, item, remove, itemEvent;
4919
4920 // Remove all items
4921 for ( i = 0, len = this.items.length; i < len; i++ ) {
4922 item = this.items[ i ];
4923 if (
4924 item.connect && item.disconnect &&
4925 !$.isEmptyObject( this.aggregateItemEvents )
4926 ) {
4927 remove = {};
4928 if ( Object.prototype.hasOwnProperty.call( this.aggregateItemEvents, itemEvent ) ) {
4929 remove[ itemEvent ] = [ 'emit', this.aggregateItemEvents[ itemEvent ], item ];
4930 }
4931 item.disconnect( this, remove );
4932 }
4933 item.setElementGroup( null );
4934 item.$element.detach();
4935 }
4936
4937 this.items = [];
4938 return this;
4939 };
4940
4941 /**
4942 * DraggableElement is a mixin class used to create elements that can be clicked
4943 * and dragged by a mouse to a new position within a group. This class must be used
4944 * in conjunction with OO.ui.mixin.DraggableGroupElement, which provides a container for
4945 * the draggable elements.
4946 *
4947 * @abstract
4948 * @class
4949 *
4950 * @constructor
4951 */
4952 OO.ui.mixin.DraggableElement = function OoUiMixinDraggableElement() {
4953 // Properties
4954 this.index = null;
4955
4956 // Initialize and events
4957 this.$element
4958 .attr( 'draggable', true )
4959 .addClass( 'oo-ui-draggableElement' )
4960 .on( {
4961 dragstart: this.onDragStart.bind( this ),
4962 dragover: this.onDragOver.bind( this ),
4963 dragend: this.onDragEnd.bind( this ),
4964 drop: this.onDrop.bind( this )
4965 } );
4966 };
4967
4968 OO.initClass( OO.ui.mixin.DraggableElement );
4969
4970 /* Events */
4971
4972 /**
4973 * @event dragstart
4974 *
4975 * A dragstart event is emitted when the user clicks and begins dragging an item.
4976 * @param {OO.ui.mixin.DraggableElement} item The item the user has clicked and is dragging with the mouse.
4977 */
4978
4979 /**
4980 * @event dragend
4981 * A dragend event is emitted when the user drags an item and releases the mouse,
4982 * thus terminating the drag operation.
4983 */
4984
4985 /**
4986 * @event drop
4987 * A drop event is emitted when the user drags an item and then releases the mouse button
4988 * over a valid target.
4989 */
4990
4991 /* Static Properties */
4992
4993 /**
4994 * @inheritdoc OO.ui.mixin.ButtonElement
4995 */
4996 OO.ui.mixin.DraggableElement.static.cancelButtonMouseDownEvents = false;
4997
4998 /* Methods */
4999
5000 /**
5001 * Respond to dragstart event.
5002 *
5003 * @private
5004 * @param {jQuery.Event} event jQuery event
5005 * @fires dragstart
5006 */
5007 OO.ui.mixin.DraggableElement.prototype.onDragStart = function ( e ) {
5008 var dataTransfer = e.originalEvent.dataTransfer;
5009 // Define drop effect
5010 dataTransfer.dropEffect = 'none';
5011 dataTransfer.effectAllowed = 'move';
5012 // Support: Firefox
5013 // We must set up a dataTransfer data property or Firefox seems to
5014 // ignore the fact the element is draggable.
5015 try {
5016 dataTransfer.setData( 'application-x/OOjs-UI-draggable', this.getIndex() );
5017 } catch ( err ) {
5018 // The above is only for Firefox. Move on if it fails.
5019 }
5020 // Add dragging class
5021 this.$element.addClass( 'oo-ui-draggableElement-dragging' );
5022 // Emit event
5023 this.emit( 'dragstart', this );
5024 return true;
5025 };
5026
5027 /**
5028 * Respond to dragend event.
5029 *
5030 * @private
5031 * @fires dragend
5032 */
5033 OO.ui.mixin.DraggableElement.prototype.onDragEnd = function () {
5034 this.$element.removeClass( 'oo-ui-draggableElement-dragging' );
5035 this.emit( 'dragend' );
5036 };
5037
5038 /**
5039 * Handle drop event.
5040 *
5041 * @private
5042 * @param {jQuery.Event} event jQuery event
5043 * @fires drop
5044 */
5045 OO.ui.mixin.DraggableElement.prototype.onDrop = function ( e ) {
5046 e.preventDefault();
5047 this.emit( 'drop', e );
5048 };
5049
5050 /**
5051 * In order for drag/drop to work, the dragover event must
5052 * return false and stop propogation.
5053 *
5054 * @private
5055 */
5056 OO.ui.mixin.DraggableElement.prototype.onDragOver = function ( e ) {
5057 e.preventDefault();
5058 };
5059
5060 /**
5061 * Set item index.
5062 * Store it in the DOM so we can access from the widget drag event
5063 *
5064 * @private
5065 * @param {number} Item index
5066 */
5067 OO.ui.mixin.DraggableElement.prototype.setIndex = function ( index ) {
5068 if ( this.index !== index ) {
5069 this.index = index;
5070 this.$element.data( 'index', index );
5071 }
5072 };
5073
5074 /**
5075 * Get item index
5076 *
5077 * @private
5078 * @return {number} Item index
5079 */
5080 OO.ui.mixin.DraggableElement.prototype.getIndex = function () {
5081 return this.index;
5082 };
5083
5084 /**
5085 * DraggableGroupElement is a mixin class used to create a group element to
5086 * contain draggable elements, which are items that can be clicked and dragged by a mouse.
5087 * The class is used with OO.ui.mixin.DraggableElement.
5088 *
5089 * @abstract
5090 * @class
5091 * @mixins OO.ui.mixin.GroupElement
5092 *
5093 * @constructor
5094 * @param {Object} [config] Configuration options
5095 * @cfg {string} [orientation] Item orientation: 'horizontal' or 'vertical'. The orientation
5096 * should match the layout of the items. Items displayed in a single row
5097 * or in several rows should use horizontal orientation. The vertical orientation should only be
5098 * used when the items are displayed in a single column. Defaults to 'vertical'
5099 */
5100 OO.ui.mixin.DraggableGroupElement = function OoUiMixinDraggableGroupElement( config ) {
5101 // Configuration initialization
5102 config = config || {};
5103
5104 // Parent constructor
5105 OO.ui.mixin.GroupElement.call( this, config );
5106
5107 // Properties
5108 this.orientation = config.orientation || 'vertical';
5109 this.dragItem = null;
5110 this.itemDragOver = null;
5111 this.itemKeys = {};
5112 this.sideInsertion = '';
5113
5114 // Events
5115 this.aggregate( {
5116 dragstart: 'itemDragStart',
5117 dragend: 'itemDragEnd',
5118 drop: 'itemDrop'
5119 } );
5120 this.connect( this, {
5121 itemDragStart: 'onItemDragStart',
5122 itemDrop: 'onItemDrop',
5123 itemDragEnd: 'onItemDragEnd'
5124 } );
5125 this.$element.on( {
5126 dragover: this.onDragOver.bind( this ),
5127 dragleave: this.onDragLeave.bind( this )
5128 } );
5129
5130 // Initialize
5131 if ( Array.isArray( config.items ) ) {
5132 this.addItems( config.items );
5133 }
5134 this.$placeholder = $( '<div>' )
5135 .addClass( 'oo-ui-draggableGroupElement-placeholder' );
5136 this.$element
5137 .addClass( 'oo-ui-draggableGroupElement' )
5138 .append( this.$status )
5139 .toggleClass( 'oo-ui-draggableGroupElement-horizontal', this.orientation === 'horizontal' )
5140 .prepend( this.$placeholder );
5141 };
5142
5143 /* Setup */
5144 OO.mixinClass( OO.ui.mixin.DraggableGroupElement, OO.ui.mixin.GroupElement );
5145
5146 /* Events */
5147
5148 /**
5149 * A 'reorder' event is emitted when the order of items in the group changes.
5150 *
5151 * @event reorder
5152 * @param {OO.ui.mixin.DraggableElement} item Reordered item
5153 * @param {number} [newIndex] New index for the item
5154 */
5155
5156 /* Methods */
5157
5158 /**
5159 * Respond to item drag start event
5160 *
5161 * @private
5162 * @param {OO.ui.mixin.DraggableElement} item Dragged item
5163 */
5164 OO.ui.mixin.DraggableGroupElement.prototype.onItemDragStart = function ( item ) {
5165 var i, len;
5166
5167 // Map the index of each object
5168 for ( i = 0, len = this.items.length; i < len; i++ ) {
5169 this.items[ i ].setIndex( i );
5170 }
5171
5172 if ( this.orientation === 'horizontal' ) {
5173 // Set the height of the indicator
5174 this.$placeholder.css( {
5175 height: item.$element.outerHeight(),
5176 width: 2
5177 } );
5178 } else {
5179 // Set the width of the indicator
5180 this.$placeholder.css( {
5181 height: 2,
5182 width: item.$element.outerWidth()
5183 } );
5184 }
5185 this.setDragItem( item );
5186 };
5187
5188 /**
5189 * Respond to item drag end event
5190 *
5191 * @private
5192 */
5193 OO.ui.mixin.DraggableGroupElement.prototype.onItemDragEnd = function () {
5194 this.unsetDragItem();
5195 return false;
5196 };
5197
5198 /**
5199 * Handle drop event and switch the order of the items accordingly
5200 *
5201 * @private
5202 * @param {OO.ui.mixin.DraggableElement} item Dropped item
5203 * @fires reorder
5204 */
5205 OO.ui.mixin.DraggableGroupElement.prototype.onItemDrop = function ( item ) {
5206 var toIndex = item.getIndex();
5207 // Check if the dropped item is from the current group
5208 // TODO: Figure out a way to configure a list of legally droppable
5209 // elements even if they are not yet in the list
5210 if ( this.getDragItem() ) {
5211 // If the insertion point is 'after', the insertion index
5212 // is shifted to the right (or to the left in RTL, hence 'after')
5213 if ( this.sideInsertion === 'after' ) {
5214 toIndex++;
5215 }
5216 // Emit change event
5217 this.emit( 'reorder', this.getDragItem(), toIndex );
5218 }
5219 this.unsetDragItem();
5220 // Return false to prevent propogation
5221 return false;
5222 };
5223
5224 /**
5225 * Handle dragleave event.
5226 *
5227 * @private
5228 */
5229 OO.ui.mixin.DraggableGroupElement.prototype.onDragLeave = function () {
5230 // This means the item was dragged outside the widget
5231 this.$placeholder
5232 .css( 'left', 0 )
5233 .addClass( 'oo-ui-element-hidden' );
5234 };
5235
5236 /**
5237 * Respond to dragover event
5238 *
5239 * @private
5240 * @param {jQuery.Event} event Event details
5241 */
5242 OO.ui.mixin.DraggableGroupElement.prototype.onDragOver = function ( e ) {
5243 var dragOverObj, $optionWidget, itemOffset, itemMidpoint, itemBoundingRect,
5244 itemSize, cssOutput, dragPosition, itemIndex, itemPosition,
5245 clientX = e.originalEvent.clientX,
5246 clientY = e.originalEvent.clientY;
5247
5248 // Get the OptionWidget item we are dragging over
5249 dragOverObj = this.getElementDocument().elementFromPoint( clientX, clientY );
5250 $optionWidget = $( dragOverObj ).closest( '.oo-ui-draggableElement' );
5251 if ( $optionWidget[ 0 ] ) {
5252 itemOffset = $optionWidget.offset();
5253 itemBoundingRect = $optionWidget[ 0 ].getBoundingClientRect();
5254 itemPosition = $optionWidget.position();
5255 itemIndex = $optionWidget.data( 'index' );
5256 }
5257
5258 if (
5259 itemOffset &&
5260 this.isDragging() &&
5261 itemIndex !== this.getDragItem().getIndex()
5262 ) {
5263 if ( this.orientation === 'horizontal' ) {
5264 // Calculate where the mouse is relative to the item width
5265 itemSize = itemBoundingRect.width;
5266 itemMidpoint = itemBoundingRect.left + itemSize / 2;
5267 dragPosition = clientX;
5268 // Which side of the item we hover over will dictate
5269 // where the placeholder will appear, on the left or
5270 // on the right
5271 cssOutput = {
5272 left: dragPosition < itemMidpoint ? itemPosition.left : itemPosition.left + itemSize,
5273 top: itemPosition.top
5274 };
5275 } else {
5276 // Calculate where the mouse is relative to the item height
5277 itemSize = itemBoundingRect.height;
5278 itemMidpoint = itemBoundingRect.top + itemSize / 2;
5279 dragPosition = clientY;
5280 // Which side of the item we hover over will dictate
5281 // where the placeholder will appear, on the top or
5282 // on the bottom
5283 cssOutput = {
5284 top: dragPosition < itemMidpoint ? itemPosition.top : itemPosition.top + itemSize,
5285 left: itemPosition.left
5286 };
5287 }
5288 // Store whether we are before or after an item to rearrange
5289 // For horizontal layout, we need to account for RTL, as this is flipped
5290 if ( this.orientation === 'horizontal' && this.$element.css( 'direction' ) === 'rtl' ) {
5291 this.sideInsertion = dragPosition < itemMidpoint ? 'after' : 'before';
5292 } else {
5293 this.sideInsertion = dragPosition < itemMidpoint ? 'before' : 'after';
5294 }
5295 // Add drop indicator between objects
5296 this.$placeholder
5297 .css( cssOutput )
5298 .removeClass( 'oo-ui-element-hidden' );
5299 } else {
5300 // This means the item was dragged outside the widget
5301 this.$placeholder
5302 .css( 'left', 0 )
5303 .addClass( 'oo-ui-element-hidden' );
5304 }
5305 // Prevent default
5306 e.preventDefault();
5307 };
5308
5309 /**
5310 * Set a dragged item
5311 *
5312 * @param {OO.ui.mixin.DraggableElement} item Dragged item
5313 */
5314 OO.ui.mixin.DraggableGroupElement.prototype.setDragItem = function ( item ) {
5315 this.dragItem = item;
5316 };
5317
5318 /**
5319 * Unset the current dragged item
5320 */
5321 OO.ui.mixin.DraggableGroupElement.prototype.unsetDragItem = function () {
5322 this.dragItem = null;
5323 this.itemDragOver = null;
5324 this.$placeholder.addClass( 'oo-ui-element-hidden' );
5325 this.sideInsertion = '';
5326 };
5327
5328 /**
5329 * Get the item that is currently being dragged.
5330 *
5331 * @return {OO.ui.mixin.DraggableElement|null} The currently dragged item, or `null` if no item is being dragged
5332 */
5333 OO.ui.mixin.DraggableGroupElement.prototype.getDragItem = function () {
5334 return this.dragItem;
5335 };
5336
5337 /**
5338 * Check if an item in the group is currently being dragged.
5339 *
5340 * @return {Boolean} Item is being dragged
5341 */
5342 OO.ui.mixin.DraggableGroupElement.prototype.isDragging = function () {
5343 return this.getDragItem() !== null;
5344 };
5345
5346 /**
5347 * IconElement is often mixed into other classes to generate an icon.
5348 * Icons are graphics, about the size of normal text. They are used to aid the user
5349 * in locating a control or to convey information in a space-efficient way. See the
5350 * [OOjs UI documentation on MediaWiki] [1] for a list of icons
5351 * included in the library.
5352 *
5353 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
5354 *
5355 * @abstract
5356 * @class
5357 *
5358 * @constructor
5359 * @param {Object} [config] Configuration options
5360 * @cfg {jQuery} [$icon] The icon element created by the class. If this configuration is omitted,
5361 * the icon element will use a generated `<span>`. To use a different HTML tag, or to specify that
5362 * the icon element be set to an existing icon instead of the one generated by this class, set a
5363 * value using a jQuery selection. For example:
5364 *
5365 * // Use a <div> tag instead of a <span>
5366 * $icon: $("<div>")
5367 * // Use an existing icon element instead of the one generated by the class
5368 * $icon: this.$element
5369 * // Use an icon element from a child widget
5370 * $icon: this.childwidget.$element
5371 * @cfg {Object|string} [icon=''] The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of
5372 * symbolic names. A map is used for i18n purposes and contains a `default` icon
5373 * name and additional names keyed by language code. The `default` name is used when no icon is keyed
5374 * by the user's language.
5375 *
5376 * Example of an i18n map:
5377 *
5378 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
5379 * See the [OOjs UI documentation on MediaWiki] [2] for a list of icons included in the library.
5380 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
5381 * @cfg {string|Function} [iconTitle] A text string used as the icon title, or a function that returns title
5382 * text. The icon title is displayed when users move the mouse over the icon.
5383 */
5384 OO.ui.mixin.IconElement = function OoUiMixinIconElement( config ) {
5385 // Configuration initialization
5386 config = config || {};
5387
5388 // Properties
5389 this.$icon = null;
5390 this.icon = null;
5391 this.iconTitle = null;
5392
5393 // Initialization
5394 this.setIcon( config.icon || this.constructor.static.icon );
5395 this.setIconTitle( config.iconTitle || this.constructor.static.iconTitle );
5396 this.setIconElement( config.$icon || $( '<span>' ) );
5397 };
5398
5399 /* Setup */
5400
5401 OO.initClass( OO.ui.mixin.IconElement );
5402
5403 /* Static Properties */
5404
5405 /**
5406 * The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of symbolic names. A map is used
5407 * for i18n purposes and contains a `default` icon name and additional names keyed by
5408 * language code. The `default` name is used when no icon is keyed by the user's language.
5409 *
5410 * Example of an i18n map:
5411 *
5412 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
5413 *
5414 * Note: the static property will be overridden if the #icon configuration is used.
5415 *
5416 * @static
5417 * @inheritable
5418 * @property {Object|string}
5419 */
5420 OO.ui.mixin.IconElement.static.icon = null;
5421
5422 /**
5423 * The icon title, displayed when users move the mouse over the icon. The value can be text, a
5424 * function that returns title text, or `null` for no title.
5425 *
5426 * The static property will be overridden if the #iconTitle configuration is used.
5427 *
5428 * @static
5429 * @inheritable
5430 * @property {string|Function|null}
5431 */
5432 OO.ui.mixin.IconElement.static.iconTitle = null;
5433
5434 /* Methods */
5435
5436 /**
5437 * Set the icon element. This method is used to retarget an icon mixin so that its functionality
5438 * applies to the specified icon element instead of the one created by the class. If an icon
5439 * element is already set, the mixin’s effect on that element is removed. Generated CSS classes
5440 * and mixin methods will no longer affect the element.
5441 *
5442 * @param {jQuery} $icon Element to use as icon
5443 */
5444 OO.ui.mixin.IconElement.prototype.setIconElement = function ( $icon ) {
5445 if ( this.$icon ) {
5446 this.$icon
5447 .removeClass( 'oo-ui-iconElement-icon oo-ui-icon-' + this.icon )
5448 .removeAttr( 'title' );
5449 }
5450
5451 this.$icon = $icon
5452 .addClass( 'oo-ui-iconElement-icon' )
5453 .toggleClass( 'oo-ui-icon-' + this.icon, !!this.icon );
5454 if ( this.iconTitle !== null ) {
5455 this.$icon.attr( 'title', this.iconTitle );
5456 }
5457
5458 this.updateThemeClasses();
5459 };
5460
5461 /**
5462 * Set icon by symbolic name (e.g., ‘remove’ or ‘menu’). Use `null` to remove an icon.
5463 * The icon parameter can also be set to a map of icon names. See the #icon config setting
5464 * for an example.
5465 *
5466 * @param {Object|string|null} icon A symbolic icon name, a {@link #icon map of icon names} keyed
5467 * by language code, or `null` to remove the icon.
5468 * @chainable
5469 */
5470 OO.ui.mixin.IconElement.prototype.setIcon = function ( icon ) {
5471 icon = OO.isPlainObject( icon ) ? OO.ui.getLocalValue( icon, null, 'default' ) : icon;
5472 icon = typeof icon === 'string' && icon.trim().length ? icon.trim() : null;
5473
5474 if ( this.icon !== icon ) {
5475 if ( this.$icon ) {
5476 if ( this.icon !== null ) {
5477 this.$icon.removeClass( 'oo-ui-icon-' + this.icon );
5478 }
5479 if ( icon !== null ) {
5480 this.$icon.addClass( 'oo-ui-icon-' + icon );
5481 }
5482 }
5483 this.icon = icon;
5484 }
5485
5486 this.$element.toggleClass( 'oo-ui-iconElement', !!this.icon );
5487 this.updateThemeClasses();
5488
5489 return this;
5490 };
5491
5492 /**
5493 * Set the icon title. Use `null` to remove the title.
5494 *
5495 * @param {string|Function|null} iconTitle A text string used as the icon title,
5496 * a function that returns title text, or `null` for no title.
5497 * @chainable
5498 */
5499 OO.ui.mixin.IconElement.prototype.setIconTitle = function ( iconTitle ) {
5500 iconTitle = typeof iconTitle === 'function' ||
5501 ( typeof iconTitle === 'string' && iconTitle.length ) ?
5502 OO.ui.resolveMsg( iconTitle ) : null;
5503
5504 if ( this.iconTitle !== iconTitle ) {
5505 this.iconTitle = iconTitle;
5506 if ( this.$icon ) {
5507 if ( this.iconTitle !== null ) {
5508 this.$icon.attr( 'title', iconTitle );
5509 } else {
5510 this.$icon.removeAttr( 'title' );
5511 }
5512 }
5513 }
5514
5515 return this;
5516 };
5517
5518 /**
5519 * Get the symbolic name of the icon.
5520 *
5521 * @return {string} Icon name
5522 */
5523 OO.ui.mixin.IconElement.prototype.getIcon = function () {
5524 return this.icon;
5525 };
5526
5527 /**
5528 * Get the icon title. The title text is displayed when a user moves the mouse over the icon.
5529 *
5530 * @return {string} Icon title text
5531 */
5532 OO.ui.mixin.IconElement.prototype.getIconTitle = function () {
5533 return this.iconTitle;
5534 };
5535
5536 /**
5537 * IndicatorElement is often mixed into other classes to generate an indicator.
5538 * Indicators are small graphics that are generally used in two ways:
5539 *
5540 * - To draw attention to the status of an item. For example, an indicator might be
5541 * used to show that an item in a list has errors that need to be resolved.
5542 * - To clarify the function of a control that acts in an exceptional way (a button
5543 * that opens a menu instead of performing an action directly, for example).
5544 *
5545 * For a list of indicators included in the library, please see the
5546 * [OOjs UI documentation on MediaWiki] [1].
5547 *
5548 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
5549 *
5550 * @abstract
5551 * @class
5552 *
5553 * @constructor
5554 * @param {Object} [config] Configuration options
5555 * @cfg {jQuery} [$indicator] The indicator element created by the class. If this
5556 * configuration is omitted, the indicator element will use a generated `<span>`.
5557 * @cfg {string} [indicator] Symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
5558 * See the [OOjs UI documentation on MediaWiki][2] for a list of indicators included
5559 * in the library.
5560 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
5561 * @cfg {string|Function} [indicatorTitle] A text string used as the indicator title,
5562 * or a function that returns title text. The indicator title is displayed when users move
5563 * the mouse over the indicator.
5564 */
5565 OO.ui.mixin.IndicatorElement = function OoUiMixinIndicatorElement( config ) {
5566 // Configuration initialization
5567 config = config || {};
5568
5569 // Properties
5570 this.$indicator = null;
5571 this.indicator = null;
5572 this.indicatorTitle = null;
5573
5574 // Initialization
5575 this.setIndicator( config.indicator || this.constructor.static.indicator );
5576 this.setIndicatorTitle( config.indicatorTitle || this.constructor.static.indicatorTitle );
5577 this.setIndicatorElement( config.$indicator || $( '<span>' ) );
5578 };
5579
5580 /* Setup */
5581
5582 OO.initClass( OO.ui.mixin.IndicatorElement );
5583
5584 /* Static Properties */
5585
5586 /**
5587 * Symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
5588 * The static property will be overridden if the #indicator configuration is used.
5589 *
5590 * @static
5591 * @inheritable
5592 * @property {string|null}
5593 */
5594 OO.ui.mixin.IndicatorElement.static.indicator = null;
5595
5596 /**
5597 * A text string used as the indicator title, a function that returns title text, or `null`
5598 * for no title. The static property will be overridden if the #indicatorTitle configuration is used.
5599 *
5600 * @static
5601 * @inheritable
5602 * @property {string|Function|null}
5603 */
5604 OO.ui.mixin.IndicatorElement.static.indicatorTitle = null;
5605
5606 /* Methods */
5607
5608 /**
5609 * Set the indicator element.
5610 *
5611 * If an element is already set, it will be cleaned up before setting up the new element.
5612 *
5613 * @param {jQuery} $indicator Element to use as indicator
5614 */
5615 OO.ui.mixin.IndicatorElement.prototype.setIndicatorElement = function ( $indicator ) {
5616 if ( this.$indicator ) {
5617 this.$indicator
5618 .removeClass( 'oo-ui-indicatorElement-indicator oo-ui-indicator-' + this.indicator )
5619 .removeAttr( 'title' );
5620 }
5621
5622 this.$indicator = $indicator
5623 .addClass( 'oo-ui-indicatorElement-indicator' )
5624 .toggleClass( 'oo-ui-indicator-' + this.indicator, !!this.indicator );
5625 if ( this.indicatorTitle !== null ) {
5626 this.$indicator.attr( 'title', this.indicatorTitle );
5627 }
5628
5629 this.updateThemeClasses();
5630 };
5631
5632 /**
5633 * Set the indicator by its symbolic name: ‘alert’, ‘down’, ‘next’, ‘previous’, ‘required’, ‘up’. Use `null` to remove the indicator.
5634 *
5635 * @param {string|null} indicator Symbolic name of indicator, or `null` for no indicator
5636 * @chainable
5637 */
5638 OO.ui.mixin.IndicatorElement.prototype.setIndicator = function ( indicator ) {
5639 indicator = typeof indicator === 'string' && indicator.length ? indicator.trim() : null;
5640
5641 if ( this.indicator !== indicator ) {
5642 if ( this.$indicator ) {
5643 if ( this.indicator !== null ) {
5644 this.$indicator.removeClass( 'oo-ui-indicator-' + this.indicator );
5645 }
5646 if ( indicator !== null ) {
5647 this.$indicator.addClass( 'oo-ui-indicator-' + indicator );
5648 }
5649 }
5650 this.indicator = indicator;
5651 }
5652
5653 this.$element.toggleClass( 'oo-ui-indicatorElement', !!this.indicator );
5654 this.updateThemeClasses();
5655
5656 return this;
5657 };
5658
5659 /**
5660 * Set the indicator title.
5661 *
5662 * The title is displayed when a user moves the mouse over the indicator.
5663 *
5664 * @param {string|Function|null} indicator Indicator title text, a function that returns text, or
5665 * `null` for no indicator title
5666 * @chainable
5667 */
5668 OO.ui.mixin.IndicatorElement.prototype.setIndicatorTitle = function ( indicatorTitle ) {
5669 indicatorTitle = typeof indicatorTitle === 'function' ||
5670 ( typeof indicatorTitle === 'string' && indicatorTitle.length ) ?
5671 OO.ui.resolveMsg( indicatorTitle ) : null;
5672
5673 if ( this.indicatorTitle !== indicatorTitle ) {
5674 this.indicatorTitle = indicatorTitle;
5675 if ( this.$indicator ) {
5676 if ( this.indicatorTitle !== null ) {
5677 this.$indicator.attr( 'title', indicatorTitle );
5678 } else {
5679 this.$indicator.removeAttr( 'title' );
5680 }
5681 }
5682 }
5683
5684 return this;
5685 };
5686
5687 /**
5688 * Get the symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
5689 *
5690 * @return {string} Symbolic name of indicator
5691 */
5692 OO.ui.mixin.IndicatorElement.prototype.getIndicator = function () {
5693 return this.indicator;
5694 };
5695
5696 /**
5697 * Get the indicator title.
5698 *
5699 * The title is displayed when a user moves the mouse over the indicator.
5700 *
5701 * @return {string} Indicator title text
5702 */
5703 OO.ui.mixin.IndicatorElement.prototype.getIndicatorTitle = function () {
5704 return this.indicatorTitle;
5705 };
5706
5707 /**
5708 * LabelElement is often mixed into other classes to generate a label, which
5709 * helps identify the function of an interface element.
5710 * See the [OOjs UI documentation on MediaWiki] [1] for more information.
5711 *
5712 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Labels
5713 *
5714 * @abstract
5715 * @class
5716 *
5717 * @constructor
5718 * @param {Object} [config] Configuration options
5719 * @cfg {jQuery} [$label] The label element created by the class. If this
5720 * configuration is omitted, the label element will use a generated `<span>`.
5721 * @cfg {jQuery|string|Function|OO.ui.HtmlSnippet} [label] The label text. The label can be specified
5722 * as a plaintext string, a jQuery selection of elements, or a function that will produce a string
5723 * in the future. See the [OOjs UI documentation on MediaWiki] [2] for examples.
5724 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Labels
5725 * @cfg {boolean} [autoFitLabel=true] Fit the label to the width of the parent element.
5726 * The label will be truncated to fit if necessary.
5727 */
5728 OO.ui.mixin.LabelElement = function OoUiMixinLabelElement( config ) {
5729 // Configuration initialization
5730 config = config || {};
5731
5732 // Properties
5733 this.$label = null;
5734 this.label = null;
5735 this.autoFitLabel = config.autoFitLabel === undefined || !!config.autoFitLabel;
5736
5737 // Initialization
5738 this.setLabel( config.label || this.constructor.static.label );
5739 this.setLabelElement( config.$label || $( '<span>' ) );
5740 };
5741
5742 /* Setup */
5743
5744 OO.initClass( OO.ui.mixin.LabelElement );
5745
5746 /* Events */
5747
5748 /**
5749 * @event labelChange
5750 * @param {string} value
5751 */
5752
5753 /* Static Properties */
5754
5755 /**
5756 * The label text. The label can be specified as a plaintext string, a function that will
5757 * produce a string in the future, or `null` for no label. The static value will
5758 * be overridden if a label is specified with the #label config option.
5759 *
5760 * @static
5761 * @inheritable
5762 * @property {string|Function|null}
5763 */
5764 OO.ui.mixin.LabelElement.static.label = null;
5765
5766 /* Methods */
5767
5768 /**
5769 * Set the label element.
5770 *
5771 * If an element is already set, it will be cleaned up before setting up the new element.
5772 *
5773 * @param {jQuery} $label Element to use as label
5774 */
5775 OO.ui.mixin.LabelElement.prototype.setLabelElement = function ( $label ) {
5776 if ( this.$label ) {
5777 this.$label.removeClass( 'oo-ui-labelElement-label' ).empty();
5778 }
5779
5780 this.$label = $label.addClass( 'oo-ui-labelElement-label' );
5781 this.setLabelContent( this.label );
5782 };
5783
5784 /**
5785 * Set the label.
5786 *
5787 * An empty string will result in the label being hidden. A string containing only whitespace will
5788 * be converted to a single `&nbsp;`.
5789 *
5790 * @param {jQuery|string|OO.ui.HtmlSnippet|Function|null} label Label nodes; text; a function that returns nodes or
5791 * text; or null for no label
5792 * @chainable
5793 */
5794 OO.ui.mixin.LabelElement.prototype.setLabel = function ( label ) {
5795 label = typeof label === 'function' ? OO.ui.resolveMsg( label ) : label;
5796 label = ( ( typeof label === 'string' && label.length ) || label instanceof jQuery || label instanceof OO.ui.HtmlSnippet ) ? label : null;
5797
5798 this.$element.toggleClass( 'oo-ui-labelElement', !!label );
5799
5800 if ( this.label !== label ) {
5801 if ( this.$label ) {
5802 this.setLabelContent( label );
5803 }
5804 this.label = label;
5805 this.emit( 'labelChange' );
5806 }
5807
5808 return this;
5809 };
5810
5811 /**
5812 * Get the label.
5813 *
5814 * @return {jQuery|string|Function|null} Label nodes; text; a function that returns nodes or
5815 * text; or null for no label
5816 */
5817 OO.ui.mixin.LabelElement.prototype.getLabel = function () {
5818 return this.label;
5819 };
5820
5821 /**
5822 * Fit the label.
5823 *
5824 * @chainable
5825 */
5826 OO.ui.mixin.LabelElement.prototype.fitLabel = function () {
5827 if ( this.$label && this.$label.autoEllipsis && this.autoFitLabel ) {
5828 this.$label.autoEllipsis( { hasSpan: false, tooltip: true } );
5829 }
5830
5831 return this;
5832 };
5833
5834 /**
5835 * Set the content of the label.
5836 *
5837 * Do not call this method until after the label element has been set by #setLabelElement.
5838 *
5839 * @private
5840 * @param {jQuery|string|Function|null} label Label nodes; text; a function that returns nodes or
5841 * text; or null for no label
5842 */
5843 OO.ui.mixin.LabelElement.prototype.setLabelContent = function ( label ) {
5844 if ( typeof label === 'string' ) {
5845 if ( label.match( /^\s*$/ ) ) {
5846 // Convert whitespace only string to a single non-breaking space
5847 this.$label.html( '&nbsp;' );
5848 } else {
5849 this.$label.text( label );
5850 }
5851 } else if ( label instanceof OO.ui.HtmlSnippet ) {
5852 this.$label.html( label.toString() );
5853 } else if ( label instanceof jQuery ) {
5854 this.$label.empty().append( label );
5855 } else {
5856 this.$label.empty();
5857 }
5858 };
5859
5860 /**
5861 * LookupElement is a mixin that creates a {@link OO.ui.FloatingMenuSelectWidget menu} of suggested values for
5862 * a {@link OO.ui.TextInputWidget text input widget}. Suggested values are based on the characters the user types
5863 * into the text input field and, in general, the menu is only displayed when the user types. If a suggested value is chosen
5864 * from the lookup menu, that value becomes the value of the input field.
5865 *
5866 * Note that a new menu of suggested items is displayed when a value is chosen from the lookup menu. If this is
5867 * not the desired behavior, disable lookup menus with the #setLookupsDisabled method, then set the value, then
5868 * re-enable lookups.
5869 *
5870 * See the [OOjs UI demos][1] for an example.
5871 *
5872 * [1]: https://tools.wmflabs.org/oojs-ui/oojs-ui/demos/index.html#widgets-apex-vector-ltr
5873 *
5874 * @class
5875 * @abstract
5876 *
5877 * @constructor
5878 * @param {Object} [config] Configuration options
5879 * @cfg {jQuery} [$overlay] Overlay for the lookup menu; defaults to relative positioning
5880 * @cfg {jQuery} [$container=this.$element] The container element. The lookup menu is rendered beneath the specified element.
5881 * @cfg {boolean} [allowSuggestionsWhenEmpty=false] Request and display a lookup menu when the text input is empty.
5882 * By default, the lookup menu is not generated and displayed until the user begins to type.
5883 */
5884 OO.ui.mixin.LookupElement = function OoUiMixinLookupElement( config ) {
5885 // Configuration initialization
5886 config = config || {};
5887
5888 // Properties
5889 this.$overlay = config.$overlay || this.$element;
5890 this.lookupMenu = new OO.ui.FloatingMenuSelectWidget( {
5891 widget: this,
5892 input: this,
5893 $container: config.$container || this.$element
5894 } );
5895
5896 this.allowSuggestionsWhenEmpty = config.allowSuggestionsWhenEmpty || false;
5897
5898 this.lookupCache = {};
5899 this.lookupQuery = null;
5900 this.lookupRequest = null;
5901 this.lookupsDisabled = false;
5902 this.lookupInputFocused = false;
5903
5904 // Events
5905 this.$input.on( {
5906 focus: this.onLookupInputFocus.bind( this ),
5907 blur: this.onLookupInputBlur.bind( this ),
5908 mousedown: this.onLookupInputMouseDown.bind( this )
5909 } );
5910 this.connect( this, { change: 'onLookupInputChange' } );
5911 this.lookupMenu.connect( this, {
5912 toggle: 'onLookupMenuToggle',
5913 choose: 'onLookupMenuItemChoose'
5914 } );
5915
5916 // Initialization
5917 this.$element.addClass( 'oo-ui-lookupElement' );
5918 this.lookupMenu.$element.addClass( 'oo-ui-lookupElement-menu' );
5919 this.$overlay.append( this.lookupMenu.$element );
5920 };
5921
5922 /* Methods */
5923
5924 /**
5925 * Handle input focus event.
5926 *
5927 * @protected
5928 * @param {jQuery.Event} e Input focus event
5929 */
5930 OO.ui.mixin.LookupElement.prototype.onLookupInputFocus = function () {
5931 this.lookupInputFocused = true;
5932 this.populateLookupMenu();
5933 };
5934
5935 /**
5936 * Handle input blur event.
5937 *
5938 * @protected
5939 * @param {jQuery.Event} e Input blur event
5940 */
5941 OO.ui.mixin.LookupElement.prototype.onLookupInputBlur = function () {
5942 this.closeLookupMenu();
5943 this.lookupInputFocused = false;
5944 };
5945
5946 /**
5947 * Handle input mouse down event.
5948 *
5949 * @protected
5950 * @param {jQuery.Event} e Input mouse down event
5951 */
5952 OO.ui.mixin.LookupElement.prototype.onLookupInputMouseDown = function () {
5953 // Only open the menu if the input was already focused.
5954 // This way we allow the user to open the menu again after closing it with Esc
5955 // by clicking in the input. Opening (and populating) the menu when initially
5956 // clicking into the input is handled by the focus handler.
5957 if ( this.lookupInputFocused && !this.lookupMenu.isVisible() ) {
5958 this.populateLookupMenu();
5959 }
5960 };
5961
5962 /**
5963 * Handle input change event.
5964 *
5965 * @protected
5966 * @param {string} value New input value
5967 */
5968 OO.ui.mixin.LookupElement.prototype.onLookupInputChange = function () {
5969 if ( this.lookupInputFocused ) {
5970 this.populateLookupMenu();
5971 }
5972 };
5973
5974 /**
5975 * Handle the lookup menu being shown/hidden.
5976 *
5977 * @protected
5978 * @param {boolean} visible Whether the lookup menu is now visible.
5979 */
5980 OO.ui.mixin.LookupElement.prototype.onLookupMenuToggle = function ( visible ) {
5981 if ( !visible ) {
5982 // When the menu is hidden, abort any active request and clear the menu.
5983 // This has to be done here in addition to closeLookupMenu(), because
5984 // MenuSelectWidget will close itself when the user presses Esc.
5985 this.abortLookupRequest();
5986 this.lookupMenu.clearItems();
5987 }
5988 };
5989
5990 /**
5991 * Handle menu item 'choose' event, updating the text input value to the value of the clicked item.
5992 *
5993 * @protected
5994 * @param {OO.ui.MenuOptionWidget} item Selected item
5995 */
5996 OO.ui.mixin.LookupElement.prototype.onLookupMenuItemChoose = function ( item ) {
5997 this.setValue( item.getData() );
5998 };
5999
6000 /**
6001 * Get lookup menu.
6002 *
6003 * @private
6004 * @return {OO.ui.FloatingMenuSelectWidget}
6005 */
6006 OO.ui.mixin.LookupElement.prototype.getLookupMenu = function () {
6007 return this.lookupMenu;
6008 };
6009
6010 /**
6011 * Disable or re-enable lookups.
6012 *
6013 * When lookups are disabled, calls to #populateLookupMenu will be ignored.
6014 *
6015 * @param {boolean} disabled Disable lookups
6016 */
6017 OO.ui.mixin.LookupElement.prototype.setLookupsDisabled = function ( disabled ) {
6018 this.lookupsDisabled = !!disabled;
6019 };
6020
6021 /**
6022 * Open the menu. If there are no entries in the menu, this does nothing.
6023 *
6024 * @private
6025 * @chainable
6026 */
6027 OO.ui.mixin.LookupElement.prototype.openLookupMenu = function () {
6028 if ( !this.lookupMenu.isEmpty() ) {
6029 this.lookupMenu.toggle( true );
6030 }
6031 return this;
6032 };
6033
6034 /**
6035 * Close the menu, empty it, and abort any pending request.
6036 *
6037 * @private
6038 * @chainable
6039 */
6040 OO.ui.mixin.LookupElement.prototype.closeLookupMenu = function () {
6041 this.lookupMenu.toggle( false );
6042 this.abortLookupRequest();
6043 this.lookupMenu.clearItems();
6044 return this;
6045 };
6046
6047 /**
6048 * Request menu items based on the input's current value, and when they arrive,
6049 * populate the menu with these items and show the menu.
6050 *
6051 * If lookups have been disabled with #setLookupsDisabled, this function does nothing.
6052 *
6053 * @private
6054 * @chainable
6055 */
6056 OO.ui.mixin.LookupElement.prototype.populateLookupMenu = function () {
6057 var widget = this,
6058 value = this.getValue();
6059
6060 if ( this.lookupsDisabled || this.isReadOnly() ) {
6061 return;
6062 }
6063
6064 // If the input is empty, clear the menu, unless suggestions when empty are allowed.
6065 if ( !this.allowSuggestionsWhenEmpty && value === '' ) {
6066 this.closeLookupMenu();
6067 // Skip population if there is already a request pending for the current value
6068 } else if ( value !== this.lookupQuery ) {
6069 this.getLookupMenuItems()
6070 .done( function ( items ) {
6071 widget.lookupMenu.clearItems();
6072 if ( items.length ) {
6073 widget.lookupMenu
6074 .addItems( items )
6075 .toggle( true );
6076 widget.initializeLookupMenuSelection();
6077 } else {
6078 widget.lookupMenu.toggle( false );
6079 }
6080 } )
6081 .fail( function () {
6082 widget.lookupMenu.clearItems();
6083 } );
6084 }
6085
6086 return this;
6087 };
6088
6089 /**
6090 * Highlight the first selectable item in the menu.
6091 *
6092 * @private
6093 * @chainable
6094 */
6095 OO.ui.mixin.LookupElement.prototype.initializeLookupMenuSelection = function () {
6096 if ( !this.lookupMenu.getSelectedItem() ) {
6097 this.lookupMenu.highlightItem( this.lookupMenu.getFirstSelectableItem() );
6098 }
6099 };
6100
6101 /**
6102 * Get lookup menu items for the current query.
6103 *
6104 * @private
6105 * @return {jQuery.Promise} Promise object which will be passed menu items as the first argument of
6106 * the done event. If the request was aborted to make way for a subsequent request, this promise
6107 * will not be rejected: it will remain pending forever.
6108 */
6109 OO.ui.mixin.LookupElement.prototype.getLookupMenuItems = function () {
6110 var widget = this,
6111 value = this.getValue(),
6112 deferred = $.Deferred(),
6113 ourRequest;
6114
6115 this.abortLookupRequest();
6116 if ( Object.prototype.hasOwnProperty.call( this.lookupCache, value ) ) {
6117 deferred.resolve( this.getLookupMenuOptionsFromData( this.lookupCache[ value ] ) );
6118 } else {
6119 this.pushPending();
6120 this.lookupQuery = value;
6121 ourRequest = this.lookupRequest = this.getLookupRequest();
6122 ourRequest
6123 .always( function () {
6124 // We need to pop pending even if this is an old request, otherwise
6125 // the widget will remain pending forever.
6126 // TODO: this assumes that an aborted request will fail or succeed soon after
6127 // being aborted, or at least eventually. It would be nice if we could popPending()
6128 // at abort time, but only if we knew that we hadn't already called popPending()
6129 // for that request.
6130 widget.popPending();
6131 } )
6132 .done( function ( response ) {
6133 // If this is an old request (and aborting it somehow caused it to still succeed),
6134 // ignore its success completely
6135 if ( ourRequest === widget.lookupRequest ) {
6136 widget.lookupQuery = null;
6137 widget.lookupRequest = null;
6138 widget.lookupCache[ value ] = widget.getLookupCacheDataFromResponse( response );
6139 deferred.resolve( widget.getLookupMenuOptionsFromData( widget.lookupCache[ value ] ) );
6140 }
6141 } )
6142 .fail( function () {
6143 // If this is an old request (or a request failing because it's being aborted),
6144 // ignore its failure completely
6145 if ( ourRequest === widget.lookupRequest ) {
6146 widget.lookupQuery = null;
6147 widget.lookupRequest = null;
6148 deferred.reject();
6149 }
6150 } );
6151 }
6152 return deferred.promise();
6153 };
6154
6155 /**
6156 * Abort the currently pending lookup request, if any.
6157 *
6158 * @private
6159 */
6160 OO.ui.mixin.LookupElement.prototype.abortLookupRequest = function () {
6161 var oldRequest = this.lookupRequest;
6162 if ( oldRequest ) {
6163 // First unset this.lookupRequest to the fail handler will notice
6164 // that the request is no longer current
6165 this.lookupRequest = null;
6166 this.lookupQuery = null;
6167 oldRequest.abort();
6168 }
6169 };
6170
6171 /**
6172 * Get a new request object of the current lookup query value.
6173 *
6174 * @protected
6175 * @abstract
6176 * @return {jQuery.Promise} jQuery AJAX object, or promise object with an .abort() method
6177 */
6178 OO.ui.mixin.LookupElement.prototype.getLookupRequest = function () {
6179 // Stub, implemented in subclass
6180 return null;
6181 };
6182
6183 /**
6184 * Pre-process data returned by the request from #getLookupRequest.
6185 *
6186 * The return value of this function will be cached, and any further queries for the given value
6187 * will use the cache rather than doing API requests.
6188 *
6189 * @protected
6190 * @abstract
6191 * @param {Mixed} response Response from server
6192 * @return {Mixed} Cached result data
6193 */
6194 OO.ui.mixin.LookupElement.prototype.getLookupCacheDataFromResponse = function () {
6195 // Stub, implemented in subclass
6196 return [];
6197 };
6198
6199 /**
6200 * Get a list of menu option widgets from the (possibly cached) data returned by
6201 * #getLookupCacheDataFromResponse.
6202 *
6203 * @protected
6204 * @abstract
6205 * @param {Mixed} data Cached result data, usually an array
6206 * @return {OO.ui.MenuOptionWidget[]} Menu items
6207 */
6208 OO.ui.mixin.LookupElement.prototype.getLookupMenuOptionsFromData = function () {
6209 // Stub, implemented in subclass
6210 return [];
6211 };
6212
6213 /**
6214 * Set the read-only state of the widget.
6215 *
6216 * This will also disable/enable the lookups functionality.
6217 *
6218 * @param {boolean} readOnly Make input read-only
6219 * @chainable
6220 */
6221 OO.ui.mixin.LookupElement.prototype.setReadOnly = function ( readOnly ) {
6222 // Parent method
6223 // Note: Calling #setReadOnly this way assumes this is mixed into an OO.ui.TextInputWidget
6224 OO.ui.TextInputWidget.prototype.setReadOnly.call( this, readOnly );
6225
6226 // During construction, #setReadOnly is called before the OO.ui.mixin.LookupElement constructor
6227 if ( this.isReadOnly() && this.lookupMenu ) {
6228 this.closeLookupMenu();
6229 }
6230
6231 return this;
6232 };
6233
6234 /**
6235 * PopupElement is mixed into other classes to generate a {@link OO.ui.PopupWidget popup widget}.
6236 * A popup is a container for content. It is overlaid and positioned absolutely. By default, each
6237 * popup has an anchor, which is an arrow-like protrusion that points toward the popup’s origin.
6238 * See {@link OO.ui.PopupWidget PopupWidget} for an example.
6239 *
6240 * @abstract
6241 * @class
6242 *
6243 * @constructor
6244 * @param {Object} [config] Configuration options
6245 * @cfg {Object} [popup] Configuration to pass to popup
6246 * @cfg {boolean} [popup.autoClose=true] Popup auto-closes when it loses focus
6247 */
6248 OO.ui.mixin.PopupElement = function OoUiMixinPopupElement( config ) {
6249 // Configuration initialization
6250 config = config || {};
6251
6252 // Properties
6253 this.popup = new OO.ui.PopupWidget( $.extend(
6254 { autoClose: true },
6255 config.popup,
6256 { $autoCloseIgnore: this.$element }
6257 ) );
6258 };
6259
6260 /* Methods */
6261
6262 /**
6263 * Get popup.
6264 *
6265 * @return {OO.ui.PopupWidget} Popup widget
6266 */
6267 OO.ui.mixin.PopupElement.prototype.getPopup = function () {
6268 return this.popup;
6269 };
6270
6271 /**
6272 * The FlaggedElement class is an attribute mixin, meaning that it is used to add
6273 * additional functionality to an element created by another class. The class provides
6274 * a ‘flags’ property assigned the name (or an array of names) of styling flags,
6275 * which are used to customize the look and feel of a widget to better describe its
6276 * importance and functionality.
6277 *
6278 * The library currently contains the following styling flags for general use:
6279 *
6280 * - **progressive**: Progressive styling is applied to convey that the widget will move the user forward in a process.
6281 * - **destructive**: Destructive styling is applied to convey that the widget will remove something.
6282 * - **constructive**: Constructive styling is applied to convey that the widget will create something.
6283 *
6284 * The flags affect the appearance of the buttons:
6285 *
6286 * @example
6287 * // FlaggedElement is mixed into ButtonWidget to provide styling flags
6288 * var button1 = new OO.ui.ButtonWidget( {
6289 * label: 'Constructive',
6290 * flags: 'constructive'
6291 * } );
6292 * var button2 = new OO.ui.ButtonWidget( {
6293 * label: 'Destructive',
6294 * flags: 'destructive'
6295 * } );
6296 * var button3 = new OO.ui.ButtonWidget( {
6297 * label: 'Progressive',
6298 * flags: 'progressive'
6299 * } );
6300 * $( 'body' ).append( button1.$element, button2.$element, button3.$element );
6301 *
6302 * {@link OO.ui.ActionWidget ActionWidgets}, which are a special kind of button that execute an action, use these flags: **primary** and **safe**.
6303 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information.
6304 *
6305 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Flagged
6306 *
6307 * @abstract
6308 * @class
6309 *
6310 * @constructor
6311 * @param {Object} [config] Configuration options
6312 * @cfg {string|string[]} [flags] The name or names of the flags (e.g., 'constructive' or 'primary') to apply.
6313 * Please see the [OOjs UI documentation on MediaWiki] [2] for more information about available flags.
6314 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Flagged
6315 * @cfg {jQuery} [$flagged] The flagged element. By default,
6316 * the flagged functionality is applied to the element created by the class ($element).
6317 * If a different element is specified, the flagged functionality will be applied to it instead.
6318 */
6319 OO.ui.mixin.FlaggedElement = function OoUiMixinFlaggedElement( config ) {
6320 // Configuration initialization
6321 config = config || {};
6322
6323 // Properties
6324 this.flags = {};
6325 this.$flagged = null;
6326
6327 // Initialization
6328 this.setFlags( config.flags );
6329 this.setFlaggedElement( config.$flagged || this.$element );
6330 };
6331
6332 /* Events */
6333
6334 /**
6335 * @event flag
6336 * A flag event is emitted when the #clearFlags or #setFlags methods are used. The `changes`
6337 * parameter contains the name of each modified flag and indicates whether it was
6338 * added or removed.
6339 *
6340 * @param {Object.<string,boolean>} changes Object keyed by flag name. A Boolean `true` indicates
6341 * that the flag was added, `false` that the flag was removed.
6342 */
6343
6344 /* Methods */
6345
6346 /**
6347 * Set the flagged element.
6348 *
6349 * This method is used to retarget a flagged mixin so that its functionality applies to the specified element.
6350 * If an element is already set, the method will remove the mixin’s effect on that element.
6351 *
6352 * @param {jQuery} $flagged Element that should be flagged
6353 */
6354 OO.ui.mixin.FlaggedElement.prototype.setFlaggedElement = function ( $flagged ) {
6355 var classNames = Object.keys( this.flags ).map( function ( flag ) {
6356 return 'oo-ui-flaggedElement-' + flag;
6357 } ).join( ' ' );
6358
6359 if ( this.$flagged ) {
6360 this.$flagged.removeClass( classNames );
6361 }
6362
6363 this.$flagged = $flagged.addClass( classNames );
6364 };
6365
6366 /**
6367 * Check if the specified flag is set.
6368 *
6369 * @param {string} flag Name of flag
6370 * @return {boolean} The flag is set
6371 */
6372 OO.ui.mixin.FlaggedElement.prototype.hasFlag = function ( flag ) {
6373 // This may be called before the constructor, thus before this.flags is set
6374 return this.flags && ( flag in this.flags );
6375 };
6376
6377 /**
6378 * Get the names of all flags set.
6379 *
6380 * @return {string[]} Flag names
6381 */
6382 OO.ui.mixin.FlaggedElement.prototype.getFlags = function () {
6383 // This may be called before the constructor, thus before this.flags is set
6384 return Object.keys( this.flags || {} );
6385 };
6386
6387 /**
6388 * Clear all flags.
6389 *
6390 * @chainable
6391 * @fires flag
6392 */
6393 OO.ui.mixin.FlaggedElement.prototype.clearFlags = function () {
6394 var flag, className,
6395 changes = {},
6396 remove = [],
6397 classPrefix = 'oo-ui-flaggedElement-';
6398
6399 for ( flag in this.flags ) {
6400 className = classPrefix + flag;
6401 changes[ flag ] = false;
6402 delete this.flags[ flag ];
6403 remove.push( className );
6404 }
6405
6406 if ( this.$flagged ) {
6407 this.$flagged.removeClass( remove.join( ' ' ) );
6408 }
6409
6410 this.updateThemeClasses();
6411 this.emit( 'flag', changes );
6412
6413 return this;
6414 };
6415
6416 /**
6417 * Add one or more flags.
6418 *
6419 * @param {string|string[]|Object.<string, boolean>} flags A flag name, an array of flag names,
6420 * or an object keyed by flag name with a boolean value that indicates whether the flag should
6421 * be added (`true`) or removed (`false`).
6422 * @chainable
6423 * @fires flag
6424 */
6425 OO.ui.mixin.FlaggedElement.prototype.setFlags = function ( flags ) {
6426 var i, len, flag, className,
6427 changes = {},
6428 add = [],
6429 remove = [],
6430 classPrefix = 'oo-ui-flaggedElement-';
6431
6432 if ( typeof flags === 'string' ) {
6433 className = classPrefix + flags;
6434 // Set
6435 if ( !this.flags[ flags ] ) {
6436 this.flags[ flags ] = true;
6437 add.push( className );
6438 }
6439 } else if ( Array.isArray( flags ) ) {
6440 for ( i = 0, len = flags.length; i < len; i++ ) {
6441 flag = flags[ i ];
6442 className = classPrefix + flag;
6443 // Set
6444 if ( !this.flags[ flag ] ) {
6445 changes[ flag ] = true;
6446 this.flags[ flag ] = true;
6447 add.push( className );
6448 }
6449 }
6450 } else if ( OO.isPlainObject( flags ) ) {
6451 for ( flag in flags ) {
6452 className = classPrefix + flag;
6453 if ( flags[ flag ] ) {
6454 // Set
6455 if ( !this.flags[ flag ] ) {
6456 changes[ flag ] = true;
6457 this.flags[ flag ] = true;
6458 add.push( className );
6459 }
6460 } else {
6461 // Remove
6462 if ( this.flags[ flag ] ) {
6463 changes[ flag ] = false;
6464 delete this.flags[ flag ];
6465 remove.push( className );
6466 }
6467 }
6468 }
6469 }
6470
6471 if ( this.$flagged ) {
6472 this.$flagged
6473 .addClass( add.join( ' ' ) )
6474 .removeClass( remove.join( ' ' ) );
6475 }
6476
6477 this.updateThemeClasses();
6478 this.emit( 'flag', changes );
6479
6480 return this;
6481 };
6482
6483 /**
6484 * TitledElement is mixed into other classes to provide a `title` attribute.
6485 * Titles are rendered by the browser and are made visible when the user moves
6486 * the mouse over the element. Titles are not visible on touch devices.
6487 *
6488 * @example
6489 * // TitledElement provides a 'title' attribute to the
6490 * // ButtonWidget class
6491 * var button = new OO.ui.ButtonWidget( {
6492 * label: 'Button with Title',
6493 * title: 'I am a button'
6494 * } );
6495 * $( 'body' ).append( button.$element );
6496 *
6497 * @abstract
6498 * @class
6499 *
6500 * @constructor
6501 * @param {Object} [config] Configuration options
6502 * @cfg {jQuery} [$titled] The element to which the `title` attribute is applied.
6503 * If this config is omitted, the title functionality is applied to $element, the
6504 * element created by the class.
6505 * @cfg {string|Function} [title] The title text or a function that returns text. If
6506 * this config is omitted, the value of the {@link #static-title static title} property is used.
6507 */
6508 OO.ui.mixin.TitledElement = function OoUiMixinTitledElement( config ) {
6509 // Configuration initialization
6510 config = config || {};
6511
6512 // Properties
6513 this.$titled = null;
6514 this.title = null;
6515
6516 // Initialization
6517 this.setTitle( config.title || this.constructor.static.title );
6518 this.setTitledElement( config.$titled || this.$element );
6519 };
6520
6521 /* Setup */
6522
6523 OO.initClass( OO.ui.mixin.TitledElement );
6524
6525 /* Static Properties */
6526
6527 /**
6528 * The title text, a function that returns text, or `null` for no title. The value of the static property
6529 * is overridden if the #title config option is used.
6530 *
6531 * @static
6532 * @inheritable
6533 * @property {string|Function|null}
6534 */
6535 OO.ui.mixin.TitledElement.static.title = null;
6536
6537 /* Methods */
6538
6539 /**
6540 * Set the titled element.
6541 *
6542 * This method is used to retarget a titledElement mixin so that its functionality applies to the specified element.
6543 * If an element is already set, the mixin’s effect on that element is removed before the new element is set up.
6544 *
6545 * @param {jQuery} $titled Element that should use the 'titled' functionality
6546 */
6547 OO.ui.mixin.TitledElement.prototype.setTitledElement = function ( $titled ) {
6548 if ( this.$titled ) {
6549 this.$titled.removeAttr( 'title' );
6550 }
6551
6552 this.$titled = $titled;
6553 if ( this.title ) {
6554 this.$titled.attr( 'title', this.title );
6555 }
6556 };
6557
6558 /**
6559 * Set title.
6560 *
6561 * @param {string|Function|null} title Title text, a function that returns text, or `null` for no title
6562 * @chainable
6563 */
6564 OO.ui.mixin.TitledElement.prototype.setTitle = function ( title ) {
6565 title = typeof title === 'string' ? OO.ui.resolveMsg( title ) : null;
6566
6567 if ( this.title !== title ) {
6568 if ( this.$titled ) {
6569 if ( title !== null ) {
6570 this.$titled.attr( 'title', title );
6571 } else {
6572 this.$titled.removeAttr( 'title' );
6573 }
6574 }
6575 this.title = title;
6576 }
6577
6578 return this;
6579 };
6580
6581 /**
6582 * Get title.
6583 *
6584 * @return {string} Title string
6585 */
6586 OO.ui.mixin.TitledElement.prototype.getTitle = function () {
6587 return this.title;
6588 };
6589
6590 /**
6591 * Element that can be automatically clipped to visible boundaries.
6592 *
6593 * Whenever the element's natural height changes, you have to call
6594 * {@link OO.ui.mixin.ClippableElement#clip} to make sure it's still
6595 * clipping correctly.
6596 *
6597 * The dimensions of #$clippableContainer will be compared to the boundaries of the
6598 * nearest scrollable container. If #$clippableContainer is too tall and/or too wide,
6599 * then #$clippable will be given a fixed reduced height and/or width and will be made
6600 * scrollable. By default, #$clippable and #$clippableContainer are the same element,
6601 * but you can build a static footer by setting #$clippableContainer to an element that contains
6602 * #$clippable and the footer.
6603 *
6604 * @abstract
6605 * @class
6606 *
6607 * @constructor
6608 * @param {Object} [config] Configuration options
6609 * @cfg {jQuery} [$clippable] Node to clip, assigned to #$clippable, omit to use #$element
6610 * @cfg {jQuery} [$clippableContainer] Node to keep visible, assigned to #$clippableContainer,
6611 * omit to use #$clippable
6612 */
6613 OO.ui.mixin.ClippableElement = function OoUiMixinClippableElement( config ) {
6614 // Configuration initialization
6615 config = config || {};
6616
6617 // Properties
6618 this.$clippable = null;
6619 this.$clippableContainer = null;
6620 this.clipping = false;
6621 this.clippedHorizontally = false;
6622 this.clippedVertically = false;
6623 this.$clippableScrollableContainer = null;
6624 this.$clippableScroller = null;
6625 this.$clippableWindow = null;
6626 this.idealWidth = null;
6627 this.idealHeight = null;
6628 this.onClippableScrollHandler = this.clip.bind( this );
6629 this.onClippableWindowResizeHandler = this.clip.bind( this );
6630
6631 // Initialization
6632 if ( config.$clippableContainer ) {
6633 this.setClippableContainer( config.$clippableContainer );
6634 }
6635 this.setClippableElement( config.$clippable || this.$element );
6636 };
6637
6638 /* Methods */
6639
6640 /**
6641 * Set clippable element.
6642 *
6643 * If an element is already set, it will be cleaned up before setting up the new element.
6644 *
6645 * @param {jQuery} $clippable Element to make clippable
6646 */
6647 OO.ui.mixin.ClippableElement.prototype.setClippableElement = function ( $clippable ) {
6648 if ( this.$clippable ) {
6649 this.$clippable.removeClass( 'oo-ui-clippableElement-clippable' );
6650 this.$clippable.css( { width: '', height: '', overflowX: '', overflowY: '' } );
6651 OO.ui.Element.static.reconsiderScrollbars( this.$clippable[ 0 ] );
6652 }
6653
6654 this.$clippable = $clippable.addClass( 'oo-ui-clippableElement-clippable' );
6655 this.clip();
6656 };
6657
6658 /**
6659 * Set clippable container.
6660 *
6661 * This is the container that will be measured when deciding whether to clip. When clipping,
6662 * #$clippable will be resized in order to keep the clippable container fully visible.
6663 *
6664 * If the clippable container is unset, #$clippable will be used.
6665 *
6666 * @param {jQuery|null} $clippableContainer Container to keep visible, or null to unset
6667 */
6668 OO.ui.mixin.ClippableElement.prototype.setClippableContainer = function ( $clippableContainer ) {
6669 this.$clippableContainer = $clippableContainer;
6670 if ( this.$clippable ) {
6671 this.clip();
6672 }
6673 };
6674
6675 /**
6676 * Toggle clipping.
6677 *
6678 * Do not turn clipping on until after the element is attached to the DOM and visible.
6679 *
6680 * @param {boolean} [clipping] Enable clipping, omit to toggle
6681 * @chainable
6682 */
6683 OO.ui.mixin.ClippableElement.prototype.toggleClipping = function ( clipping ) {
6684 clipping = clipping === undefined ? !this.clipping : !!clipping;
6685
6686 if ( this.clipping !== clipping ) {
6687 this.clipping = clipping;
6688 if ( clipping ) {
6689 this.$clippableScrollableContainer = $( this.getClosestScrollableElementContainer() );
6690 // If the clippable container is the root, we have to listen to scroll events and check
6691 // jQuery.scrollTop on the window because of browser inconsistencies
6692 this.$clippableScroller = this.$clippableScrollableContainer.is( 'html, body' ) ?
6693 $( OO.ui.Element.static.getWindow( this.$clippableScrollableContainer ) ) :
6694 this.$clippableScrollableContainer;
6695 this.$clippableScroller.on( 'scroll', this.onClippableScrollHandler );
6696 this.$clippableWindow = $( this.getElementWindow() )
6697 .on( 'resize', this.onClippableWindowResizeHandler );
6698 // Initial clip after visible
6699 this.clip();
6700 } else {
6701 this.$clippable.css( { width: '', height: '', overflowX: '', overflowY: '' } );
6702 OO.ui.Element.static.reconsiderScrollbars( this.$clippable[ 0 ] );
6703
6704 this.$clippableScrollableContainer = null;
6705 this.$clippableScroller.off( 'scroll', this.onClippableScrollHandler );
6706 this.$clippableScroller = null;
6707 this.$clippableWindow.off( 'resize', this.onClippableWindowResizeHandler );
6708 this.$clippableWindow = null;
6709 }
6710 }
6711
6712 return this;
6713 };
6714
6715 /**
6716 * Check if the element will be clipped to fit the visible area of the nearest scrollable container.
6717 *
6718 * @return {boolean} Element will be clipped to the visible area
6719 */
6720 OO.ui.mixin.ClippableElement.prototype.isClipping = function () {
6721 return this.clipping;
6722 };
6723
6724 /**
6725 * Check if the bottom or right of the element is being clipped by the nearest scrollable container.
6726 *
6727 * @return {boolean} Part of the element is being clipped
6728 */
6729 OO.ui.mixin.ClippableElement.prototype.isClipped = function () {
6730 return this.clippedHorizontally || this.clippedVertically;
6731 };
6732
6733 /**
6734 * Check if the right of the element is being clipped by the nearest scrollable container.
6735 *
6736 * @return {boolean} Part of the element is being clipped
6737 */
6738 OO.ui.mixin.ClippableElement.prototype.isClippedHorizontally = function () {
6739 return this.clippedHorizontally;
6740 };
6741
6742 /**
6743 * Check if the bottom of the element is being clipped by the nearest scrollable container.
6744 *
6745 * @return {boolean} Part of the element is being clipped
6746 */
6747 OO.ui.mixin.ClippableElement.prototype.isClippedVertically = function () {
6748 return this.clippedVertically;
6749 };
6750
6751 /**
6752 * Set the ideal size. These are the dimensions the element will have when it's not being clipped.
6753 *
6754 * @param {number|string} [width] Width as a number of pixels or CSS string with unit suffix
6755 * @param {number|string} [height] Height as a number of pixels or CSS string with unit suffix
6756 */
6757 OO.ui.mixin.ClippableElement.prototype.setIdealSize = function ( width, height ) {
6758 this.idealWidth = width;
6759 this.idealHeight = height;
6760
6761 if ( !this.clipping ) {
6762 // Update dimensions
6763 this.$clippable.css( { width: width, height: height } );
6764 }
6765 // While clipping, idealWidth and idealHeight are not considered
6766 };
6767
6768 /**
6769 * Clip element to visible boundaries and allow scrolling when needed. Call this method when
6770 * the element's natural height changes.
6771 *
6772 * Element will be clipped the bottom or right of the element is within 10px of the edge of, or
6773 * overlapped by, the visible area of the nearest scrollable container.
6774 *
6775 * @chainable
6776 */
6777 OO.ui.mixin.ClippableElement.prototype.clip = function () {
6778 var $container, extraHeight, extraWidth, ccOffset,
6779 $scrollableContainer, scOffset, scHeight, scWidth,
6780 ccWidth, scrollerIsWindow, scrollTop, scrollLeft,
6781 desiredWidth, desiredHeight, allotedWidth, allotedHeight,
6782 naturalWidth, naturalHeight, clipWidth, clipHeight,
6783 buffer = 7; // Chosen by fair dice roll
6784
6785 if ( !this.clipping ) {
6786 // this.$clippableScrollableContainer and this.$clippableWindow are null, so the below will fail
6787 return this;
6788 }
6789
6790 $container = this.$clippableContainer || this.$clippable;
6791 extraHeight = $container.outerHeight() - this.$clippable.outerHeight();
6792 extraWidth = $container.outerWidth() - this.$clippable.outerWidth();
6793 ccOffset = $container.offset();
6794 $scrollableContainer = this.$clippableScrollableContainer.is( 'html, body' ) ?
6795 this.$clippableWindow : this.$clippableScrollableContainer;
6796 scOffset = $scrollableContainer.offset() || { top: 0, left: 0 };
6797 scHeight = $scrollableContainer.innerHeight() - buffer;
6798 scWidth = $scrollableContainer.innerWidth() - buffer;
6799 ccWidth = $container.outerWidth() + buffer;
6800 scrollerIsWindow = this.$clippableScroller[ 0 ] === this.$clippableWindow[ 0 ];
6801 scrollTop = scrollerIsWindow ? this.$clippableScroller.scrollTop() : 0;
6802 scrollLeft = scrollerIsWindow ? this.$clippableScroller.scrollLeft() : 0;
6803 desiredWidth = ccOffset.left < 0 ?
6804 ccWidth + ccOffset.left :
6805 ( scOffset.left + scrollLeft + scWidth ) - ccOffset.left;
6806 desiredHeight = ( scOffset.top + scrollTop + scHeight ) - ccOffset.top;
6807 allotedWidth = desiredWidth - extraWidth;
6808 allotedHeight = desiredHeight - extraHeight;
6809 naturalWidth = this.$clippable.prop( 'scrollWidth' );
6810 naturalHeight = this.$clippable.prop( 'scrollHeight' );
6811 clipWidth = allotedWidth < naturalWidth;
6812 clipHeight = allotedHeight < naturalHeight;
6813
6814 if ( clipWidth ) {
6815 this.$clippable.css( { overflowX: 'scroll', width: Math.max( 0, allotedWidth ) } );
6816 } else {
6817 this.$clippable.css( { width: this.idealWidth ? this.idealWidth - extraWidth : '', overflowX: '' } );
6818 }
6819 if ( clipHeight ) {
6820 this.$clippable.css( { overflowY: 'scroll', height: Math.max( 0, allotedHeight ) } );
6821 } else {
6822 this.$clippable.css( { height: this.idealHeight ? this.idealHeight - extraHeight : '', overflowY: '' } );
6823 }
6824
6825 // If we stopped clipping in at least one of the dimensions
6826 if ( ( this.clippedHorizontally && !clipWidth ) || ( this.clippedVertically && !clipHeight ) ) {
6827 OO.ui.Element.static.reconsiderScrollbars( this.$clippable[ 0 ] );
6828 }
6829
6830 this.clippedHorizontally = clipWidth;
6831 this.clippedVertically = clipHeight;
6832
6833 return this;
6834 };
6835
6836 /**
6837 * Element that will stick under a specified container, even when it is inserted elsewhere in the
6838 * document (for example, in a OO.ui.Window's $overlay).
6839 *
6840 * The elements's position is automatically calculated and maintained when window is resized or the
6841 * page is scrolled. If you reposition the container manually, you have to call #position to make
6842 * sure the element is still placed correctly.
6843 *
6844 * As positioning is only possible when both the element and the container are attached to the DOM
6845 * and visible, it's only done after you call #togglePositioning. You might want to do this inside
6846 * the #toggle method to display a floating popup, for example.
6847 *
6848 * @abstract
6849 * @class
6850 *
6851 * @constructor
6852 * @param {Object} [config] Configuration options
6853 * @cfg {jQuery} [$floatable] Node to position, assigned to #$floatable, omit to use #$element
6854 * @cfg {jQuery} [$floatableContainer] Node to position below
6855 */
6856 OO.ui.mixin.FloatableElement = function OoUiMixinFloatableElement( config ) {
6857 // Configuration initialization
6858 config = config || {};
6859
6860 // Properties
6861 this.$floatable = null;
6862 this.$floatableContainer = null;
6863 this.$floatableWindow = null;
6864 this.$floatableClosestScrollable = null;
6865 this.onFloatableScrollHandler = this.position.bind( this );
6866 this.onFloatableWindowResizeHandler = this.position.bind( this );
6867
6868 // Initialization
6869 this.setFloatableContainer( config.$floatableContainer );
6870 this.setFloatableElement( config.$floatable || this.$element );
6871 };
6872
6873 /* Methods */
6874
6875 /**
6876 * Set floatable element.
6877 *
6878 * If an element is already set, it will be cleaned up before setting up the new element.
6879 *
6880 * @param {jQuery} $floatable Element to make floatable
6881 */
6882 OO.ui.mixin.FloatableElement.prototype.setFloatableElement = function ( $floatable ) {
6883 if ( this.$floatable ) {
6884 this.$floatable.removeClass( 'oo-ui-floatableElement-floatable' );
6885 this.$floatable.css( { left: '', top: '' } );
6886 }
6887
6888 this.$floatable = $floatable.addClass( 'oo-ui-floatableElement-floatable' );
6889 this.position();
6890 };
6891
6892 /**
6893 * Set floatable container.
6894 *
6895 * The element will be always positioned under the specified container.
6896 *
6897 * @param {jQuery|null} $floatableContainer Container to keep visible, or null to unset
6898 */
6899 OO.ui.mixin.FloatableElement.prototype.setFloatableContainer = function ( $floatableContainer ) {
6900 this.$floatableContainer = $floatableContainer;
6901 if ( this.$floatable ) {
6902 this.position();
6903 }
6904 };
6905
6906 /**
6907 * Toggle positioning.
6908 *
6909 * Do not turn positioning on until after the element is attached to the DOM and visible.
6910 *
6911 * @param {boolean} [positioning] Enable positioning, omit to toggle
6912 * @chainable
6913 */
6914 OO.ui.mixin.FloatableElement.prototype.togglePositioning = function ( positioning ) {
6915 var closestScrollableOfContainer, closestScrollableOfFloatable;
6916
6917 positioning = positioning === undefined ? !this.positioning : !!positioning;
6918
6919 if ( this.positioning !== positioning ) {
6920 this.positioning = positioning;
6921
6922 closestScrollableOfContainer = OO.ui.Element.static.getClosestScrollableContainer( this.$floatableContainer[ 0 ] );
6923 closestScrollableOfFloatable = OO.ui.Element.static.getClosestScrollableContainer( this.$floatable[ 0 ] );
6924 if ( closestScrollableOfContainer !== closestScrollableOfFloatable ) {
6925 // If the scrollable is the root, we have to listen to scroll events
6926 // on the window because of browser inconsistencies (or do we? someone should verify this)
6927 if ( $( closestScrollableOfContainer ).is( 'html, body' ) ) {
6928 closestScrollableOfContainer = OO.ui.Element.static.getWindow( closestScrollableOfContainer );
6929 }
6930 }
6931
6932 if ( positioning ) {
6933 this.$floatableWindow = $( this.getElementWindow() );
6934 this.$floatableWindow.on( 'resize', this.onFloatableWindowResizeHandler );
6935
6936 if ( closestScrollableOfContainer !== closestScrollableOfFloatable ) {
6937 this.$floatableClosestScrollable = $( closestScrollableOfContainer );
6938 this.$floatableClosestScrollable.on( 'scroll', this.onFloatableScrollHandler );
6939 }
6940
6941 // Initial position after visible
6942 this.position();
6943 } else {
6944 if ( this.$floatableWindow ) {
6945 this.$floatableWindow.off( 'resize', this.onFloatableWindowResizeHandler );
6946 this.$floatableWindow = null;
6947 }
6948
6949 if ( this.$floatableClosestScrollable ) {
6950 this.$floatableClosestScrollable.off( 'scroll', this.onFloatableScrollHandler );
6951 this.$floatableClosestScrollable = null;
6952 }
6953
6954 this.$floatable.css( { left: '', top: '' } );
6955 }
6956 }
6957
6958 return this;
6959 };
6960
6961 /**
6962 * Position the floatable below its container.
6963 *
6964 * This should only be done when both of them are attached to the DOM and visible.
6965 *
6966 * @chainable
6967 */
6968 OO.ui.mixin.FloatableElement.prototype.position = function () {
6969 var pos;
6970
6971 if ( !this.positioning ) {
6972 return this;
6973 }
6974
6975 pos = OO.ui.Element.static.getRelativePosition( this.$floatableContainer, this.$floatable.offsetParent() );
6976
6977 // Position under container
6978 pos.top += this.$floatableContainer.height();
6979 this.$floatable.css( pos );
6980
6981 // We updated the position, so re-evaluate the clipping state.
6982 // (ClippableElement does not listen to 'scroll' events on $floatableContainer's parent, and so
6983 // will not notice the need to update itself.)
6984 // TODO: This is terrible, we shouldn't need to know about ClippableElement at all here. Why does
6985 // it not listen to the right events in the right places?
6986 if ( this.clip ) {
6987 this.clip();
6988 }
6989
6990 return this;
6991 };
6992
6993 /**
6994 * AccessKeyedElement is mixed into other classes to provide an `accesskey` attribute.
6995 * Accesskeys allow an user to go to a specific element by using
6996 * a shortcut combination of a browser specific keys + the key
6997 * set to the field.
6998 *
6999 * @example
7000 * // AccessKeyedElement provides an 'accesskey' attribute to the
7001 * // ButtonWidget class
7002 * var button = new OO.ui.ButtonWidget( {
7003 * label: 'Button with Accesskey',
7004 * accessKey: 'k'
7005 * } );
7006 * $( 'body' ).append( button.$element );
7007 *
7008 * @abstract
7009 * @class
7010 *
7011 * @constructor
7012 * @param {Object} [config] Configuration options
7013 * @cfg {jQuery} [$accessKeyed] The element to which the `accesskey` attribute is applied.
7014 * If this config is omitted, the accesskey functionality is applied to $element, the
7015 * element created by the class.
7016 * @cfg {string|Function} [accessKey] The key or a function that returns the key. If
7017 * this config is omitted, no accesskey will be added.
7018 */
7019 OO.ui.mixin.AccessKeyedElement = function OoUiMixinAccessKeyedElement( config ) {
7020 // Configuration initialization
7021 config = config || {};
7022
7023 // Properties
7024 this.$accessKeyed = null;
7025 this.accessKey = null;
7026
7027 // Initialization
7028 this.setAccessKey( config.accessKey || null );
7029 this.setAccessKeyedElement( config.$accessKeyed || this.$element );
7030 };
7031
7032 /* Setup */
7033
7034 OO.initClass( OO.ui.mixin.AccessKeyedElement );
7035
7036 /* Static Properties */
7037
7038 /**
7039 * The access key, a function that returns a key, or `null` for no accesskey.
7040 *
7041 * @static
7042 * @inheritable
7043 * @property {string|Function|null}
7044 */
7045 OO.ui.mixin.AccessKeyedElement.static.accessKey = null;
7046
7047 /* Methods */
7048
7049 /**
7050 * Set the accesskeyed element.
7051 *
7052 * This method is used to retarget a AccessKeyedElement mixin so that its functionality applies to the specified element.
7053 * If an element is already set, the mixin's effect on that element is removed before the new element is set up.
7054 *
7055 * @param {jQuery} $accessKeyed Element that should use the 'accesskeyes' functionality
7056 */
7057 OO.ui.mixin.AccessKeyedElement.prototype.setAccessKeyedElement = function ( $accessKeyed ) {
7058 if ( this.$accessKeyed ) {
7059 this.$accessKeyed.removeAttr( 'accesskey' );
7060 }
7061
7062 this.$accessKeyed = $accessKeyed;
7063 if ( this.accessKey ) {
7064 this.$accessKeyed.attr( 'accesskey', this.accessKey );
7065 }
7066 };
7067
7068 /**
7069 * Set accesskey.
7070 *
7071 * @param {string|Function|null} accesskey Key, a function that returns a key, or `null` for no accesskey
7072 * @chainable
7073 */
7074 OO.ui.mixin.AccessKeyedElement.prototype.setAccessKey = function ( accessKey ) {
7075 accessKey = typeof accessKey === 'string' ? OO.ui.resolveMsg( accessKey ) : null;
7076
7077 if ( this.accessKey !== accessKey ) {
7078 if ( this.$accessKeyed ) {
7079 if ( accessKey !== null ) {
7080 this.$accessKeyed.attr( 'accesskey', accessKey );
7081 } else {
7082 this.$accessKeyed.removeAttr( 'accesskey' );
7083 }
7084 }
7085 this.accessKey = accessKey;
7086 }
7087
7088 return this;
7089 };
7090
7091 /**
7092 * Get accesskey.
7093 *
7094 * @return {string} accessKey string
7095 */
7096 OO.ui.mixin.AccessKeyedElement.prototype.getAccessKey = function () {
7097 return this.accessKey;
7098 };
7099
7100 /**
7101 * Tools, together with {@link OO.ui.ToolGroup toolgroups}, constitute {@link OO.ui.Toolbar toolbars}.
7102 * Each tool is configured with a static name, title, and icon and is customized with the command to carry
7103 * out when the tool is selected. Tools must also be registered with a {@link OO.ui.ToolFactory tool factory},
7104 * which creates the tools on demand.
7105 *
7106 * Tools are added to toolgroups ({@link OO.ui.ListToolGroup ListToolGroup},
7107 * {@link OO.ui.BarToolGroup BarToolGroup}, or {@link OO.ui.MenuToolGroup MenuToolGroup}), which determine how
7108 * the tool is displayed in the toolbar. See {@link OO.ui.Toolbar toolbars} for an example.
7109 *
7110 * For more information, please see the [OOjs UI documentation on MediaWiki][1].
7111 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
7112 *
7113 * @abstract
7114 * @class
7115 * @extends OO.ui.Widget
7116 * @mixins OO.ui.mixin.IconElement
7117 * @mixins OO.ui.mixin.FlaggedElement
7118 * @mixins OO.ui.mixin.TabIndexedElement
7119 *
7120 * @constructor
7121 * @param {OO.ui.ToolGroup} toolGroup
7122 * @param {Object} [config] Configuration options
7123 * @cfg {string|Function} [title] Title text or a function that returns text. If this config is omitted, the value of
7124 * the {@link #static-title static title} property is used.
7125 *
7126 * The title is used in different ways depending on the type of toolgroup that contains the tool. The
7127 * 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
7128 * part of a {@link OO.ui.ListToolGroup list} or {@link OO.ui.MenuToolGroup menu} toolgroup.
7129 *
7130 * For bar toolgroups, a description of the accelerator key is appended to the title if an accelerator key
7131 * is associated with an action by the same name as the tool and accelerator functionality has been added to the application.
7132 * To add accelerator key functionality, you must subclass OO.ui.Toolbar and override the {@link OO.ui.Toolbar#getToolAccelerator getToolAccelerator} method.
7133 */
7134 OO.ui.Tool = function OoUiTool( toolGroup, config ) {
7135 // Allow passing positional parameters inside the config object
7136 if ( OO.isPlainObject( toolGroup ) && config === undefined ) {
7137 config = toolGroup;
7138 toolGroup = config.toolGroup;
7139 }
7140
7141 // Configuration initialization
7142 config = config || {};
7143
7144 // Parent constructor
7145 OO.ui.Tool.parent.call( this, config );
7146
7147 // Properties
7148 this.toolGroup = toolGroup;
7149 this.toolbar = this.toolGroup.getToolbar();
7150 this.active = false;
7151 this.$title = $( '<span>' );
7152 this.$accel = $( '<span>' );
7153 this.$link = $( '<a>' );
7154 this.title = null;
7155
7156 // Mixin constructors
7157 OO.ui.mixin.IconElement.call( this, config );
7158 OO.ui.mixin.FlaggedElement.call( this, config );
7159 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$link } ) );
7160
7161 // Events
7162 this.toolbar.connect( this, { updateState: 'onUpdateState' } );
7163
7164 // Initialization
7165 this.$title.addClass( 'oo-ui-tool-title' );
7166 this.$accel
7167 .addClass( 'oo-ui-tool-accel' )
7168 .prop( {
7169 // This may need to be changed if the key names are ever localized,
7170 // but for now they are essentially written in English
7171 dir: 'ltr',
7172 lang: 'en'
7173 } );
7174 this.$link
7175 .addClass( 'oo-ui-tool-link' )
7176 .append( this.$icon, this.$title, this.$accel )
7177 .attr( 'role', 'button' );
7178 this.$element
7179 .data( 'oo-ui-tool', this )
7180 .addClass(
7181 'oo-ui-tool ' + 'oo-ui-tool-name-' +
7182 this.constructor.static.name.replace( /^([^\/]+)\/([^\/]+).*$/, '$1-$2' )
7183 )
7184 .toggleClass( 'oo-ui-tool-with-label', this.constructor.static.displayBothIconAndLabel )
7185 .append( this.$link );
7186 this.setTitle( config.title || this.constructor.static.title );
7187 };
7188
7189 /* Setup */
7190
7191 OO.inheritClass( OO.ui.Tool, OO.ui.Widget );
7192 OO.mixinClass( OO.ui.Tool, OO.ui.mixin.IconElement );
7193 OO.mixinClass( OO.ui.Tool, OO.ui.mixin.FlaggedElement );
7194 OO.mixinClass( OO.ui.Tool, OO.ui.mixin.TabIndexedElement );
7195
7196 /* Static Properties */
7197
7198 /**
7199 * @static
7200 * @inheritdoc
7201 */
7202 OO.ui.Tool.static.tagName = 'span';
7203
7204 /**
7205 * Symbolic name of tool.
7206 *
7207 * The symbolic name is used internally to register the tool with a {@link OO.ui.ToolFactory ToolFactory}. It can
7208 * also be used when adding tools to toolgroups.
7209 *
7210 * @abstract
7211 * @static
7212 * @inheritable
7213 * @property {string}
7214 */
7215 OO.ui.Tool.static.name = '';
7216
7217 /**
7218 * Symbolic name of the group.
7219 *
7220 * The group name is used to associate tools with each other so that they can be selected later by
7221 * a {@link OO.ui.ToolGroup toolgroup}.
7222 *
7223 * @abstract
7224 * @static
7225 * @inheritable
7226 * @property {string}
7227 */
7228 OO.ui.Tool.static.group = '';
7229
7230 /**
7231 * 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.
7232 *
7233 * @abstract
7234 * @static
7235 * @inheritable
7236 * @property {string|Function}
7237 */
7238 OO.ui.Tool.static.title = '';
7239
7240 /**
7241 * Display both icon and label when the tool is used in a {@link OO.ui.BarToolGroup bar} toolgroup.
7242 * Normally only the icon is displayed, or only the label if no icon is given.
7243 *
7244 * @static
7245 * @inheritable
7246 * @property {boolean}
7247 */
7248 OO.ui.Tool.static.displayBothIconAndLabel = false;
7249
7250 /**
7251 * Add tool to catch-all groups automatically.
7252 *
7253 * A catch-all group, which contains all tools that do not currently belong to a toolgroup,
7254 * can be included in a toolgroup using the wildcard selector, an asterisk (*).
7255 *
7256 * @static
7257 * @inheritable
7258 * @property {boolean}
7259 */
7260 OO.ui.Tool.static.autoAddToCatchall = true;
7261
7262 /**
7263 * Add tool to named groups automatically.
7264 *
7265 * By default, tools that are configured with a static ‘group’ property are added
7266 * to that group and will be selected when the symbolic name of the group is specified (e.g., when
7267 * toolgroups include tools by group name).
7268 *
7269 * @static
7270 * @property {boolean}
7271 * @inheritable
7272 */
7273 OO.ui.Tool.static.autoAddToGroup = true;
7274
7275 /**
7276 * Check if this tool is compatible with given data.
7277 *
7278 * This is a stub that can be overriden to provide support for filtering tools based on an
7279 * arbitrary piece of information (e.g., where the cursor is in a document). The implementation
7280 * must also call this method so that the compatibility check can be performed.
7281 *
7282 * @static
7283 * @inheritable
7284 * @param {Mixed} data Data to check
7285 * @return {boolean} Tool can be used with data
7286 */
7287 OO.ui.Tool.static.isCompatibleWith = function () {
7288 return false;
7289 };
7290
7291 /* Methods */
7292
7293 /**
7294 * Handle the toolbar state being updated.
7295 *
7296 * This is an abstract method that must be overridden in a concrete subclass.
7297 *
7298 * @protected
7299 * @abstract
7300 */
7301 OO.ui.Tool.prototype.onUpdateState = function () {
7302 throw new Error(
7303 'OO.ui.Tool.onUpdateState not implemented in this subclass:' + this.constructor
7304 );
7305 };
7306
7307 /**
7308 * Handle the tool being selected.
7309 *
7310 * This is an abstract method that must be overridden in a concrete subclass.
7311 *
7312 * @protected
7313 * @abstract
7314 */
7315 OO.ui.Tool.prototype.onSelect = function () {
7316 throw new Error(
7317 'OO.ui.Tool.onSelect not implemented in this subclass:' + this.constructor
7318 );
7319 };
7320
7321 /**
7322 * Check if the tool is active.
7323 *
7324 * Tools become active when their #onSelect or #onUpdateState handlers change them to appear pressed
7325 * with the #setActive method. Additional CSS is applied to the tool to reflect the active state.
7326 *
7327 * @return {boolean} Tool is active
7328 */
7329 OO.ui.Tool.prototype.isActive = function () {
7330 return this.active;
7331 };
7332
7333 /**
7334 * Make the tool appear active or inactive.
7335 *
7336 * This method should be called within #onSelect or #onUpdateState event handlers to make the tool
7337 * appear pressed or not.
7338 *
7339 * @param {boolean} state Make tool appear active
7340 */
7341 OO.ui.Tool.prototype.setActive = function ( state ) {
7342 this.active = !!state;
7343 if ( this.active ) {
7344 this.$element.addClass( 'oo-ui-tool-active' );
7345 } else {
7346 this.$element.removeClass( 'oo-ui-tool-active' );
7347 }
7348 };
7349
7350 /**
7351 * Set the tool #title.
7352 *
7353 * @param {string|Function} title Title text or a function that returns text
7354 * @chainable
7355 */
7356 OO.ui.Tool.prototype.setTitle = function ( title ) {
7357 this.title = OO.ui.resolveMsg( title );
7358 this.updateTitle();
7359 return this;
7360 };
7361
7362 /**
7363 * Get the tool #title.
7364 *
7365 * @return {string} Title text
7366 */
7367 OO.ui.Tool.prototype.getTitle = function () {
7368 return this.title;
7369 };
7370
7371 /**
7372 * Get the tool's symbolic name.
7373 *
7374 * @return {string} Symbolic name of tool
7375 */
7376 OO.ui.Tool.prototype.getName = function () {
7377 return this.constructor.static.name;
7378 };
7379
7380 /**
7381 * Update the title.
7382 */
7383 OO.ui.Tool.prototype.updateTitle = function () {
7384 var titleTooltips = this.toolGroup.constructor.static.titleTooltips,
7385 accelTooltips = this.toolGroup.constructor.static.accelTooltips,
7386 accel = this.toolbar.getToolAccelerator( this.constructor.static.name ),
7387 tooltipParts = [];
7388
7389 this.$title.text( this.title );
7390 this.$accel.text( accel );
7391
7392 if ( titleTooltips && typeof this.title === 'string' && this.title.length ) {
7393 tooltipParts.push( this.title );
7394 }
7395 if ( accelTooltips && typeof accel === 'string' && accel.length ) {
7396 tooltipParts.push( accel );
7397 }
7398 if ( tooltipParts.length ) {
7399 this.$link.attr( 'title', tooltipParts.join( ' ' ) );
7400 } else {
7401 this.$link.removeAttr( 'title' );
7402 }
7403 };
7404
7405 /**
7406 * Destroy tool.
7407 *
7408 * Destroying the tool removes all event handlers and the tool’s DOM elements.
7409 * Call this method whenever you are done using a tool.
7410 */
7411 OO.ui.Tool.prototype.destroy = function () {
7412 this.toolbar.disconnect( this );
7413 this.$element.remove();
7414 };
7415
7416 /**
7417 * Toolbars are complex interface components that permit users to easily access a variety
7418 * of {@link OO.ui.Tool tools} (e.g., formatting commands) and actions, which are additional commands that are
7419 * part of the toolbar, but not configured as tools.
7420 *
7421 * Individual tools are customized and then registered with a {@link OO.ui.ToolFactory tool factory}, which creates
7422 * the tools on demand. Each tool has a symbolic name (used when registering the tool), a title (e.g., ‘Insert
7423 * picture’), and an icon.
7424 *
7425 * Individual tools are organized in {@link OO.ui.ToolGroup toolgroups}, which can be {@link OO.ui.MenuToolGroup menus}
7426 * of tools, {@link OO.ui.ListToolGroup lists} of tools, or a single {@link OO.ui.BarToolGroup bar} of tools.
7427 * The arrangement and order of the toolgroups is customized when the toolbar is set up. Tools can be presented in
7428 * any order, but each can only appear once in the toolbar.
7429 *
7430 * The following is an example of a basic toolbar.
7431 *
7432 * @example
7433 * // Example of a toolbar
7434 * // Create the toolbar
7435 * var toolFactory = new OO.ui.ToolFactory();
7436 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
7437 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
7438 *
7439 * // We will be placing status text in this element when tools are used
7440 * var $area = $( '<p>' ).text( 'Toolbar example' );
7441 *
7442 * // Define the tools that we're going to place in our toolbar
7443 *
7444 * // Create a class inheriting from OO.ui.Tool
7445 * function PictureTool() {
7446 * PictureTool.parent.apply( this, arguments );
7447 * }
7448 * OO.inheritClass( PictureTool, OO.ui.Tool );
7449 * // Each tool must have a 'name' (used as an internal identifier, see later) and at least one
7450 * // of 'icon' and 'title' (displayed icon and text).
7451 * PictureTool.static.name = 'picture';
7452 * PictureTool.static.icon = 'picture';
7453 * PictureTool.static.title = 'Insert picture';
7454 * // Defines the action that will happen when this tool is selected (clicked).
7455 * PictureTool.prototype.onSelect = function () {
7456 * $area.text( 'Picture tool clicked!' );
7457 * // Never display this tool as "active" (selected).
7458 * this.setActive( false );
7459 * };
7460 * // Make this tool available in our toolFactory and thus our toolbar
7461 * toolFactory.register( PictureTool );
7462 *
7463 * // Register two more tools, nothing interesting here
7464 * function SettingsTool() {
7465 * SettingsTool.parent.apply( this, arguments );
7466 * }
7467 * OO.inheritClass( SettingsTool, OO.ui.Tool );
7468 * SettingsTool.static.name = 'settings';
7469 * SettingsTool.static.icon = 'settings';
7470 * SettingsTool.static.title = 'Change settings';
7471 * SettingsTool.prototype.onSelect = function () {
7472 * $area.text( 'Settings tool clicked!' );
7473 * this.setActive( false );
7474 * };
7475 * toolFactory.register( SettingsTool );
7476 *
7477 * // Register two more tools, nothing interesting here
7478 * function StuffTool() {
7479 * StuffTool.parent.apply( this, arguments );
7480 * }
7481 * OO.inheritClass( StuffTool, OO.ui.Tool );
7482 * StuffTool.static.name = 'stuff';
7483 * StuffTool.static.icon = 'ellipsis';
7484 * StuffTool.static.title = 'More stuff';
7485 * StuffTool.prototype.onSelect = function () {
7486 * $area.text( 'More stuff tool clicked!' );
7487 * this.setActive( false );
7488 * };
7489 * toolFactory.register( StuffTool );
7490 *
7491 * // This is a PopupTool. Rather than having a custom 'onSelect' action, it will display a
7492 * // little popup window (a PopupWidget).
7493 * function HelpTool( toolGroup, config ) {
7494 * OO.ui.PopupTool.call( this, toolGroup, $.extend( { popup: {
7495 * padded: true,
7496 * label: 'Help',
7497 * head: true
7498 * } }, config ) );
7499 * this.popup.$body.append( '<p>I am helpful!</p>' );
7500 * }
7501 * OO.inheritClass( HelpTool, OO.ui.PopupTool );
7502 * HelpTool.static.name = 'help';
7503 * HelpTool.static.icon = 'help';
7504 * HelpTool.static.title = 'Help';
7505 * toolFactory.register( HelpTool );
7506 *
7507 * // Finally define which tools and in what order appear in the toolbar. Each tool may only be
7508 * // used once (but not all defined tools must be used).
7509 * toolbar.setup( [
7510 * {
7511 * // 'bar' tool groups display tools' icons only, side-by-side.
7512 * type: 'bar',
7513 * include: [ 'picture', 'help' ]
7514 * },
7515 * {
7516 * // 'list' tool groups display both the titles and icons, in a dropdown list.
7517 * type: 'list',
7518 * indicator: 'down',
7519 * label: 'More',
7520 * include: [ 'settings', 'stuff' ]
7521 * }
7522 * // Note how the tools themselves are toolgroup-agnostic - the same tool can be displayed
7523 * // either in a 'list' or a 'bar'. There is a 'menu' tool group too, not showcased here,
7524 * // since it's more complicated to use. (See the next example snippet on this page.)
7525 * ] );
7526 *
7527 * // Create some UI around the toolbar and place it in the document
7528 * var frame = new OO.ui.PanelLayout( {
7529 * expanded: false,
7530 * framed: true
7531 * } );
7532 * var contentFrame = new OO.ui.PanelLayout( {
7533 * expanded: false,
7534 * padded: true
7535 * } );
7536 * frame.$element.append(
7537 * toolbar.$element,
7538 * contentFrame.$element.append( $area )
7539 * );
7540 * $( 'body' ).append( frame.$element );
7541 *
7542 * // Here is where the toolbar is actually built. This must be done after inserting it into the
7543 * // document.
7544 * toolbar.initialize();
7545 *
7546 * The following example extends the previous one to illustrate 'menu' toolgroups and the usage of
7547 * 'updateState' event.
7548 *
7549 * @example
7550 * // Create the toolbar
7551 * var toolFactory = new OO.ui.ToolFactory();
7552 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
7553 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
7554 *
7555 * // We will be placing status text in this element when tools are used
7556 * var $area = $( '<p>' ).text( 'Toolbar example' );
7557 *
7558 * // Define the tools that we're going to place in our toolbar
7559 *
7560 * // Create a class inheriting from OO.ui.Tool
7561 * function PictureTool() {
7562 * PictureTool.parent.apply( this, arguments );
7563 * }
7564 * OO.inheritClass( PictureTool, OO.ui.Tool );
7565 * // Each tool must have a 'name' (used as an internal identifier, see later) and at least one
7566 * // of 'icon' and 'title' (displayed icon and text).
7567 * PictureTool.static.name = 'picture';
7568 * PictureTool.static.icon = 'picture';
7569 * PictureTool.static.title = 'Insert picture';
7570 * // Defines the action that will happen when this tool is selected (clicked).
7571 * PictureTool.prototype.onSelect = function () {
7572 * $area.text( 'Picture tool clicked!' );
7573 * // Never display this tool as "active" (selected).
7574 * this.setActive( false );
7575 * };
7576 * // The toolbar can be synchronized with the state of some external stuff, like a text
7577 * // editor's editing area, highlighting the tools (e.g. a 'bold' tool would be shown as active
7578 * // when the text cursor was inside bolded text). Here we simply disable this feature.
7579 * PictureTool.prototype.onUpdateState = function () {
7580 * };
7581 * // Make this tool available in our toolFactory and thus our toolbar
7582 * toolFactory.register( PictureTool );
7583 *
7584 * // Register two more tools, nothing interesting here
7585 * function SettingsTool() {
7586 * SettingsTool.parent.apply( this, arguments );
7587 * this.reallyActive = false;
7588 * }
7589 * OO.inheritClass( SettingsTool, OO.ui.Tool );
7590 * SettingsTool.static.name = 'settings';
7591 * SettingsTool.static.icon = 'settings';
7592 * SettingsTool.static.title = 'Change settings';
7593 * SettingsTool.prototype.onSelect = function () {
7594 * $area.text( 'Settings tool clicked!' );
7595 * // Toggle the active state on each click
7596 * this.reallyActive = !this.reallyActive;
7597 * this.setActive( this.reallyActive );
7598 * // To update the menu label
7599 * this.toolbar.emit( 'updateState' );
7600 * };
7601 * SettingsTool.prototype.onUpdateState = function () {
7602 * };
7603 * toolFactory.register( SettingsTool );
7604 *
7605 * // Register two more tools, nothing interesting here
7606 * function StuffTool() {
7607 * StuffTool.parent.apply( this, arguments );
7608 * this.reallyActive = false;
7609 * }
7610 * OO.inheritClass( StuffTool, OO.ui.Tool );
7611 * StuffTool.static.name = 'stuff';
7612 * StuffTool.static.icon = 'ellipsis';
7613 * StuffTool.static.title = 'More stuff';
7614 * StuffTool.prototype.onSelect = function () {
7615 * $area.text( 'More stuff tool clicked!' );
7616 * // Toggle the active state on each click
7617 * this.reallyActive = !this.reallyActive;
7618 * this.setActive( this.reallyActive );
7619 * // To update the menu label
7620 * this.toolbar.emit( 'updateState' );
7621 * };
7622 * StuffTool.prototype.onUpdateState = function () {
7623 * };
7624 * toolFactory.register( StuffTool );
7625 *
7626 * // This is a PopupTool. Rather than having a custom 'onSelect' action, it will display a
7627 * // little popup window (a PopupWidget). 'onUpdateState' is also already implemented.
7628 * function HelpTool( toolGroup, config ) {
7629 * OO.ui.PopupTool.call( this, toolGroup, $.extend( { popup: {
7630 * padded: true,
7631 * label: 'Help',
7632 * head: true
7633 * } }, config ) );
7634 * this.popup.$body.append( '<p>I am helpful!</p>' );
7635 * }
7636 * OO.inheritClass( HelpTool, OO.ui.PopupTool );
7637 * HelpTool.static.name = 'help';
7638 * HelpTool.static.icon = 'help';
7639 * HelpTool.static.title = 'Help';
7640 * toolFactory.register( HelpTool );
7641 *
7642 * // Finally define which tools and in what order appear in the toolbar. Each tool may only be
7643 * // used once (but not all defined tools must be used).
7644 * toolbar.setup( [
7645 * {
7646 * // 'bar' tool groups display tools' icons only, side-by-side.
7647 * type: 'bar',
7648 * include: [ 'picture', 'help' ]
7649 * },
7650 * {
7651 * // 'menu' tool groups display both the titles and icons, in a dropdown menu.
7652 * // Menu label indicates which items are selected.
7653 * type: 'menu',
7654 * indicator: 'down',
7655 * include: [ 'settings', 'stuff' ]
7656 * }
7657 * ] );
7658 *
7659 * // Create some UI around the toolbar and place it in the document
7660 * var frame = new OO.ui.PanelLayout( {
7661 * expanded: false,
7662 * framed: true
7663 * } );
7664 * var contentFrame = new OO.ui.PanelLayout( {
7665 * expanded: false,
7666 * padded: true
7667 * } );
7668 * frame.$element.append(
7669 * toolbar.$element,
7670 * contentFrame.$element.append( $area )
7671 * );
7672 * $( 'body' ).append( frame.$element );
7673 *
7674 * // Here is where the toolbar is actually built. This must be done after inserting it into the
7675 * // document.
7676 * toolbar.initialize();
7677 * toolbar.emit( 'updateState' );
7678 *
7679 * @class
7680 * @extends OO.ui.Element
7681 * @mixins OO.EventEmitter
7682 * @mixins OO.ui.mixin.GroupElement
7683 *
7684 * @constructor
7685 * @param {OO.ui.ToolFactory} toolFactory Factory for creating tools
7686 * @param {OO.ui.ToolGroupFactory} toolGroupFactory Factory for creating toolgroups
7687 * @param {Object} [config] Configuration options
7688 * @cfg {boolean} [actions] Add an actions section to the toolbar. Actions are commands that are included
7689 * in the toolbar, but are not configured as tools. By default, actions are displayed on the right side of
7690 * the toolbar.
7691 * @cfg {boolean} [shadow] Add a shadow below the toolbar.
7692 */
7693 OO.ui.Toolbar = function OoUiToolbar( toolFactory, toolGroupFactory, config ) {
7694 // Allow passing positional parameters inside the config object
7695 if ( OO.isPlainObject( toolFactory ) && config === undefined ) {
7696 config = toolFactory;
7697 toolFactory = config.toolFactory;
7698 toolGroupFactory = config.toolGroupFactory;
7699 }
7700
7701 // Configuration initialization
7702 config = config || {};
7703
7704 // Parent constructor
7705 OO.ui.Toolbar.parent.call( this, config );
7706
7707 // Mixin constructors
7708 OO.EventEmitter.call( this );
7709 OO.ui.mixin.GroupElement.call( this, config );
7710
7711 // Properties
7712 this.toolFactory = toolFactory;
7713 this.toolGroupFactory = toolGroupFactory;
7714 this.groups = [];
7715 this.tools = {};
7716 this.$bar = $( '<div>' );
7717 this.$actions = $( '<div>' );
7718 this.initialized = false;
7719 this.onWindowResizeHandler = this.onWindowResize.bind( this );
7720
7721 // Events
7722 this.$element
7723 .add( this.$bar ).add( this.$group ).add( this.$actions )
7724 .on( 'mousedown keydown', this.onPointerDown.bind( this ) );
7725
7726 // Initialization
7727 this.$group.addClass( 'oo-ui-toolbar-tools' );
7728 if ( config.actions ) {
7729 this.$bar.append( this.$actions.addClass( 'oo-ui-toolbar-actions' ) );
7730 }
7731 this.$bar
7732 .addClass( 'oo-ui-toolbar-bar' )
7733 .append( this.$group, '<div style="clear:both"></div>' );
7734 if ( config.shadow ) {
7735 this.$bar.append( '<div class="oo-ui-toolbar-shadow"></div>' );
7736 }
7737 this.$element.addClass( 'oo-ui-toolbar' ).append( this.$bar );
7738 };
7739
7740 /* Setup */
7741
7742 OO.inheritClass( OO.ui.Toolbar, OO.ui.Element );
7743 OO.mixinClass( OO.ui.Toolbar, OO.EventEmitter );
7744 OO.mixinClass( OO.ui.Toolbar, OO.ui.mixin.GroupElement );
7745
7746 /* Methods */
7747
7748 /**
7749 * Get the tool factory.
7750 *
7751 * @return {OO.ui.ToolFactory} Tool factory
7752 */
7753 OO.ui.Toolbar.prototype.getToolFactory = function () {
7754 return this.toolFactory;
7755 };
7756
7757 /**
7758 * Get the toolgroup factory.
7759 *
7760 * @return {OO.Factory} Toolgroup factory
7761 */
7762 OO.ui.Toolbar.prototype.getToolGroupFactory = function () {
7763 return this.toolGroupFactory;
7764 };
7765
7766 /**
7767 * Handles mouse down events.
7768 *
7769 * @private
7770 * @param {jQuery.Event} e Mouse down event
7771 */
7772 OO.ui.Toolbar.prototype.onPointerDown = function ( e ) {
7773 var $closestWidgetToEvent = $( e.target ).closest( '.oo-ui-widget' ),
7774 $closestWidgetToToolbar = this.$element.closest( '.oo-ui-widget' );
7775 if ( !$closestWidgetToEvent.length || $closestWidgetToEvent[ 0 ] === $closestWidgetToToolbar[ 0 ] ) {
7776 return false;
7777 }
7778 };
7779
7780 /**
7781 * Handle window resize event.
7782 *
7783 * @private
7784 * @param {jQuery.Event} e Window resize event
7785 */
7786 OO.ui.Toolbar.prototype.onWindowResize = function () {
7787 this.$element.toggleClass(
7788 'oo-ui-toolbar-narrow',
7789 this.$bar.width() <= this.narrowThreshold
7790 );
7791 };
7792
7793 /**
7794 * Sets up handles and preloads required information for the toolbar to work.
7795 * This must be called after it is attached to a visible document and before doing anything else.
7796 */
7797 OO.ui.Toolbar.prototype.initialize = function () {
7798 if ( !this.initialized ) {
7799 this.initialized = true;
7800 this.narrowThreshold = this.$group.width() + this.$actions.width();
7801 $( this.getElementWindow() ).on( 'resize', this.onWindowResizeHandler );
7802 this.onWindowResize();
7803 }
7804 };
7805
7806 /**
7807 * Set up the toolbar.
7808 *
7809 * The toolbar is set up with a list of toolgroup configurations that specify the type of
7810 * toolgroup ({@link OO.ui.BarToolGroup bar}, {@link OO.ui.MenuToolGroup menu}, or {@link OO.ui.ListToolGroup list})
7811 * to add and which tools to include, exclude, promote, or demote within that toolgroup. Please
7812 * see {@link OO.ui.ToolGroup toolgroups} for more information about including tools in toolgroups.
7813 *
7814 * @param {Object.<string,Array>} groups List of toolgroup configurations
7815 * @param {Array|string} [groups.include] Tools to include in the toolgroup
7816 * @param {Array|string} [groups.exclude] Tools to exclude from the toolgroup
7817 * @param {Array|string} [groups.promote] Tools to promote to the beginning of the toolgroup
7818 * @param {Array|string} [groups.demote] Tools to demote to the end of the toolgroup
7819 */
7820 OO.ui.Toolbar.prototype.setup = function ( groups ) {
7821 var i, len, type, group,
7822 items = [],
7823 defaultType = 'bar';
7824
7825 // Cleanup previous groups
7826 this.reset();
7827
7828 // Build out new groups
7829 for ( i = 0, len = groups.length; i < len; i++ ) {
7830 group = groups[ i ];
7831 if ( group.include === '*' ) {
7832 // Apply defaults to catch-all groups
7833 if ( group.type === undefined ) {
7834 group.type = 'list';
7835 }
7836 if ( group.label === undefined ) {
7837 group.label = OO.ui.msg( 'ooui-toolbar-more' );
7838 }
7839 }
7840 // Check type has been registered
7841 type = this.getToolGroupFactory().lookup( group.type ) ? group.type : defaultType;
7842 items.push(
7843 this.getToolGroupFactory().create( type, this, group )
7844 );
7845 }
7846 this.addItems( items );
7847 };
7848
7849 /**
7850 * Remove all tools and toolgroups from the toolbar.
7851 */
7852 OO.ui.Toolbar.prototype.reset = function () {
7853 var i, len;
7854
7855 this.groups = [];
7856 this.tools = {};
7857 for ( i = 0, len = this.items.length; i < len; i++ ) {
7858 this.items[ i ].destroy();
7859 }
7860 this.clearItems();
7861 };
7862
7863 /**
7864 * Destroy the toolbar.
7865 *
7866 * Destroying the toolbar removes all event handlers and DOM elements that constitute the toolbar. Call
7867 * this method whenever you are done using a toolbar.
7868 */
7869 OO.ui.Toolbar.prototype.destroy = function () {
7870 $( this.getElementWindow() ).off( 'resize', this.onWindowResizeHandler );
7871 this.reset();
7872 this.$element.remove();
7873 };
7874
7875 /**
7876 * Check if the tool is available.
7877 *
7878 * Available tools are ones that have not yet been added to the toolbar.
7879 *
7880 * @param {string} name Symbolic name of tool
7881 * @return {boolean} Tool is available
7882 */
7883 OO.ui.Toolbar.prototype.isToolAvailable = function ( name ) {
7884 return !this.tools[ name ];
7885 };
7886
7887 /**
7888 * Prevent tool from being used again.
7889 *
7890 * @param {OO.ui.Tool} tool Tool to reserve
7891 */
7892 OO.ui.Toolbar.prototype.reserveTool = function ( tool ) {
7893 this.tools[ tool.getName() ] = tool;
7894 };
7895
7896 /**
7897 * Allow tool to be used again.
7898 *
7899 * @param {OO.ui.Tool} tool Tool to release
7900 */
7901 OO.ui.Toolbar.prototype.releaseTool = function ( tool ) {
7902 delete this.tools[ tool.getName() ];
7903 };
7904
7905 /**
7906 * Get accelerator label for tool.
7907 *
7908 * The OOjs UI library does not contain an accelerator system, but this is the hook for one. To
7909 * use an accelerator system, subclass the toolbar and override this method, which is meant to return a label
7910 * that describes the accelerator keys for the tool passed (by symbolic name) to the method.
7911 *
7912 * @param {string} name Symbolic name of tool
7913 * @return {string|undefined} Tool accelerator label if available
7914 */
7915 OO.ui.Toolbar.prototype.getToolAccelerator = function () {
7916 return undefined;
7917 };
7918
7919 /**
7920 * ToolGroups are collections of {@link OO.ui.Tool tools} that are used in a {@link OO.ui.Toolbar toolbar}.
7921 * The type of toolgroup ({@link OO.ui.ListToolGroup list}, {@link OO.ui.BarToolGroup bar}, or {@link OO.ui.MenuToolGroup menu})
7922 * to which a tool belongs determines how the tool is arranged and displayed in the toolbar. Toolgroups
7923 * themselves are created on demand with a {@link OO.ui.ToolGroupFactory toolgroup factory}.
7924 *
7925 * Toolgroups can contain individual tools, groups of tools, or all available tools:
7926 *
7927 * To include an individual tool (or array of individual tools), specify tools by symbolic name:
7928 *
7929 * include: [ 'tool-name' ] or [ { name: 'tool-name' }]
7930 *
7931 * 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.)
7932 *
7933 * include: [ { group: 'group-name' } ]
7934 *
7935 * To include all tools that are not yet assigned to a toolgroup, use the catch-all selector, an asterisk (*):
7936 *
7937 * include: '*'
7938 *
7939 * See {@link OO.ui.Toolbar toolbars} for a full example. For more information about toolbars in general,
7940 * please see the [OOjs UI documentation on MediaWiki][1].
7941 *
7942 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
7943 *
7944 * @abstract
7945 * @class
7946 * @extends OO.ui.Widget
7947 * @mixins OO.ui.mixin.GroupElement
7948 *
7949 * @constructor
7950 * @param {OO.ui.Toolbar} toolbar
7951 * @param {Object} [config] Configuration options
7952 * @cfg {Array|string} [include=[]] List of tools to include in the toolgroup.
7953 * @cfg {Array|string} [exclude=[]] List of tools to exclude from the toolgroup.
7954 * @cfg {Array|string} [promote=[]] List of tools to promote to the beginning of the toolgroup.
7955 * @cfg {Array|string} [demote=[]] List of tools to demote to the end of the toolgroup.
7956 * This setting is particularly useful when tools have been added to the toolgroup
7957 * en masse (e.g., via the catch-all selector).
7958 */
7959 OO.ui.ToolGroup = function OoUiToolGroup( toolbar, config ) {
7960 // Allow passing positional parameters inside the config object
7961 if ( OO.isPlainObject( toolbar ) && config === undefined ) {
7962 config = toolbar;
7963 toolbar = config.toolbar;
7964 }
7965
7966 // Configuration initialization
7967 config = config || {};
7968
7969 // Parent constructor
7970 OO.ui.ToolGroup.parent.call( this, config );
7971
7972 // Mixin constructors
7973 OO.ui.mixin.GroupElement.call( this, config );
7974
7975 // Properties
7976 this.toolbar = toolbar;
7977 this.tools = {};
7978 this.pressed = null;
7979 this.autoDisabled = false;
7980 this.include = config.include || [];
7981 this.exclude = config.exclude || [];
7982 this.promote = config.promote || [];
7983 this.demote = config.demote || [];
7984 this.onCapturedMouseKeyUpHandler = this.onCapturedMouseKeyUp.bind( this );
7985
7986 // Events
7987 this.$element.on( {
7988 mousedown: this.onMouseKeyDown.bind( this ),
7989 mouseup: this.onMouseKeyUp.bind( this ),
7990 keydown: this.onMouseKeyDown.bind( this ),
7991 keyup: this.onMouseKeyUp.bind( this ),
7992 focus: this.onMouseOverFocus.bind( this ),
7993 blur: this.onMouseOutBlur.bind( this ),
7994 mouseover: this.onMouseOverFocus.bind( this ),
7995 mouseout: this.onMouseOutBlur.bind( this )
7996 } );
7997 this.toolbar.getToolFactory().connect( this, { register: 'onToolFactoryRegister' } );
7998 this.aggregate( { disable: 'itemDisable' } );
7999 this.connect( this, { itemDisable: 'updateDisabled' } );
8000
8001 // Initialization
8002 this.$group.addClass( 'oo-ui-toolGroup-tools' );
8003 this.$element
8004 .addClass( 'oo-ui-toolGroup' )
8005 .append( this.$group );
8006 this.populate();
8007 };
8008
8009 /* Setup */
8010
8011 OO.inheritClass( OO.ui.ToolGroup, OO.ui.Widget );
8012 OO.mixinClass( OO.ui.ToolGroup, OO.ui.mixin.GroupElement );
8013
8014 /* Events */
8015
8016 /**
8017 * @event update
8018 */
8019
8020 /* Static Properties */
8021
8022 /**
8023 * Show labels in tooltips.
8024 *
8025 * @static
8026 * @inheritable
8027 * @property {boolean}
8028 */
8029 OO.ui.ToolGroup.static.titleTooltips = false;
8030
8031 /**
8032 * Show acceleration labels in tooltips.
8033 *
8034 * Note: The OOjs UI library does not include an accelerator system, but does contain
8035 * a hook for one. To use an accelerator system, subclass the {@link OO.ui.Toolbar toolbar} and
8036 * override the {@link OO.ui.Toolbar#getToolAccelerator getToolAccelerator} method, which is
8037 * meant to return a label that describes the accelerator keys for a given tool (e.g., 'Ctrl + M').
8038 *
8039 * @static
8040 * @inheritable
8041 * @property {boolean}
8042 */
8043 OO.ui.ToolGroup.static.accelTooltips = false;
8044
8045 /**
8046 * Automatically disable the toolgroup when all tools are disabled
8047 *
8048 * @static
8049 * @inheritable
8050 * @property {boolean}
8051 */
8052 OO.ui.ToolGroup.static.autoDisable = true;
8053
8054 /* Methods */
8055
8056 /**
8057 * @inheritdoc
8058 */
8059 OO.ui.ToolGroup.prototype.isDisabled = function () {
8060 return this.autoDisabled || OO.ui.ToolGroup.parent.prototype.isDisabled.apply( this, arguments );
8061 };
8062
8063 /**
8064 * @inheritdoc
8065 */
8066 OO.ui.ToolGroup.prototype.updateDisabled = function () {
8067 var i, item, allDisabled = true;
8068
8069 if ( this.constructor.static.autoDisable ) {
8070 for ( i = this.items.length - 1; i >= 0; i-- ) {
8071 item = this.items[ i ];
8072 if ( !item.isDisabled() ) {
8073 allDisabled = false;
8074 break;
8075 }
8076 }
8077 this.autoDisabled = allDisabled;
8078 }
8079 OO.ui.ToolGroup.parent.prototype.updateDisabled.apply( this, arguments );
8080 };
8081
8082 /**
8083 * Handle mouse down and key down events.
8084 *
8085 * @protected
8086 * @param {jQuery.Event} e Mouse down or key down event
8087 */
8088 OO.ui.ToolGroup.prototype.onMouseKeyDown = function ( e ) {
8089 if (
8090 !this.isDisabled() &&
8091 ( e.which === 1 || e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
8092 ) {
8093 this.pressed = this.getTargetTool( e );
8094 if ( this.pressed ) {
8095 this.pressed.setActive( true );
8096 OO.ui.addCaptureEventListener( this.getElementDocument(), 'mouseup', this.onCapturedMouseKeyUpHandler );
8097 OO.ui.addCaptureEventListener( this.getElementDocument(), 'keyup', this.onCapturedMouseKeyUpHandler );
8098 }
8099 return false;
8100 }
8101 };
8102
8103 /**
8104 * Handle captured mouse up and key up events.
8105 *
8106 * @protected
8107 * @param {Event} e Mouse up or key up event
8108 */
8109 OO.ui.ToolGroup.prototype.onCapturedMouseKeyUp = function ( e ) {
8110 OO.ui.removeCaptureEventListener( this.getElementDocument(), 'mouseup', this.onCapturedMouseKeyUpHandler );
8111 OO.ui.removeCaptureEventListener( this.getElementDocument(), 'keyup', this.onCapturedMouseKeyUpHandler );
8112 // onMouseKeyUp may be called a second time, depending on where the mouse is when the button is
8113 // released, but since `this.pressed` will no longer be true, the second call will be ignored.
8114 this.onMouseKeyUp( e );
8115 };
8116
8117 /**
8118 * Handle mouse up and key up events.
8119 *
8120 * @protected
8121 * @param {jQuery.Event} e Mouse up or key up event
8122 */
8123 OO.ui.ToolGroup.prototype.onMouseKeyUp = function ( e ) {
8124 var tool = this.getTargetTool( e );
8125
8126 if (
8127 !this.isDisabled() && this.pressed && this.pressed === tool &&
8128 ( e.which === 1 || e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
8129 ) {
8130 this.pressed.onSelect();
8131 this.pressed = null;
8132 return false;
8133 }
8134
8135 this.pressed = null;
8136 };
8137
8138 /**
8139 * Handle mouse over and focus events.
8140 *
8141 * @protected
8142 * @param {jQuery.Event} e Mouse over or focus event
8143 */
8144 OO.ui.ToolGroup.prototype.onMouseOverFocus = function ( e ) {
8145 var tool = this.getTargetTool( e );
8146
8147 if ( this.pressed && this.pressed === tool ) {
8148 this.pressed.setActive( true );
8149 }
8150 };
8151
8152 /**
8153 * Handle mouse out and blur events.
8154 *
8155 * @protected
8156 * @param {jQuery.Event} e Mouse out or blur event
8157 */
8158 OO.ui.ToolGroup.prototype.onMouseOutBlur = function ( e ) {
8159 var tool = this.getTargetTool( e );
8160
8161 if ( this.pressed && this.pressed === tool ) {
8162 this.pressed.setActive( false );
8163 }
8164 };
8165
8166 /**
8167 * Get the closest tool to a jQuery.Event.
8168 *
8169 * Only tool links are considered, which prevents other elements in the tool such as popups from
8170 * triggering tool group interactions.
8171 *
8172 * @private
8173 * @param {jQuery.Event} e
8174 * @return {OO.ui.Tool|null} Tool, `null` if none was found
8175 */
8176 OO.ui.ToolGroup.prototype.getTargetTool = function ( e ) {
8177 var tool,
8178 $item = $( e.target ).closest( '.oo-ui-tool-link' );
8179
8180 if ( $item.length ) {
8181 tool = $item.parent().data( 'oo-ui-tool' );
8182 }
8183
8184 return tool && !tool.isDisabled() ? tool : null;
8185 };
8186
8187 /**
8188 * Handle tool registry register events.
8189 *
8190 * If a tool is registered after the group is created, we must repopulate the list to account for:
8191 *
8192 * - a tool being added that may be included
8193 * - a tool already included being overridden
8194 *
8195 * @protected
8196 * @param {string} name Symbolic name of tool
8197 */
8198 OO.ui.ToolGroup.prototype.onToolFactoryRegister = function () {
8199 this.populate();
8200 };
8201
8202 /**
8203 * Get the toolbar that contains the toolgroup.
8204 *
8205 * @return {OO.ui.Toolbar} Toolbar that contains the toolgroup
8206 */
8207 OO.ui.ToolGroup.prototype.getToolbar = function () {
8208 return this.toolbar;
8209 };
8210
8211 /**
8212 * Add and remove tools based on configuration.
8213 */
8214 OO.ui.ToolGroup.prototype.populate = function () {
8215 var i, len, name, tool,
8216 toolFactory = this.toolbar.getToolFactory(),
8217 names = {},
8218 add = [],
8219 remove = [],
8220 list = this.toolbar.getToolFactory().getTools(
8221 this.include, this.exclude, this.promote, this.demote
8222 );
8223
8224 // Build a list of needed tools
8225 for ( i = 0, len = list.length; i < len; i++ ) {
8226 name = list[ i ];
8227 if (
8228 // Tool exists
8229 toolFactory.lookup( name ) &&
8230 // Tool is available or is already in this group
8231 ( this.toolbar.isToolAvailable( name ) || this.tools[ name ] )
8232 ) {
8233 // Hack to prevent infinite recursion via ToolGroupTool. We need to reserve the tool before
8234 // creating it, but we can't call reserveTool() yet because we haven't created the tool.
8235 this.toolbar.tools[ name ] = true;
8236 tool = this.tools[ name ];
8237 if ( !tool ) {
8238 // Auto-initialize tools on first use
8239 this.tools[ name ] = tool = toolFactory.create( name, this );
8240 tool.updateTitle();
8241 }
8242 this.toolbar.reserveTool( tool );
8243 add.push( tool );
8244 names[ name ] = true;
8245 }
8246 }
8247 // Remove tools that are no longer needed
8248 for ( name in this.tools ) {
8249 if ( !names[ name ] ) {
8250 this.tools[ name ].destroy();
8251 this.toolbar.releaseTool( this.tools[ name ] );
8252 remove.push( this.tools[ name ] );
8253 delete this.tools[ name ];
8254 }
8255 }
8256 if ( remove.length ) {
8257 this.removeItems( remove );
8258 }
8259 // Update emptiness state
8260 if ( add.length ) {
8261 this.$element.removeClass( 'oo-ui-toolGroup-empty' );
8262 } else {
8263 this.$element.addClass( 'oo-ui-toolGroup-empty' );
8264 }
8265 // Re-add tools (moving existing ones to new locations)
8266 this.addItems( add );
8267 // Disabled state may depend on items
8268 this.updateDisabled();
8269 };
8270
8271 /**
8272 * Destroy toolgroup.
8273 */
8274 OO.ui.ToolGroup.prototype.destroy = function () {
8275 var name;
8276
8277 this.clearItems();
8278 this.toolbar.getToolFactory().disconnect( this );
8279 for ( name in this.tools ) {
8280 this.toolbar.releaseTool( this.tools[ name ] );
8281 this.tools[ name ].disconnect( this ).destroy();
8282 delete this.tools[ name ];
8283 }
8284 this.$element.remove();
8285 };
8286
8287 /**
8288 * MessageDialogs display a confirmation or alert message. By default, the rendered dialog box
8289 * consists of a header that contains the dialog title, a body with the message, and a footer that
8290 * contains any {@link OO.ui.ActionWidget action widgets}. The MessageDialog class is the only type
8291 * of {@link OO.ui.Dialog dialog} that is usually instantiated directly.
8292 *
8293 * There are two basic types of message dialogs, confirmation and alert:
8294 *
8295 * - **confirmation**: the dialog title describes what a progressive action will do and the message provides
8296 * more details about the consequences.
8297 * - **alert**: the dialog title describes which event occurred and the message provides more information
8298 * about why the event occurred.
8299 *
8300 * The MessageDialog class specifies two actions: ‘accept’, the primary
8301 * action (e.g., ‘ok’) and ‘reject,’ the safe action (e.g., ‘cancel’). Both will close the window,
8302 * passing along the selected action.
8303 *
8304 * For more information and examples, please see the [OOjs UI documentation on MediaWiki][1].
8305 *
8306 * @example
8307 * // Example: Creating and opening a message dialog window.
8308 * var messageDialog = new OO.ui.MessageDialog();
8309 *
8310 * // Create and append a window manager.
8311 * var windowManager = new OO.ui.WindowManager();
8312 * $( 'body' ).append( windowManager.$element );
8313 * windowManager.addWindows( [ messageDialog ] );
8314 * // Open the window.
8315 * windowManager.openWindow( messageDialog, {
8316 * title: 'Basic message dialog',
8317 * message: 'This is the message'
8318 * } );
8319 *
8320 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Message_Dialogs
8321 *
8322 * @class
8323 * @extends OO.ui.Dialog
8324 *
8325 * @constructor
8326 * @param {Object} [config] Configuration options
8327 */
8328 OO.ui.MessageDialog = function OoUiMessageDialog( config ) {
8329 // Parent constructor
8330 OO.ui.MessageDialog.parent.call( this, config );
8331
8332 // Properties
8333 this.verticalActionLayout = null;
8334
8335 // Initialization
8336 this.$element.addClass( 'oo-ui-messageDialog' );
8337 };
8338
8339 /* Setup */
8340
8341 OO.inheritClass( OO.ui.MessageDialog, OO.ui.Dialog );
8342
8343 /* Static Properties */
8344
8345 OO.ui.MessageDialog.static.name = 'message';
8346
8347 OO.ui.MessageDialog.static.size = 'small';
8348
8349 OO.ui.MessageDialog.static.verbose = false;
8350
8351 /**
8352 * Dialog title.
8353 *
8354 * The title of a confirmation dialog describes what a progressive action will do. The
8355 * title of an alert dialog describes which event occurred.
8356 *
8357 * @static
8358 * @inheritable
8359 * @property {jQuery|string|Function|null}
8360 */
8361 OO.ui.MessageDialog.static.title = null;
8362
8363 /**
8364 * The message displayed in the dialog body.
8365 *
8366 * A confirmation message describes the consequences of a progressive action. An alert
8367 * message describes why an event occurred.
8368 *
8369 * @static
8370 * @inheritable
8371 * @property {jQuery|string|Function|null}
8372 */
8373 OO.ui.MessageDialog.static.message = null;
8374
8375 OO.ui.MessageDialog.static.actions = [
8376 { action: 'accept', label: OO.ui.deferMsg( 'ooui-dialog-message-accept' ), flags: 'primary' },
8377 { action: 'reject', label: OO.ui.deferMsg( 'ooui-dialog-message-reject' ), flags: 'safe' }
8378 ];
8379
8380 /* Methods */
8381
8382 /**
8383 * @inheritdoc
8384 */
8385 OO.ui.MessageDialog.prototype.setManager = function ( manager ) {
8386 OO.ui.MessageDialog.parent.prototype.setManager.call( this, manager );
8387
8388 // Events
8389 this.manager.connect( this, {
8390 resize: 'onResize'
8391 } );
8392
8393 return this;
8394 };
8395
8396 /**
8397 * @inheritdoc
8398 */
8399 OO.ui.MessageDialog.prototype.onActionResize = function ( action ) {
8400 this.fitActions();
8401 return OO.ui.MessageDialog.parent.prototype.onActionResize.call( this, action );
8402 };
8403
8404 /**
8405 * Handle window resized events.
8406 *
8407 * @private
8408 */
8409 OO.ui.MessageDialog.prototype.onResize = function () {
8410 var dialog = this;
8411 dialog.fitActions();
8412 // Wait for CSS transition to finish and do it again :(
8413 setTimeout( function () {
8414 dialog.fitActions();
8415 }, 300 );
8416 };
8417
8418 /**
8419 * Toggle action layout between vertical and horizontal.
8420 *
8421 * @private
8422 * @param {boolean} [value] Layout actions vertically, omit to toggle
8423 * @chainable
8424 */
8425 OO.ui.MessageDialog.prototype.toggleVerticalActionLayout = function ( value ) {
8426 value = value === undefined ? !this.verticalActionLayout : !!value;
8427
8428 if ( value !== this.verticalActionLayout ) {
8429 this.verticalActionLayout = value;
8430 this.$actions
8431 .toggleClass( 'oo-ui-messageDialog-actions-vertical', value )
8432 .toggleClass( 'oo-ui-messageDialog-actions-horizontal', !value );
8433 }
8434
8435 return this;
8436 };
8437
8438 /**
8439 * @inheritdoc
8440 */
8441 OO.ui.MessageDialog.prototype.getActionProcess = function ( action ) {
8442 if ( action ) {
8443 return new OO.ui.Process( function () {
8444 this.close( { action: action } );
8445 }, this );
8446 }
8447 return OO.ui.MessageDialog.parent.prototype.getActionProcess.call( this, action );
8448 };
8449
8450 /**
8451 * @inheritdoc
8452 *
8453 * @param {Object} [data] Dialog opening data
8454 * @param {jQuery|string|Function|null} [data.title] Description of the action being confirmed
8455 * @param {jQuery|string|Function|null} [data.message] Description of the action's consequence
8456 * @param {boolean} [data.verbose] Message is verbose and should be styled as a long message
8457 * @param {Object[]} [data.actions] List of OO.ui.ActionOptionWidget configuration options for each
8458 * action item
8459 */
8460 OO.ui.MessageDialog.prototype.getSetupProcess = function ( data ) {
8461 data = data || {};
8462
8463 // Parent method
8464 return OO.ui.MessageDialog.parent.prototype.getSetupProcess.call( this, data )
8465 .next( function () {
8466 this.title.setLabel(
8467 data.title !== undefined ? data.title : this.constructor.static.title
8468 );
8469 this.message.setLabel(
8470 data.message !== undefined ? data.message : this.constructor.static.message
8471 );
8472 this.message.$element.toggleClass(
8473 'oo-ui-messageDialog-message-verbose',
8474 data.verbose !== undefined ? data.verbose : this.constructor.static.verbose
8475 );
8476 }, this );
8477 };
8478
8479 /**
8480 * @inheritdoc
8481 */
8482 OO.ui.MessageDialog.prototype.getReadyProcess = function ( data ) {
8483 data = data || {};
8484
8485 // Parent method
8486 return OO.ui.MessageDialog.parent.prototype.getReadyProcess.call( this, data )
8487 .next( function () {
8488 // Focus the primary action button
8489 var actions = this.actions.get();
8490 actions = actions.filter( function ( action ) {
8491 return action.getFlags().indexOf( 'primary' ) > -1;
8492 } );
8493 if ( actions.length > 0 ) {
8494 actions[ 0 ].$button.focus();
8495 }
8496 }, this );
8497 };
8498
8499 /**
8500 * @inheritdoc
8501 */
8502 OO.ui.MessageDialog.prototype.getBodyHeight = function () {
8503 var bodyHeight, oldOverflow,
8504 $scrollable = this.container.$element;
8505
8506 oldOverflow = $scrollable[ 0 ].style.overflow;
8507 $scrollable[ 0 ].style.overflow = 'hidden';
8508
8509 OO.ui.Element.static.reconsiderScrollbars( $scrollable[ 0 ] );
8510
8511 bodyHeight = this.text.$element.outerHeight( true );
8512 $scrollable[ 0 ].style.overflow = oldOverflow;
8513
8514 return bodyHeight;
8515 };
8516
8517 /**
8518 * @inheritdoc
8519 */
8520 OO.ui.MessageDialog.prototype.setDimensions = function ( dim ) {
8521 var $scrollable = this.container.$element;
8522 OO.ui.MessageDialog.parent.prototype.setDimensions.call( this, dim );
8523
8524 // Twiddle the overflow property, otherwise an unnecessary scrollbar will be produced.
8525 // Need to do it after transition completes (250ms), add 50ms just in case.
8526 setTimeout( function () {
8527 var oldOverflow = $scrollable[ 0 ].style.overflow;
8528 $scrollable[ 0 ].style.overflow = 'hidden';
8529
8530 OO.ui.Element.static.reconsiderScrollbars( $scrollable[ 0 ] );
8531
8532 $scrollable[ 0 ].style.overflow = oldOverflow;
8533 }, 300 );
8534
8535 return this;
8536 };
8537
8538 /**
8539 * @inheritdoc
8540 */
8541 OO.ui.MessageDialog.prototype.initialize = function () {
8542 // Parent method
8543 OO.ui.MessageDialog.parent.prototype.initialize.call( this );
8544
8545 // Properties
8546 this.$actions = $( '<div>' );
8547 this.container = new OO.ui.PanelLayout( {
8548 scrollable: true, classes: [ 'oo-ui-messageDialog-container' ]
8549 } );
8550 this.text = new OO.ui.PanelLayout( {
8551 padded: true, expanded: false, classes: [ 'oo-ui-messageDialog-text' ]
8552 } );
8553 this.message = new OO.ui.LabelWidget( {
8554 classes: [ 'oo-ui-messageDialog-message' ]
8555 } );
8556
8557 // Initialization
8558 this.title.$element.addClass( 'oo-ui-messageDialog-title' );
8559 this.$content.addClass( 'oo-ui-messageDialog-content' );
8560 this.container.$element.append( this.text.$element );
8561 this.text.$element.append( this.title.$element, this.message.$element );
8562 this.$body.append( this.container.$element );
8563 this.$actions.addClass( 'oo-ui-messageDialog-actions' );
8564 this.$foot.append( this.$actions );
8565 };
8566
8567 /**
8568 * @inheritdoc
8569 */
8570 OO.ui.MessageDialog.prototype.attachActions = function () {
8571 var i, len, other, special, others;
8572
8573 // Parent method
8574 OO.ui.MessageDialog.parent.prototype.attachActions.call( this );
8575
8576 special = this.actions.getSpecial();
8577 others = this.actions.getOthers();
8578
8579 if ( special.safe ) {
8580 this.$actions.append( special.safe.$element );
8581 special.safe.toggleFramed( false );
8582 }
8583 if ( others.length ) {
8584 for ( i = 0, len = others.length; i < len; i++ ) {
8585 other = others[ i ];
8586 this.$actions.append( other.$element );
8587 other.toggleFramed( false );
8588 }
8589 }
8590 if ( special.primary ) {
8591 this.$actions.append( special.primary.$element );
8592 special.primary.toggleFramed( false );
8593 }
8594
8595 if ( !this.isOpening() ) {
8596 // If the dialog is currently opening, this will be called automatically soon.
8597 // This also calls #fitActions.
8598 this.updateSize();
8599 }
8600 };
8601
8602 /**
8603 * Fit action actions into columns or rows.
8604 *
8605 * Columns will be used if all labels can fit without overflow, otherwise rows will be used.
8606 *
8607 * @private
8608 */
8609 OO.ui.MessageDialog.prototype.fitActions = function () {
8610 var i, len, action,
8611 previous = this.verticalActionLayout,
8612 actions = this.actions.get();
8613
8614 // Detect clipping
8615 this.toggleVerticalActionLayout( false );
8616 for ( i = 0, len = actions.length; i < len; i++ ) {
8617 action = actions[ i ];
8618 if ( action.$element.innerWidth() < action.$label.outerWidth( true ) ) {
8619 this.toggleVerticalActionLayout( true );
8620 break;
8621 }
8622 }
8623
8624 // Move the body out of the way of the foot
8625 this.$body.css( 'bottom', this.$foot.outerHeight( true ) );
8626
8627 if ( this.verticalActionLayout !== previous ) {
8628 // We changed the layout, window height might need to be updated.
8629 this.updateSize();
8630 }
8631 };
8632
8633 /**
8634 * ProcessDialog windows encapsulate a {@link OO.ui.Process process} and all of the code necessary
8635 * to complete it. If the process terminates with an error, a customizable {@link OO.ui.Error error
8636 * interface} alerts users to the trouble, permitting the user to dismiss the error and try again when
8637 * relevant. The ProcessDialog class is always extended and customized with the actions and content
8638 * required for each process.
8639 *
8640 * The process dialog box consists of a header that visually represents the ‘working’ state of long
8641 * processes with an animation. The header contains the dialog title as well as
8642 * two {@link OO.ui.ActionWidget action widgets}: a ‘safe’ action on the left (e.g., ‘Cancel’) and
8643 * a ‘primary’ action on the right (e.g., ‘Done’).
8644 *
8645 * Like other windows, the process dialog is managed by a {@link OO.ui.WindowManager window manager}.
8646 * Please see the [OOjs UI documentation on MediaWiki][1] for more information and examples.
8647 *
8648 * @example
8649 * // Example: Creating and opening a process dialog window.
8650 * function MyProcessDialog( config ) {
8651 * MyProcessDialog.parent.call( this, config );
8652 * }
8653 * OO.inheritClass( MyProcessDialog, OO.ui.ProcessDialog );
8654 *
8655 * MyProcessDialog.static.title = 'Process dialog';
8656 * MyProcessDialog.static.actions = [
8657 * { action: 'save', label: 'Done', flags: 'primary' },
8658 * { label: 'Cancel', flags: 'safe' }
8659 * ];
8660 *
8661 * MyProcessDialog.prototype.initialize = function () {
8662 * MyProcessDialog.parent.prototype.initialize.apply( this, arguments );
8663 * this.content = new OO.ui.PanelLayout( { padded: true, expanded: false } );
8664 * 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>' );
8665 * this.$body.append( this.content.$element );
8666 * };
8667 * MyProcessDialog.prototype.getActionProcess = function ( action ) {
8668 * var dialog = this;
8669 * if ( action ) {
8670 * return new OO.ui.Process( function () {
8671 * dialog.close( { action: action } );
8672 * } );
8673 * }
8674 * return MyProcessDialog.parent.prototype.getActionProcess.call( this, action );
8675 * };
8676 *
8677 * var windowManager = new OO.ui.WindowManager();
8678 * $( 'body' ).append( windowManager.$element );
8679 *
8680 * var dialog = new MyProcessDialog();
8681 * windowManager.addWindows( [ dialog ] );
8682 * windowManager.openWindow( dialog );
8683 *
8684 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs
8685 *
8686 * @abstract
8687 * @class
8688 * @extends OO.ui.Dialog
8689 *
8690 * @constructor
8691 * @param {Object} [config] Configuration options
8692 */
8693 OO.ui.ProcessDialog = function OoUiProcessDialog( config ) {
8694 // Parent constructor
8695 OO.ui.ProcessDialog.parent.call( this, config );
8696
8697 // Properties
8698 this.fitOnOpen = false;
8699
8700 // Initialization
8701 this.$element.addClass( 'oo-ui-processDialog' );
8702 };
8703
8704 /* Setup */
8705
8706 OO.inheritClass( OO.ui.ProcessDialog, OO.ui.Dialog );
8707
8708 /* Methods */
8709
8710 /**
8711 * Handle dismiss button click events.
8712 *
8713 * Hides errors.
8714 *
8715 * @private
8716 */
8717 OO.ui.ProcessDialog.prototype.onDismissErrorButtonClick = function () {
8718 this.hideErrors();
8719 };
8720
8721 /**
8722 * Handle retry button click events.
8723 *
8724 * Hides errors and then tries again.
8725 *
8726 * @private
8727 */
8728 OO.ui.ProcessDialog.prototype.onRetryButtonClick = function () {
8729 this.hideErrors();
8730 this.executeAction( this.currentAction );
8731 };
8732
8733 /**
8734 * @inheritdoc
8735 */
8736 OO.ui.ProcessDialog.prototype.onActionResize = function ( action ) {
8737 if ( this.actions.isSpecial( action ) ) {
8738 this.fitLabel();
8739 }
8740 return OO.ui.ProcessDialog.parent.prototype.onActionResize.call( this, action );
8741 };
8742
8743 /**
8744 * @inheritdoc
8745 */
8746 OO.ui.ProcessDialog.prototype.initialize = function () {
8747 // Parent method
8748 OO.ui.ProcessDialog.parent.prototype.initialize.call( this );
8749
8750 // Properties
8751 this.$navigation = $( '<div>' );
8752 this.$location = $( '<div>' );
8753 this.$safeActions = $( '<div>' );
8754 this.$primaryActions = $( '<div>' );
8755 this.$otherActions = $( '<div>' );
8756 this.dismissButton = new OO.ui.ButtonWidget( {
8757 label: OO.ui.msg( 'ooui-dialog-process-dismiss' )
8758 } );
8759 this.retryButton = new OO.ui.ButtonWidget();
8760 this.$errors = $( '<div>' );
8761 this.$errorsTitle = $( '<div>' );
8762
8763 // Events
8764 this.dismissButton.connect( this, { click: 'onDismissErrorButtonClick' } );
8765 this.retryButton.connect( this, { click: 'onRetryButtonClick' } );
8766
8767 // Initialization
8768 this.title.$element.addClass( 'oo-ui-processDialog-title' );
8769 this.$location
8770 .append( this.title.$element )
8771 .addClass( 'oo-ui-processDialog-location' );
8772 this.$safeActions.addClass( 'oo-ui-processDialog-actions-safe' );
8773 this.$primaryActions.addClass( 'oo-ui-processDialog-actions-primary' );
8774 this.$otherActions.addClass( 'oo-ui-processDialog-actions-other' );
8775 this.$errorsTitle
8776 .addClass( 'oo-ui-processDialog-errors-title' )
8777 .text( OO.ui.msg( 'ooui-dialog-process-error' ) );
8778 this.$errors
8779 .addClass( 'oo-ui-processDialog-errors oo-ui-element-hidden' )
8780 .append( this.$errorsTitle, this.dismissButton.$element, this.retryButton.$element );
8781 this.$content
8782 .addClass( 'oo-ui-processDialog-content' )
8783 .append( this.$errors );
8784 this.$navigation
8785 .addClass( 'oo-ui-processDialog-navigation' )
8786 .append( this.$safeActions, this.$location, this.$primaryActions );
8787 this.$head.append( this.$navigation );
8788 this.$foot.append( this.$otherActions );
8789 };
8790
8791 /**
8792 * @inheritdoc
8793 */
8794 OO.ui.ProcessDialog.prototype.getActionWidgets = function ( actions ) {
8795 var i, len, widgets = [];
8796 for ( i = 0, len = actions.length; i < len; i++ ) {
8797 widgets.push(
8798 new OO.ui.ActionWidget( $.extend( { framed: true }, actions[ i ] ) )
8799 );
8800 }
8801 return widgets;
8802 };
8803
8804 /**
8805 * @inheritdoc
8806 */
8807 OO.ui.ProcessDialog.prototype.attachActions = function () {
8808 var i, len, other, special, others;
8809
8810 // Parent method
8811 OO.ui.ProcessDialog.parent.prototype.attachActions.call( this );
8812
8813 special = this.actions.getSpecial();
8814 others = this.actions.getOthers();
8815 if ( special.primary ) {
8816 this.$primaryActions.append( special.primary.$element );
8817 }
8818 for ( i = 0, len = others.length; i < len; i++ ) {
8819 other = others[ i ];
8820 this.$otherActions.append( other.$element );
8821 }
8822 if ( special.safe ) {
8823 this.$safeActions.append( special.safe.$element );
8824 }
8825
8826 this.fitLabel();
8827 this.$body.css( 'bottom', this.$foot.outerHeight( true ) );
8828 };
8829
8830 /**
8831 * @inheritdoc
8832 */
8833 OO.ui.ProcessDialog.prototype.executeAction = function ( action ) {
8834 var process = this;
8835 return OO.ui.ProcessDialog.parent.prototype.executeAction.call( this, action )
8836 .fail( function ( errors ) {
8837 process.showErrors( errors || [] );
8838 } );
8839 };
8840
8841 /**
8842 * @inheritdoc
8843 */
8844 OO.ui.ProcessDialog.prototype.setDimensions = function () {
8845 // Parent method
8846 OO.ui.ProcessDialog.parent.prototype.setDimensions.apply( this, arguments );
8847
8848 this.fitLabel();
8849 };
8850
8851 /**
8852 * Fit label between actions.
8853 *
8854 * @private
8855 * @chainable
8856 */
8857 OO.ui.ProcessDialog.prototype.fitLabel = function () {
8858 var safeWidth, primaryWidth, biggerWidth, labelWidth, navigationWidth, leftWidth, rightWidth,
8859 size = this.getSizeProperties();
8860
8861 if ( typeof size.width !== 'number' ) {
8862 if ( this.isOpened() ) {
8863 navigationWidth = this.$head.width() - 20;
8864 } else if ( this.isOpening() ) {
8865 if ( !this.fitOnOpen ) {
8866 // Size is relative and the dialog isn't open yet, so wait.
8867 this.manager.opening.done( this.fitLabel.bind( this ) );
8868 this.fitOnOpen = true;
8869 }
8870 return;
8871 } else {
8872 return;
8873 }
8874 } else {
8875 navigationWidth = size.width - 20;
8876 }
8877
8878 safeWidth = this.$safeActions.is( ':visible' ) ? this.$safeActions.width() : 0;
8879 primaryWidth = this.$primaryActions.is( ':visible' ) ? this.$primaryActions.width() : 0;
8880 biggerWidth = Math.max( safeWidth, primaryWidth );
8881
8882 labelWidth = this.title.$element.width();
8883
8884 if ( 2 * biggerWidth + labelWidth < navigationWidth ) {
8885 // We have enough space to center the label
8886 leftWidth = rightWidth = biggerWidth;
8887 } else {
8888 // Let's hope we at least have enough space not to overlap, because we can't wrap the label…
8889 if ( this.getDir() === 'ltr' ) {
8890 leftWidth = safeWidth;
8891 rightWidth = primaryWidth;
8892 } else {
8893 leftWidth = primaryWidth;
8894 rightWidth = safeWidth;
8895 }
8896 }
8897
8898 this.$location.css( { paddingLeft: leftWidth, paddingRight: rightWidth } );
8899
8900 return this;
8901 };
8902
8903 /**
8904 * Handle errors that occurred during accept or reject processes.
8905 *
8906 * @private
8907 * @param {OO.ui.Error[]|OO.ui.Error} errors Errors to be handled
8908 */
8909 OO.ui.ProcessDialog.prototype.showErrors = function ( errors ) {
8910 var i, len, $item, actions,
8911 items = [],
8912 abilities = {},
8913 recoverable = true,
8914 warning = false;
8915
8916 if ( errors instanceof OO.ui.Error ) {
8917 errors = [ errors ];
8918 }
8919
8920 for ( i = 0, len = errors.length; i < len; i++ ) {
8921 if ( !errors[ i ].isRecoverable() ) {
8922 recoverable = false;
8923 }
8924 if ( errors[ i ].isWarning() ) {
8925 warning = true;
8926 }
8927 $item = $( '<div>' )
8928 .addClass( 'oo-ui-processDialog-error' )
8929 .append( errors[ i ].getMessage() );
8930 items.push( $item[ 0 ] );
8931 }
8932 this.$errorItems = $( items );
8933 if ( recoverable ) {
8934 abilities[ this.currentAction ] = true;
8935 // Copy the flags from the first matching action
8936 actions = this.actions.get( { actions: this.currentAction } );
8937 if ( actions.length ) {
8938 this.retryButton.clearFlags().setFlags( actions[ 0 ].getFlags() );
8939 }
8940 } else {
8941 abilities[ this.currentAction ] = false;
8942 this.actions.setAbilities( abilities );
8943 }
8944 if ( warning ) {
8945 this.retryButton.setLabel( OO.ui.msg( 'ooui-dialog-process-continue' ) );
8946 } else {
8947 this.retryButton.setLabel( OO.ui.msg( 'ooui-dialog-process-retry' ) );
8948 }
8949 this.retryButton.toggle( recoverable );
8950 this.$errorsTitle.after( this.$errorItems );
8951 this.$errors.removeClass( 'oo-ui-element-hidden' ).scrollTop( 0 );
8952 };
8953
8954 /**
8955 * Hide errors.
8956 *
8957 * @private
8958 */
8959 OO.ui.ProcessDialog.prototype.hideErrors = function () {
8960 this.$errors.addClass( 'oo-ui-element-hidden' );
8961 if ( this.$errorItems ) {
8962 this.$errorItems.remove();
8963 this.$errorItems = null;
8964 }
8965 };
8966
8967 /**
8968 * @inheritdoc
8969 */
8970 OO.ui.ProcessDialog.prototype.getTeardownProcess = function ( data ) {
8971 // Parent method
8972 return OO.ui.ProcessDialog.parent.prototype.getTeardownProcess.call( this, data )
8973 .first( function () {
8974 // Make sure to hide errors
8975 this.hideErrors();
8976 this.fitOnOpen = false;
8977 }, this );
8978 };
8979
8980 /**
8981 * FieldLayouts are used with OO.ui.FieldsetLayout. Each FieldLayout requires a field-widget,
8982 * which is a widget that is specified by reference before any optional configuration settings.
8983 *
8984 * Field layouts can be configured with help text and/or labels. Labels are aligned in one of four ways:
8985 *
8986 * - **left**: The label is placed before the field-widget and aligned with the left margin.
8987 * A left-alignment is used for forms with many fields.
8988 * - **right**: The label is placed before the field-widget and aligned to the right margin.
8989 * A right-alignment is used for long but familiar forms which users tab through,
8990 * verifying the current field with a quick glance at the label.
8991 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
8992 * that users fill out from top to bottom.
8993 * - **inline**: The label is placed after the field-widget and aligned to the left.
8994 * An inline-alignment is best used with checkboxes or radio buttons.
8995 *
8996 * Help text is accessed via a help icon that appears in the upper right corner of the rendered field layout.
8997 * Please see the [OOjs UI documentation on MediaWiki] [1] for examples and more information.
8998 *
8999 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Fields_and_Fieldsets
9000 * @class
9001 * @extends OO.ui.Layout
9002 * @mixins OO.ui.mixin.LabelElement
9003 * @mixins OO.ui.mixin.TitledElement
9004 *
9005 * @constructor
9006 * @param {OO.ui.Widget} fieldWidget Field widget
9007 * @param {Object} [config] Configuration options
9008 * @cfg {string} [align='left'] Alignment of the label: 'left', 'right', 'top' or 'inline'
9009 * @cfg {Array} [errors] Error messages about the widget, which will be displayed below the widget.
9010 * The array may contain strings or OO.ui.HtmlSnippet instances.
9011 * @cfg {Array} [notices] Notices about the widget, which will be displayed below the widget.
9012 * The array may contain strings or OO.ui.HtmlSnippet instances.
9013 * @cfg {string|OO.ui.HtmlSnippet} [help] Help text. When help text is specified, a "help" icon will appear
9014 * in the upper-right corner of the rendered field; clicking it will display the text in a popup.
9015 * For important messages, you are advised to use `notices`, as they are always shown.
9016 *
9017 * @throws {Error} An error is thrown if no widget is specified
9018 */
9019 OO.ui.FieldLayout = function OoUiFieldLayout( fieldWidget, config ) {
9020 var hasInputWidget, div, i;
9021
9022 // Allow passing positional parameters inside the config object
9023 if ( OO.isPlainObject( fieldWidget ) && config === undefined ) {
9024 config = fieldWidget;
9025 fieldWidget = config.fieldWidget;
9026 }
9027
9028 // Make sure we have required constructor arguments
9029 if ( fieldWidget === undefined ) {
9030 throw new Error( 'Widget not found' );
9031 }
9032
9033 hasInputWidget = fieldWidget.constructor.static.supportsSimpleLabel;
9034
9035 // Configuration initialization
9036 config = $.extend( { align: 'left' }, config );
9037
9038 // Parent constructor
9039 OO.ui.FieldLayout.parent.call( this, config );
9040
9041 // Mixin constructors
9042 OO.ui.mixin.LabelElement.call( this, config );
9043 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$label } ) );
9044
9045 // Properties
9046 this.fieldWidget = fieldWidget;
9047 this.errors = config.errors || [];
9048 this.notices = config.notices || [];
9049 this.$field = $( '<div>' );
9050 this.$messages = $( '<ul>' );
9051 this.$body = $( '<' + ( hasInputWidget ? 'label' : 'div' ) + '>' );
9052 this.align = null;
9053 if ( config.help ) {
9054 this.popupButtonWidget = new OO.ui.PopupButtonWidget( {
9055 classes: [ 'oo-ui-fieldLayout-help' ],
9056 framed: false,
9057 icon: 'info'
9058 } );
9059
9060 div = $( '<div>' );
9061 if ( config.help instanceof OO.ui.HtmlSnippet ) {
9062 div.html( config.help.toString() );
9063 } else {
9064 div.text( config.help );
9065 }
9066 this.popupButtonWidget.getPopup().$body.append(
9067 div.addClass( 'oo-ui-fieldLayout-help-content' )
9068 );
9069 this.$help = this.popupButtonWidget.$element;
9070 } else {
9071 this.$help = $( [] );
9072 }
9073
9074 // Events
9075 if ( hasInputWidget ) {
9076 this.$label.on( 'click', this.onLabelClick.bind( this ) );
9077 }
9078 this.fieldWidget.connect( this, { disable: 'onFieldDisable' } );
9079
9080 // Initialization
9081 this.$element
9082 .addClass( 'oo-ui-fieldLayout' )
9083 .append( this.$help, this.$body );
9084 if ( this.errors.length || this.notices.length ) {
9085 this.$element.append( this.$messages );
9086 }
9087 this.$body.addClass( 'oo-ui-fieldLayout-body' );
9088 this.$messages.addClass( 'oo-ui-fieldLayout-messages' );
9089 this.$field
9090 .addClass( 'oo-ui-fieldLayout-field' )
9091 .toggleClass( 'oo-ui-fieldLayout-disable', this.fieldWidget.isDisabled() )
9092 .append( this.fieldWidget.$element );
9093
9094 for ( i = 0; i < this.notices.length; i++ ) {
9095 this.$messages.append( this.makeMessage( 'notice', this.notices[ i ] ) );
9096 }
9097 for ( i = 0; i < this.errors.length; i++ ) {
9098 this.$messages.append( this.makeMessage( 'error', this.errors[ i ] ) );
9099 }
9100
9101 this.setAlignment( config.align );
9102 };
9103
9104 /* Setup */
9105
9106 OO.inheritClass( OO.ui.FieldLayout, OO.ui.Layout );
9107 OO.mixinClass( OO.ui.FieldLayout, OO.ui.mixin.LabelElement );
9108 OO.mixinClass( OO.ui.FieldLayout, OO.ui.mixin.TitledElement );
9109
9110 /* Methods */
9111
9112 /**
9113 * Handle field disable events.
9114 *
9115 * @private
9116 * @param {boolean} value Field is disabled
9117 */
9118 OO.ui.FieldLayout.prototype.onFieldDisable = function ( value ) {
9119 this.$element.toggleClass( 'oo-ui-fieldLayout-disabled', value );
9120 };
9121
9122 /**
9123 * Handle label mouse click events.
9124 *
9125 * @private
9126 * @param {jQuery.Event} e Mouse click event
9127 */
9128 OO.ui.FieldLayout.prototype.onLabelClick = function () {
9129 this.fieldWidget.simulateLabelClick();
9130 return false;
9131 };
9132
9133 /**
9134 * Get the widget contained by the field.
9135 *
9136 * @return {OO.ui.Widget} Field widget
9137 */
9138 OO.ui.FieldLayout.prototype.getField = function () {
9139 return this.fieldWidget;
9140 };
9141
9142 /**
9143 * @param {string} kind 'error' or 'notice'
9144 * @param {string|OO.ui.HtmlSnippet} text
9145 * @return {jQuery}
9146 */
9147 OO.ui.FieldLayout.prototype.makeMessage = function ( kind, text ) {
9148 var $listItem, $icon, message;
9149 $listItem = $( '<li>' );
9150 if ( kind === 'error' ) {
9151 $icon = new OO.ui.IconWidget( { icon: 'alert', flags: [ 'warning' ] } ).$element;
9152 } else if ( kind === 'notice' ) {
9153 $icon = new OO.ui.IconWidget( { icon: 'info' } ).$element;
9154 } else {
9155 $icon = '';
9156 }
9157 message = new OO.ui.LabelWidget( { label: text } );
9158 $listItem
9159 .append( $icon, message.$element )
9160 .addClass( 'oo-ui-fieldLayout-messages-' + kind );
9161 return $listItem;
9162 };
9163
9164 /**
9165 * Set the field alignment mode.
9166 *
9167 * @private
9168 * @param {string} value Alignment mode, either 'left', 'right', 'top' or 'inline'
9169 * @chainable
9170 */
9171 OO.ui.FieldLayout.prototype.setAlignment = function ( value ) {
9172 if ( value !== this.align ) {
9173 // Default to 'left'
9174 if ( [ 'left', 'right', 'top', 'inline' ].indexOf( value ) === -1 ) {
9175 value = 'left';
9176 }
9177 // Reorder elements
9178 if ( value === 'inline' ) {
9179 this.$body.append( this.$field, this.$label );
9180 } else {
9181 this.$body.append( this.$label, this.$field );
9182 }
9183 // Set classes. The following classes can be used here:
9184 // * oo-ui-fieldLayout-align-left
9185 // * oo-ui-fieldLayout-align-right
9186 // * oo-ui-fieldLayout-align-top
9187 // * oo-ui-fieldLayout-align-inline
9188 if ( this.align ) {
9189 this.$element.removeClass( 'oo-ui-fieldLayout-align-' + this.align );
9190 }
9191 this.$element.addClass( 'oo-ui-fieldLayout-align-' + value );
9192 this.align = value;
9193 }
9194
9195 return this;
9196 };
9197
9198 /**
9199 * ActionFieldLayouts are used with OO.ui.FieldsetLayout. The layout consists of a field-widget, a button,
9200 * and an optional label and/or help text. The field-widget (e.g., a {@link OO.ui.TextInputWidget TextInputWidget}),
9201 * is required and is specified before any optional configuration settings.
9202 *
9203 * Labels can be aligned in one of four ways:
9204 *
9205 * - **left**: The label is placed before the field-widget and aligned with the left margin.
9206 * A left-alignment is used for forms with many fields.
9207 * - **right**: The label is placed before the field-widget and aligned to the right margin.
9208 * A right-alignment is used for long but familiar forms which users tab through,
9209 * verifying the current field with a quick glance at the label.
9210 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
9211 * that users fill out from top to bottom.
9212 * - **inline**: The label is placed after the field-widget and aligned to the left.
9213 * An inline-alignment is best used with checkboxes or radio buttons.
9214 *
9215 * Help text is accessed via a help icon that appears in the upper right corner of the rendered field layout when help
9216 * text is specified.
9217 *
9218 * @example
9219 * // Example of an ActionFieldLayout
9220 * var actionFieldLayout = new OO.ui.ActionFieldLayout(
9221 * new OO.ui.TextInputWidget( {
9222 * placeholder: 'Field widget'
9223 * } ),
9224 * new OO.ui.ButtonWidget( {
9225 * label: 'Button'
9226 * } ),
9227 * {
9228 * label: 'An ActionFieldLayout. This label is aligned top',
9229 * align: 'top',
9230 * help: 'This is help text'
9231 * }
9232 * );
9233 *
9234 * $( 'body' ).append( actionFieldLayout.$element );
9235 *
9236 * @class
9237 * @extends OO.ui.FieldLayout
9238 *
9239 * @constructor
9240 * @param {OO.ui.Widget} fieldWidget Field widget
9241 * @param {OO.ui.ButtonWidget} buttonWidget Button widget
9242 */
9243 OO.ui.ActionFieldLayout = function OoUiActionFieldLayout( fieldWidget, buttonWidget, config ) {
9244 // Allow passing positional parameters inside the config object
9245 if ( OO.isPlainObject( fieldWidget ) && config === undefined ) {
9246 config = fieldWidget;
9247 fieldWidget = config.fieldWidget;
9248 buttonWidget = config.buttonWidget;
9249 }
9250
9251 // Parent constructor
9252 OO.ui.ActionFieldLayout.parent.call( this, fieldWidget, config );
9253
9254 // Properties
9255 this.buttonWidget = buttonWidget;
9256 this.$button = $( '<div>' );
9257 this.$input = $( '<div>' );
9258
9259 // Initialization
9260 this.$element
9261 .addClass( 'oo-ui-actionFieldLayout' );
9262 this.$button
9263 .addClass( 'oo-ui-actionFieldLayout-button' )
9264 .append( this.buttonWidget.$element );
9265 this.$input
9266 .addClass( 'oo-ui-actionFieldLayout-input' )
9267 .append( this.fieldWidget.$element );
9268 this.$field
9269 .append( this.$input, this.$button );
9270 };
9271
9272 /* Setup */
9273
9274 OO.inheritClass( OO.ui.ActionFieldLayout, OO.ui.FieldLayout );
9275
9276 /**
9277 * FieldsetLayouts are composed of one or more {@link OO.ui.FieldLayout FieldLayouts},
9278 * which each contain an individual widget and, optionally, a label. Each Fieldset can be
9279 * configured with a label as well. For more information and examples,
9280 * please see the [OOjs UI documentation on MediaWiki][1].
9281 *
9282 * @example
9283 * // Example of a fieldset layout
9284 * var input1 = new OO.ui.TextInputWidget( {
9285 * placeholder: 'A text input field'
9286 * } );
9287 *
9288 * var input2 = new OO.ui.TextInputWidget( {
9289 * placeholder: 'A text input field'
9290 * } );
9291 *
9292 * var fieldset = new OO.ui.FieldsetLayout( {
9293 * label: 'Example of a fieldset layout'
9294 * } );
9295 *
9296 * fieldset.addItems( [
9297 * new OO.ui.FieldLayout( input1, {
9298 * label: 'Field One'
9299 * } ),
9300 * new OO.ui.FieldLayout( input2, {
9301 * label: 'Field Two'
9302 * } )
9303 * ] );
9304 * $( 'body' ).append( fieldset.$element );
9305 *
9306 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Fields_and_Fieldsets
9307 *
9308 * @class
9309 * @extends OO.ui.Layout
9310 * @mixins OO.ui.mixin.IconElement
9311 * @mixins OO.ui.mixin.LabelElement
9312 * @mixins OO.ui.mixin.GroupElement
9313 *
9314 * @constructor
9315 * @param {Object} [config] Configuration options
9316 * @cfg {OO.ui.FieldLayout[]} [items] An array of fields to add to the fieldset. See OO.ui.FieldLayout for more information about fields.
9317 */
9318 OO.ui.FieldsetLayout = function OoUiFieldsetLayout( config ) {
9319 // Configuration initialization
9320 config = config || {};
9321
9322 // Parent constructor
9323 OO.ui.FieldsetLayout.parent.call( this, config );
9324
9325 // Mixin constructors
9326 OO.ui.mixin.IconElement.call( this, config );
9327 OO.ui.mixin.LabelElement.call( this, config );
9328 OO.ui.mixin.GroupElement.call( this, config );
9329
9330 if ( config.help ) {
9331 this.popupButtonWidget = new OO.ui.PopupButtonWidget( {
9332 classes: [ 'oo-ui-fieldsetLayout-help' ],
9333 framed: false,
9334 icon: 'info'
9335 } );
9336
9337 this.popupButtonWidget.getPopup().$body.append(
9338 $( '<div>' )
9339 .text( config.help )
9340 .addClass( 'oo-ui-fieldsetLayout-help-content' )
9341 );
9342 this.$help = this.popupButtonWidget.$element;
9343 } else {
9344 this.$help = $( [] );
9345 }
9346
9347 // Initialization
9348 this.$element
9349 .addClass( 'oo-ui-fieldsetLayout' )
9350 .prepend( this.$help, this.$icon, this.$label, this.$group );
9351 if ( Array.isArray( config.items ) ) {
9352 this.addItems( config.items );
9353 }
9354 };
9355
9356 /* Setup */
9357
9358 OO.inheritClass( OO.ui.FieldsetLayout, OO.ui.Layout );
9359 OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.mixin.IconElement );
9360 OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.mixin.LabelElement );
9361 OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.mixin.GroupElement );
9362
9363 /**
9364 * FormLayouts are used to wrap {@link OO.ui.FieldsetLayout FieldsetLayouts} when you intend to use browser-based
9365 * form submission for the fields instead of handling them in JavaScript. Form layouts can be configured with an
9366 * HTML form action, an encoding type, and a method using the #action, #enctype, and #method configs, respectively.
9367 * See the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
9368 *
9369 * Only widgets from the {@link OO.ui.InputWidget InputWidget} family support form submission. It
9370 * includes standard form elements like {@link OO.ui.CheckboxInputWidget checkboxes}, {@link
9371 * OO.ui.RadioInputWidget radio buttons} and {@link OO.ui.TextInputWidget text fields}, as well as
9372 * some fancier controls. Some controls have both regular and InputWidget variants, for example
9373 * OO.ui.DropdownWidget and OO.ui.DropdownInputWidget – only the latter support form submission and
9374 * often have simplified APIs to match the capabilities of HTML forms.
9375 * See the [OOjs UI Inputs documentation on MediaWiki] [2] for more information about InputWidgets.
9376 *
9377 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Forms
9378 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
9379 *
9380 * @example
9381 * // Example of a form layout that wraps a fieldset layout
9382 * var input1 = new OO.ui.TextInputWidget( {
9383 * placeholder: 'Username'
9384 * } );
9385 * var input2 = new OO.ui.TextInputWidget( {
9386 * placeholder: 'Password',
9387 * type: 'password'
9388 * } );
9389 * var submit = new OO.ui.ButtonInputWidget( {
9390 * label: 'Submit'
9391 * } );
9392 *
9393 * var fieldset = new OO.ui.FieldsetLayout( {
9394 * label: 'A form layout'
9395 * } );
9396 * fieldset.addItems( [
9397 * new OO.ui.FieldLayout( input1, {
9398 * label: 'Username',
9399 * align: 'top'
9400 * } ),
9401 * new OO.ui.FieldLayout( input2, {
9402 * label: 'Password',
9403 * align: 'top'
9404 * } ),
9405 * new OO.ui.FieldLayout( submit )
9406 * ] );
9407 * var form = new OO.ui.FormLayout( {
9408 * items: [ fieldset ],
9409 * action: '/api/formhandler',
9410 * method: 'get'
9411 * } )
9412 * $( 'body' ).append( form.$element );
9413 *
9414 * @class
9415 * @extends OO.ui.Layout
9416 * @mixins OO.ui.mixin.GroupElement
9417 *
9418 * @constructor
9419 * @param {Object} [config] Configuration options
9420 * @cfg {string} [method] HTML form `method` attribute
9421 * @cfg {string} [action] HTML form `action` attribute
9422 * @cfg {string} [enctype] HTML form `enctype` attribute
9423 * @cfg {OO.ui.FieldsetLayout[]} [items] Fieldset layouts to add to the form layout.
9424 */
9425 OO.ui.FormLayout = function OoUiFormLayout( config ) {
9426 // Configuration initialization
9427 config = config || {};
9428
9429 // Parent constructor
9430 OO.ui.FormLayout.parent.call( this, config );
9431
9432 // Mixin constructors
9433 OO.ui.mixin.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) );
9434
9435 // Events
9436 this.$element.on( 'submit', this.onFormSubmit.bind( this ) );
9437
9438 // Make sure the action is safe
9439 if ( config.action !== undefined && !OO.ui.isSafeUrl( config.action ) ) {
9440 throw new Error( 'Potentially unsafe action provided: ' + config.action );
9441 }
9442
9443 // Initialization
9444 this.$element
9445 .addClass( 'oo-ui-formLayout' )
9446 .attr( {
9447 method: config.method,
9448 action: config.action,
9449 enctype: config.enctype
9450 } );
9451 if ( Array.isArray( config.items ) ) {
9452 this.addItems( config.items );
9453 }
9454 };
9455
9456 /* Setup */
9457
9458 OO.inheritClass( OO.ui.FormLayout, OO.ui.Layout );
9459 OO.mixinClass( OO.ui.FormLayout, OO.ui.mixin.GroupElement );
9460
9461 /* Events */
9462
9463 /**
9464 * A 'submit' event is emitted when the form is submitted.
9465 *
9466 * @event submit
9467 */
9468
9469 /* Static Properties */
9470
9471 OO.ui.FormLayout.static.tagName = 'form';
9472
9473 /* Methods */
9474
9475 /**
9476 * Handle form submit events.
9477 *
9478 * @private
9479 * @param {jQuery.Event} e Submit event
9480 * @fires submit
9481 */
9482 OO.ui.FormLayout.prototype.onFormSubmit = function () {
9483 if ( this.emit( 'submit' ) ) {
9484 return false;
9485 }
9486 };
9487
9488 /**
9489 * 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)
9490 * and its size is customized with the #menuSize config. The content area will fill all remaining space.
9491 *
9492 * @example
9493 * var menuLayout = new OO.ui.MenuLayout( {
9494 * position: 'top'
9495 * } ),
9496 * menuPanel = new OO.ui.PanelLayout( { padded: true, expanded: true, scrollable: true } ),
9497 * contentPanel = new OO.ui.PanelLayout( { padded: true, expanded: true, scrollable: true } ),
9498 * select = new OO.ui.SelectWidget( {
9499 * items: [
9500 * new OO.ui.OptionWidget( {
9501 * data: 'before',
9502 * label: 'Before',
9503 * } ),
9504 * new OO.ui.OptionWidget( {
9505 * data: 'after',
9506 * label: 'After',
9507 * } ),
9508 * new OO.ui.OptionWidget( {
9509 * data: 'top',
9510 * label: 'Top',
9511 * } ),
9512 * new OO.ui.OptionWidget( {
9513 * data: 'bottom',
9514 * label: 'Bottom',
9515 * } )
9516 * ]
9517 * } ).on( 'select', function ( item ) {
9518 * menuLayout.setMenuPosition( item.getData() );
9519 * } );
9520 *
9521 * menuLayout.$menu.append(
9522 * menuPanel.$element.append( '<b>Menu panel</b>', select.$element )
9523 * );
9524 * menuLayout.$content.append(
9525 * contentPanel.$element.append( '<b>Content panel</b>', '<p>Note that the menu is positioned relative to the content panel: top, bottom, after, before.</p>')
9526 * );
9527 * $( 'body' ).append( menuLayout.$element );
9528 *
9529 * If menu size needs to be overridden, it can be accomplished using CSS similar to the snippet
9530 * below. MenuLayout's CSS will override the appropriate values with 'auto' or '0' to display the
9531 * menu correctly. If `menuPosition` is known beforehand, CSS rules corresponding to other positions
9532 * may be omitted.
9533 *
9534 * .oo-ui-menuLayout-menu {
9535 * height: 200px;
9536 * width: 200px;
9537 * }
9538 * .oo-ui-menuLayout-content {
9539 * top: 200px;
9540 * left: 200px;
9541 * right: 200px;
9542 * bottom: 200px;
9543 * }
9544 *
9545 * @class
9546 * @extends OO.ui.Layout
9547 *
9548 * @constructor
9549 * @param {Object} [config] Configuration options
9550 * @cfg {boolean} [showMenu=true] Show menu
9551 * @cfg {string} [menuPosition='before'] Position of menu: `top`, `after`, `bottom` or `before`
9552 */
9553 OO.ui.MenuLayout = function OoUiMenuLayout( config ) {
9554 // Configuration initialization
9555 config = $.extend( {
9556 showMenu: true,
9557 menuPosition: 'before'
9558 }, config );
9559
9560 // Parent constructor
9561 OO.ui.MenuLayout.parent.call( this, config );
9562
9563 /**
9564 * Menu DOM node
9565 *
9566 * @property {jQuery}
9567 */
9568 this.$menu = $( '<div>' );
9569 /**
9570 * Content DOM node
9571 *
9572 * @property {jQuery}
9573 */
9574 this.$content = $( '<div>' );
9575
9576 // Initialization
9577 this.$menu
9578 .addClass( 'oo-ui-menuLayout-menu' );
9579 this.$content.addClass( 'oo-ui-menuLayout-content' );
9580 this.$element
9581 .addClass( 'oo-ui-menuLayout' )
9582 .append( this.$content, this.$menu );
9583 this.setMenuPosition( config.menuPosition );
9584 this.toggleMenu( config.showMenu );
9585 };
9586
9587 /* Setup */
9588
9589 OO.inheritClass( OO.ui.MenuLayout, OO.ui.Layout );
9590
9591 /* Methods */
9592
9593 /**
9594 * Toggle menu.
9595 *
9596 * @param {boolean} showMenu Show menu, omit to toggle
9597 * @chainable
9598 */
9599 OO.ui.MenuLayout.prototype.toggleMenu = function ( showMenu ) {
9600 showMenu = showMenu === undefined ? !this.showMenu : !!showMenu;
9601
9602 if ( this.showMenu !== showMenu ) {
9603 this.showMenu = showMenu;
9604 this.$element
9605 .toggleClass( 'oo-ui-menuLayout-showMenu', this.showMenu )
9606 .toggleClass( 'oo-ui-menuLayout-hideMenu', !this.showMenu );
9607 }
9608
9609 return this;
9610 };
9611
9612 /**
9613 * Check if menu is visible
9614 *
9615 * @return {boolean} Menu is visible
9616 */
9617 OO.ui.MenuLayout.prototype.isMenuVisible = function () {
9618 return this.showMenu;
9619 };
9620
9621 /**
9622 * Set menu position.
9623 *
9624 * @param {string} position Position of menu, either `top`, `after`, `bottom` or `before`
9625 * @throws {Error} If position value is not supported
9626 * @chainable
9627 */
9628 OO.ui.MenuLayout.prototype.setMenuPosition = function ( position ) {
9629 this.$element.removeClass( 'oo-ui-menuLayout-' + this.menuPosition );
9630 this.menuPosition = position;
9631 this.$element.addClass( 'oo-ui-menuLayout-' + position );
9632
9633 return this;
9634 };
9635
9636 /**
9637 * Get menu position.
9638 *
9639 * @return {string} Menu position
9640 */
9641 OO.ui.MenuLayout.prototype.getMenuPosition = function () {
9642 return this.menuPosition;
9643 };
9644
9645 /**
9646 * BookletLayouts contain {@link OO.ui.PageLayout page layouts} as well as
9647 * an {@link OO.ui.OutlineSelectWidget outline} that allows users to easily navigate
9648 * through the pages and select which one to display. By default, only one page is
9649 * displayed at a time and the outline is hidden. When a user navigates to a new page,
9650 * the booklet layout automatically focuses on the first focusable element, unless the
9651 * default setting is changed. Optionally, booklets can be configured to show
9652 * {@link OO.ui.OutlineControlsWidget controls} for adding, moving, and removing items.
9653 *
9654 * @example
9655 * // Example of a BookletLayout that contains two PageLayouts.
9656 *
9657 * function PageOneLayout( name, config ) {
9658 * PageOneLayout.parent.call( this, name, config );
9659 * this.$element.append( '<p>First page</p><p>(This booklet has an outline, displayed on the left)</p>' );
9660 * }
9661 * OO.inheritClass( PageOneLayout, OO.ui.PageLayout );
9662 * PageOneLayout.prototype.setupOutlineItem = function () {
9663 * this.outlineItem.setLabel( 'Page One' );
9664 * };
9665 *
9666 * function PageTwoLayout( name, config ) {
9667 * PageTwoLayout.parent.call( this, name, config );
9668 * this.$element.append( '<p>Second page</p>' );
9669 * }
9670 * OO.inheritClass( PageTwoLayout, OO.ui.PageLayout );
9671 * PageTwoLayout.prototype.setupOutlineItem = function () {
9672 * this.outlineItem.setLabel( 'Page Two' );
9673 * };
9674 *
9675 * var page1 = new PageOneLayout( 'one' ),
9676 * page2 = new PageTwoLayout( 'two' );
9677 *
9678 * var booklet = new OO.ui.BookletLayout( {
9679 * outlined: true
9680 * } );
9681 *
9682 * booklet.addPages ( [ page1, page2 ] );
9683 * $( 'body' ).append( booklet.$element );
9684 *
9685 * @class
9686 * @extends OO.ui.MenuLayout
9687 *
9688 * @constructor
9689 * @param {Object} [config] Configuration options
9690 * @cfg {boolean} [continuous=false] Show all pages, one after another
9691 * @cfg {boolean} [autoFocus=true] Focus on the first focusable element when a new page is displayed.
9692 * @cfg {boolean} [outlined=false] Show the outline. The outline is used to navigate through the pages of the booklet.
9693 * @cfg {boolean} [editable=false] Show controls for adding, removing and reordering pages
9694 */
9695 OO.ui.BookletLayout = function OoUiBookletLayout( config ) {
9696 // Configuration initialization
9697 config = config || {};
9698
9699 // Parent constructor
9700 OO.ui.BookletLayout.parent.call( this, config );
9701
9702 // Properties
9703 this.currentPageName = null;
9704 this.pages = {};
9705 this.ignoreFocus = false;
9706 this.stackLayout = new OO.ui.StackLayout( { continuous: !!config.continuous } );
9707 this.$content.append( this.stackLayout.$element );
9708 this.autoFocus = config.autoFocus === undefined || !!config.autoFocus;
9709 this.outlineVisible = false;
9710 this.outlined = !!config.outlined;
9711 if ( this.outlined ) {
9712 this.editable = !!config.editable;
9713 this.outlineControlsWidget = null;
9714 this.outlineSelectWidget = new OO.ui.OutlineSelectWidget();
9715 this.outlinePanel = new OO.ui.PanelLayout( { scrollable: true } );
9716 this.$menu.append( this.outlinePanel.$element );
9717 this.outlineVisible = true;
9718 if ( this.editable ) {
9719 this.outlineControlsWidget = new OO.ui.OutlineControlsWidget(
9720 this.outlineSelectWidget
9721 );
9722 }
9723 }
9724 this.toggleMenu( this.outlined );
9725
9726 // Events
9727 this.stackLayout.connect( this, { set: 'onStackLayoutSet' } );
9728 if ( this.outlined ) {
9729 this.outlineSelectWidget.connect( this, { select: 'onOutlineSelectWidgetSelect' } );
9730 }
9731 if ( this.autoFocus ) {
9732 // Event 'focus' does not bubble, but 'focusin' does
9733 this.stackLayout.$element.on( 'focusin', this.onStackLayoutFocus.bind( this ) );
9734 }
9735
9736 // Initialization
9737 this.$element.addClass( 'oo-ui-bookletLayout' );
9738 this.stackLayout.$element.addClass( 'oo-ui-bookletLayout-stackLayout' );
9739 if ( this.outlined ) {
9740 this.outlinePanel.$element
9741 .addClass( 'oo-ui-bookletLayout-outlinePanel' )
9742 .append( this.outlineSelectWidget.$element );
9743 if ( this.editable ) {
9744 this.outlinePanel.$element
9745 .addClass( 'oo-ui-bookletLayout-outlinePanel-editable' )
9746 .append( this.outlineControlsWidget.$element );
9747 }
9748 }
9749 };
9750
9751 /* Setup */
9752
9753 OO.inheritClass( OO.ui.BookletLayout, OO.ui.MenuLayout );
9754
9755 /* Events */
9756
9757 /**
9758 * A 'set' event is emitted when a page is {@link #setPage set} to be displayed by the booklet layout.
9759 * @event set
9760 * @param {OO.ui.PageLayout} page Current page
9761 */
9762
9763 /**
9764 * An 'add' event is emitted when pages are {@link #addPages added} to the booklet layout.
9765 *
9766 * @event add
9767 * @param {OO.ui.PageLayout[]} page Added pages
9768 * @param {number} index Index pages were added at
9769 */
9770
9771 /**
9772 * A 'remove' event is emitted when pages are {@link #clearPages cleared} or
9773 * {@link #removePages removed} from the booklet.
9774 *
9775 * @event remove
9776 * @param {OO.ui.PageLayout[]} pages Removed pages
9777 */
9778
9779 /* Methods */
9780
9781 /**
9782 * Handle stack layout focus.
9783 *
9784 * @private
9785 * @param {jQuery.Event} e Focusin event
9786 */
9787 OO.ui.BookletLayout.prototype.onStackLayoutFocus = function ( e ) {
9788 var name, $target;
9789
9790 // Find the page that an element was focused within
9791 $target = $( e.target ).closest( '.oo-ui-pageLayout' );
9792 for ( name in this.pages ) {
9793 // Check for page match, exclude current page to find only page changes
9794 if ( this.pages[ name ].$element[ 0 ] === $target[ 0 ] && name !== this.currentPageName ) {
9795 this.setPage( name );
9796 break;
9797 }
9798 }
9799 };
9800
9801 /**
9802 * Handle stack layout set events.
9803 *
9804 * @private
9805 * @param {OO.ui.PanelLayout|null} page The page panel that is now the current panel
9806 */
9807 OO.ui.BookletLayout.prototype.onStackLayoutSet = function ( page ) {
9808 var layout = this;
9809 if ( page ) {
9810 page.scrollElementIntoView( { complete: function () {
9811 if ( layout.autoFocus ) {
9812 layout.focus();
9813 }
9814 } } );
9815 }
9816 };
9817
9818 /**
9819 * Focus the first input in the current page.
9820 *
9821 * If no page is selected, the first selectable page will be selected.
9822 * If the focus is already in an element on the current page, nothing will happen.
9823 * @param {number} [itemIndex] A specific item to focus on
9824 */
9825 OO.ui.BookletLayout.prototype.focus = function ( itemIndex ) {
9826 var page,
9827 items = this.stackLayout.getItems();
9828
9829 if ( itemIndex !== undefined && items[ itemIndex ] ) {
9830 page = items[ itemIndex ];
9831 } else {
9832 page = this.stackLayout.getCurrentItem();
9833 }
9834
9835 if ( !page && this.outlined ) {
9836 this.selectFirstSelectablePage();
9837 page = this.stackLayout.getCurrentItem();
9838 }
9839 if ( !page ) {
9840 return;
9841 }
9842 // Only change the focus if is not already in the current page
9843 if ( !page.$element.find( ':focus' ).length ) {
9844 OO.ui.findFocusable( page.$element ).focus();
9845 }
9846 };
9847
9848 /**
9849 * Find the first focusable input in the booklet layout and focus
9850 * on it.
9851 */
9852 OO.ui.BookletLayout.prototype.focusFirstFocusable = function () {
9853 OO.ui.findFocusable( this.stackLayout.$element ).focus();
9854 };
9855
9856 /**
9857 * Handle outline widget select events.
9858 *
9859 * @private
9860 * @param {OO.ui.OptionWidget|null} item Selected item
9861 */
9862 OO.ui.BookletLayout.prototype.onOutlineSelectWidgetSelect = function ( item ) {
9863 if ( item ) {
9864 this.setPage( item.getData() );
9865 }
9866 };
9867
9868 /**
9869 * Check if booklet has an outline.
9870 *
9871 * @return {boolean} Booklet has an outline
9872 */
9873 OO.ui.BookletLayout.prototype.isOutlined = function () {
9874 return this.outlined;
9875 };
9876
9877 /**
9878 * Check if booklet has editing controls.
9879 *
9880 * @return {boolean} Booklet is editable
9881 */
9882 OO.ui.BookletLayout.prototype.isEditable = function () {
9883 return this.editable;
9884 };
9885
9886 /**
9887 * Check if booklet has a visible outline.
9888 *
9889 * @return {boolean} Outline is visible
9890 */
9891 OO.ui.BookletLayout.prototype.isOutlineVisible = function () {
9892 return this.outlined && this.outlineVisible;
9893 };
9894
9895 /**
9896 * Hide or show the outline.
9897 *
9898 * @param {boolean} [show] Show outline, omit to invert current state
9899 * @chainable
9900 */
9901 OO.ui.BookletLayout.prototype.toggleOutline = function ( show ) {
9902 if ( this.outlined ) {
9903 show = show === undefined ? !this.outlineVisible : !!show;
9904 this.outlineVisible = show;
9905 this.toggleMenu( show );
9906 }
9907
9908 return this;
9909 };
9910
9911 /**
9912 * Get the page closest to the specified page.
9913 *
9914 * @param {OO.ui.PageLayout} page Page to use as a reference point
9915 * @return {OO.ui.PageLayout|null} Page closest to the specified page
9916 */
9917 OO.ui.BookletLayout.prototype.getClosestPage = function ( page ) {
9918 var next, prev, level,
9919 pages = this.stackLayout.getItems(),
9920 index = pages.indexOf( page );
9921
9922 if ( index !== -1 ) {
9923 next = pages[ index + 1 ];
9924 prev = pages[ index - 1 ];
9925 // Prefer adjacent pages at the same level
9926 if ( this.outlined ) {
9927 level = this.outlineSelectWidget.getItemFromData( page.getName() ).getLevel();
9928 if (
9929 prev &&
9930 level === this.outlineSelectWidget.getItemFromData( prev.getName() ).getLevel()
9931 ) {
9932 return prev;
9933 }
9934 if (
9935 next &&
9936 level === this.outlineSelectWidget.getItemFromData( next.getName() ).getLevel()
9937 ) {
9938 return next;
9939 }
9940 }
9941 }
9942 return prev || next || null;
9943 };
9944
9945 /**
9946 * Get the outline widget.
9947 *
9948 * If the booklet is not outlined, the method will return `null`.
9949 *
9950 * @return {OO.ui.OutlineSelectWidget|null} Outline widget, or null if the booklet is not outlined
9951 */
9952 OO.ui.BookletLayout.prototype.getOutline = function () {
9953 return this.outlineSelectWidget;
9954 };
9955
9956 /**
9957 * Get the outline controls widget.
9958 *
9959 * If the outline is not editable, the method will return `null`.
9960 *
9961 * @return {OO.ui.OutlineControlsWidget|null} The outline controls widget.
9962 */
9963 OO.ui.BookletLayout.prototype.getOutlineControls = function () {
9964 return this.outlineControlsWidget;
9965 };
9966
9967 /**
9968 * Get a page by its symbolic name.
9969 *
9970 * @param {string} name Symbolic name of page
9971 * @return {OO.ui.PageLayout|undefined} Page, if found
9972 */
9973 OO.ui.BookletLayout.prototype.getPage = function ( name ) {
9974 return this.pages[ name ];
9975 };
9976
9977 /**
9978 * Get the current page.
9979 *
9980 * @return {OO.ui.PageLayout|undefined} Current page, if found
9981 */
9982 OO.ui.BookletLayout.prototype.getCurrentPage = function () {
9983 var name = this.getCurrentPageName();
9984 return name ? this.getPage( name ) : undefined;
9985 };
9986
9987 /**
9988 * Get the symbolic name of the current page.
9989 *
9990 * @return {string|null} Symbolic name of the current page
9991 */
9992 OO.ui.BookletLayout.prototype.getCurrentPageName = function () {
9993 return this.currentPageName;
9994 };
9995
9996 /**
9997 * Add pages to the booklet layout
9998 *
9999 * When pages are added with the same names as existing pages, the existing pages will be
10000 * automatically removed before the new pages are added.
10001 *
10002 * @param {OO.ui.PageLayout[]} pages Pages to add
10003 * @param {number} index Index of the insertion point
10004 * @fires add
10005 * @chainable
10006 */
10007 OO.ui.BookletLayout.prototype.addPages = function ( pages, index ) {
10008 var i, len, name, page, item, currentIndex,
10009 stackLayoutPages = this.stackLayout.getItems(),
10010 remove = [],
10011 items = [];
10012
10013 // Remove pages with same names
10014 for ( i = 0, len = pages.length; i < len; i++ ) {
10015 page = pages[ i ];
10016 name = page.getName();
10017
10018 if ( Object.prototype.hasOwnProperty.call( this.pages, name ) ) {
10019 // Correct the insertion index
10020 currentIndex = stackLayoutPages.indexOf( this.pages[ name ] );
10021 if ( currentIndex !== -1 && currentIndex + 1 < index ) {
10022 index--;
10023 }
10024 remove.push( this.pages[ name ] );
10025 }
10026 }
10027 if ( remove.length ) {
10028 this.removePages( remove );
10029 }
10030
10031 // Add new pages
10032 for ( i = 0, len = pages.length; i < len; i++ ) {
10033 page = pages[ i ];
10034 name = page.getName();
10035 this.pages[ page.getName() ] = page;
10036 if ( this.outlined ) {
10037 item = new OO.ui.OutlineOptionWidget( { data: name } );
10038 page.setOutlineItem( item );
10039 items.push( item );
10040 }
10041 }
10042
10043 if ( this.outlined && items.length ) {
10044 this.outlineSelectWidget.addItems( items, index );
10045 this.selectFirstSelectablePage();
10046 }
10047 this.stackLayout.addItems( pages, index );
10048 this.emit( 'add', pages, index );
10049
10050 return this;
10051 };
10052
10053 /**
10054 * Remove the specified pages from the booklet layout.
10055 *
10056 * To remove all pages from the booklet, you may wish to use the #clearPages method instead.
10057 *
10058 * @param {OO.ui.PageLayout[]} pages An array of pages to remove
10059 * @fires remove
10060 * @chainable
10061 */
10062 OO.ui.BookletLayout.prototype.removePages = function ( pages ) {
10063 var i, len, name, page,
10064 items = [];
10065
10066 for ( i = 0, len = pages.length; i < len; i++ ) {
10067 page = pages[ i ];
10068 name = page.getName();
10069 delete this.pages[ name ];
10070 if ( this.outlined ) {
10071 items.push( this.outlineSelectWidget.getItemFromData( name ) );
10072 page.setOutlineItem( null );
10073 }
10074 }
10075 if ( this.outlined && items.length ) {
10076 this.outlineSelectWidget.removeItems( items );
10077 this.selectFirstSelectablePage();
10078 }
10079 this.stackLayout.removeItems( pages );
10080 this.emit( 'remove', pages );
10081
10082 return this;
10083 };
10084
10085 /**
10086 * Clear all pages from the booklet layout.
10087 *
10088 * To remove only a subset of pages from the booklet, use the #removePages method.
10089 *
10090 * @fires remove
10091 * @chainable
10092 */
10093 OO.ui.BookletLayout.prototype.clearPages = function () {
10094 var i, len,
10095 pages = this.stackLayout.getItems();
10096
10097 this.pages = {};
10098 this.currentPageName = null;
10099 if ( this.outlined ) {
10100 this.outlineSelectWidget.clearItems();
10101 for ( i = 0, len = pages.length; i < len; i++ ) {
10102 pages[ i ].setOutlineItem( null );
10103 }
10104 }
10105 this.stackLayout.clearItems();
10106
10107 this.emit( 'remove', pages );
10108
10109 return this;
10110 };
10111
10112 /**
10113 * Set the current page by symbolic name.
10114 *
10115 * @fires set
10116 * @param {string} name Symbolic name of page
10117 */
10118 OO.ui.BookletLayout.prototype.setPage = function ( name ) {
10119 var selectedItem,
10120 $focused,
10121 page = this.pages[ name ],
10122 previousPage = this.currentPageName && this.pages[ this.currentPageName ];
10123
10124 if ( name !== this.currentPageName ) {
10125 if ( this.outlined ) {
10126 selectedItem = this.outlineSelectWidget.getSelectedItem();
10127 if ( selectedItem && selectedItem.getData() !== name ) {
10128 this.outlineSelectWidget.selectItemByData( name );
10129 }
10130 }
10131 if ( page ) {
10132 if ( previousPage ) {
10133 previousPage.setActive( false );
10134 // Blur anything focused if the next page doesn't have anything focusable.
10135 // This is not needed if the next page has something focusable (because once it is focused
10136 // this blur happens automatically). If the layout is non-continuous, this check is
10137 // meaningless because the next page is not visible yet and thus can't hold focus.
10138 if (
10139 this.autoFocus &&
10140 this.stackLayout.continuous &&
10141 OO.ui.findFocusable( page.$element ).length !== 0
10142 ) {
10143 $focused = previousPage.$element.find( ':focus' );
10144 if ( $focused.length ) {
10145 $focused[ 0 ].blur();
10146 }
10147 }
10148 }
10149 this.currentPageName = name;
10150 page.setActive( true );
10151 this.stackLayout.setItem( page );
10152 if ( !this.stackLayout.continuous && previousPage ) {
10153 // This should not be necessary, since any inputs on the previous page should have been
10154 // blurred when it was hidden, but browsers are not very consistent about this.
10155 $focused = previousPage.$element.find( ':focus' );
10156 if ( $focused.length ) {
10157 $focused[ 0 ].blur();
10158 }
10159 }
10160 this.emit( 'set', page );
10161 }
10162 }
10163 };
10164
10165 /**
10166 * Select the first selectable page.
10167 *
10168 * @chainable
10169 */
10170 OO.ui.BookletLayout.prototype.selectFirstSelectablePage = function () {
10171 if ( !this.outlineSelectWidget.getSelectedItem() ) {
10172 this.outlineSelectWidget.selectItem( this.outlineSelectWidget.getFirstSelectableItem() );
10173 }
10174
10175 return this;
10176 };
10177
10178 /**
10179 * IndexLayouts contain {@link OO.ui.CardLayout card layouts} as well as
10180 * {@link OO.ui.TabSelectWidget tabs} that allow users to easily navigate through the cards and
10181 * select which one to display. By default, only one card is displayed at a time. When a user
10182 * navigates to a new card, the index layout automatically focuses on the first focusable element,
10183 * unless the default setting is changed.
10184 *
10185 * TODO: This class is similar to BookletLayout, we may want to refactor to reduce duplication
10186 *
10187 * @example
10188 * // Example of a IndexLayout that contains two CardLayouts.
10189 *
10190 * function CardOneLayout( name, config ) {
10191 * CardOneLayout.parent.call( this, name, config );
10192 * this.$element.append( '<p>First card</p>' );
10193 * }
10194 * OO.inheritClass( CardOneLayout, OO.ui.CardLayout );
10195 * CardOneLayout.prototype.setupTabItem = function () {
10196 * this.tabItem.setLabel( 'Card one' );
10197 * };
10198 *
10199 * var card1 = new CardOneLayout( 'one' ),
10200 * card2 = new CardLayout( 'two', { label: 'Card two' } );
10201 *
10202 * card2.$element.append( '<p>Second card</p>' );
10203 *
10204 * var index = new OO.ui.IndexLayout();
10205 *
10206 * index.addCards ( [ card1, card2 ] );
10207 * $( 'body' ).append( index.$element );
10208 *
10209 * @class
10210 * @extends OO.ui.MenuLayout
10211 *
10212 * @constructor
10213 * @param {Object} [config] Configuration options
10214 * @cfg {boolean} [continuous=false] Show all cards, one after another
10215 * @cfg {boolean} [expanded=true] Expand the content panel to fill the entire parent element.
10216 * @cfg {boolean} [autoFocus=true] Focus on the first focusable element when a new card is displayed.
10217 */
10218 OO.ui.IndexLayout = function OoUiIndexLayout( config ) {
10219 // Configuration initialization
10220 config = $.extend( {}, config, { menuPosition: 'top' } );
10221
10222 // Parent constructor
10223 OO.ui.IndexLayout.parent.call( this, config );
10224
10225 // Properties
10226 this.currentCardName = null;
10227 this.cards = {};
10228 this.ignoreFocus = false;
10229 this.stackLayout = new OO.ui.StackLayout( {
10230 continuous: !!config.continuous,
10231 expanded: config.expanded
10232 } );
10233 this.$content.append( this.stackLayout.$element );
10234 this.autoFocus = config.autoFocus === undefined || !!config.autoFocus;
10235
10236 this.tabSelectWidget = new OO.ui.TabSelectWidget();
10237 this.tabPanel = new OO.ui.PanelLayout();
10238 this.$menu.append( this.tabPanel.$element );
10239
10240 this.toggleMenu( true );
10241
10242 // Events
10243 this.stackLayout.connect( this, { set: 'onStackLayoutSet' } );
10244 this.tabSelectWidget.connect( this, { select: 'onTabSelectWidgetSelect' } );
10245 if ( this.autoFocus ) {
10246 // Event 'focus' does not bubble, but 'focusin' does
10247 this.stackLayout.$element.on( 'focusin', this.onStackLayoutFocus.bind( this ) );
10248 }
10249
10250 // Initialization
10251 this.$element.addClass( 'oo-ui-indexLayout' );
10252 this.stackLayout.$element.addClass( 'oo-ui-indexLayout-stackLayout' );
10253 this.tabPanel.$element
10254 .addClass( 'oo-ui-indexLayout-tabPanel' )
10255 .append( this.tabSelectWidget.$element );
10256 };
10257
10258 /* Setup */
10259
10260 OO.inheritClass( OO.ui.IndexLayout, OO.ui.MenuLayout );
10261
10262 /* Events */
10263
10264 /**
10265 * A 'set' event is emitted when a card is {@link #setCard set} to be displayed by the index layout.
10266 * @event set
10267 * @param {OO.ui.CardLayout} card Current card
10268 */
10269
10270 /**
10271 * An 'add' event is emitted when cards are {@link #addCards added} to the index layout.
10272 *
10273 * @event add
10274 * @param {OO.ui.CardLayout[]} card Added cards
10275 * @param {number} index Index cards were added at
10276 */
10277
10278 /**
10279 * A 'remove' event is emitted when cards are {@link #clearCards cleared} or
10280 * {@link #removeCards removed} from the index.
10281 *
10282 * @event remove
10283 * @param {OO.ui.CardLayout[]} cards Removed cards
10284 */
10285
10286 /* Methods */
10287
10288 /**
10289 * Handle stack layout focus.
10290 *
10291 * @private
10292 * @param {jQuery.Event} e Focusin event
10293 */
10294 OO.ui.IndexLayout.prototype.onStackLayoutFocus = function ( e ) {
10295 var name, $target;
10296
10297 // Find the card that an element was focused within
10298 $target = $( e.target ).closest( '.oo-ui-cardLayout' );
10299 for ( name in this.cards ) {
10300 // Check for card match, exclude current card to find only card changes
10301 if ( this.cards[ name ].$element[ 0 ] === $target[ 0 ] && name !== this.currentCardName ) {
10302 this.setCard( name );
10303 break;
10304 }
10305 }
10306 };
10307
10308 /**
10309 * Handle stack layout set events.
10310 *
10311 * @private
10312 * @param {OO.ui.PanelLayout|null} card The card panel that is now the current panel
10313 */
10314 OO.ui.IndexLayout.prototype.onStackLayoutSet = function ( card ) {
10315 var layout = this;
10316 if ( card ) {
10317 card.scrollElementIntoView( { complete: function () {
10318 if ( layout.autoFocus ) {
10319 layout.focus();
10320 }
10321 } } );
10322 }
10323 };
10324
10325 /**
10326 * Focus the first input in the current card.
10327 *
10328 * If no card is selected, the first selectable card will be selected.
10329 * If the focus is already in an element on the current card, nothing will happen.
10330 * @param {number} [itemIndex] A specific item to focus on
10331 */
10332 OO.ui.IndexLayout.prototype.focus = function ( itemIndex ) {
10333 var card,
10334 items = this.stackLayout.getItems();
10335
10336 if ( itemIndex !== undefined && items[ itemIndex ] ) {
10337 card = items[ itemIndex ];
10338 } else {
10339 card = this.stackLayout.getCurrentItem();
10340 }
10341
10342 if ( !card ) {
10343 this.selectFirstSelectableCard();
10344 card = this.stackLayout.getCurrentItem();
10345 }
10346 if ( !card ) {
10347 return;
10348 }
10349 // Only change the focus if is not already in the current card
10350 if ( !card.$element.find( ':focus' ).length ) {
10351 OO.ui.findFocusable( card.$element ).focus();
10352 }
10353 };
10354
10355 /**
10356 * Find the first focusable input in the index layout and focus
10357 * on it.
10358 */
10359 OO.ui.IndexLayout.prototype.focusFirstFocusable = function () {
10360 OO.ui.findFocusable( this.stackLayout.$element ).focus();
10361 };
10362
10363 /**
10364 * Handle tab widget select events.
10365 *
10366 * @private
10367 * @param {OO.ui.OptionWidget|null} item Selected item
10368 */
10369 OO.ui.IndexLayout.prototype.onTabSelectWidgetSelect = function ( item ) {
10370 if ( item ) {
10371 this.setCard( item.getData() );
10372 }
10373 };
10374
10375 /**
10376 * Get the card closest to the specified card.
10377 *
10378 * @param {OO.ui.CardLayout} card Card to use as a reference point
10379 * @return {OO.ui.CardLayout|null} Card closest to the specified card
10380 */
10381 OO.ui.IndexLayout.prototype.getClosestCard = function ( card ) {
10382 var next, prev, level,
10383 cards = this.stackLayout.getItems(),
10384 index = cards.indexOf( card );
10385
10386 if ( index !== -1 ) {
10387 next = cards[ index + 1 ];
10388 prev = cards[ index - 1 ];
10389 // Prefer adjacent cards at the same level
10390 level = this.tabSelectWidget.getItemFromData( card.getName() ).getLevel();
10391 if (
10392 prev &&
10393 level === this.tabSelectWidget.getItemFromData( prev.getName() ).getLevel()
10394 ) {
10395 return prev;
10396 }
10397 if (
10398 next &&
10399 level === this.tabSelectWidget.getItemFromData( next.getName() ).getLevel()
10400 ) {
10401 return next;
10402 }
10403 }
10404 return prev || next || null;
10405 };
10406
10407 /**
10408 * Get the tabs widget.
10409 *
10410 * @return {OO.ui.TabSelectWidget} Tabs widget
10411 */
10412 OO.ui.IndexLayout.prototype.getTabs = function () {
10413 return this.tabSelectWidget;
10414 };
10415
10416 /**
10417 * Get a card by its symbolic name.
10418 *
10419 * @param {string} name Symbolic name of card
10420 * @return {OO.ui.CardLayout|undefined} Card, if found
10421 */
10422 OO.ui.IndexLayout.prototype.getCard = function ( name ) {
10423 return this.cards[ name ];
10424 };
10425
10426 /**
10427 * Get the current card.
10428 *
10429 * @return {OO.ui.CardLayout|undefined} Current card, if found
10430 */
10431 OO.ui.IndexLayout.prototype.getCurrentCard = function () {
10432 var name = this.getCurrentCardName();
10433 return name ? this.getCard( name ) : undefined;
10434 };
10435
10436 /**
10437 * Get the symbolic name of the current card.
10438 *
10439 * @return {string|null} Symbolic name of the current card
10440 */
10441 OO.ui.IndexLayout.prototype.getCurrentCardName = function () {
10442 return this.currentCardName;
10443 };
10444
10445 /**
10446 * Add cards to the index layout
10447 *
10448 * When cards are added with the same names as existing cards, the existing cards will be
10449 * automatically removed before the new cards are added.
10450 *
10451 * @param {OO.ui.CardLayout[]} cards Cards to add
10452 * @param {number} index Index of the insertion point
10453 * @fires add
10454 * @chainable
10455 */
10456 OO.ui.IndexLayout.prototype.addCards = function ( cards, index ) {
10457 var i, len, name, card, item, currentIndex,
10458 stackLayoutCards = this.stackLayout.getItems(),
10459 remove = [],
10460 items = [];
10461
10462 // Remove cards with same names
10463 for ( i = 0, len = cards.length; i < len; i++ ) {
10464 card = cards[ i ];
10465 name = card.getName();
10466
10467 if ( Object.prototype.hasOwnProperty.call( this.cards, name ) ) {
10468 // Correct the insertion index
10469 currentIndex = stackLayoutCards.indexOf( this.cards[ name ] );
10470 if ( currentIndex !== -1 && currentIndex + 1 < index ) {
10471 index--;
10472 }
10473 remove.push( this.cards[ name ] );
10474 }
10475 }
10476 if ( remove.length ) {
10477 this.removeCards( remove );
10478 }
10479
10480 // Add new cards
10481 for ( i = 0, len = cards.length; i < len; i++ ) {
10482 card = cards[ i ];
10483 name = card.getName();
10484 this.cards[ card.getName() ] = card;
10485 item = new OO.ui.TabOptionWidget( { data: name } );
10486 card.setTabItem( item );
10487 items.push( item );
10488 }
10489
10490 if ( items.length ) {
10491 this.tabSelectWidget.addItems( items, index );
10492 this.selectFirstSelectableCard();
10493 }
10494 this.stackLayout.addItems( cards, index );
10495 this.emit( 'add', cards, index );
10496
10497 return this;
10498 };
10499
10500 /**
10501 * Remove the specified cards from the index layout.
10502 *
10503 * To remove all cards from the index, you may wish to use the #clearCards method instead.
10504 *
10505 * @param {OO.ui.CardLayout[]} cards An array of cards to remove
10506 * @fires remove
10507 * @chainable
10508 */
10509 OO.ui.IndexLayout.prototype.removeCards = function ( cards ) {
10510 var i, len, name, card,
10511 items = [];
10512
10513 for ( i = 0, len = cards.length; i < len; i++ ) {
10514 card = cards[ i ];
10515 name = card.getName();
10516 delete this.cards[ name ];
10517 items.push( this.tabSelectWidget.getItemFromData( name ) );
10518 card.setTabItem( null );
10519 }
10520 if ( items.length ) {
10521 this.tabSelectWidget.removeItems( items );
10522 this.selectFirstSelectableCard();
10523 }
10524 this.stackLayout.removeItems( cards );
10525 this.emit( 'remove', cards );
10526
10527 return this;
10528 };
10529
10530 /**
10531 * Clear all cards from the index layout.
10532 *
10533 * To remove only a subset of cards from the index, use the #removeCards method.
10534 *
10535 * @fires remove
10536 * @chainable
10537 */
10538 OO.ui.IndexLayout.prototype.clearCards = function () {
10539 var i, len,
10540 cards = this.stackLayout.getItems();
10541
10542 this.cards = {};
10543 this.currentCardName = null;
10544 this.tabSelectWidget.clearItems();
10545 for ( i = 0, len = cards.length; i < len; i++ ) {
10546 cards[ i ].setTabItem( null );
10547 }
10548 this.stackLayout.clearItems();
10549
10550 this.emit( 'remove', cards );
10551
10552 return this;
10553 };
10554
10555 /**
10556 * Set the current card by symbolic name.
10557 *
10558 * @fires set
10559 * @param {string} name Symbolic name of card
10560 */
10561 OO.ui.IndexLayout.prototype.setCard = function ( name ) {
10562 var selectedItem,
10563 $focused,
10564 card = this.cards[ name ],
10565 previousCard = this.currentCardName && this.cards[ this.currentCardName ];
10566
10567 if ( name !== this.currentCardName ) {
10568 selectedItem = this.tabSelectWidget.getSelectedItem();
10569 if ( selectedItem && selectedItem.getData() !== name ) {
10570 this.tabSelectWidget.selectItemByData( name );
10571 }
10572 if ( card ) {
10573 if ( previousCard ) {
10574 previousCard.setActive( false );
10575 // Blur anything focused if the next card doesn't have anything focusable.
10576 // This is not needed if the next card has something focusable (because once it is focused
10577 // this blur happens automatically). If the layout is non-continuous, this check is
10578 // meaningless because the next card is not visible yet and thus can't hold focus.
10579 if (
10580 this.autoFocus &&
10581 this.stackLayout.continuous &&
10582 OO.ui.findFocusable( card.$element ).length !== 0
10583 ) {
10584 $focused = previousCard.$element.find( ':focus' );
10585 if ( $focused.length ) {
10586 $focused[ 0 ].blur();
10587 }
10588 }
10589 }
10590 this.currentCardName = name;
10591 card.setActive( true );
10592 this.stackLayout.setItem( card );
10593 if ( !this.stackLayout.continuous && previousCard ) {
10594 // This should not be necessary, since any inputs on the previous card should have been
10595 // blurred when it was hidden, but browsers are not very consistent about this.
10596 $focused = previousCard.$element.find( ':focus' );
10597 if ( $focused.length ) {
10598 $focused[ 0 ].blur();
10599 }
10600 }
10601 this.emit( 'set', card );
10602 }
10603 }
10604 };
10605
10606 /**
10607 * Select the first selectable card.
10608 *
10609 * @chainable
10610 */
10611 OO.ui.IndexLayout.prototype.selectFirstSelectableCard = function () {
10612 if ( !this.tabSelectWidget.getSelectedItem() ) {
10613 this.tabSelectWidget.selectItem( this.tabSelectWidget.getFirstSelectableItem() );
10614 }
10615
10616 return this;
10617 };
10618
10619 /**
10620 * PanelLayouts expand to cover the entire area of their parent. They can be configured with scrolling, padding,
10621 * and a frame, and are often used together with {@link OO.ui.StackLayout StackLayouts}.
10622 *
10623 * @example
10624 * // Example of a panel layout
10625 * var panel = new OO.ui.PanelLayout( {
10626 * expanded: false,
10627 * framed: true,
10628 * padded: true,
10629 * $content: $( '<p>A panel layout with padding and a frame.</p>' )
10630 * } );
10631 * $( 'body' ).append( panel.$element );
10632 *
10633 * @class
10634 * @extends OO.ui.Layout
10635 *
10636 * @constructor
10637 * @param {Object} [config] Configuration options
10638 * @cfg {boolean} [scrollable=false] Allow vertical scrolling
10639 * @cfg {boolean} [padded=false] Add padding between the content and the edges of the panel.
10640 * @cfg {boolean} [expanded=true] Expand the panel to fill the entire parent element.
10641 * @cfg {boolean} [framed=false] Render the panel with a frame to visually separate it from outside content.
10642 */
10643 OO.ui.PanelLayout = function OoUiPanelLayout( config ) {
10644 // Configuration initialization
10645 config = $.extend( {
10646 scrollable: false,
10647 padded: false,
10648 expanded: true,
10649 framed: false
10650 }, config );
10651
10652 // Parent constructor
10653 OO.ui.PanelLayout.parent.call( this, config );
10654
10655 // Initialization
10656 this.$element.addClass( 'oo-ui-panelLayout' );
10657 if ( config.scrollable ) {
10658 this.$element.addClass( 'oo-ui-panelLayout-scrollable' );
10659 }
10660 if ( config.padded ) {
10661 this.$element.addClass( 'oo-ui-panelLayout-padded' );
10662 }
10663 if ( config.expanded ) {
10664 this.$element.addClass( 'oo-ui-panelLayout-expanded' );
10665 }
10666 if ( config.framed ) {
10667 this.$element.addClass( 'oo-ui-panelLayout-framed' );
10668 }
10669 };
10670
10671 /* Setup */
10672
10673 OO.inheritClass( OO.ui.PanelLayout, OO.ui.Layout );
10674
10675 /**
10676 * CardLayouts are used within {@link OO.ui.IndexLayout index layouts} to create cards that users can select and display
10677 * from the index's optional {@link OO.ui.TabSelectWidget tab} navigation. Cards are usually not instantiated directly,
10678 * rather extended to include the required content and functionality.
10679 *
10680 * Each card must have a unique symbolic name, which is passed to the constructor. In addition, the card's tab
10681 * item is customized (with a label) using the #setupTabItem method. See
10682 * {@link OO.ui.IndexLayout IndexLayout} for an example.
10683 *
10684 * @class
10685 * @extends OO.ui.PanelLayout
10686 *
10687 * @constructor
10688 * @param {string} name Unique symbolic name of card
10689 * @param {Object} [config] Configuration options
10690 * @cfg {jQuery|string|Function|OO.ui.HtmlSnippet} [label] Label for card's tab
10691 */
10692 OO.ui.CardLayout = function OoUiCardLayout( name, config ) {
10693 // Allow passing positional parameters inside the config object
10694 if ( OO.isPlainObject( name ) && config === undefined ) {
10695 config = name;
10696 name = config.name;
10697 }
10698
10699 // Configuration initialization
10700 config = $.extend( { scrollable: true }, config );
10701
10702 // Parent constructor
10703 OO.ui.CardLayout.parent.call( this, config );
10704
10705 // Properties
10706 this.name = name;
10707 this.label = config.label;
10708 this.tabItem = null;
10709 this.active = false;
10710
10711 // Initialization
10712 this.$element.addClass( 'oo-ui-cardLayout' );
10713 };
10714
10715 /* Setup */
10716
10717 OO.inheritClass( OO.ui.CardLayout, OO.ui.PanelLayout );
10718
10719 /* Events */
10720
10721 /**
10722 * An 'active' event is emitted when the card becomes active. Cards become active when they are
10723 * shown in a index layout that is configured to display only one card at a time.
10724 *
10725 * @event active
10726 * @param {boolean} active Card is active
10727 */
10728
10729 /* Methods */
10730
10731 /**
10732 * Get the symbolic name of the card.
10733 *
10734 * @return {string} Symbolic name of card
10735 */
10736 OO.ui.CardLayout.prototype.getName = function () {
10737 return this.name;
10738 };
10739
10740 /**
10741 * Check if card is active.
10742 *
10743 * Cards become active when they are shown in a {@link OO.ui.IndexLayout index layout} that is configured to display
10744 * only one card at a time. Additional CSS is applied to the card's tab item to reflect the active state.
10745 *
10746 * @return {boolean} Card is active
10747 */
10748 OO.ui.CardLayout.prototype.isActive = function () {
10749 return this.active;
10750 };
10751
10752 /**
10753 * Get tab item.
10754 *
10755 * The tab item allows users to access the card from the index's tab
10756 * navigation. The tab item itself can be customized (with a label, level, etc.) using the #setupTabItem method.
10757 *
10758 * @return {OO.ui.TabOptionWidget|null} Tab option widget
10759 */
10760 OO.ui.CardLayout.prototype.getTabItem = function () {
10761 return this.tabItem;
10762 };
10763
10764 /**
10765 * Set or unset the tab item.
10766 *
10767 * Specify a {@link OO.ui.TabOptionWidget tab option} to set it,
10768 * or `null` to clear the tab item. To customize the tab item itself (e.g., to set a label or tab
10769 * level), use #setupTabItem instead of this method.
10770 *
10771 * @param {OO.ui.TabOptionWidget|null} tabItem Tab option widget, null to clear
10772 * @chainable
10773 */
10774 OO.ui.CardLayout.prototype.setTabItem = function ( tabItem ) {
10775 this.tabItem = tabItem || null;
10776 if ( tabItem ) {
10777 this.setupTabItem();
10778 }
10779 return this;
10780 };
10781
10782 /**
10783 * Set up the tab item.
10784 *
10785 * Use this method to customize the tab item (e.g., to add a label or tab level). To set or unset
10786 * the tab item itself (with a {@link OO.ui.TabOptionWidget tab option} or `null`), use
10787 * the #setTabItem method instead.
10788 *
10789 * @param {OO.ui.TabOptionWidget} tabItem Tab option widget to set up
10790 * @chainable
10791 */
10792 OO.ui.CardLayout.prototype.setupTabItem = function () {
10793 if ( this.label ) {
10794 this.tabItem.setLabel( this.label );
10795 }
10796 return this;
10797 };
10798
10799 /**
10800 * Set the card to its 'active' state.
10801 *
10802 * Cards become active when they are shown in a index layout that is configured to display only one card at a time. Additional
10803 * CSS is applied to the tab item to reflect the card's active state. Outside of the index
10804 * context, setting the active state on a card does nothing.
10805 *
10806 * @param {boolean} value Card is active
10807 * @fires active
10808 */
10809 OO.ui.CardLayout.prototype.setActive = function ( active ) {
10810 active = !!active;
10811
10812 if ( active !== this.active ) {
10813 this.active = active;
10814 this.$element.toggleClass( 'oo-ui-cardLayout-active', this.active );
10815 this.emit( 'active', this.active );
10816 }
10817 };
10818
10819 /**
10820 * PageLayouts are used within {@link OO.ui.BookletLayout booklet layouts} to create pages that users can select and display
10821 * from the booklet's optional {@link OO.ui.OutlineSelectWidget outline} navigation. Pages are usually not instantiated directly,
10822 * rather extended to include the required content and functionality.
10823 *
10824 * Each page must have a unique symbolic name, which is passed to the constructor. In addition, the page's outline
10825 * item is customized (with a label, outline level, etc.) using the #setupOutlineItem method. See
10826 * {@link OO.ui.BookletLayout BookletLayout} for an example.
10827 *
10828 * @class
10829 * @extends OO.ui.PanelLayout
10830 *
10831 * @constructor
10832 * @param {string} name Unique symbolic name of page
10833 * @param {Object} [config] Configuration options
10834 */
10835 OO.ui.PageLayout = function OoUiPageLayout( name, config ) {
10836 // Allow passing positional parameters inside the config object
10837 if ( OO.isPlainObject( name ) && config === undefined ) {
10838 config = name;
10839 name = config.name;
10840 }
10841
10842 // Configuration initialization
10843 config = $.extend( { scrollable: true }, config );
10844
10845 // Parent constructor
10846 OO.ui.PageLayout.parent.call( this, config );
10847
10848 // Properties
10849 this.name = name;
10850 this.outlineItem = null;
10851 this.active = false;
10852
10853 // Initialization
10854 this.$element.addClass( 'oo-ui-pageLayout' );
10855 };
10856
10857 /* Setup */
10858
10859 OO.inheritClass( OO.ui.PageLayout, OO.ui.PanelLayout );
10860
10861 /* Events */
10862
10863 /**
10864 * An 'active' event is emitted when the page becomes active. Pages become active when they are
10865 * shown in a booklet layout that is configured to display only one page at a time.
10866 *
10867 * @event active
10868 * @param {boolean} active Page is active
10869 */
10870
10871 /* Methods */
10872
10873 /**
10874 * Get the symbolic name of the page.
10875 *
10876 * @return {string} Symbolic name of page
10877 */
10878 OO.ui.PageLayout.prototype.getName = function () {
10879 return this.name;
10880 };
10881
10882 /**
10883 * Check if page is active.
10884 *
10885 * Pages become active when they are shown in a {@link OO.ui.BookletLayout booklet layout} that is configured to display
10886 * only one page at a time. Additional CSS is applied to the page's outline item to reflect the active state.
10887 *
10888 * @return {boolean} Page is active
10889 */
10890 OO.ui.PageLayout.prototype.isActive = function () {
10891 return this.active;
10892 };
10893
10894 /**
10895 * Get outline item.
10896 *
10897 * The outline item allows users to access the page from the booklet's outline
10898 * navigation. The outline item itself can be customized (with a label, level, etc.) using the #setupOutlineItem method.
10899 *
10900 * @return {OO.ui.OutlineOptionWidget|null} Outline option widget
10901 */
10902 OO.ui.PageLayout.prototype.getOutlineItem = function () {
10903 return this.outlineItem;
10904 };
10905
10906 /**
10907 * Set or unset the outline item.
10908 *
10909 * Specify an {@link OO.ui.OutlineOptionWidget outline option} to set it,
10910 * or `null` to clear the outline item. To customize the outline item itself (e.g., to set a label or outline
10911 * level), use #setupOutlineItem instead of this method.
10912 *
10913 * @param {OO.ui.OutlineOptionWidget|null} outlineItem Outline option widget, null to clear
10914 * @chainable
10915 */
10916 OO.ui.PageLayout.prototype.setOutlineItem = function ( outlineItem ) {
10917 this.outlineItem = outlineItem || null;
10918 if ( outlineItem ) {
10919 this.setupOutlineItem();
10920 }
10921 return this;
10922 };
10923
10924 /**
10925 * Set up the outline item.
10926 *
10927 * Use this method to customize the outline item (e.g., to add a label or outline level). To set or unset
10928 * the outline item itself (with an {@link OO.ui.OutlineOptionWidget outline option} or `null`), use
10929 * the #setOutlineItem method instead.
10930 *
10931 * @param {OO.ui.OutlineOptionWidget} outlineItem Outline option widget to set up
10932 * @chainable
10933 */
10934 OO.ui.PageLayout.prototype.setupOutlineItem = function () {
10935 return this;
10936 };
10937
10938 /**
10939 * Set the page to its 'active' state.
10940 *
10941 * Pages become active when they are shown in a booklet layout that is configured to display only one page at a time. Additional
10942 * CSS is applied to the outline item to reflect the page's active state. Outside of the booklet
10943 * context, setting the active state on a page does nothing.
10944 *
10945 * @param {boolean} value Page is active
10946 * @fires active
10947 */
10948 OO.ui.PageLayout.prototype.setActive = function ( active ) {
10949 active = !!active;
10950
10951 if ( active !== this.active ) {
10952 this.active = active;
10953 this.$element.toggleClass( 'oo-ui-pageLayout-active', active );
10954 this.emit( 'active', this.active );
10955 }
10956 };
10957
10958 /**
10959 * StackLayouts contain a series of {@link OO.ui.PanelLayout panel layouts}. By default, only one panel is displayed
10960 * at a time, though the stack layout can also be configured to show all contained panels, one after another,
10961 * by setting the #continuous option to 'true'.
10962 *
10963 * @example
10964 * // A stack layout with two panels, configured to be displayed continously
10965 * var myStack = new OO.ui.StackLayout( {
10966 * items: [
10967 * new OO.ui.PanelLayout( {
10968 * $content: $( '<p>Panel One</p>' ),
10969 * padded: true,
10970 * framed: true
10971 * } ),
10972 * new OO.ui.PanelLayout( {
10973 * $content: $( '<p>Panel Two</p>' ),
10974 * padded: true,
10975 * framed: true
10976 * } )
10977 * ],
10978 * continuous: true
10979 * } );
10980 * $( 'body' ).append( myStack.$element );
10981 *
10982 * @class
10983 * @extends OO.ui.PanelLayout
10984 * @mixins OO.ui.mixin.GroupElement
10985 *
10986 * @constructor
10987 * @param {Object} [config] Configuration options
10988 * @cfg {boolean} [continuous=false] Show all panels, one after another. By default, only one panel is displayed at a time.
10989 * @cfg {OO.ui.Layout[]} [items] Panel layouts to add to the stack layout.
10990 */
10991 OO.ui.StackLayout = function OoUiStackLayout( config ) {
10992 // Configuration initialization
10993 config = $.extend( { scrollable: true }, config );
10994
10995 // Parent constructor
10996 OO.ui.StackLayout.parent.call( this, config );
10997
10998 // Mixin constructors
10999 OO.ui.mixin.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) );
11000
11001 // Properties
11002 this.currentItem = null;
11003 this.continuous = !!config.continuous;
11004
11005 // Initialization
11006 this.$element.addClass( 'oo-ui-stackLayout' );
11007 if ( this.continuous ) {
11008 this.$element.addClass( 'oo-ui-stackLayout-continuous' );
11009 }
11010 if ( Array.isArray( config.items ) ) {
11011 this.addItems( config.items );
11012 }
11013 };
11014
11015 /* Setup */
11016
11017 OO.inheritClass( OO.ui.StackLayout, OO.ui.PanelLayout );
11018 OO.mixinClass( OO.ui.StackLayout, OO.ui.mixin.GroupElement );
11019
11020 /* Events */
11021
11022 /**
11023 * A 'set' event is emitted when panels are {@link #addItems added}, {@link #removeItems removed},
11024 * {@link #clearItems cleared} or {@link #setItem displayed}.
11025 *
11026 * @event set
11027 * @param {OO.ui.Layout|null} item Current panel or `null` if no panel is shown
11028 */
11029
11030 /* Methods */
11031
11032 /**
11033 * Get the current panel.
11034 *
11035 * @return {OO.ui.Layout|null}
11036 */
11037 OO.ui.StackLayout.prototype.getCurrentItem = function () {
11038 return this.currentItem;
11039 };
11040
11041 /**
11042 * Unset the current item.
11043 *
11044 * @private
11045 * @param {OO.ui.StackLayout} layout
11046 * @fires set
11047 */
11048 OO.ui.StackLayout.prototype.unsetCurrentItem = function () {
11049 var prevItem = this.currentItem;
11050 if ( prevItem === null ) {
11051 return;
11052 }
11053
11054 this.currentItem = null;
11055 this.emit( 'set', null );
11056 };
11057
11058 /**
11059 * Add panel layouts to the stack layout.
11060 *
11061 * Panels will be added to the end of the stack layout array unless the optional index parameter specifies a different
11062 * insertion point. Adding a panel that is already in the stack will move it to the end of the array or the point specified
11063 * by the index.
11064 *
11065 * @param {OO.ui.Layout[]} items Panels to add
11066 * @param {number} [index] Index of the insertion point
11067 * @chainable
11068 */
11069 OO.ui.StackLayout.prototype.addItems = function ( items, index ) {
11070 // Update the visibility
11071 this.updateHiddenState( items, this.currentItem );
11072
11073 // Mixin method
11074 OO.ui.mixin.GroupElement.prototype.addItems.call( this, items, index );
11075
11076 if ( !this.currentItem && items.length ) {
11077 this.setItem( items[ 0 ] );
11078 }
11079
11080 return this;
11081 };
11082
11083 /**
11084 * Remove the specified panels from the stack layout.
11085 *
11086 * Removed panels are detached from the DOM, not removed, so that they may be reused. To remove all panels,
11087 * you may wish to use the #clearItems method instead.
11088 *
11089 * @param {OO.ui.Layout[]} items Panels to remove
11090 * @chainable
11091 * @fires set
11092 */
11093 OO.ui.StackLayout.prototype.removeItems = function ( items ) {
11094 // Mixin method
11095 OO.ui.mixin.GroupElement.prototype.removeItems.call( this, items );
11096
11097 if ( items.indexOf( this.currentItem ) !== -1 ) {
11098 if ( this.items.length ) {
11099 this.setItem( this.items[ 0 ] );
11100 } else {
11101 this.unsetCurrentItem();
11102 }
11103 }
11104
11105 return this;
11106 };
11107
11108 /**
11109 * Clear all panels from the stack layout.
11110 *
11111 * Cleared panels are detached from the DOM, not removed, so that they may be reused. To remove only
11112 * a subset of panels, use the #removeItems method.
11113 *
11114 * @chainable
11115 * @fires set
11116 */
11117 OO.ui.StackLayout.prototype.clearItems = function () {
11118 this.unsetCurrentItem();
11119 OO.ui.mixin.GroupElement.prototype.clearItems.call( this );
11120
11121 return this;
11122 };
11123
11124 /**
11125 * Show the specified panel.
11126 *
11127 * If another panel is currently displayed, it will be hidden.
11128 *
11129 * @param {OO.ui.Layout} item Panel to show
11130 * @chainable
11131 * @fires set
11132 */
11133 OO.ui.StackLayout.prototype.setItem = function ( item ) {
11134 if ( item !== this.currentItem ) {
11135 this.updateHiddenState( this.items, item );
11136
11137 if ( this.items.indexOf( item ) !== -1 ) {
11138 this.currentItem = item;
11139 this.emit( 'set', item );
11140 } else {
11141 this.unsetCurrentItem();
11142 }
11143 }
11144
11145 return this;
11146 };
11147
11148 /**
11149 * Update the visibility of all items in case of non-continuous view.
11150 *
11151 * Ensure all items are hidden except for the selected one.
11152 * This method does nothing when the stack is continuous.
11153 *
11154 * @private
11155 * @param {OO.ui.Layout[]} items Item list iterate over
11156 * @param {OO.ui.Layout} [selectedItem] Selected item to show
11157 */
11158 OO.ui.StackLayout.prototype.updateHiddenState = function ( items, selectedItem ) {
11159 var i, len;
11160
11161 if ( !this.continuous ) {
11162 for ( i = 0, len = items.length; i < len; i++ ) {
11163 if ( !selectedItem || selectedItem !== items[ i ] ) {
11164 items[ i ].$element.addClass( 'oo-ui-element-hidden' );
11165 }
11166 }
11167 if ( selectedItem ) {
11168 selectedItem.$element.removeClass( 'oo-ui-element-hidden' );
11169 }
11170 }
11171 };
11172
11173 /**
11174 * HorizontalLayout arranges its contents in a single line (using `display: inline-block` for its
11175 * items), with small margins between them. Convenient when you need to put a number of block-level
11176 * widgets on a single line next to each other.
11177 *
11178 * Note that inline elements, such as OO.ui.ButtonWidgets, do not need this wrapper.
11179 *
11180 * @example
11181 * // HorizontalLayout with a text input and a label
11182 * var layout = new OO.ui.HorizontalLayout( {
11183 * items: [
11184 * new OO.ui.LabelWidget( { label: 'Label' } ),
11185 * new OO.ui.TextInputWidget( { value: 'Text' } )
11186 * ]
11187 * } );
11188 * $( 'body' ).append( layout.$element );
11189 *
11190 * @class
11191 * @extends OO.ui.Layout
11192 * @mixins OO.ui.mixin.GroupElement
11193 *
11194 * @constructor
11195 * @param {Object} [config] Configuration options
11196 * @cfg {OO.ui.Widget[]|OO.ui.Layout[]} [items] Widgets or other layouts to add to the layout.
11197 */
11198 OO.ui.HorizontalLayout = function OoUiHorizontalLayout( config ) {
11199 // Configuration initialization
11200 config = config || {};
11201
11202 // Parent constructor
11203 OO.ui.HorizontalLayout.parent.call( this, config );
11204
11205 // Mixin constructors
11206 OO.ui.mixin.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) );
11207
11208 // Initialization
11209 this.$element.addClass( 'oo-ui-horizontalLayout' );
11210 if ( Array.isArray( config.items ) ) {
11211 this.addItems( config.items );
11212 }
11213 };
11214
11215 /* Setup */
11216
11217 OO.inheritClass( OO.ui.HorizontalLayout, OO.ui.Layout );
11218 OO.mixinClass( OO.ui.HorizontalLayout, OO.ui.mixin.GroupElement );
11219
11220 /**
11221 * BarToolGroups are one of three types of {@link OO.ui.ToolGroup toolgroups} that are used to
11222 * create {@link OO.ui.Toolbar toolbars} (the other types of groups are {@link OO.ui.MenuToolGroup MenuToolGroup}
11223 * and {@link OO.ui.ListToolGroup ListToolGroup}). The {@link OO.ui.Tool tools} in a BarToolGroup are
11224 * displayed by icon in a single row. The title of the tool is displayed when users move the mouse over
11225 * the tool.
11226 *
11227 * BarToolGroups are created by a {@link OO.ui.ToolGroupFactory tool group factory} when the toolbar is
11228 * set up.
11229 *
11230 * @example
11231 * // Example of a BarToolGroup with two tools
11232 * var toolFactory = new OO.ui.ToolFactory();
11233 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
11234 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
11235 *
11236 * // We will be placing status text in this element when tools are used
11237 * var $area = $( '<p>' ).text( 'Example of a BarToolGroup with two tools.' );
11238 *
11239 * // Define the tools that we're going to place in our toolbar
11240 *
11241 * // Create a class inheriting from OO.ui.Tool
11242 * function PictureTool() {
11243 * PictureTool.parent.apply( this, arguments );
11244 * }
11245 * OO.inheritClass( PictureTool, OO.ui.Tool );
11246 * // Each tool must have a 'name' (used as an internal identifier, see later) and at least one
11247 * // of 'icon' and 'title' (displayed icon and text).
11248 * PictureTool.static.name = 'picture';
11249 * PictureTool.static.icon = 'picture';
11250 * PictureTool.static.title = 'Insert picture';
11251 * // Defines the action that will happen when this tool is selected (clicked).
11252 * PictureTool.prototype.onSelect = function () {
11253 * $area.text( 'Picture tool clicked!' );
11254 * // Never display this tool as "active" (selected).
11255 * this.setActive( false );
11256 * };
11257 * // Make this tool available in our toolFactory and thus our toolbar
11258 * toolFactory.register( PictureTool );
11259 *
11260 * // This is a PopupTool. Rather than having a custom 'onSelect' action, it will display a
11261 * // little popup window (a PopupWidget).
11262 * function HelpTool( toolGroup, config ) {
11263 * OO.ui.PopupTool.call( this, toolGroup, $.extend( { popup: {
11264 * padded: true,
11265 * label: 'Help',
11266 * head: true
11267 * } }, config ) );
11268 * this.popup.$body.append( '<p>I am helpful!</p>' );
11269 * }
11270 * OO.inheritClass( HelpTool, OO.ui.PopupTool );
11271 * HelpTool.static.name = 'help';
11272 * HelpTool.static.icon = 'help';
11273 * HelpTool.static.title = 'Help';
11274 * toolFactory.register( HelpTool );
11275 *
11276 * // Finally define which tools and in what order appear in the toolbar. Each tool may only be
11277 * // used once (but not all defined tools must be used).
11278 * toolbar.setup( [
11279 * {
11280 * // 'bar' tool groups display tools by icon only
11281 * type: 'bar',
11282 * include: [ 'picture', 'help' ]
11283 * }
11284 * ] );
11285 *
11286 * // Create some UI around the toolbar and place it in the document
11287 * var frame = new OO.ui.PanelLayout( {
11288 * expanded: false,
11289 * framed: true
11290 * } );
11291 * var contentFrame = new OO.ui.PanelLayout( {
11292 * expanded: false,
11293 * padded: true
11294 * } );
11295 * frame.$element.append(
11296 * toolbar.$element,
11297 * contentFrame.$element.append( $area )
11298 * );
11299 * $( 'body' ).append( frame.$element );
11300 *
11301 * // Here is where the toolbar is actually built. This must be done after inserting it into the
11302 * // document.
11303 * toolbar.initialize();
11304 *
11305 * For more information about how to add tools to a bar tool group, please see {@link OO.ui.ToolGroup toolgroup}.
11306 * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki][1].
11307 *
11308 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
11309 *
11310 * @class
11311 * @extends OO.ui.ToolGroup
11312 *
11313 * @constructor
11314 * @param {OO.ui.Toolbar} toolbar
11315 * @param {Object} [config] Configuration options
11316 */
11317 OO.ui.BarToolGroup = function OoUiBarToolGroup( toolbar, config ) {
11318 // Allow passing positional parameters inside the config object
11319 if ( OO.isPlainObject( toolbar ) && config === undefined ) {
11320 config = toolbar;
11321 toolbar = config.toolbar;
11322 }
11323
11324 // Parent constructor
11325 OO.ui.BarToolGroup.parent.call( this, toolbar, config );
11326
11327 // Initialization
11328 this.$element.addClass( 'oo-ui-barToolGroup' );
11329 };
11330
11331 /* Setup */
11332
11333 OO.inheritClass( OO.ui.BarToolGroup, OO.ui.ToolGroup );
11334
11335 /* Static Properties */
11336
11337 OO.ui.BarToolGroup.static.titleTooltips = true;
11338
11339 OO.ui.BarToolGroup.static.accelTooltips = true;
11340
11341 OO.ui.BarToolGroup.static.name = 'bar';
11342
11343 /**
11344 * PopupToolGroup is an abstract base class used by both {@link OO.ui.MenuToolGroup MenuToolGroup}
11345 * and {@link OO.ui.ListToolGroup ListToolGroup} to provide a popup--an overlaid menu or list of tools with an
11346 * optional icon and label. This class can be used for other base classes that also use this functionality.
11347 *
11348 * @abstract
11349 * @class
11350 * @extends OO.ui.ToolGroup
11351 * @mixins OO.ui.mixin.IconElement
11352 * @mixins OO.ui.mixin.IndicatorElement
11353 * @mixins OO.ui.mixin.LabelElement
11354 * @mixins OO.ui.mixin.TitledElement
11355 * @mixins OO.ui.mixin.ClippableElement
11356 * @mixins OO.ui.mixin.TabIndexedElement
11357 *
11358 * @constructor
11359 * @param {OO.ui.Toolbar} toolbar
11360 * @param {Object} [config] Configuration options
11361 * @cfg {string} [header] Text to display at the top of the popup
11362 */
11363 OO.ui.PopupToolGroup = function OoUiPopupToolGroup( toolbar, config ) {
11364 // Allow passing positional parameters inside the config object
11365 if ( OO.isPlainObject( toolbar ) && config === undefined ) {
11366 config = toolbar;
11367 toolbar = config.toolbar;
11368 }
11369
11370 // Configuration initialization
11371 config = config || {};
11372
11373 // Parent constructor
11374 OO.ui.PopupToolGroup.parent.call( this, toolbar, config );
11375
11376 // Properties
11377 this.active = false;
11378 this.dragging = false;
11379 this.onBlurHandler = this.onBlur.bind( this );
11380 this.$handle = $( '<span>' );
11381
11382 // Mixin constructors
11383 OO.ui.mixin.IconElement.call( this, config );
11384 OO.ui.mixin.IndicatorElement.call( this, config );
11385 OO.ui.mixin.LabelElement.call( this, config );
11386 OO.ui.mixin.TitledElement.call( this, config );
11387 OO.ui.mixin.ClippableElement.call( this, $.extend( {}, config, { $clippable: this.$group } ) );
11388 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$handle } ) );
11389
11390 // Events
11391 this.$handle.on( {
11392 keydown: this.onHandleMouseKeyDown.bind( this ),
11393 keyup: this.onHandleMouseKeyUp.bind( this ),
11394 mousedown: this.onHandleMouseKeyDown.bind( this ),
11395 mouseup: this.onHandleMouseKeyUp.bind( this )
11396 } );
11397
11398 // Initialization
11399 this.$handle
11400 .addClass( 'oo-ui-popupToolGroup-handle' )
11401 .append( this.$icon, this.$label, this.$indicator );
11402 // If the pop-up should have a header, add it to the top of the toolGroup.
11403 // Note: If this feature is useful for other widgets, we could abstract it into an
11404 // OO.ui.HeaderedElement mixin constructor.
11405 if ( config.header !== undefined ) {
11406 this.$group
11407 .prepend( $( '<span>' )
11408 .addClass( 'oo-ui-popupToolGroup-header' )
11409 .text( config.header )
11410 );
11411 }
11412 this.$element
11413 .addClass( 'oo-ui-popupToolGroup' )
11414 .prepend( this.$handle );
11415 };
11416
11417 /* Setup */
11418
11419 OO.inheritClass( OO.ui.PopupToolGroup, OO.ui.ToolGroup );
11420 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.mixin.IconElement );
11421 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.mixin.IndicatorElement );
11422 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.mixin.LabelElement );
11423 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.mixin.TitledElement );
11424 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.mixin.ClippableElement );
11425 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.mixin.TabIndexedElement );
11426
11427 /* Methods */
11428
11429 /**
11430 * @inheritdoc
11431 */
11432 OO.ui.PopupToolGroup.prototype.setDisabled = function () {
11433 // Parent method
11434 OO.ui.PopupToolGroup.parent.prototype.setDisabled.apply( this, arguments );
11435
11436 if ( this.isDisabled() && this.isElementAttached() ) {
11437 this.setActive( false );
11438 }
11439 };
11440
11441 /**
11442 * Handle focus being lost.
11443 *
11444 * The event is actually generated from a mouseup/keyup, so it is not a normal blur event object.
11445 *
11446 * @protected
11447 * @param {jQuery.Event} e Mouse up or key up event
11448 */
11449 OO.ui.PopupToolGroup.prototype.onBlur = function ( e ) {
11450 // Only deactivate when clicking outside the dropdown element
11451 if ( $( e.target ).closest( '.oo-ui-popupToolGroup' )[ 0 ] !== this.$element[ 0 ] ) {
11452 this.setActive( false );
11453 }
11454 };
11455
11456 /**
11457 * @inheritdoc
11458 */
11459 OO.ui.PopupToolGroup.prototype.onMouseKeyUp = function ( e ) {
11460 // Only close toolgroup when a tool was actually selected
11461 if (
11462 !this.isDisabled() && this.pressed && this.pressed === this.getTargetTool( e ) &&
11463 ( e.which === 1 || e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
11464 ) {
11465 this.setActive( false );
11466 }
11467 return OO.ui.PopupToolGroup.parent.prototype.onMouseKeyUp.call( this, e );
11468 };
11469
11470 /**
11471 * Handle mouse up and key up events.
11472 *
11473 * @protected
11474 * @param {jQuery.Event} e Mouse up or key up event
11475 */
11476 OO.ui.PopupToolGroup.prototype.onHandleMouseKeyUp = function ( e ) {
11477 if (
11478 !this.isDisabled() &&
11479 ( e.which === 1 || e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
11480 ) {
11481 return false;
11482 }
11483 };
11484
11485 /**
11486 * Handle mouse down and key down events.
11487 *
11488 * @protected
11489 * @param {jQuery.Event} e Mouse down or key down event
11490 */
11491 OO.ui.PopupToolGroup.prototype.onHandleMouseKeyDown = function ( e ) {
11492 if (
11493 !this.isDisabled() &&
11494 ( e.which === 1 || e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
11495 ) {
11496 this.setActive( !this.active );
11497 return false;
11498 }
11499 };
11500
11501 /**
11502 * Switch into 'active' mode.
11503 *
11504 * When active, the popup is visible. A mouseup event anywhere in the document will trigger
11505 * deactivation.
11506 */
11507 OO.ui.PopupToolGroup.prototype.setActive = function ( value ) {
11508 var containerWidth, containerLeft;
11509 value = !!value;
11510 if ( this.active !== value ) {
11511 this.active = value;
11512 if ( value ) {
11513 OO.ui.addCaptureEventListener( this.getElementDocument(), 'mouseup', this.onBlurHandler );
11514 OO.ui.addCaptureEventListener( this.getElementDocument(), 'keyup', this.onBlurHandler );
11515
11516 this.$clippable.css( 'left', '' );
11517 // Try anchoring the popup to the left first
11518 this.$element.addClass( 'oo-ui-popupToolGroup-active oo-ui-popupToolGroup-left' );
11519 this.toggleClipping( true );
11520 if ( this.isClippedHorizontally() ) {
11521 // Anchoring to the left caused the popup to clip, so anchor it to the right instead
11522 this.toggleClipping( false );
11523 this.$element
11524 .removeClass( 'oo-ui-popupToolGroup-left' )
11525 .addClass( 'oo-ui-popupToolGroup-right' );
11526 this.toggleClipping( true );
11527 }
11528 if ( this.isClippedHorizontally() ) {
11529 // Anchoring to the right also caused the popup to clip, so just make it fill the container
11530 containerWidth = this.$clippableScrollableContainer.width();
11531 containerLeft = this.$clippableScrollableContainer.offset().left;
11532
11533 this.toggleClipping( false );
11534 this.$element.removeClass( 'oo-ui-popupToolGroup-right' );
11535
11536 this.$clippable.css( {
11537 left: -( this.$element.offset().left - containerLeft ),
11538 width: containerWidth
11539 } );
11540 }
11541 } else {
11542 OO.ui.removeCaptureEventListener( this.getElementDocument(), 'mouseup', this.onBlurHandler );
11543 OO.ui.removeCaptureEventListener( this.getElementDocument(), 'keyup', this.onBlurHandler );
11544 this.$element.removeClass(
11545 'oo-ui-popupToolGroup-active oo-ui-popupToolGroup-left oo-ui-popupToolGroup-right'
11546 );
11547 this.toggleClipping( false );
11548 }
11549 }
11550 };
11551
11552 /**
11553 * ListToolGroups are one of three types of {@link OO.ui.ToolGroup toolgroups} that are used to
11554 * create {@link OO.ui.Toolbar toolbars} (the other types of groups are {@link OO.ui.MenuToolGroup MenuToolGroup}
11555 * and {@link OO.ui.BarToolGroup BarToolGroup}). The {@link OO.ui.Tool tools} in a ListToolGroup are displayed
11556 * by label in a dropdown menu. The title of the tool is used as the label text. The menu itself can be configured
11557 * with a label, icon, indicator, header, and title.
11558 *
11559 * ListToolGroups can be configured to be expanded and collapsed. Collapsed lists will have a ‘More’ option that
11560 * users can select to see the full list of tools. If a collapsed toolgroup is expanded, a ‘Fewer’ option permits
11561 * users to collapse the list again.
11562 *
11563 * ListToolGroups are created by a {@link OO.ui.ToolGroupFactory toolgroup factory} when the toolbar is set up. The factory
11564 * requires the ListToolGroup's symbolic name, 'list', which is specified along with the other configurations. For more
11565 * information about how to add tools to a ListToolGroup, please see {@link OO.ui.ToolGroup toolgroup}.
11566 *
11567 * @example
11568 * // Example of a ListToolGroup
11569 * var toolFactory = new OO.ui.ToolFactory();
11570 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
11571 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
11572 *
11573 * // Configure and register two tools
11574 * function SettingsTool() {
11575 * SettingsTool.parent.apply( this, arguments );
11576 * }
11577 * OO.inheritClass( SettingsTool, OO.ui.Tool );
11578 * SettingsTool.static.name = 'settings';
11579 * SettingsTool.static.icon = 'settings';
11580 * SettingsTool.static.title = 'Change settings';
11581 * SettingsTool.prototype.onSelect = function () {
11582 * this.setActive( false );
11583 * };
11584 * toolFactory.register( SettingsTool );
11585 * // Register two more tools, nothing interesting here
11586 * function StuffTool() {
11587 * StuffTool.parent.apply( this, arguments );
11588 * }
11589 * OO.inheritClass( StuffTool, OO.ui.Tool );
11590 * StuffTool.static.name = 'stuff';
11591 * StuffTool.static.icon = 'ellipsis';
11592 * StuffTool.static.title = 'Change the world';
11593 * StuffTool.prototype.onSelect = function () {
11594 * this.setActive( false );
11595 * };
11596 * toolFactory.register( StuffTool );
11597 * toolbar.setup( [
11598 * {
11599 * // Configurations for list toolgroup.
11600 * type: 'list',
11601 * label: 'ListToolGroup',
11602 * indicator: 'down',
11603 * icon: 'picture',
11604 * title: 'This is the title, displayed when user moves the mouse over the list toolgroup',
11605 * header: 'This is the header',
11606 * include: [ 'settings', 'stuff' ],
11607 * allowCollapse: ['stuff']
11608 * }
11609 * ] );
11610 *
11611 * // Create some UI around the toolbar and place it in the document
11612 * var frame = new OO.ui.PanelLayout( {
11613 * expanded: false,
11614 * framed: true
11615 * } );
11616 * frame.$element.append(
11617 * toolbar.$element
11618 * );
11619 * $( 'body' ).append( frame.$element );
11620 * // Build the toolbar. This must be done after the toolbar has been appended to the document.
11621 * toolbar.initialize();
11622 *
11623 * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki][1].
11624 *
11625 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
11626 *
11627 * @class
11628 * @extends OO.ui.PopupToolGroup
11629 *
11630 * @constructor
11631 * @param {OO.ui.Toolbar} toolbar
11632 * @param {Object} [config] Configuration options
11633 * @cfg {Array} [allowCollapse] Allow the specified tools to be collapsed. By default, collapsible tools
11634 * will only be displayed if users click the ‘More’ option displayed at the bottom of the list. If
11635 * the list is expanded, a ‘Fewer’ option permits users to collapse the list again. Any tools that
11636 * are included in the toolgroup, but are not designated as collapsible, will always be displayed.
11637 * To open a collapsible list in its expanded state, set #expanded to 'true'.
11638 * @cfg {Array} [forceExpand] Expand the specified tools. All other tools will be designated as collapsible.
11639 * Unless #expanded is set to true, the collapsible tools will be collapsed when the list is first opened.
11640 * @cfg {boolean} [expanded=false] Expand collapsible tools. This config is only relevant if tools have
11641 * been designated as collapsible. When expanded is set to true, all tools in the group will be displayed
11642 * when the list is first opened. Users can collapse the list with a ‘Fewer’ option at the bottom.
11643 */
11644 OO.ui.ListToolGroup = function OoUiListToolGroup( toolbar, config ) {
11645 // Allow passing positional parameters inside the config object
11646 if ( OO.isPlainObject( toolbar ) && config === undefined ) {
11647 config = toolbar;
11648 toolbar = config.toolbar;
11649 }
11650
11651 // Configuration initialization
11652 config = config || {};
11653
11654 // Properties (must be set before parent constructor, which calls #populate)
11655 this.allowCollapse = config.allowCollapse;
11656 this.forceExpand = config.forceExpand;
11657 this.expanded = config.expanded !== undefined ? config.expanded : false;
11658 this.collapsibleTools = [];
11659
11660 // Parent constructor
11661 OO.ui.ListToolGroup.parent.call( this, toolbar, config );
11662
11663 // Initialization
11664 this.$element.addClass( 'oo-ui-listToolGroup' );
11665 };
11666
11667 /* Setup */
11668
11669 OO.inheritClass( OO.ui.ListToolGroup, OO.ui.PopupToolGroup );
11670
11671 /* Static Properties */
11672
11673 OO.ui.ListToolGroup.static.name = 'list';
11674
11675 /* Methods */
11676
11677 /**
11678 * @inheritdoc
11679 */
11680 OO.ui.ListToolGroup.prototype.populate = function () {
11681 var i, len, allowCollapse = [];
11682
11683 OO.ui.ListToolGroup.parent.prototype.populate.call( this );
11684
11685 // Update the list of collapsible tools
11686 if ( this.allowCollapse !== undefined ) {
11687 allowCollapse = this.allowCollapse;
11688 } else if ( this.forceExpand !== undefined ) {
11689 allowCollapse = OO.simpleArrayDifference( Object.keys( this.tools ), this.forceExpand );
11690 }
11691
11692 this.collapsibleTools = [];
11693 for ( i = 0, len = allowCollapse.length; i < len; i++ ) {
11694 if ( this.tools[ allowCollapse[ i ] ] !== undefined ) {
11695 this.collapsibleTools.push( this.tools[ allowCollapse[ i ] ] );
11696 }
11697 }
11698
11699 // Keep at the end, even when tools are added
11700 this.$group.append( this.getExpandCollapseTool().$element );
11701
11702 this.getExpandCollapseTool().toggle( this.collapsibleTools.length !== 0 );
11703 this.updateCollapsibleState();
11704 };
11705
11706 OO.ui.ListToolGroup.prototype.getExpandCollapseTool = function () {
11707 var ExpandCollapseTool;
11708 if ( this.expandCollapseTool === undefined ) {
11709 ExpandCollapseTool = function () {
11710 ExpandCollapseTool.parent.apply( this, arguments );
11711 };
11712
11713 OO.inheritClass( ExpandCollapseTool, OO.ui.Tool );
11714
11715 ExpandCollapseTool.prototype.onSelect = function () {
11716 this.toolGroup.expanded = !this.toolGroup.expanded;
11717 this.toolGroup.updateCollapsibleState();
11718 this.setActive( false );
11719 };
11720 ExpandCollapseTool.prototype.onUpdateState = function () {
11721 // Do nothing. Tool interface requires an implementation of this function.
11722 };
11723
11724 ExpandCollapseTool.static.name = 'more-fewer';
11725
11726 this.expandCollapseTool = new ExpandCollapseTool( this );
11727 }
11728 return this.expandCollapseTool;
11729 };
11730
11731 /**
11732 * @inheritdoc
11733 */
11734 OO.ui.ListToolGroup.prototype.onMouseKeyUp = function ( e ) {
11735 // Do not close the popup when the user wants to show more/fewer tools
11736 if (
11737 $( e.target ).closest( '.oo-ui-tool-name-more-fewer' ).length &&
11738 ( e.which === 1 || e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
11739 ) {
11740 // HACK: Prevent the popup list from being hidden. Skip the PopupToolGroup implementation (which
11741 // hides the popup list when a tool is selected) and call ToolGroup's implementation directly.
11742 return OO.ui.ListToolGroup.parent.parent.prototype.onMouseKeyUp.call( this, e );
11743 } else {
11744 return OO.ui.ListToolGroup.parent.prototype.onMouseKeyUp.call( this, e );
11745 }
11746 };
11747
11748 OO.ui.ListToolGroup.prototype.updateCollapsibleState = function () {
11749 var i, len;
11750
11751 this.getExpandCollapseTool()
11752 .setIcon( this.expanded ? 'collapse' : 'expand' )
11753 .setTitle( OO.ui.msg( this.expanded ? 'ooui-toolgroup-collapse' : 'ooui-toolgroup-expand' ) );
11754
11755 for ( i = 0, len = this.collapsibleTools.length; i < len; i++ ) {
11756 this.collapsibleTools[ i ].toggle( this.expanded );
11757 }
11758 };
11759
11760 /**
11761 * MenuToolGroups are one of three types of {@link OO.ui.ToolGroup toolgroups} that are used to
11762 * create {@link OO.ui.Toolbar toolbars} (the other types of groups are {@link OO.ui.BarToolGroup BarToolGroup}
11763 * and {@link OO.ui.ListToolGroup ListToolGroup}). MenuToolGroups contain selectable {@link OO.ui.Tool tools},
11764 * which are displayed by label in a dropdown menu. The tool's title is used as the label text, and the
11765 * menu label is updated to reflect which tool or tools are currently selected. If no tools are selected,
11766 * the menu label is empty. The menu can be configured with an indicator, icon, title, and/or header.
11767 *
11768 * MenuToolGroups are created by a {@link OO.ui.ToolGroupFactory tool group factory} when the toolbar
11769 * is set up. Note that all tools must define an {@link OO.ui.Tool#onUpdateState onUpdateState} method if
11770 * a MenuToolGroup is used.
11771 *
11772 * @example
11773 * // Example of a MenuToolGroup
11774 * var toolFactory = new OO.ui.ToolFactory();
11775 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
11776 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
11777 *
11778 * // We will be placing status text in this element when tools are used
11779 * var $area = $( '<p>' ).text( 'An example of a MenuToolGroup. Select a tool from the dropdown menu.' );
11780 *
11781 * // Define the tools that we're going to place in our toolbar
11782 *
11783 * function SettingsTool() {
11784 * SettingsTool.parent.apply( this, arguments );
11785 * this.reallyActive = false;
11786 * }
11787 * OO.inheritClass( SettingsTool, OO.ui.Tool );
11788 * SettingsTool.static.name = 'settings';
11789 * SettingsTool.static.icon = 'settings';
11790 * SettingsTool.static.title = 'Change settings';
11791 * SettingsTool.prototype.onSelect = function () {
11792 * $area.text( 'Settings tool clicked!' );
11793 * // Toggle the active state on each click
11794 * this.reallyActive = !this.reallyActive;
11795 * this.setActive( this.reallyActive );
11796 * // To update the menu label
11797 * this.toolbar.emit( 'updateState' );
11798 * };
11799 * SettingsTool.prototype.onUpdateState = function () {
11800 * };
11801 * toolFactory.register( SettingsTool );
11802 *
11803 * function StuffTool() {
11804 * StuffTool.parent.apply( this, arguments );
11805 * this.reallyActive = false;
11806 * }
11807 * OO.inheritClass( StuffTool, OO.ui.Tool );
11808 * StuffTool.static.name = 'stuff';
11809 * StuffTool.static.icon = 'ellipsis';
11810 * StuffTool.static.title = 'More stuff';
11811 * StuffTool.prototype.onSelect = function () {
11812 * $area.text( 'More stuff tool clicked!' );
11813 * // Toggle the active state on each click
11814 * this.reallyActive = !this.reallyActive;
11815 * this.setActive( this.reallyActive );
11816 * // To update the menu label
11817 * this.toolbar.emit( 'updateState' );
11818 * };
11819 * StuffTool.prototype.onUpdateState = function () {
11820 * };
11821 * toolFactory.register( StuffTool );
11822 *
11823 * // Finally define which tools and in what order appear in the toolbar. Each tool may only be
11824 * // used once (but not all defined tools must be used).
11825 * toolbar.setup( [
11826 * {
11827 * type: 'menu',
11828 * header: 'This is the (optional) header',
11829 * title: 'This is the (optional) title',
11830 * indicator: 'down',
11831 * include: [ 'settings', 'stuff' ]
11832 * }
11833 * ] );
11834 *
11835 * // Create some UI around the toolbar and place it in the document
11836 * var frame = new OO.ui.PanelLayout( {
11837 * expanded: false,
11838 * framed: true
11839 * } );
11840 * var contentFrame = new OO.ui.PanelLayout( {
11841 * expanded: false,
11842 * padded: true
11843 * } );
11844 * frame.$element.append(
11845 * toolbar.$element,
11846 * contentFrame.$element.append( $area )
11847 * );
11848 * $( 'body' ).append( frame.$element );
11849 *
11850 * // Here is where the toolbar is actually built. This must be done after inserting it into the
11851 * // document.
11852 * toolbar.initialize();
11853 * toolbar.emit( 'updateState' );
11854 *
11855 * For more information about how to add tools to a MenuToolGroup, please see {@link OO.ui.ToolGroup toolgroup}.
11856 * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki] [1].
11857 *
11858 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
11859 *
11860 * @class
11861 * @extends OO.ui.PopupToolGroup
11862 *
11863 * @constructor
11864 * @param {OO.ui.Toolbar} toolbar
11865 * @param {Object} [config] Configuration options
11866 */
11867 OO.ui.MenuToolGroup = function OoUiMenuToolGroup( toolbar, config ) {
11868 // Allow passing positional parameters inside the config object
11869 if ( OO.isPlainObject( toolbar ) && config === undefined ) {
11870 config = toolbar;
11871 toolbar = config.toolbar;
11872 }
11873
11874 // Configuration initialization
11875 config = config || {};
11876
11877 // Parent constructor
11878 OO.ui.MenuToolGroup.parent.call( this, toolbar, config );
11879
11880 // Events
11881 this.toolbar.connect( this, { updateState: 'onUpdateState' } );
11882
11883 // Initialization
11884 this.$element.addClass( 'oo-ui-menuToolGroup' );
11885 };
11886
11887 /* Setup */
11888
11889 OO.inheritClass( OO.ui.MenuToolGroup, OO.ui.PopupToolGroup );
11890
11891 /* Static Properties */
11892
11893 OO.ui.MenuToolGroup.static.name = 'menu';
11894
11895 /* Methods */
11896
11897 /**
11898 * Handle the toolbar state being updated.
11899 *
11900 * When the state changes, the title of each active item in the menu will be joined together and
11901 * used as a label for the group. The label will be empty if none of the items are active.
11902 *
11903 * @private
11904 */
11905 OO.ui.MenuToolGroup.prototype.onUpdateState = function () {
11906 var name,
11907 labelTexts = [];
11908
11909 for ( name in this.tools ) {
11910 if ( this.tools[ name ].isActive() ) {
11911 labelTexts.push( this.tools[ name ].getTitle() );
11912 }
11913 }
11914
11915 this.setLabel( labelTexts.join( ', ' ) || ' ' );
11916 };
11917
11918 /**
11919 * Popup tools open a popup window when they are selected from the {@link OO.ui.Toolbar toolbar}. Each popup tool is configured
11920 * 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
11921 * an #onSelect or #onUpdateState method, as these methods have been implemented already.
11922 *
11923 * // Example of a popup tool. When selected, a popup tool displays
11924 * // a popup window.
11925 * function HelpTool( toolGroup, config ) {
11926 * OO.ui.PopupTool.call( this, toolGroup, $.extend( { popup: {
11927 * padded: true,
11928 * label: 'Help',
11929 * head: true
11930 * } }, config ) );
11931 * this.popup.$body.append( '<p>I am helpful!</p>' );
11932 * };
11933 * OO.inheritClass( HelpTool, OO.ui.PopupTool );
11934 * HelpTool.static.name = 'help';
11935 * HelpTool.static.icon = 'help';
11936 * HelpTool.static.title = 'Help';
11937 * toolFactory.register( HelpTool );
11938 *
11939 * For an example of a toolbar that contains a popup tool, see {@link OO.ui.Toolbar toolbars}. For more information about
11940 * toolbars in genreral, please see the [OOjs UI documentation on MediaWiki][1].
11941 *
11942 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
11943 *
11944 * @abstract
11945 * @class
11946 * @extends OO.ui.Tool
11947 * @mixins OO.ui.mixin.PopupElement
11948 *
11949 * @constructor
11950 * @param {OO.ui.ToolGroup} toolGroup
11951 * @param {Object} [config] Configuration options
11952 */
11953 OO.ui.PopupTool = function OoUiPopupTool( toolGroup, config ) {
11954 // Allow passing positional parameters inside the config object
11955 if ( OO.isPlainObject( toolGroup ) && config === undefined ) {
11956 config = toolGroup;
11957 toolGroup = config.toolGroup;
11958 }
11959
11960 // Parent constructor
11961 OO.ui.PopupTool.parent.call( this, toolGroup, config );
11962
11963 // Mixin constructors
11964 OO.ui.mixin.PopupElement.call( this, config );
11965
11966 // Initialization
11967 this.$element
11968 .addClass( 'oo-ui-popupTool' )
11969 .append( this.popup.$element );
11970 };
11971
11972 /* Setup */
11973
11974 OO.inheritClass( OO.ui.PopupTool, OO.ui.Tool );
11975 OO.mixinClass( OO.ui.PopupTool, OO.ui.mixin.PopupElement );
11976
11977 /* Methods */
11978
11979 /**
11980 * Handle the tool being selected.
11981 *
11982 * @inheritdoc
11983 */
11984 OO.ui.PopupTool.prototype.onSelect = function () {
11985 if ( !this.isDisabled() ) {
11986 this.popup.toggle();
11987 }
11988 this.setActive( false );
11989 return false;
11990 };
11991
11992 /**
11993 * Handle the toolbar state being updated.
11994 *
11995 * @inheritdoc
11996 */
11997 OO.ui.PopupTool.prototype.onUpdateState = function () {
11998 this.setActive( false );
11999 };
12000
12001 /**
12002 * A ToolGroupTool is a special sort of tool that can contain other {@link OO.ui.Tool tools}
12003 * and {@link OO.ui.ToolGroup toolgroups}. The ToolGroupTool was specifically designed to be used
12004 * inside a {@link OO.ui.BarToolGroup bar} toolgroup to provide access to additional tools from
12005 * the bar item. Included tools will be displayed in a dropdown {@link OO.ui.ListToolGroup list}
12006 * when the ToolGroupTool is selected.
12007 *
12008 * // Example: ToolGroupTool with two nested tools, 'setting1' and 'setting2', defined elsewhere.
12009 *
12010 * function SettingsTool() {
12011 * SettingsTool.parent.apply( this, arguments );
12012 * };
12013 * OO.inheritClass( SettingsTool, OO.ui.ToolGroupTool );
12014 * SettingsTool.static.name = 'settings';
12015 * SettingsTool.static.title = 'Change settings';
12016 * SettingsTool.static.groupConfig = {
12017 * icon: 'settings',
12018 * label: 'ToolGroupTool',
12019 * include: [ 'setting1', 'setting2' ]
12020 * };
12021 * toolFactory.register( SettingsTool );
12022 *
12023 * For more information, please see the [OOjs UI documentation on MediaWiki][1].
12024 *
12025 * Please note that this implementation is subject to change per [T74159] [2].
12026 *
12027 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars#ToolGroupTool
12028 * [2]: https://phabricator.wikimedia.org/T74159
12029 *
12030 * @abstract
12031 * @class
12032 * @extends OO.ui.Tool
12033 *
12034 * @constructor
12035 * @param {OO.ui.ToolGroup} toolGroup
12036 * @param {Object} [config] Configuration options
12037 */
12038 OO.ui.ToolGroupTool = function OoUiToolGroupTool( toolGroup, config ) {
12039 // Allow passing positional parameters inside the config object
12040 if ( OO.isPlainObject( toolGroup ) && config === undefined ) {
12041 config = toolGroup;
12042 toolGroup = config.toolGroup;
12043 }
12044
12045 // Parent constructor
12046 OO.ui.ToolGroupTool.parent.call( this, toolGroup, config );
12047
12048 // Properties
12049 this.innerToolGroup = this.createGroup( this.constructor.static.groupConfig );
12050
12051 // Events
12052 this.innerToolGroup.connect( this, { disable: 'onToolGroupDisable' } );
12053
12054 // Initialization
12055 this.$link.remove();
12056 this.$element
12057 .addClass( 'oo-ui-toolGroupTool' )
12058 .append( this.innerToolGroup.$element );
12059 };
12060
12061 /* Setup */
12062
12063 OO.inheritClass( OO.ui.ToolGroupTool, OO.ui.Tool );
12064
12065 /* Static Properties */
12066
12067 /**
12068 * Toolgroup configuration.
12069 *
12070 * The toolgroup configuration consists of the tools to include, as well as an icon and label
12071 * to use for the bar item. Tools can be included by symbolic name, group, or with the
12072 * wildcard selector. Please see {@link OO.ui.ToolGroup toolgroup} for more information.
12073 *
12074 * @property {Object.<string,Array>}
12075 */
12076 OO.ui.ToolGroupTool.static.groupConfig = {};
12077
12078 /* Methods */
12079
12080 /**
12081 * Handle the tool being selected.
12082 *
12083 * @inheritdoc
12084 */
12085 OO.ui.ToolGroupTool.prototype.onSelect = function () {
12086 this.innerToolGroup.setActive( !this.innerToolGroup.active );
12087 return false;
12088 };
12089
12090 /**
12091 * Synchronize disabledness state of the tool with the inner toolgroup.
12092 *
12093 * @private
12094 * @param {boolean} disabled Element is disabled
12095 */
12096 OO.ui.ToolGroupTool.prototype.onToolGroupDisable = function ( disabled ) {
12097 this.setDisabled( disabled );
12098 };
12099
12100 /**
12101 * Handle the toolbar state being updated.
12102 *
12103 * @inheritdoc
12104 */
12105 OO.ui.ToolGroupTool.prototype.onUpdateState = function () {
12106 this.setActive( false );
12107 };
12108
12109 /**
12110 * Build a {@link OO.ui.ToolGroup toolgroup} from the specified configuration.
12111 *
12112 * @param {Object.<string,Array>} group Toolgroup configuration. Please see {@link OO.ui.ToolGroup toolgroup} for
12113 * more information.
12114 * @return {OO.ui.ListToolGroup}
12115 */
12116 OO.ui.ToolGroupTool.prototype.createGroup = function ( group ) {
12117 if ( group.include === '*' ) {
12118 // Apply defaults to catch-all groups
12119 if ( group.label === undefined ) {
12120 group.label = OO.ui.msg( 'ooui-toolbar-more' );
12121 }
12122 }
12123
12124 return this.toolbar.getToolGroupFactory().create( 'list', this.toolbar, group );
12125 };
12126
12127 /**
12128 * Mixin for OO.ui.Widget subclasses to provide OO.ui.mixin.GroupElement.
12129 *
12130 * Use together with OO.ui.mixin.ItemWidget to make disabled state inheritable.
12131 *
12132 * @private
12133 * @abstract
12134 * @class
12135 * @extends OO.ui.mixin.GroupElement
12136 *
12137 * @constructor
12138 * @param {Object} [config] Configuration options
12139 */
12140 OO.ui.mixin.GroupWidget = function OoUiMixinGroupWidget( config ) {
12141 // Parent constructor
12142 OO.ui.mixin.GroupWidget.parent.call( this, config );
12143 };
12144
12145 /* Setup */
12146
12147 OO.inheritClass( OO.ui.mixin.GroupWidget, OO.ui.mixin.GroupElement );
12148
12149 /* Methods */
12150
12151 /**
12152 * Set the disabled state of the widget.
12153 *
12154 * This will also update the disabled state of child widgets.
12155 *
12156 * @param {boolean} disabled Disable widget
12157 * @chainable
12158 */
12159 OO.ui.mixin.GroupWidget.prototype.setDisabled = function ( disabled ) {
12160 var i, len;
12161
12162 // Parent method
12163 // Note: Calling #setDisabled this way assumes this is mixed into an OO.ui.Widget
12164 OO.ui.Widget.prototype.setDisabled.call( this, disabled );
12165
12166 // During construction, #setDisabled is called before the OO.ui.mixin.GroupElement constructor
12167 if ( this.items ) {
12168 for ( i = 0, len = this.items.length; i < len; i++ ) {
12169 this.items[ i ].updateDisabled();
12170 }
12171 }
12172
12173 return this;
12174 };
12175
12176 /**
12177 * Mixin for widgets used as items in widgets that mix in OO.ui.mixin.GroupWidget.
12178 *
12179 * Item widgets have a reference to a OO.ui.mixin.GroupWidget while they are attached to the group. This
12180 * allows bidirectional communication.
12181 *
12182 * Use together with OO.ui.mixin.GroupWidget to make disabled state inheritable.
12183 *
12184 * @private
12185 * @abstract
12186 * @class
12187 *
12188 * @constructor
12189 */
12190 OO.ui.mixin.ItemWidget = function OoUiMixinItemWidget() {
12191 //
12192 };
12193
12194 /* Methods */
12195
12196 /**
12197 * Check if widget is disabled.
12198 *
12199 * Checks parent if present, making disabled state inheritable.
12200 *
12201 * @return {boolean} Widget is disabled
12202 */
12203 OO.ui.mixin.ItemWidget.prototype.isDisabled = function () {
12204 return this.disabled ||
12205 ( this.elementGroup instanceof OO.ui.Widget && this.elementGroup.isDisabled() );
12206 };
12207
12208 /**
12209 * Set group element is in.
12210 *
12211 * @param {OO.ui.mixin.GroupElement|null} group Group element, null if none
12212 * @chainable
12213 */
12214 OO.ui.mixin.ItemWidget.prototype.setElementGroup = function ( group ) {
12215 // Parent method
12216 // Note: Calling #setElementGroup this way assumes this is mixed into an OO.ui.Element
12217 OO.ui.Element.prototype.setElementGroup.call( this, group );
12218
12219 // Initialize item disabled states
12220 this.updateDisabled();
12221
12222 return this;
12223 };
12224
12225 /**
12226 * OutlineControlsWidget is a set of controls for an {@link OO.ui.OutlineSelectWidget outline select widget}.
12227 * Controls include moving items up and down, removing items, and adding different kinds of items.
12228 *
12229 * **Currently, this class is only used by {@link OO.ui.BookletLayout booklet layouts}.**
12230 *
12231 * @class
12232 * @extends OO.ui.Widget
12233 * @mixins OO.ui.mixin.GroupElement
12234 * @mixins OO.ui.mixin.IconElement
12235 *
12236 * @constructor
12237 * @param {OO.ui.OutlineSelectWidget} outline Outline to control
12238 * @param {Object} [config] Configuration options
12239 * @cfg {Object} [abilities] List of abilties
12240 * @cfg {boolean} [abilities.move=true] Allow moving movable items
12241 * @cfg {boolean} [abilities.remove=true] Allow removing removable items
12242 */
12243 OO.ui.OutlineControlsWidget = function OoUiOutlineControlsWidget( outline, config ) {
12244 // Allow passing positional parameters inside the config object
12245 if ( OO.isPlainObject( outline ) && config === undefined ) {
12246 config = outline;
12247 outline = config.outline;
12248 }
12249
12250 // Configuration initialization
12251 config = $.extend( { icon: 'add' }, config );
12252
12253 // Parent constructor
12254 OO.ui.OutlineControlsWidget.parent.call( this, config );
12255
12256 // Mixin constructors
12257 OO.ui.mixin.GroupElement.call( this, config );
12258 OO.ui.mixin.IconElement.call( this, config );
12259
12260 // Properties
12261 this.outline = outline;
12262 this.$movers = $( '<div>' );
12263 this.upButton = new OO.ui.ButtonWidget( {
12264 framed: false,
12265 icon: 'collapse',
12266 title: OO.ui.msg( 'ooui-outline-control-move-up' )
12267 } );
12268 this.downButton = new OO.ui.ButtonWidget( {
12269 framed: false,
12270 icon: 'expand',
12271 title: OO.ui.msg( 'ooui-outline-control-move-down' )
12272 } );
12273 this.removeButton = new OO.ui.ButtonWidget( {
12274 framed: false,
12275 icon: 'remove',
12276 title: OO.ui.msg( 'ooui-outline-control-remove' )
12277 } );
12278 this.abilities = { move: true, remove: true };
12279
12280 // Events
12281 outline.connect( this, {
12282 select: 'onOutlineChange',
12283 add: 'onOutlineChange',
12284 remove: 'onOutlineChange'
12285 } );
12286 this.upButton.connect( this, { click: [ 'emit', 'move', -1 ] } );
12287 this.downButton.connect( this, { click: [ 'emit', 'move', 1 ] } );
12288 this.removeButton.connect( this, { click: [ 'emit', 'remove' ] } );
12289
12290 // Initialization
12291 this.$element.addClass( 'oo-ui-outlineControlsWidget' );
12292 this.$group.addClass( 'oo-ui-outlineControlsWidget-items' );
12293 this.$movers
12294 .addClass( 'oo-ui-outlineControlsWidget-movers' )
12295 .append( this.removeButton.$element, this.upButton.$element, this.downButton.$element );
12296 this.$element.append( this.$icon, this.$group, this.$movers );
12297 this.setAbilities( config.abilities || {} );
12298 };
12299
12300 /* Setup */
12301
12302 OO.inheritClass( OO.ui.OutlineControlsWidget, OO.ui.Widget );
12303 OO.mixinClass( OO.ui.OutlineControlsWidget, OO.ui.mixin.GroupElement );
12304 OO.mixinClass( OO.ui.OutlineControlsWidget, OO.ui.mixin.IconElement );
12305
12306 /* Events */
12307
12308 /**
12309 * @event move
12310 * @param {number} places Number of places to move
12311 */
12312
12313 /**
12314 * @event remove
12315 */
12316
12317 /* Methods */
12318
12319 /**
12320 * Set abilities.
12321 *
12322 * @param {Object} abilities List of abilties
12323 * @param {boolean} [abilities.move] Allow moving movable items
12324 * @param {boolean} [abilities.remove] Allow removing removable items
12325 */
12326 OO.ui.OutlineControlsWidget.prototype.setAbilities = function ( abilities ) {
12327 var ability;
12328
12329 for ( ability in this.abilities ) {
12330 if ( abilities[ ability ] !== undefined ) {
12331 this.abilities[ ability ] = !!abilities[ ability ];
12332 }
12333 }
12334
12335 this.onOutlineChange();
12336 };
12337
12338 /**
12339 * @private
12340 * Handle outline change events.
12341 */
12342 OO.ui.OutlineControlsWidget.prototype.onOutlineChange = function () {
12343 var i, len, firstMovable, lastMovable,
12344 items = this.outline.getItems(),
12345 selectedItem = this.outline.getSelectedItem(),
12346 movable = this.abilities.move && selectedItem && selectedItem.isMovable(),
12347 removable = this.abilities.remove && selectedItem && selectedItem.isRemovable();
12348
12349 if ( movable ) {
12350 i = -1;
12351 len = items.length;
12352 while ( ++i < len ) {
12353 if ( items[ i ].isMovable() ) {
12354 firstMovable = items[ i ];
12355 break;
12356 }
12357 }
12358 i = len;
12359 while ( i-- ) {
12360 if ( items[ i ].isMovable() ) {
12361 lastMovable = items[ i ];
12362 break;
12363 }
12364 }
12365 }
12366 this.upButton.setDisabled( !movable || selectedItem === firstMovable );
12367 this.downButton.setDisabled( !movable || selectedItem === lastMovable );
12368 this.removeButton.setDisabled( !removable );
12369 };
12370
12371 /**
12372 * ToggleWidget implements basic behavior of widgets with an on/off state.
12373 * Please see OO.ui.ToggleButtonWidget and OO.ui.ToggleSwitchWidget for examples.
12374 *
12375 * @abstract
12376 * @class
12377 * @extends OO.ui.Widget
12378 *
12379 * @constructor
12380 * @param {Object} [config] Configuration options
12381 * @cfg {boolean} [value=false] The toggle’s initial on/off state.
12382 * By default, the toggle is in the 'off' state.
12383 */
12384 OO.ui.ToggleWidget = function OoUiToggleWidget( config ) {
12385 // Configuration initialization
12386 config = config || {};
12387
12388 // Parent constructor
12389 OO.ui.ToggleWidget.parent.call( this, config );
12390
12391 // Properties
12392 this.value = null;
12393
12394 // Initialization
12395 this.$element.addClass( 'oo-ui-toggleWidget' );
12396 this.setValue( !!config.value );
12397 };
12398
12399 /* Setup */
12400
12401 OO.inheritClass( OO.ui.ToggleWidget, OO.ui.Widget );
12402
12403 /* Events */
12404
12405 /**
12406 * @event change
12407 *
12408 * A change event is emitted when the on/off state of the toggle changes.
12409 *
12410 * @param {boolean} value Value representing the new state of the toggle
12411 */
12412
12413 /* Methods */
12414
12415 /**
12416 * Get the value representing the toggle’s state.
12417 *
12418 * @return {boolean} The on/off state of the toggle
12419 */
12420 OO.ui.ToggleWidget.prototype.getValue = function () {
12421 return this.value;
12422 };
12423
12424 /**
12425 * Set the state of the toggle: `true` for 'on', `false' for 'off'.
12426 *
12427 * @param {boolean} value The state of the toggle
12428 * @fires change
12429 * @chainable
12430 */
12431 OO.ui.ToggleWidget.prototype.setValue = function ( value ) {
12432 value = !!value;
12433 if ( this.value !== value ) {
12434 this.value = value;
12435 this.emit( 'change', value );
12436 this.$element.toggleClass( 'oo-ui-toggleWidget-on', value );
12437 this.$element.toggleClass( 'oo-ui-toggleWidget-off', !value );
12438 this.$element.attr( 'aria-checked', value.toString() );
12439 }
12440 return this;
12441 };
12442
12443 /**
12444 * A ButtonGroupWidget groups related buttons and is used together with OO.ui.ButtonWidget and
12445 * its subclasses. Each button in a group is addressed by a unique reference. Buttons can be added,
12446 * removed, and cleared from the group.
12447 *
12448 * @example
12449 * // Example: A ButtonGroupWidget with two buttons
12450 * var button1 = new OO.ui.PopupButtonWidget( {
12451 * label: 'Select a category',
12452 * icon: 'menu',
12453 * popup: {
12454 * $content: $( '<p>List of categories...</p>' ),
12455 * padded: true,
12456 * align: 'left'
12457 * }
12458 * } );
12459 * var button2 = new OO.ui.ButtonWidget( {
12460 * label: 'Add item'
12461 * });
12462 * var buttonGroup = new OO.ui.ButtonGroupWidget( {
12463 * items: [button1, button2]
12464 * } );
12465 * $( 'body' ).append( buttonGroup.$element );
12466 *
12467 * @class
12468 * @extends OO.ui.Widget
12469 * @mixins OO.ui.mixin.GroupElement
12470 *
12471 * @constructor
12472 * @param {Object} [config] Configuration options
12473 * @cfg {OO.ui.ButtonWidget[]} [items] Buttons to add
12474 */
12475 OO.ui.ButtonGroupWidget = function OoUiButtonGroupWidget( config ) {
12476 // Configuration initialization
12477 config = config || {};
12478
12479 // Parent constructor
12480 OO.ui.ButtonGroupWidget.parent.call( this, config );
12481
12482 // Mixin constructors
12483 OO.ui.mixin.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) );
12484
12485 // Initialization
12486 this.$element.addClass( 'oo-ui-buttonGroupWidget' );
12487 if ( Array.isArray( config.items ) ) {
12488 this.addItems( config.items );
12489 }
12490 };
12491
12492 /* Setup */
12493
12494 OO.inheritClass( OO.ui.ButtonGroupWidget, OO.ui.Widget );
12495 OO.mixinClass( OO.ui.ButtonGroupWidget, OO.ui.mixin.GroupElement );
12496
12497 /**
12498 * ButtonWidget is a generic widget for buttons. A wide variety of looks,
12499 * feels, and functionality can be customized via the class’s configuration options
12500 * and methods. Please see the [OOjs UI documentation on MediaWiki] [1] for more information
12501 * and examples.
12502 *
12503 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches
12504 *
12505 * @example
12506 * // A button widget
12507 * var button = new OO.ui.ButtonWidget( {
12508 * label: 'Button with Icon',
12509 * icon: 'remove',
12510 * iconTitle: 'Remove'
12511 * } );
12512 * $( 'body' ).append( button.$element );
12513 *
12514 * NOTE: HTML form buttons should use the OO.ui.ButtonInputWidget class.
12515 *
12516 * @class
12517 * @extends OO.ui.Widget
12518 * @mixins OO.ui.mixin.ButtonElement
12519 * @mixins OO.ui.mixin.IconElement
12520 * @mixins OO.ui.mixin.IndicatorElement
12521 * @mixins OO.ui.mixin.LabelElement
12522 * @mixins OO.ui.mixin.TitledElement
12523 * @mixins OO.ui.mixin.FlaggedElement
12524 * @mixins OO.ui.mixin.TabIndexedElement
12525 * @mixins OO.ui.mixin.AccessKeyedElement
12526 *
12527 * @constructor
12528 * @param {Object} [config] Configuration options
12529 * @cfg {string} [href] Hyperlink to visit when the button is clicked.
12530 * @cfg {string} [target] The frame or window in which to open the hyperlink.
12531 * @cfg {boolean} [noFollow] Search engine traversal hint (default: true)
12532 */
12533 OO.ui.ButtonWidget = function OoUiButtonWidget( config ) {
12534 // Configuration initialization
12535 config = config || {};
12536
12537 // Parent constructor
12538 OO.ui.ButtonWidget.parent.call( this, config );
12539
12540 // Mixin constructors
12541 OO.ui.mixin.ButtonElement.call( this, config );
12542 OO.ui.mixin.IconElement.call( this, config );
12543 OO.ui.mixin.IndicatorElement.call( this, config );
12544 OO.ui.mixin.LabelElement.call( this, config );
12545 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$button } ) );
12546 OO.ui.mixin.FlaggedElement.call( this, config );
12547 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$button } ) );
12548 OO.ui.mixin.AccessKeyedElement.call( this, $.extend( {}, config, { $accessKeyed: this.$button } ) );
12549
12550 // Properties
12551 this.href = null;
12552 this.target = null;
12553 this.noFollow = false;
12554
12555 // Events
12556 this.connect( this, { disable: 'onDisable' } );
12557
12558 // Initialization
12559 this.$button.append( this.$icon, this.$label, this.$indicator );
12560 this.$element
12561 .addClass( 'oo-ui-buttonWidget' )
12562 .append( this.$button );
12563 this.setHref( config.href );
12564 this.setTarget( config.target );
12565 this.setNoFollow( config.noFollow );
12566 };
12567
12568 /* Setup */
12569
12570 OO.inheritClass( OO.ui.ButtonWidget, OO.ui.Widget );
12571 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.ButtonElement );
12572 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.IconElement );
12573 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.IndicatorElement );
12574 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.LabelElement );
12575 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.TitledElement );
12576 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.FlaggedElement );
12577 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.TabIndexedElement );
12578 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.AccessKeyedElement );
12579
12580 /* Methods */
12581
12582 /**
12583 * @inheritdoc
12584 */
12585 OO.ui.ButtonWidget.prototype.onMouseDown = function ( e ) {
12586 if ( !this.isDisabled() ) {
12587 // Remove the tab-index while the button is down to prevent the button from stealing focus
12588 this.$button.removeAttr( 'tabindex' );
12589 }
12590
12591 return OO.ui.mixin.ButtonElement.prototype.onMouseDown.call( this, e );
12592 };
12593
12594 /**
12595 * @inheritdoc
12596 */
12597 OO.ui.ButtonWidget.prototype.onMouseUp = function ( e ) {
12598 if ( !this.isDisabled() ) {
12599 // Restore the tab-index after the button is up to restore the button's accessibility
12600 this.$button.attr( 'tabindex', this.tabIndex );
12601 }
12602
12603 return OO.ui.mixin.ButtonElement.prototype.onMouseUp.call( this, e );
12604 };
12605
12606 /**
12607 * Get hyperlink location.
12608 *
12609 * @return {string} Hyperlink location
12610 */
12611 OO.ui.ButtonWidget.prototype.getHref = function () {
12612 return this.href;
12613 };
12614
12615 /**
12616 * Get hyperlink target.
12617 *
12618 * @return {string} Hyperlink target
12619 */
12620 OO.ui.ButtonWidget.prototype.getTarget = function () {
12621 return this.target;
12622 };
12623
12624 /**
12625 * Get search engine traversal hint.
12626 *
12627 * @return {boolean} Whether search engines should avoid traversing this hyperlink
12628 */
12629 OO.ui.ButtonWidget.prototype.getNoFollow = function () {
12630 return this.noFollow;
12631 };
12632
12633 /**
12634 * Set hyperlink location.
12635 *
12636 * @param {string|null} href Hyperlink location, null to remove
12637 */
12638 OO.ui.ButtonWidget.prototype.setHref = function ( href ) {
12639 href = typeof href === 'string' ? href : null;
12640 if ( href !== null ) {
12641 if ( !OO.ui.isSafeUrl( href ) ) {
12642 throw new Error( 'Potentially unsafe href provided: ' + href );
12643 }
12644
12645 }
12646
12647 if ( href !== this.href ) {
12648 this.href = href;
12649 this.updateHref();
12650 }
12651
12652 return this;
12653 };
12654
12655 /**
12656 * Update the `href` attribute, in case of changes to href or
12657 * disabled state.
12658 *
12659 * @private
12660 * @chainable
12661 */
12662 OO.ui.ButtonWidget.prototype.updateHref = function () {
12663 if ( this.href !== null && !this.isDisabled() ) {
12664 this.$button.attr( 'href', this.href );
12665 } else {
12666 this.$button.removeAttr( 'href' );
12667 }
12668
12669 return this;
12670 };
12671
12672 /**
12673 * Handle disable events.
12674 *
12675 * @private
12676 * @param {boolean} disabled Element is disabled
12677 */
12678 OO.ui.ButtonWidget.prototype.onDisable = function () {
12679 this.updateHref();
12680 };
12681
12682 /**
12683 * Set hyperlink target.
12684 *
12685 * @param {string|null} target Hyperlink target, null to remove
12686 */
12687 OO.ui.ButtonWidget.prototype.setTarget = function ( target ) {
12688 target = typeof target === 'string' ? target : null;
12689
12690 if ( target !== this.target ) {
12691 this.target = target;
12692 if ( target !== null ) {
12693 this.$button.attr( 'target', target );
12694 } else {
12695 this.$button.removeAttr( 'target' );
12696 }
12697 }
12698
12699 return this;
12700 };
12701
12702 /**
12703 * Set search engine traversal hint.
12704 *
12705 * @param {boolean} noFollow True if search engines should avoid traversing this hyperlink
12706 */
12707 OO.ui.ButtonWidget.prototype.setNoFollow = function ( noFollow ) {
12708 noFollow = typeof noFollow === 'boolean' ? noFollow : true;
12709
12710 if ( noFollow !== this.noFollow ) {
12711 this.noFollow = noFollow;
12712 if ( noFollow ) {
12713 this.$button.attr( 'rel', 'nofollow' );
12714 } else {
12715 this.$button.removeAttr( 'rel' );
12716 }
12717 }
12718
12719 return this;
12720 };
12721
12722 /**
12723 * An ActionWidget is a {@link OO.ui.ButtonWidget button widget} that executes an action.
12724 * Action widgets are used with OO.ui.ActionSet, which manages the behavior and availability
12725 * of the actions.
12726 *
12727 * Both actions and action sets are primarily used with {@link OO.ui.Dialog Dialogs}.
12728 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information
12729 * and examples.
12730 *
12731 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Action_sets
12732 *
12733 * @class
12734 * @extends OO.ui.ButtonWidget
12735 * @mixins OO.ui.mixin.PendingElement
12736 *
12737 * @constructor
12738 * @param {Object} [config] Configuration options
12739 * @cfg {string} [action] Symbolic name of the action (e.g., ‘continue’ or ‘cancel’).
12740 * @cfg {string[]} [modes] Symbolic names of the modes (e.g., ‘edit’ or ‘read’) in which the action
12741 * should be made available. See the action set's {@link OO.ui.ActionSet#setMode setMode} method
12742 * for more information about setting modes.
12743 * @cfg {boolean} [framed=false] Render the action button with a frame
12744 */
12745 OO.ui.ActionWidget = function OoUiActionWidget( config ) {
12746 // Configuration initialization
12747 config = $.extend( { framed: false }, config );
12748
12749 // Parent constructor
12750 OO.ui.ActionWidget.parent.call( this, config );
12751
12752 // Mixin constructors
12753 OO.ui.mixin.PendingElement.call( this, config );
12754
12755 // Properties
12756 this.action = config.action || '';
12757 this.modes = config.modes || [];
12758 this.width = 0;
12759 this.height = 0;
12760
12761 // Initialization
12762 this.$element.addClass( 'oo-ui-actionWidget' );
12763 };
12764
12765 /* Setup */
12766
12767 OO.inheritClass( OO.ui.ActionWidget, OO.ui.ButtonWidget );
12768 OO.mixinClass( OO.ui.ActionWidget, OO.ui.mixin.PendingElement );
12769
12770 /* Events */
12771
12772 /**
12773 * A resize event is emitted when the size of the widget changes.
12774 *
12775 * @event resize
12776 */
12777
12778 /* Methods */
12779
12780 /**
12781 * Check if the action is configured to be available in the specified `mode`.
12782 *
12783 * @param {string} mode Name of mode
12784 * @return {boolean} The action is configured with the mode
12785 */
12786 OO.ui.ActionWidget.prototype.hasMode = function ( mode ) {
12787 return this.modes.indexOf( mode ) !== -1;
12788 };
12789
12790 /**
12791 * Get the symbolic name of the action (e.g., ‘continue’ or ‘cancel’).
12792 *
12793 * @return {string}
12794 */
12795 OO.ui.ActionWidget.prototype.getAction = function () {
12796 return this.action;
12797 };
12798
12799 /**
12800 * Get the symbolic name of the mode or modes for which the action is configured to be available.
12801 *
12802 * The current mode is set with the action set's {@link OO.ui.ActionSet#setMode setMode} method.
12803 * Only actions that are configured to be avaiable in the current mode will be visible. All other actions
12804 * are hidden.
12805 *
12806 * @return {string[]}
12807 */
12808 OO.ui.ActionWidget.prototype.getModes = function () {
12809 return this.modes.slice();
12810 };
12811
12812 /**
12813 * Emit a resize event if the size has changed.
12814 *
12815 * @private
12816 * @chainable
12817 */
12818 OO.ui.ActionWidget.prototype.propagateResize = function () {
12819 var width, height;
12820
12821 if ( this.isElementAttached() ) {
12822 width = this.$element.width();
12823 height = this.$element.height();
12824
12825 if ( width !== this.width || height !== this.height ) {
12826 this.width = width;
12827 this.height = height;
12828 this.emit( 'resize' );
12829 }
12830 }
12831
12832 return this;
12833 };
12834
12835 /**
12836 * @inheritdoc
12837 */
12838 OO.ui.ActionWidget.prototype.setIcon = function () {
12839 // Mixin method
12840 OO.ui.mixin.IconElement.prototype.setIcon.apply( this, arguments );
12841 this.propagateResize();
12842
12843 return this;
12844 };
12845
12846 /**
12847 * @inheritdoc
12848 */
12849 OO.ui.ActionWidget.prototype.setLabel = function () {
12850 // Mixin method
12851 OO.ui.mixin.LabelElement.prototype.setLabel.apply( this, arguments );
12852 this.propagateResize();
12853
12854 return this;
12855 };
12856
12857 /**
12858 * @inheritdoc
12859 */
12860 OO.ui.ActionWidget.prototype.setFlags = function () {
12861 // Mixin method
12862 OO.ui.mixin.FlaggedElement.prototype.setFlags.apply( this, arguments );
12863 this.propagateResize();
12864
12865 return this;
12866 };
12867
12868 /**
12869 * @inheritdoc
12870 */
12871 OO.ui.ActionWidget.prototype.clearFlags = function () {
12872 // Mixin method
12873 OO.ui.mixin.FlaggedElement.prototype.clearFlags.apply( this, arguments );
12874 this.propagateResize();
12875
12876 return this;
12877 };
12878
12879 /**
12880 * Toggle the visibility of the action button.
12881 *
12882 * @param {boolean} [show] Show button, omit to toggle visibility
12883 * @chainable
12884 */
12885 OO.ui.ActionWidget.prototype.toggle = function () {
12886 // Parent method
12887 OO.ui.ActionWidget.parent.prototype.toggle.apply( this, arguments );
12888 this.propagateResize();
12889
12890 return this;
12891 };
12892
12893 /**
12894 * PopupButtonWidgets toggle the visibility of a contained {@link OO.ui.PopupWidget PopupWidget},
12895 * which is used to display additional information or options.
12896 *
12897 * @example
12898 * // Example of a popup button.
12899 * var popupButton = new OO.ui.PopupButtonWidget( {
12900 * label: 'Popup button with options',
12901 * icon: 'menu',
12902 * popup: {
12903 * $content: $( '<p>Additional options here.</p>' ),
12904 * padded: true,
12905 * align: 'force-left'
12906 * }
12907 * } );
12908 * // Append the button to the DOM.
12909 * $( 'body' ).append( popupButton.$element );
12910 *
12911 * @class
12912 * @extends OO.ui.ButtonWidget
12913 * @mixins OO.ui.mixin.PopupElement
12914 *
12915 * @constructor
12916 * @param {Object} [config] Configuration options
12917 */
12918 OO.ui.PopupButtonWidget = function OoUiPopupButtonWidget( config ) {
12919 // Parent constructor
12920 OO.ui.PopupButtonWidget.parent.call( this, config );
12921
12922 // Mixin constructors
12923 OO.ui.mixin.PopupElement.call( this, config );
12924
12925 // Events
12926 this.connect( this, { click: 'onAction' } );
12927
12928 // Initialization
12929 this.$element
12930 .addClass( 'oo-ui-popupButtonWidget' )
12931 .attr( 'aria-haspopup', 'true' )
12932 .append( this.popup.$element );
12933 };
12934
12935 /* Setup */
12936
12937 OO.inheritClass( OO.ui.PopupButtonWidget, OO.ui.ButtonWidget );
12938 OO.mixinClass( OO.ui.PopupButtonWidget, OO.ui.mixin.PopupElement );
12939
12940 /* Methods */
12941
12942 /**
12943 * Handle the button action being triggered.
12944 *
12945 * @private
12946 */
12947 OO.ui.PopupButtonWidget.prototype.onAction = function () {
12948 this.popup.toggle();
12949 };
12950
12951 /**
12952 * ToggleButtons are buttons that have a state (‘on’ or ‘off’) that is represented by a
12953 * Boolean value. Like other {@link OO.ui.ButtonWidget buttons}, toggle buttons can be
12954 * configured with {@link OO.ui.mixin.IconElement icons}, {@link OO.ui.mixin.IndicatorElement indicators},
12955 * {@link OO.ui.mixin.TitledElement titles}, {@link OO.ui.mixin.FlaggedElement styling flags},
12956 * and {@link OO.ui.mixin.LabelElement labels}. Please see
12957 * the [OOjs UI documentation][1] on MediaWiki for more information.
12958 *
12959 * @example
12960 * // Toggle buttons in the 'off' and 'on' state.
12961 * var toggleButton1 = new OO.ui.ToggleButtonWidget( {
12962 * label: 'Toggle Button off'
12963 * } );
12964 * var toggleButton2 = new OO.ui.ToggleButtonWidget( {
12965 * label: 'Toggle Button on',
12966 * value: true
12967 * } );
12968 * // Append the buttons to the DOM.
12969 * $( 'body' ).append( toggleButton1.$element, toggleButton2.$element );
12970 *
12971 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#Toggle_buttons
12972 *
12973 * @class
12974 * @extends OO.ui.ToggleWidget
12975 * @mixins OO.ui.mixin.ButtonElement
12976 * @mixins OO.ui.mixin.IconElement
12977 * @mixins OO.ui.mixin.IndicatorElement
12978 * @mixins OO.ui.mixin.LabelElement
12979 * @mixins OO.ui.mixin.TitledElement
12980 * @mixins OO.ui.mixin.FlaggedElement
12981 * @mixins OO.ui.mixin.TabIndexedElement
12982 *
12983 * @constructor
12984 * @param {Object} [config] Configuration options
12985 * @cfg {boolean} [value=false] The toggle button’s initial on/off
12986 * state. By default, the button is in the 'off' state.
12987 */
12988 OO.ui.ToggleButtonWidget = function OoUiToggleButtonWidget( config ) {
12989 // Configuration initialization
12990 config = config || {};
12991
12992 // Parent constructor
12993 OO.ui.ToggleButtonWidget.parent.call( this, config );
12994
12995 // Mixin constructors
12996 OO.ui.mixin.ButtonElement.call( this, config );
12997 OO.ui.mixin.IconElement.call( this, config );
12998 OO.ui.mixin.IndicatorElement.call( this, config );
12999 OO.ui.mixin.LabelElement.call( this, config );
13000 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$button } ) );
13001 OO.ui.mixin.FlaggedElement.call( this, config );
13002 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$button } ) );
13003
13004 // Events
13005 this.connect( this, { click: 'onAction' } );
13006
13007 // Initialization
13008 this.$button.append( this.$icon, this.$label, this.$indicator );
13009 this.$element
13010 .addClass( 'oo-ui-toggleButtonWidget' )
13011 .append( this.$button );
13012 };
13013
13014 /* Setup */
13015
13016 OO.inheritClass( OO.ui.ToggleButtonWidget, OO.ui.ToggleWidget );
13017 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.ButtonElement );
13018 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.IconElement );
13019 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.IndicatorElement );
13020 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.LabelElement );
13021 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.TitledElement );
13022 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.FlaggedElement );
13023 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.TabIndexedElement );
13024
13025 /* Methods */
13026
13027 /**
13028 * Handle the button action being triggered.
13029 *
13030 * @private
13031 */
13032 OO.ui.ToggleButtonWidget.prototype.onAction = function () {
13033 this.setValue( !this.value );
13034 };
13035
13036 /**
13037 * @inheritdoc
13038 */
13039 OO.ui.ToggleButtonWidget.prototype.setValue = function ( value ) {
13040 value = !!value;
13041 if ( value !== this.value ) {
13042 // Might be called from parent constructor before ButtonElement constructor
13043 if ( this.$button ) {
13044 this.$button.attr( 'aria-pressed', value.toString() );
13045 }
13046 this.setActive( value );
13047 }
13048
13049 // Parent method
13050 OO.ui.ToggleButtonWidget.parent.prototype.setValue.call( this, value );
13051
13052 return this;
13053 };
13054
13055 /**
13056 * @inheritdoc
13057 */
13058 OO.ui.ToggleButtonWidget.prototype.setButtonElement = function ( $button ) {
13059 if ( this.$button ) {
13060 this.$button.removeAttr( 'aria-pressed' );
13061 }
13062 OO.ui.mixin.ButtonElement.prototype.setButtonElement.call( this, $button );
13063 this.$button.attr( 'aria-pressed', this.value.toString() );
13064 };
13065
13066 /**
13067 * CapsuleMultiSelectWidgets are something like a {@link OO.ui.ComboBoxWidget combo box widget}
13068 * that allows for selecting multiple values.
13069 *
13070 * For more information about menus and options, please see the [OOjs UI documentation on MediaWiki][1].
13071 *
13072 * @example
13073 * // Example: A CapsuleMultiSelectWidget.
13074 * var capsule = new OO.ui.CapsuleMultiSelectWidget( {
13075 * label: 'CapsuleMultiSelectWidget',
13076 * selected: [ 'Option 1', 'Option 3' ],
13077 * menu: {
13078 * items: [
13079 * new OO.ui.MenuOptionWidget( {
13080 * data: 'Option 1',
13081 * label: 'Option One'
13082 * } ),
13083 * new OO.ui.MenuOptionWidget( {
13084 * data: 'Option 2',
13085 * label: 'Option Two'
13086 * } ),
13087 * new OO.ui.MenuOptionWidget( {
13088 * data: 'Option 3',
13089 * label: 'Option Three'
13090 * } ),
13091 * new OO.ui.MenuOptionWidget( {
13092 * data: 'Option 4',
13093 * label: 'Option Four'
13094 * } ),
13095 * new OO.ui.MenuOptionWidget( {
13096 * data: 'Option 5',
13097 * label: 'Option Five'
13098 * } )
13099 * ]
13100 * }
13101 * } );
13102 * $( 'body' ).append( capsule.$element );
13103 *
13104 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
13105 *
13106 * @class
13107 * @extends OO.ui.Widget
13108 * @mixins OO.ui.mixin.TabIndexedElement
13109 * @mixins OO.ui.mixin.GroupElement
13110 *
13111 * @constructor
13112 * @param {Object} [config] Configuration options
13113 * @cfg {boolean} [allowArbitrary=false] Allow data items to be added even if not present in the menu.
13114 * @cfg {Object} [menu] Configuration options to pass to the {@link OO.ui.MenuSelectWidget menu select widget}.
13115 * @cfg {Object} [popup] Configuration options to pass to the {@link OO.ui.PopupWidget popup widget}.
13116 * If specified, this popup will be shown instead of the menu (but the menu
13117 * will still be used for item labels and allowArbitrary=false). The widgets
13118 * in the popup should use this.addItemsFromData() or this.addItems() as necessary.
13119 * @cfg {jQuery} [$overlay] Render the menu or popup into a separate layer.
13120 * This configuration is useful in cases where the expanded menu is larger than
13121 * its containing `<div>`. The specified overlay layer is usually on top of
13122 * the containing `<div>` and has a larger area. By default, the menu uses
13123 * relative positioning.
13124 */
13125 OO.ui.CapsuleMultiSelectWidget = function OoUiCapsuleMultiSelectWidget( config ) {
13126 var $tabFocus;
13127
13128 // Configuration initialization
13129 config = config || {};
13130
13131 // Parent constructor
13132 OO.ui.CapsuleMultiSelectWidget.parent.call( this, config );
13133
13134 // Properties (must be set before mixin constructor calls)
13135 this.$input = config.popup ? null : $( '<input>' );
13136 this.$handle = $( '<div>' );
13137
13138 // Mixin constructors
13139 OO.ui.mixin.GroupElement.call( this, config );
13140 if ( config.popup ) {
13141 config.popup = $.extend( {}, config.popup, {
13142 align: 'forwards',
13143 anchor: false
13144 } );
13145 OO.ui.mixin.PopupElement.call( this, config );
13146 $tabFocus = $( '<span>' );
13147 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: $tabFocus } ) );
13148 } else {
13149 this.popup = null;
13150 $tabFocus = null;
13151 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$input } ) );
13152 }
13153 OO.ui.mixin.IndicatorElement.call( this, config );
13154 OO.ui.mixin.IconElement.call( this, config );
13155
13156 // Properties
13157 this.allowArbitrary = !!config.allowArbitrary;
13158 this.$overlay = config.$overlay || this.$element;
13159 this.menu = new OO.ui.FloatingMenuSelectWidget( $.extend(
13160 {
13161 widget: this,
13162 $input: this.$input,
13163 $container: this.$element,
13164 filterFromInput: true,
13165 disabled: this.isDisabled()
13166 },
13167 config.menu
13168 ) );
13169
13170 // Events
13171 if ( this.popup ) {
13172 $tabFocus.on( {
13173 focus: this.onFocusForPopup.bind( this )
13174 } );
13175 this.popup.$element.on( 'focusout', this.onPopupFocusOut.bind( this ) );
13176 if ( this.popup.$autoCloseIgnore ) {
13177 this.popup.$autoCloseIgnore.on( 'focusout', this.onPopupFocusOut.bind( this ) );
13178 }
13179 this.popup.connect( this, {
13180 toggle: function ( visible ) {
13181 $tabFocus.toggle( !visible );
13182 }
13183 } );
13184 } else {
13185 this.$input.on( {
13186 focus: this.onInputFocus.bind( this ),
13187 blur: this.onInputBlur.bind( this ),
13188 'propertychange change click mouseup keydown keyup input cut paste select': this.onInputChange.bind( this ),
13189 keydown: this.onKeyDown.bind( this ),
13190 keypress: this.onKeyPress.bind( this )
13191 } );
13192 }
13193 this.menu.connect( this, {
13194 choose: 'onMenuChoose',
13195 add: 'onMenuItemsChange',
13196 remove: 'onMenuItemsChange'
13197 } );
13198 this.$handle.on( {
13199 click: this.onClick.bind( this )
13200 } );
13201
13202 // Initialization
13203 if ( this.$input ) {
13204 this.$input.prop( 'disabled', this.isDisabled() );
13205 this.$input.attr( {
13206 role: 'combobox',
13207 'aria-autocomplete': 'list'
13208 } );
13209 this.$input.width( '1em' );
13210 }
13211 if ( config.data ) {
13212 this.setItemsFromData( config.data );
13213 }
13214 this.$group.addClass( 'oo-ui-capsuleMultiSelectWidget-group' );
13215 this.$handle.addClass( 'oo-ui-capsuleMultiSelectWidget-handle' )
13216 .append( this.$indicator, this.$icon, this.$group );
13217 this.$element.addClass( 'oo-ui-capsuleMultiSelectWidget' )
13218 .append( this.$handle );
13219 if ( this.popup ) {
13220 this.$handle.append( $tabFocus );
13221 this.$overlay.append( this.popup.$element );
13222 } else {
13223 this.$handle.append( this.$input );
13224 this.$overlay.append( this.menu.$element );
13225 }
13226 this.onMenuItemsChange();
13227 };
13228
13229 /* Setup */
13230
13231 OO.inheritClass( OO.ui.CapsuleMultiSelectWidget, OO.ui.Widget );
13232 OO.mixinClass( OO.ui.CapsuleMultiSelectWidget, OO.ui.mixin.GroupElement );
13233 OO.mixinClass( OO.ui.CapsuleMultiSelectWidget, OO.ui.mixin.PopupElement );
13234 OO.mixinClass( OO.ui.CapsuleMultiSelectWidget, OO.ui.mixin.TabIndexedElement );
13235 OO.mixinClass( OO.ui.CapsuleMultiSelectWidget, OO.ui.mixin.IndicatorElement );
13236 OO.mixinClass( OO.ui.CapsuleMultiSelectWidget, OO.ui.mixin.IconElement );
13237
13238 /* Events */
13239
13240 /**
13241 * @event change
13242 *
13243 * A change event is emitted when the set of selected items changes.
13244 *
13245 * @param {Mixed[]} datas Data of the now-selected items
13246 */
13247
13248 /* Methods */
13249
13250 /**
13251 * Construct a OO.ui.CapsuleItemWidget (or a subclass thereof) from given label and data.
13252 *
13253 * @protected
13254 * @param {Mixed} data Custom data of any type.
13255 * @param {string} label The label text.
13256 * @return {OO.ui.CapsuleItemWidget}
13257 */
13258 OO.ui.CapsuleMultiSelectWidget.prototype.createItemWidget = function ( data, label ) {
13259 return new OO.ui.CapsuleItemWidget( { data: data, label: label } );
13260 };
13261
13262 /**
13263 * Get the data of the items in the capsule
13264 * @return {Mixed[]}
13265 */
13266 OO.ui.CapsuleMultiSelectWidget.prototype.getItemsData = function () {
13267 return $.map( this.getItems(), function ( e ) { return e.data; } );
13268 };
13269
13270 /**
13271 * Set the items in the capsule by providing data
13272 * @chainable
13273 * @param {Mixed[]} datas
13274 * @return {OO.ui.CapsuleMultiSelectWidget}
13275 */
13276 OO.ui.CapsuleMultiSelectWidget.prototype.setItemsFromData = function ( datas ) {
13277 var widget = this,
13278 menu = this.menu,
13279 items = this.getItems();
13280
13281 $.each( datas, function ( i, data ) {
13282 var j, label,
13283 item = menu.getItemFromData( data );
13284
13285 if ( item ) {
13286 label = item.label;
13287 } else if ( widget.allowArbitrary ) {
13288 label = String( data );
13289 } else {
13290 return;
13291 }
13292
13293 item = null;
13294 for ( j = 0; j < items.length; j++ ) {
13295 if ( items[ j ].data === data && items[ j ].label === label ) {
13296 item = items[ j ];
13297 items.splice( j, 1 );
13298 break;
13299 }
13300 }
13301 if ( !item ) {
13302 item = widget.createItemWidget( data, label );
13303 }
13304 widget.addItems( [ item ], i );
13305 } );
13306
13307 if ( items.length ) {
13308 widget.removeItems( items );
13309 }
13310
13311 return this;
13312 };
13313
13314 /**
13315 * Add items to the capsule by providing their data
13316 * @chainable
13317 * @param {Mixed[]} datas
13318 * @return {OO.ui.CapsuleMultiSelectWidget}
13319 */
13320 OO.ui.CapsuleMultiSelectWidget.prototype.addItemsFromData = function ( datas ) {
13321 var widget = this,
13322 menu = this.menu,
13323 items = [];
13324
13325 $.each( datas, function ( i, data ) {
13326 var item;
13327
13328 if ( !widget.getItemFromData( data ) ) {
13329 item = menu.getItemFromData( data );
13330 if ( item ) {
13331 items.push( widget.createItemWidget( data, item.label ) );
13332 } else if ( widget.allowArbitrary ) {
13333 items.push( widget.createItemWidget( data, String( data ) ) );
13334 }
13335 }
13336 } );
13337
13338 if ( items.length ) {
13339 this.addItems( items );
13340 }
13341
13342 return this;
13343 };
13344
13345 /**
13346 * Remove items by data
13347 * @chainable
13348 * @param {Mixed[]} datas
13349 * @return {OO.ui.CapsuleMultiSelectWidget}
13350 */
13351 OO.ui.CapsuleMultiSelectWidget.prototype.removeItemsFromData = function ( datas ) {
13352 var widget = this,
13353 items = [];
13354
13355 $.each( datas, function ( i, data ) {
13356 var item = widget.getItemFromData( data );
13357 if ( item ) {
13358 items.push( item );
13359 }
13360 } );
13361
13362 if ( items.length ) {
13363 this.removeItems( items );
13364 }
13365
13366 return this;
13367 };
13368
13369 /**
13370 * @inheritdoc
13371 */
13372 OO.ui.CapsuleMultiSelectWidget.prototype.addItems = function ( items ) {
13373 var same, i, l,
13374 oldItems = this.items.slice();
13375
13376 OO.ui.mixin.GroupElement.prototype.addItems.call( this, items );
13377
13378 if ( this.items.length !== oldItems.length ) {
13379 same = false;
13380 } else {
13381 same = true;
13382 for ( i = 0, l = oldItems.length; same && i < l; i++ ) {
13383 same = same && this.items[ i ] === oldItems[ i ];
13384 }
13385 }
13386 if ( !same ) {
13387 this.emit( 'change', this.getItemsData() );
13388 }
13389
13390 return this;
13391 };
13392
13393 /**
13394 * @inheritdoc
13395 */
13396 OO.ui.CapsuleMultiSelectWidget.prototype.removeItems = function ( items ) {
13397 var same, i, l,
13398 oldItems = this.items.slice();
13399
13400 OO.ui.mixin.GroupElement.prototype.removeItems.call( this, items );
13401
13402 if ( this.items.length !== oldItems.length ) {
13403 same = false;
13404 } else {
13405 same = true;
13406 for ( i = 0, l = oldItems.length; same && i < l; i++ ) {
13407 same = same && this.items[ i ] === oldItems[ i ];
13408 }
13409 }
13410 if ( !same ) {
13411 this.emit( 'change', this.getItemsData() );
13412 }
13413
13414 return this;
13415 };
13416
13417 /**
13418 * @inheritdoc
13419 */
13420 OO.ui.CapsuleMultiSelectWidget.prototype.clearItems = function () {
13421 if ( this.items.length ) {
13422 OO.ui.mixin.GroupElement.prototype.clearItems.call( this );
13423 this.emit( 'change', this.getItemsData() );
13424 }
13425 return this;
13426 };
13427
13428 /**
13429 * Get the capsule widget's menu.
13430 * @return {OO.ui.MenuSelectWidget} Menu widget
13431 */
13432 OO.ui.CapsuleMultiSelectWidget.prototype.getMenu = function () {
13433 return this.menu;
13434 };
13435
13436 /**
13437 * Handle focus events
13438 *
13439 * @private
13440 * @param {jQuery.Event} event
13441 */
13442 OO.ui.CapsuleMultiSelectWidget.prototype.onInputFocus = function () {
13443 if ( !this.isDisabled() ) {
13444 this.menu.toggle( true );
13445 }
13446 };
13447
13448 /**
13449 * Handle blur events
13450 *
13451 * @private
13452 * @param {jQuery.Event} event
13453 */
13454 OO.ui.CapsuleMultiSelectWidget.prototype.onInputBlur = function () {
13455 this.clearInput();
13456 };
13457
13458 /**
13459 * Handle focus events
13460 *
13461 * @private
13462 * @param {jQuery.Event} event
13463 */
13464 OO.ui.CapsuleMultiSelectWidget.prototype.onFocusForPopup = function () {
13465 if ( !this.isDisabled() ) {
13466 this.popup.setSize( this.$handle.width() );
13467 this.popup.toggle( true );
13468 this.popup.$element.find( '*' )
13469 .filter( function () { return OO.ui.isFocusableElement( $( this ), true ); } )
13470 .first()
13471 .focus();
13472 }
13473 };
13474
13475 /**
13476 * Handles popup focus out events.
13477 *
13478 * @private
13479 * @param {Event} e Focus out event
13480 */
13481 OO.ui.CapsuleMultiSelectWidget.prototype.onPopupFocusOut = function () {
13482 var widget = this.popup;
13483
13484 setTimeout( function () {
13485 if (
13486 widget.isVisible() &&
13487 !OO.ui.contains( widget.$element[ 0 ], document.activeElement, true ) &&
13488 ( !widget.$autoCloseIgnore || !widget.$autoCloseIgnore.has( document.activeElement ).length )
13489 ) {
13490 widget.toggle( false );
13491 }
13492 } );
13493 };
13494
13495 /**
13496 * Handle mouse click events.
13497 *
13498 * @private
13499 * @param {jQuery.Event} e Mouse click event
13500 */
13501 OO.ui.CapsuleMultiSelectWidget.prototype.onClick = function ( e ) {
13502 if ( e.which === 1 ) {
13503 this.focus();
13504 return false;
13505 }
13506 };
13507
13508 /**
13509 * Handle key press events.
13510 *
13511 * @private
13512 * @param {jQuery.Event} e Key press event
13513 */
13514 OO.ui.CapsuleMultiSelectWidget.prototype.onKeyPress = function ( e ) {
13515 var item;
13516
13517 if ( !this.isDisabled() ) {
13518 if ( e.which === OO.ui.Keys.ESCAPE ) {
13519 this.clearInput();
13520 return false;
13521 }
13522
13523 if ( !this.popup ) {
13524 this.menu.toggle( true );
13525 if ( e.which === OO.ui.Keys.ENTER ) {
13526 item = this.menu.getItemFromLabel( this.$input.val(), true );
13527 if ( item ) {
13528 this.addItemsFromData( [ item.data ] );
13529 this.clearInput();
13530 } else if ( this.allowArbitrary && this.$input.val().trim() !== '' ) {
13531 this.addItemsFromData( [ this.$input.val() ] );
13532 this.clearInput();
13533 }
13534 return false;
13535 }
13536
13537 // Make sure the input gets resized.
13538 setTimeout( this.onInputChange.bind( this ), 0 );
13539 }
13540 }
13541 };
13542
13543 /**
13544 * Handle key down events.
13545 *
13546 * @private
13547 * @param {jQuery.Event} e Key down event
13548 */
13549 OO.ui.CapsuleMultiSelectWidget.prototype.onKeyDown = function ( e ) {
13550 if ( !this.isDisabled() ) {
13551 // 'keypress' event is not triggered for Backspace
13552 if ( e.keyCode === OO.ui.Keys.BACKSPACE && this.$input.val() === '' ) {
13553 if ( this.items.length ) {
13554 this.removeItems( this.items.slice( -1 ) );
13555 }
13556 return false;
13557 }
13558 }
13559 };
13560
13561 /**
13562 * Handle input change events.
13563 *
13564 * @private
13565 * @param {jQuery.Event} e Event of some sort
13566 */
13567 OO.ui.CapsuleMultiSelectWidget.prototype.onInputChange = function () {
13568 if ( !this.isDisabled() ) {
13569 this.$input.width( this.$input.val().length + 'em' );
13570 }
13571 };
13572
13573 /**
13574 * Handle menu choose events.
13575 *
13576 * @private
13577 * @param {OO.ui.OptionWidget} item Chosen item
13578 */
13579 OO.ui.CapsuleMultiSelectWidget.prototype.onMenuChoose = function ( item ) {
13580 if ( item && item.isVisible() ) {
13581 this.addItemsFromData( [ item.getData() ] );
13582 this.clearInput();
13583 }
13584 };
13585
13586 /**
13587 * Handle menu item change events.
13588 *
13589 * @private
13590 */
13591 OO.ui.CapsuleMultiSelectWidget.prototype.onMenuItemsChange = function () {
13592 this.setItemsFromData( this.getItemsData() );
13593 this.$element.toggleClass( 'oo-ui-capsuleMultiSelectWidget-empty', this.menu.isEmpty() );
13594 };
13595
13596 /**
13597 * Clear the input field
13598 * @private
13599 */
13600 OO.ui.CapsuleMultiSelectWidget.prototype.clearInput = function () {
13601 if ( this.$input ) {
13602 this.$input.val( '' );
13603 this.$input.width( '1em' );
13604 }
13605 if ( this.popup ) {
13606 this.popup.toggle( false );
13607 }
13608 this.menu.toggle( false );
13609 this.menu.selectItem();
13610 this.menu.highlightItem();
13611 };
13612
13613 /**
13614 * @inheritdoc
13615 */
13616 OO.ui.CapsuleMultiSelectWidget.prototype.setDisabled = function ( disabled ) {
13617 var i, len;
13618
13619 // Parent method
13620 OO.ui.CapsuleMultiSelectWidget.parent.prototype.setDisabled.call( this, disabled );
13621
13622 if ( this.$input ) {
13623 this.$input.prop( 'disabled', this.isDisabled() );
13624 }
13625 if ( this.menu ) {
13626 this.menu.setDisabled( this.isDisabled() );
13627 }
13628 if ( this.popup ) {
13629 this.popup.setDisabled( this.isDisabled() );
13630 }
13631
13632 if ( this.items ) {
13633 for ( i = 0, len = this.items.length; i < len; i++ ) {
13634 this.items[ i ].updateDisabled();
13635 }
13636 }
13637
13638 return this;
13639 };
13640
13641 /**
13642 * Focus the widget
13643 * @chainable
13644 * @return {OO.ui.CapsuleMultiSelectWidget}
13645 */
13646 OO.ui.CapsuleMultiSelectWidget.prototype.focus = function () {
13647 if ( !this.isDisabled() ) {
13648 if ( this.popup ) {
13649 this.popup.setSize( this.$handle.width() );
13650 this.popup.toggle( true );
13651 this.popup.$element.find( '*' )
13652 .filter( function () { return OO.ui.isFocusableElement( $( this ), true ); } )
13653 .first()
13654 .focus();
13655 } else {
13656 this.menu.toggle( true );
13657 this.$input.focus();
13658 }
13659 }
13660 return this;
13661 };
13662
13663 /**
13664 * CapsuleItemWidgets are used within a {@link OO.ui.CapsuleMultiSelectWidget
13665 * CapsuleMultiSelectWidget} to display the selected items.
13666 *
13667 * @class
13668 * @extends OO.ui.Widget
13669 * @mixins OO.ui.mixin.ItemWidget
13670 * @mixins OO.ui.mixin.IndicatorElement
13671 * @mixins OO.ui.mixin.LabelElement
13672 * @mixins OO.ui.mixin.FlaggedElement
13673 * @mixins OO.ui.mixin.TabIndexedElement
13674 *
13675 * @constructor
13676 * @param {Object} [config] Configuration options
13677 */
13678 OO.ui.CapsuleItemWidget = function OoUiCapsuleItemWidget( config ) {
13679 // Configuration initialization
13680 config = config || {};
13681
13682 // Parent constructor
13683 OO.ui.CapsuleItemWidget.parent.call( this, config );
13684
13685 // Properties (must be set before mixin constructor calls)
13686 this.$indicator = $( '<span>' );
13687
13688 // Mixin constructors
13689 OO.ui.mixin.ItemWidget.call( this );
13690 OO.ui.mixin.IndicatorElement.call( this, $.extend( {}, config, { $indicator: this.$indicator, indicator: 'clear' } ) );
13691 OO.ui.mixin.LabelElement.call( this, config );
13692 OO.ui.mixin.FlaggedElement.call( this, config );
13693 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$indicator } ) );
13694
13695 // Events
13696 this.$indicator.on( {
13697 keydown: this.onCloseKeyDown.bind( this ),
13698 click: this.onCloseClick.bind( this )
13699 } );
13700 this.$element.on( 'click', false );
13701
13702 // Initialization
13703 this.$element
13704 .addClass( 'oo-ui-capsuleItemWidget' )
13705 .append( this.$indicator, this.$label );
13706 };
13707
13708 /* Setup */
13709
13710 OO.inheritClass( OO.ui.CapsuleItemWidget, OO.ui.Widget );
13711 OO.mixinClass( OO.ui.CapsuleItemWidget, OO.ui.mixin.ItemWidget );
13712 OO.mixinClass( OO.ui.CapsuleItemWidget, OO.ui.mixin.IndicatorElement );
13713 OO.mixinClass( OO.ui.CapsuleItemWidget, OO.ui.mixin.LabelElement );
13714 OO.mixinClass( OO.ui.CapsuleItemWidget, OO.ui.mixin.FlaggedElement );
13715 OO.mixinClass( OO.ui.CapsuleItemWidget, OO.ui.mixin.TabIndexedElement );
13716
13717 /* Methods */
13718
13719 /**
13720 * Handle close icon clicks
13721 * @param {jQuery.Event} event
13722 */
13723 OO.ui.CapsuleItemWidget.prototype.onCloseClick = function () {
13724 var element = this.getElementGroup();
13725
13726 if ( !this.isDisabled() && element && $.isFunction( element.removeItems ) ) {
13727 element.removeItems( [ this ] );
13728 element.focus();
13729 }
13730 };
13731
13732 /**
13733 * Handle close keyboard events
13734 * @param {jQuery.Event} event Key down event
13735 */
13736 OO.ui.CapsuleItemWidget.prototype.onCloseKeyDown = function ( e ) {
13737 if ( !this.isDisabled() && $.isFunction( this.getElementGroup().removeItems ) ) {
13738 switch ( e.which ) {
13739 case OO.ui.Keys.ENTER:
13740 case OO.ui.Keys.BACKSPACE:
13741 case OO.ui.Keys.SPACE:
13742 this.getElementGroup().removeItems( [ this ] );
13743 return false;
13744 }
13745 }
13746 };
13747
13748 /**
13749 * DropdownWidgets are not menus themselves, rather they contain a menu of options created with
13750 * OO.ui.MenuOptionWidget. The DropdownWidget takes care of opening and displaying the menu so that
13751 * users can interact with it.
13752 *
13753 * If you want to use this within a HTML form, such as a OO.ui.FormLayout, use
13754 * OO.ui.DropdownInputWidget instead.
13755 *
13756 * @example
13757 * // Example: A DropdownWidget with a menu that contains three options
13758 * var dropDown = new OO.ui.DropdownWidget( {
13759 * label: 'Dropdown menu: Select a menu option',
13760 * menu: {
13761 * items: [
13762 * new OO.ui.MenuOptionWidget( {
13763 * data: 'a',
13764 * label: 'First'
13765 * } ),
13766 * new OO.ui.MenuOptionWidget( {
13767 * data: 'b',
13768 * label: 'Second'
13769 * } ),
13770 * new OO.ui.MenuOptionWidget( {
13771 * data: 'c',
13772 * label: 'Third'
13773 * } )
13774 * ]
13775 * }
13776 * } );
13777 *
13778 * $( 'body' ).append( dropDown.$element );
13779 *
13780 * dropDown.getMenu().selectItemByData( 'b' );
13781 *
13782 * dropDown.getMenu().getSelectedItem().getData(); // returns 'b'
13783 *
13784 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
13785 *
13786 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
13787 *
13788 * @class
13789 * @extends OO.ui.Widget
13790 * @mixins OO.ui.mixin.IconElement
13791 * @mixins OO.ui.mixin.IndicatorElement
13792 * @mixins OO.ui.mixin.LabelElement
13793 * @mixins OO.ui.mixin.TitledElement
13794 * @mixins OO.ui.mixin.TabIndexedElement
13795 *
13796 * @constructor
13797 * @param {Object} [config] Configuration options
13798 * @cfg {Object} [menu] Configuration options to pass to {@link OO.ui.FloatingMenuSelectWidget menu select widget}
13799 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
13800 * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
13801 * containing `<div>` and has a larger area. By default, the menu uses relative positioning.
13802 */
13803 OO.ui.DropdownWidget = function OoUiDropdownWidget( config ) {
13804 // Configuration initialization
13805 config = $.extend( { indicator: 'down' }, config );
13806
13807 // Parent constructor
13808 OO.ui.DropdownWidget.parent.call( this, config );
13809
13810 // Properties (must be set before TabIndexedElement constructor call)
13811 this.$handle = this.$( '<span>' );
13812 this.$overlay = config.$overlay || this.$element;
13813
13814 // Mixin constructors
13815 OO.ui.mixin.IconElement.call( this, config );
13816 OO.ui.mixin.IndicatorElement.call( this, config );
13817 OO.ui.mixin.LabelElement.call( this, config );
13818 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$label } ) );
13819 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$handle } ) );
13820
13821 // Properties
13822 this.menu = new OO.ui.FloatingMenuSelectWidget( $.extend( {
13823 widget: this,
13824 $container: this.$element
13825 }, config.menu ) );
13826
13827 // Events
13828 this.$handle.on( {
13829 click: this.onClick.bind( this ),
13830 keypress: this.onKeyPress.bind( this )
13831 } );
13832 this.menu.connect( this, { select: 'onMenuSelect' } );
13833
13834 // Initialization
13835 this.$handle
13836 .addClass( 'oo-ui-dropdownWidget-handle' )
13837 .append( this.$icon, this.$label, this.$indicator );
13838 this.$element
13839 .addClass( 'oo-ui-dropdownWidget' )
13840 .append( this.$handle );
13841 this.$overlay.append( this.menu.$element );
13842 };
13843
13844 /* Setup */
13845
13846 OO.inheritClass( OO.ui.DropdownWidget, OO.ui.Widget );
13847 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.IconElement );
13848 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.IndicatorElement );
13849 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.LabelElement );
13850 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.TitledElement );
13851 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.TabIndexedElement );
13852
13853 /* Methods */
13854
13855 /**
13856 * Get the menu.
13857 *
13858 * @return {OO.ui.MenuSelectWidget} Menu of widget
13859 */
13860 OO.ui.DropdownWidget.prototype.getMenu = function () {
13861 return this.menu;
13862 };
13863
13864 /**
13865 * Handles menu select events.
13866 *
13867 * @private
13868 * @param {OO.ui.MenuOptionWidget} item Selected menu item
13869 */
13870 OO.ui.DropdownWidget.prototype.onMenuSelect = function ( item ) {
13871 var selectedLabel;
13872
13873 if ( !item ) {
13874 this.setLabel( null );
13875 return;
13876 }
13877
13878 selectedLabel = item.getLabel();
13879
13880 // If the label is a DOM element, clone it, because setLabel will append() it
13881 if ( selectedLabel instanceof jQuery ) {
13882 selectedLabel = selectedLabel.clone();
13883 }
13884
13885 this.setLabel( selectedLabel );
13886 };
13887
13888 /**
13889 * Handle mouse click events.
13890 *
13891 * @private
13892 * @param {jQuery.Event} e Mouse click event
13893 */
13894 OO.ui.DropdownWidget.prototype.onClick = function ( e ) {
13895 if ( !this.isDisabled() && e.which === 1 ) {
13896 this.menu.toggle();
13897 }
13898 return false;
13899 };
13900
13901 /**
13902 * Handle key press events.
13903 *
13904 * @private
13905 * @param {jQuery.Event} e Key press event
13906 */
13907 OO.ui.DropdownWidget.prototype.onKeyPress = function ( e ) {
13908 if ( !this.isDisabled() &&
13909 ( ( e.which === OO.ui.Keys.SPACE && !this.menu.isVisible() ) || e.which === OO.ui.Keys.ENTER )
13910 ) {
13911 this.menu.toggle();
13912 return false;
13913 }
13914 };
13915
13916 /**
13917 * SelectFileWidgets allow for selecting files, using the HTML5 File API. These
13918 * widgets can be configured with {@link OO.ui.mixin.IconElement icons} and {@link
13919 * OO.ui.mixin.IndicatorElement indicators}.
13920 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
13921 *
13922 * @example
13923 * // Example of a file select widget
13924 * var selectFile = new OO.ui.SelectFileWidget();
13925 * $( 'body' ).append( selectFile.$element );
13926 *
13927 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets
13928 *
13929 * @class
13930 * @extends OO.ui.Widget
13931 * @mixins OO.ui.mixin.IconElement
13932 * @mixins OO.ui.mixin.IndicatorElement
13933 * @mixins OO.ui.mixin.PendingElement
13934 * @mixins OO.ui.mixin.LabelElement
13935 *
13936 * @constructor
13937 * @param {Object} [config] Configuration options
13938 * @cfg {string[]|null} [accept=null] MIME types to accept. null accepts all types.
13939 * @cfg {string} [placeholder] Text to display when no file is selected.
13940 * @cfg {string} [notsupported] Text to display when file support is missing in the browser.
13941 * @cfg {boolean} [droppable=true] Whether to accept files by drag and drop.
13942 * @cfg {boolean} [showDropTarget=false] Whether to show a drop target. Requires droppable to be true.
13943 * @cfg {boolean} [dragDropUI=false] Deprecated alias for showDropTarget
13944 */
13945 OO.ui.SelectFileWidget = function OoUiSelectFileWidget( config ) {
13946 var dragHandler;
13947
13948 // TODO: Remove in next release
13949 if ( config && config.dragDropUI ) {
13950 config.showDropTarget = true;
13951 }
13952
13953 // Configuration initialization
13954 config = $.extend( {
13955 accept: null,
13956 placeholder: OO.ui.msg( 'ooui-selectfile-placeholder' ),
13957 notsupported: OO.ui.msg( 'ooui-selectfile-not-supported' ),
13958 droppable: true,
13959 showDropTarget: false
13960 }, config );
13961
13962 // Parent constructor
13963 OO.ui.SelectFileWidget.parent.call( this, config );
13964
13965 // Mixin constructors
13966 OO.ui.mixin.IconElement.call( this, config );
13967 OO.ui.mixin.IndicatorElement.call( this, config );
13968 OO.ui.mixin.PendingElement.call( this, $.extend( {}, config, { $pending: this.$info } ) );
13969 OO.ui.mixin.LabelElement.call( this, $.extend( {}, config, { autoFitLabel: true } ) );
13970
13971 // Properties
13972 this.$info = $( '<span>' );
13973
13974 // Properties
13975 this.showDropTarget = config.showDropTarget;
13976 this.isSupported = this.constructor.static.isSupported();
13977 this.currentFile = null;
13978 if ( Array.isArray( config.accept ) ) {
13979 this.accept = config.accept;
13980 } else {
13981 this.accept = null;
13982 }
13983 this.placeholder = config.placeholder;
13984 this.notsupported = config.notsupported;
13985 this.onFileSelectedHandler = this.onFileSelected.bind( this );
13986
13987 this.selectButton = new OO.ui.ButtonWidget( {
13988 classes: [ 'oo-ui-selectFileWidget-selectButton' ],
13989 label: 'Select a file',
13990 disabled: this.disabled || !this.isSupported
13991 } );
13992
13993 this.clearButton = new OO.ui.ButtonWidget( {
13994 classes: [ 'oo-ui-selectFileWidget-clearButton' ],
13995 framed: false,
13996 icon: 'remove',
13997 disabled: this.disabled
13998 } );
13999
14000 // Events
14001 this.selectButton.$button.on( {
14002 keypress: this.onKeyPress.bind( this )
14003 } );
14004 this.clearButton.connect( this, {
14005 click: 'onClearClick'
14006 } );
14007 if ( config.droppable ) {
14008 dragHandler = this.onDragEnterOrOver.bind( this );
14009 this.$element.on( {
14010 dragenter: dragHandler,
14011 dragover: dragHandler,
14012 dragleave: this.onDragLeave.bind( this ),
14013 drop: this.onDrop.bind( this )
14014 } );
14015 }
14016
14017 // Initialization
14018 this.addInput();
14019 this.updateUI();
14020 this.$label.addClass( 'oo-ui-selectFileWidget-label' );
14021 this.$info
14022 .addClass( 'oo-ui-selectFileWidget-info' )
14023 .append( this.$icon, this.$label, this.clearButton.$element, this.$indicator );
14024 this.$element
14025 .addClass( 'oo-ui-selectFileWidget' )
14026 .append( this.$info, this.selectButton.$element );
14027 if ( config.droppable && config.showDropTarget ) {
14028 this.$dropTarget = $( '<div>' )
14029 .addClass( 'oo-ui-selectFileWidget-dropTarget' )
14030 .text( OO.ui.msg( 'ooui-selectfile-dragdrop-placeholder' ) )
14031 .on( {
14032 click: this.onDropTargetClick.bind( this )
14033 } );
14034 this.$element.prepend( this.$dropTarget );
14035 }
14036 };
14037
14038 /* Setup */
14039
14040 OO.inheritClass( OO.ui.SelectFileWidget, OO.ui.Widget );
14041 OO.mixinClass( OO.ui.SelectFileWidget, OO.ui.mixin.IconElement );
14042 OO.mixinClass( OO.ui.SelectFileWidget, OO.ui.mixin.IndicatorElement );
14043 OO.mixinClass( OO.ui.SelectFileWidget, OO.ui.mixin.PendingElement );
14044 OO.mixinClass( OO.ui.SelectFileWidget, OO.ui.mixin.LabelElement );
14045
14046 /* Static Properties */
14047
14048 /**
14049 * Check if this widget is supported
14050 *
14051 * @static
14052 * @return {boolean}
14053 */
14054 OO.ui.SelectFileWidget.static.isSupported = function () {
14055 var $input;
14056 if ( OO.ui.SelectFileWidget.static.isSupportedCache === null ) {
14057 $input = $( '<input type="file">' );
14058 OO.ui.SelectFileWidget.static.isSupportedCache = $input[ 0 ].files !== undefined;
14059 }
14060 return OO.ui.SelectFileWidget.static.isSupportedCache;
14061 };
14062
14063 OO.ui.SelectFileWidget.static.isSupportedCache = null;
14064
14065 /* Events */
14066
14067 /**
14068 * @event change
14069 *
14070 * A change event is emitted when the on/off state of the toggle changes.
14071 *
14072 * @param {File|null} value New value
14073 */
14074
14075 /* Methods */
14076
14077 /**
14078 * Get the current value of the field
14079 *
14080 * @return {File|null}
14081 */
14082 OO.ui.SelectFileWidget.prototype.getValue = function () {
14083 return this.currentFile;
14084 };
14085
14086 /**
14087 * Set the current value of the field
14088 *
14089 * @param {File|null} file File to select
14090 */
14091 OO.ui.SelectFileWidget.prototype.setValue = function ( file ) {
14092 if ( this.currentFile !== file ) {
14093 this.currentFile = file;
14094 this.updateUI();
14095 this.emit( 'change', this.currentFile );
14096 }
14097 };
14098
14099 /**
14100 * Update the user interface when a file is selected or unselected
14101 *
14102 * @protected
14103 */
14104 OO.ui.SelectFileWidget.prototype.updateUI = function () {
14105 var $label;
14106 if ( !this.isSupported ) {
14107 this.$element.addClass( 'oo-ui-selectFileWidget-notsupported' );
14108 this.$element.removeClass( 'oo-ui-selectFileWidget-empty' );
14109 this.setLabel( this.notsupported );
14110 } else {
14111 this.$element.addClass( 'oo-ui-selectFileWidget-supported' );
14112 if ( this.currentFile ) {
14113 this.$element.removeClass( 'oo-ui-selectFileWidget-empty' );
14114 $label = $( [] );
14115 if ( this.currentFile.type !== '' ) {
14116 $label = $label.add( $( '<span>' ).addClass( 'oo-ui-selectFileWidget-fileType' ).text( this.currentFile.type ) );
14117 }
14118 $label = $label.add( $( '<span>' ).text( this.currentFile.name ) );
14119 this.setLabel( $label );
14120 } else {
14121 this.$element.addClass( 'oo-ui-selectFileWidget-empty' );
14122 this.setLabel( this.placeholder );
14123 }
14124 }
14125
14126 if ( this.$input ) {
14127 this.$input.attr( 'title', this.getLabel() );
14128 }
14129 };
14130
14131 /**
14132 * Add the input to the widget
14133 *
14134 * @private
14135 */
14136 OO.ui.SelectFileWidget.prototype.addInput = function () {
14137 if ( this.$input ) {
14138 this.$input.remove();
14139 }
14140
14141 if ( !this.isSupported ) {
14142 this.$input = null;
14143 return;
14144 }
14145
14146 this.$input = $( '<input type="file">' );
14147 this.$input.on( 'change', this.onFileSelectedHandler );
14148 this.$input.attr( {
14149 tabindex: -1,
14150 title: this.getLabel()
14151 } );
14152 if ( this.accept ) {
14153 this.$input.attr( 'accept', this.accept.join( ', ' ) );
14154 }
14155 this.selectButton.$button.append( this.$input );
14156 };
14157
14158 /**
14159 * Determine if we should accept this file
14160 *
14161 * @private
14162 * @param {string} File MIME type
14163 * @return {boolean}
14164 */
14165 OO.ui.SelectFileWidget.prototype.isAllowedType = function ( mimeType ) {
14166 var i, mimeTest;
14167
14168 if ( !this.accept || !mimeType ) {
14169 return true;
14170 }
14171
14172 for ( i = 0; i < this.accept.length; i++ ) {
14173 mimeTest = this.accept[ i ];
14174 if ( mimeTest === mimeType ) {
14175 return true;
14176 } else if ( mimeTest.substr( -2 ) === '/*' ) {
14177 mimeTest = mimeTest.substr( 0, mimeTest.length - 1 );
14178 if ( mimeType.substr( 0, mimeTest.length ) === mimeTest ) {
14179 return true;
14180 }
14181 }
14182 }
14183
14184 return false;
14185 };
14186
14187 /**
14188 * Handle file selection from the input
14189 *
14190 * @private
14191 * @param {jQuery.Event} e
14192 */
14193 OO.ui.SelectFileWidget.prototype.onFileSelected = function ( e ) {
14194 var file = OO.getProp( e.target, 'files', 0 ) || null;
14195
14196 if ( file && !this.isAllowedType( file.type ) ) {
14197 file = null;
14198 }
14199
14200 this.setValue( file );
14201 this.addInput();
14202 };
14203
14204 /**
14205 * Handle clear button click events.
14206 *
14207 * @private
14208 */
14209 OO.ui.SelectFileWidget.prototype.onClearClick = function () {
14210 this.setValue( null );
14211 return false;
14212 };
14213
14214 /**
14215 * Handle key press events.
14216 *
14217 * @private
14218 * @param {jQuery.Event} e Key press event
14219 */
14220 OO.ui.SelectFileWidget.prototype.onKeyPress = function ( e ) {
14221 if ( this.isSupported && !this.isDisabled() && this.$input &&
14222 ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
14223 ) {
14224 this.$input.click();
14225 return false;
14226 }
14227 };
14228
14229 /**
14230 * Handle drop target click events.
14231 *
14232 * @private
14233 * @param {jQuery.Event} e Key press event
14234 */
14235 OO.ui.SelectFileWidget.prototype.onDropTargetClick = function () {
14236 if ( this.isSupported && !this.isDisabled() && this.$input ) {
14237 this.$input.click();
14238 return false;
14239 }
14240 };
14241
14242 /**
14243 * Handle drag enter and over events
14244 *
14245 * @private
14246 * @param {jQuery.Event} e Drag event
14247 */
14248 OO.ui.SelectFileWidget.prototype.onDragEnterOrOver = function ( e ) {
14249 var itemOrFile,
14250 droppableFile = false,
14251 dt = e.originalEvent.dataTransfer;
14252
14253 e.preventDefault();
14254 e.stopPropagation();
14255
14256 if ( this.isDisabled() || !this.isSupported ) {
14257 this.$element.removeClass( 'oo-ui-selectFileWidget-canDrop' );
14258 dt.dropEffect = 'none';
14259 return false;
14260 }
14261
14262 // DataTransferItem and File both have a type property, but in Chrome files
14263 // have no information at this point.
14264 itemOrFile = OO.getProp( dt, 'items', 0 ) || OO.getProp( dt, 'files', 0 );
14265 if ( itemOrFile ) {
14266 if ( this.isAllowedType( itemOrFile.type ) ) {
14267 droppableFile = true;
14268 }
14269 // dt.types is Array-like, but not an Array
14270 } else if ( Array.prototype.indexOf.call( OO.getProp( dt, 'types' ) || [], 'Files' ) !== -1 ) {
14271 // File information is not available at this point for security so just assume
14272 // it is acceptable for now.
14273 // https://bugzilla.mozilla.org/show_bug.cgi?id=640534
14274 droppableFile = true;
14275 }
14276
14277 this.$element.toggleClass( 'oo-ui-selectFileWidget-canDrop', droppableFile );
14278 if ( !droppableFile ) {
14279 dt.dropEffect = 'none';
14280 }
14281
14282 return false;
14283 };
14284
14285 /**
14286 * Handle drag leave events
14287 *
14288 * @private
14289 * @param {jQuery.Event} e Drag event
14290 */
14291 OO.ui.SelectFileWidget.prototype.onDragLeave = function () {
14292 this.$element.removeClass( 'oo-ui-selectFileWidget-canDrop' );
14293 };
14294
14295 /**
14296 * Handle drop events
14297 *
14298 * @private
14299 * @param {jQuery.Event} e Drop event
14300 */
14301 OO.ui.SelectFileWidget.prototype.onDrop = function ( e ) {
14302 var file = null,
14303 dt = e.originalEvent.dataTransfer;
14304
14305 e.preventDefault();
14306 e.stopPropagation();
14307 this.$element.removeClass( 'oo-ui-selectFileWidget-canDrop' );
14308
14309 if ( this.isDisabled() || !this.isSupported ) {
14310 return false;
14311 }
14312
14313 file = OO.getProp( dt, 'files', 0 );
14314 if ( file && !this.isAllowedType( file.type ) ) {
14315 file = null;
14316 }
14317 if ( file ) {
14318 this.setValue( file );
14319 }
14320
14321 return false;
14322 };
14323
14324 /**
14325 * @inheritdoc
14326 */
14327 OO.ui.SelectFileWidget.prototype.setDisabled = function ( disabled ) {
14328 OO.ui.SelectFileWidget.parent.prototype.setDisabled.call( this, disabled );
14329 if ( this.selectButton ) {
14330 this.selectButton.setDisabled( disabled );
14331 }
14332 if ( this.clearButton ) {
14333 this.clearButton.setDisabled( disabled );
14334 }
14335 return this;
14336 };
14337
14338 /**
14339 * IconWidget is a generic widget for {@link OO.ui.mixin.IconElement icons}. In general, IconWidgets should be used with OO.ui.LabelWidget,
14340 * which creates a label that identifies the icon’s function. See the [OOjs UI documentation on MediaWiki] [1]
14341 * for a list of icons included in the library.
14342 *
14343 * @example
14344 * // An icon widget with a label
14345 * var myIcon = new OO.ui.IconWidget( {
14346 * icon: 'help',
14347 * iconTitle: 'Help'
14348 * } );
14349 * // Create a label.
14350 * var iconLabel = new OO.ui.LabelWidget( {
14351 * label: 'Help'
14352 * } );
14353 * $( 'body' ).append( myIcon.$element, iconLabel.$element );
14354 *
14355 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
14356 *
14357 * @class
14358 * @extends OO.ui.Widget
14359 * @mixins OO.ui.mixin.IconElement
14360 * @mixins OO.ui.mixin.TitledElement
14361 * @mixins OO.ui.mixin.FlaggedElement
14362 *
14363 * @constructor
14364 * @param {Object} [config] Configuration options
14365 */
14366 OO.ui.IconWidget = function OoUiIconWidget( config ) {
14367 // Configuration initialization
14368 config = config || {};
14369
14370 // Parent constructor
14371 OO.ui.IconWidget.parent.call( this, config );
14372
14373 // Mixin constructors
14374 OO.ui.mixin.IconElement.call( this, $.extend( {}, config, { $icon: this.$element } ) );
14375 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$element } ) );
14376 OO.ui.mixin.FlaggedElement.call( this, $.extend( {}, config, { $flagged: this.$element } ) );
14377
14378 // Initialization
14379 this.$element.addClass( 'oo-ui-iconWidget' );
14380 };
14381
14382 /* Setup */
14383
14384 OO.inheritClass( OO.ui.IconWidget, OO.ui.Widget );
14385 OO.mixinClass( OO.ui.IconWidget, OO.ui.mixin.IconElement );
14386 OO.mixinClass( OO.ui.IconWidget, OO.ui.mixin.TitledElement );
14387 OO.mixinClass( OO.ui.IconWidget, OO.ui.mixin.FlaggedElement );
14388
14389 /* Static Properties */
14390
14391 OO.ui.IconWidget.static.tagName = 'span';
14392
14393 /**
14394 * IndicatorWidgets create indicators, which are small graphics that are generally used to draw
14395 * attention to the status of an item or to clarify the function of a control. For a list of
14396 * indicators included in the library, please see the [OOjs UI documentation on MediaWiki][1].
14397 *
14398 * @example
14399 * // Example of an indicator widget
14400 * var indicator1 = new OO.ui.IndicatorWidget( {
14401 * indicator: 'alert'
14402 * } );
14403 *
14404 * // Create a fieldset layout to add a label
14405 * var fieldset = new OO.ui.FieldsetLayout();
14406 * fieldset.addItems( [
14407 * new OO.ui.FieldLayout( indicator1, { label: 'An alert indicator:' } )
14408 * ] );
14409 * $( 'body' ).append( fieldset.$element );
14410 *
14411 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
14412 *
14413 * @class
14414 * @extends OO.ui.Widget
14415 * @mixins OO.ui.mixin.IndicatorElement
14416 * @mixins OO.ui.mixin.TitledElement
14417 *
14418 * @constructor
14419 * @param {Object} [config] Configuration options
14420 */
14421 OO.ui.IndicatorWidget = function OoUiIndicatorWidget( config ) {
14422 // Configuration initialization
14423 config = config || {};
14424
14425 // Parent constructor
14426 OO.ui.IndicatorWidget.parent.call( this, config );
14427
14428 // Mixin constructors
14429 OO.ui.mixin.IndicatorElement.call( this, $.extend( {}, config, { $indicator: this.$element } ) );
14430 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$element } ) );
14431
14432 // Initialization
14433 this.$element.addClass( 'oo-ui-indicatorWidget' );
14434 };
14435
14436 /* Setup */
14437
14438 OO.inheritClass( OO.ui.IndicatorWidget, OO.ui.Widget );
14439 OO.mixinClass( OO.ui.IndicatorWidget, OO.ui.mixin.IndicatorElement );
14440 OO.mixinClass( OO.ui.IndicatorWidget, OO.ui.mixin.TitledElement );
14441
14442 /* Static Properties */
14443
14444 OO.ui.IndicatorWidget.static.tagName = 'span';
14445
14446 /**
14447 * InputWidget is the base class for all input widgets, which
14448 * include {@link OO.ui.TextInputWidget text inputs}, {@link OO.ui.CheckboxInputWidget checkbox inputs},
14449 * {@link OO.ui.RadioInputWidget radio inputs}, and {@link OO.ui.ButtonInputWidget button inputs}.
14450 * See the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
14451 *
14452 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
14453 *
14454 * @abstract
14455 * @class
14456 * @extends OO.ui.Widget
14457 * @mixins OO.ui.mixin.FlaggedElement
14458 * @mixins OO.ui.mixin.TabIndexedElement
14459 * @mixins OO.ui.mixin.TitledElement
14460 * @mixins OO.ui.mixin.AccessKeyedElement
14461 *
14462 * @constructor
14463 * @param {Object} [config] Configuration options
14464 * @cfg {string} [name=''] The value of the input’s HTML `name` attribute.
14465 * @cfg {string} [value=''] The value of the input.
14466 * @cfg {string} [accessKey=''] The access key of the input.
14467 * @cfg {Function} [inputFilter] The name of an input filter function. Input filters modify the value of an input
14468 * before it is accepted.
14469 */
14470 OO.ui.InputWidget = function OoUiInputWidget( config ) {
14471 // Configuration initialization
14472 config = config || {};
14473
14474 // Parent constructor
14475 OO.ui.InputWidget.parent.call( this, config );
14476
14477 // Properties
14478 this.$input = this.getInputElement( config );
14479 this.value = '';
14480 this.inputFilter = config.inputFilter;
14481
14482 // Mixin constructors
14483 OO.ui.mixin.FlaggedElement.call( this, config );
14484 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$input } ) );
14485 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$input } ) );
14486 OO.ui.mixin.AccessKeyedElement.call( this, $.extend( {}, config, { $accessKeyed: this.$input } ) );
14487
14488 // Events
14489 this.$input.on( 'keydown mouseup cut paste change input select', this.onEdit.bind( this ) );
14490
14491 // Initialization
14492 this.$input
14493 .addClass( 'oo-ui-inputWidget-input' )
14494 .attr( 'name', config.name )
14495 .prop( 'disabled', this.isDisabled() );
14496 this.$element
14497 .addClass( 'oo-ui-inputWidget' )
14498 .append( this.$input );
14499 this.setValue( config.value );
14500 this.setAccessKey( config.accessKey );
14501 };
14502
14503 /* Setup */
14504
14505 OO.inheritClass( OO.ui.InputWidget, OO.ui.Widget );
14506 OO.mixinClass( OO.ui.InputWidget, OO.ui.mixin.FlaggedElement );
14507 OO.mixinClass( OO.ui.InputWidget, OO.ui.mixin.TabIndexedElement );
14508 OO.mixinClass( OO.ui.InputWidget, OO.ui.mixin.TitledElement );
14509 OO.mixinClass( OO.ui.InputWidget, OO.ui.mixin.AccessKeyedElement );
14510
14511 /* Static Properties */
14512
14513 OO.ui.InputWidget.static.supportsSimpleLabel = true;
14514
14515 /* Events */
14516
14517 /**
14518 * @event change
14519 *
14520 * A change event is emitted when the value of the input changes.
14521 *
14522 * @param {string} value
14523 */
14524
14525 /* Methods */
14526
14527 /**
14528 * Get input element.
14529 *
14530 * Subclasses of OO.ui.InputWidget use the `config` parameter to produce different elements in
14531 * different circumstances. The element must have a `value` property (like form elements).
14532 *
14533 * @protected
14534 * @param {Object} config Configuration options
14535 * @return {jQuery} Input element
14536 */
14537 OO.ui.InputWidget.prototype.getInputElement = function () {
14538 return $( '<input>' );
14539 };
14540
14541 /**
14542 * Handle potentially value-changing events.
14543 *
14544 * @private
14545 * @param {jQuery.Event} e Key down, mouse up, cut, paste, change, input, or select event
14546 */
14547 OO.ui.InputWidget.prototype.onEdit = function () {
14548 var widget = this;
14549 if ( !this.isDisabled() ) {
14550 // Allow the stack to clear so the value will be updated
14551 setTimeout( function () {
14552 widget.setValue( widget.$input.val() );
14553 } );
14554 }
14555 };
14556
14557 /**
14558 * Get the value of the input.
14559 *
14560 * @return {string} Input value
14561 */
14562 OO.ui.InputWidget.prototype.getValue = function () {
14563 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
14564 // it, and we won't know unless they're kind enough to trigger a 'change' event.
14565 var value = this.$input.val();
14566 if ( this.value !== value ) {
14567 this.setValue( value );
14568 }
14569 return this.value;
14570 };
14571
14572 /**
14573 * Set the direction of the input, either RTL (right-to-left) or LTR (left-to-right).
14574 *
14575 * @param {boolean} isRTL
14576 * Direction is right-to-left
14577 */
14578 OO.ui.InputWidget.prototype.setRTL = function ( isRTL ) {
14579 this.$input.prop( 'dir', isRTL ? 'rtl' : 'ltr' );
14580 };
14581
14582 /**
14583 * Set the value of the input.
14584 *
14585 * @param {string} value New value
14586 * @fires change
14587 * @chainable
14588 */
14589 OO.ui.InputWidget.prototype.setValue = function ( value ) {
14590 value = this.cleanUpValue( value );
14591 // Update the DOM if it has changed. Note that with cleanUpValue, it
14592 // is possible for the DOM value to change without this.value changing.
14593 if ( this.$input.val() !== value ) {
14594 this.$input.val( value );
14595 }
14596 if ( this.value !== value ) {
14597 this.value = value;
14598 this.emit( 'change', this.value );
14599 }
14600 return this;
14601 };
14602
14603 /**
14604 * Set the input's access key.
14605 * FIXME: This is the same code as in OO.ui.mixin.ButtonElement, maybe find a better place for it?
14606 *
14607 * @param {string} accessKey Input's access key, use empty string to remove
14608 * @chainable
14609 */
14610 OO.ui.InputWidget.prototype.setAccessKey = function ( accessKey ) {
14611 accessKey = typeof accessKey === 'string' && accessKey.length ? accessKey : null;
14612
14613 if ( this.accessKey !== accessKey ) {
14614 if ( this.$input ) {
14615 if ( accessKey !== null ) {
14616 this.$input.attr( 'accesskey', accessKey );
14617 } else {
14618 this.$input.removeAttr( 'accesskey' );
14619 }
14620 }
14621 this.accessKey = accessKey;
14622 }
14623
14624 return this;
14625 };
14626
14627 /**
14628 * Clean up incoming value.
14629 *
14630 * Ensures value is a string, and converts undefined and null to empty string.
14631 *
14632 * @private
14633 * @param {string} value Original value
14634 * @return {string} Cleaned up value
14635 */
14636 OO.ui.InputWidget.prototype.cleanUpValue = function ( value ) {
14637 if ( value === undefined || value === null ) {
14638 return '';
14639 } else if ( this.inputFilter ) {
14640 return this.inputFilter( String( value ) );
14641 } else {
14642 return String( value );
14643 }
14644 };
14645
14646 /**
14647 * Simulate the behavior of clicking on a label bound to this input. This method is only called by
14648 * {@link OO.ui.LabelWidget LabelWidget} and {@link OO.ui.FieldLayout FieldLayout}. It should not be
14649 * called directly.
14650 */
14651 OO.ui.InputWidget.prototype.simulateLabelClick = function () {
14652 if ( !this.isDisabled() ) {
14653 if ( this.$input.is( ':checkbox, :radio' ) ) {
14654 this.$input.click();
14655 }
14656 if ( this.$input.is( ':input' ) ) {
14657 this.$input[ 0 ].focus();
14658 }
14659 }
14660 };
14661
14662 /**
14663 * @inheritdoc
14664 */
14665 OO.ui.InputWidget.prototype.setDisabled = function ( state ) {
14666 OO.ui.InputWidget.parent.prototype.setDisabled.call( this, state );
14667 if ( this.$input ) {
14668 this.$input.prop( 'disabled', this.isDisabled() );
14669 }
14670 return this;
14671 };
14672
14673 /**
14674 * Focus the input.
14675 *
14676 * @chainable
14677 */
14678 OO.ui.InputWidget.prototype.focus = function () {
14679 this.$input[ 0 ].focus();
14680 return this;
14681 };
14682
14683 /**
14684 * Blur the input.
14685 *
14686 * @chainable
14687 */
14688 OO.ui.InputWidget.prototype.blur = function () {
14689 this.$input[ 0 ].blur();
14690 return this;
14691 };
14692
14693 /**
14694 * @inheritdoc
14695 */
14696 OO.ui.InputWidget.prototype.gatherPreInfuseState = function ( node ) {
14697 var
14698 state = OO.ui.InputWidget.parent.prototype.gatherPreInfuseState.call( this, node ),
14699 $input = state.$input || $( node ).find( '.oo-ui-inputWidget-input' );
14700 state.value = $input.val();
14701 // Might be better in TabIndexedElement, but it's awkward to do there because mixins are awkward
14702 state.focus = $input.is( ':focus' );
14703 return state;
14704 };
14705
14706 /**
14707 * @inheritdoc
14708 */
14709 OO.ui.InputWidget.prototype.restorePreInfuseState = function ( state ) {
14710 OO.ui.InputWidget.parent.prototype.restorePreInfuseState.call( this, state );
14711 if ( state.value !== undefined && state.value !== this.getValue() ) {
14712 this.setValue( state.value );
14713 }
14714 if ( state.focus ) {
14715 this.focus();
14716 }
14717 };
14718
14719 /**
14720 * ButtonInputWidget is used to submit HTML forms and is intended to be used within
14721 * a OO.ui.FormLayout. If you do not need the button to work with HTML forms, you probably
14722 * want to use OO.ui.ButtonWidget instead. Button input widgets can be rendered as either an
14723 * HTML `<button/>` (the default) or an HTML `<input/>` tags. See the
14724 * [OOjs UI documentation on MediaWiki] [1] for more information.
14725 *
14726 * @example
14727 * // A ButtonInputWidget rendered as an HTML button, the default.
14728 * var button = new OO.ui.ButtonInputWidget( {
14729 * label: 'Input button',
14730 * icon: 'check',
14731 * value: 'check'
14732 * } );
14733 * $( 'body' ).append( button.$element );
14734 *
14735 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs#Button_inputs
14736 *
14737 * @class
14738 * @extends OO.ui.InputWidget
14739 * @mixins OO.ui.mixin.ButtonElement
14740 * @mixins OO.ui.mixin.IconElement
14741 * @mixins OO.ui.mixin.IndicatorElement
14742 * @mixins OO.ui.mixin.LabelElement
14743 * @mixins OO.ui.mixin.TitledElement
14744 *
14745 * @constructor
14746 * @param {Object} [config] Configuration options
14747 * @cfg {string} [type='button'] The value of the HTML `'type'` attribute: 'button', 'submit' or 'reset'.
14748 * @cfg {boolean} [useInputTag=false] Use an `<input/>` tag instead of a `<button/>` tag, the default.
14749 * Widgets configured to be an `<input/>` do not support {@link #icon icons} and {@link #indicator indicators},
14750 * non-plaintext {@link #label labels}, or {@link #value values}. In general, useInputTag should only
14751 * be set to `true` when there’s need to support IE6 in a form with multiple buttons.
14752 */
14753 OO.ui.ButtonInputWidget = function OoUiButtonInputWidget( config ) {
14754 // Configuration initialization
14755 config = $.extend( { type: 'button', useInputTag: false }, config );
14756
14757 // Properties (must be set before parent constructor, which calls #setValue)
14758 this.useInputTag = config.useInputTag;
14759
14760 // Parent constructor
14761 OO.ui.ButtonInputWidget.parent.call( this, config );
14762
14763 // Mixin constructors
14764 OO.ui.mixin.ButtonElement.call( this, $.extend( {}, config, { $button: this.$input } ) );
14765 OO.ui.mixin.IconElement.call( this, config );
14766 OO.ui.mixin.IndicatorElement.call( this, config );
14767 OO.ui.mixin.LabelElement.call( this, config );
14768 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$input } ) );
14769
14770 // Initialization
14771 if ( !config.useInputTag ) {
14772 this.$input.append( this.$icon, this.$label, this.$indicator );
14773 }
14774 this.$element.addClass( 'oo-ui-buttonInputWidget' );
14775 };
14776
14777 /* Setup */
14778
14779 OO.inheritClass( OO.ui.ButtonInputWidget, OO.ui.InputWidget );
14780 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.ButtonElement );
14781 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.IconElement );
14782 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.IndicatorElement );
14783 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.LabelElement );
14784 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.TitledElement );
14785
14786 /* Static Properties */
14787
14788 /**
14789 * Disable generating `<label>` elements for buttons. One would very rarely need additional label
14790 * for a button, and it's already a big clickable target, and it causes unexpected rendering.
14791 */
14792 OO.ui.ButtonInputWidget.static.supportsSimpleLabel = false;
14793
14794 /* Methods */
14795
14796 /**
14797 * @inheritdoc
14798 * @protected
14799 */
14800 OO.ui.ButtonInputWidget.prototype.getInputElement = function ( config ) {
14801 var type = [ 'button', 'submit', 'reset' ].indexOf( config.type ) !== -1 ?
14802 config.type :
14803 'button';
14804 return $( '<' + ( config.useInputTag ? 'input' : 'button' ) + ' type="' + type + '">' );
14805 };
14806
14807 /**
14808 * Set label value.
14809 *
14810 * If #useInputTag is `true`, the label is set as the `value` of the `<input/>` tag.
14811 *
14812 * @param {jQuery|string|Function|null} label Label nodes, text, a function that returns nodes or
14813 * text, or `null` for no label
14814 * @chainable
14815 */
14816 OO.ui.ButtonInputWidget.prototype.setLabel = function ( label ) {
14817 OO.ui.mixin.LabelElement.prototype.setLabel.call( this, label );
14818
14819 if ( this.useInputTag ) {
14820 if ( typeof label === 'function' ) {
14821 label = OO.ui.resolveMsg( label );
14822 }
14823 if ( label instanceof jQuery ) {
14824 label = label.text();
14825 }
14826 if ( !label ) {
14827 label = '';
14828 }
14829 this.$input.val( label );
14830 }
14831
14832 return this;
14833 };
14834
14835 /**
14836 * Set the value of the input.
14837 *
14838 * This method is disabled for button inputs configured as {@link #useInputTag <input/> tags}, as
14839 * they do not support {@link #value values}.
14840 *
14841 * @param {string} value New value
14842 * @chainable
14843 */
14844 OO.ui.ButtonInputWidget.prototype.setValue = function ( value ) {
14845 if ( !this.useInputTag ) {
14846 OO.ui.ButtonInputWidget.parent.prototype.setValue.call( this, value );
14847 }
14848 return this;
14849 };
14850
14851 /**
14852 * CheckboxInputWidgets, like HTML checkboxes, can be selected and/or configured with a value.
14853 * Note that these {@link OO.ui.InputWidget input widgets} are best laid out
14854 * in {@link OO.ui.FieldLayout field layouts} that use the {@link OO.ui.FieldLayout#align inline}
14855 * alignment. For more information, please see the [OOjs UI documentation on MediaWiki][1].
14856 *
14857 * This widget can be used inside a HTML form, such as a OO.ui.FormLayout.
14858 *
14859 * @example
14860 * // An example of selected, unselected, and disabled checkbox inputs
14861 * var checkbox1=new OO.ui.CheckboxInputWidget( {
14862 * value: 'a',
14863 * selected: true
14864 * } );
14865 * var checkbox2=new OO.ui.CheckboxInputWidget( {
14866 * value: 'b'
14867 * } );
14868 * var checkbox3=new OO.ui.CheckboxInputWidget( {
14869 * value:'c',
14870 * disabled: true
14871 * } );
14872 * // Create a fieldset layout with fields for each checkbox.
14873 * var fieldset = new OO.ui.FieldsetLayout( {
14874 * label: 'Checkboxes'
14875 * } );
14876 * fieldset.addItems( [
14877 * new OO.ui.FieldLayout( checkbox1, { label: 'Selected checkbox', align: 'inline' } ),
14878 * new OO.ui.FieldLayout( checkbox2, { label: 'Unselected checkbox', align: 'inline' } ),
14879 * new OO.ui.FieldLayout( checkbox3, { label: 'Disabled checkbox', align: 'inline' } ),
14880 * ] );
14881 * $( 'body' ).append( fieldset.$element );
14882 *
14883 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
14884 *
14885 * @class
14886 * @extends OO.ui.InputWidget
14887 *
14888 * @constructor
14889 * @param {Object} [config] Configuration options
14890 * @cfg {boolean} [selected=false] Select the checkbox initially. By default, the checkbox is not selected.
14891 */
14892 OO.ui.CheckboxInputWidget = function OoUiCheckboxInputWidget( config ) {
14893 // Configuration initialization
14894 config = config || {};
14895
14896 // Parent constructor
14897 OO.ui.CheckboxInputWidget.parent.call( this, config );
14898
14899 // Initialization
14900 this.$element
14901 .addClass( 'oo-ui-checkboxInputWidget' )
14902 // Required for pretty styling in MediaWiki theme
14903 .append( $( '<span>' ) );
14904 this.setSelected( config.selected !== undefined ? config.selected : false );
14905 };
14906
14907 /* Setup */
14908
14909 OO.inheritClass( OO.ui.CheckboxInputWidget, OO.ui.InputWidget );
14910
14911 /* Methods */
14912
14913 /**
14914 * @inheritdoc
14915 * @protected
14916 */
14917 OO.ui.CheckboxInputWidget.prototype.getInputElement = function () {
14918 return $( '<input type="checkbox" />' );
14919 };
14920
14921 /**
14922 * @inheritdoc
14923 */
14924 OO.ui.CheckboxInputWidget.prototype.onEdit = function () {
14925 var widget = this;
14926 if ( !this.isDisabled() ) {
14927 // Allow the stack to clear so the value will be updated
14928 setTimeout( function () {
14929 widget.setSelected( widget.$input.prop( 'checked' ) );
14930 } );
14931 }
14932 };
14933
14934 /**
14935 * Set selection state of this checkbox.
14936 *
14937 * @param {boolean} state `true` for selected
14938 * @chainable
14939 */
14940 OO.ui.CheckboxInputWidget.prototype.setSelected = function ( state ) {
14941 state = !!state;
14942 if ( this.selected !== state ) {
14943 this.selected = state;
14944 this.$input.prop( 'checked', this.selected );
14945 this.emit( 'change', this.selected );
14946 }
14947 return this;
14948 };
14949
14950 /**
14951 * Check if this checkbox is selected.
14952 *
14953 * @return {boolean} Checkbox is selected
14954 */
14955 OO.ui.CheckboxInputWidget.prototype.isSelected = function () {
14956 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
14957 // it, and we won't know unless they're kind enough to trigger a 'change' event.
14958 var selected = this.$input.prop( 'checked' );
14959 if ( this.selected !== selected ) {
14960 this.setSelected( selected );
14961 }
14962 return this.selected;
14963 };
14964
14965 /**
14966 * @inheritdoc
14967 */
14968 OO.ui.CheckboxInputWidget.prototype.gatherPreInfuseState = function ( node ) {
14969 var
14970 state = OO.ui.CheckboxInputWidget.parent.prototype.gatherPreInfuseState.call( this, node ),
14971 $input = $( node ).find( '.oo-ui-inputWidget-input' );
14972 state.$input = $input; // shortcut for performance, used in InputWidget
14973 state.checked = $input.prop( 'checked' );
14974 return state;
14975 };
14976
14977 /**
14978 * @inheritdoc
14979 */
14980 OO.ui.CheckboxInputWidget.prototype.restorePreInfuseState = function ( state ) {
14981 OO.ui.CheckboxInputWidget.parent.prototype.restorePreInfuseState.call( this, state );
14982 if ( state.checked !== undefined && state.checked !== this.isSelected() ) {
14983 this.setSelected( state.checked );
14984 }
14985 };
14986
14987 /**
14988 * DropdownInputWidget is a {@link OO.ui.DropdownWidget DropdownWidget} intended to be used
14989 * within a HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with the value
14990 * of a hidden HTML `input` tag. Please see the [OOjs UI documentation on MediaWiki][1] for
14991 * more information about input widgets.
14992 *
14993 * A DropdownInputWidget always has a value (one of the options is always selected), unless there
14994 * are no options. If no `value` configuration option is provided, the first option is selected.
14995 * If you need a state representing no value (no option being selected), use a DropdownWidget.
14996 *
14997 * This and OO.ui.RadioSelectInputWidget support the same configuration options.
14998 *
14999 * @example
15000 * // Example: A DropdownInputWidget with three options
15001 * var dropdownInput = new OO.ui.DropdownInputWidget( {
15002 * options: [
15003 * { data: 'a', label: 'First' },
15004 * { data: 'b', label: 'Second'},
15005 * { data: 'c', label: 'Third' }
15006 * ]
15007 * } );
15008 * $( 'body' ).append( dropdownInput.$element );
15009 *
15010 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
15011 *
15012 * @class
15013 * @extends OO.ui.InputWidget
15014 * @mixins OO.ui.mixin.TitledElement
15015 *
15016 * @constructor
15017 * @param {Object} [config] Configuration options
15018 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
15019 * @cfg {Object} [dropdown] Configuration options for {@link OO.ui.DropdownWidget DropdownWidget}
15020 */
15021 OO.ui.DropdownInputWidget = function OoUiDropdownInputWidget( config ) {
15022 // Configuration initialization
15023 config = config || {};
15024
15025 // Properties (must be done before parent constructor which calls #setDisabled)
15026 this.dropdownWidget = new OO.ui.DropdownWidget( config.dropdown );
15027
15028 // Parent constructor
15029 OO.ui.DropdownInputWidget.parent.call( this, config );
15030
15031 // Mixin constructors
15032 OO.ui.mixin.TitledElement.call( this, config );
15033
15034 // Events
15035 this.dropdownWidget.getMenu().connect( this, { select: 'onMenuSelect' } );
15036
15037 // Initialization
15038 this.setOptions( config.options || [] );
15039 this.$element
15040 .addClass( 'oo-ui-dropdownInputWidget' )
15041 .append( this.dropdownWidget.$element );
15042 };
15043
15044 /* Setup */
15045
15046 OO.inheritClass( OO.ui.DropdownInputWidget, OO.ui.InputWidget );
15047 OO.mixinClass( OO.ui.DropdownInputWidget, OO.ui.mixin.TitledElement );
15048
15049 /* Methods */
15050
15051 /**
15052 * @inheritdoc
15053 * @protected
15054 */
15055 OO.ui.DropdownInputWidget.prototype.getInputElement = function () {
15056 return $( '<input type="hidden">' );
15057 };
15058
15059 /**
15060 * Handles menu select events.
15061 *
15062 * @private
15063 * @param {OO.ui.MenuOptionWidget} item Selected menu item
15064 */
15065 OO.ui.DropdownInputWidget.prototype.onMenuSelect = function ( item ) {
15066 this.setValue( item.getData() );
15067 };
15068
15069 /**
15070 * @inheritdoc
15071 */
15072 OO.ui.DropdownInputWidget.prototype.setValue = function ( value ) {
15073 value = this.cleanUpValue( value );
15074 this.dropdownWidget.getMenu().selectItemByData( value );
15075 OO.ui.DropdownInputWidget.parent.prototype.setValue.call( this, value );
15076 return this;
15077 };
15078
15079 /**
15080 * @inheritdoc
15081 */
15082 OO.ui.DropdownInputWidget.prototype.setDisabled = function ( state ) {
15083 this.dropdownWidget.setDisabled( state );
15084 OO.ui.DropdownInputWidget.parent.prototype.setDisabled.call( this, state );
15085 return this;
15086 };
15087
15088 /**
15089 * Set the options available for this input.
15090 *
15091 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
15092 * @chainable
15093 */
15094 OO.ui.DropdownInputWidget.prototype.setOptions = function ( options ) {
15095 var
15096 value = this.getValue(),
15097 widget = this;
15098
15099 // Rebuild the dropdown menu
15100 this.dropdownWidget.getMenu()
15101 .clearItems()
15102 .addItems( options.map( function ( opt ) {
15103 var optValue = widget.cleanUpValue( opt.data );
15104 return new OO.ui.MenuOptionWidget( {
15105 data: optValue,
15106 label: opt.label !== undefined ? opt.label : optValue
15107 } );
15108 } ) );
15109
15110 // Restore the previous value, or reset to something sensible
15111 if ( this.dropdownWidget.getMenu().getItemFromData( value ) ) {
15112 // Previous value is still available, ensure consistency with the dropdown
15113 this.setValue( value );
15114 } else {
15115 // No longer valid, reset
15116 if ( options.length ) {
15117 this.setValue( options[ 0 ].data );
15118 }
15119 }
15120
15121 return this;
15122 };
15123
15124 /**
15125 * @inheritdoc
15126 */
15127 OO.ui.DropdownInputWidget.prototype.focus = function () {
15128 this.dropdownWidget.getMenu().toggle( true );
15129 return this;
15130 };
15131
15132 /**
15133 * @inheritdoc
15134 */
15135 OO.ui.DropdownInputWidget.prototype.blur = function () {
15136 this.dropdownWidget.getMenu().toggle( false );
15137 return this;
15138 };
15139
15140 /**
15141 * RadioInputWidget creates a single radio button. Because radio buttons are usually used as a set,
15142 * in most cases you will want to use a {@link OO.ui.RadioSelectWidget radio select}
15143 * with {@link OO.ui.RadioOptionWidget radio options} instead of this class. For more information,
15144 * please see the [OOjs UI documentation on MediaWiki][1].
15145 *
15146 * This widget can be used inside a HTML form, such as a OO.ui.FormLayout.
15147 *
15148 * @example
15149 * // An example of selected, unselected, and disabled radio inputs
15150 * var radio1 = new OO.ui.RadioInputWidget( {
15151 * value: 'a',
15152 * selected: true
15153 * } );
15154 * var radio2 = new OO.ui.RadioInputWidget( {
15155 * value: 'b'
15156 * } );
15157 * var radio3 = new OO.ui.RadioInputWidget( {
15158 * value: 'c',
15159 * disabled: true
15160 * } );
15161 * // Create a fieldset layout with fields for each radio button.
15162 * var fieldset = new OO.ui.FieldsetLayout( {
15163 * label: 'Radio inputs'
15164 * } );
15165 * fieldset.addItems( [
15166 * new OO.ui.FieldLayout( radio1, { label: 'Selected', align: 'inline' } ),
15167 * new OO.ui.FieldLayout( radio2, { label: 'Unselected', align: 'inline' } ),
15168 * new OO.ui.FieldLayout( radio3, { label: 'Disabled', align: 'inline' } ),
15169 * ] );
15170 * $( 'body' ).append( fieldset.$element );
15171 *
15172 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
15173 *
15174 * @class
15175 * @extends OO.ui.InputWidget
15176 *
15177 * @constructor
15178 * @param {Object} [config] Configuration options
15179 * @cfg {boolean} [selected=false] Select the radio button initially. By default, the radio button is not selected.
15180 */
15181 OO.ui.RadioInputWidget = function OoUiRadioInputWidget( config ) {
15182 // Configuration initialization
15183 config = config || {};
15184
15185 // Parent constructor
15186 OO.ui.RadioInputWidget.parent.call( this, config );
15187
15188 // Initialization
15189 this.$element
15190 .addClass( 'oo-ui-radioInputWidget' )
15191 // Required for pretty styling in MediaWiki theme
15192 .append( $( '<span>' ) );
15193 this.setSelected( config.selected !== undefined ? config.selected : false );
15194 };
15195
15196 /* Setup */
15197
15198 OO.inheritClass( OO.ui.RadioInputWidget, OO.ui.InputWidget );
15199
15200 /* Methods */
15201
15202 /**
15203 * @inheritdoc
15204 * @protected
15205 */
15206 OO.ui.RadioInputWidget.prototype.getInputElement = function () {
15207 return $( '<input type="radio" />' );
15208 };
15209
15210 /**
15211 * @inheritdoc
15212 */
15213 OO.ui.RadioInputWidget.prototype.onEdit = function () {
15214 // RadioInputWidget doesn't track its state.
15215 };
15216
15217 /**
15218 * Set selection state of this radio button.
15219 *
15220 * @param {boolean} state `true` for selected
15221 * @chainable
15222 */
15223 OO.ui.RadioInputWidget.prototype.setSelected = function ( state ) {
15224 // RadioInputWidget doesn't track its state.
15225 this.$input.prop( 'checked', state );
15226 return this;
15227 };
15228
15229 /**
15230 * Check if this radio button is selected.
15231 *
15232 * @return {boolean} Radio is selected
15233 */
15234 OO.ui.RadioInputWidget.prototype.isSelected = function () {
15235 return this.$input.prop( 'checked' );
15236 };
15237
15238 /**
15239 * @inheritdoc
15240 */
15241 OO.ui.RadioInputWidget.prototype.gatherPreInfuseState = function ( node ) {
15242 var
15243 state = OO.ui.RadioInputWidget.parent.prototype.gatherPreInfuseState.call( this, node ),
15244 $input = $( node ).find( '.oo-ui-inputWidget-input' );
15245 state.$input = $input; // shortcut for performance, used in InputWidget
15246 state.checked = $input.prop( 'checked' );
15247 return state;
15248 };
15249
15250 /**
15251 * @inheritdoc
15252 */
15253 OO.ui.RadioInputWidget.prototype.restorePreInfuseState = function ( state ) {
15254 OO.ui.RadioInputWidget.parent.prototype.restorePreInfuseState.call( this, state );
15255 if ( state.checked !== undefined && state.checked !== this.isSelected() ) {
15256 this.setSelected( state.checked );
15257 }
15258 };
15259
15260 /**
15261 * RadioSelectInputWidget is a {@link OO.ui.RadioSelectWidget RadioSelectWidget} intended to be used
15262 * within a HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with the value
15263 * of a hidden HTML `input` tag. Please see the [OOjs UI documentation on MediaWiki][1] for
15264 * more information about input widgets.
15265 *
15266 * This and OO.ui.DropdownInputWidget support the same configuration options.
15267 *
15268 * @example
15269 * // Example: A RadioSelectInputWidget with three options
15270 * var radioSelectInput = new OO.ui.RadioSelectInputWidget( {
15271 * options: [
15272 * { data: 'a', label: 'First' },
15273 * { data: 'b', label: 'Second'},
15274 * { data: 'c', label: 'Third' }
15275 * ]
15276 * } );
15277 * $( 'body' ).append( radioSelectInput.$element );
15278 *
15279 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
15280 *
15281 * @class
15282 * @extends OO.ui.InputWidget
15283 *
15284 * @constructor
15285 * @param {Object} [config] Configuration options
15286 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
15287 */
15288 OO.ui.RadioSelectInputWidget = function OoUiRadioSelectInputWidget( config ) {
15289 // Configuration initialization
15290 config = config || {};
15291
15292 // Properties (must be done before parent constructor which calls #setDisabled)
15293 this.radioSelectWidget = new OO.ui.RadioSelectWidget();
15294
15295 // Parent constructor
15296 OO.ui.RadioSelectInputWidget.parent.call( this, config );
15297
15298 // Events
15299 this.radioSelectWidget.connect( this, { select: 'onMenuSelect' } );
15300
15301 // Initialization
15302 this.setOptions( config.options || [] );
15303 this.$element
15304 .addClass( 'oo-ui-radioSelectInputWidget' )
15305 .append( this.radioSelectWidget.$element );
15306 };
15307
15308 /* Setup */
15309
15310 OO.inheritClass( OO.ui.RadioSelectInputWidget, OO.ui.InputWidget );
15311
15312 /* Static Properties */
15313
15314 OO.ui.RadioSelectInputWidget.static.supportsSimpleLabel = false;
15315
15316 /* Methods */
15317
15318 /**
15319 * @inheritdoc
15320 * @protected
15321 */
15322 OO.ui.RadioSelectInputWidget.prototype.getInputElement = function () {
15323 return $( '<input type="hidden">' );
15324 };
15325
15326 /**
15327 * Handles menu select events.
15328 *
15329 * @private
15330 * @param {OO.ui.RadioOptionWidget} item Selected menu item
15331 */
15332 OO.ui.RadioSelectInputWidget.prototype.onMenuSelect = function ( item ) {
15333 this.setValue( item.getData() );
15334 };
15335
15336 /**
15337 * @inheritdoc
15338 */
15339 OO.ui.RadioSelectInputWidget.prototype.setValue = function ( value ) {
15340 value = this.cleanUpValue( value );
15341 this.radioSelectWidget.selectItemByData( value );
15342 OO.ui.RadioSelectInputWidget.parent.prototype.setValue.call( this, value );
15343 return this;
15344 };
15345
15346 /**
15347 * @inheritdoc
15348 */
15349 OO.ui.RadioSelectInputWidget.prototype.setDisabled = function ( state ) {
15350 this.radioSelectWidget.setDisabled( state );
15351 OO.ui.RadioSelectInputWidget.parent.prototype.setDisabled.call( this, state );
15352 return this;
15353 };
15354
15355 /**
15356 * Set the options available for this input.
15357 *
15358 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
15359 * @chainable
15360 */
15361 OO.ui.RadioSelectInputWidget.prototype.setOptions = function ( options ) {
15362 var
15363 value = this.getValue(),
15364 widget = this;
15365
15366 // Rebuild the radioSelect menu
15367 this.radioSelectWidget
15368 .clearItems()
15369 .addItems( options.map( function ( opt ) {
15370 var optValue = widget.cleanUpValue( opt.data );
15371 return new OO.ui.RadioOptionWidget( {
15372 data: optValue,
15373 label: opt.label !== undefined ? opt.label : optValue
15374 } );
15375 } ) );
15376
15377 // Restore the previous value, or reset to something sensible
15378 if ( this.radioSelectWidget.getItemFromData( value ) ) {
15379 // Previous value is still available, ensure consistency with the radioSelect
15380 this.setValue( value );
15381 } else {
15382 // No longer valid, reset
15383 if ( options.length ) {
15384 this.setValue( options[ 0 ].data );
15385 }
15386 }
15387
15388 return this;
15389 };
15390
15391 /**
15392 * @inheritdoc
15393 */
15394 OO.ui.RadioSelectInputWidget.prototype.gatherPreInfuseState = function ( node ) {
15395 var state = OO.ui.RadioSelectInputWidget.parent.prototype.gatherPreInfuseState.call( this, node );
15396 state.value = $( node ).find( '.oo-ui-radioInputWidget .oo-ui-inputWidget-input:checked' ).val();
15397 return state;
15398 };
15399
15400 /**
15401 * TextInputWidgets, like HTML text inputs, can be configured with options that customize the
15402 * size of the field as well as its presentation. In addition, these widgets can be configured
15403 * with {@link OO.ui.mixin.IconElement icons}, {@link OO.ui.mixin.IndicatorElement indicators}, an optional
15404 * validation-pattern (used to determine if an input value is valid or not) and an input filter,
15405 * which modifies incoming values rather than validating them.
15406 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
15407 *
15408 * This widget can be used inside a HTML form, such as a OO.ui.FormLayout.
15409 *
15410 * @example
15411 * // Example of a text input widget
15412 * var textInput = new OO.ui.TextInputWidget( {
15413 * value: 'Text input'
15414 * } )
15415 * $( 'body' ).append( textInput.$element );
15416 *
15417 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
15418 *
15419 * @class
15420 * @extends OO.ui.InputWidget
15421 * @mixins OO.ui.mixin.IconElement
15422 * @mixins OO.ui.mixin.IndicatorElement
15423 * @mixins OO.ui.mixin.PendingElement
15424 * @mixins OO.ui.mixin.LabelElement
15425 *
15426 * @constructor
15427 * @param {Object} [config] Configuration options
15428 * @cfg {string} [type='text'] The value of the HTML `type` attribute: 'text', 'password', 'search',
15429 * 'email' or 'url'. Ignored if `multiline` is true.
15430 *
15431 * Some values of `type` result in additional behaviors:
15432 *
15433 * - `search`: implies `icon: 'search'` and `indicator: 'clear'`; when clicked, the indicator
15434 * empties the text field
15435 * @cfg {string} [placeholder] Placeholder text
15436 * @cfg {boolean} [autofocus=false] Use an HTML `autofocus` attribute to
15437 * instruct the browser to focus this widget.
15438 * @cfg {boolean} [readOnly=false] Prevent changes to the value of the text input.
15439 * @cfg {number} [maxLength] Maximum number of characters allowed in the input.
15440 * @cfg {boolean} [multiline=false] Allow multiple lines of text
15441 * @cfg {number} [rows] If multiline, number of visible lines in textarea. If used with `autosize`,
15442 * specifies minimum number of rows to display.
15443 * @cfg {boolean} [autosize=false] Automatically resize the text input to fit its content.
15444 * Use the #maxRows config to specify a maximum number of displayed rows.
15445 * @cfg {boolean} [maxRows] Maximum number of rows to display when #autosize is set to true.
15446 * Defaults to the maximum of `10` and `2 * rows`, or `10` if `rows` isn't provided.
15447 * @cfg {string} [labelPosition='after'] The position of the inline label relative to that of
15448 * the value or placeholder text: `'before'` or `'after'`
15449 * @cfg {boolean} [required=false] Mark the field as required. Implies `indicator: 'required'`.
15450 * @cfg {boolean} [autocomplete=true] Should the browser support autocomplete for this field
15451 * @cfg {RegExp|Function|string} [validate] Validation pattern: when string, a symbolic name of a
15452 * pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer'
15453 * (the value must contain only numbers); when RegExp, a regular expression that must match the
15454 * value for it to be considered valid; when Function, a function receiving the value as parameter
15455 * that must return true, or promise resolving to true, for it to be considered valid.
15456 */
15457 OO.ui.TextInputWidget = function OoUiTextInputWidget( config ) {
15458 // Configuration initialization
15459 config = $.extend( {
15460 type: 'text',
15461 labelPosition: 'after'
15462 }, config );
15463 if ( config.type === 'search' ) {
15464 if ( config.icon === undefined ) {
15465 config.icon = 'search';
15466 }
15467 // indicator: 'clear' is set dynamically later, depending on value
15468 }
15469 if ( config.required ) {
15470 if ( config.indicator === undefined ) {
15471 config.indicator = 'required';
15472 }
15473 }
15474
15475 // Parent constructor
15476 OO.ui.TextInputWidget.parent.call( this, config );
15477
15478 // Mixin constructors
15479 OO.ui.mixin.IconElement.call( this, config );
15480 OO.ui.mixin.IndicatorElement.call( this, config );
15481 OO.ui.mixin.PendingElement.call( this, $.extend( {}, config, { $pending: this.$input } ) );
15482 OO.ui.mixin.LabelElement.call( this, config );
15483
15484 // Properties
15485 this.type = this.getSaneType( config );
15486 this.readOnly = false;
15487 this.multiline = !!config.multiline;
15488 this.autosize = !!config.autosize;
15489 this.minRows = config.rows !== undefined ? config.rows : '';
15490 this.maxRows = config.maxRows || Math.max( 2 * ( this.minRows || 0 ), 10 );
15491 this.validate = null;
15492
15493 // Clone for resizing
15494 if ( this.autosize ) {
15495 this.$clone = this.$input
15496 .clone()
15497 .insertAfter( this.$input )
15498 .attr( 'aria-hidden', 'true' )
15499 .addClass( 'oo-ui-element-hidden' );
15500 }
15501
15502 this.setValidation( config.validate );
15503 this.setLabelPosition( config.labelPosition );
15504
15505 // Events
15506 this.$input.on( {
15507 keypress: this.onKeyPress.bind( this ),
15508 blur: this.onBlur.bind( this )
15509 } );
15510 this.$input.one( {
15511 focus: this.onElementAttach.bind( this )
15512 } );
15513 this.$icon.on( 'mousedown', this.onIconMouseDown.bind( this ) );
15514 this.$indicator.on( 'mousedown', this.onIndicatorMouseDown.bind( this ) );
15515 this.on( 'labelChange', this.updatePosition.bind( this ) );
15516 this.connect( this, {
15517 change: 'onChange',
15518 disable: 'onDisable'
15519 } );
15520
15521 // Initialization
15522 this.$element
15523 .addClass( 'oo-ui-textInputWidget oo-ui-textInputWidget-type-' + this.type )
15524 .append( this.$icon, this.$indicator );
15525 this.setReadOnly( !!config.readOnly );
15526 this.updateSearchIndicator();
15527 if ( config.placeholder ) {
15528 this.$input.attr( 'placeholder', config.placeholder );
15529 }
15530 if ( config.maxLength !== undefined ) {
15531 this.$input.attr( 'maxlength', config.maxLength );
15532 }
15533 if ( config.autofocus ) {
15534 this.$input.attr( 'autofocus', 'autofocus' );
15535 }
15536 if ( config.required ) {
15537 this.$input.attr( 'required', 'required' );
15538 this.$input.attr( 'aria-required', 'true' );
15539 }
15540 if ( config.autocomplete === false ) {
15541 this.$input.attr( 'autocomplete', 'off' );
15542 }
15543 if ( this.multiline && config.rows ) {
15544 this.$input.attr( 'rows', config.rows );
15545 }
15546 if ( this.label || config.autosize ) {
15547 this.installParentChangeDetector();
15548 }
15549 };
15550
15551 /* Setup */
15552
15553 OO.inheritClass( OO.ui.TextInputWidget, OO.ui.InputWidget );
15554 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.mixin.IconElement );
15555 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.mixin.IndicatorElement );
15556 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.mixin.PendingElement );
15557 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.mixin.LabelElement );
15558
15559 /* Static Properties */
15560
15561 OO.ui.TextInputWidget.static.validationPatterns = {
15562 'non-empty': /.+/,
15563 integer: /^\d+$/
15564 };
15565
15566 /* Events */
15567
15568 /**
15569 * An `enter` event is emitted when the user presses 'enter' inside the text box.
15570 *
15571 * Not emitted if the input is multiline.
15572 *
15573 * @event enter
15574 */
15575
15576 /* Methods */
15577
15578 /**
15579 * Handle icon mouse down events.
15580 *
15581 * @private
15582 * @param {jQuery.Event} e Mouse down event
15583 * @fires icon
15584 */
15585 OO.ui.TextInputWidget.prototype.onIconMouseDown = function ( e ) {
15586 if ( e.which === 1 ) {
15587 this.$input[ 0 ].focus();
15588 return false;
15589 }
15590 };
15591
15592 /**
15593 * Handle indicator mouse down events.
15594 *
15595 * @private
15596 * @param {jQuery.Event} e Mouse down event
15597 * @fires indicator
15598 */
15599 OO.ui.TextInputWidget.prototype.onIndicatorMouseDown = function ( e ) {
15600 if ( e.which === 1 ) {
15601 if ( this.type === 'search' ) {
15602 // Clear the text field
15603 this.setValue( '' );
15604 }
15605 this.$input[ 0 ].focus();
15606 return false;
15607 }
15608 };
15609
15610 /**
15611 * Handle key press events.
15612 *
15613 * @private
15614 * @param {jQuery.Event} e Key press event
15615 * @fires enter If enter key is pressed and input is not multiline
15616 */
15617 OO.ui.TextInputWidget.prototype.onKeyPress = function ( e ) {
15618 if ( e.which === OO.ui.Keys.ENTER && !this.multiline ) {
15619 this.emit( 'enter', e );
15620 }
15621 };
15622
15623 /**
15624 * Handle blur events.
15625 *
15626 * @private
15627 * @param {jQuery.Event} e Blur event
15628 */
15629 OO.ui.TextInputWidget.prototype.onBlur = function () {
15630 this.setValidityFlag();
15631 };
15632
15633 /**
15634 * Handle element attach events.
15635 *
15636 * @private
15637 * @param {jQuery.Event} e Element attach event
15638 */
15639 OO.ui.TextInputWidget.prototype.onElementAttach = function () {
15640 // Any previously calculated size is now probably invalid if we reattached elsewhere
15641 this.valCache = null;
15642 this.adjustSize();
15643 this.positionLabel();
15644 };
15645
15646 /**
15647 * Handle change events.
15648 *
15649 * @param {string} value
15650 * @private
15651 */
15652 OO.ui.TextInputWidget.prototype.onChange = function () {
15653 this.updateSearchIndicator();
15654 this.setValidityFlag();
15655 this.adjustSize();
15656 };
15657
15658 /**
15659 * Handle disable events.
15660 *
15661 * @param {boolean} disabled Element is disabled
15662 * @private
15663 */
15664 OO.ui.TextInputWidget.prototype.onDisable = function () {
15665 this.updateSearchIndicator();
15666 };
15667
15668 /**
15669 * Check if the input is {@link #readOnly read-only}.
15670 *
15671 * @return {boolean}
15672 */
15673 OO.ui.TextInputWidget.prototype.isReadOnly = function () {
15674 return this.readOnly;
15675 };
15676
15677 /**
15678 * Set the {@link #readOnly read-only} state of the input.
15679 *
15680 * @param {boolean} state Make input read-only
15681 * @chainable
15682 */
15683 OO.ui.TextInputWidget.prototype.setReadOnly = function ( state ) {
15684 this.readOnly = !!state;
15685 this.$input.prop( 'readOnly', this.readOnly );
15686 this.updateSearchIndicator();
15687 return this;
15688 };
15689
15690 /**
15691 * Support function for making #onElementAttach work across browsers.
15692 *
15693 * This whole function could be replaced with one line of code using the DOMNodeInsertedIntoDocument
15694 * event, but it's not supported by Firefox and allegedly deprecated, so we only use it as fallback.
15695 *
15696 * Due to MutationObserver performance woes, #onElementAttach is only somewhat reliably called the
15697 * first time that the element gets attached to the documented.
15698 */
15699 OO.ui.TextInputWidget.prototype.installParentChangeDetector = function () {
15700 var mutationObserver, onRemove, topmostNode, fakeParentNode,
15701 MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver,
15702 widget = this;
15703
15704 if ( MutationObserver ) {
15705 // The new way. If only it wasn't so ugly.
15706
15707 if ( this.$element.closest( 'html' ).length ) {
15708 // Widget is attached already, do nothing. This breaks the functionality of this function when
15709 // the widget is detached and reattached. Alas, doing this correctly with MutationObserver
15710 // would require observation of the whole document, which would hurt performance of other,
15711 // more important code.
15712 return;
15713 }
15714
15715 // Find topmost node in the tree
15716 topmostNode = this.$element[ 0 ];
15717 while ( topmostNode.parentNode ) {
15718 topmostNode = topmostNode.parentNode;
15719 }
15720
15721 // We have no way to detect the $element being attached somewhere without observing the entire
15722 // DOM with subtree modifications, which would hurt performance. So we cheat: we hook to the
15723 // parent node of $element, and instead detect when $element is removed from it (and thus
15724 // probably attached somewhere else). If there is no parent, we create a "fake" one. If it
15725 // doesn't get attached, we end up back here and create the parent.
15726
15727 mutationObserver = new MutationObserver( function ( mutations ) {
15728 var i, j, removedNodes;
15729 for ( i = 0; i < mutations.length; i++ ) {
15730 removedNodes = mutations[ i ].removedNodes;
15731 for ( j = 0; j < removedNodes.length; j++ ) {
15732 if ( removedNodes[ j ] === topmostNode ) {
15733 setTimeout( onRemove, 0 );
15734 return;
15735 }
15736 }
15737 }
15738 } );
15739
15740 onRemove = function () {
15741 // If the node was attached somewhere else, report it
15742 if ( widget.$element.closest( 'html' ).length ) {
15743 widget.onElementAttach();
15744 }
15745 mutationObserver.disconnect();
15746 widget.installParentChangeDetector();
15747 };
15748
15749 // Create a fake parent and observe it
15750 fakeParentNode = $( '<div>' ).append( topmostNode )[ 0 ];
15751 mutationObserver.observe( fakeParentNode, { childList: true } );
15752 } else {
15753 // Using the DOMNodeInsertedIntoDocument event is much nicer and less magical, and works for
15754 // detachment and reattachment, but it's not supported by Firefox and allegedly deprecated.
15755 this.$element.on( 'DOMNodeInsertedIntoDocument', this.onElementAttach.bind( this ) );
15756 }
15757 };
15758
15759 /**
15760 * Automatically adjust the size of the text input.
15761 *
15762 * This only affects #multiline inputs that are {@link #autosize autosized}.
15763 *
15764 * @chainable
15765 */
15766 OO.ui.TextInputWidget.prototype.adjustSize = function () {
15767 var scrollHeight, innerHeight, outerHeight, maxInnerHeight, measurementError, idealHeight;
15768
15769 if ( this.multiline && this.autosize && this.$input.val() !== this.valCache ) {
15770 this.$clone
15771 .val( this.$input.val() )
15772 .attr( 'rows', this.minRows )
15773 // Set inline height property to 0 to measure scroll height
15774 .css( 'height', 0 );
15775
15776 this.$clone.removeClass( 'oo-ui-element-hidden' );
15777
15778 this.valCache = this.$input.val();
15779
15780 scrollHeight = this.$clone[ 0 ].scrollHeight;
15781
15782 // Remove inline height property to measure natural heights
15783 this.$clone.css( 'height', '' );
15784 innerHeight = this.$clone.innerHeight();
15785 outerHeight = this.$clone.outerHeight();
15786
15787 // Measure max rows height
15788 this.$clone
15789 .attr( 'rows', this.maxRows )
15790 .css( 'height', 'auto' )
15791 .val( '' );
15792 maxInnerHeight = this.$clone.innerHeight();
15793
15794 // Difference between reported innerHeight and scrollHeight with no scrollbars present
15795 // Equals 1 on Blink-based browsers and 0 everywhere else
15796 measurementError = maxInnerHeight - this.$clone[ 0 ].scrollHeight;
15797 idealHeight = Math.min( maxInnerHeight, scrollHeight + measurementError );
15798
15799 this.$clone.addClass( 'oo-ui-element-hidden' );
15800
15801 // Only apply inline height when expansion beyond natural height is needed
15802 if ( idealHeight > innerHeight ) {
15803 // Use the difference between the inner and outer height as a buffer
15804 this.$input.css( 'height', idealHeight + ( outerHeight - innerHeight ) );
15805 } else {
15806 this.$input.css( 'height', '' );
15807 }
15808 }
15809 return this;
15810 };
15811
15812 /**
15813 * @inheritdoc
15814 * @protected
15815 */
15816 OO.ui.TextInputWidget.prototype.getInputElement = function ( config ) {
15817 return config.multiline ?
15818 $( '<textarea>' ) :
15819 $( '<input type="' + this.getSaneType( config ) + '" />' );
15820 };
15821
15822 /**
15823 * Get sanitized value for 'type' for given config.
15824 *
15825 * @param {Object} config Configuration options
15826 * @return {string|null}
15827 * @private
15828 */
15829 OO.ui.TextInputWidget.prototype.getSaneType = function ( config ) {
15830 var type = [ 'text', 'password', 'search', 'email', 'url' ].indexOf( config.type ) !== -1 ?
15831 config.type :
15832 'text';
15833 return config.multiline ? 'multiline' : type;
15834 };
15835
15836 /**
15837 * Check if the input supports multiple lines.
15838 *
15839 * @return {boolean}
15840 */
15841 OO.ui.TextInputWidget.prototype.isMultiline = function () {
15842 return !!this.multiline;
15843 };
15844
15845 /**
15846 * Check if the input automatically adjusts its size.
15847 *
15848 * @return {boolean}
15849 */
15850 OO.ui.TextInputWidget.prototype.isAutosizing = function () {
15851 return !!this.autosize;
15852 };
15853
15854 /**
15855 * Select the entire text of the input.
15856 *
15857 * @chainable
15858 */
15859 OO.ui.TextInputWidget.prototype.select = function () {
15860 this.$input.select();
15861 return this;
15862 };
15863
15864 /**
15865 * Focus the input and move the cursor to the end.
15866 */
15867 OO.ui.TextInputWidget.prototype.moveCursorToEnd = function () {
15868 var textRange,
15869 element = this.$input[ 0 ];
15870 this.focus();
15871 if ( element.selectionStart !== undefined ) {
15872 element.selectionStart = element.selectionEnd = element.value.length;
15873 } else if ( element.createTextRange ) {
15874 // IE 8 and below
15875 textRange = element.createTextRange();
15876 textRange.collapse( false );
15877 textRange.select();
15878 }
15879 };
15880
15881 /**
15882 * Set the validation pattern.
15883 *
15884 * The validation pattern is either a regular expression, a function, or the symbolic name of a
15885 * pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer' (the
15886 * value must contain only numbers).
15887 *
15888 * @param {RegExp|Function|string|null} validate Regular expression, function, or the symbolic name
15889 * of a pattern (either ‘integer’ or ‘non-empty’) defined by the class.
15890 */
15891 OO.ui.TextInputWidget.prototype.setValidation = function ( validate ) {
15892 if ( validate instanceof RegExp || validate instanceof Function ) {
15893 this.validate = validate;
15894 } else {
15895 this.validate = this.constructor.static.validationPatterns[ validate ] || /.*/;
15896 }
15897 };
15898
15899 /**
15900 * Sets the 'invalid' flag appropriately.
15901 *
15902 * @param {boolean} [isValid] Optionally override validation result
15903 */
15904 OO.ui.TextInputWidget.prototype.setValidityFlag = function ( isValid ) {
15905 var widget = this,
15906 setFlag = function ( valid ) {
15907 if ( !valid ) {
15908 widget.$input.attr( 'aria-invalid', 'true' );
15909 } else {
15910 widget.$input.removeAttr( 'aria-invalid' );
15911 }
15912 widget.setFlags( { invalid: !valid } );
15913 };
15914
15915 if ( isValid !== undefined ) {
15916 setFlag( isValid );
15917 } else {
15918 this.getValidity().then( function () {
15919 setFlag( true );
15920 }, function () {
15921 setFlag( false );
15922 } );
15923 }
15924 };
15925
15926 /**
15927 * Check if a value is valid.
15928 *
15929 * This method returns a promise that resolves with a boolean `true` if the current value is
15930 * considered valid according to the supplied {@link #validate validation pattern}.
15931 *
15932 * @deprecated
15933 * @return {jQuery.Promise} A promise that resolves to a boolean `true` if the value is valid.
15934 */
15935 OO.ui.TextInputWidget.prototype.isValid = function () {
15936 var result;
15937
15938 if ( this.validate instanceof Function ) {
15939 result = this.validate( this.getValue() );
15940 if ( $.isFunction( result.promise ) ) {
15941 return result.promise();
15942 } else {
15943 return $.Deferred().resolve( !!result ).promise();
15944 }
15945 } else {
15946 return $.Deferred().resolve( !!this.getValue().match( this.validate ) ).promise();
15947 }
15948 };
15949
15950 /**
15951 * Get the validity of current value.
15952 *
15953 * This method returns a promise that resolves if the value is valid and rejects if
15954 * it isn't. Uses the {@link #validate validation pattern} to check for validity.
15955 *
15956 * @return {jQuery.Promise} A promise that resolves if the value is valid, rejects if not.
15957 */
15958 OO.ui.TextInputWidget.prototype.getValidity = function () {
15959 var result, promise;
15960
15961 function rejectOrResolve( valid ) {
15962 if ( valid ) {
15963 return $.Deferred().resolve().promise();
15964 } else {
15965 return $.Deferred().reject().promise();
15966 }
15967 }
15968
15969 if ( this.validate instanceof Function ) {
15970 result = this.validate( this.getValue() );
15971
15972 if ( $.isFunction( result.promise ) ) {
15973 promise = $.Deferred();
15974
15975 result.then( function ( valid ) {
15976 if ( valid ) {
15977 promise.resolve();
15978 } else {
15979 promise.reject();
15980 }
15981 }, function () {
15982 promise.reject();
15983 } );
15984
15985 return promise.promise();
15986 } else {
15987 return rejectOrResolve( result );
15988 }
15989 } else {
15990 return rejectOrResolve( this.getValue().match( this.validate ) );
15991 }
15992 };
15993
15994 /**
15995 * Set the position of the inline label relative to that of the value: `‘before’` or `‘after’`.
15996 *
15997 * @param {string} labelPosition Label position, 'before' or 'after'
15998 * @chainable
15999 */
16000 OO.ui.TextInputWidget.prototype.setLabelPosition = function ( labelPosition ) {
16001 this.labelPosition = labelPosition;
16002 this.updatePosition();
16003 return this;
16004 };
16005
16006 /**
16007 * Deprecated alias of #setLabelPosition
16008 *
16009 * @deprecated Use setLabelPosition instead.
16010 */
16011 OO.ui.TextInputWidget.prototype.setPosition =
16012 OO.ui.TextInputWidget.prototype.setLabelPosition;
16013
16014 /**
16015 * Update the position of the inline label.
16016 *
16017 * This method is called by #setLabelPosition, and can also be called on its own if
16018 * something causes the label to be mispositioned.
16019 *
16020 * @chainable
16021 */
16022 OO.ui.TextInputWidget.prototype.updatePosition = function () {
16023 var after = this.labelPosition === 'after';
16024
16025 this.$element
16026 .toggleClass( 'oo-ui-textInputWidget-labelPosition-after', !!this.label && after )
16027 .toggleClass( 'oo-ui-textInputWidget-labelPosition-before', !!this.label && !after );
16028
16029 this.positionLabel();
16030
16031 return this;
16032 };
16033
16034 /**
16035 * Update the 'clear' indicator displayed on type: 'search' text fields, hiding it when the field is
16036 * already empty or when it's not editable.
16037 */
16038 OO.ui.TextInputWidget.prototype.updateSearchIndicator = function () {
16039 if ( this.type === 'search' ) {
16040 if ( this.getValue() === '' || this.isDisabled() || this.isReadOnly() ) {
16041 this.setIndicator( null );
16042 } else {
16043 this.setIndicator( 'clear' );
16044 }
16045 }
16046 };
16047
16048 /**
16049 * Position the label by setting the correct padding on the input.
16050 *
16051 * @private
16052 * @chainable
16053 */
16054 OO.ui.TextInputWidget.prototype.positionLabel = function () {
16055 var after, rtl, property;
16056 // Clear old values
16057 this.$input
16058 // Clear old values if present
16059 .css( {
16060 'padding-right': '',
16061 'padding-left': ''
16062 } );
16063
16064 if ( this.label ) {
16065 this.$element.append( this.$label );
16066 } else {
16067 this.$label.detach();
16068 return;
16069 }
16070
16071 after = this.labelPosition === 'after';
16072 rtl = this.$element.css( 'direction' ) === 'rtl';
16073 property = after === rtl ? 'padding-left' : 'padding-right';
16074
16075 this.$input.css( property, this.$label.outerWidth( true ) );
16076
16077 return this;
16078 };
16079
16080 /**
16081 * @inheritdoc
16082 */
16083 OO.ui.TextInputWidget.prototype.gatherPreInfuseState = function ( node ) {
16084 var
16085 state = OO.ui.TextInputWidget.parent.prototype.gatherPreInfuseState.call( this, node ),
16086 $input = $( node ).find( '.oo-ui-inputWidget-input' );
16087 state.$input = $input; // shortcut for performance, used in InputWidget
16088 if ( this.multiline ) {
16089 state.scrollTop = $input.scrollTop();
16090 }
16091 return state;
16092 };
16093
16094 /**
16095 * @inheritdoc
16096 */
16097 OO.ui.TextInputWidget.prototype.restorePreInfuseState = function ( state ) {
16098 OO.ui.TextInputWidget.parent.prototype.restorePreInfuseState.call( this, state );
16099 if ( state.scrollTop !== undefined ) {
16100 this.$input.scrollTop( state.scrollTop );
16101 }
16102 };
16103
16104 /**
16105 * ComboBoxWidgets combine a {@link OO.ui.TextInputWidget text input} (where a value
16106 * can be entered manually) and a {@link OO.ui.MenuSelectWidget menu of options} (from which
16107 * a value can be chosen instead). Users can choose options from the combo box in one of two ways:
16108 *
16109 * - by typing a value in the text input field. If the value exactly matches the value of a menu
16110 * option, that option will appear to be selected.
16111 * - by choosing a value from the menu. The value of the chosen option will then appear in the text
16112 * input field.
16113 *
16114 * For more information about menus and options, please see the [OOjs UI documentation on MediaWiki][1].
16115 *
16116 * @example
16117 * // Example: A ComboBoxWidget.
16118 * var comboBox = new OO.ui.ComboBoxWidget( {
16119 * label: 'ComboBoxWidget',
16120 * input: { value: 'Option One' },
16121 * menu: {
16122 * items: [
16123 * new OO.ui.MenuOptionWidget( {
16124 * data: 'Option 1',
16125 * label: 'Option One'
16126 * } ),
16127 * new OO.ui.MenuOptionWidget( {
16128 * data: 'Option 2',
16129 * label: 'Option Two'
16130 * } ),
16131 * new OO.ui.MenuOptionWidget( {
16132 * data: 'Option 3',
16133 * label: 'Option Three'
16134 * } ),
16135 * new OO.ui.MenuOptionWidget( {
16136 * data: 'Option 4',
16137 * label: 'Option Four'
16138 * } ),
16139 * new OO.ui.MenuOptionWidget( {
16140 * data: 'Option 5',
16141 * label: 'Option Five'
16142 * } )
16143 * ]
16144 * }
16145 * } );
16146 * $( 'body' ).append( comboBox.$element );
16147 *
16148 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
16149 *
16150 * @class
16151 * @extends OO.ui.Widget
16152 * @mixins OO.ui.mixin.TabIndexedElement
16153 *
16154 * @constructor
16155 * @param {Object} [config] Configuration options
16156 * @cfg {Object} [menu] Configuration options to pass to the {@link OO.ui.FloatingMenuSelectWidget menu select widget}.
16157 * @cfg {Object} [input] Configuration options to pass to the {@link OO.ui.TextInputWidget text input widget}.
16158 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
16159 * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
16160 * containing `<div>` and has a larger area. By default, the menu uses relative positioning.
16161 */
16162 OO.ui.ComboBoxWidget = function OoUiComboBoxWidget( config ) {
16163 // Configuration initialization
16164 config = config || {};
16165
16166 // Parent constructor
16167 OO.ui.ComboBoxWidget.parent.call( this, config );
16168
16169 // Properties (must be set before TabIndexedElement constructor call)
16170 this.$indicator = this.$( '<span>' );
16171
16172 // Mixin constructors
16173 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$indicator } ) );
16174
16175 // Properties
16176 this.$overlay = config.$overlay || this.$element;
16177 this.input = new OO.ui.TextInputWidget( $.extend(
16178 {
16179 indicator: 'down',
16180 $indicator: this.$indicator,
16181 disabled: this.isDisabled()
16182 },
16183 config.input
16184 ) );
16185 this.input.$input.eq( 0 ).attr( {
16186 role: 'combobox',
16187 'aria-autocomplete': 'list'
16188 } );
16189 this.menu = new OO.ui.FloatingMenuSelectWidget( $.extend(
16190 {
16191 widget: this,
16192 input: this.input,
16193 $container: this.input.$element,
16194 disabled: this.isDisabled()
16195 },
16196 config.menu
16197 ) );
16198
16199 // Events
16200 this.$indicator.on( {
16201 click: this.onClick.bind( this ),
16202 keypress: this.onKeyPress.bind( this )
16203 } );
16204 this.input.connect( this, {
16205 change: 'onInputChange',
16206 enter: 'onInputEnter'
16207 } );
16208 this.menu.connect( this, {
16209 choose: 'onMenuChoose',
16210 add: 'onMenuItemsChange',
16211 remove: 'onMenuItemsChange'
16212 } );
16213
16214 // Initialization
16215 this.$element.addClass( 'oo-ui-comboBoxWidget' ).append( this.input.$element );
16216 this.$overlay.append( this.menu.$element );
16217 this.onMenuItemsChange();
16218 };
16219
16220 /* Setup */
16221
16222 OO.inheritClass( OO.ui.ComboBoxWidget, OO.ui.Widget );
16223 OO.mixinClass( OO.ui.ComboBoxWidget, OO.ui.mixin.TabIndexedElement );
16224
16225 /* Methods */
16226
16227 /**
16228 * Get the combobox's menu.
16229 * @return {OO.ui.FloatingMenuSelectWidget} Menu widget
16230 */
16231 OO.ui.ComboBoxWidget.prototype.getMenu = function () {
16232 return this.menu;
16233 };
16234
16235 /**
16236 * Get the combobox's text input widget.
16237 * @return {OO.ui.TextInputWidget} Text input widget
16238 */
16239 OO.ui.ComboBoxWidget.prototype.getInput = function () {
16240 return this.input;
16241 };
16242
16243 /**
16244 * Handle input change events.
16245 *
16246 * @private
16247 * @param {string} value New value
16248 */
16249 OO.ui.ComboBoxWidget.prototype.onInputChange = function ( value ) {
16250 var match = this.menu.getItemFromData( value );
16251
16252 this.menu.selectItem( match );
16253 if ( this.menu.getHighlightedItem() ) {
16254 this.menu.highlightItem( match );
16255 }
16256
16257 if ( !this.isDisabled() ) {
16258 this.menu.toggle( true );
16259 }
16260 };
16261
16262 /**
16263 * Handle mouse click events.
16264 *
16265 * @private
16266 * @param {jQuery.Event} e Mouse click event
16267 */
16268 OO.ui.ComboBoxWidget.prototype.onClick = function ( e ) {
16269 if ( !this.isDisabled() && e.which === 1 ) {
16270 this.menu.toggle();
16271 this.input.$input[ 0 ].focus();
16272 }
16273 return false;
16274 };
16275
16276 /**
16277 * Handle key press events.
16278 *
16279 * @private
16280 * @param {jQuery.Event} e Key press event
16281 */
16282 OO.ui.ComboBoxWidget.prototype.onKeyPress = function ( e ) {
16283 if ( !this.isDisabled() && ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER ) ) {
16284 this.menu.toggle();
16285 this.input.$input[ 0 ].focus();
16286 return false;
16287 }
16288 };
16289
16290 /**
16291 * Handle input enter events.
16292 *
16293 * @private
16294 */
16295 OO.ui.ComboBoxWidget.prototype.onInputEnter = function () {
16296 if ( !this.isDisabled() ) {
16297 this.menu.toggle( false );
16298 }
16299 };
16300
16301 /**
16302 * Handle menu choose events.
16303 *
16304 * @private
16305 * @param {OO.ui.OptionWidget} item Chosen item
16306 */
16307 OO.ui.ComboBoxWidget.prototype.onMenuChoose = function ( item ) {
16308 this.input.setValue( item.getData() );
16309 };
16310
16311 /**
16312 * Handle menu item change events.
16313 *
16314 * @private
16315 */
16316 OO.ui.ComboBoxWidget.prototype.onMenuItemsChange = function () {
16317 var match = this.menu.getItemFromData( this.input.getValue() );
16318 this.menu.selectItem( match );
16319 if ( this.menu.getHighlightedItem() ) {
16320 this.menu.highlightItem( match );
16321 }
16322 this.$element.toggleClass( 'oo-ui-comboBoxWidget-empty', this.menu.isEmpty() );
16323 };
16324
16325 /**
16326 * @inheritdoc
16327 */
16328 OO.ui.ComboBoxWidget.prototype.setDisabled = function ( disabled ) {
16329 // Parent method
16330 OO.ui.ComboBoxWidget.parent.prototype.setDisabled.call( this, disabled );
16331
16332 if ( this.input ) {
16333 this.input.setDisabled( this.isDisabled() );
16334 }
16335 if ( this.menu ) {
16336 this.menu.setDisabled( this.isDisabled() );
16337 }
16338
16339 return this;
16340 };
16341
16342 /**
16343 * LabelWidgets help identify the function of interface elements. Each LabelWidget can
16344 * be configured with a `label` option that is set to a string, a label node, or a function:
16345 *
16346 * - String: a plaintext string
16347 * - jQuery selection: a jQuery selection, used for anything other than a plaintext label, e.g., a
16348 * label that includes a link or special styling, such as a gray color or additional graphical elements.
16349 * - Function: a function that will produce a string in the future. Functions are used
16350 * in cases where the value of the label is not currently defined.
16351 *
16352 * In addition, the LabelWidget can be associated with an {@link OO.ui.InputWidget input widget}, which
16353 * will come into focus when the label is clicked.
16354 *
16355 * @example
16356 * // Examples of LabelWidgets
16357 * var label1 = new OO.ui.LabelWidget( {
16358 * label: 'plaintext label'
16359 * } );
16360 * var label2 = new OO.ui.LabelWidget( {
16361 * label: $( '<a href="default.html">jQuery label</a>' )
16362 * } );
16363 * // Create a fieldset layout with fields for each example
16364 * var fieldset = new OO.ui.FieldsetLayout();
16365 * fieldset.addItems( [
16366 * new OO.ui.FieldLayout( label1 ),
16367 * new OO.ui.FieldLayout( label2 )
16368 * ] );
16369 * $( 'body' ).append( fieldset.$element );
16370 *
16371 * @class
16372 * @extends OO.ui.Widget
16373 * @mixins OO.ui.mixin.LabelElement
16374 *
16375 * @constructor
16376 * @param {Object} [config] Configuration options
16377 * @cfg {OO.ui.InputWidget} [input] {@link OO.ui.InputWidget Input widget} that uses the label.
16378 * Clicking the label will focus the specified input field.
16379 */
16380 OO.ui.LabelWidget = function OoUiLabelWidget( config ) {
16381 // Configuration initialization
16382 config = config || {};
16383
16384 // Parent constructor
16385 OO.ui.LabelWidget.parent.call( this, config );
16386
16387 // Mixin constructors
16388 OO.ui.mixin.LabelElement.call( this, $.extend( {}, config, { $label: this.$element } ) );
16389 OO.ui.mixin.TitledElement.call( this, config );
16390
16391 // Properties
16392 this.input = config.input;
16393
16394 // Events
16395 if ( this.input instanceof OO.ui.InputWidget ) {
16396 this.$element.on( 'click', this.onClick.bind( this ) );
16397 }
16398
16399 // Initialization
16400 this.$element.addClass( 'oo-ui-labelWidget' );
16401 };
16402
16403 /* Setup */
16404
16405 OO.inheritClass( OO.ui.LabelWidget, OO.ui.Widget );
16406 OO.mixinClass( OO.ui.LabelWidget, OO.ui.mixin.LabelElement );
16407 OO.mixinClass( OO.ui.LabelWidget, OO.ui.mixin.TitledElement );
16408
16409 /* Static Properties */
16410
16411 OO.ui.LabelWidget.static.tagName = 'span';
16412
16413 /* Methods */
16414
16415 /**
16416 * Handles label mouse click events.
16417 *
16418 * @private
16419 * @param {jQuery.Event} e Mouse click event
16420 */
16421 OO.ui.LabelWidget.prototype.onClick = function () {
16422 this.input.simulateLabelClick();
16423 return false;
16424 };
16425
16426 /**
16427 * OptionWidgets are special elements that can be selected and configured with data. The
16428 * data is often unique for each option, but it does not have to be. OptionWidgets are used
16429 * with OO.ui.SelectWidget to create a selection of mutually exclusive options. For more information
16430 * and examples, please see the [OOjs UI documentation on MediaWiki][1].
16431 *
16432 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
16433 *
16434 * @class
16435 * @extends OO.ui.Widget
16436 * @mixins OO.ui.mixin.LabelElement
16437 * @mixins OO.ui.mixin.FlaggedElement
16438 *
16439 * @constructor
16440 * @param {Object} [config] Configuration options
16441 */
16442 OO.ui.OptionWidget = function OoUiOptionWidget( config ) {
16443 // Configuration initialization
16444 config = config || {};
16445
16446 // Parent constructor
16447 OO.ui.OptionWidget.parent.call( this, config );
16448
16449 // Mixin constructors
16450 OO.ui.mixin.ItemWidget.call( this );
16451 OO.ui.mixin.LabelElement.call( this, config );
16452 OO.ui.mixin.FlaggedElement.call( this, config );
16453
16454 // Properties
16455 this.selected = false;
16456 this.highlighted = false;
16457 this.pressed = false;
16458
16459 // Initialization
16460 this.$element
16461 .data( 'oo-ui-optionWidget', this )
16462 .attr( 'role', 'option' )
16463 .attr( 'aria-selected', 'false' )
16464 .addClass( 'oo-ui-optionWidget' )
16465 .append( this.$label );
16466 };
16467
16468 /* Setup */
16469
16470 OO.inheritClass( OO.ui.OptionWidget, OO.ui.Widget );
16471 OO.mixinClass( OO.ui.OptionWidget, OO.ui.mixin.ItemWidget );
16472 OO.mixinClass( OO.ui.OptionWidget, OO.ui.mixin.LabelElement );
16473 OO.mixinClass( OO.ui.OptionWidget, OO.ui.mixin.FlaggedElement );
16474
16475 /* Static Properties */
16476
16477 OO.ui.OptionWidget.static.selectable = true;
16478
16479 OO.ui.OptionWidget.static.highlightable = true;
16480
16481 OO.ui.OptionWidget.static.pressable = true;
16482
16483 OO.ui.OptionWidget.static.scrollIntoViewOnSelect = false;
16484
16485 /* Methods */
16486
16487 /**
16488 * Check if the option can be selected.
16489 *
16490 * @return {boolean} Item is selectable
16491 */
16492 OO.ui.OptionWidget.prototype.isSelectable = function () {
16493 return this.constructor.static.selectable && !this.isDisabled() && this.isVisible();
16494 };
16495
16496 /**
16497 * Check if the option can be highlighted. A highlight indicates that the option
16498 * may be selected when a user presses enter or clicks. Disabled items cannot
16499 * be highlighted.
16500 *
16501 * @return {boolean} Item is highlightable
16502 */
16503 OO.ui.OptionWidget.prototype.isHighlightable = function () {
16504 return this.constructor.static.highlightable && !this.isDisabled() && this.isVisible();
16505 };
16506
16507 /**
16508 * Check if the option can be pressed. The pressed state occurs when a user mouses
16509 * down on an item, but has not yet let go of the mouse.
16510 *
16511 * @return {boolean} Item is pressable
16512 */
16513 OO.ui.OptionWidget.prototype.isPressable = function () {
16514 return this.constructor.static.pressable && !this.isDisabled() && this.isVisible();
16515 };
16516
16517 /**
16518 * Check if the option is selected.
16519 *
16520 * @return {boolean} Item is selected
16521 */
16522 OO.ui.OptionWidget.prototype.isSelected = function () {
16523 return this.selected;
16524 };
16525
16526 /**
16527 * Check if the option is highlighted. A highlight indicates that the
16528 * item may be selected when a user presses enter or clicks.
16529 *
16530 * @return {boolean} Item is highlighted
16531 */
16532 OO.ui.OptionWidget.prototype.isHighlighted = function () {
16533 return this.highlighted;
16534 };
16535
16536 /**
16537 * Check if the option is pressed. The pressed state occurs when a user mouses
16538 * down on an item, but has not yet let go of the mouse. The item may appear
16539 * selected, but it will not be selected until the user releases the mouse.
16540 *
16541 * @return {boolean} Item is pressed
16542 */
16543 OO.ui.OptionWidget.prototype.isPressed = function () {
16544 return this.pressed;
16545 };
16546
16547 /**
16548 * Set the option’s selected state. In general, all modifications to the selection
16549 * should be handled by the SelectWidget’s {@link OO.ui.SelectWidget#selectItem selectItem( [item] )}
16550 * method instead of this method.
16551 *
16552 * @param {boolean} [state=false] Select option
16553 * @chainable
16554 */
16555 OO.ui.OptionWidget.prototype.setSelected = function ( state ) {
16556 if ( this.constructor.static.selectable ) {
16557 this.selected = !!state;
16558 this.$element
16559 .toggleClass( 'oo-ui-optionWidget-selected', state )
16560 .attr( 'aria-selected', state.toString() );
16561 if ( state && this.constructor.static.scrollIntoViewOnSelect ) {
16562 this.scrollElementIntoView();
16563 }
16564 this.updateThemeClasses();
16565 }
16566 return this;
16567 };
16568
16569 /**
16570 * Set the option’s highlighted state. In general, all programmatic
16571 * modifications to the highlight should be handled by the
16572 * SelectWidget’s {@link OO.ui.SelectWidget#highlightItem highlightItem( [item] )}
16573 * method instead of this method.
16574 *
16575 * @param {boolean} [state=false] Highlight option
16576 * @chainable
16577 */
16578 OO.ui.OptionWidget.prototype.setHighlighted = function ( state ) {
16579 if ( this.constructor.static.highlightable ) {
16580 this.highlighted = !!state;
16581 this.$element.toggleClass( 'oo-ui-optionWidget-highlighted', state );
16582 this.updateThemeClasses();
16583 }
16584 return this;
16585 };
16586
16587 /**
16588 * Set the option’s pressed state. In general, all
16589 * programmatic modifications to the pressed state should be handled by the
16590 * SelectWidget’s {@link OO.ui.SelectWidget#pressItem pressItem( [item] )}
16591 * method instead of this method.
16592 *
16593 * @param {boolean} [state=false] Press option
16594 * @chainable
16595 */
16596 OO.ui.OptionWidget.prototype.setPressed = function ( state ) {
16597 if ( this.constructor.static.pressable ) {
16598 this.pressed = !!state;
16599 this.$element.toggleClass( 'oo-ui-optionWidget-pressed', state );
16600 this.updateThemeClasses();
16601 }
16602 return this;
16603 };
16604
16605 /**
16606 * DecoratedOptionWidgets are {@link OO.ui.OptionWidget options} that can be configured
16607 * with an {@link OO.ui.mixin.IconElement icon} and/or {@link OO.ui.mixin.IndicatorElement indicator}.
16608 * This class is used with OO.ui.SelectWidget to create a selection of mutually exclusive
16609 * options. For more information about options and selects, please see the
16610 * [OOjs UI documentation on MediaWiki][1].
16611 *
16612 * @example
16613 * // Decorated options in a select widget
16614 * var select = new OO.ui.SelectWidget( {
16615 * items: [
16616 * new OO.ui.DecoratedOptionWidget( {
16617 * data: 'a',
16618 * label: 'Option with icon',
16619 * icon: 'help'
16620 * } ),
16621 * new OO.ui.DecoratedOptionWidget( {
16622 * data: 'b',
16623 * label: 'Option with indicator',
16624 * indicator: 'next'
16625 * } )
16626 * ]
16627 * } );
16628 * $( 'body' ).append( select.$element );
16629 *
16630 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
16631 *
16632 * @class
16633 * @extends OO.ui.OptionWidget
16634 * @mixins OO.ui.mixin.IconElement
16635 * @mixins OO.ui.mixin.IndicatorElement
16636 *
16637 * @constructor
16638 * @param {Object} [config] Configuration options
16639 */
16640 OO.ui.DecoratedOptionWidget = function OoUiDecoratedOptionWidget( config ) {
16641 // Parent constructor
16642 OO.ui.DecoratedOptionWidget.parent.call( this, config );
16643
16644 // Mixin constructors
16645 OO.ui.mixin.IconElement.call( this, config );
16646 OO.ui.mixin.IndicatorElement.call( this, config );
16647
16648 // Initialization
16649 this.$element
16650 .addClass( 'oo-ui-decoratedOptionWidget' )
16651 .prepend( this.$icon )
16652 .append( this.$indicator );
16653 };
16654
16655 /* Setup */
16656
16657 OO.inheritClass( OO.ui.DecoratedOptionWidget, OO.ui.OptionWidget );
16658 OO.mixinClass( OO.ui.DecoratedOptionWidget, OO.ui.mixin.IconElement );
16659 OO.mixinClass( OO.ui.DecoratedOptionWidget, OO.ui.mixin.IndicatorElement );
16660
16661 /**
16662 * ButtonOptionWidget is a special type of {@link OO.ui.mixin.ButtonElement button element} that
16663 * can be selected and configured with data. The class is
16664 * used with OO.ui.ButtonSelectWidget to create a selection of button options. Please see the
16665 * [OOjs UI documentation on MediaWiki] [1] for more information.
16666 *
16667 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Button_selects_and_options
16668 *
16669 * @class
16670 * @extends OO.ui.DecoratedOptionWidget
16671 * @mixins OO.ui.mixin.ButtonElement
16672 * @mixins OO.ui.mixin.TabIndexedElement
16673 * @mixins OO.ui.mixin.TitledElement
16674 *
16675 * @constructor
16676 * @param {Object} [config] Configuration options
16677 */
16678 OO.ui.ButtonOptionWidget = function OoUiButtonOptionWidget( config ) {
16679 // Configuration initialization
16680 config = config || {};
16681
16682 // Parent constructor
16683 OO.ui.ButtonOptionWidget.parent.call( this, config );
16684
16685 // Mixin constructors
16686 OO.ui.mixin.ButtonElement.call( this, config );
16687 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$button } ) );
16688 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, {
16689 $tabIndexed: this.$button,
16690 tabIndex: -1
16691 } ) );
16692
16693 // Initialization
16694 this.$element.addClass( 'oo-ui-buttonOptionWidget' );
16695 this.$button.append( this.$element.contents() );
16696 this.$element.append( this.$button );
16697 };
16698
16699 /* Setup */
16700
16701 OO.inheritClass( OO.ui.ButtonOptionWidget, OO.ui.DecoratedOptionWidget );
16702 OO.mixinClass( OO.ui.ButtonOptionWidget, OO.ui.mixin.ButtonElement );
16703 OO.mixinClass( OO.ui.ButtonOptionWidget, OO.ui.mixin.TitledElement );
16704 OO.mixinClass( OO.ui.ButtonOptionWidget, OO.ui.mixin.TabIndexedElement );
16705
16706 /* Static Properties */
16707
16708 // Allow button mouse down events to pass through so they can be handled by the parent select widget
16709 OO.ui.ButtonOptionWidget.static.cancelButtonMouseDownEvents = false;
16710
16711 OO.ui.ButtonOptionWidget.static.highlightable = false;
16712
16713 /* Methods */
16714
16715 /**
16716 * @inheritdoc
16717 */
16718 OO.ui.ButtonOptionWidget.prototype.setSelected = function ( state ) {
16719 OO.ui.ButtonOptionWidget.parent.prototype.setSelected.call( this, state );
16720
16721 if ( this.constructor.static.selectable ) {
16722 this.setActive( state );
16723 }
16724
16725 return this;
16726 };
16727
16728 /**
16729 * RadioOptionWidget is an option widget that looks like a radio button.
16730 * The class is used with OO.ui.RadioSelectWidget to create a selection of radio options.
16731 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information.
16732 *
16733 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Button_selects_and_option
16734 *
16735 * @class
16736 * @extends OO.ui.OptionWidget
16737 *
16738 * @constructor
16739 * @param {Object} [config] Configuration options
16740 */
16741 OO.ui.RadioOptionWidget = function OoUiRadioOptionWidget( config ) {
16742 // Configuration initialization
16743 config = config || {};
16744
16745 // Properties (must be done before parent constructor which calls #setDisabled)
16746 this.radio = new OO.ui.RadioInputWidget( { value: config.data, tabIndex: -1 } );
16747
16748 // Parent constructor
16749 OO.ui.RadioOptionWidget.parent.call( this, config );
16750
16751 // Events
16752 this.radio.$input.on( 'focus', this.onInputFocus.bind( this ) );
16753
16754 // Initialization
16755 // Remove implicit role, we're handling it ourselves
16756 this.radio.$input.attr( 'role', 'presentation' );
16757 this.$element
16758 .addClass( 'oo-ui-radioOptionWidget' )
16759 .attr( 'role', 'radio' )
16760 .attr( 'aria-checked', 'false' )
16761 .removeAttr( 'aria-selected' )
16762 .prepend( this.radio.$element );
16763 };
16764
16765 /* Setup */
16766
16767 OO.inheritClass( OO.ui.RadioOptionWidget, OO.ui.OptionWidget );
16768
16769 /* Static Properties */
16770
16771 OO.ui.RadioOptionWidget.static.highlightable = false;
16772
16773 OO.ui.RadioOptionWidget.static.scrollIntoViewOnSelect = true;
16774
16775 OO.ui.RadioOptionWidget.static.pressable = false;
16776
16777 OO.ui.RadioOptionWidget.static.tagName = 'label';
16778
16779 /* Methods */
16780
16781 /**
16782 * @param {jQuery.Event} e Focus event
16783 * @private
16784 */
16785 OO.ui.RadioOptionWidget.prototype.onInputFocus = function () {
16786 this.radio.$input.blur();
16787 this.$element.parent().focus();
16788 };
16789
16790 /**
16791 * @inheritdoc
16792 */
16793 OO.ui.RadioOptionWidget.prototype.setSelected = function ( state ) {
16794 OO.ui.RadioOptionWidget.parent.prototype.setSelected.call( this, state );
16795
16796 this.radio.setSelected( state );
16797 this.$element
16798 .attr( 'aria-checked', state.toString() )
16799 .removeAttr( 'aria-selected' );
16800
16801 return this;
16802 };
16803
16804 /**
16805 * @inheritdoc
16806 */
16807 OO.ui.RadioOptionWidget.prototype.setDisabled = function ( disabled ) {
16808 OO.ui.RadioOptionWidget.parent.prototype.setDisabled.call( this, disabled );
16809
16810 this.radio.setDisabled( this.isDisabled() );
16811
16812 return this;
16813 };
16814
16815 /**
16816 * MenuOptionWidget is an option widget that looks like a menu item. The class is used with
16817 * OO.ui.MenuSelectWidget to create a menu of mutually exclusive options. Please see
16818 * the [OOjs UI documentation on MediaWiki] [1] for more information.
16819 *
16820 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
16821 *
16822 * @class
16823 * @extends OO.ui.DecoratedOptionWidget
16824 *
16825 * @constructor
16826 * @param {Object} [config] Configuration options
16827 */
16828 OO.ui.MenuOptionWidget = function OoUiMenuOptionWidget( config ) {
16829 // Configuration initialization
16830 config = $.extend( { icon: 'check' }, config );
16831
16832 // Parent constructor
16833 OO.ui.MenuOptionWidget.parent.call( this, config );
16834
16835 // Initialization
16836 this.$element
16837 .attr( 'role', 'menuitem' )
16838 .addClass( 'oo-ui-menuOptionWidget' );
16839 };
16840
16841 /* Setup */
16842
16843 OO.inheritClass( OO.ui.MenuOptionWidget, OO.ui.DecoratedOptionWidget );
16844
16845 /* Static Properties */
16846
16847 OO.ui.MenuOptionWidget.static.scrollIntoViewOnSelect = true;
16848
16849 /**
16850 * MenuSectionOptionWidgets are used inside {@link OO.ui.MenuSelectWidget menu select widgets} to group one or more related
16851 * {@link OO.ui.MenuOptionWidget menu options}. MenuSectionOptionWidgets cannot be highlighted or selected.
16852 *
16853 * @example
16854 * var myDropdown = new OO.ui.DropdownWidget( {
16855 * menu: {
16856 * items: [
16857 * new OO.ui.MenuSectionOptionWidget( {
16858 * label: 'Dogs'
16859 * } ),
16860 * new OO.ui.MenuOptionWidget( {
16861 * data: 'corgi',
16862 * label: 'Welsh Corgi'
16863 * } ),
16864 * new OO.ui.MenuOptionWidget( {
16865 * data: 'poodle',
16866 * label: 'Standard Poodle'
16867 * } ),
16868 * new OO.ui.MenuSectionOptionWidget( {
16869 * label: 'Cats'
16870 * } ),
16871 * new OO.ui.MenuOptionWidget( {
16872 * data: 'lion',
16873 * label: 'Lion'
16874 * } )
16875 * ]
16876 * }
16877 * } );
16878 * $( 'body' ).append( myDropdown.$element );
16879 *
16880 * @class
16881 * @extends OO.ui.DecoratedOptionWidget
16882 *
16883 * @constructor
16884 * @param {Object} [config] Configuration options
16885 */
16886 OO.ui.MenuSectionOptionWidget = function OoUiMenuSectionOptionWidget( config ) {
16887 // Parent constructor
16888 OO.ui.MenuSectionOptionWidget.parent.call( this, config );
16889
16890 // Initialization
16891 this.$element.addClass( 'oo-ui-menuSectionOptionWidget' );
16892 };
16893
16894 /* Setup */
16895
16896 OO.inheritClass( OO.ui.MenuSectionOptionWidget, OO.ui.DecoratedOptionWidget );
16897
16898 /* Static Properties */
16899
16900 OO.ui.MenuSectionOptionWidget.static.selectable = false;
16901
16902 OO.ui.MenuSectionOptionWidget.static.highlightable = false;
16903
16904 /**
16905 * OutlineOptionWidget is an item in an {@link OO.ui.OutlineSelectWidget OutlineSelectWidget}.
16906 *
16907 * Currently, this class is only used by {@link OO.ui.BookletLayout booklet layouts}, which contain
16908 * {@link OO.ui.PageLayout page layouts}. See {@link OO.ui.BookletLayout BookletLayout}
16909 * for an example.
16910 *
16911 * @class
16912 * @extends OO.ui.DecoratedOptionWidget
16913 *
16914 * @constructor
16915 * @param {Object} [config] Configuration options
16916 * @cfg {number} [level] Indentation level
16917 * @cfg {boolean} [movable] Allow modification from {@link OO.ui.OutlineControlsWidget outline controls}.
16918 */
16919 OO.ui.OutlineOptionWidget = function OoUiOutlineOptionWidget( config ) {
16920 // Configuration initialization
16921 config = config || {};
16922
16923 // Parent constructor
16924 OO.ui.OutlineOptionWidget.parent.call( this, config );
16925
16926 // Properties
16927 this.level = 0;
16928 this.movable = !!config.movable;
16929 this.removable = !!config.removable;
16930
16931 // Initialization
16932 this.$element.addClass( 'oo-ui-outlineOptionWidget' );
16933 this.setLevel( config.level );
16934 };
16935
16936 /* Setup */
16937
16938 OO.inheritClass( OO.ui.OutlineOptionWidget, OO.ui.DecoratedOptionWidget );
16939
16940 /* Static Properties */
16941
16942 OO.ui.OutlineOptionWidget.static.highlightable = false;
16943
16944 OO.ui.OutlineOptionWidget.static.scrollIntoViewOnSelect = true;
16945
16946 OO.ui.OutlineOptionWidget.static.levelClass = 'oo-ui-outlineOptionWidget-level-';
16947
16948 OO.ui.OutlineOptionWidget.static.levels = 3;
16949
16950 /* Methods */
16951
16952 /**
16953 * Check if item is movable.
16954 *
16955 * Movability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
16956 *
16957 * @return {boolean} Item is movable
16958 */
16959 OO.ui.OutlineOptionWidget.prototype.isMovable = function () {
16960 return this.movable;
16961 };
16962
16963 /**
16964 * Check if item is removable.
16965 *
16966 * Removability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
16967 *
16968 * @return {boolean} Item is removable
16969 */
16970 OO.ui.OutlineOptionWidget.prototype.isRemovable = function () {
16971 return this.removable;
16972 };
16973
16974 /**
16975 * Get indentation level.
16976 *
16977 * @return {number} Indentation level
16978 */
16979 OO.ui.OutlineOptionWidget.prototype.getLevel = function () {
16980 return this.level;
16981 };
16982
16983 /**
16984 * Set movability.
16985 *
16986 * Movability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
16987 *
16988 * @param {boolean} movable Item is movable
16989 * @chainable
16990 */
16991 OO.ui.OutlineOptionWidget.prototype.setMovable = function ( movable ) {
16992 this.movable = !!movable;
16993 this.updateThemeClasses();
16994 return this;
16995 };
16996
16997 /**
16998 * Set removability.
16999 *
17000 * Removability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
17001 *
17002 * @param {boolean} movable Item is removable
17003 * @chainable
17004 */
17005 OO.ui.OutlineOptionWidget.prototype.setRemovable = function ( removable ) {
17006 this.removable = !!removable;
17007 this.updateThemeClasses();
17008 return this;
17009 };
17010
17011 /**
17012 * Set indentation level.
17013 *
17014 * @param {number} [level=0] Indentation level, in the range of [0,#maxLevel]
17015 * @chainable
17016 */
17017 OO.ui.OutlineOptionWidget.prototype.setLevel = function ( level ) {
17018 var levels = this.constructor.static.levels,
17019 levelClass = this.constructor.static.levelClass,
17020 i = levels;
17021
17022 this.level = level ? Math.max( 0, Math.min( levels - 1, level ) ) : 0;
17023 while ( i-- ) {
17024 if ( this.level === i ) {
17025 this.$element.addClass( levelClass + i );
17026 } else {
17027 this.$element.removeClass( levelClass + i );
17028 }
17029 }
17030 this.updateThemeClasses();
17031
17032 return this;
17033 };
17034
17035 /**
17036 * TabOptionWidget is an item in a {@link OO.ui.TabSelectWidget TabSelectWidget}.
17037 *
17038 * Currently, this class is only used by {@link OO.ui.IndexLayout index layouts}, which contain
17039 * {@link OO.ui.CardLayout card layouts}. See {@link OO.ui.IndexLayout IndexLayout}
17040 * for an example.
17041 *
17042 * @class
17043 * @extends OO.ui.OptionWidget
17044 *
17045 * @constructor
17046 * @param {Object} [config] Configuration options
17047 */
17048 OO.ui.TabOptionWidget = function OoUiTabOptionWidget( config ) {
17049 // Configuration initialization
17050 config = config || {};
17051
17052 // Parent constructor
17053 OO.ui.TabOptionWidget.parent.call( this, config );
17054
17055 // Initialization
17056 this.$element.addClass( 'oo-ui-tabOptionWidget' );
17057 };
17058
17059 /* Setup */
17060
17061 OO.inheritClass( OO.ui.TabOptionWidget, OO.ui.OptionWidget );
17062
17063 /* Static Properties */
17064
17065 OO.ui.TabOptionWidget.static.highlightable = false;
17066
17067 /**
17068 * PopupWidget is a container for content. The popup is overlaid and positioned absolutely.
17069 * By default, each popup has an anchor that points toward its origin.
17070 * Please see the [OOjs UI documentation on Mediawiki] [1] for more information and examples.
17071 *
17072 * @example
17073 * // A popup widget.
17074 * var popup = new OO.ui.PopupWidget( {
17075 * $content: $( '<p>Hi there!</p>' ),
17076 * padded: true,
17077 * width: 300
17078 * } );
17079 *
17080 * $( 'body' ).append( popup.$element );
17081 * // To display the popup, toggle the visibility to 'true'.
17082 * popup.toggle( true );
17083 *
17084 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups
17085 *
17086 * @class
17087 * @extends OO.ui.Widget
17088 * @mixins OO.ui.mixin.LabelElement
17089 * @mixins OO.ui.mixin.ClippableElement
17090 *
17091 * @constructor
17092 * @param {Object} [config] Configuration options
17093 * @cfg {number} [width=320] Width of popup in pixels
17094 * @cfg {number} [height] Height of popup in pixels. Omit to use the automatic height.
17095 * @cfg {boolean} [anchor=true] Show anchor pointing to origin of popup
17096 * @cfg {string} [align='center'] Alignment of the popup: `center`, `force-left`, `force-right`, `backwards` or `forwards`.
17097 * If the popup is forced-left the popup body is leaning towards the left. For force-right alignment, the body of the
17098 * popup is leaning towards the right of the screen.
17099 * Using 'backwards' is a logical direction which will result in the popup leaning towards the beginning of the sentence
17100 * in the given language, which means it will flip to the correct positioning in right-to-left languages.
17101 * Using 'forward' will also result in a logical alignment where the body of the popup leans towards the end of the
17102 * sentence in the given language.
17103 * @cfg {jQuery} [$container] Constrain the popup to the boundaries of the specified container.
17104 * See the [OOjs UI docs on MediaWiki][3] for an example.
17105 * [3]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups#containerExample
17106 * @cfg {number} [containerPadding=10] Padding between the popup and its container, specified as a number of pixels.
17107 * @cfg {jQuery} [$content] Content to append to the popup's body
17108 * @cfg {jQuery} [$footer] Content to append to the popup's footer
17109 * @cfg {boolean} [autoClose=false] Automatically close the popup when it loses focus.
17110 * @cfg {jQuery} [$autoCloseIgnore] Elements that will not close the popup when clicked.
17111 * This config option is only relevant if #autoClose is set to `true`. See the [OOjs UI docs on MediaWiki][2]
17112 * for an example.
17113 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups#autocloseExample
17114 * @cfg {boolean} [head] Show a popup header that contains a #label (if specified) and close
17115 * button.
17116 * @cfg {boolean} [padded] Add padding to the popup's body
17117 */
17118 OO.ui.PopupWidget = function OoUiPopupWidget( config ) {
17119 // Configuration initialization
17120 config = config || {};
17121
17122 // Parent constructor
17123 OO.ui.PopupWidget.parent.call( this, config );
17124
17125 // Properties (must be set before ClippableElement constructor call)
17126 this.$body = $( '<div>' );
17127 this.$popup = $( '<div>' );
17128
17129 // Mixin constructors
17130 OO.ui.mixin.LabelElement.call( this, config );
17131 OO.ui.mixin.ClippableElement.call( this, $.extend( {}, config, {
17132 $clippable: this.$body,
17133 $clippableContainer: this.$popup
17134 } ) );
17135
17136 // Properties
17137 this.$head = $( '<div>' );
17138 this.$footer = $( '<div>' );
17139 this.$anchor = $( '<div>' );
17140 // If undefined, will be computed lazily in updateDimensions()
17141 this.$container = config.$container;
17142 this.containerPadding = config.containerPadding !== undefined ? config.containerPadding : 10;
17143 this.autoClose = !!config.autoClose;
17144 this.$autoCloseIgnore = config.$autoCloseIgnore;
17145 this.transitionTimeout = null;
17146 this.anchor = null;
17147 this.width = config.width !== undefined ? config.width : 320;
17148 this.height = config.height !== undefined ? config.height : null;
17149 this.setAlignment( config.align );
17150 this.closeButton = new OO.ui.ButtonWidget( { framed: false, icon: 'close' } );
17151 this.onMouseDownHandler = this.onMouseDown.bind( this );
17152 this.onDocumentKeyDownHandler = this.onDocumentKeyDown.bind( this );
17153
17154 // Events
17155 this.closeButton.connect( this, { click: 'onCloseButtonClick' } );
17156
17157 // Initialization
17158 this.toggleAnchor( config.anchor === undefined || config.anchor );
17159 this.$body.addClass( 'oo-ui-popupWidget-body' );
17160 this.$anchor.addClass( 'oo-ui-popupWidget-anchor' );
17161 this.$head
17162 .addClass( 'oo-ui-popupWidget-head' )
17163 .append( this.$label, this.closeButton.$element );
17164 this.$footer.addClass( 'oo-ui-popupWidget-footer' );
17165 if ( !config.head ) {
17166 this.$head.addClass( 'oo-ui-element-hidden' );
17167 }
17168 if ( !config.$footer ) {
17169 this.$footer.addClass( 'oo-ui-element-hidden' );
17170 }
17171 this.$popup
17172 .addClass( 'oo-ui-popupWidget-popup' )
17173 .append( this.$head, this.$body, this.$footer );
17174 this.$element
17175 .addClass( 'oo-ui-popupWidget' )
17176 .append( this.$popup, this.$anchor );
17177 // Move content, which was added to #$element by OO.ui.Widget, to the body
17178 if ( config.$content instanceof jQuery ) {
17179 this.$body.append( config.$content );
17180 }
17181 if ( config.$footer instanceof jQuery ) {
17182 this.$footer.append( config.$footer );
17183 }
17184 if ( config.padded ) {
17185 this.$body.addClass( 'oo-ui-popupWidget-body-padded' );
17186 }
17187
17188 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
17189 // that reference properties not initialized at that time of parent class construction
17190 // TODO: Find a better way to handle post-constructor setup
17191 this.visible = false;
17192 this.$element.addClass( 'oo-ui-element-hidden' );
17193 };
17194
17195 /* Setup */
17196
17197 OO.inheritClass( OO.ui.PopupWidget, OO.ui.Widget );
17198 OO.mixinClass( OO.ui.PopupWidget, OO.ui.mixin.LabelElement );
17199 OO.mixinClass( OO.ui.PopupWidget, OO.ui.mixin.ClippableElement );
17200
17201 /* Methods */
17202
17203 /**
17204 * Handles mouse down events.
17205 *
17206 * @private
17207 * @param {MouseEvent} e Mouse down event
17208 */
17209 OO.ui.PopupWidget.prototype.onMouseDown = function ( e ) {
17210 if (
17211 this.isVisible() &&
17212 !$.contains( this.$element[ 0 ], e.target ) &&
17213 ( !this.$autoCloseIgnore || !this.$autoCloseIgnore.has( e.target ).length )
17214 ) {
17215 this.toggle( false );
17216 }
17217 };
17218
17219 /**
17220 * Bind mouse down listener.
17221 *
17222 * @private
17223 */
17224 OO.ui.PopupWidget.prototype.bindMouseDownListener = function () {
17225 // Capture clicks outside popup
17226 OO.ui.addCaptureEventListener( this.getElementWindow(), 'mousedown', this.onMouseDownHandler );
17227 };
17228
17229 /**
17230 * Handles close button click events.
17231 *
17232 * @private
17233 */
17234 OO.ui.PopupWidget.prototype.onCloseButtonClick = function () {
17235 if ( this.isVisible() ) {
17236 this.toggle( false );
17237 }
17238 };
17239
17240 /**
17241 * Unbind mouse down listener.
17242 *
17243 * @private
17244 */
17245 OO.ui.PopupWidget.prototype.unbindMouseDownListener = function () {
17246 OO.ui.removeCaptureEventListener( this.getElementWindow(), 'mousedown', this.onMouseDownHandler );
17247 };
17248
17249 /**
17250 * Handles key down events.
17251 *
17252 * @private
17253 * @param {KeyboardEvent} e Key down event
17254 */
17255 OO.ui.PopupWidget.prototype.onDocumentKeyDown = function ( e ) {
17256 if (
17257 e.which === OO.ui.Keys.ESCAPE &&
17258 this.isVisible()
17259 ) {
17260 this.toggle( false );
17261 e.preventDefault();
17262 e.stopPropagation();
17263 }
17264 };
17265
17266 /**
17267 * Bind key down listener.
17268 *
17269 * @private
17270 */
17271 OO.ui.PopupWidget.prototype.bindKeyDownListener = function () {
17272 OO.ui.addCaptureEventListener( this.getElementWindow(), 'keydown', this.onDocumentKeyDownHandler );
17273 };
17274
17275 /**
17276 * Unbind key down listener.
17277 *
17278 * @private
17279 */
17280 OO.ui.PopupWidget.prototype.unbindKeyDownListener = function () {
17281 OO.ui.removeCaptureEventListener( this.getElementWindow(), 'keydown', this.onDocumentKeyDownHandler );
17282 };
17283
17284 /**
17285 * Show, hide, or toggle the visibility of the anchor.
17286 *
17287 * @param {boolean} [show] Show anchor, omit to toggle
17288 */
17289 OO.ui.PopupWidget.prototype.toggleAnchor = function ( show ) {
17290 show = show === undefined ? !this.anchored : !!show;
17291
17292 if ( this.anchored !== show ) {
17293 if ( show ) {
17294 this.$element.addClass( 'oo-ui-popupWidget-anchored' );
17295 } else {
17296 this.$element.removeClass( 'oo-ui-popupWidget-anchored' );
17297 }
17298 this.anchored = show;
17299 }
17300 };
17301
17302 /**
17303 * Check if the anchor is visible.
17304 *
17305 * @return {boolean} Anchor is visible
17306 */
17307 OO.ui.PopupWidget.prototype.hasAnchor = function () {
17308 return this.anchor;
17309 };
17310
17311 /**
17312 * @inheritdoc
17313 */
17314 OO.ui.PopupWidget.prototype.toggle = function ( show ) {
17315 var change;
17316 show = show === undefined ? !this.isVisible() : !!show;
17317
17318 change = show !== this.isVisible();
17319
17320 // Parent method
17321 OO.ui.PopupWidget.parent.prototype.toggle.call( this, show );
17322
17323 if ( change ) {
17324 if ( show ) {
17325 if ( this.autoClose ) {
17326 this.bindMouseDownListener();
17327 this.bindKeyDownListener();
17328 }
17329 this.updateDimensions();
17330 this.toggleClipping( true );
17331 } else {
17332 this.toggleClipping( false );
17333 if ( this.autoClose ) {
17334 this.unbindMouseDownListener();
17335 this.unbindKeyDownListener();
17336 }
17337 }
17338 }
17339
17340 return this;
17341 };
17342
17343 /**
17344 * Set the size of the popup.
17345 *
17346 * Changing the size may also change the popup's position depending on the alignment.
17347 *
17348 * @param {number} width Width in pixels
17349 * @param {number} height Height in pixels
17350 * @param {boolean} [transition=false] Use a smooth transition
17351 * @chainable
17352 */
17353 OO.ui.PopupWidget.prototype.setSize = function ( width, height, transition ) {
17354 this.width = width;
17355 this.height = height !== undefined ? height : null;
17356 if ( this.isVisible() ) {
17357 this.updateDimensions( transition );
17358 }
17359 };
17360
17361 /**
17362 * Update the size and position.
17363 *
17364 * Only use this to keep the popup properly anchored. Use #setSize to change the size, and this will
17365 * be called automatically.
17366 *
17367 * @param {boolean} [transition=false] Use a smooth transition
17368 * @chainable
17369 */
17370 OO.ui.PopupWidget.prototype.updateDimensions = function ( transition ) {
17371 var popupOffset, originOffset, containerLeft, containerWidth, containerRight,
17372 popupLeft, popupRight, overlapLeft, overlapRight, anchorWidth,
17373 align = this.align,
17374 widget = this;
17375
17376 if ( !this.$container ) {
17377 // Lazy-initialize $container if not specified in constructor
17378 this.$container = $( this.getClosestScrollableElementContainer() );
17379 }
17380
17381 // Set height and width before measuring things, since it might cause our measurements
17382 // to change (e.g. due to scrollbars appearing or disappearing)
17383 this.$popup.css( {
17384 width: this.width,
17385 height: this.height !== null ? this.height : 'auto'
17386 } );
17387
17388 // If we are in RTL, we need to flip the alignment, unless it is center
17389 if ( align === 'forwards' || align === 'backwards' ) {
17390 if ( this.$container.css( 'direction' ) === 'rtl' ) {
17391 align = ( { forwards: 'force-left', backwards: 'force-right' } )[ this.align ];
17392 } else {
17393 align = ( { forwards: 'force-right', backwards: 'force-left' } )[ this.align ];
17394 }
17395
17396 }
17397
17398 // Compute initial popupOffset based on alignment
17399 popupOffset = this.width * ( { 'force-left': -1, center: -0.5, 'force-right': 0 } )[ align ];
17400
17401 // Figure out if this will cause the popup to go beyond the edge of the container
17402 originOffset = this.$element.offset().left;
17403 containerLeft = this.$container.offset().left;
17404 containerWidth = this.$container.innerWidth();
17405 containerRight = containerLeft + containerWidth;
17406 popupLeft = popupOffset - this.containerPadding;
17407 popupRight = popupOffset + this.containerPadding + this.width + this.containerPadding;
17408 overlapLeft = ( originOffset + popupLeft ) - containerLeft;
17409 overlapRight = containerRight - ( originOffset + popupRight );
17410
17411 // Adjust offset to make the popup not go beyond the edge, if needed
17412 if ( overlapRight < 0 ) {
17413 popupOffset += overlapRight;
17414 } else if ( overlapLeft < 0 ) {
17415 popupOffset -= overlapLeft;
17416 }
17417
17418 // Adjust offset to avoid anchor being rendered too close to the edge
17419 // $anchor.width() doesn't work with the pure CSS anchor (returns 0)
17420 // TODO: Find a measurement that works for CSS anchors and image anchors
17421 anchorWidth = this.$anchor[ 0 ].scrollWidth * 2;
17422 if ( popupOffset + this.width < anchorWidth ) {
17423 popupOffset = anchorWidth - this.width;
17424 } else if ( -popupOffset < anchorWidth ) {
17425 popupOffset = -anchorWidth;
17426 }
17427
17428 // Prevent transition from being interrupted
17429 clearTimeout( this.transitionTimeout );
17430 if ( transition ) {
17431 // Enable transition
17432 this.$element.addClass( 'oo-ui-popupWidget-transitioning' );
17433 }
17434
17435 // Position body relative to anchor
17436 this.$popup.css( 'margin-left', popupOffset );
17437
17438 if ( transition ) {
17439 // Prevent transitioning after transition is complete
17440 this.transitionTimeout = setTimeout( function () {
17441 widget.$element.removeClass( 'oo-ui-popupWidget-transitioning' );
17442 }, 200 );
17443 } else {
17444 // Prevent transitioning immediately
17445 this.$element.removeClass( 'oo-ui-popupWidget-transitioning' );
17446 }
17447
17448 // Reevaluate clipping state since we've relocated and resized the popup
17449 this.clip();
17450
17451 return this;
17452 };
17453
17454 /**
17455 * Set popup alignment
17456 * @param {string} align Alignment of the popup, `center`, `force-left`, `force-right`,
17457 * `backwards` or `forwards`.
17458 */
17459 OO.ui.PopupWidget.prototype.setAlignment = function ( align ) {
17460 // Validate alignment and transform deprecated values
17461 if ( [ 'left', 'right', 'force-left', 'force-right', 'backwards', 'forwards', 'center' ].indexOf( align ) > -1 ) {
17462 this.align = { left: 'force-right', right: 'force-left' }[ align ] || align;
17463 } else {
17464 this.align = 'center';
17465 }
17466 };
17467
17468 /**
17469 * Get popup alignment
17470 * @return {string} align Alignment of the popup, `center`, `force-left`, `force-right`,
17471 * `backwards` or `forwards`.
17472 */
17473 OO.ui.PopupWidget.prototype.getAlignment = function () {
17474 return this.align;
17475 };
17476
17477 /**
17478 * Progress bars visually display the status of an operation, such as a download,
17479 * and can be either determinate or indeterminate:
17480 *
17481 * - **determinate** process bars show the percent of an operation that is complete.
17482 *
17483 * - **indeterminate** process bars use a visual display of motion to indicate that an operation
17484 * is taking place. Because the extent of an indeterminate operation is unknown, the bar does
17485 * not use percentages.
17486 *
17487 * The value of the `progress` configuration determines whether the bar is determinate or indeterminate.
17488 *
17489 * @example
17490 * // Examples of determinate and indeterminate progress bars.
17491 * var progressBar1 = new OO.ui.ProgressBarWidget( {
17492 * progress: 33
17493 * } );
17494 * var progressBar2 = new OO.ui.ProgressBarWidget();
17495 *
17496 * // Create a FieldsetLayout to layout progress bars
17497 * var fieldset = new OO.ui.FieldsetLayout;
17498 * fieldset.addItems( [
17499 * new OO.ui.FieldLayout( progressBar1, {label: 'Determinate', align: 'top'}),
17500 * new OO.ui.FieldLayout( progressBar2, {label: 'Indeterminate', align: 'top'})
17501 * ] );
17502 * $( 'body' ).append( fieldset.$element );
17503 *
17504 * @class
17505 * @extends OO.ui.Widget
17506 *
17507 * @constructor
17508 * @param {Object} [config] Configuration options
17509 * @cfg {number|boolean} [progress=false] The type of progress bar (determinate or indeterminate).
17510 * To create a determinate progress bar, specify a number that reflects the initial percent complete.
17511 * By default, the progress bar is indeterminate.
17512 */
17513 OO.ui.ProgressBarWidget = function OoUiProgressBarWidget( config ) {
17514 // Configuration initialization
17515 config = config || {};
17516
17517 // Parent constructor
17518 OO.ui.ProgressBarWidget.parent.call( this, config );
17519
17520 // Properties
17521 this.$bar = $( '<div>' );
17522 this.progress = null;
17523
17524 // Initialization
17525 this.setProgress( config.progress !== undefined ? config.progress : false );
17526 this.$bar.addClass( 'oo-ui-progressBarWidget-bar' );
17527 this.$element
17528 .attr( {
17529 role: 'progressbar',
17530 'aria-valuemin': 0,
17531 'aria-valuemax': 100
17532 } )
17533 .addClass( 'oo-ui-progressBarWidget' )
17534 .append( this.$bar );
17535 };
17536
17537 /* Setup */
17538
17539 OO.inheritClass( OO.ui.ProgressBarWidget, OO.ui.Widget );
17540
17541 /* Static Properties */
17542
17543 OO.ui.ProgressBarWidget.static.tagName = 'div';
17544
17545 /* Methods */
17546
17547 /**
17548 * Get the percent of the progress that has been completed. Indeterminate progresses will return `false`.
17549 *
17550 * @return {number|boolean} Progress percent
17551 */
17552 OO.ui.ProgressBarWidget.prototype.getProgress = function () {
17553 return this.progress;
17554 };
17555
17556 /**
17557 * Set the percent of the process completed or `false` for an indeterminate process.
17558 *
17559 * @param {number|boolean} progress Progress percent or `false` for indeterminate
17560 */
17561 OO.ui.ProgressBarWidget.prototype.setProgress = function ( progress ) {
17562 this.progress = progress;
17563
17564 if ( progress !== false ) {
17565 this.$bar.css( 'width', this.progress + '%' );
17566 this.$element.attr( 'aria-valuenow', this.progress );
17567 } else {
17568 this.$bar.css( 'width', '' );
17569 this.$element.removeAttr( 'aria-valuenow' );
17570 }
17571 this.$element.toggleClass( 'oo-ui-progressBarWidget-indeterminate', !progress );
17572 };
17573
17574 /**
17575 * SearchWidgets combine a {@link OO.ui.TextInputWidget text input field}, where users can type a search query,
17576 * and a menu of search results, which is displayed beneath the query
17577 * field. Unlike {@link OO.ui.mixin.LookupElement lookup menus}, search result menus are always visible to the user.
17578 * Users can choose an item from the menu or type a query into the text field to search for a matching result item.
17579 * In general, search widgets are used inside a separate {@link OO.ui.Dialog dialog} window.
17580 *
17581 * Each time the query is changed, the search result menu is cleared and repopulated. Please see
17582 * the [OOjs UI demos][1] for an example.
17583 *
17584 * [1]: https://tools.wmflabs.org/oojs-ui/oojs-ui/demos/#dialogs-mediawiki-vector-ltr
17585 *
17586 * @class
17587 * @extends OO.ui.Widget
17588 *
17589 * @constructor
17590 * @param {Object} [config] Configuration options
17591 * @cfg {string|jQuery} [placeholder] Placeholder text for query input
17592 * @cfg {string} [value] Initial query value
17593 */
17594 OO.ui.SearchWidget = function OoUiSearchWidget( config ) {
17595 // Configuration initialization
17596 config = config || {};
17597
17598 // Parent constructor
17599 OO.ui.SearchWidget.parent.call( this, config );
17600
17601 // Properties
17602 this.query = new OO.ui.TextInputWidget( {
17603 icon: 'search',
17604 placeholder: config.placeholder,
17605 value: config.value
17606 } );
17607 this.results = new OO.ui.SelectWidget();
17608 this.$query = $( '<div>' );
17609 this.$results = $( '<div>' );
17610
17611 // Events
17612 this.query.connect( this, {
17613 change: 'onQueryChange',
17614 enter: 'onQueryEnter'
17615 } );
17616 this.query.$input.on( 'keydown', this.onQueryKeydown.bind( this ) );
17617
17618 // Initialization
17619 this.$query
17620 .addClass( 'oo-ui-searchWidget-query' )
17621 .append( this.query.$element );
17622 this.$results
17623 .addClass( 'oo-ui-searchWidget-results' )
17624 .append( this.results.$element );
17625 this.$element
17626 .addClass( 'oo-ui-searchWidget' )
17627 .append( this.$results, this.$query );
17628 };
17629
17630 /* Setup */
17631
17632 OO.inheritClass( OO.ui.SearchWidget, OO.ui.Widget );
17633
17634 /* Methods */
17635
17636 /**
17637 * Handle query key down events.
17638 *
17639 * @private
17640 * @param {jQuery.Event} e Key down event
17641 */
17642 OO.ui.SearchWidget.prototype.onQueryKeydown = function ( e ) {
17643 var highlightedItem, nextItem,
17644 dir = e.which === OO.ui.Keys.DOWN ? 1 : ( e.which === OO.ui.Keys.UP ? -1 : 0 );
17645
17646 if ( dir ) {
17647 highlightedItem = this.results.getHighlightedItem();
17648 if ( !highlightedItem ) {
17649 highlightedItem = this.results.getSelectedItem();
17650 }
17651 nextItem = this.results.getRelativeSelectableItem( highlightedItem, dir );
17652 this.results.highlightItem( nextItem );
17653 nextItem.scrollElementIntoView();
17654 }
17655 };
17656
17657 /**
17658 * Handle select widget select events.
17659 *
17660 * Clears existing results. Subclasses should repopulate items according to new query.
17661 *
17662 * @private
17663 * @param {string} value New value
17664 */
17665 OO.ui.SearchWidget.prototype.onQueryChange = function () {
17666 // Reset
17667 this.results.clearItems();
17668 };
17669
17670 /**
17671 * Handle select widget enter key events.
17672 *
17673 * Chooses highlighted item.
17674 *
17675 * @private
17676 * @param {string} value New value
17677 */
17678 OO.ui.SearchWidget.prototype.onQueryEnter = function () {
17679 // Reset
17680 this.results.chooseItem( this.results.getHighlightedItem() );
17681 };
17682
17683 /**
17684 * Get the query input.
17685 *
17686 * @return {OO.ui.TextInputWidget} Query input
17687 */
17688 OO.ui.SearchWidget.prototype.getQuery = function () {
17689 return this.query;
17690 };
17691
17692 /**
17693 * Get the search results menu.
17694 *
17695 * @return {OO.ui.SelectWidget} Menu of search results
17696 */
17697 OO.ui.SearchWidget.prototype.getResults = function () {
17698 return this.results;
17699 };
17700
17701 /**
17702 * A SelectWidget is of a generic selection of options. The OOjs UI library contains several types of
17703 * select widgets, including {@link OO.ui.ButtonSelectWidget button selects},
17704 * {@link OO.ui.RadioSelectWidget radio selects}, and {@link OO.ui.MenuSelectWidget
17705 * menu selects}.
17706 *
17707 * This class should be used together with OO.ui.OptionWidget or OO.ui.DecoratedOptionWidget. For more
17708 * information, please see the [OOjs UI documentation on MediaWiki][1].
17709 *
17710 * @example
17711 * // Example of a select widget with three options
17712 * var select = new OO.ui.SelectWidget( {
17713 * items: [
17714 * new OO.ui.OptionWidget( {
17715 * data: 'a',
17716 * label: 'Option One',
17717 * } ),
17718 * new OO.ui.OptionWidget( {
17719 * data: 'b',
17720 * label: 'Option Two',
17721 * } ),
17722 * new OO.ui.OptionWidget( {
17723 * data: 'c',
17724 * label: 'Option Three',
17725 * } )
17726 * ]
17727 * } );
17728 * $( 'body' ).append( select.$element );
17729 *
17730 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
17731 *
17732 * @abstract
17733 * @class
17734 * @extends OO.ui.Widget
17735 * @mixins OO.ui.mixin.GroupWidget
17736 *
17737 * @constructor
17738 * @param {Object} [config] Configuration options
17739 * @cfg {OO.ui.OptionWidget[]} [items] An array of options to add to the select.
17740 * Options are created with {@link OO.ui.OptionWidget OptionWidget} classes. See
17741 * the [OOjs UI documentation on MediaWiki] [2] for examples.
17742 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
17743 */
17744 OO.ui.SelectWidget = function OoUiSelectWidget( config ) {
17745 // Configuration initialization
17746 config = config || {};
17747
17748 // Parent constructor
17749 OO.ui.SelectWidget.parent.call( this, config );
17750
17751 // Mixin constructors
17752 OO.ui.mixin.GroupWidget.call( this, $.extend( {}, config, { $group: this.$element } ) );
17753
17754 // Properties
17755 this.pressed = false;
17756 this.selecting = null;
17757 this.onMouseUpHandler = this.onMouseUp.bind( this );
17758 this.onMouseMoveHandler = this.onMouseMove.bind( this );
17759 this.onKeyDownHandler = this.onKeyDown.bind( this );
17760 this.onKeyPressHandler = this.onKeyPress.bind( this );
17761 this.keyPressBuffer = '';
17762 this.keyPressBufferTimer = null;
17763
17764 // Events
17765 this.connect( this, {
17766 toggle: 'onToggle'
17767 } );
17768 this.$element.on( {
17769 mousedown: this.onMouseDown.bind( this ),
17770 mouseover: this.onMouseOver.bind( this ),
17771 mouseleave: this.onMouseLeave.bind( this )
17772 } );
17773
17774 // Initialization
17775 this.$element
17776 .addClass( 'oo-ui-selectWidget oo-ui-selectWidget-depressed' )
17777 .attr( 'role', 'listbox' );
17778 if ( Array.isArray( config.items ) ) {
17779 this.addItems( config.items );
17780 }
17781 };
17782
17783 /* Setup */
17784
17785 OO.inheritClass( OO.ui.SelectWidget, OO.ui.Widget );
17786
17787 // Need to mixin base class as well
17788 OO.mixinClass( OO.ui.SelectWidget, OO.ui.mixin.GroupElement );
17789 OO.mixinClass( OO.ui.SelectWidget, OO.ui.mixin.GroupWidget );
17790
17791 /* Static */
17792 OO.ui.SelectWidget.static.passAllFilter = function () {
17793 return true;
17794 };
17795
17796 /* Events */
17797
17798 /**
17799 * @event highlight
17800 *
17801 * A `highlight` event is emitted when the highlight is changed with the #highlightItem method.
17802 *
17803 * @param {OO.ui.OptionWidget|null} item Highlighted item
17804 */
17805
17806 /**
17807 * @event press
17808 *
17809 * A `press` event is emitted when the #pressItem method is used to programmatically modify the
17810 * pressed state of an option.
17811 *
17812 * @param {OO.ui.OptionWidget|null} item Pressed item
17813 */
17814
17815 /**
17816 * @event select
17817 *
17818 * A `select` event is emitted when the selection is modified programmatically with the #selectItem method.
17819 *
17820 * @param {OO.ui.OptionWidget|null} item Selected item
17821 */
17822
17823 /**
17824 * @event choose
17825 * A `choose` event is emitted when an item is chosen with the #chooseItem method.
17826 * @param {OO.ui.OptionWidget} item Chosen item
17827 */
17828
17829 /**
17830 * @event add
17831 *
17832 * An `add` event is emitted when options are added to the select with the #addItems method.
17833 *
17834 * @param {OO.ui.OptionWidget[]} items Added items
17835 * @param {number} index Index of insertion point
17836 */
17837
17838 /**
17839 * @event remove
17840 *
17841 * A `remove` event is emitted when options are removed from the select with the #clearItems
17842 * or #removeItems methods.
17843 *
17844 * @param {OO.ui.OptionWidget[]} items Removed items
17845 */
17846
17847 /* Methods */
17848
17849 /**
17850 * Handle mouse down events.
17851 *
17852 * @private
17853 * @param {jQuery.Event} e Mouse down event
17854 */
17855 OO.ui.SelectWidget.prototype.onMouseDown = function ( e ) {
17856 var item;
17857
17858 if ( !this.isDisabled() && e.which === 1 ) {
17859 this.togglePressed( true );
17860 item = this.getTargetItem( e );
17861 if ( item && item.isSelectable() ) {
17862 this.pressItem( item );
17863 this.selecting = item;
17864 OO.ui.addCaptureEventListener(
17865 this.getElementDocument(),
17866 'mouseup',
17867 this.onMouseUpHandler
17868 );
17869 OO.ui.addCaptureEventListener(
17870 this.getElementDocument(),
17871 'mousemove',
17872 this.onMouseMoveHandler
17873 );
17874 }
17875 }
17876 return false;
17877 };
17878
17879 /**
17880 * Handle mouse up events.
17881 *
17882 * @private
17883 * @param {jQuery.Event} e Mouse up event
17884 */
17885 OO.ui.SelectWidget.prototype.onMouseUp = function ( e ) {
17886 var item;
17887
17888 this.togglePressed( false );
17889 if ( !this.selecting ) {
17890 item = this.getTargetItem( e );
17891 if ( item && item.isSelectable() ) {
17892 this.selecting = item;
17893 }
17894 }
17895 if ( !this.isDisabled() && e.which === 1 && this.selecting ) {
17896 this.pressItem( null );
17897 this.chooseItem( this.selecting );
17898 this.selecting = null;
17899 }
17900
17901 OO.ui.removeCaptureEventListener( this.getElementDocument(), 'mouseup',
17902 this.onMouseUpHandler );
17903 OO.ui.removeCaptureEventListener( this.getElementDocument(), 'mousemove',
17904 this.onMouseMoveHandler );
17905
17906 return false;
17907 };
17908
17909 /**
17910 * Handle mouse move events.
17911 *
17912 * @private
17913 * @param {jQuery.Event} e Mouse move event
17914 */
17915 OO.ui.SelectWidget.prototype.onMouseMove = function ( e ) {
17916 var item;
17917
17918 if ( !this.isDisabled() && this.pressed ) {
17919 item = this.getTargetItem( e );
17920 if ( item && item !== this.selecting && item.isSelectable() ) {
17921 this.pressItem( item );
17922 this.selecting = item;
17923 }
17924 }
17925 return false;
17926 };
17927
17928 /**
17929 * Handle mouse over events.
17930 *
17931 * @private
17932 * @param {jQuery.Event} e Mouse over event
17933 */
17934 OO.ui.SelectWidget.prototype.onMouseOver = function ( e ) {
17935 var item;
17936
17937 if ( !this.isDisabled() ) {
17938 item = this.getTargetItem( e );
17939 this.highlightItem( item && item.isHighlightable() ? item : null );
17940 }
17941 return false;
17942 };
17943
17944 /**
17945 * Handle mouse leave events.
17946 *
17947 * @private
17948 * @param {jQuery.Event} e Mouse over event
17949 */
17950 OO.ui.SelectWidget.prototype.onMouseLeave = function () {
17951 if ( !this.isDisabled() ) {
17952 this.highlightItem( null );
17953 }
17954 return false;
17955 };
17956
17957 /**
17958 * Handle key down events.
17959 *
17960 * @protected
17961 * @param {jQuery.Event} e Key down event
17962 */
17963 OO.ui.SelectWidget.prototype.onKeyDown = function ( e ) {
17964 var nextItem,
17965 handled = false,
17966 currentItem = this.getHighlightedItem() || this.getSelectedItem();
17967
17968 if ( !this.isDisabled() && this.isVisible() ) {
17969 switch ( e.keyCode ) {
17970 case OO.ui.Keys.ENTER:
17971 if ( currentItem && currentItem.constructor.static.highlightable ) {
17972 // Was only highlighted, now let's select it. No-op if already selected.
17973 this.chooseItem( currentItem );
17974 handled = true;
17975 }
17976 break;
17977 case OO.ui.Keys.UP:
17978 case OO.ui.Keys.LEFT:
17979 this.clearKeyPressBuffer();
17980 nextItem = this.getRelativeSelectableItem( currentItem, -1 );
17981 handled = true;
17982 break;
17983 case OO.ui.Keys.DOWN:
17984 case OO.ui.Keys.RIGHT:
17985 this.clearKeyPressBuffer();
17986 nextItem = this.getRelativeSelectableItem( currentItem, 1 );
17987 handled = true;
17988 break;
17989 case OO.ui.Keys.ESCAPE:
17990 case OO.ui.Keys.TAB:
17991 if ( currentItem && currentItem.constructor.static.highlightable ) {
17992 currentItem.setHighlighted( false );
17993 }
17994 this.unbindKeyDownListener();
17995 this.unbindKeyPressListener();
17996 // Don't prevent tabbing away / defocusing
17997 handled = false;
17998 break;
17999 }
18000
18001 if ( nextItem ) {
18002 if ( nextItem.constructor.static.highlightable ) {
18003 this.highlightItem( nextItem );
18004 } else {
18005 this.chooseItem( nextItem );
18006 }
18007 nextItem.scrollElementIntoView();
18008 }
18009
18010 if ( handled ) {
18011 // Can't just return false, because e is not always a jQuery event
18012 e.preventDefault();
18013 e.stopPropagation();
18014 }
18015 }
18016 };
18017
18018 /**
18019 * Bind key down listener.
18020 *
18021 * @protected
18022 */
18023 OO.ui.SelectWidget.prototype.bindKeyDownListener = function () {
18024 OO.ui.addCaptureEventListener( this.getElementWindow(), 'keydown', this.onKeyDownHandler );
18025 };
18026
18027 /**
18028 * Unbind key down listener.
18029 *
18030 * @protected
18031 */
18032 OO.ui.SelectWidget.prototype.unbindKeyDownListener = function () {
18033 OO.ui.removeCaptureEventListener( this.getElementWindow(), 'keydown', this.onKeyDownHandler );
18034 };
18035
18036 /**
18037 * Clear the key-press buffer
18038 *
18039 * @protected
18040 */
18041 OO.ui.SelectWidget.prototype.clearKeyPressBuffer = function () {
18042 if ( this.keyPressBufferTimer ) {
18043 clearTimeout( this.keyPressBufferTimer );
18044 this.keyPressBufferTimer = null;
18045 }
18046 this.keyPressBuffer = '';
18047 };
18048
18049 /**
18050 * Handle key press events.
18051 *
18052 * @protected
18053 * @param {jQuery.Event} e Key press event
18054 */
18055 OO.ui.SelectWidget.prototype.onKeyPress = function ( e ) {
18056 var c, filter, item;
18057
18058 if ( !e.charCode ) {
18059 if ( e.keyCode === OO.ui.Keys.BACKSPACE && this.keyPressBuffer !== '' ) {
18060 this.keyPressBuffer = this.keyPressBuffer.substr( 0, this.keyPressBuffer.length - 1 );
18061 return false;
18062 }
18063 return;
18064 }
18065 if ( String.fromCodePoint ) {
18066 c = String.fromCodePoint( e.charCode );
18067 } else {
18068 c = String.fromCharCode( e.charCode );
18069 }
18070
18071 if ( this.keyPressBufferTimer ) {
18072 clearTimeout( this.keyPressBufferTimer );
18073 }
18074 this.keyPressBufferTimer = setTimeout( this.clearKeyPressBuffer.bind( this ), 1500 );
18075
18076 item = this.getHighlightedItem() || this.getSelectedItem();
18077
18078 if ( this.keyPressBuffer === c ) {
18079 // Common (if weird) special case: typing "xxxx" will cycle through all
18080 // the items beginning with "x".
18081 if ( item ) {
18082 item = this.getRelativeSelectableItem( item, 1 );
18083 }
18084 } else {
18085 this.keyPressBuffer += c;
18086 }
18087
18088 filter = this.getItemMatcher( this.keyPressBuffer, false );
18089 if ( !item || !filter( item ) ) {
18090 item = this.getRelativeSelectableItem( item, 1, filter );
18091 }
18092 if ( item ) {
18093 if ( item.constructor.static.highlightable ) {
18094 this.highlightItem( item );
18095 } else {
18096 this.chooseItem( item );
18097 }
18098 item.scrollElementIntoView();
18099 }
18100
18101 return false;
18102 };
18103
18104 /**
18105 * Get a matcher for the specific string
18106 *
18107 * @protected
18108 * @param {string} s String to match against items
18109 * @param {boolean} [exact=false] Only accept exact matches
18110 * @return {Function} function ( OO.ui.OptionItem ) => boolean
18111 */
18112 OO.ui.SelectWidget.prototype.getItemMatcher = function ( s, exact ) {
18113 var re;
18114
18115 if ( s.normalize ) {
18116 s = s.normalize();
18117 }
18118 s = exact ? s.trim() : s.replace( /^\s+/, '' );
18119 re = '^\\s*' + s.replace( /([\\{}()|.?*+\-\^$\[\]])/g, '\\$1' ).replace( /\s+/g, '\\s+' );
18120 if ( exact ) {
18121 re += '\\s*$';
18122 }
18123 re = new RegExp( re, 'i' );
18124 return function ( item ) {
18125 var l = item.getLabel();
18126 if ( typeof l !== 'string' ) {
18127 l = item.$label.text();
18128 }
18129 if ( l.normalize ) {
18130 l = l.normalize();
18131 }
18132 return re.test( l );
18133 };
18134 };
18135
18136 /**
18137 * Bind key press listener.
18138 *
18139 * @protected
18140 */
18141 OO.ui.SelectWidget.prototype.bindKeyPressListener = function () {
18142 OO.ui.addCaptureEventListener( this.getElementWindow(), 'keypress', this.onKeyPressHandler );
18143 };
18144
18145 /**
18146 * Unbind key down listener.
18147 *
18148 * If you override this, be sure to call this.clearKeyPressBuffer() from your
18149 * implementation.
18150 *
18151 * @protected
18152 */
18153 OO.ui.SelectWidget.prototype.unbindKeyPressListener = function () {
18154 OO.ui.removeCaptureEventListener( this.getElementWindow(), 'keypress', this.onKeyPressHandler );
18155 this.clearKeyPressBuffer();
18156 };
18157
18158 /**
18159 * Visibility change handler
18160 *
18161 * @protected
18162 * @param {boolean} visible
18163 */
18164 OO.ui.SelectWidget.prototype.onToggle = function ( visible ) {
18165 if ( !visible ) {
18166 this.clearKeyPressBuffer();
18167 }
18168 };
18169
18170 /**
18171 * Get the closest item to a jQuery.Event.
18172 *
18173 * @private
18174 * @param {jQuery.Event} e
18175 * @return {OO.ui.OptionWidget|null} Outline item widget, `null` if none was found
18176 */
18177 OO.ui.SelectWidget.prototype.getTargetItem = function ( e ) {
18178 return $( e.target ).closest( '.oo-ui-optionWidget' ).data( 'oo-ui-optionWidget' ) || null;
18179 };
18180
18181 /**
18182 * Get selected item.
18183 *
18184 * @return {OO.ui.OptionWidget|null} Selected item, `null` if no item is selected
18185 */
18186 OO.ui.SelectWidget.prototype.getSelectedItem = function () {
18187 var i, len;
18188
18189 for ( i = 0, len = this.items.length; i < len; i++ ) {
18190 if ( this.items[ i ].isSelected() ) {
18191 return this.items[ i ];
18192 }
18193 }
18194 return null;
18195 };
18196
18197 /**
18198 * Get highlighted item.
18199 *
18200 * @return {OO.ui.OptionWidget|null} Highlighted item, `null` if no item is highlighted
18201 */
18202 OO.ui.SelectWidget.prototype.getHighlightedItem = function () {
18203 var i, len;
18204
18205 for ( i = 0, len = this.items.length; i < len; i++ ) {
18206 if ( this.items[ i ].isHighlighted() ) {
18207 return this.items[ i ];
18208 }
18209 }
18210 return null;
18211 };
18212
18213 /**
18214 * Toggle pressed state.
18215 *
18216 * Press is a state that occurs when a user mouses down on an item, but
18217 * has not yet let go of the mouse. The item may appear selected, but it will not be selected
18218 * until the user releases the mouse.
18219 *
18220 * @param {boolean} pressed An option is being pressed
18221 */
18222 OO.ui.SelectWidget.prototype.togglePressed = function ( pressed ) {
18223 if ( pressed === undefined ) {
18224 pressed = !this.pressed;
18225 }
18226 if ( pressed !== this.pressed ) {
18227 this.$element
18228 .toggleClass( 'oo-ui-selectWidget-pressed', pressed )
18229 .toggleClass( 'oo-ui-selectWidget-depressed', !pressed );
18230 this.pressed = pressed;
18231 }
18232 };
18233
18234 /**
18235 * Highlight an option. If the `item` param is omitted, no options will be highlighted
18236 * and any existing highlight will be removed. The highlight is mutually exclusive.
18237 *
18238 * @param {OO.ui.OptionWidget} [item] Item to highlight, omit for no highlight
18239 * @fires highlight
18240 * @chainable
18241 */
18242 OO.ui.SelectWidget.prototype.highlightItem = function ( item ) {
18243 var i, len, highlighted,
18244 changed = false;
18245
18246 for ( i = 0, len = this.items.length; i < len; i++ ) {
18247 highlighted = this.items[ i ] === item;
18248 if ( this.items[ i ].isHighlighted() !== highlighted ) {
18249 this.items[ i ].setHighlighted( highlighted );
18250 changed = true;
18251 }
18252 }
18253 if ( changed ) {
18254 this.emit( 'highlight', item );
18255 }
18256
18257 return this;
18258 };
18259
18260 /**
18261 * Fetch an item by its label.
18262 *
18263 * @param {string} label Label of the item to select.
18264 * @param {boolean} [prefix=false] Allow a prefix match, if only a single item matches
18265 * @return {OO.ui.Element|null} Item with equivalent label, `null` if none exists
18266 */
18267 OO.ui.SelectWidget.prototype.getItemFromLabel = function ( label, prefix ) {
18268 var i, item, found,
18269 len = this.items.length,
18270 filter = this.getItemMatcher( label, true );
18271
18272 for ( i = 0; i < len; i++ ) {
18273 item = this.items[ i ];
18274 if ( item instanceof OO.ui.OptionWidget && item.isSelectable() && filter( item ) ) {
18275 return item;
18276 }
18277 }
18278
18279 if ( prefix ) {
18280 found = null;
18281 filter = this.getItemMatcher( label, false );
18282 for ( i = 0; i < len; i++ ) {
18283 item = this.items[ i ];
18284 if ( item instanceof OO.ui.OptionWidget && item.isSelectable() && filter( item ) ) {
18285 if ( found ) {
18286 return null;
18287 }
18288 found = item;
18289 }
18290 }
18291 if ( found ) {
18292 return found;
18293 }
18294 }
18295
18296 return null;
18297 };
18298
18299 /**
18300 * Programmatically select an option by its label. If the item does not exist,
18301 * all options will be deselected.
18302 *
18303 * @param {string} [label] Label of the item to select.
18304 * @param {boolean} [prefix=false] Allow a prefix match, if only a single item matches
18305 * @fires select
18306 * @chainable
18307 */
18308 OO.ui.SelectWidget.prototype.selectItemByLabel = function ( label, prefix ) {
18309 var itemFromLabel = this.getItemFromLabel( label, !!prefix );
18310 if ( label === undefined || !itemFromLabel ) {
18311 return this.selectItem();
18312 }
18313 return this.selectItem( itemFromLabel );
18314 };
18315
18316 /**
18317 * Programmatically select an option by its data. If the `data` parameter is omitted,
18318 * or if the item does not exist, all options will be deselected.
18319 *
18320 * @param {Object|string} [data] Value of the item to select, omit to deselect all
18321 * @fires select
18322 * @chainable
18323 */
18324 OO.ui.SelectWidget.prototype.selectItemByData = function ( data ) {
18325 var itemFromData = this.getItemFromData( data );
18326 if ( data === undefined || !itemFromData ) {
18327 return this.selectItem();
18328 }
18329 return this.selectItem( itemFromData );
18330 };
18331
18332 /**
18333 * Programmatically select an option by its reference. If the `item` parameter is omitted,
18334 * all options will be deselected.
18335 *
18336 * @param {OO.ui.OptionWidget} [item] Item to select, omit to deselect all
18337 * @fires select
18338 * @chainable
18339 */
18340 OO.ui.SelectWidget.prototype.selectItem = function ( item ) {
18341 var i, len, selected,
18342 changed = false;
18343
18344 for ( i = 0, len = this.items.length; i < len; i++ ) {
18345 selected = this.items[ i ] === item;
18346 if ( this.items[ i ].isSelected() !== selected ) {
18347 this.items[ i ].setSelected( selected );
18348 changed = true;
18349 }
18350 }
18351 if ( changed ) {
18352 this.emit( 'select', item );
18353 }
18354
18355 return this;
18356 };
18357
18358 /**
18359 * Press an item.
18360 *
18361 * Press is a state that occurs when a user mouses down on an item, but has not
18362 * yet let go of the mouse. The item may appear selected, but it will not be selected until the user
18363 * releases the mouse.
18364 *
18365 * @param {OO.ui.OptionWidget} [item] Item to press, omit to depress all
18366 * @fires press
18367 * @chainable
18368 */
18369 OO.ui.SelectWidget.prototype.pressItem = function ( item ) {
18370 var i, len, pressed,
18371 changed = false;
18372
18373 for ( i = 0, len = this.items.length; i < len; i++ ) {
18374 pressed = this.items[ i ] === item;
18375 if ( this.items[ i ].isPressed() !== pressed ) {
18376 this.items[ i ].setPressed( pressed );
18377 changed = true;
18378 }
18379 }
18380 if ( changed ) {
18381 this.emit( 'press', item );
18382 }
18383
18384 return this;
18385 };
18386
18387 /**
18388 * Choose an item.
18389 *
18390 * Note that ‘choose’ should never be modified programmatically. A user can choose
18391 * an option with the keyboard or mouse and it becomes selected. To select an item programmatically,
18392 * use the #selectItem method.
18393 *
18394 * This method is identical to #selectItem, but may vary in subclasses that take additional action
18395 * when users choose an item with the keyboard or mouse.
18396 *
18397 * @param {OO.ui.OptionWidget} item Item to choose
18398 * @fires choose
18399 * @chainable
18400 */
18401 OO.ui.SelectWidget.prototype.chooseItem = function ( item ) {
18402 this.selectItem( item );
18403 this.emit( 'choose', item );
18404
18405 return this;
18406 };
18407
18408 /**
18409 * Get an option by its position relative to the specified item (or to the start of the option array,
18410 * if item is `null`). The direction in which to search through the option array is specified with a
18411 * number: -1 for reverse (the default) or 1 for forward. The method will return an option, or
18412 * `null` if there are no options in the array.
18413 *
18414 * @param {OO.ui.OptionWidget|null} item Item to describe the start position, or `null` to start at the beginning of the array.
18415 * @param {number} direction Direction to move in: -1 to move backward, 1 to move forward
18416 * @param {Function} filter Only consider items for which this function returns
18417 * true. Function takes an OO.ui.OptionWidget and returns a boolean.
18418 * @return {OO.ui.OptionWidget|null} Item at position, `null` if there are no items in the select
18419 */
18420 OO.ui.SelectWidget.prototype.getRelativeSelectableItem = function ( item, direction, filter ) {
18421 var currentIndex, nextIndex, i,
18422 increase = direction > 0 ? 1 : -1,
18423 len = this.items.length;
18424
18425 if ( !$.isFunction( filter ) ) {
18426 filter = OO.ui.SelectWidget.static.passAllFilter;
18427 }
18428
18429 if ( item instanceof OO.ui.OptionWidget ) {
18430 currentIndex = this.items.indexOf( item );
18431 nextIndex = ( currentIndex + increase + len ) % len;
18432 } else {
18433 // If no item is selected and moving forward, start at the beginning.
18434 // If moving backward, start at the end.
18435 nextIndex = direction > 0 ? 0 : len - 1;
18436 }
18437
18438 for ( i = 0; i < len; i++ ) {
18439 item = this.items[ nextIndex ];
18440 if ( item instanceof OO.ui.OptionWidget && item.isSelectable() && filter( item ) ) {
18441 return item;
18442 }
18443 nextIndex = ( nextIndex + increase + len ) % len;
18444 }
18445 return null;
18446 };
18447
18448 /**
18449 * Get the next selectable item or `null` if there are no selectable items.
18450 * Disabled options and menu-section markers and breaks are not selectable.
18451 *
18452 * @return {OO.ui.OptionWidget|null} Item, `null` if there aren't any selectable items
18453 */
18454 OO.ui.SelectWidget.prototype.getFirstSelectableItem = function () {
18455 var i, len, item;
18456
18457 for ( i = 0, len = this.items.length; i < len; i++ ) {
18458 item = this.items[ i ];
18459 if ( item instanceof OO.ui.OptionWidget && item.isSelectable() ) {
18460 return item;
18461 }
18462 }
18463
18464 return null;
18465 };
18466
18467 /**
18468 * Add an array of options to the select. Optionally, an index number can be used to
18469 * specify an insertion point.
18470 *
18471 * @param {OO.ui.OptionWidget[]} items Items to add
18472 * @param {number} [index] Index to insert items after
18473 * @fires add
18474 * @chainable
18475 */
18476 OO.ui.SelectWidget.prototype.addItems = function ( items, index ) {
18477 // Mixin method
18478 OO.ui.mixin.GroupWidget.prototype.addItems.call( this, items, index );
18479
18480 // Always provide an index, even if it was omitted
18481 this.emit( 'add', items, index === undefined ? this.items.length - items.length - 1 : index );
18482
18483 return this;
18484 };
18485
18486 /**
18487 * Remove the specified array of options from the select. Options will be detached
18488 * from the DOM, not removed, so they can be reused later. To remove all options from
18489 * the select, you may wish to use the #clearItems method instead.
18490 *
18491 * @param {OO.ui.OptionWidget[]} items Items to remove
18492 * @fires remove
18493 * @chainable
18494 */
18495 OO.ui.SelectWidget.prototype.removeItems = function ( items ) {
18496 var i, len, item;
18497
18498 // Deselect items being removed
18499 for ( i = 0, len = items.length; i < len; i++ ) {
18500 item = items[ i ];
18501 if ( item.isSelected() ) {
18502 this.selectItem( null );
18503 }
18504 }
18505
18506 // Mixin method
18507 OO.ui.mixin.GroupWidget.prototype.removeItems.call( this, items );
18508
18509 this.emit( 'remove', items );
18510
18511 return this;
18512 };
18513
18514 /**
18515 * Clear all options from the select. Options will be detached from the DOM, not removed,
18516 * so that they can be reused later. To remove a subset of options from the select, use
18517 * the #removeItems method.
18518 *
18519 * @fires remove
18520 * @chainable
18521 */
18522 OO.ui.SelectWidget.prototype.clearItems = function () {
18523 var items = this.items.slice();
18524
18525 // Mixin method
18526 OO.ui.mixin.GroupWidget.prototype.clearItems.call( this );
18527
18528 // Clear selection
18529 this.selectItem( null );
18530
18531 this.emit( 'remove', items );
18532
18533 return this;
18534 };
18535
18536 /**
18537 * ButtonSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains
18538 * button options and is used together with
18539 * OO.ui.ButtonOptionWidget. The ButtonSelectWidget provides an interface for
18540 * highlighting, choosing, and selecting mutually exclusive options. Please see
18541 * the [OOjs UI documentation on MediaWiki] [1] for more information.
18542 *
18543 * @example
18544 * // Example: A ButtonSelectWidget that contains three ButtonOptionWidgets
18545 * var option1 = new OO.ui.ButtonOptionWidget( {
18546 * data: 1,
18547 * label: 'Option 1',
18548 * title: 'Button option 1'
18549 * } );
18550 *
18551 * var option2 = new OO.ui.ButtonOptionWidget( {
18552 * data: 2,
18553 * label: 'Option 2',
18554 * title: 'Button option 2'
18555 * } );
18556 *
18557 * var option3 = new OO.ui.ButtonOptionWidget( {
18558 * data: 3,
18559 * label: 'Option 3',
18560 * title: 'Button option 3'
18561 * } );
18562 *
18563 * var buttonSelect=new OO.ui.ButtonSelectWidget( {
18564 * items: [ option1, option2, option3 ]
18565 * } );
18566 * $( 'body' ).append( buttonSelect.$element );
18567 *
18568 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
18569 *
18570 * @class
18571 * @extends OO.ui.SelectWidget
18572 * @mixins OO.ui.mixin.TabIndexedElement
18573 *
18574 * @constructor
18575 * @param {Object} [config] Configuration options
18576 */
18577 OO.ui.ButtonSelectWidget = function OoUiButtonSelectWidget( config ) {
18578 // Parent constructor
18579 OO.ui.ButtonSelectWidget.parent.call( this, config );
18580
18581 // Mixin constructors
18582 OO.ui.mixin.TabIndexedElement.call( this, config );
18583
18584 // Events
18585 this.$element.on( {
18586 focus: this.bindKeyDownListener.bind( this ),
18587 blur: this.unbindKeyDownListener.bind( this )
18588 } );
18589
18590 // Initialization
18591 this.$element.addClass( 'oo-ui-buttonSelectWidget' );
18592 };
18593
18594 /* Setup */
18595
18596 OO.inheritClass( OO.ui.ButtonSelectWidget, OO.ui.SelectWidget );
18597 OO.mixinClass( OO.ui.ButtonSelectWidget, OO.ui.mixin.TabIndexedElement );
18598
18599 /**
18600 * RadioSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains radio
18601 * options and is used together with OO.ui.RadioOptionWidget. The RadioSelectWidget provides
18602 * an interface for adding, removing and selecting options.
18603 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
18604 *
18605 * If you want to use this within a HTML form, such as a OO.ui.FormLayout, use
18606 * OO.ui.RadioSelectInputWidget instead.
18607 *
18608 * @example
18609 * // A RadioSelectWidget with RadioOptions.
18610 * var option1 = new OO.ui.RadioOptionWidget( {
18611 * data: 'a',
18612 * label: 'Selected radio option'
18613 * } );
18614 *
18615 * var option2 = new OO.ui.RadioOptionWidget( {
18616 * data: 'b',
18617 * label: 'Unselected radio option'
18618 * } );
18619 *
18620 * var radioSelect=new OO.ui.RadioSelectWidget( {
18621 * items: [ option1, option2 ]
18622 * } );
18623 *
18624 * // Select 'option 1' using the RadioSelectWidget's selectItem() method.
18625 * radioSelect.selectItem( option1 );
18626 *
18627 * $( 'body' ).append( radioSelect.$element );
18628 *
18629 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
18630
18631 *
18632 * @class
18633 * @extends OO.ui.SelectWidget
18634 * @mixins OO.ui.mixin.TabIndexedElement
18635 *
18636 * @constructor
18637 * @param {Object} [config] Configuration options
18638 */
18639 OO.ui.RadioSelectWidget = function OoUiRadioSelectWidget( config ) {
18640 // Parent constructor
18641 OO.ui.RadioSelectWidget.parent.call( this, config );
18642
18643 // Mixin constructors
18644 OO.ui.mixin.TabIndexedElement.call( this, config );
18645
18646 // Events
18647 this.$element.on( {
18648 focus: this.bindKeyDownListener.bind( this ),
18649 blur: this.unbindKeyDownListener.bind( this )
18650 } );
18651
18652 // Initialization
18653 this.$element
18654 .addClass( 'oo-ui-radioSelectWidget' )
18655 .attr( 'role', 'radiogroup' );
18656 };
18657
18658 /* Setup */
18659
18660 OO.inheritClass( OO.ui.RadioSelectWidget, OO.ui.SelectWidget );
18661 OO.mixinClass( OO.ui.RadioSelectWidget, OO.ui.mixin.TabIndexedElement );
18662
18663 /**
18664 * MenuSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains options and
18665 * is used together with OO.ui.MenuOptionWidget. It is designed be used as part of another widget.
18666 * See {@link OO.ui.DropdownWidget DropdownWidget}, {@link OO.ui.ComboBoxWidget ComboBoxWidget},
18667 * and {@link OO.ui.mixin.LookupElement LookupElement} for examples of widgets that contain menus.
18668 * MenuSelectWidgets themselves are not instantiated directly, rather subclassed
18669 * and customized to be opened, closed, and displayed as needed.
18670 *
18671 * By default, menus are clipped to the visible viewport and are not visible when a user presses the
18672 * mouse outside the menu.
18673 *
18674 * Menus also have support for keyboard interaction:
18675 *
18676 * - Enter/Return key: choose and select a menu option
18677 * - Up-arrow key: highlight the previous menu option
18678 * - Down-arrow key: highlight the next menu option
18679 * - Esc key: hide the menu
18680 *
18681 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
18682 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
18683 *
18684 * @class
18685 * @extends OO.ui.SelectWidget
18686 * @mixins OO.ui.mixin.ClippableElement
18687 *
18688 * @constructor
18689 * @param {Object} [config] Configuration options
18690 * @cfg {OO.ui.TextInputWidget} [input] Text input used to implement option highlighting for menu items that match
18691 * the text the user types. This config is used by {@link OO.ui.ComboBoxWidget ComboBoxWidget}
18692 * and {@link OO.ui.mixin.LookupElement LookupElement}
18693 * @cfg {jQuery} [$input] Text input used to implement option highlighting for menu items that match
18694 * the text the user types. This config is used by {@link OO.ui.CapsuleMultiSelectWidget CapsuleMultiSelectWidget}
18695 * @cfg {OO.ui.Widget} [widget] Widget associated with the menu's active state. If the user clicks the mouse
18696 * anywhere on the page outside of this widget, the menu is hidden. For example, if there is a button
18697 * that toggles the menu's visibility on click, the menu will be hidden then re-shown when the user clicks
18698 * that button, unless the button (or its parent widget) is passed in here.
18699 * @cfg {boolean} [autoHide=true] Hide the menu when the mouse is pressed outside the menu.
18700 * @cfg {boolean} [filterFromInput=false] Filter the displayed options from the input
18701 */
18702 OO.ui.MenuSelectWidget = function OoUiMenuSelectWidget( config ) {
18703 // Configuration initialization
18704 config = config || {};
18705
18706 // Parent constructor
18707 OO.ui.MenuSelectWidget.parent.call( this, config );
18708
18709 // Mixin constructors
18710 OO.ui.mixin.ClippableElement.call( this, $.extend( {}, config, { $clippable: this.$group } ) );
18711
18712 // Properties
18713 this.newItems = null;
18714 this.autoHide = config.autoHide === undefined || !!config.autoHide;
18715 this.filterFromInput = !!config.filterFromInput;
18716 this.$input = config.$input ? config.$input : config.input ? config.input.$input : null;
18717 this.$widget = config.widget ? config.widget.$element : null;
18718 this.onDocumentMouseDownHandler = this.onDocumentMouseDown.bind( this );
18719 this.onInputEditHandler = OO.ui.debounce( this.updateItemVisibility.bind( this ), 100 );
18720
18721 // Initialization
18722 this.$element
18723 .addClass( 'oo-ui-menuSelectWidget' )
18724 .attr( 'role', 'menu' );
18725
18726 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
18727 // that reference properties not initialized at that time of parent class construction
18728 // TODO: Find a better way to handle post-constructor setup
18729 this.visible = false;
18730 this.$element.addClass( 'oo-ui-element-hidden' );
18731 };
18732
18733 /* Setup */
18734
18735 OO.inheritClass( OO.ui.MenuSelectWidget, OO.ui.SelectWidget );
18736 OO.mixinClass( OO.ui.MenuSelectWidget, OO.ui.mixin.ClippableElement );
18737
18738 /* Methods */
18739
18740 /**
18741 * Handles document mouse down events.
18742 *
18743 * @protected
18744 * @param {jQuery.Event} e Key down event
18745 */
18746 OO.ui.MenuSelectWidget.prototype.onDocumentMouseDown = function ( e ) {
18747 if (
18748 !OO.ui.contains( this.$element[ 0 ], e.target, true ) &&
18749 ( !this.$widget || !OO.ui.contains( this.$widget[ 0 ], e.target, true ) )
18750 ) {
18751 this.toggle( false );
18752 }
18753 };
18754
18755 /**
18756 * @inheritdoc
18757 */
18758 OO.ui.MenuSelectWidget.prototype.onKeyDown = function ( e ) {
18759 var currentItem = this.getHighlightedItem() || this.getSelectedItem();
18760
18761 if ( !this.isDisabled() && this.isVisible() ) {
18762 switch ( e.keyCode ) {
18763 case OO.ui.Keys.LEFT:
18764 case OO.ui.Keys.RIGHT:
18765 // Do nothing if a text field is associated, arrow keys will be handled natively
18766 if ( !this.$input ) {
18767 OO.ui.MenuSelectWidget.parent.prototype.onKeyDown.call( this, e );
18768 }
18769 break;
18770 case OO.ui.Keys.ESCAPE:
18771 case OO.ui.Keys.TAB:
18772 if ( currentItem ) {
18773 currentItem.setHighlighted( false );
18774 }
18775 this.toggle( false );
18776 // Don't prevent tabbing away, prevent defocusing
18777 if ( e.keyCode === OO.ui.Keys.ESCAPE ) {
18778 e.preventDefault();
18779 e.stopPropagation();
18780 }
18781 break;
18782 default:
18783 OO.ui.MenuSelectWidget.parent.prototype.onKeyDown.call( this, e );
18784 return;
18785 }
18786 }
18787 };
18788
18789 /**
18790 * Update menu item visibility after input changes.
18791 * @protected
18792 */
18793 OO.ui.MenuSelectWidget.prototype.updateItemVisibility = function () {
18794 var i, item,
18795 len = this.items.length,
18796 showAll = !this.isVisible(),
18797 filter = showAll ? null : this.getItemMatcher( this.$input.val() );
18798
18799 for ( i = 0; i < len; i++ ) {
18800 item = this.items[ i ];
18801 if ( item instanceof OO.ui.OptionWidget ) {
18802 item.toggle( showAll || filter( item ) );
18803 }
18804 }
18805
18806 // Reevaluate clipping
18807 this.clip();
18808 };
18809
18810 /**
18811 * @inheritdoc
18812 */
18813 OO.ui.MenuSelectWidget.prototype.bindKeyDownListener = function () {
18814 if ( this.$input ) {
18815 this.$input.on( 'keydown', this.onKeyDownHandler );
18816 } else {
18817 OO.ui.MenuSelectWidget.parent.prototype.bindKeyDownListener.call( this );
18818 }
18819 };
18820
18821 /**
18822 * @inheritdoc
18823 */
18824 OO.ui.MenuSelectWidget.prototype.unbindKeyDownListener = function () {
18825 if ( this.$input ) {
18826 this.$input.off( 'keydown', this.onKeyDownHandler );
18827 } else {
18828 OO.ui.MenuSelectWidget.parent.prototype.unbindKeyDownListener.call( this );
18829 }
18830 };
18831
18832 /**
18833 * @inheritdoc
18834 */
18835 OO.ui.MenuSelectWidget.prototype.bindKeyPressListener = function () {
18836 if ( this.$input ) {
18837 if ( this.filterFromInput ) {
18838 this.$input.on( 'keydown mouseup cut paste change input select', this.onInputEditHandler );
18839 }
18840 } else {
18841 OO.ui.MenuSelectWidget.parent.prototype.bindKeyPressListener.call( this );
18842 }
18843 };
18844
18845 /**
18846 * @inheritdoc
18847 */
18848 OO.ui.MenuSelectWidget.prototype.unbindKeyPressListener = function () {
18849 if ( this.$input ) {
18850 if ( this.filterFromInput ) {
18851 this.$input.off( 'keydown mouseup cut paste change input select', this.onInputEditHandler );
18852 this.updateItemVisibility();
18853 }
18854 } else {
18855 OO.ui.MenuSelectWidget.parent.prototype.unbindKeyPressListener.call( this );
18856 }
18857 };
18858
18859 /**
18860 * Choose an item.
18861 *
18862 * When a user chooses an item, the menu is closed.
18863 *
18864 * Note that ‘choose’ should never be modified programmatically. A user can choose an option with the keyboard
18865 * or mouse and it becomes selected. To select an item programmatically, use the #selectItem method.
18866 * @param {OO.ui.OptionWidget} item Item to choose
18867 * @chainable
18868 */
18869 OO.ui.MenuSelectWidget.prototype.chooseItem = function ( item ) {
18870 OO.ui.MenuSelectWidget.parent.prototype.chooseItem.call( this, item );
18871 this.toggle( false );
18872 return this;
18873 };
18874
18875 /**
18876 * @inheritdoc
18877 */
18878 OO.ui.MenuSelectWidget.prototype.addItems = function ( items, index ) {
18879 var i, len, item;
18880
18881 // Parent method
18882 OO.ui.MenuSelectWidget.parent.prototype.addItems.call( this, items, index );
18883
18884 // Auto-initialize
18885 if ( !this.newItems ) {
18886 this.newItems = [];
18887 }
18888
18889 for ( i = 0, len = items.length; i < len; i++ ) {
18890 item = items[ i ];
18891 if ( this.isVisible() ) {
18892 // Defer fitting label until item has been attached
18893 item.fitLabel();
18894 } else {
18895 this.newItems.push( item );
18896 }
18897 }
18898
18899 // Reevaluate clipping
18900 this.clip();
18901
18902 return this;
18903 };
18904
18905 /**
18906 * @inheritdoc
18907 */
18908 OO.ui.MenuSelectWidget.prototype.removeItems = function ( items ) {
18909 // Parent method
18910 OO.ui.MenuSelectWidget.parent.prototype.removeItems.call( this, items );
18911
18912 // Reevaluate clipping
18913 this.clip();
18914
18915 return this;
18916 };
18917
18918 /**
18919 * @inheritdoc
18920 */
18921 OO.ui.MenuSelectWidget.prototype.clearItems = function () {
18922 // Parent method
18923 OO.ui.MenuSelectWidget.parent.prototype.clearItems.call( this );
18924
18925 // Reevaluate clipping
18926 this.clip();
18927
18928 return this;
18929 };
18930
18931 /**
18932 * @inheritdoc
18933 */
18934 OO.ui.MenuSelectWidget.prototype.toggle = function ( visible ) {
18935 var i, len, change;
18936
18937 visible = ( visible === undefined ? !this.visible : !!visible ) && !!this.items.length;
18938 change = visible !== this.isVisible();
18939
18940 // Parent method
18941 OO.ui.MenuSelectWidget.parent.prototype.toggle.call( this, visible );
18942
18943 if ( change ) {
18944 if ( visible ) {
18945 this.bindKeyDownListener();
18946 this.bindKeyPressListener();
18947
18948 if ( this.newItems && this.newItems.length ) {
18949 for ( i = 0, len = this.newItems.length; i < len; i++ ) {
18950 this.newItems[ i ].fitLabel();
18951 }
18952 this.newItems = null;
18953 }
18954 this.toggleClipping( true );
18955
18956 // Auto-hide
18957 if ( this.autoHide ) {
18958 OO.ui.addCaptureEventListener( this.getElementDocument(), 'mousedown', this.onDocumentMouseDownHandler );
18959 }
18960 } else {
18961 this.unbindKeyDownListener();
18962 this.unbindKeyPressListener();
18963 OO.ui.removeCaptureEventListener( this.getElementDocument(), 'mousedown', this.onDocumentMouseDownHandler );
18964 this.toggleClipping( false );
18965 }
18966 }
18967
18968 return this;
18969 };
18970
18971 /**
18972 * FloatingMenuSelectWidget is a menu that will stick under a specified
18973 * container, even when it is inserted elsewhere in the document (for example,
18974 * in a OO.ui.Window's $overlay). This is sometimes necessary to prevent the
18975 * menu from being clipped too aggresively.
18976 *
18977 * The menu's position is automatically calculated and maintained when the menu
18978 * is toggled or the window is resized.
18979 *
18980 * See OO.ui.ComboBoxWidget for an example of a widget that uses this class.
18981 *
18982 * @class
18983 * @extends OO.ui.MenuSelectWidget
18984 * @mixins OO.ui.mixin.FloatableElement
18985 *
18986 * @constructor
18987 * @param {OO.ui.Widget} [inputWidget] Widget to provide the menu for.
18988 * Deprecated, omit this parameter and specify `$container` instead.
18989 * @param {Object} [config] Configuration options
18990 * @cfg {jQuery} [$container=inputWidget.$element] Element to render menu under
18991 */
18992 OO.ui.FloatingMenuSelectWidget = function OoUiFloatingMenuSelectWidget( inputWidget, config ) {
18993 // Allow 'inputWidget' parameter and config for backwards compatibility
18994 if ( OO.isPlainObject( inputWidget ) && config === undefined ) {
18995 config = inputWidget;
18996 inputWidget = config.inputWidget;
18997 }
18998
18999 // Configuration initialization
19000 config = config || {};
19001
19002 // Parent constructor
19003 OO.ui.FloatingMenuSelectWidget.parent.call( this, config );
19004
19005 // Properties (must be set before mixin constructors)
19006 this.inputWidget = inputWidget; // For backwards compatibility
19007 this.$container = config.$container || this.inputWidget.$element;
19008
19009 // Mixins constructors
19010 OO.ui.mixin.FloatableElement.call( this, $.extend( {}, config, { $floatableContainer: this.$container } ) );
19011
19012 // Initialization
19013 this.$element.addClass( 'oo-ui-floatingMenuSelectWidget' );
19014 // For backwards compatibility
19015 this.$element.addClass( 'oo-ui-textInputMenuSelectWidget' );
19016 };
19017
19018 /* Setup */
19019
19020 OO.inheritClass( OO.ui.FloatingMenuSelectWidget, OO.ui.MenuSelectWidget );
19021 OO.mixinClass( OO.ui.FloatingMenuSelectWidget, OO.ui.mixin.FloatableElement );
19022
19023 // For backwards compatibility
19024 OO.ui.TextInputMenuSelectWidget = OO.ui.FloatingMenuSelectWidget;
19025
19026 /* Methods */
19027
19028 /**
19029 * @inheritdoc
19030 */
19031 OO.ui.FloatingMenuSelectWidget.prototype.toggle = function ( visible ) {
19032 var change;
19033 visible = visible === undefined ? !this.isVisible() : !!visible;
19034 change = visible !== this.isVisible();
19035
19036 if ( change && visible ) {
19037 // Make sure the width is set before the parent method runs.
19038 this.setIdealSize( this.$container.width() );
19039 }
19040
19041 // Parent method
19042 // This will call this.clip(), which is nonsensical since we're not positioned yet...
19043 OO.ui.FloatingMenuSelectWidget.parent.prototype.toggle.call( this, visible );
19044
19045 if ( change ) {
19046 this.togglePositioning( this.isVisible() );
19047 }
19048
19049 return this;
19050 };
19051
19052 /**
19053 * OutlineSelectWidget is a structured list that contains {@link OO.ui.OutlineOptionWidget outline options}
19054 * A set of controls can be provided with an {@link OO.ui.OutlineControlsWidget outline controls} widget.
19055 *
19056 * **Currently, this class is only used by {@link OO.ui.BookletLayout booklet layouts}.**
19057 *
19058 * @class
19059 * @extends OO.ui.SelectWidget
19060 * @mixins OO.ui.mixin.TabIndexedElement
19061 *
19062 * @constructor
19063 * @param {Object} [config] Configuration options
19064 */
19065 OO.ui.OutlineSelectWidget = function OoUiOutlineSelectWidget( config ) {
19066 // Parent constructor
19067 OO.ui.OutlineSelectWidget.parent.call( this, config );
19068
19069 // Mixin constructors
19070 OO.ui.mixin.TabIndexedElement.call( this, config );
19071
19072 // Events
19073 this.$element.on( {
19074 focus: this.bindKeyDownListener.bind( this ),
19075 blur: this.unbindKeyDownListener.bind( this )
19076 } );
19077
19078 // Initialization
19079 this.$element.addClass( 'oo-ui-outlineSelectWidget' );
19080 };
19081
19082 /* Setup */
19083
19084 OO.inheritClass( OO.ui.OutlineSelectWidget, OO.ui.SelectWidget );
19085 OO.mixinClass( OO.ui.OutlineSelectWidget, OO.ui.mixin.TabIndexedElement );
19086
19087 /**
19088 * TabSelectWidget is a list that contains {@link OO.ui.TabOptionWidget tab options}
19089 *
19090 * **Currently, this class is only used by {@link OO.ui.IndexLayout index layouts}.**
19091 *
19092 * @class
19093 * @extends OO.ui.SelectWidget
19094 * @mixins OO.ui.mixin.TabIndexedElement
19095 *
19096 * @constructor
19097 * @param {Object} [config] Configuration options
19098 */
19099 OO.ui.TabSelectWidget = function OoUiTabSelectWidget( config ) {
19100 // Parent constructor
19101 OO.ui.TabSelectWidget.parent.call( this, config );
19102
19103 // Mixin constructors
19104 OO.ui.mixin.TabIndexedElement.call( this, config );
19105
19106 // Events
19107 this.$element.on( {
19108 focus: this.bindKeyDownListener.bind( this ),
19109 blur: this.unbindKeyDownListener.bind( this )
19110 } );
19111
19112 // Initialization
19113 this.$element.addClass( 'oo-ui-tabSelectWidget' );
19114 };
19115
19116 /* Setup */
19117
19118 OO.inheritClass( OO.ui.TabSelectWidget, OO.ui.SelectWidget );
19119 OO.mixinClass( OO.ui.TabSelectWidget, OO.ui.mixin.TabIndexedElement );
19120
19121 /**
19122 * NumberInputWidgets combine a {@link OO.ui.TextInputWidget text input} (where a value
19123 * can be entered manually) and two {@link OO.ui.ButtonWidget button widgets}
19124 * (to adjust the value in increments) to allow the user to enter a number.
19125 *
19126 * @example
19127 * // Example: A NumberInputWidget.
19128 * var numberInput = new OO.ui.NumberInputWidget( {
19129 * label: 'NumberInputWidget',
19130 * input: { value: 5, min: 1, max: 10 }
19131 * } );
19132 * $( 'body' ).append( numberInput.$element );
19133 *
19134 * @class
19135 * @extends OO.ui.Widget
19136 *
19137 * @constructor
19138 * @param {Object} [config] Configuration options
19139 * @cfg {Object} [input] Configuration options to pass to the {@link OO.ui.TextInputWidget text input widget}.
19140 * @cfg {Object} [minusButton] Configuration options to pass to the {@link OO.ui.ButtonWidget decrementing button widget}.
19141 * @cfg {Object} [plusButton] Configuration options to pass to the {@link OO.ui.ButtonWidget incrementing button widget}.
19142 * @cfg {boolean} [isInteger=false] Whether the field accepts only integer values.
19143 * @cfg {number} [min=-Infinity] Minimum allowed value
19144 * @cfg {number} [max=Infinity] Maximum allowed value
19145 * @cfg {number} [step=1] Delta when using the buttons or up/down arrow keys
19146 * @cfg {number|null} [pageStep] Delta when using the page-up/page-down keys. Defaults to 10 times #step.
19147 */
19148 OO.ui.NumberInputWidget = function OoUiNumberInputWidget( config ) {
19149 // Configuration initialization
19150 config = $.extend( {
19151 isInteger: false,
19152 min: -Infinity,
19153 max: Infinity,
19154 step: 1,
19155 pageStep: null
19156 }, config );
19157
19158 // Parent constructor
19159 OO.ui.NumberInputWidget.parent.call( this, config );
19160
19161 // Properties
19162 this.input = new OO.ui.TextInputWidget( $.extend(
19163 {
19164 disabled: this.isDisabled()
19165 },
19166 config.input
19167 ) );
19168 this.minusButton = new OO.ui.ButtonWidget( $.extend(
19169 {
19170 disabled: this.isDisabled(),
19171 tabIndex: -1
19172 },
19173 config.minusButton,
19174 {
19175 classes: [ 'oo-ui-numberInputWidget-minusButton' ],
19176 label: '−'
19177 }
19178 ) );
19179 this.plusButton = new OO.ui.ButtonWidget( $.extend(
19180 {
19181 disabled: this.isDisabled(),
19182 tabIndex: -1
19183 },
19184 config.plusButton,
19185 {
19186 classes: [ 'oo-ui-numberInputWidget-plusButton' ],
19187 label: '+'
19188 }
19189 ) );
19190
19191 // Events
19192 this.input.connect( this, {
19193 change: this.emit.bind( this, 'change' ),
19194 enter: this.emit.bind( this, 'enter' )
19195 } );
19196 this.input.$input.on( {
19197 keydown: this.onKeyDown.bind( this ),
19198 'wheel mousewheel DOMMouseScroll': this.onWheel.bind( this )
19199 } );
19200 this.plusButton.connect( this, {
19201 click: [ 'onButtonClick', +1 ]
19202 } );
19203 this.minusButton.connect( this, {
19204 click: [ 'onButtonClick', -1 ]
19205 } );
19206
19207 // Initialization
19208 this.setIsInteger( !!config.isInteger );
19209 this.setRange( config.min, config.max );
19210 this.setStep( config.step, config.pageStep );
19211
19212 this.$field = $( '<div>' ).addClass( 'oo-ui-numberInputWidget-field' )
19213 .append(
19214 this.minusButton.$element,
19215 this.input.$element,
19216 this.plusButton.$element
19217 );
19218 this.$element.addClass( 'oo-ui-numberInputWidget' ).append( this.$field );
19219 this.input.setValidation( this.validateNumber.bind( this ) );
19220 };
19221
19222 /* Setup */
19223
19224 OO.inheritClass( OO.ui.NumberInputWidget, OO.ui.Widget );
19225
19226 /* Events */
19227
19228 /**
19229 * A `change` event is emitted when the value of the input changes.
19230 *
19231 * @event change
19232 */
19233
19234 /**
19235 * An `enter` event is emitted when the user presses 'enter' inside the text box.
19236 *
19237 * @event enter
19238 */
19239
19240 /* Methods */
19241
19242 /**
19243 * Set whether only integers are allowed
19244 * @param {boolean} flag
19245 */
19246 OO.ui.NumberInputWidget.prototype.setIsInteger = function ( flag ) {
19247 this.isInteger = !!flag;
19248 this.input.setValidityFlag();
19249 };
19250
19251 /**
19252 * Get whether only integers are allowed
19253 * @return {boolean} Flag value
19254 */
19255 OO.ui.NumberInputWidget.prototype.getIsInteger = function () {
19256 return this.isInteger;
19257 };
19258
19259 /**
19260 * Set the range of allowed values
19261 * @param {number} min Minimum allowed value
19262 * @param {number} max Maximum allowed value
19263 */
19264 OO.ui.NumberInputWidget.prototype.setRange = function ( min, max ) {
19265 if ( min > max ) {
19266 throw new Error( 'Minimum (' + min + ') must not be greater than maximum (' + max + ')' );
19267 }
19268 this.min = min;
19269 this.max = max;
19270 this.input.setValidityFlag();
19271 };
19272
19273 /**
19274 * Get the current range
19275 * @return {number[]} Minimum and maximum values
19276 */
19277 OO.ui.NumberInputWidget.prototype.getRange = function () {
19278 return [ this.min, this.max ];
19279 };
19280
19281 /**
19282 * Set the stepping deltas
19283 * @param {number} step Normal step
19284 * @param {number|null} pageStep Page step. If null, 10 * step will be used.
19285 */
19286 OO.ui.NumberInputWidget.prototype.setStep = function ( step, pageStep ) {
19287 if ( step <= 0 ) {
19288 throw new Error( 'Step value must be positive' );
19289 }
19290 if ( pageStep === null ) {
19291 pageStep = step * 10;
19292 } else if ( pageStep <= 0 ) {
19293 throw new Error( 'Page step value must be positive' );
19294 }
19295 this.step = step;
19296 this.pageStep = pageStep;
19297 };
19298
19299 /**
19300 * Get the current stepping values
19301 * @return {number[]} Step and page step
19302 */
19303 OO.ui.NumberInputWidget.prototype.getStep = function () {
19304 return [ this.step, this.pageStep ];
19305 };
19306
19307 /**
19308 * Get the current value of the widget
19309 * @return {string}
19310 */
19311 OO.ui.NumberInputWidget.prototype.getValue = function () {
19312 return this.input.getValue();
19313 };
19314
19315 /**
19316 * Get the current value of the widget as a number
19317 * @return {number} May be NaN, or an invalid number
19318 */
19319 OO.ui.NumberInputWidget.prototype.getNumericValue = function () {
19320 return +this.input.getValue();
19321 };
19322
19323 /**
19324 * Set the value of the widget
19325 * @param {string} value Invalid values are allowed
19326 */
19327 OO.ui.NumberInputWidget.prototype.setValue = function ( value ) {
19328 this.input.setValue( value );
19329 };
19330
19331 /**
19332 * Adjust the value of the widget
19333 * @param {number} delta Adjustment amount
19334 */
19335 OO.ui.NumberInputWidget.prototype.adjustValue = function ( delta ) {
19336 var n, v = this.getNumericValue();
19337
19338 delta = +delta;
19339 if ( isNaN( delta ) || !isFinite( delta ) ) {
19340 throw new Error( 'Delta must be a finite number' );
19341 }
19342
19343 if ( isNaN( v ) ) {
19344 n = 0;
19345 } else {
19346 n = v + delta;
19347 n = Math.max( Math.min( n, this.max ), this.min );
19348 if ( this.isInteger ) {
19349 n = Math.round( n );
19350 }
19351 }
19352
19353 if ( n !== v ) {
19354 this.setValue( n );
19355 }
19356 };
19357
19358 /**
19359 * Validate input
19360 * @private
19361 * @param {string} value Field value
19362 * @return {boolean}
19363 */
19364 OO.ui.NumberInputWidget.prototype.validateNumber = function ( value ) {
19365 var n = +value;
19366 if ( isNaN( n ) || !isFinite( n ) ) {
19367 return false;
19368 }
19369
19370 /*jshint bitwise: false */
19371 if ( this.isInteger && ( n | 0 ) !== n ) {
19372 return false;
19373 }
19374 /*jshint bitwise: true */
19375
19376 if ( n < this.min || n > this.max ) {
19377 return false;
19378 }
19379
19380 return true;
19381 };
19382
19383 /**
19384 * Handle mouse click events.
19385 *
19386 * @private
19387 * @param {number} dir +1 or -1
19388 */
19389 OO.ui.NumberInputWidget.prototype.onButtonClick = function ( dir ) {
19390 this.adjustValue( dir * this.step );
19391 };
19392
19393 /**
19394 * Handle mouse wheel events.
19395 *
19396 * @private
19397 * @param {jQuery.Event} event
19398 */
19399 OO.ui.NumberInputWidget.prototype.onWheel = function ( event ) {
19400 var delta = 0;
19401
19402 // Standard 'wheel' event
19403 if ( event.originalEvent.deltaMode !== undefined ) {
19404 this.sawWheelEvent = true;
19405 }
19406 if ( event.originalEvent.deltaY ) {
19407 delta = -event.originalEvent.deltaY;
19408 } else if ( event.originalEvent.deltaX ) {
19409 delta = event.originalEvent.deltaX;
19410 }
19411
19412 // Non-standard events
19413 if ( !this.sawWheelEvent ) {
19414 if ( event.originalEvent.wheelDeltaX ) {
19415 delta = -event.originalEvent.wheelDeltaX;
19416 } else if ( event.originalEvent.wheelDeltaY ) {
19417 delta = event.originalEvent.wheelDeltaY;
19418 } else if ( event.originalEvent.wheelDelta ) {
19419 delta = event.originalEvent.wheelDelta;
19420 } else if ( event.originalEvent.detail ) {
19421 delta = -event.originalEvent.detail;
19422 }
19423 }
19424
19425 if ( delta ) {
19426 delta = delta < 0 ? -1 : 1;
19427 this.adjustValue( delta * this.step );
19428 }
19429
19430 return false;
19431 };
19432
19433 /**
19434 * Handle key down events.
19435 *
19436 * @private
19437 * @param {jQuery.Event} e Key down event
19438 */
19439 OO.ui.NumberInputWidget.prototype.onKeyDown = function ( e ) {
19440 if ( !this.isDisabled() ) {
19441 switch ( e.which ) {
19442 case OO.ui.Keys.UP:
19443 this.adjustValue( this.step );
19444 return false;
19445 case OO.ui.Keys.DOWN:
19446 this.adjustValue( -this.step );
19447 return false;
19448 case OO.ui.Keys.PAGEUP:
19449 this.adjustValue( this.pageStep );
19450 return false;
19451 case OO.ui.Keys.PAGEDOWN:
19452 this.adjustValue( -this.pageStep );
19453 return false;
19454 }
19455 }
19456 };
19457
19458 /**
19459 * @inheritdoc
19460 */
19461 OO.ui.NumberInputWidget.prototype.setDisabled = function ( disabled ) {
19462 // Parent method
19463 OO.ui.NumberInputWidget.parent.prototype.setDisabled.call( this, disabled );
19464
19465 if ( this.input ) {
19466 this.input.setDisabled( this.isDisabled() );
19467 }
19468 if ( this.minusButton ) {
19469 this.minusButton.setDisabled( this.isDisabled() );
19470 }
19471 if ( this.plusButton ) {
19472 this.plusButton.setDisabled( this.isDisabled() );
19473 }
19474
19475 return this;
19476 };
19477
19478 /**
19479 * ToggleSwitches are switches that slide on and off. Their state is represented by a Boolean
19480 * value (`true` for ‘on’, and `false` otherwise, the default). The ‘off’ state is represented
19481 * visually by a slider in the leftmost position.
19482 *
19483 * @example
19484 * // Toggle switches in the 'off' and 'on' position.
19485 * var toggleSwitch1 = new OO.ui.ToggleSwitchWidget();
19486 * var toggleSwitch2 = new OO.ui.ToggleSwitchWidget( {
19487 * value: true
19488 * } );
19489 *
19490 * // Create a FieldsetLayout to layout and label switches
19491 * var fieldset = new OO.ui.FieldsetLayout( {
19492 * label: 'Toggle switches'
19493 * } );
19494 * fieldset.addItems( [
19495 * new OO.ui.FieldLayout( toggleSwitch1, { label: 'Off', align: 'top' } ),
19496 * new OO.ui.FieldLayout( toggleSwitch2, { label: 'On', align: 'top' } )
19497 * ] );
19498 * $( 'body' ).append( fieldset.$element );
19499 *
19500 * @class
19501 * @extends OO.ui.ToggleWidget
19502 * @mixins OO.ui.mixin.TabIndexedElement
19503 *
19504 * @constructor
19505 * @param {Object} [config] Configuration options
19506 * @cfg {boolean} [value=false] The toggle switch’s initial on/off state.
19507 * By default, the toggle switch is in the 'off' position.
19508 */
19509 OO.ui.ToggleSwitchWidget = function OoUiToggleSwitchWidget( config ) {
19510 // Parent constructor
19511 OO.ui.ToggleSwitchWidget.parent.call( this, config );
19512
19513 // Mixin constructors
19514 OO.ui.mixin.TabIndexedElement.call( this, config );
19515
19516 // Properties
19517 this.dragging = false;
19518 this.dragStart = null;
19519 this.sliding = false;
19520 this.$glow = $( '<span>' );
19521 this.$grip = $( '<span>' );
19522
19523 // Events
19524 this.$element.on( {
19525 click: this.onClick.bind( this ),
19526 keypress: this.onKeyPress.bind( this )
19527 } );
19528
19529 // Initialization
19530 this.$glow.addClass( 'oo-ui-toggleSwitchWidget-glow' );
19531 this.$grip.addClass( 'oo-ui-toggleSwitchWidget-grip' );
19532 this.$element
19533 .addClass( 'oo-ui-toggleSwitchWidget' )
19534 .attr( 'role', 'checkbox' )
19535 .append( this.$glow, this.$grip );
19536 };
19537
19538 /* Setup */
19539
19540 OO.inheritClass( OO.ui.ToggleSwitchWidget, OO.ui.ToggleWidget );
19541 OO.mixinClass( OO.ui.ToggleSwitchWidget, OO.ui.mixin.TabIndexedElement );
19542
19543 /* Methods */
19544
19545 /**
19546 * Handle mouse click events.
19547 *
19548 * @private
19549 * @param {jQuery.Event} e Mouse click event
19550 */
19551 OO.ui.ToggleSwitchWidget.prototype.onClick = function ( e ) {
19552 if ( !this.isDisabled() && e.which === 1 ) {
19553 this.setValue( !this.value );
19554 }
19555 return false;
19556 };
19557
19558 /**
19559 * Handle key press events.
19560 *
19561 * @private
19562 * @param {jQuery.Event} e Key press event
19563 */
19564 OO.ui.ToggleSwitchWidget.prototype.onKeyPress = function ( e ) {
19565 if ( !this.isDisabled() && ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER ) ) {
19566 this.setValue( !this.value );
19567 return false;
19568 }
19569 };
19570
19571 /*!
19572 * Deprecated aliases for classes in the `OO.ui.mixin` namespace.
19573 */
19574
19575 /**
19576 * @inheritdoc OO.ui.mixin.ButtonElement
19577 * @deprecated Use {@link OO.ui.mixin.ButtonElement} instead.
19578 */
19579 OO.ui.ButtonElement = OO.ui.mixin.ButtonElement;
19580
19581 /**
19582 * @inheritdoc OO.ui.mixin.ClippableElement
19583 * @deprecated Use {@link OO.ui.mixin.ClippableElement} instead.
19584 */
19585 OO.ui.ClippableElement = OO.ui.mixin.ClippableElement;
19586
19587 /**
19588 * @inheritdoc OO.ui.mixin.DraggableElement
19589 * @deprecated Use {@link OO.ui.mixin.DraggableElement} instead.
19590 */
19591 OO.ui.DraggableElement = OO.ui.mixin.DraggableElement;
19592
19593 /**
19594 * @inheritdoc OO.ui.mixin.DraggableGroupElement
19595 * @deprecated Use {@link OO.ui.mixin.DraggableGroupElement} instead.
19596 */
19597 OO.ui.DraggableGroupElement = OO.ui.mixin.DraggableGroupElement;
19598
19599 /**
19600 * @inheritdoc OO.ui.mixin.FlaggedElement
19601 * @deprecated Use {@link OO.ui.mixin.FlaggedElement} instead.
19602 */
19603 OO.ui.FlaggedElement = OO.ui.mixin.FlaggedElement;
19604
19605 /**
19606 * @inheritdoc OO.ui.mixin.GroupElement
19607 * @deprecated Use {@link OO.ui.mixin.GroupElement} instead.
19608 */
19609 OO.ui.GroupElement = OO.ui.mixin.GroupElement;
19610
19611 /**
19612 * @inheritdoc OO.ui.mixin.GroupWidget
19613 * @deprecated Use {@link OO.ui.mixin.GroupWidget} instead.
19614 */
19615 OO.ui.GroupWidget = OO.ui.mixin.GroupWidget;
19616
19617 /**
19618 * @inheritdoc OO.ui.mixin.IconElement
19619 * @deprecated Use {@link OO.ui.mixin.IconElement} instead.
19620 */
19621 OO.ui.IconElement = OO.ui.mixin.IconElement;
19622
19623 /**
19624 * @inheritdoc OO.ui.mixin.IndicatorElement
19625 * @deprecated Use {@link OO.ui.mixin.IndicatorElement} instead.
19626 */
19627 OO.ui.IndicatorElement = OO.ui.mixin.IndicatorElement;
19628
19629 /**
19630 * @inheritdoc OO.ui.mixin.ItemWidget
19631 * @deprecated Use {@link OO.ui.mixin.ItemWidget} instead.
19632 */
19633 OO.ui.ItemWidget = OO.ui.mixin.ItemWidget;
19634
19635 /**
19636 * @inheritdoc OO.ui.mixin.LabelElement
19637 * @deprecated Use {@link OO.ui.mixin.LabelElement} instead.
19638 */
19639 OO.ui.LabelElement = OO.ui.mixin.LabelElement;
19640
19641 /**
19642 * @inheritdoc OO.ui.mixin.LookupElement
19643 * @deprecated Use {@link OO.ui.mixin.LookupElement} instead.
19644 */
19645 OO.ui.LookupElement = OO.ui.mixin.LookupElement;
19646
19647 /**
19648 * @inheritdoc OO.ui.mixin.PendingElement
19649 * @deprecated Use {@link OO.ui.mixin.PendingElement} instead.
19650 */
19651 OO.ui.PendingElement = OO.ui.mixin.PendingElement;
19652
19653 /**
19654 * @inheritdoc OO.ui.mixin.PopupElement
19655 * @deprecated Use {@link OO.ui.mixin.PopupElement} instead.
19656 */
19657 OO.ui.PopupElement = OO.ui.mixin.PopupElement;
19658
19659 /**
19660 * @inheritdoc OO.ui.mixin.TabIndexedElement
19661 * @deprecated Use {@link OO.ui.mixin.TabIndexedElement} instead.
19662 */
19663 OO.ui.TabIndexedElement = OO.ui.mixin.TabIndexedElement;
19664
19665 /**
19666 * @inheritdoc OO.ui.mixin.TitledElement
19667 * @deprecated Use {@link OO.ui.mixin.TitledElement} instead.
19668 */
19669 OO.ui.TitledElement = OO.ui.mixin.TitledElement;
19670
19671 }( OO ) );