Merge "Prevent revisions with rev_page = 0 from being inserted into the DB"
[lhc/web/wiklou.git] / resources / lib / oojs-ui / oojs-ui.js
1 /*!
2 * OOjs UI v0.15.0
3 * https://www.mediawiki.org/wiki/OOjs_UI
4 *
5 * Copyright 2011–2016 OOjs UI Team and other contributors.
6 * Released under the MIT license
7 * http://oojs.mit-license.org
8 *
9 * Date: 2016-01-12T23:06:31Z
10 */
11 ( function ( OO ) {
12
13 'use strict';
14
15 /**
16 * Namespace for all classes, static methods and static properties.
17 *
18 * @class
19 * @singleton
20 */
21 OO.ui = {};
22
23 OO.ui.bind = $.proxy;
24
25 /**
26 * @property {Object}
27 */
28 OO.ui.Keys = {
29 UNDEFINED: 0,
30 BACKSPACE: 8,
31 DELETE: 46,
32 LEFT: 37,
33 RIGHT: 39,
34 UP: 38,
35 DOWN: 40,
36 ENTER: 13,
37 END: 35,
38 HOME: 36,
39 TAB: 9,
40 PAGEUP: 33,
41 PAGEDOWN: 34,
42 ESCAPE: 27,
43 SHIFT: 16,
44 SPACE: 32
45 };
46
47 /**
48 * Constants for MouseEvent.which
49 *
50 * @property {Object}
51 */
52 OO.ui.MouseButtons = {
53 LEFT: 1,
54 MIDDLE: 2,
55 RIGHT: 3
56 };
57
58 /**
59 * @property {Number}
60 */
61 OO.ui.elementId = 0;
62
63 /**
64 * Generate a unique ID for element
65 *
66 * @return {String} [id]
67 */
68 OO.ui.generateElementId = function () {
69 OO.ui.elementId += 1;
70 return 'oojsui-' + OO.ui.elementId;
71 };
72
73 /**
74 * Check if an element is focusable.
75 * Inspired from :focusable in jQueryUI v1.11.4 - 2015-04-14
76 *
77 * @param {jQuery} element Element to test
78 * @return {boolean}
79 */
80 OO.ui.isFocusableElement = function ( $element ) {
81 var nodeName,
82 element = $element[ 0 ];
83
84 // Anything disabled is not focusable
85 if ( element.disabled ) {
86 return false;
87 }
88
89 // Check if the element is visible
90 if ( !(
91 // This is quicker than calling $element.is( ':visible' )
92 $.expr.filters.visible( element ) &&
93 // Check that all parents are visible
94 !$element.parents().addBack().filter( function () {
95 return $.css( this, 'visibility' ) === 'hidden';
96 } ).length
97 ) ) {
98 return false;
99 }
100
101 // Check if the element is ContentEditable, which is the string 'true'
102 if ( element.contentEditable === 'true' ) {
103 return true;
104 }
105
106 // Anything with a non-negative numeric tabIndex is focusable.
107 // Use .prop to avoid browser bugs
108 if ( $element.prop( 'tabIndex' ) >= 0 ) {
109 return true;
110 }
111
112 // Some element types are naturally focusable
113 // (indexOf is much faster than regex in Chrome and about the
114 // same in FF: https://jsperf.com/regex-vs-indexof-array2)
115 nodeName = element.nodeName.toLowerCase();
116 if ( [ 'input', 'select', 'textarea', 'button', 'object' ].indexOf( nodeName ) !== -1 ) {
117 return true;
118 }
119
120 // Links and areas are focusable if they have an href
121 if ( ( nodeName === 'a' || nodeName === 'area' ) && $element.attr( 'href' ) !== undefined ) {
122 return true;
123 }
124
125 return false;
126 };
127
128 /**
129 * Find a focusable child
130 *
131 * @param {jQuery} $container Container to search in
132 * @param {boolean} [backwards] Search backwards
133 * @return {jQuery} Focusable child, an empty jQuery object if none found
134 */
135 OO.ui.findFocusable = function ( $container, backwards ) {
136 var $focusable = $( [] ),
137 // $focusableCandidates is a superset of things that
138 // could get matched by isFocusableElement
139 $focusableCandidates = $container
140 .find( 'input, select, textarea, button, object, a, area, [contenteditable], [tabindex]' );
141
142 if ( backwards ) {
143 $focusableCandidates = Array.prototype.reverse.call( $focusableCandidates );
144 }
145
146 $focusableCandidates.each( function () {
147 var $this = $( this );
148 if ( OO.ui.isFocusableElement( $this ) ) {
149 $focusable = $this;
150 return false;
151 }
152 } );
153 return $focusable;
154 };
155
156 /**
157 * Get the user's language and any fallback languages.
158 *
159 * These language codes are used to localize user interface elements in the user's language.
160 *
161 * In environments that provide a localization system, this function should be overridden to
162 * return the user's language(s). The default implementation returns English (en) only.
163 *
164 * @return {string[]} Language codes, in descending order of priority
165 */
166 OO.ui.getUserLanguages = function () {
167 return [ 'en' ];
168 };
169
170 /**
171 * Get a value in an object keyed by language code.
172 *
173 * @param {Object.<string,Mixed>} obj Object keyed by language code
174 * @param {string|null} [lang] Language code, if omitted or null defaults to any user language
175 * @param {string} [fallback] Fallback code, used if no matching language can be found
176 * @return {Mixed} Local value
177 */
178 OO.ui.getLocalValue = function ( obj, lang, fallback ) {
179 var i, len, langs;
180
181 // Requested language
182 if ( obj[ lang ] ) {
183 return obj[ lang ];
184 }
185 // Known user language
186 langs = OO.ui.getUserLanguages();
187 for ( i = 0, len = langs.length; i < len; i++ ) {
188 lang = langs[ i ];
189 if ( obj[ lang ] ) {
190 return obj[ lang ];
191 }
192 }
193 // Fallback language
194 if ( obj[ fallback ] ) {
195 return obj[ fallback ];
196 }
197 // First existing language
198 for ( lang in obj ) {
199 return obj[ lang ];
200 }
201
202 return undefined;
203 };
204
205 /**
206 * Check if a node is contained within another node
207 *
208 * Similar to jQuery#contains except a list of containers can be supplied
209 * and a boolean argument allows you to include the container in the match list
210 *
211 * @param {HTMLElement|HTMLElement[]} containers Container node(s) to search in
212 * @param {HTMLElement} contained Node to find
213 * @param {boolean} [matchContainers] Include the container(s) in the list of nodes to match, otherwise only match descendants
214 * @return {boolean} The node is in the list of target nodes
215 */
216 OO.ui.contains = function ( containers, contained, matchContainers ) {
217 var i;
218 if ( !Array.isArray( containers ) ) {
219 containers = [ containers ];
220 }
221 for ( i = containers.length - 1; i >= 0; i-- ) {
222 if ( ( matchContainers && contained === containers[ i ] ) || $.contains( containers[ i ], contained ) ) {
223 return true;
224 }
225 }
226 return false;
227 };
228
229 /**
230 * Return a function, that, as long as it continues to be invoked, will not
231 * be triggered. The function will be called after it stops being called for
232 * N milliseconds. If `immediate` is passed, trigger the function on the
233 * leading edge, instead of the trailing.
234 *
235 * Ported from: http://underscorejs.org/underscore.js
236 *
237 * @param {Function} func
238 * @param {number} wait
239 * @param {boolean} immediate
240 * @return {Function}
241 */
242 OO.ui.debounce = function ( func, wait, immediate ) {
243 var timeout;
244 return function () {
245 var context = this,
246 args = arguments,
247 later = function () {
248 timeout = null;
249 if ( !immediate ) {
250 func.apply( context, args );
251 }
252 };
253 if ( immediate && !timeout ) {
254 func.apply( context, args );
255 }
256 clearTimeout( timeout );
257 timeout = setTimeout( later, wait );
258 };
259 };
260
261 /**
262 * Proxy for `node.addEventListener( eventName, handler, true )`.
263 *
264 * @param {HTMLElement} node
265 * @param {string} eventName
266 * @param {Function} handler
267 * @deprecated
268 */
269 OO.ui.addCaptureEventListener = function ( node, eventName, handler ) {
270 node.addEventListener( eventName, handler, true );
271 };
272
273 /**
274 * Proxy for `node.removeEventListener( eventName, handler, true )`.
275 *
276 * @param {HTMLElement} node
277 * @param {string} eventName
278 * @param {Function} handler
279 * @deprecated
280 */
281 OO.ui.removeCaptureEventListener = function ( node, eventName, handler ) {
282 node.removeEventListener( eventName, handler, true );
283 };
284
285 /**
286 * Reconstitute a JavaScript object corresponding to a widget created by
287 * the PHP implementation.
288 *
289 * This is an alias for `OO.ui.Element.static.infuse()`.
290 *
291 * @param {string|HTMLElement|jQuery} idOrNode
292 * A DOM id (if a string) or node for the widget to infuse.
293 * @return {OO.ui.Element}
294 * The `OO.ui.Element` corresponding to this (infusable) document node.
295 */
296 OO.ui.infuse = function ( idOrNode ) {
297 return OO.ui.Element.static.infuse( idOrNode );
298 };
299
300 ( function () {
301 /**
302 * Message store for the default implementation of OO.ui.msg
303 *
304 * Environments that provide a localization system should not use this, but should override
305 * OO.ui.msg altogether.
306 *
307 * @private
308 */
309 var messages = {
310 // Tool tip for a button that moves items in a list down one place
311 'ooui-outline-control-move-down': 'Move item down',
312 // Tool tip for a button that moves items in a list up one place
313 'ooui-outline-control-move-up': 'Move item up',
314 // Tool tip for a button that removes items from a list
315 'ooui-outline-control-remove': 'Remove item',
316 // Label for the toolbar group that contains a list of all other available tools
317 'ooui-toolbar-more': 'More',
318 // Label for the fake tool that expands the full list of tools in a toolbar group
319 'ooui-toolgroup-expand': 'More',
320 // Label for the fake tool that collapses the full list of tools in a toolbar group
321 'ooui-toolgroup-collapse': 'Fewer',
322 // Default label for the accept button of a confirmation dialog
323 'ooui-dialog-message-accept': 'OK',
324 // Default label for the reject button of a confirmation dialog
325 'ooui-dialog-message-reject': 'Cancel',
326 // Title for process dialog error description
327 'ooui-dialog-process-error': 'Something went wrong',
328 // Label for process dialog dismiss error button, visible when describing errors
329 'ooui-dialog-process-dismiss': 'Dismiss',
330 // Label for process dialog retry action button, visible when describing only recoverable errors
331 'ooui-dialog-process-retry': 'Try again',
332 // Label for process dialog retry action button, visible when describing only warnings
333 'ooui-dialog-process-continue': 'Continue',
334 // Label for the file selection widget's select file button
335 'ooui-selectfile-button-select': 'Select a file',
336 // Label for the file selection widget if file selection is not supported
337 'ooui-selectfile-not-supported': 'File selection is not supported',
338 // Label for the file selection widget when no file is currently selected
339 'ooui-selectfile-placeholder': 'No file is selected',
340 // Label for the file selection widget's drop target
341 'ooui-selectfile-dragdrop-placeholder': 'Drop file here'
342 };
343
344 /**
345 * Get a localized message.
346 *
347 * In environments that provide a localization system, this function should be overridden to
348 * return the message translated in the user's language. The default implementation always returns
349 * English messages.
350 *
351 * After the message key, message parameters may optionally be passed. In the default implementation,
352 * any occurrences of $1 are replaced with the first parameter, $2 with the second parameter, etc.
353 * Alternative implementations of OO.ui.msg may use any substitution system they like, as long as
354 * they support unnamed, ordered message parameters.
355 *
356 * @param {string} key Message key
357 * @param {Mixed...} [params] Message parameters
358 * @return {string} Translated message with parameters substituted
359 */
360 OO.ui.msg = function ( key ) {
361 var message = messages[ key ],
362 params = Array.prototype.slice.call( arguments, 1 );
363 if ( typeof message === 'string' ) {
364 // Perform $1 substitution
365 message = message.replace( /\$(\d+)/g, function ( unused, n ) {
366 var i = parseInt( n, 10 );
367 return params[ i - 1 ] !== undefined ? params[ i - 1 ] : '$' + n;
368 } );
369 } else {
370 // Return placeholder if message not found
371 message = '[' + key + ']';
372 }
373 return message;
374 };
375 } )();
376
377 /**
378 * Package a message and arguments for deferred resolution.
379 *
380 * Use this when you are statically specifying a message and the message may not yet be present.
381 *
382 * @param {string} key Message key
383 * @param {Mixed...} [params] Message parameters
384 * @return {Function} Function that returns the resolved message when executed
385 */
386 OO.ui.deferMsg = function () {
387 var args = arguments;
388 return function () {
389 return OO.ui.msg.apply( OO.ui, args );
390 };
391 };
392
393 /**
394 * Resolve a message.
395 *
396 * If the message is a function it will be executed, otherwise it will pass through directly.
397 *
398 * @param {Function|string} msg Deferred message, or message text
399 * @return {string} Resolved message
400 */
401 OO.ui.resolveMsg = function ( msg ) {
402 if ( $.isFunction( msg ) ) {
403 return msg();
404 }
405 return msg;
406 };
407
408 /**
409 * @param {string} url
410 * @return {boolean}
411 */
412 OO.ui.isSafeUrl = function ( url ) {
413 var protocol,
414 // Keep in sync with php/Tag.php
415 whitelist = [
416 'bitcoin:', 'ftp:', 'ftps:', 'geo:', 'git:', 'gopher:', 'http:', 'https:', 'irc:', 'ircs:',
417 'magnet:', 'mailto:', 'mms:', 'news:', 'nntp:', 'redis:', 'sftp:', 'sip:', 'sips:', 'sms:', 'ssh:',
418 'svn:', 'tel:', 'telnet:', 'urn:', 'worldwind:', 'xmpp:'
419 ];
420
421 if ( url.indexOf( ':' ) === -1 ) {
422 // No protocol, safe
423 return true;
424 }
425
426 protocol = url.split( ':', 1 )[ 0 ] + ':';
427 if ( !protocol.match( /^([A-za-z0-9\+\.\-])+:/ ) ) {
428 // Not a valid protocol, safe
429 return true;
430 }
431
432 // Safe if in the whitelist
433 return whitelist.indexOf( protocol ) !== -1;
434 };
435
436 /**
437 * Lazy-initialize and return a global OO.ui.WindowManager instance, used by OO.ui.alert and
438 * OO.ui.confirm.
439 *
440 * @private
441 * @return {OO.ui.WindowManager}
442 */
443 OO.ui.getWindowManager = function () {
444 if ( !OO.ui.windowManager ) {
445 OO.ui.windowManager = new OO.ui.WindowManager();
446 $( 'body' ).append( OO.ui.windowManager.$element );
447 OO.ui.windowManager.addWindows( {
448 messageDialog: new OO.ui.MessageDialog()
449 } );
450 }
451 return OO.ui.windowManager;
452 };
453
454 /**
455 * Display a quick modal alert dialog, using a OO.ui.MessageDialog. While the dialog is open, the
456 * rest of the page will be dimmed out and the user won't be able to interact with it. The dialog
457 * has only one action button, labelled "OK", clicking it will simply close the dialog.
458 *
459 * A window manager is created automatically when this function is called for the first time.
460 *
461 * @example
462 * OO.ui.alert( 'Something happened!' ).done( function () {
463 * console.log( 'User closed the dialog.' );
464 * } );
465 *
466 * @param {jQuery|string} text Message text to display
467 * @param {Object} [options] Additional options, see OO.ui.MessageDialog#getSetupProcess
468 * @return {jQuery.Promise} Promise resolved when the user closes the dialog
469 */
470 OO.ui.alert = function ( text, options ) {
471 return OO.ui.getWindowManager().openWindow( 'messageDialog', $.extend( {
472 message: text,
473 verbose: true,
474 actions: [ OO.ui.MessageDialog.static.actions[ 0 ] ]
475 }, options ) ).then( function ( opened ) {
476 return opened.then( function ( closing ) {
477 return closing.then( function () {
478 return $.Deferred().resolve();
479 } );
480 } );
481 } );
482 };
483
484 /**
485 * Display a quick modal confirmation dialog, using a OO.ui.MessageDialog. While the dialog is open,
486 * the rest of the page will be dimmed out and the user won't be able to interact with it. The
487 * dialog has two action buttons, one to confirm an operation (labelled "OK") and one to cancel it
488 * (labelled "Cancel").
489 *
490 * A window manager is created automatically when this function is called for the first time.
491 *
492 * @example
493 * OO.ui.confirm( 'Are you sure?' ).done( function ( confirmed ) {
494 * if ( confirmed ) {
495 * console.log( 'User clicked "OK"!' );
496 * } else {
497 * console.log( 'User clicked "Cancel" or closed the dialog.' );
498 * }
499 * } );
500 *
501 * @param {jQuery|string} text Message text to display
502 * @param {Object} [options] Additional options, see OO.ui.MessageDialog#getSetupProcess
503 * @return {jQuery.Promise} Promise resolved when the user closes the dialog. If the user chose to
504 * confirm, the promise will resolve to boolean `true`; otherwise, it will resolve to boolean
505 * `false`.
506 */
507 OO.ui.confirm = function ( text, options ) {
508 return OO.ui.getWindowManager().openWindow( 'messageDialog', $.extend( {
509 message: text,
510 verbose: true
511 }, options ) ).then( function ( opened ) {
512 return opened.then( function ( closing ) {
513 return closing.then( function ( data ) {
514 return $.Deferred().resolve( !!( data && data.action === 'accept' ) );
515 } );
516 } );
517 } );
518 };
519
520 /*!
521 * Mixin namespace.
522 */
523
524 /**
525 * Namespace for OOjs UI mixins.
526 *
527 * Mixins are named according to the type of object they are intended to
528 * be mixed in to. For example, OO.ui.mixin.GroupElement is intended to be
529 * mixed in to an instance of OO.ui.Element, and OO.ui.mixin.GroupWidget
530 * is intended to be mixed in to an instance of OO.ui.Widget.
531 *
532 * @class
533 * @singleton
534 */
535 OO.ui.mixin = {};
536
537 /**
538 * PendingElement is a mixin that is used to create elements that notify users that something is happening
539 * and that they should wait before proceeding. The pending state is visually represented with a pending
540 * texture that appears in the head of a pending {@link OO.ui.ProcessDialog process dialog} or in the input
541 * field of a {@link OO.ui.TextInputWidget text input widget}.
542 *
543 * Currently, {@link OO.ui.ActionWidget Action widgets}, which mix in this class, can also be marked as pending, but only when
544 * used in {@link OO.ui.MessageDialog message dialogs}. The behavior is not currently supported for action widgets used
545 * in process dialogs.
546 *
547 * @example
548 * function MessageDialog( config ) {
549 * MessageDialog.parent.call( this, config );
550 * }
551 * OO.inheritClass( MessageDialog, OO.ui.MessageDialog );
552 *
553 * MessageDialog.static.actions = [
554 * { action: 'save', label: 'Done', flags: 'primary' },
555 * { label: 'Cancel', flags: 'safe' }
556 * ];
557 *
558 * MessageDialog.prototype.initialize = function () {
559 * MessageDialog.parent.prototype.initialize.apply( this, arguments );
560 * this.content = new OO.ui.PanelLayout( { $: this.$, padded: true } );
561 * 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>' );
562 * this.$body.append( this.content.$element );
563 * };
564 * MessageDialog.prototype.getBodyHeight = function () {
565 * return 100;
566 * }
567 * MessageDialog.prototype.getActionProcess = function ( action ) {
568 * var dialog = this;
569 * if ( action === 'save' ) {
570 * dialog.getActions().get({actions: 'save'})[0].pushPending();
571 * return new OO.ui.Process()
572 * .next( 1000 )
573 * .next( function () {
574 * dialog.getActions().get({actions: 'save'})[0].popPending();
575 * } );
576 * }
577 * return MessageDialog.parent.prototype.getActionProcess.call( this, action );
578 * };
579 *
580 * var windowManager = new OO.ui.WindowManager();
581 * $( 'body' ).append( windowManager.$element );
582 *
583 * var dialog = new MessageDialog();
584 * windowManager.addWindows( [ dialog ] );
585 * windowManager.openWindow( dialog );
586 *
587 * @abstract
588 * @class
589 *
590 * @constructor
591 * @param {Object} [config] Configuration options
592 * @cfg {jQuery} [$pending] Element to mark as pending, defaults to this.$element
593 */
594 OO.ui.mixin.PendingElement = function OoUiMixinPendingElement( config ) {
595 // Configuration initialization
596 config = config || {};
597
598 // Properties
599 this.pending = 0;
600 this.$pending = null;
601
602 // Initialisation
603 this.setPendingElement( config.$pending || this.$element );
604 };
605
606 /* Setup */
607
608 OO.initClass( OO.ui.mixin.PendingElement );
609
610 /* Methods */
611
612 /**
613 * Set the pending element (and clean up any existing one).
614 *
615 * @param {jQuery} $pending The element to set to pending.
616 */
617 OO.ui.mixin.PendingElement.prototype.setPendingElement = function ( $pending ) {
618 if ( this.$pending ) {
619 this.$pending.removeClass( 'oo-ui-pendingElement-pending' );
620 }
621
622 this.$pending = $pending;
623 if ( this.pending > 0 ) {
624 this.$pending.addClass( 'oo-ui-pendingElement-pending' );
625 }
626 };
627
628 /**
629 * Check if an element is pending.
630 *
631 * @return {boolean} Element is pending
632 */
633 OO.ui.mixin.PendingElement.prototype.isPending = function () {
634 return !!this.pending;
635 };
636
637 /**
638 * Increase the pending counter. The pending state will remain active until the counter is zero
639 * (i.e., the number of calls to #pushPending and #popPending is the same).
640 *
641 * @chainable
642 */
643 OO.ui.mixin.PendingElement.prototype.pushPending = function () {
644 if ( this.pending === 0 ) {
645 this.$pending.addClass( 'oo-ui-pendingElement-pending' );
646 this.updateThemeClasses();
647 }
648 this.pending++;
649
650 return this;
651 };
652
653 /**
654 * Decrease the pending counter. The pending state will remain active until the counter is zero
655 * (i.e., the number of calls to #pushPending and #popPending is the same).
656 *
657 * @chainable
658 */
659 OO.ui.mixin.PendingElement.prototype.popPending = function () {
660 if ( this.pending === 1 ) {
661 this.$pending.removeClass( 'oo-ui-pendingElement-pending' );
662 this.updateThemeClasses();
663 }
664 this.pending = Math.max( 0, this.pending - 1 );
665
666 return this;
667 };
668
669 /**
670 * ActionSets manage the behavior of the {@link OO.ui.ActionWidget action widgets} that comprise them.
671 * Actions can be made available for specific contexts (modes) and circumstances
672 * (abilities). Action sets are primarily used with {@link OO.ui.Dialog Dialogs}.
673 *
674 * ActionSets contain two types of actions:
675 *
676 * - 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.
677 * - Other: Other actions include all non-special visible actions.
678 *
679 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
680 *
681 * @example
682 * // Example: An action set used in a process dialog
683 * function MyProcessDialog( config ) {
684 * MyProcessDialog.parent.call( this, config );
685 * }
686 * OO.inheritClass( MyProcessDialog, OO.ui.ProcessDialog );
687 * MyProcessDialog.static.title = 'An action set in a process dialog';
688 * // An action set that uses modes ('edit' and 'help' mode, in this example).
689 * MyProcessDialog.static.actions = [
690 * { action: 'continue', modes: 'edit', label: 'Continue', flags: [ 'primary', 'constructive' ] },
691 * { action: 'help', modes: 'edit', label: 'Help' },
692 * { modes: 'edit', label: 'Cancel', flags: 'safe' },
693 * { action: 'back', modes: 'help', label: 'Back', flags: 'safe' }
694 * ];
695 *
696 * MyProcessDialog.prototype.initialize = function () {
697 * MyProcessDialog.parent.prototype.initialize.apply( this, arguments );
698 * this.panel1 = new OO.ui.PanelLayout( { padded: true, expanded: false } );
699 * 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>' );
700 * this.panel2 = new OO.ui.PanelLayout( { padded: true, expanded: false } );
701 * 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>' );
702 * this.stackLayout = new OO.ui.StackLayout( {
703 * items: [ this.panel1, this.panel2 ]
704 * } );
705 * this.$body.append( this.stackLayout.$element );
706 * };
707 * MyProcessDialog.prototype.getSetupProcess = function ( data ) {
708 * return MyProcessDialog.parent.prototype.getSetupProcess.call( this, data )
709 * .next( function () {
710 * this.actions.setMode( 'edit' );
711 * }, this );
712 * };
713 * MyProcessDialog.prototype.getActionProcess = function ( action ) {
714 * if ( action === 'help' ) {
715 * this.actions.setMode( 'help' );
716 * this.stackLayout.setItem( this.panel2 );
717 * } else if ( action === 'back' ) {
718 * this.actions.setMode( 'edit' );
719 * this.stackLayout.setItem( this.panel1 );
720 * } else if ( action === 'continue' ) {
721 * var dialog = this;
722 * return new OO.ui.Process( function () {
723 * dialog.close();
724 * } );
725 * }
726 * return MyProcessDialog.parent.prototype.getActionProcess.call( this, action );
727 * };
728 * MyProcessDialog.prototype.getBodyHeight = function () {
729 * return this.panel1.$element.outerHeight( true );
730 * };
731 * var windowManager = new OO.ui.WindowManager();
732 * $( 'body' ).append( windowManager.$element );
733 * var dialog = new MyProcessDialog( {
734 * size: 'medium'
735 * } );
736 * windowManager.addWindows( [ dialog ] );
737 * windowManager.openWindow( dialog );
738 *
739 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Action_sets
740 *
741 * @abstract
742 * @class
743 * @mixins OO.EventEmitter
744 *
745 * @constructor
746 * @param {Object} [config] Configuration options
747 */
748 OO.ui.ActionSet = function OoUiActionSet( config ) {
749 // Configuration initialization
750 config = config || {};
751
752 // Mixin constructors
753 OO.EventEmitter.call( this );
754
755 // Properties
756 this.list = [];
757 this.categories = {
758 actions: 'getAction',
759 flags: 'getFlags',
760 modes: 'getModes'
761 };
762 this.categorized = {};
763 this.special = {};
764 this.others = [];
765 this.organized = false;
766 this.changing = false;
767 this.changed = false;
768 };
769
770 /* Setup */
771
772 OO.mixinClass( OO.ui.ActionSet, OO.EventEmitter );
773
774 /* Static Properties */
775
776 /**
777 * Symbolic name of the flags used to identify special actions. Special actions are displayed in the
778 * header of a {@link OO.ui.ProcessDialog process dialog}.
779 * See the [OOjs UI documentation on MediaWiki][2] for more information and examples.
780 *
781 * [2]:https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs
782 *
783 * @abstract
784 * @static
785 * @inheritable
786 * @property {string}
787 */
788 OO.ui.ActionSet.static.specialFlags = [ 'safe', 'primary' ];
789
790 /* Events */
791
792 /**
793 * @event click
794 *
795 * A 'click' event is emitted when an action is clicked.
796 *
797 * @param {OO.ui.ActionWidget} action Action that was clicked
798 */
799
800 /**
801 * @event resize
802 *
803 * A 'resize' event is emitted when an action widget is resized.
804 *
805 * @param {OO.ui.ActionWidget} action Action that was resized
806 */
807
808 /**
809 * @event add
810 *
811 * An 'add' event is emitted when actions are {@link #method-add added} to the action set.
812 *
813 * @param {OO.ui.ActionWidget[]} added Actions added
814 */
815
816 /**
817 * @event remove
818 *
819 * A 'remove' event is emitted when actions are {@link #method-remove removed}
820 * or {@link #clear cleared}.
821 *
822 * @param {OO.ui.ActionWidget[]} added Actions removed
823 */
824
825 /**
826 * @event change
827 *
828 * A 'change' event is emitted when actions are {@link #method-add added}, {@link #clear cleared},
829 * or {@link #method-remove removed} from the action set or when the {@link #setMode mode} is changed.
830 *
831 */
832
833 /* Methods */
834
835 /**
836 * Handle action change events.
837 *
838 * @private
839 * @fires change
840 */
841 OO.ui.ActionSet.prototype.onActionChange = function () {
842 this.organized = false;
843 if ( this.changing ) {
844 this.changed = true;
845 } else {
846 this.emit( 'change' );
847 }
848 };
849
850 /**
851 * Check if an action is one of the special actions.
852 *
853 * @param {OO.ui.ActionWidget} action Action to check
854 * @return {boolean} Action is special
855 */
856 OO.ui.ActionSet.prototype.isSpecial = function ( action ) {
857 var flag;
858
859 for ( flag in this.special ) {
860 if ( action === this.special[ flag ] ) {
861 return true;
862 }
863 }
864
865 return false;
866 };
867
868 /**
869 * Get action widgets based on the specified filter: ‘actions’, ‘flags’, ‘modes’, ‘visible’,
870 * or ‘disabled’.
871 *
872 * @param {Object} [filters] Filters to use, omit to get all actions
873 * @param {string|string[]} [filters.actions] Actions that action widgets must have
874 * @param {string|string[]} [filters.flags] Flags that action widgets must have (e.g., 'safe')
875 * @param {string|string[]} [filters.modes] Modes that action widgets must have
876 * @param {boolean} [filters.visible] Action widgets must be visible
877 * @param {boolean} [filters.disabled] Action widgets must be disabled
878 * @return {OO.ui.ActionWidget[]} Action widgets matching all criteria
879 */
880 OO.ui.ActionSet.prototype.get = function ( filters ) {
881 var i, len, list, category, actions, index, match, matches;
882
883 if ( filters ) {
884 this.organize();
885
886 // Collect category candidates
887 matches = [];
888 for ( category in this.categorized ) {
889 list = filters[ category ];
890 if ( list ) {
891 if ( !Array.isArray( list ) ) {
892 list = [ list ];
893 }
894 for ( i = 0, len = list.length; i < len; i++ ) {
895 actions = this.categorized[ category ][ list[ i ] ];
896 if ( Array.isArray( actions ) ) {
897 matches.push.apply( matches, actions );
898 }
899 }
900 }
901 }
902 // Remove by boolean filters
903 for ( i = 0, len = matches.length; i < len; i++ ) {
904 match = matches[ i ];
905 if (
906 ( filters.visible !== undefined && match.isVisible() !== filters.visible ) ||
907 ( filters.disabled !== undefined && match.isDisabled() !== filters.disabled )
908 ) {
909 matches.splice( i, 1 );
910 len--;
911 i--;
912 }
913 }
914 // Remove duplicates
915 for ( i = 0, len = matches.length; i < len; i++ ) {
916 match = matches[ i ];
917 index = matches.lastIndexOf( match );
918 while ( index !== i ) {
919 matches.splice( index, 1 );
920 len--;
921 index = matches.lastIndexOf( match );
922 }
923 }
924 return matches;
925 }
926 return this.list.slice();
927 };
928
929 /**
930 * Get 'special' actions.
931 *
932 * Special actions are the first visible action widgets with special flags, such as 'safe' and 'primary'.
933 * Special flags can be configured in subclasses by changing the static #specialFlags property.
934 *
935 * @return {OO.ui.ActionWidget[]|null} 'Special' action widgets.
936 */
937 OO.ui.ActionSet.prototype.getSpecial = function () {
938 this.organize();
939 return $.extend( {}, this.special );
940 };
941
942 /**
943 * Get 'other' actions.
944 *
945 * Other actions include all non-special visible action widgets.
946 *
947 * @return {OO.ui.ActionWidget[]} 'Other' action widgets
948 */
949 OO.ui.ActionSet.prototype.getOthers = function () {
950 this.organize();
951 return this.others.slice();
952 };
953
954 /**
955 * Set the mode (e.g., ‘edit’ or ‘view’). Only {@link OO.ui.ActionWidget#modes actions} configured
956 * to be available in the specified mode will be made visible. All other actions will be hidden.
957 *
958 * @param {string} mode The mode. Only actions configured to be available in the specified
959 * mode will be made visible.
960 * @chainable
961 * @fires toggle
962 * @fires change
963 */
964 OO.ui.ActionSet.prototype.setMode = function ( mode ) {
965 var i, len, action;
966
967 this.changing = true;
968 for ( i = 0, len = this.list.length; i < len; i++ ) {
969 action = this.list[ i ];
970 action.toggle( action.hasMode( mode ) );
971 }
972
973 this.organized = false;
974 this.changing = false;
975 this.emit( 'change' );
976
977 return this;
978 };
979
980 /**
981 * Set the abilities of the specified actions.
982 *
983 * Action widgets that are configured with the specified actions will be enabled
984 * or disabled based on the boolean values specified in the `actions`
985 * parameter.
986 *
987 * @param {Object.<string,boolean>} actions A list keyed by action name with boolean
988 * values that indicate whether or not the action should be enabled.
989 * @chainable
990 */
991 OO.ui.ActionSet.prototype.setAbilities = function ( actions ) {
992 var i, len, action, item;
993
994 for ( i = 0, len = this.list.length; i < len; i++ ) {
995 item = this.list[ i ];
996 action = item.getAction();
997 if ( actions[ action ] !== undefined ) {
998 item.setDisabled( !actions[ action ] );
999 }
1000 }
1001
1002 return this;
1003 };
1004
1005 /**
1006 * Executes a function once per action.
1007 *
1008 * When making changes to multiple actions, use this method instead of iterating over the actions
1009 * manually to defer emitting a #change event until after all actions have been changed.
1010 *
1011 * @param {Object|null} actions Filters to use to determine which actions to iterate over; see #get
1012 * @param {Function} callback Callback to run for each action; callback is invoked with three
1013 * arguments: the action, the action's index, the list of actions being iterated over
1014 * @chainable
1015 */
1016 OO.ui.ActionSet.prototype.forEach = function ( filter, callback ) {
1017 this.changed = false;
1018 this.changing = true;
1019 this.get( filter ).forEach( callback );
1020 this.changing = false;
1021 if ( this.changed ) {
1022 this.emit( 'change' );
1023 }
1024
1025 return this;
1026 };
1027
1028 /**
1029 * Add action widgets to the action set.
1030 *
1031 * @param {OO.ui.ActionWidget[]} actions Action widgets to add
1032 * @chainable
1033 * @fires add
1034 * @fires change
1035 */
1036 OO.ui.ActionSet.prototype.add = function ( actions ) {
1037 var i, len, action;
1038
1039 this.changing = true;
1040 for ( i = 0, len = actions.length; i < len; i++ ) {
1041 action = actions[ i ];
1042 action.connect( this, {
1043 click: [ 'emit', 'click', action ],
1044 resize: [ 'emit', 'resize', action ],
1045 toggle: [ 'onActionChange' ]
1046 } );
1047 this.list.push( action );
1048 }
1049 this.organized = false;
1050 this.emit( 'add', actions );
1051 this.changing = false;
1052 this.emit( 'change' );
1053
1054 return this;
1055 };
1056
1057 /**
1058 * Remove action widgets from the set.
1059 *
1060 * To remove all actions, you may wish to use the #clear method instead.
1061 *
1062 * @param {OO.ui.ActionWidget[]} actions Action widgets to remove
1063 * @chainable
1064 * @fires remove
1065 * @fires change
1066 */
1067 OO.ui.ActionSet.prototype.remove = function ( actions ) {
1068 var i, len, index, action;
1069
1070 this.changing = true;
1071 for ( i = 0, len = actions.length; i < len; i++ ) {
1072 action = actions[ i ];
1073 index = this.list.indexOf( action );
1074 if ( index !== -1 ) {
1075 action.disconnect( this );
1076 this.list.splice( index, 1 );
1077 }
1078 }
1079 this.organized = false;
1080 this.emit( 'remove', actions );
1081 this.changing = false;
1082 this.emit( 'change' );
1083
1084 return this;
1085 };
1086
1087 /**
1088 * Remove all action widets from the set.
1089 *
1090 * To remove only specified actions, use the {@link #method-remove remove} method instead.
1091 *
1092 * @chainable
1093 * @fires remove
1094 * @fires change
1095 */
1096 OO.ui.ActionSet.prototype.clear = function () {
1097 var i, len, action,
1098 removed = this.list.slice();
1099
1100 this.changing = true;
1101 for ( i = 0, len = this.list.length; i < len; i++ ) {
1102 action = this.list[ i ];
1103 action.disconnect( this );
1104 }
1105
1106 this.list = [];
1107
1108 this.organized = false;
1109 this.emit( 'remove', removed );
1110 this.changing = false;
1111 this.emit( 'change' );
1112
1113 return this;
1114 };
1115
1116 /**
1117 * Organize actions.
1118 *
1119 * This is called whenever organized information is requested. It will only reorganize the actions
1120 * if something has changed since the last time it ran.
1121 *
1122 * @private
1123 * @chainable
1124 */
1125 OO.ui.ActionSet.prototype.organize = function () {
1126 var i, iLen, j, jLen, flag, action, category, list, item, special,
1127 specialFlags = this.constructor.static.specialFlags;
1128
1129 if ( !this.organized ) {
1130 this.categorized = {};
1131 this.special = {};
1132 this.others = [];
1133 for ( i = 0, iLen = this.list.length; i < iLen; i++ ) {
1134 action = this.list[ i ];
1135 if ( action.isVisible() ) {
1136 // Populate categories
1137 for ( category in this.categories ) {
1138 if ( !this.categorized[ category ] ) {
1139 this.categorized[ category ] = {};
1140 }
1141 list = action[ this.categories[ category ] ]();
1142 if ( !Array.isArray( list ) ) {
1143 list = [ list ];
1144 }
1145 for ( j = 0, jLen = list.length; j < jLen; j++ ) {
1146 item = list[ j ];
1147 if ( !this.categorized[ category ][ item ] ) {
1148 this.categorized[ category ][ item ] = [];
1149 }
1150 this.categorized[ category ][ item ].push( action );
1151 }
1152 }
1153 // Populate special/others
1154 special = false;
1155 for ( j = 0, jLen = specialFlags.length; j < jLen; j++ ) {
1156 flag = specialFlags[ j ];
1157 if ( !this.special[ flag ] && action.hasFlag( flag ) ) {
1158 this.special[ flag ] = action;
1159 special = true;
1160 break;
1161 }
1162 }
1163 if ( !special ) {
1164 this.others.push( action );
1165 }
1166 }
1167 }
1168 this.organized = true;
1169 }
1170
1171 return this;
1172 };
1173
1174 /**
1175 * Each Element represents a rendering in the DOM—a button or an icon, for example, or anything
1176 * that is visible to a user. Unlike {@link OO.ui.Widget widgets}, plain elements usually do not have events
1177 * connected to them and can't be interacted with.
1178 *
1179 * @abstract
1180 * @class
1181 *
1182 * @constructor
1183 * @param {Object} [config] Configuration options
1184 * @cfg {string[]} [classes] The names of the CSS classes to apply to the element. CSS styles are added
1185 * to the top level (e.g., the outermost div) of the element. See the [OOjs UI documentation on MediaWiki][2]
1186 * for an example.
1187 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#cssExample
1188 * @cfg {string} [id] The HTML id attribute used in the rendered tag.
1189 * @cfg {string} [text] Text to insert
1190 * @cfg {Array} [content] An array of content elements to append (after #text).
1191 * Strings will be html-escaped; use an OO.ui.HtmlSnippet to append raw HTML.
1192 * Instances of OO.ui.Element will have their $element appended.
1193 * @cfg {jQuery} [$content] Content elements to append (after #text).
1194 * @cfg {jQuery} [$element] Wrapper element. Defaults to a new element with #getTagName.
1195 * @cfg {Mixed} [data] Custom data of any type or combination of types (e.g., string, number, array, object).
1196 * Data can also be specified with the #setData method.
1197 */
1198 OO.ui.Element = function OoUiElement( config ) {
1199 // Configuration initialization
1200 config = config || {};
1201
1202 // Properties
1203 this.$ = $;
1204 this.visible = true;
1205 this.data = config.data;
1206 this.$element = config.$element ||
1207 $( document.createElement( this.getTagName() ) );
1208 this.elementGroup = null;
1209 this.debouncedUpdateThemeClassesHandler = OO.ui.debounce( this.debouncedUpdateThemeClasses );
1210
1211 // Initialization
1212 if ( Array.isArray( config.classes ) ) {
1213 this.$element.addClass( config.classes.join( ' ' ) );
1214 }
1215 if ( config.id ) {
1216 this.$element.attr( 'id', config.id );
1217 }
1218 if ( config.text ) {
1219 this.$element.text( config.text );
1220 }
1221 if ( config.content ) {
1222 // The `content` property treats plain strings as text; use an
1223 // HtmlSnippet to append HTML content. `OO.ui.Element`s get their
1224 // appropriate $element appended.
1225 this.$element.append( config.content.map( function ( v ) {
1226 if ( typeof v === 'string' ) {
1227 // Escape string so it is properly represented in HTML.
1228 return document.createTextNode( v );
1229 } else if ( v instanceof OO.ui.HtmlSnippet ) {
1230 // Bypass escaping.
1231 return v.toString();
1232 } else if ( v instanceof OO.ui.Element ) {
1233 return v.$element;
1234 }
1235 return v;
1236 } ) );
1237 }
1238 if ( config.$content ) {
1239 // The `$content` property treats plain strings as HTML.
1240 this.$element.append( config.$content );
1241 }
1242 };
1243
1244 /* Setup */
1245
1246 OO.initClass( OO.ui.Element );
1247
1248 /* Static Properties */
1249
1250 /**
1251 * The name of the HTML tag used by the element.
1252 *
1253 * The static value may be ignored if the #getTagName method is overridden.
1254 *
1255 * @static
1256 * @inheritable
1257 * @property {string}
1258 */
1259 OO.ui.Element.static.tagName = 'div';
1260
1261 /* Static Methods */
1262
1263 /**
1264 * Reconstitute a JavaScript object corresponding to a widget created
1265 * by the PHP implementation.
1266 *
1267 * @param {string|HTMLElement|jQuery} idOrNode
1268 * A DOM id (if a string) or node for the widget to infuse.
1269 * @return {OO.ui.Element}
1270 * The `OO.ui.Element` corresponding to this (infusable) document node.
1271 * For `Tag` objects emitted on the HTML side (used occasionally for content)
1272 * the value returned is a newly-created Element wrapping around the existing
1273 * DOM node.
1274 */
1275 OO.ui.Element.static.infuse = function ( idOrNode ) {
1276 var obj = OO.ui.Element.static.unsafeInfuse( idOrNode, false );
1277 // Verify that the type matches up.
1278 // FIXME: uncomment after T89721 is fixed (see T90929)
1279 /*
1280 if ( !( obj instanceof this['class'] ) ) {
1281 throw new Error( 'Infusion type mismatch!' );
1282 }
1283 */
1284 return obj;
1285 };
1286
1287 /**
1288 * Implementation helper for `infuse`; skips the type check and has an
1289 * extra property so that only the top-level invocation touches the DOM.
1290 * @private
1291 * @param {string|HTMLElement|jQuery} idOrNode
1292 * @param {jQuery.Promise|boolean} domPromise A promise that will be resolved
1293 * when the top-level widget of this infusion is inserted into DOM,
1294 * replacing the original node; or false for top-level invocation.
1295 * @return {OO.ui.Element}
1296 */
1297 OO.ui.Element.static.unsafeInfuse = function ( idOrNode, domPromise ) {
1298 // look for a cached result of a previous infusion.
1299 var id, $elem, data, cls, parts, parent, obj, top, state;
1300 if ( typeof idOrNode === 'string' ) {
1301 id = idOrNode;
1302 $elem = $( document.getElementById( id ) );
1303 } else {
1304 $elem = $( idOrNode );
1305 id = $elem.attr( 'id' );
1306 }
1307 if ( !$elem.length ) {
1308 throw new Error( 'Widget not found: ' + id );
1309 }
1310 data = $elem.data( 'ooui-infused' ) || $elem[ 0 ].oouiInfused;
1311 if ( data ) {
1312 // cached!
1313 if ( data === true ) {
1314 throw new Error( 'Circular dependency! ' + id );
1315 }
1316 return data;
1317 }
1318 data = $elem.attr( 'data-ooui' );
1319 if ( !data ) {
1320 throw new Error( 'No infusion data found: ' + id );
1321 }
1322 try {
1323 data = $.parseJSON( data );
1324 } catch ( _ ) {
1325 data = null;
1326 }
1327 if ( !( data && data._ ) ) {
1328 throw new Error( 'No valid infusion data found: ' + id );
1329 }
1330 if ( data._ === 'Tag' ) {
1331 // Special case: this is a raw Tag; wrap existing node, don't rebuild.
1332 return new OO.ui.Element( { $element: $elem } );
1333 }
1334 parts = data._.split( '.' );
1335 cls = OO.getProp.apply( OO, [ window ].concat( parts ) );
1336 if ( cls === undefined ) {
1337 // The PHP output might be old and not including the "OO.ui" prefix
1338 // TODO: Remove this back-compat after next major release
1339 cls = OO.getProp.apply( OO, [ OO.ui ].concat( parts ) );
1340 if ( cls === undefined ) {
1341 throw new Error( 'Unknown widget type: id: ' + id + ', class: ' + data._ );
1342 }
1343 }
1344
1345 // Verify that we're creating an OO.ui.Element instance
1346 parent = cls.parent;
1347
1348 while ( parent !== undefined ) {
1349 if ( parent === OO.ui.Element ) {
1350 // Safe
1351 break;
1352 }
1353
1354 parent = parent.parent;
1355 }
1356
1357 if ( parent !== OO.ui.Element ) {
1358 throw new Error( 'Unknown widget type: id: ' + id + ', class: ' + data._ );
1359 }
1360
1361 if ( domPromise === false ) {
1362 top = $.Deferred();
1363 domPromise = top.promise();
1364 }
1365 $elem.data( 'ooui-infused', true ); // prevent loops
1366 data.id = id; // implicit
1367 data = OO.copy( data, null, function deserialize( value ) {
1368 if ( OO.isPlainObject( value ) ) {
1369 if ( value.tag ) {
1370 return OO.ui.Element.static.unsafeInfuse( value.tag, domPromise );
1371 }
1372 if ( value.html ) {
1373 return new OO.ui.HtmlSnippet( value.html );
1374 }
1375 }
1376 } );
1377 // allow widgets to reuse parts of the DOM
1378 data = cls.static.reusePreInfuseDOM( $elem[ 0 ], data );
1379 // pick up dynamic state, like focus, value of form inputs, scroll position, etc.
1380 state = cls.static.gatherPreInfuseState( $elem[ 0 ], data );
1381 // rebuild widget
1382 // jscs:disable requireCapitalizedConstructors
1383 obj = new cls( data );
1384 // jscs:enable requireCapitalizedConstructors
1385 // now replace old DOM with this new DOM.
1386 if ( top ) {
1387 // An efficient constructor might be able to reuse the entire DOM tree of the original element,
1388 // so only mutate the DOM if we need to.
1389 if ( $elem[ 0 ] !== obj.$element[ 0 ] ) {
1390 $elem.replaceWith( obj.$element );
1391 // This element is now gone from the DOM, but if anyone is holding a reference to it,
1392 // let's allow them to OO.ui.infuse() it and do what they expect (T105828).
1393 // Do not use jQuery.data(), as using it on detached nodes leaks memory in 1.x line by design.
1394 $elem[ 0 ].oouiInfused = obj;
1395 }
1396 top.resolve();
1397 }
1398 obj.$element.data( 'ooui-infused', obj );
1399 // set the 'data-ooui' attribute so we can identify infused widgets
1400 obj.$element.attr( 'data-ooui', '' );
1401 // restore dynamic state after the new element is inserted into DOM
1402 domPromise.done( obj.restorePreInfuseState.bind( obj, state ) );
1403 return obj;
1404 };
1405
1406 /**
1407 * Pick out parts of `node`'s DOM to be reused when infusing a widget.
1408 *
1409 * This method **must not** make any changes to the DOM, only find interesting pieces and add them
1410 * to `config` (which should then be returned). Actual DOM juggling should then be done by the
1411 * constructor, which will be given the enhanced config.
1412 *
1413 * @protected
1414 * @param {HTMLElement} node
1415 * @param {Object} config
1416 * @return {Object}
1417 */
1418 OO.ui.Element.static.reusePreInfuseDOM = function ( node, config ) {
1419 return config;
1420 };
1421
1422 /**
1423 * Gather the dynamic state (focus, value of form inputs, scroll position, etc.) of a HTML DOM node
1424 * (and its children) that represent an Element of the same class and the given configuration,
1425 * generated by the PHP implementation.
1426 *
1427 * This method is called just before `node` is detached from the DOM. The return value of this
1428 * function will be passed to #restorePreInfuseState after the newly created widget's #$element
1429 * is inserted into DOM to replace `node`.
1430 *
1431 * @protected
1432 * @param {HTMLElement} node
1433 * @param {Object} config
1434 * @return {Object}
1435 */
1436 OO.ui.Element.static.gatherPreInfuseState = function () {
1437 return {};
1438 };
1439
1440 /**
1441 * Get a jQuery function within a specific document.
1442 *
1443 * @static
1444 * @param {jQuery|HTMLElement|HTMLDocument|Window} context Context to bind the function to
1445 * @param {jQuery} [$iframe] HTML iframe element that contains the document, omit if document is
1446 * not in an iframe
1447 * @return {Function} Bound jQuery function
1448 */
1449 OO.ui.Element.static.getJQuery = function ( context, $iframe ) {
1450 function wrapper( selector ) {
1451 return $( selector, wrapper.context );
1452 }
1453
1454 wrapper.context = this.getDocument( context );
1455
1456 if ( $iframe ) {
1457 wrapper.$iframe = $iframe;
1458 }
1459
1460 return wrapper;
1461 };
1462
1463 /**
1464 * Get the document of an element.
1465 *
1466 * @static
1467 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Object to get the document for
1468 * @return {HTMLDocument|null} Document object
1469 */
1470 OO.ui.Element.static.getDocument = function ( obj ) {
1471 // jQuery - selections created "offscreen" won't have a context, so .context isn't reliable
1472 return ( obj[ 0 ] && obj[ 0 ].ownerDocument ) ||
1473 // Empty jQuery selections might have a context
1474 obj.context ||
1475 // HTMLElement
1476 obj.ownerDocument ||
1477 // Window
1478 obj.document ||
1479 // HTMLDocument
1480 ( obj.nodeType === 9 && obj ) ||
1481 null;
1482 };
1483
1484 /**
1485 * Get the window of an element or document.
1486 *
1487 * @static
1488 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the window for
1489 * @return {Window} Window object
1490 */
1491 OO.ui.Element.static.getWindow = function ( obj ) {
1492 var doc = this.getDocument( obj );
1493 return doc.defaultView;
1494 };
1495
1496 /**
1497 * Get the direction of an element or document.
1498 *
1499 * @static
1500 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the direction for
1501 * @return {string} Text direction, either 'ltr' or 'rtl'
1502 */
1503 OO.ui.Element.static.getDir = function ( obj ) {
1504 var isDoc, isWin;
1505
1506 if ( obj instanceof jQuery ) {
1507 obj = obj[ 0 ];
1508 }
1509 isDoc = obj.nodeType === 9;
1510 isWin = obj.document !== undefined;
1511 if ( isDoc || isWin ) {
1512 if ( isWin ) {
1513 obj = obj.document;
1514 }
1515 obj = obj.body;
1516 }
1517 return $( obj ).css( 'direction' );
1518 };
1519
1520 /**
1521 * Get the offset between two frames.
1522 *
1523 * TODO: Make this function not use recursion.
1524 *
1525 * @static
1526 * @param {Window} from Window of the child frame
1527 * @param {Window} [to=window] Window of the parent frame
1528 * @param {Object} [offset] Offset to start with, used internally
1529 * @return {Object} Offset object, containing left and top properties
1530 */
1531 OO.ui.Element.static.getFrameOffset = function ( from, to, offset ) {
1532 var i, len, frames, frame, rect;
1533
1534 if ( !to ) {
1535 to = window;
1536 }
1537 if ( !offset ) {
1538 offset = { top: 0, left: 0 };
1539 }
1540 if ( from.parent === from ) {
1541 return offset;
1542 }
1543
1544 // Get iframe element
1545 frames = from.parent.document.getElementsByTagName( 'iframe' );
1546 for ( i = 0, len = frames.length; i < len; i++ ) {
1547 if ( frames[ i ].contentWindow === from ) {
1548 frame = frames[ i ];
1549 break;
1550 }
1551 }
1552
1553 // Recursively accumulate offset values
1554 if ( frame ) {
1555 rect = frame.getBoundingClientRect();
1556 offset.left += rect.left;
1557 offset.top += rect.top;
1558 if ( from !== to ) {
1559 this.getFrameOffset( from.parent, offset );
1560 }
1561 }
1562 return offset;
1563 };
1564
1565 /**
1566 * Get the offset between two elements.
1567 *
1568 * The two elements may be in a different frame, but in that case the frame $element is in must
1569 * be contained in the frame $anchor is in.
1570 *
1571 * @static
1572 * @param {jQuery} $element Element whose position to get
1573 * @param {jQuery} $anchor Element to get $element's position relative to
1574 * @return {Object} Translated position coordinates, containing top and left properties
1575 */
1576 OO.ui.Element.static.getRelativePosition = function ( $element, $anchor ) {
1577 var iframe, iframePos,
1578 pos = $element.offset(),
1579 anchorPos = $anchor.offset(),
1580 elementDocument = this.getDocument( $element ),
1581 anchorDocument = this.getDocument( $anchor );
1582
1583 // If $element isn't in the same document as $anchor, traverse up
1584 while ( elementDocument !== anchorDocument ) {
1585 iframe = elementDocument.defaultView.frameElement;
1586 if ( !iframe ) {
1587 throw new Error( '$element frame is not contained in $anchor frame' );
1588 }
1589 iframePos = $( iframe ).offset();
1590 pos.left += iframePos.left;
1591 pos.top += iframePos.top;
1592 elementDocument = iframe.ownerDocument;
1593 }
1594 pos.left -= anchorPos.left;
1595 pos.top -= anchorPos.top;
1596 return pos;
1597 };
1598
1599 /**
1600 * Get element border sizes.
1601 *
1602 * @static
1603 * @param {HTMLElement} el Element to measure
1604 * @return {Object} Dimensions object with `top`, `left`, `bottom` and `right` properties
1605 */
1606 OO.ui.Element.static.getBorders = function ( el ) {
1607 var doc = el.ownerDocument,
1608 win = doc.defaultView,
1609 style = win.getComputedStyle( el, null ),
1610 $el = $( el ),
1611 top = parseFloat( style ? style.borderTopWidth : $el.css( 'borderTopWidth' ) ) || 0,
1612 left = parseFloat( style ? style.borderLeftWidth : $el.css( 'borderLeftWidth' ) ) || 0,
1613 bottom = parseFloat( style ? style.borderBottomWidth : $el.css( 'borderBottomWidth' ) ) || 0,
1614 right = parseFloat( style ? style.borderRightWidth : $el.css( 'borderRightWidth' ) ) || 0;
1615
1616 return {
1617 top: top,
1618 left: left,
1619 bottom: bottom,
1620 right: right
1621 };
1622 };
1623
1624 /**
1625 * Get dimensions of an element or window.
1626 *
1627 * @static
1628 * @param {HTMLElement|Window} el Element to measure
1629 * @return {Object} Dimensions object with `borders`, `scroll`, `scrollbar` and `rect` properties
1630 */
1631 OO.ui.Element.static.getDimensions = function ( el ) {
1632 var $el, $win,
1633 doc = el.ownerDocument || el.document,
1634 win = doc.defaultView;
1635
1636 if ( win === el || el === doc.documentElement ) {
1637 $win = $( win );
1638 return {
1639 borders: { top: 0, left: 0, bottom: 0, right: 0 },
1640 scroll: {
1641 top: $win.scrollTop(),
1642 left: $win.scrollLeft()
1643 },
1644 scrollbar: { right: 0, bottom: 0 },
1645 rect: {
1646 top: 0,
1647 left: 0,
1648 bottom: $win.innerHeight(),
1649 right: $win.innerWidth()
1650 }
1651 };
1652 } else {
1653 $el = $( el );
1654 return {
1655 borders: this.getBorders( el ),
1656 scroll: {
1657 top: $el.scrollTop(),
1658 left: $el.scrollLeft()
1659 },
1660 scrollbar: {
1661 right: $el.innerWidth() - el.clientWidth,
1662 bottom: $el.innerHeight() - el.clientHeight
1663 },
1664 rect: el.getBoundingClientRect()
1665 };
1666 }
1667 };
1668
1669 /**
1670 * Get scrollable object parent
1671 *
1672 * documentElement can't be used to get or set the scrollTop
1673 * property on Blink. Changing and testing its value lets us
1674 * use 'body' or 'documentElement' based on what is working.
1675 *
1676 * https://code.google.com/p/chromium/issues/detail?id=303131
1677 *
1678 * @static
1679 * @param {HTMLElement} el Element to find scrollable parent for
1680 * @return {HTMLElement} Scrollable parent
1681 */
1682 OO.ui.Element.static.getRootScrollableElement = function ( el ) {
1683 var scrollTop, body;
1684
1685 if ( OO.ui.scrollableElement === undefined ) {
1686 body = el.ownerDocument.body;
1687 scrollTop = body.scrollTop;
1688 body.scrollTop = 1;
1689
1690 if ( body.scrollTop === 1 ) {
1691 body.scrollTop = scrollTop;
1692 OO.ui.scrollableElement = 'body';
1693 } else {
1694 OO.ui.scrollableElement = 'documentElement';
1695 }
1696 }
1697
1698 return el.ownerDocument[ OO.ui.scrollableElement ];
1699 };
1700
1701 /**
1702 * Get closest scrollable container.
1703 *
1704 * Traverses up until either a scrollable element or the root is reached, in which case the window
1705 * will be returned.
1706 *
1707 * @static
1708 * @param {HTMLElement} el Element to find scrollable container for
1709 * @param {string} [dimension] Dimension of scrolling to look for; `x`, `y` or omit for either
1710 * @return {HTMLElement} Closest scrollable container
1711 */
1712 OO.ui.Element.static.getClosestScrollableContainer = function ( el, dimension ) {
1713 var i, val,
1714 // props = [ 'overflow' ] doesn't work due to https://bugzilla.mozilla.org/show_bug.cgi?id=889091
1715 props = [ 'overflow-x', 'overflow-y' ],
1716 $parent = $( el ).parent();
1717
1718 if ( dimension === 'x' || dimension === 'y' ) {
1719 props = [ 'overflow-' + dimension ];
1720 }
1721
1722 while ( $parent.length ) {
1723 if ( $parent[ 0 ] === this.getRootScrollableElement( el ) ) {
1724 return $parent[ 0 ];
1725 }
1726 i = props.length;
1727 while ( i-- ) {
1728 val = $parent.css( props[ i ] );
1729 if ( val === 'auto' || val === 'scroll' ) {
1730 return $parent[ 0 ];
1731 }
1732 }
1733 $parent = $parent.parent();
1734 }
1735 return this.getDocument( el ).body;
1736 };
1737
1738 /**
1739 * Scroll element into view.
1740 *
1741 * @static
1742 * @param {HTMLElement} el Element to scroll into view
1743 * @param {Object} [config] Configuration options
1744 * @param {string} [config.duration] jQuery animation duration value
1745 * @param {string} [config.direction] Scroll in only one direction, e.g. 'x' or 'y', omit
1746 * to scroll in both directions
1747 * @param {Function} [config.complete] Function to call when scrolling completes
1748 */
1749 OO.ui.Element.static.scrollIntoView = function ( el, config ) {
1750 var rel, anim, callback, sc, $sc, eld, scd, $win;
1751
1752 // Configuration initialization
1753 config = config || {};
1754
1755 anim = {};
1756 callback = typeof config.complete === 'function' && config.complete;
1757 sc = this.getClosestScrollableContainer( el, config.direction );
1758 $sc = $( sc );
1759 eld = this.getDimensions( el );
1760 scd = this.getDimensions( sc );
1761 $win = $( this.getWindow( el ) );
1762
1763 // Compute the distances between the edges of el and the edges of the scroll viewport
1764 if ( $sc.is( 'html, body' ) ) {
1765 // If the scrollable container is the root, this is easy
1766 rel = {
1767 top: eld.rect.top,
1768 bottom: $win.innerHeight() - eld.rect.bottom,
1769 left: eld.rect.left,
1770 right: $win.innerWidth() - eld.rect.right
1771 };
1772 } else {
1773 // Otherwise, we have to subtract el's coordinates from sc's coordinates
1774 rel = {
1775 top: eld.rect.top - ( scd.rect.top + scd.borders.top ),
1776 bottom: scd.rect.bottom - scd.borders.bottom - scd.scrollbar.bottom - eld.rect.bottom,
1777 left: eld.rect.left - ( scd.rect.left + scd.borders.left ),
1778 right: scd.rect.right - scd.borders.right - scd.scrollbar.right - eld.rect.right
1779 };
1780 }
1781
1782 if ( !config.direction || config.direction === 'y' ) {
1783 if ( rel.top < 0 ) {
1784 anim.scrollTop = scd.scroll.top + rel.top;
1785 } else if ( rel.top > 0 && rel.bottom < 0 ) {
1786 anim.scrollTop = scd.scroll.top + Math.min( rel.top, -rel.bottom );
1787 }
1788 }
1789 if ( !config.direction || config.direction === 'x' ) {
1790 if ( rel.left < 0 ) {
1791 anim.scrollLeft = scd.scroll.left + rel.left;
1792 } else if ( rel.left > 0 && rel.right < 0 ) {
1793 anim.scrollLeft = scd.scroll.left + Math.min( rel.left, -rel.right );
1794 }
1795 }
1796 if ( !$.isEmptyObject( anim ) ) {
1797 $sc.stop( true ).animate( anim, config.duration || 'fast' );
1798 if ( callback ) {
1799 $sc.queue( function ( next ) {
1800 callback();
1801 next();
1802 } );
1803 }
1804 } else {
1805 if ( callback ) {
1806 callback();
1807 }
1808 }
1809 };
1810
1811 /**
1812 * Force the browser to reconsider whether it really needs to render scrollbars inside the element
1813 * and reserve space for them, because it probably doesn't.
1814 *
1815 * Workaround primarily for <https://code.google.com/p/chromium/issues/detail?id=387290>, but also
1816 * similar bugs in other browsers. "Just" forcing a reflow is not sufficient in all cases, we need
1817 * to first actually detach (or hide, but detaching is simpler) all children, *then* force a reflow,
1818 * and then reattach (or show) them back.
1819 *
1820 * @static
1821 * @param {HTMLElement} el Element to reconsider the scrollbars on
1822 */
1823 OO.ui.Element.static.reconsiderScrollbars = function ( el ) {
1824 var i, len, scrollLeft, scrollTop, nodes = [];
1825 // Save scroll position
1826 scrollLeft = el.scrollLeft;
1827 scrollTop = el.scrollTop;
1828 // Detach all children
1829 while ( el.firstChild ) {
1830 nodes.push( el.firstChild );
1831 el.removeChild( el.firstChild );
1832 }
1833 // Force reflow
1834 void el.offsetHeight;
1835 // Reattach all children
1836 for ( i = 0, len = nodes.length; i < len; i++ ) {
1837 el.appendChild( nodes[ i ] );
1838 }
1839 // Restore scroll position (no-op if scrollbars disappeared)
1840 el.scrollLeft = scrollLeft;
1841 el.scrollTop = scrollTop;
1842 };
1843
1844 /* Methods */
1845
1846 /**
1847 * Toggle visibility of an element.
1848 *
1849 * @param {boolean} [show] Make element visible, omit to toggle visibility
1850 * @fires visible
1851 * @chainable
1852 */
1853 OO.ui.Element.prototype.toggle = function ( show ) {
1854 show = show === undefined ? !this.visible : !!show;
1855
1856 if ( show !== this.isVisible() ) {
1857 this.visible = show;
1858 this.$element.toggleClass( 'oo-ui-element-hidden', !this.visible );
1859 this.emit( 'toggle', show );
1860 }
1861
1862 return this;
1863 };
1864
1865 /**
1866 * Check if element is visible.
1867 *
1868 * @return {boolean} element is visible
1869 */
1870 OO.ui.Element.prototype.isVisible = function () {
1871 return this.visible;
1872 };
1873
1874 /**
1875 * Get element data.
1876 *
1877 * @return {Mixed} Element data
1878 */
1879 OO.ui.Element.prototype.getData = function () {
1880 return this.data;
1881 };
1882
1883 /**
1884 * Set element data.
1885 *
1886 * @param {Mixed} Element data
1887 * @chainable
1888 */
1889 OO.ui.Element.prototype.setData = function ( data ) {
1890 this.data = data;
1891 return this;
1892 };
1893
1894 /**
1895 * Check if element supports one or more methods.
1896 *
1897 * @param {string|string[]} methods Method or list of methods to check
1898 * @return {boolean} All methods are supported
1899 */
1900 OO.ui.Element.prototype.supports = function ( methods ) {
1901 var i, len,
1902 support = 0;
1903
1904 methods = Array.isArray( methods ) ? methods : [ methods ];
1905 for ( i = 0, len = methods.length; i < len; i++ ) {
1906 if ( $.isFunction( this[ methods[ i ] ] ) ) {
1907 support++;
1908 }
1909 }
1910
1911 return methods.length === support;
1912 };
1913
1914 /**
1915 * Update the theme-provided classes.
1916 *
1917 * @localdoc This is called in element mixins and widget classes any time state changes.
1918 * Updating is debounced, minimizing overhead of changing multiple attributes and
1919 * guaranteeing that theme updates do not occur within an element's constructor
1920 */
1921 OO.ui.Element.prototype.updateThemeClasses = function () {
1922 this.debouncedUpdateThemeClassesHandler();
1923 };
1924
1925 /**
1926 * @private
1927 * @localdoc This method is called directly from the QUnit tests instead of #updateThemeClasses, to
1928 * make them synchronous.
1929 */
1930 OO.ui.Element.prototype.debouncedUpdateThemeClasses = function () {
1931 OO.ui.theme.updateElementClasses( this );
1932 };
1933
1934 /**
1935 * Get the HTML tag name.
1936 *
1937 * Override this method to base the result on instance information.
1938 *
1939 * @return {string} HTML tag name
1940 */
1941 OO.ui.Element.prototype.getTagName = function () {
1942 return this.constructor.static.tagName;
1943 };
1944
1945 /**
1946 * Check if the element is attached to the DOM
1947 * @return {boolean} The element is attached to the DOM
1948 */
1949 OO.ui.Element.prototype.isElementAttached = function () {
1950 return $.contains( this.getElementDocument(), this.$element[ 0 ] );
1951 };
1952
1953 /**
1954 * Get the DOM document.
1955 *
1956 * @return {HTMLDocument} Document object
1957 */
1958 OO.ui.Element.prototype.getElementDocument = function () {
1959 // Don't cache this in other ways either because subclasses could can change this.$element
1960 return OO.ui.Element.static.getDocument( this.$element );
1961 };
1962
1963 /**
1964 * Get the DOM window.
1965 *
1966 * @return {Window} Window object
1967 */
1968 OO.ui.Element.prototype.getElementWindow = function () {
1969 return OO.ui.Element.static.getWindow( this.$element );
1970 };
1971
1972 /**
1973 * Get closest scrollable container.
1974 */
1975 OO.ui.Element.prototype.getClosestScrollableElementContainer = function () {
1976 return OO.ui.Element.static.getClosestScrollableContainer( this.$element[ 0 ] );
1977 };
1978
1979 /**
1980 * Get group element is in.
1981 *
1982 * @return {OO.ui.mixin.GroupElement|null} Group element, null if none
1983 */
1984 OO.ui.Element.prototype.getElementGroup = function () {
1985 return this.elementGroup;
1986 };
1987
1988 /**
1989 * Set group element is in.
1990 *
1991 * @param {OO.ui.mixin.GroupElement|null} group Group element, null if none
1992 * @chainable
1993 */
1994 OO.ui.Element.prototype.setElementGroup = function ( group ) {
1995 this.elementGroup = group;
1996 return this;
1997 };
1998
1999 /**
2000 * Scroll element into view.
2001 *
2002 * @param {Object} [config] Configuration options
2003 */
2004 OO.ui.Element.prototype.scrollElementIntoView = function ( config ) {
2005 return OO.ui.Element.static.scrollIntoView( this.$element[ 0 ], config );
2006 };
2007
2008 /**
2009 * Restore the pre-infusion dynamic state for this widget.
2010 *
2011 * This method is called after #$element has been inserted into DOM. The parameter is the return
2012 * value of #gatherPreInfuseState.
2013 *
2014 * @protected
2015 * @param {Object} state
2016 */
2017 OO.ui.Element.prototype.restorePreInfuseState = function () {
2018 };
2019
2020 /**
2021 * Layouts are containers for elements and are used to arrange other widgets of arbitrary type in a way
2022 * that is centrally controlled and can be updated dynamically. Layouts can be, and usually are, combined.
2023 * See {@link OO.ui.FieldsetLayout FieldsetLayout}, {@link OO.ui.FieldLayout FieldLayout}, {@link OO.ui.FormLayout FormLayout},
2024 * {@link OO.ui.PanelLayout PanelLayout}, {@link OO.ui.StackLayout StackLayout}, {@link OO.ui.PageLayout PageLayout},
2025 * {@link OO.ui.HorizontalLayout HorizontalLayout}, and {@link OO.ui.BookletLayout BookletLayout} for more information and examples.
2026 *
2027 * @abstract
2028 * @class
2029 * @extends OO.ui.Element
2030 * @mixins OO.EventEmitter
2031 *
2032 * @constructor
2033 * @param {Object} [config] Configuration options
2034 */
2035 OO.ui.Layout = function OoUiLayout( config ) {
2036 // Configuration initialization
2037 config = config || {};
2038
2039 // Parent constructor
2040 OO.ui.Layout.parent.call( this, config );
2041
2042 // Mixin constructors
2043 OO.EventEmitter.call( this );
2044
2045 // Initialization
2046 this.$element.addClass( 'oo-ui-layout' );
2047 };
2048
2049 /* Setup */
2050
2051 OO.inheritClass( OO.ui.Layout, OO.ui.Element );
2052 OO.mixinClass( OO.ui.Layout, OO.EventEmitter );
2053
2054 /**
2055 * Widgets are compositions of one or more OOjs UI elements that users can both view
2056 * and interact with. All widgets can be configured and modified via a standard API,
2057 * and their state can change dynamically according to a model.
2058 *
2059 * @abstract
2060 * @class
2061 * @extends OO.ui.Element
2062 * @mixins OO.EventEmitter
2063 *
2064 * @constructor
2065 * @param {Object} [config] Configuration options
2066 * @cfg {boolean} [disabled=false] Disable the widget. Disabled widgets cannot be used and their
2067 * appearance reflects this state.
2068 */
2069 OO.ui.Widget = function OoUiWidget( config ) {
2070 // Initialize config
2071 config = $.extend( { disabled: false }, config );
2072
2073 // Parent constructor
2074 OO.ui.Widget.parent.call( this, config );
2075
2076 // Mixin constructors
2077 OO.EventEmitter.call( this );
2078
2079 // Properties
2080 this.disabled = null;
2081 this.wasDisabled = null;
2082
2083 // Initialization
2084 this.$element.addClass( 'oo-ui-widget' );
2085 this.setDisabled( !!config.disabled );
2086 };
2087
2088 /* Setup */
2089
2090 OO.inheritClass( OO.ui.Widget, OO.ui.Element );
2091 OO.mixinClass( OO.ui.Widget, OO.EventEmitter );
2092
2093 /* Static Properties */
2094
2095 /**
2096 * Whether this widget will behave reasonably when wrapped in a HTML `<label>`. If this is true,
2097 * wrappers such as OO.ui.FieldLayout may use a `<label>` instead of implementing own label click
2098 * handling.
2099 *
2100 * @static
2101 * @inheritable
2102 * @property {boolean}
2103 */
2104 OO.ui.Widget.static.supportsSimpleLabel = false;
2105
2106 /* Events */
2107
2108 /**
2109 * @event disable
2110 *
2111 * A 'disable' event is emitted when the disabled state of the widget changes
2112 * (i.e. on disable **and** enable).
2113 *
2114 * @param {boolean} disabled Widget is disabled
2115 */
2116
2117 /**
2118 * @event toggle
2119 *
2120 * A 'toggle' event is emitted when the visibility of the widget changes.
2121 *
2122 * @param {boolean} visible Widget is visible
2123 */
2124
2125 /* Methods */
2126
2127 /**
2128 * Check if the widget is disabled.
2129 *
2130 * @return {boolean} Widget is disabled
2131 */
2132 OO.ui.Widget.prototype.isDisabled = function () {
2133 return this.disabled;
2134 };
2135
2136 /**
2137 * Set the 'disabled' state of the widget.
2138 *
2139 * When a widget is disabled, it cannot be used and its appearance is updated to reflect this state.
2140 *
2141 * @param {boolean} disabled Disable widget
2142 * @chainable
2143 */
2144 OO.ui.Widget.prototype.setDisabled = function ( disabled ) {
2145 var isDisabled;
2146
2147 this.disabled = !!disabled;
2148 isDisabled = this.isDisabled();
2149 if ( isDisabled !== this.wasDisabled ) {
2150 this.$element.toggleClass( 'oo-ui-widget-disabled', isDisabled );
2151 this.$element.toggleClass( 'oo-ui-widget-enabled', !isDisabled );
2152 this.$element.attr( 'aria-disabled', isDisabled.toString() );
2153 this.emit( 'disable', isDisabled );
2154 this.updateThemeClasses();
2155 }
2156 this.wasDisabled = isDisabled;
2157
2158 return this;
2159 };
2160
2161 /**
2162 * Update the disabled state, in case of changes in parent widget.
2163 *
2164 * @chainable
2165 */
2166 OO.ui.Widget.prototype.updateDisabled = function () {
2167 this.setDisabled( this.disabled );
2168 return this;
2169 };
2170
2171 /**
2172 * A window is a container for elements that are in a child frame. They are used with
2173 * a window manager (OO.ui.WindowManager), which is used to open and close the window and control
2174 * its presentation. The size of a window is specified using a symbolic name (e.g., ‘small’, ‘medium’,
2175 * ‘large’), which is interpreted by the window manager. If the requested size is not recognized,
2176 * the window manager will choose a sensible fallback.
2177 *
2178 * The lifecycle of a window has three primary stages (opening, opened, and closing) in which
2179 * different processes are executed:
2180 *
2181 * **opening**: The opening stage begins when the window manager's {@link OO.ui.WindowManager#openWindow
2182 * openWindow} or the window's {@link #open open} methods are used, and the window manager begins to open
2183 * the window.
2184 *
2185 * - {@link #getSetupProcess} method is called and its result executed
2186 * - {@link #getReadyProcess} method is called and its result executed
2187 *
2188 * **opened**: The window is now open
2189 *
2190 * **closing**: The closing stage begins when the window manager's
2191 * {@link OO.ui.WindowManager#closeWindow closeWindow}
2192 * or the window's {@link #close} methods are used, and the window manager begins to close the window.
2193 *
2194 * - {@link #getHoldProcess} method is called and its result executed
2195 * - {@link #getTeardownProcess} method is called and its result executed. The window is now closed
2196 *
2197 * Each of the window's processes (setup, ready, hold, and teardown) can be extended in subclasses
2198 * by overriding the window's #getSetupProcess, #getReadyProcess, #getHoldProcess and #getTeardownProcess
2199 * methods. Note that each {@link OO.ui.Process process} is executed in series, so asynchronous
2200 * processing can complete. Always assume window processes are executed asynchronously.
2201 *
2202 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
2203 *
2204 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows
2205 *
2206 * @abstract
2207 * @class
2208 * @extends OO.ui.Element
2209 * @mixins OO.EventEmitter
2210 *
2211 * @constructor
2212 * @param {Object} [config] Configuration options
2213 * @cfg {string} [size] Symbolic name of the dialog size: `small`, `medium`, `large`, `larger` or
2214 * `full`. If omitted, the value of the {@link #static-size static size} property will be used.
2215 */
2216 OO.ui.Window = function OoUiWindow( config ) {
2217 // Configuration initialization
2218 config = config || {};
2219
2220 // Parent constructor
2221 OO.ui.Window.parent.call( this, config );
2222
2223 // Mixin constructors
2224 OO.EventEmitter.call( this );
2225
2226 // Properties
2227 this.manager = null;
2228 this.size = config.size || this.constructor.static.size;
2229 this.$frame = $( '<div>' );
2230 this.$overlay = $( '<div>' );
2231 this.$content = $( '<div>' );
2232
2233 this.$focusTrapBefore = $( '<div>' ).prop( 'tabIndex', 0 );
2234 this.$focusTrapAfter = $( '<div>' ).prop( 'tabIndex', 0 );
2235 this.$focusTraps = this.$focusTrapBefore.add( this.$focusTrapAfter );
2236
2237 // Initialization
2238 this.$overlay.addClass( 'oo-ui-window-overlay' );
2239 this.$content
2240 .addClass( 'oo-ui-window-content' )
2241 .attr( 'tabindex', 0 );
2242 this.$frame
2243 .addClass( 'oo-ui-window-frame' )
2244 .append( this.$focusTrapBefore, this.$content, this.$focusTrapAfter );
2245
2246 this.$element
2247 .addClass( 'oo-ui-window' )
2248 .append( this.$frame, this.$overlay );
2249
2250 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
2251 // that reference properties not initialized at that time of parent class construction
2252 // TODO: Find a better way to handle post-constructor setup
2253 this.visible = false;
2254 this.$element.addClass( 'oo-ui-element-hidden' );
2255 };
2256
2257 /* Setup */
2258
2259 OO.inheritClass( OO.ui.Window, OO.ui.Element );
2260 OO.mixinClass( OO.ui.Window, OO.EventEmitter );
2261
2262 /* Static Properties */
2263
2264 /**
2265 * Symbolic name of the window size: `small`, `medium`, `large`, `larger` or `full`.
2266 *
2267 * The static size is used if no #size is configured during construction.
2268 *
2269 * @static
2270 * @inheritable
2271 * @property {string}
2272 */
2273 OO.ui.Window.static.size = 'medium';
2274
2275 /* Methods */
2276
2277 /**
2278 * Handle mouse down events.
2279 *
2280 * @private
2281 * @param {jQuery.Event} e Mouse down event
2282 */
2283 OO.ui.Window.prototype.onMouseDown = function ( e ) {
2284 // Prevent clicking on the click-block from stealing focus
2285 if ( e.target === this.$element[ 0 ] ) {
2286 return false;
2287 }
2288 };
2289
2290 /**
2291 * Check if the window has been initialized.
2292 *
2293 * Initialization occurs when a window is added to a manager.
2294 *
2295 * @return {boolean} Window has been initialized
2296 */
2297 OO.ui.Window.prototype.isInitialized = function () {
2298 return !!this.manager;
2299 };
2300
2301 /**
2302 * Check if the window is visible.
2303 *
2304 * @return {boolean} Window is visible
2305 */
2306 OO.ui.Window.prototype.isVisible = function () {
2307 return this.visible;
2308 };
2309
2310 /**
2311 * Check if the window is opening.
2312 *
2313 * This method is a wrapper around the window manager's {@link OO.ui.WindowManager#isOpening isOpening}
2314 * method.
2315 *
2316 * @return {boolean} Window is opening
2317 */
2318 OO.ui.Window.prototype.isOpening = function () {
2319 return this.manager.isOpening( this );
2320 };
2321
2322 /**
2323 * Check if the window is closing.
2324 *
2325 * This method is a wrapper around the window manager's {@link OO.ui.WindowManager#isClosing isClosing} method.
2326 *
2327 * @return {boolean} Window is closing
2328 */
2329 OO.ui.Window.prototype.isClosing = function () {
2330 return this.manager.isClosing( this );
2331 };
2332
2333 /**
2334 * Check if the window is opened.
2335 *
2336 * This method is a wrapper around the window manager's {@link OO.ui.WindowManager#isOpened isOpened} method.
2337 *
2338 * @return {boolean} Window is opened
2339 */
2340 OO.ui.Window.prototype.isOpened = function () {
2341 return this.manager.isOpened( this );
2342 };
2343
2344 /**
2345 * Get the window manager.
2346 *
2347 * All windows must be attached to a window manager, which is used to open
2348 * and close the window and control its presentation.
2349 *
2350 * @return {OO.ui.WindowManager} Manager of window
2351 */
2352 OO.ui.Window.prototype.getManager = function () {
2353 return this.manager;
2354 };
2355
2356 /**
2357 * Get the symbolic name of the window size (e.g., `small` or `medium`).
2358 *
2359 * @return {string} Symbolic name of the size: `small`, `medium`, `large`, `larger`, `full`
2360 */
2361 OO.ui.Window.prototype.getSize = function () {
2362 var viewport = OO.ui.Element.static.getDimensions( this.getElementWindow() ),
2363 sizes = this.manager.constructor.static.sizes,
2364 size = this.size;
2365
2366 if ( !sizes[ size ] ) {
2367 size = this.manager.constructor.static.defaultSize;
2368 }
2369 if ( size !== 'full' && viewport.rect.right - viewport.rect.left < sizes[ size ].width ) {
2370 size = 'full';
2371 }
2372
2373 return size;
2374 };
2375
2376 /**
2377 * Get the size properties associated with the current window size
2378 *
2379 * @return {Object} Size properties
2380 */
2381 OO.ui.Window.prototype.getSizeProperties = function () {
2382 return this.manager.constructor.static.sizes[ this.getSize() ];
2383 };
2384
2385 /**
2386 * Disable transitions on window's frame for the duration of the callback function, then enable them
2387 * back.
2388 *
2389 * @private
2390 * @param {Function} callback Function to call while transitions are disabled
2391 */
2392 OO.ui.Window.prototype.withoutSizeTransitions = function ( callback ) {
2393 // Temporarily resize the frame so getBodyHeight() can use scrollHeight measurements.
2394 // Disable transitions first, otherwise we'll get values from when the window was animating.
2395 var oldTransition,
2396 styleObj = this.$frame[ 0 ].style;
2397 oldTransition = styleObj.transition || styleObj.OTransition || styleObj.MsTransition ||
2398 styleObj.MozTransition || styleObj.WebkitTransition;
2399 styleObj.transition = styleObj.OTransition = styleObj.MsTransition =
2400 styleObj.MozTransition = styleObj.WebkitTransition = 'none';
2401 callback();
2402 // Force reflow to make sure the style changes done inside callback really are not transitioned
2403 this.$frame.height();
2404 styleObj.transition = styleObj.OTransition = styleObj.MsTransition =
2405 styleObj.MozTransition = styleObj.WebkitTransition = oldTransition;
2406 };
2407
2408 /**
2409 * Get the height of the full window contents (i.e., the window head, body and foot together).
2410 *
2411 * What consistitutes the head, body, and foot varies depending on the window type.
2412 * A {@link OO.ui.MessageDialog message dialog} displays a title and message in its body,
2413 * and any actions in the foot. A {@link OO.ui.ProcessDialog process dialog} displays a title
2414 * and special actions in the head, and dialog content in the body.
2415 *
2416 * To get just the height of the dialog body, use the #getBodyHeight method.
2417 *
2418 * @return {number} The height of the window contents (the dialog head, body and foot) in pixels
2419 */
2420 OO.ui.Window.prototype.getContentHeight = function () {
2421 var bodyHeight,
2422 win = this,
2423 bodyStyleObj = this.$body[ 0 ].style,
2424 frameStyleObj = this.$frame[ 0 ].style;
2425
2426 // Temporarily resize the frame so getBodyHeight() can use scrollHeight measurements.
2427 // Disable transitions first, otherwise we'll get values from when the window was animating.
2428 this.withoutSizeTransitions( function () {
2429 var oldHeight = frameStyleObj.height,
2430 oldPosition = bodyStyleObj.position;
2431 frameStyleObj.height = '1px';
2432 // Force body to resize to new width
2433 bodyStyleObj.position = 'relative';
2434 bodyHeight = win.getBodyHeight();
2435 frameStyleObj.height = oldHeight;
2436 bodyStyleObj.position = oldPosition;
2437 } );
2438
2439 return (
2440 // Add buffer for border
2441 ( this.$frame.outerHeight() - this.$frame.innerHeight() ) +
2442 // Use combined heights of children
2443 ( this.$head.outerHeight( true ) + bodyHeight + this.$foot.outerHeight( true ) )
2444 );
2445 };
2446
2447 /**
2448 * Get the height of the window body.
2449 *
2450 * To get the height of the full window contents (the window body, head, and foot together),
2451 * use #getContentHeight.
2452 *
2453 * When this function is called, the window will temporarily have been resized
2454 * to height=1px, so .scrollHeight measurements can be taken accurately.
2455 *
2456 * @return {number} Height of the window body in pixels
2457 */
2458 OO.ui.Window.prototype.getBodyHeight = function () {
2459 return this.$body[ 0 ].scrollHeight;
2460 };
2461
2462 /**
2463 * Get the directionality of the frame (right-to-left or left-to-right).
2464 *
2465 * @return {string} Directionality: `'ltr'` or `'rtl'`
2466 */
2467 OO.ui.Window.prototype.getDir = function () {
2468 return OO.ui.Element.static.getDir( this.$content ) || 'ltr';
2469 };
2470
2471 /**
2472 * Get the 'setup' process.
2473 *
2474 * The setup process is used to set up a window for use in a particular context,
2475 * based on the `data` argument. This method is called during the opening phase of the window’s
2476 * lifecycle.
2477 *
2478 * Override this method to add additional steps to the ‘setup’ process the parent method provides
2479 * using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next} methods
2480 * of OO.ui.Process.
2481 *
2482 * To add window content that persists between openings, you may wish to use the #initialize method
2483 * instead.
2484 *
2485 * @param {Object} [data] Window opening data
2486 * @return {OO.ui.Process} Setup process
2487 */
2488 OO.ui.Window.prototype.getSetupProcess = function () {
2489 return new OO.ui.Process();
2490 };
2491
2492 /**
2493 * Get the ‘ready’ process.
2494 *
2495 * The ready process is used to ready a window for use in a particular
2496 * context, based on the `data` argument. This method is called during the opening phase of
2497 * the window’s lifecycle, after the window has been {@link #getSetupProcess setup}.
2498 *
2499 * Override this method to add additional steps to the ‘ready’ process the parent method
2500 * provides using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next}
2501 * methods of OO.ui.Process.
2502 *
2503 * @param {Object} [data] Window opening data
2504 * @return {OO.ui.Process} Ready process
2505 */
2506 OO.ui.Window.prototype.getReadyProcess = function () {
2507 return new OO.ui.Process();
2508 };
2509
2510 /**
2511 * Get the 'hold' process.
2512 *
2513 * The hold proccess is used to keep a window from being used in a particular context,
2514 * based on the `data` argument. This method is called during the closing phase of the window’s
2515 * lifecycle.
2516 *
2517 * Override this method to add additional steps to the 'hold' process the parent method provides
2518 * using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next} methods
2519 * of OO.ui.Process.
2520 *
2521 * @param {Object} [data] Window closing data
2522 * @return {OO.ui.Process} Hold process
2523 */
2524 OO.ui.Window.prototype.getHoldProcess = function () {
2525 return new OO.ui.Process();
2526 };
2527
2528 /**
2529 * Get the ‘teardown’ process.
2530 *
2531 * The teardown process is used to teardown a window after use. During teardown,
2532 * user interactions within the window are conveyed and the window is closed, based on the `data`
2533 * argument. This method is called during the closing phase of the window’s lifecycle.
2534 *
2535 * Override this method to add additional steps to the ‘teardown’ process the parent method provides
2536 * using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next} methods
2537 * of OO.ui.Process.
2538 *
2539 * @param {Object} [data] Window closing data
2540 * @return {OO.ui.Process} Teardown process
2541 */
2542 OO.ui.Window.prototype.getTeardownProcess = function () {
2543 return new OO.ui.Process();
2544 };
2545
2546 /**
2547 * Set the window manager.
2548 *
2549 * This will cause the window to initialize. Calling it more than once will cause an error.
2550 *
2551 * @param {OO.ui.WindowManager} manager Manager for this window
2552 * @throws {Error} An error is thrown if the method is called more than once
2553 * @chainable
2554 */
2555 OO.ui.Window.prototype.setManager = function ( manager ) {
2556 if ( this.manager ) {
2557 throw new Error( 'Cannot set window manager, window already has a manager' );
2558 }
2559
2560 this.manager = manager;
2561 this.initialize();
2562
2563 return this;
2564 };
2565
2566 /**
2567 * Set the window size by symbolic name (e.g., 'small' or 'medium')
2568 *
2569 * @param {string} size Symbolic name of size: `small`, `medium`, `large`, `larger` or
2570 * `full`
2571 * @chainable
2572 */
2573 OO.ui.Window.prototype.setSize = function ( size ) {
2574 this.size = size;
2575 this.updateSize();
2576 return this;
2577 };
2578
2579 /**
2580 * Update the window size.
2581 *
2582 * @throws {Error} An error is thrown if the window is not attached to a window manager
2583 * @chainable
2584 */
2585 OO.ui.Window.prototype.updateSize = function () {
2586 if ( !this.manager ) {
2587 throw new Error( 'Cannot update window size, must be attached to a manager' );
2588 }
2589
2590 this.manager.updateWindowSize( this );
2591
2592 return this;
2593 };
2594
2595 /**
2596 * Set window dimensions. This method is called by the {@link OO.ui.WindowManager window manager}
2597 * when the window is opening. In general, setDimensions should not be called directly.
2598 *
2599 * To set the size of the window, use the #setSize method.
2600 *
2601 * @param {Object} dim CSS dimension properties
2602 * @param {string|number} [dim.width] Width
2603 * @param {string|number} [dim.minWidth] Minimum width
2604 * @param {string|number} [dim.maxWidth] Maximum width
2605 * @param {string|number} [dim.width] Height, omit to set based on height of contents
2606 * @param {string|number} [dim.minWidth] Minimum height
2607 * @param {string|number} [dim.maxWidth] Maximum height
2608 * @chainable
2609 */
2610 OO.ui.Window.prototype.setDimensions = function ( dim ) {
2611 var height,
2612 win = this,
2613 styleObj = this.$frame[ 0 ].style;
2614
2615 // Calculate the height we need to set using the correct width
2616 if ( dim.height === undefined ) {
2617 this.withoutSizeTransitions( function () {
2618 var oldWidth = styleObj.width;
2619 win.$frame.css( 'width', dim.width || '' );
2620 height = win.getContentHeight();
2621 styleObj.width = oldWidth;
2622 } );
2623 } else {
2624 height = dim.height;
2625 }
2626
2627 this.$frame.css( {
2628 width: dim.width || '',
2629 minWidth: dim.minWidth || '',
2630 maxWidth: dim.maxWidth || '',
2631 height: height || '',
2632 minHeight: dim.minHeight || '',
2633 maxHeight: dim.maxHeight || ''
2634 } );
2635
2636 return this;
2637 };
2638
2639 /**
2640 * Initialize window contents.
2641 *
2642 * Before the window is opened for the first time, #initialize is called so that content that
2643 * persists between openings can be added to the window.
2644 *
2645 * To set up a window with new content each time the window opens, use #getSetupProcess.
2646 *
2647 * @throws {Error} An error is thrown if the window is not attached to a window manager
2648 * @chainable
2649 */
2650 OO.ui.Window.prototype.initialize = function () {
2651 if ( !this.manager ) {
2652 throw new Error( 'Cannot initialize window, must be attached to a manager' );
2653 }
2654
2655 // Properties
2656 this.$head = $( '<div>' );
2657 this.$body = $( '<div>' );
2658 this.$foot = $( '<div>' );
2659 this.$document = $( this.getElementDocument() );
2660
2661 // Events
2662 this.$element.on( 'mousedown', this.onMouseDown.bind( this ) );
2663
2664 // Initialization
2665 this.$head.addClass( 'oo-ui-window-head' );
2666 this.$body.addClass( 'oo-ui-window-body' );
2667 this.$foot.addClass( 'oo-ui-window-foot' );
2668 this.$content.append( this.$head, this.$body, this.$foot );
2669
2670 return this;
2671 };
2672
2673 /**
2674 * Called when someone tries to focus the hidden element at the end of the dialog.
2675 * Sends focus back to the start of the dialog.
2676 *
2677 * @param {jQuery.Event} event Focus event
2678 */
2679 OO.ui.Window.prototype.onFocusTrapFocused = function ( event ) {
2680 if ( this.$focusTrapBefore.is( event.target ) ) {
2681 OO.ui.findFocusable( this.$content, true ).focus();
2682 } else {
2683 // this.$content is the part of the focus cycle, and is the first focusable element
2684 this.$content.focus();
2685 }
2686 };
2687
2688 /**
2689 * Open the window.
2690 *
2691 * This method is a wrapper around a call to the window manager’s {@link OO.ui.WindowManager#openWindow openWindow}
2692 * method, which returns a promise resolved when the window is done opening.
2693 *
2694 * To customize the window each time it opens, use #getSetupProcess or #getReadyProcess.
2695 *
2696 * @param {Object} [data] Window opening data
2697 * @return {jQuery.Promise} Promise resolved with a value when the window is opened, or rejected
2698 * if the window fails to open. When the promise is resolved successfully, the first argument of the
2699 * value is a new promise, which is resolved when the window begins closing.
2700 * @throws {Error} An error is thrown if the window is not attached to a window manager
2701 */
2702 OO.ui.Window.prototype.open = function ( data ) {
2703 if ( !this.manager ) {
2704 throw new Error( 'Cannot open window, must be attached to a manager' );
2705 }
2706
2707 return this.manager.openWindow( this, data );
2708 };
2709
2710 /**
2711 * Close the window.
2712 *
2713 * This method is a wrapper around a call to the window
2714 * manager’s {@link OO.ui.WindowManager#closeWindow closeWindow} method,
2715 * which returns a closing promise resolved when the window is done closing.
2716 *
2717 * The window's #getHoldProcess and #getTeardownProcess methods are called during the closing
2718 * phase of the window’s lifecycle and can be used to specify closing behavior each time
2719 * the window closes.
2720 *
2721 * @param {Object} [data] Window closing data
2722 * @return {jQuery.Promise} Promise resolved when window is closed
2723 * @throws {Error} An error is thrown if the window is not attached to a window manager
2724 */
2725 OO.ui.Window.prototype.close = function ( data ) {
2726 if ( !this.manager ) {
2727 throw new Error( 'Cannot close window, must be attached to a manager' );
2728 }
2729
2730 return this.manager.closeWindow( this, data );
2731 };
2732
2733 /**
2734 * Setup window.
2735 *
2736 * This is called by OO.ui.WindowManager during window opening, and should not be called directly
2737 * by other systems.
2738 *
2739 * @param {Object} [data] Window opening data
2740 * @return {jQuery.Promise} Promise resolved when window is setup
2741 */
2742 OO.ui.Window.prototype.setup = function ( data ) {
2743 var win = this;
2744
2745 this.toggle( true );
2746
2747 this.focusTrapHandler = OO.ui.bind( this.onFocusTrapFocused, this );
2748 this.$focusTraps.on( 'focus', this.focusTrapHandler );
2749
2750 return this.getSetupProcess( data ).execute().then( function () {
2751 // Force redraw by asking the browser to measure the elements' widths
2752 win.$element.addClass( 'oo-ui-window-active oo-ui-window-setup' ).width();
2753 win.$content.addClass( 'oo-ui-window-content-setup' ).width();
2754 } );
2755 };
2756
2757 /**
2758 * Ready window.
2759 *
2760 * This is called by OO.ui.WindowManager during window opening, and should not be called directly
2761 * by other systems.
2762 *
2763 * @param {Object} [data] Window opening data
2764 * @return {jQuery.Promise} Promise resolved when window is ready
2765 */
2766 OO.ui.Window.prototype.ready = function ( data ) {
2767 var win = this;
2768
2769 this.$content.focus();
2770 return this.getReadyProcess( data ).execute().then( function () {
2771 // Force redraw by asking the browser to measure the elements' widths
2772 win.$element.addClass( 'oo-ui-window-ready' ).width();
2773 win.$content.addClass( 'oo-ui-window-content-ready' ).width();
2774 } );
2775 };
2776
2777 /**
2778 * Hold window.
2779 *
2780 * This is called by OO.ui.WindowManager during window closing, and should not be called directly
2781 * by other systems.
2782 *
2783 * @param {Object} [data] Window closing data
2784 * @return {jQuery.Promise} Promise resolved when window is held
2785 */
2786 OO.ui.Window.prototype.hold = function ( data ) {
2787 var win = this;
2788
2789 return this.getHoldProcess( data ).execute().then( function () {
2790 // Get the focused element within the window's content
2791 var $focus = win.$content.find( OO.ui.Element.static.getDocument( win.$content ).activeElement );
2792
2793 // Blur the focused element
2794 if ( $focus.length ) {
2795 $focus[ 0 ].blur();
2796 }
2797
2798 // Force redraw by asking the browser to measure the elements' widths
2799 win.$element.removeClass( 'oo-ui-window-ready' ).width();
2800 win.$content.removeClass( 'oo-ui-window-content-ready' ).width();
2801 } );
2802 };
2803
2804 /**
2805 * Teardown window.
2806 *
2807 * This is called by OO.ui.WindowManager during window closing, and should not be called directly
2808 * by other systems.
2809 *
2810 * @param {Object} [data] Window closing data
2811 * @return {jQuery.Promise} Promise resolved when window is torn down
2812 */
2813 OO.ui.Window.prototype.teardown = function ( data ) {
2814 var win = this;
2815
2816 return this.getTeardownProcess( data ).execute().then( function () {
2817 // Force redraw by asking the browser to measure the elements' widths
2818 win.$element.removeClass( 'oo-ui-window-active oo-ui-window-setup' ).width();
2819 win.$content.removeClass( 'oo-ui-window-content-setup' ).width();
2820 win.$focusTraps.off( 'focus', win.focusTrapHandler );
2821 win.toggle( false );
2822 } );
2823 };
2824
2825 /**
2826 * The Dialog class serves as the base class for the other types of dialogs.
2827 * Unless extended to include controls, the rendered dialog box is a simple window
2828 * that users can close by hitting the ‘Esc’ key. Dialog windows are used with OO.ui.WindowManager,
2829 * which opens, closes, and controls the presentation of the window. See the
2830 * [OOjs UI documentation on MediaWiki] [1] for more information.
2831 *
2832 * @example
2833 * // A simple dialog window.
2834 * function MyDialog( config ) {
2835 * MyDialog.parent.call( this, config );
2836 * }
2837 * OO.inheritClass( MyDialog, OO.ui.Dialog );
2838 * MyDialog.prototype.initialize = function () {
2839 * MyDialog.parent.prototype.initialize.call( this );
2840 * this.content = new OO.ui.PanelLayout( { padded: true, expanded: false } );
2841 * this.content.$element.append( '<p>A simple dialog window. Press \'Esc\' to close.</p>' );
2842 * this.$body.append( this.content.$element );
2843 * };
2844 * MyDialog.prototype.getBodyHeight = function () {
2845 * return this.content.$element.outerHeight( true );
2846 * };
2847 * var myDialog = new MyDialog( {
2848 * size: 'medium'
2849 * } );
2850 * // Create and append a window manager, which opens and closes the window.
2851 * var windowManager = new OO.ui.WindowManager();
2852 * $( 'body' ).append( windowManager.$element );
2853 * windowManager.addWindows( [ myDialog ] );
2854 * // Open the window!
2855 * windowManager.openWindow( myDialog );
2856 *
2857 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Dialogs
2858 *
2859 * @abstract
2860 * @class
2861 * @extends OO.ui.Window
2862 * @mixins OO.ui.mixin.PendingElement
2863 *
2864 * @constructor
2865 * @param {Object} [config] Configuration options
2866 */
2867 OO.ui.Dialog = function OoUiDialog( config ) {
2868 // Parent constructor
2869 OO.ui.Dialog.parent.call( this, config );
2870
2871 // Mixin constructors
2872 OO.ui.mixin.PendingElement.call( this );
2873
2874 // Properties
2875 this.actions = new OO.ui.ActionSet();
2876 this.attachedActions = [];
2877 this.currentAction = null;
2878 this.onDialogKeyDownHandler = this.onDialogKeyDown.bind( this );
2879
2880 // Events
2881 this.actions.connect( this, {
2882 click: 'onActionClick',
2883 resize: 'onActionResize',
2884 change: 'onActionsChange'
2885 } );
2886
2887 // Initialization
2888 this.$element
2889 .addClass( 'oo-ui-dialog' )
2890 .attr( 'role', 'dialog' );
2891 };
2892
2893 /* Setup */
2894
2895 OO.inheritClass( OO.ui.Dialog, OO.ui.Window );
2896 OO.mixinClass( OO.ui.Dialog, OO.ui.mixin.PendingElement );
2897
2898 /* Static Properties */
2899
2900 /**
2901 * Symbolic name of dialog.
2902 *
2903 * The dialog class must have a symbolic name in order to be registered with OO.Factory.
2904 * Please see the [OOjs UI documentation on MediaWiki] [3] for more information.
2905 *
2906 * [3]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
2907 *
2908 * @abstract
2909 * @static
2910 * @inheritable
2911 * @property {string}
2912 */
2913 OO.ui.Dialog.static.name = '';
2914
2915 /**
2916 * The dialog title.
2917 *
2918 * The title can be specified as a plaintext string, a {@link OO.ui.mixin.LabelElement Label} node, or a function
2919 * that will produce a Label node or string. The title can also be specified with data passed to the
2920 * constructor (see #getSetupProcess). In this case, the static value will be overridden.
2921 *
2922 * @abstract
2923 * @static
2924 * @inheritable
2925 * @property {jQuery|string|Function}
2926 */
2927 OO.ui.Dialog.static.title = '';
2928
2929 /**
2930 * An array of configured {@link OO.ui.ActionWidget action widgets}.
2931 *
2932 * Actions can also be specified with data passed to the constructor (see #getSetupProcess). In this case, the static
2933 * value will be overridden.
2934 *
2935 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Action_sets
2936 *
2937 * @static
2938 * @inheritable
2939 * @property {Object[]}
2940 */
2941 OO.ui.Dialog.static.actions = [];
2942
2943 /**
2944 * Close the dialog when the 'Esc' key is pressed.
2945 *
2946 * @static
2947 * @abstract
2948 * @inheritable
2949 * @property {boolean}
2950 */
2951 OO.ui.Dialog.static.escapable = true;
2952
2953 /* Methods */
2954
2955 /**
2956 * Handle frame document key down events.
2957 *
2958 * @private
2959 * @param {jQuery.Event} e Key down event
2960 */
2961 OO.ui.Dialog.prototype.onDialogKeyDown = function ( e ) {
2962 if ( e.which === OO.ui.Keys.ESCAPE ) {
2963 this.executeAction( '' );
2964 e.preventDefault();
2965 e.stopPropagation();
2966 }
2967 };
2968
2969 /**
2970 * Handle action resized events.
2971 *
2972 * @private
2973 * @param {OO.ui.ActionWidget} action Action that was resized
2974 */
2975 OO.ui.Dialog.prototype.onActionResize = function () {
2976 // Override in subclass
2977 };
2978
2979 /**
2980 * Handle action click events.
2981 *
2982 * @private
2983 * @param {OO.ui.ActionWidget} action Action that was clicked
2984 */
2985 OO.ui.Dialog.prototype.onActionClick = function ( action ) {
2986 if ( !this.isPending() ) {
2987 this.executeAction( action.getAction() );
2988 }
2989 };
2990
2991 /**
2992 * Handle actions change event.
2993 *
2994 * @private
2995 */
2996 OO.ui.Dialog.prototype.onActionsChange = function () {
2997 this.detachActions();
2998 if ( !this.isClosing() ) {
2999 this.attachActions();
3000 }
3001 };
3002
3003 /**
3004 * Get the set of actions used by the dialog.
3005 *
3006 * @return {OO.ui.ActionSet}
3007 */
3008 OO.ui.Dialog.prototype.getActions = function () {
3009 return this.actions;
3010 };
3011
3012 /**
3013 * Get a process for taking action.
3014 *
3015 * When you override this method, you can create a new OO.ui.Process and return it, or add additional
3016 * accept steps to the process the parent method provides using the {@link OO.ui.Process#first 'first'}
3017 * and {@link OO.ui.Process#next 'next'} methods of OO.ui.Process.
3018 *
3019 * @param {string} [action] Symbolic name of action
3020 * @return {OO.ui.Process} Action process
3021 */
3022 OO.ui.Dialog.prototype.getActionProcess = function ( action ) {
3023 return new OO.ui.Process()
3024 .next( function () {
3025 if ( !action ) {
3026 // An empty action always closes the dialog without data, which should always be
3027 // safe and make no changes
3028 this.close();
3029 }
3030 }, this );
3031 };
3032
3033 /**
3034 * @inheritdoc
3035 *
3036 * @param {Object} [data] Dialog opening data
3037 * @param {jQuery|string|Function|null} [data.title] Dialog title, omit to use
3038 * the {@link #static-title static title}
3039 * @param {Object[]} [data.actions] List of configuration options for each
3040 * {@link OO.ui.ActionWidget action widget}, omit to use {@link #static-actions static actions}.
3041 */
3042 OO.ui.Dialog.prototype.getSetupProcess = function ( data ) {
3043 data = data || {};
3044
3045 // Parent method
3046 return OO.ui.Dialog.parent.prototype.getSetupProcess.call( this, data )
3047 .next( function () {
3048 var config = this.constructor.static,
3049 actions = data.actions !== undefined ? data.actions : config.actions;
3050
3051 this.title.setLabel(
3052 data.title !== undefined ? data.title : this.constructor.static.title
3053 );
3054 this.actions.add( this.getActionWidgets( actions ) );
3055
3056 if ( this.constructor.static.escapable ) {
3057 this.$element.on( 'keydown', this.onDialogKeyDownHandler );
3058 }
3059 }, this );
3060 };
3061
3062 /**
3063 * @inheritdoc
3064 */
3065 OO.ui.Dialog.prototype.getTeardownProcess = function ( data ) {
3066 // Parent method
3067 return OO.ui.Dialog.parent.prototype.getTeardownProcess.call( this, data )
3068 .first( function () {
3069 if ( this.constructor.static.escapable ) {
3070 this.$element.off( 'keydown', this.onDialogKeyDownHandler );
3071 }
3072
3073 this.actions.clear();
3074 this.currentAction = null;
3075 }, this );
3076 };
3077
3078 /**
3079 * @inheritdoc
3080 */
3081 OO.ui.Dialog.prototype.initialize = function () {
3082 var titleId;
3083
3084 // Parent method
3085 OO.ui.Dialog.parent.prototype.initialize.call( this );
3086
3087 titleId = OO.ui.generateElementId();
3088
3089 // Properties
3090 this.title = new OO.ui.LabelWidget( {
3091 id: titleId
3092 } );
3093
3094 // Initialization
3095 this.$content.addClass( 'oo-ui-dialog-content' );
3096 this.$element.attr( 'aria-labelledby', titleId );
3097 this.setPendingElement( this.$head );
3098 };
3099
3100 /**
3101 * Get action widgets from a list of configs
3102 *
3103 * @param {Object[]} actions Action widget configs
3104 * @return {OO.ui.ActionWidget[]} Action widgets
3105 */
3106 OO.ui.Dialog.prototype.getActionWidgets = function ( actions ) {
3107 var i, len, widgets = [];
3108 for ( i = 0, len = actions.length; i < len; i++ ) {
3109 widgets.push(
3110 new OO.ui.ActionWidget( actions[ i ] )
3111 );
3112 }
3113 return widgets;
3114 };
3115
3116 /**
3117 * Attach action actions.
3118 *
3119 * @protected
3120 */
3121 OO.ui.Dialog.prototype.attachActions = function () {
3122 // Remember the list of potentially attached actions
3123 this.attachedActions = this.actions.get();
3124 };
3125
3126 /**
3127 * Detach action actions.
3128 *
3129 * @protected
3130 * @chainable
3131 */
3132 OO.ui.Dialog.prototype.detachActions = function () {
3133 var i, len;
3134
3135 // Detach all actions that may have been previously attached
3136 for ( i = 0, len = this.attachedActions.length; i < len; i++ ) {
3137 this.attachedActions[ i ].$element.detach();
3138 }
3139 this.attachedActions = [];
3140 };
3141
3142 /**
3143 * Execute an action.
3144 *
3145 * @param {string} action Symbolic name of action to execute
3146 * @return {jQuery.Promise} Promise resolved when action completes, rejected if it fails
3147 */
3148 OO.ui.Dialog.prototype.executeAction = function ( action ) {
3149 this.pushPending();
3150 this.currentAction = action;
3151 return this.getActionProcess( action ).execute()
3152 .always( this.popPending.bind( this ) );
3153 };
3154
3155 /**
3156 * Window managers are used to open and close {@link OO.ui.Window windows} and control their presentation.
3157 * Managed windows are mutually exclusive. If a new window is opened while a current window is opening
3158 * or is opened, the current window will be closed and any ongoing {@link OO.ui.Process process} will be cancelled. Windows
3159 * themselves are persistent and—rather than being torn down when closed—can be repopulated with the
3160 * pertinent data and reused.
3161 *
3162 * Over the lifecycle of a window, the window manager makes available three promises: `opening`,
3163 * `opened`, and `closing`, which represent the primary stages of the cycle:
3164 *
3165 * **Opening**: the opening stage begins when the window manager’s #openWindow or a window’s
3166 * {@link OO.ui.Window#open open} method is used, and the window manager begins to open the window.
3167 *
3168 * - an `opening` event is emitted with an `opening` promise
3169 * - the #getSetupDelay method is called and the returned value is used to time a pause in execution before
3170 * the window’s {@link OO.ui.Window#getSetupProcess getSetupProcess} method is called on the
3171 * window and its result executed
3172 * - a `setup` progress notification is emitted from the `opening` promise
3173 * - the #getReadyDelay method is called the returned value is used to time a pause in execution before
3174 * the window’s {@link OO.ui.Window#getReadyProcess getReadyProcess} method is called on the
3175 * window and its result executed
3176 * - a `ready` progress notification is emitted from the `opening` promise
3177 * - the `opening` promise is resolved with an `opened` promise
3178 *
3179 * **Opened**: the window is now open.
3180 *
3181 * **Closing**: the closing stage begins when the window manager's #closeWindow or the
3182 * window's {@link OO.ui.Window#close close} methods is used, and the window manager begins
3183 * to close the window.
3184 *
3185 * - the `opened` promise is resolved with `closing` promise and a `closing` event is emitted
3186 * - the #getHoldDelay method is called and the returned value is used to time a pause in execution before
3187 * the window's {@link OO.ui.Window#getHoldProcess getHoldProces} method is called on the
3188 * window and its result executed
3189 * - a `hold` progress notification is emitted from the `closing` promise
3190 * - the #getTeardownDelay() method is called and the returned value is used to time a pause in execution before
3191 * the window's {@link OO.ui.Window#getTeardownProcess getTeardownProcess} method is called on the
3192 * window and its result executed
3193 * - a `teardown` progress notification is emitted from the `closing` promise
3194 * - the `closing` promise is resolved. The window is now closed
3195 *
3196 * See the [OOjs UI documentation on MediaWiki][1] for more information.
3197 *
3198 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
3199 *
3200 * @class
3201 * @extends OO.ui.Element
3202 * @mixins OO.EventEmitter
3203 *
3204 * @constructor
3205 * @param {Object} [config] Configuration options
3206 * @cfg {OO.Factory} [factory] Window factory to use for automatic instantiation
3207 * Note that window classes that are instantiated with a factory must have
3208 * a {@link OO.ui.Dialog#static-name static name} property that specifies a symbolic name.
3209 * @cfg {boolean} [modal=true] Prevent interaction outside the dialog
3210 */
3211 OO.ui.WindowManager = function OoUiWindowManager( config ) {
3212 // Configuration initialization
3213 config = config || {};
3214
3215 // Parent constructor
3216 OO.ui.WindowManager.parent.call( this, config );
3217
3218 // Mixin constructors
3219 OO.EventEmitter.call( this );
3220
3221 // Properties
3222 this.factory = config.factory;
3223 this.modal = config.modal === undefined || !!config.modal;
3224 this.windows = {};
3225 this.opening = null;
3226 this.opened = null;
3227 this.closing = null;
3228 this.preparingToOpen = null;
3229 this.preparingToClose = null;
3230 this.currentWindow = null;
3231 this.globalEvents = false;
3232 this.$ariaHidden = null;
3233 this.onWindowResizeTimeout = null;
3234 this.onWindowResizeHandler = this.onWindowResize.bind( this );
3235 this.afterWindowResizeHandler = this.afterWindowResize.bind( this );
3236
3237 // Initialization
3238 this.$element
3239 .addClass( 'oo-ui-windowManager' )
3240 .toggleClass( 'oo-ui-windowManager-modal', this.modal );
3241 };
3242
3243 /* Setup */
3244
3245 OO.inheritClass( OO.ui.WindowManager, OO.ui.Element );
3246 OO.mixinClass( OO.ui.WindowManager, OO.EventEmitter );
3247
3248 /* Events */
3249
3250 /**
3251 * An 'opening' event is emitted when the window begins to be opened.
3252 *
3253 * @event opening
3254 * @param {OO.ui.Window} win Window that's being opened
3255 * @param {jQuery.Promise} opening An `opening` promise resolved with a value when the window is opened successfully.
3256 * When the `opening` promise is resolved, the first argument of the value is an 'opened' promise, the second argument
3257 * is the opening data. The `opening` promise emits `setup` and `ready` notifications when those processes are complete.
3258 * @param {Object} data Window opening data
3259 */
3260
3261 /**
3262 * A 'closing' event is emitted when the window begins to be closed.
3263 *
3264 * @event closing
3265 * @param {OO.ui.Window} win Window that's being closed
3266 * @param {jQuery.Promise} closing A `closing` promise is resolved with a value when the window
3267 * is closed successfully. The promise emits `hold` and `teardown` notifications when those
3268 * processes are complete. When the `closing` promise is resolved, the first argument of its value
3269 * is the closing data.
3270 * @param {Object} data Window closing data
3271 */
3272
3273 /**
3274 * A 'resize' event is emitted when a window is resized.
3275 *
3276 * @event resize
3277 * @param {OO.ui.Window} win Window that was resized
3278 */
3279
3280 /* Static Properties */
3281
3282 /**
3283 * Map of the symbolic name of each window size and its CSS properties.
3284 *
3285 * @static
3286 * @inheritable
3287 * @property {Object}
3288 */
3289 OO.ui.WindowManager.static.sizes = {
3290 small: {
3291 width: 300
3292 },
3293 medium: {
3294 width: 500
3295 },
3296 large: {
3297 width: 700
3298 },
3299 larger: {
3300 width: 900
3301 },
3302 full: {
3303 // These can be non-numeric because they are never used in calculations
3304 width: '100%',
3305 height: '100%'
3306 }
3307 };
3308
3309 /**
3310 * Symbolic name of the default window size.
3311 *
3312 * The default size is used if the window's requested size is not recognized.
3313 *
3314 * @static
3315 * @inheritable
3316 * @property {string}
3317 */
3318 OO.ui.WindowManager.static.defaultSize = 'medium';
3319
3320 /* Methods */
3321
3322 /**
3323 * Handle window resize events.
3324 *
3325 * @private
3326 * @param {jQuery.Event} e Window resize event
3327 */
3328 OO.ui.WindowManager.prototype.onWindowResize = function () {
3329 clearTimeout( this.onWindowResizeTimeout );
3330 this.onWindowResizeTimeout = setTimeout( this.afterWindowResizeHandler, 200 );
3331 };
3332
3333 /**
3334 * Handle window resize events.
3335 *
3336 * @private
3337 * @param {jQuery.Event} e Window resize event
3338 */
3339 OO.ui.WindowManager.prototype.afterWindowResize = function () {
3340 if ( this.currentWindow ) {
3341 this.updateWindowSize( this.currentWindow );
3342 }
3343 };
3344
3345 /**
3346 * Check if window is opening.
3347 *
3348 * @return {boolean} Window is opening
3349 */
3350 OO.ui.WindowManager.prototype.isOpening = function ( win ) {
3351 return win === this.currentWindow && !!this.opening && this.opening.state() === 'pending';
3352 };
3353
3354 /**
3355 * Check if window is closing.
3356 *
3357 * @return {boolean} Window is closing
3358 */
3359 OO.ui.WindowManager.prototype.isClosing = function ( win ) {
3360 return win === this.currentWindow && !!this.closing && this.closing.state() === 'pending';
3361 };
3362
3363 /**
3364 * Check if window is opened.
3365 *
3366 * @return {boolean} Window is opened
3367 */
3368 OO.ui.WindowManager.prototype.isOpened = function ( win ) {
3369 return win === this.currentWindow && !!this.opened && this.opened.state() === 'pending';
3370 };
3371
3372 /**
3373 * Check if a window is being managed.
3374 *
3375 * @param {OO.ui.Window} win Window to check
3376 * @return {boolean} Window is being managed
3377 */
3378 OO.ui.WindowManager.prototype.hasWindow = function ( win ) {
3379 var name;
3380
3381 for ( name in this.windows ) {
3382 if ( this.windows[ name ] === win ) {
3383 return true;
3384 }
3385 }
3386
3387 return false;
3388 };
3389
3390 /**
3391 * Get the number of milliseconds to wait after opening begins before executing the ‘setup’ process.
3392 *
3393 * @param {OO.ui.Window} win Window being opened
3394 * @param {Object} [data] Window opening data
3395 * @return {number} Milliseconds to wait
3396 */
3397 OO.ui.WindowManager.prototype.getSetupDelay = function () {
3398 return 0;
3399 };
3400
3401 /**
3402 * Get the number of milliseconds to wait after setup has finished before executing the ‘ready’ process.
3403 *
3404 * @param {OO.ui.Window} win Window being opened
3405 * @param {Object} [data] Window opening data
3406 * @return {number} Milliseconds to wait
3407 */
3408 OO.ui.WindowManager.prototype.getReadyDelay = function () {
3409 return 0;
3410 };
3411
3412 /**
3413 * Get the number of milliseconds to wait after closing has begun before executing the 'hold' process.
3414 *
3415 * @param {OO.ui.Window} win Window being closed
3416 * @param {Object} [data] Window closing data
3417 * @return {number} Milliseconds to wait
3418 */
3419 OO.ui.WindowManager.prototype.getHoldDelay = function () {
3420 return 0;
3421 };
3422
3423 /**
3424 * Get the number of milliseconds to wait after the ‘hold’ process has finished before
3425 * executing the ‘teardown’ process.
3426 *
3427 * @param {OO.ui.Window} win Window being closed
3428 * @param {Object} [data] Window closing data
3429 * @return {number} Milliseconds to wait
3430 */
3431 OO.ui.WindowManager.prototype.getTeardownDelay = function () {
3432 return this.modal ? 250 : 0;
3433 };
3434
3435 /**
3436 * Get a window by its symbolic name.
3437 *
3438 * If the window is not yet instantiated and its symbolic name is recognized by a factory, it will be
3439 * instantiated and added to the window manager automatically. Please see the [OOjs UI documentation on MediaWiki][3]
3440 * for more information about using factories.
3441 * [3]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
3442 *
3443 * @param {string} name Symbolic name of the window
3444 * @return {jQuery.Promise} Promise resolved with matching window, or rejected with an OO.ui.Error
3445 * @throws {Error} An error is thrown if the symbolic name is not recognized by the factory.
3446 * @throws {Error} An error is thrown if the named window is not recognized as a managed window.
3447 */
3448 OO.ui.WindowManager.prototype.getWindow = function ( name ) {
3449 var deferred = $.Deferred(),
3450 win = this.windows[ name ];
3451
3452 if ( !( win instanceof OO.ui.Window ) ) {
3453 if ( this.factory ) {
3454 if ( !this.factory.lookup( name ) ) {
3455 deferred.reject( new OO.ui.Error(
3456 'Cannot auto-instantiate window: symbolic name is unrecognized by the factory'
3457 ) );
3458 } else {
3459 win = this.factory.create( name );
3460 this.addWindows( [ win ] );
3461 deferred.resolve( win );
3462 }
3463 } else {
3464 deferred.reject( new OO.ui.Error(
3465 'Cannot get unmanaged window: symbolic name unrecognized as a managed window'
3466 ) );
3467 }
3468 } else {
3469 deferred.resolve( win );
3470 }
3471
3472 return deferred.promise();
3473 };
3474
3475 /**
3476 * Get current window.
3477 *
3478 * @return {OO.ui.Window|null} Currently opening/opened/closing window
3479 */
3480 OO.ui.WindowManager.prototype.getCurrentWindow = function () {
3481 return this.currentWindow;
3482 };
3483
3484 /**
3485 * Open a window.
3486 *
3487 * @param {OO.ui.Window|string} win Window object or symbolic name of window to open
3488 * @param {Object} [data] Window opening data
3489 * @return {jQuery.Promise} An `opening` promise resolved when the window is done opening.
3490 * See {@link #event-opening 'opening' event} for more information about `opening` promises.
3491 * @fires opening
3492 */
3493 OO.ui.WindowManager.prototype.openWindow = function ( win, data ) {
3494 var manager = this,
3495 opening = $.Deferred();
3496
3497 // Argument handling
3498 if ( typeof win === 'string' ) {
3499 return this.getWindow( win ).then( function ( win ) {
3500 return manager.openWindow( win, data );
3501 } );
3502 }
3503
3504 // Error handling
3505 if ( !this.hasWindow( win ) ) {
3506 opening.reject( new OO.ui.Error(
3507 'Cannot open window: window is not attached to manager'
3508 ) );
3509 } else if ( this.preparingToOpen || this.opening || this.opened ) {
3510 opening.reject( new OO.ui.Error(
3511 'Cannot open window: another window is opening or open'
3512 ) );
3513 }
3514
3515 // Window opening
3516 if ( opening.state() !== 'rejected' ) {
3517 // If a window is currently closing, wait for it to complete
3518 this.preparingToOpen = $.when( this.closing );
3519 // Ensure handlers get called after preparingToOpen is set
3520 this.preparingToOpen.done( function () {
3521 if ( manager.modal ) {
3522 manager.toggleGlobalEvents( true );
3523 manager.toggleAriaIsolation( true );
3524 }
3525 manager.currentWindow = win;
3526 manager.opening = opening;
3527 manager.preparingToOpen = null;
3528 manager.emit( 'opening', win, opening, data );
3529 setTimeout( function () {
3530 win.setup( data ).then( function () {
3531 manager.updateWindowSize( win );
3532 manager.opening.notify( { state: 'setup' } );
3533 setTimeout( function () {
3534 win.ready( data ).then( function () {
3535 manager.opening.notify( { state: 'ready' } );
3536 manager.opening = null;
3537 manager.opened = $.Deferred();
3538 opening.resolve( manager.opened.promise(), data );
3539 }, function () {
3540 manager.opening = null;
3541 manager.opened = $.Deferred();
3542 opening.reject();
3543 manager.closeWindow( win );
3544 } );
3545 }, manager.getReadyDelay() );
3546 }, function () {
3547 manager.opening = null;
3548 manager.opened = $.Deferred();
3549 opening.reject();
3550 manager.closeWindow( win );
3551 } );
3552 }, manager.getSetupDelay() );
3553 } );
3554 }
3555
3556 return opening.promise();
3557 };
3558
3559 /**
3560 * Close a window.
3561 *
3562 * @param {OO.ui.Window|string} win Window object or symbolic name of window to close
3563 * @param {Object} [data] Window closing data
3564 * @return {jQuery.Promise} A `closing` promise resolved when the window is done closing.
3565 * See {@link #event-closing 'closing' event} for more information about closing promises.
3566 * @throws {Error} An error is thrown if the window is not managed by the window manager.
3567 * @fires closing
3568 */
3569 OO.ui.WindowManager.prototype.closeWindow = function ( win, data ) {
3570 var manager = this,
3571 closing = $.Deferred(),
3572 opened;
3573
3574 // Argument handling
3575 if ( typeof win === 'string' ) {
3576 win = this.windows[ win ];
3577 } else if ( !this.hasWindow( win ) ) {
3578 win = null;
3579 }
3580
3581 // Error handling
3582 if ( !win ) {
3583 closing.reject( new OO.ui.Error(
3584 'Cannot close window: window is not attached to manager'
3585 ) );
3586 } else if ( win !== this.currentWindow ) {
3587 closing.reject( new OO.ui.Error(
3588 'Cannot close window: window already closed with different data'
3589 ) );
3590 } else if ( this.preparingToClose || this.closing ) {
3591 closing.reject( new OO.ui.Error(
3592 'Cannot close window: window already closing with different data'
3593 ) );
3594 }
3595
3596 // Window closing
3597 if ( closing.state() !== 'rejected' ) {
3598 // If the window is currently opening, close it when it's done
3599 this.preparingToClose = $.when( this.opening );
3600 // Ensure handlers get called after preparingToClose is set
3601 this.preparingToClose.always( function () {
3602 manager.closing = closing;
3603 manager.preparingToClose = null;
3604 manager.emit( 'closing', win, closing, data );
3605 opened = manager.opened;
3606 manager.opened = null;
3607 opened.resolve( closing.promise(), data );
3608 setTimeout( function () {
3609 win.hold( data ).then( function () {
3610 closing.notify( { state: 'hold' } );
3611 setTimeout( function () {
3612 win.teardown( data ).then( function () {
3613 closing.notify( { state: 'teardown' } );
3614 if ( manager.modal ) {
3615 manager.toggleGlobalEvents( false );
3616 manager.toggleAriaIsolation( false );
3617 }
3618 manager.closing = null;
3619 manager.currentWindow = null;
3620 closing.resolve( data );
3621 } );
3622 }, manager.getTeardownDelay() );
3623 } );
3624 }, manager.getHoldDelay() );
3625 } );
3626 }
3627
3628 return closing.promise();
3629 };
3630
3631 /**
3632 * Add windows to the window manager.
3633 *
3634 * Windows can be added by reference, symbolic name, or explicitly defined symbolic names.
3635 * See the [OOjs ui documentation on MediaWiki] [2] for examples.
3636 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
3637 *
3638 * @param {Object.<string,OO.ui.Window>|OO.ui.Window[]} windows An array of window objects specified
3639 * by reference, symbolic name, or explicitly defined symbolic names.
3640 * @throws {Error} An error is thrown if a window is added by symbolic name, but has neither an
3641 * explicit nor a statically configured symbolic name.
3642 */
3643 OO.ui.WindowManager.prototype.addWindows = function ( windows ) {
3644 var i, len, win, name, list;
3645
3646 if ( Array.isArray( windows ) ) {
3647 // Convert to map of windows by looking up symbolic names from static configuration
3648 list = {};
3649 for ( i = 0, len = windows.length; i < len; i++ ) {
3650 name = windows[ i ].constructor.static.name;
3651 if ( typeof name !== 'string' ) {
3652 throw new Error( 'Cannot add window' );
3653 }
3654 list[ name ] = windows[ i ];
3655 }
3656 } else if ( OO.isPlainObject( windows ) ) {
3657 list = windows;
3658 }
3659
3660 // Add windows
3661 for ( name in list ) {
3662 win = list[ name ];
3663 this.windows[ name ] = win.toggle( false );
3664 this.$element.append( win.$element );
3665 win.setManager( this );
3666 }
3667 };
3668
3669 /**
3670 * Remove the specified windows from the windows manager.
3671 *
3672 * Windows will be closed before they are removed. If you wish to remove all windows, you may wish to use
3673 * the #clearWindows method instead. If you no longer need the window manager and want to ensure that it no
3674 * longer listens to events, use the #destroy method.
3675 *
3676 * @param {string[]} names Symbolic names of windows to remove
3677 * @return {jQuery.Promise} Promise resolved when window is closed and removed
3678 * @throws {Error} An error is thrown if the named windows are not managed by the window manager.
3679 */
3680 OO.ui.WindowManager.prototype.removeWindows = function ( names ) {
3681 var i, len, win, name, cleanupWindow,
3682 manager = this,
3683 promises = [],
3684 cleanup = function ( name, win ) {
3685 delete manager.windows[ name ];
3686 win.$element.detach();
3687 };
3688
3689 for ( i = 0, len = names.length; i < len; i++ ) {
3690 name = names[ i ];
3691 win = this.windows[ name ];
3692 if ( !win ) {
3693 throw new Error( 'Cannot remove window' );
3694 }
3695 cleanupWindow = cleanup.bind( null, name, win );
3696 promises.push( this.closeWindow( name ).then( cleanupWindow, cleanupWindow ) );
3697 }
3698
3699 return $.when.apply( $, promises );
3700 };
3701
3702 /**
3703 * Remove all windows from the window manager.
3704 *
3705 * Windows will be closed before they are removed. Note that the window manager, though not in use, will still
3706 * listen to events. If the window manager will not be used again, you may wish to use the #destroy method instead.
3707 * To remove just a subset of windows, use the #removeWindows method.
3708 *
3709 * @return {jQuery.Promise} Promise resolved when all windows are closed and removed
3710 */
3711 OO.ui.WindowManager.prototype.clearWindows = function () {
3712 return this.removeWindows( Object.keys( this.windows ) );
3713 };
3714
3715 /**
3716 * Set dialog size. In general, this method should not be called directly.
3717 *
3718 * Fullscreen mode will be used if the dialog is too wide to fit in the screen.
3719 *
3720 * @chainable
3721 */
3722 OO.ui.WindowManager.prototype.updateWindowSize = function ( win ) {
3723 var isFullscreen;
3724
3725 // Bypass for non-current, and thus invisible, windows
3726 if ( win !== this.currentWindow ) {
3727 return;
3728 }
3729
3730 isFullscreen = win.getSize() === 'full';
3731
3732 this.$element.toggleClass( 'oo-ui-windowManager-fullscreen', isFullscreen );
3733 this.$element.toggleClass( 'oo-ui-windowManager-floating', !isFullscreen );
3734 win.setDimensions( win.getSizeProperties() );
3735
3736 this.emit( 'resize', win );
3737
3738 return this;
3739 };
3740
3741 /**
3742 * Bind or unbind global events for scrolling.
3743 *
3744 * @private
3745 * @param {boolean} [on] Bind global events
3746 * @chainable
3747 */
3748 OO.ui.WindowManager.prototype.toggleGlobalEvents = function ( on ) {
3749 var scrollWidth, bodyMargin,
3750 $body = $( this.getElementDocument().body ),
3751 // We could have multiple window managers open so only modify
3752 // the body css at the bottom of the stack
3753 stackDepth = $body.data( 'windowManagerGlobalEvents' ) || 0 ;
3754
3755 on = on === undefined ? !!this.globalEvents : !!on;
3756
3757 if ( on ) {
3758 if ( !this.globalEvents ) {
3759 $( this.getElementWindow() ).on( {
3760 // Start listening for top-level window dimension changes
3761 'orientationchange resize': this.onWindowResizeHandler
3762 } );
3763 if ( stackDepth === 0 ) {
3764 scrollWidth = window.innerWidth - document.documentElement.clientWidth;
3765 bodyMargin = parseFloat( $body.css( 'margin-right' ) ) || 0;
3766 $body.css( {
3767 overflow: 'hidden',
3768 'margin-right': bodyMargin + scrollWidth
3769 } );
3770 }
3771 stackDepth++;
3772 this.globalEvents = true;
3773 }
3774 } else if ( this.globalEvents ) {
3775 $( this.getElementWindow() ).off( {
3776 // Stop listening for top-level window dimension changes
3777 'orientationchange resize': this.onWindowResizeHandler
3778 } );
3779 stackDepth--;
3780 if ( stackDepth === 0 ) {
3781 $body.css( {
3782 overflow: '',
3783 'margin-right': ''
3784 } );
3785 }
3786 this.globalEvents = false;
3787 }
3788 $body.data( 'windowManagerGlobalEvents', stackDepth );
3789
3790 return this;
3791 };
3792
3793 /**
3794 * Toggle screen reader visibility of content other than the window manager.
3795 *
3796 * @private
3797 * @param {boolean} [isolate] Make only the window manager visible to screen readers
3798 * @chainable
3799 */
3800 OO.ui.WindowManager.prototype.toggleAriaIsolation = function ( isolate ) {
3801 isolate = isolate === undefined ? !this.$ariaHidden : !!isolate;
3802
3803 if ( isolate ) {
3804 if ( !this.$ariaHidden ) {
3805 // Hide everything other than the window manager from screen readers
3806 this.$ariaHidden = $( 'body' )
3807 .children()
3808 .not( this.$element.parentsUntil( 'body' ).last() )
3809 .attr( 'aria-hidden', '' );
3810 }
3811 } else if ( this.$ariaHidden ) {
3812 // Restore screen reader visibility
3813 this.$ariaHidden.removeAttr( 'aria-hidden' );
3814 this.$ariaHidden = null;
3815 }
3816
3817 return this;
3818 };
3819
3820 /**
3821 * Destroy the window manager.
3822 *
3823 * Destroying the window manager ensures that it will no longer listen to events. If you would like to
3824 * continue using the window manager, but wish to remove all windows from it, use the #clearWindows method
3825 * instead.
3826 */
3827 OO.ui.WindowManager.prototype.destroy = function () {
3828 this.toggleGlobalEvents( false );
3829 this.toggleAriaIsolation( false );
3830 this.clearWindows();
3831 this.$element.remove();
3832 };
3833
3834 /**
3835 * Errors contain a required message (either a string or jQuery selection) that is used to describe what went wrong
3836 * in a {@link OO.ui.Process process}. The error's #recoverable and #warning configurations are used to customize the
3837 * appearance and functionality of the error interface.
3838 *
3839 * The basic error interface contains a formatted error message as well as two buttons: 'Dismiss' and 'Try again' (i.e., the error
3840 * is 'recoverable' by default). If the error is not recoverable, the 'Try again' button will not be rendered and the widget
3841 * that initiated the failed process will be disabled.
3842 *
3843 * If the error is a warning, the error interface will include a 'Dismiss' and a 'Continue' button, which will try the
3844 * process again.
3845 *
3846 * For an example of error interfaces, please see the [OOjs UI documentation on MediaWiki][1].
3847 *
3848 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Processes_and_errors
3849 *
3850 * @class
3851 *
3852 * @constructor
3853 * @param {string|jQuery} message Description of error
3854 * @param {Object} [config] Configuration options
3855 * @cfg {boolean} [recoverable=true] Error is recoverable.
3856 * By default, errors are recoverable, and users can try the process again.
3857 * @cfg {boolean} [warning=false] Error is a warning.
3858 * If the error is a warning, the error interface will include a
3859 * 'Dismiss' and a 'Continue' button. It is the responsibility of the developer to ensure that the warning
3860 * is not triggered a second time if the user chooses to continue.
3861 */
3862 OO.ui.Error = function OoUiError( message, config ) {
3863 // Allow passing positional parameters inside the config object
3864 if ( OO.isPlainObject( message ) && config === undefined ) {
3865 config = message;
3866 message = config.message;
3867 }
3868
3869 // Configuration initialization
3870 config = config || {};
3871
3872 // Properties
3873 this.message = message instanceof jQuery ? message : String( message );
3874 this.recoverable = config.recoverable === undefined || !!config.recoverable;
3875 this.warning = !!config.warning;
3876 };
3877
3878 /* Setup */
3879
3880 OO.initClass( OO.ui.Error );
3881
3882 /* Methods */
3883
3884 /**
3885 * Check if the error is recoverable.
3886 *
3887 * If the error is recoverable, users are able to try the process again.
3888 *
3889 * @return {boolean} Error is recoverable
3890 */
3891 OO.ui.Error.prototype.isRecoverable = function () {
3892 return this.recoverable;
3893 };
3894
3895 /**
3896 * Check if the error is a warning.
3897 *
3898 * If the error is a warning, the error interface will include a 'Dismiss' and a 'Continue' button.
3899 *
3900 * @return {boolean} Error is warning
3901 */
3902 OO.ui.Error.prototype.isWarning = function () {
3903 return this.warning;
3904 };
3905
3906 /**
3907 * Get error message as DOM nodes.
3908 *
3909 * @return {jQuery} Error message in DOM nodes
3910 */
3911 OO.ui.Error.prototype.getMessage = function () {
3912 return this.message instanceof jQuery ?
3913 this.message.clone() :
3914 $( '<div>' ).text( this.message ).contents();
3915 };
3916
3917 /**
3918 * Get the error message text.
3919 *
3920 * @return {string} Error message
3921 */
3922 OO.ui.Error.prototype.getMessageText = function () {
3923 return this.message instanceof jQuery ? this.message.text() : this.message;
3924 };
3925
3926 /**
3927 * Wraps an HTML snippet for use with configuration values which default
3928 * to strings. This bypasses the default html-escaping done to string
3929 * values.
3930 *
3931 * @class
3932 *
3933 * @constructor
3934 * @param {string} [content] HTML content
3935 */
3936 OO.ui.HtmlSnippet = function OoUiHtmlSnippet( content ) {
3937 // Properties
3938 this.content = content;
3939 };
3940
3941 /* Setup */
3942
3943 OO.initClass( OO.ui.HtmlSnippet );
3944
3945 /* Methods */
3946
3947 /**
3948 * Render into HTML.
3949 *
3950 * @return {string} Unchanged HTML snippet.
3951 */
3952 OO.ui.HtmlSnippet.prototype.toString = function () {
3953 return this.content;
3954 };
3955
3956 /**
3957 * A Process is a list of steps that are called in sequence. The step can be a number, a jQuery promise,
3958 * or a function:
3959 *
3960 * - **number**: the process will wait for the specified number of milliseconds before proceeding.
3961 * - **promise**: the process will continue to the next step when the promise is successfully resolved
3962 * or stop if the promise is rejected.
3963 * - **function**: the process will execute the function. The process will stop if the function returns
3964 * either a boolean `false` or a promise that is rejected; if the function returns a number, the process
3965 * will wait for that number of milliseconds before proceeding.
3966 *
3967 * If the process fails, an {@link OO.ui.Error error} is generated. Depending on how the error is
3968 * configured, users can dismiss the error and try the process again, or not. If a process is stopped,
3969 * its remaining steps will not be performed.
3970 *
3971 * @class
3972 *
3973 * @constructor
3974 * @param {number|jQuery.Promise|Function} step Number of miliseconds to wait before proceeding, promise
3975 * that must be resolved before proceeding, or a function to execute. See #createStep for more information. see #createStep for more information
3976 * @param {Object} [context=null] Execution context of the function. The context is ignored if the step is
3977 * a number or promise.
3978 * @return {Object} Step object, with `callback` and `context` properties
3979 */
3980 OO.ui.Process = function ( step, context ) {
3981 // Properties
3982 this.steps = [];
3983
3984 // Initialization
3985 if ( step !== undefined ) {
3986 this.next( step, context );
3987 }
3988 };
3989
3990 /* Setup */
3991
3992 OO.initClass( OO.ui.Process );
3993
3994 /* Methods */
3995
3996 /**
3997 * Start the process.
3998 *
3999 * @return {jQuery.Promise} Promise that is resolved when all steps have successfully completed.
4000 * If any of the steps return a promise that is rejected or a boolean false, this promise is rejected
4001 * and any remaining steps are not performed.
4002 */
4003 OO.ui.Process.prototype.execute = function () {
4004 var i, len, promise;
4005
4006 /**
4007 * Continue execution.
4008 *
4009 * @ignore
4010 * @param {Array} step A function and the context it should be called in
4011 * @return {Function} Function that continues the process
4012 */
4013 function proceed( step ) {
4014 return function () {
4015 // Execute step in the correct context
4016 var deferred,
4017 result = step.callback.call( step.context );
4018
4019 if ( result === false ) {
4020 // Use rejected promise for boolean false results
4021 return $.Deferred().reject( [] ).promise();
4022 }
4023 if ( typeof result === 'number' ) {
4024 if ( result < 0 ) {
4025 throw new Error( 'Cannot go back in time: flux capacitor is out of service' );
4026 }
4027 // Use a delayed promise for numbers, expecting them to be in milliseconds
4028 deferred = $.Deferred();
4029 setTimeout( deferred.resolve, result );
4030 return deferred.promise();
4031 }
4032 if ( result instanceof OO.ui.Error ) {
4033 // Use rejected promise for error
4034 return $.Deferred().reject( [ result ] ).promise();
4035 }
4036 if ( Array.isArray( result ) && result.length && result[ 0 ] instanceof OO.ui.Error ) {
4037 // Use rejected promise for list of errors
4038 return $.Deferred().reject( result ).promise();
4039 }
4040 // Duck-type the object to see if it can produce a promise
4041 if ( result && $.isFunction( result.promise ) ) {
4042 // Use a promise generated from the result
4043 return result.promise();
4044 }
4045 // Use resolved promise for other results
4046 return $.Deferred().resolve().promise();
4047 };
4048 }
4049
4050 if ( this.steps.length ) {
4051 // Generate a chain reaction of promises
4052 promise = proceed( this.steps[ 0 ] )();
4053 for ( i = 1, len = this.steps.length; i < len; i++ ) {
4054 promise = promise.then( proceed( this.steps[ i ] ) );
4055 }
4056 } else {
4057 promise = $.Deferred().resolve().promise();
4058 }
4059
4060 return promise;
4061 };
4062
4063 /**
4064 * Create a process step.
4065 *
4066 * @private
4067 * @param {number|jQuery.Promise|Function} step
4068 *
4069 * - Number of milliseconds to wait before proceeding
4070 * - Promise that must be resolved before proceeding
4071 * - Function to execute
4072 * - If the function returns a boolean false the process will stop
4073 * - If the function returns a promise, the process will continue to the next
4074 * step when the promise is resolved or stop if the promise is rejected
4075 * - If the function returns a number, the process will wait for that number of
4076 * milliseconds before proceeding
4077 * @param {Object} [context=null] Execution context of the function. The context is
4078 * ignored if the step is a number or promise.
4079 * @return {Object} Step object, with `callback` and `context` properties
4080 */
4081 OO.ui.Process.prototype.createStep = function ( step, context ) {
4082 if ( typeof step === 'number' || $.isFunction( step.promise ) ) {
4083 return {
4084 callback: function () {
4085 return step;
4086 },
4087 context: null
4088 };
4089 }
4090 if ( $.isFunction( step ) ) {
4091 return {
4092 callback: step,
4093 context: context
4094 };
4095 }
4096 throw new Error( 'Cannot create process step: number, promise or function expected' );
4097 };
4098
4099 /**
4100 * Add step to the beginning of the process.
4101 *
4102 * @inheritdoc #createStep
4103 * @return {OO.ui.Process} this
4104 * @chainable
4105 */
4106 OO.ui.Process.prototype.first = function ( step, context ) {
4107 this.steps.unshift( this.createStep( step, context ) );
4108 return this;
4109 };
4110
4111 /**
4112 * Add step to the end of the process.
4113 *
4114 * @inheritdoc #createStep
4115 * @return {OO.ui.Process} this
4116 * @chainable
4117 */
4118 OO.ui.Process.prototype.next = function ( step, context ) {
4119 this.steps.push( this.createStep( step, context ) );
4120 return this;
4121 };
4122
4123 /**
4124 * A ToolFactory creates tools on demand. All tools ({@link OO.ui.Tool Tools}, {@link OO.ui.PopupTool PopupTools},
4125 * and {@link OO.ui.ToolGroupTool ToolGroupTools}) must be registered with a tool factory. Tools are
4126 * registered by their symbolic name. See {@link OO.ui.Toolbar toolbars} for an example.
4127 *
4128 * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki][1].
4129 *
4130 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
4131 *
4132 * @class
4133 * @extends OO.Factory
4134 * @constructor
4135 */
4136 OO.ui.ToolFactory = function OoUiToolFactory() {
4137 // Parent constructor
4138 OO.ui.ToolFactory.parent.call( this );
4139 };
4140
4141 /* Setup */
4142
4143 OO.inheritClass( OO.ui.ToolFactory, OO.Factory );
4144
4145 /* Methods */
4146
4147 /**
4148 * Get tools from the factory
4149 *
4150 * @param {Array|string} [include] Included tools, see #extract for format
4151 * @param {Array|string} [exclude] Excluded tools, see #extract for format
4152 * @param {Array|string} [promote] Promoted tools, see #extract for format
4153 * @param {Array|string} [demote] Demoted tools, see #extract for format
4154 * @return {string[]} List of tools
4155 */
4156 OO.ui.ToolFactory.prototype.getTools = function ( include, exclude, promote, demote ) {
4157 var i, len, included, promoted, demoted,
4158 auto = [],
4159 used = {};
4160
4161 // Collect included and not excluded tools
4162 included = OO.simpleArrayDifference( this.extract( include ), this.extract( exclude ) );
4163
4164 // Promotion
4165 promoted = this.extract( promote, used );
4166 demoted = this.extract( demote, used );
4167
4168 // Auto
4169 for ( i = 0, len = included.length; i < len; i++ ) {
4170 if ( !used[ included[ i ] ] ) {
4171 auto.push( included[ i ] );
4172 }
4173 }
4174
4175 return promoted.concat( auto ).concat( demoted );
4176 };
4177
4178 /**
4179 * Get a flat list of names from a list of names or groups.
4180 *
4181 * Normally, `collection` is an array of tool specifications. Tools can be specified in the
4182 * following ways:
4183 *
4184 * - To include an individual tool, use the symbolic name: `{ name: 'tool-name' }` or `'tool-name'`.
4185 * - To include all tools in a group, use the group name: `{ group: 'group-name' }`. (To assign the
4186 * tool to a group, use OO.ui.Tool.static.group.)
4187 *
4188 * Alternatively, to include all tools that are not yet assigned to any other toolgroup, use the
4189 * catch-all selector `'*'`.
4190 *
4191 * If `used` is passed, tool names that appear as properties in this object will be considered
4192 * already assigned, and will not be returned even if specified otherwise. The tool names extracted
4193 * by this function call will be added as new properties in the object.
4194 *
4195 * @private
4196 * @param {Array|string} collection List of tools, see above
4197 * @param {Object} [used] Object containing information about used tools, see above
4198 * @return {string[]} List of extracted tool names
4199 */
4200 OO.ui.ToolFactory.prototype.extract = function ( collection, used ) {
4201 var i, len, item, name, tool,
4202 names = [];
4203
4204 if ( collection === '*' ) {
4205 for ( name in this.registry ) {
4206 tool = this.registry[ name ];
4207 if (
4208 // Only add tools by group name when auto-add is enabled
4209 tool.static.autoAddToCatchall &&
4210 // Exclude already used tools
4211 ( !used || !used[ name ] )
4212 ) {
4213 names.push( name );
4214 if ( used ) {
4215 used[ name ] = true;
4216 }
4217 }
4218 }
4219 } else if ( Array.isArray( collection ) ) {
4220 for ( i = 0, len = collection.length; i < len; i++ ) {
4221 item = collection[ i ];
4222 // Allow plain strings as shorthand for named tools
4223 if ( typeof item === 'string' ) {
4224 item = { name: item };
4225 }
4226 if ( OO.isPlainObject( item ) ) {
4227 if ( item.group ) {
4228 for ( name in this.registry ) {
4229 tool = this.registry[ name ];
4230 if (
4231 // Include tools with matching group
4232 tool.static.group === item.group &&
4233 // Only add tools by group name when auto-add is enabled
4234 tool.static.autoAddToGroup &&
4235 // Exclude already used tools
4236 ( !used || !used[ name ] )
4237 ) {
4238 names.push( name );
4239 if ( used ) {
4240 used[ name ] = true;
4241 }
4242 }
4243 }
4244 // Include tools with matching name and exclude already used tools
4245 } else if ( item.name && ( !used || !used[ item.name ] ) ) {
4246 names.push( item.name );
4247 if ( used ) {
4248 used[ item.name ] = true;
4249 }
4250 }
4251 }
4252 }
4253 }
4254 return names;
4255 };
4256
4257 /**
4258 * ToolGroupFactories create {@link OO.ui.ToolGroup toolgroups} on demand. The toolgroup classes must
4259 * specify a symbolic name and be registered with the factory. The following classes are registered by
4260 * default:
4261 *
4262 * - {@link OO.ui.BarToolGroup BarToolGroups} (‘bar’)
4263 * - {@link OO.ui.MenuToolGroup MenuToolGroups} (‘menu’)
4264 * - {@link OO.ui.ListToolGroup ListToolGroups} (‘list’)
4265 *
4266 * See {@link OO.ui.Toolbar toolbars} for an example.
4267 *
4268 * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki][1].
4269 *
4270 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
4271 * @class
4272 * @extends OO.Factory
4273 * @constructor
4274 */
4275 OO.ui.ToolGroupFactory = function OoUiToolGroupFactory() {
4276 var i, l, defaultClasses;
4277 // Parent constructor
4278 OO.Factory.call( this );
4279
4280 defaultClasses = this.constructor.static.getDefaultClasses();
4281
4282 // Register default toolgroups
4283 for ( i = 0, l = defaultClasses.length; i < l; i++ ) {
4284 this.register( defaultClasses[ i ] );
4285 }
4286 };
4287
4288 /* Setup */
4289
4290 OO.inheritClass( OO.ui.ToolGroupFactory, OO.Factory );
4291
4292 /* Static Methods */
4293
4294 /**
4295 * Get a default set of classes to be registered on construction.
4296 *
4297 * @return {Function[]} Default classes
4298 */
4299 OO.ui.ToolGroupFactory.static.getDefaultClasses = function () {
4300 return [
4301 OO.ui.BarToolGroup,
4302 OO.ui.ListToolGroup,
4303 OO.ui.MenuToolGroup
4304 ];
4305 };
4306
4307 /**
4308 * Theme logic.
4309 *
4310 * @abstract
4311 * @class
4312 *
4313 * @constructor
4314 * @param {Object} [config] Configuration options
4315 */
4316 OO.ui.Theme = function OoUiTheme( config ) {
4317 // Configuration initialization
4318 config = config || {};
4319 };
4320
4321 /* Setup */
4322
4323 OO.initClass( OO.ui.Theme );
4324
4325 /* Methods */
4326
4327 /**
4328 * Get a list of classes to be applied to a widget.
4329 *
4330 * The 'on' and 'off' lists combined MUST contain keys for all classes the theme adds or removes,
4331 * otherwise state transitions will not work properly.
4332 *
4333 * @param {OO.ui.Element} element Element for which to get classes
4334 * @return {Object.<string,string[]>} Categorized class names with `on` and `off` lists
4335 */
4336 OO.ui.Theme.prototype.getElementClasses = function () {
4337 return { on: [], off: [] };
4338 };
4339
4340 /**
4341 * Update CSS classes provided by the theme.
4342 *
4343 * For elements with theme logic hooks, this should be called any time there's a state change.
4344 *
4345 * @param {OO.ui.Element} element Element for which to update classes
4346 * @return {Object.<string,string[]>} Categorized class names with `on` and `off` lists
4347 */
4348 OO.ui.Theme.prototype.updateElementClasses = function ( element ) {
4349 var $elements = $( [] ),
4350 classes = this.getElementClasses( element );
4351
4352 if ( element.$icon ) {
4353 $elements = $elements.add( element.$icon );
4354 }
4355 if ( element.$indicator ) {
4356 $elements = $elements.add( element.$indicator );
4357 }
4358
4359 $elements
4360 .removeClass( classes.off.join( ' ' ) )
4361 .addClass( classes.on.join( ' ' ) );
4362 };
4363
4364 /**
4365 * RequestManager is a mixin that manages the lifecycle of a promise-backed request for a widget, such as
4366 * the {@link OO.ui.mixin.LookupElement}.
4367 *
4368 * @class
4369 * @abstract
4370 *
4371 * @constructor
4372 */
4373 OO.ui.mixin.RequestManager = function OoUiMixinRequestManager() {
4374 this.requestCache = {};
4375 this.requestQuery = null;
4376 this.requestRequest = null;
4377 };
4378
4379 /* Setup */
4380
4381 OO.initClass( OO.ui.mixin.RequestManager );
4382
4383 /**
4384 * Get request results for the current query.
4385 *
4386 * @return {jQuery.Promise} Promise object which will be passed response data as the first argument of
4387 * the done event. If the request was aborted to make way for a subsequent request, this promise
4388 * may not be rejected, depending on what jQuery feels like doing.
4389 */
4390 OO.ui.mixin.RequestManager.prototype.getRequestData = function () {
4391 var widget = this,
4392 value = this.getRequestQuery(),
4393 deferred = $.Deferred(),
4394 ourRequest;
4395
4396 this.abortRequest();
4397 if ( Object.prototype.hasOwnProperty.call( this.requestCache, value ) ) {
4398 deferred.resolve( this.requestCache[ value ] );
4399 } else {
4400 if ( this.pushPending ) {
4401 this.pushPending();
4402 }
4403 this.requestQuery = value;
4404 ourRequest = this.requestRequest = this.getRequest();
4405 ourRequest
4406 .always( function () {
4407 // We need to pop pending even if this is an old request, otherwise
4408 // the widget will remain pending forever.
4409 // TODO: this assumes that an aborted request will fail or succeed soon after
4410 // being aborted, or at least eventually. It would be nice if we could popPending()
4411 // at abort time, but only if we knew that we hadn't already called popPending()
4412 // for that request.
4413 if ( widget.popPending ) {
4414 widget.popPending();
4415 }
4416 } )
4417 .done( function ( response ) {
4418 // If this is an old request (and aborting it somehow caused it to still succeed),
4419 // ignore its success completely
4420 if ( ourRequest === widget.requestRequest ) {
4421 widget.requestQuery = null;
4422 widget.requestRequest = null;
4423 widget.requestCache[ value ] = widget.getRequestCacheDataFromResponse( response );
4424 deferred.resolve( widget.requestCache[ value ] );
4425 }
4426 } )
4427 .fail( function () {
4428 // If this is an old request (or a request failing because it's being aborted),
4429 // ignore its failure completely
4430 if ( ourRequest === widget.requestRequest ) {
4431 widget.requestQuery = null;
4432 widget.requestRequest = null;
4433 deferred.reject();
4434 }
4435 } );
4436 }
4437 return deferred.promise();
4438 };
4439
4440 /**
4441 * Abort the currently pending request, if any.
4442 *
4443 * @private
4444 */
4445 OO.ui.mixin.RequestManager.prototype.abortRequest = function () {
4446 var oldRequest = this.requestRequest;
4447 if ( oldRequest ) {
4448 // First unset this.requestRequest to the fail handler will notice
4449 // that the request is no longer current
4450 this.requestRequest = null;
4451 this.requestQuery = null;
4452 oldRequest.abort();
4453 }
4454 };
4455
4456 /**
4457 * Get the query to be made.
4458 *
4459 * @protected
4460 * @method
4461 * @abstract
4462 * @return {string} query to be used
4463 */
4464 OO.ui.mixin.RequestManager.prototype.getRequestQuery = null;
4465
4466 /**
4467 * Get a new request object of the current query value.
4468 *
4469 * @protected
4470 * @method
4471 * @abstract
4472 * @return {jQuery.Promise} jQuery AJAX object, or promise object with an .abort() method
4473 */
4474 OO.ui.mixin.RequestManager.prototype.getRequest = null;
4475
4476 /**
4477 * Pre-process data returned by the request from #getRequest.
4478 *
4479 * The return value of this function will be cached, and any further queries for the given value
4480 * will use the cache rather than doing API requests.
4481 *
4482 * @protected
4483 * @method
4484 * @abstract
4485 * @param {Mixed} response Response from server
4486 * @return {Mixed} Cached result data
4487 */
4488 OO.ui.mixin.RequestManager.prototype.getRequestCacheDataFromResponse = null;
4489
4490 /**
4491 * The TabIndexedElement class is an attribute mixin used to add additional functionality to an
4492 * element created by another class. The mixin provides a ‘tabIndex’ property, which specifies the
4493 * order in which users will navigate through the focusable elements via the "tab" key.
4494 *
4495 * @example
4496 * // TabIndexedElement is mixed into the ButtonWidget class
4497 * // to provide a tabIndex property.
4498 * var button1 = new OO.ui.ButtonWidget( {
4499 * label: 'fourth',
4500 * tabIndex: 4
4501 * } );
4502 * var button2 = new OO.ui.ButtonWidget( {
4503 * label: 'second',
4504 * tabIndex: 2
4505 * } );
4506 * var button3 = new OO.ui.ButtonWidget( {
4507 * label: 'third',
4508 * tabIndex: 3
4509 * } );
4510 * var button4 = new OO.ui.ButtonWidget( {
4511 * label: 'first',
4512 * tabIndex: 1
4513 * } );
4514 * $( 'body' ).append( button1.$element, button2.$element, button3.$element, button4.$element );
4515 *
4516 * @abstract
4517 * @class
4518 *
4519 * @constructor
4520 * @param {Object} [config] Configuration options
4521 * @cfg {jQuery} [$tabIndexed] The element that should use the tabindex functionality. By default,
4522 * the functionality is applied to the element created by the class ($element). If a different element is specified, the tabindex
4523 * functionality will be applied to it instead.
4524 * @cfg {number|null} [tabIndex=0] Number that specifies the element’s position in the tab-navigation
4525 * order (e.g., 1 for the first focusable element). Use 0 to use the default navigation order; use -1
4526 * to remove the element from the tab-navigation flow.
4527 */
4528 OO.ui.mixin.TabIndexedElement = function OoUiMixinTabIndexedElement( config ) {
4529 // Configuration initialization
4530 config = $.extend( { tabIndex: 0 }, config );
4531
4532 // Properties
4533 this.$tabIndexed = null;
4534 this.tabIndex = null;
4535
4536 // Events
4537 this.connect( this, { disable: 'onTabIndexedElementDisable' } );
4538
4539 // Initialization
4540 this.setTabIndex( config.tabIndex );
4541 this.setTabIndexedElement( config.$tabIndexed || this.$element );
4542 };
4543
4544 /* Setup */
4545
4546 OO.initClass( OO.ui.mixin.TabIndexedElement );
4547
4548 /* Methods */
4549
4550 /**
4551 * Set the element that should use the tabindex functionality.
4552 *
4553 * This method is used to retarget a tabindex mixin so that its functionality applies
4554 * to the specified element. If an element is currently using the functionality, the mixin’s
4555 * effect on that element is removed before the new element is set up.
4556 *
4557 * @param {jQuery} $tabIndexed Element that should use the tabindex functionality
4558 * @chainable
4559 */
4560 OO.ui.mixin.TabIndexedElement.prototype.setTabIndexedElement = function ( $tabIndexed ) {
4561 var tabIndex = this.tabIndex;
4562 // Remove attributes from old $tabIndexed
4563 this.setTabIndex( null );
4564 // Force update of new $tabIndexed
4565 this.$tabIndexed = $tabIndexed;
4566 this.tabIndex = tabIndex;
4567 return this.updateTabIndex();
4568 };
4569
4570 /**
4571 * Set the value of the tabindex.
4572 *
4573 * @param {number|null} tabIndex Tabindex value, or `null` for no tabindex
4574 * @chainable
4575 */
4576 OO.ui.mixin.TabIndexedElement.prototype.setTabIndex = function ( tabIndex ) {
4577 tabIndex = typeof tabIndex === 'number' ? tabIndex : null;
4578
4579 if ( this.tabIndex !== tabIndex ) {
4580 this.tabIndex = tabIndex;
4581 this.updateTabIndex();
4582 }
4583
4584 return this;
4585 };
4586
4587 /**
4588 * Update the `tabindex` attribute, in case of changes to tab index or
4589 * disabled state.
4590 *
4591 * @private
4592 * @chainable
4593 */
4594 OO.ui.mixin.TabIndexedElement.prototype.updateTabIndex = function () {
4595 if ( this.$tabIndexed ) {
4596 if ( this.tabIndex !== null ) {
4597 // Do not index over disabled elements
4598 this.$tabIndexed.attr( {
4599 tabindex: this.isDisabled() ? -1 : this.tabIndex,
4600 // Support: ChromeVox and NVDA
4601 // These do not seem to inherit aria-disabled from parent elements
4602 'aria-disabled': this.isDisabled().toString()
4603 } );
4604 } else {
4605 this.$tabIndexed.removeAttr( 'tabindex aria-disabled' );
4606 }
4607 }
4608 return this;
4609 };
4610
4611 /**
4612 * Handle disable events.
4613 *
4614 * @private
4615 * @param {boolean} disabled Element is disabled
4616 */
4617 OO.ui.mixin.TabIndexedElement.prototype.onTabIndexedElementDisable = function () {
4618 this.updateTabIndex();
4619 };
4620
4621 /**
4622 * Get the value of the tabindex.
4623 *
4624 * @return {number|null} Tabindex value
4625 */
4626 OO.ui.mixin.TabIndexedElement.prototype.getTabIndex = function () {
4627 return this.tabIndex;
4628 };
4629
4630 /**
4631 * ButtonElement is often mixed into other classes to generate a button, which is a clickable
4632 * interface element that can be configured with access keys for accessibility.
4633 * See the [OOjs UI documentation on MediaWiki] [1] for examples.
4634 *
4635 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#Buttons
4636 * @abstract
4637 * @class
4638 *
4639 * @constructor
4640 * @param {Object} [config] Configuration options
4641 * @cfg {jQuery} [$button] The button element created by the class.
4642 * If this configuration is omitted, the button element will use a generated `<a>`.
4643 * @cfg {boolean} [framed=true] Render the button with a frame
4644 */
4645 OO.ui.mixin.ButtonElement = function OoUiMixinButtonElement( config ) {
4646 // Configuration initialization
4647 config = config || {};
4648
4649 // Properties
4650 this.$button = null;
4651 this.framed = null;
4652 this.active = false;
4653 this.onMouseUpHandler = this.onMouseUp.bind( this );
4654 this.onMouseDownHandler = this.onMouseDown.bind( this );
4655 this.onKeyDownHandler = this.onKeyDown.bind( this );
4656 this.onKeyUpHandler = this.onKeyUp.bind( this );
4657 this.onClickHandler = this.onClick.bind( this );
4658 this.onKeyPressHandler = this.onKeyPress.bind( this );
4659
4660 // Initialization
4661 this.$element.addClass( 'oo-ui-buttonElement' );
4662 this.toggleFramed( config.framed === undefined || config.framed );
4663 this.setButtonElement( config.$button || $( '<a>' ) );
4664 };
4665
4666 /* Setup */
4667
4668 OO.initClass( OO.ui.mixin.ButtonElement );
4669
4670 /* Static Properties */
4671
4672 /**
4673 * Cancel mouse down events.
4674 *
4675 * This property is usually set to `true` to prevent the focus from changing when the button is clicked.
4676 * Classes such as {@link OO.ui.mixin.DraggableElement DraggableElement} and {@link OO.ui.ButtonOptionWidget ButtonOptionWidget}
4677 * use a value of `false` so that dragging behavior is possible and mousedown events can be handled by a
4678 * parent widget.
4679 *
4680 * @static
4681 * @inheritable
4682 * @property {boolean}
4683 */
4684 OO.ui.mixin.ButtonElement.static.cancelButtonMouseDownEvents = true;
4685
4686 /* Events */
4687
4688 /**
4689 * A 'click' event is emitted when the button element is clicked.
4690 *
4691 * @event click
4692 */
4693
4694 /* Methods */
4695
4696 /**
4697 * Set the button element.
4698 *
4699 * This method is used to retarget a button mixin so that its functionality applies to
4700 * the specified button element instead of the one created by the class. If a button element
4701 * is already set, the method will remove the mixin’s effect on that element.
4702 *
4703 * @param {jQuery} $button Element to use as button
4704 */
4705 OO.ui.mixin.ButtonElement.prototype.setButtonElement = function ( $button ) {
4706 if ( this.$button ) {
4707 this.$button
4708 .removeClass( 'oo-ui-buttonElement-button' )
4709 .removeAttr( 'role accesskey' )
4710 .off( {
4711 mousedown: this.onMouseDownHandler,
4712 keydown: this.onKeyDownHandler,
4713 click: this.onClickHandler,
4714 keypress: this.onKeyPressHandler
4715 } );
4716 }
4717
4718 this.$button = $button
4719 .addClass( 'oo-ui-buttonElement-button' )
4720 .attr( { role: 'button' } )
4721 .on( {
4722 mousedown: this.onMouseDownHandler,
4723 keydown: this.onKeyDownHandler,
4724 click: this.onClickHandler,
4725 keypress: this.onKeyPressHandler
4726 } );
4727 };
4728
4729 /**
4730 * Handles mouse down events.
4731 *
4732 * @protected
4733 * @param {jQuery.Event} e Mouse down event
4734 */
4735 OO.ui.mixin.ButtonElement.prototype.onMouseDown = function ( e ) {
4736 if ( this.isDisabled() || e.which !== OO.ui.MouseButtons.LEFT ) {
4737 return;
4738 }
4739 this.$element.addClass( 'oo-ui-buttonElement-pressed' );
4740 // Run the mouseup handler no matter where the mouse is when the button is let go, so we can
4741 // reliably remove the pressed class
4742 this.getElementDocument().addEventListener( 'mouseup', this.onMouseUpHandler, true );
4743 // Prevent change of focus unless specifically configured otherwise
4744 if ( this.constructor.static.cancelButtonMouseDownEvents ) {
4745 return false;
4746 }
4747 };
4748
4749 /**
4750 * Handles mouse up events.
4751 *
4752 * @protected
4753 * @param {jQuery.Event} e Mouse up event
4754 */
4755 OO.ui.mixin.ButtonElement.prototype.onMouseUp = function ( e ) {
4756 if ( this.isDisabled() || e.which !== OO.ui.MouseButtons.LEFT ) {
4757 return;
4758 }
4759 this.$element.removeClass( 'oo-ui-buttonElement-pressed' );
4760 // Stop listening for mouseup, since we only needed this once
4761 this.getElementDocument().removeEventListener( 'mouseup', this.onMouseUpHandler, true );
4762 };
4763
4764 /**
4765 * Handles mouse click events.
4766 *
4767 * @protected
4768 * @param {jQuery.Event} e Mouse click event
4769 * @fires click
4770 */
4771 OO.ui.mixin.ButtonElement.prototype.onClick = function ( e ) {
4772 if ( !this.isDisabled() && e.which === OO.ui.MouseButtons.LEFT ) {
4773 if ( this.emit( 'click' ) ) {
4774 return false;
4775 }
4776 }
4777 };
4778
4779 /**
4780 * Handles key down events.
4781 *
4782 * @protected
4783 * @param {jQuery.Event} e Key down event
4784 */
4785 OO.ui.mixin.ButtonElement.prototype.onKeyDown = function ( e ) {
4786 if ( this.isDisabled() || ( e.which !== OO.ui.Keys.SPACE && e.which !== OO.ui.Keys.ENTER ) ) {
4787 return;
4788 }
4789 this.$element.addClass( 'oo-ui-buttonElement-pressed' );
4790 // Run the keyup handler no matter where the key is when the button is let go, so we can
4791 // reliably remove the pressed class
4792 this.getElementDocument().addEventListener( 'keyup', this.onKeyUpHandler, true );
4793 };
4794
4795 /**
4796 * Handles key up events.
4797 *
4798 * @protected
4799 * @param {jQuery.Event} e Key up event
4800 */
4801 OO.ui.mixin.ButtonElement.prototype.onKeyUp = function ( e ) {
4802 if ( this.isDisabled() || ( e.which !== OO.ui.Keys.SPACE && e.which !== OO.ui.Keys.ENTER ) ) {
4803 return;
4804 }
4805 this.$element.removeClass( 'oo-ui-buttonElement-pressed' );
4806 // Stop listening for keyup, since we only needed this once
4807 this.getElementDocument().removeEventListener( 'keyup', this.onKeyUpHandler, true );
4808 };
4809
4810 /**
4811 * Handles key press events.
4812 *
4813 * @protected
4814 * @param {jQuery.Event} e Key press event
4815 * @fires click
4816 */
4817 OO.ui.mixin.ButtonElement.prototype.onKeyPress = function ( e ) {
4818 if ( !this.isDisabled() && ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER ) ) {
4819 if ( this.emit( 'click' ) ) {
4820 return false;
4821 }
4822 }
4823 };
4824
4825 /**
4826 * Check if button has a frame.
4827 *
4828 * @return {boolean} Button is framed
4829 */
4830 OO.ui.mixin.ButtonElement.prototype.isFramed = function () {
4831 return this.framed;
4832 };
4833
4834 /**
4835 * Render the button with or without a frame. Omit the `framed` parameter to toggle the button frame on and off.
4836 *
4837 * @param {boolean} [framed] Make button framed, omit to toggle
4838 * @chainable
4839 */
4840 OO.ui.mixin.ButtonElement.prototype.toggleFramed = function ( framed ) {
4841 framed = framed === undefined ? !this.framed : !!framed;
4842 if ( framed !== this.framed ) {
4843 this.framed = framed;
4844 this.$element
4845 .toggleClass( 'oo-ui-buttonElement-frameless', !framed )
4846 .toggleClass( 'oo-ui-buttonElement-framed', framed );
4847 this.updateThemeClasses();
4848 }
4849
4850 return this;
4851 };
4852
4853 /**
4854 * Set the button's active state.
4855 *
4856 * The active state occurs when a {@link OO.ui.ButtonOptionWidget ButtonOptionWidget} or
4857 * a {@link OO.ui.ToggleButtonWidget ToggleButtonWidget} is pressed. This method does nothing
4858 * for other button types.
4859 *
4860 * @param {boolean} value Make button active
4861 * @chainable
4862 */
4863 OO.ui.mixin.ButtonElement.prototype.setActive = function ( value ) {
4864 this.active = !!value;
4865 this.$element.toggleClass( 'oo-ui-buttonElement-active', this.active );
4866 return this;
4867 };
4868
4869 /**
4870 * Check if the button is active
4871 *
4872 * @return {boolean} The button is active
4873 */
4874 OO.ui.mixin.ButtonElement.prototype.isActive = function () {
4875 return this.active;
4876 };
4877
4878 /**
4879 * Any OOjs UI widget that contains other widgets (such as {@link OO.ui.ButtonWidget buttons} or
4880 * {@link OO.ui.OptionWidget options}) mixes in GroupElement. Adding, removing, and clearing
4881 * items from the group is done through the interface the class provides.
4882 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
4883 *
4884 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Groups
4885 *
4886 * @abstract
4887 * @class
4888 *
4889 * @constructor
4890 * @param {Object} [config] Configuration options
4891 * @cfg {jQuery} [$group] The container element created by the class. If this configuration
4892 * is omitted, the group element will use a generated `<div>`.
4893 */
4894 OO.ui.mixin.GroupElement = function OoUiMixinGroupElement( config ) {
4895 // Configuration initialization
4896 config = config || {};
4897
4898 // Properties
4899 this.$group = null;
4900 this.items = [];
4901 this.aggregateItemEvents = {};
4902
4903 // Initialization
4904 this.setGroupElement( config.$group || $( '<div>' ) );
4905 };
4906
4907 /* Methods */
4908
4909 /**
4910 * Set the group element.
4911 *
4912 * If an element is already set, items will be moved to the new element.
4913 *
4914 * @param {jQuery} $group Element to use as group
4915 */
4916 OO.ui.mixin.GroupElement.prototype.setGroupElement = function ( $group ) {
4917 var i, len;
4918
4919 this.$group = $group;
4920 for ( i = 0, len = this.items.length; i < len; i++ ) {
4921 this.$group.append( this.items[ i ].$element );
4922 }
4923 };
4924
4925 /**
4926 * Check if a group contains no items.
4927 *
4928 * @return {boolean} Group is empty
4929 */
4930 OO.ui.mixin.GroupElement.prototype.isEmpty = function () {
4931 return !this.items.length;
4932 };
4933
4934 /**
4935 * Get all items in the group.
4936 *
4937 * The method returns an array of item references (e.g., [button1, button2, button3]) and is useful
4938 * when synchronizing groups of items, or whenever the references are required (e.g., when removing items
4939 * from a group).
4940 *
4941 * @return {OO.ui.Element[]} An array of items.
4942 */
4943 OO.ui.mixin.GroupElement.prototype.getItems = function () {
4944 return this.items.slice( 0 );
4945 };
4946
4947 /**
4948 * Get an item by its data.
4949 *
4950 * Only the first item with matching data will be returned. To return all matching items,
4951 * use the #getItemsFromData method.
4952 *
4953 * @param {Object} data Item data to search for
4954 * @return {OO.ui.Element|null} Item with equivalent data, `null` if none exists
4955 */
4956 OO.ui.mixin.GroupElement.prototype.getItemFromData = function ( data ) {
4957 var i, len, item,
4958 hash = OO.getHash( data );
4959
4960 for ( i = 0, len = this.items.length; i < len; i++ ) {
4961 item = this.items[ i ];
4962 if ( hash === OO.getHash( item.getData() ) ) {
4963 return item;
4964 }
4965 }
4966
4967 return null;
4968 };
4969
4970 /**
4971 * Get items by their data.
4972 *
4973 * All items with matching data will be returned. To return only the first match, use the #getItemFromData method instead.
4974 *
4975 * @param {Object} data Item data to search for
4976 * @return {OO.ui.Element[]} Items with equivalent data
4977 */
4978 OO.ui.mixin.GroupElement.prototype.getItemsFromData = function ( data ) {
4979 var i, len, item,
4980 hash = OO.getHash( data ),
4981 items = [];
4982
4983 for ( i = 0, len = this.items.length; i < len; i++ ) {
4984 item = this.items[ i ];
4985 if ( hash === OO.getHash( item.getData() ) ) {
4986 items.push( item );
4987 }
4988 }
4989
4990 return items;
4991 };
4992
4993 /**
4994 * Aggregate the events emitted by the group.
4995 *
4996 * When events are aggregated, the group will listen to all contained items for the event,
4997 * and then emit the event under a new name. The new event will contain an additional leading
4998 * parameter containing the item that emitted the original event. Other arguments emitted from
4999 * the original event are passed through.
5000 *
5001 * @param {Object.<string,string|null>} events An object keyed by the name of the event that should be
5002 * aggregated (e.g., ‘click’) and the value of the new name to use (e.g., ‘groupClick’).
5003 * A `null` value will remove aggregated events.
5004
5005 * @throws {Error} An error is thrown if aggregation already exists.
5006 */
5007 OO.ui.mixin.GroupElement.prototype.aggregate = function ( events ) {
5008 var i, len, item, add, remove, itemEvent, groupEvent;
5009
5010 for ( itemEvent in events ) {
5011 groupEvent = events[ itemEvent ];
5012
5013 // Remove existing aggregated event
5014 if ( Object.prototype.hasOwnProperty.call( this.aggregateItemEvents, itemEvent ) ) {
5015 // Don't allow duplicate aggregations
5016 if ( groupEvent ) {
5017 throw new Error( 'Duplicate item event aggregation for ' + itemEvent );
5018 }
5019 // Remove event aggregation from existing items
5020 for ( i = 0, len = this.items.length; i < len; i++ ) {
5021 item = this.items[ i ];
5022 if ( item.connect && item.disconnect ) {
5023 remove = {};
5024 remove[ itemEvent ] = [ 'emit', this.aggregateItemEvents[ itemEvent ], item ];
5025 item.disconnect( this, remove );
5026 }
5027 }
5028 // Prevent future items from aggregating event
5029 delete this.aggregateItemEvents[ itemEvent ];
5030 }
5031
5032 // Add new aggregate event
5033 if ( groupEvent ) {
5034 // Make future items aggregate event
5035 this.aggregateItemEvents[ itemEvent ] = groupEvent;
5036 // Add event aggregation to existing items
5037 for ( i = 0, len = this.items.length; i < len; i++ ) {
5038 item = this.items[ i ];
5039 if ( item.connect && item.disconnect ) {
5040 add = {};
5041 add[ itemEvent ] = [ 'emit', groupEvent, item ];
5042 item.connect( this, add );
5043 }
5044 }
5045 }
5046 }
5047 };
5048
5049 /**
5050 * Add items to the group.
5051 *
5052 * Items will be added to the end of the group array unless the optional `index` parameter specifies
5053 * a different insertion point. Adding an existing item will move it to the end of the array or the point specified by the `index`.
5054 *
5055 * @param {OO.ui.Element[]} items An array of items to add to the group
5056 * @param {number} [index] Index of the insertion point
5057 * @chainable
5058 */
5059 OO.ui.mixin.GroupElement.prototype.addItems = function ( items, index ) {
5060 var i, len, item, event, events, currentIndex,
5061 itemElements = [];
5062
5063 for ( i = 0, len = items.length; i < len; i++ ) {
5064 item = items[ i ];
5065
5066 // Check if item exists then remove it first, effectively "moving" it
5067 currentIndex = this.items.indexOf( item );
5068 if ( currentIndex >= 0 ) {
5069 this.removeItems( [ item ] );
5070 // Adjust index to compensate for removal
5071 if ( currentIndex < index ) {
5072 index--;
5073 }
5074 }
5075 // Add the item
5076 if ( item.connect && item.disconnect && !$.isEmptyObject( this.aggregateItemEvents ) ) {
5077 events = {};
5078 for ( event in this.aggregateItemEvents ) {
5079 events[ event ] = [ 'emit', this.aggregateItemEvents[ event ], item ];
5080 }
5081 item.connect( this, events );
5082 }
5083 item.setElementGroup( this );
5084 itemElements.push( item.$element.get( 0 ) );
5085 }
5086
5087 if ( index === undefined || index < 0 || index >= this.items.length ) {
5088 this.$group.append( itemElements );
5089 this.items.push.apply( this.items, items );
5090 } else if ( index === 0 ) {
5091 this.$group.prepend( itemElements );
5092 this.items.unshift.apply( this.items, items );
5093 } else {
5094 this.items[ index ].$element.before( itemElements );
5095 this.items.splice.apply( this.items, [ index, 0 ].concat( items ) );
5096 }
5097
5098 return this;
5099 };
5100
5101 /**
5102 * Remove the specified items from a group.
5103 *
5104 * Removed items are detached (not removed) from the DOM so that they may be reused.
5105 * To remove all items from a group, you may wish to use the #clearItems method instead.
5106 *
5107 * @param {OO.ui.Element[]} items An array of items to remove
5108 * @chainable
5109 */
5110 OO.ui.mixin.GroupElement.prototype.removeItems = function ( items ) {
5111 var i, len, item, index, remove, itemEvent;
5112
5113 // Remove specific items
5114 for ( i = 0, len = items.length; i < len; i++ ) {
5115 item = items[ i ];
5116 index = this.items.indexOf( item );
5117 if ( index !== -1 ) {
5118 if (
5119 item.connect && item.disconnect &&
5120 !$.isEmptyObject( this.aggregateItemEvents )
5121 ) {
5122 remove = {};
5123 if ( Object.prototype.hasOwnProperty.call( this.aggregateItemEvents, itemEvent ) ) {
5124 remove[ itemEvent ] = [ 'emit', this.aggregateItemEvents[ itemEvent ], item ];
5125 }
5126 item.disconnect( this, remove );
5127 }
5128 item.setElementGroup( null );
5129 this.items.splice( index, 1 );
5130 item.$element.detach();
5131 }
5132 }
5133
5134 return this;
5135 };
5136
5137 /**
5138 * Clear all items from the group.
5139 *
5140 * Cleared items are detached from the DOM, not removed, so that they may be reused.
5141 * To remove only a subset of items from a group, use the #removeItems method.
5142 *
5143 * @chainable
5144 */
5145 OO.ui.mixin.GroupElement.prototype.clearItems = function () {
5146 var i, len, item, remove, itemEvent;
5147
5148 // Remove all items
5149 for ( i = 0, len = this.items.length; i < len; i++ ) {
5150 item = this.items[ i ];
5151 if (
5152 item.connect && item.disconnect &&
5153 !$.isEmptyObject( this.aggregateItemEvents )
5154 ) {
5155 remove = {};
5156 if ( Object.prototype.hasOwnProperty.call( this.aggregateItemEvents, itemEvent ) ) {
5157 remove[ itemEvent ] = [ 'emit', this.aggregateItemEvents[ itemEvent ], item ];
5158 }
5159 item.disconnect( this, remove );
5160 }
5161 item.setElementGroup( null );
5162 item.$element.detach();
5163 }
5164
5165 this.items = [];
5166 return this;
5167 };
5168
5169 /**
5170 * DraggableElement is a mixin class used to create elements that can be clicked
5171 * and dragged by a mouse to a new position within a group. This class must be used
5172 * in conjunction with OO.ui.mixin.DraggableGroupElement, which provides a container for
5173 * the draggable elements.
5174 *
5175 * @abstract
5176 * @class
5177 *
5178 * @constructor
5179 */
5180 OO.ui.mixin.DraggableElement = function OoUiMixinDraggableElement() {
5181 // Properties
5182 this.index = null;
5183
5184 // Initialize and events
5185 this.$element
5186 .attr( 'draggable', true )
5187 .addClass( 'oo-ui-draggableElement' )
5188 .on( {
5189 dragstart: this.onDragStart.bind( this ),
5190 dragover: this.onDragOver.bind( this ),
5191 dragend: this.onDragEnd.bind( this ),
5192 drop: this.onDrop.bind( this )
5193 } );
5194 };
5195
5196 OO.initClass( OO.ui.mixin.DraggableElement );
5197
5198 /* Events */
5199
5200 /**
5201 * @event dragstart
5202 *
5203 * A dragstart event is emitted when the user clicks and begins dragging an item.
5204 * @param {OO.ui.mixin.DraggableElement} item The item the user has clicked and is dragging with the mouse.
5205 */
5206
5207 /**
5208 * @event dragend
5209 * A dragend event is emitted when the user drags an item and releases the mouse,
5210 * thus terminating the drag operation.
5211 */
5212
5213 /**
5214 * @event drop
5215 * A drop event is emitted when the user drags an item and then releases the mouse button
5216 * over a valid target.
5217 */
5218
5219 /* Static Properties */
5220
5221 /**
5222 * @inheritdoc OO.ui.mixin.ButtonElement
5223 */
5224 OO.ui.mixin.DraggableElement.static.cancelButtonMouseDownEvents = false;
5225
5226 /* Methods */
5227
5228 /**
5229 * Respond to dragstart event.
5230 *
5231 * @private
5232 * @param {jQuery.Event} event jQuery event
5233 * @fires dragstart
5234 */
5235 OO.ui.mixin.DraggableElement.prototype.onDragStart = function ( e ) {
5236 var dataTransfer = e.originalEvent.dataTransfer;
5237 // Define drop effect
5238 dataTransfer.dropEffect = 'none';
5239 dataTransfer.effectAllowed = 'move';
5240 // Support: Firefox
5241 // We must set up a dataTransfer data property or Firefox seems to
5242 // ignore the fact the element is draggable.
5243 try {
5244 dataTransfer.setData( 'application-x/OOjs-UI-draggable', this.getIndex() );
5245 } catch ( err ) {
5246 // The above is only for Firefox. Move on if it fails.
5247 }
5248 // Add dragging class
5249 this.$element.addClass( 'oo-ui-draggableElement-dragging' );
5250 // Emit event
5251 this.emit( 'dragstart', this );
5252 return true;
5253 };
5254
5255 /**
5256 * Respond to dragend event.
5257 *
5258 * @private
5259 * @fires dragend
5260 */
5261 OO.ui.mixin.DraggableElement.prototype.onDragEnd = function () {
5262 this.$element.removeClass( 'oo-ui-draggableElement-dragging' );
5263 this.emit( 'dragend' );
5264 };
5265
5266 /**
5267 * Handle drop event.
5268 *
5269 * @private
5270 * @param {jQuery.Event} event jQuery event
5271 * @fires drop
5272 */
5273 OO.ui.mixin.DraggableElement.prototype.onDrop = function ( e ) {
5274 e.preventDefault();
5275 this.emit( 'drop', e );
5276 };
5277
5278 /**
5279 * In order for drag/drop to work, the dragover event must
5280 * return false and stop propogation.
5281 *
5282 * @private
5283 */
5284 OO.ui.mixin.DraggableElement.prototype.onDragOver = function ( e ) {
5285 e.preventDefault();
5286 };
5287
5288 /**
5289 * Set item index.
5290 * Store it in the DOM so we can access from the widget drag event
5291 *
5292 * @private
5293 * @param {number} Item index
5294 */
5295 OO.ui.mixin.DraggableElement.prototype.setIndex = function ( index ) {
5296 if ( this.index !== index ) {
5297 this.index = index;
5298 this.$element.data( 'index', index );
5299 }
5300 };
5301
5302 /**
5303 * Get item index
5304 *
5305 * @private
5306 * @return {number} Item index
5307 */
5308 OO.ui.mixin.DraggableElement.prototype.getIndex = function () {
5309 return this.index;
5310 };
5311
5312 /**
5313 * DraggableGroupElement is a mixin class used to create a group element to
5314 * contain draggable elements, which are items that can be clicked and dragged by a mouse.
5315 * The class is used with OO.ui.mixin.DraggableElement.
5316 *
5317 * @abstract
5318 * @class
5319 * @mixins OO.ui.mixin.GroupElement
5320 *
5321 * @constructor
5322 * @param {Object} [config] Configuration options
5323 * @cfg {string} [orientation] Item orientation: 'horizontal' or 'vertical'. The orientation
5324 * should match the layout of the items. Items displayed in a single row
5325 * or in several rows should use horizontal orientation. The vertical orientation should only be
5326 * used when the items are displayed in a single column. Defaults to 'vertical'
5327 */
5328 OO.ui.mixin.DraggableGroupElement = function OoUiMixinDraggableGroupElement( config ) {
5329 // Configuration initialization
5330 config = config || {};
5331
5332 // Parent constructor
5333 OO.ui.mixin.GroupElement.call( this, config );
5334
5335 // Properties
5336 this.orientation = config.orientation || 'vertical';
5337 this.dragItem = null;
5338 this.itemDragOver = null;
5339 this.itemKeys = {};
5340 this.sideInsertion = '';
5341
5342 // Events
5343 this.aggregate( {
5344 dragstart: 'itemDragStart',
5345 dragend: 'itemDragEnd',
5346 drop: 'itemDrop'
5347 } );
5348 this.connect( this, {
5349 itemDragStart: 'onItemDragStart',
5350 itemDrop: 'onItemDrop',
5351 itemDragEnd: 'onItemDragEnd'
5352 } );
5353 this.$element.on( {
5354 dragover: this.onDragOver.bind( this ),
5355 dragleave: this.onDragLeave.bind( this )
5356 } );
5357
5358 // Initialize
5359 if ( Array.isArray( config.items ) ) {
5360 this.addItems( config.items );
5361 }
5362 this.$placeholder = $( '<div>' )
5363 .addClass( 'oo-ui-draggableGroupElement-placeholder' );
5364 this.$element
5365 .addClass( 'oo-ui-draggableGroupElement' )
5366 .append( this.$status )
5367 .toggleClass( 'oo-ui-draggableGroupElement-horizontal', this.orientation === 'horizontal' )
5368 .prepend( this.$placeholder );
5369 };
5370
5371 /* Setup */
5372 OO.mixinClass( OO.ui.mixin.DraggableGroupElement, OO.ui.mixin.GroupElement );
5373
5374 /* Events */
5375
5376 /**
5377 * A 'reorder' event is emitted when the order of items in the group changes.
5378 *
5379 * @event reorder
5380 * @param {OO.ui.mixin.DraggableElement} item Reordered item
5381 * @param {number} [newIndex] New index for the item
5382 */
5383
5384 /* Methods */
5385
5386 /**
5387 * Respond to item drag start event
5388 *
5389 * @private
5390 * @param {OO.ui.mixin.DraggableElement} item Dragged item
5391 */
5392 OO.ui.mixin.DraggableGroupElement.prototype.onItemDragStart = function ( item ) {
5393 var i, len;
5394
5395 // Map the index of each object
5396 for ( i = 0, len = this.items.length; i < len; i++ ) {
5397 this.items[ i ].setIndex( i );
5398 }
5399
5400 if ( this.orientation === 'horizontal' ) {
5401 // Set the height of the indicator
5402 this.$placeholder.css( {
5403 height: item.$element.outerHeight(),
5404 width: 2
5405 } );
5406 } else {
5407 // Set the width of the indicator
5408 this.$placeholder.css( {
5409 height: 2,
5410 width: item.$element.outerWidth()
5411 } );
5412 }
5413 this.setDragItem( item );
5414 };
5415
5416 /**
5417 * Respond to item drag end event
5418 *
5419 * @private
5420 */
5421 OO.ui.mixin.DraggableGroupElement.prototype.onItemDragEnd = function () {
5422 this.unsetDragItem();
5423 return false;
5424 };
5425
5426 /**
5427 * Handle drop event and switch the order of the items accordingly
5428 *
5429 * @private
5430 * @param {OO.ui.mixin.DraggableElement} item Dropped item
5431 * @fires reorder
5432 */
5433 OO.ui.mixin.DraggableGroupElement.prototype.onItemDrop = function ( item ) {
5434 var toIndex = item.getIndex();
5435 // Check if the dropped item is from the current group
5436 // TODO: Figure out a way to configure a list of legally droppable
5437 // elements even if they are not yet in the list
5438 if ( this.getDragItem() ) {
5439 // If the insertion point is 'after', the insertion index
5440 // is shifted to the right (or to the left in RTL, hence 'after')
5441 if ( this.sideInsertion === 'after' ) {
5442 toIndex++;
5443 }
5444 // Emit change event
5445 this.emit( 'reorder', this.getDragItem(), toIndex );
5446 }
5447 this.unsetDragItem();
5448 // Return false to prevent propogation
5449 return false;
5450 };
5451
5452 /**
5453 * Handle dragleave event.
5454 *
5455 * @private
5456 */
5457 OO.ui.mixin.DraggableGroupElement.prototype.onDragLeave = function () {
5458 // This means the item was dragged outside the widget
5459 this.$placeholder
5460 .css( 'left', 0 )
5461 .addClass( 'oo-ui-element-hidden' );
5462 };
5463
5464 /**
5465 * Respond to dragover event
5466 *
5467 * @private
5468 * @param {jQuery.Event} event Event details
5469 */
5470 OO.ui.mixin.DraggableGroupElement.prototype.onDragOver = function ( e ) {
5471 var dragOverObj, $optionWidget, itemOffset, itemMidpoint, itemBoundingRect,
5472 itemSize, cssOutput, dragPosition, itemIndex, itemPosition,
5473 clientX = e.originalEvent.clientX,
5474 clientY = e.originalEvent.clientY;
5475
5476 // Get the OptionWidget item we are dragging over
5477 dragOverObj = this.getElementDocument().elementFromPoint( clientX, clientY );
5478 $optionWidget = $( dragOverObj ).closest( '.oo-ui-draggableElement' );
5479 if ( $optionWidget[ 0 ] ) {
5480 itemOffset = $optionWidget.offset();
5481 itemBoundingRect = $optionWidget[ 0 ].getBoundingClientRect();
5482 itemPosition = $optionWidget.position();
5483 itemIndex = $optionWidget.data( 'index' );
5484 }
5485
5486 if (
5487 itemOffset &&
5488 this.isDragging() &&
5489 itemIndex !== this.getDragItem().getIndex()
5490 ) {
5491 if ( this.orientation === 'horizontal' ) {
5492 // Calculate where the mouse is relative to the item width
5493 itemSize = itemBoundingRect.width;
5494 itemMidpoint = itemBoundingRect.left + itemSize / 2;
5495 dragPosition = clientX;
5496 // Which side of the item we hover over will dictate
5497 // where the placeholder will appear, on the left or
5498 // on the right
5499 cssOutput = {
5500 left: dragPosition < itemMidpoint ? itemPosition.left : itemPosition.left + itemSize,
5501 top: itemPosition.top
5502 };
5503 } else {
5504 // Calculate where the mouse is relative to the item height
5505 itemSize = itemBoundingRect.height;
5506 itemMidpoint = itemBoundingRect.top + itemSize / 2;
5507 dragPosition = clientY;
5508 // Which side of the item we hover over will dictate
5509 // where the placeholder will appear, on the top or
5510 // on the bottom
5511 cssOutput = {
5512 top: dragPosition < itemMidpoint ? itemPosition.top : itemPosition.top + itemSize,
5513 left: itemPosition.left
5514 };
5515 }
5516 // Store whether we are before or after an item to rearrange
5517 // For horizontal layout, we need to account for RTL, as this is flipped
5518 if ( this.orientation === 'horizontal' && this.$element.css( 'direction' ) === 'rtl' ) {
5519 this.sideInsertion = dragPosition < itemMidpoint ? 'after' : 'before';
5520 } else {
5521 this.sideInsertion = dragPosition < itemMidpoint ? 'before' : 'after';
5522 }
5523 // Add drop indicator between objects
5524 this.$placeholder
5525 .css( cssOutput )
5526 .removeClass( 'oo-ui-element-hidden' );
5527 } else {
5528 // This means the item was dragged outside the widget
5529 this.$placeholder
5530 .css( 'left', 0 )
5531 .addClass( 'oo-ui-element-hidden' );
5532 }
5533 // Prevent default
5534 e.preventDefault();
5535 };
5536
5537 /**
5538 * Set a dragged item
5539 *
5540 * @param {OO.ui.mixin.DraggableElement} item Dragged item
5541 */
5542 OO.ui.mixin.DraggableGroupElement.prototype.setDragItem = function ( item ) {
5543 this.dragItem = item;
5544 };
5545
5546 /**
5547 * Unset the current dragged item
5548 */
5549 OO.ui.mixin.DraggableGroupElement.prototype.unsetDragItem = function () {
5550 this.dragItem = null;
5551 this.itemDragOver = null;
5552 this.$placeholder.addClass( 'oo-ui-element-hidden' );
5553 this.sideInsertion = '';
5554 };
5555
5556 /**
5557 * Get the item that is currently being dragged.
5558 *
5559 * @return {OO.ui.mixin.DraggableElement|null} The currently dragged item, or `null` if no item is being dragged
5560 */
5561 OO.ui.mixin.DraggableGroupElement.prototype.getDragItem = function () {
5562 return this.dragItem;
5563 };
5564
5565 /**
5566 * Check if an item in the group is currently being dragged.
5567 *
5568 * @return {Boolean} Item is being dragged
5569 */
5570 OO.ui.mixin.DraggableGroupElement.prototype.isDragging = function () {
5571 return this.getDragItem() !== null;
5572 };
5573
5574 /**
5575 * IconElement is often mixed into other classes to generate an icon.
5576 * Icons are graphics, about the size of normal text. They are used to aid the user
5577 * in locating a control or to convey information in a space-efficient way. See the
5578 * [OOjs UI documentation on MediaWiki] [1] for a list of icons
5579 * included in the library.
5580 *
5581 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
5582 *
5583 * @abstract
5584 * @class
5585 *
5586 * @constructor
5587 * @param {Object} [config] Configuration options
5588 * @cfg {jQuery} [$icon] The icon element created by the class. If this configuration is omitted,
5589 * the icon element will use a generated `<span>`. To use a different HTML tag, or to specify that
5590 * the icon element be set to an existing icon instead of the one generated by this class, set a
5591 * value using a jQuery selection. For example:
5592 *
5593 * // Use a <div> tag instead of a <span>
5594 * $icon: $("<div>")
5595 * // Use an existing icon element instead of the one generated by the class
5596 * $icon: this.$element
5597 * // Use an icon element from a child widget
5598 * $icon: this.childwidget.$element
5599 * @cfg {Object|string} [icon=''] The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of
5600 * symbolic names. A map is used for i18n purposes and contains a `default` icon
5601 * name and additional names keyed by language code. The `default` name is used when no icon is keyed
5602 * by the user's language.
5603 *
5604 * Example of an i18n map:
5605 *
5606 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
5607 * See the [OOjs UI documentation on MediaWiki] [2] for a list of icons included in the library.
5608 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
5609 * @cfg {string|Function} [iconTitle] A text string used as the icon title, or a function that returns title
5610 * text. The icon title is displayed when users move the mouse over the icon.
5611 */
5612 OO.ui.mixin.IconElement = function OoUiMixinIconElement( config ) {
5613 // Configuration initialization
5614 config = config || {};
5615
5616 // Properties
5617 this.$icon = null;
5618 this.icon = null;
5619 this.iconTitle = null;
5620
5621 // Initialization
5622 this.setIcon( config.icon || this.constructor.static.icon );
5623 this.setIconTitle( config.iconTitle || this.constructor.static.iconTitle );
5624 this.setIconElement( config.$icon || $( '<span>' ) );
5625 };
5626
5627 /* Setup */
5628
5629 OO.initClass( OO.ui.mixin.IconElement );
5630
5631 /* Static Properties */
5632
5633 /**
5634 * The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of symbolic names. A map is used
5635 * for i18n purposes and contains a `default` icon name and additional names keyed by
5636 * language code. The `default` name is used when no icon is keyed by the user's language.
5637 *
5638 * Example of an i18n map:
5639 *
5640 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
5641 *
5642 * Note: the static property will be overridden if the #icon configuration is used.
5643 *
5644 * @static
5645 * @inheritable
5646 * @property {Object|string}
5647 */
5648 OO.ui.mixin.IconElement.static.icon = null;
5649
5650 /**
5651 * The icon title, displayed when users move the mouse over the icon. The value can be text, a
5652 * function that returns title text, or `null` for no title.
5653 *
5654 * The static property will be overridden if the #iconTitle configuration is used.
5655 *
5656 * @static
5657 * @inheritable
5658 * @property {string|Function|null}
5659 */
5660 OO.ui.mixin.IconElement.static.iconTitle = null;
5661
5662 /* Methods */
5663
5664 /**
5665 * Set the icon element. This method is used to retarget an icon mixin so that its functionality
5666 * applies to the specified icon element instead of the one created by the class. If an icon
5667 * element is already set, the mixin’s effect on that element is removed. Generated CSS classes
5668 * and mixin methods will no longer affect the element.
5669 *
5670 * @param {jQuery} $icon Element to use as icon
5671 */
5672 OO.ui.mixin.IconElement.prototype.setIconElement = function ( $icon ) {
5673 if ( this.$icon ) {
5674 this.$icon
5675 .removeClass( 'oo-ui-iconElement-icon oo-ui-icon-' + this.icon )
5676 .removeAttr( 'title' );
5677 }
5678
5679 this.$icon = $icon
5680 .addClass( 'oo-ui-iconElement-icon' )
5681 .toggleClass( 'oo-ui-icon-' + this.icon, !!this.icon );
5682 if ( this.iconTitle !== null ) {
5683 this.$icon.attr( 'title', this.iconTitle );
5684 }
5685
5686 this.updateThemeClasses();
5687 };
5688
5689 /**
5690 * Set icon by symbolic name (e.g., ‘remove’ or ‘menu’). Use `null` to remove an icon.
5691 * The icon parameter can also be set to a map of icon names. See the #icon config setting
5692 * for an example.
5693 *
5694 * @param {Object|string|null} icon A symbolic icon name, a {@link #icon map of icon names} keyed
5695 * by language code, or `null` to remove the icon.
5696 * @chainable
5697 */
5698 OO.ui.mixin.IconElement.prototype.setIcon = function ( icon ) {
5699 icon = OO.isPlainObject( icon ) ? OO.ui.getLocalValue( icon, null, 'default' ) : icon;
5700 icon = typeof icon === 'string' && icon.trim().length ? icon.trim() : null;
5701
5702 if ( this.icon !== icon ) {
5703 if ( this.$icon ) {
5704 if ( this.icon !== null ) {
5705 this.$icon.removeClass( 'oo-ui-icon-' + this.icon );
5706 }
5707 if ( icon !== null ) {
5708 this.$icon.addClass( 'oo-ui-icon-' + icon );
5709 }
5710 }
5711 this.icon = icon;
5712 }
5713
5714 this.$element.toggleClass( 'oo-ui-iconElement', !!this.icon );
5715 this.updateThemeClasses();
5716
5717 return this;
5718 };
5719
5720 /**
5721 * Set the icon title. Use `null` to remove the title.
5722 *
5723 * @param {string|Function|null} iconTitle A text string used as the icon title,
5724 * a function that returns title text, or `null` for no title.
5725 * @chainable
5726 */
5727 OO.ui.mixin.IconElement.prototype.setIconTitle = function ( iconTitle ) {
5728 iconTitle = typeof iconTitle === 'function' ||
5729 ( typeof iconTitle === 'string' && iconTitle.length ) ?
5730 OO.ui.resolveMsg( iconTitle ) : null;
5731
5732 if ( this.iconTitle !== iconTitle ) {
5733 this.iconTitle = iconTitle;
5734 if ( this.$icon ) {
5735 if ( this.iconTitle !== null ) {
5736 this.$icon.attr( 'title', iconTitle );
5737 } else {
5738 this.$icon.removeAttr( 'title' );
5739 }
5740 }
5741 }
5742
5743 return this;
5744 };
5745
5746 /**
5747 * Get the symbolic name of the icon.
5748 *
5749 * @return {string} Icon name
5750 */
5751 OO.ui.mixin.IconElement.prototype.getIcon = function () {
5752 return this.icon;
5753 };
5754
5755 /**
5756 * Get the icon title. The title text is displayed when a user moves the mouse over the icon.
5757 *
5758 * @return {string} Icon title text
5759 */
5760 OO.ui.mixin.IconElement.prototype.getIconTitle = function () {
5761 return this.iconTitle;
5762 };
5763
5764 /**
5765 * IndicatorElement is often mixed into other classes to generate an indicator.
5766 * Indicators are small graphics that are generally used in two ways:
5767 *
5768 * - To draw attention to the status of an item. For example, an indicator might be
5769 * used to show that an item in a list has errors that need to be resolved.
5770 * - To clarify the function of a control that acts in an exceptional way (a button
5771 * that opens a menu instead of performing an action directly, for example).
5772 *
5773 * For a list of indicators included in the library, please see the
5774 * [OOjs UI documentation on MediaWiki] [1].
5775 *
5776 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
5777 *
5778 * @abstract
5779 * @class
5780 *
5781 * @constructor
5782 * @param {Object} [config] Configuration options
5783 * @cfg {jQuery} [$indicator] The indicator element created by the class. If this
5784 * configuration is omitted, the indicator element will use a generated `<span>`.
5785 * @cfg {string} [indicator] Symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
5786 * See the [OOjs UI documentation on MediaWiki][2] for a list of indicators included
5787 * in the library.
5788 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
5789 * @cfg {string|Function} [indicatorTitle] A text string used as the indicator title,
5790 * or a function that returns title text. The indicator title is displayed when users move
5791 * the mouse over the indicator.
5792 */
5793 OO.ui.mixin.IndicatorElement = function OoUiMixinIndicatorElement( config ) {
5794 // Configuration initialization
5795 config = config || {};
5796
5797 // Properties
5798 this.$indicator = null;
5799 this.indicator = null;
5800 this.indicatorTitle = null;
5801
5802 // Initialization
5803 this.setIndicator( config.indicator || this.constructor.static.indicator );
5804 this.setIndicatorTitle( config.indicatorTitle || this.constructor.static.indicatorTitle );
5805 this.setIndicatorElement( config.$indicator || $( '<span>' ) );
5806 };
5807
5808 /* Setup */
5809
5810 OO.initClass( OO.ui.mixin.IndicatorElement );
5811
5812 /* Static Properties */
5813
5814 /**
5815 * Symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
5816 * The static property will be overridden if the #indicator configuration is used.
5817 *
5818 * @static
5819 * @inheritable
5820 * @property {string|null}
5821 */
5822 OO.ui.mixin.IndicatorElement.static.indicator = null;
5823
5824 /**
5825 * A text string used as the indicator title, a function that returns title text, or `null`
5826 * for no title. The static property will be overridden if the #indicatorTitle configuration is used.
5827 *
5828 * @static
5829 * @inheritable
5830 * @property {string|Function|null}
5831 */
5832 OO.ui.mixin.IndicatorElement.static.indicatorTitle = null;
5833
5834 /* Methods */
5835
5836 /**
5837 * Set the indicator element.
5838 *
5839 * If an element is already set, it will be cleaned up before setting up the new element.
5840 *
5841 * @param {jQuery} $indicator Element to use as indicator
5842 */
5843 OO.ui.mixin.IndicatorElement.prototype.setIndicatorElement = function ( $indicator ) {
5844 if ( this.$indicator ) {
5845 this.$indicator
5846 .removeClass( 'oo-ui-indicatorElement-indicator oo-ui-indicator-' + this.indicator )
5847 .removeAttr( 'title' );
5848 }
5849
5850 this.$indicator = $indicator
5851 .addClass( 'oo-ui-indicatorElement-indicator' )
5852 .toggleClass( 'oo-ui-indicator-' + this.indicator, !!this.indicator );
5853 if ( this.indicatorTitle !== null ) {
5854 this.$indicator.attr( 'title', this.indicatorTitle );
5855 }
5856
5857 this.updateThemeClasses();
5858 };
5859
5860 /**
5861 * Set the indicator by its symbolic name: ‘alert’, ‘down’, ‘next’, ‘previous’, ‘required’, ‘up’. Use `null` to remove the indicator.
5862 *
5863 * @param {string|null} indicator Symbolic name of indicator, or `null` for no indicator
5864 * @chainable
5865 */
5866 OO.ui.mixin.IndicatorElement.prototype.setIndicator = function ( indicator ) {
5867 indicator = typeof indicator === 'string' && indicator.length ? indicator.trim() : null;
5868
5869 if ( this.indicator !== indicator ) {
5870 if ( this.$indicator ) {
5871 if ( this.indicator !== null ) {
5872 this.$indicator.removeClass( 'oo-ui-indicator-' + this.indicator );
5873 }
5874 if ( indicator !== null ) {
5875 this.$indicator.addClass( 'oo-ui-indicator-' + indicator );
5876 }
5877 }
5878 this.indicator = indicator;
5879 }
5880
5881 this.$element.toggleClass( 'oo-ui-indicatorElement', !!this.indicator );
5882 this.updateThemeClasses();
5883
5884 return this;
5885 };
5886
5887 /**
5888 * Set the indicator title.
5889 *
5890 * The title is displayed when a user moves the mouse over the indicator.
5891 *
5892 * @param {string|Function|null} indicator Indicator title text, a function that returns text, or
5893 * `null` for no indicator title
5894 * @chainable
5895 */
5896 OO.ui.mixin.IndicatorElement.prototype.setIndicatorTitle = function ( indicatorTitle ) {
5897 indicatorTitle = typeof indicatorTitle === 'function' ||
5898 ( typeof indicatorTitle === 'string' && indicatorTitle.length ) ?
5899 OO.ui.resolveMsg( indicatorTitle ) : null;
5900
5901 if ( this.indicatorTitle !== indicatorTitle ) {
5902 this.indicatorTitle = indicatorTitle;
5903 if ( this.$indicator ) {
5904 if ( this.indicatorTitle !== null ) {
5905 this.$indicator.attr( 'title', indicatorTitle );
5906 } else {
5907 this.$indicator.removeAttr( 'title' );
5908 }
5909 }
5910 }
5911
5912 return this;
5913 };
5914
5915 /**
5916 * Get the symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
5917 *
5918 * @return {string} Symbolic name of indicator
5919 */
5920 OO.ui.mixin.IndicatorElement.prototype.getIndicator = function () {
5921 return this.indicator;
5922 };
5923
5924 /**
5925 * Get the indicator title.
5926 *
5927 * The title is displayed when a user moves the mouse over the indicator.
5928 *
5929 * @return {string} Indicator title text
5930 */
5931 OO.ui.mixin.IndicatorElement.prototype.getIndicatorTitle = function () {
5932 return this.indicatorTitle;
5933 };
5934
5935 /**
5936 * LabelElement is often mixed into other classes to generate a label, which
5937 * helps identify the function of an interface element.
5938 * See the [OOjs UI documentation on MediaWiki] [1] for more information.
5939 *
5940 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Labels
5941 *
5942 * @abstract
5943 * @class
5944 *
5945 * @constructor
5946 * @param {Object} [config] Configuration options
5947 * @cfg {jQuery} [$label] The label element created by the class. If this
5948 * configuration is omitted, the label element will use a generated `<span>`.
5949 * @cfg {jQuery|string|Function|OO.ui.HtmlSnippet} [label] The label text. The label can be specified
5950 * as a plaintext string, a jQuery selection of elements, or a function that will produce a string
5951 * in the future. See the [OOjs UI documentation on MediaWiki] [2] for examples.
5952 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Labels
5953 * @cfg {boolean} [autoFitLabel=true] Fit the label to the width of the parent element.
5954 * The label will be truncated to fit if necessary.
5955 */
5956 OO.ui.mixin.LabelElement = function OoUiMixinLabelElement( config ) {
5957 // Configuration initialization
5958 config = config || {};
5959
5960 // Properties
5961 this.$label = null;
5962 this.label = null;
5963 this.autoFitLabel = config.autoFitLabel === undefined || !!config.autoFitLabel;
5964
5965 // Initialization
5966 this.setLabel( config.label || this.constructor.static.label );
5967 this.setLabelElement( config.$label || $( '<span>' ) );
5968 };
5969
5970 /* Setup */
5971
5972 OO.initClass( OO.ui.mixin.LabelElement );
5973
5974 /* Events */
5975
5976 /**
5977 * @event labelChange
5978 * @param {string} value
5979 */
5980
5981 /* Static Properties */
5982
5983 /**
5984 * The label text. The label can be specified as a plaintext string, a function that will
5985 * produce a string in the future, or `null` for no label. The static value will
5986 * be overridden if a label is specified with the #label config option.
5987 *
5988 * @static
5989 * @inheritable
5990 * @property {string|Function|null}
5991 */
5992 OO.ui.mixin.LabelElement.static.label = null;
5993
5994 /* Methods */
5995
5996 /**
5997 * Set the label element.
5998 *
5999 * If an element is already set, it will be cleaned up before setting up the new element.
6000 *
6001 * @param {jQuery} $label Element to use as label
6002 */
6003 OO.ui.mixin.LabelElement.prototype.setLabelElement = function ( $label ) {
6004 if ( this.$label ) {
6005 this.$label.removeClass( 'oo-ui-labelElement-label' ).empty();
6006 }
6007
6008 this.$label = $label.addClass( 'oo-ui-labelElement-label' );
6009 this.setLabelContent( this.label );
6010 };
6011
6012 /**
6013 * Set the label.
6014 *
6015 * An empty string will result in the label being hidden. A string containing only whitespace will
6016 * be converted to a single `&nbsp;`.
6017 *
6018 * @param {jQuery|string|OO.ui.HtmlSnippet|Function|null} label Label nodes; text; a function that returns nodes or
6019 * text; or null for no label
6020 * @chainable
6021 */
6022 OO.ui.mixin.LabelElement.prototype.setLabel = function ( label ) {
6023 label = typeof label === 'function' ? OO.ui.resolveMsg( label ) : label;
6024 label = ( ( typeof label === 'string' && label.length ) || label instanceof jQuery || label instanceof OO.ui.HtmlSnippet ) ? label : null;
6025
6026 this.$element.toggleClass( 'oo-ui-labelElement', !!label );
6027
6028 if ( this.label !== label ) {
6029 if ( this.$label ) {
6030 this.setLabelContent( label );
6031 }
6032 this.label = label;
6033 this.emit( 'labelChange' );
6034 }
6035
6036 return this;
6037 };
6038
6039 /**
6040 * Get the label.
6041 *
6042 * @return {jQuery|string|Function|null} Label nodes; text; a function that returns nodes or
6043 * text; or null for no label
6044 */
6045 OO.ui.mixin.LabelElement.prototype.getLabel = function () {
6046 return this.label;
6047 };
6048
6049 /**
6050 * Fit the label.
6051 *
6052 * @chainable
6053 */
6054 OO.ui.mixin.LabelElement.prototype.fitLabel = function () {
6055 if ( this.$label && this.$label.autoEllipsis && this.autoFitLabel ) {
6056 this.$label.autoEllipsis( { hasSpan: false, tooltip: true } );
6057 }
6058
6059 return this;
6060 };
6061
6062 /**
6063 * Set the content of the label.
6064 *
6065 * Do not call this method until after the label element has been set by #setLabelElement.
6066 *
6067 * @private
6068 * @param {jQuery|string|Function|null} label Label nodes; text; a function that returns nodes or
6069 * text; or null for no label
6070 */
6071 OO.ui.mixin.LabelElement.prototype.setLabelContent = function ( label ) {
6072 if ( typeof label === 'string' ) {
6073 if ( label.match( /^\s*$/ ) ) {
6074 // Convert whitespace only string to a single non-breaking space
6075 this.$label.html( '&nbsp;' );
6076 } else {
6077 this.$label.text( label );
6078 }
6079 } else if ( label instanceof OO.ui.HtmlSnippet ) {
6080 this.$label.html( label.toString() );
6081 } else if ( label instanceof jQuery ) {
6082 this.$label.empty().append( label );
6083 } else {
6084 this.$label.empty();
6085 }
6086 };
6087
6088 /**
6089 * LookupElement is a mixin that creates a {@link OO.ui.FloatingMenuSelectWidget menu} of suggested values for
6090 * a {@link OO.ui.TextInputWidget text input widget}. Suggested values are based on the characters the user types
6091 * into the text input field and, in general, the menu is only displayed when the user types. If a suggested value is chosen
6092 * from the lookup menu, that value becomes the value of the input field.
6093 *
6094 * Note that a new menu of suggested items is displayed when a value is chosen from the lookup menu. If this is
6095 * not the desired behavior, disable lookup menus with the #setLookupsDisabled method, then set the value, then
6096 * re-enable lookups.
6097 *
6098 * See the [OOjs UI demos][1] for an example.
6099 *
6100 * [1]: https://tools.wmflabs.org/oojs-ui/oojs-ui/demos/index.html#widgets-apex-vector-ltr
6101 *
6102 * @class
6103 * @abstract
6104 *
6105 * @constructor
6106 * @param {Object} [config] Configuration options
6107 * @cfg {jQuery} [$overlay] Overlay for the lookup menu; defaults to relative positioning
6108 * @cfg {jQuery} [$container=this.$element] The container element. The lookup menu is rendered beneath the specified element.
6109 * @cfg {boolean} [allowSuggestionsWhenEmpty=false] Request and display a lookup menu when the text input is empty.
6110 * By default, the lookup menu is not generated and displayed until the user begins to type.
6111 * @cfg {boolean} [highlightFirst=true] Whether the first lookup result should be highlighted (so, that the user can
6112 * take it over into the input with simply pressing return) automatically or not.
6113 */
6114 OO.ui.mixin.LookupElement = function OoUiMixinLookupElement( config ) {
6115 // Configuration initialization
6116 config = $.extend( { highlightFirst: true }, config );
6117
6118 // Mixin constructors
6119 OO.ui.mixin.RequestManager.call( this, config );
6120
6121 // Properties
6122 this.$overlay = config.$overlay || this.$element;
6123 this.lookupMenu = new OO.ui.FloatingMenuSelectWidget( {
6124 widget: this,
6125 input: this,
6126 $container: config.$container || this.$element
6127 } );
6128
6129 this.allowSuggestionsWhenEmpty = config.allowSuggestionsWhenEmpty || false;
6130
6131 this.lookupsDisabled = false;
6132 this.lookupInputFocused = false;
6133 this.lookupHighlightFirstItem = config.highlightFirst;
6134
6135 // Events
6136 this.$input.on( {
6137 focus: this.onLookupInputFocus.bind( this ),
6138 blur: this.onLookupInputBlur.bind( this ),
6139 mousedown: this.onLookupInputMouseDown.bind( this )
6140 } );
6141 this.connect( this, { change: 'onLookupInputChange' } );
6142 this.lookupMenu.connect( this, {
6143 toggle: 'onLookupMenuToggle',
6144 choose: 'onLookupMenuItemChoose'
6145 } );
6146
6147 // Initialization
6148 this.$element.addClass( 'oo-ui-lookupElement' );
6149 this.lookupMenu.$element.addClass( 'oo-ui-lookupElement-menu' );
6150 this.$overlay.append( this.lookupMenu.$element );
6151 };
6152
6153 /* Setup */
6154
6155 OO.mixinClass( OO.ui.mixin.LookupElement, OO.ui.mixin.RequestManager );
6156
6157 /* Methods */
6158
6159 /**
6160 * Handle input focus event.
6161 *
6162 * @protected
6163 * @param {jQuery.Event} e Input focus event
6164 */
6165 OO.ui.mixin.LookupElement.prototype.onLookupInputFocus = function () {
6166 this.lookupInputFocused = true;
6167 this.populateLookupMenu();
6168 };
6169
6170 /**
6171 * Handle input blur event.
6172 *
6173 * @protected
6174 * @param {jQuery.Event} e Input blur event
6175 */
6176 OO.ui.mixin.LookupElement.prototype.onLookupInputBlur = function () {
6177 this.closeLookupMenu();
6178 this.lookupInputFocused = false;
6179 };
6180
6181 /**
6182 * Handle input mouse down event.
6183 *
6184 * @protected
6185 * @param {jQuery.Event} e Input mouse down event
6186 */
6187 OO.ui.mixin.LookupElement.prototype.onLookupInputMouseDown = function () {
6188 // Only open the menu if the input was already focused.
6189 // This way we allow the user to open the menu again after closing it with Esc
6190 // by clicking in the input. Opening (and populating) the menu when initially
6191 // clicking into the input is handled by the focus handler.
6192 if ( this.lookupInputFocused && !this.lookupMenu.isVisible() ) {
6193 this.populateLookupMenu();
6194 }
6195 };
6196
6197 /**
6198 * Handle input change event.
6199 *
6200 * @protected
6201 * @param {string} value New input value
6202 */
6203 OO.ui.mixin.LookupElement.prototype.onLookupInputChange = function () {
6204 if ( this.lookupInputFocused ) {
6205 this.populateLookupMenu();
6206 }
6207 };
6208
6209 /**
6210 * Handle the lookup menu being shown/hidden.
6211 *
6212 * @protected
6213 * @param {boolean} visible Whether the lookup menu is now visible.
6214 */
6215 OO.ui.mixin.LookupElement.prototype.onLookupMenuToggle = function ( visible ) {
6216 if ( !visible ) {
6217 // When the menu is hidden, abort any active request and clear the menu.
6218 // This has to be done here in addition to closeLookupMenu(), because
6219 // MenuSelectWidget will close itself when the user presses Esc.
6220 this.abortLookupRequest();
6221 this.lookupMenu.clearItems();
6222 }
6223 };
6224
6225 /**
6226 * Handle menu item 'choose' event, updating the text input value to the value of the clicked item.
6227 *
6228 * @protected
6229 * @param {OO.ui.MenuOptionWidget} item Selected item
6230 */
6231 OO.ui.mixin.LookupElement.prototype.onLookupMenuItemChoose = function ( item ) {
6232 this.setValue( item.getData() );
6233 };
6234
6235 /**
6236 * Get lookup menu.
6237 *
6238 * @private
6239 * @return {OO.ui.FloatingMenuSelectWidget}
6240 */
6241 OO.ui.mixin.LookupElement.prototype.getLookupMenu = function () {
6242 return this.lookupMenu;
6243 };
6244
6245 /**
6246 * Disable or re-enable lookups.
6247 *
6248 * When lookups are disabled, calls to #populateLookupMenu will be ignored.
6249 *
6250 * @param {boolean} disabled Disable lookups
6251 */
6252 OO.ui.mixin.LookupElement.prototype.setLookupsDisabled = function ( disabled ) {
6253 this.lookupsDisabled = !!disabled;
6254 };
6255
6256 /**
6257 * Open the menu. If there are no entries in the menu, this does nothing.
6258 *
6259 * @private
6260 * @chainable
6261 */
6262 OO.ui.mixin.LookupElement.prototype.openLookupMenu = function () {
6263 if ( !this.lookupMenu.isEmpty() ) {
6264 this.lookupMenu.toggle( true );
6265 }
6266 return this;
6267 };
6268
6269 /**
6270 * Close the menu, empty it, and abort any pending request.
6271 *
6272 * @private
6273 * @chainable
6274 */
6275 OO.ui.mixin.LookupElement.prototype.closeLookupMenu = function () {
6276 this.lookupMenu.toggle( false );
6277 this.abortLookupRequest();
6278 this.lookupMenu.clearItems();
6279 return this;
6280 };
6281
6282 /**
6283 * Request menu items based on the input's current value, and when they arrive,
6284 * populate the menu with these items and show the menu.
6285 *
6286 * If lookups have been disabled with #setLookupsDisabled, this function does nothing.
6287 *
6288 * @private
6289 * @chainable
6290 */
6291 OO.ui.mixin.LookupElement.prototype.populateLookupMenu = function () {
6292 var widget = this,
6293 value = this.getValue();
6294
6295 if ( this.lookupsDisabled || this.isReadOnly() ) {
6296 return;
6297 }
6298
6299 // If the input is empty, clear the menu, unless suggestions when empty are allowed.
6300 if ( !this.allowSuggestionsWhenEmpty && value === '' ) {
6301 this.closeLookupMenu();
6302 // Skip population if there is already a request pending for the current value
6303 } else if ( value !== this.lookupQuery ) {
6304 this.getLookupMenuItems()
6305 .done( function ( items ) {
6306 widget.lookupMenu.clearItems();
6307 if ( items.length ) {
6308 widget.lookupMenu
6309 .addItems( items )
6310 .toggle( true );
6311 widget.initializeLookupMenuSelection();
6312 } else {
6313 widget.lookupMenu.toggle( false );
6314 }
6315 } )
6316 .fail( function () {
6317 widget.lookupMenu.clearItems();
6318 } );
6319 }
6320
6321 return this;
6322 };
6323
6324 /**
6325 * Highlight the first selectable item in the menu, if configured.
6326 *
6327 * @private
6328 * @chainable
6329 */
6330 OO.ui.mixin.LookupElement.prototype.initializeLookupMenuSelection = function () {
6331 if ( this.lookupHighlightFirstItem && !this.lookupMenu.getSelectedItem() ) {
6332 this.lookupMenu.highlightItem( this.lookupMenu.getFirstSelectableItem() );
6333 }
6334 };
6335
6336 /**
6337 * Get lookup menu items for the current query.
6338 *
6339 * @private
6340 * @return {jQuery.Promise} Promise object which will be passed menu items as the first argument of
6341 * the done event. If the request was aborted to make way for a subsequent request, this promise
6342 * will not be rejected: it will remain pending forever.
6343 */
6344 OO.ui.mixin.LookupElement.prototype.getLookupMenuItems = function () {
6345 return this.getRequestData().then( function ( data ) {
6346 return this.getLookupMenuOptionsFromData( data );
6347 }.bind( this ) );
6348 };
6349
6350 /**
6351 * Abort the currently pending lookup request, if any.
6352 *
6353 * @private
6354 */
6355 OO.ui.mixin.LookupElement.prototype.abortLookupRequest = function () {
6356 this.abortRequest();
6357 };
6358
6359 /**
6360 * Get a new request object of the current lookup query value.
6361 *
6362 * @protected
6363 * @method
6364 * @abstract
6365 * @return {jQuery.Promise} jQuery AJAX object, or promise object with an .abort() method
6366 */
6367 OO.ui.mixin.LookupElement.prototype.getLookupRequest = null;
6368
6369 /**
6370 * Pre-process data returned by the request from #getLookupRequest.
6371 *
6372 * The return value of this function will be cached, and any further queries for the given value
6373 * will use the cache rather than doing API requests.
6374 *
6375 * @protected
6376 * @method
6377 * @abstract
6378 * @param {Mixed} response Response from server
6379 * @return {Mixed} Cached result data
6380 */
6381 OO.ui.mixin.LookupElement.prototype.getLookupCacheDataFromResponse = null;
6382
6383 /**
6384 * Get a list of menu option widgets from the (possibly cached) data returned by
6385 * #getLookupCacheDataFromResponse.
6386 *
6387 * @protected
6388 * @method
6389 * @abstract
6390 * @param {Mixed} data Cached result data, usually an array
6391 * @return {OO.ui.MenuOptionWidget[]} Menu items
6392 */
6393 OO.ui.mixin.LookupElement.prototype.getLookupMenuOptionsFromData = null;
6394
6395 /**
6396 * Set the read-only state of the widget.
6397 *
6398 * This will also disable/enable the lookups functionality.
6399 *
6400 * @param {boolean} readOnly Make input read-only
6401 * @chainable
6402 */
6403 OO.ui.mixin.LookupElement.prototype.setReadOnly = function ( readOnly ) {
6404 // Parent method
6405 // Note: Calling #setReadOnly this way assumes this is mixed into an OO.ui.TextInputWidget
6406 OO.ui.TextInputWidget.prototype.setReadOnly.call( this, readOnly );
6407
6408 // During construction, #setReadOnly is called before the OO.ui.mixin.LookupElement constructor
6409 if ( this.isReadOnly() && this.lookupMenu ) {
6410 this.closeLookupMenu();
6411 }
6412
6413 return this;
6414 };
6415
6416 /**
6417 * @inheritdoc OO.ui.mixin.RequestManager
6418 */
6419 OO.ui.mixin.LookupElement.prototype.getRequestQuery = function () {
6420 return this.getValue();
6421 };
6422
6423 /**
6424 * @inheritdoc OO.ui.mixin.RequestManager
6425 */
6426 OO.ui.mixin.LookupElement.prototype.getRequest = function () {
6427 return this.getLookupRequest();
6428 };
6429
6430 /**
6431 * @inheritdoc OO.ui.mixin.RequestManager
6432 */
6433 OO.ui.mixin.LookupElement.prototype.getRequestCacheDataFromResponse = function ( response ) {
6434 return this.getLookupCacheDataFromResponse( response );
6435 };
6436
6437 /**
6438 * PopupElement is mixed into other classes to generate a {@link OO.ui.PopupWidget popup widget}.
6439 * A popup is a container for content. It is overlaid and positioned absolutely. By default, each
6440 * popup has an anchor, which is an arrow-like protrusion that points toward the popup’s origin.
6441 * See {@link OO.ui.PopupWidget PopupWidget} for an example.
6442 *
6443 * @abstract
6444 * @class
6445 *
6446 * @constructor
6447 * @param {Object} [config] Configuration options
6448 * @cfg {Object} [popup] Configuration to pass to popup
6449 * @cfg {boolean} [popup.autoClose=true] Popup auto-closes when it loses focus
6450 */
6451 OO.ui.mixin.PopupElement = function OoUiMixinPopupElement( config ) {
6452 // Configuration initialization
6453 config = config || {};
6454
6455 // Properties
6456 this.popup = new OO.ui.PopupWidget( $.extend(
6457 { autoClose: true },
6458 config.popup,
6459 { $autoCloseIgnore: this.$element }
6460 ) );
6461 };
6462
6463 /* Methods */
6464
6465 /**
6466 * Get popup.
6467 *
6468 * @return {OO.ui.PopupWidget} Popup widget
6469 */
6470 OO.ui.mixin.PopupElement.prototype.getPopup = function () {
6471 return this.popup;
6472 };
6473
6474 /**
6475 * The FlaggedElement class is an attribute mixin, meaning that it is used to add
6476 * additional functionality to an element created by another class. The class provides
6477 * a ‘flags’ property assigned the name (or an array of names) of styling flags,
6478 * which are used to customize the look and feel of a widget to better describe its
6479 * importance and functionality.
6480 *
6481 * The library currently contains the following styling flags for general use:
6482 *
6483 * - **progressive**: Progressive styling is applied to convey that the widget will move the user forward in a process.
6484 * - **destructive**: Destructive styling is applied to convey that the widget will remove something.
6485 * - **constructive**: Constructive styling is applied to convey that the widget will create something.
6486 *
6487 * The flags affect the appearance of the buttons:
6488 *
6489 * @example
6490 * // FlaggedElement is mixed into ButtonWidget to provide styling flags
6491 * var button1 = new OO.ui.ButtonWidget( {
6492 * label: 'Constructive',
6493 * flags: 'constructive'
6494 * } );
6495 * var button2 = new OO.ui.ButtonWidget( {
6496 * label: 'Destructive',
6497 * flags: 'destructive'
6498 * } );
6499 * var button3 = new OO.ui.ButtonWidget( {
6500 * label: 'Progressive',
6501 * flags: 'progressive'
6502 * } );
6503 * $( 'body' ).append( button1.$element, button2.$element, button3.$element );
6504 *
6505 * {@link OO.ui.ActionWidget ActionWidgets}, which are a special kind of button that execute an action, use these flags: **primary** and **safe**.
6506 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information.
6507 *
6508 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Flagged
6509 *
6510 * @abstract
6511 * @class
6512 *
6513 * @constructor
6514 * @param {Object} [config] Configuration options
6515 * @cfg {string|string[]} [flags] The name or names of the flags (e.g., 'constructive' or 'primary') to apply.
6516 * Please see the [OOjs UI documentation on MediaWiki] [2] for more information about available flags.
6517 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Flagged
6518 * @cfg {jQuery} [$flagged] The flagged element. By default,
6519 * the flagged functionality is applied to the element created by the class ($element).
6520 * If a different element is specified, the flagged functionality will be applied to it instead.
6521 */
6522 OO.ui.mixin.FlaggedElement = function OoUiMixinFlaggedElement( config ) {
6523 // Configuration initialization
6524 config = config || {};
6525
6526 // Properties
6527 this.flags = {};
6528 this.$flagged = null;
6529
6530 // Initialization
6531 this.setFlags( config.flags );
6532 this.setFlaggedElement( config.$flagged || this.$element );
6533 };
6534
6535 /* Events */
6536
6537 /**
6538 * @event flag
6539 * A flag event is emitted when the #clearFlags or #setFlags methods are used. The `changes`
6540 * parameter contains the name of each modified flag and indicates whether it was
6541 * added or removed.
6542 *
6543 * @param {Object.<string,boolean>} changes Object keyed by flag name. A Boolean `true` indicates
6544 * that the flag was added, `false` that the flag was removed.
6545 */
6546
6547 /* Methods */
6548
6549 /**
6550 * Set the flagged element.
6551 *
6552 * This method is used to retarget a flagged mixin so that its functionality applies to the specified element.
6553 * If an element is already set, the method will remove the mixin’s effect on that element.
6554 *
6555 * @param {jQuery} $flagged Element that should be flagged
6556 */
6557 OO.ui.mixin.FlaggedElement.prototype.setFlaggedElement = function ( $flagged ) {
6558 var classNames = Object.keys( this.flags ).map( function ( flag ) {
6559 return 'oo-ui-flaggedElement-' + flag;
6560 } ).join( ' ' );
6561
6562 if ( this.$flagged ) {
6563 this.$flagged.removeClass( classNames );
6564 }
6565
6566 this.$flagged = $flagged.addClass( classNames );
6567 };
6568
6569 /**
6570 * Check if the specified flag is set.
6571 *
6572 * @param {string} flag Name of flag
6573 * @return {boolean} The flag is set
6574 */
6575 OO.ui.mixin.FlaggedElement.prototype.hasFlag = function ( flag ) {
6576 // This may be called before the constructor, thus before this.flags is set
6577 return this.flags && ( flag in this.flags );
6578 };
6579
6580 /**
6581 * Get the names of all flags set.
6582 *
6583 * @return {string[]} Flag names
6584 */
6585 OO.ui.mixin.FlaggedElement.prototype.getFlags = function () {
6586 // This may be called before the constructor, thus before this.flags is set
6587 return Object.keys( this.flags || {} );
6588 };
6589
6590 /**
6591 * Clear all flags.
6592 *
6593 * @chainable
6594 * @fires flag
6595 */
6596 OO.ui.mixin.FlaggedElement.prototype.clearFlags = function () {
6597 var flag, className,
6598 changes = {},
6599 remove = [],
6600 classPrefix = 'oo-ui-flaggedElement-';
6601
6602 for ( flag in this.flags ) {
6603 className = classPrefix + flag;
6604 changes[ flag ] = false;
6605 delete this.flags[ flag ];
6606 remove.push( className );
6607 }
6608
6609 if ( this.$flagged ) {
6610 this.$flagged.removeClass( remove.join( ' ' ) );
6611 }
6612
6613 this.updateThemeClasses();
6614 this.emit( 'flag', changes );
6615
6616 return this;
6617 };
6618
6619 /**
6620 * Add one or more flags.
6621 *
6622 * @param {string|string[]|Object.<string, boolean>} flags A flag name, an array of flag names,
6623 * or an object keyed by flag name with a boolean value that indicates whether the flag should
6624 * be added (`true`) or removed (`false`).
6625 * @chainable
6626 * @fires flag
6627 */
6628 OO.ui.mixin.FlaggedElement.prototype.setFlags = function ( flags ) {
6629 var i, len, flag, className,
6630 changes = {},
6631 add = [],
6632 remove = [],
6633 classPrefix = 'oo-ui-flaggedElement-';
6634
6635 if ( typeof flags === 'string' ) {
6636 className = classPrefix + flags;
6637 // Set
6638 if ( !this.flags[ flags ] ) {
6639 this.flags[ flags ] = true;
6640 add.push( className );
6641 }
6642 } else if ( Array.isArray( flags ) ) {
6643 for ( i = 0, len = flags.length; i < len; i++ ) {
6644 flag = flags[ i ];
6645 className = classPrefix + flag;
6646 // Set
6647 if ( !this.flags[ flag ] ) {
6648 changes[ flag ] = true;
6649 this.flags[ flag ] = true;
6650 add.push( className );
6651 }
6652 }
6653 } else if ( OO.isPlainObject( flags ) ) {
6654 for ( flag in flags ) {
6655 className = classPrefix + flag;
6656 if ( flags[ flag ] ) {
6657 // Set
6658 if ( !this.flags[ flag ] ) {
6659 changes[ flag ] = true;
6660 this.flags[ flag ] = true;
6661 add.push( className );
6662 }
6663 } else {
6664 // Remove
6665 if ( this.flags[ flag ] ) {
6666 changes[ flag ] = false;
6667 delete this.flags[ flag ];
6668 remove.push( className );
6669 }
6670 }
6671 }
6672 }
6673
6674 if ( this.$flagged ) {
6675 this.$flagged
6676 .addClass( add.join( ' ' ) )
6677 .removeClass( remove.join( ' ' ) );
6678 }
6679
6680 this.updateThemeClasses();
6681 this.emit( 'flag', changes );
6682
6683 return this;
6684 };
6685
6686 /**
6687 * TitledElement is mixed into other classes to provide a `title` attribute.
6688 * Titles are rendered by the browser and are made visible when the user moves
6689 * the mouse over the element. Titles are not visible on touch devices.
6690 *
6691 * @example
6692 * // TitledElement provides a 'title' attribute to the
6693 * // ButtonWidget class
6694 * var button = new OO.ui.ButtonWidget( {
6695 * label: 'Button with Title',
6696 * title: 'I am a button'
6697 * } );
6698 * $( 'body' ).append( button.$element );
6699 *
6700 * @abstract
6701 * @class
6702 *
6703 * @constructor
6704 * @param {Object} [config] Configuration options
6705 * @cfg {jQuery} [$titled] The element to which the `title` attribute is applied.
6706 * If this config is omitted, the title functionality is applied to $element, the
6707 * element created by the class.
6708 * @cfg {string|Function} [title] The title text or a function that returns text. If
6709 * this config is omitted, the value of the {@link #static-title static title} property is used.
6710 */
6711 OO.ui.mixin.TitledElement = function OoUiMixinTitledElement( config ) {
6712 // Configuration initialization
6713 config = config || {};
6714
6715 // Properties
6716 this.$titled = null;
6717 this.title = null;
6718
6719 // Initialization
6720 this.setTitle( config.title || this.constructor.static.title );
6721 this.setTitledElement( config.$titled || this.$element );
6722 };
6723
6724 /* Setup */
6725
6726 OO.initClass( OO.ui.mixin.TitledElement );
6727
6728 /* Static Properties */
6729
6730 /**
6731 * The title text, a function that returns text, or `null` for no title. The value of the static property
6732 * is overridden if the #title config option is used.
6733 *
6734 * @static
6735 * @inheritable
6736 * @property {string|Function|null}
6737 */
6738 OO.ui.mixin.TitledElement.static.title = null;
6739
6740 /* Methods */
6741
6742 /**
6743 * Set the titled element.
6744 *
6745 * This method is used to retarget a titledElement mixin so that its functionality applies to the specified element.
6746 * If an element is already set, the mixin’s effect on that element is removed before the new element is set up.
6747 *
6748 * @param {jQuery} $titled Element that should use the 'titled' functionality
6749 */
6750 OO.ui.mixin.TitledElement.prototype.setTitledElement = function ( $titled ) {
6751 if ( this.$titled ) {
6752 this.$titled.removeAttr( 'title' );
6753 }
6754
6755 this.$titled = $titled;
6756 if ( this.title ) {
6757 this.$titled.attr( 'title', this.title );
6758 }
6759 };
6760
6761 /**
6762 * Set title.
6763 *
6764 * @param {string|Function|null} title Title text, a function that returns text, or `null` for no title
6765 * @chainable
6766 */
6767 OO.ui.mixin.TitledElement.prototype.setTitle = function ( title ) {
6768 title = typeof title === 'function' ? OO.ui.resolveMsg( title ) : title;
6769 title = ( typeof title === 'string' && title.length ) ? title : null;
6770
6771 if ( this.title !== title ) {
6772 if ( this.$titled ) {
6773 if ( title !== null ) {
6774 this.$titled.attr( 'title', title );
6775 } else {
6776 this.$titled.removeAttr( 'title' );
6777 }
6778 }
6779 this.title = title;
6780 }
6781
6782 return this;
6783 };
6784
6785 /**
6786 * Get title.
6787 *
6788 * @return {string} Title string
6789 */
6790 OO.ui.mixin.TitledElement.prototype.getTitle = function () {
6791 return this.title;
6792 };
6793
6794 /**
6795 * Element that can be automatically clipped to visible boundaries.
6796 *
6797 * Whenever the element's natural height changes, you have to call
6798 * {@link OO.ui.mixin.ClippableElement#clip} to make sure it's still
6799 * clipping correctly.
6800 *
6801 * The dimensions of #$clippableContainer will be compared to the boundaries of the
6802 * nearest scrollable container. If #$clippableContainer is too tall and/or too wide,
6803 * then #$clippable will be given a fixed reduced height and/or width and will be made
6804 * scrollable. By default, #$clippable and #$clippableContainer are the same element,
6805 * but you can build a static footer by setting #$clippableContainer to an element that contains
6806 * #$clippable and the footer.
6807 *
6808 * @abstract
6809 * @class
6810 *
6811 * @constructor
6812 * @param {Object} [config] Configuration options
6813 * @cfg {jQuery} [$clippable] Node to clip, assigned to #$clippable, omit to use #$element
6814 * @cfg {jQuery} [$clippableContainer] Node to keep visible, assigned to #$clippableContainer,
6815 * omit to use #$clippable
6816 */
6817 OO.ui.mixin.ClippableElement = function OoUiMixinClippableElement( config ) {
6818 // Configuration initialization
6819 config = config || {};
6820
6821 // Properties
6822 this.$clippable = null;
6823 this.$clippableContainer = null;
6824 this.clipping = false;
6825 this.clippedHorizontally = false;
6826 this.clippedVertically = false;
6827 this.$clippableScrollableContainer = null;
6828 this.$clippableScroller = null;
6829 this.$clippableWindow = null;
6830 this.idealWidth = null;
6831 this.idealHeight = null;
6832 this.onClippableScrollHandler = this.clip.bind( this );
6833 this.onClippableWindowResizeHandler = this.clip.bind( this );
6834
6835 // Initialization
6836 if ( config.$clippableContainer ) {
6837 this.setClippableContainer( config.$clippableContainer );
6838 }
6839 this.setClippableElement( config.$clippable || this.$element );
6840 };
6841
6842 /* Methods */
6843
6844 /**
6845 * Set clippable element.
6846 *
6847 * If an element is already set, it will be cleaned up before setting up the new element.
6848 *
6849 * @param {jQuery} $clippable Element to make clippable
6850 */
6851 OO.ui.mixin.ClippableElement.prototype.setClippableElement = function ( $clippable ) {
6852 if ( this.$clippable ) {
6853 this.$clippable.removeClass( 'oo-ui-clippableElement-clippable' );
6854 this.$clippable.css( { width: '', height: '', overflowX: '', overflowY: '' } );
6855 OO.ui.Element.static.reconsiderScrollbars( this.$clippable[ 0 ] );
6856 }
6857
6858 this.$clippable = $clippable.addClass( 'oo-ui-clippableElement-clippable' );
6859 this.clip();
6860 };
6861
6862 /**
6863 * Set clippable container.
6864 *
6865 * This is the container that will be measured when deciding whether to clip. When clipping,
6866 * #$clippable will be resized in order to keep the clippable container fully visible.
6867 *
6868 * If the clippable container is unset, #$clippable will be used.
6869 *
6870 * @param {jQuery|null} $clippableContainer Container to keep visible, or null to unset
6871 */
6872 OO.ui.mixin.ClippableElement.prototype.setClippableContainer = function ( $clippableContainer ) {
6873 this.$clippableContainer = $clippableContainer;
6874 if ( this.$clippable ) {
6875 this.clip();
6876 }
6877 };
6878
6879 /**
6880 * Toggle clipping.
6881 *
6882 * Do not turn clipping on until after the element is attached to the DOM and visible.
6883 *
6884 * @param {boolean} [clipping] Enable clipping, omit to toggle
6885 * @chainable
6886 */
6887 OO.ui.mixin.ClippableElement.prototype.toggleClipping = function ( clipping ) {
6888 clipping = clipping === undefined ? !this.clipping : !!clipping;
6889
6890 if ( this.clipping !== clipping ) {
6891 this.clipping = clipping;
6892 if ( clipping ) {
6893 this.$clippableScrollableContainer = $( this.getClosestScrollableElementContainer() );
6894 // If the clippable container is the root, we have to listen to scroll events and check
6895 // jQuery.scrollTop on the window because of browser inconsistencies
6896 this.$clippableScroller = this.$clippableScrollableContainer.is( 'html, body' ) ?
6897 $( OO.ui.Element.static.getWindow( this.$clippableScrollableContainer ) ) :
6898 this.$clippableScrollableContainer;
6899 this.$clippableScroller.on( 'scroll', this.onClippableScrollHandler );
6900 this.$clippableWindow = $( this.getElementWindow() )
6901 .on( 'resize', this.onClippableWindowResizeHandler );
6902 // Initial clip after visible
6903 this.clip();
6904 } else {
6905 this.$clippable.css( { width: '', height: '', overflowX: '', overflowY: '' } );
6906 OO.ui.Element.static.reconsiderScrollbars( this.$clippable[ 0 ] );
6907
6908 this.$clippableScrollableContainer = null;
6909 this.$clippableScroller.off( 'scroll', this.onClippableScrollHandler );
6910 this.$clippableScroller = null;
6911 this.$clippableWindow.off( 'resize', this.onClippableWindowResizeHandler );
6912 this.$clippableWindow = null;
6913 }
6914 }
6915
6916 return this;
6917 };
6918
6919 /**
6920 * Check if the element will be clipped to fit the visible area of the nearest scrollable container.
6921 *
6922 * @return {boolean} Element will be clipped to the visible area
6923 */
6924 OO.ui.mixin.ClippableElement.prototype.isClipping = function () {
6925 return this.clipping;
6926 };
6927
6928 /**
6929 * Check if the bottom or right of the element is being clipped by the nearest scrollable container.
6930 *
6931 * @return {boolean} Part of the element is being clipped
6932 */
6933 OO.ui.mixin.ClippableElement.prototype.isClipped = function () {
6934 return this.clippedHorizontally || this.clippedVertically;
6935 };
6936
6937 /**
6938 * Check if the right of the element is being clipped by the nearest scrollable container.
6939 *
6940 * @return {boolean} Part of the element is being clipped
6941 */
6942 OO.ui.mixin.ClippableElement.prototype.isClippedHorizontally = function () {
6943 return this.clippedHorizontally;
6944 };
6945
6946 /**
6947 * Check if the bottom of the element is being clipped by the nearest scrollable container.
6948 *
6949 * @return {boolean} Part of the element is being clipped
6950 */
6951 OO.ui.mixin.ClippableElement.prototype.isClippedVertically = function () {
6952 return this.clippedVertically;
6953 };
6954
6955 /**
6956 * Set the ideal size. These are the dimensions the element will have when it's not being clipped.
6957 *
6958 * @param {number|string} [width] Width as a number of pixels or CSS string with unit suffix
6959 * @param {number|string} [height] Height as a number of pixels or CSS string with unit suffix
6960 */
6961 OO.ui.mixin.ClippableElement.prototype.setIdealSize = function ( width, height ) {
6962 this.idealWidth = width;
6963 this.idealHeight = height;
6964
6965 if ( !this.clipping ) {
6966 // Update dimensions
6967 this.$clippable.css( { width: width, height: height } );
6968 }
6969 // While clipping, idealWidth and idealHeight are not considered
6970 };
6971
6972 /**
6973 * Clip element to visible boundaries and allow scrolling when needed. Call this method when
6974 * the element's natural height changes.
6975 *
6976 * Element will be clipped the bottom or right of the element is within 10px of the edge of, or
6977 * overlapped by, the visible area of the nearest scrollable container.
6978 *
6979 * @chainable
6980 */
6981 OO.ui.mixin.ClippableElement.prototype.clip = function () {
6982 var $container, extraHeight, extraWidth, ccOffset,
6983 $scrollableContainer, scOffset, scHeight, scWidth,
6984 ccWidth, scrollerIsWindow, scrollTop, scrollLeft,
6985 desiredWidth, desiredHeight, allotedWidth, allotedHeight,
6986 naturalWidth, naturalHeight, clipWidth, clipHeight,
6987 buffer = 7; // Chosen by fair dice roll
6988
6989 if ( !this.clipping ) {
6990 // this.$clippableScrollableContainer and this.$clippableWindow are null, so the below will fail
6991 return this;
6992 }
6993
6994 $container = this.$clippableContainer || this.$clippable;
6995 extraHeight = $container.outerHeight() - this.$clippable.outerHeight();
6996 extraWidth = $container.outerWidth() - this.$clippable.outerWidth();
6997 ccOffset = $container.offset();
6998 $scrollableContainer = this.$clippableScrollableContainer.is( 'html, body' ) ?
6999 this.$clippableWindow : this.$clippableScrollableContainer;
7000 scOffset = $scrollableContainer.offset() || { top: 0, left: 0 };
7001 scHeight = $scrollableContainer.innerHeight() - buffer;
7002 scWidth = $scrollableContainer.innerWidth() - buffer;
7003 ccWidth = $container.outerWidth() + buffer;
7004 scrollerIsWindow = this.$clippableScroller[ 0 ] === this.$clippableWindow[ 0 ];
7005 scrollTop = scrollerIsWindow ? this.$clippableScroller.scrollTop() : 0;
7006 scrollLeft = scrollerIsWindow ? this.$clippableScroller.scrollLeft() : 0;
7007 desiredWidth = ccOffset.left < 0 ?
7008 ccWidth + ccOffset.left :
7009 ( scOffset.left + scrollLeft + scWidth ) - ccOffset.left;
7010 desiredHeight = ( scOffset.top + scrollTop + scHeight ) - ccOffset.top;
7011 allotedWidth = desiredWidth - extraWidth;
7012 allotedHeight = desiredHeight - extraHeight;
7013 naturalWidth = this.$clippable.prop( 'scrollWidth' );
7014 naturalHeight = this.$clippable.prop( 'scrollHeight' );
7015 clipWidth = allotedWidth < naturalWidth;
7016 clipHeight = allotedHeight < naturalHeight;
7017
7018 if ( clipWidth ) {
7019 this.$clippable.css( { overflowX: 'scroll', width: Math.max( 0, allotedWidth ) } );
7020 } else {
7021 this.$clippable.css( { width: this.idealWidth ? this.idealWidth - extraWidth : '', overflowX: '' } );
7022 }
7023 if ( clipHeight ) {
7024 this.$clippable.css( { overflowY: 'scroll', height: Math.max( 0, allotedHeight ) } );
7025 } else {
7026 this.$clippable.css( { height: this.idealHeight ? this.idealHeight - extraHeight : '', overflowY: '' } );
7027 }
7028
7029 // If we stopped clipping in at least one of the dimensions
7030 if ( ( this.clippedHorizontally && !clipWidth ) || ( this.clippedVertically && !clipHeight ) ) {
7031 OO.ui.Element.static.reconsiderScrollbars( this.$clippable[ 0 ] );
7032 }
7033
7034 this.clippedHorizontally = clipWidth;
7035 this.clippedVertically = clipHeight;
7036
7037 return this;
7038 };
7039
7040 /**
7041 * Element that will stick under a specified container, even when it is inserted elsewhere in the
7042 * document (for example, in a OO.ui.Window's $overlay).
7043 *
7044 * The elements's position is automatically calculated and maintained when window is resized or the
7045 * page is scrolled. If you reposition the container manually, you have to call #position to make
7046 * sure the element is still placed correctly.
7047 *
7048 * As positioning is only possible when both the element and the container are attached to the DOM
7049 * and visible, it's only done after you call #togglePositioning. You might want to do this inside
7050 * the #toggle method to display a floating popup, for example.
7051 *
7052 * @abstract
7053 * @class
7054 *
7055 * @constructor
7056 * @param {Object} [config] Configuration options
7057 * @cfg {jQuery} [$floatable] Node to position, assigned to #$floatable, omit to use #$element
7058 * @cfg {jQuery} [$floatableContainer] Node to position below
7059 */
7060 OO.ui.mixin.FloatableElement = function OoUiMixinFloatableElement( config ) {
7061 // Configuration initialization
7062 config = config || {};
7063
7064 // Properties
7065 this.$floatable = null;
7066 this.$floatableContainer = null;
7067 this.$floatableWindow = null;
7068 this.$floatableClosestScrollable = null;
7069 this.onFloatableScrollHandler = this.position.bind( this );
7070 this.onFloatableWindowResizeHandler = this.position.bind( this );
7071
7072 // Initialization
7073 this.setFloatableContainer( config.$floatableContainer );
7074 this.setFloatableElement( config.$floatable || this.$element );
7075 };
7076
7077 /* Methods */
7078
7079 /**
7080 * Set floatable element.
7081 *
7082 * If an element is already set, it will be cleaned up before setting up the new element.
7083 *
7084 * @param {jQuery} $floatable Element to make floatable
7085 */
7086 OO.ui.mixin.FloatableElement.prototype.setFloatableElement = function ( $floatable ) {
7087 if ( this.$floatable ) {
7088 this.$floatable.removeClass( 'oo-ui-floatableElement-floatable' );
7089 this.$floatable.css( { left: '', top: '' } );
7090 }
7091
7092 this.$floatable = $floatable.addClass( 'oo-ui-floatableElement-floatable' );
7093 this.position();
7094 };
7095
7096 /**
7097 * Set floatable container.
7098 *
7099 * The element will be always positioned under the specified container.
7100 *
7101 * @param {jQuery|null} $floatableContainer Container to keep visible, or null to unset
7102 */
7103 OO.ui.mixin.FloatableElement.prototype.setFloatableContainer = function ( $floatableContainer ) {
7104 this.$floatableContainer = $floatableContainer;
7105 if ( this.$floatable ) {
7106 this.position();
7107 }
7108 };
7109
7110 /**
7111 * Toggle positioning.
7112 *
7113 * Do not turn positioning on until after the element is attached to the DOM and visible.
7114 *
7115 * @param {boolean} [positioning] Enable positioning, omit to toggle
7116 * @chainable
7117 */
7118 OO.ui.mixin.FloatableElement.prototype.togglePositioning = function ( positioning ) {
7119 var closestScrollableOfContainer, closestScrollableOfFloatable;
7120
7121 positioning = positioning === undefined ? !this.positioning : !!positioning;
7122
7123 if ( this.positioning !== positioning ) {
7124 this.positioning = positioning;
7125
7126 closestScrollableOfContainer = OO.ui.Element.static.getClosestScrollableContainer( this.$floatableContainer[ 0 ] );
7127 closestScrollableOfFloatable = OO.ui.Element.static.getClosestScrollableContainer( this.$floatable[ 0 ] );
7128 if ( closestScrollableOfContainer !== closestScrollableOfFloatable ) {
7129 // If the scrollable is the root, we have to listen to scroll events
7130 // on the window because of browser inconsistencies (or do we? someone should verify this)
7131 if ( $( closestScrollableOfContainer ).is( 'html, body' ) ) {
7132 closestScrollableOfContainer = OO.ui.Element.static.getWindow( closestScrollableOfContainer );
7133 }
7134 }
7135
7136 if ( positioning ) {
7137 this.$floatableWindow = $( this.getElementWindow() );
7138 this.$floatableWindow.on( 'resize', this.onFloatableWindowResizeHandler );
7139
7140 if ( closestScrollableOfContainer !== closestScrollableOfFloatable ) {
7141 this.$floatableClosestScrollable = $( closestScrollableOfContainer );
7142 this.$floatableClosestScrollable.on( 'scroll', this.onFloatableScrollHandler );
7143 }
7144
7145 // Initial position after visible
7146 this.position();
7147 } else {
7148 if ( this.$floatableWindow ) {
7149 this.$floatableWindow.off( 'resize', this.onFloatableWindowResizeHandler );
7150 this.$floatableWindow = null;
7151 }
7152
7153 if ( this.$floatableClosestScrollable ) {
7154 this.$floatableClosestScrollable.off( 'scroll', this.onFloatableScrollHandler );
7155 this.$floatableClosestScrollable = null;
7156 }
7157
7158 this.$floatable.css( { left: '', top: '' } );
7159 }
7160 }
7161
7162 return this;
7163 };
7164
7165 /**
7166 * Position the floatable below its container.
7167 *
7168 * This should only be done when both of them are attached to the DOM and visible.
7169 *
7170 * @chainable
7171 */
7172 OO.ui.mixin.FloatableElement.prototype.position = function () {
7173 var pos;
7174
7175 if ( !this.positioning ) {
7176 return this;
7177 }
7178
7179 pos = OO.ui.Element.static.getRelativePosition( this.$floatableContainer, this.$floatable.offsetParent() );
7180
7181 // Position under container
7182 pos.top += this.$floatableContainer.height();
7183 this.$floatable.css( pos );
7184
7185 // We updated the position, so re-evaluate the clipping state.
7186 // (ClippableElement does not listen to 'scroll' events on $floatableContainer's parent, and so
7187 // will not notice the need to update itself.)
7188 // TODO: This is terrible, we shouldn't need to know about ClippableElement at all here. Why does
7189 // it not listen to the right events in the right places?
7190 if ( this.clip ) {
7191 this.clip();
7192 }
7193
7194 return this;
7195 };
7196
7197 /**
7198 * AccessKeyedElement is mixed into other classes to provide an `accesskey` attribute.
7199 * Accesskeys allow an user to go to a specific element by using
7200 * a shortcut combination of a browser specific keys + the key
7201 * set to the field.
7202 *
7203 * @example
7204 * // AccessKeyedElement provides an 'accesskey' attribute to the
7205 * // ButtonWidget class
7206 * var button = new OO.ui.ButtonWidget( {
7207 * label: 'Button with Accesskey',
7208 * accessKey: 'k'
7209 * } );
7210 * $( 'body' ).append( button.$element );
7211 *
7212 * @abstract
7213 * @class
7214 *
7215 * @constructor
7216 * @param {Object} [config] Configuration options
7217 * @cfg {jQuery} [$accessKeyed] The element to which the `accesskey` attribute is applied.
7218 * If this config is omitted, the accesskey functionality is applied to $element, the
7219 * element created by the class.
7220 * @cfg {string|Function} [accessKey] The key or a function that returns the key. If
7221 * this config is omitted, no accesskey will be added.
7222 */
7223 OO.ui.mixin.AccessKeyedElement = function OoUiMixinAccessKeyedElement( config ) {
7224 // Configuration initialization
7225 config = config || {};
7226
7227 // Properties
7228 this.$accessKeyed = null;
7229 this.accessKey = null;
7230
7231 // Initialization
7232 this.setAccessKey( config.accessKey || null );
7233 this.setAccessKeyedElement( config.$accessKeyed || this.$element );
7234 };
7235
7236 /* Setup */
7237
7238 OO.initClass( OO.ui.mixin.AccessKeyedElement );
7239
7240 /* Static Properties */
7241
7242 /**
7243 * The access key, a function that returns a key, or `null` for no accesskey.
7244 *
7245 * @static
7246 * @inheritable
7247 * @property {string|Function|null}
7248 */
7249 OO.ui.mixin.AccessKeyedElement.static.accessKey = null;
7250
7251 /* Methods */
7252
7253 /**
7254 * Set the accesskeyed element.
7255 *
7256 * This method is used to retarget a AccessKeyedElement mixin so that its functionality applies to the specified element.
7257 * If an element is already set, the mixin's effect on that element is removed before the new element is set up.
7258 *
7259 * @param {jQuery} $accessKeyed Element that should use the 'accesskeyes' functionality
7260 */
7261 OO.ui.mixin.AccessKeyedElement.prototype.setAccessKeyedElement = function ( $accessKeyed ) {
7262 if ( this.$accessKeyed ) {
7263 this.$accessKeyed.removeAttr( 'accesskey' );
7264 }
7265
7266 this.$accessKeyed = $accessKeyed;
7267 if ( this.accessKey ) {
7268 this.$accessKeyed.attr( 'accesskey', this.accessKey );
7269 }
7270 };
7271
7272 /**
7273 * Set accesskey.
7274 *
7275 * @param {string|Function|null} accesskey Key, a function that returns a key, or `null` for no accesskey
7276 * @chainable
7277 */
7278 OO.ui.mixin.AccessKeyedElement.prototype.setAccessKey = function ( accessKey ) {
7279 accessKey = typeof accessKey === 'string' ? OO.ui.resolveMsg( accessKey ) : null;
7280
7281 if ( this.accessKey !== accessKey ) {
7282 if ( this.$accessKeyed ) {
7283 if ( accessKey !== null ) {
7284 this.$accessKeyed.attr( 'accesskey', accessKey );
7285 } else {
7286 this.$accessKeyed.removeAttr( 'accesskey' );
7287 }
7288 }
7289 this.accessKey = accessKey;
7290 }
7291
7292 return this;
7293 };
7294
7295 /**
7296 * Get accesskey.
7297 *
7298 * @return {string} accessKey string
7299 */
7300 OO.ui.mixin.AccessKeyedElement.prototype.getAccessKey = function () {
7301 return this.accessKey;
7302 };
7303
7304 /**
7305 * Tools, together with {@link OO.ui.ToolGroup toolgroups}, constitute {@link OO.ui.Toolbar toolbars}.
7306 * Each tool is configured with a static name, title, and icon and is customized with the command to carry
7307 * out when the tool is selected. Tools must also be registered with a {@link OO.ui.ToolFactory tool factory},
7308 * which creates the tools on demand.
7309 *
7310 * Every Tool subclass must implement two methods:
7311 *
7312 * - {@link #onUpdateState}
7313 * - {@link #onSelect}
7314 *
7315 * Tools are added to toolgroups ({@link OO.ui.ListToolGroup ListToolGroup},
7316 * {@link OO.ui.BarToolGroup BarToolGroup}, or {@link OO.ui.MenuToolGroup MenuToolGroup}), which determine how
7317 * the tool is displayed in the toolbar. See {@link OO.ui.Toolbar toolbars} for an example.
7318 *
7319 * For more information, please see the [OOjs UI documentation on MediaWiki][1].
7320 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
7321 *
7322 * @abstract
7323 * @class
7324 * @extends OO.ui.Widget
7325 * @mixins OO.ui.mixin.IconElement
7326 * @mixins OO.ui.mixin.FlaggedElement
7327 * @mixins OO.ui.mixin.TabIndexedElement
7328 *
7329 * @constructor
7330 * @param {OO.ui.ToolGroup} toolGroup
7331 * @param {Object} [config] Configuration options
7332 * @cfg {string|Function} [title] Title text or a function that returns text. If this config is omitted, the value of
7333 * the {@link #static-title static title} property is used.
7334 *
7335 * The title is used in different ways depending on the type of toolgroup that contains the tool. The
7336 * 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
7337 * part of a {@link OO.ui.ListToolGroup list} or {@link OO.ui.MenuToolGroup menu} toolgroup.
7338 *
7339 * For bar toolgroups, a description of the accelerator key is appended to the title if an accelerator key
7340 * is associated with an action by the same name as the tool and accelerator functionality has been added to the application.
7341 * To add accelerator key functionality, you must subclass OO.ui.Toolbar and override the {@link OO.ui.Toolbar#getToolAccelerator getToolAccelerator} method.
7342 */
7343 OO.ui.Tool = function OoUiTool( toolGroup, config ) {
7344 // Allow passing positional parameters inside the config object
7345 if ( OO.isPlainObject( toolGroup ) && config === undefined ) {
7346 config = toolGroup;
7347 toolGroup = config.toolGroup;
7348 }
7349
7350 // Configuration initialization
7351 config = config || {};
7352
7353 // Parent constructor
7354 OO.ui.Tool.parent.call( this, config );
7355
7356 // Properties
7357 this.toolGroup = toolGroup;
7358 this.toolbar = this.toolGroup.getToolbar();
7359 this.active = false;
7360 this.$title = $( '<span>' );
7361 this.$accel = $( '<span>' );
7362 this.$link = $( '<a>' );
7363 this.title = null;
7364
7365 // Mixin constructors
7366 OO.ui.mixin.IconElement.call( this, config );
7367 OO.ui.mixin.FlaggedElement.call( this, config );
7368 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$link } ) );
7369
7370 // Events
7371 this.toolbar.connect( this, { updateState: 'onUpdateState' } );
7372
7373 // Initialization
7374 this.$title.addClass( 'oo-ui-tool-title' );
7375 this.$accel
7376 .addClass( 'oo-ui-tool-accel' )
7377 .prop( {
7378 // This may need to be changed if the key names are ever localized,
7379 // but for now they are essentially written in English
7380 dir: 'ltr',
7381 lang: 'en'
7382 } );
7383 this.$link
7384 .addClass( 'oo-ui-tool-link' )
7385 .append( this.$icon, this.$title, this.$accel )
7386 .attr( 'role', 'button' );
7387 this.$element
7388 .data( 'oo-ui-tool', this )
7389 .addClass(
7390 'oo-ui-tool ' + 'oo-ui-tool-name-' +
7391 this.constructor.static.name.replace( /^([^\/]+)\/([^\/]+).*$/, '$1-$2' )
7392 )
7393 .toggleClass( 'oo-ui-tool-with-label', this.constructor.static.displayBothIconAndLabel )
7394 .append( this.$link );
7395 this.setTitle( config.title || this.constructor.static.title );
7396 };
7397
7398 /* Setup */
7399
7400 OO.inheritClass( OO.ui.Tool, OO.ui.Widget );
7401 OO.mixinClass( OO.ui.Tool, OO.ui.mixin.IconElement );
7402 OO.mixinClass( OO.ui.Tool, OO.ui.mixin.FlaggedElement );
7403 OO.mixinClass( OO.ui.Tool, OO.ui.mixin.TabIndexedElement );
7404
7405 /* Static Properties */
7406
7407 /**
7408 * @static
7409 * @inheritdoc
7410 */
7411 OO.ui.Tool.static.tagName = 'span';
7412
7413 /**
7414 * Symbolic name of tool.
7415 *
7416 * The symbolic name is used internally to register the tool with a {@link OO.ui.ToolFactory ToolFactory}. It can
7417 * also be used when adding tools to toolgroups.
7418 *
7419 * @abstract
7420 * @static
7421 * @inheritable
7422 * @property {string}
7423 */
7424 OO.ui.Tool.static.name = '';
7425
7426 /**
7427 * Symbolic name of the group.
7428 *
7429 * The group name is used to associate tools with each other so that they can be selected later by
7430 * a {@link OO.ui.ToolGroup toolgroup}.
7431 *
7432 * @abstract
7433 * @static
7434 * @inheritable
7435 * @property {string}
7436 */
7437 OO.ui.Tool.static.group = '';
7438
7439 /**
7440 * 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.
7441 *
7442 * @abstract
7443 * @static
7444 * @inheritable
7445 * @property {string|Function}
7446 */
7447 OO.ui.Tool.static.title = '';
7448
7449 /**
7450 * Display both icon and label when the tool is used in a {@link OO.ui.BarToolGroup bar} toolgroup.
7451 * Normally only the icon is displayed, or only the label if no icon is given.
7452 *
7453 * @static
7454 * @inheritable
7455 * @property {boolean}
7456 */
7457 OO.ui.Tool.static.displayBothIconAndLabel = false;
7458
7459 /**
7460 * Add tool to catch-all groups automatically.
7461 *
7462 * A catch-all group, which contains all tools that do not currently belong to a toolgroup,
7463 * can be included in a toolgroup using the wildcard selector, an asterisk (*).
7464 *
7465 * @static
7466 * @inheritable
7467 * @property {boolean}
7468 */
7469 OO.ui.Tool.static.autoAddToCatchall = true;
7470
7471 /**
7472 * Add tool to named groups automatically.
7473 *
7474 * By default, tools that are configured with a static ‘group’ property are added
7475 * to that group and will be selected when the symbolic name of the group is specified (e.g., when
7476 * toolgroups include tools by group name).
7477 *
7478 * @static
7479 * @property {boolean}
7480 * @inheritable
7481 */
7482 OO.ui.Tool.static.autoAddToGroup = true;
7483
7484 /**
7485 * Check if this tool is compatible with given data.
7486 *
7487 * This is a stub that can be overridden to provide support for filtering tools based on an
7488 * arbitrary piece of information (e.g., where the cursor is in a document). The implementation
7489 * must also call this method so that the compatibility check can be performed.
7490 *
7491 * @static
7492 * @inheritable
7493 * @param {Mixed} data Data to check
7494 * @return {boolean} Tool can be used with data
7495 */
7496 OO.ui.Tool.static.isCompatibleWith = function () {
7497 return false;
7498 };
7499
7500 /* Methods */
7501
7502 /**
7503 * Handle the toolbar state being updated. This method is called when the
7504 * {@link OO.ui.Toolbar#event-updateState 'updateState' event} is emitted on the
7505 * {@link OO.ui.Toolbar Toolbar} that uses this tool, and should set the state of this tool
7506 * depending on application state (usually by calling #setDisabled to enable or disable the tool,
7507 * or #setActive to mark is as currently in-use or not).
7508 *
7509 * This is an abstract method that must be overridden in a concrete subclass.
7510 *
7511 * @method
7512 * @protected
7513 * @abstract
7514 */
7515 OO.ui.Tool.prototype.onUpdateState = null;
7516
7517 /**
7518 * Handle the tool being selected. This method is called when the user triggers this tool,
7519 * usually by clicking on its label/icon.
7520 *
7521 * This is an abstract method that must be overridden in a concrete subclass.
7522 *
7523 * @method
7524 * @protected
7525 * @abstract
7526 */
7527 OO.ui.Tool.prototype.onSelect = null;
7528
7529 /**
7530 * Check if the tool is active.
7531 *
7532 * Tools become active when their #onSelect or #onUpdateState handlers change them to appear pressed
7533 * with the #setActive method. Additional CSS is applied to the tool to reflect the active state.
7534 *
7535 * @return {boolean} Tool is active
7536 */
7537 OO.ui.Tool.prototype.isActive = function () {
7538 return this.active;
7539 };
7540
7541 /**
7542 * Make the tool appear active or inactive.
7543 *
7544 * This method should be called within #onSelect or #onUpdateState event handlers to make the tool
7545 * appear pressed or not.
7546 *
7547 * @param {boolean} state Make tool appear active
7548 */
7549 OO.ui.Tool.prototype.setActive = function ( state ) {
7550 this.active = !!state;
7551 if ( this.active ) {
7552 this.$element.addClass( 'oo-ui-tool-active' );
7553 } else {
7554 this.$element.removeClass( 'oo-ui-tool-active' );
7555 }
7556 };
7557
7558 /**
7559 * Set the tool #title.
7560 *
7561 * @param {string|Function} title Title text or a function that returns text
7562 * @chainable
7563 */
7564 OO.ui.Tool.prototype.setTitle = function ( title ) {
7565 this.title = OO.ui.resolveMsg( title );
7566 this.updateTitle();
7567 return this;
7568 };
7569
7570 /**
7571 * Get the tool #title.
7572 *
7573 * @return {string} Title text
7574 */
7575 OO.ui.Tool.prototype.getTitle = function () {
7576 return this.title;
7577 };
7578
7579 /**
7580 * Get the tool's symbolic name.
7581 *
7582 * @return {string} Symbolic name of tool
7583 */
7584 OO.ui.Tool.prototype.getName = function () {
7585 return this.constructor.static.name;
7586 };
7587
7588 /**
7589 * Update the title.
7590 */
7591 OO.ui.Tool.prototype.updateTitle = function () {
7592 var titleTooltips = this.toolGroup.constructor.static.titleTooltips,
7593 accelTooltips = this.toolGroup.constructor.static.accelTooltips,
7594 accel = this.toolbar.getToolAccelerator( this.constructor.static.name ),
7595 tooltipParts = [];
7596
7597 this.$title.text( this.title );
7598 this.$accel.text( accel );
7599
7600 if ( titleTooltips && typeof this.title === 'string' && this.title.length ) {
7601 tooltipParts.push( this.title );
7602 }
7603 if ( accelTooltips && typeof accel === 'string' && accel.length ) {
7604 tooltipParts.push( accel );
7605 }
7606 if ( tooltipParts.length ) {
7607 this.$link.attr( 'title', tooltipParts.join( ' ' ) );
7608 } else {
7609 this.$link.removeAttr( 'title' );
7610 }
7611 };
7612
7613 /**
7614 * Destroy tool.
7615 *
7616 * Destroying the tool removes all event handlers and the tool’s DOM elements.
7617 * Call this method whenever you are done using a tool.
7618 */
7619 OO.ui.Tool.prototype.destroy = function () {
7620 this.toolbar.disconnect( this );
7621 this.$element.remove();
7622 };
7623
7624 /**
7625 * Toolbars are complex interface components that permit users to easily access a variety
7626 * of {@link OO.ui.Tool tools} (e.g., formatting commands) and actions, which are additional commands that are
7627 * part of the toolbar, but not configured as tools.
7628 *
7629 * Individual tools are customized and then registered with a {@link OO.ui.ToolFactory tool factory}, which creates
7630 * the tools on demand. Each tool has a symbolic name (used when registering the tool), a title (e.g., ‘Insert
7631 * image’), and an icon.
7632 *
7633 * Individual tools are organized in {@link OO.ui.ToolGroup toolgroups}, which can be {@link OO.ui.MenuToolGroup menus}
7634 * of tools, {@link OO.ui.ListToolGroup lists} of tools, or a single {@link OO.ui.BarToolGroup bar} of tools.
7635 * The arrangement and order of the toolgroups is customized when the toolbar is set up. Tools can be presented in
7636 * any order, but each can only appear once in the toolbar.
7637 *
7638 * The toolbar can be synchronized with the state of the external "application", like a text
7639 * editor's editing area, marking tools as active/inactive (e.g. a 'bold' tool would be shown as
7640 * active when the text cursor was inside bolded text) or enabled/disabled (e.g. a table caption
7641 * tool would be disabled while the user is not editing a table). A state change is signalled by
7642 * emitting the {@link #event-updateState 'updateState' event}, which calls Tools'
7643 * {@link OO.ui.Tool#onUpdateState onUpdateState method}.
7644 *
7645 * The following is an example of a basic toolbar.
7646 *
7647 * @example
7648 * // Example of a toolbar
7649 * // Create the toolbar
7650 * var toolFactory = new OO.ui.ToolFactory();
7651 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
7652 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
7653 *
7654 * // We will be placing status text in this element when tools are used
7655 * var $area = $( '<p>' ).text( 'Toolbar example' );
7656 *
7657 * // Define the tools that we're going to place in our toolbar
7658 *
7659 * // Create a class inheriting from OO.ui.Tool
7660 * function SearchTool() {
7661 * SearchTool.parent.apply( this, arguments );
7662 * }
7663 * OO.inheritClass( SearchTool, OO.ui.Tool );
7664 * // Each tool must have a 'name' (used as an internal identifier, see later) and at least one
7665 * // of 'icon' and 'title' (displayed icon and text).
7666 * SearchTool.static.name = 'search';
7667 * SearchTool.static.icon = 'search';
7668 * SearchTool.static.title = 'Search...';
7669 * // Defines the action that will happen when this tool is selected (clicked).
7670 * SearchTool.prototype.onSelect = function () {
7671 * $area.text( 'Search tool clicked!' );
7672 * // Never display this tool as "active" (selected).
7673 * this.setActive( false );
7674 * };
7675 * SearchTool.prototype.onUpdateState = function () {};
7676 * // Make this tool available in our toolFactory and thus our toolbar
7677 * toolFactory.register( SearchTool );
7678 *
7679 * // Register two more tools, nothing interesting here
7680 * function SettingsTool() {
7681 * SettingsTool.parent.apply( this, arguments );
7682 * }
7683 * OO.inheritClass( SettingsTool, OO.ui.Tool );
7684 * SettingsTool.static.name = 'settings';
7685 * SettingsTool.static.icon = 'settings';
7686 * SettingsTool.static.title = 'Change settings';
7687 * SettingsTool.prototype.onSelect = function () {
7688 * $area.text( 'Settings tool clicked!' );
7689 * this.setActive( false );
7690 * };
7691 * SettingsTool.prototype.onUpdateState = function () {};
7692 * toolFactory.register( SettingsTool );
7693 *
7694 * // Register two more tools, nothing interesting here
7695 * function StuffTool() {
7696 * StuffTool.parent.apply( this, arguments );
7697 * }
7698 * OO.inheritClass( StuffTool, OO.ui.Tool );
7699 * StuffTool.static.name = 'stuff';
7700 * StuffTool.static.icon = 'ellipsis';
7701 * StuffTool.static.title = 'More stuff';
7702 * StuffTool.prototype.onSelect = function () {
7703 * $area.text( 'More stuff tool clicked!' );
7704 * this.setActive( false );
7705 * };
7706 * StuffTool.prototype.onUpdateState = function () {};
7707 * toolFactory.register( StuffTool );
7708 *
7709 * // This is a PopupTool. Rather than having a custom 'onSelect' action, it will display a
7710 * // little popup window (a PopupWidget).
7711 * function HelpTool( toolGroup, config ) {
7712 * OO.ui.PopupTool.call( this, toolGroup, $.extend( { popup: {
7713 * padded: true,
7714 * label: 'Help',
7715 * head: true
7716 * } }, config ) );
7717 * this.popup.$body.append( '<p>I am helpful!</p>' );
7718 * }
7719 * OO.inheritClass( HelpTool, OO.ui.PopupTool );
7720 * HelpTool.static.name = 'help';
7721 * HelpTool.static.icon = 'help';
7722 * HelpTool.static.title = 'Help';
7723 * toolFactory.register( HelpTool );
7724 *
7725 * // Finally define which tools and in what order appear in the toolbar. Each tool may only be
7726 * // used once (but not all defined tools must be used).
7727 * toolbar.setup( [
7728 * {
7729 * // 'bar' tool groups display tools' icons only, side-by-side.
7730 * type: 'bar',
7731 * include: [ 'search', 'help' ]
7732 * },
7733 * {
7734 * // 'list' tool groups display both the titles and icons, in a dropdown list.
7735 * type: 'list',
7736 * indicator: 'down',
7737 * label: 'More',
7738 * include: [ 'settings', 'stuff' ]
7739 * }
7740 * // Note how the tools themselves are toolgroup-agnostic - the same tool can be displayed
7741 * // either in a 'list' or a 'bar'. There is a 'menu' tool group too, not showcased here,
7742 * // since it's more complicated to use. (See the next example snippet on this page.)
7743 * ] );
7744 *
7745 * // Create some UI around the toolbar and place it in the document
7746 * var frame = new OO.ui.PanelLayout( {
7747 * expanded: false,
7748 * framed: true
7749 * } );
7750 * var contentFrame = new OO.ui.PanelLayout( {
7751 * expanded: false,
7752 * padded: true
7753 * } );
7754 * frame.$element.append(
7755 * toolbar.$element,
7756 * contentFrame.$element.append( $area )
7757 * );
7758 * $( 'body' ).append( frame.$element );
7759 *
7760 * // Here is where the toolbar is actually built. This must be done after inserting it into the
7761 * // document.
7762 * toolbar.initialize();
7763 * toolbar.emit( 'updateState' );
7764 *
7765 * The following example extends the previous one to illustrate 'menu' toolgroups and the usage of
7766 * {@link #event-updateState 'updateState' event}.
7767 *
7768 * @example
7769 * // Create the toolbar
7770 * var toolFactory = new OO.ui.ToolFactory();
7771 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
7772 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
7773 *
7774 * // We will be placing status text in this element when tools are used
7775 * var $area = $( '<p>' ).text( 'Toolbar example' );
7776 *
7777 * // Define the tools that we're going to place in our toolbar
7778 *
7779 * // Create a class inheriting from OO.ui.Tool
7780 * function SearchTool() {
7781 * SearchTool.parent.apply( this, arguments );
7782 * }
7783 * OO.inheritClass( SearchTool, OO.ui.Tool );
7784 * // Each tool must have a 'name' (used as an internal identifier, see later) and at least one
7785 * // of 'icon' and 'title' (displayed icon and text).
7786 * SearchTool.static.name = 'search';
7787 * SearchTool.static.icon = 'search';
7788 * SearchTool.static.title = 'Search...';
7789 * // Defines the action that will happen when this tool is selected (clicked).
7790 * SearchTool.prototype.onSelect = function () {
7791 * $area.text( 'Search tool clicked!' );
7792 * // Never display this tool as "active" (selected).
7793 * this.setActive( false );
7794 * };
7795 * SearchTool.prototype.onUpdateState = function () {};
7796 * // Make this tool available in our toolFactory and thus our toolbar
7797 * toolFactory.register( SearchTool );
7798 *
7799 * // Register two more tools, nothing interesting here
7800 * function SettingsTool() {
7801 * SettingsTool.parent.apply( this, arguments );
7802 * this.reallyActive = false;
7803 * }
7804 * OO.inheritClass( SettingsTool, OO.ui.Tool );
7805 * SettingsTool.static.name = 'settings';
7806 * SettingsTool.static.icon = 'settings';
7807 * SettingsTool.static.title = 'Change settings';
7808 * SettingsTool.prototype.onSelect = function () {
7809 * $area.text( 'Settings tool clicked!' );
7810 * // Toggle the active state on each click
7811 * this.reallyActive = !this.reallyActive;
7812 * this.setActive( this.reallyActive );
7813 * // To update the menu label
7814 * this.toolbar.emit( 'updateState' );
7815 * };
7816 * SettingsTool.prototype.onUpdateState = function () {};
7817 * toolFactory.register( SettingsTool );
7818 *
7819 * // Register two more tools, nothing interesting here
7820 * function StuffTool() {
7821 * StuffTool.parent.apply( this, arguments );
7822 * this.reallyActive = false;
7823 * }
7824 * OO.inheritClass( StuffTool, OO.ui.Tool );
7825 * StuffTool.static.name = 'stuff';
7826 * StuffTool.static.icon = 'ellipsis';
7827 * StuffTool.static.title = 'More stuff';
7828 * StuffTool.prototype.onSelect = function () {
7829 * $area.text( 'More stuff tool clicked!' );
7830 * // Toggle the active state on each click
7831 * this.reallyActive = !this.reallyActive;
7832 * this.setActive( this.reallyActive );
7833 * // To update the menu label
7834 * this.toolbar.emit( 'updateState' );
7835 * };
7836 * StuffTool.prototype.onUpdateState = function () {};
7837 * toolFactory.register( StuffTool );
7838 *
7839 * // This is a PopupTool. Rather than having a custom 'onSelect' action, it will display a
7840 * // little popup window (a PopupWidget). 'onUpdateState' is also already implemented.
7841 * function HelpTool( toolGroup, config ) {
7842 * OO.ui.PopupTool.call( this, toolGroup, $.extend( { popup: {
7843 * padded: true,
7844 * label: 'Help',
7845 * head: true
7846 * } }, config ) );
7847 * this.popup.$body.append( '<p>I am helpful!</p>' );
7848 * }
7849 * OO.inheritClass( HelpTool, OO.ui.PopupTool );
7850 * HelpTool.static.name = 'help';
7851 * HelpTool.static.icon = 'help';
7852 * HelpTool.static.title = 'Help';
7853 * toolFactory.register( HelpTool );
7854 *
7855 * // Finally define which tools and in what order appear in the toolbar. Each tool may only be
7856 * // used once (but not all defined tools must be used).
7857 * toolbar.setup( [
7858 * {
7859 * // 'bar' tool groups display tools' icons only, side-by-side.
7860 * type: 'bar',
7861 * include: [ 'search', 'help' ]
7862 * },
7863 * {
7864 * // 'menu' tool groups display both the titles and icons, in a dropdown menu.
7865 * // Menu label indicates which items are selected.
7866 * type: 'menu',
7867 * indicator: 'down',
7868 * include: [ 'settings', 'stuff' ]
7869 * }
7870 * ] );
7871 *
7872 * // Create some UI around the toolbar and place it in the document
7873 * var frame = new OO.ui.PanelLayout( {
7874 * expanded: false,
7875 * framed: true
7876 * } );
7877 * var contentFrame = new OO.ui.PanelLayout( {
7878 * expanded: false,
7879 * padded: true
7880 * } );
7881 * frame.$element.append(
7882 * toolbar.$element,
7883 * contentFrame.$element.append( $area )
7884 * );
7885 * $( 'body' ).append( frame.$element );
7886 *
7887 * // Here is where the toolbar is actually built. This must be done after inserting it into the
7888 * // document.
7889 * toolbar.initialize();
7890 * toolbar.emit( 'updateState' );
7891 *
7892 * @class
7893 * @extends OO.ui.Element
7894 * @mixins OO.EventEmitter
7895 * @mixins OO.ui.mixin.GroupElement
7896 *
7897 * @constructor
7898 * @param {OO.ui.ToolFactory} toolFactory Factory for creating tools
7899 * @param {OO.ui.ToolGroupFactory} toolGroupFactory Factory for creating toolgroups
7900 * @param {Object} [config] Configuration options
7901 * @cfg {boolean} [actions] Add an actions section to the toolbar. Actions are commands that are included
7902 * in the toolbar, but are not configured as tools. By default, actions are displayed on the right side of
7903 * the toolbar.
7904 * @cfg {boolean} [shadow] Add a shadow below the toolbar.
7905 */
7906 OO.ui.Toolbar = function OoUiToolbar( toolFactory, toolGroupFactory, config ) {
7907 // Allow passing positional parameters inside the config object
7908 if ( OO.isPlainObject( toolFactory ) && config === undefined ) {
7909 config = toolFactory;
7910 toolFactory = config.toolFactory;
7911 toolGroupFactory = config.toolGroupFactory;
7912 }
7913
7914 // Configuration initialization
7915 config = config || {};
7916
7917 // Parent constructor
7918 OO.ui.Toolbar.parent.call( this, config );
7919
7920 // Mixin constructors
7921 OO.EventEmitter.call( this );
7922 OO.ui.mixin.GroupElement.call( this, config );
7923
7924 // Properties
7925 this.toolFactory = toolFactory;
7926 this.toolGroupFactory = toolGroupFactory;
7927 this.groups = [];
7928 this.tools = {};
7929 this.$bar = $( '<div>' );
7930 this.$actions = $( '<div>' );
7931 this.initialized = false;
7932 this.onWindowResizeHandler = this.onWindowResize.bind( this );
7933
7934 // Events
7935 this.$element
7936 .add( this.$bar ).add( this.$group ).add( this.$actions )
7937 .on( 'mousedown keydown', this.onPointerDown.bind( this ) );
7938
7939 // Initialization
7940 this.$group.addClass( 'oo-ui-toolbar-tools' );
7941 if ( config.actions ) {
7942 this.$bar.append( this.$actions.addClass( 'oo-ui-toolbar-actions' ) );
7943 }
7944 this.$bar
7945 .addClass( 'oo-ui-toolbar-bar' )
7946 .append( this.$group, '<div style="clear:both"></div>' );
7947 if ( config.shadow ) {
7948 this.$bar.append( '<div class="oo-ui-toolbar-shadow"></div>' );
7949 }
7950 this.$element.addClass( 'oo-ui-toolbar' ).append( this.$bar );
7951 };
7952
7953 /* Setup */
7954
7955 OO.inheritClass( OO.ui.Toolbar, OO.ui.Element );
7956 OO.mixinClass( OO.ui.Toolbar, OO.EventEmitter );
7957 OO.mixinClass( OO.ui.Toolbar, OO.ui.mixin.GroupElement );
7958
7959 /* Events */
7960
7961 /**
7962 * @event updateState
7963 *
7964 * An 'updateState' event must be emitted on the Toolbar (by calling `toolbar.emit( 'updateState' )`)
7965 * every time the state of the application using the toolbar changes, and an update to the state of
7966 * tools is required.
7967 *
7968 * @param {Mixed...} data Application-defined parameters
7969 */
7970
7971 /* Methods */
7972
7973 /**
7974 * Get the tool factory.
7975 *
7976 * @return {OO.ui.ToolFactory} Tool factory
7977 */
7978 OO.ui.Toolbar.prototype.getToolFactory = function () {
7979 return this.toolFactory;
7980 };
7981
7982 /**
7983 * Get the toolgroup factory.
7984 *
7985 * @return {OO.Factory} Toolgroup factory
7986 */
7987 OO.ui.Toolbar.prototype.getToolGroupFactory = function () {
7988 return this.toolGroupFactory;
7989 };
7990
7991 /**
7992 * Handles mouse down events.
7993 *
7994 * @private
7995 * @param {jQuery.Event} e Mouse down event
7996 */
7997 OO.ui.Toolbar.prototype.onPointerDown = function ( e ) {
7998 var $closestWidgetToEvent = $( e.target ).closest( '.oo-ui-widget' ),
7999 $closestWidgetToToolbar = this.$element.closest( '.oo-ui-widget' );
8000 if ( !$closestWidgetToEvent.length || $closestWidgetToEvent[ 0 ] === $closestWidgetToToolbar[ 0 ] ) {
8001 return false;
8002 }
8003 };
8004
8005 /**
8006 * Handle window resize event.
8007 *
8008 * @private
8009 * @param {jQuery.Event} e Window resize event
8010 */
8011 OO.ui.Toolbar.prototype.onWindowResize = function () {
8012 this.$element.toggleClass(
8013 'oo-ui-toolbar-narrow',
8014 this.$bar.width() <= this.narrowThreshold
8015 );
8016 };
8017
8018 /**
8019 * Sets up handles and preloads required information for the toolbar to work.
8020 * This must be called after it is attached to a visible document and before doing anything else.
8021 */
8022 OO.ui.Toolbar.prototype.initialize = function () {
8023 if ( !this.initialized ) {
8024 this.initialized = true;
8025 this.narrowThreshold = this.$group.width() + this.$actions.width();
8026 $( this.getElementWindow() ).on( 'resize', this.onWindowResizeHandler );
8027 this.onWindowResize();
8028 }
8029 };
8030
8031 /**
8032 * Set up the toolbar.
8033 *
8034 * The toolbar is set up with a list of toolgroup configurations that specify the type of
8035 * toolgroup ({@link OO.ui.BarToolGroup bar}, {@link OO.ui.MenuToolGroup menu}, or {@link OO.ui.ListToolGroup list})
8036 * to add and which tools to include, exclude, promote, or demote within that toolgroup. Please
8037 * see {@link OO.ui.ToolGroup toolgroups} for more information about including tools in toolgroups.
8038 *
8039 * @param {Object.<string,Array>} groups List of toolgroup configurations
8040 * @param {Array|string} [groups.include] Tools to include in the toolgroup
8041 * @param {Array|string} [groups.exclude] Tools to exclude from the toolgroup
8042 * @param {Array|string} [groups.promote] Tools to promote to the beginning of the toolgroup
8043 * @param {Array|string} [groups.demote] Tools to demote to the end of the toolgroup
8044 */
8045 OO.ui.Toolbar.prototype.setup = function ( groups ) {
8046 var i, len, type, group,
8047 items = [],
8048 defaultType = 'bar';
8049
8050 // Cleanup previous groups
8051 this.reset();
8052
8053 // Build out new groups
8054 for ( i = 0, len = groups.length; i < len; i++ ) {
8055 group = groups[ i ];
8056 if ( group.include === '*' ) {
8057 // Apply defaults to catch-all groups
8058 if ( group.type === undefined ) {
8059 group.type = 'list';
8060 }
8061 if ( group.label === undefined ) {
8062 group.label = OO.ui.msg( 'ooui-toolbar-more' );
8063 }
8064 }
8065 // Check type has been registered
8066 type = this.getToolGroupFactory().lookup( group.type ) ? group.type : defaultType;
8067 items.push(
8068 this.getToolGroupFactory().create( type, this, group )
8069 );
8070 }
8071 this.addItems( items );
8072 };
8073
8074 /**
8075 * Remove all tools and toolgroups from the toolbar.
8076 */
8077 OO.ui.Toolbar.prototype.reset = function () {
8078 var i, len;
8079
8080 this.groups = [];
8081 this.tools = {};
8082 for ( i = 0, len = this.items.length; i < len; i++ ) {
8083 this.items[ i ].destroy();
8084 }
8085 this.clearItems();
8086 };
8087
8088 /**
8089 * Destroy the toolbar.
8090 *
8091 * Destroying the toolbar removes all event handlers and DOM elements that constitute the toolbar. Call
8092 * this method whenever you are done using a toolbar.
8093 */
8094 OO.ui.Toolbar.prototype.destroy = function () {
8095 $( this.getElementWindow() ).off( 'resize', this.onWindowResizeHandler );
8096 this.reset();
8097 this.$element.remove();
8098 };
8099
8100 /**
8101 * Check if the tool is available.
8102 *
8103 * Available tools are ones that have not yet been added to the toolbar.
8104 *
8105 * @param {string} name Symbolic name of tool
8106 * @return {boolean} Tool is available
8107 */
8108 OO.ui.Toolbar.prototype.isToolAvailable = function ( name ) {
8109 return !this.tools[ name ];
8110 };
8111
8112 /**
8113 * Prevent tool from being used again.
8114 *
8115 * @param {OO.ui.Tool} tool Tool to reserve
8116 */
8117 OO.ui.Toolbar.prototype.reserveTool = function ( tool ) {
8118 this.tools[ tool.getName() ] = tool;
8119 };
8120
8121 /**
8122 * Allow tool to be used again.
8123 *
8124 * @param {OO.ui.Tool} tool Tool to release
8125 */
8126 OO.ui.Toolbar.prototype.releaseTool = function ( tool ) {
8127 delete this.tools[ tool.getName() ];
8128 };
8129
8130 /**
8131 * Get accelerator label for tool.
8132 *
8133 * The OOjs UI library does not contain an accelerator system, but this is the hook for one. To
8134 * use an accelerator system, subclass the toolbar and override this method, which is meant to return a label
8135 * that describes the accelerator keys for the tool passed (by symbolic name) to the method.
8136 *
8137 * @param {string} name Symbolic name of tool
8138 * @return {string|undefined} Tool accelerator label if available
8139 */
8140 OO.ui.Toolbar.prototype.getToolAccelerator = function () {
8141 return undefined;
8142 };
8143
8144 /**
8145 * ToolGroups are collections of {@link OO.ui.Tool tools} that are used in a {@link OO.ui.Toolbar toolbar}.
8146 * The type of toolgroup ({@link OO.ui.ListToolGroup list}, {@link OO.ui.BarToolGroup bar}, or {@link OO.ui.MenuToolGroup menu})
8147 * to which a tool belongs determines how the tool is arranged and displayed in the toolbar. Toolgroups
8148 * themselves are created on demand with a {@link OO.ui.ToolGroupFactory toolgroup factory}.
8149 *
8150 * Toolgroups can contain individual tools, groups of tools, or all available tools, as specified
8151 * using the `include` config option. See OO.ui.ToolFactory#extract on documentation of the format.
8152 * The options `exclude`, `promote`, and `demote` support the same formats.
8153 *
8154 * See {@link OO.ui.Toolbar toolbars} for a full example. For more information about toolbars in general,
8155 * please see the [OOjs UI documentation on MediaWiki][1].
8156 *
8157 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
8158 *
8159 * @abstract
8160 * @class
8161 * @extends OO.ui.Widget
8162 * @mixins OO.ui.mixin.GroupElement
8163 *
8164 * @constructor
8165 * @param {OO.ui.Toolbar} toolbar
8166 * @param {Object} [config] Configuration options
8167 * @cfg {Array|string} [include] List of tools to include in the toolgroup, see above.
8168 * @cfg {Array|string} [exclude] List of tools to exclude from the toolgroup, see above.
8169 * @cfg {Array|string} [promote] List of tools to promote to the beginning of the toolgroup, see above.
8170 * @cfg {Array|string} [demote] List of tools to demote to the end of the toolgroup, see above.
8171 * This setting is particularly useful when tools have been added to the toolgroup
8172 * en masse (e.g., via the catch-all selector).
8173 */
8174 OO.ui.ToolGroup = function OoUiToolGroup( toolbar, config ) {
8175 // Allow passing positional parameters inside the config object
8176 if ( OO.isPlainObject( toolbar ) && config === undefined ) {
8177 config = toolbar;
8178 toolbar = config.toolbar;
8179 }
8180
8181 // Configuration initialization
8182 config = config || {};
8183
8184 // Parent constructor
8185 OO.ui.ToolGroup.parent.call( this, config );
8186
8187 // Mixin constructors
8188 OO.ui.mixin.GroupElement.call( this, config );
8189
8190 // Properties
8191 this.toolbar = toolbar;
8192 this.tools = {};
8193 this.pressed = null;
8194 this.autoDisabled = false;
8195 this.include = config.include || [];
8196 this.exclude = config.exclude || [];
8197 this.promote = config.promote || [];
8198 this.demote = config.demote || [];
8199 this.onCapturedMouseKeyUpHandler = this.onCapturedMouseKeyUp.bind( this );
8200
8201 // Events
8202 this.$element.on( {
8203 mousedown: this.onMouseKeyDown.bind( this ),
8204 mouseup: this.onMouseKeyUp.bind( this ),
8205 keydown: this.onMouseKeyDown.bind( this ),
8206 keyup: this.onMouseKeyUp.bind( this ),
8207 focus: this.onMouseOverFocus.bind( this ),
8208 blur: this.onMouseOutBlur.bind( this ),
8209 mouseover: this.onMouseOverFocus.bind( this ),
8210 mouseout: this.onMouseOutBlur.bind( this )
8211 } );
8212 this.toolbar.getToolFactory().connect( this, { register: 'onToolFactoryRegister' } );
8213 this.aggregate( { disable: 'itemDisable' } );
8214 this.connect( this, { itemDisable: 'updateDisabled' } );
8215
8216 // Initialization
8217 this.$group.addClass( 'oo-ui-toolGroup-tools' );
8218 this.$element
8219 .addClass( 'oo-ui-toolGroup' )
8220 .append( this.$group );
8221 this.populate();
8222 };
8223
8224 /* Setup */
8225
8226 OO.inheritClass( OO.ui.ToolGroup, OO.ui.Widget );
8227 OO.mixinClass( OO.ui.ToolGroup, OO.ui.mixin.GroupElement );
8228
8229 /* Events */
8230
8231 /**
8232 * @event update
8233 */
8234
8235 /* Static Properties */
8236
8237 /**
8238 * Show labels in tooltips.
8239 *
8240 * @static
8241 * @inheritable
8242 * @property {boolean}
8243 */
8244 OO.ui.ToolGroup.static.titleTooltips = false;
8245
8246 /**
8247 * Show acceleration labels in tooltips.
8248 *
8249 * Note: The OOjs UI library does not include an accelerator system, but does contain
8250 * a hook for one. To use an accelerator system, subclass the {@link OO.ui.Toolbar toolbar} and
8251 * override the {@link OO.ui.Toolbar#getToolAccelerator getToolAccelerator} method, which is
8252 * meant to return a label that describes the accelerator keys for a given tool (e.g., 'Ctrl + M').
8253 *
8254 * @static
8255 * @inheritable
8256 * @property {boolean}
8257 */
8258 OO.ui.ToolGroup.static.accelTooltips = false;
8259
8260 /**
8261 * Automatically disable the toolgroup when all tools are disabled
8262 *
8263 * @static
8264 * @inheritable
8265 * @property {boolean}
8266 */
8267 OO.ui.ToolGroup.static.autoDisable = true;
8268
8269 /* Methods */
8270
8271 /**
8272 * @inheritdoc
8273 */
8274 OO.ui.ToolGroup.prototype.isDisabled = function () {
8275 return this.autoDisabled || OO.ui.ToolGroup.parent.prototype.isDisabled.apply( this, arguments );
8276 };
8277
8278 /**
8279 * @inheritdoc
8280 */
8281 OO.ui.ToolGroup.prototype.updateDisabled = function () {
8282 var i, item, allDisabled = true;
8283
8284 if ( this.constructor.static.autoDisable ) {
8285 for ( i = this.items.length - 1; i >= 0; i-- ) {
8286 item = this.items[ i ];
8287 if ( !item.isDisabled() ) {
8288 allDisabled = false;
8289 break;
8290 }
8291 }
8292 this.autoDisabled = allDisabled;
8293 }
8294 OO.ui.ToolGroup.parent.prototype.updateDisabled.apply( this, arguments );
8295 };
8296
8297 /**
8298 * Handle mouse down and key down events.
8299 *
8300 * @protected
8301 * @param {jQuery.Event} e Mouse down or key down event
8302 */
8303 OO.ui.ToolGroup.prototype.onMouseKeyDown = function ( e ) {
8304 if (
8305 !this.isDisabled() &&
8306 ( e.which === OO.ui.MouseButtons.LEFT || e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
8307 ) {
8308 this.pressed = this.getTargetTool( e );
8309 if ( this.pressed ) {
8310 this.pressed.setActive( true );
8311 this.getElementDocument().addEventListener( 'mouseup', this.onCapturedMouseKeyUpHandler, true );
8312 this.getElementDocument().addEventListener( 'keyup', this.onCapturedMouseKeyUpHandler, true );
8313 }
8314 return false;
8315 }
8316 };
8317
8318 /**
8319 * Handle captured mouse up and key up events.
8320 *
8321 * @protected
8322 * @param {Event} e Mouse up or key up event
8323 */
8324 OO.ui.ToolGroup.prototype.onCapturedMouseKeyUp = function ( e ) {
8325 this.getElementDocument().removeEventListener( 'mouseup', this.onCapturedMouseKeyUpHandler, true );
8326 this.getElementDocument().removeEventListener( 'keyup', this.onCapturedMouseKeyUpHandler, true );
8327 // onMouseKeyUp may be called a second time, depending on where the mouse is when the button is
8328 // released, but since `this.pressed` will no longer be true, the second call will be ignored.
8329 this.onMouseKeyUp( e );
8330 };
8331
8332 /**
8333 * Handle mouse up and key up events.
8334 *
8335 * @protected
8336 * @param {jQuery.Event} e Mouse up or key up event
8337 */
8338 OO.ui.ToolGroup.prototype.onMouseKeyUp = function ( e ) {
8339 var tool = this.getTargetTool( e );
8340
8341 if (
8342 !this.isDisabled() && this.pressed && this.pressed === tool &&
8343 ( e.which === OO.ui.MouseButtons.LEFT || e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
8344 ) {
8345 this.pressed.onSelect();
8346 this.pressed = null;
8347 return false;
8348 }
8349
8350 this.pressed = null;
8351 };
8352
8353 /**
8354 * Handle mouse over and focus events.
8355 *
8356 * @protected
8357 * @param {jQuery.Event} e Mouse over or focus event
8358 */
8359 OO.ui.ToolGroup.prototype.onMouseOverFocus = function ( e ) {
8360 var tool = this.getTargetTool( e );
8361
8362 if ( this.pressed && this.pressed === tool ) {
8363 this.pressed.setActive( true );
8364 }
8365 };
8366
8367 /**
8368 * Handle mouse out and blur events.
8369 *
8370 * @protected
8371 * @param {jQuery.Event} e Mouse out or blur event
8372 */
8373 OO.ui.ToolGroup.prototype.onMouseOutBlur = function ( e ) {
8374 var tool = this.getTargetTool( e );
8375
8376 if ( this.pressed && this.pressed === tool ) {
8377 this.pressed.setActive( false );
8378 }
8379 };
8380
8381 /**
8382 * Get the closest tool to a jQuery.Event.
8383 *
8384 * Only tool links are considered, which prevents other elements in the tool such as popups from
8385 * triggering tool group interactions.
8386 *
8387 * @private
8388 * @param {jQuery.Event} e
8389 * @return {OO.ui.Tool|null} Tool, `null` if none was found
8390 */
8391 OO.ui.ToolGroup.prototype.getTargetTool = function ( e ) {
8392 var tool,
8393 $item = $( e.target ).closest( '.oo-ui-tool-link' );
8394
8395 if ( $item.length ) {
8396 tool = $item.parent().data( 'oo-ui-tool' );
8397 }
8398
8399 return tool && !tool.isDisabled() ? tool : null;
8400 };
8401
8402 /**
8403 * Handle tool registry register events.
8404 *
8405 * If a tool is registered after the group is created, we must repopulate the list to account for:
8406 *
8407 * - a tool being added that may be included
8408 * - a tool already included being overridden
8409 *
8410 * @protected
8411 * @param {string} name Symbolic name of tool
8412 */
8413 OO.ui.ToolGroup.prototype.onToolFactoryRegister = function () {
8414 this.populate();
8415 };
8416
8417 /**
8418 * Get the toolbar that contains the toolgroup.
8419 *
8420 * @return {OO.ui.Toolbar} Toolbar that contains the toolgroup
8421 */
8422 OO.ui.ToolGroup.prototype.getToolbar = function () {
8423 return this.toolbar;
8424 };
8425
8426 /**
8427 * Add and remove tools based on configuration.
8428 */
8429 OO.ui.ToolGroup.prototype.populate = function () {
8430 var i, len, name, tool,
8431 toolFactory = this.toolbar.getToolFactory(),
8432 names = {},
8433 add = [],
8434 remove = [],
8435 list = this.toolbar.getToolFactory().getTools(
8436 this.include, this.exclude, this.promote, this.demote
8437 );
8438
8439 // Build a list of needed tools
8440 for ( i = 0, len = list.length; i < len; i++ ) {
8441 name = list[ i ];
8442 if (
8443 // Tool exists
8444 toolFactory.lookup( name ) &&
8445 // Tool is available or is already in this group
8446 ( this.toolbar.isToolAvailable( name ) || this.tools[ name ] )
8447 ) {
8448 // Hack to prevent infinite recursion via ToolGroupTool. We need to reserve the tool before
8449 // creating it, but we can't call reserveTool() yet because we haven't created the tool.
8450 this.toolbar.tools[ name ] = true;
8451 tool = this.tools[ name ];
8452 if ( !tool ) {
8453 // Auto-initialize tools on first use
8454 this.tools[ name ] = tool = toolFactory.create( name, this );
8455 tool.updateTitle();
8456 }
8457 this.toolbar.reserveTool( tool );
8458 add.push( tool );
8459 names[ name ] = true;
8460 }
8461 }
8462 // Remove tools that are no longer needed
8463 for ( name in this.tools ) {
8464 if ( !names[ name ] ) {
8465 this.tools[ name ].destroy();
8466 this.toolbar.releaseTool( this.tools[ name ] );
8467 remove.push( this.tools[ name ] );
8468 delete this.tools[ name ];
8469 }
8470 }
8471 if ( remove.length ) {
8472 this.removeItems( remove );
8473 }
8474 // Update emptiness state
8475 if ( add.length ) {
8476 this.$element.removeClass( 'oo-ui-toolGroup-empty' );
8477 } else {
8478 this.$element.addClass( 'oo-ui-toolGroup-empty' );
8479 }
8480 // Re-add tools (moving existing ones to new locations)
8481 this.addItems( add );
8482 // Disabled state may depend on items
8483 this.updateDisabled();
8484 };
8485
8486 /**
8487 * Destroy toolgroup.
8488 */
8489 OO.ui.ToolGroup.prototype.destroy = function () {
8490 var name;
8491
8492 this.clearItems();
8493 this.toolbar.getToolFactory().disconnect( this );
8494 for ( name in this.tools ) {
8495 this.toolbar.releaseTool( this.tools[ name ] );
8496 this.tools[ name ].disconnect( this ).destroy();
8497 delete this.tools[ name ];
8498 }
8499 this.$element.remove();
8500 };
8501
8502 /**
8503 * MessageDialogs display a confirmation or alert message. By default, the rendered dialog box
8504 * consists of a header that contains the dialog title, a body with the message, and a footer that
8505 * contains any {@link OO.ui.ActionWidget action widgets}. The MessageDialog class is the only type
8506 * of {@link OO.ui.Dialog dialog} that is usually instantiated directly.
8507 *
8508 * There are two basic types of message dialogs, confirmation and alert:
8509 *
8510 * - **confirmation**: the dialog title describes what a progressive action will do and the message provides
8511 * more details about the consequences.
8512 * - **alert**: the dialog title describes which event occurred and the message provides more information
8513 * about why the event occurred.
8514 *
8515 * The MessageDialog class specifies two actions: ‘accept’, the primary
8516 * action (e.g., ‘ok’) and ‘reject,’ the safe action (e.g., ‘cancel’). Both will close the window,
8517 * passing along the selected action.
8518 *
8519 * For more information and examples, please see the [OOjs UI documentation on MediaWiki][1].
8520 *
8521 * @example
8522 * // Example: Creating and opening a message dialog window.
8523 * var messageDialog = new OO.ui.MessageDialog();
8524 *
8525 * // Create and append a window manager.
8526 * var windowManager = new OO.ui.WindowManager();
8527 * $( 'body' ).append( windowManager.$element );
8528 * windowManager.addWindows( [ messageDialog ] );
8529 * // Open the window.
8530 * windowManager.openWindow( messageDialog, {
8531 * title: 'Basic message dialog',
8532 * message: 'This is the message'
8533 * } );
8534 *
8535 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Message_Dialogs
8536 *
8537 * @class
8538 * @extends OO.ui.Dialog
8539 *
8540 * @constructor
8541 * @param {Object} [config] Configuration options
8542 */
8543 OO.ui.MessageDialog = function OoUiMessageDialog( config ) {
8544 // Parent constructor
8545 OO.ui.MessageDialog.parent.call( this, config );
8546
8547 // Properties
8548 this.verticalActionLayout = null;
8549
8550 // Initialization
8551 this.$element.addClass( 'oo-ui-messageDialog' );
8552 };
8553
8554 /* Setup */
8555
8556 OO.inheritClass( OO.ui.MessageDialog, OO.ui.Dialog );
8557
8558 /* Static Properties */
8559
8560 OO.ui.MessageDialog.static.name = 'message';
8561
8562 OO.ui.MessageDialog.static.size = 'small';
8563
8564 OO.ui.MessageDialog.static.verbose = false;
8565
8566 /**
8567 * Dialog title.
8568 *
8569 * The title of a confirmation dialog describes what a progressive action will do. The
8570 * title of an alert dialog describes which event occurred.
8571 *
8572 * @static
8573 * @inheritable
8574 * @property {jQuery|string|Function|null}
8575 */
8576 OO.ui.MessageDialog.static.title = null;
8577
8578 /**
8579 * The message displayed in the dialog body.
8580 *
8581 * A confirmation message describes the consequences of a progressive action. An alert
8582 * message describes why an event occurred.
8583 *
8584 * @static
8585 * @inheritable
8586 * @property {jQuery|string|Function|null}
8587 */
8588 OO.ui.MessageDialog.static.message = null;
8589
8590 // Note that OO.ui.alert() and OO.ui.confirm() rely on these.
8591 OO.ui.MessageDialog.static.actions = [
8592 { action: 'accept', label: OO.ui.deferMsg( 'ooui-dialog-message-accept' ), flags: 'primary' },
8593 { action: 'reject', label: OO.ui.deferMsg( 'ooui-dialog-message-reject' ), flags: 'safe' }
8594 ];
8595
8596 /* Methods */
8597
8598 /**
8599 * @inheritdoc
8600 */
8601 OO.ui.MessageDialog.prototype.setManager = function ( manager ) {
8602 OO.ui.MessageDialog.parent.prototype.setManager.call( this, manager );
8603
8604 // Events
8605 this.manager.connect( this, {
8606 resize: 'onResize'
8607 } );
8608
8609 return this;
8610 };
8611
8612 /**
8613 * @inheritdoc
8614 */
8615 OO.ui.MessageDialog.prototype.onActionResize = function ( action ) {
8616 this.fitActions();
8617 return OO.ui.MessageDialog.parent.prototype.onActionResize.call( this, action );
8618 };
8619
8620 /**
8621 * Handle window resized events.
8622 *
8623 * @private
8624 */
8625 OO.ui.MessageDialog.prototype.onResize = function () {
8626 var dialog = this;
8627 dialog.fitActions();
8628 // Wait for CSS transition to finish and do it again :(
8629 setTimeout( function () {
8630 dialog.fitActions();
8631 }, 300 );
8632 };
8633
8634 /**
8635 * Toggle action layout between vertical and horizontal.
8636 *
8637 * @private
8638 * @param {boolean} [value] Layout actions vertically, omit to toggle
8639 * @chainable
8640 */
8641 OO.ui.MessageDialog.prototype.toggleVerticalActionLayout = function ( value ) {
8642 value = value === undefined ? !this.verticalActionLayout : !!value;
8643
8644 if ( value !== this.verticalActionLayout ) {
8645 this.verticalActionLayout = value;
8646 this.$actions
8647 .toggleClass( 'oo-ui-messageDialog-actions-vertical', value )
8648 .toggleClass( 'oo-ui-messageDialog-actions-horizontal', !value );
8649 }
8650
8651 return this;
8652 };
8653
8654 /**
8655 * @inheritdoc
8656 */
8657 OO.ui.MessageDialog.prototype.getActionProcess = function ( action ) {
8658 if ( action ) {
8659 return new OO.ui.Process( function () {
8660 this.close( { action: action } );
8661 }, this );
8662 }
8663 return OO.ui.MessageDialog.parent.prototype.getActionProcess.call( this, action );
8664 };
8665
8666 /**
8667 * @inheritdoc
8668 *
8669 * @param {Object} [data] Dialog opening data
8670 * @param {jQuery|string|Function|null} [data.title] Description of the action being confirmed
8671 * @param {jQuery|string|Function|null} [data.message] Description of the action's consequence
8672 * @param {boolean} [data.verbose] Message is verbose and should be styled as a long message
8673 * @param {Object[]} [data.actions] List of OO.ui.ActionOptionWidget configuration options for each
8674 * action item
8675 */
8676 OO.ui.MessageDialog.prototype.getSetupProcess = function ( data ) {
8677 data = data || {};
8678
8679 // Parent method
8680 return OO.ui.MessageDialog.parent.prototype.getSetupProcess.call( this, data )
8681 .next( function () {
8682 this.title.setLabel(
8683 data.title !== undefined ? data.title : this.constructor.static.title
8684 );
8685 this.message.setLabel(
8686 data.message !== undefined ? data.message : this.constructor.static.message
8687 );
8688 this.message.$element.toggleClass(
8689 'oo-ui-messageDialog-message-verbose',
8690 data.verbose !== undefined ? data.verbose : this.constructor.static.verbose
8691 );
8692 }, this );
8693 };
8694
8695 /**
8696 * @inheritdoc
8697 */
8698 OO.ui.MessageDialog.prototype.getReadyProcess = function ( data ) {
8699 data = data || {};
8700
8701 // Parent method
8702 return OO.ui.MessageDialog.parent.prototype.getReadyProcess.call( this, data )
8703 .next( function () {
8704 // Focus the primary action button
8705 var actions = this.actions.get();
8706 actions = actions.filter( function ( action ) {
8707 return action.getFlags().indexOf( 'primary' ) > -1;
8708 } );
8709 if ( actions.length > 0 ) {
8710 actions[ 0 ].$button.focus();
8711 }
8712 }, this );
8713 };
8714
8715 /**
8716 * @inheritdoc
8717 */
8718 OO.ui.MessageDialog.prototype.getBodyHeight = function () {
8719 var bodyHeight, oldOverflow,
8720 $scrollable = this.container.$element;
8721
8722 oldOverflow = $scrollable[ 0 ].style.overflow;
8723 $scrollable[ 0 ].style.overflow = 'hidden';
8724
8725 OO.ui.Element.static.reconsiderScrollbars( $scrollable[ 0 ] );
8726
8727 bodyHeight = this.text.$element.outerHeight( true );
8728 $scrollable[ 0 ].style.overflow = oldOverflow;
8729
8730 return bodyHeight;
8731 };
8732
8733 /**
8734 * @inheritdoc
8735 */
8736 OO.ui.MessageDialog.prototype.setDimensions = function ( dim ) {
8737 var $scrollable = this.container.$element;
8738 OO.ui.MessageDialog.parent.prototype.setDimensions.call( this, dim );
8739
8740 // Twiddle the overflow property, otherwise an unnecessary scrollbar will be produced.
8741 // Need to do it after transition completes (250ms), add 50ms just in case.
8742 setTimeout( function () {
8743 var oldOverflow = $scrollable[ 0 ].style.overflow;
8744 $scrollable[ 0 ].style.overflow = 'hidden';
8745
8746 OO.ui.Element.static.reconsiderScrollbars( $scrollable[ 0 ] );
8747
8748 $scrollable[ 0 ].style.overflow = oldOverflow;
8749 }, 300 );
8750
8751 return this;
8752 };
8753
8754 /**
8755 * @inheritdoc
8756 */
8757 OO.ui.MessageDialog.prototype.initialize = function () {
8758 // Parent method
8759 OO.ui.MessageDialog.parent.prototype.initialize.call( this );
8760
8761 // Properties
8762 this.$actions = $( '<div>' );
8763 this.container = new OO.ui.PanelLayout( {
8764 scrollable: true, classes: [ 'oo-ui-messageDialog-container' ]
8765 } );
8766 this.text = new OO.ui.PanelLayout( {
8767 padded: true, expanded: false, classes: [ 'oo-ui-messageDialog-text' ]
8768 } );
8769 this.message = new OO.ui.LabelWidget( {
8770 classes: [ 'oo-ui-messageDialog-message' ]
8771 } );
8772
8773 // Initialization
8774 this.title.$element.addClass( 'oo-ui-messageDialog-title' );
8775 this.$content.addClass( 'oo-ui-messageDialog-content' );
8776 this.container.$element.append( this.text.$element );
8777 this.text.$element.append( this.title.$element, this.message.$element );
8778 this.$body.append( this.container.$element );
8779 this.$actions.addClass( 'oo-ui-messageDialog-actions' );
8780 this.$foot.append( this.$actions );
8781 };
8782
8783 /**
8784 * @inheritdoc
8785 */
8786 OO.ui.MessageDialog.prototype.attachActions = function () {
8787 var i, len, other, special, others;
8788
8789 // Parent method
8790 OO.ui.MessageDialog.parent.prototype.attachActions.call( this );
8791
8792 special = this.actions.getSpecial();
8793 others = this.actions.getOthers();
8794
8795 if ( special.safe ) {
8796 this.$actions.append( special.safe.$element );
8797 special.safe.toggleFramed( false );
8798 }
8799 if ( others.length ) {
8800 for ( i = 0, len = others.length; i < len; i++ ) {
8801 other = others[ i ];
8802 this.$actions.append( other.$element );
8803 other.toggleFramed( false );
8804 }
8805 }
8806 if ( special.primary ) {
8807 this.$actions.append( special.primary.$element );
8808 special.primary.toggleFramed( false );
8809 }
8810
8811 if ( !this.isOpening() ) {
8812 // If the dialog is currently opening, this will be called automatically soon.
8813 // This also calls #fitActions.
8814 this.updateSize();
8815 }
8816 };
8817
8818 /**
8819 * Fit action actions into columns or rows.
8820 *
8821 * Columns will be used if all labels can fit without overflow, otherwise rows will be used.
8822 *
8823 * @private
8824 */
8825 OO.ui.MessageDialog.prototype.fitActions = function () {
8826 var i, len, action,
8827 previous = this.verticalActionLayout,
8828 actions = this.actions.get();
8829
8830 // Detect clipping
8831 this.toggleVerticalActionLayout( false );
8832 for ( i = 0, len = actions.length; i < len; i++ ) {
8833 action = actions[ i ];
8834 if ( action.$element.innerWidth() < action.$label.outerWidth( true ) ) {
8835 this.toggleVerticalActionLayout( true );
8836 break;
8837 }
8838 }
8839
8840 // Move the body out of the way of the foot
8841 this.$body.css( 'bottom', this.$foot.outerHeight( true ) );
8842
8843 if ( this.verticalActionLayout !== previous ) {
8844 // We changed the layout, window height might need to be updated.
8845 this.updateSize();
8846 }
8847 };
8848
8849 /**
8850 * ProcessDialog windows encapsulate a {@link OO.ui.Process process} and all of the code necessary
8851 * to complete it. If the process terminates with an error, a customizable {@link OO.ui.Error error
8852 * interface} alerts users to the trouble, permitting the user to dismiss the error and try again when
8853 * relevant. The ProcessDialog class is always extended and customized with the actions and content
8854 * required for each process.
8855 *
8856 * The process dialog box consists of a header that visually represents the ‘working’ state of long
8857 * processes with an animation. The header contains the dialog title as well as
8858 * two {@link OO.ui.ActionWidget action widgets}: a ‘safe’ action on the left (e.g., ‘Cancel’) and
8859 * a ‘primary’ action on the right (e.g., ‘Done’).
8860 *
8861 * Like other windows, the process dialog is managed by a {@link OO.ui.WindowManager window manager}.
8862 * Please see the [OOjs UI documentation on MediaWiki][1] for more information and examples.
8863 *
8864 * @example
8865 * // Example: Creating and opening a process dialog window.
8866 * function MyProcessDialog( config ) {
8867 * MyProcessDialog.parent.call( this, config );
8868 * }
8869 * OO.inheritClass( MyProcessDialog, OO.ui.ProcessDialog );
8870 *
8871 * MyProcessDialog.static.title = 'Process dialog';
8872 * MyProcessDialog.static.actions = [
8873 * { action: 'save', label: 'Done', flags: 'primary' },
8874 * { label: 'Cancel', flags: 'safe' }
8875 * ];
8876 *
8877 * MyProcessDialog.prototype.initialize = function () {
8878 * MyProcessDialog.parent.prototype.initialize.apply( this, arguments );
8879 * this.content = new OO.ui.PanelLayout( { padded: true, expanded: false } );
8880 * 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>' );
8881 * this.$body.append( this.content.$element );
8882 * };
8883 * MyProcessDialog.prototype.getActionProcess = function ( action ) {
8884 * var dialog = this;
8885 * if ( action ) {
8886 * return new OO.ui.Process( function () {
8887 * dialog.close( { action: action } );
8888 * } );
8889 * }
8890 * return MyProcessDialog.parent.prototype.getActionProcess.call( this, action );
8891 * };
8892 *
8893 * var windowManager = new OO.ui.WindowManager();
8894 * $( 'body' ).append( windowManager.$element );
8895 *
8896 * var dialog = new MyProcessDialog();
8897 * windowManager.addWindows( [ dialog ] );
8898 * windowManager.openWindow( dialog );
8899 *
8900 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs
8901 *
8902 * @abstract
8903 * @class
8904 * @extends OO.ui.Dialog
8905 *
8906 * @constructor
8907 * @param {Object} [config] Configuration options
8908 */
8909 OO.ui.ProcessDialog = function OoUiProcessDialog( config ) {
8910 // Parent constructor
8911 OO.ui.ProcessDialog.parent.call( this, config );
8912
8913 // Properties
8914 this.fitOnOpen = false;
8915
8916 // Initialization
8917 this.$element.addClass( 'oo-ui-processDialog' );
8918 };
8919
8920 /* Setup */
8921
8922 OO.inheritClass( OO.ui.ProcessDialog, OO.ui.Dialog );
8923
8924 /* Methods */
8925
8926 /**
8927 * Handle dismiss button click events.
8928 *
8929 * Hides errors.
8930 *
8931 * @private
8932 */
8933 OO.ui.ProcessDialog.prototype.onDismissErrorButtonClick = function () {
8934 this.hideErrors();
8935 };
8936
8937 /**
8938 * Handle retry button click events.
8939 *
8940 * Hides errors and then tries again.
8941 *
8942 * @private
8943 */
8944 OO.ui.ProcessDialog.prototype.onRetryButtonClick = function () {
8945 this.hideErrors();
8946 this.executeAction( this.currentAction );
8947 };
8948
8949 /**
8950 * @inheritdoc
8951 */
8952 OO.ui.ProcessDialog.prototype.onActionResize = function ( action ) {
8953 if ( this.actions.isSpecial( action ) ) {
8954 this.fitLabel();
8955 }
8956 return OO.ui.ProcessDialog.parent.prototype.onActionResize.call( this, action );
8957 };
8958
8959 /**
8960 * @inheritdoc
8961 */
8962 OO.ui.ProcessDialog.prototype.initialize = function () {
8963 // Parent method
8964 OO.ui.ProcessDialog.parent.prototype.initialize.call( this );
8965
8966 // Properties
8967 this.$navigation = $( '<div>' );
8968 this.$location = $( '<div>' );
8969 this.$safeActions = $( '<div>' );
8970 this.$primaryActions = $( '<div>' );
8971 this.$otherActions = $( '<div>' );
8972 this.dismissButton = new OO.ui.ButtonWidget( {
8973 label: OO.ui.msg( 'ooui-dialog-process-dismiss' )
8974 } );
8975 this.retryButton = new OO.ui.ButtonWidget();
8976 this.$errors = $( '<div>' );
8977 this.$errorsTitle = $( '<div>' );
8978
8979 // Events
8980 this.dismissButton.connect( this, { click: 'onDismissErrorButtonClick' } );
8981 this.retryButton.connect( this, { click: 'onRetryButtonClick' } );
8982
8983 // Initialization
8984 this.title.$element.addClass( 'oo-ui-processDialog-title' );
8985 this.$location
8986 .append( this.title.$element )
8987 .addClass( 'oo-ui-processDialog-location' );
8988 this.$safeActions.addClass( 'oo-ui-processDialog-actions-safe' );
8989 this.$primaryActions.addClass( 'oo-ui-processDialog-actions-primary' );
8990 this.$otherActions.addClass( 'oo-ui-processDialog-actions-other' );
8991 this.$errorsTitle
8992 .addClass( 'oo-ui-processDialog-errors-title' )
8993 .text( OO.ui.msg( 'ooui-dialog-process-error' ) );
8994 this.$errors
8995 .addClass( 'oo-ui-processDialog-errors oo-ui-element-hidden' )
8996 .append( this.$errorsTitle, this.dismissButton.$element, this.retryButton.$element );
8997 this.$content
8998 .addClass( 'oo-ui-processDialog-content' )
8999 .append( this.$errors );
9000 this.$navigation
9001 .addClass( 'oo-ui-processDialog-navigation' )
9002 .append( this.$safeActions, this.$location, this.$primaryActions );
9003 this.$head.append( this.$navigation );
9004 this.$foot.append( this.$otherActions );
9005 };
9006
9007 /**
9008 * @inheritdoc
9009 */
9010 OO.ui.ProcessDialog.prototype.getActionWidgets = function ( actions ) {
9011 var i, len, widgets = [];
9012 for ( i = 0, len = actions.length; i < len; i++ ) {
9013 widgets.push(
9014 new OO.ui.ActionWidget( $.extend( { framed: true }, actions[ i ] ) )
9015 );
9016 }
9017 return widgets;
9018 };
9019
9020 /**
9021 * @inheritdoc
9022 */
9023 OO.ui.ProcessDialog.prototype.attachActions = function () {
9024 var i, len, other, special, others;
9025
9026 // Parent method
9027 OO.ui.ProcessDialog.parent.prototype.attachActions.call( this );
9028
9029 special = this.actions.getSpecial();
9030 others = this.actions.getOthers();
9031 if ( special.primary ) {
9032 this.$primaryActions.append( special.primary.$element );
9033 }
9034 for ( i = 0, len = others.length; i < len; i++ ) {
9035 other = others[ i ];
9036 this.$otherActions.append( other.$element );
9037 }
9038 if ( special.safe ) {
9039 this.$safeActions.append( special.safe.$element );
9040 }
9041
9042 this.fitLabel();
9043 this.$body.css( 'bottom', this.$foot.outerHeight( true ) );
9044 };
9045
9046 /**
9047 * @inheritdoc
9048 */
9049 OO.ui.ProcessDialog.prototype.executeAction = function ( action ) {
9050 var process = this;
9051 return OO.ui.ProcessDialog.parent.prototype.executeAction.call( this, action )
9052 .fail( function ( errors ) {
9053 process.showErrors( errors || [] );
9054 } );
9055 };
9056
9057 /**
9058 * @inheritdoc
9059 */
9060 OO.ui.ProcessDialog.prototype.setDimensions = function () {
9061 // Parent method
9062 OO.ui.ProcessDialog.parent.prototype.setDimensions.apply( this, arguments );
9063
9064 this.fitLabel();
9065 };
9066
9067 /**
9068 * Fit label between actions.
9069 *
9070 * @private
9071 * @chainable
9072 */
9073 OO.ui.ProcessDialog.prototype.fitLabel = function () {
9074 var safeWidth, primaryWidth, biggerWidth, labelWidth, navigationWidth, leftWidth, rightWidth,
9075 size = this.getSizeProperties();
9076
9077 if ( typeof size.width !== 'number' ) {
9078 if ( this.isOpened() ) {
9079 navigationWidth = this.$head.width() - 20;
9080 } else if ( this.isOpening() ) {
9081 if ( !this.fitOnOpen ) {
9082 // Size is relative and the dialog isn't open yet, so wait.
9083 this.manager.opening.done( this.fitLabel.bind( this ) );
9084 this.fitOnOpen = true;
9085 }
9086 return;
9087 } else {
9088 return;
9089 }
9090 } else {
9091 navigationWidth = size.width - 20;
9092 }
9093
9094 safeWidth = this.$safeActions.is( ':visible' ) ? this.$safeActions.width() : 0;
9095 primaryWidth = this.$primaryActions.is( ':visible' ) ? this.$primaryActions.width() : 0;
9096 biggerWidth = Math.max( safeWidth, primaryWidth );
9097
9098 labelWidth = this.title.$element.width();
9099
9100 if ( 2 * biggerWidth + labelWidth < navigationWidth ) {
9101 // We have enough space to center the label
9102 leftWidth = rightWidth = biggerWidth;
9103 } else {
9104 // Let's hope we at least have enough space not to overlap, because we can't wrap the label…
9105 if ( this.getDir() === 'ltr' ) {
9106 leftWidth = safeWidth;
9107 rightWidth = primaryWidth;
9108 } else {
9109 leftWidth = primaryWidth;
9110 rightWidth = safeWidth;
9111 }
9112 }
9113
9114 this.$location.css( { paddingLeft: leftWidth, paddingRight: rightWidth } );
9115
9116 return this;
9117 };
9118
9119 /**
9120 * Handle errors that occurred during accept or reject processes.
9121 *
9122 * @private
9123 * @param {OO.ui.Error[]|OO.ui.Error} errors Errors to be handled
9124 */
9125 OO.ui.ProcessDialog.prototype.showErrors = function ( errors ) {
9126 var i, len, $item, actions,
9127 items = [],
9128 abilities = {},
9129 recoverable = true,
9130 warning = false;
9131
9132 if ( errors instanceof OO.ui.Error ) {
9133 errors = [ errors ];
9134 }
9135
9136 for ( i = 0, len = errors.length; i < len; i++ ) {
9137 if ( !errors[ i ].isRecoverable() ) {
9138 recoverable = false;
9139 }
9140 if ( errors[ i ].isWarning() ) {
9141 warning = true;
9142 }
9143 $item = $( '<div>' )
9144 .addClass( 'oo-ui-processDialog-error' )
9145 .append( errors[ i ].getMessage() );
9146 items.push( $item[ 0 ] );
9147 }
9148 this.$errorItems = $( items );
9149 if ( recoverable ) {
9150 abilities[ this.currentAction ] = true;
9151 // Copy the flags from the first matching action
9152 actions = this.actions.get( { actions: this.currentAction } );
9153 if ( actions.length ) {
9154 this.retryButton.clearFlags().setFlags( actions[ 0 ].getFlags() );
9155 }
9156 } else {
9157 abilities[ this.currentAction ] = false;
9158 this.actions.setAbilities( abilities );
9159 }
9160 if ( warning ) {
9161 this.retryButton.setLabel( OO.ui.msg( 'ooui-dialog-process-continue' ) );
9162 } else {
9163 this.retryButton.setLabel( OO.ui.msg( 'ooui-dialog-process-retry' ) );
9164 }
9165 this.retryButton.toggle( recoverable );
9166 this.$errorsTitle.after( this.$errorItems );
9167 this.$errors.removeClass( 'oo-ui-element-hidden' ).scrollTop( 0 );
9168 };
9169
9170 /**
9171 * Hide errors.
9172 *
9173 * @private
9174 */
9175 OO.ui.ProcessDialog.prototype.hideErrors = function () {
9176 this.$errors.addClass( 'oo-ui-element-hidden' );
9177 if ( this.$errorItems ) {
9178 this.$errorItems.remove();
9179 this.$errorItems = null;
9180 }
9181 };
9182
9183 /**
9184 * @inheritdoc
9185 */
9186 OO.ui.ProcessDialog.prototype.getTeardownProcess = function ( data ) {
9187 // Parent method
9188 return OO.ui.ProcessDialog.parent.prototype.getTeardownProcess.call( this, data )
9189 .first( function () {
9190 // Make sure to hide errors
9191 this.hideErrors();
9192 this.fitOnOpen = false;
9193 }, this );
9194 };
9195
9196 /**
9197 * FieldLayouts are used with OO.ui.FieldsetLayout. Each FieldLayout requires a field-widget,
9198 * which is a widget that is specified by reference before any optional configuration settings.
9199 *
9200 * Field layouts can be configured with help text and/or labels. Labels are aligned in one of four ways:
9201 *
9202 * - **left**: The label is placed before the field-widget and aligned with the left margin.
9203 * A left-alignment is used for forms with many fields.
9204 * - **right**: The label is placed before the field-widget and aligned to the right margin.
9205 * A right-alignment is used for long but familiar forms which users tab through,
9206 * verifying the current field with a quick glance at the label.
9207 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
9208 * that users fill out from top to bottom.
9209 * - **inline**: The label is placed after the field-widget and aligned to the left.
9210 * An inline-alignment is best used with checkboxes or radio buttons.
9211 *
9212 * Help text is accessed via a help icon that appears in the upper right corner of the rendered field layout.
9213 * Please see the [OOjs UI documentation on MediaWiki] [1] for examples and more information.
9214 *
9215 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Fields_and_Fieldsets
9216 * @class
9217 * @extends OO.ui.Layout
9218 * @mixins OO.ui.mixin.LabelElement
9219 * @mixins OO.ui.mixin.TitledElement
9220 *
9221 * @constructor
9222 * @param {OO.ui.Widget} fieldWidget Field widget
9223 * @param {Object} [config] Configuration options
9224 * @cfg {string} [align='left'] Alignment of the label: 'left', 'right', 'top' or 'inline'
9225 * @cfg {Array} [errors] Error messages about the widget, which will be displayed below the widget.
9226 * The array may contain strings or OO.ui.HtmlSnippet instances.
9227 * @cfg {Array} [notices] Notices about the widget, which will be displayed below the widget.
9228 * The array may contain strings or OO.ui.HtmlSnippet instances.
9229 * @cfg {string|OO.ui.HtmlSnippet} [help] Help text. When help text is specified, a "help" icon will appear
9230 * in the upper-right corner of the rendered field; clicking it will display the text in a popup.
9231 * For important messages, you are advised to use `notices`, as they are always shown.
9232 *
9233 * @throws {Error} An error is thrown if no widget is specified
9234 */
9235 OO.ui.FieldLayout = function OoUiFieldLayout( fieldWidget, config ) {
9236 var hasInputWidget, div;
9237
9238 // Allow passing positional parameters inside the config object
9239 if ( OO.isPlainObject( fieldWidget ) && config === undefined ) {
9240 config = fieldWidget;
9241 fieldWidget = config.fieldWidget;
9242 }
9243
9244 // Make sure we have required constructor arguments
9245 if ( fieldWidget === undefined ) {
9246 throw new Error( 'Widget not found' );
9247 }
9248
9249 hasInputWidget = fieldWidget.constructor.static.supportsSimpleLabel;
9250
9251 // Configuration initialization
9252 config = $.extend( { align: 'left' }, config );
9253
9254 // Parent constructor
9255 OO.ui.FieldLayout.parent.call( this, config );
9256
9257 // Mixin constructors
9258 OO.ui.mixin.LabelElement.call( this, config );
9259 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$label } ) );
9260
9261 // Properties
9262 this.fieldWidget = fieldWidget;
9263 this.errors = [];
9264 this.notices = [];
9265 this.$field = $( '<div>' );
9266 this.$messages = $( '<ul>' );
9267 this.$body = $( '<' + ( hasInputWidget ? 'label' : 'div' ) + '>' );
9268 this.align = null;
9269 if ( config.help ) {
9270 this.popupButtonWidget = new OO.ui.PopupButtonWidget( {
9271 classes: [ 'oo-ui-fieldLayout-help' ],
9272 framed: false,
9273 icon: 'info'
9274 } );
9275
9276 div = $( '<div>' );
9277 if ( config.help instanceof OO.ui.HtmlSnippet ) {
9278 div.html( config.help.toString() );
9279 } else {
9280 div.text( config.help );
9281 }
9282 this.popupButtonWidget.getPopup().$body.append(
9283 div.addClass( 'oo-ui-fieldLayout-help-content' )
9284 );
9285 this.$help = this.popupButtonWidget.$element;
9286 } else {
9287 this.$help = $( [] );
9288 }
9289
9290 // Events
9291 if ( hasInputWidget ) {
9292 this.$label.on( 'click', this.onLabelClick.bind( this ) );
9293 }
9294 this.fieldWidget.connect( this, { disable: 'onFieldDisable' } );
9295
9296 // Initialization
9297 this.$element
9298 .addClass( 'oo-ui-fieldLayout' )
9299 .append( this.$help, this.$body );
9300 this.$body.addClass( 'oo-ui-fieldLayout-body' );
9301 this.$messages.addClass( 'oo-ui-fieldLayout-messages' );
9302 this.$field
9303 .addClass( 'oo-ui-fieldLayout-field' )
9304 .toggleClass( 'oo-ui-fieldLayout-disable', this.fieldWidget.isDisabled() )
9305 .append( this.fieldWidget.$element );
9306
9307 this.setErrors( config.errors || [] );
9308 this.setNotices( config.notices || [] );
9309 this.setAlignment( config.align );
9310 };
9311
9312 /* Setup */
9313
9314 OO.inheritClass( OO.ui.FieldLayout, OO.ui.Layout );
9315 OO.mixinClass( OO.ui.FieldLayout, OO.ui.mixin.LabelElement );
9316 OO.mixinClass( OO.ui.FieldLayout, OO.ui.mixin.TitledElement );
9317
9318 /* Methods */
9319
9320 /**
9321 * Handle field disable events.
9322 *
9323 * @private
9324 * @param {boolean} value Field is disabled
9325 */
9326 OO.ui.FieldLayout.prototype.onFieldDisable = function ( value ) {
9327 this.$element.toggleClass( 'oo-ui-fieldLayout-disabled', value );
9328 };
9329
9330 /**
9331 * Handle label mouse click events.
9332 *
9333 * @private
9334 * @param {jQuery.Event} e Mouse click event
9335 */
9336 OO.ui.FieldLayout.prototype.onLabelClick = function () {
9337 this.fieldWidget.simulateLabelClick();
9338 return false;
9339 };
9340
9341 /**
9342 * Get the widget contained by the field.
9343 *
9344 * @return {OO.ui.Widget} Field widget
9345 */
9346 OO.ui.FieldLayout.prototype.getField = function () {
9347 return this.fieldWidget;
9348 };
9349
9350 /**
9351 * @protected
9352 * @param {string} kind 'error' or 'notice'
9353 * @param {string|OO.ui.HtmlSnippet} text
9354 * @return {jQuery}
9355 */
9356 OO.ui.FieldLayout.prototype.makeMessage = function ( kind, text ) {
9357 var $listItem, $icon, message;
9358 $listItem = $( '<li>' );
9359 if ( kind === 'error' ) {
9360 $icon = new OO.ui.IconWidget( { icon: 'alert', flags: [ 'warning' ] } ).$element;
9361 } else if ( kind === 'notice' ) {
9362 $icon = new OO.ui.IconWidget( { icon: 'info' } ).$element;
9363 } else {
9364 $icon = '';
9365 }
9366 message = new OO.ui.LabelWidget( { label: text } );
9367 $listItem
9368 .append( $icon, message.$element )
9369 .addClass( 'oo-ui-fieldLayout-messages-' + kind );
9370 return $listItem;
9371 };
9372
9373 /**
9374 * Set the field alignment mode.
9375 *
9376 * @private
9377 * @param {string} value Alignment mode, either 'left', 'right', 'top' or 'inline'
9378 * @chainable
9379 */
9380 OO.ui.FieldLayout.prototype.setAlignment = function ( value ) {
9381 if ( value !== this.align ) {
9382 // Default to 'left'
9383 if ( [ 'left', 'right', 'top', 'inline' ].indexOf( value ) === -1 ) {
9384 value = 'left';
9385 }
9386 // Reorder elements
9387 if ( value === 'inline' ) {
9388 this.$body.append( this.$field, this.$label );
9389 } else {
9390 this.$body.append( this.$label, this.$field );
9391 }
9392 // Set classes. The following classes can be used here:
9393 // * oo-ui-fieldLayout-align-left
9394 // * oo-ui-fieldLayout-align-right
9395 // * oo-ui-fieldLayout-align-top
9396 // * oo-ui-fieldLayout-align-inline
9397 if ( this.align ) {
9398 this.$element.removeClass( 'oo-ui-fieldLayout-align-' + this.align );
9399 }
9400 this.$element.addClass( 'oo-ui-fieldLayout-align-' + value );
9401 this.align = value;
9402 }
9403
9404 return this;
9405 };
9406
9407 /**
9408 * Set the list of error messages.
9409 *
9410 * @param {Array} errors Error messages about the widget, which will be displayed below the widget.
9411 * The array may contain strings or OO.ui.HtmlSnippet instances.
9412 * @chainable
9413 */
9414 OO.ui.FieldLayout.prototype.setErrors = function ( errors ) {
9415 this.errors = errors.slice();
9416 this.updateMessages();
9417 return this;
9418 };
9419
9420 /**
9421 * Set the list of notice messages.
9422 *
9423 * @param {Array} notices Notices about the widget, which will be displayed below the widget.
9424 * The array may contain strings or OO.ui.HtmlSnippet instances.
9425 * @chainable
9426 */
9427 OO.ui.FieldLayout.prototype.setNotices = function ( notices ) {
9428 this.notices = notices.slice();
9429 this.updateMessages();
9430 return this;
9431 };
9432
9433 /**
9434 * Update the rendering of error and notice messages.
9435 *
9436 * @private
9437 */
9438 OO.ui.FieldLayout.prototype.updateMessages = function () {
9439 var i;
9440 this.$messages.empty();
9441
9442 if ( this.errors.length || this.notices.length ) {
9443 this.$body.after( this.$messages );
9444 } else {
9445 this.$messages.remove();
9446 return;
9447 }
9448
9449 for ( i = 0; i < this.notices.length; i++ ) {
9450 this.$messages.append( this.makeMessage( 'notice', this.notices[ i ] ) );
9451 }
9452 for ( i = 0; i < this.errors.length; i++ ) {
9453 this.$messages.append( this.makeMessage( 'error', this.errors[ i ] ) );
9454 }
9455 };
9456
9457 /**
9458 * ActionFieldLayouts are used with OO.ui.FieldsetLayout. The layout consists of a field-widget, a button,
9459 * and an optional label and/or help text. The field-widget (e.g., a {@link OO.ui.TextInputWidget TextInputWidget}),
9460 * is required and is specified before any optional configuration settings.
9461 *
9462 * Labels can be aligned in one of four ways:
9463 *
9464 * - **left**: The label is placed before the field-widget and aligned with the left margin.
9465 * A left-alignment is used for forms with many fields.
9466 * - **right**: The label is placed before the field-widget and aligned to the right margin.
9467 * A right-alignment is used for long but familiar forms which users tab through,
9468 * verifying the current field with a quick glance at the label.
9469 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
9470 * that users fill out from top to bottom.
9471 * - **inline**: The label is placed after the field-widget and aligned to the left.
9472 * An inline-alignment is best used with checkboxes or radio buttons.
9473 *
9474 * Help text is accessed via a help icon that appears in the upper right corner of the rendered field layout when help
9475 * text is specified.
9476 *
9477 * @example
9478 * // Example of an ActionFieldLayout
9479 * var actionFieldLayout = new OO.ui.ActionFieldLayout(
9480 * new OO.ui.TextInputWidget( {
9481 * placeholder: 'Field widget'
9482 * } ),
9483 * new OO.ui.ButtonWidget( {
9484 * label: 'Button'
9485 * } ),
9486 * {
9487 * label: 'An ActionFieldLayout. This label is aligned top',
9488 * align: 'top',
9489 * help: 'This is help text'
9490 * }
9491 * );
9492 *
9493 * $( 'body' ).append( actionFieldLayout.$element );
9494 *
9495 * @class
9496 * @extends OO.ui.FieldLayout
9497 *
9498 * @constructor
9499 * @param {OO.ui.Widget} fieldWidget Field widget
9500 * @param {OO.ui.ButtonWidget} buttonWidget Button widget
9501 */
9502 OO.ui.ActionFieldLayout = function OoUiActionFieldLayout( fieldWidget, buttonWidget, config ) {
9503 // Allow passing positional parameters inside the config object
9504 if ( OO.isPlainObject( fieldWidget ) && config === undefined ) {
9505 config = fieldWidget;
9506 fieldWidget = config.fieldWidget;
9507 buttonWidget = config.buttonWidget;
9508 }
9509
9510 // Parent constructor
9511 OO.ui.ActionFieldLayout.parent.call( this, fieldWidget, config );
9512
9513 // Properties
9514 this.buttonWidget = buttonWidget;
9515 this.$button = $( '<div>' );
9516 this.$input = $( '<div>' );
9517
9518 // Initialization
9519 this.$element
9520 .addClass( 'oo-ui-actionFieldLayout' );
9521 this.$button
9522 .addClass( 'oo-ui-actionFieldLayout-button' )
9523 .append( this.buttonWidget.$element );
9524 this.$input
9525 .addClass( 'oo-ui-actionFieldLayout-input' )
9526 .append( this.fieldWidget.$element );
9527 this.$field
9528 .append( this.$input, this.$button );
9529 };
9530
9531 /* Setup */
9532
9533 OO.inheritClass( OO.ui.ActionFieldLayout, OO.ui.FieldLayout );
9534
9535 /**
9536 * FieldsetLayouts are composed of one or more {@link OO.ui.FieldLayout FieldLayouts},
9537 * which each contain an individual widget and, optionally, a label. Each Fieldset can be
9538 * configured with a label as well. For more information and examples,
9539 * please see the [OOjs UI documentation on MediaWiki][1].
9540 *
9541 * @example
9542 * // Example of a fieldset layout
9543 * var input1 = new OO.ui.TextInputWidget( {
9544 * placeholder: 'A text input field'
9545 * } );
9546 *
9547 * var input2 = new OO.ui.TextInputWidget( {
9548 * placeholder: 'A text input field'
9549 * } );
9550 *
9551 * var fieldset = new OO.ui.FieldsetLayout( {
9552 * label: 'Example of a fieldset layout'
9553 * } );
9554 *
9555 * fieldset.addItems( [
9556 * new OO.ui.FieldLayout( input1, {
9557 * label: 'Field One'
9558 * } ),
9559 * new OO.ui.FieldLayout( input2, {
9560 * label: 'Field Two'
9561 * } )
9562 * ] );
9563 * $( 'body' ).append( fieldset.$element );
9564 *
9565 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Fields_and_Fieldsets
9566 *
9567 * @class
9568 * @extends OO.ui.Layout
9569 * @mixins OO.ui.mixin.IconElement
9570 * @mixins OO.ui.mixin.LabelElement
9571 * @mixins OO.ui.mixin.GroupElement
9572 *
9573 * @constructor
9574 * @param {Object} [config] Configuration options
9575 * @cfg {OO.ui.FieldLayout[]} [items] An array of fields to add to the fieldset. See OO.ui.FieldLayout for more information about fields.
9576 */
9577 OO.ui.FieldsetLayout = function OoUiFieldsetLayout( config ) {
9578 // Configuration initialization
9579 config = config || {};
9580
9581 // Parent constructor
9582 OO.ui.FieldsetLayout.parent.call( this, config );
9583
9584 // Mixin constructors
9585 OO.ui.mixin.IconElement.call( this, config );
9586 OO.ui.mixin.LabelElement.call( this, config );
9587 OO.ui.mixin.GroupElement.call( this, config );
9588
9589 if ( config.help ) {
9590 this.popupButtonWidget = new OO.ui.PopupButtonWidget( {
9591 classes: [ 'oo-ui-fieldsetLayout-help' ],
9592 framed: false,
9593 icon: 'info'
9594 } );
9595
9596 this.popupButtonWidget.getPopup().$body.append(
9597 $( '<div>' )
9598 .text( config.help )
9599 .addClass( 'oo-ui-fieldsetLayout-help-content' )
9600 );
9601 this.$help = this.popupButtonWidget.$element;
9602 } else {
9603 this.$help = $( [] );
9604 }
9605
9606 // Initialization
9607 this.$element
9608 .addClass( 'oo-ui-fieldsetLayout' )
9609 .prepend( this.$help, this.$icon, this.$label, this.$group );
9610 if ( Array.isArray( config.items ) ) {
9611 this.addItems( config.items );
9612 }
9613 };
9614
9615 /* Setup */
9616
9617 OO.inheritClass( OO.ui.FieldsetLayout, OO.ui.Layout );
9618 OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.mixin.IconElement );
9619 OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.mixin.LabelElement );
9620 OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.mixin.GroupElement );
9621
9622 /**
9623 * FormLayouts are used to wrap {@link OO.ui.FieldsetLayout FieldsetLayouts} when you intend to use browser-based
9624 * form submission for the fields instead of handling them in JavaScript. Form layouts can be configured with an
9625 * HTML form action, an encoding type, and a method using the #action, #enctype, and #method configs, respectively.
9626 * See the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
9627 *
9628 * Only widgets from the {@link OO.ui.InputWidget InputWidget} family support form submission. It
9629 * includes standard form elements like {@link OO.ui.CheckboxInputWidget checkboxes}, {@link
9630 * OO.ui.RadioInputWidget radio buttons} and {@link OO.ui.TextInputWidget text fields}, as well as
9631 * some fancier controls. Some controls have both regular and InputWidget variants, for example
9632 * OO.ui.DropdownWidget and OO.ui.DropdownInputWidget – only the latter support form submission and
9633 * often have simplified APIs to match the capabilities of HTML forms.
9634 * See the [OOjs UI Inputs documentation on MediaWiki] [2] for more information about InputWidgets.
9635 *
9636 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Forms
9637 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
9638 *
9639 * @example
9640 * // Example of a form layout that wraps a fieldset layout
9641 * var input1 = new OO.ui.TextInputWidget( {
9642 * placeholder: 'Username'
9643 * } );
9644 * var input2 = new OO.ui.TextInputWidget( {
9645 * placeholder: 'Password',
9646 * type: 'password'
9647 * } );
9648 * var submit = new OO.ui.ButtonInputWidget( {
9649 * label: 'Submit'
9650 * } );
9651 *
9652 * var fieldset = new OO.ui.FieldsetLayout( {
9653 * label: 'A form layout'
9654 * } );
9655 * fieldset.addItems( [
9656 * new OO.ui.FieldLayout( input1, {
9657 * label: 'Username',
9658 * align: 'top'
9659 * } ),
9660 * new OO.ui.FieldLayout( input2, {
9661 * label: 'Password',
9662 * align: 'top'
9663 * } ),
9664 * new OO.ui.FieldLayout( submit )
9665 * ] );
9666 * var form = new OO.ui.FormLayout( {
9667 * items: [ fieldset ],
9668 * action: '/api/formhandler',
9669 * method: 'get'
9670 * } )
9671 * $( 'body' ).append( form.$element );
9672 *
9673 * @class
9674 * @extends OO.ui.Layout
9675 * @mixins OO.ui.mixin.GroupElement
9676 *
9677 * @constructor
9678 * @param {Object} [config] Configuration options
9679 * @cfg {string} [method] HTML form `method` attribute
9680 * @cfg {string} [action] HTML form `action` attribute
9681 * @cfg {string} [enctype] HTML form `enctype` attribute
9682 * @cfg {OO.ui.FieldsetLayout[]} [items] Fieldset layouts to add to the form layout.
9683 */
9684 OO.ui.FormLayout = function OoUiFormLayout( config ) {
9685 // Configuration initialization
9686 config = config || {};
9687
9688 // Parent constructor
9689 OO.ui.FormLayout.parent.call( this, config );
9690
9691 // Mixin constructors
9692 OO.ui.mixin.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) );
9693
9694 // Events
9695 this.$element.on( 'submit', this.onFormSubmit.bind( this ) );
9696
9697 // Make sure the action is safe
9698 if ( config.action !== undefined && !OO.ui.isSafeUrl( config.action ) ) {
9699 throw new Error( 'Potentially unsafe action provided: ' + config.action );
9700 }
9701
9702 // Initialization
9703 this.$element
9704 .addClass( 'oo-ui-formLayout' )
9705 .attr( {
9706 method: config.method,
9707 action: config.action,
9708 enctype: config.enctype
9709 } );
9710 if ( Array.isArray( config.items ) ) {
9711 this.addItems( config.items );
9712 }
9713 };
9714
9715 /* Setup */
9716
9717 OO.inheritClass( OO.ui.FormLayout, OO.ui.Layout );
9718 OO.mixinClass( OO.ui.FormLayout, OO.ui.mixin.GroupElement );
9719
9720 /* Events */
9721
9722 /**
9723 * A 'submit' event is emitted when the form is submitted.
9724 *
9725 * @event submit
9726 */
9727
9728 /* Static Properties */
9729
9730 OO.ui.FormLayout.static.tagName = 'form';
9731
9732 /* Methods */
9733
9734 /**
9735 * Handle form submit events.
9736 *
9737 * @private
9738 * @param {jQuery.Event} e Submit event
9739 * @fires submit
9740 */
9741 OO.ui.FormLayout.prototype.onFormSubmit = function () {
9742 if ( this.emit( 'submit' ) ) {
9743 return false;
9744 }
9745 };
9746
9747 /**
9748 * 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)
9749 * and its size is customized with the #menuSize config. The content area will fill all remaining space.
9750 *
9751 * @example
9752 * var menuLayout = new OO.ui.MenuLayout( {
9753 * position: 'top'
9754 * } ),
9755 * menuPanel = new OO.ui.PanelLayout( { padded: true, expanded: true, scrollable: true } ),
9756 * contentPanel = new OO.ui.PanelLayout( { padded: true, expanded: true, scrollable: true } ),
9757 * select = new OO.ui.SelectWidget( {
9758 * items: [
9759 * new OO.ui.OptionWidget( {
9760 * data: 'before',
9761 * label: 'Before',
9762 * } ),
9763 * new OO.ui.OptionWidget( {
9764 * data: 'after',
9765 * label: 'After',
9766 * } ),
9767 * new OO.ui.OptionWidget( {
9768 * data: 'top',
9769 * label: 'Top',
9770 * } ),
9771 * new OO.ui.OptionWidget( {
9772 * data: 'bottom',
9773 * label: 'Bottom',
9774 * } )
9775 * ]
9776 * } ).on( 'select', function ( item ) {
9777 * menuLayout.setMenuPosition( item.getData() );
9778 * } );
9779 *
9780 * menuLayout.$menu.append(
9781 * menuPanel.$element.append( '<b>Menu panel</b>', select.$element )
9782 * );
9783 * menuLayout.$content.append(
9784 * contentPanel.$element.append( '<b>Content panel</b>', '<p>Note that the menu is positioned relative to the content panel: top, bottom, after, before.</p>')
9785 * );
9786 * $( 'body' ).append( menuLayout.$element );
9787 *
9788 * If menu size needs to be overridden, it can be accomplished using CSS similar to the snippet
9789 * below. MenuLayout's CSS will override the appropriate values with 'auto' or '0' to display the
9790 * menu correctly. If `menuPosition` is known beforehand, CSS rules corresponding to other positions
9791 * may be omitted.
9792 *
9793 * .oo-ui-menuLayout-menu {
9794 * height: 200px;
9795 * width: 200px;
9796 * }
9797 * .oo-ui-menuLayout-content {
9798 * top: 200px;
9799 * left: 200px;
9800 * right: 200px;
9801 * bottom: 200px;
9802 * }
9803 *
9804 * @class
9805 * @extends OO.ui.Layout
9806 *
9807 * @constructor
9808 * @param {Object} [config] Configuration options
9809 * @cfg {boolean} [showMenu=true] Show menu
9810 * @cfg {string} [menuPosition='before'] Position of menu: `top`, `after`, `bottom` or `before`
9811 */
9812 OO.ui.MenuLayout = function OoUiMenuLayout( config ) {
9813 // Configuration initialization
9814 config = $.extend( {
9815 showMenu: true,
9816 menuPosition: 'before'
9817 }, config );
9818
9819 // Parent constructor
9820 OO.ui.MenuLayout.parent.call( this, config );
9821
9822 /**
9823 * Menu DOM node
9824 *
9825 * @property {jQuery}
9826 */
9827 this.$menu = $( '<div>' );
9828 /**
9829 * Content DOM node
9830 *
9831 * @property {jQuery}
9832 */
9833 this.$content = $( '<div>' );
9834
9835 // Initialization
9836 this.$menu
9837 .addClass( 'oo-ui-menuLayout-menu' );
9838 this.$content.addClass( 'oo-ui-menuLayout-content' );
9839 this.$element
9840 .addClass( 'oo-ui-menuLayout' )
9841 .append( this.$content, this.$menu );
9842 this.setMenuPosition( config.menuPosition );
9843 this.toggleMenu( config.showMenu );
9844 };
9845
9846 /* Setup */
9847
9848 OO.inheritClass( OO.ui.MenuLayout, OO.ui.Layout );
9849
9850 /* Methods */
9851
9852 /**
9853 * Toggle menu.
9854 *
9855 * @param {boolean} showMenu Show menu, omit to toggle
9856 * @chainable
9857 */
9858 OO.ui.MenuLayout.prototype.toggleMenu = function ( showMenu ) {
9859 showMenu = showMenu === undefined ? !this.showMenu : !!showMenu;
9860
9861 if ( this.showMenu !== showMenu ) {
9862 this.showMenu = showMenu;
9863 this.$element
9864 .toggleClass( 'oo-ui-menuLayout-showMenu', this.showMenu )
9865 .toggleClass( 'oo-ui-menuLayout-hideMenu', !this.showMenu );
9866 }
9867
9868 return this;
9869 };
9870
9871 /**
9872 * Check if menu is visible
9873 *
9874 * @return {boolean} Menu is visible
9875 */
9876 OO.ui.MenuLayout.prototype.isMenuVisible = function () {
9877 return this.showMenu;
9878 };
9879
9880 /**
9881 * Set menu position.
9882 *
9883 * @param {string} position Position of menu, either `top`, `after`, `bottom` or `before`
9884 * @throws {Error} If position value is not supported
9885 * @chainable
9886 */
9887 OO.ui.MenuLayout.prototype.setMenuPosition = function ( position ) {
9888 this.$element.removeClass( 'oo-ui-menuLayout-' + this.menuPosition );
9889 this.menuPosition = position;
9890 this.$element.addClass( 'oo-ui-menuLayout-' + position );
9891
9892 return this;
9893 };
9894
9895 /**
9896 * Get menu position.
9897 *
9898 * @return {string} Menu position
9899 */
9900 OO.ui.MenuLayout.prototype.getMenuPosition = function () {
9901 return this.menuPosition;
9902 };
9903
9904 /**
9905 * BookletLayouts contain {@link OO.ui.PageLayout page layouts} as well as
9906 * an {@link OO.ui.OutlineSelectWidget outline} that allows users to easily navigate
9907 * through the pages and select which one to display. By default, only one page is
9908 * displayed at a time and the outline is hidden. When a user navigates to a new page,
9909 * the booklet layout automatically focuses on the first focusable element, unless the
9910 * default setting is changed. Optionally, booklets can be configured to show
9911 * {@link OO.ui.OutlineControlsWidget controls} for adding, moving, and removing items.
9912 *
9913 * @example
9914 * // Example of a BookletLayout that contains two PageLayouts.
9915 *
9916 * function PageOneLayout( name, config ) {
9917 * PageOneLayout.parent.call( this, name, config );
9918 * this.$element.append( '<p>First page</p><p>(This booklet has an outline, displayed on the left)</p>' );
9919 * }
9920 * OO.inheritClass( PageOneLayout, OO.ui.PageLayout );
9921 * PageOneLayout.prototype.setupOutlineItem = function () {
9922 * this.outlineItem.setLabel( 'Page One' );
9923 * };
9924 *
9925 * function PageTwoLayout( name, config ) {
9926 * PageTwoLayout.parent.call( this, name, config );
9927 * this.$element.append( '<p>Second page</p>' );
9928 * }
9929 * OO.inheritClass( PageTwoLayout, OO.ui.PageLayout );
9930 * PageTwoLayout.prototype.setupOutlineItem = function () {
9931 * this.outlineItem.setLabel( 'Page Two' );
9932 * };
9933 *
9934 * var page1 = new PageOneLayout( 'one' ),
9935 * page2 = new PageTwoLayout( 'two' );
9936 *
9937 * var booklet = new OO.ui.BookletLayout( {
9938 * outlined: true
9939 * } );
9940 *
9941 * booklet.addPages ( [ page1, page2 ] );
9942 * $( 'body' ).append( booklet.$element );
9943 *
9944 * @class
9945 * @extends OO.ui.MenuLayout
9946 *
9947 * @constructor
9948 * @param {Object} [config] Configuration options
9949 * @cfg {boolean} [continuous=false] Show all pages, one after another
9950 * @cfg {boolean} [autoFocus=true] Focus on the first focusable element when a new page is displayed.
9951 * @cfg {boolean} [outlined=false] Show the outline. The outline is used to navigate through the pages of the booklet.
9952 * @cfg {boolean} [editable=false] Show controls for adding, removing and reordering pages
9953 */
9954 OO.ui.BookletLayout = function OoUiBookletLayout( config ) {
9955 // Configuration initialization
9956 config = config || {};
9957
9958 // Parent constructor
9959 OO.ui.BookletLayout.parent.call( this, config );
9960
9961 // Properties
9962 this.currentPageName = null;
9963 this.pages = {};
9964 this.ignoreFocus = false;
9965 this.stackLayout = new OO.ui.StackLayout( { continuous: !!config.continuous } );
9966 this.$content.append( this.stackLayout.$element );
9967 this.autoFocus = config.autoFocus === undefined || !!config.autoFocus;
9968 this.outlineVisible = false;
9969 this.outlined = !!config.outlined;
9970 if ( this.outlined ) {
9971 this.editable = !!config.editable;
9972 this.outlineControlsWidget = null;
9973 this.outlineSelectWidget = new OO.ui.OutlineSelectWidget();
9974 this.outlinePanel = new OO.ui.PanelLayout( { scrollable: true } );
9975 this.$menu.append( this.outlinePanel.$element );
9976 this.outlineVisible = true;
9977 if ( this.editable ) {
9978 this.outlineControlsWidget = new OO.ui.OutlineControlsWidget(
9979 this.outlineSelectWidget
9980 );
9981 }
9982 }
9983 this.toggleMenu( this.outlined );
9984
9985 // Events
9986 this.stackLayout.connect( this, { set: 'onStackLayoutSet' } );
9987 if ( this.outlined ) {
9988 this.outlineSelectWidget.connect( this, { select: 'onOutlineSelectWidgetSelect' } );
9989 this.scrolling = false;
9990 this.stackLayout.connect( this, { visibleItemChange: 'onStackLayoutVisibleItemChange' } );
9991 }
9992 if ( this.autoFocus ) {
9993 // Event 'focus' does not bubble, but 'focusin' does
9994 this.stackLayout.$element.on( 'focusin', this.onStackLayoutFocus.bind( this ) );
9995 }
9996
9997 // Initialization
9998 this.$element.addClass( 'oo-ui-bookletLayout' );
9999 this.stackLayout.$element.addClass( 'oo-ui-bookletLayout-stackLayout' );
10000 if ( this.outlined ) {
10001 this.outlinePanel.$element
10002 .addClass( 'oo-ui-bookletLayout-outlinePanel' )
10003 .append( this.outlineSelectWidget.$element );
10004 if ( this.editable ) {
10005 this.outlinePanel.$element
10006 .addClass( 'oo-ui-bookletLayout-outlinePanel-editable' )
10007 .append( this.outlineControlsWidget.$element );
10008 }
10009 }
10010 };
10011
10012 /* Setup */
10013
10014 OO.inheritClass( OO.ui.BookletLayout, OO.ui.MenuLayout );
10015
10016 /* Events */
10017
10018 /**
10019 * A 'set' event is emitted when a page is {@link #setPage set} to be displayed by the booklet layout.
10020 * @event set
10021 * @param {OO.ui.PageLayout} page Current page
10022 */
10023
10024 /**
10025 * An 'add' event is emitted when pages are {@link #addPages added} to the booklet layout.
10026 *
10027 * @event add
10028 * @param {OO.ui.PageLayout[]} page Added pages
10029 * @param {number} index Index pages were added at
10030 */
10031
10032 /**
10033 * A 'remove' event is emitted when pages are {@link #clearPages cleared} or
10034 * {@link #removePages removed} from the booklet.
10035 *
10036 * @event remove
10037 * @param {OO.ui.PageLayout[]} pages Removed pages
10038 */
10039
10040 /* Methods */
10041
10042 /**
10043 * Handle stack layout focus.
10044 *
10045 * @private
10046 * @param {jQuery.Event} e Focusin event
10047 */
10048 OO.ui.BookletLayout.prototype.onStackLayoutFocus = function ( e ) {
10049 var name, $target;
10050
10051 // Find the page that an element was focused within
10052 $target = $( e.target ).closest( '.oo-ui-pageLayout' );
10053 for ( name in this.pages ) {
10054 // Check for page match, exclude current page to find only page changes
10055 if ( this.pages[ name ].$element[ 0 ] === $target[ 0 ] && name !== this.currentPageName ) {
10056 this.setPage( name );
10057 break;
10058 }
10059 }
10060 };
10061
10062 /**
10063 * Handle visibleItemChange events from the stackLayout
10064 *
10065 * The next visible page is set as the current page by selecting it
10066 * in the outline
10067 *
10068 * @param {OO.ui.PageLayout} page The next visible page in the layout
10069 */
10070 OO.ui.BookletLayout.prototype.onStackLayoutVisibleItemChange = function ( page ) {
10071 // Set a flag to so that the resulting call to #onStackLayoutSet doesn't
10072 // try and scroll the item into view again.
10073 this.scrolling = true;
10074 this.outlineSelectWidget.selectItemByData( page.getName() );
10075 this.scrolling = false;
10076 };
10077
10078 /**
10079 * Handle stack layout set events.
10080 *
10081 * @private
10082 * @param {OO.ui.PanelLayout|null} page The page panel that is now the current panel
10083 */
10084 OO.ui.BookletLayout.prototype.onStackLayoutSet = function ( page ) {
10085 var layout = this;
10086 if ( !this.scrolling && page ) {
10087 page.scrollElementIntoView( { complete: function () {
10088 if ( layout.autoFocus ) {
10089 layout.focus();
10090 }
10091 } } );
10092 }
10093 };
10094
10095 /**
10096 * Focus the first input in the current page.
10097 *
10098 * If no page is selected, the first selectable page will be selected.
10099 * If the focus is already in an element on the current page, nothing will happen.
10100 * @param {number} [itemIndex] A specific item to focus on
10101 */
10102 OO.ui.BookletLayout.prototype.focus = function ( itemIndex ) {
10103 var page,
10104 items = this.stackLayout.getItems();
10105
10106 if ( itemIndex !== undefined && items[ itemIndex ] ) {
10107 page = items[ itemIndex ];
10108 } else {
10109 page = this.stackLayout.getCurrentItem();
10110 }
10111
10112 if ( !page && this.outlined ) {
10113 this.selectFirstSelectablePage();
10114 page = this.stackLayout.getCurrentItem();
10115 }
10116 if ( !page ) {
10117 return;
10118 }
10119 // Only change the focus if is not already in the current page
10120 if ( !OO.ui.contains( page.$element[ 0 ], this.getElementDocument().activeElement, true ) ) {
10121 page.focus();
10122 }
10123 };
10124
10125 /**
10126 * Find the first focusable input in the booklet layout and focus
10127 * on it.
10128 */
10129 OO.ui.BookletLayout.prototype.focusFirstFocusable = function () {
10130 OO.ui.findFocusable( this.stackLayout.$element ).focus();
10131 };
10132
10133 /**
10134 * Handle outline widget select events.
10135 *
10136 * @private
10137 * @param {OO.ui.OptionWidget|null} item Selected item
10138 */
10139 OO.ui.BookletLayout.prototype.onOutlineSelectWidgetSelect = function ( item ) {
10140 if ( item ) {
10141 this.setPage( item.getData() );
10142 }
10143 };
10144
10145 /**
10146 * Check if booklet has an outline.
10147 *
10148 * @return {boolean} Booklet has an outline
10149 */
10150 OO.ui.BookletLayout.prototype.isOutlined = function () {
10151 return this.outlined;
10152 };
10153
10154 /**
10155 * Check if booklet has editing controls.
10156 *
10157 * @return {boolean} Booklet is editable
10158 */
10159 OO.ui.BookletLayout.prototype.isEditable = function () {
10160 return this.editable;
10161 };
10162
10163 /**
10164 * Check if booklet has a visible outline.
10165 *
10166 * @return {boolean} Outline is visible
10167 */
10168 OO.ui.BookletLayout.prototype.isOutlineVisible = function () {
10169 return this.outlined && this.outlineVisible;
10170 };
10171
10172 /**
10173 * Hide or show the outline.
10174 *
10175 * @param {boolean} [show] Show outline, omit to invert current state
10176 * @chainable
10177 */
10178 OO.ui.BookletLayout.prototype.toggleOutline = function ( show ) {
10179 if ( this.outlined ) {
10180 show = show === undefined ? !this.outlineVisible : !!show;
10181 this.outlineVisible = show;
10182 this.toggleMenu( show );
10183 }
10184
10185 return this;
10186 };
10187
10188 /**
10189 * Get the page closest to the specified page.
10190 *
10191 * @param {OO.ui.PageLayout} page Page to use as a reference point
10192 * @return {OO.ui.PageLayout|null} Page closest to the specified page
10193 */
10194 OO.ui.BookletLayout.prototype.getClosestPage = function ( page ) {
10195 var next, prev, level,
10196 pages = this.stackLayout.getItems(),
10197 index = pages.indexOf( page );
10198
10199 if ( index !== -1 ) {
10200 next = pages[ index + 1 ];
10201 prev = pages[ index - 1 ];
10202 // Prefer adjacent pages at the same level
10203 if ( this.outlined ) {
10204 level = this.outlineSelectWidget.getItemFromData( page.getName() ).getLevel();
10205 if (
10206 prev &&
10207 level === this.outlineSelectWidget.getItemFromData( prev.getName() ).getLevel()
10208 ) {
10209 return prev;
10210 }
10211 if (
10212 next &&
10213 level === this.outlineSelectWidget.getItemFromData( next.getName() ).getLevel()
10214 ) {
10215 return next;
10216 }
10217 }
10218 }
10219 return prev || next || null;
10220 };
10221
10222 /**
10223 * Get the outline widget.
10224 *
10225 * If the booklet is not outlined, the method will return `null`.
10226 *
10227 * @return {OO.ui.OutlineSelectWidget|null} Outline widget, or null if the booklet is not outlined
10228 */
10229 OO.ui.BookletLayout.prototype.getOutline = function () {
10230 return this.outlineSelectWidget;
10231 };
10232
10233 /**
10234 * Get the outline controls widget.
10235 *
10236 * If the outline is not editable, the method will return `null`.
10237 *
10238 * @return {OO.ui.OutlineControlsWidget|null} The outline controls widget.
10239 */
10240 OO.ui.BookletLayout.prototype.getOutlineControls = function () {
10241 return this.outlineControlsWidget;
10242 };
10243
10244 /**
10245 * Get a page by its symbolic name.
10246 *
10247 * @param {string} name Symbolic name of page
10248 * @return {OO.ui.PageLayout|undefined} Page, if found
10249 */
10250 OO.ui.BookletLayout.prototype.getPage = function ( name ) {
10251 return this.pages[ name ];
10252 };
10253
10254 /**
10255 * Get the current page.
10256 *
10257 * @return {OO.ui.PageLayout|undefined} Current page, if found
10258 */
10259 OO.ui.BookletLayout.prototype.getCurrentPage = function () {
10260 var name = this.getCurrentPageName();
10261 return name ? this.getPage( name ) : undefined;
10262 };
10263
10264 /**
10265 * Get the symbolic name of the current page.
10266 *
10267 * @return {string|null} Symbolic name of the current page
10268 */
10269 OO.ui.BookletLayout.prototype.getCurrentPageName = function () {
10270 return this.currentPageName;
10271 };
10272
10273 /**
10274 * Add pages to the booklet layout
10275 *
10276 * When pages are added with the same names as existing pages, the existing pages will be
10277 * automatically removed before the new pages are added.
10278 *
10279 * @param {OO.ui.PageLayout[]} pages Pages to add
10280 * @param {number} index Index of the insertion point
10281 * @fires add
10282 * @chainable
10283 */
10284 OO.ui.BookletLayout.prototype.addPages = function ( pages, index ) {
10285 var i, len, name, page, item, currentIndex,
10286 stackLayoutPages = this.stackLayout.getItems(),
10287 remove = [],
10288 items = [];
10289
10290 // Remove pages with same names
10291 for ( i = 0, len = pages.length; i < len; i++ ) {
10292 page = pages[ i ];
10293 name = page.getName();
10294
10295 if ( Object.prototype.hasOwnProperty.call( this.pages, name ) ) {
10296 // Correct the insertion index
10297 currentIndex = stackLayoutPages.indexOf( this.pages[ name ] );
10298 if ( currentIndex !== -1 && currentIndex + 1 < index ) {
10299 index--;
10300 }
10301 remove.push( this.pages[ name ] );
10302 }
10303 }
10304 if ( remove.length ) {
10305 this.removePages( remove );
10306 }
10307
10308 // Add new pages
10309 for ( i = 0, len = pages.length; i < len; i++ ) {
10310 page = pages[ i ];
10311 name = page.getName();
10312 this.pages[ page.getName() ] = page;
10313 if ( this.outlined ) {
10314 item = new OO.ui.OutlineOptionWidget( { data: name } );
10315 page.setOutlineItem( item );
10316 items.push( item );
10317 }
10318 }
10319
10320 if ( this.outlined && items.length ) {
10321 this.outlineSelectWidget.addItems( items, index );
10322 this.selectFirstSelectablePage();
10323 }
10324 this.stackLayout.addItems( pages, index );
10325 this.emit( 'add', pages, index );
10326
10327 return this;
10328 };
10329
10330 /**
10331 * Remove the specified pages from the booklet layout.
10332 *
10333 * To remove all pages from the booklet, you may wish to use the #clearPages method instead.
10334 *
10335 * @param {OO.ui.PageLayout[]} pages An array of pages to remove
10336 * @fires remove
10337 * @chainable
10338 */
10339 OO.ui.BookletLayout.prototype.removePages = function ( pages ) {
10340 var i, len, name, page,
10341 items = [];
10342
10343 for ( i = 0, len = pages.length; i < len; i++ ) {
10344 page = pages[ i ];
10345 name = page.getName();
10346 delete this.pages[ name ];
10347 if ( this.outlined ) {
10348 items.push( this.outlineSelectWidget.getItemFromData( name ) );
10349 page.setOutlineItem( null );
10350 }
10351 }
10352 if ( this.outlined && items.length ) {
10353 this.outlineSelectWidget.removeItems( items );
10354 this.selectFirstSelectablePage();
10355 }
10356 this.stackLayout.removeItems( pages );
10357 this.emit( 'remove', pages );
10358
10359 return this;
10360 };
10361
10362 /**
10363 * Clear all pages from the booklet layout.
10364 *
10365 * To remove only a subset of pages from the booklet, use the #removePages method.
10366 *
10367 * @fires remove
10368 * @chainable
10369 */
10370 OO.ui.BookletLayout.prototype.clearPages = function () {
10371 var i, len,
10372 pages = this.stackLayout.getItems();
10373
10374 this.pages = {};
10375 this.currentPageName = null;
10376 if ( this.outlined ) {
10377 this.outlineSelectWidget.clearItems();
10378 for ( i = 0, len = pages.length; i < len; i++ ) {
10379 pages[ i ].setOutlineItem( null );
10380 }
10381 }
10382 this.stackLayout.clearItems();
10383
10384 this.emit( 'remove', pages );
10385
10386 return this;
10387 };
10388
10389 /**
10390 * Set the current page by symbolic name.
10391 *
10392 * @fires set
10393 * @param {string} name Symbolic name of page
10394 */
10395 OO.ui.BookletLayout.prototype.setPage = function ( name ) {
10396 var selectedItem,
10397 $focused,
10398 page = this.pages[ name ],
10399 previousPage = this.currentPageName && this.pages[ this.currentPageName ];
10400
10401 if ( name !== this.currentPageName ) {
10402 if ( this.outlined ) {
10403 selectedItem = this.outlineSelectWidget.getSelectedItem();
10404 if ( selectedItem && selectedItem.getData() !== name ) {
10405 this.outlineSelectWidget.selectItemByData( name );
10406 }
10407 }
10408 if ( page ) {
10409 if ( previousPage ) {
10410 previousPage.setActive( false );
10411 // Blur anything focused if the next page doesn't have anything focusable.
10412 // This is not needed if the next page has something focusable (because once it is focused
10413 // this blur happens automatically). If the layout is non-continuous, this check is
10414 // meaningless because the next page is not visible yet and thus can't hold focus.
10415 if (
10416 this.autoFocus &&
10417 this.stackLayout.continuous &&
10418 OO.ui.findFocusable( page.$element ).length !== 0
10419 ) {
10420 $focused = previousPage.$element.find( ':focus' );
10421 if ( $focused.length ) {
10422 $focused[ 0 ].blur();
10423 }
10424 }
10425 }
10426 this.currentPageName = name;
10427 page.setActive( true );
10428 this.stackLayout.setItem( page );
10429 if ( !this.stackLayout.continuous && previousPage ) {
10430 // This should not be necessary, since any inputs on the previous page should have been
10431 // blurred when it was hidden, but browsers are not very consistent about this.
10432 $focused = previousPage.$element.find( ':focus' );
10433 if ( $focused.length ) {
10434 $focused[ 0 ].blur();
10435 }
10436 }
10437 this.emit( 'set', page );
10438 }
10439 }
10440 };
10441
10442 /**
10443 * Select the first selectable page.
10444 *
10445 * @chainable
10446 */
10447 OO.ui.BookletLayout.prototype.selectFirstSelectablePage = function () {
10448 if ( !this.outlineSelectWidget.getSelectedItem() ) {
10449 this.outlineSelectWidget.selectItem( this.outlineSelectWidget.getFirstSelectableItem() );
10450 }
10451
10452 return this;
10453 };
10454
10455 /**
10456 * IndexLayouts contain {@link OO.ui.CardLayout card layouts} as well as
10457 * {@link OO.ui.TabSelectWidget tabs} that allow users to easily navigate through the cards and
10458 * select which one to display. By default, only one card is displayed at a time. When a user
10459 * navigates to a new card, the index layout automatically focuses on the first focusable element,
10460 * unless the default setting is changed.
10461 *
10462 * TODO: This class is similar to BookletLayout, we may want to refactor to reduce duplication
10463 *
10464 * @example
10465 * // Example of a IndexLayout that contains two CardLayouts.
10466 *
10467 * function CardOneLayout( name, config ) {
10468 * CardOneLayout.parent.call( this, name, config );
10469 * this.$element.append( '<p>First card</p>' );
10470 * }
10471 * OO.inheritClass( CardOneLayout, OO.ui.CardLayout );
10472 * CardOneLayout.prototype.setupTabItem = function () {
10473 * this.tabItem.setLabel( 'Card one' );
10474 * };
10475 *
10476 * var card1 = new CardOneLayout( 'one' ),
10477 * card2 = new CardLayout( 'two', { label: 'Card two' } );
10478 *
10479 * card2.$element.append( '<p>Second card</p>' );
10480 *
10481 * var index = new OO.ui.IndexLayout();
10482 *
10483 * index.addCards ( [ card1, card2 ] );
10484 * $( 'body' ).append( index.$element );
10485 *
10486 * @class
10487 * @extends OO.ui.MenuLayout
10488 *
10489 * @constructor
10490 * @param {Object} [config] Configuration options
10491 * @cfg {boolean} [continuous=false] Show all cards, one after another
10492 * @cfg {boolean} [expanded=true] Expand the content panel to fill the entire parent element.
10493 * @cfg {boolean} [autoFocus=true] Focus on the first focusable element when a new card is displayed.
10494 */
10495 OO.ui.IndexLayout = function OoUiIndexLayout( config ) {
10496 // Configuration initialization
10497 config = $.extend( {}, config, { menuPosition: 'top' } );
10498
10499 // Parent constructor
10500 OO.ui.IndexLayout.parent.call( this, config );
10501
10502 // Properties
10503 this.currentCardName = null;
10504 this.cards = {};
10505 this.ignoreFocus = false;
10506 this.stackLayout = new OO.ui.StackLayout( {
10507 continuous: !!config.continuous,
10508 expanded: config.expanded
10509 } );
10510 this.$content.append( this.stackLayout.$element );
10511 this.autoFocus = config.autoFocus === undefined || !!config.autoFocus;
10512
10513 this.tabSelectWidget = new OO.ui.TabSelectWidget();
10514 this.tabPanel = new OO.ui.PanelLayout();
10515 this.$menu.append( this.tabPanel.$element );
10516
10517 this.toggleMenu( true );
10518
10519 // Events
10520 this.stackLayout.connect( this, { set: 'onStackLayoutSet' } );
10521 this.tabSelectWidget.connect( this, { select: 'onTabSelectWidgetSelect' } );
10522 if ( this.autoFocus ) {
10523 // Event 'focus' does not bubble, but 'focusin' does
10524 this.stackLayout.$element.on( 'focusin', this.onStackLayoutFocus.bind( this ) );
10525 }
10526
10527 // Initialization
10528 this.$element.addClass( 'oo-ui-indexLayout' );
10529 this.stackLayout.$element.addClass( 'oo-ui-indexLayout-stackLayout' );
10530 this.tabPanel.$element
10531 .addClass( 'oo-ui-indexLayout-tabPanel' )
10532 .append( this.tabSelectWidget.$element );
10533 };
10534
10535 /* Setup */
10536
10537 OO.inheritClass( OO.ui.IndexLayout, OO.ui.MenuLayout );
10538
10539 /* Events */
10540
10541 /**
10542 * A 'set' event is emitted when a card is {@link #setCard set} to be displayed by the index layout.
10543 * @event set
10544 * @param {OO.ui.CardLayout} card Current card
10545 */
10546
10547 /**
10548 * An 'add' event is emitted when cards are {@link #addCards added} to the index layout.
10549 *
10550 * @event add
10551 * @param {OO.ui.CardLayout[]} card Added cards
10552 * @param {number} index Index cards were added at
10553 */
10554
10555 /**
10556 * A 'remove' event is emitted when cards are {@link #clearCards cleared} or
10557 * {@link #removeCards removed} from the index.
10558 *
10559 * @event remove
10560 * @param {OO.ui.CardLayout[]} cards Removed cards
10561 */
10562
10563 /* Methods */
10564
10565 /**
10566 * Handle stack layout focus.
10567 *
10568 * @private
10569 * @param {jQuery.Event} e Focusin event
10570 */
10571 OO.ui.IndexLayout.prototype.onStackLayoutFocus = function ( e ) {
10572 var name, $target;
10573
10574 // Find the card that an element was focused within
10575 $target = $( e.target ).closest( '.oo-ui-cardLayout' );
10576 for ( name in this.cards ) {
10577 // Check for card match, exclude current card to find only card changes
10578 if ( this.cards[ name ].$element[ 0 ] === $target[ 0 ] && name !== this.currentCardName ) {
10579 this.setCard( name );
10580 break;
10581 }
10582 }
10583 };
10584
10585 /**
10586 * Handle stack layout set events.
10587 *
10588 * @private
10589 * @param {OO.ui.PanelLayout|null} card The card panel that is now the current panel
10590 */
10591 OO.ui.IndexLayout.prototype.onStackLayoutSet = function ( card ) {
10592 var layout = this;
10593 if ( card ) {
10594 card.scrollElementIntoView( { complete: function () {
10595 if ( layout.autoFocus ) {
10596 layout.focus();
10597 }
10598 } } );
10599 }
10600 };
10601
10602 /**
10603 * Focus the first input in the current card.
10604 *
10605 * If no card is selected, the first selectable card will be selected.
10606 * If the focus is already in an element on the current card, nothing will happen.
10607 * @param {number} [itemIndex] A specific item to focus on
10608 */
10609 OO.ui.IndexLayout.prototype.focus = function ( itemIndex ) {
10610 var card,
10611 items = this.stackLayout.getItems();
10612
10613 if ( itemIndex !== undefined && items[ itemIndex ] ) {
10614 card = items[ itemIndex ];
10615 } else {
10616 card = this.stackLayout.getCurrentItem();
10617 }
10618
10619 if ( !card ) {
10620 this.selectFirstSelectableCard();
10621 card = this.stackLayout.getCurrentItem();
10622 }
10623 if ( !card ) {
10624 return;
10625 }
10626 // Only change the focus if is not already in the current page
10627 if ( !OO.ui.contains( card.$element[ 0 ], this.getElementDocument().activeElement, true ) ) {
10628 card.focus();
10629 }
10630 };
10631
10632 /**
10633 * Find the first focusable input in the index layout and focus
10634 * on it.
10635 */
10636 OO.ui.IndexLayout.prototype.focusFirstFocusable = function () {
10637 OO.ui.findFocusable( this.stackLayout.$element ).focus();
10638 };
10639
10640 /**
10641 * Handle tab widget select events.
10642 *
10643 * @private
10644 * @param {OO.ui.OptionWidget|null} item Selected item
10645 */
10646 OO.ui.IndexLayout.prototype.onTabSelectWidgetSelect = function ( item ) {
10647 if ( item ) {
10648 this.setCard( item.getData() );
10649 }
10650 };
10651
10652 /**
10653 * Get the card closest to the specified card.
10654 *
10655 * @param {OO.ui.CardLayout} card Card to use as a reference point
10656 * @return {OO.ui.CardLayout|null} Card closest to the specified card
10657 */
10658 OO.ui.IndexLayout.prototype.getClosestCard = function ( card ) {
10659 var next, prev, level,
10660 cards = this.stackLayout.getItems(),
10661 index = cards.indexOf( card );
10662
10663 if ( index !== -1 ) {
10664 next = cards[ index + 1 ];
10665 prev = cards[ index - 1 ];
10666 // Prefer adjacent cards at the same level
10667 level = this.tabSelectWidget.getItemFromData( card.getName() ).getLevel();
10668 if (
10669 prev &&
10670 level === this.tabSelectWidget.getItemFromData( prev.getName() ).getLevel()
10671 ) {
10672 return prev;
10673 }
10674 if (
10675 next &&
10676 level === this.tabSelectWidget.getItemFromData( next.getName() ).getLevel()
10677 ) {
10678 return next;
10679 }
10680 }
10681 return prev || next || null;
10682 };
10683
10684 /**
10685 * Get the tabs widget.
10686 *
10687 * @return {OO.ui.TabSelectWidget} Tabs widget
10688 */
10689 OO.ui.IndexLayout.prototype.getTabs = function () {
10690 return this.tabSelectWidget;
10691 };
10692
10693 /**
10694 * Get a card by its symbolic name.
10695 *
10696 * @param {string} name Symbolic name of card
10697 * @return {OO.ui.CardLayout|undefined} Card, if found
10698 */
10699 OO.ui.IndexLayout.prototype.getCard = function ( name ) {
10700 return this.cards[ name ];
10701 };
10702
10703 /**
10704 * Get the current card.
10705 *
10706 * @return {OO.ui.CardLayout|undefined} Current card, if found
10707 */
10708 OO.ui.IndexLayout.prototype.getCurrentCard = function () {
10709 var name = this.getCurrentCardName();
10710 return name ? this.getCard( name ) : undefined;
10711 };
10712
10713 /**
10714 * Get the symbolic name of the current card.
10715 *
10716 * @return {string|null} Symbolic name of the current card
10717 */
10718 OO.ui.IndexLayout.prototype.getCurrentCardName = function () {
10719 return this.currentCardName;
10720 };
10721
10722 /**
10723 * Add cards to the index layout
10724 *
10725 * When cards are added with the same names as existing cards, the existing cards will be
10726 * automatically removed before the new cards are added.
10727 *
10728 * @param {OO.ui.CardLayout[]} cards Cards to add
10729 * @param {number} index Index of the insertion point
10730 * @fires add
10731 * @chainable
10732 */
10733 OO.ui.IndexLayout.prototype.addCards = function ( cards, index ) {
10734 var i, len, name, card, item, currentIndex,
10735 stackLayoutCards = this.stackLayout.getItems(),
10736 remove = [],
10737 items = [];
10738
10739 // Remove cards with same names
10740 for ( i = 0, len = cards.length; i < len; i++ ) {
10741 card = cards[ i ];
10742 name = card.getName();
10743
10744 if ( Object.prototype.hasOwnProperty.call( this.cards, name ) ) {
10745 // Correct the insertion index
10746 currentIndex = stackLayoutCards.indexOf( this.cards[ name ] );
10747 if ( currentIndex !== -1 && currentIndex + 1 < index ) {
10748 index--;
10749 }
10750 remove.push( this.cards[ name ] );
10751 }
10752 }
10753 if ( remove.length ) {
10754 this.removeCards( remove );
10755 }
10756
10757 // Add new cards
10758 for ( i = 0, len = cards.length; i < len; i++ ) {
10759 card = cards[ i ];
10760 name = card.getName();
10761 this.cards[ card.getName() ] = card;
10762 item = new OO.ui.TabOptionWidget( { data: name } );
10763 card.setTabItem( item );
10764 items.push( item );
10765 }
10766
10767 if ( items.length ) {
10768 this.tabSelectWidget.addItems( items, index );
10769 this.selectFirstSelectableCard();
10770 }
10771 this.stackLayout.addItems( cards, index );
10772 this.emit( 'add', cards, index );
10773
10774 return this;
10775 };
10776
10777 /**
10778 * Remove the specified cards from the index layout.
10779 *
10780 * To remove all cards from the index, you may wish to use the #clearCards method instead.
10781 *
10782 * @param {OO.ui.CardLayout[]} cards An array of cards to remove
10783 * @fires remove
10784 * @chainable
10785 */
10786 OO.ui.IndexLayout.prototype.removeCards = function ( cards ) {
10787 var i, len, name, card,
10788 items = [];
10789
10790 for ( i = 0, len = cards.length; i < len; i++ ) {
10791 card = cards[ i ];
10792 name = card.getName();
10793 delete this.cards[ name ];
10794 items.push( this.tabSelectWidget.getItemFromData( name ) );
10795 card.setTabItem( null );
10796 }
10797 if ( items.length ) {
10798 this.tabSelectWidget.removeItems( items );
10799 this.selectFirstSelectableCard();
10800 }
10801 this.stackLayout.removeItems( cards );
10802 this.emit( 'remove', cards );
10803
10804 return this;
10805 };
10806
10807 /**
10808 * Clear all cards from the index layout.
10809 *
10810 * To remove only a subset of cards from the index, use the #removeCards method.
10811 *
10812 * @fires remove
10813 * @chainable
10814 */
10815 OO.ui.IndexLayout.prototype.clearCards = function () {
10816 var i, len,
10817 cards = this.stackLayout.getItems();
10818
10819 this.cards = {};
10820 this.currentCardName = null;
10821 this.tabSelectWidget.clearItems();
10822 for ( i = 0, len = cards.length; i < len; i++ ) {
10823 cards[ i ].setTabItem( null );
10824 }
10825 this.stackLayout.clearItems();
10826
10827 this.emit( 'remove', cards );
10828
10829 return this;
10830 };
10831
10832 /**
10833 * Set the current card by symbolic name.
10834 *
10835 * @fires set
10836 * @param {string} name Symbolic name of card
10837 */
10838 OO.ui.IndexLayout.prototype.setCard = function ( name ) {
10839 var selectedItem,
10840 $focused,
10841 card = this.cards[ name ],
10842 previousCard = this.currentCardName && this.cards[ this.currentCardName ];
10843
10844 if ( name !== this.currentCardName ) {
10845 selectedItem = this.tabSelectWidget.getSelectedItem();
10846 if ( selectedItem && selectedItem.getData() !== name ) {
10847 this.tabSelectWidget.selectItemByData( name );
10848 }
10849 if ( card ) {
10850 if ( previousCard ) {
10851 previousCard.setActive( false );
10852 // Blur anything focused if the next card doesn't have anything focusable.
10853 // This is not needed if the next card has something focusable (because once it is focused
10854 // this blur happens automatically). If the layout is non-continuous, this check is
10855 // meaningless because the next card is not visible yet and thus can't hold focus.
10856 if (
10857 this.autoFocus &&
10858 this.stackLayout.continuous &&
10859 OO.ui.findFocusable( card.$element ).length !== 0
10860 ) {
10861 $focused = previousCard.$element.find( ':focus' );
10862 if ( $focused.length ) {
10863 $focused[ 0 ].blur();
10864 }
10865 }
10866 }
10867 this.currentCardName = name;
10868 card.setActive( true );
10869 this.stackLayout.setItem( card );
10870 if ( !this.stackLayout.continuous && previousCard ) {
10871 // This should not be necessary, since any inputs on the previous card should have been
10872 // blurred when it was hidden, but browsers are not very consistent about this.
10873 $focused = previousCard.$element.find( ':focus' );
10874 if ( $focused.length ) {
10875 $focused[ 0 ].blur();
10876 }
10877 }
10878 this.emit( 'set', card );
10879 }
10880 }
10881 };
10882
10883 /**
10884 * Select the first selectable card.
10885 *
10886 * @chainable
10887 */
10888 OO.ui.IndexLayout.prototype.selectFirstSelectableCard = function () {
10889 if ( !this.tabSelectWidget.getSelectedItem() ) {
10890 this.tabSelectWidget.selectItem( this.tabSelectWidget.getFirstSelectableItem() );
10891 }
10892
10893 return this;
10894 };
10895
10896 /**
10897 * PanelLayouts expand to cover the entire area of their parent. They can be configured with scrolling, padding,
10898 * and a frame, and are often used together with {@link OO.ui.StackLayout StackLayouts}.
10899 *
10900 * @example
10901 * // Example of a panel layout
10902 * var panel = new OO.ui.PanelLayout( {
10903 * expanded: false,
10904 * framed: true,
10905 * padded: true,
10906 * $content: $( '<p>A panel layout with padding and a frame.</p>' )
10907 * } );
10908 * $( 'body' ).append( panel.$element );
10909 *
10910 * @class
10911 * @extends OO.ui.Layout
10912 *
10913 * @constructor
10914 * @param {Object} [config] Configuration options
10915 * @cfg {boolean} [scrollable=false] Allow vertical scrolling
10916 * @cfg {boolean} [padded=false] Add padding between the content and the edges of the panel.
10917 * @cfg {boolean} [expanded=true] Expand the panel to fill the entire parent element.
10918 * @cfg {boolean} [framed=false] Render the panel with a frame to visually separate it from outside content.
10919 */
10920 OO.ui.PanelLayout = function OoUiPanelLayout( config ) {
10921 // Configuration initialization
10922 config = $.extend( {
10923 scrollable: false,
10924 padded: false,
10925 expanded: true,
10926 framed: false
10927 }, config );
10928
10929 // Parent constructor
10930 OO.ui.PanelLayout.parent.call( this, config );
10931
10932 // Initialization
10933 this.$element.addClass( 'oo-ui-panelLayout' );
10934 if ( config.scrollable ) {
10935 this.$element.addClass( 'oo-ui-panelLayout-scrollable' );
10936 }
10937 if ( config.padded ) {
10938 this.$element.addClass( 'oo-ui-panelLayout-padded' );
10939 }
10940 if ( config.expanded ) {
10941 this.$element.addClass( 'oo-ui-panelLayout-expanded' );
10942 }
10943 if ( config.framed ) {
10944 this.$element.addClass( 'oo-ui-panelLayout-framed' );
10945 }
10946 };
10947
10948 /* Setup */
10949
10950 OO.inheritClass( OO.ui.PanelLayout, OO.ui.Layout );
10951
10952 /* Methods */
10953
10954 /**
10955 * Focus the panel layout
10956 *
10957 * The default implementation just focuses the first focusable element in the panel
10958 */
10959 OO.ui.PanelLayout.prototype.focus = function () {
10960 OO.ui.findFocusable( this.$element ).focus();
10961 };
10962
10963 /**
10964 * CardLayouts are used within {@link OO.ui.IndexLayout index layouts} to create cards that users can select and display
10965 * from the index's optional {@link OO.ui.TabSelectWidget tab} navigation. Cards are usually not instantiated directly,
10966 * rather extended to include the required content and functionality.
10967 *
10968 * Each card must have a unique symbolic name, which is passed to the constructor. In addition, the card's tab
10969 * item is customized (with a label) using the #setupTabItem method. See
10970 * {@link OO.ui.IndexLayout IndexLayout} for an example.
10971 *
10972 * @class
10973 * @extends OO.ui.PanelLayout
10974 *
10975 * @constructor
10976 * @param {string} name Unique symbolic name of card
10977 * @param {Object} [config] Configuration options
10978 * @cfg {jQuery|string|Function|OO.ui.HtmlSnippet} [label] Label for card's tab
10979 */
10980 OO.ui.CardLayout = function OoUiCardLayout( name, config ) {
10981 // Allow passing positional parameters inside the config object
10982 if ( OO.isPlainObject( name ) && config === undefined ) {
10983 config = name;
10984 name = config.name;
10985 }
10986
10987 // Configuration initialization
10988 config = $.extend( { scrollable: true }, config );
10989
10990 // Parent constructor
10991 OO.ui.CardLayout.parent.call( this, config );
10992
10993 // Properties
10994 this.name = name;
10995 this.label = config.label;
10996 this.tabItem = null;
10997 this.active = false;
10998
10999 // Initialization
11000 this.$element.addClass( 'oo-ui-cardLayout' );
11001 };
11002
11003 /* Setup */
11004
11005 OO.inheritClass( OO.ui.CardLayout, OO.ui.PanelLayout );
11006
11007 /* Events */
11008
11009 /**
11010 * An 'active' event is emitted when the card becomes active. Cards become active when they are
11011 * shown in a index layout that is configured to display only one card at a time.
11012 *
11013 * @event active
11014 * @param {boolean} active Card is active
11015 */
11016
11017 /* Methods */
11018
11019 /**
11020 * Get the symbolic name of the card.
11021 *
11022 * @return {string} Symbolic name of card
11023 */
11024 OO.ui.CardLayout.prototype.getName = function () {
11025 return this.name;
11026 };
11027
11028 /**
11029 * Check if card is active.
11030 *
11031 * Cards become active when they are shown in a {@link OO.ui.IndexLayout index layout} that is configured to display
11032 * only one card at a time. Additional CSS is applied to the card's tab item to reflect the active state.
11033 *
11034 * @return {boolean} Card is active
11035 */
11036 OO.ui.CardLayout.prototype.isActive = function () {
11037 return this.active;
11038 };
11039
11040 /**
11041 * Get tab item.
11042 *
11043 * The tab item allows users to access the card from the index's tab
11044 * navigation. The tab item itself can be customized (with a label, level, etc.) using the #setupTabItem method.
11045 *
11046 * @return {OO.ui.TabOptionWidget|null} Tab option widget
11047 */
11048 OO.ui.CardLayout.prototype.getTabItem = function () {
11049 return this.tabItem;
11050 };
11051
11052 /**
11053 * Set or unset the tab item.
11054 *
11055 * Specify a {@link OO.ui.TabOptionWidget tab option} to set it,
11056 * or `null` to clear the tab item. To customize the tab item itself (e.g., to set a label or tab
11057 * level), use #setupTabItem instead of this method.
11058 *
11059 * @param {OO.ui.TabOptionWidget|null} tabItem Tab option widget, null to clear
11060 * @chainable
11061 */
11062 OO.ui.CardLayout.prototype.setTabItem = function ( tabItem ) {
11063 this.tabItem = tabItem || null;
11064 if ( tabItem ) {
11065 this.setupTabItem();
11066 }
11067 return this;
11068 };
11069
11070 /**
11071 * Set up the tab item.
11072 *
11073 * Use this method to customize the tab item (e.g., to add a label or tab level). To set or unset
11074 * the tab item itself (with a {@link OO.ui.TabOptionWidget tab option} or `null`), use
11075 * the #setTabItem method instead.
11076 *
11077 * @param {OO.ui.TabOptionWidget} tabItem Tab option widget to set up
11078 * @chainable
11079 */
11080 OO.ui.CardLayout.prototype.setupTabItem = function () {
11081 if ( this.label ) {
11082 this.tabItem.setLabel( this.label );
11083 }
11084 return this;
11085 };
11086
11087 /**
11088 * Set the card to its 'active' state.
11089 *
11090 * Cards become active when they are shown in a index layout that is configured to display only one card at a time. Additional
11091 * CSS is applied to the tab item to reflect the card's active state. Outside of the index
11092 * context, setting the active state on a card does nothing.
11093 *
11094 * @param {boolean} value Card is active
11095 * @fires active
11096 */
11097 OO.ui.CardLayout.prototype.setActive = function ( active ) {
11098 active = !!active;
11099
11100 if ( active !== this.active ) {
11101 this.active = active;
11102 this.$element.toggleClass( 'oo-ui-cardLayout-active', this.active );
11103 this.emit( 'active', this.active );
11104 }
11105 };
11106
11107 /**
11108 * PageLayouts are used within {@link OO.ui.BookletLayout booklet layouts} to create pages that users can select and display
11109 * from the booklet's optional {@link OO.ui.OutlineSelectWidget outline} navigation. Pages are usually not instantiated directly,
11110 * rather extended to include the required content and functionality.
11111 *
11112 * Each page must have a unique symbolic name, which is passed to the constructor. In addition, the page's outline
11113 * item is customized (with a label, outline level, etc.) using the #setupOutlineItem method. See
11114 * {@link OO.ui.BookletLayout BookletLayout} for an example.
11115 *
11116 * @class
11117 * @extends OO.ui.PanelLayout
11118 *
11119 * @constructor
11120 * @param {string} name Unique symbolic name of page
11121 * @param {Object} [config] Configuration options
11122 */
11123 OO.ui.PageLayout = function OoUiPageLayout( name, config ) {
11124 // Allow passing positional parameters inside the config object
11125 if ( OO.isPlainObject( name ) && config === undefined ) {
11126 config = name;
11127 name = config.name;
11128 }
11129
11130 // Configuration initialization
11131 config = $.extend( { scrollable: true }, config );
11132
11133 // Parent constructor
11134 OO.ui.PageLayout.parent.call( this, config );
11135
11136 // Properties
11137 this.name = name;
11138 this.outlineItem = null;
11139 this.active = false;
11140
11141 // Initialization
11142 this.$element.addClass( 'oo-ui-pageLayout' );
11143 };
11144
11145 /* Setup */
11146
11147 OO.inheritClass( OO.ui.PageLayout, OO.ui.PanelLayout );
11148
11149 /* Events */
11150
11151 /**
11152 * An 'active' event is emitted when the page becomes active. Pages become active when they are
11153 * shown in a booklet layout that is configured to display only one page at a time.
11154 *
11155 * @event active
11156 * @param {boolean} active Page is active
11157 */
11158
11159 /* Methods */
11160
11161 /**
11162 * Get the symbolic name of the page.
11163 *
11164 * @return {string} Symbolic name of page
11165 */
11166 OO.ui.PageLayout.prototype.getName = function () {
11167 return this.name;
11168 };
11169
11170 /**
11171 * Check if page is active.
11172 *
11173 * Pages become active when they are shown in a {@link OO.ui.BookletLayout booklet layout} that is configured to display
11174 * only one page at a time. Additional CSS is applied to the page's outline item to reflect the active state.
11175 *
11176 * @return {boolean} Page is active
11177 */
11178 OO.ui.PageLayout.prototype.isActive = function () {
11179 return this.active;
11180 };
11181
11182 /**
11183 * Get outline item.
11184 *
11185 * The outline item allows users to access the page from the booklet's outline
11186 * navigation. The outline item itself can be customized (with a label, level, etc.) using the #setupOutlineItem method.
11187 *
11188 * @return {OO.ui.OutlineOptionWidget|null} Outline option widget
11189 */
11190 OO.ui.PageLayout.prototype.getOutlineItem = function () {
11191 return this.outlineItem;
11192 };
11193
11194 /**
11195 * Set or unset the outline item.
11196 *
11197 * Specify an {@link OO.ui.OutlineOptionWidget outline option} to set it,
11198 * or `null` to clear the outline item. To customize the outline item itself (e.g., to set a label or outline
11199 * level), use #setupOutlineItem instead of this method.
11200 *
11201 * @param {OO.ui.OutlineOptionWidget|null} outlineItem Outline option widget, null to clear
11202 * @chainable
11203 */
11204 OO.ui.PageLayout.prototype.setOutlineItem = function ( outlineItem ) {
11205 this.outlineItem = outlineItem || null;
11206 if ( outlineItem ) {
11207 this.setupOutlineItem();
11208 }
11209 return this;
11210 };
11211
11212 /**
11213 * Set up the outline item.
11214 *
11215 * Use this method to customize the outline item (e.g., to add a label or outline level). To set or unset
11216 * the outline item itself (with an {@link OO.ui.OutlineOptionWidget outline option} or `null`), use
11217 * the #setOutlineItem method instead.
11218 *
11219 * @param {OO.ui.OutlineOptionWidget} outlineItem Outline option widget to set up
11220 * @chainable
11221 */
11222 OO.ui.PageLayout.prototype.setupOutlineItem = function () {
11223 return this;
11224 };
11225
11226 /**
11227 * Set the page to its 'active' state.
11228 *
11229 * Pages become active when they are shown in a booklet layout that is configured to display only one page at a time. Additional
11230 * CSS is applied to the outline item to reflect the page's active state. Outside of the booklet
11231 * context, setting the active state on a page does nothing.
11232 *
11233 * @param {boolean} value Page is active
11234 * @fires active
11235 */
11236 OO.ui.PageLayout.prototype.setActive = function ( active ) {
11237 active = !!active;
11238
11239 if ( active !== this.active ) {
11240 this.active = active;
11241 this.$element.toggleClass( 'oo-ui-pageLayout-active', active );
11242 this.emit( 'active', this.active );
11243 }
11244 };
11245
11246 /**
11247 * StackLayouts contain a series of {@link OO.ui.PanelLayout panel layouts}. By default, only one panel is displayed
11248 * at a time, though the stack layout can also be configured to show all contained panels, one after another,
11249 * by setting the #continuous option to 'true'.
11250 *
11251 * @example
11252 * // A stack layout with two panels, configured to be displayed continously
11253 * var myStack = new OO.ui.StackLayout( {
11254 * items: [
11255 * new OO.ui.PanelLayout( {
11256 * $content: $( '<p>Panel One</p>' ),
11257 * padded: true,
11258 * framed: true
11259 * } ),
11260 * new OO.ui.PanelLayout( {
11261 * $content: $( '<p>Panel Two</p>' ),
11262 * padded: true,
11263 * framed: true
11264 * } )
11265 * ],
11266 * continuous: true
11267 * } );
11268 * $( 'body' ).append( myStack.$element );
11269 *
11270 * @class
11271 * @extends OO.ui.PanelLayout
11272 * @mixins OO.ui.mixin.GroupElement
11273 *
11274 * @constructor
11275 * @param {Object} [config] Configuration options
11276 * @cfg {boolean} [continuous=false] Show all panels, one after another. By default, only one panel is displayed at a time.
11277 * @cfg {OO.ui.Layout[]} [items] Panel layouts to add to the stack layout.
11278 */
11279 OO.ui.StackLayout = function OoUiStackLayout( config ) {
11280 // Configuration initialization
11281 config = $.extend( { scrollable: true }, config );
11282
11283 // Parent constructor
11284 OO.ui.StackLayout.parent.call( this, config );
11285
11286 // Mixin constructors
11287 OO.ui.mixin.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) );
11288
11289 // Properties
11290 this.currentItem = null;
11291 this.continuous = !!config.continuous;
11292
11293 // Initialization
11294 this.$element.addClass( 'oo-ui-stackLayout' );
11295 if ( this.continuous ) {
11296 this.$element.addClass( 'oo-ui-stackLayout-continuous' );
11297 this.$element.on( 'scroll', OO.ui.debounce( this.onScroll.bind( this ), 250 ) );
11298 }
11299 if ( Array.isArray( config.items ) ) {
11300 this.addItems( config.items );
11301 }
11302 };
11303
11304 /* Setup */
11305
11306 OO.inheritClass( OO.ui.StackLayout, OO.ui.PanelLayout );
11307 OO.mixinClass( OO.ui.StackLayout, OO.ui.mixin.GroupElement );
11308
11309 /* Events */
11310
11311 /**
11312 * A 'set' event is emitted when panels are {@link #addItems added}, {@link #removeItems removed},
11313 * {@link #clearItems cleared} or {@link #setItem displayed}.
11314 *
11315 * @event set
11316 * @param {OO.ui.Layout|null} item Current panel or `null` if no panel is shown
11317 */
11318
11319 /**
11320 * When used in continuous mode, this event is emitted when the user scrolls down
11321 * far enough such that currentItem is no longer visible.
11322 *
11323 * @event visibleItemChange
11324 * @param {OO.ui.PanelLayout} panel The next visible item in the layout
11325 */
11326
11327 /* Methods */
11328
11329 /**
11330 * Handle scroll events from the layout element
11331 *
11332 * @param {jQuery.Event} e
11333 * @fires visibleItemChange
11334 */
11335 OO.ui.StackLayout.prototype.onScroll = function () {
11336 var currentRect,
11337 len = this.items.length,
11338 currentIndex = this.items.indexOf( this.currentItem ),
11339 newIndex = currentIndex,
11340 containerRect = this.$element[ 0 ].getBoundingClientRect();
11341
11342 if ( !containerRect || ( !containerRect.top && !containerRect.bottom ) ) {
11343 // Can't get bounding rect, possibly not attached.
11344 return;
11345 }
11346
11347 function getRect( item ) {
11348 return item.$element[ 0 ].getBoundingClientRect();
11349 }
11350
11351 function isVisible( item ) {
11352 var rect = getRect( item );
11353 return rect.bottom > containerRect.top && rect.top < containerRect.bottom;
11354 }
11355
11356 currentRect = getRect( this.currentItem );
11357
11358 if ( currentRect.bottom < containerRect.top ) {
11359 // Scrolled down past current item
11360 while ( ++newIndex < len ) {
11361 if ( isVisible( this.items[ newIndex ] ) ) {
11362 break;
11363 }
11364 }
11365 } else if ( currentRect.top > containerRect.bottom ) {
11366 // Scrolled up past current item
11367 while ( --newIndex >= 0 ) {
11368 if ( isVisible( this.items[ newIndex ] ) ) {
11369 break;
11370 }
11371 }
11372 }
11373
11374 if ( newIndex !== currentIndex ) {
11375 this.emit( 'visibleItemChange', this.items[ newIndex ] );
11376 }
11377 };
11378
11379 /**
11380 * Get the current panel.
11381 *
11382 * @return {OO.ui.Layout|null}
11383 */
11384 OO.ui.StackLayout.prototype.getCurrentItem = function () {
11385 return this.currentItem;
11386 };
11387
11388 /**
11389 * Unset the current item.
11390 *
11391 * @private
11392 * @param {OO.ui.StackLayout} layout
11393 * @fires set
11394 */
11395 OO.ui.StackLayout.prototype.unsetCurrentItem = function () {
11396 var prevItem = this.currentItem;
11397 if ( prevItem === null ) {
11398 return;
11399 }
11400
11401 this.currentItem = null;
11402 this.emit( 'set', null );
11403 };
11404
11405 /**
11406 * Add panel layouts to the stack layout.
11407 *
11408 * Panels will be added to the end of the stack layout array unless the optional index parameter specifies a different
11409 * insertion point. Adding a panel that is already in the stack will move it to the end of the array or the point specified
11410 * by the index.
11411 *
11412 * @param {OO.ui.Layout[]} items Panels to add
11413 * @param {number} [index] Index of the insertion point
11414 * @chainable
11415 */
11416 OO.ui.StackLayout.prototype.addItems = function ( items, index ) {
11417 // Update the visibility
11418 this.updateHiddenState( items, this.currentItem );
11419
11420 // Mixin method
11421 OO.ui.mixin.GroupElement.prototype.addItems.call( this, items, index );
11422
11423 if ( !this.currentItem && items.length ) {
11424 this.setItem( items[ 0 ] );
11425 }
11426
11427 return this;
11428 };
11429
11430 /**
11431 * Remove the specified panels from the stack layout.
11432 *
11433 * Removed panels are detached from the DOM, not removed, so that they may be reused. To remove all panels,
11434 * you may wish to use the #clearItems method instead.
11435 *
11436 * @param {OO.ui.Layout[]} items Panels to remove
11437 * @chainable
11438 * @fires set
11439 */
11440 OO.ui.StackLayout.prototype.removeItems = function ( items ) {
11441 // Mixin method
11442 OO.ui.mixin.GroupElement.prototype.removeItems.call( this, items );
11443
11444 if ( items.indexOf( this.currentItem ) !== -1 ) {
11445 if ( this.items.length ) {
11446 this.setItem( this.items[ 0 ] );
11447 } else {
11448 this.unsetCurrentItem();
11449 }
11450 }
11451
11452 return this;
11453 };
11454
11455 /**
11456 * Clear all panels from the stack layout.
11457 *
11458 * Cleared panels are detached from the DOM, not removed, so that they may be reused. To remove only
11459 * a subset of panels, use the #removeItems method.
11460 *
11461 * @chainable
11462 * @fires set
11463 */
11464 OO.ui.StackLayout.prototype.clearItems = function () {
11465 this.unsetCurrentItem();
11466 OO.ui.mixin.GroupElement.prototype.clearItems.call( this );
11467
11468 return this;
11469 };
11470
11471 /**
11472 * Show the specified panel.
11473 *
11474 * If another panel is currently displayed, it will be hidden.
11475 *
11476 * @param {OO.ui.Layout} item Panel to show
11477 * @chainable
11478 * @fires set
11479 */
11480 OO.ui.StackLayout.prototype.setItem = function ( item ) {
11481 if ( item !== this.currentItem ) {
11482 this.updateHiddenState( this.items, item );
11483
11484 if ( this.items.indexOf( item ) !== -1 ) {
11485 this.currentItem = item;
11486 this.emit( 'set', item );
11487 } else {
11488 this.unsetCurrentItem();
11489 }
11490 }
11491
11492 return this;
11493 };
11494
11495 /**
11496 * Update the visibility of all items in case of non-continuous view.
11497 *
11498 * Ensure all items are hidden except for the selected one.
11499 * This method does nothing when the stack is continuous.
11500 *
11501 * @private
11502 * @param {OO.ui.Layout[]} items Item list iterate over
11503 * @param {OO.ui.Layout} [selectedItem] Selected item to show
11504 */
11505 OO.ui.StackLayout.prototype.updateHiddenState = function ( items, selectedItem ) {
11506 var i, len;
11507
11508 if ( !this.continuous ) {
11509 for ( i = 0, len = items.length; i < len; i++ ) {
11510 if ( !selectedItem || selectedItem !== items[ i ] ) {
11511 items[ i ].$element.addClass( 'oo-ui-element-hidden' );
11512 }
11513 }
11514 if ( selectedItem ) {
11515 selectedItem.$element.removeClass( 'oo-ui-element-hidden' );
11516 }
11517 }
11518 };
11519
11520 /**
11521 * HorizontalLayout arranges its contents in a single line (using `display: inline-block` for its
11522 * items), with small margins between them. Convenient when you need to put a number of block-level
11523 * widgets on a single line next to each other.
11524 *
11525 * Note that inline elements, such as OO.ui.ButtonWidgets, do not need this wrapper.
11526 *
11527 * @example
11528 * // HorizontalLayout with a text input and a label
11529 * var layout = new OO.ui.HorizontalLayout( {
11530 * items: [
11531 * new OO.ui.LabelWidget( { label: 'Label' } ),
11532 * new OO.ui.TextInputWidget( { value: 'Text' } )
11533 * ]
11534 * } );
11535 * $( 'body' ).append( layout.$element );
11536 *
11537 * @class
11538 * @extends OO.ui.Layout
11539 * @mixins OO.ui.mixin.GroupElement
11540 *
11541 * @constructor
11542 * @param {Object} [config] Configuration options
11543 * @cfg {OO.ui.Widget[]|OO.ui.Layout[]} [items] Widgets or other layouts to add to the layout.
11544 */
11545 OO.ui.HorizontalLayout = function OoUiHorizontalLayout( config ) {
11546 // Configuration initialization
11547 config = config || {};
11548
11549 // Parent constructor
11550 OO.ui.HorizontalLayout.parent.call( this, config );
11551
11552 // Mixin constructors
11553 OO.ui.mixin.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) );
11554
11555 // Initialization
11556 this.$element.addClass( 'oo-ui-horizontalLayout' );
11557 if ( Array.isArray( config.items ) ) {
11558 this.addItems( config.items );
11559 }
11560 };
11561
11562 /* Setup */
11563
11564 OO.inheritClass( OO.ui.HorizontalLayout, OO.ui.Layout );
11565 OO.mixinClass( OO.ui.HorizontalLayout, OO.ui.mixin.GroupElement );
11566
11567 /**
11568 * BarToolGroups are one of three types of {@link OO.ui.ToolGroup toolgroups} that are used to
11569 * create {@link OO.ui.Toolbar toolbars} (the other types of groups are {@link OO.ui.MenuToolGroup MenuToolGroup}
11570 * and {@link OO.ui.ListToolGroup ListToolGroup}). The {@link OO.ui.Tool tools} in a BarToolGroup are
11571 * displayed by icon in a single row. The title of the tool is displayed when users move the mouse over
11572 * the tool.
11573 *
11574 * BarToolGroups are created by a {@link OO.ui.ToolGroupFactory tool group factory} when the toolbar is
11575 * set up.
11576 *
11577 * @example
11578 * // Example of a BarToolGroup with two tools
11579 * var toolFactory = new OO.ui.ToolFactory();
11580 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
11581 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
11582 *
11583 * // We will be placing status text in this element when tools are used
11584 * var $area = $( '<p>' ).text( 'Example of a BarToolGroup with two tools.' );
11585 *
11586 * // Define the tools that we're going to place in our toolbar
11587 *
11588 * // Create a class inheriting from OO.ui.Tool
11589 * function SearchTool() {
11590 * SearchTool.parent.apply( this, arguments );
11591 * }
11592 * OO.inheritClass( SearchTool, OO.ui.Tool );
11593 * // Each tool must have a 'name' (used as an internal identifier, see later) and at least one
11594 * // of 'icon' and 'title' (displayed icon and text).
11595 * SearchTool.static.name = 'search';
11596 * SearchTool.static.icon = 'search';
11597 * SearchTool.static.title = 'Search...';
11598 * // Defines the action that will happen when this tool is selected (clicked).
11599 * SearchTool.prototype.onSelect = function () {
11600 * $area.text( 'Search tool clicked!' );
11601 * // Never display this tool as "active" (selected).
11602 * this.setActive( false );
11603 * };
11604 * SearchTool.prototype.onUpdateState = function () {};
11605 * // Make this tool available in our toolFactory and thus our toolbar
11606 * toolFactory.register( SearchTool );
11607 *
11608 * // This is a PopupTool. Rather than having a custom 'onSelect' action, it will display a
11609 * // little popup window (a PopupWidget).
11610 * function HelpTool( toolGroup, config ) {
11611 * OO.ui.PopupTool.call( this, toolGroup, $.extend( { popup: {
11612 * padded: true,
11613 * label: 'Help',
11614 * head: true
11615 * } }, config ) );
11616 * this.popup.$body.append( '<p>I am helpful!</p>' );
11617 * }
11618 * OO.inheritClass( HelpTool, OO.ui.PopupTool );
11619 * HelpTool.static.name = 'help';
11620 * HelpTool.static.icon = 'help';
11621 * HelpTool.static.title = 'Help';
11622 * toolFactory.register( HelpTool );
11623 *
11624 * // Finally define which tools and in what order appear in the toolbar. Each tool may only be
11625 * // used once (but not all defined tools must be used).
11626 * toolbar.setup( [
11627 * {
11628 * // 'bar' tool groups display tools by icon only
11629 * type: 'bar',
11630 * include: [ 'search', 'help' ]
11631 * }
11632 * ] );
11633 *
11634 * // Create some UI around the toolbar and place it in the document
11635 * var frame = new OO.ui.PanelLayout( {
11636 * expanded: false,
11637 * framed: true
11638 * } );
11639 * var contentFrame = new OO.ui.PanelLayout( {
11640 * expanded: false,
11641 * padded: true
11642 * } );
11643 * frame.$element.append(
11644 * toolbar.$element,
11645 * contentFrame.$element.append( $area )
11646 * );
11647 * $( 'body' ).append( frame.$element );
11648 *
11649 * // Here is where the toolbar is actually built. This must be done after inserting it into the
11650 * // document.
11651 * toolbar.initialize();
11652 *
11653 * For more information about how to add tools to a bar tool group, please see {@link OO.ui.ToolGroup toolgroup}.
11654 * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki][1].
11655 *
11656 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
11657 *
11658 * @class
11659 * @extends OO.ui.ToolGroup
11660 *
11661 * @constructor
11662 * @param {OO.ui.Toolbar} toolbar
11663 * @param {Object} [config] Configuration options
11664 */
11665 OO.ui.BarToolGroup = function OoUiBarToolGroup( toolbar, config ) {
11666 // Allow passing positional parameters inside the config object
11667 if ( OO.isPlainObject( toolbar ) && config === undefined ) {
11668 config = toolbar;
11669 toolbar = config.toolbar;
11670 }
11671
11672 // Parent constructor
11673 OO.ui.BarToolGroup.parent.call( this, toolbar, config );
11674
11675 // Initialization
11676 this.$element.addClass( 'oo-ui-barToolGroup' );
11677 };
11678
11679 /* Setup */
11680
11681 OO.inheritClass( OO.ui.BarToolGroup, OO.ui.ToolGroup );
11682
11683 /* Static Properties */
11684
11685 OO.ui.BarToolGroup.static.titleTooltips = true;
11686
11687 OO.ui.BarToolGroup.static.accelTooltips = true;
11688
11689 OO.ui.BarToolGroup.static.name = 'bar';
11690
11691 /**
11692 * PopupToolGroup is an abstract base class used by both {@link OO.ui.MenuToolGroup MenuToolGroup}
11693 * and {@link OO.ui.ListToolGroup ListToolGroup} to provide a popup--an overlaid menu or list of tools with an
11694 * optional icon and label. This class can be used for other base classes that also use this functionality.
11695 *
11696 * @abstract
11697 * @class
11698 * @extends OO.ui.ToolGroup
11699 * @mixins OO.ui.mixin.IconElement
11700 * @mixins OO.ui.mixin.IndicatorElement
11701 * @mixins OO.ui.mixin.LabelElement
11702 * @mixins OO.ui.mixin.TitledElement
11703 * @mixins OO.ui.mixin.ClippableElement
11704 * @mixins OO.ui.mixin.TabIndexedElement
11705 *
11706 * @constructor
11707 * @param {OO.ui.Toolbar} toolbar
11708 * @param {Object} [config] Configuration options
11709 * @cfg {string} [header] Text to display at the top of the popup
11710 */
11711 OO.ui.PopupToolGroup = function OoUiPopupToolGroup( toolbar, config ) {
11712 // Allow passing positional parameters inside the config object
11713 if ( OO.isPlainObject( toolbar ) && config === undefined ) {
11714 config = toolbar;
11715 toolbar = config.toolbar;
11716 }
11717
11718 // Configuration initialization
11719 config = config || {};
11720
11721 // Parent constructor
11722 OO.ui.PopupToolGroup.parent.call( this, toolbar, config );
11723
11724 // Properties
11725 this.active = false;
11726 this.dragging = false;
11727 this.onBlurHandler = this.onBlur.bind( this );
11728 this.$handle = $( '<span>' );
11729
11730 // Mixin constructors
11731 OO.ui.mixin.IconElement.call( this, config );
11732 OO.ui.mixin.IndicatorElement.call( this, config );
11733 OO.ui.mixin.LabelElement.call( this, config );
11734 OO.ui.mixin.TitledElement.call( this, config );
11735 OO.ui.mixin.ClippableElement.call( this, $.extend( {}, config, { $clippable: this.$group } ) );
11736 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$handle } ) );
11737
11738 // Events
11739 this.$handle.on( {
11740 keydown: this.onHandleMouseKeyDown.bind( this ),
11741 keyup: this.onHandleMouseKeyUp.bind( this ),
11742 mousedown: this.onHandleMouseKeyDown.bind( this ),
11743 mouseup: this.onHandleMouseKeyUp.bind( this )
11744 } );
11745
11746 // Initialization
11747 this.$handle
11748 .addClass( 'oo-ui-popupToolGroup-handle' )
11749 .append( this.$icon, this.$label, this.$indicator );
11750 // If the pop-up should have a header, add it to the top of the toolGroup.
11751 // Note: If this feature is useful for other widgets, we could abstract it into an
11752 // OO.ui.HeaderedElement mixin constructor.
11753 if ( config.header !== undefined ) {
11754 this.$group
11755 .prepend( $( '<span>' )
11756 .addClass( 'oo-ui-popupToolGroup-header' )
11757 .text( config.header )
11758 );
11759 }
11760 this.$element
11761 .addClass( 'oo-ui-popupToolGroup' )
11762 .prepend( this.$handle );
11763 };
11764
11765 /* Setup */
11766
11767 OO.inheritClass( OO.ui.PopupToolGroup, OO.ui.ToolGroup );
11768 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.mixin.IconElement );
11769 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.mixin.IndicatorElement );
11770 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.mixin.LabelElement );
11771 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.mixin.TitledElement );
11772 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.mixin.ClippableElement );
11773 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.mixin.TabIndexedElement );
11774
11775 /* Methods */
11776
11777 /**
11778 * @inheritdoc
11779 */
11780 OO.ui.PopupToolGroup.prototype.setDisabled = function () {
11781 // Parent method
11782 OO.ui.PopupToolGroup.parent.prototype.setDisabled.apply( this, arguments );
11783
11784 if ( this.isDisabled() && this.isElementAttached() ) {
11785 this.setActive( false );
11786 }
11787 };
11788
11789 /**
11790 * Handle focus being lost.
11791 *
11792 * The event is actually generated from a mouseup/keyup, so it is not a normal blur event object.
11793 *
11794 * @protected
11795 * @param {jQuery.Event} e Mouse up or key up event
11796 */
11797 OO.ui.PopupToolGroup.prototype.onBlur = function ( e ) {
11798 // Only deactivate when clicking outside the dropdown element
11799 if ( $( e.target ).closest( '.oo-ui-popupToolGroup' )[ 0 ] !== this.$element[ 0 ] ) {
11800 this.setActive( false );
11801 }
11802 };
11803
11804 /**
11805 * @inheritdoc
11806 */
11807 OO.ui.PopupToolGroup.prototype.onMouseKeyUp = function ( e ) {
11808 // Only close toolgroup when a tool was actually selected
11809 if (
11810 !this.isDisabled() && this.pressed && this.pressed === this.getTargetTool( e ) &&
11811 ( e.which === OO.ui.MouseButtons.LEFT || e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
11812 ) {
11813 this.setActive( false );
11814 }
11815 return OO.ui.PopupToolGroup.parent.prototype.onMouseKeyUp.call( this, e );
11816 };
11817
11818 /**
11819 * Handle mouse up and key up events.
11820 *
11821 * @protected
11822 * @param {jQuery.Event} e Mouse up or key up event
11823 */
11824 OO.ui.PopupToolGroup.prototype.onHandleMouseKeyUp = function ( e ) {
11825 if (
11826 !this.isDisabled() &&
11827 ( e.which === OO.ui.MouseButtons.LEFT || e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
11828 ) {
11829 return false;
11830 }
11831 };
11832
11833 /**
11834 * Handle mouse down and key down events.
11835 *
11836 * @protected
11837 * @param {jQuery.Event} e Mouse down or key down event
11838 */
11839 OO.ui.PopupToolGroup.prototype.onHandleMouseKeyDown = function ( e ) {
11840 if (
11841 !this.isDisabled() &&
11842 ( e.which === OO.ui.MouseButtons.LEFT || e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
11843 ) {
11844 this.setActive( !this.active );
11845 return false;
11846 }
11847 };
11848
11849 /**
11850 * Switch into 'active' mode.
11851 *
11852 * When active, the popup is visible. A mouseup event anywhere in the document will trigger
11853 * deactivation.
11854 */
11855 OO.ui.PopupToolGroup.prototype.setActive = function ( value ) {
11856 var containerWidth, containerLeft;
11857 value = !!value;
11858 if ( this.active !== value ) {
11859 this.active = value;
11860 if ( value ) {
11861 this.getElementDocument().addEventListener( 'mouseup', this.onBlurHandler, true );
11862 this.getElementDocument().addEventListener( 'keyup', this.onBlurHandler, true );
11863
11864 this.$clippable.css( 'left', '' );
11865 // Try anchoring the popup to the left first
11866 this.$element.addClass( 'oo-ui-popupToolGroup-active oo-ui-popupToolGroup-left' );
11867 this.toggleClipping( true );
11868 if ( this.isClippedHorizontally() ) {
11869 // Anchoring to the left caused the popup to clip, so anchor it to the right instead
11870 this.toggleClipping( false );
11871 this.$element
11872 .removeClass( 'oo-ui-popupToolGroup-left' )
11873 .addClass( 'oo-ui-popupToolGroup-right' );
11874 this.toggleClipping( true );
11875 }
11876 if ( this.isClippedHorizontally() ) {
11877 // Anchoring to the right also caused the popup to clip, so just make it fill the container
11878 containerWidth = this.$clippableScrollableContainer.width();
11879 containerLeft = this.$clippableScrollableContainer.offset().left;
11880
11881 this.toggleClipping( false );
11882 this.$element.removeClass( 'oo-ui-popupToolGroup-right' );
11883
11884 this.$clippable.css( {
11885 left: -( this.$element.offset().left - containerLeft ),
11886 width: containerWidth
11887 } );
11888 }
11889 } else {
11890 this.getElementDocument().removeEventListener( 'mouseup', this.onBlurHandler, true );
11891 this.getElementDocument().removeEventListener( 'keyup', this.onBlurHandler, true );
11892 this.$element.removeClass(
11893 'oo-ui-popupToolGroup-active oo-ui-popupToolGroup-left oo-ui-popupToolGroup-right'
11894 );
11895 this.toggleClipping( false );
11896 }
11897 }
11898 };
11899
11900 /**
11901 * ListToolGroups are one of three types of {@link OO.ui.ToolGroup toolgroups} that are used to
11902 * create {@link OO.ui.Toolbar toolbars} (the other types of groups are {@link OO.ui.MenuToolGroup MenuToolGroup}
11903 * and {@link OO.ui.BarToolGroup BarToolGroup}). The {@link OO.ui.Tool tools} in a ListToolGroup are displayed
11904 * by label in a dropdown menu. The title of the tool is used as the label text. The menu itself can be configured
11905 * with a label, icon, indicator, header, and title.
11906 *
11907 * ListToolGroups can be configured to be expanded and collapsed. Collapsed lists will have a ‘More’ option that
11908 * users can select to see the full list of tools. If a collapsed toolgroup is expanded, a ‘Fewer’ option permits
11909 * users to collapse the list again.
11910 *
11911 * ListToolGroups are created by a {@link OO.ui.ToolGroupFactory toolgroup factory} when the toolbar is set up. The factory
11912 * requires the ListToolGroup's symbolic name, 'list', which is specified along with the other configurations. For more
11913 * information about how to add tools to a ListToolGroup, please see {@link OO.ui.ToolGroup toolgroup}.
11914 *
11915 * @example
11916 * // Example of a ListToolGroup
11917 * var toolFactory = new OO.ui.ToolFactory();
11918 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
11919 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
11920 *
11921 * // Configure and register two tools
11922 * function SettingsTool() {
11923 * SettingsTool.parent.apply( this, arguments );
11924 * }
11925 * OO.inheritClass( SettingsTool, OO.ui.Tool );
11926 * SettingsTool.static.name = 'settings';
11927 * SettingsTool.static.icon = 'settings';
11928 * SettingsTool.static.title = 'Change settings';
11929 * SettingsTool.prototype.onSelect = function () {
11930 * this.setActive( false );
11931 * };
11932 * SettingsTool.prototype.onUpdateState = function () {};
11933 * toolFactory.register( SettingsTool );
11934 * // Register two more tools, nothing interesting here
11935 * function StuffTool() {
11936 * StuffTool.parent.apply( this, arguments );
11937 * }
11938 * OO.inheritClass( StuffTool, OO.ui.Tool );
11939 * StuffTool.static.name = 'stuff';
11940 * StuffTool.static.icon = 'search';
11941 * StuffTool.static.title = 'Change the world';
11942 * StuffTool.prototype.onSelect = function () {
11943 * this.setActive( false );
11944 * };
11945 * StuffTool.prototype.onUpdateState = function () {};
11946 * toolFactory.register( StuffTool );
11947 * toolbar.setup( [
11948 * {
11949 * // Configurations for list toolgroup.
11950 * type: 'list',
11951 * label: 'ListToolGroup',
11952 * indicator: 'down',
11953 * icon: 'ellipsis',
11954 * title: 'This is the title, displayed when user moves the mouse over the list toolgroup',
11955 * header: 'This is the header',
11956 * include: [ 'settings', 'stuff' ],
11957 * allowCollapse: ['stuff']
11958 * }
11959 * ] );
11960 *
11961 * // Create some UI around the toolbar and place it in the document
11962 * var frame = new OO.ui.PanelLayout( {
11963 * expanded: false,
11964 * framed: true
11965 * } );
11966 * frame.$element.append(
11967 * toolbar.$element
11968 * );
11969 * $( 'body' ).append( frame.$element );
11970 * // Build the toolbar. This must be done after the toolbar has been appended to the document.
11971 * toolbar.initialize();
11972 *
11973 * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki][1].
11974 *
11975 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
11976 *
11977 * @class
11978 * @extends OO.ui.PopupToolGroup
11979 *
11980 * @constructor
11981 * @param {OO.ui.Toolbar} toolbar
11982 * @param {Object} [config] Configuration options
11983 * @cfg {Array} [allowCollapse] Allow the specified tools to be collapsed. By default, collapsible tools
11984 * will only be displayed if users click the ‘More’ option displayed at the bottom of the list. If
11985 * the list is expanded, a ‘Fewer’ option permits users to collapse the list again. Any tools that
11986 * are included in the toolgroup, but are not designated as collapsible, will always be displayed.
11987 * To open a collapsible list in its expanded state, set #expanded to 'true'.
11988 * @cfg {Array} [forceExpand] Expand the specified tools. All other tools will be designated as collapsible.
11989 * Unless #expanded is set to true, the collapsible tools will be collapsed when the list is first opened.
11990 * @cfg {boolean} [expanded=false] Expand collapsible tools. This config is only relevant if tools have
11991 * been designated as collapsible. When expanded is set to true, all tools in the group will be displayed
11992 * when the list is first opened. Users can collapse the list with a ‘Fewer’ option at the bottom.
11993 */
11994 OO.ui.ListToolGroup = function OoUiListToolGroup( toolbar, config ) {
11995 // Allow passing positional parameters inside the config object
11996 if ( OO.isPlainObject( toolbar ) && config === undefined ) {
11997 config = toolbar;
11998 toolbar = config.toolbar;
11999 }
12000
12001 // Configuration initialization
12002 config = config || {};
12003
12004 // Properties (must be set before parent constructor, which calls #populate)
12005 this.allowCollapse = config.allowCollapse;
12006 this.forceExpand = config.forceExpand;
12007 this.expanded = config.expanded !== undefined ? config.expanded : false;
12008 this.collapsibleTools = [];
12009
12010 // Parent constructor
12011 OO.ui.ListToolGroup.parent.call( this, toolbar, config );
12012
12013 // Initialization
12014 this.$element.addClass( 'oo-ui-listToolGroup' );
12015 };
12016
12017 /* Setup */
12018
12019 OO.inheritClass( OO.ui.ListToolGroup, OO.ui.PopupToolGroup );
12020
12021 /* Static Properties */
12022
12023 OO.ui.ListToolGroup.static.name = 'list';
12024
12025 /* Methods */
12026
12027 /**
12028 * @inheritdoc
12029 */
12030 OO.ui.ListToolGroup.prototype.populate = function () {
12031 var i, len, allowCollapse = [];
12032
12033 OO.ui.ListToolGroup.parent.prototype.populate.call( this );
12034
12035 // Update the list of collapsible tools
12036 if ( this.allowCollapse !== undefined ) {
12037 allowCollapse = this.allowCollapse;
12038 } else if ( this.forceExpand !== undefined ) {
12039 allowCollapse = OO.simpleArrayDifference( Object.keys( this.tools ), this.forceExpand );
12040 }
12041
12042 this.collapsibleTools = [];
12043 for ( i = 0, len = allowCollapse.length; i < len; i++ ) {
12044 if ( this.tools[ allowCollapse[ i ] ] !== undefined ) {
12045 this.collapsibleTools.push( this.tools[ allowCollapse[ i ] ] );
12046 }
12047 }
12048
12049 // Keep at the end, even when tools are added
12050 this.$group.append( this.getExpandCollapseTool().$element );
12051
12052 this.getExpandCollapseTool().toggle( this.collapsibleTools.length !== 0 );
12053 this.updateCollapsibleState();
12054 };
12055
12056 OO.ui.ListToolGroup.prototype.getExpandCollapseTool = function () {
12057 var ExpandCollapseTool;
12058 if ( this.expandCollapseTool === undefined ) {
12059 ExpandCollapseTool = function () {
12060 ExpandCollapseTool.parent.apply( this, arguments );
12061 };
12062
12063 OO.inheritClass( ExpandCollapseTool, OO.ui.Tool );
12064
12065 ExpandCollapseTool.prototype.onSelect = function () {
12066 this.toolGroup.expanded = !this.toolGroup.expanded;
12067 this.toolGroup.updateCollapsibleState();
12068 this.setActive( false );
12069 };
12070 ExpandCollapseTool.prototype.onUpdateState = function () {
12071 // Do nothing. Tool interface requires an implementation of this function.
12072 };
12073
12074 ExpandCollapseTool.static.name = 'more-fewer';
12075
12076 this.expandCollapseTool = new ExpandCollapseTool( this );
12077 }
12078 return this.expandCollapseTool;
12079 };
12080
12081 /**
12082 * @inheritdoc
12083 */
12084 OO.ui.ListToolGroup.prototype.onMouseKeyUp = function ( e ) {
12085 // Do not close the popup when the user wants to show more/fewer tools
12086 if (
12087 $( e.target ).closest( '.oo-ui-tool-name-more-fewer' ).length &&
12088 ( e.which === OO.ui.MouseButtons.LEFT || e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
12089 ) {
12090 // HACK: Prevent the popup list from being hidden. Skip the PopupToolGroup implementation (which
12091 // hides the popup list when a tool is selected) and call ToolGroup's implementation directly.
12092 return OO.ui.ListToolGroup.parent.parent.prototype.onMouseKeyUp.call( this, e );
12093 } else {
12094 return OO.ui.ListToolGroup.parent.prototype.onMouseKeyUp.call( this, e );
12095 }
12096 };
12097
12098 OO.ui.ListToolGroup.prototype.updateCollapsibleState = function () {
12099 var i, len;
12100
12101 this.getExpandCollapseTool()
12102 .setIcon( this.expanded ? 'collapse' : 'expand' )
12103 .setTitle( OO.ui.msg( this.expanded ? 'ooui-toolgroup-collapse' : 'ooui-toolgroup-expand' ) );
12104
12105 for ( i = 0, len = this.collapsibleTools.length; i < len; i++ ) {
12106 this.collapsibleTools[ i ].toggle( this.expanded );
12107 }
12108 };
12109
12110 /**
12111 * MenuToolGroups are one of three types of {@link OO.ui.ToolGroup toolgroups} that are used to
12112 * create {@link OO.ui.Toolbar toolbars} (the other types of groups are {@link OO.ui.BarToolGroup BarToolGroup}
12113 * and {@link OO.ui.ListToolGroup ListToolGroup}). MenuToolGroups contain selectable {@link OO.ui.Tool tools},
12114 * which are displayed by label in a dropdown menu. The tool's title is used as the label text, and the
12115 * menu label is updated to reflect which tool or tools are currently selected. If no tools are selected,
12116 * the menu label is empty. The menu can be configured with an indicator, icon, title, and/or header.
12117 *
12118 * MenuToolGroups are created by a {@link OO.ui.ToolGroupFactory tool group factory} when the toolbar
12119 * is set up.
12120 *
12121 * @example
12122 * // Example of a MenuToolGroup
12123 * var toolFactory = new OO.ui.ToolFactory();
12124 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
12125 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
12126 *
12127 * // We will be placing status text in this element when tools are used
12128 * var $area = $( '<p>' ).text( 'An example of a MenuToolGroup. Select a tool from the dropdown menu.' );
12129 *
12130 * // Define the tools that we're going to place in our toolbar
12131 *
12132 * function SettingsTool() {
12133 * SettingsTool.parent.apply( this, arguments );
12134 * this.reallyActive = false;
12135 * }
12136 * OO.inheritClass( SettingsTool, OO.ui.Tool );
12137 * SettingsTool.static.name = 'settings';
12138 * SettingsTool.static.icon = 'settings';
12139 * SettingsTool.static.title = 'Change settings';
12140 * SettingsTool.prototype.onSelect = function () {
12141 * $area.text( 'Settings tool clicked!' );
12142 * // Toggle the active state on each click
12143 * this.reallyActive = !this.reallyActive;
12144 * this.setActive( this.reallyActive );
12145 * // To update the menu label
12146 * this.toolbar.emit( 'updateState' );
12147 * };
12148 * SettingsTool.prototype.onUpdateState = function () {};
12149 * toolFactory.register( SettingsTool );
12150 *
12151 * function StuffTool() {
12152 * StuffTool.parent.apply( this, arguments );
12153 * this.reallyActive = false;
12154 * }
12155 * OO.inheritClass( StuffTool, OO.ui.Tool );
12156 * StuffTool.static.name = 'stuff';
12157 * StuffTool.static.icon = 'ellipsis';
12158 * StuffTool.static.title = 'More stuff';
12159 * StuffTool.prototype.onSelect = function () {
12160 * $area.text( 'More stuff tool clicked!' );
12161 * // Toggle the active state on each click
12162 * this.reallyActive = !this.reallyActive;
12163 * this.setActive( this.reallyActive );
12164 * // To update the menu label
12165 * this.toolbar.emit( 'updateState' );
12166 * };
12167 * StuffTool.prototype.onUpdateState = function () {};
12168 * toolFactory.register( StuffTool );
12169 *
12170 * // Finally define which tools and in what order appear in the toolbar. Each tool may only be
12171 * // used once (but not all defined tools must be used).
12172 * toolbar.setup( [
12173 * {
12174 * type: 'menu',
12175 * header: 'This is the (optional) header',
12176 * title: 'This is the (optional) title',
12177 * indicator: 'down',
12178 * include: [ 'settings', 'stuff' ]
12179 * }
12180 * ] );
12181 *
12182 * // Create some UI around the toolbar and place it in the document
12183 * var frame = new OO.ui.PanelLayout( {
12184 * expanded: false,
12185 * framed: true
12186 * } );
12187 * var contentFrame = new OO.ui.PanelLayout( {
12188 * expanded: false,
12189 * padded: true
12190 * } );
12191 * frame.$element.append(
12192 * toolbar.$element,
12193 * contentFrame.$element.append( $area )
12194 * );
12195 * $( 'body' ).append( frame.$element );
12196 *
12197 * // Here is where the toolbar is actually built. This must be done after inserting it into the
12198 * // document.
12199 * toolbar.initialize();
12200 * toolbar.emit( 'updateState' );
12201 *
12202 * For more information about how to add tools to a MenuToolGroup, please see {@link OO.ui.ToolGroup toolgroup}.
12203 * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki] [1].
12204 *
12205 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
12206 *
12207 * @class
12208 * @extends OO.ui.PopupToolGroup
12209 *
12210 * @constructor
12211 * @param {OO.ui.Toolbar} toolbar
12212 * @param {Object} [config] Configuration options
12213 */
12214 OO.ui.MenuToolGroup = function OoUiMenuToolGroup( toolbar, config ) {
12215 // Allow passing positional parameters inside the config object
12216 if ( OO.isPlainObject( toolbar ) && config === undefined ) {
12217 config = toolbar;
12218 toolbar = config.toolbar;
12219 }
12220
12221 // Configuration initialization
12222 config = config || {};
12223
12224 // Parent constructor
12225 OO.ui.MenuToolGroup.parent.call( this, toolbar, config );
12226
12227 // Events
12228 this.toolbar.connect( this, { updateState: 'onUpdateState' } );
12229
12230 // Initialization
12231 this.$element.addClass( 'oo-ui-menuToolGroup' );
12232 };
12233
12234 /* Setup */
12235
12236 OO.inheritClass( OO.ui.MenuToolGroup, OO.ui.PopupToolGroup );
12237
12238 /* Static Properties */
12239
12240 OO.ui.MenuToolGroup.static.name = 'menu';
12241
12242 /* Methods */
12243
12244 /**
12245 * Handle the toolbar state being updated.
12246 *
12247 * When the state changes, the title of each active item in the menu will be joined together and
12248 * used as a label for the group. The label will be empty if none of the items are active.
12249 *
12250 * @private
12251 */
12252 OO.ui.MenuToolGroup.prototype.onUpdateState = function () {
12253 var name,
12254 labelTexts = [];
12255
12256 for ( name in this.tools ) {
12257 if ( this.tools[ name ].isActive() ) {
12258 labelTexts.push( this.tools[ name ].getTitle() );
12259 }
12260 }
12261
12262 this.setLabel( labelTexts.join( ', ' ) || ' ' );
12263 };
12264
12265 /**
12266 * Popup tools open a popup window when they are selected from the {@link OO.ui.Toolbar toolbar}. Each popup tool is configured
12267 * 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
12268 * an #onSelect or #onUpdateState method, as these methods have been implemented already.
12269 *
12270 * // Example of a popup tool. When selected, a popup tool displays
12271 * // a popup window.
12272 * function HelpTool( toolGroup, config ) {
12273 * OO.ui.PopupTool.call( this, toolGroup, $.extend( { popup: {
12274 * padded: true,
12275 * label: 'Help',
12276 * head: true
12277 * } }, config ) );
12278 * this.popup.$body.append( '<p>I am helpful!</p>' );
12279 * };
12280 * OO.inheritClass( HelpTool, OO.ui.PopupTool );
12281 * HelpTool.static.name = 'help';
12282 * HelpTool.static.icon = 'help';
12283 * HelpTool.static.title = 'Help';
12284 * toolFactory.register( HelpTool );
12285 *
12286 * For an example of a toolbar that contains a popup tool, see {@link OO.ui.Toolbar toolbars}. For more information about
12287 * toolbars in genreral, please see the [OOjs UI documentation on MediaWiki][1].
12288 *
12289 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
12290 *
12291 * @abstract
12292 * @class
12293 * @extends OO.ui.Tool
12294 * @mixins OO.ui.mixin.PopupElement
12295 *
12296 * @constructor
12297 * @param {OO.ui.ToolGroup} toolGroup
12298 * @param {Object} [config] Configuration options
12299 */
12300 OO.ui.PopupTool = function OoUiPopupTool( toolGroup, config ) {
12301 // Allow passing positional parameters inside the config object
12302 if ( OO.isPlainObject( toolGroup ) && config === undefined ) {
12303 config = toolGroup;
12304 toolGroup = config.toolGroup;
12305 }
12306
12307 // Parent constructor
12308 OO.ui.PopupTool.parent.call( this, toolGroup, config );
12309
12310 // Mixin constructors
12311 OO.ui.mixin.PopupElement.call( this, config );
12312
12313 // Initialization
12314 this.$element
12315 .addClass( 'oo-ui-popupTool' )
12316 .append( this.popup.$element );
12317 };
12318
12319 /* Setup */
12320
12321 OO.inheritClass( OO.ui.PopupTool, OO.ui.Tool );
12322 OO.mixinClass( OO.ui.PopupTool, OO.ui.mixin.PopupElement );
12323
12324 /* Methods */
12325
12326 /**
12327 * Handle the tool being selected.
12328 *
12329 * @inheritdoc
12330 */
12331 OO.ui.PopupTool.prototype.onSelect = function () {
12332 if ( !this.isDisabled() ) {
12333 this.popup.toggle();
12334 }
12335 this.setActive( false );
12336 return false;
12337 };
12338
12339 /**
12340 * Handle the toolbar state being updated.
12341 *
12342 * @inheritdoc
12343 */
12344 OO.ui.PopupTool.prototype.onUpdateState = function () {
12345 this.setActive( false );
12346 };
12347
12348 /**
12349 * A ToolGroupTool is a special sort of tool that can contain other {@link OO.ui.Tool tools}
12350 * and {@link OO.ui.ToolGroup toolgroups}. The ToolGroupTool was specifically designed to be used
12351 * inside a {@link OO.ui.BarToolGroup bar} toolgroup to provide access to additional tools from
12352 * the bar item. Included tools will be displayed in a dropdown {@link OO.ui.ListToolGroup list}
12353 * when the ToolGroupTool is selected.
12354 *
12355 * // Example: ToolGroupTool with two nested tools, 'setting1' and 'setting2', defined elsewhere.
12356 *
12357 * function SettingsTool() {
12358 * SettingsTool.parent.apply( this, arguments );
12359 * };
12360 * OO.inheritClass( SettingsTool, OO.ui.ToolGroupTool );
12361 * SettingsTool.static.name = 'settings';
12362 * SettingsTool.static.title = 'Change settings';
12363 * SettingsTool.static.groupConfig = {
12364 * icon: 'settings',
12365 * label: 'ToolGroupTool',
12366 * include: [ 'setting1', 'setting2' ]
12367 * };
12368 * toolFactory.register( SettingsTool );
12369 *
12370 * For more information, please see the [OOjs UI documentation on MediaWiki][1].
12371 *
12372 * Please note that this implementation is subject to change per [T74159] [2].
12373 *
12374 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars#ToolGroupTool
12375 * [2]: https://phabricator.wikimedia.org/T74159
12376 *
12377 * @abstract
12378 * @class
12379 * @extends OO.ui.Tool
12380 *
12381 * @constructor
12382 * @param {OO.ui.ToolGroup} toolGroup
12383 * @param {Object} [config] Configuration options
12384 */
12385 OO.ui.ToolGroupTool = function OoUiToolGroupTool( toolGroup, config ) {
12386 // Allow passing positional parameters inside the config object
12387 if ( OO.isPlainObject( toolGroup ) && config === undefined ) {
12388 config = toolGroup;
12389 toolGroup = config.toolGroup;
12390 }
12391
12392 // Parent constructor
12393 OO.ui.ToolGroupTool.parent.call( this, toolGroup, config );
12394
12395 // Properties
12396 this.innerToolGroup = this.createGroup( this.constructor.static.groupConfig );
12397
12398 // Events
12399 this.innerToolGroup.connect( this, { disable: 'onToolGroupDisable' } );
12400
12401 // Initialization
12402 this.$link.remove();
12403 this.$element
12404 .addClass( 'oo-ui-toolGroupTool' )
12405 .append( this.innerToolGroup.$element );
12406 };
12407
12408 /* Setup */
12409
12410 OO.inheritClass( OO.ui.ToolGroupTool, OO.ui.Tool );
12411
12412 /* Static Properties */
12413
12414 /**
12415 * Toolgroup configuration.
12416 *
12417 * The toolgroup configuration consists of the tools to include, as well as an icon and label
12418 * to use for the bar item. Tools can be included by symbolic name, group, or with the
12419 * wildcard selector. Please see {@link OO.ui.ToolGroup toolgroup} for more information.
12420 *
12421 * @property {Object.<string,Array>}
12422 */
12423 OO.ui.ToolGroupTool.static.groupConfig = {};
12424
12425 /* Methods */
12426
12427 /**
12428 * Handle the tool being selected.
12429 *
12430 * @inheritdoc
12431 */
12432 OO.ui.ToolGroupTool.prototype.onSelect = function () {
12433 this.innerToolGroup.setActive( !this.innerToolGroup.active );
12434 return false;
12435 };
12436
12437 /**
12438 * Synchronize disabledness state of the tool with the inner toolgroup.
12439 *
12440 * @private
12441 * @param {boolean} disabled Element is disabled
12442 */
12443 OO.ui.ToolGroupTool.prototype.onToolGroupDisable = function ( disabled ) {
12444 this.setDisabled( disabled );
12445 };
12446
12447 /**
12448 * Handle the toolbar state being updated.
12449 *
12450 * @inheritdoc
12451 */
12452 OO.ui.ToolGroupTool.prototype.onUpdateState = function () {
12453 this.setActive( false );
12454 };
12455
12456 /**
12457 * Build a {@link OO.ui.ToolGroup toolgroup} from the specified configuration.
12458 *
12459 * @param {Object.<string,Array>} group Toolgroup configuration. Please see {@link OO.ui.ToolGroup toolgroup} for
12460 * more information.
12461 * @return {OO.ui.ListToolGroup}
12462 */
12463 OO.ui.ToolGroupTool.prototype.createGroup = function ( group ) {
12464 if ( group.include === '*' ) {
12465 // Apply defaults to catch-all groups
12466 if ( group.label === undefined ) {
12467 group.label = OO.ui.msg( 'ooui-toolbar-more' );
12468 }
12469 }
12470
12471 return this.toolbar.getToolGroupFactory().create( 'list', this.toolbar, group );
12472 };
12473
12474 /**
12475 * Mixin for OO.ui.Widget subclasses to provide OO.ui.mixin.GroupElement.
12476 *
12477 * Use together with OO.ui.mixin.ItemWidget to make disabled state inheritable.
12478 *
12479 * @private
12480 * @abstract
12481 * @class
12482 * @extends OO.ui.mixin.GroupElement
12483 *
12484 * @constructor
12485 * @param {Object} [config] Configuration options
12486 */
12487 OO.ui.mixin.GroupWidget = function OoUiMixinGroupWidget( config ) {
12488 // Parent constructor
12489 OO.ui.mixin.GroupWidget.parent.call( this, config );
12490 };
12491
12492 /* Setup */
12493
12494 OO.inheritClass( OO.ui.mixin.GroupWidget, OO.ui.mixin.GroupElement );
12495
12496 /* Methods */
12497
12498 /**
12499 * Set the disabled state of the widget.
12500 *
12501 * This will also update the disabled state of child widgets.
12502 *
12503 * @param {boolean} disabled Disable widget
12504 * @chainable
12505 */
12506 OO.ui.mixin.GroupWidget.prototype.setDisabled = function ( disabled ) {
12507 var i, len;
12508
12509 // Parent method
12510 // Note: Calling #setDisabled this way assumes this is mixed into an OO.ui.Widget
12511 OO.ui.Widget.prototype.setDisabled.call( this, disabled );
12512
12513 // During construction, #setDisabled is called before the OO.ui.mixin.GroupElement constructor
12514 if ( this.items ) {
12515 for ( i = 0, len = this.items.length; i < len; i++ ) {
12516 this.items[ i ].updateDisabled();
12517 }
12518 }
12519
12520 return this;
12521 };
12522
12523 /**
12524 * Mixin for widgets used as items in widgets that mix in OO.ui.mixin.GroupWidget.
12525 *
12526 * Item widgets have a reference to a OO.ui.mixin.GroupWidget while they are attached to the group. This
12527 * allows bidirectional communication.
12528 *
12529 * Use together with OO.ui.mixin.GroupWidget to make disabled state inheritable.
12530 *
12531 * @private
12532 * @abstract
12533 * @class
12534 *
12535 * @constructor
12536 */
12537 OO.ui.mixin.ItemWidget = function OoUiMixinItemWidget() {
12538 //
12539 };
12540
12541 /* Methods */
12542
12543 /**
12544 * Check if widget is disabled.
12545 *
12546 * Checks parent if present, making disabled state inheritable.
12547 *
12548 * @return {boolean} Widget is disabled
12549 */
12550 OO.ui.mixin.ItemWidget.prototype.isDisabled = function () {
12551 return this.disabled ||
12552 ( this.elementGroup instanceof OO.ui.Widget && this.elementGroup.isDisabled() );
12553 };
12554
12555 /**
12556 * Set group element is in.
12557 *
12558 * @param {OO.ui.mixin.GroupElement|null} group Group element, null if none
12559 * @chainable
12560 */
12561 OO.ui.mixin.ItemWidget.prototype.setElementGroup = function ( group ) {
12562 // Parent method
12563 // Note: Calling #setElementGroup this way assumes this is mixed into an OO.ui.Element
12564 OO.ui.Element.prototype.setElementGroup.call( this, group );
12565
12566 // Initialize item disabled states
12567 this.updateDisabled();
12568
12569 return this;
12570 };
12571
12572 /**
12573 * OutlineControlsWidget is a set of controls for an {@link OO.ui.OutlineSelectWidget outline select widget}.
12574 * Controls include moving items up and down, removing items, and adding different kinds of items.
12575 *
12576 * **Currently, this class is only used by {@link OO.ui.BookletLayout booklet layouts}.**
12577 *
12578 * @class
12579 * @extends OO.ui.Widget
12580 * @mixins OO.ui.mixin.GroupElement
12581 * @mixins OO.ui.mixin.IconElement
12582 *
12583 * @constructor
12584 * @param {OO.ui.OutlineSelectWidget} outline Outline to control
12585 * @param {Object} [config] Configuration options
12586 * @cfg {Object} [abilities] List of abilties
12587 * @cfg {boolean} [abilities.move=true] Allow moving movable items
12588 * @cfg {boolean} [abilities.remove=true] Allow removing removable items
12589 */
12590 OO.ui.OutlineControlsWidget = function OoUiOutlineControlsWidget( outline, config ) {
12591 // Allow passing positional parameters inside the config object
12592 if ( OO.isPlainObject( outline ) && config === undefined ) {
12593 config = outline;
12594 outline = config.outline;
12595 }
12596
12597 // Configuration initialization
12598 config = $.extend( { icon: 'add' }, config );
12599
12600 // Parent constructor
12601 OO.ui.OutlineControlsWidget.parent.call( this, config );
12602
12603 // Mixin constructors
12604 OO.ui.mixin.GroupElement.call( this, config );
12605 OO.ui.mixin.IconElement.call( this, config );
12606
12607 // Properties
12608 this.outline = outline;
12609 this.$movers = $( '<div>' );
12610 this.upButton = new OO.ui.ButtonWidget( {
12611 framed: false,
12612 icon: 'collapse',
12613 title: OO.ui.msg( 'ooui-outline-control-move-up' )
12614 } );
12615 this.downButton = new OO.ui.ButtonWidget( {
12616 framed: false,
12617 icon: 'expand',
12618 title: OO.ui.msg( 'ooui-outline-control-move-down' )
12619 } );
12620 this.removeButton = new OO.ui.ButtonWidget( {
12621 framed: false,
12622 icon: 'remove',
12623 title: OO.ui.msg( 'ooui-outline-control-remove' )
12624 } );
12625 this.abilities = { move: true, remove: true };
12626
12627 // Events
12628 outline.connect( this, {
12629 select: 'onOutlineChange',
12630 add: 'onOutlineChange',
12631 remove: 'onOutlineChange'
12632 } );
12633 this.upButton.connect( this, { click: [ 'emit', 'move', -1 ] } );
12634 this.downButton.connect( this, { click: [ 'emit', 'move', 1 ] } );
12635 this.removeButton.connect( this, { click: [ 'emit', 'remove' ] } );
12636
12637 // Initialization
12638 this.$element.addClass( 'oo-ui-outlineControlsWidget' );
12639 this.$group.addClass( 'oo-ui-outlineControlsWidget-items' );
12640 this.$movers
12641 .addClass( 'oo-ui-outlineControlsWidget-movers' )
12642 .append( this.removeButton.$element, this.upButton.$element, this.downButton.$element );
12643 this.$element.append( this.$icon, this.$group, this.$movers );
12644 this.setAbilities( config.abilities || {} );
12645 };
12646
12647 /* Setup */
12648
12649 OO.inheritClass( OO.ui.OutlineControlsWidget, OO.ui.Widget );
12650 OO.mixinClass( OO.ui.OutlineControlsWidget, OO.ui.mixin.GroupElement );
12651 OO.mixinClass( OO.ui.OutlineControlsWidget, OO.ui.mixin.IconElement );
12652
12653 /* Events */
12654
12655 /**
12656 * @event move
12657 * @param {number} places Number of places to move
12658 */
12659
12660 /**
12661 * @event remove
12662 */
12663
12664 /* Methods */
12665
12666 /**
12667 * Set abilities.
12668 *
12669 * @param {Object} abilities List of abilties
12670 * @param {boolean} [abilities.move] Allow moving movable items
12671 * @param {boolean} [abilities.remove] Allow removing removable items
12672 */
12673 OO.ui.OutlineControlsWidget.prototype.setAbilities = function ( abilities ) {
12674 var ability;
12675
12676 for ( ability in this.abilities ) {
12677 if ( abilities[ ability ] !== undefined ) {
12678 this.abilities[ ability ] = !!abilities[ ability ];
12679 }
12680 }
12681
12682 this.onOutlineChange();
12683 };
12684
12685 /**
12686 * @private
12687 * Handle outline change events.
12688 */
12689 OO.ui.OutlineControlsWidget.prototype.onOutlineChange = function () {
12690 var i, len, firstMovable, lastMovable,
12691 items = this.outline.getItems(),
12692 selectedItem = this.outline.getSelectedItem(),
12693 movable = this.abilities.move && selectedItem && selectedItem.isMovable(),
12694 removable = this.abilities.remove && selectedItem && selectedItem.isRemovable();
12695
12696 if ( movable ) {
12697 i = -1;
12698 len = items.length;
12699 while ( ++i < len ) {
12700 if ( items[ i ].isMovable() ) {
12701 firstMovable = items[ i ];
12702 break;
12703 }
12704 }
12705 i = len;
12706 while ( i-- ) {
12707 if ( items[ i ].isMovable() ) {
12708 lastMovable = items[ i ];
12709 break;
12710 }
12711 }
12712 }
12713 this.upButton.setDisabled( !movable || selectedItem === firstMovable );
12714 this.downButton.setDisabled( !movable || selectedItem === lastMovable );
12715 this.removeButton.setDisabled( !removable );
12716 };
12717
12718 /**
12719 * ToggleWidget implements basic behavior of widgets with an on/off state.
12720 * Please see OO.ui.ToggleButtonWidget and OO.ui.ToggleSwitchWidget for examples.
12721 *
12722 * @abstract
12723 * @class
12724 * @extends OO.ui.Widget
12725 *
12726 * @constructor
12727 * @param {Object} [config] Configuration options
12728 * @cfg {boolean} [value=false] The toggle’s initial on/off state.
12729 * By default, the toggle is in the 'off' state.
12730 */
12731 OO.ui.ToggleWidget = function OoUiToggleWidget( config ) {
12732 // Configuration initialization
12733 config = config || {};
12734
12735 // Parent constructor
12736 OO.ui.ToggleWidget.parent.call( this, config );
12737
12738 // Properties
12739 this.value = null;
12740
12741 // Initialization
12742 this.$element.addClass( 'oo-ui-toggleWidget' );
12743 this.setValue( !!config.value );
12744 };
12745
12746 /* Setup */
12747
12748 OO.inheritClass( OO.ui.ToggleWidget, OO.ui.Widget );
12749
12750 /* Events */
12751
12752 /**
12753 * @event change
12754 *
12755 * A change event is emitted when the on/off state of the toggle changes.
12756 *
12757 * @param {boolean} value Value representing the new state of the toggle
12758 */
12759
12760 /* Methods */
12761
12762 /**
12763 * Get the value representing the toggle’s state.
12764 *
12765 * @return {boolean} The on/off state of the toggle
12766 */
12767 OO.ui.ToggleWidget.prototype.getValue = function () {
12768 return this.value;
12769 };
12770
12771 /**
12772 * Set the state of the toggle: `true` for 'on', `false' for 'off'.
12773 *
12774 * @param {boolean} value The state of the toggle
12775 * @fires change
12776 * @chainable
12777 */
12778 OO.ui.ToggleWidget.prototype.setValue = function ( value ) {
12779 value = !!value;
12780 if ( this.value !== value ) {
12781 this.value = value;
12782 this.emit( 'change', value );
12783 this.$element.toggleClass( 'oo-ui-toggleWidget-on', value );
12784 this.$element.toggleClass( 'oo-ui-toggleWidget-off', !value );
12785 this.$element.attr( 'aria-checked', value.toString() );
12786 }
12787 return this;
12788 };
12789
12790 /**
12791 * A ButtonGroupWidget groups related buttons and is used together with OO.ui.ButtonWidget and
12792 * its subclasses. Each button in a group is addressed by a unique reference. Buttons can be added,
12793 * removed, and cleared from the group.
12794 *
12795 * @example
12796 * // Example: A ButtonGroupWidget with two buttons
12797 * var button1 = new OO.ui.PopupButtonWidget( {
12798 * label: 'Select a category',
12799 * icon: 'menu',
12800 * popup: {
12801 * $content: $( '<p>List of categories...</p>' ),
12802 * padded: true,
12803 * align: 'left'
12804 * }
12805 * } );
12806 * var button2 = new OO.ui.ButtonWidget( {
12807 * label: 'Add item'
12808 * });
12809 * var buttonGroup = new OO.ui.ButtonGroupWidget( {
12810 * items: [button1, button2]
12811 * } );
12812 * $( 'body' ).append( buttonGroup.$element );
12813 *
12814 * @class
12815 * @extends OO.ui.Widget
12816 * @mixins OO.ui.mixin.GroupElement
12817 *
12818 * @constructor
12819 * @param {Object} [config] Configuration options
12820 * @cfg {OO.ui.ButtonWidget[]} [items] Buttons to add
12821 */
12822 OO.ui.ButtonGroupWidget = function OoUiButtonGroupWidget( config ) {
12823 // Configuration initialization
12824 config = config || {};
12825
12826 // Parent constructor
12827 OO.ui.ButtonGroupWidget.parent.call( this, config );
12828
12829 // Mixin constructors
12830 OO.ui.mixin.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) );
12831
12832 // Initialization
12833 this.$element.addClass( 'oo-ui-buttonGroupWidget' );
12834 if ( Array.isArray( config.items ) ) {
12835 this.addItems( config.items );
12836 }
12837 };
12838
12839 /* Setup */
12840
12841 OO.inheritClass( OO.ui.ButtonGroupWidget, OO.ui.Widget );
12842 OO.mixinClass( OO.ui.ButtonGroupWidget, OO.ui.mixin.GroupElement );
12843
12844 /**
12845 * ButtonWidget is a generic widget for buttons. A wide variety of looks,
12846 * feels, and functionality can be customized via the class’s configuration options
12847 * and methods. Please see the [OOjs UI documentation on MediaWiki] [1] for more information
12848 * and examples.
12849 *
12850 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches
12851 *
12852 * @example
12853 * // A button widget
12854 * var button = new OO.ui.ButtonWidget( {
12855 * label: 'Button with Icon',
12856 * icon: 'remove',
12857 * iconTitle: 'Remove'
12858 * } );
12859 * $( 'body' ).append( button.$element );
12860 *
12861 * NOTE: HTML form buttons should use the OO.ui.ButtonInputWidget class.
12862 *
12863 * @class
12864 * @extends OO.ui.Widget
12865 * @mixins OO.ui.mixin.ButtonElement
12866 * @mixins OO.ui.mixin.IconElement
12867 * @mixins OO.ui.mixin.IndicatorElement
12868 * @mixins OO.ui.mixin.LabelElement
12869 * @mixins OO.ui.mixin.TitledElement
12870 * @mixins OO.ui.mixin.FlaggedElement
12871 * @mixins OO.ui.mixin.TabIndexedElement
12872 * @mixins OO.ui.mixin.AccessKeyedElement
12873 *
12874 * @constructor
12875 * @param {Object} [config] Configuration options
12876 * @cfg {string} [href] Hyperlink to visit when the button is clicked.
12877 * @cfg {string} [target] The frame or window in which to open the hyperlink.
12878 * @cfg {boolean} [noFollow] Search engine traversal hint (default: true)
12879 */
12880 OO.ui.ButtonWidget = function OoUiButtonWidget( config ) {
12881 // Configuration initialization
12882 config = config || {};
12883
12884 // Parent constructor
12885 OO.ui.ButtonWidget.parent.call( this, config );
12886
12887 // Mixin constructors
12888 OO.ui.mixin.ButtonElement.call( this, config );
12889 OO.ui.mixin.IconElement.call( this, config );
12890 OO.ui.mixin.IndicatorElement.call( this, config );
12891 OO.ui.mixin.LabelElement.call( this, config );
12892 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$button } ) );
12893 OO.ui.mixin.FlaggedElement.call( this, config );
12894 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$button } ) );
12895 OO.ui.mixin.AccessKeyedElement.call( this, $.extend( {}, config, { $accessKeyed: this.$button } ) );
12896
12897 // Properties
12898 this.href = null;
12899 this.target = null;
12900 this.noFollow = false;
12901
12902 // Events
12903 this.connect( this, { disable: 'onDisable' } );
12904
12905 // Initialization
12906 this.$button.append( this.$icon, this.$label, this.$indicator );
12907 this.$element
12908 .addClass( 'oo-ui-buttonWidget' )
12909 .append( this.$button );
12910 this.setHref( config.href );
12911 this.setTarget( config.target );
12912 this.setNoFollow( config.noFollow );
12913 };
12914
12915 /* Setup */
12916
12917 OO.inheritClass( OO.ui.ButtonWidget, OO.ui.Widget );
12918 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.ButtonElement );
12919 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.IconElement );
12920 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.IndicatorElement );
12921 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.LabelElement );
12922 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.TitledElement );
12923 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.FlaggedElement );
12924 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.TabIndexedElement );
12925 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.AccessKeyedElement );
12926
12927 /* Methods */
12928
12929 /**
12930 * @inheritdoc
12931 */
12932 OO.ui.ButtonWidget.prototype.onMouseDown = function ( e ) {
12933 if ( !this.isDisabled() ) {
12934 // Remove the tab-index while the button is down to prevent the button from stealing focus
12935 this.$button.removeAttr( 'tabindex' );
12936 }
12937
12938 return OO.ui.mixin.ButtonElement.prototype.onMouseDown.call( this, e );
12939 };
12940
12941 /**
12942 * @inheritdoc
12943 */
12944 OO.ui.ButtonWidget.prototype.onMouseUp = function ( e ) {
12945 if ( !this.isDisabled() ) {
12946 // Restore the tab-index after the button is up to restore the button's accessibility
12947 this.$button.attr( 'tabindex', this.tabIndex );
12948 }
12949
12950 return OO.ui.mixin.ButtonElement.prototype.onMouseUp.call( this, e );
12951 };
12952
12953 /**
12954 * Get hyperlink location.
12955 *
12956 * @return {string} Hyperlink location
12957 */
12958 OO.ui.ButtonWidget.prototype.getHref = function () {
12959 return this.href;
12960 };
12961
12962 /**
12963 * Get hyperlink target.
12964 *
12965 * @return {string} Hyperlink target
12966 */
12967 OO.ui.ButtonWidget.prototype.getTarget = function () {
12968 return this.target;
12969 };
12970
12971 /**
12972 * Get search engine traversal hint.
12973 *
12974 * @return {boolean} Whether search engines should avoid traversing this hyperlink
12975 */
12976 OO.ui.ButtonWidget.prototype.getNoFollow = function () {
12977 return this.noFollow;
12978 };
12979
12980 /**
12981 * Set hyperlink location.
12982 *
12983 * @param {string|null} href Hyperlink location, null to remove
12984 */
12985 OO.ui.ButtonWidget.prototype.setHref = function ( href ) {
12986 href = typeof href === 'string' ? href : null;
12987 if ( href !== null ) {
12988 if ( !OO.ui.isSafeUrl( href ) ) {
12989 throw new Error( 'Potentially unsafe href provided: ' + href );
12990 }
12991
12992 }
12993
12994 if ( href !== this.href ) {
12995 this.href = href;
12996 this.updateHref();
12997 }
12998
12999 return this;
13000 };
13001
13002 /**
13003 * Update the `href` attribute, in case of changes to href or
13004 * disabled state.
13005 *
13006 * @private
13007 * @chainable
13008 */
13009 OO.ui.ButtonWidget.prototype.updateHref = function () {
13010 if ( this.href !== null && !this.isDisabled() ) {
13011 this.$button.attr( 'href', this.href );
13012 } else {
13013 this.$button.removeAttr( 'href' );
13014 }
13015
13016 return this;
13017 };
13018
13019 /**
13020 * Handle disable events.
13021 *
13022 * @private
13023 * @param {boolean} disabled Element is disabled
13024 */
13025 OO.ui.ButtonWidget.prototype.onDisable = function () {
13026 this.updateHref();
13027 };
13028
13029 /**
13030 * Set hyperlink target.
13031 *
13032 * @param {string|null} target Hyperlink target, null to remove
13033 */
13034 OO.ui.ButtonWidget.prototype.setTarget = function ( target ) {
13035 target = typeof target === 'string' ? target : null;
13036
13037 if ( target !== this.target ) {
13038 this.target = target;
13039 if ( target !== null ) {
13040 this.$button.attr( 'target', target );
13041 } else {
13042 this.$button.removeAttr( 'target' );
13043 }
13044 }
13045
13046 return this;
13047 };
13048
13049 /**
13050 * Set search engine traversal hint.
13051 *
13052 * @param {boolean} noFollow True if search engines should avoid traversing this hyperlink
13053 */
13054 OO.ui.ButtonWidget.prototype.setNoFollow = function ( noFollow ) {
13055 noFollow = typeof noFollow === 'boolean' ? noFollow : true;
13056
13057 if ( noFollow !== this.noFollow ) {
13058 this.noFollow = noFollow;
13059 if ( noFollow ) {
13060 this.$button.attr( 'rel', 'nofollow' );
13061 } else {
13062 this.$button.removeAttr( 'rel' );
13063 }
13064 }
13065
13066 return this;
13067 };
13068
13069 /**
13070 * An ActionWidget is a {@link OO.ui.ButtonWidget button widget} that executes an action.
13071 * Action widgets are used with OO.ui.ActionSet, which manages the behavior and availability
13072 * of the actions.
13073 *
13074 * Both actions and action sets are primarily used with {@link OO.ui.Dialog Dialogs}.
13075 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information
13076 * and examples.
13077 *
13078 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Action_sets
13079 *
13080 * @class
13081 * @extends OO.ui.ButtonWidget
13082 * @mixins OO.ui.mixin.PendingElement
13083 *
13084 * @constructor
13085 * @param {Object} [config] Configuration options
13086 * @cfg {string} [action] Symbolic name of the action (e.g., ‘continue’ or ‘cancel’).
13087 * @cfg {string[]} [modes] Symbolic names of the modes (e.g., ‘edit’ or ‘read’) in which the action
13088 * should be made available. See the action set's {@link OO.ui.ActionSet#setMode setMode} method
13089 * for more information about setting modes.
13090 * @cfg {boolean} [framed=false] Render the action button with a frame
13091 */
13092 OO.ui.ActionWidget = function OoUiActionWidget( config ) {
13093 // Configuration initialization
13094 config = $.extend( { framed: false }, config );
13095
13096 // Parent constructor
13097 OO.ui.ActionWidget.parent.call( this, config );
13098
13099 // Mixin constructors
13100 OO.ui.mixin.PendingElement.call( this, config );
13101
13102 // Properties
13103 this.action = config.action || '';
13104 this.modes = config.modes || [];
13105 this.width = 0;
13106 this.height = 0;
13107
13108 // Initialization
13109 this.$element.addClass( 'oo-ui-actionWidget' );
13110 };
13111
13112 /* Setup */
13113
13114 OO.inheritClass( OO.ui.ActionWidget, OO.ui.ButtonWidget );
13115 OO.mixinClass( OO.ui.ActionWidget, OO.ui.mixin.PendingElement );
13116
13117 /* Events */
13118
13119 /**
13120 * A resize event is emitted when the size of the widget changes.
13121 *
13122 * @event resize
13123 */
13124
13125 /* Methods */
13126
13127 /**
13128 * Check if the action is configured to be available in the specified `mode`.
13129 *
13130 * @param {string} mode Name of mode
13131 * @return {boolean} The action is configured with the mode
13132 */
13133 OO.ui.ActionWidget.prototype.hasMode = function ( mode ) {
13134 return this.modes.indexOf( mode ) !== -1;
13135 };
13136
13137 /**
13138 * Get the symbolic name of the action (e.g., ‘continue’ or ‘cancel’).
13139 *
13140 * @return {string}
13141 */
13142 OO.ui.ActionWidget.prototype.getAction = function () {
13143 return this.action;
13144 };
13145
13146 /**
13147 * Get the symbolic name of the mode or modes for which the action is configured to be available.
13148 *
13149 * The current mode is set with the action set's {@link OO.ui.ActionSet#setMode setMode} method.
13150 * Only actions that are configured to be avaiable in the current mode will be visible. All other actions
13151 * are hidden.
13152 *
13153 * @return {string[]}
13154 */
13155 OO.ui.ActionWidget.prototype.getModes = function () {
13156 return this.modes.slice();
13157 };
13158
13159 /**
13160 * Emit a resize event if the size has changed.
13161 *
13162 * @private
13163 * @chainable
13164 */
13165 OO.ui.ActionWidget.prototype.propagateResize = function () {
13166 var width, height;
13167
13168 if ( this.isElementAttached() ) {
13169 width = this.$element.width();
13170 height = this.$element.height();
13171
13172 if ( width !== this.width || height !== this.height ) {
13173 this.width = width;
13174 this.height = height;
13175 this.emit( 'resize' );
13176 }
13177 }
13178
13179 return this;
13180 };
13181
13182 /**
13183 * @inheritdoc
13184 */
13185 OO.ui.ActionWidget.prototype.setIcon = function () {
13186 // Mixin method
13187 OO.ui.mixin.IconElement.prototype.setIcon.apply( this, arguments );
13188 this.propagateResize();
13189
13190 return this;
13191 };
13192
13193 /**
13194 * @inheritdoc
13195 */
13196 OO.ui.ActionWidget.prototype.setLabel = function () {
13197 // Mixin method
13198 OO.ui.mixin.LabelElement.prototype.setLabel.apply( this, arguments );
13199 this.propagateResize();
13200
13201 return this;
13202 };
13203
13204 /**
13205 * @inheritdoc
13206 */
13207 OO.ui.ActionWidget.prototype.setFlags = function () {
13208 // Mixin method
13209 OO.ui.mixin.FlaggedElement.prototype.setFlags.apply( this, arguments );
13210 this.propagateResize();
13211
13212 return this;
13213 };
13214
13215 /**
13216 * @inheritdoc
13217 */
13218 OO.ui.ActionWidget.prototype.clearFlags = function () {
13219 // Mixin method
13220 OO.ui.mixin.FlaggedElement.prototype.clearFlags.apply( this, arguments );
13221 this.propagateResize();
13222
13223 return this;
13224 };
13225
13226 /**
13227 * Toggle the visibility of the action button.
13228 *
13229 * @param {boolean} [show] Show button, omit to toggle visibility
13230 * @chainable
13231 */
13232 OO.ui.ActionWidget.prototype.toggle = function () {
13233 // Parent method
13234 OO.ui.ActionWidget.parent.prototype.toggle.apply( this, arguments );
13235 this.propagateResize();
13236
13237 return this;
13238 };
13239
13240 /**
13241 * PopupButtonWidgets toggle the visibility of a contained {@link OO.ui.PopupWidget PopupWidget},
13242 * which is used to display additional information or options.
13243 *
13244 * @example
13245 * // Example of a popup button.
13246 * var popupButton = new OO.ui.PopupButtonWidget( {
13247 * label: 'Popup button with options',
13248 * icon: 'menu',
13249 * popup: {
13250 * $content: $( '<p>Additional options here.</p>' ),
13251 * padded: true,
13252 * align: 'force-left'
13253 * }
13254 * } );
13255 * // Append the button to the DOM.
13256 * $( 'body' ).append( popupButton.$element );
13257 *
13258 * @class
13259 * @extends OO.ui.ButtonWidget
13260 * @mixins OO.ui.mixin.PopupElement
13261 *
13262 * @constructor
13263 * @param {Object} [config] Configuration options
13264 */
13265 OO.ui.PopupButtonWidget = function OoUiPopupButtonWidget( config ) {
13266 // Parent constructor
13267 OO.ui.PopupButtonWidget.parent.call( this, config );
13268
13269 // Mixin constructors
13270 OO.ui.mixin.PopupElement.call( this, config );
13271
13272 // Events
13273 this.connect( this, { click: 'onAction' } );
13274
13275 // Initialization
13276 this.$element
13277 .addClass( 'oo-ui-popupButtonWidget' )
13278 .attr( 'aria-haspopup', 'true' )
13279 .append( this.popup.$element );
13280 };
13281
13282 /* Setup */
13283
13284 OO.inheritClass( OO.ui.PopupButtonWidget, OO.ui.ButtonWidget );
13285 OO.mixinClass( OO.ui.PopupButtonWidget, OO.ui.mixin.PopupElement );
13286
13287 /* Methods */
13288
13289 /**
13290 * Handle the button action being triggered.
13291 *
13292 * @private
13293 */
13294 OO.ui.PopupButtonWidget.prototype.onAction = function () {
13295 this.popup.toggle();
13296 };
13297
13298 /**
13299 * ToggleButtons are buttons that have a state (‘on’ or ‘off’) that is represented by a
13300 * Boolean value. Like other {@link OO.ui.ButtonWidget buttons}, toggle buttons can be
13301 * configured with {@link OO.ui.mixin.IconElement icons}, {@link OO.ui.mixin.IndicatorElement indicators},
13302 * {@link OO.ui.mixin.TitledElement titles}, {@link OO.ui.mixin.FlaggedElement styling flags},
13303 * and {@link OO.ui.mixin.LabelElement labels}. Please see
13304 * the [OOjs UI documentation][1] on MediaWiki for more information.
13305 *
13306 * @example
13307 * // Toggle buttons in the 'off' and 'on' state.
13308 * var toggleButton1 = new OO.ui.ToggleButtonWidget( {
13309 * label: 'Toggle Button off'
13310 * } );
13311 * var toggleButton2 = new OO.ui.ToggleButtonWidget( {
13312 * label: 'Toggle Button on',
13313 * value: true
13314 * } );
13315 * // Append the buttons to the DOM.
13316 * $( 'body' ).append( toggleButton1.$element, toggleButton2.$element );
13317 *
13318 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#Toggle_buttons
13319 *
13320 * @class
13321 * @extends OO.ui.ToggleWidget
13322 * @mixins OO.ui.mixin.ButtonElement
13323 * @mixins OO.ui.mixin.IconElement
13324 * @mixins OO.ui.mixin.IndicatorElement
13325 * @mixins OO.ui.mixin.LabelElement
13326 * @mixins OO.ui.mixin.TitledElement
13327 * @mixins OO.ui.mixin.FlaggedElement
13328 * @mixins OO.ui.mixin.TabIndexedElement
13329 *
13330 * @constructor
13331 * @param {Object} [config] Configuration options
13332 * @cfg {boolean} [value=false] The toggle button’s initial on/off
13333 * state. By default, the button is in the 'off' state.
13334 */
13335 OO.ui.ToggleButtonWidget = function OoUiToggleButtonWidget( config ) {
13336 // Configuration initialization
13337 config = config || {};
13338
13339 // Parent constructor
13340 OO.ui.ToggleButtonWidget.parent.call( this, config );
13341
13342 // Mixin constructors
13343 OO.ui.mixin.ButtonElement.call( this, config );
13344 OO.ui.mixin.IconElement.call( this, config );
13345 OO.ui.mixin.IndicatorElement.call( this, config );
13346 OO.ui.mixin.LabelElement.call( this, config );
13347 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$button } ) );
13348 OO.ui.mixin.FlaggedElement.call( this, config );
13349 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$button } ) );
13350
13351 // Events
13352 this.connect( this, { click: 'onAction' } );
13353
13354 // Initialization
13355 this.$button.append( this.$icon, this.$label, this.$indicator );
13356 this.$element
13357 .addClass( 'oo-ui-toggleButtonWidget' )
13358 .append( this.$button );
13359 };
13360
13361 /* Setup */
13362
13363 OO.inheritClass( OO.ui.ToggleButtonWidget, OO.ui.ToggleWidget );
13364 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.ButtonElement );
13365 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.IconElement );
13366 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.IndicatorElement );
13367 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.LabelElement );
13368 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.TitledElement );
13369 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.FlaggedElement );
13370 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.TabIndexedElement );
13371
13372 /* Methods */
13373
13374 /**
13375 * Handle the button action being triggered.
13376 *
13377 * @private
13378 */
13379 OO.ui.ToggleButtonWidget.prototype.onAction = function () {
13380 this.setValue( !this.value );
13381 };
13382
13383 /**
13384 * @inheritdoc
13385 */
13386 OO.ui.ToggleButtonWidget.prototype.setValue = function ( value ) {
13387 value = !!value;
13388 if ( value !== this.value ) {
13389 // Might be called from parent constructor before ButtonElement constructor
13390 if ( this.$button ) {
13391 this.$button.attr( 'aria-pressed', value.toString() );
13392 }
13393 this.setActive( value );
13394 }
13395
13396 // Parent method
13397 OO.ui.ToggleButtonWidget.parent.prototype.setValue.call( this, value );
13398
13399 return this;
13400 };
13401
13402 /**
13403 * @inheritdoc
13404 */
13405 OO.ui.ToggleButtonWidget.prototype.setButtonElement = function ( $button ) {
13406 if ( this.$button ) {
13407 this.$button.removeAttr( 'aria-pressed' );
13408 }
13409 OO.ui.mixin.ButtonElement.prototype.setButtonElement.call( this, $button );
13410 this.$button.attr( 'aria-pressed', this.value.toString() );
13411 };
13412
13413 /**
13414 * CapsuleMultiSelectWidgets are something like a {@link OO.ui.ComboBoxInputWidget combo box widget}
13415 * that allows for selecting multiple values.
13416 *
13417 * For more information about menus and options, please see the [OOjs UI documentation on MediaWiki][1].
13418 *
13419 * @example
13420 * // Example: A CapsuleMultiSelectWidget.
13421 * var capsule = new OO.ui.CapsuleMultiSelectWidget( {
13422 * label: 'CapsuleMultiSelectWidget',
13423 * selected: [ 'Option 1', 'Option 3' ],
13424 * menu: {
13425 * items: [
13426 * new OO.ui.MenuOptionWidget( {
13427 * data: 'Option 1',
13428 * label: 'Option One'
13429 * } ),
13430 * new OO.ui.MenuOptionWidget( {
13431 * data: 'Option 2',
13432 * label: 'Option Two'
13433 * } ),
13434 * new OO.ui.MenuOptionWidget( {
13435 * data: 'Option 3',
13436 * label: 'Option Three'
13437 * } ),
13438 * new OO.ui.MenuOptionWidget( {
13439 * data: 'Option 4',
13440 * label: 'Option Four'
13441 * } ),
13442 * new OO.ui.MenuOptionWidget( {
13443 * data: 'Option 5',
13444 * label: 'Option Five'
13445 * } )
13446 * ]
13447 * }
13448 * } );
13449 * $( 'body' ).append( capsule.$element );
13450 *
13451 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
13452 *
13453 * @class
13454 * @extends OO.ui.Widget
13455 * @mixins OO.ui.mixin.TabIndexedElement
13456 * @mixins OO.ui.mixin.GroupElement
13457 *
13458 * @constructor
13459 * @param {Object} [config] Configuration options
13460 * @cfg {boolean} [allowArbitrary=false] Allow data items to be added even if not present in the menu.
13461 * @cfg {Object} [menu] Configuration options to pass to the {@link OO.ui.MenuSelectWidget menu select widget}.
13462 * @cfg {Object} [popup] Configuration options to pass to the {@link OO.ui.PopupWidget popup widget}.
13463 * If specified, this popup will be shown instead of the menu (but the menu
13464 * will still be used for item labels and allowArbitrary=false). The widgets
13465 * in the popup should use this.addItemsFromData() or this.addItems() as necessary.
13466 * @cfg {jQuery} [$overlay] Render the menu or popup into a separate layer.
13467 * This configuration is useful in cases where the expanded menu is larger than
13468 * its containing `<div>`. The specified overlay layer is usually on top of
13469 * the containing `<div>` and has a larger area. By default, the menu uses
13470 * relative positioning.
13471 */
13472 OO.ui.CapsuleMultiSelectWidget = function OoUiCapsuleMultiSelectWidget( config ) {
13473 var $tabFocus;
13474
13475 // Configuration initialization
13476 config = config || {};
13477
13478 // Parent constructor
13479 OO.ui.CapsuleMultiSelectWidget.parent.call( this, config );
13480
13481 // Properties (must be set before mixin constructor calls)
13482 this.$input = config.popup ? null : $( '<input>' );
13483 this.$handle = $( '<div>' );
13484
13485 // Mixin constructors
13486 OO.ui.mixin.GroupElement.call( this, config );
13487 if ( config.popup ) {
13488 config.popup = $.extend( {}, config.popup, {
13489 align: 'forwards',
13490 anchor: false
13491 } );
13492 OO.ui.mixin.PopupElement.call( this, config );
13493 $tabFocus = $( '<span>' );
13494 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: $tabFocus } ) );
13495 } else {
13496 this.popup = null;
13497 $tabFocus = null;
13498 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$input } ) );
13499 }
13500 OO.ui.mixin.IndicatorElement.call( this, config );
13501 OO.ui.mixin.IconElement.call( this, config );
13502
13503 // Properties
13504 this.$content = $( '<div>' );
13505 this.allowArbitrary = !!config.allowArbitrary;
13506 this.$overlay = config.$overlay || this.$element;
13507 this.menu = new OO.ui.FloatingMenuSelectWidget( $.extend(
13508 {
13509 widget: this,
13510 $input: this.$input,
13511 $container: this.$element,
13512 filterFromInput: true,
13513 disabled: this.isDisabled()
13514 },
13515 config.menu
13516 ) );
13517
13518 // Events
13519 if ( this.popup ) {
13520 $tabFocus.on( {
13521 focus: this.onFocusForPopup.bind( this )
13522 } );
13523 this.popup.$element.on( 'focusout', this.onPopupFocusOut.bind( this ) );
13524 if ( this.popup.$autoCloseIgnore ) {
13525 this.popup.$autoCloseIgnore.on( 'focusout', this.onPopupFocusOut.bind( this ) );
13526 }
13527 this.popup.connect( this, {
13528 toggle: function ( visible ) {
13529 $tabFocus.toggle( !visible );
13530 }
13531 } );
13532 } else {
13533 this.$input.on( {
13534 focus: this.onInputFocus.bind( this ),
13535 blur: this.onInputBlur.bind( this ),
13536 'propertychange change click mouseup keydown keyup input cut paste select focus':
13537 OO.ui.debounce( this.updateInputSize.bind( this ) ),
13538 keydown: this.onKeyDown.bind( this ),
13539 keypress: this.onKeyPress.bind( this )
13540 } );
13541 }
13542 this.menu.connect( this, {
13543 choose: 'onMenuChoose',
13544 add: 'onMenuItemsChange',
13545 remove: 'onMenuItemsChange'
13546 } );
13547 this.$handle.on( {
13548 mousedown: this.onMouseDown.bind( this )
13549 } );
13550
13551 // Initialization
13552 if ( this.$input ) {
13553 this.$input.prop( 'disabled', this.isDisabled() );
13554 this.$input.attr( {
13555 role: 'combobox',
13556 'aria-autocomplete': 'list'
13557 } );
13558 this.updateInputSize();
13559 }
13560 if ( config.data ) {
13561 this.setItemsFromData( config.data );
13562 }
13563 this.$content.addClass( 'oo-ui-capsuleMultiSelectWidget-content' )
13564 .append( this.$group );
13565 this.$group.addClass( 'oo-ui-capsuleMultiSelectWidget-group' );
13566 this.$handle.addClass( 'oo-ui-capsuleMultiSelectWidget-handle' )
13567 .append( this.$indicator, this.$icon, this.$content );
13568 this.$element.addClass( 'oo-ui-capsuleMultiSelectWidget' )
13569 .append( this.$handle );
13570 if ( this.popup ) {
13571 this.$content.append( $tabFocus );
13572 this.$overlay.append( this.popup.$element );
13573 } else {
13574 this.$content.append( this.$input );
13575 this.$overlay.append( this.menu.$element );
13576 }
13577 this.onMenuItemsChange();
13578 };
13579
13580 /* Setup */
13581
13582 OO.inheritClass( OO.ui.CapsuleMultiSelectWidget, OO.ui.Widget );
13583 OO.mixinClass( OO.ui.CapsuleMultiSelectWidget, OO.ui.mixin.GroupElement );
13584 OO.mixinClass( OO.ui.CapsuleMultiSelectWidget, OO.ui.mixin.PopupElement );
13585 OO.mixinClass( OO.ui.CapsuleMultiSelectWidget, OO.ui.mixin.TabIndexedElement );
13586 OO.mixinClass( OO.ui.CapsuleMultiSelectWidget, OO.ui.mixin.IndicatorElement );
13587 OO.mixinClass( OO.ui.CapsuleMultiSelectWidget, OO.ui.mixin.IconElement );
13588
13589 /* Events */
13590
13591 /**
13592 * @event change
13593 *
13594 * A change event is emitted when the set of selected items changes.
13595 *
13596 * @param {Mixed[]} datas Data of the now-selected items
13597 */
13598
13599 /* Methods */
13600
13601 /**
13602 * Construct a OO.ui.CapsuleItemWidget (or a subclass thereof) from given label and data.
13603 *
13604 * @protected
13605 * @param {Mixed} data Custom data of any type.
13606 * @param {string} label The label text.
13607 * @return {OO.ui.CapsuleItemWidget}
13608 */
13609 OO.ui.CapsuleMultiSelectWidget.prototype.createItemWidget = function ( data, label ) {
13610 return new OO.ui.CapsuleItemWidget( { data: data, label: label } );
13611 };
13612
13613 /**
13614 * Get the data of the items in the capsule
13615 * @return {Mixed[]}
13616 */
13617 OO.ui.CapsuleMultiSelectWidget.prototype.getItemsData = function () {
13618 return $.map( this.getItems(), function ( e ) { return e.data; } );
13619 };
13620
13621 /**
13622 * Set the items in the capsule by providing data
13623 * @chainable
13624 * @param {Mixed[]} datas
13625 * @return {OO.ui.CapsuleMultiSelectWidget}
13626 */
13627 OO.ui.CapsuleMultiSelectWidget.prototype.setItemsFromData = function ( datas ) {
13628 var widget = this,
13629 menu = this.menu,
13630 items = this.getItems();
13631
13632 $.each( datas, function ( i, data ) {
13633 var j, label,
13634 item = menu.getItemFromData( data );
13635
13636 if ( item ) {
13637 label = item.label;
13638 } else if ( widget.allowArbitrary ) {
13639 label = String( data );
13640 } else {
13641 return;
13642 }
13643
13644 item = null;
13645 for ( j = 0; j < items.length; j++ ) {
13646 if ( items[ j ].data === data && items[ j ].label === label ) {
13647 item = items[ j ];
13648 items.splice( j, 1 );
13649 break;
13650 }
13651 }
13652 if ( !item ) {
13653 item = widget.createItemWidget( data, label );
13654 }
13655 widget.addItems( [ item ], i );
13656 } );
13657
13658 if ( items.length ) {
13659 widget.removeItems( items );
13660 }
13661
13662 return this;
13663 };
13664
13665 /**
13666 * Add items to the capsule by providing their data
13667 * @chainable
13668 * @param {Mixed[]} datas
13669 * @return {OO.ui.CapsuleMultiSelectWidget}
13670 */
13671 OO.ui.CapsuleMultiSelectWidget.prototype.addItemsFromData = function ( datas ) {
13672 var widget = this,
13673 menu = this.menu,
13674 items = [];
13675
13676 $.each( datas, function ( i, data ) {
13677 var item;
13678
13679 if ( !widget.getItemFromData( data ) ) {
13680 item = menu.getItemFromData( data );
13681 if ( item ) {
13682 items.push( widget.createItemWidget( data, item.label ) );
13683 } else if ( widget.allowArbitrary ) {
13684 items.push( widget.createItemWidget( data, String( data ) ) );
13685 }
13686 }
13687 } );
13688
13689 if ( items.length ) {
13690 this.addItems( items );
13691 }
13692
13693 return this;
13694 };
13695
13696 /**
13697 * Remove items by data
13698 * @chainable
13699 * @param {Mixed[]} datas
13700 * @return {OO.ui.CapsuleMultiSelectWidget}
13701 */
13702 OO.ui.CapsuleMultiSelectWidget.prototype.removeItemsFromData = function ( datas ) {
13703 var widget = this,
13704 items = [];
13705
13706 $.each( datas, function ( i, data ) {
13707 var item = widget.getItemFromData( data );
13708 if ( item ) {
13709 items.push( item );
13710 }
13711 } );
13712
13713 if ( items.length ) {
13714 this.removeItems( items );
13715 }
13716
13717 return this;
13718 };
13719
13720 /**
13721 * @inheritdoc
13722 */
13723 OO.ui.CapsuleMultiSelectWidget.prototype.addItems = function ( items ) {
13724 var same, i, l,
13725 oldItems = this.items.slice();
13726
13727 OO.ui.mixin.GroupElement.prototype.addItems.call( this, items );
13728
13729 if ( this.items.length !== oldItems.length ) {
13730 same = false;
13731 } else {
13732 same = true;
13733 for ( i = 0, l = oldItems.length; same && i < l; i++ ) {
13734 same = same && this.items[ i ] === oldItems[ i ];
13735 }
13736 }
13737 if ( !same ) {
13738 this.emit( 'change', this.getItemsData() );
13739 this.menu.position();
13740 }
13741
13742 return this;
13743 };
13744
13745 /**
13746 * @inheritdoc
13747 */
13748 OO.ui.CapsuleMultiSelectWidget.prototype.removeItems = function ( items ) {
13749 var same, i, l,
13750 oldItems = this.items.slice();
13751
13752 OO.ui.mixin.GroupElement.prototype.removeItems.call( this, items );
13753
13754 if ( this.items.length !== oldItems.length ) {
13755 same = false;
13756 } else {
13757 same = true;
13758 for ( i = 0, l = oldItems.length; same && i < l; i++ ) {
13759 same = same && this.items[ i ] === oldItems[ i ];
13760 }
13761 }
13762 if ( !same ) {
13763 this.emit( 'change', this.getItemsData() );
13764 this.menu.position();
13765 }
13766
13767 return this;
13768 };
13769
13770 /**
13771 * @inheritdoc
13772 */
13773 OO.ui.CapsuleMultiSelectWidget.prototype.clearItems = function () {
13774 if ( this.items.length ) {
13775 OO.ui.mixin.GroupElement.prototype.clearItems.call( this );
13776 this.emit( 'change', this.getItemsData() );
13777 this.menu.position();
13778 }
13779 return this;
13780 };
13781
13782 /**
13783 * Get the capsule widget's menu.
13784 * @return {OO.ui.MenuSelectWidget} Menu widget
13785 */
13786 OO.ui.CapsuleMultiSelectWidget.prototype.getMenu = function () {
13787 return this.menu;
13788 };
13789
13790 /**
13791 * Handle focus events
13792 *
13793 * @private
13794 * @param {jQuery.Event} event
13795 */
13796 OO.ui.CapsuleMultiSelectWidget.prototype.onInputFocus = function () {
13797 if ( !this.isDisabled() ) {
13798 this.menu.toggle( true );
13799 }
13800 };
13801
13802 /**
13803 * Handle blur events
13804 *
13805 * @private
13806 * @param {jQuery.Event} event
13807 */
13808 OO.ui.CapsuleMultiSelectWidget.prototype.onInputBlur = function () {
13809 if ( this.allowArbitrary && this.$input.val().trim() !== '' ) {
13810 this.addItemsFromData( [ this.$input.val() ] );
13811 }
13812 this.clearInput();
13813 };
13814
13815 /**
13816 * Handle focus events
13817 *
13818 * @private
13819 * @param {jQuery.Event} event
13820 */
13821 OO.ui.CapsuleMultiSelectWidget.prototype.onFocusForPopup = function () {
13822 if ( !this.isDisabled() ) {
13823 this.popup.setSize( this.$handle.width() );
13824 this.popup.toggle( true );
13825 this.popup.$element.find( '*' )
13826 .filter( function () { return OO.ui.isFocusableElement( $( this ), true ); } )
13827 .first()
13828 .focus();
13829 }
13830 };
13831
13832 /**
13833 * Handles popup focus out events.
13834 *
13835 * @private
13836 * @param {Event} e Focus out event
13837 */
13838 OO.ui.CapsuleMultiSelectWidget.prototype.onPopupFocusOut = function () {
13839 var widget = this.popup;
13840
13841 setTimeout( function () {
13842 if (
13843 widget.isVisible() &&
13844 !OO.ui.contains( widget.$element[ 0 ], document.activeElement, true ) &&
13845 ( !widget.$autoCloseIgnore || !widget.$autoCloseIgnore.has( document.activeElement ).length )
13846 ) {
13847 widget.toggle( false );
13848 }
13849 } );
13850 };
13851
13852 /**
13853 * Handle mouse down events.
13854 *
13855 * @private
13856 * @param {jQuery.Event} e Mouse down event
13857 */
13858 OO.ui.CapsuleMultiSelectWidget.prototype.onMouseDown = function ( e ) {
13859 if ( e.which === OO.ui.MouseButtons.LEFT ) {
13860 this.focus();
13861 return false;
13862 } else {
13863 this.updateInputSize();
13864 }
13865 };
13866
13867 /**
13868 * Handle key press events.
13869 *
13870 * @private
13871 * @param {jQuery.Event} e Key press event
13872 */
13873 OO.ui.CapsuleMultiSelectWidget.prototype.onKeyPress = function ( e ) {
13874 var item;
13875
13876 if ( !this.isDisabled() ) {
13877 if ( e.which === OO.ui.Keys.ESCAPE ) {
13878 this.clearInput();
13879 return false;
13880 }
13881
13882 if ( !this.popup ) {
13883 this.menu.toggle( true );
13884 if ( e.which === OO.ui.Keys.ENTER ) {
13885 item = this.menu.getItemFromLabel( this.$input.val(), true );
13886 if ( item ) {
13887 this.addItemsFromData( [ item.data ] );
13888 this.clearInput();
13889 } else if ( this.allowArbitrary && this.$input.val().trim() !== '' ) {
13890 this.addItemsFromData( [ this.$input.val() ] );
13891 this.clearInput();
13892 }
13893 return false;
13894 }
13895
13896 // Make sure the input gets resized.
13897 setTimeout( this.updateInputSize.bind( this ), 0 );
13898 }
13899 }
13900 };
13901
13902 /**
13903 * Handle key down events.
13904 *
13905 * @private
13906 * @param {jQuery.Event} e Key down event
13907 */
13908 OO.ui.CapsuleMultiSelectWidget.prototype.onKeyDown = function ( e ) {
13909 if ( !this.isDisabled() ) {
13910 // 'keypress' event is not triggered for Backspace
13911 if ( e.keyCode === OO.ui.Keys.BACKSPACE && this.$input.val() === '' ) {
13912 if ( this.items.length ) {
13913 this.removeItems( this.items.slice( -1 ) );
13914 }
13915 return false;
13916 }
13917 }
13918 };
13919
13920 /**
13921 * Update the dimensions of the text input field to encompass all available area.
13922 *
13923 * @private
13924 * @param {jQuery.Event} e Event of some sort
13925 */
13926 OO.ui.CapsuleMultiSelectWidget.prototype.updateInputSize = function () {
13927 var $lastItem, direction, contentWidth, currentWidth, bestWidth;
13928 if ( !this.isDisabled() ) {
13929 this.$input.css( 'width', '1em' );
13930 $lastItem = this.$group.children().last();
13931 direction = OO.ui.Element.static.getDir( this.$handle );
13932 contentWidth = this.$input[ 0 ].scrollWidth;
13933 currentWidth = this.$input.width();
13934
13935 if ( contentWidth < currentWidth ) {
13936 // All is fine, don't perform expensive calculations
13937 return;
13938 }
13939
13940 if ( !$lastItem.length ) {
13941 bestWidth = this.$content.innerWidth();
13942 } else {
13943 bestWidth = direction === 'ltr' ?
13944 this.$content.innerWidth() - $lastItem.position().left - $lastItem.outerWidth() :
13945 $lastItem.position().left;
13946 }
13947 // Some safety margin for sanity, because I *really* don't feel like finding out where the few
13948 // pixels this is off by are coming from.
13949 bestWidth -= 10;
13950 if ( contentWidth > bestWidth ) {
13951 // This will result in the input getting shifted to the next line
13952 bestWidth = this.$content.innerWidth() - 10;
13953 }
13954 this.$input.width( Math.floor( bestWidth ) );
13955
13956 this.menu.position();
13957 }
13958 };
13959
13960 /**
13961 * Handle menu choose events.
13962 *
13963 * @private
13964 * @param {OO.ui.OptionWidget} item Chosen item
13965 */
13966 OO.ui.CapsuleMultiSelectWidget.prototype.onMenuChoose = function ( item ) {
13967 if ( item && item.isVisible() ) {
13968 this.addItemsFromData( [ item.getData() ] );
13969 this.clearInput();
13970 }
13971 };
13972
13973 /**
13974 * Handle menu item change events.
13975 *
13976 * @private
13977 */
13978 OO.ui.CapsuleMultiSelectWidget.prototype.onMenuItemsChange = function () {
13979 this.setItemsFromData( this.getItemsData() );
13980 this.$element.toggleClass( 'oo-ui-capsuleMultiSelectWidget-empty', this.menu.isEmpty() );
13981 };
13982
13983 /**
13984 * Clear the input field
13985 * @private
13986 */
13987 OO.ui.CapsuleMultiSelectWidget.prototype.clearInput = function () {
13988 if ( this.$input ) {
13989 this.$input.val( '' );
13990 this.updateInputSize();
13991 }
13992 if ( this.popup ) {
13993 this.popup.toggle( false );
13994 }
13995 this.menu.toggle( false );
13996 this.menu.selectItem();
13997 this.menu.highlightItem();
13998 };
13999
14000 /**
14001 * @inheritdoc
14002 */
14003 OO.ui.CapsuleMultiSelectWidget.prototype.setDisabled = function ( disabled ) {
14004 var i, len;
14005
14006 // Parent method
14007 OO.ui.CapsuleMultiSelectWidget.parent.prototype.setDisabled.call( this, disabled );
14008
14009 if ( this.$input ) {
14010 this.$input.prop( 'disabled', this.isDisabled() );
14011 }
14012 if ( this.menu ) {
14013 this.menu.setDisabled( this.isDisabled() );
14014 }
14015 if ( this.popup ) {
14016 this.popup.setDisabled( this.isDisabled() );
14017 }
14018
14019 if ( this.items ) {
14020 for ( i = 0, len = this.items.length; i < len; i++ ) {
14021 this.items[ i ].updateDisabled();
14022 }
14023 }
14024
14025 return this;
14026 };
14027
14028 /**
14029 * Focus the widget
14030 * @chainable
14031 * @return {OO.ui.CapsuleMultiSelectWidget}
14032 */
14033 OO.ui.CapsuleMultiSelectWidget.prototype.focus = function () {
14034 if ( !this.isDisabled() ) {
14035 if ( this.popup ) {
14036 this.popup.setSize( this.$handle.width() );
14037 this.popup.toggle( true );
14038 this.popup.$element.find( '*' )
14039 .filter( function () { return OO.ui.isFocusableElement( $( this ), true ); } )
14040 .first()
14041 .focus();
14042 } else {
14043 this.updateInputSize();
14044 this.menu.toggle( true );
14045 this.$input.focus();
14046 }
14047 }
14048 return this;
14049 };
14050
14051 /**
14052 * CapsuleItemWidgets are used within a {@link OO.ui.CapsuleMultiSelectWidget
14053 * CapsuleMultiSelectWidget} to display the selected items.
14054 *
14055 * @class
14056 * @extends OO.ui.Widget
14057 * @mixins OO.ui.mixin.ItemWidget
14058 * @mixins OO.ui.mixin.IndicatorElement
14059 * @mixins OO.ui.mixin.LabelElement
14060 * @mixins OO.ui.mixin.FlaggedElement
14061 * @mixins OO.ui.mixin.TabIndexedElement
14062 *
14063 * @constructor
14064 * @param {Object} [config] Configuration options
14065 */
14066 OO.ui.CapsuleItemWidget = function OoUiCapsuleItemWidget( config ) {
14067 // Configuration initialization
14068 config = config || {};
14069
14070 // Parent constructor
14071 OO.ui.CapsuleItemWidget.parent.call( this, config );
14072
14073 // Properties (must be set before mixin constructor calls)
14074 this.$indicator = $( '<span>' );
14075
14076 // Mixin constructors
14077 OO.ui.mixin.ItemWidget.call( this );
14078 OO.ui.mixin.IndicatorElement.call( this, $.extend( {}, config, { $indicator: this.$indicator, indicator: 'clear' } ) );
14079 OO.ui.mixin.LabelElement.call( this, config );
14080 OO.ui.mixin.FlaggedElement.call( this, config );
14081 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$indicator } ) );
14082
14083 // Events
14084 this.$indicator.on( {
14085 keydown: this.onCloseKeyDown.bind( this ),
14086 click: this.onCloseClick.bind( this )
14087 } );
14088
14089 // Initialization
14090 this.$element
14091 .addClass( 'oo-ui-capsuleItemWidget' )
14092 .append( this.$indicator, this.$label );
14093 };
14094
14095 /* Setup */
14096
14097 OO.inheritClass( OO.ui.CapsuleItemWidget, OO.ui.Widget );
14098 OO.mixinClass( OO.ui.CapsuleItemWidget, OO.ui.mixin.ItemWidget );
14099 OO.mixinClass( OO.ui.CapsuleItemWidget, OO.ui.mixin.IndicatorElement );
14100 OO.mixinClass( OO.ui.CapsuleItemWidget, OO.ui.mixin.LabelElement );
14101 OO.mixinClass( OO.ui.CapsuleItemWidget, OO.ui.mixin.FlaggedElement );
14102 OO.mixinClass( OO.ui.CapsuleItemWidget, OO.ui.mixin.TabIndexedElement );
14103
14104 /* Methods */
14105
14106 /**
14107 * Handle close icon clicks
14108 * @param {jQuery.Event} event
14109 */
14110 OO.ui.CapsuleItemWidget.prototype.onCloseClick = function () {
14111 var element = this.getElementGroup();
14112
14113 if ( !this.isDisabled() && element && $.isFunction( element.removeItems ) ) {
14114 element.removeItems( [ this ] );
14115 element.focus();
14116 }
14117 };
14118
14119 /**
14120 * Handle close keyboard events
14121 * @param {jQuery.Event} event Key down event
14122 */
14123 OO.ui.CapsuleItemWidget.prototype.onCloseKeyDown = function ( e ) {
14124 if ( !this.isDisabled() && $.isFunction( this.getElementGroup().removeItems ) ) {
14125 switch ( e.which ) {
14126 case OO.ui.Keys.ENTER:
14127 case OO.ui.Keys.BACKSPACE:
14128 case OO.ui.Keys.SPACE:
14129 this.getElementGroup().removeItems( [ this ] );
14130 return false;
14131 }
14132 }
14133 };
14134
14135 /**
14136 * DropdownWidgets are not menus themselves, rather they contain a menu of options created with
14137 * OO.ui.MenuOptionWidget. The DropdownWidget takes care of opening and displaying the menu so that
14138 * users can interact with it.
14139 *
14140 * If you want to use this within a HTML form, such as a OO.ui.FormLayout, use
14141 * OO.ui.DropdownInputWidget instead.
14142 *
14143 * @example
14144 * // Example: A DropdownWidget with a menu that contains three options
14145 * var dropDown = new OO.ui.DropdownWidget( {
14146 * label: 'Dropdown menu: Select a menu option',
14147 * menu: {
14148 * items: [
14149 * new OO.ui.MenuOptionWidget( {
14150 * data: 'a',
14151 * label: 'First'
14152 * } ),
14153 * new OO.ui.MenuOptionWidget( {
14154 * data: 'b',
14155 * label: 'Second'
14156 * } ),
14157 * new OO.ui.MenuOptionWidget( {
14158 * data: 'c',
14159 * label: 'Third'
14160 * } )
14161 * ]
14162 * }
14163 * } );
14164 *
14165 * $( 'body' ).append( dropDown.$element );
14166 *
14167 * dropDown.getMenu().selectItemByData( 'b' );
14168 *
14169 * dropDown.getMenu().getSelectedItem().getData(); // returns 'b'
14170 *
14171 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
14172 *
14173 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
14174 *
14175 * @class
14176 * @extends OO.ui.Widget
14177 * @mixins OO.ui.mixin.IconElement
14178 * @mixins OO.ui.mixin.IndicatorElement
14179 * @mixins OO.ui.mixin.LabelElement
14180 * @mixins OO.ui.mixin.TitledElement
14181 * @mixins OO.ui.mixin.TabIndexedElement
14182 *
14183 * @constructor
14184 * @param {Object} [config] Configuration options
14185 * @cfg {Object} [menu] Configuration options to pass to {@link OO.ui.FloatingMenuSelectWidget menu select widget}
14186 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
14187 * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
14188 * containing `<div>` and has a larger area. By default, the menu uses relative positioning.
14189 */
14190 OO.ui.DropdownWidget = function OoUiDropdownWidget( config ) {
14191 // Configuration initialization
14192 config = $.extend( { indicator: 'down' }, config );
14193
14194 // Parent constructor
14195 OO.ui.DropdownWidget.parent.call( this, config );
14196
14197 // Properties (must be set before TabIndexedElement constructor call)
14198 this.$handle = this.$( '<span>' );
14199 this.$overlay = config.$overlay || this.$element;
14200
14201 // Mixin constructors
14202 OO.ui.mixin.IconElement.call( this, config );
14203 OO.ui.mixin.IndicatorElement.call( this, config );
14204 OO.ui.mixin.LabelElement.call( this, config );
14205 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$label } ) );
14206 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$handle } ) );
14207
14208 // Properties
14209 this.menu = new OO.ui.FloatingMenuSelectWidget( $.extend( {
14210 widget: this,
14211 $container: this.$element
14212 }, config.menu ) );
14213
14214 // Events
14215 this.$handle.on( {
14216 click: this.onClick.bind( this ),
14217 keypress: this.onKeyPress.bind( this )
14218 } );
14219 this.menu.connect( this, { select: 'onMenuSelect' } );
14220
14221 // Initialization
14222 this.$handle
14223 .addClass( 'oo-ui-dropdownWidget-handle' )
14224 .append( this.$icon, this.$label, this.$indicator );
14225 this.$element
14226 .addClass( 'oo-ui-dropdownWidget' )
14227 .append( this.$handle );
14228 this.$overlay.append( this.menu.$element );
14229 };
14230
14231 /* Setup */
14232
14233 OO.inheritClass( OO.ui.DropdownWidget, OO.ui.Widget );
14234 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.IconElement );
14235 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.IndicatorElement );
14236 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.LabelElement );
14237 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.TitledElement );
14238 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.TabIndexedElement );
14239
14240 /* Methods */
14241
14242 /**
14243 * Get the menu.
14244 *
14245 * @return {OO.ui.MenuSelectWidget} Menu of widget
14246 */
14247 OO.ui.DropdownWidget.prototype.getMenu = function () {
14248 return this.menu;
14249 };
14250
14251 /**
14252 * Handles menu select events.
14253 *
14254 * @private
14255 * @param {OO.ui.MenuOptionWidget} item Selected menu item
14256 */
14257 OO.ui.DropdownWidget.prototype.onMenuSelect = function ( item ) {
14258 var selectedLabel;
14259
14260 if ( !item ) {
14261 this.setLabel( null );
14262 return;
14263 }
14264
14265 selectedLabel = item.getLabel();
14266
14267 // If the label is a DOM element, clone it, because setLabel will append() it
14268 if ( selectedLabel instanceof jQuery ) {
14269 selectedLabel = selectedLabel.clone();
14270 }
14271
14272 this.setLabel( selectedLabel );
14273 };
14274
14275 /**
14276 * Handle mouse click events.
14277 *
14278 * @private
14279 * @param {jQuery.Event} e Mouse click event
14280 */
14281 OO.ui.DropdownWidget.prototype.onClick = function ( e ) {
14282 if ( !this.isDisabled() && e.which === OO.ui.MouseButtons.LEFT ) {
14283 this.menu.toggle();
14284 }
14285 return false;
14286 };
14287
14288 /**
14289 * Handle key press events.
14290 *
14291 * @private
14292 * @param {jQuery.Event} e Key press event
14293 */
14294 OO.ui.DropdownWidget.prototype.onKeyPress = function ( e ) {
14295 if ( !this.isDisabled() &&
14296 ( ( e.which === OO.ui.Keys.SPACE && !this.menu.isVisible() ) || e.which === OO.ui.Keys.ENTER )
14297 ) {
14298 this.menu.toggle();
14299 return false;
14300 }
14301 };
14302
14303 /**
14304 * SelectFileWidgets allow for selecting files, using the HTML5 File API. These
14305 * widgets can be configured with {@link OO.ui.mixin.IconElement icons} and {@link
14306 * OO.ui.mixin.IndicatorElement indicators}.
14307 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
14308 *
14309 * @example
14310 * // Example of a file select widget
14311 * var selectFile = new OO.ui.SelectFileWidget();
14312 * $( 'body' ).append( selectFile.$element );
14313 *
14314 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets
14315 *
14316 * @class
14317 * @extends OO.ui.Widget
14318 * @mixins OO.ui.mixin.IconElement
14319 * @mixins OO.ui.mixin.IndicatorElement
14320 * @mixins OO.ui.mixin.PendingElement
14321 * @mixins OO.ui.mixin.LabelElement
14322 *
14323 * @constructor
14324 * @param {Object} [config] Configuration options
14325 * @cfg {string[]|null} [accept=null] MIME types to accept. null accepts all types.
14326 * @cfg {string} [placeholder] Text to display when no file is selected.
14327 * @cfg {string} [notsupported] Text to display when file support is missing in the browser.
14328 * @cfg {boolean} [droppable=true] Whether to accept files by drag and drop.
14329 * @cfg {boolean} [showDropTarget=false] Whether to show a drop target. Requires droppable to be true.
14330 * @cfg {boolean} [dragDropUI=false] Deprecated alias for showDropTarget
14331 */
14332 OO.ui.SelectFileWidget = function OoUiSelectFileWidget( config ) {
14333 var dragHandler;
14334
14335 // TODO: Remove in next release
14336 if ( config && config.dragDropUI ) {
14337 config.showDropTarget = true;
14338 }
14339
14340 // Configuration initialization
14341 config = $.extend( {
14342 accept: null,
14343 placeholder: OO.ui.msg( 'ooui-selectfile-placeholder' ),
14344 notsupported: OO.ui.msg( 'ooui-selectfile-not-supported' ),
14345 droppable: true,
14346 showDropTarget: false
14347 }, config );
14348
14349 // Parent constructor
14350 OO.ui.SelectFileWidget.parent.call( this, config );
14351
14352 // Mixin constructors
14353 OO.ui.mixin.IconElement.call( this, config );
14354 OO.ui.mixin.IndicatorElement.call( this, config );
14355 OO.ui.mixin.PendingElement.call( this, $.extend( {}, config, { $pending: this.$info } ) );
14356 OO.ui.mixin.LabelElement.call( this, $.extend( {}, config, { autoFitLabel: true } ) );
14357
14358 // Properties
14359 this.$info = $( '<span>' );
14360
14361 // Properties
14362 this.showDropTarget = config.showDropTarget;
14363 this.isSupported = this.constructor.static.isSupported();
14364 this.currentFile = null;
14365 if ( Array.isArray( config.accept ) ) {
14366 this.accept = config.accept;
14367 } else {
14368 this.accept = null;
14369 }
14370 this.placeholder = config.placeholder;
14371 this.notsupported = config.notsupported;
14372 this.onFileSelectedHandler = this.onFileSelected.bind( this );
14373
14374 this.selectButton = new OO.ui.ButtonWidget( {
14375 classes: [ 'oo-ui-selectFileWidget-selectButton' ],
14376 label: OO.ui.msg( 'ooui-selectfile-button-select' ),
14377 disabled: this.disabled || !this.isSupported
14378 } );
14379
14380 this.clearButton = new OO.ui.ButtonWidget( {
14381 classes: [ 'oo-ui-selectFileWidget-clearButton' ],
14382 framed: false,
14383 icon: 'remove',
14384 disabled: this.disabled
14385 } );
14386
14387 // Events
14388 this.selectButton.$button.on( {
14389 keypress: this.onKeyPress.bind( this )
14390 } );
14391 this.clearButton.connect( this, {
14392 click: 'onClearClick'
14393 } );
14394 if ( config.droppable ) {
14395 dragHandler = this.onDragEnterOrOver.bind( this );
14396 this.$element.on( {
14397 dragenter: dragHandler,
14398 dragover: dragHandler,
14399 dragleave: this.onDragLeave.bind( this ),
14400 drop: this.onDrop.bind( this )
14401 } );
14402 }
14403
14404 // Initialization
14405 this.addInput();
14406 this.updateUI();
14407 this.$label.addClass( 'oo-ui-selectFileWidget-label' );
14408 this.$info
14409 .addClass( 'oo-ui-selectFileWidget-info' )
14410 .append( this.$icon, this.$label, this.clearButton.$element, this.$indicator );
14411 this.$element
14412 .addClass( 'oo-ui-selectFileWidget' )
14413 .append( this.$info, this.selectButton.$element );
14414 if ( config.droppable && config.showDropTarget ) {
14415 this.$dropTarget = $( '<div>' )
14416 .addClass( 'oo-ui-selectFileWidget-dropTarget' )
14417 .text( OO.ui.msg( 'ooui-selectfile-dragdrop-placeholder' ) )
14418 .on( {
14419 click: this.onDropTargetClick.bind( this )
14420 } );
14421 this.$element.prepend( this.$dropTarget );
14422 }
14423 };
14424
14425 /* Setup */
14426
14427 OO.inheritClass( OO.ui.SelectFileWidget, OO.ui.Widget );
14428 OO.mixinClass( OO.ui.SelectFileWidget, OO.ui.mixin.IconElement );
14429 OO.mixinClass( OO.ui.SelectFileWidget, OO.ui.mixin.IndicatorElement );
14430 OO.mixinClass( OO.ui.SelectFileWidget, OO.ui.mixin.PendingElement );
14431 OO.mixinClass( OO.ui.SelectFileWidget, OO.ui.mixin.LabelElement );
14432
14433 /* Static Properties */
14434
14435 /**
14436 * Check if this widget is supported
14437 *
14438 * @static
14439 * @return {boolean}
14440 */
14441 OO.ui.SelectFileWidget.static.isSupported = function () {
14442 var $input;
14443 if ( OO.ui.SelectFileWidget.static.isSupportedCache === null ) {
14444 $input = $( '<input type="file">' );
14445 OO.ui.SelectFileWidget.static.isSupportedCache = $input[ 0 ].files !== undefined;
14446 }
14447 return OO.ui.SelectFileWidget.static.isSupportedCache;
14448 };
14449
14450 OO.ui.SelectFileWidget.static.isSupportedCache = null;
14451
14452 /* Events */
14453
14454 /**
14455 * @event change
14456 *
14457 * A change event is emitted when the on/off state of the toggle changes.
14458 *
14459 * @param {File|null} value New value
14460 */
14461
14462 /* Methods */
14463
14464 /**
14465 * Get the current value of the field
14466 *
14467 * @return {File|null}
14468 */
14469 OO.ui.SelectFileWidget.prototype.getValue = function () {
14470 return this.currentFile;
14471 };
14472
14473 /**
14474 * Set the current value of the field
14475 *
14476 * @param {File|null} file File to select
14477 */
14478 OO.ui.SelectFileWidget.prototype.setValue = function ( file ) {
14479 if ( this.currentFile !== file ) {
14480 this.currentFile = file;
14481 this.updateUI();
14482 this.emit( 'change', this.currentFile );
14483 }
14484 };
14485
14486 /**
14487 * Focus the widget.
14488 *
14489 * Focusses the select file button.
14490 *
14491 * @chainable
14492 */
14493 OO.ui.SelectFileWidget.prototype.focus = function () {
14494 this.selectButton.$button[ 0 ].focus();
14495 return this;
14496 };
14497
14498 /**
14499 * Update the user interface when a file is selected or unselected
14500 *
14501 * @protected
14502 */
14503 OO.ui.SelectFileWidget.prototype.updateUI = function () {
14504 var $label;
14505 if ( !this.isSupported ) {
14506 this.$element.addClass( 'oo-ui-selectFileWidget-notsupported' );
14507 this.$element.removeClass( 'oo-ui-selectFileWidget-empty' );
14508 this.setLabel( this.notsupported );
14509 } else {
14510 this.$element.addClass( 'oo-ui-selectFileWidget-supported' );
14511 if ( this.currentFile ) {
14512 this.$element.removeClass( 'oo-ui-selectFileWidget-empty' );
14513 $label = $( [] );
14514 if ( this.currentFile.type !== '' ) {
14515 $label = $label.add( $( '<span>' ).addClass( 'oo-ui-selectFileWidget-fileType' ).text( this.currentFile.type ) );
14516 }
14517 $label = $label.add( $( '<span>' ).text( this.currentFile.name ) );
14518 this.setLabel( $label );
14519 } else {
14520 this.$element.addClass( 'oo-ui-selectFileWidget-empty' );
14521 this.setLabel( this.placeholder );
14522 }
14523 }
14524 };
14525
14526 /**
14527 * Add the input to the widget
14528 *
14529 * @private
14530 */
14531 OO.ui.SelectFileWidget.prototype.addInput = function () {
14532 if ( this.$input ) {
14533 this.$input.remove();
14534 }
14535
14536 if ( !this.isSupported ) {
14537 this.$input = null;
14538 return;
14539 }
14540
14541 this.$input = $( '<input type="file">' );
14542 this.$input.on( 'change', this.onFileSelectedHandler );
14543 this.$input.attr( {
14544 tabindex: -1
14545 } );
14546 if ( this.accept ) {
14547 this.$input.attr( 'accept', this.accept.join( ', ' ) );
14548 }
14549 this.selectButton.$button.append( this.$input );
14550 };
14551
14552 /**
14553 * Determine if we should accept this file
14554 *
14555 * @private
14556 * @param {string} File MIME type
14557 * @return {boolean}
14558 */
14559 OO.ui.SelectFileWidget.prototype.isAllowedType = function ( mimeType ) {
14560 var i, mimeTest;
14561
14562 if ( !this.accept || !mimeType ) {
14563 return true;
14564 }
14565
14566 for ( i = 0; i < this.accept.length; i++ ) {
14567 mimeTest = this.accept[ i ];
14568 if ( mimeTest === mimeType ) {
14569 return true;
14570 } else if ( mimeTest.substr( -2 ) === '/*' ) {
14571 mimeTest = mimeTest.substr( 0, mimeTest.length - 1 );
14572 if ( mimeType.substr( 0, mimeTest.length ) === mimeTest ) {
14573 return true;
14574 }
14575 }
14576 }
14577
14578 return false;
14579 };
14580
14581 /**
14582 * Handle file selection from the input
14583 *
14584 * @private
14585 * @param {jQuery.Event} e
14586 */
14587 OO.ui.SelectFileWidget.prototype.onFileSelected = function ( e ) {
14588 var file = OO.getProp( e.target, 'files', 0 ) || null;
14589
14590 if ( file && !this.isAllowedType( file.type ) ) {
14591 file = null;
14592 }
14593
14594 this.setValue( file );
14595 this.addInput();
14596 };
14597
14598 /**
14599 * Handle clear button click events.
14600 *
14601 * @private
14602 */
14603 OO.ui.SelectFileWidget.prototype.onClearClick = function () {
14604 this.setValue( null );
14605 return false;
14606 };
14607
14608 /**
14609 * Handle key press events.
14610 *
14611 * @private
14612 * @param {jQuery.Event} e Key press event
14613 */
14614 OO.ui.SelectFileWidget.prototype.onKeyPress = function ( e ) {
14615 if ( this.isSupported && !this.isDisabled() && this.$input &&
14616 ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
14617 ) {
14618 this.$input.click();
14619 return false;
14620 }
14621 };
14622
14623 /**
14624 * Handle drop target click events.
14625 *
14626 * @private
14627 * @param {jQuery.Event} e Key press event
14628 */
14629 OO.ui.SelectFileWidget.prototype.onDropTargetClick = function () {
14630 if ( this.isSupported && !this.isDisabled() && this.$input ) {
14631 this.$input.click();
14632 return false;
14633 }
14634 };
14635
14636 /**
14637 * Handle drag enter and over events
14638 *
14639 * @private
14640 * @param {jQuery.Event} e Drag event
14641 */
14642 OO.ui.SelectFileWidget.prototype.onDragEnterOrOver = function ( e ) {
14643 var itemOrFile,
14644 droppableFile = false,
14645 dt = e.originalEvent.dataTransfer;
14646
14647 e.preventDefault();
14648 e.stopPropagation();
14649
14650 if ( this.isDisabled() || !this.isSupported ) {
14651 this.$element.removeClass( 'oo-ui-selectFileWidget-canDrop' );
14652 dt.dropEffect = 'none';
14653 return false;
14654 }
14655
14656 // DataTransferItem and File both have a type property, but in Chrome files
14657 // have no information at this point.
14658 itemOrFile = OO.getProp( dt, 'items', 0 ) || OO.getProp( dt, 'files', 0 );
14659 if ( itemOrFile ) {
14660 if ( this.isAllowedType( itemOrFile.type ) ) {
14661 droppableFile = true;
14662 }
14663 // dt.types is Array-like, but not an Array
14664 } else if ( Array.prototype.indexOf.call( OO.getProp( dt, 'types' ) || [], 'Files' ) !== -1 ) {
14665 // File information is not available at this point for security so just assume
14666 // it is acceptable for now.
14667 // https://bugzilla.mozilla.org/show_bug.cgi?id=640534
14668 droppableFile = true;
14669 }
14670
14671 this.$element.toggleClass( 'oo-ui-selectFileWidget-canDrop', droppableFile );
14672 if ( !droppableFile ) {
14673 dt.dropEffect = 'none';
14674 }
14675
14676 return false;
14677 };
14678
14679 /**
14680 * Handle drag leave events
14681 *
14682 * @private
14683 * @param {jQuery.Event} e Drag event
14684 */
14685 OO.ui.SelectFileWidget.prototype.onDragLeave = function () {
14686 this.$element.removeClass( 'oo-ui-selectFileWidget-canDrop' );
14687 };
14688
14689 /**
14690 * Handle drop events
14691 *
14692 * @private
14693 * @param {jQuery.Event} e Drop event
14694 */
14695 OO.ui.SelectFileWidget.prototype.onDrop = function ( e ) {
14696 var file = null,
14697 dt = e.originalEvent.dataTransfer;
14698
14699 e.preventDefault();
14700 e.stopPropagation();
14701 this.$element.removeClass( 'oo-ui-selectFileWidget-canDrop' );
14702
14703 if ( this.isDisabled() || !this.isSupported ) {
14704 return false;
14705 }
14706
14707 file = OO.getProp( dt, 'files', 0 );
14708 if ( file && !this.isAllowedType( file.type ) ) {
14709 file = null;
14710 }
14711 if ( file ) {
14712 this.setValue( file );
14713 }
14714
14715 return false;
14716 };
14717
14718 /**
14719 * @inheritdoc
14720 */
14721 OO.ui.SelectFileWidget.prototype.setDisabled = function ( disabled ) {
14722 OO.ui.SelectFileWidget.parent.prototype.setDisabled.call( this, disabled );
14723 if ( this.selectButton ) {
14724 this.selectButton.setDisabled( disabled );
14725 }
14726 if ( this.clearButton ) {
14727 this.clearButton.setDisabled( disabled );
14728 }
14729 return this;
14730 };
14731
14732 /**
14733 * IconWidget is a generic widget for {@link OO.ui.mixin.IconElement icons}. In general, IconWidgets should be used with OO.ui.LabelWidget,
14734 * which creates a label that identifies the icon’s function. See the [OOjs UI documentation on MediaWiki] [1]
14735 * for a list of icons included in the library.
14736 *
14737 * @example
14738 * // An icon widget with a label
14739 * var myIcon = new OO.ui.IconWidget( {
14740 * icon: 'help',
14741 * iconTitle: 'Help'
14742 * } );
14743 * // Create a label.
14744 * var iconLabel = new OO.ui.LabelWidget( {
14745 * label: 'Help'
14746 * } );
14747 * $( 'body' ).append( myIcon.$element, iconLabel.$element );
14748 *
14749 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
14750 *
14751 * @class
14752 * @extends OO.ui.Widget
14753 * @mixins OO.ui.mixin.IconElement
14754 * @mixins OO.ui.mixin.TitledElement
14755 * @mixins OO.ui.mixin.FlaggedElement
14756 *
14757 * @constructor
14758 * @param {Object} [config] Configuration options
14759 */
14760 OO.ui.IconWidget = function OoUiIconWidget( config ) {
14761 // Configuration initialization
14762 config = config || {};
14763
14764 // Parent constructor
14765 OO.ui.IconWidget.parent.call( this, config );
14766
14767 // Mixin constructors
14768 OO.ui.mixin.IconElement.call( this, $.extend( {}, config, { $icon: this.$element } ) );
14769 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$element } ) );
14770 OO.ui.mixin.FlaggedElement.call( this, $.extend( {}, config, { $flagged: this.$element } ) );
14771
14772 // Initialization
14773 this.$element.addClass( 'oo-ui-iconWidget' );
14774 };
14775
14776 /* Setup */
14777
14778 OO.inheritClass( OO.ui.IconWidget, OO.ui.Widget );
14779 OO.mixinClass( OO.ui.IconWidget, OO.ui.mixin.IconElement );
14780 OO.mixinClass( OO.ui.IconWidget, OO.ui.mixin.TitledElement );
14781 OO.mixinClass( OO.ui.IconWidget, OO.ui.mixin.FlaggedElement );
14782
14783 /* Static Properties */
14784
14785 OO.ui.IconWidget.static.tagName = 'span';
14786
14787 /**
14788 * IndicatorWidgets create indicators, which are small graphics that are generally used to draw
14789 * attention to the status of an item or to clarify the function of a control. For a list of
14790 * indicators included in the library, please see the [OOjs UI documentation on MediaWiki][1].
14791 *
14792 * @example
14793 * // Example of an indicator widget
14794 * var indicator1 = new OO.ui.IndicatorWidget( {
14795 * indicator: 'alert'
14796 * } );
14797 *
14798 * // Create a fieldset layout to add a label
14799 * var fieldset = new OO.ui.FieldsetLayout();
14800 * fieldset.addItems( [
14801 * new OO.ui.FieldLayout( indicator1, { label: 'An alert indicator:' } )
14802 * ] );
14803 * $( 'body' ).append( fieldset.$element );
14804 *
14805 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
14806 *
14807 * @class
14808 * @extends OO.ui.Widget
14809 * @mixins OO.ui.mixin.IndicatorElement
14810 * @mixins OO.ui.mixin.TitledElement
14811 *
14812 * @constructor
14813 * @param {Object} [config] Configuration options
14814 */
14815 OO.ui.IndicatorWidget = function OoUiIndicatorWidget( config ) {
14816 // Configuration initialization
14817 config = config || {};
14818
14819 // Parent constructor
14820 OO.ui.IndicatorWidget.parent.call( this, config );
14821
14822 // Mixin constructors
14823 OO.ui.mixin.IndicatorElement.call( this, $.extend( {}, config, { $indicator: this.$element } ) );
14824 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$element } ) );
14825
14826 // Initialization
14827 this.$element.addClass( 'oo-ui-indicatorWidget' );
14828 };
14829
14830 /* Setup */
14831
14832 OO.inheritClass( OO.ui.IndicatorWidget, OO.ui.Widget );
14833 OO.mixinClass( OO.ui.IndicatorWidget, OO.ui.mixin.IndicatorElement );
14834 OO.mixinClass( OO.ui.IndicatorWidget, OO.ui.mixin.TitledElement );
14835
14836 /* Static Properties */
14837
14838 OO.ui.IndicatorWidget.static.tagName = 'span';
14839
14840 /**
14841 * InputWidget is the base class for all input widgets, which
14842 * include {@link OO.ui.TextInputWidget text inputs}, {@link OO.ui.CheckboxInputWidget checkbox inputs},
14843 * {@link OO.ui.RadioInputWidget radio inputs}, and {@link OO.ui.ButtonInputWidget button inputs}.
14844 * See the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
14845 *
14846 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
14847 *
14848 * @abstract
14849 * @class
14850 * @extends OO.ui.Widget
14851 * @mixins OO.ui.mixin.FlaggedElement
14852 * @mixins OO.ui.mixin.TabIndexedElement
14853 * @mixins OO.ui.mixin.TitledElement
14854 * @mixins OO.ui.mixin.AccessKeyedElement
14855 *
14856 * @constructor
14857 * @param {Object} [config] Configuration options
14858 * @cfg {string} [name=''] The value of the input’s HTML `name` attribute.
14859 * @cfg {string} [value=''] The value of the input.
14860 * @cfg {string} [dir] The directionality of the input (ltr/rtl).
14861 * @cfg {Function} [inputFilter] The name of an input filter function. Input filters modify the value of an input
14862 * before it is accepted.
14863 */
14864 OO.ui.InputWidget = function OoUiInputWidget( config ) {
14865 // Configuration initialization
14866 config = config || {};
14867
14868 // Parent constructor
14869 OO.ui.InputWidget.parent.call( this, config );
14870
14871 // Properties
14872 this.$input = this.getInputElement( config );
14873 this.value = '';
14874 this.inputFilter = config.inputFilter;
14875
14876 // Mixin constructors
14877 OO.ui.mixin.FlaggedElement.call( this, config );
14878 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$input } ) );
14879 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$input } ) );
14880 OO.ui.mixin.AccessKeyedElement.call( this, $.extend( {}, config, { $accessKeyed: this.$input } ) );
14881
14882 // Events
14883 this.$input.on( 'keydown mouseup cut paste change input select', this.onEdit.bind( this ) );
14884
14885 // Initialization
14886 this.$input
14887 .addClass( 'oo-ui-inputWidget-input' )
14888 .attr( 'name', config.name )
14889 .prop( 'disabled', this.isDisabled() );
14890 this.$element
14891 .addClass( 'oo-ui-inputWidget' )
14892 .append( this.$input );
14893 this.setValue( config.value );
14894 this.setAccessKey( config.accessKey );
14895 if ( config.dir ) {
14896 this.setDir( config.dir );
14897 }
14898 };
14899
14900 /* Setup */
14901
14902 OO.inheritClass( OO.ui.InputWidget, OO.ui.Widget );
14903 OO.mixinClass( OO.ui.InputWidget, OO.ui.mixin.FlaggedElement );
14904 OO.mixinClass( OO.ui.InputWidget, OO.ui.mixin.TabIndexedElement );
14905 OO.mixinClass( OO.ui.InputWidget, OO.ui.mixin.TitledElement );
14906 OO.mixinClass( OO.ui.InputWidget, OO.ui.mixin.AccessKeyedElement );
14907
14908 /* Static Properties */
14909
14910 OO.ui.InputWidget.static.supportsSimpleLabel = true;
14911
14912 /* Static Methods */
14913
14914 /**
14915 * @inheritdoc
14916 */
14917 OO.ui.InputWidget.static.reusePreInfuseDOM = function ( node, config ) {
14918 config = OO.ui.InputWidget.parent.static.reusePreInfuseDOM( node, config );
14919 // Reusing $input lets browsers preserve inputted values across page reloads (T114134)
14920 config.$input = $( node ).find( '.oo-ui-inputWidget-input' );
14921 return config;
14922 };
14923
14924 /**
14925 * @inheritdoc
14926 */
14927 OO.ui.InputWidget.static.gatherPreInfuseState = function ( node, config ) {
14928 var state = OO.ui.InputWidget.parent.static.gatherPreInfuseState( node, config );
14929 state.value = config.$input.val();
14930 // Might be better in TabIndexedElement, but it's awkward to do there because mixins are awkward
14931 state.focus = config.$input.is( ':focus' );
14932 return state;
14933 };
14934
14935 /* Events */
14936
14937 /**
14938 * @event change
14939 *
14940 * A change event is emitted when the value of the input changes.
14941 *
14942 * @param {string} value
14943 */
14944
14945 /* Methods */
14946
14947 /**
14948 * Get input element.
14949 *
14950 * Subclasses of OO.ui.InputWidget use the `config` parameter to produce different elements in
14951 * different circumstances. The element must have a `value` property (like form elements).
14952 *
14953 * @protected
14954 * @param {Object} config Configuration options
14955 * @return {jQuery} Input element
14956 */
14957 OO.ui.InputWidget.prototype.getInputElement = function ( config ) {
14958 // See #reusePreInfuseDOM about config.$input
14959 return config.$input || $( '<input>' );
14960 };
14961
14962 /**
14963 * Handle potentially value-changing events.
14964 *
14965 * @private
14966 * @param {jQuery.Event} e Key down, mouse up, cut, paste, change, input, or select event
14967 */
14968 OO.ui.InputWidget.prototype.onEdit = function () {
14969 var widget = this;
14970 if ( !this.isDisabled() ) {
14971 // Allow the stack to clear so the value will be updated
14972 setTimeout( function () {
14973 widget.setValue( widget.$input.val() );
14974 } );
14975 }
14976 };
14977
14978 /**
14979 * Get the value of the input.
14980 *
14981 * @return {string} Input value
14982 */
14983 OO.ui.InputWidget.prototype.getValue = function () {
14984 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
14985 // it, and we won't know unless they're kind enough to trigger a 'change' event.
14986 var value = this.$input.val();
14987 if ( this.value !== value ) {
14988 this.setValue( value );
14989 }
14990 return this.value;
14991 };
14992
14993 /**
14994 * Set the directionality of the input, either RTL (right-to-left) or LTR (left-to-right).
14995 *
14996 * @deprecated since v0.13.1, use #setDir directly
14997 * @param {boolean} isRTL Directionality is right-to-left
14998 * @chainable
14999 */
15000 OO.ui.InputWidget.prototype.setRTL = function ( isRTL ) {
15001 this.setDir( isRTL ? 'rtl' : 'ltr' );
15002 return this;
15003 };
15004
15005 /**
15006 * Set the directionality of the input.
15007 *
15008 * @param {string} dir Text directionality: 'ltr', 'rtl' or 'auto'
15009 * @chainable
15010 */
15011 OO.ui.InputWidget.prototype.setDir = function ( dir ) {
15012 this.$input.prop( 'dir', dir );
15013 return this;
15014 };
15015
15016 /**
15017 * Set the value of the input.
15018 *
15019 * @param {string} value New value
15020 * @fires change
15021 * @chainable
15022 */
15023 OO.ui.InputWidget.prototype.setValue = function ( value ) {
15024 value = this.cleanUpValue( value );
15025 // Update the DOM if it has changed. Note that with cleanUpValue, it
15026 // is possible for the DOM value to change without this.value changing.
15027 if ( this.$input.val() !== value ) {
15028 this.$input.val( value );
15029 }
15030 if ( this.value !== value ) {
15031 this.value = value;
15032 this.emit( 'change', this.value );
15033 }
15034 return this;
15035 };
15036
15037 /**
15038 * Set the input's access key.
15039 * FIXME: This is the same code as in OO.ui.mixin.ButtonElement, maybe find a better place for it?
15040 *
15041 * @param {string} accessKey Input's access key, use empty string to remove
15042 * @chainable
15043 */
15044 OO.ui.InputWidget.prototype.setAccessKey = function ( accessKey ) {
15045 accessKey = typeof accessKey === 'string' && accessKey.length ? accessKey : null;
15046
15047 if ( this.accessKey !== accessKey ) {
15048 if ( this.$input ) {
15049 if ( accessKey !== null ) {
15050 this.$input.attr( 'accesskey', accessKey );
15051 } else {
15052 this.$input.removeAttr( 'accesskey' );
15053 }
15054 }
15055 this.accessKey = accessKey;
15056 }
15057
15058 return this;
15059 };
15060
15061 /**
15062 * Clean up incoming value.
15063 *
15064 * Ensures value is a string, and converts undefined and null to empty string.
15065 *
15066 * @private
15067 * @param {string} value Original value
15068 * @return {string} Cleaned up value
15069 */
15070 OO.ui.InputWidget.prototype.cleanUpValue = function ( value ) {
15071 if ( value === undefined || value === null ) {
15072 return '';
15073 } else if ( this.inputFilter ) {
15074 return this.inputFilter( String( value ) );
15075 } else {
15076 return String( value );
15077 }
15078 };
15079
15080 /**
15081 * Simulate the behavior of clicking on a label bound to this input. This method is only called by
15082 * {@link OO.ui.LabelWidget LabelWidget} and {@link OO.ui.FieldLayout FieldLayout}. It should not be
15083 * called directly.
15084 */
15085 OO.ui.InputWidget.prototype.simulateLabelClick = function () {
15086 if ( !this.isDisabled() ) {
15087 if ( this.$input.is( ':checkbox, :radio' ) ) {
15088 this.$input.click();
15089 }
15090 if ( this.$input.is( ':input' ) ) {
15091 this.$input[ 0 ].focus();
15092 }
15093 }
15094 };
15095
15096 /**
15097 * @inheritdoc
15098 */
15099 OO.ui.InputWidget.prototype.setDisabled = function ( state ) {
15100 OO.ui.InputWidget.parent.prototype.setDisabled.call( this, state );
15101 if ( this.$input ) {
15102 this.$input.prop( 'disabled', this.isDisabled() );
15103 }
15104 return this;
15105 };
15106
15107 /**
15108 * Focus the input.
15109 *
15110 * @chainable
15111 */
15112 OO.ui.InputWidget.prototype.focus = function () {
15113 this.$input[ 0 ].focus();
15114 return this;
15115 };
15116
15117 /**
15118 * Blur the input.
15119 *
15120 * @chainable
15121 */
15122 OO.ui.InputWidget.prototype.blur = function () {
15123 this.$input[ 0 ].blur();
15124 return this;
15125 };
15126
15127 /**
15128 * @inheritdoc
15129 */
15130 OO.ui.InputWidget.prototype.restorePreInfuseState = function ( state ) {
15131 OO.ui.InputWidget.parent.prototype.restorePreInfuseState.call( this, state );
15132 if ( state.value !== undefined && state.value !== this.getValue() ) {
15133 this.setValue( state.value );
15134 }
15135 if ( state.focus ) {
15136 this.focus();
15137 }
15138 };
15139
15140 /**
15141 * ButtonInputWidget is used to submit HTML forms and is intended to be used within
15142 * a OO.ui.FormLayout. If you do not need the button to work with HTML forms, you probably
15143 * want to use OO.ui.ButtonWidget instead. Button input widgets can be rendered as either an
15144 * HTML `<button/>` (the default) or an HTML `<input/>` tags. See the
15145 * [OOjs UI documentation on MediaWiki] [1] for more information.
15146 *
15147 * @example
15148 * // A ButtonInputWidget rendered as an HTML button, the default.
15149 * var button = new OO.ui.ButtonInputWidget( {
15150 * label: 'Input button',
15151 * icon: 'check',
15152 * value: 'check'
15153 * } );
15154 * $( 'body' ).append( button.$element );
15155 *
15156 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs#Button_inputs
15157 *
15158 * @class
15159 * @extends OO.ui.InputWidget
15160 * @mixins OO.ui.mixin.ButtonElement
15161 * @mixins OO.ui.mixin.IconElement
15162 * @mixins OO.ui.mixin.IndicatorElement
15163 * @mixins OO.ui.mixin.LabelElement
15164 * @mixins OO.ui.mixin.TitledElement
15165 *
15166 * @constructor
15167 * @param {Object} [config] Configuration options
15168 * @cfg {string} [type='button'] The value of the HTML `'type'` attribute: 'button', 'submit' or 'reset'.
15169 * @cfg {boolean} [useInputTag=false] Use an `<input/>` tag instead of a `<button/>` tag, the default.
15170 * Widgets configured to be an `<input/>` do not support {@link #icon icons} and {@link #indicator indicators},
15171 * non-plaintext {@link #label labels}, or {@link #value values}. In general, useInputTag should only
15172 * be set to `true` when there’s need to support IE6 in a form with multiple buttons.
15173 */
15174 OO.ui.ButtonInputWidget = function OoUiButtonInputWidget( config ) {
15175 // Configuration initialization
15176 config = $.extend( { type: 'button', useInputTag: false }, config );
15177
15178 // Properties (must be set before parent constructor, which calls #setValue)
15179 this.useInputTag = config.useInputTag;
15180
15181 // Parent constructor
15182 OO.ui.ButtonInputWidget.parent.call( this, config );
15183
15184 // Mixin constructors
15185 OO.ui.mixin.ButtonElement.call( this, $.extend( {}, config, { $button: this.$input } ) );
15186 OO.ui.mixin.IconElement.call( this, config );
15187 OO.ui.mixin.IndicatorElement.call( this, config );
15188 OO.ui.mixin.LabelElement.call( this, config );
15189 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$input } ) );
15190
15191 // Initialization
15192 if ( !config.useInputTag ) {
15193 this.$input.append( this.$icon, this.$label, this.$indicator );
15194 }
15195 this.$element.addClass( 'oo-ui-buttonInputWidget' );
15196 };
15197
15198 /* Setup */
15199
15200 OO.inheritClass( OO.ui.ButtonInputWidget, OO.ui.InputWidget );
15201 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.ButtonElement );
15202 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.IconElement );
15203 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.IndicatorElement );
15204 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.LabelElement );
15205 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.TitledElement );
15206
15207 /* Static Properties */
15208
15209 /**
15210 * Disable generating `<label>` elements for buttons. One would very rarely need additional label
15211 * for a button, and it's already a big clickable target, and it causes unexpected rendering.
15212 */
15213 OO.ui.ButtonInputWidget.static.supportsSimpleLabel = false;
15214
15215 /* Methods */
15216
15217 /**
15218 * @inheritdoc
15219 * @protected
15220 */
15221 OO.ui.ButtonInputWidget.prototype.getInputElement = function ( config ) {
15222 var type;
15223 // See InputWidget#reusePreInfuseDOM about config.$input
15224 if ( config.$input ) {
15225 return config.$input.empty();
15226 }
15227 type = [ 'button', 'submit', 'reset' ].indexOf( config.type ) !== -1 ? config.type : 'button';
15228 return $( '<' + ( config.useInputTag ? 'input' : 'button' ) + ' type="' + type + '">' );
15229 };
15230
15231 /**
15232 * Set label value.
15233 *
15234 * If #useInputTag is `true`, the label is set as the `value` of the `<input/>` tag.
15235 *
15236 * @param {jQuery|string|Function|null} label Label nodes, text, a function that returns nodes or
15237 * text, or `null` for no label
15238 * @chainable
15239 */
15240 OO.ui.ButtonInputWidget.prototype.setLabel = function ( label ) {
15241 OO.ui.mixin.LabelElement.prototype.setLabel.call( this, label );
15242
15243 if ( this.useInputTag ) {
15244 if ( typeof label === 'function' ) {
15245 label = OO.ui.resolveMsg( label );
15246 }
15247 if ( label instanceof jQuery ) {
15248 label = label.text();
15249 }
15250 if ( !label ) {
15251 label = '';
15252 }
15253 this.$input.val( label );
15254 }
15255
15256 return this;
15257 };
15258
15259 /**
15260 * Set the value of the input.
15261 *
15262 * This method is disabled for button inputs configured as {@link #useInputTag <input/> tags}, as
15263 * they do not support {@link #value values}.
15264 *
15265 * @param {string} value New value
15266 * @chainable
15267 */
15268 OO.ui.ButtonInputWidget.prototype.setValue = function ( value ) {
15269 if ( !this.useInputTag ) {
15270 OO.ui.ButtonInputWidget.parent.prototype.setValue.call( this, value );
15271 }
15272 return this;
15273 };
15274
15275 /**
15276 * CheckboxInputWidgets, like HTML checkboxes, can be selected and/or configured with a value.
15277 * Note that these {@link OO.ui.InputWidget input widgets} are best laid out
15278 * in {@link OO.ui.FieldLayout field layouts} that use the {@link OO.ui.FieldLayout#align inline}
15279 * alignment. For more information, please see the [OOjs UI documentation on MediaWiki][1].
15280 *
15281 * This widget can be used inside a HTML form, such as a OO.ui.FormLayout.
15282 *
15283 * @example
15284 * // An example of selected, unselected, and disabled checkbox inputs
15285 * var checkbox1=new OO.ui.CheckboxInputWidget( {
15286 * value: 'a',
15287 * selected: true
15288 * } );
15289 * var checkbox2=new OO.ui.CheckboxInputWidget( {
15290 * value: 'b'
15291 * } );
15292 * var checkbox3=new OO.ui.CheckboxInputWidget( {
15293 * value:'c',
15294 * disabled: true
15295 * } );
15296 * // Create a fieldset layout with fields for each checkbox.
15297 * var fieldset = new OO.ui.FieldsetLayout( {
15298 * label: 'Checkboxes'
15299 * } );
15300 * fieldset.addItems( [
15301 * new OO.ui.FieldLayout( checkbox1, { label: 'Selected checkbox', align: 'inline' } ),
15302 * new OO.ui.FieldLayout( checkbox2, { label: 'Unselected checkbox', align: 'inline' } ),
15303 * new OO.ui.FieldLayout( checkbox3, { label: 'Disabled checkbox', align: 'inline' } ),
15304 * ] );
15305 * $( 'body' ).append( fieldset.$element );
15306 *
15307 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
15308 *
15309 * @class
15310 * @extends OO.ui.InputWidget
15311 *
15312 * @constructor
15313 * @param {Object} [config] Configuration options
15314 * @cfg {boolean} [selected=false] Select the checkbox initially. By default, the checkbox is not selected.
15315 */
15316 OO.ui.CheckboxInputWidget = function OoUiCheckboxInputWidget( config ) {
15317 // Configuration initialization
15318 config = config || {};
15319
15320 // Parent constructor
15321 OO.ui.CheckboxInputWidget.parent.call( this, config );
15322
15323 // Initialization
15324 this.$element
15325 .addClass( 'oo-ui-checkboxInputWidget' )
15326 // Required for pretty styling in MediaWiki theme
15327 .append( $( '<span>' ) );
15328 this.setSelected( config.selected !== undefined ? config.selected : false );
15329 };
15330
15331 /* Setup */
15332
15333 OO.inheritClass( OO.ui.CheckboxInputWidget, OO.ui.InputWidget );
15334
15335 /* Static Methods */
15336
15337 /**
15338 * @inheritdoc
15339 */
15340 OO.ui.CheckboxInputWidget.static.gatherPreInfuseState = function ( node, config ) {
15341 var state = OO.ui.CheckboxInputWidget.parent.static.gatherPreInfuseState( node, config );
15342 state.checked = config.$input.prop( 'checked' );
15343 return state;
15344 };
15345
15346 /* Methods */
15347
15348 /**
15349 * @inheritdoc
15350 * @protected
15351 */
15352 OO.ui.CheckboxInputWidget.prototype.getInputElement = function () {
15353 return $( '<input type="checkbox" />' );
15354 };
15355
15356 /**
15357 * @inheritdoc
15358 */
15359 OO.ui.CheckboxInputWidget.prototype.onEdit = function () {
15360 var widget = this;
15361 if ( !this.isDisabled() ) {
15362 // Allow the stack to clear so the value will be updated
15363 setTimeout( function () {
15364 widget.setSelected( widget.$input.prop( 'checked' ) );
15365 } );
15366 }
15367 };
15368
15369 /**
15370 * Set selection state of this checkbox.
15371 *
15372 * @param {boolean} state `true` for selected
15373 * @chainable
15374 */
15375 OO.ui.CheckboxInputWidget.prototype.setSelected = function ( state ) {
15376 state = !!state;
15377 if ( this.selected !== state ) {
15378 this.selected = state;
15379 this.$input.prop( 'checked', this.selected );
15380 this.emit( 'change', this.selected );
15381 }
15382 return this;
15383 };
15384
15385 /**
15386 * Check if this checkbox is selected.
15387 *
15388 * @return {boolean} Checkbox is selected
15389 */
15390 OO.ui.CheckboxInputWidget.prototype.isSelected = function () {
15391 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
15392 // it, and we won't know unless they're kind enough to trigger a 'change' event.
15393 var selected = this.$input.prop( 'checked' );
15394 if ( this.selected !== selected ) {
15395 this.setSelected( selected );
15396 }
15397 return this.selected;
15398 };
15399
15400 /**
15401 * @inheritdoc
15402 */
15403 OO.ui.CheckboxInputWidget.prototype.restorePreInfuseState = function ( state ) {
15404 OO.ui.CheckboxInputWidget.parent.prototype.restorePreInfuseState.call( this, state );
15405 if ( state.checked !== undefined && state.checked !== this.isSelected() ) {
15406 this.setSelected( state.checked );
15407 }
15408 };
15409
15410 /**
15411 * DropdownInputWidget is a {@link OO.ui.DropdownWidget DropdownWidget} intended to be used
15412 * within a HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with the value
15413 * of a hidden HTML `input` tag. Please see the [OOjs UI documentation on MediaWiki][1] for
15414 * more information about input widgets.
15415 *
15416 * A DropdownInputWidget always has a value (one of the options is always selected), unless there
15417 * are no options. If no `value` configuration option is provided, the first option is selected.
15418 * If you need a state representing no value (no option being selected), use a DropdownWidget.
15419 *
15420 * This and OO.ui.RadioSelectInputWidget support the same configuration options.
15421 *
15422 * @example
15423 * // Example: A DropdownInputWidget with three options
15424 * var dropdownInput = new OO.ui.DropdownInputWidget( {
15425 * options: [
15426 * { data: 'a', label: 'First' },
15427 * { data: 'b', label: 'Second'},
15428 * { data: 'c', label: 'Third' }
15429 * ]
15430 * } );
15431 * $( 'body' ).append( dropdownInput.$element );
15432 *
15433 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
15434 *
15435 * @class
15436 * @extends OO.ui.InputWidget
15437 * @mixins OO.ui.mixin.TitledElement
15438 *
15439 * @constructor
15440 * @param {Object} [config] Configuration options
15441 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
15442 * @cfg {Object} [dropdown] Configuration options for {@link OO.ui.DropdownWidget DropdownWidget}
15443 */
15444 OO.ui.DropdownInputWidget = function OoUiDropdownInputWidget( config ) {
15445 // Configuration initialization
15446 config = config || {};
15447
15448 // Properties (must be done before parent constructor which calls #setDisabled)
15449 this.dropdownWidget = new OO.ui.DropdownWidget( config.dropdown );
15450
15451 // Parent constructor
15452 OO.ui.DropdownInputWidget.parent.call( this, config );
15453
15454 // Mixin constructors
15455 OO.ui.mixin.TitledElement.call( this, config );
15456
15457 // Events
15458 this.dropdownWidget.getMenu().connect( this, { select: 'onMenuSelect' } );
15459
15460 // Initialization
15461 this.setOptions( config.options || [] );
15462 this.$element
15463 .addClass( 'oo-ui-dropdownInputWidget' )
15464 .append( this.dropdownWidget.$element );
15465 };
15466
15467 /* Setup */
15468
15469 OO.inheritClass( OO.ui.DropdownInputWidget, OO.ui.InputWidget );
15470 OO.mixinClass( OO.ui.DropdownInputWidget, OO.ui.mixin.TitledElement );
15471
15472 /* Methods */
15473
15474 /**
15475 * @inheritdoc
15476 * @protected
15477 */
15478 OO.ui.DropdownInputWidget.prototype.getInputElement = function ( config ) {
15479 // See InputWidget#reusePreInfuseDOM about config.$input
15480 if ( config.$input ) {
15481 return config.$input.addClass( 'oo-ui-element-hidden' );
15482 }
15483 return $( '<input type="hidden">' );
15484 };
15485
15486 /**
15487 * Handles menu select events.
15488 *
15489 * @private
15490 * @param {OO.ui.MenuOptionWidget} item Selected menu item
15491 */
15492 OO.ui.DropdownInputWidget.prototype.onMenuSelect = function ( item ) {
15493 this.setValue( item.getData() );
15494 };
15495
15496 /**
15497 * @inheritdoc
15498 */
15499 OO.ui.DropdownInputWidget.prototype.setValue = function ( value ) {
15500 value = this.cleanUpValue( value );
15501 this.dropdownWidget.getMenu().selectItemByData( value );
15502 OO.ui.DropdownInputWidget.parent.prototype.setValue.call( this, value );
15503 return this;
15504 };
15505
15506 /**
15507 * @inheritdoc
15508 */
15509 OO.ui.DropdownInputWidget.prototype.setDisabled = function ( state ) {
15510 this.dropdownWidget.setDisabled( state );
15511 OO.ui.DropdownInputWidget.parent.prototype.setDisabled.call( this, state );
15512 return this;
15513 };
15514
15515 /**
15516 * Set the options available for this input.
15517 *
15518 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
15519 * @chainable
15520 */
15521 OO.ui.DropdownInputWidget.prototype.setOptions = function ( options ) {
15522 var
15523 value = this.getValue(),
15524 widget = this;
15525
15526 // Rebuild the dropdown menu
15527 this.dropdownWidget.getMenu()
15528 .clearItems()
15529 .addItems( options.map( function ( opt ) {
15530 var optValue = widget.cleanUpValue( opt.data );
15531 return new OO.ui.MenuOptionWidget( {
15532 data: optValue,
15533 label: opt.label !== undefined ? opt.label : optValue
15534 } );
15535 } ) );
15536
15537 // Restore the previous value, or reset to something sensible
15538 if ( this.dropdownWidget.getMenu().getItemFromData( value ) ) {
15539 // Previous value is still available, ensure consistency with the dropdown
15540 this.setValue( value );
15541 } else {
15542 // No longer valid, reset
15543 if ( options.length ) {
15544 this.setValue( options[ 0 ].data );
15545 }
15546 }
15547
15548 return this;
15549 };
15550
15551 /**
15552 * @inheritdoc
15553 */
15554 OO.ui.DropdownInputWidget.prototype.focus = function () {
15555 this.dropdownWidget.getMenu().toggle( true );
15556 return this;
15557 };
15558
15559 /**
15560 * @inheritdoc
15561 */
15562 OO.ui.DropdownInputWidget.prototype.blur = function () {
15563 this.dropdownWidget.getMenu().toggle( false );
15564 return this;
15565 };
15566
15567 /**
15568 * RadioInputWidget creates a single radio button. Because radio buttons are usually used as a set,
15569 * in most cases you will want to use a {@link OO.ui.RadioSelectWidget radio select}
15570 * with {@link OO.ui.RadioOptionWidget radio options} instead of this class. For more information,
15571 * please see the [OOjs UI documentation on MediaWiki][1].
15572 *
15573 * This widget can be used inside a HTML form, such as a OO.ui.FormLayout.
15574 *
15575 * @example
15576 * // An example of selected, unselected, and disabled radio inputs
15577 * var radio1 = new OO.ui.RadioInputWidget( {
15578 * value: 'a',
15579 * selected: true
15580 * } );
15581 * var radio2 = new OO.ui.RadioInputWidget( {
15582 * value: 'b'
15583 * } );
15584 * var radio3 = new OO.ui.RadioInputWidget( {
15585 * value: 'c',
15586 * disabled: true
15587 * } );
15588 * // Create a fieldset layout with fields for each radio button.
15589 * var fieldset = new OO.ui.FieldsetLayout( {
15590 * label: 'Radio inputs'
15591 * } );
15592 * fieldset.addItems( [
15593 * new OO.ui.FieldLayout( radio1, { label: 'Selected', align: 'inline' } ),
15594 * new OO.ui.FieldLayout( radio2, { label: 'Unselected', align: 'inline' } ),
15595 * new OO.ui.FieldLayout( radio3, { label: 'Disabled', align: 'inline' } ),
15596 * ] );
15597 * $( 'body' ).append( fieldset.$element );
15598 *
15599 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
15600 *
15601 * @class
15602 * @extends OO.ui.InputWidget
15603 *
15604 * @constructor
15605 * @param {Object} [config] Configuration options
15606 * @cfg {boolean} [selected=false] Select the radio button initially. By default, the radio button is not selected.
15607 */
15608 OO.ui.RadioInputWidget = function OoUiRadioInputWidget( config ) {
15609 // Configuration initialization
15610 config = config || {};
15611
15612 // Parent constructor
15613 OO.ui.RadioInputWidget.parent.call( this, config );
15614
15615 // Initialization
15616 this.$element
15617 .addClass( 'oo-ui-radioInputWidget' )
15618 // Required for pretty styling in MediaWiki theme
15619 .append( $( '<span>' ) );
15620 this.setSelected( config.selected !== undefined ? config.selected : false );
15621 };
15622
15623 /* Setup */
15624
15625 OO.inheritClass( OO.ui.RadioInputWidget, OO.ui.InputWidget );
15626
15627 /* Static Methods */
15628
15629 /**
15630 * @inheritdoc
15631 */
15632 OO.ui.RadioInputWidget.static.gatherPreInfuseState = function ( node, config ) {
15633 var state = OO.ui.RadioInputWidget.parent.static.gatherPreInfuseState( node, config );
15634 state.checked = config.$input.prop( 'checked' );
15635 return state;
15636 };
15637
15638 /* Methods */
15639
15640 /**
15641 * @inheritdoc
15642 * @protected
15643 */
15644 OO.ui.RadioInputWidget.prototype.getInputElement = function () {
15645 return $( '<input type="radio" />' );
15646 };
15647
15648 /**
15649 * @inheritdoc
15650 */
15651 OO.ui.RadioInputWidget.prototype.onEdit = function () {
15652 // RadioInputWidget doesn't track its state.
15653 };
15654
15655 /**
15656 * Set selection state of this radio button.
15657 *
15658 * @param {boolean} state `true` for selected
15659 * @chainable
15660 */
15661 OO.ui.RadioInputWidget.prototype.setSelected = function ( state ) {
15662 // RadioInputWidget doesn't track its state.
15663 this.$input.prop( 'checked', state );
15664 return this;
15665 };
15666
15667 /**
15668 * Check if this radio button is selected.
15669 *
15670 * @return {boolean} Radio is selected
15671 */
15672 OO.ui.RadioInputWidget.prototype.isSelected = function () {
15673 return this.$input.prop( 'checked' );
15674 };
15675
15676 /**
15677 * @inheritdoc
15678 */
15679 OO.ui.RadioInputWidget.prototype.restorePreInfuseState = function ( state ) {
15680 OO.ui.RadioInputWidget.parent.prototype.restorePreInfuseState.call( this, state );
15681 if ( state.checked !== undefined && state.checked !== this.isSelected() ) {
15682 this.setSelected( state.checked );
15683 }
15684 };
15685
15686 /**
15687 * RadioSelectInputWidget is a {@link OO.ui.RadioSelectWidget RadioSelectWidget} intended to be used
15688 * within a HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with the value
15689 * of a hidden HTML `input` tag. Please see the [OOjs UI documentation on MediaWiki][1] for
15690 * more information about input widgets.
15691 *
15692 * This and OO.ui.DropdownInputWidget support the same configuration options.
15693 *
15694 * @example
15695 * // Example: A RadioSelectInputWidget with three options
15696 * var radioSelectInput = new OO.ui.RadioSelectInputWidget( {
15697 * options: [
15698 * { data: 'a', label: 'First' },
15699 * { data: 'b', label: 'Second'},
15700 * { data: 'c', label: 'Third' }
15701 * ]
15702 * } );
15703 * $( 'body' ).append( radioSelectInput.$element );
15704 *
15705 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
15706 *
15707 * @class
15708 * @extends OO.ui.InputWidget
15709 *
15710 * @constructor
15711 * @param {Object} [config] Configuration options
15712 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
15713 */
15714 OO.ui.RadioSelectInputWidget = function OoUiRadioSelectInputWidget( config ) {
15715 // Configuration initialization
15716 config = config || {};
15717
15718 // Properties (must be done before parent constructor which calls #setDisabled)
15719 this.radioSelectWidget = new OO.ui.RadioSelectWidget();
15720
15721 // Parent constructor
15722 OO.ui.RadioSelectInputWidget.parent.call( this, config );
15723
15724 // Events
15725 this.radioSelectWidget.connect( this, { select: 'onMenuSelect' } );
15726
15727 // Initialization
15728 this.setOptions( config.options || [] );
15729 this.$element
15730 .addClass( 'oo-ui-radioSelectInputWidget' )
15731 .append( this.radioSelectWidget.$element );
15732 };
15733
15734 /* Setup */
15735
15736 OO.inheritClass( OO.ui.RadioSelectInputWidget, OO.ui.InputWidget );
15737
15738 /* Static Properties */
15739
15740 OO.ui.RadioSelectInputWidget.static.supportsSimpleLabel = false;
15741
15742 /* Static Methods */
15743
15744 /**
15745 * @inheritdoc
15746 */
15747 OO.ui.RadioSelectInputWidget.static.gatherPreInfuseState = function ( node, config ) {
15748 var state = OO.ui.RadioSelectInputWidget.parent.static.gatherPreInfuseState( node, config );
15749 state.value = $( node ).find( '.oo-ui-radioInputWidget .oo-ui-inputWidget-input:checked' ).val();
15750 return state;
15751 };
15752
15753 /* Methods */
15754
15755 /**
15756 * @inheritdoc
15757 * @protected
15758 */
15759 OO.ui.RadioSelectInputWidget.prototype.getInputElement = function () {
15760 return $( '<input type="hidden">' );
15761 };
15762
15763 /**
15764 * Handles menu select events.
15765 *
15766 * @private
15767 * @param {OO.ui.RadioOptionWidget} item Selected menu item
15768 */
15769 OO.ui.RadioSelectInputWidget.prototype.onMenuSelect = function ( item ) {
15770 this.setValue( item.getData() );
15771 };
15772
15773 /**
15774 * @inheritdoc
15775 */
15776 OO.ui.RadioSelectInputWidget.prototype.setValue = function ( value ) {
15777 value = this.cleanUpValue( value );
15778 this.radioSelectWidget.selectItemByData( value );
15779 OO.ui.RadioSelectInputWidget.parent.prototype.setValue.call( this, value );
15780 return this;
15781 };
15782
15783 /**
15784 * @inheritdoc
15785 */
15786 OO.ui.RadioSelectInputWidget.prototype.setDisabled = function ( state ) {
15787 this.radioSelectWidget.setDisabled( state );
15788 OO.ui.RadioSelectInputWidget.parent.prototype.setDisabled.call( this, state );
15789 return this;
15790 };
15791
15792 /**
15793 * Set the options available for this input.
15794 *
15795 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
15796 * @chainable
15797 */
15798 OO.ui.RadioSelectInputWidget.prototype.setOptions = function ( options ) {
15799 var
15800 value = this.getValue(),
15801 widget = this;
15802
15803 // Rebuild the radioSelect menu
15804 this.radioSelectWidget
15805 .clearItems()
15806 .addItems( options.map( function ( opt ) {
15807 var optValue = widget.cleanUpValue( opt.data );
15808 return new OO.ui.RadioOptionWidget( {
15809 data: optValue,
15810 label: opt.label !== undefined ? opt.label : optValue
15811 } );
15812 } ) );
15813
15814 // Restore the previous value, or reset to something sensible
15815 if ( this.radioSelectWidget.getItemFromData( value ) ) {
15816 // Previous value is still available, ensure consistency with the radioSelect
15817 this.setValue( value );
15818 } else {
15819 // No longer valid, reset
15820 if ( options.length ) {
15821 this.setValue( options[ 0 ].data );
15822 }
15823 }
15824
15825 return this;
15826 };
15827
15828 /**
15829 * TextInputWidgets, like HTML text inputs, can be configured with options that customize the
15830 * size of the field as well as its presentation. In addition, these widgets can be configured
15831 * with {@link OO.ui.mixin.IconElement icons}, {@link OO.ui.mixin.IndicatorElement indicators}, an optional
15832 * validation-pattern (used to determine if an input value is valid or not) and an input filter,
15833 * which modifies incoming values rather than validating them.
15834 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
15835 *
15836 * This widget can be used inside a HTML form, such as a OO.ui.FormLayout.
15837 *
15838 * @example
15839 * // Example of a text input widget
15840 * var textInput = new OO.ui.TextInputWidget( {
15841 * value: 'Text input'
15842 * } )
15843 * $( 'body' ).append( textInput.$element );
15844 *
15845 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
15846 *
15847 * @class
15848 * @extends OO.ui.InputWidget
15849 * @mixins OO.ui.mixin.IconElement
15850 * @mixins OO.ui.mixin.IndicatorElement
15851 * @mixins OO.ui.mixin.PendingElement
15852 * @mixins OO.ui.mixin.LabelElement
15853 *
15854 * @constructor
15855 * @param {Object} [config] Configuration options
15856 * @cfg {string} [type='text'] The value of the HTML `type` attribute: 'text', 'password', 'search',
15857 * 'email' or 'url'. Ignored if `multiline` is true.
15858 *
15859 * Some values of `type` result in additional behaviors:
15860 *
15861 * - `search`: implies `icon: 'search'` and `indicator: 'clear'`; when clicked, the indicator
15862 * empties the text field
15863 * @cfg {string} [placeholder] Placeholder text
15864 * @cfg {boolean} [autofocus=false] Use an HTML `autofocus` attribute to
15865 * instruct the browser to focus this widget.
15866 * @cfg {boolean} [readOnly=false] Prevent changes to the value of the text input.
15867 * @cfg {number} [maxLength] Maximum number of characters allowed in the input.
15868 * @cfg {boolean} [multiline=false] Allow multiple lines of text
15869 * @cfg {number} [rows] If multiline, number of visible lines in textarea. If used with `autosize`,
15870 * specifies minimum number of rows to display.
15871 * @cfg {boolean} [autosize=false] Automatically resize the text input to fit its content.
15872 * Use the #maxRows config to specify a maximum number of displayed rows.
15873 * @cfg {boolean} [maxRows] Maximum number of rows to display when #autosize is set to true.
15874 * Defaults to the maximum of `10` and `2 * rows`, or `10` if `rows` isn't provided.
15875 * @cfg {string} [labelPosition='after'] The position of the inline label relative to that of
15876 * the value or placeholder text: `'before'` or `'after'`
15877 * @cfg {boolean} [required=false] Mark the field as required. Implies `indicator: 'required'`.
15878 * @cfg {boolean} [autocomplete=true] Should the browser support autocomplete for this field
15879 * @cfg {RegExp|Function|string} [validate] Validation pattern: when string, a symbolic name of a
15880 * pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer'
15881 * (the value must contain only numbers); when RegExp, a regular expression that must match the
15882 * value for it to be considered valid; when Function, a function receiving the value as parameter
15883 * that must return true, or promise resolving to true, for it to be considered valid.
15884 */
15885 OO.ui.TextInputWidget = function OoUiTextInputWidget( config ) {
15886 // Configuration initialization
15887 config = $.extend( {
15888 type: 'text',
15889 labelPosition: 'after'
15890 }, config );
15891 if ( config.type === 'search' ) {
15892 if ( config.icon === undefined ) {
15893 config.icon = 'search';
15894 }
15895 // indicator: 'clear' is set dynamically later, depending on value
15896 }
15897 if ( config.required ) {
15898 if ( config.indicator === undefined ) {
15899 config.indicator = 'required';
15900 }
15901 }
15902
15903 // Parent constructor
15904 OO.ui.TextInputWidget.parent.call( this, config );
15905
15906 // Mixin constructors
15907 OO.ui.mixin.IconElement.call( this, config );
15908 OO.ui.mixin.IndicatorElement.call( this, config );
15909 OO.ui.mixin.PendingElement.call( this, $.extend( {}, config, { $pending: this.$input } ) );
15910 OO.ui.mixin.LabelElement.call( this, config );
15911
15912 // Properties
15913 this.type = this.getSaneType( config );
15914 this.readOnly = false;
15915 this.multiline = !!config.multiline;
15916 this.autosize = !!config.autosize;
15917 this.minRows = config.rows !== undefined ? config.rows : '';
15918 this.maxRows = config.maxRows || Math.max( 2 * ( this.minRows || 0 ), 10 );
15919 this.validate = null;
15920 this.styleHeight = null;
15921 this.scrollWidth = null;
15922
15923 // Clone for resizing
15924 if ( this.autosize ) {
15925 this.$clone = this.$input
15926 .clone()
15927 .insertAfter( this.$input )
15928 .attr( 'aria-hidden', 'true' )
15929 .addClass( 'oo-ui-element-hidden' );
15930 }
15931
15932 this.setValidation( config.validate );
15933 this.setLabelPosition( config.labelPosition );
15934
15935 // Events
15936 this.$input.on( {
15937 keypress: this.onKeyPress.bind( this ),
15938 blur: this.onBlur.bind( this )
15939 } );
15940 this.$input.one( {
15941 focus: this.onElementAttach.bind( this )
15942 } );
15943 this.$icon.on( 'mousedown', this.onIconMouseDown.bind( this ) );
15944 this.$indicator.on( 'mousedown', this.onIndicatorMouseDown.bind( this ) );
15945 this.on( 'labelChange', this.updatePosition.bind( this ) );
15946 this.connect( this, {
15947 change: 'onChange',
15948 disable: 'onDisable'
15949 } );
15950
15951 // Initialization
15952 this.$element
15953 .addClass( 'oo-ui-textInputWidget oo-ui-textInputWidget-type-' + this.type )
15954 .append( this.$icon, this.$indicator );
15955 this.setReadOnly( !!config.readOnly );
15956 this.updateSearchIndicator();
15957 if ( config.placeholder ) {
15958 this.$input.attr( 'placeholder', config.placeholder );
15959 }
15960 if ( config.maxLength !== undefined ) {
15961 this.$input.attr( 'maxlength', config.maxLength );
15962 }
15963 if ( config.autofocus ) {
15964 this.$input.attr( 'autofocus', 'autofocus' );
15965 }
15966 if ( config.required ) {
15967 this.$input.attr( 'required', 'required' );
15968 this.$input.attr( 'aria-required', 'true' );
15969 }
15970 if ( config.autocomplete === false ) {
15971 this.$input.attr( 'autocomplete', 'off' );
15972 // Turning off autocompletion also disables "form caching" when the user navigates to a
15973 // different page and then clicks "Back". Re-enable it when leaving. Borrowed from jQuery UI.
15974 $( window ).on( {
15975 beforeunload: function () {
15976 this.$input.removeAttr( 'autocomplete' );
15977 }.bind( this ),
15978 pageshow: function () {
15979 // Browsers don't seem to actually fire this event on "Back", they instead just reload the
15980 // whole page... it shouldn't hurt, though.
15981 this.$input.attr( 'autocomplete', 'off' );
15982 }.bind( this )
15983 } );
15984 }
15985 if ( this.multiline && config.rows ) {
15986 this.$input.attr( 'rows', config.rows );
15987 }
15988 if ( this.label || config.autosize ) {
15989 this.installParentChangeDetector();
15990 }
15991 };
15992
15993 /* Setup */
15994
15995 OO.inheritClass( OO.ui.TextInputWidget, OO.ui.InputWidget );
15996 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.mixin.IconElement );
15997 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.mixin.IndicatorElement );
15998 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.mixin.PendingElement );
15999 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.mixin.LabelElement );
16000
16001 /* Static Properties */
16002
16003 OO.ui.TextInputWidget.static.validationPatterns = {
16004 'non-empty': /.+/,
16005 integer: /^\d+$/
16006 };
16007
16008 /* Static Methods */
16009
16010 /**
16011 * @inheritdoc
16012 */
16013 OO.ui.TextInputWidget.static.gatherPreInfuseState = function ( node, config ) {
16014 var state = OO.ui.TextInputWidget.parent.static.gatherPreInfuseState( node, config );
16015 if ( config.multiline ) {
16016 state.scrollTop = config.$input.scrollTop();
16017 }
16018 return state;
16019 };
16020
16021 /* Events */
16022
16023 /**
16024 * An `enter` event is emitted when the user presses 'enter' inside the text box.
16025 *
16026 * Not emitted if the input is multiline.
16027 *
16028 * @event enter
16029 */
16030
16031 /**
16032 * A `resize` event is emitted when autosize is set and the widget resizes
16033 *
16034 * @event resize
16035 */
16036
16037 /* Methods */
16038
16039 /**
16040 * Handle icon mouse down events.
16041 *
16042 * @private
16043 * @param {jQuery.Event} e Mouse down event
16044 * @fires icon
16045 */
16046 OO.ui.TextInputWidget.prototype.onIconMouseDown = function ( e ) {
16047 if ( e.which === OO.ui.MouseButtons.LEFT ) {
16048 this.$input[ 0 ].focus();
16049 return false;
16050 }
16051 };
16052
16053 /**
16054 * Handle indicator mouse down events.
16055 *
16056 * @private
16057 * @param {jQuery.Event} e Mouse down event
16058 * @fires indicator
16059 */
16060 OO.ui.TextInputWidget.prototype.onIndicatorMouseDown = function ( e ) {
16061 if ( e.which === OO.ui.MouseButtons.LEFT ) {
16062 if ( this.type === 'search' ) {
16063 // Clear the text field
16064 this.setValue( '' );
16065 }
16066 this.$input[ 0 ].focus();
16067 return false;
16068 }
16069 };
16070
16071 /**
16072 * Handle key press events.
16073 *
16074 * @private
16075 * @param {jQuery.Event} e Key press event
16076 * @fires enter If enter key is pressed and input is not multiline
16077 */
16078 OO.ui.TextInputWidget.prototype.onKeyPress = function ( e ) {
16079 if ( e.which === OO.ui.Keys.ENTER && !this.multiline ) {
16080 this.emit( 'enter', e );
16081 }
16082 };
16083
16084 /**
16085 * Handle blur events.
16086 *
16087 * @private
16088 * @param {jQuery.Event} e Blur event
16089 */
16090 OO.ui.TextInputWidget.prototype.onBlur = function () {
16091 this.setValidityFlag();
16092 };
16093
16094 /**
16095 * Handle element attach events.
16096 *
16097 * @private
16098 * @param {jQuery.Event} e Element attach event
16099 */
16100 OO.ui.TextInputWidget.prototype.onElementAttach = function () {
16101 // Any previously calculated size is now probably invalid if we reattached elsewhere
16102 this.valCache = null;
16103 this.adjustSize();
16104 this.positionLabel();
16105 };
16106
16107 /**
16108 * Handle change events.
16109 *
16110 * @param {string} value
16111 * @private
16112 */
16113 OO.ui.TextInputWidget.prototype.onChange = function () {
16114 this.updateSearchIndicator();
16115 this.setValidityFlag();
16116 this.adjustSize();
16117 };
16118
16119 /**
16120 * Handle disable events.
16121 *
16122 * @param {boolean} disabled Element is disabled
16123 * @private
16124 */
16125 OO.ui.TextInputWidget.prototype.onDisable = function () {
16126 this.updateSearchIndicator();
16127 };
16128
16129 /**
16130 * Check if the input is {@link #readOnly read-only}.
16131 *
16132 * @return {boolean}
16133 */
16134 OO.ui.TextInputWidget.prototype.isReadOnly = function () {
16135 return this.readOnly;
16136 };
16137
16138 /**
16139 * Set the {@link #readOnly read-only} state of the input.
16140 *
16141 * @param {boolean} state Make input read-only
16142 * @chainable
16143 */
16144 OO.ui.TextInputWidget.prototype.setReadOnly = function ( state ) {
16145 this.readOnly = !!state;
16146 this.$input.prop( 'readOnly', this.readOnly );
16147 this.updateSearchIndicator();
16148 return this;
16149 };
16150
16151 /**
16152 * Support function for making #onElementAttach work across browsers.
16153 *
16154 * This whole function could be replaced with one line of code using the DOMNodeInsertedIntoDocument
16155 * event, but it's not supported by Firefox and allegedly deprecated, so we only use it as fallback.
16156 *
16157 * Due to MutationObserver performance woes, #onElementAttach is only somewhat reliably called the
16158 * first time that the element gets attached to the documented.
16159 */
16160 OO.ui.TextInputWidget.prototype.installParentChangeDetector = function () {
16161 var mutationObserver, onRemove, topmostNode, fakeParentNode,
16162 MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver,
16163 widget = this;
16164
16165 if ( MutationObserver ) {
16166 // The new way. If only it wasn't so ugly.
16167
16168 if ( this.$element.closest( 'html' ).length ) {
16169 // Widget is attached already, do nothing. This breaks the functionality of this function when
16170 // the widget is detached and reattached. Alas, doing this correctly with MutationObserver
16171 // would require observation of the whole document, which would hurt performance of other,
16172 // more important code.
16173 return;
16174 }
16175
16176 // Find topmost node in the tree
16177 topmostNode = this.$element[ 0 ];
16178 while ( topmostNode.parentNode ) {
16179 topmostNode = topmostNode.parentNode;
16180 }
16181
16182 // We have no way to detect the $element being attached somewhere without observing the entire
16183 // DOM with subtree modifications, which would hurt performance. So we cheat: we hook to the
16184 // parent node of $element, and instead detect when $element is removed from it (and thus
16185 // probably attached somewhere else). If there is no parent, we create a "fake" one. If it
16186 // doesn't get attached, we end up back here and create the parent.
16187
16188 mutationObserver = new MutationObserver( function ( mutations ) {
16189 var i, j, removedNodes;
16190 for ( i = 0; i < mutations.length; i++ ) {
16191 removedNodes = mutations[ i ].removedNodes;
16192 for ( j = 0; j < removedNodes.length; j++ ) {
16193 if ( removedNodes[ j ] === topmostNode ) {
16194 setTimeout( onRemove, 0 );
16195 return;
16196 }
16197 }
16198 }
16199 } );
16200
16201 onRemove = function () {
16202 // If the node was attached somewhere else, report it
16203 if ( widget.$element.closest( 'html' ).length ) {
16204 widget.onElementAttach();
16205 }
16206 mutationObserver.disconnect();
16207 widget.installParentChangeDetector();
16208 };
16209
16210 // Create a fake parent and observe it
16211 fakeParentNode = $( '<div>' ).append( topmostNode )[ 0 ];
16212 mutationObserver.observe( fakeParentNode, { childList: true } );
16213 } else {
16214 // Using the DOMNodeInsertedIntoDocument event is much nicer and less magical, and works for
16215 // detachment and reattachment, but it's not supported by Firefox and allegedly deprecated.
16216 this.$element.on( 'DOMNodeInsertedIntoDocument', this.onElementAttach.bind( this ) );
16217 }
16218 };
16219
16220 /**
16221 * Automatically adjust the size of the text input.
16222 *
16223 * This only affects #multiline inputs that are {@link #autosize autosized}.
16224 *
16225 * @chainable
16226 * @fires resize
16227 */
16228 OO.ui.TextInputWidget.prototype.adjustSize = function () {
16229 var scrollHeight, innerHeight, outerHeight, maxInnerHeight, measurementError,
16230 idealHeight, newHeight, scrollWidth, property;
16231
16232 if ( this.multiline && this.$input.val() !== this.valCache ) {
16233 if ( this.autosize ) {
16234 this.$clone
16235 .val( this.$input.val() )
16236 .attr( 'rows', this.minRows )
16237 // Set inline height property to 0 to measure scroll height
16238 .css( 'height', 0 );
16239
16240 this.$clone.removeClass( 'oo-ui-element-hidden' );
16241
16242 this.valCache = this.$input.val();
16243
16244 scrollHeight = this.$clone[ 0 ].scrollHeight;
16245
16246 // Remove inline height property to measure natural heights
16247 this.$clone.css( 'height', '' );
16248 innerHeight = this.$clone.innerHeight();
16249 outerHeight = this.$clone.outerHeight();
16250
16251 // Measure max rows height
16252 this.$clone
16253 .attr( 'rows', this.maxRows )
16254 .css( 'height', 'auto' )
16255 .val( '' );
16256 maxInnerHeight = this.$clone.innerHeight();
16257
16258 // Difference between reported innerHeight and scrollHeight with no scrollbars present
16259 // Equals 1 on Blink-based browsers and 0 everywhere else
16260 measurementError = maxInnerHeight - this.$clone[ 0 ].scrollHeight;
16261 idealHeight = Math.min( maxInnerHeight, scrollHeight + measurementError );
16262
16263 this.$clone.addClass( 'oo-ui-element-hidden' );
16264
16265 // Only apply inline height when expansion beyond natural height is needed
16266 // Use the difference between the inner and outer height as a buffer
16267 newHeight = idealHeight > innerHeight ? idealHeight + ( outerHeight - innerHeight ) : '';
16268 if ( newHeight !== this.styleHeight ) {
16269 this.$input.css( 'height', newHeight );
16270 this.styleHeight = newHeight;
16271 this.emit( 'resize' );
16272 }
16273 }
16274 scrollWidth = this.$input[ 0 ].offsetWidth - this.$input[ 0 ].clientWidth;
16275 if ( scrollWidth !== this.scrollWidth ) {
16276 property = this.$element.css( 'direction' ) === 'rtl' ? 'left' : 'right';
16277 // Reset
16278 this.$label.css( { right: '', left: '' } );
16279 this.$indicator.css( { right: '', left: '' } );
16280
16281 if ( scrollWidth ) {
16282 this.$indicator.css( property, scrollWidth );
16283 if ( this.labelPosition === 'after' ) {
16284 this.$label.css( property, scrollWidth );
16285 }
16286 }
16287
16288 this.scrollWidth = scrollWidth;
16289 this.positionLabel();
16290 }
16291 }
16292 return this;
16293 };
16294
16295 /**
16296 * @inheritdoc
16297 * @protected
16298 */
16299 OO.ui.TextInputWidget.prototype.getInputElement = function ( config ) {
16300 return config.multiline ?
16301 $( '<textarea>' ) :
16302 $( '<input type="' + this.getSaneType( config ) + '" />' );
16303 };
16304
16305 /**
16306 * Get sanitized value for 'type' for given config.
16307 *
16308 * @param {Object} config Configuration options
16309 * @return {string|null}
16310 * @private
16311 */
16312 OO.ui.TextInputWidget.prototype.getSaneType = function ( config ) {
16313 var type = [ 'text', 'password', 'search', 'email', 'url' ].indexOf( config.type ) !== -1 ?
16314 config.type :
16315 'text';
16316 return config.multiline ? 'multiline' : type;
16317 };
16318
16319 /**
16320 * Check if the input supports multiple lines.
16321 *
16322 * @return {boolean}
16323 */
16324 OO.ui.TextInputWidget.prototype.isMultiline = function () {
16325 return !!this.multiline;
16326 };
16327
16328 /**
16329 * Check if the input automatically adjusts its size.
16330 *
16331 * @return {boolean}
16332 */
16333 OO.ui.TextInputWidget.prototype.isAutosizing = function () {
16334 return !!this.autosize;
16335 };
16336
16337 /**
16338 * Focus the input and select a specified range within the text.
16339 *
16340 * @param {number} from Select from offset
16341 * @param {number} [to] Select to offset, defaults to from
16342 * @chainable
16343 */
16344 OO.ui.TextInputWidget.prototype.selectRange = function ( from, to ) {
16345 var isBackwards, start, end,
16346 input = this.$input[ 0 ];
16347
16348 to = to || from;
16349
16350 isBackwards = to < from;
16351 start = isBackwards ? to : from;
16352 end = isBackwards ? from : to;
16353
16354 this.focus();
16355
16356 input.setSelectionRange( start, end, isBackwards ? 'backward' : 'forward' );
16357 return this;
16358 };
16359
16360 /**
16361 * Get an object describing the current selection range in a directional manner
16362 *
16363 * @return {Object} Object containing 'from' and 'to' offsets
16364 */
16365 OO.ui.TextInputWidget.prototype.getRange = function () {
16366 var input = this.$input[ 0 ],
16367 start = input.selectionStart,
16368 end = input.selectionEnd,
16369 isBackwards = input.selectionDirection === 'backward';
16370
16371 return {
16372 from: isBackwards ? end : start,
16373 to: isBackwards ? start : end
16374 };
16375 };
16376
16377 /**
16378 * Get the length of the text input value.
16379 *
16380 * This could differ from the length of #getValue if the
16381 * value gets filtered
16382 *
16383 * @return {number} Input length
16384 */
16385 OO.ui.TextInputWidget.prototype.getInputLength = function () {
16386 return this.$input[ 0 ].value.length;
16387 };
16388
16389 /**
16390 * Focus the input and select the entire text.
16391 *
16392 * @chainable
16393 */
16394 OO.ui.TextInputWidget.prototype.select = function () {
16395 return this.selectRange( 0, this.getInputLength() );
16396 };
16397
16398 /**
16399 * Focus the input and move the cursor to the start.
16400 *
16401 * @chainable
16402 */
16403 OO.ui.TextInputWidget.prototype.moveCursorToStart = function () {
16404 return this.selectRange( 0 );
16405 };
16406
16407 /**
16408 * Focus the input and move the cursor to the end.
16409 *
16410 * @chainable
16411 */
16412 OO.ui.TextInputWidget.prototype.moveCursorToEnd = function () {
16413 return this.selectRange( this.getInputLength() );
16414 };
16415
16416 /**
16417 * Insert new content into the input.
16418 *
16419 * @param {string} content Content to be inserted
16420 * @chainable
16421 */
16422 OO.ui.TextInputWidget.prototype.insertContent = function ( content ) {
16423 var start, end,
16424 range = this.getRange(),
16425 value = this.getValue();
16426
16427 start = Math.min( range.from, range.to );
16428 end = Math.max( range.from, range.to );
16429
16430 this.setValue( value.slice( 0, start ) + content + value.slice( end ) );
16431 this.selectRange( start + content.length );
16432 return this;
16433 };
16434
16435 /**
16436 * Insert new content either side of a selection.
16437 *
16438 * @param {string} pre Content to be inserted before the selection
16439 * @param {string} post Content to be inserted after the selection
16440 * @chainable
16441 */
16442 OO.ui.TextInputWidget.prototype.encapsulateContent = function ( pre, post ) {
16443 var start, end,
16444 range = this.getRange(),
16445 offset = pre.length;
16446
16447 start = Math.min( range.from, range.to );
16448 end = Math.max( range.from, range.to );
16449
16450 this.selectRange( start ).insertContent( pre );
16451 this.selectRange( offset + end ).insertContent( post );
16452
16453 this.selectRange( offset + start, offset + end );
16454 return this;
16455 };
16456
16457 /**
16458 * Set the validation pattern.
16459 *
16460 * The validation pattern is either a regular expression, a function, or the symbolic name of a
16461 * pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer' (the
16462 * value must contain only numbers).
16463 *
16464 * @param {RegExp|Function|string|null} validate Regular expression, function, or the symbolic name
16465 * of a pattern (either ‘integer’ or ‘non-empty’) defined by the class.
16466 */
16467 OO.ui.TextInputWidget.prototype.setValidation = function ( validate ) {
16468 if ( validate instanceof RegExp || validate instanceof Function ) {
16469 this.validate = validate;
16470 } else {
16471 this.validate = this.constructor.static.validationPatterns[ validate ] || /.*/;
16472 }
16473 };
16474
16475 /**
16476 * Sets the 'invalid' flag appropriately.
16477 *
16478 * @param {boolean} [isValid] Optionally override validation result
16479 */
16480 OO.ui.TextInputWidget.prototype.setValidityFlag = function ( isValid ) {
16481 var widget = this,
16482 setFlag = function ( valid ) {
16483 if ( !valid ) {
16484 widget.$input.attr( 'aria-invalid', 'true' );
16485 } else {
16486 widget.$input.removeAttr( 'aria-invalid' );
16487 }
16488 widget.setFlags( { invalid: !valid } );
16489 };
16490
16491 if ( isValid !== undefined ) {
16492 setFlag( isValid );
16493 } else {
16494 this.getValidity().then( function () {
16495 setFlag( true );
16496 }, function () {
16497 setFlag( false );
16498 } );
16499 }
16500 };
16501
16502 /**
16503 * Check if a value is valid.
16504 *
16505 * This method returns a promise that resolves with a boolean `true` if the current value is
16506 * considered valid according to the supplied {@link #validate validation pattern}.
16507 *
16508 * @deprecated
16509 * @return {jQuery.Promise} A promise that resolves to a boolean `true` if the value is valid.
16510 */
16511 OO.ui.TextInputWidget.prototype.isValid = function () {
16512 var result;
16513
16514 if ( this.validate instanceof Function ) {
16515 result = this.validate( this.getValue() );
16516 if ( $.isFunction( result.promise ) ) {
16517 return result.promise();
16518 } else {
16519 return $.Deferred().resolve( !!result ).promise();
16520 }
16521 } else {
16522 return $.Deferred().resolve( !!this.getValue().match( this.validate ) ).promise();
16523 }
16524 };
16525
16526 /**
16527 * Get the validity of current value.
16528 *
16529 * This method returns a promise that resolves if the value is valid and rejects if
16530 * it isn't. Uses the {@link #validate validation pattern} to check for validity.
16531 *
16532 * @return {jQuery.Promise} A promise that resolves if the value is valid, rejects if not.
16533 */
16534 OO.ui.TextInputWidget.prototype.getValidity = function () {
16535 var result, promise;
16536
16537 function rejectOrResolve( valid ) {
16538 if ( valid ) {
16539 return $.Deferred().resolve().promise();
16540 } else {
16541 return $.Deferred().reject().promise();
16542 }
16543 }
16544
16545 if ( this.validate instanceof Function ) {
16546 result = this.validate( this.getValue() );
16547
16548 if ( $.isFunction( result.promise ) ) {
16549 promise = $.Deferred();
16550
16551 result.then( function ( valid ) {
16552 if ( valid ) {
16553 promise.resolve();
16554 } else {
16555 promise.reject();
16556 }
16557 }, function () {
16558 promise.reject();
16559 } );
16560
16561 return promise.promise();
16562 } else {
16563 return rejectOrResolve( result );
16564 }
16565 } else {
16566 return rejectOrResolve( this.getValue().match( this.validate ) );
16567 }
16568 };
16569
16570 /**
16571 * Set the position of the inline label relative to that of the value: `‘before’` or `‘after’`.
16572 *
16573 * @param {string} labelPosition Label position, 'before' or 'after'
16574 * @chainable
16575 */
16576 OO.ui.TextInputWidget.prototype.setLabelPosition = function ( labelPosition ) {
16577 this.labelPosition = labelPosition;
16578 this.updatePosition();
16579 return this;
16580 };
16581
16582 /**
16583 * Update the position of the inline label.
16584 *
16585 * This method is called by #setLabelPosition, and can also be called on its own if
16586 * something causes the label to be mispositioned.
16587 *
16588 * @chainable
16589 */
16590 OO.ui.TextInputWidget.prototype.updatePosition = function () {
16591 var after = this.labelPosition === 'after';
16592
16593 this.$element
16594 .toggleClass( 'oo-ui-textInputWidget-labelPosition-after', !!this.label && after )
16595 .toggleClass( 'oo-ui-textInputWidget-labelPosition-before', !!this.label && !after );
16596
16597 this.valCache = null;
16598 this.scrollWidth = null;
16599 this.adjustSize();
16600 this.positionLabel();
16601
16602 return this;
16603 };
16604
16605 /**
16606 * Update the 'clear' indicator displayed on type: 'search' text fields, hiding it when the field is
16607 * already empty or when it's not editable.
16608 */
16609 OO.ui.TextInputWidget.prototype.updateSearchIndicator = function () {
16610 if ( this.type === 'search' ) {
16611 if ( this.getValue() === '' || this.isDisabled() || this.isReadOnly() ) {
16612 this.setIndicator( null );
16613 } else {
16614 this.setIndicator( 'clear' );
16615 }
16616 }
16617 };
16618
16619 /**
16620 * Position the label by setting the correct padding on the input.
16621 *
16622 * @private
16623 * @chainable
16624 */
16625 OO.ui.TextInputWidget.prototype.positionLabel = function () {
16626 var after, rtl, property;
16627 // Clear old values
16628 this.$input
16629 // Clear old values if present
16630 .css( {
16631 'padding-right': '',
16632 'padding-left': ''
16633 } );
16634
16635 if ( this.label ) {
16636 this.$element.append( this.$label );
16637 } else {
16638 this.$label.detach();
16639 return;
16640 }
16641
16642 after = this.labelPosition === 'after';
16643 rtl = this.$element.css( 'direction' ) === 'rtl';
16644 property = after === rtl ? 'padding-left' : 'padding-right';
16645
16646 this.$input.css( property, this.$label.outerWidth( true ) + ( after ? this.scrollWidth : 0 ) );
16647
16648 return this;
16649 };
16650
16651 /**
16652 * @inheritdoc
16653 */
16654 OO.ui.TextInputWidget.prototype.restorePreInfuseState = function ( state ) {
16655 OO.ui.TextInputWidget.parent.prototype.restorePreInfuseState.call( this, state );
16656 if ( state.scrollTop !== undefined ) {
16657 this.$input.scrollTop( state.scrollTop );
16658 }
16659 };
16660
16661 /**
16662 * ComboBoxInputWidgets combine a {@link OO.ui.TextInputWidget text input} (where a value
16663 * can be entered manually) and a {@link OO.ui.MenuSelectWidget menu of options} (from which
16664 * a value can be chosen instead). Users can choose options from the combo box in one of two ways:
16665 *
16666 * - by typing a value in the text input field. If the value exactly matches the value of a menu
16667 * option, that option will appear to be selected.
16668 * - by choosing a value from the menu. The value of the chosen option will then appear in the text
16669 * input field.
16670 *
16671 * This widget can be used inside a HTML form, such as a OO.ui.FormLayout.
16672 *
16673 * For more information about menus and options, please see the [OOjs UI documentation on MediaWiki][1].
16674 *
16675 * @example
16676 * // Example: A ComboBoxInputWidget.
16677 * var comboBox = new OO.ui.ComboBoxInputWidget( {
16678 * label: 'ComboBoxInputWidget',
16679 * value: 'Option 1',
16680 * menu: {
16681 * items: [
16682 * new OO.ui.MenuOptionWidget( {
16683 * data: 'Option 1',
16684 * label: 'Option One'
16685 * } ),
16686 * new OO.ui.MenuOptionWidget( {
16687 * data: 'Option 2',
16688 * label: 'Option Two'
16689 * } ),
16690 * new OO.ui.MenuOptionWidget( {
16691 * data: 'Option 3',
16692 * label: 'Option Three'
16693 * } ),
16694 * new OO.ui.MenuOptionWidget( {
16695 * data: 'Option 4',
16696 * label: 'Option Four'
16697 * } ),
16698 * new OO.ui.MenuOptionWidget( {
16699 * data: 'Option 5',
16700 * label: 'Option Five'
16701 * } )
16702 * ]
16703 * }
16704 * } );
16705 * $( 'body' ).append( comboBox.$element );
16706 *
16707 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
16708 *
16709 * @class
16710 * @extends OO.ui.TextInputWidget
16711 *
16712 * @constructor
16713 * @param {Object} [config] Configuration options
16714 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
16715 * @cfg {Object} [menu] Configuration options to pass to the {@link OO.ui.FloatingMenuSelectWidget menu select widget}.
16716 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
16717 * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
16718 * containing `<div>` and has a larger area. By default, the menu uses relative positioning.
16719 */
16720 OO.ui.ComboBoxInputWidget = function OoUiComboBoxInputWidget( config ) {
16721 // Configuration initialization
16722 config = $.extend( {
16723 indicator: 'down'
16724 }, config );
16725 // For backwards-compatibility with ComboBoxWidget config
16726 $.extend( config, config.input );
16727
16728 // Parent constructor
16729 OO.ui.ComboBoxInputWidget.parent.call( this, config );
16730
16731 // Properties
16732 this.$overlay = config.$overlay || this.$element;
16733 this.menu = new OO.ui.FloatingMenuSelectWidget( $.extend(
16734 {
16735 widget: this,
16736 input: this,
16737 $container: this.$element,
16738 disabled: this.isDisabled()
16739 },
16740 config.menu
16741 ) );
16742 // For backwards-compatibility with ComboBoxWidget
16743 this.input = this;
16744
16745 // Events
16746 this.$indicator.on( {
16747 click: this.onIndicatorClick.bind( this ),
16748 keypress: this.onIndicatorKeyPress.bind( this )
16749 } );
16750 this.connect( this, {
16751 change: 'onInputChange',
16752 enter: 'onInputEnter'
16753 } );
16754 this.menu.connect( this, {
16755 choose: 'onMenuChoose',
16756 add: 'onMenuItemsChange',
16757 remove: 'onMenuItemsChange'
16758 } );
16759
16760 // Initialization
16761 this.$input.attr( {
16762 role: 'combobox',
16763 'aria-autocomplete': 'list'
16764 } );
16765 // Do not override options set via config.menu.items
16766 if ( config.options !== undefined ) {
16767 this.setOptions( config.options );
16768 }
16769 // Extra class for backwards-compatibility with ComboBoxWidget
16770 this.$element.addClass( 'oo-ui-comboBoxInputWidget oo-ui-comboBoxWidget' );
16771 this.$overlay.append( this.menu.$element );
16772 this.onMenuItemsChange();
16773 };
16774
16775 /* Setup */
16776
16777 OO.inheritClass( OO.ui.ComboBoxInputWidget, OO.ui.TextInputWidget );
16778
16779 /* Methods */
16780
16781 /**
16782 * Get the combobox's menu.
16783 * @return {OO.ui.FloatingMenuSelectWidget} Menu widget
16784 */
16785 OO.ui.ComboBoxInputWidget.prototype.getMenu = function () {
16786 return this.menu;
16787 };
16788
16789 /**
16790 * Get the combobox's text input widget.
16791 * @return {OO.ui.TextInputWidget} Text input widget
16792 */
16793 OO.ui.ComboBoxInputWidget.prototype.getInput = function () {
16794 return this;
16795 };
16796
16797 /**
16798 * Handle input change events.
16799 *
16800 * @private
16801 * @param {string} value New value
16802 */
16803 OO.ui.ComboBoxInputWidget.prototype.onInputChange = function ( value ) {
16804 var match = this.menu.getItemFromData( value );
16805
16806 this.menu.selectItem( match );
16807 if ( this.menu.getHighlightedItem() ) {
16808 this.menu.highlightItem( match );
16809 }
16810
16811 if ( !this.isDisabled() ) {
16812 this.menu.toggle( true );
16813 }
16814 };
16815
16816 /**
16817 * Handle mouse click events.
16818 *
16819 * @private
16820 * @param {jQuery.Event} e Mouse click event
16821 */
16822 OO.ui.ComboBoxInputWidget.prototype.onIndicatorClick = function ( e ) {
16823 if ( !this.isDisabled() && e.which === OO.ui.MouseButtons.LEFT ) {
16824 this.menu.toggle();
16825 this.$input[ 0 ].focus();
16826 }
16827 return false;
16828 };
16829
16830 /**
16831 * Handle key press events.
16832 *
16833 * @private
16834 * @param {jQuery.Event} e Key press event
16835 */
16836 OO.ui.ComboBoxInputWidget.prototype.onIndicatorKeyPress = function ( e ) {
16837 if ( !this.isDisabled() && ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER ) ) {
16838 this.menu.toggle();
16839 this.$input[ 0 ].focus();
16840 return false;
16841 }
16842 };
16843
16844 /**
16845 * Handle input enter events.
16846 *
16847 * @private
16848 */
16849 OO.ui.ComboBoxInputWidget.prototype.onInputEnter = function () {
16850 if ( !this.isDisabled() ) {
16851 this.menu.toggle( false );
16852 }
16853 };
16854
16855 /**
16856 * Handle menu choose events.
16857 *
16858 * @private
16859 * @param {OO.ui.OptionWidget} item Chosen item
16860 */
16861 OO.ui.ComboBoxInputWidget.prototype.onMenuChoose = function ( item ) {
16862 this.setValue( item.getData() );
16863 };
16864
16865 /**
16866 * Handle menu item change events.
16867 *
16868 * @private
16869 */
16870 OO.ui.ComboBoxInputWidget.prototype.onMenuItemsChange = function () {
16871 var match = this.menu.getItemFromData( this.getValue() );
16872 this.menu.selectItem( match );
16873 if ( this.menu.getHighlightedItem() ) {
16874 this.menu.highlightItem( match );
16875 }
16876 this.$element.toggleClass( 'oo-ui-comboBoxInputWidget-empty', this.menu.isEmpty() );
16877 };
16878
16879 /**
16880 * @inheritdoc
16881 */
16882 OO.ui.ComboBoxInputWidget.prototype.setDisabled = function ( disabled ) {
16883 // Parent method
16884 OO.ui.ComboBoxInputWidget.parent.prototype.setDisabled.call( this, disabled );
16885
16886 if ( this.menu ) {
16887 this.menu.setDisabled( this.isDisabled() );
16888 }
16889
16890 return this;
16891 };
16892
16893 /**
16894 * Set the options available for this input.
16895 *
16896 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
16897 * @chainable
16898 */
16899 OO.ui.ComboBoxInputWidget.prototype.setOptions = function ( options ) {
16900 this.getMenu()
16901 .clearItems()
16902 .addItems( options.map( function ( opt ) {
16903 return new OO.ui.MenuOptionWidget( {
16904 data: opt.data,
16905 label: opt.label !== undefined ? opt.label : opt.data
16906 } );
16907 } ) );
16908
16909 return this;
16910 };
16911
16912 /**
16913 * @class
16914 * @deprecated Use OO.ui.ComboBoxInputWidget instead.
16915 */
16916 OO.ui.ComboBoxWidget = OO.ui.ComboBoxInputWidget;
16917
16918 /**
16919 * LabelWidgets help identify the function of interface elements. Each LabelWidget can
16920 * be configured with a `label` option that is set to a string, a label node, or a function:
16921 *
16922 * - String: a plaintext string
16923 * - jQuery selection: a jQuery selection, used for anything other than a plaintext label, e.g., a
16924 * label that includes a link or special styling, such as a gray color or additional graphical elements.
16925 * - Function: a function that will produce a string in the future. Functions are used
16926 * in cases where the value of the label is not currently defined.
16927 *
16928 * In addition, the LabelWidget can be associated with an {@link OO.ui.InputWidget input widget}, which
16929 * will come into focus when the label is clicked.
16930 *
16931 * @example
16932 * // Examples of LabelWidgets
16933 * var label1 = new OO.ui.LabelWidget( {
16934 * label: 'plaintext label'
16935 * } );
16936 * var label2 = new OO.ui.LabelWidget( {
16937 * label: $( '<a href="default.html">jQuery label</a>' )
16938 * } );
16939 * // Create a fieldset layout with fields for each example
16940 * var fieldset = new OO.ui.FieldsetLayout();
16941 * fieldset.addItems( [
16942 * new OO.ui.FieldLayout( label1 ),
16943 * new OO.ui.FieldLayout( label2 )
16944 * ] );
16945 * $( 'body' ).append( fieldset.$element );
16946 *
16947 * @class
16948 * @extends OO.ui.Widget
16949 * @mixins OO.ui.mixin.LabelElement
16950 *
16951 * @constructor
16952 * @param {Object} [config] Configuration options
16953 * @cfg {OO.ui.InputWidget} [input] {@link OO.ui.InputWidget Input widget} that uses the label.
16954 * Clicking the label will focus the specified input field.
16955 */
16956 OO.ui.LabelWidget = function OoUiLabelWidget( config ) {
16957 // Configuration initialization
16958 config = config || {};
16959
16960 // Parent constructor
16961 OO.ui.LabelWidget.parent.call( this, config );
16962
16963 // Mixin constructors
16964 OO.ui.mixin.LabelElement.call( this, $.extend( {}, config, { $label: this.$element } ) );
16965 OO.ui.mixin.TitledElement.call( this, config );
16966
16967 // Properties
16968 this.input = config.input;
16969
16970 // Events
16971 if ( this.input instanceof OO.ui.InputWidget ) {
16972 this.$element.on( 'click', this.onClick.bind( this ) );
16973 }
16974
16975 // Initialization
16976 this.$element.addClass( 'oo-ui-labelWidget' );
16977 };
16978
16979 /* Setup */
16980
16981 OO.inheritClass( OO.ui.LabelWidget, OO.ui.Widget );
16982 OO.mixinClass( OO.ui.LabelWidget, OO.ui.mixin.LabelElement );
16983 OO.mixinClass( OO.ui.LabelWidget, OO.ui.mixin.TitledElement );
16984
16985 /* Static Properties */
16986
16987 OO.ui.LabelWidget.static.tagName = 'span';
16988
16989 /* Methods */
16990
16991 /**
16992 * Handles label mouse click events.
16993 *
16994 * @private
16995 * @param {jQuery.Event} e Mouse click event
16996 */
16997 OO.ui.LabelWidget.prototype.onClick = function () {
16998 this.input.simulateLabelClick();
16999 return false;
17000 };
17001
17002 /**
17003 * OptionWidgets are special elements that can be selected and configured with data. The
17004 * data is often unique for each option, but it does not have to be. OptionWidgets are used
17005 * with OO.ui.SelectWidget to create a selection of mutually exclusive options. For more information
17006 * and examples, please see the [OOjs UI documentation on MediaWiki][1].
17007 *
17008 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
17009 *
17010 * @class
17011 * @extends OO.ui.Widget
17012 * @mixins OO.ui.mixin.LabelElement
17013 * @mixins OO.ui.mixin.FlaggedElement
17014 *
17015 * @constructor
17016 * @param {Object} [config] Configuration options
17017 */
17018 OO.ui.OptionWidget = function OoUiOptionWidget( config ) {
17019 // Configuration initialization
17020 config = config || {};
17021
17022 // Parent constructor
17023 OO.ui.OptionWidget.parent.call( this, config );
17024
17025 // Mixin constructors
17026 OO.ui.mixin.ItemWidget.call( this );
17027 OO.ui.mixin.LabelElement.call( this, config );
17028 OO.ui.mixin.FlaggedElement.call( this, config );
17029
17030 // Properties
17031 this.selected = false;
17032 this.highlighted = false;
17033 this.pressed = false;
17034
17035 // Initialization
17036 this.$element
17037 .data( 'oo-ui-optionWidget', this )
17038 .attr( 'role', 'option' )
17039 .attr( 'aria-selected', 'false' )
17040 .addClass( 'oo-ui-optionWidget' )
17041 .append( this.$label );
17042 };
17043
17044 /* Setup */
17045
17046 OO.inheritClass( OO.ui.OptionWidget, OO.ui.Widget );
17047 OO.mixinClass( OO.ui.OptionWidget, OO.ui.mixin.ItemWidget );
17048 OO.mixinClass( OO.ui.OptionWidget, OO.ui.mixin.LabelElement );
17049 OO.mixinClass( OO.ui.OptionWidget, OO.ui.mixin.FlaggedElement );
17050
17051 /* Static Properties */
17052
17053 OO.ui.OptionWidget.static.selectable = true;
17054
17055 OO.ui.OptionWidget.static.highlightable = true;
17056
17057 OO.ui.OptionWidget.static.pressable = true;
17058
17059 OO.ui.OptionWidget.static.scrollIntoViewOnSelect = false;
17060
17061 /* Methods */
17062
17063 /**
17064 * Check if the option can be selected.
17065 *
17066 * @return {boolean} Item is selectable
17067 */
17068 OO.ui.OptionWidget.prototype.isSelectable = function () {
17069 return this.constructor.static.selectable && !this.isDisabled() && this.isVisible();
17070 };
17071
17072 /**
17073 * Check if the option can be highlighted. A highlight indicates that the option
17074 * may be selected when a user presses enter or clicks. Disabled items cannot
17075 * be highlighted.
17076 *
17077 * @return {boolean} Item is highlightable
17078 */
17079 OO.ui.OptionWidget.prototype.isHighlightable = function () {
17080 return this.constructor.static.highlightable && !this.isDisabled() && this.isVisible();
17081 };
17082
17083 /**
17084 * Check if the option can be pressed. The pressed state occurs when a user mouses
17085 * down on an item, but has not yet let go of the mouse.
17086 *
17087 * @return {boolean} Item is pressable
17088 */
17089 OO.ui.OptionWidget.prototype.isPressable = function () {
17090 return this.constructor.static.pressable && !this.isDisabled() && this.isVisible();
17091 };
17092
17093 /**
17094 * Check if the option is selected.
17095 *
17096 * @return {boolean} Item is selected
17097 */
17098 OO.ui.OptionWidget.prototype.isSelected = function () {
17099 return this.selected;
17100 };
17101
17102 /**
17103 * Check if the option is highlighted. A highlight indicates that the
17104 * item may be selected when a user presses enter or clicks.
17105 *
17106 * @return {boolean} Item is highlighted
17107 */
17108 OO.ui.OptionWidget.prototype.isHighlighted = function () {
17109 return this.highlighted;
17110 };
17111
17112 /**
17113 * Check if the option is pressed. The pressed state occurs when a user mouses
17114 * down on an item, but has not yet let go of the mouse. The item may appear
17115 * selected, but it will not be selected until the user releases the mouse.
17116 *
17117 * @return {boolean} Item is pressed
17118 */
17119 OO.ui.OptionWidget.prototype.isPressed = function () {
17120 return this.pressed;
17121 };
17122
17123 /**
17124 * Set the option’s selected state. In general, all modifications to the selection
17125 * should be handled by the SelectWidget’s {@link OO.ui.SelectWidget#selectItem selectItem( [item] )}
17126 * method instead of this method.
17127 *
17128 * @param {boolean} [state=false] Select option
17129 * @chainable
17130 */
17131 OO.ui.OptionWidget.prototype.setSelected = function ( state ) {
17132 if ( this.constructor.static.selectable ) {
17133 this.selected = !!state;
17134 this.$element
17135 .toggleClass( 'oo-ui-optionWidget-selected', state )
17136 .attr( 'aria-selected', state.toString() );
17137 if ( state && this.constructor.static.scrollIntoViewOnSelect ) {
17138 this.scrollElementIntoView();
17139 }
17140 this.updateThemeClasses();
17141 }
17142 return this;
17143 };
17144
17145 /**
17146 * Set the option’s highlighted state. In general, all programmatic
17147 * modifications to the highlight should be handled by the
17148 * SelectWidget’s {@link OO.ui.SelectWidget#highlightItem highlightItem( [item] )}
17149 * method instead of this method.
17150 *
17151 * @param {boolean} [state=false] Highlight option
17152 * @chainable
17153 */
17154 OO.ui.OptionWidget.prototype.setHighlighted = function ( state ) {
17155 if ( this.constructor.static.highlightable ) {
17156 this.highlighted = !!state;
17157 this.$element.toggleClass( 'oo-ui-optionWidget-highlighted', state );
17158 this.updateThemeClasses();
17159 }
17160 return this;
17161 };
17162
17163 /**
17164 * Set the option’s pressed state. In general, all
17165 * programmatic modifications to the pressed state should be handled by the
17166 * SelectWidget’s {@link OO.ui.SelectWidget#pressItem pressItem( [item] )}
17167 * method instead of this method.
17168 *
17169 * @param {boolean} [state=false] Press option
17170 * @chainable
17171 */
17172 OO.ui.OptionWidget.prototype.setPressed = function ( state ) {
17173 if ( this.constructor.static.pressable ) {
17174 this.pressed = !!state;
17175 this.$element.toggleClass( 'oo-ui-optionWidget-pressed', state );
17176 this.updateThemeClasses();
17177 }
17178 return this;
17179 };
17180
17181 /**
17182 * DecoratedOptionWidgets are {@link OO.ui.OptionWidget options} that can be configured
17183 * with an {@link OO.ui.mixin.IconElement icon} and/or {@link OO.ui.mixin.IndicatorElement indicator}.
17184 * This class is used with OO.ui.SelectWidget to create a selection of mutually exclusive
17185 * options. For more information about options and selects, please see the
17186 * [OOjs UI documentation on MediaWiki][1].
17187 *
17188 * @example
17189 * // Decorated options in a select widget
17190 * var select = new OO.ui.SelectWidget( {
17191 * items: [
17192 * new OO.ui.DecoratedOptionWidget( {
17193 * data: 'a',
17194 * label: 'Option with icon',
17195 * icon: 'help'
17196 * } ),
17197 * new OO.ui.DecoratedOptionWidget( {
17198 * data: 'b',
17199 * label: 'Option with indicator',
17200 * indicator: 'next'
17201 * } )
17202 * ]
17203 * } );
17204 * $( 'body' ).append( select.$element );
17205 *
17206 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
17207 *
17208 * @class
17209 * @extends OO.ui.OptionWidget
17210 * @mixins OO.ui.mixin.IconElement
17211 * @mixins OO.ui.mixin.IndicatorElement
17212 *
17213 * @constructor
17214 * @param {Object} [config] Configuration options
17215 */
17216 OO.ui.DecoratedOptionWidget = function OoUiDecoratedOptionWidget( config ) {
17217 // Parent constructor
17218 OO.ui.DecoratedOptionWidget.parent.call( this, config );
17219
17220 // Mixin constructors
17221 OO.ui.mixin.IconElement.call( this, config );
17222 OO.ui.mixin.IndicatorElement.call( this, config );
17223
17224 // Initialization
17225 this.$element
17226 .addClass( 'oo-ui-decoratedOptionWidget' )
17227 .prepend( this.$icon )
17228 .append( this.$indicator );
17229 };
17230
17231 /* Setup */
17232
17233 OO.inheritClass( OO.ui.DecoratedOptionWidget, OO.ui.OptionWidget );
17234 OO.mixinClass( OO.ui.DecoratedOptionWidget, OO.ui.mixin.IconElement );
17235 OO.mixinClass( OO.ui.DecoratedOptionWidget, OO.ui.mixin.IndicatorElement );
17236
17237 /**
17238 * ButtonOptionWidget is a special type of {@link OO.ui.mixin.ButtonElement button element} that
17239 * can be selected and configured with data. The class is
17240 * used with OO.ui.ButtonSelectWidget to create a selection of button options. Please see the
17241 * [OOjs UI documentation on MediaWiki] [1] for more information.
17242 *
17243 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Button_selects_and_options
17244 *
17245 * @class
17246 * @extends OO.ui.DecoratedOptionWidget
17247 * @mixins OO.ui.mixin.ButtonElement
17248 * @mixins OO.ui.mixin.TabIndexedElement
17249 * @mixins OO.ui.mixin.TitledElement
17250 *
17251 * @constructor
17252 * @param {Object} [config] Configuration options
17253 */
17254 OO.ui.ButtonOptionWidget = function OoUiButtonOptionWidget( config ) {
17255 // Configuration initialization
17256 config = config || {};
17257
17258 // Parent constructor
17259 OO.ui.ButtonOptionWidget.parent.call( this, config );
17260
17261 // Mixin constructors
17262 OO.ui.mixin.ButtonElement.call( this, config );
17263 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$button } ) );
17264 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, {
17265 $tabIndexed: this.$button,
17266 tabIndex: -1
17267 } ) );
17268
17269 // Initialization
17270 this.$element.addClass( 'oo-ui-buttonOptionWidget' );
17271 this.$button.append( this.$element.contents() );
17272 this.$element.append( this.$button );
17273 };
17274
17275 /* Setup */
17276
17277 OO.inheritClass( OO.ui.ButtonOptionWidget, OO.ui.DecoratedOptionWidget );
17278 OO.mixinClass( OO.ui.ButtonOptionWidget, OO.ui.mixin.ButtonElement );
17279 OO.mixinClass( OO.ui.ButtonOptionWidget, OO.ui.mixin.TitledElement );
17280 OO.mixinClass( OO.ui.ButtonOptionWidget, OO.ui.mixin.TabIndexedElement );
17281
17282 /* Static Properties */
17283
17284 // Allow button mouse down events to pass through so they can be handled by the parent select widget
17285 OO.ui.ButtonOptionWidget.static.cancelButtonMouseDownEvents = false;
17286
17287 OO.ui.ButtonOptionWidget.static.highlightable = false;
17288
17289 /* Methods */
17290
17291 /**
17292 * @inheritdoc
17293 */
17294 OO.ui.ButtonOptionWidget.prototype.setSelected = function ( state ) {
17295 OO.ui.ButtonOptionWidget.parent.prototype.setSelected.call( this, state );
17296
17297 if ( this.constructor.static.selectable ) {
17298 this.setActive( state );
17299 }
17300
17301 return this;
17302 };
17303
17304 /**
17305 * RadioOptionWidget is an option widget that looks like a radio button.
17306 * The class is used with OO.ui.RadioSelectWidget to create a selection of radio options.
17307 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information.
17308 *
17309 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Button_selects_and_option
17310 *
17311 * @class
17312 * @extends OO.ui.OptionWidget
17313 *
17314 * @constructor
17315 * @param {Object} [config] Configuration options
17316 */
17317 OO.ui.RadioOptionWidget = function OoUiRadioOptionWidget( config ) {
17318 // Configuration initialization
17319 config = config || {};
17320
17321 // Properties (must be done before parent constructor which calls #setDisabled)
17322 this.radio = new OO.ui.RadioInputWidget( { value: config.data, tabIndex: -1 } );
17323
17324 // Parent constructor
17325 OO.ui.RadioOptionWidget.parent.call( this, config );
17326
17327 // Events
17328 this.radio.$input.on( 'focus', this.onInputFocus.bind( this ) );
17329
17330 // Initialization
17331 // Remove implicit role, we're handling it ourselves
17332 this.radio.$input.attr( 'role', 'presentation' );
17333 this.$element
17334 .addClass( 'oo-ui-radioOptionWidget' )
17335 .attr( 'role', 'radio' )
17336 .attr( 'aria-checked', 'false' )
17337 .removeAttr( 'aria-selected' )
17338 .prepend( this.radio.$element );
17339 };
17340
17341 /* Setup */
17342
17343 OO.inheritClass( OO.ui.RadioOptionWidget, OO.ui.OptionWidget );
17344
17345 /* Static Properties */
17346
17347 OO.ui.RadioOptionWidget.static.highlightable = false;
17348
17349 OO.ui.RadioOptionWidget.static.scrollIntoViewOnSelect = true;
17350
17351 OO.ui.RadioOptionWidget.static.pressable = false;
17352
17353 OO.ui.RadioOptionWidget.static.tagName = 'label';
17354
17355 /* Methods */
17356
17357 /**
17358 * @param {jQuery.Event} e Focus event
17359 * @private
17360 */
17361 OO.ui.RadioOptionWidget.prototype.onInputFocus = function () {
17362 this.radio.$input.blur();
17363 this.$element.parent().focus();
17364 };
17365
17366 /**
17367 * @inheritdoc
17368 */
17369 OO.ui.RadioOptionWidget.prototype.setSelected = function ( state ) {
17370 OO.ui.RadioOptionWidget.parent.prototype.setSelected.call( this, state );
17371
17372 this.radio.setSelected( state );
17373 this.$element
17374 .attr( 'aria-checked', state.toString() )
17375 .removeAttr( 'aria-selected' );
17376
17377 return this;
17378 };
17379
17380 /**
17381 * @inheritdoc
17382 */
17383 OO.ui.RadioOptionWidget.prototype.setDisabled = function ( disabled ) {
17384 OO.ui.RadioOptionWidget.parent.prototype.setDisabled.call( this, disabled );
17385
17386 this.radio.setDisabled( this.isDisabled() );
17387
17388 return this;
17389 };
17390
17391 /**
17392 * MenuOptionWidget is an option widget that looks like a menu item. The class is used with
17393 * OO.ui.MenuSelectWidget to create a menu of mutually exclusive options. Please see
17394 * the [OOjs UI documentation on MediaWiki] [1] for more information.
17395 *
17396 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
17397 *
17398 * @class
17399 * @extends OO.ui.DecoratedOptionWidget
17400 *
17401 * @constructor
17402 * @param {Object} [config] Configuration options
17403 */
17404 OO.ui.MenuOptionWidget = function OoUiMenuOptionWidget( config ) {
17405 // Configuration initialization
17406 config = $.extend( { icon: 'check' }, config );
17407
17408 // Parent constructor
17409 OO.ui.MenuOptionWidget.parent.call( this, config );
17410
17411 // Initialization
17412 this.$element
17413 .attr( 'role', 'menuitem' )
17414 .addClass( 'oo-ui-menuOptionWidget' );
17415 };
17416
17417 /* Setup */
17418
17419 OO.inheritClass( OO.ui.MenuOptionWidget, OO.ui.DecoratedOptionWidget );
17420
17421 /* Static Properties */
17422
17423 OO.ui.MenuOptionWidget.static.scrollIntoViewOnSelect = true;
17424
17425 /**
17426 * MenuSectionOptionWidgets are used inside {@link OO.ui.MenuSelectWidget menu select widgets} to group one or more related
17427 * {@link OO.ui.MenuOptionWidget menu options}. MenuSectionOptionWidgets cannot be highlighted or selected.
17428 *
17429 * @example
17430 * var myDropdown = new OO.ui.DropdownWidget( {
17431 * menu: {
17432 * items: [
17433 * new OO.ui.MenuSectionOptionWidget( {
17434 * label: 'Dogs'
17435 * } ),
17436 * new OO.ui.MenuOptionWidget( {
17437 * data: 'corgi',
17438 * label: 'Welsh Corgi'
17439 * } ),
17440 * new OO.ui.MenuOptionWidget( {
17441 * data: 'poodle',
17442 * label: 'Standard Poodle'
17443 * } ),
17444 * new OO.ui.MenuSectionOptionWidget( {
17445 * label: 'Cats'
17446 * } ),
17447 * new OO.ui.MenuOptionWidget( {
17448 * data: 'lion',
17449 * label: 'Lion'
17450 * } )
17451 * ]
17452 * }
17453 * } );
17454 * $( 'body' ).append( myDropdown.$element );
17455 *
17456 * @class
17457 * @extends OO.ui.DecoratedOptionWidget
17458 *
17459 * @constructor
17460 * @param {Object} [config] Configuration options
17461 */
17462 OO.ui.MenuSectionOptionWidget = function OoUiMenuSectionOptionWidget( config ) {
17463 // Parent constructor
17464 OO.ui.MenuSectionOptionWidget.parent.call( this, config );
17465
17466 // Initialization
17467 this.$element.addClass( 'oo-ui-menuSectionOptionWidget' );
17468 };
17469
17470 /* Setup */
17471
17472 OO.inheritClass( OO.ui.MenuSectionOptionWidget, OO.ui.DecoratedOptionWidget );
17473
17474 /* Static Properties */
17475
17476 OO.ui.MenuSectionOptionWidget.static.selectable = false;
17477
17478 OO.ui.MenuSectionOptionWidget.static.highlightable = false;
17479
17480 /**
17481 * OutlineOptionWidget is an item in an {@link OO.ui.OutlineSelectWidget OutlineSelectWidget}.
17482 *
17483 * Currently, this class is only used by {@link OO.ui.BookletLayout booklet layouts}, which contain
17484 * {@link OO.ui.PageLayout page layouts}. See {@link OO.ui.BookletLayout BookletLayout}
17485 * for an example.
17486 *
17487 * @class
17488 * @extends OO.ui.DecoratedOptionWidget
17489 *
17490 * @constructor
17491 * @param {Object} [config] Configuration options
17492 * @cfg {number} [level] Indentation level
17493 * @cfg {boolean} [movable] Allow modification from {@link OO.ui.OutlineControlsWidget outline controls}.
17494 */
17495 OO.ui.OutlineOptionWidget = function OoUiOutlineOptionWidget( config ) {
17496 // Configuration initialization
17497 config = config || {};
17498
17499 // Parent constructor
17500 OO.ui.OutlineOptionWidget.parent.call( this, config );
17501
17502 // Properties
17503 this.level = 0;
17504 this.movable = !!config.movable;
17505 this.removable = !!config.removable;
17506
17507 // Initialization
17508 this.$element.addClass( 'oo-ui-outlineOptionWidget' );
17509 this.setLevel( config.level );
17510 };
17511
17512 /* Setup */
17513
17514 OO.inheritClass( OO.ui.OutlineOptionWidget, OO.ui.DecoratedOptionWidget );
17515
17516 /* Static Properties */
17517
17518 OO.ui.OutlineOptionWidget.static.highlightable = false;
17519
17520 OO.ui.OutlineOptionWidget.static.scrollIntoViewOnSelect = true;
17521
17522 OO.ui.OutlineOptionWidget.static.levelClass = 'oo-ui-outlineOptionWidget-level-';
17523
17524 OO.ui.OutlineOptionWidget.static.levels = 3;
17525
17526 /* Methods */
17527
17528 /**
17529 * Check if item is movable.
17530 *
17531 * Movability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
17532 *
17533 * @return {boolean} Item is movable
17534 */
17535 OO.ui.OutlineOptionWidget.prototype.isMovable = function () {
17536 return this.movable;
17537 };
17538
17539 /**
17540 * Check if item is removable.
17541 *
17542 * Removability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
17543 *
17544 * @return {boolean} Item is removable
17545 */
17546 OO.ui.OutlineOptionWidget.prototype.isRemovable = function () {
17547 return this.removable;
17548 };
17549
17550 /**
17551 * Get indentation level.
17552 *
17553 * @return {number} Indentation level
17554 */
17555 OO.ui.OutlineOptionWidget.prototype.getLevel = function () {
17556 return this.level;
17557 };
17558
17559 /**
17560 * Set movability.
17561 *
17562 * Movability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
17563 *
17564 * @param {boolean} movable Item is movable
17565 * @chainable
17566 */
17567 OO.ui.OutlineOptionWidget.prototype.setMovable = function ( movable ) {
17568 this.movable = !!movable;
17569 this.updateThemeClasses();
17570 return this;
17571 };
17572
17573 /**
17574 * Set removability.
17575 *
17576 * Removability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
17577 *
17578 * @param {boolean} removable Item is removable
17579 * @chainable
17580 */
17581 OO.ui.OutlineOptionWidget.prototype.setRemovable = function ( removable ) {
17582 this.removable = !!removable;
17583 this.updateThemeClasses();
17584 return this;
17585 };
17586
17587 /**
17588 * Set indentation level.
17589 *
17590 * @param {number} [level=0] Indentation level, in the range of [0,#maxLevel]
17591 * @chainable
17592 */
17593 OO.ui.OutlineOptionWidget.prototype.setLevel = function ( level ) {
17594 var levels = this.constructor.static.levels,
17595 levelClass = this.constructor.static.levelClass,
17596 i = levels;
17597
17598 this.level = level ? Math.max( 0, Math.min( levels - 1, level ) ) : 0;
17599 while ( i-- ) {
17600 if ( this.level === i ) {
17601 this.$element.addClass( levelClass + i );
17602 } else {
17603 this.$element.removeClass( levelClass + i );
17604 }
17605 }
17606 this.updateThemeClasses();
17607
17608 return this;
17609 };
17610
17611 /**
17612 * TabOptionWidget is an item in a {@link OO.ui.TabSelectWidget TabSelectWidget}.
17613 *
17614 * Currently, this class is only used by {@link OO.ui.IndexLayout index layouts}, which contain
17615 * {@link OO.ui.CardLayout card layouts}. See {@link OO.ui.IndexLayout IndexLayout}
17616 * for an example.
17617 *
17618 * @class
17619 * @extends OO.ui.OptionWidget
17620 *
17621 * @constructor
17622 * @param {Object} [config] Configuration options
17623 */
17624 OO.ui.TabOptionWidget = function OoUiTabOptionWidget( config ) {
17625 // Configuration initialization
17626 config = config || {};
17627
17628 // Parent constructor
17629 OO.ui.TabOptionWidget.parent.call( this, config );
17630
17631 // Initialization
17632 this.$element.addClass( 'oo-ui-tabOptionWidget' );
17633 };
17634
17635 /* Setup */
17636
17637 OO.inheritClass( OO.ui.TabOptionWidget, OO.ui.OptionWidget );
17638
17639 /* Static Properties */
17640
17641 OO.ui.TabOptionWidget.static.highlightable = false;
17642
17643 /**
17644 * PopupWidget is a container for content. The popup is overlaid and positioned absolutely.
17645 * By default, each popup has an anchor that points toward its origin.
17646 * Please see the [OOjs UI documentation on Mediawiki] [1] for more information and examples.
17647 *
17648 * @example
17649 * // A popup widget.
17650 * var popup = new OO.ui.PopupWidget( {
17651 * $content: $( '<p>Hi there!</p>' ),
17652 * padded: true,
17653 * width: 300
17654 * } );
17655 *
17656 * $( 'body' ).append( popup.$element );
17657 * // To display the popup, toggle the visibility to 'true'.
17658 * popup.toggle( true );
17659 *
17660 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups
17661 *
17662 * @class
17663 * @extends OO.ui.Widget
17664 * @mixins OO.ui.mixin.LabelElement
17665 * @mixins OO.ui.mixin.ClippableElement
17666 *
17667 * @constructor
17668 * @param {Object} [config] Configuration options
17669 * @cfg {number} [width=320] Width of popup in pixels
17670 * @cfg {number} [height] Height of popup in pixels. Omit to use the automatic height.
17671 * @cfg {boolean} [anchor=true] Show anchor pointing to origin of popup
17672 * @cfg {string} [align='center'] Alignment of the popup: `center`, `force-left`, `force-right`, `backwards` or `forwards`.
17673 * If the popup is forced-left the popup body is leaning towards the left. For force-right alignment, the body of the
17674 * popup is leaning towards the right of the screen.
17675 * Using 'backwards' is a logical direction which will result in the popup leaning towards the beginning of the sentence
17676 * in the given language, which means it will flip to the correct positioning in right-to-left languages.
17677 * Using 'forward' will also result in a logical alignment where the body of the popup leans towards the end of the
17678 * sentence in the given language.
17679 * @cfg {jQuery} [$container] Constrain the popup to the boundaries of the specified container.
17680 * See the [OOjs UI docs on MediaWiki][3] for an example.
17681 * [3]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups#containerExample
17682 * @cfg {number} [containerPadding=10] Padding between the popup and its container, specified as a number of pixels.
17683 * @cfg {jQuery} [$content] Content to append to the popup's body
17684 * @cfg {jQuery} [$footer] Content to append to the popup's footer
17685 * @cfg {boolean} [autoClose=false] Automatically close the popup when it loses focus.
17686 * @cfg {jQuery} [$autoCloseIgnore] Elements that will not close the popup when clicked.
17687 * This config option is only relevant if #autoClose is set to `true`. See the [OOjs UI docs on MediaWiki][2]
17688 * for an example.
17689 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups#autocloseExample
17690 * @cfg {boolean} [head] Show a popup header that contains a #label (if specified) and close
17691 * button.
17692 * @cfg {boolean} [padded] Add padding to the popup's body
17693 */
17694 OO.ui.PopupWidget = function OoUiPopupWidget( config ) {
17695 // Configuration initialization
17696 config = config || {};
17697
17698 // Parent constructor
17699 OO.ui.PopupWidget.parent.call( this, config );
17700
17701 // Properties (must be set before ClippableElement constructor call)
17702 this.$body = $( '<div>' );
17703 this.$popup = $( '<div>' );
17704
17705 // Mixin constructors
17706 OO.ui.mixin.LabelElement.call( this, config );
17707 OO.ui.mixin.ClippableElement.call( this, $.extend( {}, config, {
17708 $clippable: this.$body,
17709 $clippableContainer: this.$popup
17710 } ) );
17711
17712 // Properties
17713 this.$head = $( '<div>' );
17714 this.$footer = $( '<div>' );
17715 this.$anchor = $( '<div>' );
17716 // If undefined, will be computed lazily in updateDimensions()
17717 this.$container = config.$container;
17718 this.containerPadding = config.containerPadding !== undefined ? config.containerPadding : 10;
17719 this.autoClose = !!config.autoClose;
17720 this.$autoCloseIgnore = config.$autoCloseIgnore;
17721 this.transitionTimeout = null;
17722 this.anchor = null;
17723 this.width = config.width !== undefined ? config.width : 320;
17724 this.height = config.height !== undefined ? config.height : null;
17725 this.setAlignment( config.align );
17726 this.closeButton = new OO.ui.ButtonWidget( { framed: false, icon: 'close' } );
17727 this.onMouseDownHandler = this.onMouseDown.bind( this );
17728 this.onDocumentKeyDownHandler = this.onDocumentKeyDown.bind( this );
17729
17730 // Events
17731 this.closeButton.connect( this, { click: 'onCloseButtonClick' } );
17732
17733 // Initialization
17734 this.toggleAnchor( config.anchor === undefined || config.anchor );
17735 this.$body.addClass( 'oo-ui-popupWidget-body' );
17736 this.$anchor.addClass( 'oo-ui-popupWidget-anchor' );
17737 this.$head
17738 .addClass( 'oo-ui-popupWidget-head' )
17739 .append( this.$label, this.closeButton.$element );
17740 this.$footer.addClass( 'oo-ui-popupWidget-footer' );
17741 if ( !config.head ) {
17742 this.$head.addClass( 'oo-ui-element-hidden' );
17743 }
17744 if ( !config.$footer ) {
17745 this.$footer.addClass( 'oo-ui-element-hidden' );
17746 }
17747 this.$popup
17748 .addClass( 'oo-ui-popupWidget-popup' )
17749 .append( this.$head, this.$body, this.$footer );
17750 this.$element
17751 .addClass( 'oo-ui-popupWidget' )
17752 .append( this.$popup, this.$anchor );
17753 // Move content, which was added to #$element by OO.ui.Widget, to the body
17754 if ( config.$content instanceof jQuery ) {
17755 this.$body.append( config.$content );
17756 }
17757 if ( config.$footer instanceof jQuery ) {
17758 this.$footer.append( config.$footer );
17759 }
17760 if ( config.padded ) {
17761 this.$body.addClass( 'oo-ui-popupWidget-body-padded' );
17762 }
17763
17764 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
17765 // that reference properties not initialized at that time of parent class construction
17766 // TODO: Find a better way to handle post-constructor setup
17767 this.visible = false;
17768 this.$element.addClass( 'oo-ui-element-hidden' );
17769 };
17770
17771 /* Setup */
17772
17773 OO.inheritClass( OO.ui.PopupWidget, OO.ui.Widget );
17774 OO.mixinClass( OO.ui.PopupWidget, OO.ui.mixin.LabelElement );
17775 OO.mixinClass( OO.ui.PopupWidget, OO.ui.mixin.ClippableElement );
17776
17777 /* Methods */
17778
17779 /**
17780 * Handles mouse down events.
17781 *
17782 * @private
17783 * @param {MouseEvent} e Mouse down event
17784 */
17785 OO.ui.PopupWidget.prototype.onMouseDown = function ( e ) {
17786 if (
17787 this.isVisible() &&
17788 !$.contains( this.$element[ 0 ], e.target ) &&
17789 ( !this.$autoCloseIgnore || !this.$autoCloseIgnore.has( e.target ).length )
17790 ) {
17791 this.toggle( false );
17792 }
17793 };
17794
17795 /**
17796 * Bind mouse down listener.
17797 *
17798 * @private
17799 */
17800 OO.ui.PopupWidget.prototype.bindMouseDownListener = function () {
17801 // Capture clicks outside popup
17802 this.getElementWindow().addEventListener( 'mousedown', this.onMouseDownHandler, true );
17803 };
17804
17805 /**
17806 * Handles close button click events.
17807 *
17808 * @private
17809 */
17810 OO.ui.PopupWidget.prototype.onCloseButtonClick = function () {
17811 if ( this.isVisible() ) {
17812 this.toggle( false );
17813 }
17814 };
17815
17816 /**
17817 * Unbind mouse down listener.
17818 *
17819 * @private
17820 */
17821 OO.ui.PopupWidget.prototype.unbindMouseDownListener = function () {
17822 this.getElementWindow().removeEventListener( 'mousedown', this.onMouseDownHandler, true );
17823 };
17824
17825 /**
17826 * Handles key down events.
17827 *
17828 * @private
17829 * @param {KeyboardEvent} e Key down event
17830 */
17831 OO.ui.PopupWidget.prototype.onDocumentKeyDown = function ( e ) {
17832 if (
17833 e.which === OO.ui.Keys.ESCAPE &&
17834 this.isVisible()
17835 ) {
17836 this.toggle( false );
17837 e.preventDefault();
17838 e.stopPropagation();
17839 }
17840 };
17841
17842 /**
17843 * Bind key down listener.
17844 *
17845 * @private
17846 */
17847 OO.ui.PopupWidget.prototype.bindKeyDownListener = function () {
17848 this.getElementWindow().addEventListener( 'keydown', this.onDocumentKeyDownHandler, true );
17849 };
17850
17851 /**
17852 * Unbind key down listener.
17853 *
17854 * @private
17855 */
17856 OO.ui.PopupWidget.prototype.unbindKeyDownListener = function () {
17857 this.getElementWindow().removeEventListener( 'keydown', this.onDocumentKeyDownHandler, true );
17858 };
17859
17860 /**
17861 * Show, hide, or toggle the visibility of the anchor.
17862 *
17863 * @param {boolean} [show] Show anchor, omit to toggle
17864 */
17865 OO.ui.PopupWidget.prototype.toggleAnchor = function ( show ) {
17866 show = show === undefined ? !this.anchored : !!show;
17867
17868 if ( this.anchored !== show ) {
17869 if ( show ) {
17870 this.$element.addClass( 'oo-ui-popupWidget-anchored' );
17871 } else {
17872 this.$element.removeClass( 'oo-ui-popupWidget-anchored' );
17873 }
17874 this.anchored = show;
17875 }
17876 };
17877
17878 /**
17879 * Check if the anchor is visible.
17880 *
17881 * @return {boolean} Anchor is visible
17882 */
17883 OO.ui.PopupWidget.prototype.hasAnchor = function () {
17884 return this.anchor;
17885 };
17886
17887 /**
17888 * @inheritdoc
17889 */
17890 OO.ui.PopupWidget.prototype.toggle = function ( show ) {
17891 var change;
17892 show = show === undefined ? !this.isVisible() : !!show;
17893
17894 change = show !== this.isVisible();
17895
17896 // Parent method
17897 OO.ui.PopupWidget.parent.prototype.toggle.call( this, show );
17898
17899 if ( change ) {
17900 if ( show ) {
17901 if ( this.autoClose ) {
17902 this.bindMouseDownListener();
17903 this.bindKeyDownListener();
17904 }
17905 this.updateDimensions();
17906 this.toggleClipping( true );
17907 } else {
17908 this.toggleClipping( false );
17909 if ( this.autoClose ) {
17910 this.unbindMouseDownListener();
17911 this.unbindKeyDownListener();
17912 }
17913 }
17914 }
17915
17916 return this;
17917 };
17918
17919 /**
17920 * Set the size of the popup.
17921 *
17922 * Changing the size may also change the popup's position depending on the alignment.
17923 *
17924 * @param {number} width Width in pixels
17925 * @param {number} height Height in pixels
17926 * @param {boolean} [transition=false] Use a smooth transition
17927 * @chainable
17928 */
17929 OO.ui.PopupWidget.prototype.setSize = function ( width, height, transition ) {
17930 this.width = width;
17931 this.height = height !== undefined ? height : null;
17932 if ( this.isVisible() ) {
17933 this.updateDimensions( transition );
17934 }
17935 };
17936
17937 /**
17938 * Update the size and position.
17939 *
17940 * Only use this to keep the popup properly anchored. Use #setSize to change the size, and this will
17941 * be called automatically.
17942 *
17943 * @param {boolean} [transition=false] Use a smooth transition
17944 * @chainable
17945 */
17946 OO.ui.PopupWidget.prototype.updateDimensions = function ( transition ) {
17947 var popupOffset, originOffset, containerLeft, containerWidth, containerRight,
17948 popupLeft, popupRight, overlapLeft, overlapRight, anchorWidth,
17949 align = this.align,
17950 widget = this;
17951
17952 if ( !this.$container ) {
17953 // Lazy-initialize $container if not specified in constructor
17954 this.$container = $( this.getClosestScrollableElementContainer() );
17955 }
17956
17957 // Set height and width before measuring things, since it might cause our measurements
17958 // to change (e.g. due to scrollbars appearing or disappearing)
17959 this.$popup.css( {
17960 width: this.width,
17961 height: this.height !== null ? this.height : 'auto'
17962 } );
17963
17964 // If we are in RTL, we need to flip the alignment, unless it is center
17965 if ( align === 'forwards' || align === 'backwards' ) {
17966 if ( this.$container.css( 'direction' ) === 'rtl' ) {
17967 align = ( { forwards: 'force-left', backwards: 'force-right' } )[ this.align ];
17968 } else {
17969 align = ( { forwards: 'force-right', backwards: 'force-left' } )[ this.align ];
17970 }
17971
17972 }
17973
17974 // Compute initial popupOffset based on alignment
17975 popupOffset = this.width * ( { 'force-left': -1, center: -0.5, 'force-right': 0 } )[ align ];
17976
17977 // Figure out if this will cause the popup to go beyond the edge of the container
17978 originOffset = this.$element.offset().left;
17979 containerLeft = this.$container.offset().left;
17980 containerWidth = this.$container.innerWidth();
17981 containerRight = containerLeft + containerWidth;
17982 popupLeft = popupOffset - this.containerPadding;
17983 popupRight = popupOffset + this.containerPadding + this.width + this.containerPadding;
17984 overlapLeft = ( originOffset + popupLeft ) - containerLeft;
17985 overlapRight = containerRight - ( originOffset + popupRight );
17986
17987 // Adjust offset to make the popup not go beyond the edge, if needed
17988 if ( overlapRight < 0 ) {
17989 popupOffset += overlapRight;
17990 } else if ( overlapLeft < 0 ) {
17991 popupOffset -= overlapLeft;
17992 }
17993
17994 // Adjust offset to avoid anchor being rendered too close to the edge
17995 // $anchor.width() doesn't work with the pure CSS anchor (returns 0)
17996 // TODO: Find a measurement that works for CSS anchors and image anchors
17997 anchorWidth = this.$anchor[ 0 ].scrollWidth * 2;
17998 if ( popupOffset + this.width < anchorWidth ) {
17999 popupOffset = anchorWidth - this.width;
18000 } else if ( -popupOffset < anchorWidth ) {
18001 popupOffset = -anchorWidth;
18002 }
18003
18004 // Prevent transition from being interrupted
18005 clearTimeout( this.transitionTimeout );
18006 if ( transition ) {
18007 // Enable transition
18008 this.$element.addClass( 'oo-ui-popupWidget-transitioning' );
18009 }
18010
18011 // Position body relative to anchor
18012 this.$popup.css( 'margin-left', popupOffset );
18013
18014 if ( transition ) {
18015 // Prevent transitioning after transition is complete
18016 this.transitionTimeout = setTimeout( function () {
18017 widget.$element.removeClass( 'oo-ui-popupWidget-transitioning' );
18018 }, 200 );
18019 } else {
18020 // Prevent transitioning immediately
18021 this.$element.removeClass( 'oo-ui-popupWidget-transitioning' );
18022 }
18023
18024 // Reevaluate clipping state since we've relocated and resized the popup
18025 this.clip();
18026
18027 return this;
18028 };
18029
18030 /**
18031 * Set popup alignment
18032 * @param {string} align Alignment of the popup, `center`, `force-left`, `force-right`,
18033 * `backwards` or `forwards`.
18034 */
18035 OO.ui.PopupWidget.prototype.setAlignment = function ( align ) {
18036 // Validate alignment and transform deprecated values
18037 if ( [ 'left', 'right', 'force-left', 'force-right', 'backwards', 'forwards', 'center' ].indexOf( align ) > -1 ) {
18038 this.align = { left: 'force-right', right: 'force-left' }[ align ] || align;
18039 } else {
18040 this.align = 'center';
18041 }
18042 };
18043
18044 /**
18045 * Get popup alignment
18046 * @return {string} align Alignment of the popup, `center`, `force-left`, `force-right`,
18047 * `backwards` or `forwards`.
18048 */
18049 OO.ui.PopupWidget.prototype.getAlignment = function () {
18050 return this.align;
18051 };
18052
18053 /**
18054 * Progress bars visually display the status of an operation, such as a download,
18055 * and can be either determinate or indeterminate:
18056 *
18057 * - **determinate** process bars show the percent of an operation that is complete.
18058 *
18059 * - **indeterminate** process bars use a visual display of motion to indicate that an operation
18060 * is taking place. Because the extent of an indeterminate operation is unknown, the bar does
18061 * not use percentages.
18062 *
18063 * The value of the `progress` configuration determines whether the bar is determinate or indeterminate.
18064 *
18065 * @example
18066 * // Examples of determinate and indeterminate progress bars.
18067 * var progressBar1 = new OO.ui.ProgressBarWidget( {
18068 * progress: 33
18069 * } );
18070 * var progressBar2 = new OO.ui.ProgressBarWidget();
18071 *
18072 * // Create a FieldsetLayout to layout progress bars
18073 * var fieldset = new OO.ui.FieldsetLayout;
18074 * fieldset.addItems( [
18075 * new OO.ui.FieldLayout( progressBar1, {label: 'Determinate', align: 'top'}),
18076 * new OO.ui.FieldLayout( progressBar2, {label: 'Indeterminate', align: 'top'})
18077 * ] );
18078 * $( 'body' ).append( fieldset.$element );
18079 *
18080 * @class
18081 * @extends OO.ui.Widget
18082 *
18083 * @constructor
18084 * @param {Object} [config] Configuration options
18085 * @cfg {number|boolean} [progress=false] The type of progress bar (determinate or indeterminate).
18086 * To create a determinate progress bar, specify a number that reflects the initial percent complete.
18087 * By default, the progress bar is indeterminate.
18088 */
18089 OO.ui.ProgressBarWidget = function OoUiProgressBarWidget( config ) {
18090 // Configuration initialization
18091 config = config || {};
18092
18093 // Parent constructor
18094 OO.ui.ProgressBarWidget.parent.call( this, config );
18095
18096 // Properties
18097 this.$bar = $( '<div>' );
18098 this.progress = null;
18099
18100 // Initialization
18101 this.setProgress( config.progress !== undefined ? config.progress : false );
18102 this.$bar.addClass( 'oo-ui-progressBarWidget-bar' );
18103 this.$element
18104 .attr( {
18105 role: 'progressbar',
18106 'aria-valuemin': 0,
18107 'aria-valuemax': 100
18108 } )
18109 .addClass( 'oo-ui-progressBarWidget' )
18110 .append( this.$bar );
18111 };
18112
18113 /* Setup */
18114
18115 OO.inheritClass( OO.ui.ProgressBarWidget, OO.ui.Widget );
18116
18117 /* Static Properties */
18118
18119 OO.ui.ProgressBarWidget.static.tagName = 'div';
18120
18121 /* Methods */
18122
18123 /**
18124 * Get the percent of the progress that has been completed. Indeterminate progresses will return `false`.
18125 *
18126 * @return {number|boolean} Progress percent
18127 */
18128 OO.ui.ProgressBarWidget.prototype.getProgress = function () {
18129 return this.progress;
18130 };
18131
18132 /**
18133 * Set the percent of the process completed or `false` for an indeterminate process.
18134 *
18135 * @param {number|boolean} progress Progress percent or `false` for indeterminate
18136 */
18137 OO.ui.ProgressBarWidget.prototype.setProgress = function ( progress ) {
18138 this.progress = progress;
18139
18140 if ( progress !== false ) {
18141 this.$bar.css( 'width', this.progress + '%' );
18142 this.$element.attr( 'aria-valuenow', this.progress );
18143 } else {
18144 this.$bar.css( 'width', '' );
18145 this.$element.removeAttr( 'aria-valuenow' );
18146 }
18147 this.$element.toggleClass( 'oo-ui-progressBarWidget-indeterminate', !progress );
18148 };
18149
18150 /**
18151 * SearchWidgets combine a {@link OO.ui.TextInputWidget text input field}, where users can type a search query,
18152 * and a menu of search results, which is displayed beneath the query
18153 * field. Unlike {@link OO.ui.mixin.LookupElement lookup menus}, search result menus are always visible to the user.
18154 * Users can choose an item from the menu or type a query into the text field to search for a matching result item.
18155 * In general, search widgets are used inside a separate {@link OO.ui.Dialog dialog} window.
18156 *
18157 * Each time the query is changed, the search result menu is cleared and repopulated. Please see
18158 * the [OOjs UI demos][1] for an example.
18159 *
18160 * [1]: https://tools.wmflabs.org/oojs-ui/oojs-ui/demos/#dialogs-mediawiki-vector-ltr
18161 *
18162 * @class
18163 * @extends OO.ui.Widget
18164 *
18165 * @constructor
18166 * @param {Object} [config] Configuration options
18167 * @cfg {string|jQuery} [placeholder] Placeholder text for query input
18168 * @cfg {string} [value] Initial query value
18169 */
18170 OO.ui.SearchWidget = function OoUiSearchWidget( config ) {
18171 // Configuration initialization
18172 config = config || {};
18173
18174 // Parent constructor
18175 OO.ui.SearchWidget.parent.call( this, config );
18176
18177 // Properties
18178 this.query = new OO.ui.TextInputWidget( {
18179 icon: 'search',
18180 placeholder: config.placeholder,
18181 value: config.value
18182 } );
18183 this.results = new OO.ui.SelectWidget();
18184 this.$query = $( '<div>' );
18185 this.$results = $( '<div>' );
18186
18187 // Events
18188 this.query.connect( this, {
18189 change: 'onQueryChange',
18190 enter: 'onQueryEnter'
18191 } );
18192 this.query.$input.on( 'keydown', this.onQueryKeydown.bind( this ) );
18193
18194 // Initialization
18195 this.$query
18196 .addClass( 'oo-ui-searchWidget-query' )
18197 .append( this.query.$element );
18198 this.$results
18199 .addClass( 'oo-ui-searchWidget-results' )
18200 .append( this.results.$element );
18201 this.$element
18202 .addClass( 'oo-ui-searchWidget' )
18203 .append( this.$results, this.$query );
18204 };
18205
18206 /* Setup */
18207
18208 OO.inheritClass( OO.ui.SearchWidget, OO.ui.Widget );
18209
18210 /* Methods */
18211
18212 /**
18213 * Handle query key down events.
18214 *
18215 * @private
18216 * @param {jQuery.Event} e Key down event
18217 */
18218 OO.ui.SearchWidget.prototype.onQueryKeydown = function ( e ) {
18219 var highlightedItem, nextItem,
18220 dir = e.which === OO.ui.Keys.DOWN ? 1 : ( e.which === OO.ui.Keys.UP ? -1 : 0 );
18221
18222 if ( dir ) {
18223 highlightedItem = this.results.getHighlightedItem();
18224 if ( !highlightedItem ) {
18225 highlightedItem = this.results.getSelectedItem();
18226 }
18227 nextItem = this.results.getRelativeSelectableItem( highlightedItem, dir );
18228 this.results.highlightItem( nextItem );
18229 nextItem.scrollElementIntoView();
18230 }
18231 };
18232
18233 /**
18234 * Handle select widget select events.
18235 *
18236 * Clears existing results. Subclasses should repopulate items according to new query.
18237 *
18238 * @private
18239 * @param {string} value New value
18240 */
18241 OO.ui.SearchWidget.prototype.onQueryChange = function () {
18242 // Reset
18243 this.results.clearItems();
18244 };
18245
18246 /**
18247 * Handle select widget enter key events.
18248 *
18249 * Chooses highlighted item.
18250 *
18251 * @private
18252 * @param {string} value New value
18253 */
18254 OO.ui.SearchWidget.prototype.onQueryEnter = function () {
18255 var highlightedItem = this.results.getHighlightedItem();
18256 if ( highlightedItem ) {
18257 this.results.chooseItem( highlightedItem );
18258 }
18259 };
18260
18261 /**
18262 * Get the query input.
18263 *
18264 * @return {OO.ui.TextInputWidget} Query input
18265 */
18266 OO.ui.SearchWidget.prototype.getQuery = function () {
18267 return this.query;
18268 };
18269
18270 /**
18271 * Get the search results menu.
18272 *
18273 * @return {OO.ui.SelectWidget} Menu of search results
18274 */
18275 OO.ui.SearchWidget.prototype.getResults = function () {
18276 return this.results;
18277 };
18278
18279 /**
18280 * A SelectWidget is of a generic selection of options. The OOjs UI library contains several types of
18281 * select widgets, including {@link OO.ui.ButtonSelectWidget button selects},
18282 * {@link OO.ui.RadioSelectWidget radio selects}, and {@link OO.ui.MenuSelectWidget
18283 * menu selects}.
18284 *
18285 * This class should be used together with OO.ui.OptionWidget or OO.ui.DecoratedOptionWidget. For more
18286 * information, please see the [OOjs UI documentation on MediaWiki][1].
18287 *
18288 * @example
18289 * // Example of a select widget with three options
18290 * var select = new OO.ui.SelectWidget( {
18291 * items: [
18292 * new OO.ui.OptionWidget( {
18293 * data: 'a',
18294 * label: 'Option One',
18295 * } ),
18296 * new OO.ui.OptionWidget( {
18297 * data: 'b',
18298 * label: 'Option Two',
18299 * } ),
18300 * new OO.ui.OptionWidget( {
18301 * data: 'c',
18302 * label: 'Option Three',
18303 * } )
18304 * ]
18305 * } );
18306 * $( 'body' ).append( select.$element );
18307 *
18308 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
18309 *
18310 * @abstract
18311 * @class
18312 * @extends OO.ui.Widget
18313 * @mixins OO.ui.mixin.GroupWidget
18314 *
18315 * @constructor
18316 * @param {Object} [config] Configuration options
18317 * @cfg {OO.ui.OptionWidget[]} [items] An array of options to add to the select.
18318 * Options are created with {@link OO.ui.OptionWidget OptionWidget} classes. See
18319 * the [OOjs UI documentation on MediaWiki] [2] for examples.
18320 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
18321 */
18322 OO.ui.SelectWidget = function OoUiSelectWidget( config ) {
18323 // Configuration initialization
18324 config = config || {};
18325
18326 // Parent constructor
18327 OO.ui.SelectWidget.parent.call( this, config );
18328
18329 // Mixin constructors
18330 OO.ui.mixin.GroupWidget.call( this, $.extend( {}, config, { $group: this.$element } ) );
18331
18332 // Properties
18333 this.pressed = false;
18334 this.selecting = null;
18335 this.onMouseUpHandler = this.onMouseUp.bind( this );
18336 this.onMouseMoveHandler = this.onMouseMove.bind( this );
18337 this.onKeyDownHandler = this.onKeyDown.bind( this );
18338 this.onKeyPressHandler = this.onKeyPress.bind( this );
18339 this.keyPressBuffer = '';
18340 this.keyPressBufferTimer = null;
18341
18342 // Events
18343 this.connect( this, {
18344 toggle: 'onToggle'
18345 } );
18346 this.$element.on( {
18347 mousedown: this.onMouseDown.bind( this ),
18348 mouseover: this.onMouseOver.bind( this ),
18349 mouseleave: this.onMouseLeave.bind( this )
18350 } );
18351
18352 // Initialization
18353 this.$element
18354 .addClass( 'oo-ui-selectWidget oo-ui-selectWidget-depressed' )
18355 .attr( 'role', 'listbox' );
18356 if ( Array.isArray( config.items ) ) {
18357 this.addItems( config.items );
18358 }
18359 };
18360
18361 /* Setup */
18362
18363 OO.inheritClass( OO.ui.SelectWidget, OO.ui.Widget );
18364
18365 // Need to mixin base class as well
18366 OO.mixinClass( OO.ui.SelectWidget, OO.ui.mixin.GroupElement );
18367 OO.mixinClass( OO.ui.SelectWidget, OO.ui.mixin.GroupWidget );
18368
18369 /* Static */
18370 OO.ui.SelectWidget.static.passAllFilter = function () {
18371 return true;
18372 };
18373
18374 /* Events */
18375
18376 /**
18377 * @event highlight
18378 *
18379 * A `highlight` event is emitted when the highlight is changed with the #highlightItem method.
18380 *
18381 * @param {OO.ui.OptionWidget|null} item Highlighted item
18382 */
18383
18384 /**
18385 * @event press
18386 *
18387 * A `press` event is emitted when the #pressItem method is used to programmatically modify the
18388 * pressed state of an option.
18389 *
18390 * @param {OO.ui.OptionWidget|null} item Pressed item
18391 */
18392
18393 /**
18394 * @event select
18395 *
18396 * A `select` event is emitted when the selection is modified programmatically with the #selectItem method.
18397 *
18398 * @param {OO.ui.OptionWidget|null} item Selected item
18399 */
18400
18401 /**
18402 * @event choose
18403 * A `choose` event is emitted when an item is chosen with the #chooseItem method.
18404 * @param {OO.ui.OptionWidget} item Chosen item
18405 */
18406
18407 /**
18408 * @event add
18409 *
18410 * An `add` event is emitted when options are added to the select with the #addItems method.
18411 *
18412 * @param {OO.ui.OptionWidget[]} items Added items
18413 * @param {number} index Index of insertion point
18414 */
18415
18416 /**
18417 * @event remove
18418 *
18419 * A `remove` event is emitted when options are removed from the select with the #clearItems
18420 * or #removeItems methods.
18421 *
18422 * @param {OO.ui.OptionWidget[]} items Removed items
18423 */
18424
18425 /* Methods */
18426
18427 /**
18428 * Handle mouse down events.
18429 *
18430 * @private
18431 * @param {jQuery.Event} e Mouse down event
18432 */
18433 OO.ui.SelectWidget.prototype.onMouseDown = function ( e ) {
18434 var item;
18435
18436 if ( !this.isDisabled() && e.which === OO.ui.MouseButtons.LEFT ) {
18437 this.togglePressed( true );
18438 item = this.getTargetItem( e );
18439 if ( item && item.isSelectable() ) {
18440 this.pressItem( item );
18441 this.selecting = item;
18442 this.getElementDocument().addEventListener( 'mouseup', this.onMouseUpHandler, true );
18443 this.getElementDocument().addEventListener( 'mousemove', this.onMouseMoveHandler, true );
18444 }
18445 }
18446 return false;
18447 };
18448
18449 /**
18450 * Handle mouse up events.
18451 *
18452 * @private
18453 * @param {jQuery.Event} e Mouse up event
18454 */
18455 OO.ui.SelectWidget.prototype.onMouseUp = function ( e ) {
18456 var item;
18457
18458 this.togglePressed( false );
18459 if ( !this.selecting ) {
18460 item = this.getTargetItem( e );
18461 if ( item && item.isSelectable() ) {
18462 this.selecting = item;
18463 }
18464 }
18465 if ( !this.isDisabled() && e.which === OO.ui.MouseButtons.LEFT && this.selecting ) {
18466 this.pressItem( null );
18467 this.chooseItem( this.selecting );
18468 this.selecting = null;
18469 }
18470
18471 this.getElementDocument().removeEventListener( 'mouseup', this.onMouseUpHandler, true );
18472 this.getElementDocument().removeEventListener( 'mousemove', this.onMouseMoveHandler, true );
18473
18474 return false;
18475 };
18476
18477 /**
18478 * Handle mouse move events.
18479 *
18480 * @private
18481 * @param {jQuery.Event} e Mouse move event
18482 */
18483 OO.ui.SelectWidget.prototype.onMouseMove = function ( e ) {
18484 var item;
18485
18486 if ( !this.isDisabled() && this.pressed ) {
18487 item = this.getTargetItem( e );
18488 if ( item && item !== this.selecting && item.isSelectable() ) {
18489 this.pressItem( item );
18490 this.selecting = item;
18491 }
18492 }
18493 return false;
18494 };
18495
18496 /**
18497 * Handle mouse over events.
18498 *
18499 * @private
18500 * @param {jQuery.Event} e Mouse over event
18501 */
18502 OO.ui.SelectWidget.prototype.onMouseOver = function ( e ) {
18503 var item;
18504
18505 if ( !this.isDisabled() ) {
18506 item = this.getTargetItem( e );
18507 this.highlightItem( item && item.isHighlightable() ? item : null );
18508 }
18509 return false;
18510 };
18511
18512 /**
18513 * Handle mouse leave events.
18514 *
18515 * @private
18516 * @param {jQuery.Event} e Mouse over event
18517 */
18518 OO.ui.SelectWidget.prototype.onMouseLeave = function () {
18519 if ( !this.isDisabled() ) {
18520 this.highlightItem( null );
18521 }
18522 return false;
18523 };
18524
18525 /**
18526 * Handle key down events.
18527 *
18528 * @protected
18529 * @param {jQuery.Event} e Key down event
18530 */
18531 OO.ui.SelectWidget.prototype.onKeyDown = function ( e ) {
18532 var nextItem,
18533 handled = false,
18534 currentItem = this.getHighlightedItem() || this.getSelectedItem();
18535
18536 if ( !this.isDisabled() && this.isVisible() ) {
18537 switch ( e.keyCode ) {
18538 case OO.ui.Keys.ENTER:
18539 if ( currentItem && currentItem.constructor.static.highlightable ) {
18540 // Was only highlighted, now let's select it. No-op if already selected.
18541 this.chooseItem( currentItem );
18542 handled = true;
18543 }
18544 break;
18545 case OO.ui.Keys.UP:
18546 case OO.ui.Keys.LEFT:
18547 this.clearKeyPressBuffer();
18548 nextItem = this.getRelativeSelectableItem( currentItem, -1 );
18549 handled = true;
18550 break;
18551 case OO.ui.Keys.DOWN:
18552 case OO.ui.Keys.RIGHT:
18553 this.clearKeyPressBuffer();
18554 nextItem = this.getRelativeSelectableItem( currentItem, 1 );
18555 handled = true;
18556 break;
18557 case OO.ui.Keys.ESCAPE:
18558 case OO.ui.Keys.TAB:
18559 if ( currentItem && currentItem.constructor.static.highlightable ) {
18560 currentItem.setHighlighted( false );
18561 }
18562 this.unbindKeyDownListener();
18563 this.unbindKeyPressListener();
18564 // Don't prevent tabbing away / defocusing
18565 handled = false;
18566 break;
18567 }
18568
18569 if ( nextItem ) {
18570 if ( nextItem.constructor.static.highlightable ) {
18571 this.highlightItem( nextItem );
18572 } else {
18573 this.chooseItem( nextItem );
18574 }
18575 nextItem.scrollElementIntoView();
18576 }
18577
18578 if ( handled ) {
18579 // Can't just return false, because e is not always a jQuery event
18580 e.preventDefault();
18581 e.stopPropagation();
18582 }
18583 }
18584 };
18585
18586 /**
18587 * Bind key down listener.
18588 *
18589 * @protected
18590 */
18591 OO.ui.SelectWidget.prototype.bindKeyDownListener = function () {
18592 this.getElementWindow().addEventListener( 'keydown', this.onKeyDownHandler, true );
18593 };
18594
18595 /**
18596 * Unbind key down listener.
18597 *
18598 * @protected
18599 */
18600 OO.ui.SelectWidget.prototype.unbindKeyDownListener = function () {
18601 this.getElementWindow().removeEventListener( 'keydown', this.onKeyDownHandler, true );
18602 };
18603
18604 /**
18605 * Clear the key-press buffer
18606 *
18607 * @protected
18608 */
18609 OO.ui.SelectWidget.prototype.clearKeyPressBuffer = function () {
18610 if ( this.keyPressBufferTimer ) {
18611 clearTimeout( this.keyPressBufferTimer );
18612 this.keyPressBufferTimer = null;
18613 }
18614 this.keyPressBuffer = '';
18615 };
18616
18617 /**
18618 * Handle key press events.
18619 *
18620 * @protected
18621 * @param {jQuery.Event} e Key press event
18622 */
18623 OO.ui.SelectWidget.prototype.onKeyPress = function ( e ) {
18624 var c, filter, item;
18625
18626 if ( !e.charCode ) {
18627 if ( e.keyCode === OO.ui.Keys.BACKSPACE && this.keyPressBuffer !== '' ) {
18628 this.keyPressBuffer = this.keyPressBuffer.substr( 0, this.keyPressBuffer.length - 1 );
18629 return false;
18630 }
18631 return;
18632 }
18633 if ( String.fromCodePoint ) {
18634 c = String.fromCodePoint( e.charCode );
18635 } else {
18636 c = String.fromCharCode( e.charCode );
18637 }
18638
18639 if ( this.keyPressBufferTimer ) {
18640 clearTimeout( this.keyPressBufferTimer );
18641 }
18642 this.keyPressBufferTimer = setTimeout( this.clearKeyPressBuffer.bind( this ), 1500 );
18643
18644 item = this.getHighlightedItem() || this.getSelectedItem();
18645
18646 if ( this.keyPressBuffer === c ) {
18647 // Common (if weird) special case: typing "xxxx" will cycle through all
18648 // the items beginning with "x".
18649 if ( item ) {
18650 item = this.getRelativeSelectableItem( item, 1 );
18651 }
18652 } else {
18653 this.keyPressBuffer += c;
18654 }
18655
18656 filter = this.getItemMatcher( this.keyPressBuffer, false );
18657 if ( !item || !filter( item ) ) {
18658 item = this.getRelativeSelectableItem( item, 1, filter );
18659 }
18660 if ( item ) {
18661 if ( item.constructor.static.highlightable ) {
18662 this.highlightItem( item );
18663 } else {
18664 this.chooseItem( item );
18665 }
18666 item.scrollElementIntoView();
18667 }
18668
18669 return false;
18670 };
18671
18672 /**
18673 * Get a matcher for the specific string
18674 *
18675 * @protected
18676 * @param {string} s String to match against items
18677 * @param {boolean} [exact=false] Only accept exact matches
18678 * @return {Function} function ( OO.ui.OptionItem ) => boolean
18679 */
18680 OO.ui.SelectWidget.prototype.getItemMatcher = function ( s, exact ) {
18681 var re;
18682
18683 if ( s.normalize ) {
18684 s = s.normalize();
18685 }
18686 s = exact ? s.trim() : s.replace( /^\s+/, '' );
18687 re = '^\\s*' + s.replace( /([\\{}()|.?*+\-\^$\[\]])/g, '\\$1' ).replace( /\s+/g, '\\s+' );
18688 if ( exact ) {
18689 re += '\\s*$';
18690 }
18691 re = new RegExp( re, 'i' );
18692 return function ( item ) {
18693 var l = item.getLabel();
18694 if ( typeof l !== 'string' ) {
18695 l = item.$label.text();
18696 }
18697 if ( l.normalize ) {
18698 l = l.normalize();
18699 }
18700 return re.test( l );
18701 };
18702 };
18703
18704 /**
18705 * Bind key press listener.
18706 *
18707 * @protected
18708 */
18709 OO.ui.SelectWidget.prototype.bindKeyPressListener = function () {
18710 this.getElementWindow().addEventListener( 'keypress', this.onKeyPressHandler, true );
18711 };
18712
18713 /**
18714 * Unbind key down listener.
18715 *
18716 * If you override this, be sure to call this.clearKeyPressBuffer() from your
18717 * implementation.
18718 *
18719 * @protected
18720 */
18721 OO.ui.SelectWidget.prototype.unbindKeyPressListener = function () {
18722 this.getElementWindow().removeEventListener( 'keypress', this.onKeyPressHandler, true );
18723 this.clearKeyPressBuffer();
18724 };
18725
18726 /**
18727 * Visibility change handler
18728 *
18729 * @protected
18730 * @param {boolean} visible
18731 */
18732 OO.ui.SelectWidget.prototype.onToggle = function ( visible ) {
18733 if ( !visible ) {
18734 this.clearKeyPressBuffer();
18735 }
18736 };
18737
18738 /**
18739 * Get the closest item to a jQuery.Event.
18740 *
18741 * @private
18742 * @param {jQuery.Event} e
18743 * @return {OO.ui.OptionWidget|null} Outline item widget, `null` if none was found
18744 */
18745 OO.ui.SelectWidget.prototype.getTargetItem = function ( e ) {
18746 return $( e.target ).closest( '.oo-ui-optionWidget' ).data( 'oo-ui-optionWidget' ) || null;
18747 };
18748
18749 /**
18750 * Get selected item.
18751 *
18752 * @return {OO.ui.OptionWidget|null} Selected item, `null` if no item is selected
18753 */
18754 OO.ui.SelectWidget.prototype.getSelectedItem = function () {
18755 var i, len;
18756
18757 for ( i = 0, len = this.items.length; i < len; i++ ) {
18758 if ( this.items[ i ].isSelected() ) {
18759 return this.items[ i ];
18760 }
18761 }
18762 return null;
18763 };
18764
18765 /**
18766 * Get highlighted item.
18767 *
18768 * @return {OO.ui.OptionWidget|null} Highlighted item, `null` if no item is highlighted
18769 */
18770 OO.ui.SelectWidget.prototype.getHighlightedItem = function () {
18771 var i, len;
18772
18773 for ( i = 0, len = this.items.length; i < len; i++ ) {
18774 if ( this.items[ i ].isHighlighted() ) {
18775 return this.items[ i ];
18776 }
18777 }
18778 return null;
18779 };
18780
18781 /**
18782 * Toggle pressed state.
18783 *
18784 * Press is a state that occurs when a user mouses down on an item, but
18785 * has not yet let go of the mouse. The item may appear selected, but it will not be selected
18786 * until the user releases the mouse.
18787 *
18788 * @param {boolean} pressed An option is being pressed
18789 */
18790 OO.ui.SelectWidget.prototype.togglePressed = function ( pressed ) {
18791 if ( pressed === undefined ) {
18792 pressed = !this.pressed;
18793 }
18794 if ( pressed !== this.pressed ) {
18795 this.$element
18796 .toggleClass( 'oo-ui-selectWidget-pressed', pressed )
18797 .toggleClass( 'oo-ui-selectWidget-depressed', !pressed );
18798 this.pressed = pressed;
18799 }
18800 };
18801
18802 /**
18803 * Highlight an option. If the `item` param is omitted, no options will be highlighted
18804 * and any existing highlight will be removed. The highlight is mutually exclusive.
18805 *
18806 * @param {OO.ui.OptionWidget} [item] Item to highlight, omit for no highlight
18807 * @fires highlight
18808 * @chainable
18809 */
18810 OO.ui.SelectWidget.prototype.highlightItem = function ( item ) {
18811 var i, len, highlighted,
18812 changed = false;
18813
18814 for ( i = 0, len = this.items.length; i < len; i++ ) {
18815 highlighted = this.items[ i ] === item;
18816 if ( this.items[ i ].isHighlighted() !== highlighted ) {
18817 this.items[ i ].setHighlighted( highlighted );
18818 changed = true;
18819 }
18820 }
18821 if ( changed ) {
18822 this.emit( 'highlight', item );
18823 }
18824
18825 return this;
18826 };
18827
18828 /**
18829 * Fetch an item by its label.
18830 *
18831 * @param {string} label Label of the item to select.
18832 * @param {boolean} [prefix=false] Allow a prefix match, if only a single item matches
18833 * @return {OO.ui.Element|null} Item with equivalent label, `null` if none exists
18834 */
18835 OO.ui.SelectWidget.prototype.getItemFromLabel = function ( label, prefix ) {
18836 var i, item, found,
18837 len = this.items.length,
18838 filter = this.getItemMatcher( label, true );
18839
18840 for ( i = 0; i < len; i++ ) {
18841 item = this.items[ i ];
18842 if ( item instanceof OO.ui.OptionWidget && item.isSelectable() && filter( item ) ) {
18843 return item;
18844 }
18845 }
18846
18847 if ( prefix ) {
18848 found = null;
18849 filter = this.getItemMatcher( label, false );
18850 for ( i = 0; i < len; i++ ) {
18851 item = this.items[ i ];
18852 if ( item instanceof OO.ui.OptionWidget && item.isSelectable() && filter( item ) ) {
18853 if ( found ) {
18854 return null;
18855 }
18856 found = item;
18857 }
18858 }
18859 if ( found ) {
18860 return found;
18861 }
18862 }
18863
18864 return null;
18865 };
18866
18867 /**
18868 * Programmatically select an option by its label. If the item does not exist,
18869 * all options will be deselected.
18870 *
18871 * @param {string} [label] Label of the item to select.
18872 * @param {boolean} [prefix=false] Allow a prefix match, if only a single item matches
18873 * @fires select
18874 * @chainable
18875 */
18876 OO.ui.SelectWidget.prototype.selectItemByLabel = function ( label, prefix ) {
18877 var itemFromLabel = this.getItemFromLabel( label, !!prefix );
18878 if ( label === undefined || !itemFromLabel ) {
18879 return this.selectItem();
18880 }
18881 return this.selectItem( itemFromLabel );
18882 };
18883
18884 /**
18885 * Programmatically select an option by its data. If the `data` parameter is omitted,
18886 * or if the item does not exist, all options will be deselected.
18887 *
18888 * @param {Object|string} [data] Value of the item to select, omit to deselect all
18889 * @fires select
18890 * @chainable
18891 */
18892 OO.ui.SelectWidget.prototype.selectItemByData = function ( data ) {
18893 var itemFromData = this.getItemFromData( data );
18894 if ( data === undefined || !itemFromData ) {
18895 return this.selectItem();
18896 }
18897 return this.selectItem( itemFromData );
18898 };
18899
18900 /**
18901 * Programmatically select an option by its reference. If the `item` parameter is omitted,
18902 * all options will be deselected.
18903 *
18904 * @param {OO.ui.OptionWidget} [item] Item to select, omit to deselect all
18905 * @fires select
18906 * @chainable
18907 */
18908 OO.ui.SelectWidget.prototype.selectItem = function ( item ) {
18909 var i, len, selected,
18910 changed = false;
18911
18912 for ( i = 0, len = this.items.length; i < len; i++ ) {
18913 selected = this.items[ i ] === item;
18914 if ( this.items[ i ].isSelected() !== selected ) {
18915 this.items[ i ].setSelected( selected );
18916 changed = true;
18917 }
18918 }
18919 if ( changed ) {
18920 this.emit( 'select', item );
18921 }
18922
18923 return this;
18924 };
18925
18926 /**
18927 * Press an item.
18928 *
18929 * Press is a state that occurs when a user mouses down on an item, but has not
18930 * yet let go of the mouse. The item may appear selected, but it will not be selected until the user
18931 * releases the mouse.
18932 *
18933 * @param {OO.ui.OptionWidget} [item] Item to press, omit to depress all
18934 * @fires press
18935 * @chainable
18936 */
18937 OO.ui.SelectWidget.prototype.pressItem = function ( item ) {
18938 var i, len, pressed,
18939 changed = false;
18940
18941 for ( i = 0, len = this.items.length; i < len; i++ ) {
18942 pressed = this.items[ i ] === item;
18943 if ( this.items[ i ].isPressed() !== pressed ) {
18944 this.items[ i ].setPressed( pressed );
18945 changed = true;
18946 }
18947 }
18948 if ( changed ) {
18949 this.emit( 'press', item );
18950 }
18951
18952 return this;
18953 };
18954
18955 /**
18956 * Choose an item.
18957 *
18958 * Note that ‘choose’ should never be modified programmatically. A user can choose
18959 * an option with the keyboard or mouse and it becomes selected. To select an item programmatically,
18960 * use the #selectItem method.
18961 *
18962 * This method is identical to #selectItem, but may vary in subclasses that take additional action
18963 * when users choose an item with the keyboard or mouse.
18964 *
18965 * @param {OO.ui.OptionWidget} item Item to choose
18966 * @fires choose
18967 * @chainable
18968 */
18969 OO.ui.SelectWidget.prototype.chooseItem = function ( item ) {
18970 if ( item ) {
18971 this.selectItem( item );
18972 this.emit( 'choose', item );
18973 }
18974
18975 return this;
18976 };
18977
18978 /**
18979 * Get an option by its position relative to the specified item (or to the start of the option array,
18980 * if item is `null`). The direction in which to search through the option array is specified with a
18981 * number: -1 for reverse (the default) or 1 for forward. The method will return an option, or
18982 * `null` if there are no options in the array.
18983 *
18984 * @param {OO.ui.OptionWidget|null} item Item to describe the start position, or `null` to start at the beginning of the array.
18985 * @param {number} direction Direction to move in: -1 to move backward, 1 to move forward
18986 * @param {Function} filter Only consider items for which this function returns
18987 * true. Function takes an OO.ui.OptionWidget and returns a boolean.
18988 * @return {OO.ui.OptionWidget|null} Item at position, `null` if there are no items in the select
18989 */
18990 OO.ui.SelectWidget.prototype.getRelativeSelectableItem = function ( item, direction, filter ) {
18991 var currentIndex, nextIndex, i,
18992 increase = direction > 0 ? 1 : -1,
18993 len = this.items.length;
18994
18995 if ( !$.isFunction( filter ) ) {
18996 filter = OO.ui.SelectWidget.static.passAllFilter;
18997 }
18998
18999 if ( item instanceof OO.ui.OptionWidget ) {
19000 currentIndex = this.items.indexOf( item );
19001 nextIndex = ( currentIndex + increase + len ) % len;
19002 } else {
19003 // If no item is selected and moving forward, start at the beginning.
19004 // If moving backward, start at the end.
19005 nextIndex = direction > 0 ? 0 : len - 1;
19006 }
19007
19008 for ( i = 0; i < len; i++ ) {
19009 item = this.items[ nextIndex ];
19010 if ( item instanceof OO.ui.OptionWidget && item.isSelectable() && filter( item ) ) {
19011 return item;
19012 }
19013 nextIndex = ( nextIndex + increase + len ) % len;
19014 }
19015 return null;
19016 };
19017
19018 /**
19019 * Get the next selectable item or `null` if there are no selectable items.
19020 * Disabled options and menu-section markers and breaks are not selectable.
19021 *
19022 * @return {OO.ui.OptionWidget|null} Item, `null` if there aren't any selectable items
19023 */
19024 OO.ui.SelectWidget.prototype.getFirstSelectableItem = function () {
19025 var i, len, item;
19026
19027 for ( i = 0, len = this.items.length; i < len; i++ ) {
19028 item = this.items[ i ];
19029 if ( item instanceof OO.ui.OptionWidget && item.isSelectable() ) {
19030 return item;
19031 }
19032 }
19033
19034 return null;
19035 };
19036
19037 /**
19038 * Add an array of options to the select. Optionally, an index number can be used to
19039 * specify an insertion point.
19040 *
19041 * @param {OO.ui.OptionWidget[]} items Items to add
19042 * @param {number} [index] Index to insert items after
19043 * @fires add
19044 * @chainable
19045 */
19046 OO.ui.SelectWidget.prototype.addItems = function ( items, index ) {
19047 // Mixin method
19048 OO.ui.mixin.GroupWidget.prototype.addItems.call( this, items, index );
19049
19050 // Always provide an index, even if it was omitted
19051 this.emit( 'add', items, index === undefined ? this.items.length - items.length - 1 : index );
19052
19053 return this;
19054 };
19055
19056 /**
19057 * Remove the specified array of options from the select. Options will be detached
19058 * from the DOM, not removed, so they can be reused later. To remove all options from
19059 * the select, you may wish to use the #clearItems method instead.
19060 *
19061 * @param {OO.ui.OptionWidget[]} items Items to remove
19062 * @fires remove
19063 * @chainable
19064 */
19065 OO.ui.SelectWidget.prototype.removeItems = function ( items ) {
19066 var i, len, item;
19067
19068 // Deselect items being removed
19069 for ( i = 0, len = items.length; i < len; i++ ) {
19070 item = items[ i ];
19071 if ( item.isSelected() ) {
19072 this.selectItem( null );
19073 }
19074 }
19075
19076 // Mixin method
19077 OO.ui.mixin.GroupWidget.prototype.removeItems.call( this, items );
19078
19079 this.emit( 'remove', items );
19080
19081 return this;
19082 };
19083
19084 /**
19085 * Clear all options from the select. Options will be detached from the DOM, not removed,
19086 * so that they can be reused later. To remove a subset of options from the select, use
19087 * the #removeItems method.
19088 *
19089 * @fires remove
19090 * @chainable
19091 */
19092 OO.ui.SelectWidget.prototype.clearItems = function () {
19093 var items = this.items.slice();
19094
19095 // Mixin method
19096 OO.ui.mixin.GroupWidget.prototype.clearItems.call( this );
19097
19098 // Clear selection
19099 this.selectItem( null );
19100
19101 this.emit( 'remove', items );
19102
19103 return this;
19104 };
19105
19106 /**
19107 * ButtonSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains
19108 * button options and is used together with
19109 * OO.ui.ButtonOptionWidget. The ButtonSelectWidget provides an interface for
19110 * highlighting, choosing, and selecting mutually exclusive options. Please see
19111 * the [OOjs UI documentation on MediaWiki] [1] for more information.
19112 *
19113 * @example
19114 * // Example: A ButtonSelectWidget that contains three ButtonOptionWidgets
19115 * var option1 = new OO.ui.ButtonOptionWidget( {
19116 * data: 1,
19117 * label: 'Option 1',
19118 * title: 'Button option 1'
19119 * } );
19120 *
19121 * var option2 = new OO.ui.ButtonOptionWidget( {
19122 * data: 2,
19123 * label: 'Option 2',
19124 * title: 'Button option 2'
19125 * } );
19126 *
19127 * var option3 = new OO.ui.ButtonOptionWidget( {
19128 * data: 3,
19129 * label: 'Option 3',
19130 * title: 'Button option 3'
19131 * } );
19132 *
19133 * var buttonSelect=new OO.ui.ButtonSelectWidget( {
19134 * items: [ option1, option2, option3 ]
19135 * } );
19136 * $( 'body' ).append( buttonSelect.$element );
19137 *
19138 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
19139 *
19140 * @class
19141 * @extends OO.ui.SelectWidget
19142 * @mixins OO.ui.mixin.TabIndexedElement
19143 *
19144 * @constructor
19145 * @param {Object} [config] Configuration options
19146 */
19147 OO.ui.ButtonSelectWidget = function OoUiButtonSelectWidget( config ) {
19148 // Parent constructor
19149 OO.ui.ButtonSelectWidget.parent.call( this, config );
19150
19151 // Mixin constructors
19152 OO.ui.mixin.TabIndexedElement.call( this, config );
19153
19154 // Events
19155 this.$element.on( {
19156 focus: this.bindKeyDownListener.bind( this ),
19157 blur: this.unbindKeyDownListener.bind( this )
19158 } );
19159
19160 // Initialization
19161 this.$element.addClass( 'oo-ui-buttonSelectWidget' );
19162 };
19163
19164 /* Setup */
19165
19166 OO.inheritClass( OO.ui.ButtonSelectWidget, OO.ui.SelectWidget );
19167 OO.mixinClass( OO.ui.ButtonSelectWidget, OO.ui.mixin.TabIndexedElement );
19168
19169 /**
19170 * RadioSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains radio
19171 * options and is used together with OO.ui.RadioOptionWidget. The RadioSelectWidget provides
19172 * an interface for adding, removing and selecting options.
19173 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
19174 *
19175 * If you want to use this within a HTML form, such as a OO.ui.FormLayout, use
19176 * OO.ui.RadioSelectInputWidget instead.
19177 *
19178 * @example
19179 * // A RadioSelectWidget with RadioOptions.
19180 * var option1 = new OO.ui.RadioOptionWidget( {
19181 * data: 'a',
19182 * label: 'Selected radio option'
19183 * } );
19184 *
19185 * var option2 = new OO.ui.RadioOptionWidget( {
19186 * data: 'b',
19187 * label: 'Unselected radio option'
19188 * } );
19189 *
19190 * var radioSelect=new OO.ui.RadioSelectWidget( {
19191 * items: [ option1, option2 ]
19192 * } );
19193 *
19194 * // Select 'option 1' using the RadioSelectWidget's selectItem() method.
19195 * radioSelect.selectItem( option1 );
19196 *
19197 * $( 'body' ).append( radioSelect.$element );
19198 *
19199 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
19200
19201 *
19202 * @class
19203 * @extends OO.ui.SelectWidget
19204 * @mixins OO.ui.mixin.TabIndexedElement
19205 *
19206 * @constructor
19207 * @param {Object} [config] Configuration options
19208 */
19209 OO.ui.RadioSelectWidget = function OoUiRadioSelectWidget( config ) {
19210 // Parent constructor
19211 OO.ui.RadioSelectWidget.parent.call( this, config );
19212
19213 // Mixin constructors
19214 OO.ui.mixin.TabIndexedElement.call( this, config );
19215
19216 // Events
19217 this.$element.on( {
19218 focus: this.bindKeyDownListener.bind( this ),
19219 blur: this.unbindKeyDownListener.bind( this )
19220 } );
19221
19222 // Initialization
19223 this.$element
19224 .addClass( 'oo-ui-radioSelectWidget' )
19225 .attr( 'role', 'radiogroup' );
19226 };
19227
19228 /* Setup */
19229
19230 OO.inheritClass( OO.ui.RadioSelectWidget, OO.ui.SelectWidget );
19231 OO.mixinClass( OO.ui.RadioSelectWidget, OO.ui.mixin.TabIndexedElement );
19232
19233 /**
19234 * MenuSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains options and
19235 * is used together with OO.ui.MenuOptionWidget. It is designed be used as part of another widget.
19236 * See {@link OO.ui.DropdownWidget DropdownWidget}, {@link OO.ui.ComboBoxInputWidget ComboBoxInputWidget},
19237 * and {@link OO.ui.mixin.LookupElement LookupElement} for examples of widgets that contain menus.
19238 * MenuSelectWidgets themselves are not instantiated directly, rather subclassed
19239 * and customized to be opened, closed, and displayed as needed.
19240 *
19241 * By default, menus are clipped to the visible viewport and are not visible when a user presses the
19242 * mouse outside the menu.
19243 *
19244 * Menus also have support for keyboard interaction:
19245 *
19246 * - Enter/Return key: choose and select a menu option
19247 * - Up-arrow key: highlight the previous menu option
19248 * - Down-arrow key: highlight the next menu option
19249 * - Esc key: hide the menu
19250 *
19251 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
19252 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
19253 *
19254 * @class
19255 * @extends OO.ui.SelectWidget
19256 * @mixins OO.ui.mixin.ClippableElement
19257 *
19258 * @constructor
19259 * @param {Object} [config] Configuration options
19260 * @cfg {OO.ui.TextInputWidget} [input] Text input used to implement option highlighting for menu items that match
19261 * the text the user types. This config is used by {@link OO.ui.ComboBoxInputWidget ComboBoxInputWidget}
19262 * and {@link OO.ui.mixin.LookupElement LookupElement}
19263 * @cfg {jQuery} [$input] Text input used to implement option highlighting for menu items that match
19264 * the text the user types. This config is used by {@link OO.ui.CapsuleMultiSelectWidget CapsuleMultiSelectWidget}
19265 * @cfg {OO.ui.Widget} [widget] Widget associated with the menu's active state. If the user clicks the mouse
19266 * anywhere on the page outside of this widget, the menu is hidden. For example, if there is a button
19267 * that toggles the menu's visibility on click, the menu will be hidden then re-shown when the user clicks
19268 * that button, unless the button (or its parent widget) is passed in here.
19269 * @cfg {boolean} [autoHide=true] Hide the menu when the mouse is pressed outside the menu.
19270 * @cfg {boolean} [filterFromInput=false] Filter the displayed options from the input
19271 */
19272 OO.ui.MenuSelectWidget = function OoUiMenuSelectWidget( config ) {
19273 // Configuration initialization
19274 config = config || {};
19275
19276 // Parent constructor
19277 OO.ui.MenuSelectWidget.parent.call( this, config );
19278
19279 // Mixin constructors
19280 OO.ui.mixin.ClippableElement.call( this, $.extend( {}, config, { $clippable: this.$group } ) );
19281
19282 // Properties
19283 this.newItems = null;
19284 this.autoHide = config.autoHide === undefined || !!config.autoHide;
19285 this.filterFromInput = !!config.filterFromInput;
19286 this.$input = config.$input ? config.$input : config.input ? config.input.$input : null;
19287 this.$widget = config.widget ? config.widget.$element : null;
19288 this.onDocumentMouseDownHandler = this.onDocumentMouseDown.bind( this );
19289 this.onInputEditHandler = OO.ui.debounce( this.updateItemVisibility.bind( this ), 100 );
19290
19291 // Initialization
19292 this.$element
19293 .addClass( 'oo-ui-menuSelectWidget' )
19294 .attr( 'role', 'menu' );
19295
19296 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
19297 // that reference properties not initialized at that time of parent class construction
19298 // TODO: Find a better way to handle post-constructor setup
19299 this.visible = false;
19300 this.$element.addClass( 'oo-ui-element-hidden' );
19301 };
19302
19303 /* Setup */
19304
19305 OO.inheritClass( OO.ui.MenuSelectWidget, OO.ui.SelectWidget );
19306 OO.mixinClass( OO.ui.MenuSelectWidget, OO.ui.mixin.ClippableElement );
19307
19308 /* Methods */
19309
19310 /**
19311 * Handles document mouse down events.
19312 *
19313 * @protected
19314 * @param {jQuery.Event} e Key down event
19315 */
19316 OO.ui.MenuSelectWidget.prototype.onDocumentMouseDown = function ( e ) {
19317 if (
19318 !OO.ui.contains( this.$element[ 0 ], e.target, true ) &&
19319 ( !this.$widget || !OO.ui.contains( this.$widget[ 0 ], e.target, true ) )
19320 ) {
19321 this.toggle( false );
19322 }
19323 };
19324
19325 /**
19326 * @inheritdoc
19327 */
19328 OO.ui.MenuSelectWidget.prototype.onKeyDown = function ( e ) {
19329 var currentItem = this.getHighlightedItem() || this.getSelectedItem();
19330
19331 if ( !this.isDisabled() && this.isVisible() ) {
19332 switch ( e.keyCode ) {
19333 case OO.ui.Keys.LEFT:
19334 case OO.ui.Keys.RIGHT:
19335 // Do nothing if a text field is associated, arrow keys will be handled natively
19336 if ( !this.$input ) {
19337 OO.ui.MenuSelectWidget.parent.prototype.onKeyDown.call( this, e );
19338 }
19339 break;
19340 case OO.ui.Keys.ESCAPE:
19341 case OO.ui.Keys.TAB:
19342 if ( currentItem ) {
19343 currentItem.setHighlighted( false );
19344 }
19345 this.toggle( false );
19346 // Don't prevent tabbing away, prevent defocusing
19347 if ( e.keyCode === OO.ui.Keys.ESCAPE ) {
19348 e.preventDefault();
19349 e.stopPropagation();
19350 }
19351 break;
19352 default:
19353 OO.ui.MenuSelectWidget.parent.prototype.onKeyDown.call( this, e );
19354 return;
19355 }
19356 }
19357 };
19358
19359 /**
19360 * Update menu item visibility after input changes.
19361 * @protected
19362 */
19363 OO.ui.MenuSelectWidget.prototype.updateItemVisibility = function () {
19364 var i, item,
19365 len = this.items.length,
19366 showAll = !this.isVisible(),
19367 filter = showAll ? null : this.getItemMatcher( this.$input.val() );
19368
19369 for ( i = 0; i < len; i++ ) {
19370 item = this.items[ i ];
19371 if ( item instanceof OO.ui.OptionWidget ) {
19372 item.toggle( showAll || filter( item ) );
19373 }
19374 }
19375
19376 // Reevaluate clipping
19377 this.clip();
19378 };
19379
19380 /**
19381 * @inheritdoc
19382 */
19383 OO.ui.MenuSelectWidget.prototype.bindKeyDownListener = function () {
19384 if ( this.$input ) {
19385 this.$input.on( 'keydown', this.onKeyDownHandler );
19386 } else {
19387 OO.ui.MenuSelectWidget.parent.prototype.bindKeyDownListener.call( this );
19388 }
19389 };
19390
19391 /**
19392 * @inheritdoc
19393 */
19394 OO.ui.MenuSelectWidget.prototype.unbindKeyDownListener = function () {
19395 if ( this.$input ) {
19396 this.$input.off( 'keydown', this.onKeyDownHandler );
19397 } else {
19398 OO.ui.MenuSelectWidget.parent.prototype.unbindKeyDownListener.call( this );
19399 }
19400 };
19401
19402 /**
19403 * @inheritdoc
19404 */
19405 OO.ui.MenuSelectWidget.prototype.bindKeyPressListener = function () {
19406 if ( this.$input ) {
19407 if ( this.filterFromInput ) {
19408 this.$input.on( 'keydown mouseup cut paste change input select', this.onInputEditHandler );
19409 }
19410 } else {
19411 OO.ui.MenuSelectWidget.parent.prototype.bindKeyPressListener.call( this );
19412 }
19413 };
19414
19415 /**
19416 * @inheritdoc
19417 */
19418 OO.ui.MenuSelectWidget.prototype.unbindKeyPressListener = function () {
19419 if ( this.$input ) {
19420 if ( this.filterFromInput ) {
19421 this.$input.off( 'keydown mouseup cut paste change input select', this.onInputEditHandler );
19422 this.updateItemVisibility();
19423 }
19424 } else {
19425 OO.ui.MenuSelectWidget.parent.prototype.unbindKeyPressListener.call( this );
19426 }
19427 };
19428
19429 /**
19430 * Choose an item.
19431 *
19432 * When a user chooses an item, the menu is closed.
19433 *
19434 * Note that ‘choose’ should never be modified programmatically. A user can choose an option with the keyboard
19435 * or mouse and it becomes selected. To select an item programmatically, use the #selectItem method.
19436 * @param {OO.ui.OptionWidget} item Item to choose
19437 * @chainable
19438 */
19439 OO.ui.MenuSelectWidget.prototype.chooseItem = function ( item ) {
19440 OO.ui.MenuSelectWidget.parent.prototype.chooseItem.call( this, item );
19441 this.toggle( false );
19442 return this;
19443 };
19444
19445 /**
19446 * @inheritdoc
19447 */
19448 OO.ui.MenuSelectWidget.prototype.addItems = function ( items, index ) {
19449 var i, len, item;
19450
19451 // Parent method
19452 OO.ui.MenuSelectWidget.parent.prototype.addItems.call( this, items, index );
19453
19454 // Auto-initialize
19455 if ( !this.newItems ) {
19456 this.newItems = [];
19457 }
19458
19459 for ( i = 0, len = items.length; i < len; i++ ) {
19460 item = items[ i ];
19461 if ( this.isVisible() ) {
19462 // Defer fitting label until item has been attached
19463 item.fitLabel();
19464 } else {
19465 this.newItems.push( item );
19466 }
19467 }
19468
19469 // Reevaluate clipping
19470 this.clip();
19471
19472 return this;
19473 };
19474
19475 /**
19476 * @inheritdoc
19477 */
19478 OO.ui.MenuSelectWidget.prototype.removeItems = function ( items ) {
19479 // Parent method
19480 OO.ui.MenuSelectWidget.parent.prototype.removeItems.call( this, items );
19481
19482 // Reevaluate clipping
19483 this.clip();
19484
19485 return this;
19486 };
19487
19488 /**
19489 * @inheritdoc
19490 */
19491 OO.ui.MenuSelectWidget.prototype.clearItems = function () {
19492 // Parent method
19493 OO.ui.MenuSelectWidget.parent.prototype.clearItems.call( this );
19494
19495 // Reevaluate clipping
19496 this.clip();
19497
19498 return this;
19499 };
19500
19501 /**
19502 * @inheritdoc
19503 */
19504 OO.ui.MenuSelectWidget.prototype.toggle = function ( visible ) {
19505 var i, len, change;
19506
19507 visible = ( visible === undefined ? !this.visible : !!visible ) && !!this.items.length;
19508 change = visible !== this.isVisible();
19509
19510 // Parent method
19511 OO.ui.MenuSelectWidget.parent.prototype.toggle.call( this, visible );
19512
19513 if ( change ) {
19514 if ( visible ) {
19515 this.bindKeyDownListener();
19516 this.bindKeyPressListener();
19517
19518 if ( this.newItems && this.newItems.length ) {
19519 for ( i = 0, len = this.newItems.length; i < len; i++ ) {
19520 this.newItems[ i ].fitLabel();
19521 }
19522 this.newItems = null;
19523 }
19524 this.toggleClipping( true );
19525
19526 // Auto-hide
19527 if ( this.autoHide ) {
19528 this.getElementDocument().addEventListener( 'mousedown', this.onDocumentMouseDownHandler, true );
19529 }
19530 } else {
19531 this.unbindKeyDownListener();
19532 this.unbindKeyPressListener();
19533 this.getElementDocument().removeEventListener( 'mousedown', this.onDocumentMouseDownHandler, true );
19534 this.toggleClipping( false );
19535 }
19536 }
19537
19538 return this;
19539 };
19540
19541 /**
19542 * FloatingMenuSelectWidget is a menu that will stick under a specified
19543 * container, even when it is inserted elsewhere in the document (for example,
19544 * in a OO.ui.Window's $overlay). This is sometimes necessary to prevent the
19545 * menu from being clipped too aggresively.
19546 *
19547 * The menu's position is automatically calculated and maintained when the menu
19548 * is toggled or the window is resized.
19549 *
19550 * See OO.ui.ComboBoxInputWidget for an example of a widget that uses this class.
19551 *
19552 * @class
19553 * @extends OO.ui.MenuSelectWidget
19554 * @mixins OO.ui.mixin.FloatableElement
19555 *
19556 * @constructor
19557 * @param {OO.ui.Widget} [inputWidget] Widget to provide the menu for.
19558 * Deprecated, omit this parameter and specify `$container` instead.
19559 * @param {Object} [config] Configuration options
19560 * @cfg {jQuery} [$container=inputWidget.$element] Element to render menu under
19561 */
19562 OO.ui.FloatingMenuSelectWidget = function OoUiFloatingMenuSelectWidget( inputWidget, config ) {
19563 // Allow 'inputWidget' parameter and config for backwards compatibility
19564 if ( OO.isPlainObject( inputWidget ) && config === undefined ) {
19565 config = inputWidget;
19566 inputWidget = config.inputWidget;
19567 }
19568
19569 // Configuration initialization
19570 config = config || {};
19571
19572 // Parent constructor
19573 OO.ui.FloatingMenuSelectWidget.parent.call( this, config );
19574
19575 // Properties (must be set before mixin constructors)
19576 this.inputWidget = inputWidget; // For backwards compatibility
19577 this.$container = config.$container || this.inputWidget.$element;
19578
19579 // Mixins constructors
19580 OO.ui.mixin.FloatableElement.call( this, $.extend( {}, config, { $floatableContainer: this.$container } ) );
19581
19582 // Initialization
19583 this.$element.addClass( 'oo-ui-floatingMenuSelectWidget' );
19584 // For backwards compatibility
19585 this.$element.addClass( 'oo-ui-textInputMenuSelectWidget' );
19586 };
19587
19588 /* Setup */
19589
19590 OO.inheritClass( OO.ui.FloatingMenuSelectWidget, OO.ui.MenuSelectWidget );
19591 OO.mixinClass( OO.ui.FloatingMenuSelectWidget, OO.ui.mixin.FloatableElement );
19592
19593 // For backwards compatibility
19594 OO.ui.TextInputMenuSelectWidget = OO.ui.FloatingMenuSelectWidget;
19595
19596 /* Methods */
19597
19598 /**
19599 * @inheritdoc
19600 */
19601 OO.ui.FloatingMenuSelectWidget.prototype.toggle = function ( visible ) {
19602 var change;
19603 visible = visible === undefined ? !this.isVisible() : !!visible;
19604 change = visible !== this.isVisible();
19605
19606 if ( change && visible ) {
19607 // Make sure the width is set before the parent method runs.
19608 this.setIdealSize( this.$container.width() );
19609 }
19610
19611 // Parent method
19612 // This will call this.clip(), which is nonsensical since we're not positioned yet...
19613 OO.ui.FloatingMenuSelectWidget.parent.prototype.toggle.call( this, visible );
19614
19615 if ( change ) {
19616 this.togglePositioning( this.isVisible() );
19617 }
19618
19619 return this;
19620 };
19621
19622 /**
19623 * OutlineSelectWidget is a structured list that contains {@link OO.ui.OutlineOptionWidget outline options}
19624 * A set of controls can be provided with an {@link OO.ui.OutlineControlsWidget outline controls} widget.
19625 *
19626 * **Currently, this class is only used by {@link OO.ui.BookletLayout booklet layouts}.**
19627 *
19628 * @class
19629 * @extends OO.ui.SelectWidget
19630 * @mixins OO.ui.mixin.TabIndexedElement
19631 *
19632 * @constructor
19633 * @param {Object} [config] Configuration options
19634 */
19635 OO.ui.OutlineSelectWidget = function OoUiOutlineSelectWidget( config ) {
19636 // Parent constructor
19637 OO.ui.OutlineSelectWidget.parent.call( this, config );
19638
19639 // Mixin constructors
19640 OO.ui.mixin.TabIndexedElement.call( this, config );
19641
19642 // Events
19643 this.$element.on( {
19644 focus: this.bindKeyDownListener.bind( this ),
19645 blur: this.unbindKeyDownListener.bind( this )
19646 } );
19647
19648 // Initialization
19649 this.$element.addClass( 'oo-ui-outlineSelectWidget' );
19650 };
19651
19652 /* Setup */
19653
19654 OO.inheritClass( OO.ui.OutlineSelectWidget, OO.ui.SelectWidget );
19655 OO.mixinClass( OO.ui.OutlineSelectWidget, OO.ui.mixin.TabIndexedElement );
19656
19657 /**
19658 * TabSelectWidget is a list that contains {@link OO.ui.TabOptionWidget tab options}
19659 *
19660 * **Currently, this class is only used by {@link OO.ui.IndexLayout index layouts}.**
19661 *
19662 * @class
19663 * @extends OO.ui.SelectWidget
19664 * @mixins OO.ui.mixin.TabIndexedElement
19665 *
19666 * @constructor
19667 * @param {Object} [config] Configuration options
19668 */
19669 OO.ui.TabSelectWidget = function OoUiTabSelectWidget( config ) {
19670 // Parent constructor
19671 OO.ui.TabSelectWidget.parent.call( this, config );
19672
19673 // Mixin constructors
19674 OO.ui.mixin.TabIndexedElement.call( this, config );
19675
19676 // Events
19677 this.$element.on( {
19678 focus: this.bindKeyDownListener.bind( this ),
19679 blur: this.unbindKeyDownListener.bind( this )
19680 } );
19681
19682 // Initialization
19683 this.$element.addClass( 'oo-ui-tabSelectWidget' );
19684 };
19685
19686 /* Setup */
19687
19688 OO.inheritClass( OO.ui.TabSelectWidget, OO.ui.SelectWidget );
19689 OO.mixinClass( OO.ui.TabSelectWidget, OO.ui.mixin.TabIndexedElement );
19690
19691 /**
19692 * NumberInputWidgets combine a {@link OO.ui.TextInputWidget text input} (where a value
19693 * can be entered manually) and two {@link OO.ui.ButtonWidget button widgets}
19694 * (to adjust the value in increments) to allow the user to enter a number.
19695 *
19696 * @example
19697 * // Example: A NumberInputWidget.
19698 * var numberInput = new OO.ui.NumberInputWidget( {
19699 * label: 'NumberInputWidget',
19700 * input: { value: 5, min: 1, max: 10 }
19701 * } );
19702 * $( 'body' ).append( numberInput.$element );
19703 *
19704 * @class
19705 * @extends OO.ui.Widget
19706 *
19707 * @constructor
19708 * @param {Object} [config] Configuration options
19709 * @cfg {Object} [input] Configuration options to pass to the {@link OO.ui.TextInputWidget text input widget}.
19710 * @cfg {Object} [minusButton] Configuration options to pass to the {@link OO.ui.ButtonWidget decrementing button widget}.
19711 * @cfg {Object} [plusButton] Configuration options to pass to the {@link OO.ui.ButtonWidget incrementing button widget}.
19712 * @cfg {boolean} [isInteger=false] Whether the field accepts only integer values.
19713 * @cfg {number} [min=-Infinity] Minimum allowed value
19714 * @cfg {number} [max=Infinity] Maximum allowed value
19715 * @cfg {number} [step=1] Delta when using the buttons or up/down arrow keys
19716 * @cfg {number|null} [pageStep] Delta when using the page-up/page-down keys. Defaults to 10 times #step.
19717 */
19718 OO.ui.NumberInputWidget = function OoUiNumberInputWidget( config ) {
19719 // Configuration initialization
19720 config = $.extend( {
19721 isInteger: false,
19722 min: -Infinity,
19723 max: Infinity,
19724 step: 1,
19725 pageStep: null
19726 }, config );
19727
19728 // Parent constructor
19729 OO.ui.NumberInputWidget.parent.call( this, config );
19730
19731 // Properties
19732 this.input = new OO.ui.TextInputWidget( $.extend(
19733 {
19734 disabled: this.isDisabled()
19735 },
19736 config.input
19737 ) );
19738 this.minusButton = new OO.ui.ButtonWidget( $.extend(
19739 {
19740 disabled: this.isDisabled(),
19741 tabIndex: -1
19742 },
19743 config.minusButton,
19744 {
19745 classes: [ 'oo-ui-numberInputWidget-minusButton' ],
19746 label: '−'
19747 }
19748 ) );
19749 this.plusButton = new OO.ui.ButtonWidget( $.extend(
19750 {
19751 disabled: this.isDisabled(),
19752 tabIndex: -1
19753 },
19754 config.plusButton,
19755 {
19756 classes: [ 'oo-ui-numberInputWidget-plusButton' ],
19757 label: '+'
19758 }
19759 ) );
19760
19761 // Events
19762 this.input.connect( this, {
19763 change: this.emit.bind( this, 'change' ),
19764 enter: this.emit.bind( this, 'enter' )
19765 } );
19766 this.input.$input.on( {
19767 keydown: this.onKeyDown.bind( this ),
19768 'wheel mousewheel DOMMouseScroll': this.onWheel.bind( this )
19769 } );
19770 this.plusButton.connect( this, {
19771 click: [ 'onButtonClick', +1 ]
19772 } );
19773 this.minusButton.connect( this, {
19774 click: [ 'onButtonClick', -1 ]
19775 } );
19776
19777 // Initialization
19778 this.setIsInteger( !!config.isInteger );
19779 this.setRange( config.min, config.max );
19780 this.setStep( config.step, config.pageStep );
19781
19782 this.$field = $( '<div>' ).addClass( 'oo-ui-numberInputWidget-field' )
19783 .append(
19784 this.minusButton.$element,
19785 this.input.$element,
19786 this.plusButton.$element
19787 );
19788 this.$element.addClass( 'oo-ui-numberInputWidget' ).append( this.$field );
19789 this.input.setValidation( this.validateNumber.bind( this ) );
19790 };
19791
19792 /* Setup */
19793
19794 OO.inheritClass( OO.ui.NumberInputWidget, OO.ui.Widget );
19795
19796 /* Events */
19797
19798 /**
19799 * A `change` event is emitted when the value of the input changes.
19800 *
19801 * @event change
19802 */
19803
19804 /**
19805 * An `enter` event is emitted when the user presses 'enter' inside the text box.
19806 *
19807 * @event enter
19808 */
19809
19810 /* Methods */
19811
19812 /**
19813 * Set whether only integers are allowed
19814 * @param {boolean} flag
19815 */
19816 OO.ui.NumberInputWidget.prototype.setIsInteger = function ( flag ) {
19817 this.isInteger = !!flag;
19818 this.input.setValidityFlag();
19819 };
19820
19821 /**
19822 * Get whether only integers are allowed
19823 * @return {boolean} Flag value
19824 */
19825 OO.ui.NumberInputWidget.prototype.getIsInteger = function () {
19826 return this.isInteger;
19827 };
19828
19829 /**
19830 * Set the range of allowed values
19831 * @param {number} min Minimum allowed value
19832 * @param {number} max Maximum allowed value
19833 */
19834 OO.ui.NumberInputWidget.prototype.setRange = function ( min, max ) {
19835 if ( min > max ) {
19836 throw new Error( 'Minimum (' + min + ') must not be greater than maximum (' + max + ')' );
19837 }
19838 this.min = min;
19839 this.max = max;
19840 this.input.setValidityFlag();
19841 };
19842
19843 /**
19844 * Get the current range
19845 * @return {number[]} Minimum and maximum values
19846 */
19847 OO.ui.NumberInputWidget.prototype.getRange = function () {
19848 return [ this.min, this.max ];
19849 };
19850
19851 /**
19852 * Set the stepping deltas
19853 * @param {number} step Normal step
19854 * @param {number|null} pageStep Page step. If null, 10 * step will be used.
19855 */
19856 OO.ui.NumberInputWidget.prototype.setStep = function ( step, pageStep ) {
19857 if ( step <= 0 ) {
19858 throw new Error( 'Step value must be positive' );
19859 }
19860 if ( pageStep === null ) {
19861 pageStep = step * 10;
19862 } else if ( pageStep <= 0 ) {
19863 throw new Error( 'Page step value must be positive' );
19864 }
19865 this.step = step;
19866 this.pageStep = pageStep;
19867 };
19868
19869 /**
19870 * Get the current stepping values
19871 * @return {number[]} Step and page step
19872 */
19873 OO.ui.NumberInputWidget.prototype.getStep = function () {
19874 return [ this.step, this.pageStep ];
19875 };
19876
19877 /**
19878 * Get the current value of the widget
19879 * @return {string}
19880 */
19881 OO.ui.NumberInputWidget.prototype.getValue = function () {
19882 return this.input.getValue();
19883 };
19884
19885 /**
19886 * Get the current value of the widget as a number
19887 * @return {number} May be NaN, or an invalid number
19888 */
19889 OO.ui.NumberInputWidget.prototype.getNumericValue = function () {
19890 return +this.input.getValue();
19891 };
19892
19893 /**
19894 * Set the value of the widget
19895 * @param {string} value Invalid values are allowed
19896 */
19897 OO.ui.NumberInputWidget.prototype.setValue = function ( value ) {
19898 this.input.setValue( value );
19899 };
19900
19901 /**
19902 * Adjust the value of the widget
19903 * @param {number} delta Adjustment amount
19904 */
19905 OO.ui.NumberInputWidget.prototype.adjustValue = function ( delta ) {
19906 var n, v = this.getNumericValue();
19907
19908 delta = +delta;
19909 if ( isNaN( delta ) || !isFinite( delta ) ) {
19910 throw new Error( 'Delta must be a finite number' );
19911 }
19912
19913 if ( isNaN( v ) ) {
19914 n = 0;
19915 } else {
19916 n = v + delta;
19917 n = Math.max( Math.min( n, this.max ), this.min );
19918 if ( this.isInteger ) {
19919 n = Math.round( n );
19920 }
19921 }
19922
19923 if ( n !== v ) {
19924 this.setValue( n );
19925 }
19926 };
19927
19928 /**
19929 * Validate input
19930 * @private
19931 * @param {string} value Field value
19932 * @return {boolean}
19933 */
19934 OO.ui.NumberInputWidget.prototype.validateNumber = function ( value ) {
19935 var n = +value;
19936 if ( isNaN( n ) || !isFinite( n ) ) {
19937 return false;
19938 }
19939
19940 /*jshint bitwise: false */
19941 if ( this.isInteger && ( n | 0 ) !== n ) {
19942 return false;
19943 }
19944 /*jshint bitwise: true */
19945
19946 if ( n < this.min || n > this.max ) {
19947 return false;
19948 }
19949
19950 return true;
19951 };
19952
19953 /**
19954 * Handle mouse click events.
19955 *
19956 * @private
19957 * @param {number} dir +1 or -1
19958 */
19959 OO.ui.NumberInputWidget.prototype.onButtonClick = function ( dir ) {
19960 this.adjustValue( dir * this.step );
19961 };
19962
19963 /**
19964 * Handle mouse wheel events.
19965 *
19966 * @private
19967 * @param {jQuery.Event} event
19968 */
19969 OO.ui.NumberInputWidget.prototype.onWheel = function ( event ) {
19970 var delta = 0;
19971
19972 // Standard 'wheel' event
19973 if ( event.originalEvent.deltaMode !== undefined ) {
19974 this.sawWheelEvent = true;
19975 }
19976 if ( event.originalEvent.deltaY ) {
19977 delta = -event.originalEvent.deltaY;
19978 } else if ( event.originalEvent.deltaX ) {
19979 delta = event.originalEvent.deltaX;
19980 }
19981
19982 // Non-standard events
19983 if ( !this.sawWheelEvent ) {
19984 if ( event.originalEvent.wheelDeltaX ) {
19985 delta = -event.originalEvent.wheelDeltaX;
19986 } else if ( event.originalEvent.wheelDeltaY ) {
19987 delta = event.originalEvent.wheelDeltaY;
19988 } else if ( event.originalEvent.wheelDelta ) {
19989 delta = event.originalEvent.wheelDelta;
19990 } else if ( event.originalEvent.detail ) {
19991 delta = -event.originalEvent.detail;
19992 }
19993 }
19994
19995 if ( delta ) {
19996 delta = delta < 0 ? -1 : 1;
19997 this.adjustValue( delta * this.step );
19998 }
19999
20000 return false;
20001 };
20002
20003 /**
20004 * Handle key down events.
20005 *
20006 * @private
20007 * @param {jQuery.Event} e Key down event
20008 */
20009 OO.ui.NumberInputWidget.prototype.onKeyDown = function ( e ) {
20010 if ( !this.isDisabled() ) {
20011 switch ( e.which ) {
20012 case OO.ui.Keys.UP:
20013 this.adjustValue( this.step );
20014 return false;
20015 case OO.ui.Keys.DOWN:
20016 this.adjustValue( -this.step );
20017 return false;
20018 case OO.ui.Keys.PAGEUP:
20019 this.adjustValue( this.pageStep );
20020 return false;
20021 case OO.ui.Keys.PAGEDOWN:
20022 this.adjustValue( -this.pageStep );
20023 return false;
20024 }
20025 }
20026 };
20027
20028 /**
20029 * @inheritdoc
20030 */
20031 OO.ui.NumberInputWidget.prototype.setDisabled = function ( disabled ) {
20032 // Parent method
20033 OO.ui.NumberInputWidget.parent.prototype.setDisabled.call( this, disabled );
20034
20035 if ( this.input ) {
20036 this.input.setDisabled( this.isDisabled() );
20037 }
20038 if ( this.minusButton ) {
20039 this.minusButton.setDisabled( this.isDisabled() );
20040 }
20041 if ( this.plusButton ) {
20042 this.plusButton.setDisabled( this.isDisabled() );
20043 }
20044
20045 return this;
20046 };
20047
20048 /**
20049 * ToggleSwitches are switches that slide on and off. Their state is represented by a Boolean
20050 * value (`true` for ‘on’, and `false` otherwise, the default). The ‘off’ state is represented
20051 * visually by a slider in the leftmost position.
20052 *
20053 * @example
20054 * // Toggle switches in the 'off' and 'on' position.
20055 * var toggleSwitch1 = new OO.ui.ToggleSwitchWidget();
20056 * var toggleSwitch2 = new OO.ui.ToggleSwitchWidget( {
20057 * value: true
20058 * } );
20059 *
20060 * // Create a FieldsetLayout to layout and label switches
20061 * var fieldset = new OO.ui.FieldsetLayout( {
20062 * label: 'Toggle switches'
20063 * } );
20064 * fieldset.addItems( [
20065 * new OO.ui.FieldLayout( toggleSwitch1, { label: 'Off', align: 'top' } ),
20066 * new OO.ui.FieldLayout( toggleSwitch2, { label: 'On', align: 'top' } )
20067 * ] );
20068 * $( 'body' ).append( fieldset.$element );
20069 *
20070 * @class
20071 * @extends OO.ui.ToggleWidget
20072 * @mixins OO.ui.mixin.TabIndexedElement
20073 *
20074 * @constructor
20075 * @param {Object} [config] Configuration options
20076 * @cfg {boolean} [value=false] The toggle switch’s initial on/off state.
20077 * By default, the toggle switch is in the 'off' position.
20078 */
20079 OO.ui.ToggleSwitchWidget = function OoUiToggleSwitchWidget( config ) {
20080 // Parent constructor
20081 OO.ui.ToggleSwitchWidget.parent.call( this, config );
20082
20083 // Mixin constructors
20084 OO.ui.mixin.TabIndexedElement.call( this, config );
20085
20086 // Properties
20087 this.dragging = false;
20088 this.dragStart = null;
20089 this.sliding = false;
20090 this.$glow = $( '<span>' );
20091 this.$grip = $( '<span>' );
20092
20093 // Events
20094 this.$element.on( {
20095 click: this.onClick.bind( this ),
20096 keypress: this.onKeyPress.bind( this )
20097 } );
20098
20099 // Initialization
20100 this.$glow.addClass( 'oo-ui-toggleSwitchWidget-glow' );
20101 this.$grip.addClass( 'oo-ui-toggleSwitchWidget-grip' );
20102 this.$element
20103 .addClass( 'oo-ui-toggleSwitchWidget' )
20104 .attr( 'role', 'checkbox' )
20105 .append( this.$glow, this.$grip );
20106 };
20107
20108 /* Setup */
20109
20110 OO.inheritClass( OO.ui.ToggleSwitchWidget, OO.ui.ToggleWidget );
20111 OO.mixinClass( OO.ui.ToggleSwitchWidget, OO.ui.mixin.TabIndexedElement );
20112
20113 /* Methods */
20114
20115 /**
20116 * Handle mouse click events.
20117 *
20118 * @private
20119 * @param {jQuery.Event} e Mouse click event
20120 */
20121 OO.ui.ToggleSwitchWidget.prototype.onClick = function ( e ) {
20122 if ( !this.isDisabled() && e.which === OO.ui.MouseButtons.LEFT ) {
20123 this.setValue( !this.value );
20124 }
20125 return false;
20126 };
20127
20128 /**
20129 * Handle key press events.
20130 *
20131 * @private
20132 * @param {jQuery.Event} e Key press event
20133 */
20134 OO.ui.ToggleSwitchWidget.prototype.onKeyPress = function ( e ) {
20135 if ( !this.isDisabled() && ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER ) ) {
20136 this.setValue( !this.value );
20137 return false;
20138 }
20139 };
20140
20141 }( OO ) );