Merge "Set Language in SpecialSearchTest.php"
[lhc/web/wiklou.git] / resources / lib / oojs-ui / oojs-ui.js
1 /*!
2 * OOjs UI v0.14.1
3 * https://www.mediawiki.org/wiki/OOjs_UI
4 *
5 * Copyright 2011–2015 OOjs UI Team and other contributors.
6 * Released under the MIT license
7 * http://oojs.mit-license.org
8 *
9 * Date: 2015-12-08T21:43:47Z
10 */
11 ( function ( OO ) {
12
13 'use strict';
14
15 /**
16 * Namespace for all classes, static methods and static properties.
17 *
18 * @class
19 * @singleton
20 */
21 OO.ui = {};
22
23 OO.ui.bind = $.proxy;
24
25 /**
26 * @property {Object}
27 */
28 OO.ui.Keys = {
29 UNDEFINED: 0,
30 BACKSPACE: 8,
31 DELETE: 46,
32 LEFT: 37,
33 RIGHT: 39,
34 UP: 38,
35 DOWN: 40,
36 ENTER: 13,
37 END: 35,
38 HOME: 36,
39 TAB: 9,
40 PAGEUP: 33,
41 PAGEDOWN: 34,
42 ESCAPE: 27,
43 SHIFT: 16,
44 SPACE: 32
45 };
46
47 /**
48 * @property {Number}
49 */
50 OO.ui.elementId = 0;
51
52 /**
53 * Generate a unique ID for element
54 *
55 * @return {String} [id]
56 */
57 OO.ui.generateElementId = function () {
58 OO.ui.elementId += 1;
59 return 'oojsui-' + OO.ui.elementId;
60 };
61
62 /**
63 * Check if an element is focusable.
64 * Inspired from :focusable in jQueryUI v1.11.4 - 2015-04-14
65 *
66 * @param {jQuery} element Element to test
67 * @return {boolean}
68 */
69 OO.ui.isFocusableElement = function ( $element ) {
70 var nodeName,
71 element = $element[ 0 ];
72
73 // Anything disabled is not focusable
74 if ( element.disabled ) {
75 return false;
76 }
77
78 // Check if the element is visible
79 if ( !(
80 // This is quicker than calling $element.is( ':visible' )
81 $.expr.filters.visible( element ) &&
82 // Check that all parents are visible
83 !$element.parents().addBack().filter( function () {
84 return $.css( this, 'visibility' ) === 'hidden';
85 } ).length
86 ) ) {
87 return false;
88 }
89
90 // Check if the element is ContentEditable, which is the string 'true'
91 if ( element.contentEditable === 'true' ) {
92 return true;
93 }
94
95 // Anything with a non-negative numeric tabIndex is focusable.
96 // Use .prop to avoid browser bugs
97 if ( $element.prop( 'tabIndex' ) >= 0 ) {
98 return true;
99 }
100
101 // Some element types are naturally focusable
102 // (indexOf is much faster than regex in Chrome and about the
103 // same in FF: https://jsperf.com/regex-vs-indexof-array2)
104 nodeName = element.nodeName.toLowerCase();
105 if ( [ 'input', 'select', 'textarea', 'button', 'object' ].indexOf( nodeName ) !== -1 ) {
106 return true;
107 }
108
109 // Links and areas are focusable if they have an href
110 if ( ( nodeName === 'a' || nodeName === 'area' ) && $element.attr( 'href' ) !== undefined ) {
111 return true;
112 }
113
114 return false;
115 };
116
117 /**
118 * Find a focusable child
119 *
120 * @param {jQuery} $container Container to search in
121 * @param {boolean} [backwards] Search backwards
122 * @return {jQuery} Focusable child, an empty jQuery object if none found
123 */
124 OO.ui.findFocusable = function ( $container, backwards ) {
125 var $focusable = $( [] ),
126 // $focusableCandidates is a superset of things that
127 // could get matched by isFocusableElement
128 $focusableCandidates = $container
129 .find( 'input, select, textarea, button, object, a, area, [contenteditable], [tabindex]' );
130
131 if ( backwards ) {
132 $focusableCandidates = Array.prototype.reverse.call( $focusableCandidates );
133 }
134
135 $focusableCandidates.each( function () {
136 var $this = $( this );
137 if ( OO.ui.isFocusableElement( $this ) ) {
138 $focusable = $this;
139 return false;
140 }
141 } );
142 return $focusable;
143 };
144
145 /**
146 * Get the user's language and any fallback languages.
147 *
148 * These language codes are used to localize user interface elements in the user's language.
149 *
150 * In environments that provide a localization system, this function should be overridden to
151 * return the user's language(s). The default implementation returns English (en) only.
152 *
153 * @return {string[]} Language codes, in descending order of priority
154 */
155 OO.ui.getUserLanguages = function () {
156 return [ 'en' ];
157 };
158
159 /**
160 * Get a value in an object keyed by language code.
161 *
162 * @param {Object.<string,Mixed>} obj Object keyed by language code
163 * @param {string|null} [lang] Language code, if omitted or null defaults to any user language
164 * @param {string} [fallback] Fallback code, used if no matching language can be found
165 * @return {Mixed} Local value
166 */
167 OO.ui.getLocalValue = function ( obj, lang, fallback ) {
168 var i, len, langs;
169
170 // Requested language
171 if ( obj[ lang ] ) {
172 return obj[ lang ];
173 }
174 // Known user language
175 langs = OO.ui.getUserLanguages();
176 for ( i = 0, len = langs.length; i < len; i++ ) {
177 lang = langs[ i ];
178 if ( obj[ lang ] ) {
179 return obj[ lang ];
180 }
181 }
182 // Fallback language
183 if ( obj[ fallback ] ) {
184 return obj[ fallback ];
185 }
186 // First existing language
187 for ( lang in obj ) {
188 return obj[ lang ];
189 }
190
191 return undefined;
192 };
193
194 /**
195 * Check if a node is contained within another node
196 *
197 * Similar to jQuery#contains except a list of containers can be supplied
198 * and a boolean argument allows you to include the container in the match list
199 *
200 * @param {HTMLElement|HTMLElement[]} containers Container node(s) to search in
201 * @param {HTMLElement} contained Node to find
202 * @param {boolean} [matchContainers] Include the container(s) in the list of nodes to match, otherwise only match descendants
203 * @return {boolean} The node is in the list of target nodes
204 */
205 OO.ui.contains = function ( containers, contained, matchContainers ) {
206 var i;
207 if ( !Array.isArray( containers ) ) {
208 containers = [ containers ];
209 }
210 for ( i = containers.length - 1; i >= 0; i-- ) {
211 if ( ( matchContainers && contained === containers[ i ] ) || $.contains( containers[ i ], contained ) ) {
212 return true;
213 }
214 }
215 return false;
216 };
217
218 /**
219 * Return a function, that, as long as it continues to be invoked, will not
220 * be triggered. The function will be called after it stops being called for
221 * N milliseconds. If `immediate` is passed, trigger the function on the
222 * leading edge, instead of the trailing.
223 *
224 * Ported from: http://underscorejs.org/underscore.js
225 *
226 * @param {Function} func
227 * @param {number} wait
228 * @param {boolean} immediate
229 * @return {Function}
230 */
231 OO.ui.debounce = function ( func, wait, immediate ) {
232 var timeout;
233 return function () {
234 var context = this,
235 args = arguments,
236 later = function () {
237 timeout = null;
238 if ( !immediate ) {
239 func.apply( context, args );
240 }
241 };
242 if ( immediate && !timeout ) {
243 func.apply( context, args );
244 }
245 clearTimeout( timeout );
246 timeout = setTimeout( later, wait );
247 };
248 };
249
250 /**
251 * Proxy for `node.addEventListener( eventName, handler, true )`, if the browser supports it.
252 * Otherwise falls back to non-capturing event listeners.
253 *
254 * @param {HTMLElement} node
255 * @param {string} eventName
256 * @param {Function} handler
257 */
258 OO.ui.addCaptureEventListener = function ( node, eventName, handler ) {
259 if ( node.addEventListener ) {
260 node.addEventListener( eventName, handler, true );
261 } else {
262 node.attachEvent( 'on' + eventName, handler );
263 }
264 };
265
266 /**
267 * Proxy for `node.removeEventListener( eventName, handler, true )`, if the browser supports it.
268 * Otherwise falls back to non-capturing event listeners.
269 *
270 * @param {HTMLElement} node
271 * @param {string} eventName
272 * @param {Function} handler
273 */
274 OO.ui.removeCaptureEventListener = function ( node, eventName, handler ) {
275 if ( node.addEventListener ) {
276 node.removeEventListener( eventName, handler, true );
277 } else {
278 node.detachEvent( 'on' + eventName, handler );
279 }
280 };
281
282 /**
283 * Reconstitute a JavaScript object corresponding to a widget created by
284 * the PHP implementation.
285 *
286 * This is an alias for `OO.ui.Element.static.infuse()`.
287 *
288 * @param {string|HTMLElement|jQuery} idOrNode
289 * A DOM id (if a string) or node for the widget to infuse.
290 * @return {OO.ui.Element}
291 * The `OO.ui.Element` corresponding to this (infusable) document node.
292 */
293 OO.ui.infuse = function ( idOrNode ) {
294 return OO.ui.Element.static.infuse( idOrNode );
295 };
296
297 ( function () {
298 /**
299 * Message store for the default implementation of OO.ui.msg
300 *
301 * Environments that provide a localization system should not use this, but should override
302 * OO.ui.msg altogether.
303 *
304 * @private
305 */
306 var messages = {
307 // Tool tip for a button that moves items in a list down one place
308 'ooui-outline-control-move-down': 'Move item down',
309 // Tool tip for a button that moves items in a list up one place
310 'ooui-outline-control-move-up': 'Move item up',
311 // Tool tip for a button that removes items from a list
312 'ooui-outline-control-remove': 'Remove item',
313 // Label for the toolbar group that contains a list of all other available tools
314 'ooui-toolbar-more': 'More',
315 // Label for the fake tool that expands the full list of tools in a toolbar group
316 'ooui-toolgroup-expand': 'More',
317 // Label for the fake tool that collapses the full list of tools in a toolbar group
318 'ooui-toolgroup-collapse': 'Fewer',
319 // Default label for the accept button of a confirmation dialog
320 'ooui-dialog-message-accept': 'OK',
321 // Default label for the reject button of a confirmation dialog
322 'ooui-dialog-message-reject': 'Cancel',
323 // Title for process dialog error description
324 'ooui-dialog-process-error': 'Something went wrong',
325 // Label for process dialog dismiss error button, visible when describing errors
326 'ooui-dialog-process-dismiss': 'Dismiss',
327 // Label for process dialog retry action button, visible when describing only recoverable errors
328 'ooui-dialog-process-retry': 'Try again',
329 // Label for process dialog retry action button, visible when describing only warnings
330 'ooui-dialog-process-continue': 'Continue',
331 // Label for the file selection widget's select file button
332 'ooui-selectfile-button-select': 'Select a file',
333 // Label for the file selection widget if file selection is not supported
334 'ooui-selectfile-not-supported': 'File selection is not supported',
335 // Label for the file selection widget when no file is currently selected
336 'ooui-selectfile-placeholder': 'No file is selected',
337 // Label for the file selection widget's drop target
338 'ooui-selectfile-dragdrop-placeholder': 'Drop file here'
339 };
340
341 /**
342 * Get a localized message.
343 *
344 * In environments that provide a localization system, this function should be overridden to
345 * return the message translated in the user's language. The default implementation always returns
346 * English messages.
347 *
348 * After the message key, message parameters may optionally be passed. In the default implementation,
349 * any occurrences of $1 are replaced with the first parameter, $2 with the second parameter, etc.
350 * Alternative implementations of OO.ui.msg may use any substitution system they like, as long as
351 * they support unnamed, ordered message parameters.
352 *
353 * @param {string} key Message key
354 * @param {Mixed...} [params] Message parameters
355 * @return {string} Translated message with parameters substituted
356 */
357 OO.ui.msg = function ( key ) {
358 var message = messages[ key ],
359 params = Array.prototype.slice.call( arguments, 1 );
360 if ( typeof message === 'string' ) {
361 // Perform $1 substitution
362 message = message.replace( /\$(\d+)/g, function ( unused, n ) {
363 var i = parseInt( n, 10 );
364 return params[ i - 1 ] !== undefined ? params[ i - 1 ] : '$' + n;
365 } );
366 } else {
367 // Return placeholder if message not found
368 message = '[' + key + ']';
369 }
370 return message;
371 };
372 } )();
373
374 /**
375 * Package a message and arguments for deferred resolution.
376 *
377 * Use this when you are statically specifying a message and the message may not yet be present.
378 *
379 * @param {string} key Message key
380 * @param {Mixed...} [params] Message parameters
381 * @return {Function} Function that returns the resolved message when executed
382 */
383 OO.ui.deferMsg = function () {
384 var args = arguments;
385 return function () {
386 return OO.ui.msg.apply( OO.ui, args );
387 };
388 };
389
390 /**
391 * Resolve a message.
392 *
393 * If the message is a function it will be executed, otherwise it will pass through directly.
394 *
395 * @param {Function|string} msg Deferred message, or message text
396 * @return {string} Resolved message
397 */
398 OO.ui.resolveMsg = function ( msg ) {
399 if ( $.isFunction( msg ) ) {
400 return msg();
401 }
402 return msg;
403 };
404
405 /**
406 * @param {string} url
407 * @return {boolean}
408 */
409 OO.ui.isSafeUrl = function ( url ) {
410 var protocol,
411 // Keep in sync with php/Tag.php
412 whitelist = [
413 'bitcoin:', 'ftp:', 'ftps:', 'geo:', 'git:', 'gopher:', 'http:', 'https:', 'irc:', 'ircs:',
414 'magnet:', 'mailto:', 'mms:', 'news:', 'nntp:', 'redis:', 'sftp:', 'sip:', 'sips:', 'sms:', 'ssh:',
415 'svn:', 'tel:', 'telnet:', 'urn:', 'worldwind:', 'xmpp:'
416 ];
417
418 if ( url.indexOf( ':' ) === -1 ) {
419 // No protocol, safe
420 return true;
421 }
422
423 protocol = url.split( ':', 1 )[ 0 ] + ':';
424 if ( !protocol.match( /^([A-za-z0-9\+\.\-])+:/ ) ) {
425 // Not a valid protocol, safe
426 return true;
427 }
428
429 // Safe if in the whitelist
430 return whitelist.indexOf( protocol ) !== -1;
431 };
432
433 /**
434 * Lazy-initialize and return a global OO.ui.WindowManager instance, used by OO.ui.alert and
435 * OO.ui.confirm.
436 *
437 * @private
438 * @return {OO.ui.WindowManager}
439 */
440 OO.ui.getWindowManager = function () {
441 if ( !OO.ui.windowManager ) {
442 OO.ui.windowManager = new OO.ui.WindowManager();
443 $( 'body' ).append( OO.ui.windowManager.$element );
444 OO.ui.windowManager.addWindows( {
445 messageDialog: new OO.ui.MessageDialog()
446 } );
447 }
448 return OO.ui.windowManager;
449 };
450
451 /**
452 * Display a quick modal alert dialog, using a OO.ui.MessageDialog. While the dialog is open, the
453 * rest of the page will be dimmed out and the user won't be able to interact with it. The dialog
454 * has only one action button, labelled "OK", clicking it will simply close the dialog.
455 *
456 * A window manager is created automatically when this function is called for the first time.
457 *
458 * @example
459 * OO.ui.alert( 'Something happened!' ).done( function () {
460 * console.log( 'User closed the dialog.' );
461 * } );
462 *
463 * @param {jQuery|string} text Message text to display
464 * @param {Object} [options] Additional options, see OO.ui.MessageDialog#getSetupProcess
465 * @return {jQuery.Promise} Promise resolved when the user closes the dialog
466 */
467 OO.ui.alert = function ( text, options ) {
468 return OO.ui.getWindowManager().openWindow( 'messageDialog', $.extend( {
469 message: text,
470 verbose: true,
471 actions: [ OO.ui.MessageDialog.static.actions[ 0 ] ]
472 }, options ) ).then( function ( opened ) {
473 return opened.then( function ( closing ) {
474 return closing.then( function () {
475 return $.Deferred().resolve();
476 } );
477 } );
478 } );
479 };
480
481 /**
482 * Display a quick modal confirmation dialog, using a OO.ui.MessageDialog. While the dialog is open,
483 * the rest of the page will be dimmed out and the user won't be able to interact with it. The
484 * dialog has two action buttons, one to confirm an operation (labelled "OK") and one to cancel it
485 * (labelled "Cancel").
486 *
487 * A window manager is created automatically when this function is called for the first time.
488 *
489 * @example
490 * OO.ui.confirm( 'Are you sure?' ).done( function ( confirmed ) {
491 * if ( confirmed ) {
492 * console.log( 'User clicked "OK"!' );
493 * } else {
494 * console.log( 'User clicked "Cancel" or closed the dialog.' );
495 * }
496 * } );
497 *
498 * @param {jQuery|string} text Message text to display
499 * @param {Object} [options] Additional options, see OO.ui.MessageDialog#getSetupProcess
500 * @return {jQuery.Promise} Promise resolved when the user closes the dialog. If the user chose to
501 * confirm, the promise will resolve to boolean `true`; otherwise, it will resolve to boolean
502 * `false`.
503 */
504 OO.ui.confirm = function ( text, options ) {
505 return OO.ui.getWindowManager().openWindow( 'messageDialog', $.extend( {
506 message: text,
507 verbose: true
508 }, options ) ).then( function ( opened ) {
509 return opened.then( function ( closing ) {
510 return closing.then( function ( data ) {
511 return $.Deferred().resolve( !!( data && data.action === 'accept' ) );
512 } );
513 } );
514 } );
515 };
516
517 /*!
518 * Mixin namespace.
519 */
520
521 /**
522 * Namespace for OOjs UI mixins.
523 *
524 * Mixins are named according to the type of object they are intended to
525 * be mixed in to. For example, OO.ui.mixin.GroupElement is intended to be
526 * mixed in to an instance of OO.ui.Element, and OO.ui.mixin.GroupWidget
527 * is intended to be mixed in to an instance of OO.ui.Widget.
528 *
529 * @class
530 * @singleton
531 */
532 OO.ui.mixin = {};
533
534 /**
535 * PendingElement is a mixin that is used to create elements that notify users that something is happening
536 * and that they should wait before proceeding. The pending state is visually represented with a pending
537 * texture that appears in the head of a pending {@link OO.ui.ProcessDialog process dialog} or in the input
538 * field of a {@link OO.ui.TextInputWidget text input widget}.
539 *
540 * Currently, {@link OO.ui.ActionWidget Action widgets}, which mix in this class, can also be marked as pending, but only when
541 * used in {@link OO.ui.MessageDialog message dialogs}. The behavior is not currently supported for action widgets used
542 * in process dialogs.
543 *
544 * @example
545 * function MessageDialog( config ) {
546 * MessageDialog.parent.call( this, config );
547 * }
548 * OO.inheritClass( MessageDialog, OO.ui.MessageDialog );
549 *
550 * MessageDialog.static.actions = [
551 * { action: 'save', label: 'Done', flags: 'primary' },
552 * { label: 'Cancel', flags: 'safe' }
553 * ];
554 *
555 * MessageDialog.prototype.initialize = function () {
556 * MessageDialog.parent.prototype.initialize.apply( this, arguments );
557 * this.content = new OO.ui.PanelLayout( { $: this.$, padded: true } );
558 * 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>' );
559 * this.$body.append( this.content.$element );
560 * };
561 * MessageDialog.prototype.getBodyHeight = function () {
562 * return 100;
563 * }
564 * MessageDialog.prototype.getActionProcess = function ( action ) {
565 * var dialog = this;
566 * if ( action === 'save' ) {
567 * dialog.getActions().get({actions: 'save'})[0].pushPending();
568 * return new OO.ui.Process()
569 * .next( 1000 )
570 * .next( function () {
571 * dialog.getActions().get({actions: 'save'})[0].popPending();
572 * } );
573 * }
574 * return MessageDialog.parent.prototype.getActionProcess.call( this, action );
575 * };
576 *
577 * var windowManager = new OO.ui.WindowManager();
578 * $( 'body' ).append( windowManager.$element );
579 *
580 * var dialog = new MessageDialog();
581 * windowManager.addWindows( [ dialog ] );
582 * windowManager.openWindow( dialog );
583 *
584 * @abstract
585 * @class
586 *
587 * @constructor
588 * @param {Object} [config] Configuration options
589 * @cfg {jQuery} [$pending] Element to mark as pending, defaults to this.$element
590 */
591 OO.ui.mixin.PendingElement = function OoUiMixinPendingElement( config ) {
592 // Configuration initialization
593 config = config || {};
594
595 // Properties
596 this.pending = 0;
597 this.$pending = null;
598
599 // Initialisation
600 this.setPendingElement( config.$pending || this.$element );
601 };
602
603 /* Setup */
604
605 OO.initClass( OO.ui.mixin.PendingElement );
606
607 /* Methods */
608
609 /**
610 * Set the pending element (and clean up any existing one).
611 *
612 * @param {jQuery} $pending The element to set to pending.
613 */
614 OO.ui.mixin.PendingElement.prototype.setPendingElement = function ( $pending ) {
615 if ( this.$pending ) {
616 this.$pending.removeClass( 'oo-ui-pendingElement-pending' );
617 }
618
619 this.$pending = $pending;
620 if ( this.pending > 0 ) {
621 this.$pending.addClass( 'oo-ui-pendingElement-pending' );
622 }
623 };
624
625 /**
626 * Check if an element is pending.
627 *
628 * @return {boolean} Element is pending
629 */
630 OO.ui.mixin.PendingElement.prototype.isPending = function () {
631 return !!this.pending;
632 };
633
634 /**
635 * Increase the pending counter. The pending state will remain active until the counter is zero
636 * (i.e., the number of calls to #pushPending and #popPending is the same).
637 *
638 * @chainable
639 */
640 OO.ui.mixin.PendingElement.prototype.pushPending = function () {
641 if ( this.pending === 0 ) {
642 this.$pending.addClass( 'oo-ui-pendingElement-pending' );
643 this.updateThemeClasses();
644 }
645 this.pending++;
646
647 return this;
648 };
649
650 /**
651 * Decrease the pending counter. The pending state will remain active until the counter is zero
652 * (i.e., the number of calls to #pushPending and #popPending is the same).
653 *
654 * @chainable
655 */
656 OO.ui.mixin.PendingElement.prototype.popPending = function () {
657 if ( this.pending === 1 ) {
658 this.$pending.removeClass( 'oo-ui-pendingElement-pending' );
659 this.updateThemeClasses();
660 }
661 this.pending = Math.max( 0, this.pending - 1 );
662
663 return this;
664 };
665
666 /**
667 * ActionSets manage the behavior of the {@link OO.ui.ActionWidget action widgets} that comprise them.
668 * Actions can be made available for specific contexts (modes) and circumstances
669 * (abilities). Action sets are primarily used with {@link OO.ui.Dialog Dialogs}.
670 *
671 * ActionSets contain two types of actions:
672 *
673 * - 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.
674 * - Other: Other actions include all non-special visible actions.
675 *
676 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
677 *
678 * @example
679 * // Example: An action set used in a process dialog
680 * function MyProcessDialog( config ) {
681 * MyProcessDialog.parent.call( this, config );
682 * }
683 * OO.inheritClass( MyProcessDialog, OO.ui.ProcessDialog );
684 * MyProcessDialog.static.title = 'An action set in a process dialog';
685 * // An action set that uses modes ('edit' and 'help' mode, in this example).
686 * MyProcessDialog.static.actions = [
687 * { action: 'continue', modes: 'edit', label: 'Continue', flags: [ 'primary', 'constructive' ] },
688 * { action: 'help', modes: 'edit', label: 'Help' },
689 * { modes: 'edit', label: 'Cancel', flags: 'safe' },
690 * { action: 'back', modes: 'help', label: 'Back', flags: 'safe' }
691 * ];
692 *
693 * MyProcessDialog.prototype.initialize = function () {
694 * MyProcessDialog.parent.prototype.initialize.apply( this, arguments );
695 * this.panel1 = new OO.ui.PanelLayout( { padded: true, expanded: false } );
696 * 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>' );
697 * this.panel2 = new OO.ui.PanelLayout( { padded: true, expanded: false } );
698 * 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>' );
699 * this.stackLayout = new OO.ui.StackLayout( {
700 * items: [ this.panel1, this.panel2 ]
701 * } );
702 * this.$body.append( this.stackLayout.$element );
703 * };
704 * MyProcessDialog.prototype.getSetupProcess = function ( data ) {
705 * return MyProcessDialog.parent.prototype.getSetupProcess.call( this, data )
706 * .next( function () {
707 * this.actions.setMode( 'edit' );
708 * }, this );
709 * };
710 * MyProcessDialog.prototype.getActionProcess = function ( action ) {
711 * if ( action === 'help' ) {
712 * this.actions.setMode( 'help' );
713 * this.stackLayout.setItem( this.panel2 );
714 * } else if ( action === 'back' ) {
715 * this.actions.setMode( 'edit' );
716 * this.stackLayout.setItem( this.panel1 );
717 * } else if ( action === 'continue' ) {
718 * var dialog = this;
719 * return new OO.ui.Process( function () {
720 * dialog.close();
721 * } );
722 * }
723 * return MyProcessDialog.parent.prototype.getActionProcess.call( this, action );
724 * };
725 * MyProcessDialog.prototype.getBodyHeight = function () {
726 * return this.panel1.$element.outerHeight( true );
727 * };
728 * var windowManager = new OO.ui.WindowManager();
729 * $( 'body' ).append( windowManager.$element );
730 * var dialog = new MyProcessDialog( {
731 * size: 'medium'
732 * } );
733 * windowManager.addWindows( [ dialog ] );
734 * windowManager.openWindow( dialog );
735 *
736 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Action_sets
737 *
738 * @abstract
739 * @class
740 * @mixins OO.EventEmitter
741 *
742 * @constructor
743 * @param {Object} [config] Configuration options
744 */
745 OO.ui.ActionSet = function OoUiActionSet( config ) {
746 // Configuration initialization
747 config = config || {};
748
749 // Mixin constructors
750 OO.EventEmitter.call( this );
751
752 // Properties
753 this.list = [];
754 this.categories = {
755 actions: 'getAction',
756 flags: 'getFlags',
757 modes: 'getModes'
758 };
759 this.categorized = {};
760 this.special = {};
761 this.others = [];
762 this.organized = false;
763 this.changing = false;
764 this.changed = false;
765 };
766
767 /* Setup */
768
769 OO.mixinClass( OO.ui.ActionSet, OO.EventEmitter );
770
771 /* Static Properties */
772
773 /**
774 * Symbolic name of the flags used to identify special actions. Special actions are displayed in the
775 * header of a {@link OO.ui.ProcessDialog process dialog}.
776 * See the [OOjs UI documentation on MediaWiki][2] for more information and examples.
777 *
778 * [2]:https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs
779 *
780 * @abstract
781 * @static
782 * @inheritable
783 * @property {string}
784 */
785 OO.ui.ActionSet.static.specialFlags = [ 'safe', 'primary' ];
786
787 /* Events */
788
789 /**
790 * @event click
791 *
792 * A 'click' event is emitted when an action is clicked.
793 *
794 * @param {OO.ui.ActionWidget} action Action that was clicked
795 */
796
797 /**
798 * @event resize
799 *
800 * A 'resize' event is emitted when an action widget is resized.
801 *
802 * @param {OO.ui.ActionWidget} action Action that was resized
803 */
804
805 /**
806 * @event add
807 *
808 * An 'add' event is emitted when actions are {@link #method-add added} to the action set.
809 *
810 * @param {OO.ui.ActionWidget[]} added Actions added
811 */
812
813 /**
814 * @event remove
815 *
816 * A 'remove' event is emitted when actions are {@link #method-remove removed}
817 * or {@link #clear cleared}.
818 *
819 * @param {OO.ui.ActionWidget[]} added Actions removed
820 */
821
822 /**
823 * @event change
824 *
825 * A 'change' event is emitted when actions are {@link #method-add added}, {@link #clear cleared},
826 * or {@link #method-remove removed} from the action set or when the {@link #setMode mode} is changed.
827 *
828 */
829
830 /* Methods */
831
832 /**
833 * Handle action change events.
834 *
835 * @private
836 * @fires change
837 */
838 OO.ui.ActionSet.prototype.onActionChange = function () {
839 this.organized = false;
840 if ( this.changing ) {
841 this.changed = true;
842 } else {
843 this.emit( 'change' );
844 }
845 };
846
847 /**
848 * Check if an action is one of the special actions.
849 *
850 * @param {OO.ui.ActionWidget} action Action to check
851 * @return {boolean} Action is special
852 */
853 OO.ui.ActionSet.prototype.isSpecial = function ( action ) {
854 var flag;
855
856 for ( flag in this.special ) {
857 if ( action === this.special[ flag ] ) {
858 return true;
859 }
860 }
861
862 return false;
863 };
864
865 /**
866 * Get action widgets based on the specified filter: ‘actions’, ‘flags’, ‘modes’, ‘visible’,
867 * or ‘disabled’.
868 *
869 * @param {Object} [filters] Filters to use, omit to get all actions
870 * @param {string|string[]} [filters.actions] Actions that action widgets must have
871 * @param {string|string[]} [filters.flags] Flags that action widgets must have (e.g., 'safe')
872 * @param {string|string[]} [filters.modes] Modes that action widgets must have
873 * @param {boolean} [filters.visible] Action widgets must be visible
874 * @param {boolean} [filters.disabled] Action widgets must be disabled
875 * @return {OO.ui.ActionWidget[]} Action widgets matching all criteria
876 */
877 OO.ui.ActionSet.prototype.get = function ( filters ) {
878 var i, len, list, category, actions, index, match, matches;
879
880 if ( filters ) {
881 this.organize();
882
883 // Collect category candidates
884 matches = [];
885 for ( category in this.categorized ) {
886 list = filters[ category ];
887 if ( list ) {
888 if ( !Array.isArray( list ) ) {
889 list = [ list ];
890 }
891 for ( i = 0, len = list.length; i < len; i++ ) {
892 actions = this.categorized[ category ][ list[ i ] ];
893 if ( Array.isArray( actions ) ) {
894 matches.push.apply( matches, actions );
895 }
896 }
897 }
898 }
899 // Remove by boolean filters
900 for ( i = 0, len = matches.length; i < len; i++ ) {
901 match = matches[ i ];
902 if (
903 ( filters.visible !== undefined && match.isVisible() !== filters.visible ) ||
904 ( filters.disabled !== undefined && match.isDisabled() !== filters.disabled )
905 ) {
906 matches.splice( i, 1 );
907 len--;
908 i--;
909 }
910 }
911 // Remove duplicates
912 for ( i = 0, len = matches.length; i < len; i++ ) {
913 match = matches[ i ];
914 index = matches.lastIndexOf( match );
915 while ( index !== i ) {
916 matches.splice( index, 1 );
917 len--;
918 index = matches.lastIndexOf( match );
919 }
920 }
921 return matches;
922 }
923 return this.list.slice();
924 };
925
926 /**
927 * Get 'special' actions.
928 *
929 * Special actions are the first visible action widgets with special flags, such as 'safe' and 'primary'.
930 * Special flags can be configured in subclasses by changing the static #specialFlags property.
931 *
932 * @return {OO.ui.ActionWidget[]|null} 'Special' action widgets.
933 */
934 OO.ui.ActionSet.prototype.getSpecial = function () {
935 this.organize();
936 return $.extend( {}, this.special );
937 };
938
939 /**
940 * Get 'other' actions.
941 *
942 * Other actions include all non-special visible action widgets.
943 *
944 * @return {OO.ui.ActionWidget[]} 'Other' action widgets
945 */
946 OO.ui.ActionSet.prototype.getOthers = function () {
947 this.organize();
948 return this.others.slice();
949 };
950
951 /**
952 * Set the mode (e.g., ‘edit’ or ‘view’). Only {@link OO.ui.ActionWidget#modes actions} configured
953 * to be available in the specified mode will be made visible. All other actions will be hidden.
954 *
955 * @param {string} mode The mode. Only actions configured to be available in the specified
956 * mode will be made visible.
957 * @chainable
958 * @fires toggle
959 * @fires change
960 */
961 OO.ui.ActionSet.prototype.setMode = function ( mode ) {
962 var i, len, action;
963
964 this.changing = true;
965 for ( i = 0, len = this.list.length; i < len; i++ ) {
966 action = this.list[ i ];
967 action.toggle( action.hasMode( mode ) );
968 }
969
970 this.organized = false;
971 this.changing = false;
972 this.emit( 'change' );
973
974 return this;
975 };
976
977 /**
978 * Set the abilities of the specified actions.
979 *
980 * Action widgets that are configured with the specified actions will be enabled
981 * or disabled based on the boolean values specified in the `actions`
982 * parameter.
983 *
984 * @param {Object.<string,boolean>} actions A list keyed by action name with boolean
985 * values that indicate whether or not the action should be enabled.
986 * @chainable
987 */
988 OO.ui.ActionSet.prototype.setAbilities = function ( actions ) {
989 var i, len, action, item;
990
991 for ( i = 0, len = this.list.length; i < len; i++ ) {
992 item = this.list[ i ];
993 action = item.getAction();
994 if ( actions[ action ] !== undefined ) {
995 item.setDisabled( !actions[ action ] );
996 }
997 }
998
999 return this;
1000 };
1001
1002 /**
1003 * Executes a function once per action.
1004 *
1005 * When making changes to multiple actions, use this method instead of iterating over the actions
1006 * manually to defer emitting a #change event until after all actions have been changed.
1007 *
1008 * @param {Object|null} actions Filters to use to determine which actions to iterate over; see #get
1009 * @param {Function} callback Callback to run for each action; callback is invoked with three
1010 * arguments: the action, the action's index, the list of actions being iterated over
1011 * @chainable
1012 */
1013 OO.ui.ActionSet.prototype.forEach = function ( filter, callback ) {
1014 this.changed = false;
1015 this.changing = true;
1016 this.get( filter ).forEach( callback );
1017 this.changing = false;
1018 if ( this.changed ) {
1019 this.emit( 'change' );
1020 }
1021
1022 return this;
1023 };
1024
1025 /**
1026 * Add action widgets to the action set.
1027 *
1028 * @param {OO.ui.ActionWidget[]} actions Action widgets to add
1029 * @chainable
1030 * @fires add
1031 * @fires change
1032 */
1033 OO.ui.ActionSet.prototype.add = function ( actions ) {
1034 var i, len, action;
1035
1036 this.changing = true;
1037 for ( i = 0, len = actions.length; i < len; i++ ) {
1038 action = actions[ i ];
1039 action.connect( this, {
1040 click: [ 'emit', 'click', action ],
1041 resize: [ 'emit', 'resize', action ],
1042 toggle: [ 'onActionChange' ]
1043 } );
1044 this.list.push( action );
1045 }
1046 this.organized = false;
1047 this.emit( 'add', actions );
1048 this.changing = false;
1049 this.emit( 'change' );
1050
1051 return this;
1052 };
1053
1054 /**
1055 * Remove action widgets from the set.
1056 *
1057 * To remove all actions, you may wish to use the #clear method instead.
1058 *
1059 * @param {OO.ui.ActionWidget[]} actions Action widgets to remove
1060 * @chainable
1061 * @fires remove
1062 * @fires change
1063 */
1064 OO.ui.ActionSet.prototype.remove = function ( actions ) {
1065 var i, len, index, action;
1066
1067 this.changing = true;
1068 for ( i = 0, len = actions.length; i < len; i++ ) {
1069 action = actions[ i ];
1070 index = this.list.indexOf( action );
1071 if ( index !== -1 ) {
1072 action.disconnect( this );
1073 this.list.splice( index, 1 );
1074 }
1075 }
1076 this.organized = false;
1077 this.emit( 'remove', actions );
1078 this.changing = false;
1079 this.emit( 'change' );
1080
1081 return this;
1082 };
1083
1084 /**
1085 * Remove all action widets from the set.
1086 *
1087 * To remove only specified actions, use the {@link #method-remove remove} method instead.
1088 *
1089 * @chainable
1090 * @fires remove
1091 * @fires change
1092 */
1093 OO.ui.ActionSet.prototype.clear = function () {
1094 var i, len, action,
1095 removed = this.list.slice();
1096
1097 this.changing = true;
1098 for ( i = 0, len = this.list.length; i < len; i++ ) {
1099 action = this.list[ i ];
1100 action.disconnect( this );
1101 }
1102
1103 this.list = [];
1104
1105 this.organized = false;
1106 this.emit( 'remove', removed );
1107 this.changing = false;
1108 this.emit( 'change' );
1109
1110 return this;
1111 };
1112
1113 /**
1114 * Organize actions.
1115 *
1116 * This is called whenever organized information is requested. It will only reorganize the actions
1117 * if something has changed since the last time it ran.
1118 *
1119 * @private
1120 * @chainable
1121 */
1122 OO.ui.ActionSet.prototype.organize = function () {
1123 var i, iLen, j, jLen, flag, action, category, list, item, special,
1124 specialFlags = this.constructor.static.specialFlags;
1125
1126 if ( !this.organized ) {
1127 this.categorized = {};
1128 this.special = {};
1129 this.others = [];
1130 for ( i = 0, iLen = this.list.length; i < iLen; i++ ) {
1131 action = this.list[ i ];
1132 if ( action.isVisible() ) {
1133 // Populate categories
1134 for ( category in this.categories ) {
1135 if ( !this.categorized[ category ] ) {
1136 this.categorized[ category ] = {};
1137 }
1138 list = action[ this.categories[ category ] ]();
1139 if ( !Array.isArray( list ) ) {
1140 list = [ list ];
1141 }
1142 for ( j = 0, jLen = list.length; j < jLen; j++ ) {
1143 item = list[ j ];
1144 if ( !this.categorized[ category ][ item ] ) {
1145 this.categorized[ category ][ item ] = [];
1146 }
1147 this.categorized[ category ][ item ].push( action );
1148 }
1149 }
1150 // Populate special/others
1151 special = false;
1152 for ( j = 0, jLen = specialFlags.length; j < jLen; j++ ) {
1153 flag = specialFlags[ j ];
1154 if ( !this.special[ flag ] && action.hasFlag( flag ) ) {
1155 this.special[ flag ] = action;
1156 special = true;
1157 break;
1158 }
1159 }
1160 if ( !special ) {
1161 this.others.push( action );
1162 }
1163 }
1164 }
1165 this.organized = true;
1166 }
1167
1168 return this;
1169 };
1170
1171 /**
1172 * Each Element represents a rendering in the DOM—a button or an icon, for example, or anything
1173 * that is visible to a user. Unlike {@link OO.ui.Widget widgets}, plain elements usually do not have events
1174 * connected to them and can't be interacted with.
1175 *
1176 * @abstract
1177 * @class
1178 *
1179 * @constructor
1180 * @param {Object} [config] Configuration options
1181 * @cfg {string[]} [classes] The names of the CSS classes to apply to the element. CSS styles are added
1182 * to the top level (e.g., the outermost div) of the element. See the [OOjs UI documentation on MediaWiki][2]
1183 * for an example.
1184 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#cssExample
1185 * @cfg {string} [id] The HTML id attribute used in the rendered tag.
1186 * @cfg {string} [text] Text to insert
1187 * @cfg {Array} [content] An array of content elements to append (after #text).
1188 * Strings will be html-escaped; use an OO.ui.HtmlSnippet to append raw HTML.
1189 * Instances of OO.ui.Element will have their $element appended.
1190 * @cfg {jQuery} [$content] Content elements to append (after #text).
1191 * @cfg {jQuery} [$element] Wrapper element. Defaults to a new element with #getTagName.
1192 * @cfg {Mixed} [data] Custom data of any type or combination of types (e.g., string, number, array, object).
1193 * Data can also be specified with the #setData method.
1194 */
1195 OO.ui.Element = function OoUiElement( config ) {
1196 // Configuration initialization
1197 config = config || {};
1198
1199 // Properties
1200 this.$ = $;
1201 this.visible = true;
1202 this.data = config.data;
1203 this.$element = config.$element ||
1204 $( document.createElement( this.getTagName() ) );
1205 this.elementGroup = null;
1206 this.debouncedUpdateThemeClassesHandler = OO.ui.debounce( this.debouncedUpdateThemeClasses );
1207
1208 // Initialization
1209 if ( Array.isArray( config.classes ) ) {
1210 this.$element.addClass( config.classes.join( ' ' ) );
1211 }
1212 if ( config.id ) {
1213 this.$element.attr( 'id', config.id );
1214 }
1215 if ( config.text ) {
1216 this.$element.text( config.text );
1217 }
1218 if ( config.content ) {
1219 // The `content` property treats plain strings as text; use an
1220 // HtmlSnippet to append HTML content. `OO.ui.Element`s get their
1221 // appropriate $element appended.
1222 this.$element.append( config.content.map( function ( v ) {
1223 if ( typeof v === 'string' ) {
1224 // Escape string so it is properly represented in HTML.
1225 return document.createTextNode( v );
1226 } else if ( v instanceof OO.ui.HtmlSnippet ) {
1227 // Bypass escaping.
1228 return v.toString();
1229 } else if ( v instanceof OO.ui.Element ) {
1230 return v.$element;
1231 }
1232 return v;
1233 } ) );
1234 }
1235 if ( config.$content ) {
1236 // The `$content` property treats plain strings as HTML.
1237 this.$element.append( config.$content );
1238 }
1239 };
1240
1241 /* Setup */
1242
1243 OO.initClass( OO.ui.Element );
1244
1245 /* Static Properties */
1246
1247 /**
1248 * The name of the HTML tag used by the element.
1249 *
1250 * The static value may be ignored if the #getTagName method is overridden.
1251 *
1252 * @static
1253 * @inheritable
1254 * @property {string}
1255 */
1256 OO.ui.Element.static.tagName = 'div';
1257
1258 /* Static Methods */
1259
1260 /**
1261 * Reconstitute a JavaScript object corresponding to a widget created
1262 * by the PHP implementation.
1263 *
1264 * @param {string|HTMLElement|jQuery} idOrNode
1265 * A DOM id (if a string) or node for the widget to infuse.
1266 * @return {OO.ui.Element}
1267 * The `OO.ui.Element` corresponding to this (infusable) document node.
1268 * For `Tag` objects emitted on the HTML side (used occasionally for content)
1269 * the value returned is a newly-created Element wrapping around the existing
1270 * DOM node.
1271 */
1272 OO.ui.Element.static.infuse = function ( idOrNode ) {
1273 var obj = OO.ui.Element.static.unsafeInfuse( idOrNode, false );
1274 // Verify that the type matches up.
1275 // FIXME: uncomment after T89721 is fixed (see T90929)
1276 /*
1277 if ( !( obj instanceof this['class'] ) ) {
1278 throw new Error( 'Infusion type mismatch!' );
1279 }
1280 */
1281 return obj;
1282 };
1283
1284 /**
1285 * Implementation helper for `infuse`; skips the type check and has an
1286 * extra property so that only the top-level invocation touches the DOM.
1287 * @private
1288 * @param {string|HTMLElement|jQuery} idOrNode
1289 * @param {jQuery.Promise|boolean} domPromise A promise that will be resolved
1290 * when the top-level widget of this infusion is inserted into DOM,
1291 * replacing the original node; or false for top-level invocation.
1292 * @return {OO.ui.Element}
1293 */
1294 OO.ui.Element.static.unsafeInfuse = function ( idOrNode, domPromise ) {
1295 // look for a cached result of a previous infusion.
1296 var id, $elem, data, cls, parts, parent, obj, top, state;
1297 if ( typeof idOrNode === 'string' ) {
1298 id = idOrNode;
1299 $elem = $( document.getElementById( id ) );
1300 } else {
1301 $elem = $( idOrNode );
1302 id = $elem.attr( 'id' );
1303 }
1304 if ( !$elem.length ) {
1305 throw new Error( 'Widget not found: ' + id );
1306 }
1307 data = $elem.data( 'ooui-infused' ) || $elem[ 0 ].oouiInfused;
1308 if ( data ) {
1309 // cached!
1310 if ( data === true ) {
1311 throw new Error( 'Circular dependency! ' + id );
1312 }
1313 return data;
1314 }
1315 data = $elem.attr( 'data-ooui' );
1316 if ( !data ) {
1317 throw new Error( 'No infusion data found: ' + id );
1318 }
1319 try {
1320 data = $.parseJSON( data );
1321 } catch ( _ ) {
1322 data = null;
1323 }
1324 if ( !( data && data._ ) ) {
1325 throw new Error( 'No valid infusion data found: ' + id );
1326 }
1327 if ( data._ === 'Tag' ) {
1328 // Special case: this is a raw Tag; wrap existing node, don't rebuild.
1329 return new OO.ui.Element( { $element: $elem } );
1330 }
1331 parts = data._.split( '.' );
1332 cls = OO.getProp.apply( OO, [ window ].concat( parts ) );
1333 if ( cls === undefined ) {
1334 // The PHP output might be old and not including the "OO.ui" prefix
1335 // TODO: Remove this back-compat after next major release
1336 cls = OO.getProp.apply( OO, [ OO.ui ].concat( parts ) );
1337 if ( cls === undefined ) {
1338 throw new Error( 'Unknown widget type: id: ' + id + ', class: ' + data._ );
1339 }
1340 }
1341
1342 // Verify that we're creating an OO.ui.Element instance
1343 parent = cls.parent;
1344
1345 while ( parent !== undefined ) {
1346 if ( parent === OO.ui.Element ) {
1347 // Safe
1348 break;
1349 }
1350
1351 parent = parent.parent;
1352 }
1353
1354 if ( parent !== OO.ui.Element ) {
1355 throw new Error( 'Unknown widget type: id: ' + id + ', class: ' + data._ );
1356 }
1357
1358 if ( domPromise === false ) {
1359 top = $.Deferred();
1360 domPromise = top.promise();
1361 }
1362 $elem.data( 'ooui-infused', true ); // prevent loops
1363 data.id = id; // implicit
1364 data = OO.copy( data, null, function deserialize( value ) {
1365 if ( OO.isPlainObject( value ) ) {
1366 if ( value.tag ) {
1367 return OO.ui.Element.static.unsafeInfuse( value.tag, domPromise );
1368 }
1369 if ( value.html ) {
1370 return new OO.ui.HtmlSnippet( value.html );
1371 }
1372 }
1373 } );
1374 // allow widgets to reuse parts of the DOM
1375 data = cls.static.reusePreInfuseDOM( $elem[ 0 ], data );
1376 // pick up dynamic state, like focus, value of form inputs, scroll position, etc.
1377 state = cls.static.gatherPreInfuseState( $elem[ 0 ], data );
1378 // rebuild widget
1379 // jscs:disable requireCapitalizedConstructors
1380 obj = new cls( data );
1381 // jscs:enable requireCapitalizedConstructors
1382 // now replace old DOM with this new DOM.
1383 if ( top ) {
1384 // An efficient constructor might be able to reuse the entire DOM tree of the original element,
1385 // so only mutate the DOM if we need to.
1386 if ( $elem[ 0 ] !== obj.$element[ 0 ] ) {
1387 $elem.replaceWith( obj.$element );
1388 // This element is now gone from the DOM, but if anyone is holding a reference to it,
1389 // let's allow them to OO.ui.infuse() it and do what they expect (T105828).
1390 // Do not use jQuery.data(), as using it on detached nodes leaks memory in 1.x line by design.
1391 $elem[ 0 ].oouiInfused = obj;
1392 }
1393 top.resolve();
1394 }
1395 obj.$element.data( 'ooui-infused', obj );
1396 // set the 'data-ooui' attribute so we can identify infused widgets
1397 obj.$element.attr( 'data-ooui', '' );
1398 // restore dynamic state after the new element is inserted into DOM
1399 domPromise.done( obj.restorePreInfuseState.bind( obj, state ) );
1400 return obj;
1401 };
1402
1403 /**
1404 * Pick out parts of `node`'s DOM to be reused when infusing a widget.
1405 *
1406 * This method **must not** make any changes to the DOM, only find interesting pieces and add them
1407 * to `config` (which should then be returned). Actual DOM juggling should then be done by the
1408 * constructor, which will be given the enhanced config.
1409 *
1410 * @protected
1411 * @param {HTMLElement} node
1412 * @param {Object} config
1413 * @return {Object}
1414 */
1415 OO.ui.Element.static.reusePreInfuseDOM = function ( node, config ) {
1416 return config;
1417 };
1418
1419 /**
1420 * Gather the dynamic state (focus, value of form inputs, scroll position, etc.) of a HTML DOM node
1421 * (and its children) that represent an Element of the same class and the given configuration,
1422 * generated by the PHP implementation.
1423 *
1424 * This method is called just before `node` is detached from the DOM. The return value of this
1425 * function will be passed to #restorePreInfuseState after the newly created widget's #$element
1426 * is inserted into DOM to replace `node`.
1427 *
1428 * @protected
1429 * @param {HTMLElement} node
1430 * @param {Object} config
1431 * @return {Object}
1432 */
1433 OO.ui.Element.static.gatherPreInfuseState = function () {
1434 return {};
1435 };
1436
1437 /**
1438 * Get a jQuery function within a specific document.
1439 *
1440 * @static
1441 * @param {jQuery|HTMLElement|HTMLDocument|Window} context Context to bind the function to
1442 * @param {jQuery} [$iframe] HTML iframe element that contains the document, omit if document is
1443 * not in an iframe
1444 * @return {Function} Bound jQuery function
1445 */
1446 OO.ui.Element.static.getJQuery = function ( context, $iframe ) {
1447 function wrapper( selector ) {
1448 return $( selector, wrapper.context );
1449 }
1450
1451 wrapper.context = this.getDocument( context );
1452
1453 if ( $iframe ) {
1454 wrapper.$iframe = $iframe;
1455 }
1456
1457 return wrapper;
1458 };
1459
1460 /**
1461 * Get the document of an element.
1462 *
1463 * @static
1464 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Object to get the document for
1465 * @return {HTMLDocument|null} Document object
1466 */
1467 OO.ui.Element.static.getDocument = function ( obj ) {
1468 // jQuery - selections created "offscreen" won't have a context, so .context isn't reliable
1469 return ( obj[ 0 ] && obj[ 0 ].ownerDocument ) ||
1470 // Empty jQuery selections might have a context
1471 obj.context ||
1472 // HTMLElement
1473 obj.ownerDocument ||
1474 // Window
1475 obj.document ||
1476 // HTMLDocument
1477 ( obj.nodeType === 9 && obj ) ||
1478 null;
1479 };
1480
1481 /**
1482 * Get the window of an element or document.
1483 *
1484 * @static
1485 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the window for
1486 * @return {Window} Window object
1487 */
1488 OO.ui.Element.static.getWindow = function ( obj ) {
1489 var doc = this.getDocument( obj );
1490 // Support: IE 8
1491 // Standard Document.defaultView is IE9+
1492 return doc.parentWindow || doc.defaultView;
1493 };
1494
1495 /**
1496 * Get the direction of an element or document.
1497 *
1498 * @static
1499 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the direction for
1500 * @return {string} Text direction, either 'ltr' or 'rtl'
1501 */
1502 OO.ui.Element.static.getDir = function ( obj ) {
1503 var isDoc, isWin;
1504
1505 if ( obj instanceof jQuery ) {
1506 obj = obj[ 0 ];
1507 }
1508 isDoc = obj.nodeType === 9;
1509 isWin = obj.document !== undefined;
1510 if ( isDoc || isWin ) {
1511 if ( isWin ) {
1512 obj = obj.document;
1513 }
1514 obj = obj.body;
1515 }
1516 return $( obj ).css( 'direction' );
1517 };
1518
1519 /**
1520 * Get the offset between two frames.
1521 *
1522 * TODO: Make this function not use recursion.
1523 *
1524 * @static
1525 * @param {Window} from Window of the child frame
1526 * @param {Window} [to=window] Window of the parent frame
1527 * @param {Object} [offset] Offset to start with, used internally
1528 * @return {Object} Offset object, containing left and top properties
1529 */
1530 OO.ui.Element.static.getFrameOffset = function ( from, to, offset ) {
1531 var i, len, frames, frame, rect;
1532
1533 if ( !to ) {
1534 to = window;
1535 }
1536 if ( !offset ) {
1537 offset = { top: 0, left: 0 };
1538 }
1539 if ( from.parent === from ) {
1540 return offset;
1541 }
1542
1543 // Get iframe element
1544 frames = from.parent.document.getElementsByTagName( 'iframe' );
1545 for ( i = 0, len = frames.length; i < len; i++ ) {
1546 if ( frames[ i ].contentWindow === from ) {
1547 frame = frames[ i ];
1548 break;
1549 }
1550 }
1551
1552 // Recursively accumulate offset values
1553 if ( frame ) {
1554 rect = frame.getBoundingClientRect();
1555 offset.left += rect.left;
1556 offset.top += rect.top;
1557 if ( from !== to ) {
1558 this.getFrameOffset( from.parent, offset );
1559 }
1560 }
1561 return offset;
1562 };
1563
1564 /**
1565 * Get the offset between two elements.
1566 *
1567 * The two elements may be in a different frame, but in that case the frame $element is in must
1568 * be contained in the frame $anchor is in.
1569 *
1570 * @static
1571 * @param {jQuery} $element Element whose position to get
1572 * @param {jQuery} $anchor Element to get $element's position relative to
1573 * @return {Object} Translated position coordinates, containing top and left properties
1574 */
1575 OO.ui.Element.static.getRelativePosition = function ( $element, $anchor ) {
1576 var iframe, iframePos,
1577 pos = $element.offset(),
1578 anchorPos = $anchor.offset(),
1579 elementDocument = this.getDocument( $element ),
1580 anchorDocument = this.getDocument( $anchor );
1581
1582 // If $element isn't in the same document as $anchor, traverse up
1583 while ( elementDocument !== anchorDocument ) {
1584 iframe = elementDocument.defaultView.frameElement;
1585 if ( !iframe ) {
1586 throw new Error( '$element frame is not contained in $anchor frame' );
1587 }
1588 iframePos = $( iframe ).offset();
1589 pos.left += iframePos.left;
1590 pos.top += iframePos.top;
1591 elementDocument = iframe.ownerDocument;
1592 }
1593 pos.left -= anchorPos.left;
1594 pos.top -= anchorPos.top;
1595 return pos;
1596 };
1597
1598 /**
1599 * Get element border sizes.
1600 *
1601 * @static
1602 * @param {HTMLElement} el Element to measure
1603 * @return {Object} Dimensions object with `top`, `left`, `bottom` and `right` properties
1604 */
1605 OO.ui.Element.static.getBorders = function ( el ) {
1606 var doc = el.ownerDocument,
1607 // Support: IE 8
1608 // Standard Document.defaultView is IE9+
1609 win = doc.parentWindow || doc.defaultView,
1610 style = win && win.getComputedStyle ?
1611 win.getComputedStyle( el, null ) :
1612 // Support: IE 8
1613 // Standard getComputedStyle() is IE9+
1614 el.currentStyle,
1615 $el = $( el ),
1616 top = parseFloat( style ? style.borderTopWidth : $el.css( 'borderTopWidth' ) ) || 0,
1617 left = parseFloat( style ? style.borderLeftWidth : $el.css( 'borderLeftWidth' ) ) || 0,
1618 bottom = parseFloat( style ? style.borderBottomWidth : $el.css( 'borderBottomWidth' ) ) || 0,
1619 right = parseFloat( style ? style.borderRightWidth : $el.css( 'borderRightWidth' ) ) || 0;
1620
1621 return {
1622 top: top,
1623 left: left,
1624 bottom: bottom,
1625 right: right
1626 };
1627 };
1628
1629 /**
1630 * Get dimensions of an element or window.
1631 *
1632 * @static
1633 * @param {HTMLElement|Window} el Element to measure
1634 * @return {Object} Dimensions object with `borders`, `scroll`, `scrollbar` and `rect` properties
1635 */
1636 OO.ui.Element.static.getDimensions = function ( el ) {
1637 var $el, $win,
1638 doc = el.ownerDocument || el.document,
1639 // Support: IE 8
1640 // Standard Document.defaultView is IE9+
1641 win = doc.parentWindow || doc.defaultView;
1642
1643 if ( win === el || el === doc.documentElement ) {
1644 $win = $( win );
1645 return {
1646 borders: { top: 0, left: 0, bottom: 0, right: 0 },
1647 scroll: {
1648 top: $win.scrollTop(),
1649 left: $win.scrollLeft()
1650 },
1651 scrollbar: { right: 0, bottom: 0 },
1652 rect: {
1653 top: 0,
1654 left: 0,
1655 bottom: $win.innerHeight(),
1656 right: $win.innerWidth()
1657 }
1658 };
1659 } else {
1660 $el = $( el );
1661 return {
1662 borders: this.getBorders( el ),
1663 scroll: {
1664 top: $el.scrollTop(),
1665 left: $el.scrollLeft()
1666 },
1667 scrollbar: {
1668 right: $el.innerWidth() - el.clientWidth,
1669 bottom: $el.innerHeight() - el.clientHeight
1670 },
1671 rect: el.getBoundingClientRect()
1672 };
1673 }
1674 };
1675
1676 /**
1677 * Get scrollable object parent
1678 *
1679 * documentElement can't be used to get or set the scrollTop
1680 * property on Blink. Changing and testing its value lets us
1681 * use 'body' or 'documentElement' based on what is working.
1682 *
1683 * https://code.google.com/p/chromium/issues/detail?id=303131
1684 *
1685 * @static
1686 * @param {HTMLElement} el Element to find scrollable parent for
1687 * @return {HTMLElement} Scrollable parent
1688 */
1689 OO.ui.Element.static.getRootScrollableElement = function ( el ) {
1690 var scrollTop, body;
1691
1692 if ( OO.ui.scrollableElement === undefined ) {
1693 body = el.ownerDocument.body;
1694 scrollTop = body.scrollTop;
1695 body.scrollTop = 1;
1696
1697 if ( body.scrollTop === 1 ) {
1698 body.scrollTop = scrollTop;
1699 OO.ui.scrollableElement = 'body';
1700 } else {
1701 OO.ui.scrollableElement = 'documentElement';
1702 }
1703 }
1704
1705 return el.ownerDocument[ OO.ui.scrollableElement ];
1706 };
1707
1708 /**
1709 * Get closest scrollable container.
1710 *
1711 * Traverses up until either a scrollable element or the root is reached, in which case the window
1712 * will be returned.
1713 *
1714 * @static
1715 * @param {HTMLElement} el Element to find scrollable container for
1716 * @param {string} [dimension] Dimension of scrolling to look for; `x`, `y` or omit for either
1717 * @return {HTMLElement} Closest scrollable container
1718 */
1719 OO.ui.Element.static.getClosestScrollableContainer = function ( el, dimension ) {
1720 var i, val,
1721 // props = [ 'overflow' ] doesn't work due to https://bugzilla.mozilla.org/show_bug.cgi?id=889091
1722 props = [ 'overflow-x', 'overflow-y' ],
1723 $parent = $( el ).parent();
1724
1725 if ( dimension === 'x' || dimension === 'y' ) {
1726 props = [ 'overflow-' + dimension ];
1727 }
1728
1729 while ( $parent.length ) {
1730 if ( $parent[ 0 ] === this.getRootScrollableElement( el ) ) {
1731 return $parent[ 0 ];
1732 }
1733 i = props.length;
1734 while ( i-- ) {
1735 val = $parent.css( props[ i ] );
1736 if ( val === 'auto' || val === 'scroll' ) {
1737 return $parent[ 0 ];
1738 }
1739 }
1740 $parent = $parent.parent();
1741 }
1742 return this.getDocument( el ).body;
1743 };
1744
1745 /**
1746 * Scroll element into view.
1747 *
1748 * @static
1749 * @param {HTMLElement} el Element to scroll into view
1750 * @param {Object} [config] Configuration options
1751 * @param {string} [config.duration] jQuery animation duration value
1752 * @param {string} [config.direction] Scroll in only one direction, e.g. 'x' or 'y', omit
1753 * to scroll in both directions
1754 * @param {Function} [config.complete] Function to call when scrolling completes
1755 */
1756 OO.ui.Element.static.scrollIntoView = function ( el, config ) {
1757 var rel, anim, callback, sc, $sc, eld, scd, $win;
1758
1759 // Configuration initialization
1760 config = config || {};
1761
1762 anim = {};
1763 callback = typeof config.complete === 'function' && config.complete;
1764 sc = this.getClosestScrollableContainer( el, config.direction );
1765 $sc = $( sc );
1766 eld = this.getDimensions( el );
1767 scd = this.getDimensions( sc );
1768 $win = $( this.getWindow( el ) );
1769
1770 // Compute the distances between the edges of el and the edges of the scroll viewport
1771 if ( $sc.is( 'html, body' ) ) {
1772 // If the scrollable container is the root, this is easy
1773 rel = {
1774 top: eld.rect.top,
1775 bottom: $win.innerHeight() - eld.rect.bottom,
1776 left: eld.rect.left,
1777 right: $win.innerWidth() - eld.rect.right
1778 };
1779 } else {
1780 // Otherwise, we have to subtract el's coordinates from sc's coordinates
1781 rel = {
1782 top: eld.rect.top - ( scd.rect.top + scd.borders.top ),
1783 bottom: scd.rect.bottom - scd.borders.bottom - scd.scrollbar.bottom - eld.rect.bottom,
1784 left: eld.rect.left - ( scd.rect.left + scd.borders.left ),
1785 right: scd.rect.right - scd.borders.right - scd.scrollbar.right - eld.rect.right
1786 };
1787 }
1788
1789 if ( !config.direction || config.direction === 'y' ) {
1790 if ( rel.top < 0 ) {
1791 anim.scrollTop = scd.scroll.top + rel.top;
1792 } else if ( rel.top > 0 && rel.bottom < 0 ) {
1793 anim.scrollTop = scd.scroll.top + Math.min( rel.top, -rel.bottom );
1794 }
1795 }
1796 if ( !config.direction || config.direction === 'x' ) {
1797 if ( rel.left < 0 ) {
1798 anim.scrollLeft = scd.scroll.left + rel.left;
1799 } else if ( rel.left > 0 && rel.right < 0 ) {
1800 anim.scrollLeft = scd.scroll.left + Math.min( rel.left, -rel.right );
1801 }
1802 }
1803 if ( !$.isEmptyObject( anim ) ) {
1804 $sc.stop( true ).animate( anim, config.duration || 'fast' );
1805 if ( callback ) {
1806 $sc.queue( function ( next ) {
1807 callback();
1808 next();
1809 } );
1810 }
1811 } else {
1812 if ( callback ) {
1813 callback();
1814 }
1815 }
1816 };
1817
1818 /**
1819 * Force the browser to reconsider whether it really needs to render scrollbars inside the element
1820 * and reserve space for them, because it probably doesn't.
1821 *
1822 * Workaround primarily for <https://code.google.com/p/chromium/issues/detail?id=387290>, but also
1823 * similar bugs in other browsers. "Just" forcing a reflow is not sufficient in all cases, we need
1824 * to first actually detach (or hide, but detaching is simpler) all children, *then* force a reflow,
1825 * and then reattach (or show) them back.
1826 *
1827 * @static
1828 * @param {HTMLElement} el Element to reconsider the scrollbars on
1829 */
1830 OO.ui.Element.static.reconsiderScrollbars = function ( el ) {
1831 var i, len, scrollLeft, scrollTop, nodes = [];
1832 // Save scroll position
1833 scrollLeft = el.scrollLeft;
1834 scrollTop = el.scrollTop;
1835 // Detach all children
1836 while ( el.firstChild ) {
1837 nodes.push( el.firstChild );
1838 el.removeChild( el.firstChild );
1839 }
1840 // Force reflow
1841 void el.offsetHeight;
1842 // Reattach all children
1843 for ( i = 0, len = nodes.length; i < len; i++ ) {
1844 el.appendChild( nodes[ i ] );
1845 }
1846 // Restore scroll position (no-op if scrollbars disappeared)
1847 el.scrollLeft = scrollLeft;
1848 el.scrollTop = scrollTop;
1849 };
1850
1851 /* Methods */
1852
1853 /**
1854 * Toggle visibility of an element.
1855 *
1856 * @param {boolean} [show] Make element visible, omit to toggle visibility
1857 * @fires visible
1858 * @chainable
1859 */
1860 OO.ui.Element.prototype.toggle = function ( show ) {
1861 show = show === undefined ? !this.visible : !!show;
1862
1863 if ( show !== this.isVisible() ) {
1864 this.visible = show;
1865 this.$element.toggleClass( 'oo-ui-element-hidden', !this.visible );
1866 this.emit( 'toggle', show );
1867 }
1868
1869 return this;
1870 };
1871
1872 /**
1873 * Check if element is visible.
1874 *
1875 * @return {boolean} element is visible
1876 */
1877 OO.ui.Element.prototype.isVisible = function () {
1878 return this.visible;
1879 };
1880
1881 /**
1882 * Get element data.
1883 *
1884 * @return {Mixed} Element data
1885 */
1886 OO.ui.Element.prototype.getData = function () {
1887 return this.data;
1888 };
1889
1890 /**
1891 * Set element data.
1892 *
1893 * @param {Mixed} Element data
1894 * @chainable
1895 */
1896 OO.ui.Element.prototype.setData = function ( data ) {
1897 this.data = data;
1898 return this;
1899 };
1900
1901 /**
1902 * Check if element supports one or more methods.
1903 *
1904 * @param {string|string[]} methods Method or list of methods to check
1905 * @return {boolean} All methods are supported
1906 */
1907 OO.ui.Element.prototype.supports = function ( methods ) {
1908 var i, len,
1909 support = 0;
1910
1911 methods = Array.isArray( methods ) ? methods : [ methods ];
1912 for ( i = 0, len = methods.length; i < len; i++ ) {
1913 if ( $.isFunction( this[ methods[ i ] ] ) ) {
1914 support++;
1915 }
1916 }
1917
1918 return methods.length === support;
1919 };
1920
1921 /**
1922 * Update the theme-provided classes.
1923 *
1924 * @localdoc This is called in element mixins and widget classes any time state changes.
1925 * Updating is debounced, minimizing overhead of changing multiple attributes and
1926 * guaranteeing that theme updates do not occur within an element's constructor
1927 */
1928 OO.ui.Element.prototype.updateThemeClasses = function () {
1929 this.debouncedUpdateThemeClassesHandler();
1930 };
1931
1932 /**
1933 * @private
1934 * @localdoc This method is called directly from the QUnit tests instead of #updateThemeClasses, to
1935 * make them synchronous.
1936 */
1937 OO.ui.Element.prototype.debouncedUpdateThemeClasses = function () {
1938 OO.ui.theme.updateElementClasses( this );
1939 };
1940
1941 /**
1942 * Get the HTML tag name.
1943 *
1944 * Override this method to base the result on instance information.
1945 *
1946 * @return {string} HTML tag name
1947 */
1948 OO.ui.Element.prototype.getTagName = function () {
1949 return this.constructor.static.tagName;
1950 };
1951
1952 /**
1953 * Check if the element is attached to the DOM
1954 * @return {boolean} The element is attached to the DOM
1955 */
1956 OO.ui.Element.prototype.isElementAttached = function () {
1957 return $.contains( this.getElementDocument(), this.$element[ 0 ] );
1958 };
1959
1960 /**
1961 * Get the DOM document.
1962 *
1963 * @return {HTMLDocument} Document object
1964 */
1965 OO.ui.Element.prototype.getElementDocument = function () {
1966 // Don't cache this in other ways either because subclasses could can change this.$element
1967 return OO.ui.Element.static.getDocument( this.$element );
1968 };
1969
1970 /**
1971 * Get the DOM window.
1972 *
1973 * @return {Window} Window object
1974 */
1975 OO.ui.Element.prototype.getElementWindow = function () {
1976 return OO.ui.Element.static.getWindow( this.$element );
1977 };
1978
1979 /**
1980 * Get closest scrollable container.
1981 */
1982 OO.ui.Element.prototype.getClosestScrollableElementContainer = function () {
1983 return OO.ui.Element.static.getClosestScrollableContainer( this.$element[ 0 ] );
1984 };
1985
1986 /**
1987 * Get group element is in.
1988 *
1989 * @return {OO.ui.mixin.GroupElement|null} Group element, null if none
1990 */
1991 OO.ui.Element.prototype.getElementGroup = function () {
1992 return this.elementGroup;
1993 };
1994
1995 /**
1996 * Set group element is in.
1997 *
1998 * @param {OO.ui.mixin.GroupElement|null} group Group element, null if none
1999 * @chainable
2000 */
2001 OO.ui.Element.prototype.setElementGroup = function ( group ) {
2002 this.elementGroup = group;
2003 return this;
2004 };
2005
2006 /**
2007 * Scroll element into view.
2008 *
2009 * @param {Object} [config] Configuration options
2010 */
2011 OO.ui.Element.prototype.scrollElementIntoView = function ( config ) {
2012 return OO.ui.Element.static.scrollIntoView( this.$element[ 0 ], config );
2013 };
2014
2015 /**
2016 * Restore the pre-infusion dynamic state for this widget.
2017 *
2018 * This method is called after #$element has been inserted into DOM. The parameter is the return
2019 * value of #gatherPreInfuseState.
2020 *
2021 * @protected
2022 * @param {Object} state
2023 */
2024 OO.ui.Element.prototype.restorePreInfuseState = function () {
2025 };
2026
2027 /**
2028 * Layouts are containers for elements and are used to arrange other widgets of arbitrary type in a way
2029 * that is centrally controlled and can be updated dynamically. Layouts can be, and usually are, combined.
2030 * See {@link OO.ui.FieldsetLayout FieldsetLayout}, {@link OO.ui.FieldLayout FieldLayout}, {@link OO.ui.FormLayout FormLayout},
2031 * {@link OO.ui.PanelLayout PanelLayout}, {@link OO.ui.StackLayout StackLayout}, {@link OO.ui.PageLayout PageLayout},
2032 * {@link OO.ui.HorizontalLayout HorizontalLayout}, and {@link OO.ui.BookletLayout BookletLayout} for more information and examples.
2033 *
2034 * @abstract
2035 * @class
2036 * @extends OO.ui.Element
2037 * @mixins OO.EventEmitter
2038 *
2039 * @constructor
2040 * @param {Object} [config] Configuration options
2041 */
2042 OO.ui.Layout = function OoUiLayout( config ) {
2043 // Configuration initialization
2044 config = config || {};
2045
2046 // Parent constructor
2047 OO.ui.Layout.parent.call( this, config );
2048
2049 // Mixin constructors
2050 OO.EventEmitter.call( this );
2051
2052 // Initialization
2053 this.$element.addClass( 'oo-ui-layout' );
2054 };
2055
2056 /* Setup */
2057
2058 OO.inheritClass( OO.ui.Layout, OO.ui.Element );
2059 OO.mixinClass( OO.ui.Layout, OO.EventEmitter );
2060
2061 /**
2062 * Widgets are compositions of one or more OOjs UI elements that users can both view
2063 * and interact with. All widgets can be configured and modified via a standard API,
2064 * and their state can change dynamically according to a model.
2065 *
2066 * @abstract
2067 * @class
2068 * @extends OO.ui.Element
2069 * @mixins OO.EventEmitter
2070 *
2071 * @constructor
2072 * @param {Object} [config] Configuration options
2073 * @cfg {boolean} [disabled=false] Disable the widget. Disabled widgets cannot be used and their
2074 * appearance reflects this state.
2075 */
2076 OO.ui.Widget = function OoUiWidget( config ) {
2077 // Initialize config
2078 config = $.extend( { disabled: false }, config );
2079
2080 // Parent constructor
2081 OO.ui.Widget.parent.call( this, config );
2082
2083 // Mixin constructors
2084 OO.EventEmitter.call( this );
2085
2086 // Properties
2087 this.disabled = null;
2088 this.wasDisabled = null;
2089
2090 // Initialization
2091 this.$element.addClass( 'oo-ui-widget' );
2092 this.setDisabled( !!config.disabled );
2093 };
2094
2095 /* Setup */
2096
2097 OO.inheritClass( OO.ui.Widget, OO.ui.Element );
2098 OO.mixinClass( OO.ui.Widget, OO.EventEmitter );
2099
2100 /* Static Properties */
2101
2102 /**
2103 * Whether this widget will behave reasonably when wrapped in a HTML `<label>`. If this is true,
2104 * wrappers such as OO.ui.FieldLayout may use a `<label>` instead of implementing own label click
2105 * handling.
2106 *
2107 * @static
2108 * @inheritable
2109 * @property {boolean}
2110 */
2111 OO.ui.Widget.static.supportsSimpleLabel = false;
2112
2113 /* Events */
2114
2115 /**
2116 * @event disable
2117 *
2118 * A 'disable' event is emitted when the disabled state of the widget changes
2119 * (i.e. on disable **and** enable).
2120 *
2121 * @param {boolean} disabled Widget is disabled
2122 */
2123
2124 /**
2125 * @event toggle
2126 *
2127 * A 'toggle' event is emitted when the visibility of the widget changes.
2128 *
2129 * @param {boolean} visible Widget is visible
2130 */
2131
2132 /* Methods */
2133
2134 /**
2135 * Check if the widget is disabled.
2136 *
2137 * @return {boolean} Widget is disabled
2138 */
2139 OO.ui.Widget.prototype.isDisabled = function () {
2140 return this.disabled;
2141 };
2142
2143 /**
2144 * Set the 'disabled' state of the widget.
2145 *
2146 * When a widget is disabled, it cannot be used and its appearance is updated to reflect this state.
2147 *
2148 * @param {boolean} disabled Disable widget
2149 * @chainable
2150 */
2151 OO.ui.Widget.prototype.setDisabled = function ( disabled ) {
2152 var isDisabled;
2153
2154 this.disabled = !!disabled;
2155 isDisabled = this.isDisabled();
2156 if ( isDisabled !== this.wasDisabled ) {
2157 this.$element.toggleClass( 'oo-ui-widget-disabled', isDisabled );
2158 this.$element.toggleClass( 'oo-ui-widget-enabled', !isDisabled );
2159 this.$element.attr( 'aria-disabled', isDisabled.toString() );
2160 this.emit( 'disable', isDisabled );
2161 this.updateThemeClasses();
2162 }
2163 this.wasDisabled = isDisabled;
2164
2165 return this;
2166 };
2167
2168 /**
2169 * Update the disabled state, in case of changes in parent widget.
2170 *
2171 * @chainable
2172 */
2173 OO.ui.Widget.prototype.updateDisabled = function () {
2174 this.setDisabled( this.disabled );
2175 return this;
2176 };
2177
2178 /**
2179 * A window is a container for elements that are in a child frame. They are used with
2180 * a window manager (OO.ui.WindowManager), which is used to open and close the window and control
2181 * its presentation. The size of a window is specified using a symbolic name (e.g., ‘small’, ‘medium’,
2182 * ‘large’), which is interpreted by the window manager. If the requested size is not recognized,
2183 * the window manager will choose a sensible fallback.
2184 *
2185 * The lifecycle of a window has three primary stages (opening, opened, and closing) in which
2186 * different processes are executed:
2187 *
2188 * **opening**: The opening stage begins when the window manager's {@link OO.ui.WindowManager#openWindow
2189 * openWindow} or the window's {@link #open open} methods are used, and the window manager begins to open
2190 * the window.
2191 *
2192 * - {@link #getSetupProcess} method is called and its result executed
2193 * - {@link #getReadyProcess} method is called and its result executed
2194 *
2195 * **opened**: The window is now open
2196 *
2197 * **closing**: The closing stage begins when the window manager's
2198 * {@link OO.ui.WindowManager#closeWindow closeWindow}
2199 * or the window's {@link #close} methods are used, and the window manager begins to close the window.
2200 *
2201 * - {@link #getHoldProcess} method is called and its result executed
2202 * - {@link #getTeardownProcess} method is called and its result executed. The window is now closed
2203 *
2204 * Each of the window's processes (setup, ready, hold, and teardown) can be extended in subclasses
2205 * by overriding the window's #getSetupProcess, #getReadyProcess, #getHoldProcess and #getTeardownProcess
2206 * methods. Note that each {@link OO.ui.Process process} is executed in series, so asynchronous
2207 * processing can complete. Always assume window processes are executed asynchronously.
2208 *
2209 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
2210 *
2211 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows
2212 *
2213 * @abstract
2214 * @class
2215 * @extends OO.ui.Element
2216 * @mixins OO.EventEmitter
2217 *
2218 * @constructor
2219 * @param {Object} [config] Configuration options
2220 * @cfg {string} [size] Symbolic name of the dialog size: `small`, `medium`, `large`, `larger` or
2221 * `full`. If omitted, the value of the {@link #static-size static size} property will be used.
2222 */
2223 OO.ui.Window = function OoUiWindow( config ) {
2224 // Configuration initialization
2225 config = config || {};
2226
2227 // Parent constructor
2228 OO.ui.Window.parent.call( this, config );
2229
2230 // Mixin constructors
2231 OO.EventEmitter.call( this );
2232
2233 // Properties
2234 this.manager = null;
2235 this.size = config.size || this.constructor.static.size;
2236 this.$frame = $( '<div>' );
2237 this.$overlay = $( '<div>' );
2238 this.$content = $( '<div>' );
2239
2240 this.$focusTrapBefore = $( '<div>' ).prop( 'tabIndex', 0 );
2241 this.$focusTrapAfter = $( '<div>' ).prop( 'tabIndex', 0 );
2242 this.$focusTraps = this.$focusTrapBefore.add( this.$focusTrapAfter );
2243
2244 // Initialization
2245 this.$overlay.addClass( 'oo-ui-window-overlay' );
2246 this.$content
2247 .addClass( 'oo-ui-window-content' )
2248 .attr( 'tabindex', 0 );
2249 this.$frame
2250 .addClass( 'oo-ui-window-frame' )
2251 .append( this.$focusTrapBefore, this.$content, this.$focusTrapAfter );
2252
2253 this.$element
2254 .addClass( 'oo-ui-window' )
2255 .append( this.$frame, this.$overlay );
2256
2257 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
2258 // that reference properties not initialized at that time of parent class construction
2259 // TODO: Find a better way to handle post-constructor setup
2260 this.visible = false;
2261 this.$element.addClass( 'oo-ui-element-hidden' );
2262 };
2263
2264 /* Setup */
2265
2266 OO.inheritClass( OO.ui.Window, OO.ui.Element );
2267 OO.mixinClass( OO.ui.Window, OO.EventEmitter );
2268
2269 /* Static Properties */
2270
2271 /**
2272 * Symbolic name of the window size: `small`, `medium`, `large`, `larger` or `full`.
2273 *
2274 * The static size is used if no #size is configured during construction.
2275 *
2276 * @static
2277 * @inheritable
2278 * @property {string}
2279 */
2280 OO.ui.Window.static.size = 'medium';
2281
2282 /* Methods */
2283
2284 /**
2285 * Handle mouse down events.
2286 *
2287 * @private
2288 * @param {jQuery.Event} e Mouse down event
2289 */
2290 OO.ui.Window.prototype.onMouseDown = function ( e ) {
2291 // Prevent clicking on the click-block from stealing focus
2292 if ( e.target === this.$element[ 0 ] ) {
2293 return false;
2294 }
2295 };
2296
2297 /**
2298 * Check if the window has been initialized.
2299 *
2300 * Initialization occurs when a window is added to a manager.
2301 *
2302 * @return {boolean} Window has been initialized
2303 */
2304 OO.ui.Window.prototype.isInitialized = function () {
2305 return !!this.manager;
2306 };
2307
2308 /**
2309 * Check if the window is visible.
2310 *
2311 * @return {boolean} Window is visible
2312 */
2313 OO.ui.Window.prototype.isVisible = function () {
2314 return this.visible;
2315 };
2316
2317 /**
2318 * Check if the window is opening.
2319 *
2320 * This method is a wrapper around the window manager's {@link OO.ui.WindowManager#isOpening isOpening}
2321 * method.
2322 *
2323 * @return {boolean} Window is opening
2324 */
2325 OO.ui.Window.prototype.isOpening = function () {
2326 return this.manager.isOpening( this );
2327 };
2328
2329 /**
2330 * Check if the window is closing.
2331 *
2332 * This method is a wrapper around the window manager's {@link OO.ui.WindowManager#isClosing isClosing} method.
2333 *
2334 * @return {boolean} Window is closing
2335 */
2336 OO.ui.Window.prototype.isClosing = function () {
2337 return this.manager.isClosing( this );
2338 };
2339
2340 /**
2341 * Check if the window is opened.
2342 *
2343 * This method is a wrapper around the window manager's {@link OO.ui.WindowManager#isOpened isOpened} method.
2344 *
2345 * @return {boolean} Window is opened
2346 */
2347 OO.ui.Window.prototype.isOpened = function () {
2348 return this.manager.isOpened( this );
2349 };
2350
2351 /**
2352 * Get the window manager.
2353 *
2354 * All windows must be attached to a window manager, which is used to open
2355 * and close the window and control its presentation.
2356 *
2357 * @return {OO.ui.WindowManager} Manager of window
2358 */
2359 OO.ui.Window.prototype.getManager = function () {
2360 return this.manager;
2361 };
2362
2363 /**
2364 * Get the symbolic name of the window size (e.g., `small` or `medium`).
2365 *
2366 * @return {string} Symbolic name of the size: `small`, `medium`, `large`, `larger`, `full`
2367 */
2368 OO.ui.Window.prototype.getSize = function () {
2369 var viewport = OO.ui.Element.static.getDimensions( this.getElementWindow() ),
2370 sizes = this.manager.constructor.static.sizes,
2371 size = this.size;
2372
2373 if ( !sizes[ size ] ) {
2374 size = this.manager.constructor.static.defaultSize;
2375 }
2376 if ( size !== 'full' && viewport.rect.right - viewport.rect.left < sizes[ size ].width ) {
2377 size = 'full';
2378 }
2379
2380 return size;
2381 };
2382
2383 /**
2384 * Get the size properties associated with the current window size
2385 *
2386 * @return {Object} Size properties
2387 */
2388 OO.ui.Window.prototype.getSizeProperties = function () {
2389 return this.manager.constructor.static.sizes[ this.getSize() ];
2390 };
2391
2392 /**
2393 * Disable transitions on window's frame for the duration of the callback function, then enable them
2394 * back.
2395 *
2396 * @private
2397 * @param {Function} callback Function to call while transitions are disabled
2398 */
2399 OO.ui.Window.prototype.withoutSizeTransitions = function ( callback ) {
2400 // Temporarily resize the frame so getBodyHeight() can use scrollHeight measurements.
2401 // Disable transitions first, otherwise we'll get values from when the window was animating.
2402 var oldTransition,
2403 styleObj = this.$frame[ 0 ].style;
2404 oldTransition = styleObj.transition || styleObj.OTransition || styleObj.MsTransition ||
2405 styleObj.MozTransition || styleObj.WebkitTransition;
2406 styleObj.transition = styleObj.OTransition = styleObj.MsTransition =
2407 styleObj.MozTransition = styleObj.WebkitTransition = 'none';
2408 callback();
2409 // Force reflow to make sure the style changes done inside callback really are not transitioned
2410 this.$frame.height();
2411 styleObj.transition = styleObj.OTransition = styleObj.MsTransition =
2412 styleObj.MozTransition = styleObj.WebkitTransition = oldTransition;
2413 };
2414
2415 /**
2416 * Get the height of the full window contents (i.e., the window head, body and foot together).
2417 *
2418 * What consistitutes the head, body, and foot varies depending on the window type.
2419 * A {@link OO.ui.MessageDialog message dialog} displays a title and message in its body,
2420 * and any actions in the foot. A {@link OO.ui.ProcessDialog process dialog} displays a title
2421 * and special actions in the head, and dialog content in the body.
2422 *
2423 * To get just the height of the dialog body, use the #getBodyHeight method.
2424 *
2425 * @return {number} The height of the window contents (the dialog head, body and foot) in pixels
2426 */
2427 OO.ui.Window.prototype.getContentHeight = function () {
2428 var bodyHeight,
2429 win = this,
2430 bodyStyleObj = this.$body[ 0 ].style,
2431 frameStyleObj = this.$frame[ 0 ].style;
2432
2433 // Temporarily resize the frame so getBodyHeight() can use scrollHeight measurements.
2434 // Disable transitions first, otherwise we'll get values from when the window was animating.
2435 this.withoutSizeTransitions( function () {
2436 var oldHeight = frameStyleObj.height,
2437 oldPosition = bodyStyleObj.position;
2438 frameStyleObj.height = '1px';
2439 // Force body to resize to new width
2440 bodyStyleObj.position = 'relative';
2441 bodyHeight = win.getBodyHeight();
2442 frameStyleObj.height = oldHeight;
2443 bodyStyleObj.position = oldPosition;
2444 } );
2445
2446 return (
2447 // Add buffer for border
2448 ( this.$frame.outerHeight() - this.$frame.innerHeight() ) +
2449 // Use combined heights of children
2450 ( this.$head.outerHeight( true ) + bodyHeight + this.$foot.outerHeight( true ) )
2451 );
2452 };
2453
2454 /**
2455 * Get the height of the window body.
2456 *
2457 * To get the height of the full window contents (the window body, head, and foot together),
2458 * use #getContentHeight.
2459 *
2460 * When this function is called, the window will temporarily have been resized
2461 * to height=1px, so .scrollHeight measurements can be taken accurately.
2462 *
2463 * @return {number} Height of the window body in pixels
2464 */
2465 OO.ui.Window.prototype.getBodyHeight = function () {
2466 return this.$body[ 0 ].scrollHeight;
2467 };
2468
2469 /**
2470 * Get the directionality of the frame (right-to-left or left-to-right).
2471 *
2472 * @return {string} Directionality: `'ltr'` or `'rtl'`
2473 */
2474 OO.ui.Window.prototype.getDir = function () {
2475 return OO.ui.Element.static.getDir( this.$content ) || 'ltr';
2476 };
2477
2478 /**
2479 * Get the 'setup' process.
2480 *
2481 * The setup process is used to set up a window for use in a particular context,
2482 * based on the `data` argument. This method is called during the opening phase of the window’s
2483 * lifecycle.
2484 *
2485 * Override this method to add additional steps to the ‘setup’ process the parent method provides
2486 * using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next} methods
2487 * of OO.ui.Process.
2488 *
2489 * To add window content that persists between openings, you may wish to use the #initialize method
2490 * instead.
2491 *
2492 * @param {Object} [data] Window opening data
2493 * @return {OO.ui.Process} Setup process
2494 */
2495 OO.ui.Window.prototype.getSetupProcess = function () {
2496 return new OO.ui.Process();
2497 };
2498
2499 /**
2500 * Get the ‘ready’ process.
2501 *
2502 * The ready process is used to ready a window for use in a particular
2503 * context, based on the `data` argument. This method is called during the opening phase of
2504 * the window’s lifecycle, after the window has been {@link #getSetupProcess setup}.
2505 *
2506 * Override this method to add additional steps to the ‘ready’ process the parent method
2507 * provides using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next}
2508 * methods of OO.ui.Process.
2509 *
2510 * @param {Object} [data] Window opening data
2511 * @return {OO.ui.Process} Ready process
2512 */
2513 OO.ui.Window.prototype.getReadyProcess = function () {
2514 return new OO.ui.Process();
2515 };
2516
2517 /**
2518 * Get the 'hold' process.
2519 *
2520 * The hold proccess is used to keep a window from being used in a particular context,
2521 * based on the `data` argument. This method is called during the closing phase of the window’s
2522 * lifecycle.
2523 *
2524 * Override this method to add additional steps to the 'hold' process the parent method provides
2525 * using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next} methods
2526 * of OO.ui.Process.
2527 *
2528 * @param {Object} [data] Window closing data
2529 * @return {OO.ui.Process} Hold process
2530 */
2531 OO.ui.Window.prototype.getHoldProcess = function () {
2532 return new OO.ui.Process();
2533 };
2534
2535 /**
2536 * Get the ‘teardown’ process.
2537 *
2538 * The teardown process is used to teardown a window after use. During teardown,
2539 * user interactions within the window are conveyed and the window is closed, based on the `data`
2540 * argument. This method is called during the closing phase of the window’s lifecycle.
2541 *
2542 * Override this method to add additional steps to the ‘teardown’ process the parent method provides
2543 * using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next} methods
2544 * of OO.ui.Process.
2545 *
2546 * @param {Object} [data] Window closing data
2547 * @return {OO.ui.Process} Teardown process
2548 */
2549 OO.ui.Window.prototype.getTeardownProcess = function () {
2550 return new OO.ui.Process();
2551 };
2552
2553 /**
2554 * Set the window manager.
2555 *
2556 * This will cause the window to initialize. Calling it more than once will cause an error.
2557 *
2558 * @param {OO.ui.WindowManager} manager Manager for this window
2559 * @throws {Error} An error is thrown if the method is called more than once
2560 * @chainable
2561 */
2562 OO.ui.Window.prototype.setManager = function ( manager ) {
2563 if ( this.manager ) {
2564 throw new Error( 'Cannot set window manager, window already has a manager' );
2565 }
2566
2567 this.manager = manager;
2568 this.initialize();
2569
2570 return this;
2571 };
2572
2573 /**
2574 * Set the window size by symbolic name (e.g., 'small' or 'medium')
2575 *
2576 * @param {string} size Symbolic name of size: `small`, `medium`, `large`, `larger` or
2577 * `full`
2578 * @chainable
2579 */
2580 OO.ui.Window.prototype.setSize = function ( size ) {
2581 this.size = size;
2582 this.updateSize();
2583 return this;
2584 };
2585
2586 /**
2587 * Update the window size.
2588 *
2589 * @throws {Error} An error is thrown if the window is not attached to a window manager
2590 * @chainable
2591 */
2592 OO.ui.Window.prototype.updateSize = function () {
2593 if ( !this.manager ) {
2594 throw new Error( 'Cannot update window size, must be attached to a manager' );
2595 }
2596
2597 this.manager.updateWindowSize( this );
2598
2599 return this;
2600 };
2601
2602 /**
2603 * Set window dimensions. This method is called by the {@link OO.ui.WindowManager window manager}
2604 * when the window is opening. In general, setDimensions should not be called directly.
2605 *
2606 * To set the size of the window, use the #setSize method.
2607 *
2608 * @param {Object} dim CSS dimension properties
2609 * @param {string|number} [dim.width] Width
2610 * @param {string|number} [dim.minWidth] Minimum width
2611 * @param {string|number} [dim.maxWidth] Maximum width
2612 * @param {string|number} [dim.width] Height, omit to set based on height of contents
2613 * @param {string|number} [dim.minWidth] Minimum height
2614 * @param {string|number} [dim.maxWidth] Maximum height
2615 * @chainable
2616 */
2617 OO.ui.Window.prototype.setDimensions = function ( dim ) {
2618 var height,
2619 win = this,
2620 styleObj = this.$frame[ 0 ].style;
2621
2622 // Calculate the height we need to set using the correct width
2623 if ( dim.height === undefined ) {
2624 this.withoutSizeTransitions( function () {
2625 var oldWidth = styleObj.width;
2626 win.$frame.css( 'width', dim.width || '' );
2627 height = win.getContentHeight();
2628 styleObj.width = oldWidth;
2629 } );
2630 } else {
2631 height = dim.height;
2632 }
2633
2634 this.$frame.css( {
2635 width: dim.width || '',
2636 minWidth: dim.minWidth || '',
2637 maxWidth: dim.maxWidth || '',
2638 height: height || '',
2639 minHeight: dim.minHeight || '',
2640 maxHeight: dim.maxHeight || ''
2641 } );
2642
2643 return this;
2644 };
2645
2646 /**
2647 * Initialize window contents.
2648 *
2649 * Before the window is opened for the first time, #initialize is called so that content that
2650 * persists between openings can be added to the window.
2651 *
2652 * To set up a window with new content each time the window opens, use #getSetupProcess.
2653 *
2654 * @throws {Error} An error is thrown if the window is not attached to a window manager
2655 * @chainable
2656 */
2657 OO.ui.Window.prototype.initialize = function () {
2658 if ( !this.manager ) {
2659 throw new Error( 'Cannot initialize window, must be attached to a manager' );
2660 }
2661
2662 // Properties
2663 this.$head = $( '<div>' );
2664 this.$body = $( '<div>' );
2665 this.$foot = $( '<div>' );
2666 this.$document = $( this.getElementDocument() );
2667
2668 // Events
2669 this.$element.on( 'mousedown', this.onMouseDown.bind( this ) );
2670
2671 // Initialization
2672 this.$head.addClass( 'oo-ui-window-head' );
2673 this.$body.addClass( 'oo-ui-window-body' );
2674 this.$foot.addClass( 'oo-ui-window-foot' );
2675 this.$content.append( this.$head, this.$body, this.$foot );
2676
2677 return this;
2678 };
2679
2680 /**
2681 * Called when someone tries to focus the hidden element at the end of the dialog.
2682 * Sends focus back to the start of the dialog.
2683 *
2684 * @param {jQuery.Event} event Focus event
2685 */
2686 OO.ui.Window.prototype.onFocusTrapFocused = function ( event ) {
2687 if ( this.$focusTrapBefore.is( event.target ) ) {
2688 OO.ui.findFocusable( this.$content, true ).focus();
2689 } else {
2690 // this.$content is the part of the focus cycle, and is the first focusable element
2691 this.$content.focus();
2692 }
2693 };
2694
2695 /**
2696 * Open the window.
2697 *
2698 * This method is a wrapper around a call to the window manager’s {@link OO.ui.WindowManager#openWindow openWindow}
2699 * method, which returns a promise resolved when the window is done opening.
2700 *
2701 * To customize the window each time it opens, use #getSetupProcess or #getReadyProcess.
2702 *
2703 * @param {Object} [data] Window opening data
2704 * @return {jQuery.Promise} Promise resolved with a value when the window is opened, or rejected
2705 * if the window fails to open. When the promise is resolved successfully, the first argument of the
2706 * value is a new promise, which is resolved when the window begins closing.
2707 * @throws {Error} An error is thrown if the window is not attached to a window manager
2708 */
2709 OO.ui.Window.prototype.open = function ( data ) {
2710 if ( !this.manager ) {
2711 throw new Error( 'Cannot open window, must be attached to a manager' );
2712 }
2713
2714 return this.manager.openWindow( this, data );
2715 };
2716
2717 /**
2718 * Close the window.
2719 *
2720 * This method is a wrapper around a call to the window
2721 * manager’s {@link OO.ui.WindowManager#closeWindow closeWindow} method,
2722 * which returns a closing promise resolved when the window is done closing.
2723 *
2724 * The window's #getHoldProcess and #getTeardownProcess methods are called during the closing
2725 * phase of the window’s lifecycle and can be used to specify closing behavior each time
2726 * the window closes.
2727 *
2728 * @param {Object} [data] Window closing data
2729 * @return {jQuery.Promise} Promise resolved when window is closed
2730 * @throws {Error} An error is thrown if the window is not attached to a window manager
2731 */
2732 OO.ui.Window.prototype.close = function ( data ) {
2733 if ( !this.manager ) {
2734 throw new Error( 'Cannot close window, must be attached to a manager' );
2735 }
2736
2737 return this.manager.closeWindow( this, data );
2738 };
2739
2740 /**
2741 * Setup window.
2742 *
2743 * This is called by OO.ui.WindowManager during window opening, and should not be called directly
2744 * by other systems.
2745 *
2746 * @param {Object} [data] Window opening data
2747 * @return {jQuery.Promise} Promise resolved when window is setup
2748 */
2749 OO.ui.Window.prototype.setup = function ( data ) {
2750 var win = this;
2751
2752 this.toggle( true );
2753
2754 this.focusTrapHandler = OO.ui.bind( this.onFocusTrapFocused, this );
2755 this.$focusTraps.on( 'focus', this.focusTrapHandler );
2756
2757 return this.getSetupProcess( data ).execute().then( function () {
2758 // Force redraw by asking the browser to measure the elements' widths
2759 win.$element.addClass( 'oo-ui-window-active oo-ui-window-setup' ).width();
2760 win.$content.addClass( 'oo-ui-window-content-setup' ).width();
2761 } );
2762 };
2763
2764 /**
2765 * Ready window.
2766 *
2767 * This is called by OO.ui.WindowManager during window opening, and should not be called directly
2768 * by other systems.
2769 *
2770 * @param {Object} [data] Window opening data
2771 * @return {jQuery.Promise} Promise resolved when window is ready
2772 */
2773 OO.ui.Window.prototype.ready = function ( data ) {
2774 var win = this;
2775
2776 this.$content.focus();
2777 return this.getReadyProcess( data ).execute().then( function () {
2778 // Force redraw by asking the browser to measure the elements' widths
2779 win.$element.addClass( 'oo-ui-window-ready' ).width();
2780 win.$content.addClass( 'oo-ui-window-content-ready' ).width();
2781 } );
2782 };
2783
2784 /**
2785 * Hold window.
2786 *
2787 * This is called by OO.ui.WindowManager during window closing, and should not be called directly
2788 * by other systems.
2789 *
2790 * @param {Object} [data] Window closing data
2791 * @return {jQuery.Promise} Promise resolved when window is held
2792 */
2793 OO.ui.Window.prototype.hold = function ( data ) {
2794 var win = this;
2795
2796 return this.getHoldProcess( data ).execute().then( function () {
2797 // Get the focused element within the window's content
2798 var $focus = win.$content.find( OO.ui.Element.static.getDocument( win.$content ).activeElement );
2799
2800 // Blur the focused element
2801 if ( $focus.length ) {
2802 $focus[ 0 ].blur();
2803 }
2804
2805 // Force redraw by asking the browser to measure the elements' widths
2806 win.$element.removeClass( 'oo-ui-window-ready' ).width();
2807 win.$content.removeClass( 'oo-ui-window-content-ready' ).width();
2808 } );
2809 };
2810
2811 /**
2812 * Teardown window.
2813 *
2814 * This is called by OO.ui.WindowManager during window closing, and should not be called directly
2815 * by other systems.
2816 *
2817 * @param {Object} [data] Window closing data
2818 * @return {jQuery.Promise} Promise resolved when window is torn down
2819 */
2820 OO.ui.Window.prototype.teardown = function ( data ) {
2821 var win = this;
2822
2823 return this.getTeardownProcess( data ).execute().then( function () {
2824 // Force redraw by asking the browser to measure the elements' widths
2825 win.$element.removeClass( 'oo-ui-window-active oo-ui-window-setup' ).width();
2826 win.$content.removeClass( 'oo-ui-window-content-setup' ).width();
2827 win.$focusTraps.off( 'focus', win.focusTrapHandler );
2828 win.toggle( false );
2829 } );
2830 };
2831
2832 /**
2833 * The Dialog class serves as the base class for the other types of dialogs.
2834 * Unless extended to include controls, the rendered dialog box is a simple window
2835 * that users can close by hitting the ‘Esc’ key. Dialog windows are used with OO.ui.WindowManager,
2836 * which opens, closes, and controls the presentation of the window. See the
2837 * [OOjs UI documentation on MediaWiki] [1] for more information.
2838 *
2839 * @example
2840 * // A simple dialog window.
2841 * function MyDialog( config ) {
2842 * MyDialog.parent.call( this, config );
2843 * }
2844 * OO.inheritClass( MyDialog, OO.ui.Dialog );
2845 * MyDialog.prototype.initialize = function () {
2846 * MyDialog.parent.prototype.initialize.call( this );
2847 * this.content = new OO.ui.PanelLayout( { padded: true, expanded: false } );
2848 * this.content.$element.append( '<p>A simple dialog window. Press \'Esc\' to close.</p>' );
2849 * this.$body.append( this.content.$element );
2850 * };
2851 * MyDialog.prototype.getBodyHeight = function () {
2852 * return this.content.$element.outerHeight( true );
2853 * };
2854 * var myDialog = new MyDialog( {
2855 * size: 'medium'
2856 * } );
2857 * // Create and append a window manager, which opens and closes the window.
2858 * var windowManager = new OO.ui.WindowManager();
2859 * $( 'body' ).append( windowManager.$element );
2860 * windowManager.addWindows( [ myDialog ] );
2861 * // Open the window!
2862 * windowManager.openWindow( myDialog );
2863 *
2864 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Dialogs
2865 *
2866 * @abstract
2867 * @class
2868 * @extends OO.ui.Window
2869 * @mixins OO.ui.mixin.PendingElement
2870 *
2871 * @constructor
2872 * @param {Object} [config] Configuration options
2873 */
2874 OO.ui.Dialog = function OoUiDialog( config ) {
2875 // Parent constructor
2876 OO.ui.Dialog.parent.call( this, config );
2877
2878 // Mixin constructors
2879 OO.ui.mixin.PendingElement.call( this );
2880
2881 // Properties
2882 this.actions = new OO.ui.ActionSet();
2883 this.attachedActions = [];
2884 this.currentAction = null;
2885 this.onDialogKeyDownHandler = this.onDialogKeyDown.bind( this );
2886
2887 // Events
2888 this.actions.connect( this, {
2889 click: 'onActionClick',
2890 resize: 'onActionResize',
2891 change: 'onActionsChange'
2892 } );
2893
2894 // Initialization
2895 this.$element
2896 .addClass( 'oo-ui-dialog' )
2897 .attr( 'role', 'dialog' );
2898 };
2899
2900 /* Setup */
2901
2902 OO.inheritClass( OO.ui.Dialog, OO.ui.Window );
2903 OO.mixinClass( OO.ui.Dialog, OO.ui.mixin.PendingElement );
2904
2905 /* Static Properties */
2906
2907 /**
2908 * Symbolic name of dialog.
2909 *
2910 * The dialog class must have a symbolic name in order to be registered with OO.Factory.
2911 * Please see the [OOjs UI documentation on MediaWiki] [3] for more information.
2912 *
2913 * [3]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
2914 *
2915 * @abstract
2916 * @static
2917 * @inheritable
2918 * @property {string}
2919 */
2920 OO.ui.Dialog.static.name = '';
2921
2922 /**
2923 * The dialog title.
2924 *
2925 * The title can be specified as a plaintext string, a {@link OO.ui.mixin.LabelElement Label} node, or a function
2926 * that will produce a Label node or string. The title can also be specified with data passed to the
2927 * constructor (see #getSetupProcess). In this case, the static value will be overriden.
2928 *
2929 * @abstract
2930 * @static
2931 * @inheritable
2932 * @property {jQuery|string|Function}
2933 */
2934 OO.ui.Dialog.static.title = '';
2935
2936 /**
2937 * An array of configured {@link OO.ui.ActionWidget action widgets}.
2938 *
2939 * Actions can also be specified with data passed to the constructor (see #getSetupProcess). In this case, the static
2940 * value will be overriden.
2941 *
2942 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Action_sets
2943 *
2944 * @static
2945 * @inheritable
2946 * @property {Object[]}
2947 */
2948 OO.ui.Dialog.static.actions = [];
2949
2950 /**
2951 * Close the dialog when the 'Esc' key is pressed.
2952 *
2953 * @static
2954 * @abstract
2955 * @inheritable
2956 * @property {boolean}
2957 */
2958 OO.ui.Dialog.static.escapable = true;
2959
2960 /* Methods */
2961
2962 /**
2963 * Handle frame document key down events.
2964 *
2965 * @private
2966 * @param {jQuery.Event} e Key down event
2967 */
2968 OO.ui.Dialog.prototype.onDialogKeyDown = function ( e ) {
2969 if ( e.which === OO.ui.Keys.ESCAPE ) {
2970 this.close();
2971 e.preventDefault();
2972 e.stopPropagation();
2973 }
2974 };
2975
2976 /**
2977 * Handle action resized events.
2978 *
2979 * @private
2980 * @param {OO.ui.ActionWidget} action Action that was resized
2981 */
2982 OO.ui.Dialog.prototype.onActionResize = function () {
2983 // Override in subclass
2984 };
2985
2986 /**
2987 * Handle action click events.
2988 *
2989 * @private
2990 * @param {OO.ui.ActionWidget} action Action that was clicked
2991 */
2992 OO.ui.Dialog.prototype.onActionClick = function ( action ) {
2993 if ( !this.isPending() ) {
2994 this.executeAction( action.getAction() );
2995 }
2996 };
2997
2998 /**
2999 * Handle actions change event.
3000 *
3001 * @private
3002 */
3003 OO.ui.Dialog.prototype.onActionsChange = function () {
3004 this.detachActions();
3005 if ( !this.isClosing() ) {
3006 this.attachActions();
3007 }
3008 };
3009
3010 /**
3011 * Get the set of actions used by the dialog.
3012 *
3013 * @return {OO.ui.ActionSet}
3014 */
3015 OO.ui.Dialog.prototype.getActions = function () {
3016 return this.actions;
3017 };
3018
3019 /**
3020 * Get a process for taking action.
3021 *
3022 * When you override this method, you can create a new OO.ui.Process and return it, or add additional
3023 * accept steps to the process the parent method provides using the {@link OO.ui.Process#first 'first'}
3024 * and {@link OO.ui.Process#next 'next'} methods of OO.ui.Process.
3025 *
3026 * @param {string} [action] Symbolic name of action
3027 * @return {OO.ui.Process} Action process
3028 */
3029 OO.ui.Dialog.prototype.getActionProcess = function ( action ) {
3030 return new OO.ui.Process()
3031 .next( function () {
3032 if ( !action ) {
3033 // An empty action always closes the dialog without data, which should always be
3034 // safe and make no changes
3035 this.close();
3036 }
3037 }, this );
3038 };
3039
3040 /**
3041 * @inheritdoc
3042 *
3043 * @param {Object} [data] Dialog opening data
3044 * @param {jQuery|string|Function|null} [data.title] Dialog title, omit to use
3045 * the {@link #static-title static title}
3046 * @param {Object[]} [data.actions] List of configuration options for each
3047 * {@link OO.ui.ActionWidget action widget}, omit to use {@link #static-actions static actions}.
3048 */
3049 OO.ui.Dialog.prototype.getSetupProcess = function ( data ) {
3050 data = data || {};
3051
3052 // Parent method
3053 return OO.ui.Dialog.parent.prototype.getSetupProcess.call( this, data )
3054 .next( function () {
3055 var config = this.constructor.static,
3056 actions = data.actions !== undefined ? data.actions : config.actions;
3057
3058 this.title.setLabel(
3059 data.title !== undefined ? data.title : this.constructor.static.title
3060 );
3061 this.actions.add( this.getActionWidgets( actions ) );
3062
3063 if ( this.constructor.static.escapable ) {
3064 this.$element.on( 'keydown', this.onDialogKeyDownHandler );
3065 }
3066 }, this );
3067 };
3068
3069 /**
3070 * @inheritdoc
3071 */
3072 OO.ui.Dialog.prototype.getTeardownProcess = function ( data ) {
3073 // Parent method
3074 return OO.ui.Dialog.parent.prototype.getTeardownProcess.call( this, data )
3075 .first( function () {
3076 if ( this.constructor.static.escapable ) {
3077 this.$element.off( 'keydown', this.onDialogKeyDownHandler );
3078 }
3079
3080 this.actions.clear();
3081 this.currentAction = null;
3082 }, this );
3083 };
3084
3085 /**
3086 * @inheritdoc
3087 */
3088 OO.ui.Dialog.prototype.initialize = function () {
3089 var titleId;
3090
3091 // Parent method
3092 OO.ui.Dialog.parent.prototype.initialize.call( this );
3093
3094 titleId = OO.ui.generateElementId();
3095
3096 // Properties
3097 this.title = new OO.ui.LabelWidget( {
3098 id: titleId
3099 } );
3100
3101 // Initialization
3102 this.$content.addClass( 'oo-ui-dialog-content' );
3103 this.$element.attr( 'aria-labelledby', titleId );
3104 this.setPendingElement( this.$head );
3105 };
3106
3107 /**
3108 * Get action widgets from a list of configs
3109 *
3110 * @param {Object[]} actions Action widget configs
3111 * @return {OO.ui.ActionWidget[]} Action widgets
3112 */
3113 OO.ui.Dialog.prototype.getActionWidgets = function ( actions ) {
3114 var i, len, widgets = [];
3115 for ( i = 0, len = actions.length; i < len; i++ ) {
3116 widgets.push(
3117 new OO.ui.ActionWidget( actions[ i ] )
3118 );
3119 }
3120 return widgets;
3121 };
3122
3123 /**
3124 * Attach action actions.
3125 *
3126 * @protected
3127 */
3128 OO.ui.Dialog.prototype.attachActions = function () {
3129 // Remember the list of potentially attached actions
3130 this.attachedActions = this.actions.get();
3131 };
3132
3133 /**
3134 * Detach action actions.
3135 *
3136 * @protected
3137 * @chainable
3138 */
3139 OO.ui.Dialog.prototype.detachActions = function () {
3140 var i, len;
3141
3142 // Detach all actions that may have been previously attached
3143 for ( i = 0, len = this.attachedActions.length; i < len; i++ ) {
3144 this.attachedActions[ i ].$element.detach();
3145 }
3146 this.attachedActions = [];
3147 };
3148
3149 /**
3150 * Execute an action.
3151 *
3152 * @param {string} action Symbolic name of action to execute
3153 * @return {jQuery.Promise} Promise resolved when action completes, rejected if it fails
3154 */
3155 OO.ui.Dialog.prototype.executeAction = function ( action ) {
3156 this.pushPending();
3157 this.currentAction = action;
3158 return this.getActionProcess( action ).execute()
3159 .always( this.popPending.bind( this ) );
3160 };
3161
3162 /**
3163 * Window managers are used to open and close {@link OO.ui.Window windows} and control their presentation.
3164 * Managed windows are mutually exclusive. If a new window is opened while a current window is opening
3165 * or is opened, the current window will be closed and any ongoing {@link OO.ui.Process process} will be cancelled. Windows
3166 * themselves are persistent and—rather than being torn down when closed—can be repopulated with the
3167 * pertinent data and reused.
3168 *
3169 * Over the lifecycle of a window, the window manager makes available three promises: `opening`,
3170 * `opened`, and `closing`, which represent the primary stages of the cycle:
3171 *
3172 * **Opening**: the opening stage begins when the window manager’s #openWindow or a window’s
3173 * {@link OO.ui.Window#open open} method is used, and the window manager begins to open the window.
3174 *
3175 * - an `opening` event is emitted with an `opening` promise
3176 * - the #getSetupDelay method is called and the returned value is used to time a pause in execution before
3177 * the window’s {@link OO.ui.Window#getSetupProcess getSetupProcess} method is called on the
3178 * window and its result executed
3179 * - a `setup` progress notification is emitted from the `opening` promise
3180 * - the #getReadyDelay method is called the returned value is used to time a pause in execution before
3181 * the window’s {@link OO.ui.Window#getReadyProcess getReadyProcess} method is called on the
3182 * window and its result executed
3183 * - a `ready` progress notification is emitted from the `opening` promise
3184 * - the `opening` promise is resolved with an `opened` promise
3185 *
3186 * **Opened**: the window is now open.
3187 *
3188 * **Closing**: the closing stage begins when the window manager's #closeWindow or the
3189 * window's {@link OO.ui.Window#close close} methods is used, and the window manager begins
3190 * to close the window.
3191 *
3192 * - the `opened` promise is resolved with `closing` promise and a `closing` event is emitted
3193 * - the #getHoldDelay method is called and the returned value is used to time a pause in execution before
3194 * the window's {@link OO.ui.Window#getHoldProcess getHoldProces} method is called on the
3195 * window and its result executed
3196 * - a `hold` progress notification is emitted from the `closing` promise
3197 * - the #getTeardownDelay() method is called and the returned value is used to time a pause in execution before
3198 * the window's {@link OO.ui.Window#getTeardownProcess getTeardownProcess} method is called on the
3199 * window and its result executed
3200 * - a `teardown` progress notification is emitted from the `closing` promise
3201 * - the `closing` promise is resolved. The window is now closed
3202 *
3203 * See the [OOjs UI documentation on MediaWiki][1] for more information.
3204 *
3205 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
3206 *
3207 * @class
3208 * @extends OO.ui.Element
3209 * @mixins OO.EventEmitter
3210 *
3211 * @constructor
3212 * @param {Object} [config] Configuration options
3213 * @cfg {OO.Factory} [factory] Window factory to use for automatic instantiation
3214 * Note that window classes that are instantiated with a factory must have
3215 * a {@link OO.ui.Dialog#static-name static name} property that specifies a symbolic name.
3216 * @cfg {boolean} [modal=true] Prevent interaction outside the dialog
3217 */
3218 OO.ui.WindowManager = function OoUiWindowManager( config ) {
3219 // Configuration initialization
3220 config = config || {};
3221
3222 // Parent constructor
3223 OO.ui.WindowManager.parent.call( this, config );
3224
3225 // Mixin constructors
3226 OO.EventEmitter.call( this );
3227
3228 // Properties
3229 this.factory = config.factory;
3230 this.modal = config.modal === undefined || !!config.modal;
3231 this.windows = {};
3232 this.opening = null;
3233 this.opened = null;
3234 this.closing = null;
3235 this.preparingToOpen = null;
3236 this.preparingToClose = null;
3237 this.currentWindow = null;
3238 this.globalEvents = false;
3239 this.$ariaHidden = null;
3240 this.onWindowResizeTimeout = null;
3241 this.onWindowResizeHandler = this.onWindowResize.bind( this );
3242 this.afterWindowResizeHandler = this.afterWindowResize.bind( this );
3243
3244 // Initialization
3245 this.$element
3246 .addClass( 'oo-ui-windowManager' )
3247 .toggleClass( 'oo-ui-windowManager-modal', this.modal );
3248 };
3249
3250 /* Setup */
3251
3252 OO.inheritClass( OO.ui.WindowManager, OO.ui.Element );
3253 OO.mixinClass( OO.ui.WindowManager, OO.EventEmitter );
3254
3255 /* Events */
3256
3257 /**
3258 * An 'opening' event is emitted when the window begins to be opened.
3259 *
3260 * @event opening
3261 * @param {OO.ui.Window} win Window that's being opened
3262 * @param {jQuery.Promise} opening An `opening` promise resolved with a value when the window is opened successfully.
3263 * When the `opening` promise is resolved, the first argument of the value is an 'opened' promise, the second argument
3264 * is the opening data. The `opening` promise emits `setup` and `ready` notifications when those processes are complete.
3265 * @param {Object} data Window opening data
3266 */
3267
3268 /**
3269 * A 'closing' event is emitted when the window begins to be closed.
3270 *
3271 * @event closing
3272 * @param {OO.ui.Window} win Window that's being closed
3273 * @param {jQuery.Promise} closing A `closing` promise is resolved with a value when the window
3274 * is closed successfully. The promise emits `hold` and `teardown` notifications when those
3275 * processes are complete. When the `closing` promise is resolved, the first argument of its value
3276 * is the closing data.
3277 * @param {Object} data Window closing data
3278 */
3279
3280 /**
3281 * A 'resize' event is emitted when a window is resized.
3282 *
3283 * @event resize
3284 * @param {OO.ui.Window} win Window that was resized
3285 */
3286
3287 /* Static Properties */
3288
3289 /**
3290 * Map of the symbolic name of each window size and its CSS properties.
3291 *
3292 * @static
3293 * @inheritable
3294 * @property {Object}
3295 */
3296 OO.ui.WindowManager.static.sizes = {
3297 small: {
3298 width: 300
3299 },
3300 medium: {
3301 width: 500
3302 },
3303 large: {
3304 width: 700
3305 },
3306 larger: {
3307 width: 900
3308 },
3309 full: {
3310 // These can be non-numeric because they are never used in calculations
3311 width: '100%',
3312 height: '100%'
3313 }
3314 };
3315
3316 /**
3317 * Symbolic name of the default window size.
3318 *
3319 * The default size is used if the window's requested size is not recognized.
3320 *
3321 * @static
3322 * @inheritable
3323 * @property {string}
3324 */
3325 OO.ui.WindowManager.static.defaultSize = 'medium';
3326
3327 /* Methods */
3328
3329 /**
3330 * Handle window resize events.
3331 *
3332 * @private
3333 * @param {jQuery.Event} e Window resize event
3334 */
3335 OO.ui.WindowManager.prototype.onWindowResize = function () {
3336 clearTimeout( this.onWindowResizeTimeout );
3337 this.onWindowResizeTimeout = setTimeout( this.afterWindowResizeHandler, 200 );
3338 };
3339
3340 /**
3341 * Handle window resize events.
3342 *
3343 * @private
3344 * @param {jQuery.Event} e Window resize event
3345 */
3346 OO.ui.WindowManager.prototype.afterWindowResize = function () {
3347 if ( this.currentWindow ) {
3348 this.updateWindowSize( this.currentWindow );
3349 }
3350 };
3351
3352 /**
3353 * Check if window is opening.
3354 *
3355 * @return {boolean} Window is opening
3356 */
3357 OO.ui.WindowManager.prototype.isOpening = function ( win ) {
3358 return win === this.currentWindow && !!this.opening && this.opening.state() === 'pending';
3359 };
3360
3361 /**
3362 * Check if window is closing.
3363 *
3364 * @return {boolean} Window is closing
3365 */
3366 OO.ui.WindowManager.prototype.isClosing = function ( win ) {
3367 return win === this.currentWindow && !!this.closing && this.closing.state() === 'pending';
3368 };
3369
3370 /**
3371 * Check if window is opened.
3372 *
3373 * @return {boolean} Window is opened
3374 */
3375 OO.ui.WindowManager.prototype.isOpened = function ( win ) {
3376 return win === this.currentWindow && !!this.opened && this.opened.state() === 'pending';
3377 };
3378
3379 /**
3380 * Check if a window is being managed.
3381 *
3382 * @param {OO.ui.Window} win Window to check
3383 * @return {boolean} Window is being managed
3384 */
3385 OO.ui.WindowManager.prototype.hasWindow = function ( win ) {
3386 var name;
3387
3388 for ( name in this.windows ) {
3389 if ( this.windows[ name ] === win ) {
3390 return true;
3391 }
3392 }
3393
3394 return false;
3395 };
3396
3397 /**
3398 * Get the number of milliseconds to wait after opening begins before executing the ‘setup’ process.
3399 *
3400 * @param {OO.ui.Window} win Window being opened
3401 * @param {Object} [data] Window opening data
3402 * @return {number} Milliseconds to wait
3403 */
3404 OO.ui.WindowManager.prototype.getSetupDelay = function () {
3405 return 0;
3406 };
3407
3408 /**
3409 * Get the number of milliseconds to wait after setup has finished before executing the ‘ready’ process.
3410 *
3411 * @param {OO.ui.Window} win Window being opened
3412 * @param {Object} [data] Window opening data
3413 * @return {number} Milliseconds to wait
3414 */
3415 OO.ui.WindowManager.prototype.getReadyDelay = function () {
3416 return 0;
3417 };
3418
3419 /**
3420 * Get the number of milliseconds to wait after closing has begun before executing the 'hold' process.
3421 *
3422 * @param {OO.ui.Window} win Window being closed
3423 * @param {Object} [data] Window closing data
3424 * @return {number} Milliseconds to wait
3425 */
3426 OO.ui.WindowManager.prototype.getHoldDelay = function () {
3427 return 0;
3428 };
3429
3430 /**
3431 * Get the number of milliseconds to wait after the ‘hold’ process has finished before
3432 * executing the ‘teardown’ process.
3433 *
3434 * @param {OO.ui.Window} win Window being closed
3435 * @param {Object} [data] Window closing data
3436 * @return {number} Milliseconds to wait
3437 */
3438 OO.ui.WindowManager.prototype.getTeardownDelay = function () {
3439 return this.modal ? 250 : 0;
3440 };
3441
3442 /**
3443 * Get a window by its symbolic name.
3444 *
3445 * If the window is not yet instantiated and its symbolic name is recognized by a factory, it will be
3446 * instantiated and added to the window manager automatically. Please see the [OOjs UI documentation on MediaWiki][3]
3447 * for more information about using factories.
3448 * [3]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
3449 *
3450 * @param {string} name Symbolic name of the window
3451 * @return {jQuery.Promise} Promise resolved with matching window, or rejected with an OO.ui.Error
3452 * @throws {Error} An error is thrown if the symbolic name is not recognized by the factory.
3453 * @throws {Error} An error is thrown if the named window is not recognized as a managed window.
3454 */
3455 OO.ui.WindowManager.prototype.getWindow = function ( name ) {
3456 var deferred = $.Deferred(),
3457 win = this.windows[ name ];
3458
3459 if ( !( win instanceof OO.ui.Window ) ) {
3460 if ( this.factory ) {
3461 if ( !this.factory.lookup( name ) ) {
3462 deferred.reject( new OO.ui.Error(
3463 'Cannot auto-instantiate window: symbolic name is unrecognized by the factory'
3464 ) );
3465 } else {
3466 win = this.factory.create( name );
3467 this.addWindows( [ win ] );
3468 deferred.resolve( win );
3469 }
3470 } else {
3471 deferred.reject( new OO.ui.Error(
3472 'Cannot get unmanaged window: symbolic name unrecognized as a managed window'
3473 ) );
3474 }
3475 } else {
3476 deferred.resolve( win );
3477 }
3478
3479 return deferred.promise();
3480 };
3481
3482 /**
3483 * Get current window.
3484 *
3485 * @return {OO.ui.Window|null} Currently opening/opened/closing window
3486 */
3487 OO.ui.WindowManager.prototype.getCurrentWindow = function () {
3488 return this.currentWindow;
3489 };
3490
3491 /**
3492 * Open a window.
3493 *
3494 * @param {OO.ui.Window|string} win Window object or symbolic name of window to open
3495 * @param {Object} [data] Window opening data
3496 * @return {jQuery.Promise} An `opening` promise resolved when the window is done opening.
3497 * See {@link #event-opening 'opening' event} for more information about `opening` promises.
3498 * @fires opening
3499 */
3500 OO.ui.WindowManager.prototype.openWindow = function ( win, data ) {
3501 var manager = this,
3502 opening = $.Deferred();
3503
3504 // Argument handling
3505 if ( typeof win === 'string' ) {
3506 return this.getWindow( win ).then( function ( win ) {
3507 return manager.openWindow( win, data );
3508 } );
3509 }
3510
3511 // Error handling
3512 if ( !this.hasWindow( win ) ) {
3513 opening.reject( new OO.ui.Error(
3514 'Cannot open window: window is not attached to manager'
3515 ) );
3516 } else if ( this.preparingToOpen || this.opening || this.opened ) {
3517 opening.reject( new OO.ui.Error(
3518 'Cannot open window: another window is opening or open'
3519 ) );
3520 }
3521
3522 // Window opening
3523 if ( opening.state() !== 'rejected' ) {
3524 // If a window is currently closing, wait for it to complete
3525 this.preparingToOpen = $.when( this.closing );
3526 // Ensure handlers get called after preparingToOpen is set
3527 this.preparingToOpen.done( function () {
3528 if ( manager.modal ) {
3529 manager.toggleGlobalEvents( true );
3530 manager.toggleAriaIsolation( true );
3531 }
3532 manager.currentWindow = win;
3533 manager.opening = opening;
3534 manager.preparingToOpen = null;
3535 manager.emit( 'opening', win, opening, data );
3536 setTimeout( function () {
3537 win.setup( data ).then( function () {
3538 manager.updateWindowSize( win );
3539 manager.opening.notify( { state: 'setup' } );
3540 setTimeout( function () {
3541 win.ready( data ).then( function () {
3542 manager.opening.notify( { state: 'ready' } );
3543 manager.opening = null;
3544 manager.opened = $.Deferred();
3545 opening.resolve( manager.opened.promise(), data );
3546 }, function () {
3547 manager.opening = null;
3548 manager.opened = $.Deferred();
3549 opening.reject();
3550 manager.closeWindow( win );
3551 } );
3552 }, manager.getReadyDelay() );
3553 }, function () {
3554 manager.opening = null;
3555 manager.opened = $.Deferred();
3556 opening.reject();
3557 manager.closeWindow( win );
3558 } );
3559 }, manager.getSetupDelay() );
3560 } );
3561 }
3562
3563 return opening.promise();
3564 };
3565
3566 /**
3567 * Close a window.
3568 *
3569 * @param {OO.ui.Window|string} win Window object or symbolic name of window to close
3570 * @param {Object} [data] Window closing data
3571 * @return {jQuery.Promise} A `closing` promise resolved when the window is done closing.
3572 * See {@link #event-closing 'closing' event} for more information about closing promises.
3573 * @throws {Error} An error is thrown if the window is not managed by the window manager.
3574 * @fires closing
3575 */
3576 OO.ui.WindowManager.prototype.closeWindow = function ( win, data ) {
3577 var manager = this,
3578 closing = $.Deferred(),
3579 opened;
3580
3581 // Argument handling
3582 if ( typeof win === 'string' ) {
3583 win = this.windows[ win ];
3584 } else if ( !this.hasWindow( win ) ) {
3585 win = null;
3586 }
3587
3588 // Error handling
3589 if ( !win ) {
3590 closing.reject( new OO.ui.Error(
3591 'Cannot close window: window is not attached to manager'
3592 ) );
3593 } else if ( win !== this.currentWindow ) {
3594 closing.reject( new OO.ui.Error(
3595 'Cannot close window: window already closed with different data'
3596 ) );
3597 } else if ( this.preparingToClose || this.closing ) {
3598 closing.reject( new OO.ui.Error(
3599 'Cannot close window: window already closing with different data'
3600 ) );
3601 }
3602
3603 // Window closing
3604 if ( closing.state() !== 'rejected' ) {
3605 // If the window is currently opening, close it when it's done
3606 this.preparingToClose = $.when( this.opening );
3607 // Ensure handlers get called after preparingToClose is set
3608 this.preparingToClose.always( function () {
3609 manager.closing = closing;
3610 manager.preparingToClose = null;
3611 manager.emit( 'closing', win, closing, data );
3612 opened = manager.opened;
3613 manager.opened = null;
3614 opened.resolve( closing.promise(), data );
3615 setTimeout( function () {
3616 win.hold( data ).then( function () {
3617 closing.notify( { state: 'hold' } );
3618 setTimeout( function () {
3619 win.teardown( data ).then( function () {
3620 closing.notify( { state: 'teardown' } );
3621 if ( manager.modal ) {
3622 manager.toggleGlobalEvents( false );
3623 manager.toggleAriaIsolation( false );
3624 }
3625 manager.closing = null;
3626 manager.currentWindow = null;
3627 closing.resolve( data );
3628 } );
3629 }, manager.getTeardownDelay() );
3630 } );
3631 }, manager.getHoldDelay() );
3632 } );
3633 }
3634
3635 return closing.promise();
3636 };
3637
3638 /**
3639 * Add windows to the window manager.
3640 *
3641 * Windows can be added by reference, symbolic name, or explicitly defined symbolic names.
3642 * See the [OOjs ui documentation on MediaWiki] [2] for examples.
3643 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
3644 *
3645 * @param {Object.<string,OO.ui.Window>|OO.ui.Window[]} windows An array of window objects specified
3646 * by reference, symbolic name, or explicitly defined symbolic names.
3647 * @throws {Error} An error is thrown if a window is added by symbolic name, but has neither an
3648 * explicit nor a statically configured symbolic name.
3649 */
3650 OO.ui.WindowManager.prototype.addWindows = function ( windows ) {
3651 var i, len, win, name, list;
3652
3653 if ( Array.isArray( windows ) ) {
3654 // Convert to map of windows by looking up symbolic names from static configuration
3655 list = {};
3656 for ( i = 0, len = windows.length; i < len; i++ ) {
3657 name = windows[ i ].constructor.static.name;
3658 if ( typeof name !== 'string' ) {
3659 throw new Error( 'Cannot add window' );
3660 }
3661 list[ name ] = windows[ i ];
3662 }
3663 } else if ( OO.isPlainObject( windows ) ) {
3664 list = windows;
3665 }
3666
3667 // Add windows
3668 for ( name in list ) {
3669 win = list[ name ];
3670 this.windows[ name ] = win.toggle( false );
3671 this.$element.append( win.$element );
3672 win.setManager( this );
3673 }
3674 };
3675
3676 /**
3677 * Remove the specified windows from the windows manager.
3678 *
3679 * Windows will be closed before they are removed. If you wish to remove all windows, you may wish to use
3680 * the #clearWindows method instead. If you no longer need the window manager and want to ensure that it no
3681 * longer listens to events, use the #destroy method.
3682 *
3683 * @param {string[]} names Symbolic names of windows to remove
3684 * @return {jQuery.Promise} Promise resolved when window is closed and removed
3685 * @throws {Error} An error is thrown if the named windows are not managed by the window manager.
3686 */
3687 OO.ui.WindowManager.prototype.removeWindows = function ( names ) {
3688 var i, len, win, name, cleanupWindow,
3689 manager = this,
3690 promises = [],
3691 cleanup = function ( name, win ) {
3692 delete manager.windows[ name ];
3693 win.$element.detach();
3694 };
3695
3696 for ( i = 0, len = names.length; i < len; i++ ) {
3697 name = names[ i ];
3698 win = this.windows[ name ];
3699 if ( !win ) {
3700 throw new Error( 'Cannot remove window' );
3701 }
3702 cleanupWindow = cleanup.bind( null, name, win );
3703 promises.push( this.closeWindow( name ).then( cleanupWindow, cleanupWindow ) );
3704 }
3705
3706 return $.when.apply( $, promises );
3707 };
3708
3709 /**
3710 * Remove all windows from the window manager.
3711 *
3712 * Windows will be closed before they are removed. Note that the window manager, though not in use, will still
3713 * listen to events. If the window manager will not be used again, you may wish to use the #destroy method instead.
3714 * To remove just a subset of windows, use the #removeWindows method.
3715 *
3716 * @return {jQuery.Promise} Promise resolved when all windows are closed and removed
3717 */
3718 OO.ui.WindowManager.prototype.clearWindows = function () {
3719 return this.removeWindows( Object.keys( this.windows ) );
3720 };
3721
3722 /**
3723 * Set dialog size. In general, this method should not be called directly.
3724 *
3725 * Fullscreen mode will be used if the dialog is too wide to fit in the screen.
3726 *
3727 * @chainable
3728 */
3729 OO.ui.WindowManager.prototype.updateWindowSize = function ( win ) {
3730 var isFullscreen;
3731
3732 // Bypass for non-current, and thus invisible, windows
3733 if ( win !== this.currentWindow ) {
3734 return;
3735 }
3736
3737 isFullscreen = win.getSize() === 'full';
3738
3739 this.$element.toggleClass( 'oo-ui-windowManager-fullscreen', isFullscreen );
3740 this.$element.toggleClass( 'oo-ui-windowManager-floating', !isFullscreen );
3741 win.setDimensions( win.getSizeProperties() );
3742
3743 this.emit( 'resize', win );
3744
3745 return this;
3746 };
3747
3748 /**
3749 * Bind or unbind global events for scrolling.
3750 *
3751 * @private
3752 * @param {boolean} [on] Bind global events
3753 * @chainable
3754 */
3755 OO.ui.WindowManager.prototype.toggleGlobalEvents = function ( on ) {
3756 var scrollWidth, bodyMargin,
3757 $body = $( this.getElementDocument().body ),
3758 // We could have multiple window managers open so only modify
3759 // the body css at the bottom of the stack
3760 stackDepth = $body.data( 'windowManagerGlobalEvents' ) || 0 ;
3761
3762 on = on === undefined ? !!this.globalEvents : !!on;
3763
3764 if ( on ) {
3765 if ( !this.globalEvents ) {
3766 $( this.getElementWindow() ).on( {
3767 // Start listening for top-level window dimension changes
3768 'orientationchange resize': this.onWindowResizeHandler
3769 } );
3770 if ( stackDepth === 0 ) {
3771 scrollWidth = window.innerWidth - document.documentElement.clientWidth;
3772 bodyMargin = parseFloat( $body.css( 'margin-right' ) ) || 0;
3773 $body.css( {
3774 overflow: 'hidden',
3775 'margin-right': bodyMargin + scrollWidth
3776 } );
3777 }
3778 stackDepth++;
3779 this.globalEvents = true;
3780 }
3781 } else if ( this.globalEvents ) {
3782 $( this.getElementWindow() ).off( {
3783 // Stop listening for top-level window dimension changes
3784 'orientationchange resize': this.onWindowResizeHandler
3785 } );
3786 stackDepth--;
3787 if ( stackDepth === 0 ) {
3788 $body.css( {
3789 overflow: '',
3790 'margin-right': ''
3791 } );
3792 }
3793 this.globalEvents = false;
3794 }
3795 $body.data( 'windowManagerGlobalEvents', stackDepth );
3796
3797 return this;
3798 };
3799
3800 /**
3801 * Toggle screen reader visibility of content other than the window manager.
3802 *
3803 * @private
3804 * @param {boolean} [isolate] Make only the window manager visible to screen readers
3805 * @chainable
3806 */
3807 OO.ui.WindowManager.prototype.toggleAriaIsolation = function ( isolate ) {
3808 isolate = isolate === undefined ? !this.$ariaHidden : !!isolate;
3809
3810 if ( isolate ) {
3811 if ( !this.$ariaHidden ) {
3812 // Hide everything other than the window manager from screen readers
3813 this.$ariaHidden = $( 'body' )
3814 .children()
3815 .not( this.$element.parentsUntil( 'body' ).last() )
3816 .attr( 'aria-hidden', '' );
3817 }
3818 } else if ( this.$ariaHidden ) {
3819 // Restore screen reader visibility
3820 this.$ariaHidden.removeAttr( 'aria-hidden' );
3821 this.$ariaHidden = null;
3822 }
3823
3824 return this;
3825 };
3826
3827 /**
3828 * Destroy the window manager.
3829 *
3830 * Destroying the window manager ensures that it will no longer listen to events. If you would like to
3831 * continue using the window manager, but wish to remove all windows from it, use the #clearWindows method
3832 * instead.
3833 */
3834 OO.ui.WindowManager.prototype.destroy = function () {
3835 this.toggleGlobalEvents( false );
3836 this.toggleAriaIsolation( false );
3837 this.clearWindows();
3838 this.$element.remove();
3839 };
3840
3841 /**
3842 * Errors contain a required message (either a string or jQuery selection) that is used to describe what went wrong
3843 * in a {@link OO.ui.Process process}. The error's #recoverable and #warning configurations are used to customize the
3844 * appearance and functionality of the error interface.
3845 *
3846 * The basic error interface contains a formatted error message as well as two buttons: 'Dismiss' and 'Try again' (i.e., the error
3847 * is 'recoverable' by default). If the error is not recoverable, the 'Try again' button will not be rendered and the widget
3848 * that initiated the failed process will be disabled.
3849 *
3850 * If the error is a warning, the error interface will include a 'Dismiss' and a 'Continue' button, which will try the
3851 * process again.
3852 *
3853 * For an example of error interfaces, please see the [OOjs UI documentation on MediaWiki][1].
3854 *
3855 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Processes_and_errors
3856 *
3857 * @class
3858 *
3859 * @constructor
3860 * @param {string|jQuery} message Description of error
3861 * @param {Object} [config] Configuration options
3862 * @cfg {boolean} [recoverable=true] Error is recoverable.
3863 * By default, errors are recoverable, and users can try the process again.
3864 * @cfg {boolean} [warning=false] Error is a warning.
3865 * If the error is a warning, the error interface will include a
3866 * 'Dismiss' and a 'Continue' button. It is the responsibility of the developer to ensure that the warning
3867 * is not triggered a second time if the user chooses to continue.
3868 */
3869 OO.ui.Error = function OoUiError( message, config ) {
3870 // Allow passing positional parameters inside the config object
3871 if ( OO.isPlainObject( message ) && config === undefined ) {
3872 config = message;
3873 message = config.message;
3874 }
3875
3876 // Configuration initialization
3877 config = config || {};
3878
3879 // Properties
3880 this.message = message instanceof jQuery ? message : String( message );
3881 this.recoverable = config.recoverable === undefined || !!config.recoverable;
3882 this.warning = !!config.warning;
3883 };
3884
3885 /* Setup */
3886
3887 OO.initClass( OO.ui.Error );
3888
3889 /* Methods */
3890
3891 /**
3892 * Check if the error is recoverable.
3893 *
3894 * If the error is recoverable, users are able to try the process again.
3895 *
3896 * @return {boolean} Error is recoverable
3897 */
3898 OO.ui.Error.prototype.isRecoverable = function () {
3899 return this.recoverable;
3900 };
3901
3902 /**
3903 * Check if the error is a warning.
3904 *
3905 * If the error is a warning, the error interface will include a 'Dismiss' and a 'Continue' button.
3906 *
3907 * @return {boolean} Error is warning
3908 */
3909 OO.ui.Error.prototype.isWarning = function () {
3910 return this.warning;
3911 };
3912
3913 /**
3914 * Get error message as DOM nodes.
3915 *
3916 * @return {jQuery} Error message in DOM nodes
3917 */
3918 OO.ui.Error.prototype.getMessage = function () {
3919 return this.message instanceof jQuery ?
3920 this.message.clone() :
3921 $( '<div>' ).text( this.message ).contents();
3922 };
3923
3924 /**
3925 * Get the error message text.
3926 *
3927 * @return {string} Error message
3928 */
3929 OO.ui.Error.prototype.getMessageText = function () {
3930 return this.message instanceof jQuery ? this.message.text() : this.message;
3931 };
3932
3933 /**
3934 * Wraps an HTML snippet for use with configuration values which default
3935 * to strings. This bypasses the default html-escaping done to string
3936 * values.
3937 *
3938 * @class
3939 *
3940 * @constructor
3941 * @param {string} [content] HTML content
3942 */
3943 OO.ui.HtmlSnippet = function OoUiHtmlSnippet( content ) {
3944 // Properties
3945 this.content = content;
3946 };
3947
3948 /* Setup */
3949
3950 OO.initClass( OO.ui.HtmlSnippet );
3951
3952 /* Methods */
3953
3954 /**
3955 * Render into HTML.
3956 *
3957 * @return {string} Unchanged HTML snippet.
3958 */
3959 OO.ui.HtmlSnippet.prototype.toString = function () {
3960 return this.content;
3961 };
3962
3963 /**
3964 * A Process is a list of steps that are called in sequence. The step can be a number, a jQuery promise,
3965 * or a function:
3966 *
3967 * - **number**: the process will wait for the specified number of milliseconds before proceeding.
3968 * - **promise**: the process will continue to the next step when the promise is successfully resolved
3969 * or stop if the promise is rejected.
3970 * - **function**: the process will execute the function. The process will stop if the function returns
3971 * either a boolean `false` or a promise that is rejected; if the function returns a number, the process
3972 * will wait for that number of milliseconds before proceeding.
3973 *
3974 * If the process fails, an {@link OO.ui.Error error} is generated. Depending on how the error is
3975 * configured, users can dismiss the error and try the process again, or not. If a process is stopped,
3976 * its remaining steps will not be performed.
3977 *
3978 * @class
3979 *
3980 * @constructor
3981 * @param {number|jQuery.Promise|Function} step Number of miliseconds to wait before proceeding, promise
3982 * that must be resolved before proceeding, or a function to execute. See #createStep for more information. see #createStep for more information
3983 * @param {Object} [context=null] Execution context of the function. The context is ignored if the step is
3984 * a number or promise.
3985 * @return {Object} Step object, with `callback` and `context` properties
3986 */
3987 OO.ui.Process = function ( step, context ) {
3988 // Properties
3989 this.steps = [];
3990
3991 // Initialization
3992 if ( step !== undefined ) {
3993 this.next( step, context );
3994 }
3995 };
3996
3997 /* Setup */
3998
3999 OO.initClass( OO.ui.Process );
4000
4001 /* Methods */
4002
4003 /**
4004 * Start the process.
4005 *
4006 * @return {jQuery.Promise} Promise that is resolved when all steps have successfully completed.
4007 * If any of the steps return a promise that is rejected or a boolean false, this promise is rejected
4008 * and any remaining steps are not performed.
4009 */
4010 OO.ui.Process.prototype.execute = function () {
4011 var i, len, promise;
4012
4013 /**
4014 * Continue execution.
4015 *
4016 * @ignore
4017 * @param {Array} step A function and the context it should be called in
4018 * @return {Function} Function that continues the process
4019 */
4020 function proceed( step ) {
4021 return function () {
4022 // Execute step in the correct context
4023 var deferred,
4024 result = step.callback.call( step.context );
4025
4026 if ( result === false ) {
4027 // Use rejected promise for boolean false results
4028 return $.Deferred().reject( [] ).promise();
4029 }
4030 if ( typeof result === 'number' ) {
4031 if ( result < 0 ) {
4032 throw new Error( 'Cannot go back in time: flux capacitor is out of service' );
4033 }
4034 // Use a delayed promise for numbers, expecting them to be in milliseconds
4035 deferred = $.Deferred();
4036 setTimeout( deferred.resolve, result );
4037 return deferred.promise();
4038 }
4039 if ( result instanceof OO.ui.Error ) {
4040 // Use rejected promise for error
4041 return $.Deferred().reject( [ result ] ).promise();
4042 }
4043 if ( Array.isArray( result ) && result.length && result[ 0 ] instanceof OO.ui.Error ) {
4044 // Use rejected promise for list of errors
4045 return $.Deferred().reject( result ).promise();
4046 }
4047 // Duck-type the object to see if it can produce a promise
4048 if ( result && $.isFunction( result.promise ) ) {
4049 // Use a promise generated from the result
4050 return result.promise();
4051 }
4052 // Use resolved promise for other results
4053 return $.Deferred().resolve().promise();
4054 };
4055 }
4056
4057 if ( this.steps.length ) {
4058 // Generate a chain reaction of promises
4059 promise = proceed( this.steps[ 0 ] )();
4060 for ( i = 1, len = this.steps.length; i < len; i++ ) {
4061 promise = promise.then( proceed( this.steps[ i ] ) );
4062 }
4063 } else {
4064 promise = $.Deferred().resolve().promise();
4065 }
4066
4067 return promise;
4068 };
4069
4070 /**
4071 * Create a process step.
4072 *
4073 * @private
4074 * @param {number|jQuery.Promise|Function} step
4075 *
4076 * - Number of milliseconds to wait before proceeding
4077 * - Promise that must be resolved before proceeding
4078 * - Function to execute
4079 * - If the function returns a boolean false the process will stop
4080 * - If the function returns a promise, the process will continue to the next
4081 * step when the promise is resolved or stop if the promise is rejected
4082 * - If the function returns a number, the process will wait for that number of
4083 * milliseconds before proceeding
4084 * @param {Object} [context=null] Execution context of the function. The context is
4085 * ignored if the step is a number or promise.
4086 * @return {Object} Step object, with `callback` and `context` properties
4087 */
4088 OO.ui.Process.prototype.createStep = function ( step, context ) {
4089 if ( typeof step === 'number' || $.isFunction( step.promise ) ) {
4090 return {
4091 callback: function () {
4092 return step;
4093 },
4094 context: null
4095 };
4096 }
4097 if ( $.isFunction( step ) ) {
4098 return {
4099 callback: step,
4100 context: context
4101 };
4102 }
4103 throw new Error( 'Cannot create process step: number, promise or function expected' );
4104 };
4105
4106 /**
4107 * Add step to the beginning of the process.
4108 *
4109 * @inheritdoc #createStep
4110 * @return {OO.ui.Process} this
4111 * @chainable
4112 */
4113 OO.ui.Process.prototype.first = function ( step, context ) {
4114 this.steps.unshift( this.createStep( step, context ) );
4115 return this;
4116 };
4117
4118 /**
4119 * Add step to the end of the process.
4120 *
4121 * @inheritdoc #createStep
4122 * @return {OO.ui.Process} this
4123 * @chainable
4124 */
4125 OO.ui.Process.prototype.next = function ( step, context ) {
4126 this.steps.push( this.createStep( step, context ) );
4127 return this;
4128 };
4129
4130 /**
4131 * A ToolFactory creates tools on demand. All tools ({@link OO.ui.Tool Tools}, {@link OO.ui.PopupTool PopupTools},
4132 * and {@link OO.ui.ToolGroupTool ToolGroupTools}) must be registered with a tool factory. Tools are
4133 * registered by their symbolic name. See {@link OO.ui.Toolbar toolbars} for an example.
4134 *
4135 * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki][1].
4136 *
4137 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
4138 *
4139 * @class
4140 * @extends OO.Factory
4141 * @constructor
4142 */
4143 OO.ui.ToolFactory = function OoUiToolFactory() {
4144 // Parent constructor
4145 OO.ui.ToolFactory.parent.call( this );
4146 };
4147
4148 /* Setup */
4149
4150 OO.inheritClass( OO.ui.ToolFactory, OO.Factory );
4151
4152 /* Methods */
4153
4154 /**
4155 * Get tools from the factory
4156 *
4157 * @param {Array|string} [include] Included tools, see #extract for format
4158 * @param {Array|string} [exclude] Excluded tools, see #extract for format
4159 * @param {Array|string} [promote] Promoted tools, see #extract for format
4160 * @param {Array|string} [demote] Demoted tools, see #extract for format
4161 * @return {string[]} List of tools
4162 */
4163 OO.ui.ToolFactory.prototype.getTools = function ( include, exclude, promote, demote ) {
4164 var i, len, included, promoted, demoted,
4165 auto = [],
4166 used = {};
4167
4168 // Collect included and not excluded tools
4169 included = OO.simpleArrayDifference( this.extract( include ), this.extract( exclude ) );
4170
4171 // Promotion
4172 promoted = this.extract( promote, used );
4173 demoted = this.extract( demote, used );
4174
4175 // Auto
4176 for ( i = 0, len = included.length; i < len; i++ ) {
4177 if ( !used[ included[ i ] ] ) {
4178 auto.push( included[ i ] );
4179 }
4180 }
4181
4182 return promoted.concat( auto ).concat( demoted );
4183 };
4184
4185 /**
4186 * Get a flat list of names from a list of names or groups.
4187 *
4188 * Normally, `collection` is an array of tool specifications. Tools can be specified in the
4189 * following ways:
4190 *
4191 * - To include an individual tool, use the symbolic name: `{ name: 'tool-name' }` or `'tool-name'`.
4192 * - To include all tools in a group, use the group name: `{ group: 'group-name' }`. (To assign the
4193 * tool to a group, use OO.ui.Tool.static.group.)
4194 *
4195 * Alternatively, to include all tools that are not yet assigned to any other toolgroup, use the
4196 * catch-all selector `'*'`.
4197 *
4198 * If `used` is passed, tool names that appear as properties in this object will be considered
4199 * already assigned, and will not be returned even if specified otherwise. The tool names extracted
4200 * by this function call will be added as new properties in the object.
4201 *
4202 * @private
4203 * @param {Array|string} collection List of tools, see above
4204 * @param {Object} [used] Object containing information about used tools, see above
4205 * @return {string[]} List of extracted tool names
4206 */
4207 OO.ui.ToolFactory.prototype.extract = function ( collection, used ) {
4208 var i, len, item, name, tool,
4209 names = [];
4210
4211 if ( collection === '*' ) {
4212 for ( name in this.registry ) {
4213 tool = this.registry[ name ];
4214 if (
4215 // Only add tools by group name when auto-add is enabled
4216 tool.static.autoAddToCatchall &&
4217 // Exclude already used tools
4218 ( !used || !used[ name ] )
4219 ) {
4220 names.push( name );
4221 if ( used ) {
4222 used[ name ] = true;
4223 }
4224 }
4225 }
4226 } else if ( Array.isArray( collection ) ) {
4227 for ( i = 0, len = collection.length; i < len; i++ ) {
4228 item = collection[ i ];
4229 // Allow plain strings as shorthand for named tools
4230 if ( typeof item === 'string' ) {
4231 item = { name: item };
4232 }
4233 if ( OO.isPlainObject( item ) ) {
4234 if ( item.group ) {
4235 for ( name in this.registry ) {
4236 tool = this.registry[ name ];
4237 if (
4238 // Include tools with matching group
4239 tool.static.group === item.group &&
4240 // Only add tools by group name when auto-add is enabled
4241 tool.static.autoAddToGroup &&
4242 // Exclude already used tools
4243 ( !used || !used[ name ] )
4244 ) {
4245 names.push( name );
4246 if ( used ) {
4247 used[ name ] = true;
4248 }
4249 }
4250 }
4251 // Include tools with matching name and exclude already used tools
4252 } else if ( item.name && ( !used || !used[ item.name ] ) ) {
4253 names.push( item.name );
4254 if ( used ) {
4255 used[ item.name ] = true;
4256 }
4257 }
4258 }
4259 }
4260 }
4261 return names;
4262 };
4263
4264 /**
4265 * ToolGroupFactories create {@link OO.ui.ToolGroup toolgroups} on demand. The toolgroup classes must
4266 * specify a symbolic name and be registered with the factory. The following classes are registered by
4267 * default:
4268 *
4269 * - {@link OO.ui.BarToolGroup BarToolGroups} (‘bar’)
4270 * - {@link OO.ui.MenuToolGroup MenuToolGroups} (‘menu’)
4271 * - {@link OO.ui.ListToolGroup ListToolGroups} (‘list’)
4272 *
4273 * See {@link OO.ui.Toolbar toolbars} for an example.
4274 *
4275 * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki][1].
4276 *
4277 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
4278 * @class
4279 * @extends OO.Factory
4280 * @constructor
4281 */
4282 OO.ui.ToolGroupFactory = function OoUiToolGroupFactory() {
4283 var i, l, defaultClasses;
4284 // Parent constructor
4285 OO.Factory.call( this );
4286
4287 defaultClasses = this.constructor.static.getDefaultClasses();
4288
4289 // Register default toolgroups
4290 for ( i = 0, l = defaultClasses.length; i < l; i++ ) {
4291 this.register( defaultClasses[ i ] );
4292 }
4293 };
4294
4295 /* Setup */
4296
4297 OO.inheritClass( OO.ui.ToolGroupFactory, OO.Factory );
4298
4299 /* Static Methods */
4300
4301 /**
4302 * Get a default set of classes to be registered on construction.
4303 *
4304 * @return {Function[]} Default classes
4305 */
4306 OO.ui.ToolGroupFactory.static.getDefaultClasses = function () {
4307 return [
4308 OO.ui.BarToolGroup,
4309 OO.ui.ListToolGroup,
4310 OO.ui.MenuToolGroup
4311 ];
4312 };
4313
4314 /**
4315 * Theme logic.
4316 *
4317 * @abstract
4318 * @class
4319 *
4320 * @constructor
4321 * @param {Object} [config] Configuration options
4322 */
4323 OO.ui.Theme = function OoUiTheme( config ) {
4324 // Configuration initialization
4325 config = config || {};
4326 };
4327
4328 /* Setup */
4329
4330 OO.initClass( OO.ui.Theme );
4331
4332 /* Methods */
4333
4334 /**
4335 * Get a list of classes to be applied to a widget.
4336 *
4337 * The 'on' and 'off' lists combined MUST contain keys for all classes the theme adds or removes,
4338 * otherwise state transitions will not work properly.
4339 *
4340 * @param {OO.ui.Element} element Element for which to get classes
4341 * @return {Object.<string,string[]>} Categorized class names with `on` and `off` lists
4342 */
4343 OO.ui.Theme.prototype.getElementClasses = function () {
4344 return { on: [], off: [] };
4345 };
4346
4347 /**
4348 * Update CSS classes provided by the theme.
4349 *
4350 * For elements with theme logic hooks, this should be called any time there's a state change.
4351 *
4352 * @param {OO.ui.Element} element Element for which to update classes
4353 * @return {Object.<string,string[]>} Categorized class names with `on` and `off` lists
4354 */
4355 OO.ui.Theme.prototype.updateElementClasses = function ( element ) {
4356 var $elements = $( [] ),
4357 classes = this.getElementClasses( element );
4358
4359 if ( element.$icon ) {
4360 $elements = $elements.add( element.$icon );
4361 }
4362 if ( element.$indicator ) {
4363 $elements = $elements.add( element.$indicator );
4364 }
4365
4366 $elements
4367 .removeClass( classes.off.join( ' ' ) )
4368 .addClass( classes.on.join( ' ' ) );
4369 };
4370
4371 /**
4372 * RequestManager is a mixin that manages the lifecycle of a promise-backed request for a widget, such as
4373 * the {@link OO.ui.mixin.LookupElement}.
4374 *
4375 * @class
4376 * @abstract
4377 *
4378 * @constructor
4379 */
4380 OO.ui.mixin.RequestManager = function OoUiMixinRequestManager() {
4381 this.requestCache = {};
4382 this.requestQuery = null;
4383 this.requestRequest = null;
4384 };
4385
4386 /* Setup */
4387
4388 OO.initClass( OO.ui.mixin.RequestManager );
4389
4390 /**
4391 * Get request results for the current query.
4392 *
4393 * @return {jQuery.Promise} Promise object which will be passed response data as the first argument of
4394 * the done event. If the request was aborted to make way for a subsequent request, this promise
4395 * may not be rejected, depending on what jQuery feels like doing.
4396 */
4397 OO.ui.mixin.RequestManager.prototype.getRequestData = function () {
4398 var widget = this,
4399 value = this.getRequestQuery(),
4400 deferred = $.Deferred(),
4401 ourRequest;
4402
4403 this.abortRequest();
4404 if ( Object.prototype.hasOwnProperty.call( this.requestCache, value ) ) {
4405 deferred.resolve( this.requestCache[ value ] );
4406 } else {
4407 if ( this.pushPending ) {
4408 this.pushPending();
4409 }
4410 this.requestQuery = value;
4411 ourRequest = this.requestRequest = this.getRequest();
4412 ourRequest
4413 .always( function () {
4414 // We need to pop pending even if this is an old request, otherwise
4415 // the widget will remain pending forever.
4416 // TODO: this assumes that an aborted request will fail or succeed soon after
4417 // being aborted, or at least eventually. It would be nice if we could popPending()
4418 // at abort time, but only if we knew that we hadn't already called popPending()
4419 // for that request.
4420 if ( widget.popPending ) {
4421 widget.popPending();
4422 }
4423 } )
4424 .done( function ( response ) {
4425 // If this is an old request (and aborting it somehow caused it to still succeed),
4426 // ignore its success completely
4427 if ( ourRequest === widget.requestRequest ) {
4428 widget.requestQuery = null;
4429 widget.requestRequest = null;
4430 widget.requestCache[ value ] = widget.getRequestCacheDataFromResponse( response );
4431 deferred.resolve( widget.requestCache[ value ] );
4432 }
4433 } )
4434 .fail( function () {
4435 // If this is an old request (or a request failing because it's being aborted),
4436 // ignore its failure completely
4437 if ( ourRequest === widget.requestRequest ) {
4438 widget.requestQuery = null;
4439 widget.requestRequest = null;
4440 deferred.reject();
4441 }
4442 } );
4443 }
4444 return deferred.promise();
4445 };
4446
4447 /**
4448 * Abort the currently pending request, if any.
4449 *
4450 * @private
4451 */
4452 OO.ui.mixin.RequestManager.prototype.abortRequest = function () {
4453 var oldRequest = this.requestRequest;
4454 if ( oldRequest ) {
4455 // First unset this.requestRequest to the fail handler will notice
4456 // that the request is no longer current
4457 this.requestRequest = null;
4458 this.requestQuery = null;
4459 oldRequest.abort();
4460 }
4461 };
4462
4463 /**
4464 * Get the query to be made.
4465 *
4466 * @protected
4467 * @method
4468 * @abstract
4469 * @return {string} query to be used
4470 */
4471 OO.ui.mixin.RequestManager.prototype.getRequestQuery = null;
4472
4473 /**
4474 * Get a new request object of the current query value.
4475 *
4476 * @protected
4477 * @method
4478 * @abstract
4479 * @return {jQuery.Promise} jQuery AJAX object, or promise object with an .abort() method
4480 */
4481 OO.ui.mixin.RequestManager.prototype.getRequest = null;
4482
4483 /**
4484 * Pre-process data returned by the request from #getRequest.
4485 *
4486 * The return value of this function will be cached, and any further queries for the given value
4487 * will use the cache rather than doing API requests.
4488 *
4489 * @protected
4490 * @method
4491 * @abstract
4492 * @param {Mixed} response Response from server
4493 * @return {Mixed} Cached result data
4494 */
4495 OO.ui.mixin.RequestManager.prototype.getRequestCacheDataFromResponse = null;
4496
4497 /**
4498 * The TabIndexedElement class is an attribute mixin used to add additional functionality to an
4499 * element created by another class. The mixin provides a ‘tabIndex’ property, which specifies the
4500 * order in which users will navigate through the focusable elements via the "tab" key.
4501 *
4502 * @example
4503 * // TabIndexedElement is mixed into the ButtonWidget class
4504 * // to provide a tabIndex property.
4505 * var button1 = new OO.ui.ButtonWidget( {
4506 * label: 'fourth',
4507 * tabIndex: 4
4508 * } );
4509 * var button2 = new OO.ui.ButtonWidget( {
4510 * label: 'second',
4511 * tabIndex: 2
4512 * } );
4513 * var button3 = new OO.ui.ButtonWidget( {
4514 * label: 'third',
4515 * tabIndex: 3
4516 * } );
4517 * var button4 = new OO.ui.ButtonWidget( {
4518 * label: 'first',
4519 * tabIndex: 1
4520 * } );
4521 * $( 'body' ).append( button1.$element, button2.$element, button3.$element, button4.$element );
4522 *
4523 * @abstract
4524 * @class
4525 *
4526 * @constructor
4527 * @param {Object} [config] Configuration options
4528 * @cfg {jQuery} [$tabIndexed] The element that should use the tabindex functionality. By default,
4529 * the functionality is applied to the element created by the class ($element). If a different element is specified, the tabindex
4530 * functionality will be applied to it instead.
4531 * @cfg {number|null} [tabIndex=0] Number that specifies the element’s position in the tab-navigation
4532 * order (e.g., 1 for the first focusable element). Use 0 to use the default navigation order; use -1
4533 * to remove the element from the tab-navigation flow.
4534 */
4535 OO.ui.mixin.TabIndexedElement = function OoUiMixinTabIndexedElement( config ) {
4536 // Configuration initialization
4537 config = $.extend( { tabIndex: 0 }, config );
4538
4539 // Properties
4540 this.$tabIndexed = null;
4541 this.tabIndex = null;
4542
4543 // Events
4544 this.connect( this, { disable: 'onTabIndexedElementDisable' } );
4545
4546 // Initialization
4547 this.setTabIndex( config.tabIndex );
4548 this.setTabIndexedElement( config.$tabIndexed || this.$element );
4549 };
4550
4551 /* Setup */
4552
4553 OO.initClass( OO.ui.mixin.TabIndexedElement );
4554
4555 /* Methods */
4556
4557 /**
4558 * Set the element that should use the tabindex functionality.
4559 *
4560 * This method is used to retarget a tabindex mixin so that its functionality applies
4561 * to the specified element. If an element is currently using the functionality, the mixin’s
4562 * effect on that element is removed before the new element is set up.
4563 *
4564 * @param {jQuery} $tabIndexed Element that should use the tabindex functionality
4565 * @chainable
4566 */
4567 OO.ui.mixin.TabIndexedElement.prototype.setTabIndexedElement = function ( $tabIndexed ) {
4568 var tabIndex = this.tabIndex;
4569 // Remove attributes from old $tabIndexed
4570 this.setTabIndex( null );
4571 // Force update of new $tabIndexed
4572 this.$tabIndexed = $tabIndexed;
4573 this.tabIndex = tabIndex;
4574 return this.updateTabIndex();
4575 };
4576
4577 /**
4578 * Set the value of the tabindex.
4579 *
4580 * @param {number|null} tabIndex Tabindex value, or `null` for no tabindex
4581 * @chainable
4582 */
4583 OO.ui.mixin.TabIndexedElement.prototype.setTabIndex = function ( tabIndex ) {
4584 tabIndex = typeof tabIndex === 'number' ? tabIndex : null;
4585
4586 if ( this.tabIndex !== tabIndex ) {
4587 this.tabIndex = tabIndex;
4588 this.updateTabIndex();
4589 }
4590
4591 return this;
4592 };
4593
4594 /**
4595 * Update the `tabindex` attribute, in case of changes to tab index or
4596 * disabled state.
4597 *
4598 * @private
4599 * @chainable
4600 */
4601 OO.ui.mixin.TabIndexedElement.prototype.updateTabIndex = function () {
4602 if ( this.$tabIndexed ) {
4603 if ( this.tabIndex !== null ) {
4604 // Do not index over disabled elements
4605 this.$tabIndexed.attr( {
4606 tabindex: this.isDisabled() ? -1 : this.tabIndex,
4607 // Support: ChromeVox and NVDA
4608 // These do not seem to inherit aria-disabled from parent elements
4609 'aria-disabled': this.isDisabled().toString()
4610 } );
4611 } else {
4612 this.$tabIndexed.removeAttr( 'tabindex aria-disabled' );
4613 }
4614 }
4615 return this;
4616 };
4617
4618 /**
4619 * Handle disable events.
4620 *
4621 * @private
4622 * @param {boolean} disabled Element is disabled
4623 */
4624 OO.ui.mixin.TabIndexedElement.prototype.onTabIndexedElementDisable = function () {
4625 this.updateTabIndex();
4626 };
4627
4628 /**
4629 * Get the value of the tabindex.
4630 *
4631 * @return {number|null} Tabindex value
4632 */
4633 OO.ui.mixin.TabIndexedElement.prototype.getTabIndex = function () {
4634 return this.tabIndex;
4635 };
4636
4637 /**
4638 * ButtonElement is often mixed into other classes to generate a button, which is a clickable
4639 * interface element that can be configured with access keys for accessibility.
4640 * See the [OOjs UI documentation on MediaWiki] [1] for examples.
4641 *
4642 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#Buttons
4643 * @abstract
4644 * @class
4645 *
4646 * @constructor
4647 * @param {Object} [config] Configuration options
4648 * @cfg {jQuery} [$button] The button element created by the class.
4649 * If this configuration is omitted, the button element will use a generated `<a>`.
4650 * @cfg {boolean} [framed=true] Render the button with a frame
4651 */
4652 OO.ui.mixin.ButtonElement = function OoUiMixinButtonElement( config ) {
4653 // Configuration initialization
4654 config = config || {};
4655
4656 // Properties
4657 this.$button = null;
4658 this.framed = null;
4659 this.active = false;
4660 this.onMouseUpHandler = this.onMouseUp.bind( this );
4661 this.onMouseDownHandler = this.onMouseDown.bind( this );
4662 this.onKeyDownHandler = this.onKeyDown.bind( this );
4663 this.onKeyUpHandler = this.onKeyUp.bind( this );
4664 this.onClickHandler = this.onClick.bind( this );
4665 this.onKeyPressHandler = this.onKeyPress.bind( this );
4666
4667 // Initialization
4668 this.$element.addClass( 'oo-ui-buttonElement' );
4669 this.toggleFramed( config.framed === undefined || config.framed );
4670 this.setButtonElement( config.$button || $( '<a>' ) );
4671 };
4672
4673 /* Setup */
4674
4675 OO.initClass( OO.ui.mixin.ButtonElement );
4676
4677 /* Static Properties */
4678
4679 /**
4680 * Cancel mouse down events.
4681 *
4682 * This property is usually set to `true` to prevent the focus from changing when the button is clicked.
4683 * Classes such as {@link OO.ui.mixin.DraggableElement DraggableElement} and {@link OO.ui.ButtonOptionWidget ButtonOptionWidget}
4684 * use a value of `false` so that dragging behavior is possible and mousedown events can be handled by a
4685 * parent widget.
4686 *
4687 * @static
4688 * @inheritable
4689 * @property {boolean}
4690 */
4691 OO.ui.mixin.ButtonElement.static.cancelButtonMouseDownEvents = true;
4692
4693 /* Events */
4694
4695 /**
4696 * A 'click' event is emitted when the button element is clicked.
4697 *
4698 * @event click
4699 */
4700
4701 /* Methods */
4702
4703 /**
4704 * Set the button element.
4705 *
4706 * This method is used to retarget a button mixin so that its functionality applies to
4707 * the specified button element instead of the one created by the class. If a button element
4708 * is already set, the method will remove the mixin’s effect on that element.
4709 *
4710 * @param {jQuery} $button Element to use as button
4711 */
4712 OO.ui.mixin.ButtonElement.prototype.setButtonElement = function ( $button ) {
4713 if ( this.$button ) {
4714 this.$button
4715 .removeClass( 'oo-ui-buttonElement-button' )
4716 .removeAttr( 'role accesskey' )
4717 .off( {
4718 mousedown: this.onMouseDownHandler,
4719 keydown: this.onKeyDownHandler,
4720 click: this.onClickHandler,
4721 keypress: this.onKeyPressHandler
4722 } );
4723 }
4724
4725 this.$button = $button
4726 .addClass( 'oo-ui-buttonElement-button' )
4727 .attr( { role: 'button' } )
4728 .on( {
4729 mousedown: this.onMouseDownHandler,
4730 keydown: this.onKeyDownHandler,
4731 click: this.onClickHandler,
4732 keypress: this.onKeyPressHandler
4733 } );
4734 };
4735
4736 /**
4737 * Handles mouse down events.
4738 *
4739 * @protected
4740 * @param {jQuery.Event} e Mouse down event
4741 */
4742 OO.ui.mixin.ButtonElement.prototype.onMouseDown = function ( e ) {
4743 if ( this.isDisabled() || e.which !== 1 ) {
4744 return;
4745 }
4746 this.$element.addClass( 'oo-ui-buttonElement-pressed' );
4747 // Run the mouseup handler no matter where the mouse is when the button is let go, so we can
4748 // reliably remove the pressed class
4749 OO.ui.addCaptureEventListener( this.getElementDocument(), 'mouseup', this.onMouseUpHandler );
4750 // Prevent change of focus unless specifically configured otherwise
4751 if ( this.constructor.static.cancelButtonMouseDownEvents ) {
4752 return false;
4753 }
4754 };
4755
4756 /**
4757 * Handles mouse up events.
4758 *
4759 * @protected
4760 * @param {jQuery.Event} e Mouse up event
4761 */
4762 OO.ui.mixin.ButtonElement.prototype.onMouseUp = function ( e ) {
4763 if ( this.isDisabled() || e.which !== 1 ) {
4764 return;
4765 }
4766 this.$element.removeClass( 'oo-ui-buttonElement-pressed' );
4767 // Stop listening for mouseup, since we only needed this once
4768 OO.ui.removeCaptureEventListener( this.getElementDocument(), 'mouseup', this.onMouseUpHandler );
4769 };
4770
4771 /**
4772 * Handles mouse click events.
4773 *
4774 * @protected
4775 * @param {jQuery.Event} e Mouse click event
4776 * @fires click
4777 */
4778 OO.ui.mixin.ButtonElement.prototype.onClick = function ( e ) {
4779 if ( !this.isDisabled() && e.which === 1 ) {
4780 if ( this.emit( 'click' ) ) {
4781 return false;
4782 }
4783 }
4784 };
4785
4786 /**
4787 * Handles key down events.
4788 *
4789 * @protected
4790 * @param {jQuery.Event} e Key down event
4791 */
4792 OO.ui.mixin.ButtonElement.prototype.onKeyDown = function ( e ) {
4793 if ( this.isDisabled() || ( e.which !== OO.ui.Keys.SPACE && e.which !== OO.ui.Keys.ENTER ) ) {
4794 return;
4795 }
4796 this.$element.addClass( 'oo-ui-buttonElement-pressed' );
4797 // Run the keyup handler no matter where the key is when the button is let go, so we can
4798 // reliably remove the pressed class
4799 OO.ui.addCaptureEventListener( this.getElementDocument(), 'keyup', this.onKeyUpHandler );
4800 };
4801
4802 /**
4803 * Handles key up events.
4804 *
4805 * @protected
4806 * @param {jQuery.Event} e Key up event
4807 */
4808 OO.ui.mixin.ButtonElement.prototype.onKeyUp = function ( e ) {
4809 if ( this.isDisabled() || ( e.which !== OO.ui.Keys.SPACE && e.which !== OO.ui.Keys.ENTER ) ) {
4810 return;
4811 }
4812 this.$element.removeClass( 'oo-ui-buttonElement-pressed' );
4813 // Stop listening for keyup, since we only needed this once
4814 OO.ui.removeCaptureEventListener( this.getElementDocument(), 'keyup', this.onKeyUpHandler );
4815 };
4816
4817 /**
4818 * Handles key press events.
4819 *
4820 * @protected
4821 * @param {jQuery.Event} e Key press event
4822 * @fires click
4823 */
4824 OO.ui.mixin.ButtonElement.prototype.onKeyPress = function ( e ) {
4825 if ( !this.isDisabled() && ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER ) ) {
4826 if ( this.emit( 'click' ) ) {
4827 return false;
4828 }
4829 }
4830 };
4831
4832 /**
4833 * Check if button has a frame.
4834 *
4835 * @return {boolean} Button is framed
4836 */
4837 OO.ui.mixin.ButtonElement.prototype.isFramed = function () {
4838 return this.framed;
4839 };
4840
4841 /**
4842 * Render the button with or without a frame. Omit the `framed` parameter to toggle the button frame on and off.
4843 *
4844 * @param {boolean} [framed] Make button framed, omit to toggle
4845 * @chainable
4846 */
4847 OO.ui.mixin.ButtonElement.prototype.toggleFramed = function ( framed ) {
4848 framed = framed === undefined ? !this.framed : !!framed;
4849 if ( framed !== this.framed ) {
4850 this.framed = framed;
4851 this.$element
4852 .toggleClass( 'oo-ui-buttonElement-frameless', !framed )
4853 .toggleClass( 'oo-ui-buttonElement-framed', framed );
4854 this.updateThemeClasses();
4855 }
4856
4857 return this;
4858 };
4859
4860 /**
4861 * Set the button's active state.
4862 *
4863 * The active state occurs when a {@link OO.ui.ButtonOptionWidget ButtonOptionWidget} or
4864 * a {@link OO.ui.ToggleButtonWidget ToggleButtonWidget} is pressed. This method does nothing
4865 * for other button types.
4866 *
4867 * @param {boolean} value Make button active
4868 * @chainable
4869 */
4870 OO.ui.mixin.ButtonElement.prototype.setActive = function ( value ) {
4871 this.active = !!value;
4872 this.$element.toggleClass( 'oo-ui-buttonElement-active', this.active );
4873 return this;
4874 };
4875
4876 /**
4877 * Check if the button is active
4878 *
4879 * @return {boolean} The button is active
4880 */
4881 OO.ui.mixin.ButtonElement.prototype.isActive = function () {
4882 return this.active;
4883 };
4884
4885 /**
4886 * Any OOjs UI widget that contains other widgets (such as {@link OO.ui.ButtonWidget buttons} or
4887 * {@link OO.ui.OptionWidget options}) mixes in GroupElement. Adding, removing, and clearing
4888 * items from the group is done through the interface the class provides.
4889 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
4890 *
4891 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Groups
4892 *
4893 * @abstract
4894 * @class
4895 *
4896 * @constructor
4897 * @param {Object} [config] Configuration options
4898 * @cfg {jQuery} [$group] The container element created by the class. If this configuration
4899 * is omitted, the group element will use a generated `<div>`.
4900 */
4901 OO.ui.mixin.GroupElement = function OoUiMixinGroupElement( config ) {
4902 // Configuration initialization
4903 config = config || {};
4904
4905 // Properties
4906 this.$group = null;
4907 this.items = [];
4908 this.aggregateItemEvents = {};
4909
4910 // Initialization
4911 this.setGroupElement( config.$group || $( '<div>' ) );
4912 };
4913
4914 /* Methods */
4915
4916 /**
4917 * Set the group element.
4918 *
4919 * If an element is already set, items will be moved to the new element.
4920 *
4921 * @param {jQuery} $group Element to use as group
4922 */
4923 OO.ui.mixin.GroupElement.prototype.setGroupElement = function ( $group ) {
4924 var i, len;
4925
4926 this.$group = $group;
4927 for ( i = 0, len = this.items.length; i < len; i++ ) {
4928 this.$group.append( this.items[ i ].$element );
4929 }
4930 };
4931
4932 /**
4933 * Check if a group contains no items.
4934 *
4935 * @return {boolean} Group is empty
4936 */
4937 OO.ui.mixin.GroupElement.prototype.isEmpty = function () {
4938 return !this.items.length;
4939 };
4940
4941 /**
4942 * Get all items in the group.
4943 *
4944 * The method returns an array of item references (e.g., [button1, button2, button3]) and is useful
4945 * when synchronizing groups of items, or whenever the references are required (e.g., when removing items
4946 * from a group).
4947 *
4948 * @return {OO.ui.Element[]} An array of items.
4949 */
4950 OO.ui.mixin.GroupElement.prototype.getItems = function () {
4951 return this.items.slice( 0 );
4952 };
4953
4954 /**
4955 * Get an item by its data.
4956 *
4957 * Only the first item with matching data will be returned. To return all matching items,
4958 * use the #getItemsFromData method.
4959 *
4960 * @param {Object} data Item data to search for
4961 * @return {OO.ui.Element|null} Item with equivalent data, `null` if none exists
4962 */
4963 OO.ui.mixin.GroupElement.prototype.getItemFromData = function ( data ) {
4964 var i, len, item,
4965 hash = OO.getHash( data );
4966
4967 for ( i = 0, len = this.items.length; i < len; i++ ) {
4968 item = this.items[ i ];
4969 if ( hash === OO.getHash( item.getData() ) ) {
4970 return item;
4971 }
4972 }
4973
4974 return null;
4975 };
4976
4977 /**
4978 * Get items by their data.
4979 *
4980 * All items with matching data will be returned. To return only the first match, use the #getItemFromData method instead.
4981 *
4982 * @param {Object} data Item data to search for
4983 * @return {OO.ui.Element[]} Items with equivalent data
4984 */
4985 OO.ui.mixin.GroupElement.prototype.getItemsFromData = function ( data ) {
4986 var i, len, item,
4987 hash = OO.getHash( data ),
4988 items = [];
4989
4990 for ( i = 0, len = this.items.length; i < len; i++ ) {
4991 item = this.items[ i ];
4992 if ( hash === OO.getHash( item.getData() ) ) {
4993 items.push( item );
4994 }
4995 }
4996
4997 return items;
4998 };
4999
5000 /**
5001 * Aggregate the events emitted by the group.
5002 *
5003 * When events are aggregated, the group will listen to all contained items for the event,
5004 * and then emit the event under a new name. The new event will contain an additional leading
5005 * parameter containing the item that emitted the original event. Other arguments emitted from
5006 * the original event are passed through.
5007 *
5008 * @param {Object.<string,string|null>} events An object keyed by the name of the event that should be
5009 * aggregated (e.g., ‘click’) and the value of the new name to use (e.g., ‘groupClick’).
5010 * A `null` value will remove aggregated events.
5011
5012 * @throws {Error} An error is thrown if aggregation already exists.
5013 */
5014 OO.ui.mixin.GroupElement.prototype.aggregate = function ( events ) {
5015 var i, len, item, add, remove, itemEvent, groupEvent;
5016
5017 for ( itemEvent in events ) {
5018 groupEvent = events[ itemEvent ];
5019
5020 // Remove existing aggregated event
5021 if ( Object.prototype.hasOwnProperty.call( this.aggregateItemEvents, itemEvent ) ) {
5022 // Don't allow duplicate aggregations
5023 if ( groupEvent ) {
5024 throw new Error( 'Duplicate item event aggregation for ' + itemEvent );
5025 }
5026 // Remove event aggregation from existing items
5027 for ( i = 0, len = this.items.length; i < len; i++ ) {
5028 item = this.items[ i ];
5029 if ( item.connect && item.disconnect ) {
5030 remove = {};
5031 remove[ itemEvent ] = [ 'emit', this.aggregateItemEvents[ itemEvent ], item ];
5032 item.disconnect( this, remove );
5033 }
5034 }
5035 // Prevent future items from aggregating event
5036 delete this.aggregateItemEvents[ itemEvent ];
5037 }
5038
5039 // Add new aggregate event
5040 if ( groupEvent ) {
5041 // Make future items aggregate event
5042 this.aggregateItemEvents[ itemEvent ] = groupEvent;
5043 // Add event aggregation to existing items
5044 for ( i = 0, len = this.items.length; i < len; i++ ) {
5045 item = this.items[ i ];
5046 if ( item.connect && item.disconnect ) {
5047 add = {};
5048 add[ itemEvent ] = [ 'emit', groupEvent, item ];
5049 item.connect( this, add );
5050 }
5051 }
5052 }
5053 }
5054 };
5055
5056 /**
5057 * Add items to the group.
5058 *
5059 * Items will be added to the end of the group array unless the optional `index` parameter specifies
5060 * a different insertion point. Adding an existing item will move it to the end of the array or the point specified by the `index`.
5061 *
5062 * @param {OO.ui.Element[]} items An array of items to add to the group
5063 * @param {number} [index] Index of the insertion point
5064 * @chainable
5065 */
5066 OO.ui.mixin.GroupElement.prototype.addItems = function ( items, index ) {
5067 var i, len, item, event, events, currentIndex,
5068 itemElements = [];
5069
5070 for ( i = 0, len = items.length; i < len; i++ ) {
5071 item = items[ i ];
5072
5073 // Check if item exists then remove it first, effectively "moving" it
5074 currentIndex = this.items.indexOf( item );
5075 if ( currentIndex >= 0 ) {
5076 this.removeItems( [ item ] );
5077 // Adjust index to compensate for removal
5078 if ( currentIndex < index ) {
5079 index--;
5080 }
5081 }
5082 // Add the item
5083 if ( item.connect && item.disconnect && !$.isEmptyObject( this.aggregateItemEvents ) ) {
5084 events = {};
5085 for ( event in this.aggregateItemEvents ) {
5086 events[ event ] = [ 'emit', this.aggregateItemEvents[ event ], item ];
5087 }
5088 item.connect( this, events );
5089 }
5090 item.setElementGroup( this );
5091 itemElements.push( item.$element.get( 0 ) );
5092 }
5093
5094 if ( index === undefined || index < 0 || index >= this.items.length ) {
5095 this.$group.append( itemElements );
5096 this.items.push.apply( this.items, items );
5097 } else if ( index === 0 ) {
5098 this.$group.prepend( itemElements );
5099 this.items.unshift.apply( this.items, items );
5100 } else {
5101 this.items[ index ].$element.before( itemElements );
5102 this.items.splice.apply( this.items, [ index, 0 ].concat( items ) );
5103 }
5104
5105 return this;
5106 };
5107
5108 /**
5109 * Remove the specified items from a group.
5110 *
5111 * Removed items are detached (not removed) from the DOM so that they may be reused.
5112 * To remove all items from a group, you may wish to use the #clearItems method instead.
5113 *
5114 * @param {OO.ui.Element[]} items An array of items to remove
5115 * @chainable
5116 */
5117 OO.ui.mixin.GroupElement.prototype.removeItems = function ( items ) {
5118 var i, len, item, index, remove, itemEvent;
5119
5120 // Remove specific items
5121 for ( i = 0, len = items.length; i < len; i++ ) {
5122 item = items[ i ];
5123 index = this.items.indexOf( item );
5124 if ( index !== -1 ) {
5125 if (
5126 item.connect && item.disconnect &&
5127 !$.isEmptyObject( this.aggregateItemEvents )
5128 ) {
5129 remove = {};
5130 if ( Object.prototype.hasOwnProperty.call( this.aggregateItemEvents, itemEvent ) ) {
5131 remove[ itemEvent ] = [ 'emit', this.aggregateItemEvents[ itemEvent ], item ];
5132 }
5133 item.disconnect( this, remove );
5134 }
5135 item.setElementGroup( null );
5136 this.items.splice( index, 1 );
5137 item.$element.detach();
5138 }
5139 }
5140
5141 return this;
5142 };
5143
5144 /**
5145 * Clear all items from the group.
5146 *
5147 * Cleared items are detached from the DOM, not removed, so that they may be reused.
5148 * To remove only a subset of items from a group, use the #removeItems method.
5149 *
5150 * @chainable
5151 */
5152 OO.ui.mixin.GroupElement.prototype.clearItems = function () {
5153 var i, len, item, remove, itemEvent;
5154
5155 // Remove all items
5156 for ( i = 0, len = this.items.length; i < len; i++ ) {
5157 item = this.items[ i ];
5158 if (
5159 item.connect && item.disconnect &&
5160 !$.isEmptyObject( this.aggregateItemEvents )
5161 ) {
5162 remove = {};
5163 if ( Object.prototype.hasOwnProperty.call( this.aggregateItemEvents, itemEvent ) ) {
5164 remove[ itemEvent ] = [ 'emit', this.aggregateItemEvents[ itemEvent ], item ];
5165 }
5166 item.disconnect( this, remove );
5167 }
5168 item.setElementGroup( null );
5169 item.$element.detach();
5170 }
5171
5172 this.items = [];
5173 return this;
5174 };
5175
5176 /**
5177 * DraggableElement is a mixin class used to create elements that can be clicked
5178 * and dragged by a mouse to a new position within a group. This class must be used
5179 * in conjunction with OO.ui.mixin.DraggableGroupElement, which provides a container for
5180 * the draggable elements.
5181 *
5182 * @abstract
5183 * @class
5184 *
5185 * @constructor
5186 */
5187 OO.ui.mixin.DraggableElement = function OoUiMixinDraggableElement() {
5188 // Properties
5189 this.index = null;
5190
5191 // Initialize and events
5192 this.$element
5193 .attr( 'draggable', true )
5194 .addClass( 'oo-ui-draggableElement' )
5195 .on( {
5196 dragstart: this.onDragStart.bind( this ),
5197 dragover: this.onDragOver.bind( this ),
5198 dragend: this.onDragEnd.bind( this ),
5199 drop: this.onDrop.bind( this )
5200 } );
5201 };
5202
5203 OO.initClass( OO.ui.mixin.DraggableElement );
5204
5205 /* Events */
5206
5207 /**
5208 * @event dragstart
5209 *
5210 * A dragstart event is emitted when the user clicks and begins dragging an item.
5211 * @param {OO.ui.mixin.DraggableElement} item The item the user has clicked and is dragging with the mouse.
5212 */
5213
5214 /**
5215 * @event dragend
5216 * A dragend event is emitted when the user drags an item and releases the mouse,
5217 * thus terminating the drag operation.
5218 */
5219
5220 /**
5221 * @event drop
5222 * A drop event is emitted when the user drags an item and then releases the mouse button
5223 * over a valid target.
5224 */
5225
5226 /* Static Properties */
5227
5228 /**
5229 * @inheritdoc OO.ui.mixin.ButtonElement
5230 */
5231 OO.ui.mixin.DraggableElement.static.cancelButtonMouseDownEvents = false;
5232
5233 /* Methods */
5234
5235 /**
5236 * Respond to dragstart event.
5237 *
5238 * @private
5239 * @param {jQuery.Event} event jQuery event
5240 * @fires dragstart
5241 */
5242 OO.ui.mixin.DraggableElement.prototype.onDragStart = function ( e ) {
5243 var dataTransfer = e.originalEvent.dataTransfer;
5244 // Define drop effect
5245 dataTransfer.dropEffect = 'none';
5246 dataTransfer.effectAllowed = 'move';
5247 // Support: Firefox
5248 // We must set up a dataTransfer data property or Firefox seems to
5249 // ignore the fact the element is draggable.
5250 try {
5251 dataTransfer.setData( 'application-x/OOjs-UI-draggable', this.getIndex() );
5252 } catch ( err ) {
5253 // The above is only for Firefox. Move on if it fails.
5254 }
5255 // Add dragging class
5256 this.$element.addClass( 'oo-ui-draggableElement-dragging' );
5257 // Emit event
5258 this.emit( 'dragstart', this );
5259 return true;
5260 };
5261
5262 /**
5263 * Respond to dragend event.
5264 *
5265 * @private
5266 * @fires dragend
5267 */
5268 OO.ui.mixin.DraggableElement.prototype.onDragEnd = function () {
5269 this.$element.removeClass( 'oo-ui-draggableElement-dragging' );
5270 this.emit( 'dragend' );
5271 };
5272
5273 /**
5274 * Handle drop event.
5275 *
5276 * @private
5277 * @param {jQuery.Event} event jQuery event
5278 * @fires drop
5279 */
5280 OO.ui.mixin.DraggableElement.prototype.onDrop = function ( e ) {
5281 e.preventDefault();
5282 this.emit( 'drop', e );
5283 };
5284
5285 /**
5286 * In order for drag/drop to work, the dragover event must
5287 * return false and stop propogation.
5288 *
5289 * @private
5290 */
5291 OO.ui.mixin.DraggableElement.prototype.onDragOver = function ( e ) {
5292 e.preventDefault();
5293 };
5294
5295 /**
5296 * Set item index.
5297 * Store it in the DOM so we can access from the widget drag event
5298 *
5299 * @private
5300 * @param {number} Item index
5301 */
5302 OO.ui.mixin.DraggableElement.prototype.setIndex = function ( index ) {
5303 if ( this.index !== index ) {
5304 this.index = index;
5305 this.$element.data( 'index', index );
5306 }
5307 };
5308
5309 /**
5310 * Get item index
5311 *
5312 * @private
5313 * @return {number} Item index
5314 */
5315 OO.ui.mixin.DraggableElement.prototype.getIndex = function () {
5316 return this.index;
5317 };
5318
5319 /**
5320 * DraggableGroupElement is a mixin class used to create a group element to
5321 * contain draggable elements, which are items that can be clicked and dragged by a mouse.
5322 * The class is used with OO.ui.mixin.DraggableElement.
5323 *
5324 * @abstract
5325 * @class
5326 * @mixins OO.ui.mixin.GroupElement
5327 *
5328 * @constructor
5329 * @param {Object} [config] Configuration options
5330 * @cfg {string} [orientation] Item orientation: 'horizontal' or 'vertical'. The orientation
5331 * should match the layout of the items. Items displayed in a single row
5332 * or in several rows should use horizontal orientation. The vertical orientation should only be
5333 * used when the items are displayed in a single column. Defaults to 'vertical'
5334 */
5335 OO.ui.mixin.DraggableGroupElement = function OoUiMixinDraggableGroupElement( config ) {
5336 // Configuration initialization
5337 config = config || {};
5338
5339 // Parent constructor
5340 OO.ui.mixin.GroupElement.call( this, config );
5341
5342 // Properties
5343 this.orientation = config.orientation || 'vertical';
5344 this.dragItem = null;
5345 this.itemDragOver = null;
5346 this.itemKeys = {};
5347 this.sideInsertion = '';
5348
5349 // Events
5350 this.aggregate( {
5351 dragstart: 'itemDragStart',
5352 dragend: 'itemDragEnd',
5353 drop: 'itemDrop'
5354 } );
5355 this.connect( this, {
5356 itemDragStart: 'onItemDragStart',
5357 itemDrop: 'onItemDrop',
5358 itemDragEnd: 'onItemDragEnd'
5359 } );
5360 this.$element.on( {
5361 dragover: this.onDragOver.bind( this ),
5362 dragleave: this.onDragLeave.bind( this )
5363 } );
5364
5365 // Initialize
5366 if ( Array.isArray( config.items ) ) {
5367 this.addItems( config.items );
5368 }
5369 this.$placeholder = $( '<div>' )
5370 .addClass( 'oo-ui-draggableGroupElement-placeholder' );
5371 this.$element
5372 .addClass( 'oo-ui-draggableGroupElement' )
5373 .append( this.$status )
5374 .toggleClass( 'oo-ui-draggableGroupElement-horizontal', this.orientation === 'horizontal' )
5375 .prepend( this.$placeholder );
5376 };
5377
5378 /* Setup */
5379 OO.mixinClass( OO.ui.mixin.DraggableGroupElement, OO.ui.mixin.GroupElement );
5380
5381 /* Events */
5382
5383 /**
5384 * A 'reorder' event is emitted when the order of items in the group changes.
5385 *
5386 * @event reorder
5387 * @param {OO.ui.mixin.DraggableElement} item Reordered item
5388 * @param {number} [newIndex] New index for the item
5389 */
5390
5391 /* Methods */
5392
5393 /**
5394 * Respond to item drag start event
5395 *
5396 * @private
5397 * @param {OO.ui.mixin.DraggableElement} item Dragged item
5398 */
5399 OO.ui.mixin.DraggableGroupElement.prototype.onItemDragStart = function ( item ) {
5400 var i, len;
5401
5402 // Map the index of each object
5403 for ( i = 0, len = this.items.length; i < len; i++ ) {
5404 this.items[ i ].setIndex( i );
5405 }
5406
5407 if ( this.orientation === 'horizontal' ) {
5408 // Set the height of the indicator
5409 this.$placeholder.css( {
5410 height: item.$element.outerHeight(),
5411 width: 2
5412 } );
5413 } else {
5414 // Set the width of the indicator
5415 this.$placeholder.css( {
5416 height: 2,
5417 width: item.$element.outerWidth()
5418 } );
5419 }
5420 this.setDragItem( item );
5421 };
5422
5423 /**
5424 * Respond to item drag end event
5425 *
5426 * @private
5427 */
5428 OO.ui.mixin.DraggableGroupElement.prototype.onItemDragEnd = function () {
5429 this.unsetDragItem();
5430 return false;
5431 };
5432
5433 /**
5434 * Handle drop event and switch the order of the items accordingly
5435 *
5436 * @private
5437 * @param {OO.ui.mixin.DraggableElement} item Dropped item
5438 * @fires reorder
5439 */
5440 OO.ui.mixin.DraggableGroupElement.prototype.onItemDrop = function ( item ) {
5441 var toIndex = item.getIndex();
5442 // Check if the dropped item is from the current group
5443 // TODO: Figure out a way to configure a list of legally droppable
5444 // elements even if they are not yet in the list
5445 if ( this.getDragItem() ) {
5446 // If the insertion point is 'after', the insertion index
5447 // is shifted to the right (or to the left in RTL, hence 'after')
5448 if ( this.sideInsertion === 'after' ) {
5449 toIndex++;
5450 }
5451 // Emit change event
5452 this.emit( 'reorder', this.getDragItem(), toIndex );
5453 }
5454 this.unsetDragItem();
5455 // Return false to prevent propogation
5456 return false;
5457 };
5458
5459 /**
5460 * Handle dragleave event.
5461 *
5462 * @private
5463 */
5464 OO.ui.mixin.DraggableGroupElement.prototype.onDragLeave = function () {
5465 // This means the item was dragged outside the widget
5466 this.$placeholder
5467 .css( 'left', 0 )
5468 .addClass( 'oo-ui-element-hidden' );
5469 };
5470
5471 /**
5472 * Respond to dragover event
5473 *
5474 * @private
5475 * @param {jQuery.Event} event Event details
5476 */
5477 OO.ui.mixin.DraggableGroupElement.prototype.onDragOver = function ( e ) {
5478 var dragOverObj, $optionWidget, itemOffset, itemMidpoint, itemBoundingRect,
5479 itemSize, cssOutput, dragPosition, itemIndex, itemPosition,
5480 clientX = e.originalEvent.clientX,
5481 clientY = e.originalEvent.clientY;
5482
5483 // Get the OptionWidget item we are dragging over
5484 dragOverObj = this.getElementDocument().elementFromPoint( clientX, clientY );
5485 $optionWidget = $( dragOverObj ).closest( '.oo-ui-draggableElement' );
5486 if ( $optionWidget[ 0 ] ) {
5487 itemOffset = $optionWidget.offset();
5488 itemBoundingRect = $optionWidget[ 0 ].getBoundingClientRect();
5489 itemPosition = $optionWidget.position();
5490 itemIndex = $optionWidget.data( 'index' );
5491 }
5492
5493 if (
5494 itemOffset &&
5495 this.isDragging() &&
5496 itemIndex !== this.getDragItem().getIndex()
5497 ) {
5498 if ( this.orientation === 'horizontal' ) {
5499 // Calculate where the mouse is relative to the item width
5500 itemSize = itemBoundingRect.width;
5501 itemMidpoint = itemBoundingRect.left + itemSize / 2;
5502 dragPosition = clientX;
5503 // Which side of the item we hover over will dictate
5504 // where the placeholder will appear, on the left or
5505 // on the right
5506 cssOutput = {
5507 left: dragPosition < itemMidpoint ? itemPosition.left : itemPosition.left + itemSize,
5508 top: itemPosition.top
5509 };
5510 } else {
5511 // Calculate where the mouse is relative to the item height
5512 itemSize = itemBoundingRect.height;
5513 itemMidpoint = itemBoundingRect.top + itemSize / 2;
5514 dragPosition = clientY;
5515 // Which side of the item we hover over will dictate
5516 // where the placeholder will appear, on the top or
5517 // on the bottom
5518 cssOutput = {
5519 top: dragPosition < itemMidpoint ? itemPosition.top : itemPosition.top + itemSize,
5520 left: itemPosition.left
5521 };
5522 }
5523 // Store whether we are before or after an item to rearrange
5524 // For horizontal layout, we need to account for RTL, as this is flipped
5525 if ( this.orientation === 'horizontal' && this.$element.css( 'direction' ) === 'rtl' ) {
5526 this.sideInsertion = dragPosition < itemMidpoint ? 'after' : 'before';
5527 } else {
5528 this.sideInsertion = dragPosition < itemMidpoint ? 'before' : 'after';
5529 }
5530 // Add drop indicator between objects
5531 this.$placeholder
5532 .css( cssOutput )
5533 .removeClass( 'oo-ui-element-hidden' );
5534 } else {
5535 // This means the item was dragged outside the widget
5536 this.$placeholder
5537 .css( 'left', 0 )
5538 .addClass( 'oo-ui-element-hidden' );
5539 }
5540 // Prevent default
5541 e.preventDefault();
5542 };
5543
5544 /**
5545 * Set a dragged item
5546 *
5547 * @param {OO.ui.mixin.DraggableElement} item Dragged item
5548 */
5549 OO.ui.mixin.DraggableGroupElement.prototype.setDragItem = function ( item ) {
5550 this.dragItem = item;
5551 };
5552
5553 /**
5554 * Unset the current dragged item
5555 */
5556 OO.ui.mixin.DraggableGroupElement.prototype.unsetDragItem = function () {
5557 this.dragItem = null;
5558 this.itemDragOver = null;
5559 this.$placeholder.addClass( 'oo-ui-element-hidden' );
5560 this.sideInsertion = '';
5561 };
5562
5563 /**
5564 * Get the item that is currently being dragged.
5565 *
5566 * @return {OO.ui.mixin.DraggableElement|null} The currently dragged item, or `null` if no item is being dragged
5567 */
5568 OO.ui.mixin.DraggableGroupElement.prototype.getDragItem = function () {
5569 return this.dragItem;
5570 };
5571
5572 /**
5573 * Check if an item in the group is currently being dragged.
5574 *
5575 * @return {Boolean} Item is being dragged
5576 */
5577 OO.ui.mixin.DraggableGroupElement.prototype.isDragging = function () {
5578 return this.getDragItem() !== null;
5579 };
5580
5581 /**
5582 * IconElement is often mixed into other classes to generate an icon.
5583 * Icons are graphics, about the size of normal text. They are used to aid the user
5584 * in locating a control or to convey information in a space-efficient way. See the
5585 * [OOjs UI documentation on MediaWiki] [1] for a list of icons
5586 * included in the library.
5587 *
5588 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
5589 *
5590 * @abstract
5591 * @class
5592 *
5593 * @constructor
5594 * @param {Object} [config] Configuration options
5595 * @cfg {jQuery} [$icon] The icon element created by the class. If this configuration is omitted,
5596 * the icon element will use a generated `<span>`. To use a different HTML tag, or to specify that
5597 * the icon element be set to an existing icon instead of the one generated by this class, set a
5598 * value using a jQuery selection. For example:
5599 *
5600 * // Use a <div> tag instead of a <span>
5601 * $icon: $("<div>")
5602 * // Use an existing icon element instead of the one generated by the class
5603 * $icon: this.$element
5604 * // Use an icon element from a child widget
5605 * $icon: this.childwidget.$element
5606 * @cfg {Object|string} [icon=''] The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of
5607 * symbolic names. A map is used for i18n purposes and contains a `default` icon
5608 * name and additional names keyed by language code. The `default` name is used when no icon is keyed
5609 * by the user's language.
5610 *
5611 * Example of an i18n map:
5612 *
5613 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
5614 * See the [OOjs UI documentation on MediaWiki] [2] for a list of icons included in the library.
5615 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
5616 * @cfg {string|Function} [iconTitle] A text string used as the icon title, or a function that returns title
5617 * text. The icon title is displayed when users move the mouse over the icon.
5618 */
5619 OO.ui.mixin.IconElement = function OoUiMixinIconElement( config ) {
5620 // Configuration initialization
5621 config = config || {};
5622
5623 // Properties
5624 this.$icon = null;
5625 this.icon = null;
5626 this.iconTitle = null;
5627
5628 // Initialization
5629 this.setIcon( config.icon || this.constructor.static.icon );
5630 this.setIconTitle( config.iconTitle || this.constructor.static.iconTitle );
5631 this.setIconElement( config.$icon || $( '<span>' ) );
5632 };
5633
5634 /* Setup */
5635
5636 OO.initClass( OO.ui.mixin.IconElement );
5637
5638 /* Static Properties */
5639
5640 /**
5641 * The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of symbolic names. A map is used
5642 * for i18n purposes and contains a `default` icon name and additional names keyed by
5643 * language code. The `default` name is used when no icon is keyed by the user's language.
5644 *
5645 * Example of an i18n map:
5646 *
5647 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
5648 *
5649 * Note: the static property will be overridden if the #icon configuration is used.
5650 *
5651 * @static
5652 * @inheritable
5653 * @property {Object|string}
5654 */
5655 OO.ui.mixin.IconElement.static.icon = null;
5656
5657 /**
5658 * The icon title, displayed when users move the mouse over the icon. The value can be text, a
5659 * function that returns title text, or `null` for no title.
5660 *
5661 * The static property will be overridden if the #iconTitle configuration is used.
5662 *
5663 * @static
5664 * @inheritable
5665 * @property {string|Function|null}
5666 */
5667 OO.ui.mixin.IconElement.static.iconTitle = null;
5668
5669 /* Methods */
5670
5671 /**
5672 * Set the icon element. This method is used to retarget an icon mixin so that its functionality
5673 * applies to the specified icon element instead of the one created by the class. If an icon
5674 * element is already set, the mixin’s effect on that element is removed. Generated CSS classes
5675 * and mixin methods will no longer affect the element.
5676 *
5677 * @param {jQuery} $icon Element to use as icon
5678 */
5679 OO.ui.mixin.IconElement.prototype.setIconElement = function ( $icon ) {
5680 if ( this.$icon ) {
5681 this.$icon
5682 .removeClass( 'oo-ui-iconElement-icon oo-ui-icon-' + this.icon )
5683 .removeAttr( 'title' );
5684 }
5685
5686 this.$icon = $icon
5687 .addClass( 'oo-ui-iconElement-icon' )
5688 .toggleClass( 'oo-ui-icon-' + this.icon, !!this.icon );
5689 if ( this.iconTitle !== null ) {
5690 this.$icon.attr( 'title', this.iconTitle );
5691 }
5692
5693 this.updateThemeClasses();
5694 };
5695
5696 /**
5697 * Set icon by symbolic name (e.g., ‘remove’ or ‘menu’). Use `null` to remove an icon.
5698 * The icon parameter can also be set to a map of icon names. See the #icon config setting
5699 * for an example.
5700 *
5701 * @param {Object|string|null} icon A symbolic icon name, a {@link #icon map of icon names} keyed
5702 * by language code, or `null` to remove the icon.
5703 * @chainable
5704 */
5705 OO.ui.mixin.IconElement.prototype.setIcon = function ( icon ) {
5706 icon = OO.isPlainObject( icon ) ? OO.ui.getLocalValue( icon, null, 'default' ) : icon;
5707 icon = typeof icon === 'string' && icon.trim().length ? icon.trim() : null;
5708
5709 if ( this.icon !== icon ) {
5710 if ( this.$icon ) {
5711 if ( this.icon !== null ) {
5712 this.$icon.removeClass( 'oo-ui-icon-' + this.icon );
5713 }
5714 if ( icon !== null ) {
5715 this.$icon.addClass( 'oo-ui-icon-' + icon );
5716 }
5717 }
5718 this.icon = icon;
5719 }
5720
5721 this.$element.toggleClass( 'oo-ui-iconElement', !!this.icon );
5722 this.updateThemeClasses();
5723
5724 return this;
5725 };
5726
5727 /**
5728 * Set the icon title. Use `null` to remove the title.
5729 *
5730 * @param {string|Function|null} iconTitle A text string used as the icon title,
5731 * a function that returns title text, or `null` for no title.
5732 * @chainable
5733 */
5734 OO.ui.mixin.IconElement.prototype.setIconTitle = function ( iconTitle ) {
5735 iconTitle = typeof iconTitle === 'function' ||
5736 ( typeof iconTitle === 'string' && iconTitle.length ) ?
5737 OO.ui.resolveMsg( iconTitle ) : null;
5738
5739 if ( this.iconTitle !== iconTitle ) {
5740 this.iconTitle = iconTitle;
5741 if ( this.$icon ) {
5742 if ( this.iconTitle !== null ) {
5743 this.$icon.attr( 'title', iconTitle );
5744 } else {
5745 this.$icon.removeAttr( 'title' );
5746 }
5747 }
5748 }
5749
5750 return this;
5751 };
5752
5753 /**
5754 * Get the symbolic name of the icon.
5755 *
5756 * @return {string} Icon name
5757 */
5758 OO.ui.mixin.IconElement.prototype.getIcon = function () {
5759 return this.icon;
5760 };
5761
5762 /**
5763 * Get the icon title. The title text is displayed when a user moves the mouse over the icon.
5764 *
5765 * @return {string} Icon title text
5766 */
5767 OO.ui.mixin.IconElement.prototype.getIconTitle = function () {
5768 return this.iconTitle;
5769 };
5770
5771 /**
5772 * IndicatorElement is often mixed into other classes to generate an indicator.
5773 * Indicators are small graphics that are generally used in two ways:
5774 *
5775 * - To draw attention to the status of an item. For example, an indicator might be
5776 * used to show that an item in a list has errors that need to be resolved.
5777 * - To clarify the function of a control that acts in an exceptional way (a button
5778 * that opens a menu instead of performing an action directly, for example).
5779 *
5780 * For a list of indicators included in the library, please see the
5781 * [OOjs UI documentation on MediaWiki] [1].
5782 *
5783 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
5784 *
5785 * @abstract
5786 * @class
5787 *
5788 * @constructor
5789 * @param {Object} [config] Configuration options
5790 * @cfg {jQuery} [$indicator] The indicator element created by the class. If this
5791 * configuration is omitted, the indicator element will use a generated `<span>`.
5792 * @cfg {string} [indicator] Symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
5793 * See the [OOjs UI documentation on MediaWiki][2] for a list of indicators included
5794 * in the library.
5795 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
5796 * @cfg {string|Function} [indicatorTitle] A text string used as the indicator title,
5797 * or a function that returns title text. The indicator title is displayed when users move
5798 * the mouse over the indicator.
5799 */
5800 OO.ui.mixin.IndicatorElement = function OoUiMixinIndicatorElement( config ) {
5801 // Configuration initialization
5802 config = config || {};
5803
5804 // Properties
5805 this.$indicator = null;
5806 this.indicator = null;
5807 this.indicatorTitle = null;
5808
5809 // Initialization
5810 this.setIndicator( config.indicator || this.constructor.static.indicator );
5811 this.setIndicatorTitle( config.indicatorTitle || this.constructor.static.indicatorTitle );
5812 this.setIndicatorElement( config.$indicator || $( '<span>' ) );
5813 };
5814
5815 /* Setup */
5816
5817 OO.initClass( OO.ui.mixin.IndicatorElement );
5818
5819 /* Static Properties */
5820
5821 /**
5822 * Symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
5823 * The static property will be overridden if the #indicator configuration is used.
5824 *
5825 * @static
5826 * @inheritable
5827 * @property {string|null}
5828 */
5829 OO.ui.mixin.IndicatorElement.static.indicator = null;
5830
5831 /**
5832 * A text string used as the indicator title, a function that returns title text, or `null`
5833 * for no title. The static property will be overridden if the #indicatorTitle configuration is used.
5834 *
5835 * @static
5836 * @inheritable
5837 * @property {string|Function|null}
5838 */
5839 OO.ui.mixin.IndicatorElement.static.indicatorTitle = null;
5840
5841 /* Methods */
5842
5843 /**
5844 * Set the indicator element.
5845 *
5846 * If an element is already set, it will be cleaned up before setting up the new element.
5847 *
5848 * @param {jQuery} $indicator Element to use as indicator
5849 */
5850 OO.ui.mixin.IndicatorElement.prototype.setIndicatorElement = function ( $indicator ) {
5851 if ( this.$indicator ) {
5852 this.$indicator
5853 .removeClass( 'oo-ui-indicatorElement-indicator oo-ui-indicator-' + this.indicator )
5854 .removeAttr( 'title' );
5855 }
5856
5857 this.$indicator = $indicator
5858 .addClass( 'oo-ui-indicatorElement-indicator' )
5859 .toggleClass( 'oo-ui-indicator-' + this.indicator, !!this.indicator );
5860 if ( this.indicatorTitle !== null ) {
5861 this.$indicator.attr( 'title', this.indicatorTitle );
5862 }
5863
5864 this.updateThemeClasses();
5865 };
5866
5867 /**
5868 * Set the indicator by its symbolic name: ‘alert’, ‘down’, ‘next’, ‘previous’, ‘required’, ‘up’. Use `null` to remove the indicator.
5869 *
5870 * @param {string|null} indicator Symbolic name of indicator, or `null` for no indicator
5871 * @chainable
5872 */
5873 OO.ui.mixin.IndicatorElement.prototype.setIndicator = function ( indicator ) {
5874 indicator = typeof indicator === 'string' && indicator.length ? indicator.trim() : null;
5875
5876 if ( this.indicator !== indicator ) {
5877 if ( this.$indicator ) {
5878 if ( this.indicator !== null ) {
5879 this.$indicator.removeClass( 'oo-ui-indicator-' + this.indicator );
5880 }
5881 if ( indicator !== null ) {
5882 this.$indicator.addClass( 'oo-ui-indicator-' + indicator );
5883 }
5884 }
5885 this.indicator = indicator;
5886 }
5887
5888 this.$element.toggleClass( 'oo-ui-indicatorElement', !!this.indicator );
5889 this.updateThemeClasses();
5890
5891 return this;
5892 };
5893
5894 /**
5895 * Set the indicator title.
5896 *
5897 * The title is displayed when a user moves the mouse over the indicator.
5898 *
5899 * @param {string|Function|null} indicator Indicator title text, a function that returns text, or
5900 * `null` for no indicator title
5901 * @chainable
5902 */
5903 OO.ui.mixin.IndicatorElement.prototype.setIndicatorTitle = function ( indicatorTitle ) {
5904 indicatorTitle = typeof indicatorTitle === 'function' ||
5905 ( typeof indicatorTitle === 'string' && indicatorTitle.length ) ?
5906 OO.ui.resolveMsg( indicatorTitle ) : null;
5907
5908 if ( this.indicatorTitle !== indicatorTitle ) {
5909 this.indicatorTitle = indicatorTitle;
5910 if ( this.$indicator ) {
5911 if ( this.indicatorTitle !== null ) {
5912 this.$indicator.attr( 'title', indicatorTitle );
5913 } else {
5914 this.$indicator.removeAttr( 'title' );
5915 }
5916 }
5917 }
5918
5919 return this;
5920 };
5921
5922 /**
5923 * Get the symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
5924 *
5925 * @return {string} Symbolic name of indicator
5926 */
5927 OO.ui.mixin.IndicatorElement.prototype.getIndicator = function () {
5928 return this.indicator;
5929 };
5930
5931 /**
5932 * Get the indicator title.
5933 *
5934 * The title is displayed when a user moves the mouse over the indicator.
5935 *
5936 * @return {string} Indicator title text
5937 */
5938 OO.ui.mixin.IndicatorElement.prototype.getIndicatorTitle = function () {
5939 return this.indicatorTitle;
5940 };
5941
5942 /**
5943 * LabelElement is often mixed into other classes to generate a label, which
5944 * helps identify the function of an interface element.
5945 * See the [OOjs UI documentation on MediaWiki] [1] for more information.
5946 *
5947 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Labels
5948 *
5949 * @abstract
5950 * @class
5951 *
5952 * @constructor
5953 * @param {Object} [config] Configuration options
5954 * @cfg {jQuery} [$label] The label element created by the class. If this
5955 * configuration is omitted, the label element will use a generated `<span>`.
5956 * @cfg {jQuery|string|Function|OO.ui.HtmlSnippet} [label] The label text. The label can be specified
5957 * as a plaintext string, a jQuery selection of elements, or a function that will produce a string
5958 * in the future. See the [OOjs UI documentation on MediaWiki] [2] for examples.
5959 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Labels
5960 * @cfg {boolean} [autoFitLabel=true] Fit the label to the width of the parent element.
5961 * The label will be truncated to fit if necessary.
5962 */
5963 OO.ui.mixin.LabelElement = function OoUiMixinLabelElement( config ) {
5964 // Configuration initialization
5965 config = config || {};
5966
5967 // Properties
5968 this.$label = null;
5969 this.label = null;
5970 this.autoFitLabel = config.autoFitLabel === undefined || !!config.autoFitLabel;
5971
5972 // Initialization
5973 this.setLabel( config.label || this.constructor.static.label );
5974 this.setLabelElement( config.$label || $( '<span>' ) );
5975 };
5976
5977 /* Setup */
5978
5979 OO.initClass( OO.ui.mixin.LabelElement );
5980
5981 /* Events */
5982
5983 /**
5984 * @event labelChange
5985 * @param {string} value
5986 */
5987
5988 /* Static Properties */
5989
5990 /**
5991 * The label text. The label can be specified as a plaintext string, a function that will
5992 * produce a string in the future, or `null` for no label. The static value will
5993 * be overridden if a label is specified with the #label config option.
5994 *
5995 * @static
5996 * @inheritable
5997 * @property {string|Function|null}
5998 */
5999 OO.ui.mixin.LabelElement.static.label = null;
6000
6001 /* Methods */
6002
6003 /**
6004 * Set the label element.
6005 *
6006 * If an element is already set, it will be cleaned up before setting up the new element.
6007 *
6008 * @param {jQuery} $label Element to use as label
6009 */
6010 OO.ui.mixin.LabelElement.prototype.setLabelElement = function ( $label ) {
6011 if ( this.$label ) {
6012 this.$label.removeClass( 'oo-ui-labelElement-label' ).empty();
6013 }
6014
6015 this.$label = $label.addClass( 'oo-ui-labelElement-label' );
6016 this.setLabelContent( this.label );
6017 };
6018
6019 /**
6020 * Set the label.
6021 *
6022 * An empty string will result in the label being hidden. A string containing only whitespace will
6023 * be converted to a single `&nbsp;`.
6024 *
6025 * @param {jQuery|string|OO.ui.HtmlSnippet|Function|null} label Label nodes; text; a function that returns nodes or
6026 * text; or null for no label
6027 * @chainable
6028 */
6029 OO.ui.mixin.LabelElement.prototype.setLabel = function ( label ) {
6030 label = typeof label === 'function' ? OO.ui.resolveMsg( label ) : label;
6031 label = ( ( typeof label === 'string' && label.length ) || label instanceof jQuery || label instanceof OO.ui.HtmlSnippet ) ? label : null;
6032
6033 this.$element.toggleClass( 'oo-ui-labelElement', !!label );
6034
6035 if ( this.label !== label ) {
6036 if ( this.$label ) {
6037 this.setLabelContent( label );
6038 }
6039 this.label = label;
6040 this.emit( 'labelChange' );
6041 }
6042
6043 return this;
6044 };
6045
6046 /**
6047 * Get the label.
6048 *
6049 * @return {jQuery|string|Function|null} Label nodes; text; a function that returns nodes or
6050 * text; or null for no label
6051 */
6052 OO.ui.mixin.LabelElement.prototype.getLabel = function () {
6053 return this.label;
6054 };
6055
6056 /**
6057 * Fit the label.
6058 *
6059 * @chainable
6060 */
6061 OO.ui.mixin.LabelElement.prototype.fitLabel = function () {
6062 if ( this.$label && this.$label.autoEllipsis && this.autoFitLabel ) {
6063 this.$label.autoEllipsis( { hasSpan: false, tooltip: true } );
6064 }
6065
6066 return this;
6067 };
6068
6069 /**
6070 * Set the content of the label.
6071 *
6072 * Do not call this method until after the label element has been set by #setLabelElement.
6073 *
6074 * @private
6075 * @param {jQuery|string|Function|null} label Label nodes; text; a function that returns nodes or
6076 * text; or null for no label
6077 */
6078 OO.ui.mixin.LabelElement.prototype.setLabelContent = function ( label ) {
6079 if ( typeof label === 'string' ) {
6080 if ( label.match( /^\s*$/ ) ) {
6081 // Convert whitespace only string to a single non-breaking space
6082 this.$label.html( '&nbsp;' );
6083 } else {
6084 this.$label.text( label );
6085 }
6086 } else if ( label instanceof OO.ui.HtmlSnippet ) {
6087 this.$label.html( label.toString() );
6088 } else if ( label instanceof jQuery ) {
6089 this.$label.empty().append( label );
6090 } else {
6091 this.$label.empty();
6092 }
6093 };
6094
6095 /**
6096 * LookupElement is a mixin that creates a {@link OO.ui.FloatingMenuSelectWidget menu} of suggested values for
6097 * a {@link OO.ui.TextInputWidget text input widget}. Suggested values are based on the characters the user types
6098 * into the text input field and, in general, the menu is only displayed when the user types. If a suggested value is chosen
6099 * from the lookup menu, that value becomes the value of the input field.
6100 *
6101 * Note that a new menu of suggested items is displayed when a value is chosen from the lookup menu. If this is
6102 * not the desired behavior, disable lookup menus with the #setLookupsDisabled method, then set the value, then
6103 * re-enable lookups.
6104 *
6105 * See the [OOjs UI demos][1] for an example.
6106 *
6107 * [1]: https://tools.wmflabs.org/oojs-ui/oojs-ui/demos/index.html#widgets-apex-vector-ltr
6108 *
6109 * @class
6110 * @abstract
6111 *
6112 * @constructor
6113 * @param {Object} [config] Configuration options
6114 * @cfg {jQuery} [$overlay] Overlay for the lookup menu; defaults to relative positioning
6115 * @cfg {jQuery} [$container=this.$element] The container element. The lookup menu is rendered beneath the specified element.
6116 * @cfg {boolean} [allowSuggestionsWhenEmpty=false] Request and display a lookup menu when the text input is empty.
6117 * By default, the lookup menu is not generated and displayed until the user begins to type.
6118 * @cfg {boolean} [highlightFirst=true] Whether the first lookup result should be highlighted (so, that the user can
6119 * take it over into the input with simply pressing return) automatically or not.
6120 */
6121 OO.ui.mixin.LookupElement = function OoUiMixinLookupElement( config ) {
6122 // Configuration initialization
6123 config = $.extend( { highlightFirst: true }, config );
6124
6125 // Mixin constructors
6126 OO.ui.mixin.RequestManager.call( this, config );
6127
6128 // Properties
6129 this.$overlay = config.$overlay || this.$element;
6130 this.lookupMenu = new OO.ui.FloatingMenuSelectWidget( {
6131 widget: this,
6132 input: this,
6133 $container: config.$container || this.$element
6134 } );
6135
6136 this.allowSuggestionsWhenEmpty = config.allowSuggestionsWhenEmpty || false;
6137
6138 this.lookupsDisabled = false;
6139 this.lookupInputFocused = false;
6140 this.lookupHighlightFirstItem = config.highlightFirst;
6141
6142 // Events
6143 this.$input.on( {
6144 focus: this.onLookupInputFocus.bind( this ),
6145 blur: this.onLookupInputBlur.bind( this ),
6146 mousedown: this.onLookupInputMouseDown.bind( this )
6147 } );
6148 this.connect( this, { change: 'onLookupInputChange' } );
6149 this.lookupMenu.connect( this, {
6150 toggle: 'onLookupMenuToggle',
6151 choose: 'onLookupMenuItemChoose'
6152 } );
6153
6154 // Initialization
6155 this.$element.addClass( 'oo-ui-lookupElement' );
6156 this.lookupMenu.$element.addClass( 'oo-ui-lookupElement-menu' );
6157 this.$overlay.append( this.lookupMenu.$element );
6158 };
6159
6160 /* Setup */
6161
6162 OO.mixinClass( OO.ui.mixin.LookupElement, OO.ui.mixin.RequestManager );
6163
6164 /* Methods */
6165
6166 /**
6167 * Handle input focus event.
6168 *
6169 * @protected
6170 * @param {jQuery.Event} e Input focus event
6171 */
6172 OO.ui.mixin.LookupElement.prototype.onLookupInputFocus = function () {
6173 this.lookupInputFocused = true;
6174 this.populateLookupMenu();
6175 };
6176
6177 /**
6178 * Handle input blur event.
6179 *
6180 * @protected
6181 * @param {jQuery.Event} e Input blur event
6182 */
6183 OO.ui.mixin.LookupElement.prototype.onLookupInputBlur = function () {
6184 this.closeLookupMenu();
6185 this.lookupInputFocused = false;
6186 };
6187
6188 /**
6189 * Handle input mouse down event.
6190 *
6191 * @protected
6192 * @param {jQuery.Event} e Input mouse down event
6193 */
6194 OO.ui.mixin.LookupElement.prototype.onLookupInputMouseDown = function () {
6195 // Only open the menu if the input was already focused.
6196 // This way we allow the user to open the menu again after closing it with Esc
6197 // by clicking in the input. Opening (and populating) the menu when initially
6198 // clicking into the input is handled by the focus handler.
6199 if ( this.lookupInputFocused && !this.lookupMenu.isVisible() ) {
6200 this.populateLookupMenu();
6201 }
6202 };
6203
6204 /**
6205 * Handle input change event.
6206 *
6207 * @protected
6208 * @param {string} value New input value
6209 */
6210 OO.ui.mixin.LookupElement.prototype.onLookupInputChange = function () {
6211 if ( this.lookupInputFocused ) {
6212 this.populateLookupMenu();
6213 }
6214 };
6215
6216 /**
6217 * Handle the lookup menu being shown/hidden.
6218 *
6219 * @protected
6220 * @param {boolean} visible Whether the lookup menu is now visible.
6221 */
6222 OO.ui.mixin.LookupElement.prototype.onLookupMenuToggle = function ( visible ) {
6223 if ( !visible ) {
6224 // When the menu is hidden, abort any active request and clear the menu.
6225 // This has to be done here in addition to closeLookupMenu(), because
6226 // MenuSelectWidget will close itself when the user presses Esc.
6227 this.abortLookupRequest();
6228 this.lookupMenu.clearItems();
6229 }
6230 };
6231
6232 /**
6233 * Handle menu item 'choose' event, updating the text input value to the value of the clicked item.
6234 *
6235 * @protected
6236 * @param {OO.ui.MenuOptionWidget} item Selected item
6237 */
6238 OO.ui.mixin.LookupElement.prototype.onLookupMenuItemChoose = function ( item ) {
6239 this.setValue( item.getData() );
6240 };
6241
6242 /**
6243 * Get lookup menu.
6244 *
6245 * @private
6246 * @return {OO.ui.FloatingMenuSelectWidget}
6247 */
6248 OO.ui.mixin.LookupElement.prototype.getLookupMenu = function () {
6249 return this.lookupMenu;
6250 };
6251
6252 /**
6253 * Disable or re-enable lookups.
6254 *
6255 * When lookups are disabled, calls to #populateLookupMenu will be ignored.
6256 *
6257 * @param {boolean} disabled Disable lookups
6258 */
6259 OO.ui.mixin.LookupElement.prototype.setLookupsDisabled = function ( disabled ) {
6260 this.lookupsDisabled = !!disabled;
6261 };
6262
6263 /**
6264 * Open the menu. If there are no entries in the menu, this does nothing.
6265 *
6266 * @private
6267 * @chainable
6268 */
6269 OO.ui.mixin.LookupElement.prototype.openLookupMenu = function () {
6270 if ( !this.lookupMenu.isEmpty() ) {
6271 this.lookupMenu.toggle( true );
6272 }
6273 return this;
6274 };
6275
6276 /**
6277 * Close the menu, empty it, and abort any pending request.
6278 *
6279 * @private
6280 * @chainable
6281 */
6282 OO.ui.mixin.LookupElement.prototype.closeLookupMenu = function () {
6283 this.lookupMenu.toggle( false );
6284 this.abortLookupRequest();
6285 this.lookupMenu.clearItems();
6286 return this;
6287 };
6288
6289 /**
6290 * Request menu items based on the input's current value, and when they arrive,
6291 * populate the menu with these items and show the menu.
6292 *
6293 * If lookups have been disabled with #setLookupsDisabled, this function does nothing.
6294 *
6295 * @private
6296 * @chainable
6297 */
6298 OO.ui.mixin.LookupElement.prototype.populateLookupMenu = function () {
6299 var widget = this,
6300 value = this.getValue();
6301
6302 if ( this.lookupsDisabled || this.isReadOnly() ) {
6303 return;
6304 }
6305
6306 // If the input is empty, clear the menu, unless suggestions when empty are allowed.
6307 if ( !this.allowSuggestionsWhenEmpty && value === '' ) {
6308 this.closeLookupMenu();
6309 // Skip population if there is already a request pending for the current value
6310 } else if ( value !== this.lookupQuery ) {
6311 this.getLookupMenuItems()
6312 .done( function ( items ) {
6313 widget.lookupMenu.clearItems();
6314 if ( items.length ) {
6315 widget.lookupMenu
6316 .addItems( items )
6317 .toggle( true );
6318 widget.initializeLookupMenuSelection();
6319 } else {
6320 widget.lookupMenu.toggle( false );
6321 }
6322 } )
6323 .fail( function () {
6324 widget.lookupMenu.clearItems();
6325 } );
6326 }
6327
6328 return this;
6329 };
6330
6331 /**
6332 * Highlight the first selectable item in the menu, if configured.
6333 *
6334 * @private
6335 * @chainable
6336 */
6337 OO.ui.mixin.LookupElement.prototype.initializeLookupMenuSelection = function () {
6338 if ( this.lookupHighlightFirstItem && !this.lookupMenu.getSelectedItem() ) {
6339 this.lookupMenu.highlightItem( this.lookupMenu.getFirstSelectableItem() );
6340 }
6341 };
6342
6343 /**
6344 * Get lookup menu items for the current query.
6345 *
6346 * @private
6347 * @return {jQuery.Promise} Promise object which will be passed menu items as the first argument of
6348 * the done event. If the request was aborted to make way for a subsequent request, this promise
6349 * will not be rejected: it will remain pending forever.
6350 */
6351 OO.ui.mixin.LookupElement.prototype.getLookupMenuItems = function () {
6352 return this.getRequestData().then( function ( data ) {
6353 return this.getLookupMenuOptionsFromData( data );
6354 }.bind( this ) );
6355 };
6356
6357 /**
6358 * Abort the currently pending lookup request, if any.
6359 *
6360 * @private
6361 */
6362 OO.ui.mixin.LookupElement.prototype.abortLookupRequest = function () {
6363 this.abortRequest();
6364 };
6365
6366 /**
6367 * Get a new request object of the current lookup query value.
6368 *
6369 * @protected
6370 * @method
6371 * @abstract
6372 * @return {jQuery.Promise} jQuery AJAX object, or promise object with an .abort() method
6373 */
6374 OO.ui.mixin.LookupElement.prototype.getLookupRequest = null;
6375
6376 /**
6377 * Pre-process data returned by the request from #getLookupRequest.
6378 *
6379 * The return value of this function will be cached, and any further queries for the given value
6380 * will use the cache rather than doing API requests.
6381 *
6382 * @protected
6383 * @method
6384 * @abstract
6385 * @param {Mixed} response Response from server
6386 * @return {Mixed} Cached result data
6387 */
6388 OO.ui.mixin.LookupElement.prototype.getLookupCacheDataFromResponse = null;
6389
6390 /**
6391 * Get a list of menu option widgets from the (possibly cached) data returned by
6392 * #getLookupCacheDataFromResponse.
6393 *
6394 * @protected
6395 * @method
6396 * @abstract
6397 * @param {Mixed} data Cached result data, usually an array
6398 * @return {OO.ui.MenuOptionWidget[]} Menu items
6399 */
6400 OO.ui.mixin.LookupElement.prototype.getLookupMenuOptionsFromData = null;
6401
6402 /**
6403 * Set the read-only state of the widget.
6404 *
6405 * This will also disable/enable the lookups functionality.
6406 *
6407 * @param {boolean} readOnly Make input read-only
6408 * @chainable
6409 */
6410 OO.ui.mixin.LookupElement.prototype.setReadOnly = function ( readOnly ) {
6411 // Parent method
6412 // Note: Calling #setReadOnly this way assumes this is mixed into an OO.ui.TextInputWidget
6413 OO.ui.TextInputWidget.prototype.setReadOnly.call( this, readOnly );
6414
6415 // During construction, #setReadOnly is called before the OO.ui.mixin.LookupElement constructor
6416 if ( this.isReadOnly() && this.lookupMenu ) {
6417 this.closeLookupMenu();
6418 }
6419
6420 return this;
6421 };
6422
6423 /**
6424 * @inheritdoc OO.ui.mixin.RequestManager
6425 */
6426 OO.ui.mixin.LookupElement.prototype.getRequestQuery = function () {
6427 return this.getValue();
6428 };
6429
6430 /**
6431 * @inheritdoc OO.ui.mixin.RequestManager
6432 */
6433 OO.ui.mixin.LookupElement.prototype.getRequest = function () {
6434 return this.getLookupRequest();
6435 };
6436
6437 /**
6438 * @inheritdoc OO.ui.mixin.RequestManager
6439 */
6440 OO.ui.mixin.LookupElement.prototype.getRequestCacheDataFromResponse = function ( response ) {
6441 return this.getLookupCacheDataFromResponse( response );
6442 };
6443
6444 /**
6445 * PopupElement is mixed into other classes to generate a {@link OO.ui.PopupWidget popup widget}.
6446 * A popup is a container for content. It is overlaid and positioned absolutely. By default, each
6447 * popup has an anchor, which is an arrow-like protrusion that points toward the popup’s origin.
6448 * See {@link OO.ui.PopupWidget PopupWidget} for an example.
6449 *
6450 * @abstract
6451 * @class
6452 *
6453 * @constructor
6454 * @param {Object} [config] Configuration options
6455 * @cfg {Object} [popup] Configuration to pass to popup
6456 * @cfg {boolean} [popup.autoClose=true] Popup auto-closes when it loses focus
6457 */
6458 OO.ui.mixin.PopupElement = function OoUiMixinPopupElement( config ) {
6459 // Configuration initialization
6460 config = config || {};
6461
6462 // Properties
6463 this.popup = new OO.ui.PopupWidget( $.extend(
6464 { autoClose: true },
6465 config.popup,
6466 { $autoCloseIgnore: this.$element }
6467 ) );
6468 };
6469
6470 /* Methods */
6471
6472 /**
6473 * Get popup.
6474 *
6475 * @return {OO.ui.PopupWidget} Popup widget
6476 */
6477 OO.ui.mixin.PopupElement.prototype.getPopup = function () {
6478 return this.popup;
6479 };
6480
6481 /**
6482 * The FlaggedElement class is an attribute mixin, meaning that it is used to add
6483 * additional functionality to an element created by another class. The class provides
6484 * a ‘flags’ property assigned the name (or an array of names) of styling flags,
6485 * which are used to customize the look and feel of a widget to better describe its
6486 * importance and functionality.
6487 *
6488 * The library currently contains the following styling flags for general use:
6489 *
6490 * - **progressive**: Progressive styling is applied to convey that the widget will move the user forward in a process.
6491 * - **destructive**: Destructive styling is applied to convey that the widget will remove something.
6492 * - **constructive**: Constructive styling is applied to convey that the widget will create something.
6493 *
6494 * The flags affect the appearance of the buttons:
6495 *
6496 * @example
6497 * // FlaggedElement is mixed into ButtonWidget to provide styling flags
6498 * var button1 = new OO.ui.ButtonWidget( {
6499 * label: 'Constructive',
6500 * flags: 'constructive'
6501 * } );
6502 * var button2 = new OO.ui.ButtonWidget( {
6503 * label: 'Destructive',
6504 * flags: 'destructive'
6505 * } );
6506 * var button3 = new OO.ui.ButtonWidget( {
6507 * label: 'Progressive',
6508 * flags: 'progressive'
6509 * } );
6510 * $( 'body' ).append( button1.$element, button2.$element, button3.$element );
6511 *
6512 * {@link OO.ui.ActionWidget ActionWidgets}, which are a special kind of button that execute an action, use these flags: **primary** and **safe**.
6513 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information.
6514 *
6515 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Flagged
6516 *
6517 * @abstract
6518 * @class
6519 *
6520 * @constructor
6521 * @param {Object} [config] Configuration options
6522 * @cfg {string|string[]} [flags] The name or names of the flags (e.g., 'constructive' or 'primary') to apply.
6523 * Please see the [OOjs UI documentation on MediaWiki] [2] for more information about available flags.
6524 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Flagged
6525 * @cfg {jQuery} [$flagged] The flagged element. By default,
6526 * the flagged functionality is applied to the element created by the class ($element).
6527 * If a different element is specified, the flagged functionality will be applied to it instead.
6528 */
6529 OO.ui.mixin.FlaggedElement = function OoUiMixinFlaggedElement( config ) {
6530 // Configuration initialization
6531 config = config || {};
6532
6533 // Properties
6534 this.flags = {};
6535 this.$flagged = null;
6536
6537 // Initialization
6538 this.setFlags( config.flags );
6539 this.setFlaggedElement( config.$flagged || this.$element );
6540 };
6541
6542 /* Events */
6543
6544 /**
6545 * @event flag
6546 * A flag event is emitted when the #clearFlags or #setFlags methods are used. The `changes`
6547 * parameter contains the name of each modified flag and indicates whether it was
6548 * added or removed.
6549 *
6550 * @param {Object.<string,boolean>} changes Object keyed by flag name. A Boolean `true` indicates
6551 * that the flag was added, `false` that the flag was removed.
6552 */
6553
6554 /* Methods */
6555
6556 /**
6557 * Set the flagged element.
6558 *
6559 * This method is used to retarget a flagged mixin so that its functionality applies to the specified element.
6560 * If an element is already set, the method will remove the mixin’s effect on that element.
6561 *
6562 * @param {jQuery} $flagged Element that should be flagged
6563 */
6564 OO.ui.mixin.FlaggedElement.prototype.setFlaggedElement = function ( $flagged ) {
6565 var classNames = Object.keys( this.flags ).map( function ( flag ) {
6566 return 'oo-ui-flaggedElement-' + flag;
6567 } ).join( ' ' );
6568
6569 if ( this.$flagged ) {
6570 this.$flagged.removeClass( classNames );
6571 }
6572
6573 this.$flagged = $flagged.addClass( classNames );
6574 };
6575
6576 /**
6577 * Check if the specified flag is set.
6578 *
6579 * @param {string} flag Name of flag
6580 * @return {boolean} The flag is set
6581 */
6582 OO.ui.mixin.FlaggedElement.prototype.hasFlag = function ( flag ) {
6583 // This may be called before the constructor, thus before this.flags is set
6584 return this.flags && ( flag in this.flags );
6585 };
6586
6587 /**
6588 * Get the names of all flags set.
6589 *
6590 * @return {string[]} Flag names
6591 */
6592 OO.ui.mixin.FlaggedElement.prototype.getFlags = function () {
6593 // This may be called before the constructor, thus before this.flags is set
6594 return Object.keys( this.flags || {} );
6595 };
6596
6597 /**
6598 * Clear all flags.
6599 *
6600 * @chainable
6601 * @fires flag
6602 */
6603 OO.ui.mixin.FlaggedElement.prototype.clearFlags = function () {
6604 var flag, className,
6605 changes = {},
6606 remove = [],
6607 classPrefix = 'oo-ui-flaggedElement-';
6608
6609 for ( flag in this.flags ) {
6610 className = classPrefix + flag;
6611 changes[ flag ] = false;
6612 delete this.flags[ flag ];
6613 remove.push( className );
6614 }
6615
6616 if ( this.$flagged ) {
6617 this.$flagged.removeClass( remove.join( ' ' ) );
6618 }
6619
6620 this.updateThemeClasses();
6621 this.emit( 'flag', changes );
6622
6623 return this;
6624 };
6625
6626 /**
6627 * Add one or more flags.
6628 *
6629 * @param {string|string[]|Object.<string, boolean>} flags A flag name, an array of flag names,
6630 * or an object keyed by flag name with a boolean value that indicates whether the flag should
6631 * be added (`true`) or removed (`false`).
6632 * @chainable
6633 * @fires flag
6634 */
6635 OO.ui.mixin.FlaggedElement.prototype.setFlags = function ( flags ) {
6636 var i, len, flag, className,
6637 changes = {},
6638 add = [],
6639 remove = [],
6640 classPrefix = 'oo-ui-flaggedElement-';
6641
6642 if ( typeof flags === 'string' ) {
6643 className = classPrefix + flags;
6644 // Set
6645 if ( !this.flags[ flags ] ) {
6646 this.flags[ flags ] = true;
6647 add.push( className );
6648 }
6649 } else if ( Array.isArray( flags ) ) {
6650 for ( i = 0, len = flags.length; i < len; i++ ) {
6651 flag = flags[ i ];
6652 className = classPrefix + flag;
6653 // Set
6654 if ( !this.flags[ flag ] ) {
6655 changes[ flag ] = true;
6656 this.flags[ flag ] = true;
6657 add.push( className );
6658 }
6659 }
6660 } else if ( OO.isPlainObject( flags ) ) {
6661 for ( flag in flags ) {
6662 className = classPrefix + flag;
6663 if ( flags[ flag ] ) {
6664 // Set
6665 if ( !this.flags[ flag ] ) {
6666 changes[ flag ] = true;
6667 this.flags[ flag ] = true;
6668 add.push( className );
6669 }
6670 } else {
6671 // Remove
6672 if ( this.flags[ flag ] ) {
6673 changes[ flag ] = false;
6674 delete this.flags[ flag ];
6675 remove.push( className );
6676 }
6677 }
6678 }
6679 }
6680
6681 if ( this.$flagged ) {
6682 this.$flagged
6683 .addClass( add.join( ' ' ) )
6684 .removeClass( remove.join( ' ' ) );
6685 }
6686
6687 this.updateThemeClasses();
6688 this.emit( 'flag', changes );
6689
6690 return this;
6691 };
6692
6693 /**
6694 * TitledElement is mixed into other classes to provide a `title` attribute.
6695 * Titles are rendered by the browser and are made visible when the user moves
6696 * the mouse over the element. Titles are not visible on touch devices.
6697 *
6698 * @example
6699 * // TitledElement provides a 'title' attribute to the
6700 * // ButtonWidget class
6701 * var button = new OO.ui.ButtonWidget( {
6702 * label: 'Button with Title',
6703 * title: 'I am a button'
6704 * } );
6705 * $( 'body' ).append( button.$element );
6706 *
6707 * @abstract
6708 * @class
6709 *
6710 * @constructor
6711 * @param {Object} [config] Configuration options
6712 * @cfg {jQuery} [$titled] The element to which the `title` attribute is applied.
6713 * If this config is omitted, the title functionality is applied to $element, the
6714 * element created by the class.
6715 * @cfg {string|Function} [title] The title text or a function that returns text. If
6716 * this config is omitted, the value of the {@link #static-title static title} property is used.
6717 */
6718 OO.ui.mixin.TitledElement = function OoUiMixinTitledElement( config ) {
6719 // Configuration initialization
6720 config = config || {};
6721
6722 // Properties
6723 this.$titled = null;
6724 this.title = null;
6725
6726 // Initialization
6727 this.setTitle( config.title || this.constructor.static.title );
6728 this.setTitledElement( config.$titled || this.$element );
6729 };
6730
6731 /* Setup */
6732
6733 OO.initClass( OO.ui.mixin.TitledElement );
6734
6735 /* Static Properties */
6736
6737 /**
6738 * The title text, a function that returns text, or `null` for no title. The value of the static property
6739 * is overridden if the #title config option is used.
6740 *
6741 * @static
6742 * @inheritable
6743 * @property {string|Function|null}
6744 */
6745 OO.ui.mixin.TitledElement.static.title = null;
6746
6747 /* Methods */
6748
6749 /**
6750 * Set the titled element.
6751 *
6752 * This method is used to retarget a titledElement mixin so that its functionality applies to the specified element.
6753 * If an element is already set, the mixin’s effect on that element is removed before the new element is set up.
6754 *
6755 * @param {jQuery} $titled Element that should use the 'titled' functionality
6756 */
6757 OO.ui.mixin.TitledElement.prototype.setTitledElement = function ( $titled ) {
6758 if ( this.$titled ) {
6759 this.$titled.removeAttr( 'title' );
6760 }
6761
6762 this.$titled = $titled;
6763 if ( this.title ) {
6764 this.$titled.attr( 'title', this.title );
6765 }
6766 };
6767
6768 /**
6769 * Set title.
6770 *
6771 * @param {string|Function|null} title Title text, a function that returns text, or `null` for no title
6772 * @chainable
6773 */
6774 OO.ui.mixin.TitledElement.prototype.setTitle = function ( title ) {
6775 title = typeof title === 'function' ? OO.ui.resolveMsg( title ) : title;
6776 title = ( typeof title === 'string' && title.length ) ? title : null;
6777
6778 if ( this.title !== title ) {
6779 if ( this.$titled ) {
6780 if ( title !== null ) {
6781 this.$titled.attr( 'title', title );
6782 } else {
6783 this.$titled.removeAttr( 'title' );
6784 }
6785 }
6786 this.title = title;
6787 }
6788
6789 return this;
6790 };
6791
6792 /**
6793 * Get title.
6794 *
6795 * @return {string} Title string
6796 */
6797 OO.ui.mixin.TitledElement.prototype.getTitle = function () {
6798 return this.title;
6799 };
6800
6801 /**
6802 * Element that can be automatically clipped to visible boundaries.
6803 *
6804 * Whenever the element's natural height changes, you have to call
6805 * {@link OO.ui.mixin.ClippableElement#clip} to make sure it's still
6806 * clipping correctly.
6807 *
6808 * The dimensions of #$clippableContainer will be compared to the boundaries of the
6809 * nearest scrollable container. If #$clippableContainer is too tall and/or too wide,
6810 * then #$clippable will be given a fixed reduced height and/or width and will be made
6811 * scrollable. By default, #$clippable and #$clippableContainer are the same element,
6812 * but you can build a static footer by setting #$clippableContainer to an element that contains
6813 * #$clippable and the footer.
6814 *
6815 * @abstract
6816 * @class
6817 *
6818 * @constructor
6819 * @param {Object} [config] Configuration options
6820 * @cfg {jQuery} [$clippable] Node to clip, assigned to #$clippable, omit to use #$element
6821 * @cfg {jQuery} [$clippableContainer] Node to keep visible, assigned to #$clippableContainer,
6822 * omit to use #$clippable
6823 */
6824 OO.ui.mixin.ClippableElement = function OoUiMixinClippableElement( config ) {
6825 // Configuration initialization
6826 config = config || {};
6827
6828 // Properties
6829 this.$clippable = null;
6830 this.$clippableContainer = null;
6831 this.clipping = false;
6832 this.clippedHorizontally = false;
6833 this.clippedVertically = false;
6834 this.$clippableScrollableContainer = null;
6835 this.$clippableScroller = null;
6836 this.$clippableWindow = null;
6837 this.idealWidth = null;
6838 this.idealHeight = null;
6839 this.onClippableScrollHandler = this.clip.bind( this );
6840 this.onClippableWindowResizeHandler = this.clip.bind( this );
6841
6842 // Initialization
6843 if ( config.$clippableContainer ) {
6844 this.setClippableContainer( config.$clippableContainer );
6845 }
6846 this.setClippableElement( config.$clippable || this.$element );
6847 };
6848
6849 /* Methods */
6850
6851 /**
6852 * Set clippable element.
6853 *
6854 * If an element is already set, it will be cleaned up before setting up the new element.
6855 *
6856 * @param {jQuery} $clippable Element to make clippable
6857 */
6858 OO.ui.mixin.ClippableElement.prototype.setClippableElement = function ( $clippable ) {
6859 if ( this.$clippable ) {
6860 this.$clippable.removeClass( 'oo-ui-clippableElement-clippable' );
6861 this.$clippable.css( { width: '', height: '', overflowX: '', overflowY: '' } );
6862 OO.ui.Element.static.reconsiderScrollbars( this.$clippable[ 0 ] );
6863 }
6864
6865 this.$clippable = $clippable.addClass( 'oo-ui-clippableElement-clippable' );
6866 this.clip();
6867 };
6868
6869 /**
6870 * Set clippable container.
6871 *
6872 * This is the container that will be measured when deciding whether to clip. When clipping,
6873 * #$clippable will be resized in order to keep the clippable container fully visible.
6874 *
6875 * If the clippable container is unset, #$clippable will be used.
6876 *
6877 * @param {jQuery|null} $clippableContainer Container to keep visible, or null to unset
6878 */
6879 OO.ui.mixin.ClippableElement.prototype.setClippableContainer = function ( $clippableContainer ) {
6880 this.$clippableContainer = $clippableContainer;
6881 if ( this.$clippable ) {
6882 this.clip();
6883 }
6884 };
6885
6886 /**
6887 * Toggle clipping.
6888 *
6889 * Do not turn clipping on until after the element is attached to the DOM and visible.
6890 *
6891 * @param {boolean} [clipping] Enable clipping, omit to toggle
6892 * @chainable
6893 */
6894 OO.ui.mixin.ClippableElement.prototype.toggleClipping = function ( clipping ) {
6895 clipping = clipping === undefined ? !this.clipping : !!clipping;
6896
6897 if ( this.clipping !== clipping ) {
6898 this.clipping = clipping;
6899 if ( clipping ) {
6900 this.$clippableScrollableContainer = $( this.getClosestScrollableElementContainer() );
6901 // If the clippable container is the root, we have to listen to scroll events and check
6902 // jQuery.scrollTop on the window because of browser inconsistencies
6903 this.$clippableScroller = this.$clippableScrollableContainer.is( 'html, body' ) ?
6904 $( OO.ui.Element.static.getWindow( this.$clippableScrollableContainer ) ) :
6905 this.$clippableScrollableContainer;
6906 this.$clippableScroller.on( 'scroll', this.onClippableScrollHandler );
6907 this.$clippableWindow = $( this.getElementWindow() )
6908 .on( 'resize', this.onClippableWindowResizeHandler );
6909 // Initial clip after visible
6910 this.clip();
6911 } else {
6912 this.$clippable.css( { width: '', height: '', overflowX: '', overflowY: '' } );
6913 OO.ui.Element.static.reconsiderScrollbars( this.$clippable[ 0 ] );
6914
6915 this.$clippableScrollableContainer = null;
6916 this.$clippableScroller.off( 'scroll', this.onClippableScrollHandler );
6917 this.$clippableScroller = null;
6918 this.$clippableWindow.off( 'resize', this.onClippableWindowResizeHandler );
6919 this.$clippableWindow = null;
6920 }
6921 }
6922
6923 return this;
6924 };
6925
6926 /**
6927 * Check if the element will be clipped to fit the visible area of the nearest scrollable container.
6928 *
6929 * @return {boolean} Element will be clipped to the visible area
6930 */
6931 OO.ui.mixin.ClippableElement.prototype.isClipping = function () {
6932 return this.clipping;
6933 };
6934
6935 /**
6936 * Check if the bottom or right of the element is being clipped by the nearest scrollable container.
6937 *
6938 * @return {boolean} Part of the element is being clipped
6939 */
6940 OO.ui.mixin.ClippableElement.prototype.isClipped = function () {
6941 return this.clippedHorizontally || this.clippedVertically;
6942 };
6943
6944 /**
6945 * Check if the right of the element is being clipped by the nearest scrollable container.
6946 *
6947 * @return {boolean} Part of the element is being clipped
6948 */
6949 OO.ui.mixin.ClippableElement.prototype.isClippedHorizontally = function () {
6950 return this.clippedHorizontally;
6951 };
6952
6953 /**
6954 * Check if the bottom of the element is being clipped by the nearest scrollable container.
6955 *
6956 * @return {boolean} Part of the element is being clipped
6957 */
6958 OO.ui.mixin.ClippableElement.prototype.isClippedVertically = function () {
6959 return this.clippedVertically;
6960 };
6961
6962 /**
6963 * Set the ideal size. These are the dimensions the element will have when it's not being clipped.
6964 *
6965 * @param {number|string} [width] Width as a number of pixels or CSS string with unit suffix
6966 * @param {number|string} [height] Height as a number of pixels or CSS string with unit suffix
6967 */
6968 OO.ui.mixin.ClippableElement.prototype.setIdealSize = function ( width, height ) {
6969 this.idealWidth = width;
6970 this.idealHeight = height;
6971
6972 if ( !this.clipping ) {
6973 // Update dimensions
6974 this.$clippable.css( { width: width, height: height } );
6975 }
6976 // While clipping, idealWidth and idealHeight are not considered
6977 };
6978
6979 /**
6980 * Clip element to visible boundaries and allow scrolling when needed. Call this method when
6981 * the element's natural height changes.
6982 *
6983 * Element will be clipped the bottom or right of the element is within 10px of the edge of, or
6984 * overlapped by, the visible area of the nearest scrollable container.
6985 *
6986 * @chainable
6987 */
6988 OO.ui.mixin.ClippableElement.prototype.clip = function () {
6989 var $container, extraHeight, extraWidth, ccOffset,
6990 $scrollableContainer, scOffset, scHeight, scWidth,
6991 ccWidth, scrollerIsWindow, scrollTop, scrollLeft,
6992 desiredWidth, desiredHeight, allotedWidth, allotedHeight,
6993 naturalWidth, naturalHeight, clipWidth, clipHeight,
6994 buffer = 7; // Chosen by fair dice roll
6995
6996 if ( !this.clipping ) {
6997 // this.$clippableScrollableContainer and this.$clippableWindow are null, so the below will fail
6998 return this;
6999 }
7000
7001 $container = this.$clippableContainer || this.$clippable;
7002 extraHeight = $container.outerHeight() - this.$clippable.outerHeight();
7003 extraWidth = $container.outerWidth() - this.$clippable.outerWidth();
7004 ccOffset = $container.offset();
7005 $scrollableContainer = this.$clippableScrollableContainer.is( 'html, body' ) ?
7006 this.$clippableWindow : this.$clippableScrollableContainer;
7007 scOffset = $scrollableContainer.offset() || { top: 0, left: 0 };
7008 scHeight = $scrollableContainer.innerHeight() - buffer;
7009 scWidth = $scrollableContainer.innerWidth() - buffer;
7010 ccWidth = $container.outerWidth() + buffer;
7011 scrollerIsWindow = this.$clippableScroller[ 0 ] === this.$clippableWindow[ 0 ];
7012 scrollTop = scrollerIsWindow ? this.$clippableScroller.scrollTop() : 0;
7013 scrollLeft = scrollerIsWindow ? this.$clippableScroller.scrollLeft() : 0;
7014 desiredWidth = ccOffset.left < 0 ?
7015 ccWidth + ccOffset.left :
7016 ( scOffset.left + scrollLeft + scWidth ) - ccOffset.left;
7017 desiredHeight = ( scOffset.top + scrollTop + scHeight ) - ccOffset.top;
7018 allotedWidth = desiredWidth - extraWidth;
7019 allotedHeight = desiredHeight - extraHeight;
7020 naturalWidth = this.$clippable.prop( 'scrollWidth' );
7021 naturalHeight = this.$clippable.prop( 'scrollHeight' );
7022 clipWidth = allotedWidth < naturalWidth;
7023 clipHeight = allotedHeight < naturalHeight;
7024
7025 if ( clipWidth ) {
7026 this.$clippable.css( { overflowX: 'scroll', width: Math.max( 0, allotedWidth ) } );
7027 } else {
7028 this.$clippable.css( { width: this.idealWidth ? this.idealWidth - extraWidth : '', overflowX: '' } );
7029 }
7030 if ( clipHeight ) {
7031 this.$clippable.css( { overflowY: 'scroll', height: Math.max( 0, allotedHeight ) } );
7032 } else {
7033 this.$clippable.css( { height: this.idealHeight ? this.idealHeight - extraHeight : '', overflowY: '' } );
7034 }
7035
7036 // If we stopped clipping in at least one of the dimensions
7037 if ( ( this.clippedHorizontally && !clipWidth ) || ( this.clippedVertically && !clipHeight ) ) {
7038 OO.ui.Element.static.reconsiderScrollbars( this.$clippable[ 0 ] );
7039 }
7040
7041 this.clippedHorizontally = clipWidth;
7042 this.clippedVertically = clipHeight;
7043
7044 return this;
7045 };
7046
7047 /**
7048 * Element that will stick under a specified container, even when it is inserted elsewhere in the
7049 * document (for example, in a OO.ui.Window's $overlay).
7050 *
7051 * The elements's position is automatically calculated and maintained when window is resized or the
7052 * page is scrolled. If you reposition the container manually, you have to call #position to make
7053 * sure the element is still placed correctly.
7054 *
7055 * As positioning is only possible when both the element and the container are attached to the DOM
7056 * and visible, it's only done after you call #togglePositioning. You might want to do this inside
7057 * the #toggle method to display a floating popup, for example.
7058 *
7059 * @abstract
7060 * @class
7061 *
7062 * @constructor
7063 * @param {Object} [config] Configuration options
7064 * @cfg {jQuery} [$floatable] Node to position, assigned to #$floatable, omit to use #$element
7065 * @cfg {jQuery} [$floatableContainer] Node to position below
7066 */
7067 OO.ui.mixin.FloatableElement = function OoUiMixinFloatableElement( config ) {
7068 // Configuration initialization
7069 config = config || {};
7070
7071 // Properties
7072 this.$floatable = null;
7073 this.$floatableContainer = null;
7074 this.$floatableWindow = null;
7075 this.$floatableClosestScrollable = null;
7076 this.onFloatableScrollHandler = this.position.bind( this );
7077 this.onFloatableWindowResizeHandler = this.position.bind( this );
7078
7079 // Initialization
7080 this.setFloatableContainer( config.$floatableContainer );
7081 this.setFloatableElement( config.$floatable || this.$element );
7082 };
7083
7084 /* Methods */
7085
7086 /**
7087 * Set floatable element.
7088 *
7089 * If an element is already set, it will be cleaned up before setting up the new element.
7090 *
7091 * @param {jQuery} $floatable Element to make floatable
7092 */
7093 OO.ui.mixin.FloatableElement.prototype.setFloatableElement = function ( $floatable ) {
7094 if ( this.$floatable ) {
7095 this.$floatable.removeClass( 'oo-ui-floatableElement-floatable' );
7096 this.$floatable.css( { left: '', top: '' } );
7097 }
7098
7099 this.$floatable = $floatable.addClass( 'oo-ui-floatableElement-floatable' );
7100 this.position();
7101 };
7102
7103 /**
7104 * Set floatable container.
7105 *
7106 * The element will be always positioned under the specified container.
7107 *
7108 * @param {jQuery|null} $floatableContainer Container to keep visible, or null to unset
7109 */
7110 OO.ui.mixin.FloatableElement.prototype.setFloatableContainer = function ( $floatableContainer ) {
7111 this.$floatableContainer = $floatableContainer;
7112 if ( this.$floatable ) {
7113 this.position();
7114 }
7115 };
7116
7117 /**
7118 * Toggle positioning.
7119 *
7120 * Do not turn positioning on until after the element is attached to the DOM and visible.
7121 *
7122 * @param {boolean} [positioning] Enable positioning, omit to toggle
7123 * @chainable
7124 */
7125 OO.ui.mixin.FloatableElement.prototype.togglePositioning = function ( positioning ) {
7126 var closestScrollableOfContainer, closestScrollableOfFloatable;
7127
7128 positioning = positioning === undefined ? !this.positioning : !!positioning;
7129
7130 if ( this.positioning !== positioning ) {
7131 this.positioning = positioning;
7132
7133 closestScrollableOfContainer = OO.ui.Element.static.getClosestScrollableContainer( this.$floatableContainer[ 0 ] );
7134 closestScrollableOfFloatable = OO.ui.Element.static.getClosestScrollableContainer( this.$floatable[ 0 ] );
7135 if ( closestScrollableOfContainer !== closestScrollableOfFloatable ) {
7136 // If the scrollable is the root, we have to listen to scroll events
7137 // on the window because of browser inconsistencies (or do we? someone should verify this)
7138 if ( $( closestScrollableOfContainer ).is( 'html, body' ) ) {
7139 closestScrollableOfContainer = OO.ui.Element.static.getWindow( closestScrollableOfContainer );
7140 }
7141 }
7142
7143 if ( positioning ) {
7144 this.$floatableWindow = $( this.getElementWindow() );
7145 this.$floatableWindow.on( 'resize', this.onFloatableWindowResizeHandler );
7146
7147 if ( closestScrollableOfContainer !== closestScrollableOfFloatable ) {
7148 this.$floatableClosestScrollable = $( closestScrollableOfContainer );
7149 this.$floatableClosestScrollable.on( 'scroll', this.onFloatableScrollHandler );
7150 }
7151
7152 // Initial position after visible
7153 this.position();
7154 } else {
7155 if ( this.$floatableWindow ) {
7156 this.$floatableWindow.off( 'resize', this.onFloatableWindowResizeHandler );
7157 this.$floatableWindow = null;
7158 }
7159
7160 if ( this.$floatableClosestScrollable ) {
7161 this.$floatableClosestScrollable.off( 'scroll', this.onFloatableScrollHandler );
7162 this.$floatableClosestScrollable = null;
7163 }
7164
7165 this.$floatable.css( { left: '', top: '' } );
7166 }
7167 }
7168
7169 return this;
7170 };
7171
7172 /**
7173 * Position the floatable below its container.
7174 *
7175 * This should only be done when both of them are attached to the DOM and visible.
7176 *
7177 * @chainable
7178 */
7179 OO.ui.mixin.FloatableElement.prototype.position = function () {
7180 var pos;
7181
7182 if ( !this.positioning ) {
7183 return this;
7184 }
7185
7186 pos = OO.ui.Element.static.getRelativePosition( this.$floatableContainer, this.$floatable.offsetParent() );
7187
7188 // Position under container
7189 pos.top += this.$floatableContainer.height();
7190 this.$floatable.css( pos );
7191
7192 // We updated the position, so re-evaluate the clipping state.
7193 // (ClippableElement does not listen to 'scroll' events on $floatableContainer's parent, and so
7194 // will not notice the need to update itself.)
7195 // TODO: This is terrible, we shouldn't need to know about ClippableElement at all here. Why does
7196 // it not listen to the right events in the right places?
7197 if ( this.clip ) {
7198 this.clip();
7199 }
7200
7201 return this;
7202 };
7203
7204 /**
7205 * AccessKeyedElement is mixed into other classes to provide an `accesskey` attribute.
7206 * Accesskeys allow an user to go to a specific element by using
7207 * a shortcut combination of a browser specific keys + the key
7208 * set to the field.
7209 *
7210 * @example
7211 * // AccessKeyedElement provides an 'accesskey' attribute to the
7212 * // ButtonWidget class
7213 * var button = new OO.ui.ButtonWidget( {
7214 * label: 'Button with Accesskey',
7215 * accessKey: 'k'
7216 * } );
7217 * $( 'body' ).append( button.$element );
7218 *
7219 * @abstract
7220 * @class
7221 *
7222 * @constructor
7223 * @param {Object} [config] Configuration options
7224 * @cfg {jQuery} [$accessKeyed] The element to which the `accesskey` attribute is applied.
7225 * If this config is omitted, the accesskey functionality is applied to $element, the
7226 * element created by the class.
7227 * @cfg {string|Function} [accessKey] The key or a function that returns the key. If
7228 * this config is omitted, no accesskey will be added.
7229 */
7230 OO.ui.mixin.AccessKeyedElement = function OoUiMixinAccessKeyedElement( config ) {
7231 // Configuration initialization
7232 config = config || {};
7233
7234 // Properties
7235 this.$accessKeyed = null;
7236 this.accessKey = null;
7237
7238 // Initialization
7239 this.setAccessKey( config.accessKey || null );
7240 this.setAccessKeyedElement( config.$accessKeyed || this.$element );
7241 };
7242
7243 /* Setup */
7244
7245 OO.initClass( OO.ui.mixin.AccessKeyedElement );
7246
7247 /* Static Properties */
7248
7249 /**
7250 * The access key, a function that returns a key, or `null` for no accesskey.
7251 *
7252 * @static
7253 * @inheritable
7254 * @property {string|Function|null}
7255 */
7256 OO.ui.mixin.AccessKeyedElement.static.accessKey = null;
7257
7258 /* Methods */
7259
7260 /**
7261 * Set the accesskeyed element.
7262 *
7263 * This method is used to retarget a AccessKeyedElement mixin so that its functionality applies to the specified element.
7264 * If an element is already set, the mixin's effect on that element is removed before the new element is set up.
7265 *
7266 * @param {jQuery} $accessKeyed Element that should use the 'accesskeyes' functionality
7267 */
7268 OO.ui.mixin.AccessKeyedElement.prototype.setAccessKeyedElement = function ( $accessKeyed ) {
7269 if ( this.$accessKeyed ) {
7270 this.$accessKeyed.removeAttr( 'accesskey' );
7271 }
7272
7273 this.$accessKeyed = $accessKeyed;
7274 if ( this.accessKey ) {
7275 this.$accessKeyed.attr( 'accesskey', this.accessKey );
7276 }
7277 };
7278
7279 /**
7280 * Set accesskey.
7281 *
7282 * @param {string|Function|null} accesskey Key, a function that returns a key, or `null` for no accesskey
7283 * @chainable
7284 */
7285 OO.ui.mixin.AccessKeyedElement.prototype.setAccessKey = function ( accessKey ) {
7286 accessKey = typeof accessKey === 'string' ? OO.ui.resolveMsg( accessKey ) : null;
7287
7288 if ( this.accessKey !== accessKey ) {
7289 if ( this.$accessKeyed ) {
7290 if ( accessKey !== null ) {
7291 this.$accessKeyed.attr( 'accesskey', accessKey );
7292 } else {
7293 this.$accessKeyed.removeAttr( 'accesskey' );
7294 }
7295 }
7296 this.accessKey = accessKey;
7297 }
7298
7299 return this;
7300 };
7301
7302 /**
7303 * Get accesskey.
7304 *
7305 * @return {string} accessKey string
7306 */
7307 OO.ui.mixin.AccessKeyedElement.prototype.getAccessKey = function () {
7308 return this.accessKey;
7309 };
7310
7311 /**
7312 * Tools, together with {@link OO.ui.ToolGroup toolgroups}, constitute {@link OO.ui.Toolbar toolbars}.
7313 * Each tool is configured with a static name, title, and icon and is customized with the command to carry
7314 * out when the tool is selected. Tools must also be registered with a {@link OO.ui.ToolFactory tool factory},
7315 * which creates the tools on demand.
7316 *
7317 * Every Tool subclass must implement two methods:
7318 *
7319 * - {@link #onUpdateState}
7320 * - {@link #onSelect}
7321 *
7322 * Tools are added to toolgroups ({@link OO.ui.ListToolGroup ListToolGroup},
7323 * {@link OO.ui.BarToolGroup BarToolGroup}, or {@link OO.ui.MenuToolGroup MenuToolGroup}), which determine how
7324 * the tool is displayed in the toolbar. See {@link OO.ui.Toolbar toolbars} for an example.
7325 *
7326 * For more information, please see the [OOjs UI documentation on MediaWiki][1].
7327 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
7328 *
7329 * @abstract
7330 * @class
7331 * @extends OO.ui.Widget
7332 * @mixins OO.ui.mixin.IconElement
7333 * @mixins OO.ui.mixin.FlaggedElement
7334 * @mixins OO.ui.mixin.TabIndexedElement
7335 *
7336 * @constructor
7337 * @param {OO.ui.ToolGroup} toolGroup
7338 * @param {Object} [config] Configuration options
7339 * @cfg {string|Function} [title] Title text or a function that returns text. If this config is omitted, the value of
7340 * the {@link #static-title static title} property is used.
7341 *
7342 * The title is used in different ways depending on the type of toolgroup that contains the tool. The
7343 * 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
7344 * part of a {@link OO.ui.ListToolGroup list} or {@link OO.ui.MenuToolGroup menu} toolgroup.
7345 *
7346 * For bar toolgroups, a description of the accelerator key is appended to the title if an accelerator key
7347 * is associated with an action by the same name as the tool and accelerator functionality has been added to the application.
7348 * To add accelerator key functionality, you must subclass OO.ui.Toolbar and override the {@link OO.ui.Toolbar#getToolAccelerator getToolAccelerator} method.
7349 */
7350 OO.ui.Tool = function OoUiTool( toolGroup, config ) {
7351 // Allow passing positional parameters inside the config object
7352 if ( OO.isPlainObject( toolGroup ) && config === undefined ) {
7353 config = toolGroup;
7354 toolGroup = config.toolGroup;
7355 }
7356
7357 // Configuration initialization
7358 config = config || {};
7359
7360 // Parent constructor
7361 OO.ui.Tool.parent.call( this, config );
7362
7363 // Properties
7364 this.toolGroup = toolGroup;
7365 this.toolbar = this.toolGroup.getToolbar();
7366 this.active = false;
7367 this.$title = $( '<span>' );
7368 this.$accel = $( '<span>' );
7369 this.$link = $( '<a>' );
7370 this.title = null;
7371
7372 // Mixin constructors
7373 OO.ui.mixin.IconElement.call( this, config );
7374 OO.ui.mixin.FlaggedElement.call( this, config );
7375 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$link } ) );
7376
7377 // Events
7378 this.toolbar.connect( this, { updateState: 'onUpdateState' } );
7379
7380 // Initialization
7381 this.$title.addClass( 'oo-ui-tool-title' );
7382 this.$accel
7383 .addClass( 'oo-ui-tool-accel' )
7384 .prop( {
7385 // This may need to be changed if the key names are ever localized,
7386 // but for now they are essentially written in English
7387 dir: 'ltr',
7388 lang: 'en'
7389 } );
7390 this.$link
7391 .addClass( 'oo-ui-tool-link' )
7392 .append( this.$icon, this.$title, this.$accel )
7393 .attr( 'role', 'button' );
7394 this.$element
7395 .data( 'oo-ui-tool', this )
7396 .addClass(
7397 'oo-ui-tool ' + 'oo-ui-tool-name-' +
7398 this.constructor.static.name.replace( /^([^\/]+)\/([^\/]+).*$/, '$1-$2' )
7399 )
7400 .toggleClass( 'oo-ui-tool-with-label', this.constructor.static.displayBothIconAndLabel )
7401 .append( this.$link );
7402 this.setTitle( config.title || this.constructor.static.title );
7403 };
7404
7405 /* Setup */
7406
7407 OO.inheritClass( OO.ui.Tool, OO.ui.Widget );
7408 OO.mixinClass( OO.ui.Tool, OO.ui.mixin.IconElement );
7409 OO.mixinClass( OO.ui.Tool, OO.ui.mixin.FlaggedElement );
7410 OO.mixinClass( OO.ui.Tool, OO.ui.mixin.TabIndexedElement );
7411
7412 /* Static Properties */
7413
7414 /**
7415 * @static
7416 * @inheritdoc
7417 */
7418 OO.ui.Tool.static.tagName = 'span';
7419
7420 /**
7421 * Symbolic name of tool.
7422 *
7423 * The symbolic name is used internally to register the tool with a {@link OO.ui.ToolFactory ToolFactory}. It can
7424 * also be used when adding tools to toolgroups.
7425 *
7426 * @abstract
7427 * @static
7428 * @inheritable
7429 * @property {string}
7430 */
7431 OO.ui.Tool.static.name = '';
7432
7433 /**
7434 * Symbolic name of the group.
7435 *
7436 * The group name is used to associate tools with each other so that they can be selected later by
7437 * a {@link OO.ui.ToolGroup toolgroup}.
7438 *
7439 * @abstract
7440 * @static
7441 * @inheritable
7442 * @property {string}
7443 */
7444 OO.ui.Tool.static.group = '';
7445
7446 /**
7447 * 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.
7448 *
7449 * @abstract
7450 * @static
7451 * @inheritable
7452 * @property {string|Function}
7453 */
7454 OO.ui.Tool.static.title = '';
7455
7456 /**
7457 * Display both icon and label when the tool is used in a {@link OO.ui.BarToolGroup bar} toolgroup.
7458 * Normally only the icon is displayed, or only the label if no icon is given.
7459 *
7460 * @static
7461 * @inheritable
7462 * @property {boolean}
7463 */
7464 OO.ui.Tool.static.displayBothIconAndLabel = false;
7465
7466 /**
7467 * Add tool to catch-all groups automatically.
7468 *
7469 * A catch-all group, which contains all tools that do not currently belong to a toolgroup,
7470 * can be included in a toolgroup using the wildcard selector, an asterisk (*).
7471 *
7472 * @static
7473 * @inheritable
7474 * @property {boolean}
7475 */
7476 OO.ui.Tool.static.autoAddToCatchall = true;
7477
7478 /**
7479 * Add tool to named groups automatically.
7480 *
7481 * By default, tools that are configured with a static ‘group’ property are added
7482 * to that group and will be selected when the symbolic name of the group is specified (e.g., when
7483 * toolgroups include tools by group name).
7484 *
7485 * @static
7486 * @property {boolean}
7487 * @inheritable
7488 */
7489 OO.ui.Tool.static.autoAddToGroup = true;
7490
7491 /**
7492 * Check if this tool is compatible with given data.
7493 *
7494 * This is a stub that can be overriden to provide support for filtering tools based on an
7495 * arbitrary piece of information (e.g., where the cursor is in a document). The implementation
7496 * must also call this method so that the compatibility check can be performed.
7497 *
7498 * @static
7499 * @inheritable
7500 * @param {Mixed} data Data to check
7501 * @return {boolean} Tool can be used with data
7502 */
7503 OO.ui.Tool.static.isCompatibleWith = function () {
7504 return false;
7505 };
7506
7507 /* Methods */
7508
7509 /**
7510 * Handle the toolbar state being updated. This method is called when the
7511 * {@link OO.ui.Toolbar#event-updateState 'updateState' event} is emitted on the
7512 * {@link OO.ui.Toolbar Toolbar} that uses this tool, and should set the state of this tool
7513 * depending on application state (usually by calling #setDisabled to enable or disable the tool,
7514 * or #setActive to mark is as currently in-use or not).
7515 *
7516 * This is an abstract method that must be overridden in a concrete subclass.
7517 *
7518 * @method
7519 * @protected
7520 * @abstract
7521 */
7522 OO.ui.Tool.prototype.onUpdateState = null;
7523
7524 /**
7525 * Handle the tool being selected. This method is called when the user triggers this tool,
7526 * usually by clicking on its label/icon.
7527 *
7528 * This is an abstract method that must be overridden in a concrete subclass.
7529 *
7530 * @method
7531 * @protected
7532 * @abstract
7533 */
7534 OO.ui.Tool.prototype.onSelect = null;
7535
7536 /**
7537 * Check if the tool is active.
7538 *
7539 * Tools become active when their #onSelect or #onUpdateState handlers change them to appear pressed
7540 * with the #setActive method. Additional CSS is applied to the tool to reflect the active state.
7541 *
7542 * @return {boolean} Tool is active
7543 */
7544 OO.ui.Tool.prototype.isActive = function () {
7545 return this.active;
7546 };
7547
7548 /**
7549 * Make the tool appear active or inactive.
7550 *
7551 * This method should be called within #onSelect or #onUpdateState event handlers to make the tool
7552 * appear pressed or not.
7553 *
7554 * @param {boolean} state Make tool appear active
7555 */
7556 OO.ui.Tool.prototype.setActive = function ( state ) {
7557 this.active = !!state;
7558 if ( this.active ) {
7559 this.$element.addClass( 'oo-ui-tool-active' );
7560 } else {
7561 this.$element.removeClass( 'oo-ui-tool-active' );
7562 }
7563 };
7564
7565 /**
7566 * Set the tool #title.
7567 *
7568 * @param {string|Function} title Title text or a function that returns text
7569 * @chainable
7570 */
7571 OO.ui.Tool.prototype.setTitle = function ( title ) {
7572 this.title = OO.ui.resolveMsg( title );
7573 this.updateTitle();
7574 return this;
7575 };
7576
7577 /**
7578 * Get the tool #title.
7579 *
7580 * @return {string} Title text
7581 */
7582 OO.ui.Tool.prototype.getTitle = function () {
7583 return this.title;
7584 };
7585
7586 /**
7587 * Get the tool's symbolic name.
7588 *
7589 * @return {string} Symbolic name of tool
7590 */
7591 OO.ui.Tool.prototype.getName = function () {
7592 return this.constructor.static.name;
7593 };
7594
7595 /**
7596 * Update the title.
7597 */
7598 OO.ui.Tool.prototype.updateTitle = function () {
7599 var titleTooltips = this.toolGroup.constructor.static.titleTooltips,
7600 accelTooltips = this.toolGroup.constructor.static.accelTooltips,
7601 accel = this.toolbar.getToolAccelerator( this.constructor.static.name ),
7602 tooltipParts = [];
7603
7604 this.$title.text( this.title );
7605 this.$accel.text( accel );
7606
7607 if ( titleTooltips && typeof this.title === 'string' && this.title.length ) {
7608 tooltipParts.push( this.title );
7609 }
7610 if ( accelTooltips && typeof accel === 'string' && accel.length ) {
7611 tooltipParts.push( accel );
7612 }
7613 if ( tooltipParts.length ) {
7614 this.$link.attr( 'title', tooltipParts.join( ' ' ) );
7615 } else {
7616 this.$link.removeAttr( 'title' );
7617 }
7618 };
7619
7620 /**
7621 * Destroy tool.
7622 *
7623 * Destroying the tool removes all event handlers and the tool’s DOM elements.
7624 * Call this method whenever you are done using a tool.
7625 */
7626 OO.ui.Tool.prototype.destroy = function () {
7627 this.toolbar.disconnect( this );
7628 this.$element.remove();
7629 };
7630
7631 /**
7632 * Toolbars are complex interface components that permit users to easily access a variety
7633 * of {@link OO.ui.Tool tools} (e.g., formatting commands) and actions, which are additional commands that are
7634 * part of the toolbar, but not configured as tools.
7635 *
7636 * Individual tools are customized and then registered with a {@link OO.ui.ToolFactory tool factory}, which creates
7637 * the tools on demand. Each tool has a symbolic name (used when registering the tool), a title (e.g., ‘Insert
7638 * image’), and an icon.
7639 *
7640 * Individual tools are organized in {@link OO.ui.ToolGroup toolgroups}, which can be {@link OO.ui.MenuToolGroup menus}
7641 * of tools, {@link OO.ui.ListToolGroup lists} of tools, or a single {@link OO.ui.BarToolGroup bar} of tools.
7642 * The arrangement and order of the toolgroups is customized when the toolbar is set up. Tools can be presented in
7643 * any order, but each can only appear once in the toolbar.
7644 *
7645 * The toolbar can be synchronized with the state of the external "application", like a text
7646 * editor's editing area, marking tools as active/inactive (e.g. a 'bold' tool would be shown as
7647 * active when the text cursor was inside bolded text) or enabled/disabled (e.g. a table caption
7648 * tool would be disabled while the user is not editing a table). A state change is signalled by
7649 * emitting the {@link #event-updateState 'updateState' event}, which calls Tools'
7650 * {@link OO.ui.Tool#onUpdateState onUpdateState method}.
7651 *
7652 * The following is an example of a basic toolbar.
7653 *
7654 * @example
7655 * // Example of a toolbar
7656 * // Create the toolbar
7657 * var toolFactory = new OO.ui.ToolFactory();
7658 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
7659 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
7660 *
7661 * // We will be placing status text in this element when tools are used
7662 * var $area = $( '<p>' ).text( 'Toolbar example' );
7663 *
7664 * // Define the tools that we're going to place in our toolbar
7665 *
7666 * // Create a class inheriting from OO.ui.Tool
7667 * function SearchTool() {
7668 * SearchTool.parent.apply( this, arguments );
7669 * }
7670 * OO.inheritClass( SearchTool, OO.ui.Tool );
7671 * // Each tool must have a 'name' (used as an internal identifier, see later) and at least one
7672 * // of 'icon' and 'title' (displayed icon and text).
7673 * SearchTool.static.name = 'search';
7674 * SearchTool.static.icon = 'search';
7675 * SearchTool.static.title = 'Search...';
7676 * // Defines the action that will happen when this tool is selected (clicked).
7677 * SearchTool.prototype.onSelect = function () {
7678 * $area.text( 'Search tool clicked!' );
7679 * // Never display this tool as "active" (selected).
7680 * this.setActive( false );
7681 * };
7682 * SearchTool.prototype.onUpdateState = function () {};
7683 * // Make this tool available in our toolFactory and thus our toolbar
7684 * toolFactory.register( SearchTool );
7685 *
7686 * // Register two more tools, nothing interesting here
7687 * function SettingsTool() {
7688 * SettingsTool.parent.apply( this, arguments );
7689 * }
7690 * OO.inheritClass( SettingsTool, OO.ui.Tool );
7691 * SettingsTool.static.name = 'settings';
7692 * SettingsTool.static.icon = 'settings';
7693 * SettingsTool.static.title = 'Change settings';
7694 * SettingsTool.prototype.onSelect = function () {
7695 * $area.text( 'Settings tool clicked!' );
7696 * this.setActive( false );
7697 * };
7698 * SettingsTool.prototype.onUpdateState = function () {};
7699 * toolFactory.register( SettingsTool );
7700 *
7701 * // Register two more tools, nothing interesting here
7702 * function StuffTool() {
7703 * StuffTool.parent.apply( this, arguments );
7704 * }
7705 * OO.inheritClass( StuffTool, OO.ui.Tool );
7706 * StuffTool.static.name = 'stuff';
7707 * StuffTool.static.icon = 'ellipsis';
7708 * StuffTool.static.title = 'More stuff';
7709 * StuffTool.prototype.onSelect = function () {
7710 * $area.text( 'More stuff tool clicked!' );
7711 * this.setActive( false );
7712 * };
7713 * StuffTool.prototype.onUpdateState = function () {};
7714 * toolFactory.register( StuffTool );
7715 *
7716 * // This is a PopupTool. Rather than having a custom 'onSelect' action, it will display a
7717 * // little popup window (a PopupWidget).
7718 * function HelpTool( toolGroup, config ) {
7719 * OO.ui.PopupTool.call( this, toolGroup, $.extend( { popup: {
7720 * padded: true,
7721 * label: 'Help',
7722 * head: true
7723 * } }, config ) );
7724 * this.popup.$body.append( '<p>I am helpful!</p>' );
7725 * }
7726 * OO.inheritClass( HelpTool, OO.ui.PopupTool );
7727 * HelpTool.static.name = 'help';
7728 * HelpTool.static.icon = 'help';
7729 * HelpTool.static.title = 'Help';
7730 * toolFactory.register( HelpTool );
7731 *
7732 * // Finally define which tools and in what order appear in the toolbar. Each tool may only be
7733 * // used once (but not all defined tools must be used).
7734 * toolbar.setup( [
7735 * {
7736 * // 'bar' tool groups display tools' icons only, side-by-side.
7737 * type: 'bar',
7738 * include: [ 'search', 'help' ]
7739 * },
7740 * {
7741 * // 'list' tool groups display both the titles and icons, in a dropdown list.
7742 * type: 'list',
7743 * indicator: 'down',
7744 * label: 'More',
7745 * include: [ 'settings', 'stuff' ]
7746 * }
7747 * // Note how the tools themselves are toolgroup-agnostic - the same tool can be displayed
7748 * // either in a 'list' or a 'bar'. There is a 'menu' tool group too, not showcased here,
7749 * // since it's more complicated to use. (See the next example snippet on this page.)
7750 * ] );
7751 *
7752 * // Create some UI around the toolbar and place it in the document
7753 * var frame = new OO.ui.PanelLayout( {
7754 * expanded: false,
7755 * framed: true
7756 * } );
7757 * var contentFrame = new OO.ui.PanelLayout( {
7758 * expanded: false,
7759 * padded: true
7760 * } );
7761 * frame.$element.append(
7762 * toolbar.$element,
7763 * contentFrame.$element.append( $area )
7764 * );
7765 * $( 'body' ).append( frame.$element );
7766 *
7767 * // Here is where the toolbar is actually built. This must be done after inserting it into the
7768 * // document.
7769 * toolbar.initialize();
7770 * toolbar.emit( 'updateState' );
7771 *
7772 * The following example extends the previous one to illustrate 'menu' toolgroups and the usage of
7773 * {@link #event-updateState 'updateState' event}.
7774 *
7775 * @example
7776 * // Create the toolbar
7777 * var toolFactory = new OO.ui.ToolFactory();
7778 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
7779 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
7780 *
7781 * // We will be placing status text in this element when tools are used
7782 * var $area = $( '<p>' ).text( 'Toolbar example' );
7783 *
7784 * // Define the tools that we're going to place in our toolbar
7785 *
7786 * // Create a class inheriting from OO.ui.Tool
7787 * function SearchTool() {
7788 * SearchTool.parent.apply( this, arguments );
7789 * }
7790 * OO.inheritClass( SearchTool, OO.ui.Tool );
7791 * // Each tool must have a 'name' (used as an internal identifier, see later) and at least one
7792 * // of 'icon' and 'title' (displayed icon and text).
7793 * SearchTool.static.name = 'search';
7794 * SearchTool.static.icon = 'search';
7795 * SearchTool.static.title = 'Search...';
7796 * // Defines the action that will happen when this tool is selected (clicked).
7797 * SearchTool.prototype.onSelect = function () {
7798 * $area.text( 'Search tool clicked!' );
7799 * // Never display this tool as "active" (selected).
7800 * this.setActive( false );
7801 * };
7802 * SearchTool.prototype.onUpdateState = function () {};
7803 * // Make this tool available in our toolFactory and thus our toolbar
7804 * toolFactory.register( SearchTool );
7805 *
7806 * // Register two more tools, nothing interesting here
7807 * function SettingsTool() {
7808 * SettingsTool.parent.apply( this, arguments );
7809 * this.reallyActive = false;
7810 * }
7811 * OO.inheritClass( SettingsTool, OO.ui.Tool );
7812 * SettingsTool.static.name = 'settings';
7813 * SettingsTool.static.icon = 'settings';
7814 * SettingsTool.static.title = 'Change settings';
7815 * SettingsTool.prototype.onSelect = function () {
7816 * $area.text( 'Settings tool clicked!' );
7817 * // Toggle the active state on each click
7818 * this.reallyActive = !this.reallyActive;
7819 * this.setActive( this.reallyActive );
7820 * // To update the menu label
7821 * this.toolbar.emit( 'updateState' );
7822 * };
7823 * SettingsTool.prototype.onUpdateState = function () {};
7824 * toolFactory.register( SettingsTool );
7825 *
7826 * // Register two more tools, nothing interesting here
7827 * function StuffTool() {
7828 * StuffTool.parent.apply( this, arguments );
7829 * this.reallyActive = false;
7830 * }
7831 * OO.inheritClass( StuffTool, OO.ui.Tool );
7832 * StuffTool.static.name = 'stuff';
7833 * StuffTool.static.icon = 'ellipsis';
7834 * StuffTool.static.title = 'More stuff';
7835 * StuffTool.prototype.onSelect = function () {
7836 * $area.text( 'More stuff tool clicked!' );
7837 * // Toggle the active state on each click
7838 * this.reallyActive = !this.reallyActive;
7839 * this.setActive( this.reallyActive );
7840 * // To update the menu label
7841 * this.toolbar.emit( 'updateState' );
7842 * };
7843 * StuffTool.prototype.onUpdateState = function () {};
7844 * toolFactory.register( StuffTool );
7845 *
7846 * // This is a PopupTool. Rather than having a custom 'onSelect' action, it will display a
7847 * // little popup window (a PopupWidget). 'onUpdateState' is also already implemented.
7848 * function HelpTool( toolGroup, config ) {
7849 * OO.ui.PopupTool.call( this, toolGroup, $.extend( { popup: {
7850 * padded: true,
7851 * label: 'Help',
7852 * head: true
7853 * } }, config ) );
7854 * this.popup.$body.append( '<p>I am helpful!</p>' );
7855 * }
7856 * OO.inheritClass( HelpTool, OO.ui.PopupTool );
7857 * HelpTool.static.name = 'help';
7858 * HelpTool.static.icon = 'help';
7859 * HelpTool.static.title = 'Help';
7860 * toolFactory.register( HelpTool );
7861 *
7862 * // Finally define which tools and in what order appear in the toolbar. Each tool may only be
7863 * // used once (but not all defined tools must be used).
7864 * toolbar.setup( [
7865 * {
7866 * // 'bar' tool groups display tools' icons only, side-by-side.
7867 * type: 'bar',
7868 * include: [ 'search', 'help' ]
7869 * },
7870 * {
7871 * // 'menu' tool groups display both the titles and icons, in a dropdown menu.
7872 * // Menu label indicates which items are selected.
7873 * type: 'menu',
7874 * indicator: 'down',
7875 * include: [ 'settings', 'stuff' ]
7876 * }
7877 * ] );
7878 *
7879 * // Create some UI around the toolbar and place it in the document
7880 * var frame = new OO.ui.PanelLayout( {
7881 * expanded: false,
7882 * framed: true
7883 * } );
7884 * var contentFrame = new OO.ui.PanelLayout( {
7885 * expanded: false,
7886 * padded: true
7887 * } );
7888 * frame.$element.append(
7889 * toolbar.$element,
7890 * contentFrame.$element.append( $area )
7891 * );
7892 * $( 'body' ).append( frame.$element );
7893 *
7894 * // Here is where the toolbar is actually built. This must be done after inserting it into the
7895 * // document.
7896 * toolbar.initialize();
7897 * toolbar.emit( 'updateState' );
7898 *
7899 * @class
7900 * @extends OO.ui.Element
7901 * @mixins OO.EventEmitter
7902 * @mixins OO.ui.mixin.GroupElement
7903 *
7904 * @constructor
7905 * @param {OO.ui.ToolFactory} toolFactory Factory for creating tools
7906 * @param {OO.ui.ToolGroupFactory} toolGroupFactory Factory for creating toolgroups
7907 * @param {Object} [config] Configuration options
7908 * @cfg {boolean} [actions] Add an actions section to the toolbar. Actions are commands that are included
7909 * in the toolbar, but are not configured as tools. By default, actions are displayed on the right side of
7910 * the toolbar.
7911 * @cfg {boolean} [shadow] Add a shadow below the toolbar.
7912 */
7913 OO.ui.Toolbar = function OoUiToolbar( toolFactory, toolGroupFactory, config ) {
7914 // Allow passing positional parameters inside the config object
7915 if ( OO.isPlainObject( toolFactory ) && config === undefined ) {
7916 config = toolFactory;
7917 toolFactory = config.toolFactory;
7918 toolGroupFactory = config.toolGroupFactory;
7919 }
7920
7921 // Configuration initialization
7922 config = config || {};
7923
7924 // Parent constructor
7925 OO.ui.Toolbar.parent.call( this, config );
7926
7927 // Mixin constructors
7928 OO.EventEmitter.call( this );
7929 OO.ui.mixin.GroupElement.call( this, config );
7930
7931 // Properties
7932 this.toolFactory = toolFactory;
7933 this.toolGroupFactory = toolGroupFactory;
7934 this.groups = [];
7935 this.tools = {};
7936 this.$bar = $( '<div>' );
7937 this.$actions = $( '<div>' );
7938 this.initialized = false;
7939 this.onWindowResizeHandler = this.onWindowResize.bind( this );
7940
7941 // Events
7942 this.$element
7943 .add( this.$bar ).add( this.$group ).add( this.$actions )
7944 .on( 'mousedown keydown', this.onPointerDown.bind( this ) );
7945
7946 // Initialization
7947 this.$group.addClass( 'oo-ui-toolbar-tools' );
7948 if ( config.actions ) {
7949 this.$bar.append( this.$actions.addClass( 'oo-ui-toolbar-actions' ) );
7950 }
7951 this.$bar
7952 .addClass( 'oo-ui-toolbar-bar' )
7953 .append( this.$group, '<div style="clear:both"></div>' );
7954 if ( config.shadow ) {
7955 this.$bar.append( '<div class="oo-ui-toolbar-shadow"></div>' );
7956 }
7957 this.$element.addClass( 'oo-ui-toolbar' ).append( this.$bar );
7958 };
7959
7960 /* Setup */
7961
7962 OO.inheritClass( OO.ui.Toolbar, OO.ui.Element );
7963 OO.mixinClass( OO.ui.Toolbar, OO.EventEmitter );
7964 OO.mixinClass( OO.ui.Toolbar, OO.ui.mixin.GroupElement );
7965
7966 /* Events */
7967
7968 /**
7969 * @event updateState
7970 *
7971 * An 'updateState' event must be emitted on the Toolbar (by calling `toolbar.emit( 'updateState' )`)
7972 * every time the state of the application using the toolbar changes, and an update to the state of
7973 * tools is required.
7974 *
7975 * @param {Mixed...} data Application-defined parameters
7976 */
7977
7978 /* Methods */
7979
7980 /**
7981 * Get the tool factory.
7982 *
7983 * @return {OO.ui.ToolFactory} Tool factory
7984 */
7985 OO.ui.Toolbar.prototype.getToolFactory = function () {
7986 return this.toolFactory;
7987 };
7988
7989 /**
7990 * Get the toolgroup factory.
7991 *
7992 * @return {OO.Factory} Toolgroup factory
7993 */
7994 OO.ui.Toolbar.prototype.getToolGroupFactory = function () {
7995 return this.toolGroupFactory;
7996 };
7997
7998 /**
7999 * Handles mouse down events.
8000 *
8001 * @private
8002 * @param {jQuery.Event} e Mouse down event
8003 */
8004 OO.ui.Toolbar.prototype.onPointerDown = function ( e ) {
8005 var $closestWidgetToEvent = $( e.target ).closest( '.oo-ui-widget' ),
8006 $closestWidgetToToolbar = this.$element.closest( '.oo-ui-widget' );
8007 if ( !$closestWidgetToEvent.length || $closestWidgetToEvent[ 0 ] === $closestWidgetToToolbar[ 0 ] ) {
8008 return false;
8009 }
8010 };
8011
8012 /**
8013 * Handle window resize event.
8014 *
8015 * @private
8016 * @param {jQuery.Event} e Window resize event
8017 */
8018 OO.ui.Toolbar.prototype.onWindowResize = function () {
8019 this.$element.toggleClass(
8020 'oo-ui-toolbar-narrow',
8021 this.$bar.width() <= this.narrowThreshold
8022 );
8023 };
8024
8025 /**
8026 * Sets up handles and preloads required information for the toolbar to work.
8027 * This must be called after it is attached to a visible document and before doing anything else.
8028 */
8029 OO.ui.Toolbar.prototype.initialize = function () {
8030 if ( !this.initialized ) {
8031 this.initialized = true;
8032 this.narrowThreshold = this.$group.width() + this.$actions.width();
8033 $( this.getElementWindow() ).on( 'resize', this.onWindowResizeHandler );
8034 this.onWindowResize();
8035 }
8036 };
8037
8038 /**
8039 * Set up the toolbar.
8040 *
8041 * The toolbar is set up with a list of toolgroup configurations that specify the type of
8042 * toolgroup ({@link OO.ui.BarToolGroup bar}, {@link OO.ui.MenuToolGroup menu}, or {@link OO.ui.ListToolGroup list})
8043 * to add and which tools to include, exclude, promote, or demote within that toolgroup. Please
8044 * see {@link OO.ui.ToolGroup toolgroups} for more information about including tools in toolgroups.
8045 *
8046 * @param {Object.<string,Array>} groups List of toolgroup configurations
8047 * @param {Array|string} [groups.include] Tools to include in the toolgroup
8048 * @param {Array|string} [groups.exclude] Tools to exclude from the toolgroup
8049 * @param {Array|string} [groups.promote] Tools to promote to the beginning of the toolgroup
8050 * @param {Array|string} [groups.demote] Tools to demote to the end of the toolgroup
8051 */
8052 OO.ui.Toolbar.prototype.setup = function ( groups ) {
8053 var i, len, type, group,
8054 items = [],
8055 defaultType = 'bar';
8056
8057 // Cleanup previous groups
8058 this.reset();
8059
8060 // Build out new groups
8061 for ( i = 0, len = groups.length; i < len; i++ ) {
8062 group = groups[ i ];
8063 if ( group.include === '*' ) {
8064 // Apply defaults to catch-all groups
8065 if ( group.type === undefined ) {
8066 group.type = 'list';
8067 }
8068 if ( group.label === undefined ) {
8069 group.label = OO.ui.msg( 'ooui-toolbar-more' );
8070 }
8071 }
8072 // Check type has been registered
8073 type = this.getToolGroupFactory().lookup( group.type ) ? group.type : defaultType;
8074 items.push(
8075 this.getToolGroupFactory().create( type, this, group )
8076 );
8077 }
8078 this.addItems( items );
8079 };
8080
8081 /**
8082 * Remove all tools and toolgroups from the toolbar.
8083 */
8084 OO.ui.Toolbar.prototype.reset = function () {
8085 var i, len;
8086
8087 this.groups = [];
8088 this.tools = {};
8089 for ( i = 0, len = this.items.length; i < len; i++ ) {
8090 this.items[ i ].destroy();
8091 }
8092 this.clearItems();
8093 };
8094
8095 /**
8096 * Destroy the toolbar.
8097 *
8098 * Destroying the toolbar removes all event handlers and DOM elements that constitute the toolbar. Call
8099 * this method whenever you are done using a toolbar.
8100 */
8101 OO.ui.Toolbar.prototype.destroy = function () {
8102 $( this.getElementWindow() ).off( 'resize', this.onWindowResizeHandler );
8103 this.reset();
8104 this.$element.remove();
8105 };
8106
8107 /**
8108 * Check if the tool is available.
8109 *
8110 * Available tools are ones that have not yet been added to the toolbar.
8111 *
8112 * @param {string} name Symbolic name of tool
8113 * @return {boolean} Tool is available
8114 */
8115 OO.ui.Toolbar.prototype.isToolAvailable = function ( name ) {
8116 return !this.tools[ name ];
8117 };
8118
8119 /**
8120 * Prevent tool from being used again.
8121 *
8122 * @param {OO.ui.Tool} tool Tool to reserve
8123 */
8124 OO.ui.Toolbar.prototype.reserveTool = function ( tool ) {
8125 this.tools[ tool.getName() ] = tool;
8126 };
8127
8128 /**
8129 * Allow tool to be used again.
8130 *
8131 * @param {OO.ui.Tool} tool Tool to release
8132 */
8133 OO.ui.Toolbar.prototype.releaseTool = function ( tool ) {
8134 delete this.tools[ tool.getName() ];
8135 };
8136
8137 /**
8138 * Get accelerator label for tool.
8139 *
8140 * The OOjs UI library does not contain an accelerator system, but this is the hook for one. To
8141 * use an accelerator system, subclass the toolbar and override this method, which is meant to return a label
8142 * that describes the accelerator keys for the tool passed (by symbolic name) to the method.
8143 *
8144 * @param {string} name Symbolic name of tool
8145 * @return {string|undefined} Tool accelerator label if available
8146 */
8147 OO.ui.Toolbar.prototype.getToolAccelerator = function () {
8148 return undefined;
8149 };
8150
8151 /**
8152 * ToolGroups are collections of {@link OO.ui.Tool tools} that are used in a {@link OO.ui.Toolbar toolbar}.
8153 * The type of toolgroup ({@link OO.ui.ListToolGroup list}, {@link OO.ui.BarToolGroup bar}, or {@link OO.ui.MenuToolGroup menu})
8154 * to which a tool belongs determines how the tool is arranged and displayed in the toolbar. Toolgroups
8155 * themselves are created on demand with a {@link OO.ui.ToolGroupFactory toolgroup factory}.
8156 *
8157 * Toolgroups can contain individual tools, groups of tools, or all available tools, as specified
8158 * using the `include` config option. See OO.ui.ToolFactory#extract on documentation of the format.
8159 * The options `exclude`, `promote`, and `demote` support the same formats.
8160 *
8161 * See {@link OO.ui.Toolbar toolbars} for a full example. For more information about toolbars in general,
8162 * please see the [OOjs UI documentation on MediaWiki][1].
8163 *
8164 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
8165 *
8166 * @abstract
8167 * @class
8168 * @extends OO.ui.Widget
8169 * @mixins OO.ui.mixin.GroupElement
8170 *
8171 * @constructor
8172 * @param {OO.ui.Toolbar} toolbar
8173 * @param {Object} [config] Configuration options
8174 * @cfg {Array|string} [include] List of tools to include in the toolgroup, see above.
8175 * @cfg {Array|string} [exclude] List of tools to exclude from the toolgroup, see above.
8176 * @cfg {Array|string} [promote] List of tools to promote to the beginning of the toolgroup, see above.
8177 * @cfg {Array|string} [demote] List of tools to demote to the end of the toolgroup, see above.
8178 * This setting is particularly useful when tools have been added to the toolgroup
8179 * en masse (e.g., via the catch-all selector).
8180 */
8181 OO.ui.ToolGroup = function OoUiToolGroup( toolbar, config ) {
8182 // Allow passing positional parameters inside the config object
8183 if ( OO.isPlainObject( toolbar ) && config === undefined ) {
8184 config = toolbar;
8185 toolbar = config.toolbar;
8186 }
8187
8188 // Configuration initialization
8189 config = config || {};
8190
8191 // Parent constructor
8192 OO.ui.ToolGroup.parent.call( this, config );
8193
8194 // Mixin constructors
8195 OO.ui.mixin.GroupElement.call( this, config );
8196
8197 // Properties
8198 this.toolbar = toolbar;
8199 this.tools = {};
8200 this.pressed = null;
8201 this.autoDisabled = false;
8202 this.include = config.include || [];
8203 this.exclude = config.exclude || [];
8204 this.promote = config.promote || [];
8205 this.demote = config.demote || [];
8206 this.onCapturedMouseKeyUpHandler = this.onCapturedMouseKeyUp.bind( this );
8207
8208 // Events
8209 this.$element.on( {
8210 mousedown: this.onMouseKeyDown.bind( this ),
8211 mouseup: this.onMouseKeyUp.bind( this ),
8212 keydown: this.onMouseKeyDown.bind( this ),
8213 keyup: this.onMouseKeyUp.bind( this ),
8214 focus: this.onMouseOverFocus.bind( this ),
8215 blur: this.onMouseOutBlur.bind( this ),
8216 mouseover: this.onMouseOverFocus.bind( this ),
8217 mouseout: this.onMouseOutBlur.bind( this )
8218 } );
8219 this.toolbar.getToolFactory().connect( this, { register: 'onToolFactoryRegister' } );
8220 this.aggregate( { disable: 'itemDisable' } );
8221 this.connect( this, { itemDisable: 'updateDisabled' } );
8222
8223 // Initialization
8224 this.$group.addClass( 'oo-ui-toolGroup-tools' );
8225 this.$element
8226 .addClass( 'oo-ui-toolGroup' )
8227 .append( this.$group );
8228 this.populate();
8229 };
8230
8231 /* Setup */
8232
8233 OO.inheritClass( OO.ui.ToolGroup, OO.ui.Widget );
8234 OO.mixinClass( OO.ui.ToolGroup, OO.ui.mixin.GroupElement );
8235
8236 /* Events */
8237
8238 /**
8239 * @event update
8240 */
8241
8242 /* Static Properties */
8243
8244 /**
8245 * Show labels in tooltips.
8246 *
8247 * @static
8248 * @inheritable
8249 * @property {boolean}
8250 */
8251 OO.ui.ToolGroup.static.titleTooltips = false;
8252
8253 /**
8254 * Show acceleration labels in tooltips.
8255 *
8256 * Note: The OOjs UI library does not include an accelerator system, but does contain
8257 * a hook for one. To use an accelerator system, subclass the {@link OO.ui.Toolbar toolbar} and
8258 * override the {@link OO.ui.Toolbar#getToolAccelerator getToolAccelerator} method, which is
8259 * meant to return a label that describes the accelerator keys for a given tool (e.g., 'Ctrl + M').
8260 *
8261 * @static
8262 * @inheritable
8263 * @property {boolean}
8264 */
8265 OO.ui.ToolGroup.static.accelTooltips = false;
8266
8267 /**
8268 * Automatically disable the toolgroup when all tools are disabled
8269 *
8270 * @static
8271 * @inheritable
8272 * @property {boolean}
8273 */
8274 OO.ui.ToolGroup.static.autoDisable = true;
8275
8276 /* Methods */
8277
8278 /**
8279 * @inheritdoc
8280 */
8281 OO.ui.ToolGroup.prototype.isDisabled = function () {
8282 return this.autoDisabled || OO.ui.ToolGroup.parent.prototype.isDisabled.apply( this, arguments );
8283 };
8284
8285 /**
8286 * @inheritdoc
8287 */
8288 OO.ui.ToolGroup.prototype.updateDisabled = function () {
8289 var i, item, allDisabled = true;
8290
8291 if ( this.constructor.static.autoDisable ) {
8292 for ( i = this.items.length - 1; i >= 0; i-- ) {
8293 item = this.items[ i ];
8294 if ( !item.isDisabled() ) {
8295 allDisabled = false;
8296 break;
8297 }
8298 }
8299 this.autoDisabled = allDisabled;
8300 }
8301 OO.ui.ToolGroup.parent.prototype.updateDisabled.apply( this, arguments );
8302 };
8303
8304 /**
8305 * Handle mouse down and key down events.
8306 *
8307 * @protected
8308 * @param {jQuery.Event} e Mouse down or key down event
8309 */
8310 OO.ui.ToolGroup.prototype.onMouseKeyDown = function ( e ) {
8311 if (
8312 !this.isDisabled() &&
8313 ( e.which === 1 || e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
8314 ) {
8315 this.pressed = this.getTargetTool( e );
8316 if ( this.pressed ) {
8317 this.pressed.setActive( true );
8318 OO.ui.addCaptureEventListener( this.getElementDocument(), 'mouseup', this.onCapturedMouseKeyUpHandler );
8319 OO.ui.addCaptureEventListener( this.getElementDocument(), 'keyup', this.onCapturedMouseKeyUpHandler );
8320 }
8321 return false;
8322 }
8323 };
8324
8325 /**
8326 * Handle captured mouse up and key up events.
8327 *
8328 * @protected
8329 * @param {Event} e Mouse up or key up event
8330 */
8331 OO.ui.ToolGroup.prototype.onCapturedMouseKeyUp = function ( e ) {
8332 OO.ui.removeCaptureEventListener( this.getElementDocument(), 'mouseup', this.onCapturedMouseKeyUpHandler );
8333 OO.ui.removeCaptureEventListener( this.getElementDocument(), 'keyup', this.onCapturedMouseKeyUpHandler );
8334 // onMouseKeyUp may be called a second time, depending on where the mouse is when the button is
8335 // released, but since `this.pressed` will no longer be true, the second call will be ignored.
8336 this.onMouseKeyUp( e );
8337 };
8338
8339 /**
8340 * Handle mouse up and key up events.
8341 *
8342 * @protected
8343 * @param {jQuery.Event} e Mouse up or key up event
8344 */
8345 OO.ui.ToolGroup.prototype.onMouseKeyUp = function ( e ) {
8346 var tool = this.getTargetTool( e );
8347
8348 if (
8349 !this.isDisabled() && this.pressed && this.pressed === tool &&
8350 ( e.which === 1 || e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
8351 ) {
8352 this.pressed.onSelect();
8353 this.pressed = null;
8354 return false;
8355 }
8356
8357 this.pressed = null;
8358 };
8359
8360 /**
8361 * Handle mouse over and focus events.
8362 *
8363 * @protected
8364 * @param {jQuery.Event} e Mouse over or focus event
8365 */
8366 OO.ui.ToolGroup.prototype.onMouseOverFocus = function ( e ) {
8367 var tool = this.getTargetTool( e );
8368
8369 if ( this.pressed && this.pressed === tool ) {
8370 this.pressed.setActive( true );
8371 }
8372 };
8373
8374 /**
8375 * Handle mouse out and blur events.
8376 *
8377 * @protected
8378 * @param {jQuery.Event} e Mouse out or blur event
8379 */
8380 OO.ui.ToolGroup.prototype.onMouseOutBlur = function ( e ) {
8381 var tool = this.getTargetTool( e );
8382
8383 if ( this.pressed && this.pressed === tool ) {
8384 this.pressed.setActive( false );
8385 }
8386 };
8387
8388 /**
8389 * Get the closest tool to a jQuery.Event.
8390 *
8391 * Only tool links are considered, which prevents other elements in the tool such as popups from
8392 * triggering tool group interactions.
8393 *
8394 * @private
8395 * @param {jQuery.Event} e
8396 * @return {OO.ui.Tool|null} Tool, `null` if none was found
8397 */
8398 OO.ui.ToolGroup.prototype.getTargetTool = function ( e ) {
8399 var tool,
8400 $item = $( e.target ).closest( '.oo-ui-tool-link' );
8401
8402 if ( $item.length ) {
8403 tool = $item.parent().data( 'oo-ui-tool' );
8404 }
8405
8406 return tool && !tool.isDisabled() ? tool : null;
8407 };
8408
8409 /**
8410 * Handle tool registry register events.
8411 *
8412 * If a tool is registered after the group is created, we must repopulate the list to account for:
8413 *
8414 * - a tool being added that may be included
8415 * - a tool already included being overridden
8416 *
8417 * @protected
8418 * @param {string} name Symbolic name of tool
8419 */
8420 OO.ui.ToolGroup.prototype.onToolFactoryRegister = function () {
8421 this.populate();
8422 };
8423
8424 /**
8425 * Get the toolbar that contains the toolgroup.
8426 *
8427 * @return {OO.ui.Toolbar} Toolbar that contains the toolgroup
8428 */
8429 OO.ui.ToolGroup.prototype.getToolbar = function () {
8430 return this.toolbar;
8431 };
8432
8433 /**
8434 * Add and remove tools based on configuration.
8435 */
8436 OO.ui.ToolGroup.prototype.populate = function () {
8437 var i, len, name, tool,
8438 toolFactory = this.toolbar.getToolFactory(),
8439 names = {},
8440 add = [],
8441 remove = [],
8442 list = this.toolbar.getToolFactory().getTools(
8443 this.include, this.exclude, this.promote, this.demote
8444 );
8445
8446 // Build a list of needed tools
8447 for ( i = 0, len = list.length; i < len; i++ ) {
8448 name = list[ i ];
8449 if (
8450 // Tool exists
8451 toolFactory.lookup( name ) &&
8452 // Tool is available or is already in this group
8453 ( this.toolbar.isToolAvailable( name ) || this.tools[ name ] )
8454 ) {
8455 // Hack to prevent infinite recursion via ToolGroupTool. We need to reserve the tool before
8456 // creating it, but we can't call reserveTool() yet because we haven't created the tool.
8457 this.toolbar.tools[ name ] = true;
8458 tool = this.tools[ name ];
8459 if ( !tool ) {
8460 // Auto-initialize tools on first use
8461 this.tools[ name ] = tool = toolFactory.create( name, this );
8462 tool.updateTitle();
8463 }
8464 this.toolbar.reserveTool( tool );
8465 add.push( tool );
8466 names[ name ] = true;
8467 }
8468 }
8469 // Remove tools that are no longer needed
8470 for ( name in this.tools ) {
8471 if ( !names[ name ] ) {
8472 this.tools[ name ].destroy();
8473 this.toolbar.releaseTool( this.tools[ name ] );
8474 remove.push( this.tools[ name ] );
8475 delete this.tools[ name ];
8476 }
8477 }
8478 if ( remove.length ) {
8479 this.removeItems( remove );
8480 }
8481 // Update emptiness state
8482 if ( add.length ) {
8483 this.$element.removeClass( 'oo-ui-toolGroup-empty' );
8484 } else {
8485 this.$element.addClass( 'oo-ui-toolGroup-empty' );
8486 }
8487 // Re-add tools (moving existing ones to new locations)
8488 this.addItems( add );
8489 // Disabled state may depend on items
8490 this.updateDisabled();
8491 };
8492
8493 /**
8494 * Destroy toolgroup.
8495 */
8496 OO.ui.ToolGroup.prototype.destroy = function () {
8497 var name;
8498
8499 this.clearItems();
8500 this.toolbar.getToolFactory().disconnect( this );
8501 for ( name in this.tools ) {
8502 this.toolbar.releaseTool( this.tools[ name ] );
8503 this.tools[ name ].disconnect( this ).destroy();
8504 delete this.tools[ name ];
8505 }
8506 this.$element.remove();
8507 };
8508
8509 /**
8510 * MessageDialogs display a confirmation or alert message. By default, the rendered dialog box
8511 * consists of a header that contains the dialog title, a body with the message, and a footer that
8512 * contains any {@link OO.ui.ActionWidget action widgets}. The MessageDialog class is the only type
8513 * of {@link OO.ui.Dialog dialog} that is usually instantiated directly.
8514 *
8515 * There are two basic types of message dialogs, confirmation and alert:
8516 *
8517 * - **confirmation**: the dialog title describes what a progressive action will do and the message provides
8518 * more details about the consequences.
8519 * - **alert**: the dialog title describes which event occurred and the message provides more information
8520 * about why the event occurred.
8521 *
8522 * The MessageDialog class specifies two actions: ‘accept’, the primary
8523 * action (e.g., ‘ok’) and ‘reject,’ the safe action (e.g., ‘cancel’). Both will close the window,
8524 * passing along the selected action.
8525 *
8526 * For more information and examples, please see the [OOjs UI documentation on MediaWiki][1].
8527 *
8528 * @example
8529 * // Example: Creating and opening a message dialog window.
8530 * var messageDialog = new OO.ui.MessageDialog();
8531 *
8532 * // Create and append a window manager.
8533 * var windowManager = new OO.ui.WindowManager();
8534 * $( 'body' ).append( windowManager.$element );
8535 * windowManager.addWindows( [ messageDialog ] );
8536 * // Open the window.
8537 * windowManager.openWindow( messageDialog, {
8538 * title: 'Basic message dialog',
8539 * message: 'This is the message'
8540 * } );
8541 *
8542 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Message_Dialogs
8543 *
8544 * @class
8545 * @extends OO.ui.Dialog
8546 *
8547 * @constructor
8548 * @param {Object} [config] Configuration options
8549 */
8550 OO.ui.MessageDialog = function OoUiMessageDialog( config ) {
8551 // Parent constructor
8552 OO.ui.MessageDialog.parent.call( this, config );
8553
8554 // Properties
8555 this.verticalActionLayout = null;
8556
8557 // Initialization
8558 this.$element.addClass( 'oo-ui-messageDialog' );
8559 };
8560
8561 /* Setup */
8562
8563 OO.inheritClass( OO.ui.MessageDialog, OO.ui.Dialog );
8564
8565 /* Static Properties */
8566
8567 OO.ui.MessageDialog.static.name = 'message';
8568
8569 OO.ui.MessageDialog.static.size = 'small';
8570
8571 OO.ui.MessageDialog.static.verbose = false;
8572
8573 /**
8574 * Dialog title.
8575 *
8576 * The title of a confirmation dialog describes what a progressive action will do. The
8577 * title of an alert dialog describes which event occurred.
8578 *
8579 * @static
8580 * @inheritable
8581 * @property {jQuery|string|Function|null}
8582 */
8583 OO.ui.MessageDialog.static.title = null;
8584
8585 /**
8586 * The message displayed in the dialog body.
8587 *
8588 * A confirmation message describes the consequences of a progressive action. An alert
8589 * message describes why an event occurred.
8590 *
8591 * @static
8592 * @inheritable
8593 * @property {jQuery|string|Function|null}
8594 */
8595 OO.ui.MessageDialog.static.message = null;
8596
8597 // Note that OO.ui.alert() and OO.ui.confirm() rely on these.
8598 OO.ui.MessageDialog.static.actions = [
8599 { action: 'accept', label: OO.ui.deferMsg( 'ooui-dialog-message-accept' ), flags: 'primary' },
8600 { action: 'reject', label: OO.ui.deferMsg( 'ooui-dialog-message-reject' ), flags: 'safe' }
8601 ];
8602
8603 /* Methods */
8604
8605 /**
8606 * @inheritdoc
8607 */
8608 OO.ui.MessageDialog.prototype.setManager = function ( manager ) {
8609 OO.ui.MessageDialog.parent.prototype.setManager.call( this, manager );
8610
8611 // Events
8612 this.manager.connect( this, {
8613 resize: 'onResize'
8614 } );
8615
8616 return this;
8617 };
8618
8619 /**
8620 * @inheritdoc
8621 */
8622 OO.ui.MessageDialog.prototype.onActionResize = function ( action ) {
8623 this.fitActions();
8624 return OO.ui.MessageDialog.parent.prototype.onActionResize.call( this, action );
8625 };
8626
8627 /**
8628 * Handle window resized events.
8629 *
8630 * @private
8631 */
8632 OO.ui.MessageDialog.prototype.onResize = function () {
8633 var dialog = this;
8634 dialog.fitActions();
8635 // Wait for CSS transition to finish and do it again :(
8636 setTimeout( function () {
8637 dialog.fitActions();
8638 }, 300 );
8639 };
8640
8641 /**
8642 * Toggle action layout between vertical and horizontal.
8643 *
8644 * @private
8645 * @param {boolean} [value] Layout actions vertically, omit to toggle
8646 * @chainable
8647 */
8648 OO.ui.MessageDialog.prototype.toggleVerticalActionLayout = function ( value ) {
8649 value = value === undefined ? !this.verticalActionLayout : !!value;
8650
8651 if ( value !== this.verticalActionLayout ) {
8652 this.verticalActionLayout = value;
8653 this.$actions
8654 .toggleClass( 'oo-ui-messageDialog-actions-vertical', value )
8655 .toggleClass( 'oo-ui-messageDialog-actions-horizontal', !value );
8656 }
8657
8658 return this;
8659 };
8660
8661 /**
8662 * @inheritdoc
8663 */
8664 OO.ui.MessageDialog.prototype.getActionProcess = function ( action ) {
8665 if ( action ) {
8666 return new OO.ui.Process( function () {
8667 this.close( { action: action } );
8668 }, this );
8669 }
8670 return OO.ui.MessageDialog.parent.prototype.getActionProcess.call( this, action );
8671 };
8672
8673 /**
8674 * @inheritdoc
8675 *
8676 * @param {Object} [data] Dialog opening data
8677 * @param {jQuery|string|Function|null} [data.title] Description of the action being confirmed
8678 * @param {jQuery|string|Function|null} [data.message] Description of the action's consequence
8679 * @param {boolean} [data.verbose] Message is verbose and should be styled as a long message
8680 * @param {Object[]} [data.actions] List of OO.ui.ActionOptionWidget configuration options for each
8681 * action item
8682 */
8683 OO.ui.MessageDialog.prototype.getSetupProcess = function ( data ) {
8684 data = data || {};
8685
8686 // Parent method
8687 return OO.ui.MessageDialog.parent.prototype.getSetupProcess.call( this, data )
8688 .next( function () {
8689 this.title.setLabel(
8690 data.title !== undefined ? data.title : this.constructor.static.title
8691 );
8692 this.message.setLabel(
8693 data.message !== undefined ? data.message : this.constructor.static.message
8694 );
8695 this.message.$element.toggleClass(
8696 'oo-ui-messageDialog-message-verbose',
8697 data.verbose !== undefined ? data.verbose : this.constructor.static.verbose
8698 );
8699 }, this );
8700 };
8701
8702 /**
8703 * @inheritdoc
8704 */
8705 OO.ui.MessageDialog.prototype.getReadyProcess = function ( data ) {
8706 data = data || {};
8707
8708 // Parent method
8709 return OO.ui.MessageDialog.parent.prototype.getReadyProcess.call( this, data )
8710 .next( function () {
8711 // Focus the primary action button
8712 var actions = this.actions.get();
8713 actions = actions.filter( function ( action ) {
8714 return action.getFlags().indexOf( 'primary' ) > -1;
8715 } );
8716 if ( actions.length > 0 ) {
8717 actions[ 0 ].$button.focus();
8718 }
8719 }, this );
8720 };
8721
8722 /**
8723 * @inheritdoc
8724 */
8725 OO.ui.MessageDialog.prototype.getBodyHeight = function () {
8726 var bodyHeight, oldOverflow,
8727 $scrollable = this.container.$element;
8728
8729 oldOverflow = $scrollable[ 0 ].style.overflow;
8730 $scrollable[ 0 ].style.overflow = 'hidden';
8731
8732 OO.ui.Element.static.reconsiderScrollbars( $scrollable[ 0 ] );
8733
8734 bodyHeight = this.text.$element.outerHeight( true );
8735 $scrollable[ 0 ].style.overflow = oldOverflow;
8736
8737 return bodyHeight;
8738 };
8739
8740 /**
8741 * @inheritdoc
8742 */
8743 OO.ui.MessageDialog.prototype.setDimensions = function ( dim ) {
8744 var $scrollable = this.container.$element;
8745 OO.ui.MessageDialog.parent.prototype.setDimensions.call( this, dim );
8746
8747 // Twiddle the overflow property, otherwise an unnecessary scrollbar will be produced.
8748 // Need to do it after transition completes (250ms), add 50ms just in case.
8749 setTimeout( function () {
8750 var oldOverflow = $scrollable[ 0 ].style.overflow;
8751 $scrollable[ 0 ].style.overflow = 'hidden';
8752
8753 OO.ui.Element.static.reconsiderScrollbars( $scrollable[ 0 ] );
8754
8755 $scrollable[ 0 ].style.overflow = oldOverflow;
8756 }, 300 );
8757
8758 return this;
8759 };
8760
8761 /**
8762 * @inheritdoc
8763 */
8764 OO.ui.MessageDialog.prototype.initialize = function () {
8765 // Parent method
8766 OO.ui.MessageDialog.parent.prototype.initialize.call( this );
8767
8768 // Properties
8769 this.$actions = $( '<div>' );
8770 this.container = new OO.ui.PanelLayout( {
8771 scrollable: true, classes: [ 'oo-ui-messageDialog-container' ]
8772 } );
8773 this.text = new OO.ui.PanelLayout( {
8774 padded: true, expanded: false, classes: [ 'oo-ui-messageDialog-text' ]
8775 } );
8776 this.message = new OO.ui.LabelWidget( {
8777 classes: [ 'oo-ui-messageDialog-message' ]
8778 } );
8779
8780 // Initialization
8781 this.title.$element.addClass( 'oo-ui-messageDialog-title' );
8782 this.$content.addClass( 'oo-ui-messageDialog-content' );
8783 this.container.$element.append( this.text.$element );
8784 this.text.$element.append( this.title.$element, this.message.$element );
8785 this.$body.append( this.container.$element );
8786 this.$actions.addClass( 'oo-ui-messageDialog-actions' );
8787 this.$foot.append( this.$actions );
8788 };
8789
8790 /**
8791 * @inheritdoc
8792 */
8793 OO.ui.MessageDialog.prototype.attachActions = function () {
8794 var i, len, other, special, others;
8795
8796 // Parent method
8797 OO.ui.MessageDialog.parent.prototype.attachActions.call( this );
8798
8799 special = this.actions.getSpecial();
8800 others = this.actions.getOthers();
8801
8802 if ( special.safe ) {
8803 this.$actions.append( special.safe.$element );
8804 special.safe.toggleFramed( false );
8805 }
8806 if ( others.length ) {
8807 for ( i = 0, len = others.length; i < len; i++ ) {
8808 other = others[ i ];
8809 this.$actions.append( other.$element );
8810 other.toggleFramed( false );
8811 }
8812 }
8813 if ( special.primary ) {
8814 this.$actions.append( special.primary.$element );
8815 special.primary.toggleFramed( false );
8816 }
8817
8818 if ( !this.isOpening() ) {
8819 // If the dialog is currently opening, this will be called automatically soon.
8820 // This also calls #fitActions.
8821 this.updateSize();
8822 }
8823 };
8824
8825 /**
8826 * Fit action actions into columns or rows.
8827 *
8828 * Columns will be used if all labels can fit without overflow, otherwise rows will be used.
8829 *
8830 * @private
8831 */
8832 OO.ui.MessageDialog.prototype.fitActions = function () {
8833 var i, len, action,
8834 previous = this.verticalActionLayout,
8835 actions = this.actions.get();
8836
8837 // Detect clipping
8838 this.toggleVerticalActionLayout( false );
8839 for ( i = 0, len = actions.length; i < len; i++ ) {
8840 action = actions[ i ];
8841 if ( action.$element.innerWidth() < action.$label.outerWidth( true ) ) {
8842 this.toggleVerticalActionLayout( true );
8843 break;
8844 }
8845 }
8846
8847 // Move the body out of the way of the foot
8848 this.$body.css( 'bottom', this.$foot.outerHeight( true ) );
8849
8850 if ( this.verticalActionLayout !== previous ) {
8851 // We changed the layout, window height might need to be updated.
8852 this.updateSize();
8853 }
8854 };
8855
8856 /**
8857 * ProcessDialog windows encapsulate a {@link OO.ui.Process process} and all of the code necessary
8858 * to complete it. If the process terminates with an error, a customizable {@link OO.ui.Error error
8859 * interface} alerts users to the trouble, permitting the user to dismiss the error and try again when
8860 * relevant. The ProcessDialog class is always extended and customized with the actions and content
8861 * required for each process.
8862 *
8863 * The process dialog box consists of a header that visually represents the ‘working’ state of long
8864 * processes with an animation. The header contains the dialog title as well as
8865 * two {@link OO.ui.ActionWidget action widgets}: a ‘safe’ action on the left (e.g., ‘Cancel’) and
8866 * a ‘primary’ action on the right (e.g., ‘Done’).
8867 *
8868 * Like other windows, the process dialog is managed by a {@link OO.ui.WindowManager window manager}.
8869 * Please see the [OOjs UI documentation on MediaWiki][1] for more information and examples.
8870 *
8871 * @example
8872 * // Example: Creating and opening a process dialog window.
8873 * function MyProcessDialog( config ) {
8874 * MyProcessDialog.parent.call( this, config );
8875 * }
8876 * OO.inheritClass( MyProcessDialog, OO.ui.ProcessDialog );
8877 *
8878 * MyProcessDialog.static.title = 'Process dialog';
8879 * MyProcessDialog.static.actions = [
8880 * { action: 'save', label: 'Done', flags: 'primary' },
8881 * { label: 'Cancel', flags: 'safe' }
8882 * ];
8883 *
8884 * MyProcessDialog.prototype.initialize = function () {
8885 * MyProcessDialog.parent.prototype.initialize.apply( this, arguments );
8886 * this.content = new OO.ui.PanelLayout( { padded: true, expanded: false } );
8887 * 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>' );
8888 * this.$body.append( this.content.$element );
8889 * };
8890 * MyProcessDialog.prototype.getActionProcess = function ( action ) {
8891 * var dialog = this;
8892 * if ( action ) {
8893 * return new OO.ui.Process( function () {
8894 * dialog.close( { action: action } );
8895 * } );
8896 * }
8897 * return MyProcessDialog.parent.prototype.getActionProcess.call( this, action );
8898 * };
8899 *
8900 * var windowManager = new OO.ui.WindowManager();
8901 * $( 'body' ).append( windowManager.$element );
8902 *
8903 * var dialog = new MyProcessDialog();
8904 * windowManager.addWindows( [ dialog ] );
8905 * windowManager.openWindow( dialog );
8906 *
8907 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs
8908 *
8909 * @abstract
8910 * @class
8911 * @extends OO.ui.Dialog
8912 *
8913 * @constructor
8914 * @param {Object} [config] Configuration options
8915 */
8916 OO.ui.ProcessDialog = function OoUiProcessDialog( config ) {
8917 // Parent constructor
8918 OO.ui.ProcessDialog.parent.call( this, config );
8919
8920 // Properties
8921 this.fitOnOpen = false;
8922
8923 // Initialization
8924 this.$element.addClass( 'oo-ui-processDialog' );
8925 };
8926
8927 /* Setup */
8928
8929 OO.inheritClass( OO.ui.ProcessDialog, OO.ui.Dialog );
8930
8931 /* Methods */
8932
8933 /**
8934 * Handle dismiss button click events.
8935 *
8936 * Hides errors.
8937 *
8938 * @private
8939 */
8940 OO.ui.ProcessDialog.prototype.onDismissErrorButtonClick = function () {
8941 this.hideErrors();
8942 };
8943
8944 /**
8945 * Handle retry button click events.
8946 *
8947 * Hides errors and then tries again.
8948 *
8949 * @private
8950 */
8951 OO.ui.ProcessDialog.prototype.onRetryButtonClick = function () {
8952 this.hideErrors();
8953 this.executeAction( this.currentAction );
8954 };
8955
8956 /**
8957 * @inheritdoc
8958 */
8959 OO.ui.ProcessDialog.prototype.onActionResize = function ( action ) {
8960 if ( this.actions.isSpecial( action ) ) {
8961 this.fitLabel();
8962 }
8963 return OO.ui.ProcessDialog.parent.prototype.onActionResize.call( this, action );
8964 };
8965
8966 /**
8967 * @inheritdoc
8968 */
8969 OO.ui.ProcessDialog.prototype.initialize = function () {
8970 // Parent method
8971 OO.ui.ProcessDialog.parent.prototype.initialize.call( this );
8972
8973 // Properties
8974 this.$navigation = $( '<div>' );
8975 this.$location = $( '<div>' );
8976 this.$safeActions = $( '<div>' );
8977 this.$primaryActions = $( '<div>' );
8978 this.$otherActions = $( '<div>' );
8979 this.dismissButton = new OO.ui.ButtonWidget( {
8980 label: OO.ui.msg( 'ooui-dialog-process-dismiss' )
8981 } );
8982 this.retryButton = new OO.ui.ButtonWidget();
8983 this.$errors = $( '<div>' );
8984 this.$errorsTitle = $( '<div>' );
8985
8986 // Events
8987 this.dismissButton.connect( this, { click: 'onDismissErrorButtonClick' } );
8988 this.retryButton.connect( this, { click: 'onRetryButtonClick' } );
8989
8990 // Initialization
8991 this.title.$element.addClass( 'oo-ui-processDialog-title' );
8992 this.$location
8993 .append( this.title.$element )
8994 .addClass( 'oo-ui-processDialog-location' );
8995 this.$safeActions.addClass( 'oo-ui-processDialog-actions-safe' );
8996 this.$primaryActions.addClass( 'oo-ui-processDialog-actions-primary' );
8997 this.$otherActions.addClass( 'oo-ui-processDialog-actions-other' );
8998 this.$errorsTitle
8999 .addClass( 'oo-ui-processDialog-errors-title' )
9000 .text( OO.ui.msg( 'ooui-dialog-process-error' ) );
9001 this.$errors
9002 .addClass( 'oo-ui-processDialog-errors oo-ui-element-hidden' )
9003 .append( this.$errorsTitle, this.dismissButton.$element, this.retryButton.$element );
9004 this.$content
9005 .addClass( 'oo-ui-processDialog-content' )
9006 .append( this.$errors );
9007 this.$navigation
9008 .addClass( 'oo-ui-processDialog-navigation' )
9009 .append( this.$safeActions, this.$location, this.$primaryActions );
9010 this.$head.append( this.$navigation );
9011 this.$foot.append( this.$otherActions );
9012 };
9013
9014 /**
9015 * @inheritdoc
9016 */
9017 OO.ui.ProcessDialog.prototype.getActionWidgets = function ( actions ) {
9018 var i, len, widgets = [];
9019 for ( i = 0, len = actions.length; i < len; i++ ) {
9020 widgets.push(
9021 new OO.ui.ActionWidget( $.extend( { framed: true }, actions[ i ] ) )
9022 );
9023 }
9024 return widgets;
9025 };
9026
9027 /**
9028 * @inheritdoc
9029 */
9030 OO.ui.ProcessDialog.prototype.attachActions = function () {
9031 var i, len, other, special, others;
9032
9033 // Parent method
9034 OO.ui.ProcessDialog.parent.prototype.attachActions.call( this );
9035
9036 special = this.actions.getSpecial();
9037 others = this.actions.getOthers();
9038 if ( special.primary ) {
9039 this.$primaryActions.append( special.primary.$element );
9040 }
9041 for ( i = 0, len = others.length; i < len; i++ ) {
9042 other = others[ i ];
9043 this.$otherActions.append( other.$element );
9044 }
9045 if ( special.safe ) {
9046 this.$safeActions.append( special.safe.$element );
9047 }
9048
9049 this.fitLabel();
9050 this.$body.css( 'bottom', this.$foot.outerHeight( true ) );
9051 };
9052
9053 /**
9054 * @inheritdoc
9055 */
9056 OO.ui.ProcessDialog.prototype.executeAction = function ( action ) {
9057 var process = this;
9058 return OO.ui.ProcessDialog.parent.prototype.executeAction.call( this, action )
9059 .fail( function ( errors ) {
9060 process.showErrors( errors || [] );
9061 } );
9062 };
9063
9064 /**
9065 * @inheritdoc
9066 */
9067 OO.ui.ProcessDialog.prototype.setDimensions = function () {
9068 // Parent method
9069 OO.ui.ProcessDialog.parent.prototype.setDimensions.apply( this, arguments );
9070
9071 this.fitLabel();
9072 };
9073
9074 /**
9075 * Fit label between actions.
9076 *
9077 * @private
9078 * @chainable
9079 */
9080 OO.ui.ProcessDialog.prototype.fitLabel = function () {
9081 var safeWidth, primaryWidth, biggerWidth, labelWidth, navigationWidth, leftWidth, rightWidth,
9082 size = this.getSizeProperties();
9083
9084 if ( typeof size.width !== 'number' ) {
9085 if ( this.isOpened() ) {
9086 navigationWidth = this.$head.width() - 20;
9087 } else if ( this.isOpening() ) {
9088 if ( !this.fitOnOpen ) {
9089 // Size is relative and the dialog isn't open yet, so wait.
9090 this.manager.opening.done( this.fitLabel.bind( this ) );
9091 this.fitOnOpen = true;
9092 }
9093 return;
9094 } else {
9095 return;
9096 }
9097 } else {
9098 navigationWidth = size.width - 20;
9099 }
9100
9101 safeWidth = this.$safeActions.is( ':visible' ) ? this.$safeActions.width() : 0;
9102 primaryWidth = this.$primaryActions.is( ':visible' ) ? this.$primaryActions.width() : 0;
9103 biggerWidth = Math.max( safeWidth, primaryWidth );
9104
9105 labelWidth = this.title.$element.width();
9106
9107 if ( 2 * biggerWidth + labelWidth < navigationWidth ) {
9108 // We have enough space to center the label
9109 leftWidth = rightWidth = biggerWidth;
9110 } else {
9111 // Let's hope we at least have enough space not to overlap, because we can't wrap the label…
9112 if ( this.getDir() === 'ltr' ) {
9113 leftWidth = safeWidth;
9114 rightWidth = primaryWidth;
9115 } else {
9116 leftWidth = primaryWidth;
9117 rightWidth = safeWidth;
9118 }
9119 }
9120
9121 this.$location.css( { paddingLeft: leftWidth, paddingRight: rightWidth } );
9122
9123 return this;
9124 };
9125
9126 /**
9127 * Handle errors that occurred during accept or reject processes.
9128 *
9129 * @private
9130 * @param {OO.ui.Error[]|OO.ui.Error} errors Errors to be handled
9131 */
9132 OO.ui.ProcessDialog.prototype.showErrors = function ( errors ) {
9133 var i, len, $item, actions,
9134 items = [],
9135 abilities = {},
9136 recoverable = true,
9137 warning = false;
9138
9139 if ( errors instanceof OO.ui.Error ) {
9140 errors = [ errors ];
9141 }
9142
9143 for ( i = 0, len = errors.length; i < len; i++ ) {
9144 if ( !errors[ i ].isRecoverable() ) {
9145 recoverable = false;
9146 }
9147 if ( errors[ i ].isWarning() ) {
9148 warning = true;
9149 }
9150 $item = $( '<div>' )
9151 .addClass( 'oo-ui-processDialog-error' )
9152 .append( errors[ i ].getMessage() );
9153 items.push( $item[ 0 ] );
9154 }
9155 this.$errorItems = $( items );
9156 if ( recoverable ) {
9157 abilities[ this.currentAction ] = true;
9158 // Copy the flags from the first matching action
9159 actions = this.actions.get( { actions: this.currentAction } );
9160 if ( actions.length ) {
9161 this.retryButton.clearFlags().setFlags( actions[ 0 ].getFlags() );
9162 }
9163 } else {
9164 abilities[ this.currentAction ] = false;
9165 this.actions.setAbilities( abilities );
9166 }
9167 if ( warning ) {
9168 this.retryButton.setLabel( OO.ui.msg( 'ooui-dialog-process-continue' ) );
9169 } else {
9170 this.retryButton.setLabel( OO.ui.msg( 'ooui-dialog-process-retry' ) );
9171 }
9172 this.retryButton.toggle( recoverable );
9173 this.$errorsTitle.after( this.$errorItems );
9174 this.$errors.removeClass( 'oo-ui-element-hidden' ).scrollTop( 0 );
9175 };
9176
9177 /**
9178 * Hide errors.
9179 *
9180 * @private
9181 */
9182 OO.ui.ProcessDialog.prototype.hideErrors = function () {
9183 this.$errors.addClass( 'oo-ui-element-hidden' );
9184 if ( this.$errorItems ) {
9185 this.$errorItems.remove();
9186 this.$errorItems = null;
9187 }
9188 };
9189
9190 /**
9191 * @inheritdoc
9192 */
9193 OO.ui.ProcessDialog.prototype.getTeardownProcess = function ( data ) {
9194 // Parent method
9195 return OO.ui.ProcessDialog.parent.prototype.getTeardownProcess.call( this, data )
9196 .first( function () {
9197 // Make sure to hide errors
9198 this.hideErrors();
9199 this.fitOnOpen = false;
9200 }, this );
9201 };
9202
9203 /**
9204 * FieldLayouts are used with OO.ui.FieldsetLayout. Each FieldLayout requires a field-widget,
9205 * which is a widget that is specified by reference before any optional configuration settings.
9206 *
9207 * Field layouts can be configured with help text and/or labels. Labels are aligned in one of four ways:
9208 *
9209 * - **left**: The label is placed before the field-widget and aligned with the left margin.
9210 * A left-alignment is used for forms with many fields.
9211 * - **right**: The label is placed before the field-widget and aligned to the right margin.
9212 * A right-alignment is used for long but familiar forms which users tab through,
9213 * verifying the current field with a quick glance at the label.
9214 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
9215 * that users fill out from top to bottom.
9216 * - **inline**: The label is placed after the field-widget and aligned to the left.
9217 * An inline-alignment is best used with checkboxes or radio buttons.
9218 *
9219 * Help text is accessed via a help icon that appears in the upper right corner of the rendered field layout.
9220 * Please see the [OOjs UI documentation on MediaWiki] [1] for examples and more information.
9221 *
9222 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Fields_and_Fieldsets
9223 * @class
9224 * @extends OO.ui.Layout
9225 * @mixins OO.ui.mixin.LabelElement
9226 * @mixins OO.ui.mixin.TitledElement
9227 *
9228 * @constructor
9229 * @param {OO.ui.Widget} fieldWidget Field widget
9230 * @param {Object} [config] Configuration options
9231 * @cfg {string} [align='left'] Alignment of the label: 'left', 'right', 'top' or 'inline'
9232 * @cfg {Array} [errors] Error messages about the widget, which will be displayed below the widget.
9233 * The array may contain strings or OO.ui.HtmlSnippet instances.
9234 * @cfg {Array} [notices] Notices about the widget, which will be displayed below the widget.
9235 * The array may contain strings or OO.ui.HtmlSnippet instances.
9236 * @cfg {string|OO.ui.HtmlSnippet} [help] Help text. When help text is specified, a "help" icon will appear
9237 * in the upper-right corner of the rendered field; clicking it will display the text in a popup.
9238 * For important messages, you are advised to use `notices`, as they are always shown.
9239 *
9240 * @throws {Error} An error is thrown if no widget is specified
9241 */
9242 OO.ui.FieldLayout = function OoUiFieldLayout( fieldWidget, config ) {
9243 var hasInputWidget, div;
9244
9245 // Allow passing positional parameters inside the config object
9246 if ( OO.isPlainObject( fieldWidget ) && config === undefined ) {
9247 config = fieldWidget;
9248 fieldWidget = config.fieldWidget;
9249 }
9250
9251 // Make sure we have required constructor arguments
9252 if ( fieldWidget === undefined ) {
9253 throw new Error( 'Widget not found' );
9254 }
9255
9256 hasInputWidget = fieldWidget.constructor.static.supportsSimpleLabel;
9257
9258 // Configuration initialization
9259 config = $.extend( { align: 'left' }, config );
9260
9261 // Parent constructor
9262 OO.ui.FieldLayout.parent.call( this, config );
9263
9264 // Mixin constructors
9265 OO.ui.mixin.LabelElement.call( this, config );
9266 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$label } ) );
9267
9268 // Properties
9269 this.fieldWidget = fieldWidget;
9270 this.errors = [];
9271 this.notices = [];
9272 this.$field = $( '<div>' );
9273 this.$messages = $( '<ul>' );
9274 this.$body = $( '<' + ( hasInputWidget ? 'label' : 'div' ) + '>' );
9275 this.align = null;
9276 if ( config.help ) {
9277 this.popupButtonWidget = new OO.ui.PopupButtonWidget( {
9278 classes: [ 'oo-ui-fieldLayout-help' ],
9279 framed: false,
9280 icon: 'info'
9281 } );
9282
9283 div = $( '<div>' );
9284 if ( config.help instanceof OO.ui.HtmlSnippet ) {
9285 div.html( config.help.toString() );
9286 } else {
9287 div.text( config.help );
9288 }
9289 this.popupButtonWidget.getPopup().$body.append(
9290 div.addClass( 'oo-ui-fieldLayout-help-content' )
9291 );
9292 this.$help = this.popupButtonWidget.$element;
9293 } else {
9294 this.$help = $( [] );
9295 }
9296
9297 // Events
9298 if ( hasInputWidget ) {
9299 this.$label.on( 'click', this.onLabelClick.bind( this ) );
9300 }
9301 this.fieldWidget.connect( this, { disable: 'onFieldDisable' } );
9302
9303 // Initialization
9304 this.$element
9305 .addClass( 'oo-ui-fieldLayout' )
9306 .append( this.$help, this.$body );
9307 this.$body.addClass( 'oo-ui-fieldLayout-body' );
9308 this.$messages.addClass( 'oo-ui-fieldLayout-messages' );
9309 this.$field
9310 .addClass( 'oo-ui-fieldLayout-field' )
9311 .toggleClass( 'oo-ui-fieldLayout-disable', this.fieldWidget.isDisabled() )
9312 .append( this.fieldWidget.$element );
9313
9314 this.setErrors( config.errors || [] );
9315 this.setNotices( config.notices || [] );
9316 this.setAlignment( config.align );
9317 };
9318
9319 /* Setup */
9320
9321 OO.inheritClass( OO.ui.FieldLayout, OO.ui.Layout );
9322 OO.mixinClass( OO.ui.FieldLayout, OO.ui.mixin.LabelElement );
9323 OO.mixinClass( OO.ui.FieldLayout, OO.ui.mixin.TitledElement );
9324
9325 /* Methods */
9326
9327 /**
9328 * Handle field disable events.
9329 *
9330 * @private
9331 * @param {boolean} value Field is disabled
9332 */
9333 OO.ui.FieldLayout.prototype.onFieldDisable = function ( value ) {
9334 this.$element.toggleClass( 'oo-ui-fieldLayout-disabled', value );
9335 };
9336
9337 /**
9338 * Handle label mouse click events.
9339 *
9340 * @private
9341 * @param {jQuery.Event} e Mouse click event
9342 */
9343 OO.ui.FieldLayout.prototype.onLabelClick = function () {
9344 this.fieldWidget.simulateLabelClick();
9345 return false;
9346 };
9347
9348 /**
9349 * Get the widget contained by the field.
9350 *
9351 * @return {OO.ui.Widget} Field widget
9352 */
9353 OO.ui.FieldLayout.prototype.getField = function () {
9354 return this.fieldWidget;
9355 };
9356
9357 /**
9358 * @protected
9359 * @param {string} kind 'error' or 'notice'
9360 * @param {string|OO.ui.HtmlSnippet} text
9361 * @return {jQuery}
9362 */
9363 OO.ui.FieldLayout.prototype.makeMessage = function ( kind, text ) {
9364 var $listItem, $icon, message;
9365 $listItem = $( '<li>' );
9366 if ( kind === 'error' ) {
9367 $icon = new OO.ui.IconWidget( { icon: 'alert', flags: [ 'warning' ] } ).$element;
9368 } else if ( kind === 'notice' ) {
9369 $icon = new OO.ui.IconWidget( { icon: 'info' } ).$element;
9370 } else {
9371 $icon = '';
9372 }
9373 message = new OO.ui.LabelWidget( { label: text } );
9374 $listItem
9375 .append( $icon, message.$element )
9376 .addClass( 'oo-ui-fieldLayout-messages-' + kind );
9377 return $listItem;
9378 };
9379
9380 /**
9381 * Set the field alignment mode.
9382 *
9383 * @private
9384 * @param {string} value Alignment mode, either 'left', 'right', 'top' or 'inline'
9385 * @chainable
9386 */
9387 OO.ui.FieldLayout.prototype.setAlignment = function ( value ) {
9388 if ( value !== this.align ) {
9389 // Default to 'left'
9390 if ( [ 'left', 'right', 'top', 'inline' ].indexOf( value ) === -1 ) {
9391 value = 'left';
9392 }
9393 // Reorder elements
9394 if ( value === 'inline' ) {
9395 this.$body.append( this.$field, this.$label );
9396 } else {
9397 this.$body.append( this.$label, this.$field );
9398 }
9399 // Set classes. The following classes can be used here:
9400 // * oo-ui-fieldLayout-align-left
9401 // * oo-ui-fieldLayout-align-right
9402 // * oo-ui-fieldLayout-align-top
9403 // * oo-ui-fieldLayout-align-inline
9404 if ( this.align ) {
9405 this.$element.removeClass( 'oo-ui-fieldLayout-align-' + this.align );
9406 }
9407 this.$element.addClass( 'oo-ui-fieldLayout-align-' + value );
9408 this.align = value;
9409 }
9410
9411 return this;
9412 };
9413
9414 /**
9415 * Set the list of error messages.
9416 *
9417 * @param {Array} errors Error messages about the widget, which will be displayed below the widget.
9418 * The array may contain strings or OO.ui.HtmlSnippet instances.
9419 * @chainable
9420 */
9421 OO.ui.FieldLayout.prototype.setErrors = function ( errors ) {
9422 this.errors = errors.slice();
9423 this.updateMessages();
9424 return this;
9425 };
9426
9427 /**
9428 * Set the list of notice messages.
9429 *
9430 * @param {Array} notices Notices about the widget, which will be displayed below the widget.
9431 * The array may contain strings or OO.ui.HtmlSnippet instances.
9432 * @chainable
9433 */
9434 OO.ui.FieldLayout.prototype.setNotices = function ( notices ) {
9435 this.notices = notices.slice();
9436 this.updateMessages();
9437 return this;
9438 };
9439
9440 /**
9441 * Update the rendering of error and notice messages.
9442 *
9443 * @private
9444 */
9445 OO.ui.FieldLayout.prototype.updateMessages = function () {
9446 var i;
9447 this.$messages.empty();
9448
9449 if ( this.errors.length || this.notices.length ) {
9450 this.$body.after( this.$messages );
9451 } else {
9452 this.$messages.remove();
9453 return;
9454 }
9455
9456 for ( i = 0; i < this.notices.length; i++ ) {
9457 this.$messages.append( this.makeMessage( 'notice', this.notices[ i ] ) );
9458 }
9459 for ( i = 0; i < this.errors.length; i++ ) {
9460 this.$messages.append( this.makeMessage( 'error', this.errors[ i ] ) );
9461 }
9462 };
9463
9464 /**
9465 * ActionFieldLayouts are used with OO.ui.FieldsetLayout. The layout consists of a field-widget, a button,
9466 * and an optional label and/or help text. The field-widget (e.g., a {@link OO.ui.TextInputWidget TextInputWidget}),
9467 * is required and is specified before any optional configuration settings.
9468 *
9469 * Labels can be aligned in one of four ways:
9470 *
9471 * - **left**: The label is placed before the field-widget and aligned with the left margin.
9472 * A left-alignment is used for forms with many fields.
9473 * - **right**: The label is placed before the field-widget and aligned to the right margin.
9474 * A right-alignment is used for long but familiar forms which users tab through,
9475 * verifying the current field with a quick glance at the label.
9476 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
9477 * that users fill out from top to bottom.
9478 * - **inline**: The label is placed after the field-widget and aligned to the left.
9479 * An inline-alignment is best used with checkboxes or radio buttons.
9480 *
9481 * Help text is accessed via a help icon that appears in the upper right corner of the rendered field layout when help
9482 * text is specified.
9483 *
9484 * @example
9485 * // Example of an ActionFieldLayout
9486 * var actionFieldLayout = new OO.ui.ActionFieldLayout(
9487 * new OO.ui.TextInputWidget( {
9488 * placeholder: 'Field widget'
9489 * } ),
9490 * new OO.ui.ButtonWidget( {
9491 * label: 'Button'
9492 * } ),
9493 * {
9494 * label: 'An ActionFieldLayout. This label is aligned top',
9495 * align: 'top',
9496 * help: 'This is help text'
9497 * }
9498 * );
9499 *
9500 * $( 'body' ).append( actionFieldLayout.$element );
9501 *
9502 * @class
9503 * @extends OO.ui.FieldLayout
9504 *
9505 * @constructor
9506 * @param {OO.ui.Widget} fieldWidget Field widget
9507 * @param {OO.ui.ButtonWidget} buttonWidget Button widget
9508 */
9509 OO.ui.ActionFieldLayout = function OoUiActionFieldLayout( fieldWidget, buttonWidget, config ) {
9510 // Allow passing positional parameters inside the config object
9511 if ( OO.isPlainObject( fieldWidget ) && config === undefined ) {
9512 config = fieldWidget;
9513 fieldWidget = config.fieldWidget;
9514 buttonWidget = config.buttonWidget;
9515 }
9516
9517 // Parent constructor
9518 OO.ui.ActionFieldLayout.parent.call( this, fieldWidget, config );
9519
9520 // Properties
9521 this.buttonWidget = buttonWidget;
9522 this.$button = $( '<div>' );
9523 this.$input = $( '<div>' );
9524
9525 // Initialization
9526 this.$element
9527 .addClass( 'oo-ui-actionFieldLayout' );
9528 this.$button
9529 .addClass( 'oo-ui-actionFieldLayout-button' )
9530 .append( this.buttonWidget.$element );
9531 this.$input
9532 .addClass( 'oo-ui-actionFieldLayout-input' )
9533 .append( this.fieldWidget.$element );
9534 this.$field
9535 .append( this.$input, this.$button );
9536 };
9537
9538 /* Setup */
9539
9540 OO.inheritClass( OO.ui.ActionFieldLayout, OO.ui.FieldLayout );
9541
9542 /**
9543 * FieldsetLayouts are composed of one or more {@link OO.ui.FieldLayout FieldLayouts},
9544 * which each contain an individual widget and, optionally, a label. Each Fieldset can be
9545 * configured with a label as well. For more information and examples,
9546 * please see the [OOjs UI documentation on MediaWiki][1].
9547 *
9548 * @example
9549 * // Example of a fieldset layout
9550 * var input1 = new OO.ui.TextInputWidget( {
9551 * placeholder: 'A text input field'
9552 * } );
9553 *
9554 * var input2 = new OO.ui.TextInputWidget( {
9555 * placeholder: 'A text input field'
9556 * } );
9557 *
9558 * var fieldset = new OO.ui.FieldsetLayout( {
9559 * label: 'Example of a fieldset layout'
9560 * } );
9561 *
9562 * fieldset.addItems( [
9563 * new OO.ui.FieldLayout( input1, {
9564 * label: 'Field One'
9565 * } ),
9566 * new OO.ui.FieldLayout( input2, {
9567 * label: 'Field Two'
9568 * } )
9569 * ] );
9570 * $( 'body' ).append( fieldset.$element );
9571 *
9572 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Fields_and_Fieldsets
9573 *
9574 * @class
9575 * @extends OO.ui.Layout
9576 * @mixins OO.ui.mixin.IconElement
9577 * @mixins OO.ui.mixin.LabelElement
9578 * @mixins OO.ui.mixin.GroupElement
9579 *
9580 * @constructor
9581 * @param {Object} [config] Configuration options
9582 * @cfg {OO.ui.FieldLayout[]} [items] An array of fields to add to the fieldset. See OO.ui.FieldLayout for more information about fields.
9583 */
9584 OO.ui.FieldsetLayout = function OoUiFieldsetLayout( config ) {
9585 // Configuration initialization
9586 config = config || {};
9587
9588 // Parent constructor
9589 OO.ui.FieldsetLayout.parent.call( this, config );
9590
9591 // Mixin constructors
9592 OO.ui.mixin.IconElement.call( this, config );
9593 OO.ui.mixin.LabelElement.call( this, config );
9594 OO.ui.mixin.GroupElement.call( this, config );
9595
9596 if ( config.help ) {
9597 this.popupButtonWidget = new OO.ui.PopupButtonWidget( {
9598 classes: [ 'oo-ui-fieldsetLayout-help' ],
9599 framed: false,
9600 icon: 'info'
9601 } );
9602
9603 this.popupButtonWidget.getPopup().$body.append(
9604 $( '<div>' )
9605 .text( config.help )
9606 .addClass( 'oo-ui-fieldsetLayout-help-content' )
9607 );
9608 this.$help = this.popupButtonWidget.$element;
9609 } else {
9610 this.$help = $( [] );
9611 }
9612
9613 // Initialization
9614 this.$element
9615 .addClass( 'oo-ui-fieldsetLayout' )
9616 .prepend( this.$help, this.$icon, this.$label, this.$group );
9617 if ( Array.isArray( config.items ) ) {
9618 this.addItems( config.items );
9619 }
9620 };
9621
9622 /* Setup */
9623
9624 OO.inheritClass( OO.ui.FieldsetLayout, OO.ui.Layout );
9625 OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.mixin.IconElement );
9626 OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.mixin.LabelElement );
9627 OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.mixin.GroupElement );
9628
9629 /**
9630 * FormLayouts are used to wrap {@link OO.ui.FieldsetLayout FieldsetLayouts} when you intend to use browser-based
9631 * form submission for the fields instead of handling them in JavaScript. Form layouts can be configured with an
9632 * HTML form action, an encoding type, and a method using the #action, #enctype, and #method configs, respectively.
9633 * See the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
9634 *
9635 * Only widgets from the {@link OO.ui.InputWidget InputWidget} family support form submission. It
9636 * includes standard form elements like {@link OO.ui.CheckboxInputWidget checkboxes}, {@link
9637 * OO.ui.RadioInputWidget radio buttons} and {@link OO.ui.TextInputWidget text fields}, as well as
9638 * some fancier controls. Some controls have both regular and InputWidget variants, for example
9639 * OO.ui.DropdownWidget and OO.ui.DropdownInputWidget – only the latter support form submission and
9640 * often have simplified APIs to match the capabilities of HTML forms.
9641 * See the [OOjs UI Inputs documentation on MediaWiki] [2] for more information about InputWidgets.
9642 *
9643 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Forms
9644 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
9645 *
9646 * @example
9647 * // Example of a form layout that wraps a fieldset layout
9648 * var input1 = new OO.ui.TextInputWidget( {
9649 * placeholder: 'Username'
9650 * } );
9651 * var input2 = new OO.ui.TextInputWidget( {
9652 * placeholder: 'Password',
9653 * type: 'password'
9654 * } );
9655 * var submit = new OO.ui.ButtonInputWidget( {
9656 * label: 'Submit'
9657 * } );
9658 *
9659 * var fieldset = new OO.ui.FieldsetLayout( {
9660 * label: 'A form layout'
9661 * } );
9662 * fieldset.addItems( [
9663 * new OO.ui.FieldLayout( input1, {
9664 * label: 'Username',
9665 * align: 'top'
9666 * } ),
9667 * new OO.ui.FieldLayout( input2, {
9668 * label: 'Password',
9669 * align: 'top'
9670 * } ),
9671 * new OO.ui.FieldLayout( submit )
9672 * ] );
9673 * var form = new OO.ui.FormLayout( {
9674 * items: [ fieldset ],
9675 * action: '/api/formhandler',
9676 * method: 'get'
9677 * } )
9678 * $( 'body' ).append( form.$element );
9679 *
9680 * @class
9681 * @extends OO.ui.Layout
9682 * @mixins OO.ui.mixin.GroupElement
9683 *
9684 * @constructor
9685 * @param {Object} [config] Configuration options
9686 * @cfg {string} [method] HTML form `method` attribute
9687 * @cfg {string} [action] HTML form `action` attribute
9688 * @cfg {string} [enctype] HTML form `enctype` attribute
9689 * @cfg {OO.ui.FieldsetLayout[]} [items] Fieldset layouts to add to the form layout.
9690 */
9691 OO.ui.FormLayout = function OoUiFormLayout( config ) {
9692 // Configuration initialization
9693 config = config || {};
9694
9695 // Parent constructor
9696 OO.ui.FormLayout.parent.call( this, config );
9697
9698 // Mixin constructors
9699 OO.ui.mixin.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) );
9700
9701 // Events
9702 this.$element.on( 'submit', this.onFormSubmit.bind( this ) );
9703
9704 // Make sure the action is safe
9705 if ( config.action !== undefined && !OO.ui.isSafeUrl( config.action ) ) {
9706 throw new Error( 'Potentially unsafe action provided: ' + config.action );
9707 }
9708
9709 // Initialization
9710 this.$element
9711 .addClass( 'oo-ui-formLayout' )
9712 .attr( {
9713 method: config.method,
9714 action: config.action,
9715 enctype: config.enctype
9716 } );
9717 if ( Array.isArray( config.items ) ) {
9718 this.addItems( config.items );
9719 }
9720 };
9721
9722 /* Setup */
9723
9724 OO.inheritClass( OO.ui.FormLayout, OO.ui.Layout );
9725 OO.mixinClass( OO.ui.FormLayout, OO.ui.mixin.GroupElement );
9726
9727 /* Events */
9728
9729 /**
9730 * A 'submit' event is emitted when the form is submitted.
9731 *
9732 * @event submit
9733 */
9734
9735 /* Static Properties */
9736
9737 OO.ui.FormLayout.static.tagName = 'form';
9738
9739 /* Methods */
9740
9741 /**
9742 * Handle form submit events.
9743 *
9744 * @private
9745 * @param {jQuery.Event} e Submit event
9746 * @fires submit
9747 */
9748 OO.ui.FormLayout.prototype.onFormSubmit = function () {
9749 if ( this.emit( 'submit' ) ) {
9750 return false;
9751 }
9752 };
9753
9754 /**
9755 * 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)
9756 * and its size is customized with the #menuSize config. The content area will fill all remaining space.
9757 *
9758 * @example
9759 * var menuLayout = new OO.ui.MenuLayout( {
9760 * position: 'top'
9761 * } ),
9762 * menuPanel = new OO.ui.PanelLayout( { padded: true, expanded: true, scrollable: true } ),
9763 * contentPanel = new OO.ui.PanelLayout( { padded: true, expanded: true, scrollable: true } ),
9764 * select = new OO.ui.SelectWidget( {
9765 * items: [
9766 * new OO.ui.OptionWidget( {
9767 * data: 'before',
9768 * label: 'Before',
9769 * } ),
9770 * new OO.ui.OptionWidget( {
9771 * data: 'after',
9772 * label: 'After',
9773 * } ),
9774 * new OO.ui.OptionWidget( {
9775 * data: 'top',
9776 * label: 'Top',
9777 * } ),
9778 * new OO.ui.OptionWidget( {
9779 * data: 'bottom',
9780 * label: 'Bottom',
9781 * } )
9782 * ]
9783 * } ).on( 'select', function ( item ) {
9784 * menuLayout.setMenuPosition( item.getData() );
9785 * } );
9786 *
9787 * menuLayout.$menu.append(
9788 * menuPanel.$element.append( '<b>Menu panel</b>', select.$element )
9789 * );
9790 * menuLayout.$content.append(
9791 * contentPanel.$element.append( '<b>Content panel</b>', '<p>Note that the menu is positioned relative to the content panel: top, bottom, after, before.</p>')
9792 * );
9793 * $( 'body' ).append( menuLayout.$element );
9794 *
9795 * If menu size needs to be overridden, it can be accomplished using CSS similar to the snippet
9796 * below. MenuLayout's CSS will override the appropriate values with 'auto' or '0' to display the
9797 * menu correctly. If `menuPosition` is known beforehand, CSS rules corresponding to other positions
9798 * may be omitted.
9799 *
9800 * .oo-ui-menuLayout-menu {
9801 * height: 200px;
9802 * width: 200px;
9803 * }
9804 * .oo-ui-menuLayout-content {
9805 * top: 200px;
9806 * left: 200px;
9807 * right: 200px;
9808 * bottom: 200px;
9809 * }
9810 *
9811 * @class
9812 * @extends OO.ui.Layout
9813 *
9814 * @constructor
9815 * @param {Object} [config] Configuration options
9816 * @cfg {boolean} [showMenu=true] Show menu
9817 * @cfg {string} [menuPosition='before'] Position of menu: `top`, `after`, `bottom` or `before`
9818 */
9819 OO.ui.MenuLayout = function OoUiMenuLayout( config ) {
9820 // Configuration initialization
9821 config = $.extend( {
9822 showMenu: true,
9823 menuPosition: 'before'
9824 }, config );
9825
9826 // Parent constructor
9827 OO.ui.MenuLayout.parent.call( this, config );
9828
9829 /**
9830 * Menu DOM node
9831 *
9832 * @property {jQuery}
9833 */
9834 this.$menu = $( '<div>' );
9835 /**
9836 * Content DOM node
9837 *
9838 * @property {jQuery}
9839 */
9840 this.$content = $( '<div>' );
9841
9842 // Initialization
9843 this.$menu
9844 .addClass( 'oo-ui-menuLayout-menu' );
9845 this.$content.addClass( 'oo-ui-menuLayout-content' );
9846 this.$element
9847 .addClass( 'oo-ui-menuLayout' )
9848 .append( this.$content, this.$menu );
9849 this.setMenuPosition( config.menuPosition );
9850 this.toggleMenu( config.showMenu );
9851 };
9852
9853 /* Setup */
9854
9855 OO.inheritClass( OO.ui.MenuLayout, OO.ui.Layout );
9856
9857 /* Methods */
9858
9859 /**
9860 * Toggle menu.
9861 *
9862 * @param {boolean} showMenu Show menu, omit to toggle
9863 * @chainable
9864 */
9865 OO.ui.MenuLayout.prototype.toggleMenu = function ( showMenu ) {
9866 showMenu = showMenu === undefined ? !this.showMenu : !!showMenu;
9867
9868 if ( this.showMenu !== showMenu ) {
9869 this.showMenu = showMenu;
9870 this.$element
9871 .toggleClass( 'oo-ui-menuLayout-showMenu', this.showMenu )
9872 .toggleClass( 'oo-ui-menuLayout-hideMenu', !this.showMenu );
9873 }
9874
9875 return this;
9876 };
9877
9878 /**
9879 * Check if menu is visible
9880 *
9881 * @return {boolean} Menu is visible
9882 */
9883 OO.ui.MenuLayout.prototype.isMenuVisible = function () {
9884 return this.showMenu;
9885 };
9886
9887 /**
9888 * Set menu position.
9889 *
9890 * @param {string} position Position of menu, either `top`, `after`, `bottom` or `before`
9891 * @throws {Error} If position value is not supported
9892 * @chainable
9893 */
9894 OO.ui.MenuLayout.prototype.setMenuPosition = function ( position ) {
9895 this.$element.removeClass( 'oo-ui-menuLayout-' + this.menuPosition );
9896 this.menuPosition = position;
9897 this.$element.addClass( 'oo-ui-menuLayout-' + position );
9898
9899 return this;
9900 };
9901
9902 /**
9903 * Get menu position.
9904 *
9905 * @return {string} Menu position
9906 */
9907 OO.ui.MenuLayout.prototype.getMenuPosition = function () {
9908 return this.menuPosition;
9909 };
9910
9911 /**
9912 * BookletLayouts contain {@link OO.ui.PageLayout page layouts} as well as
9913 * an {@link OO.ui.OutlineSelectWidget outline} that allows users to easily navigate
9914 * through the pages and select which one to display. By default, only one page is
9915 * displayed at a time and the outline is hidden. When a user navigates to a new page,
9916 * the booklet layout automatically focuses on the first focusable element, unless the
9917 * default setting is changed. Optionally, booklets can be configured to show
9918 * {@link OO.ui.OutlineControlsWidget controls} for adding, moving, and removing items.
9919 *
9920 * @example
9921 * // Example of a BookletLayout that contains two PageLayouts.
9922 *
9923 * function PageOneLayout( name, config ) {
9924 * PageOneLayout.parent.call( this, name, config );
9925 * this.$element.append( '<p>First page</p><p>(This booklet has an outline, displayed on the left)</p>' );
9926 * }
9927 * OO.inheritClass( PageOneLayout, OO.ui.PageLayout );
9928 * PageOneLayout.prototype.setupOutlineItem = function () {
9929 * this.outlineItem.setLabel( 'Page One' );
9930 * };
9931 *
9932 * function PageTwoLayout( name, config ) {
9933 * PageTwoLayout.parent.call( this, name, config );
9934 * this.$element.append( '<p>Second page</p>' );
9935 * }
9936 * OO.inheritClass( PageTwoLayout, OO.ui.PageLayout );
9937 * PageTwoLayout.prototype.setupOutlineItem = function () {
9938 * this.outlineItem.setLabel( 'Page Two' );
9939 * };
9940 *
9941 * var page1 = new PageOneLayout( 'one' ),
9942 * page2 = new PageTwoLayout( 'two' );
9943 *
9944 * var booklet = new OO.ui.BookletLayout( {
9945 * outlined: true
9946 * } );
9947 *
9948 * booklet.addPages ( [ page1, page2 ] );
9949 * $( 'body' ).append( booklet.$element );
9950 *
9951 * @class
9952 * @extends OO.ui.MenuLayout
9953 *
9954 * @constructor
9955 * @param {Object} [config] Configuration options
9956 * @cfg {boolean} [continuous=false] Show all pages, one after another
9957 * @cfg {boolean} [autoFocus=true] Focus on the first focusable element when a new page is displayed.
9958 * @cfg {boolean} [outlined=false] Show the outline. The outline is used to navigate through the pages of the booklet.
9959 * @cfg {boolean} [editable=false] Show controls for adding, removing and reordering pages
9960 */
9961 OO.ui.BookletLayout = function OoUiBookletLayout( config ) {
9962 // Configuration initialization
9963 config = config || {};
9964
9965 // Parent constructor
9966 OO.ui.BookletLayout.parent.call( this, config );
9967
9968 // Properties
9969 this.currentPageName = null;
9970 this.pages = {};
9971 this.ignoreFocus = false;
9972 this.stackLayout = new OO.ui.StackLayout( { continuous: !!config.continuous } );
9973 this.$content.append( this.stackLayout.$element );
9974 this.autoFocus = config.autoFocus === undefined || !!config.autoFocus;
9975 this.outlineVisible = false;
9976 this.outlined = !!config.outlined;
9977 if ( this.outlined ) {
9978 this.editable = !!config.editable;
9979 this.outlineControlsWidget = null;
9980 this.outlineSelectWidget = new OO.ui.OutlineSelectWidget();
9981 this.outlinePanel = new OO.ui.PanelLayout( { scrollable: true } );
9982 this.$menu.append( this.outlinePanel.$element );
9983 this.outlineVisible = true;
9984 if ( this.editable ) {
9985 this.outlineControlsWidget = new OO.ui.OutlineControlsWidget(
9986 this.outlineSelectWidget
9987 );
9988 }
9989 }
9990 this.toggleMenu( this.outlined );
9991
9992 // Events
9993 this.stackLayout.connect( this, { set: 'onStackLayoutSet' } );
9994 if ( this.outlined ) {
9995 this.outlineSelectWidget.connect( this, { select: 'onOutlineSelectWidgetSelect' } );
9996 this.scrolling = false;
9997 this.stackLayout.connect( this, { visibleItemChange: 'onStackLayoutVisibleItemChange' } );
9998 }
9999 if ( this.autoFocus ) {
10000 // Event 'focus' does not bubble, but 'focusin' does
10001 this.stackLayout.$element.on( 'focusin', this.onStackLayoutFocus.bind( this ) );
10002 }
10003
10004 // Initialization
10005 this.$element.addClass( 'oo-ui-bookletLayout' );
10006 this.stackLayout.$element.addClass( 'oo-ui-bookletLayout-stackLayout' );
10007 if ( this.outlined ) {
10008 this.outlinePanel.$element
10009 .addClass( 'oo-ui-bookletLayout-outlinePanel' )
10010 .append( this.outlineSelectWidget.$element );
10011 if ( this.editable ) {
10012 this.outlinePanel.$element
10013 .addClass( 'oo-ui-bookletLayout-outlinePanel-editable' )
10014 .append( this.outlineControlsWidget.$element );
10015 }
10016 }
10017 };
10018
10019 /* Setup */
10020
10021 OO.inheritClass( OO.ui.BookletLayout, OO.ui.MenuLayout );
10022
10023 /* Events */
10024
10025 /**
10026 * A 'set' event is emitted when a page is {@link #setPage set} to be displayed by the booklet layout.
10027 * @event set
10028 * @param {OO.ui.PageLayout} page Current page
10029 */
10030
10031 /**
10032 * An 'add' event is emitted when pages are {@link #addPages added} to the booklet layout.
10033 *
10034 * @event add
10035 * @param {OO.ui.PageLayout[]} page Added pages
10036 * @param {number} index Index pages were added at
10037 */
10038
10039 /**
10040 * A 'remove' event is emitted when pages are {@link #clearPages cleared} or
10041 * {@link #removePages removed} from the booklet.
10042 *
10043 * @event remove
10044 * @param {OO.ui.PageLayout[]} pages Removed pages
10045 */
10046
10047 /* Methods */
10048
10049 /**
10050 * Handle stack layout focus.
10051 *
10052 * @private
10053 * @param {jQuery.Event} e Focusin event
10054 */
10055 OO.ui.BookletLayout.prototype.onStackLayoutFocus = function ( e ) {
10056 var name, $target;
10057
10058 // Find the page that an element was focused within
10059 $target = $( e.target ).closest( '.oo-ui-pageLayout' );
10060 for ( name in this.pages ) {
10061 // Check for page match, exclude current page to find only page changes
10062 if ( this.pages[ name ].$element[ 0 ] === $target[ 0 ] && name !== this.currentPageName ) {
10063 this.setPage( name );
10064 break;
10065 }
10066 }
10067 };
10068
10069 /**
10070 * Handle visibleItemChange events from the stackLayout
10071 *
10072 * The next visible page is set as the current page by selecting it
10073 * in the outline
10074 *
10075 * @param {OO.ui.PageLayout} page The next visible page in the layout
10076 */
10077 OO.ui.BookletLayout.prototype.onStackLayoutVisibleItemChange = function ( page ) {
10078 // Set a flag to so that the resulting call to #onStackLayoutSet doesn't
10079 // try and scroll the item into view again.
10080 this.scrolling = true;
10081 this.outlineSelectWidget.selectItemByData( page.getName() );
10082 this.scrolling = false;
10083 };
10084
10085 /**
10086 * Handle stack layout set events.
10087 *
10088 * @private
10089 * @param {OO.ui.PanelLayout|null} page The page panel that is now the current panel
10090 */
10091 OO.ui.BookletLayout.prototype.onStackLayoutSet = function ( page ) {
10092 var layout = this;
10093 if ( !this.scrolling && page ) {
10094 page.scrollElementIntoView( { complete: function () {
10095 if ( layout.autoFocus ) {
10096 layout.focus();
10097 }
10098 } } );
10099 }
10100 };
10101
10102 /**
10103 * Focus the first input in the current page.
10104 *
10105 * If no page is selected, the first selectable page will be selected.
10106 * If the focus is already in an element on the current page, nothing will happen.
10107 * @param {number} [itemIndex] A specific item to focus on
10108 */
10109 OO.ui.BookletLayout.prototype.focus = function ( itemIndex ) {
10110 var page,
10111 items = this.stackLayout.getItems();
10112
10113 if ( itemIndex !== undefined && items[ itemIndex ] ) {
10114 page = items[ itemIndex ];
10115 } else {
10116 page = this.stackLayout.getCurrentItem();
10117 }
10118
10119 if ( !page && this.outlined ) {
10120 this.selectFirstSelectablePage();
10121 page = this.stackLayout.getCurrentItem();
10122 }
10123 if ( !page ) {
10124 return;
10125 }
10126 // Only change the focus if is not already in the current page
10127 if ( !OO.ui.contains( page.$element[ 0 ], this.getElementDocument().activeElement, true ) ) {
10128 page.focus();
10129 }
10130 };
10131
10132 /**
10133 * Find the first focusable input in the booklet layout and focus
10134 * on it.
10135 */
10136 OO.ui.BookletLayout.prototype.focusFirstFocusable = function () {
10137 OO.ui.findFocusable( this.stackLayout.$element ).focus();
10138 };
10139
10140 /**
10141 * Handle outline widget select events.
10142 *
10143 * @private
10144 * @param {OO.ui.OptionWidget|null} item Selected item
10145 */
10146 OO.ui.BookletLayout.prototype.onOutlineSelectWidgetSelect = function ( item ) {
10147 if ( item ) {
10148 this.setPage( item.getData() );
10149 }
10150 };
10151
10152 /**
10153 * Check if booklet has an outline.
10154 *
10155 * @return {boolean} Booklet has an outline
10156 */
10157 OO.ui.BookletLayout.prototype.isOutlined = function () {
10158 return this.outlined;
10159 };
10160
10161 /**
10162 * Check if booklet has editing controls.
10163 *
10164 * @return {boolean} Booklet is editable
10165 */
10166 OO.ui.BookletLayout.prototype.isEditable = function () {
10167 return this.editable;
10168 };
10169
10170 /**
10171 * Check if booklet has a visible outline.
10172 *
10173 * @return {boolean} Outline is visible
10174 */
10175 OO.ui.BookletLayout.prototype.isOutlineVisible = function () {
10176 return this.outlined && this.outlineVisible;
10177 };
10178
10179 /**
10180 * Hide or show the outline.
10181 *
10182 * @param {boolean} [show] Show outline, omit to invert current state
10183 * @chainable
10184 */
10185 OO.ui.BookletLayout.prototype.toggleOutline = function ( show ) {
10186 if ( this.outlined ) {
10187 show = show === undefined ? !this.outlineVisible : !!show;
10188 this.outlineVisible = show;
10189 this.toggleMenu( show );
10190 }
10191
10192 return this;
10193 };
10194
10195 /**
10196 * Get the page closest to the specified page.
10197 *
10198 * @param {OO.ui.PageLayout} page Page to use as a reference point
10199 * @return {OO.ui.PageLayout|null} Page closest to the specified page
10200 */
10201 OO.ui.BookletLayout.prototype.getClosestPage = function ( page ) {
10202 var next, prev, level,
10203 pages = this.stackLayout.getItems(),
10204 index = pages.indexOf( page );
10205
10206 if ( index !== -1 ) {
10207 next = pages[ index + 1 ];
10208 prev = pages[ index - 1 ];
10209 // Prefer adjacent pages at the same level
10210 if ( this.outlined ) {
10211 level = this.outlineSelectWidget.getItemFromData( page.getName() ).getLevel();
10212 if (
10213 prev &&
10214 level === this.outlineSelectWidget.getItemFromData( prev.getName() ).getLevel()
10215 ) {
10216 return prev;
10217 }
10218 if (
10219 next &&
10220 level === this.outlineSelectWidget.getItemFromData( next.getName() ).getLevel()
10221 ) {
10222 return next;
10223 }
10224 }
10225 }
10226 return prev || next || null;
10227 };
10228
10229 /**
10230 * Get the outline widget.
10231 *
10232 * If the booklet is not outlined, the method will return `null`.
10233 *
10234 * @return {OO.ui.OutlineSelectWidget|null} Outline widget, or null if the booklet is not outlined
10235 */
10236 OO.ui.BookletLayout.prototype.getOutline = function () {
10237 return this.outlineSelectWidget;
10238 };
10239
10240 /**
10241 * Get the outline controls widget.
10242 *
10243 * If the outline is not editable, the method will return `null`.
10244 *
10245 * @return {OO.ui.OutlineControlsWidget|null} The outline controls widget.
10246 */
10247 OO.ui.BookletLayout.prototype.getOutlineControls = function () {
10248 return this.outlineControlsWidget;
10249 };
10250
10251 /**
10252 * Get a page by its symbolic name.
10253 *
10254 * @param {string} name Symbolic name of page
10255 * @return {OO.ui.PageLayout|undefined} Page, if found
10256 */
10257 OO.ui.BookletLayout.prototype.getPage = function ( name ) {
10258 return this.pages[ name ];
10259 };
10260
10261 /**
10262 * Get the current page.
10263 *
10264 * @return {OO.ui.PageLayout|undefined} Current page, if found
10265 */
10266 OO.ui.BookletLayout.prototype.getCurrentPage = function () {
10267 var name = this.getCurrentPageName();
10268 return name ? this.getPage( name ) : undefined;
10269 };
10270
10271 /**
10272 * Get the symbolic name of the current page.
10273 *
10274 * @return {string|null} Symbolic name of the current page
10275 */
10276 OO.ui.BookletLayout.prototype.getCurrentPageName = function () {
10277 return this.currentPageName;
10278 };
10279
10280 /**
10281 * Add pages to the booklet layout
10282 *
10283 * When pages are added with the same names as existing pages, the existing pages will be
10284 * automatically removed before the new pages are added.
10285 *
10286 * @param {OO.ui.PageLayout[]} pages Pages to add
10287 * @param {number} index Index of the insertion point
10288 * @fires add
10289 * @chainable
10290 */
10291 OO.ui.BookletLayout.prototype.addPages = function ( pages, index ) {
10292 var i, len, name, page, item, currentIndex,
10293 stackLayoutPages = this.stackLayout.getItems(),
10294 remove = [],
10295 items = [];
10296
10297 // Remove pages with same names
10298 for ( i = 0, len = pages.length; i < len; i++ ) {
10299 page = pages[ i ];
10300 name = page.getName();
10301
10302 if ( Object.prototype.hasOwnProperty.call( this.pages, name ) ) {
10303 // Correct the insertion index
10304 currentIndex = stackLayoutPages.indexOf( this.pages[ name ] );
10305 if ( currentIndex !== -1 && currentIndex + 1 < index ) {
10306 index--;
10307 }
10308 remove.push( this.pages[ name ] );
10309 }
10310 }
10311 if ( remove.length ) {
10312 this.removePages( remove );
10313 }
10314
10315 // Add new pages
10316 for ( i = 0, len = pages.length; i < len; i++ ) {
10317 page = pages[ i ];
10318 name = page.getName();
10319 this.pages[ page.getName() ] = page;
10320 if ( this.outlined ) {
10321 item = new OO.ui.OutlineOptionWidget( { data: name } );
10322 page.setOutlineItem( item );
10323 items.push( item );
10324 }
10325 }
10326
10327 if ( this.outlined && items.length ) {
10328 this.outlineSelectWidget.addItems( items, index );
10329 this.selectFirstSelectablePage();
10330 }
10331 this.stackLayout.addItems( pages, index );
10332 this.emit( 'add', pages, index );
10333
10334 return this;
10335 };
10336
10337 /**
10338 * Remove the specified pages from the booklet layout.
10339 *
10340 * To remove all pages from the booklet, you may wish to use the #clearPages method instead.
10341 *
10342 * @param {OO.ui.PageLayout[]} pages An array of pages to remove
10343 * @fires remove
10344 * @chainable
10345 */
10346 OO.ui.BookletLayout.prototype.removePages = function ( pages ) {
10347 var i, len, name, page,
10348 items = [];
10349
10350 for ( i = 0, len = pages.length; i < len; i++ ) {
10351 page = pages[ i ];
10352 name = page.getName();
10353 delete this.pages[ name ];
10354 if ( this.outlined ) {
10355 items.push( this.outlineSelectWidget.getItemFromData( name ) );
10356 page.setOutlineItem( null );
10357 }
10358 }
10359 if ( this.outlined && items.length ) {
10360 this.outlineSelectWidget.removeItems( items );
10361 this.selectFirstSelectablePage();
10362 }
10363 this.stackLayout.removeItems( pages );
10364 this.emit( 'remove', pages );
10365
10366 return this;
10367 };
10368
10369 /**
10370 * Clear all pages from the booklet layout.
10371 *
10372 * To remove only a subset of pages from the booklet, use the #removePages method.
10373 *
10374 * @fires remove
10375 * @chainable
10376 */
10377 OO.ui.BookletLayout.prototype.clearPages = function () {
10378 var i, len,
10379 pages = this.stackLayout.getItems();
10380
10381 this.pages = {};
10382 this.currentPageName = null;
10383 if ( this.outlined ) {
10384 this.outlineSelectWidget.clearItems();
10385 for ( i = 0, len = pages.length; i < len; i++ ) {
10386 pages[ i ].setOutlineItem( null );
10387 }
10388 }
10389 this.stackLayout.clearItems();
10390
10391 this.emit( 'remove', pages );
10392
10393 return this;
10394 };
10395
10396 /**
10397 * Set the current page by symbolic name.
10398 *
10399 * @fires set
10400 * @param {string} name Symbolic name of page
10401 */
10402 OO.ui.BookletLayout.prototype.setPage = function ( name ) {
10403 var selectedItem,
10404 $focused,
10405 page = this.pages[ name ],
10406 previousPage = this.currentPageName && this.pages[ this.currentPageName ];
10407
10408 if ( name !== this.currentPageName ) {
10409 if ( this.outlined ) {
10410 selectedItem = this.outlineSelectWidget.getSelectedItem();
10411 if ( selectedItem && selectedItem.getData() !== name ) {
10412 this.outlineSelectWidget.selectItemByData( name );
10413 }
10414 }
10415 if ( page ) {
10416 if ( previousPage ) {
10417 previousPage.setActive( false );
10418 // Blur anything focused if the next page doesn't have anything focusable.
10419 // This is not needed if the next page has something focusable (because once it is focused
10420 // this blur happens automatically). If the layout is non-continuous, this check is
10421 // meaningless because the next page is not visible yet and thus can't hold focus.
10422 if (
10423 this.autoFocus &&
10424 this.stackLayout.continuous &&
10425 OO.ui.findFocusable( page.$element ).length !== 0
10426 ) {
10427 $focused = previousPage.$element.find( ':focus' );
10428 if ( $focused.length ) {
10429 $focused[ 0 ].blur();
10430 }
10431 }
10432 }
10433 this.currentPageName = name;
10434 page.setActive( true );
10435 this.stackLayout.setItem( page );
10436 if ( !this.stackLayout.continuous && previousPage ) {
10437 // This should not be necessary, since any inputs on the previous page should have been
10438 // blurred when it was hidden, but browsers are not very consistent about this.
10439 $focused = previousPage.$element.find( ':focus' );
10440 if ( $focused.length ) {
10441 $focused[ 0 ].blur();
10442 }
10443 }
10444 this.emit( 'set', page );
10445 }
10446 }
10447 };
10448
10449 /**
10450 * Select the first selectable page.
10451 *
10452 * @chainable
10453 */
10454 OO.ui.BookletLayout.prototype.selectFirstSelectablePage = function () {
10455 if ( !this.outlineSelectWidget.getSelectedItem() ) {
10456 this.outlineSelectWidget.selectItem( this.outlineSelectWidget.getFirstSelectableItem() );
10457 }
10458
10459 return this;
10460 };
10461
10462 /**
10463 * IndexLayouts contain {@link OO.ui.CardLayout card layouts} as well as
10464 * {@link OO.ui.TabSelectWidget tabs} that allow users to easily navigate through the cards and
10465 * select which one to display. By default, only one card is displayed at a time. When a user
10466 * navigates to a new card, the index layout automatically focuses on the first focusable element,
10467 * unless the default setting is changed.
10468 *
10469 * TODO: This class is similar to BookletLayout, we may want to refactor to reduce duplication
10470 *
10471 * @example
10472 * // Example of a IndexLayout that contains two CardLayouts.
10473 *
10474 * function CardOneLayout( name, config ) {
10475 * CardOneLayout.parent.call( this, name, config );
10476 * this.$element.append( '<p>First card</p>' );
10477 * }
10478 * OO.inheritClass( CardOneLayout, OO.ui.CardLayout );
10479 * CardOneLayout.prototype.setupTabItem = function () {
10480 * this.tabItem.setLabel( 'Card one' );
10481 * };
10482 *
10483 * var card1 = new CardOneLayout( 'one' ),
10484 * card2 = new CardLayout( 'two', { label: 'Card two' } );
10485 *
10486 * card2.$element.append( '<p>Second card</p>' );
10487 *
10488 * var index = new OO.ui.IndexLayout();
10489 *
10490 * index.addCards ( [ card1, card2 ] );
10491 * $( 'body' ).append( index.$element );
10492 *
10493 * @class
10494 * @extends OO.ui.MenuLayout
10495 *
10496 * @constructor
10497 * @param {Object} [config] Configuration options
10498 * @cfg {boolean} [continuous=false] Show all cards, one after another
10499 * @cfg {boolean} [expanded=true] Expand the content panel to fill the entire parent element.
10500 * @cfg {boolean} [autoFocus=true] Focus on the first focusable element when a new card is displayed.
10501 */
10502 OO.ui.IndexLayout = function OoUiIndexLayout( config ) {
10503 // Configuration initialization
10504 config = $.extend( {}, config, { menuPosition: 'top' } );
10505
10506 // Parent constructor
10507 OO.ui.IndexLayout.parent.call( this, config );
10508
10509 // Properties
10510 this.currentCardName = null;
10511 this.cards = {};
10512 this.ignoreFocus = false;
10513 this.stackLayout = new OO.ui.StackLayout( {
10514 continuous: !!config.continuous,
10515 expanded: config.expanded
10516 } );
10517 this.$content.append( this.stackLayout.$element );
10518 this.autoFocus = config.autoFocus === undefined || !!config.autoFocus;
10519
10520 this.tabSelectWidget = new OO.ui.TabSelectWidget();
10521 this.tabPanel = new OO.ui.PanelLayout();
10522 this.$menu.append( this.tabPanel.$element );
10523
10524 this.toggleMenu( true );
10525
10526 // Events
10527 this.stackLayout.connect( this, { set: 'onStackLayoutSet' } );
10528 this.tabSelectWidget.connect( this, { select: 'onTabSelectWidgetSelect' } );
10529 if ( this.autoFocus ) {
10530 // Event 'focus' does not bubble, but 'focusin' does
10531 this.stackLayout.$element.on( 'focusin', this.onStackLayoutFocus.bind( this ) );
10532 }
10533
10534 // Initialization
10535 this.$element.addClass( 'oo-ui-indexLayout' );
10536 this.stackLayout.$element.addClass( 'oo-ui-indexLayout-stackLayout' );
10537 this.tabPanel.$element
10538 .addClass( 'oo-ui-indexLayout-tabPanel' )
10539 .append( this.tabSelectWidget.$element );
10540 };
10541
10542 /* Setup */
10543
10544 OO.inheritClass( OO.ui.IndexLayout, OO.ui.MenuLayout );
10545
10546 /* Events */
10547
10548 /**
10549 * A 'set' event is emitted when a card is {@link #setCard set} to be displayed by the index layout.
10550 * @event set
10551 * @param {OO.ui.CardLayout} card Current card
10552 */
10553
10554 /**
10555 * An 'add' event is emitted when cards are {@link #addCards added} to the index layout.
10556 *
10557 * @event add
10558 * @param {OO.ui.CardLayout[]} card Added cards
10559 * @param {number} index Index cards were added at
10560 */
10561
10562 /**
10563 * A 'remove' event is emitted when cards are {@link #clearCards cleared} or
10564 * {@link #removeCards removed} from the index.
10565 *
10566 * @event remove
10567 * @param {OO.ui.CardLayout[]} cards Removed cards
10568 */
10569
10570 /* Methods */
10571
10572 /**
10573 * Handle stack layout focus.
10574 *
10575 * @private
10576 * @param {jQuery.Event} e Focusin event
10577 */
10578 OO.ui.IndexLayout.prototype.onStackLayoutFocus = function ( e ) {
10579 var name, $target;
10580
10581 // Find the card that an element was focused within
10582 $target = $( e.target ).closest( '.oo-ui-cardLayout' );
10583 for ( name in this.cards ) {
10584 // Check for card match, exclude current card to find only card changes
10585 if ( this.cards[ name ].$element[ 0 ] === $target[ 0 ] && name !== this.currentCardName ) {
10586 this.setCard( name );
10587 break;
10588 }
10589 }
10590 };
10591
10592 /**
10593 * Handle stack layout set events.
10594 *
10595 * @private
10596 * @param {OO.ui.PanelLayout|null} card The card panel that is now the current panel
10597 */
10598 OO.ui.IndexLayout.prototype.onStackLayoutSet = function ( card ) {
10599 var layout = this;
10600 if ( card ) {
10601 card.scrollElementIntoView( { complete: function () {
10602 if ( layout.autoFocus ) {
10603 layout.focus();
10604 }
10605 } } );
10606 }
10607 };
10608
10609 /**
10610 * Focus the first input in the current card.
10611 *
10612 * If no card is selected, the first selectable card will be selected.
10613 * If the focus is already in an element on the current card, nothing will happen.
10614 * @param {number} [itemIndex] A specific item to focus on
10615 */
10616 OO.ui.IndexLayout.prototype.focus = function ( itemIndex ) {
10617 var card,
10618 items = this.stackLayout.getItems();
10619
10620 if ( itemIndex !== undefined && items[ itemIndex ] ) {
10621 card = items[ itemIndex ];
10622 } else {
10623 card = this.stackLayout.getCurrentItem();
10624 }
10625
10626 if ( !card ) {
10627 this.selectFirstSelectableCard();
10628 card = this.stackLayout.getCurrentItem();
10629 }
10630 if ( !card ) {
10631 return;
10632 }
10633 // Only change the focus if is not already in the current page
10634 if ( !OO.ui.contains( card.$element[ 0 ], this.getElementDocument().activeElement, true ) ) {
10635 card.focus();
10636 }
10637 };
10638
10639 /**
10640 * Find the first focusable input in the index layout and focus
10641 * on it.
10642 */
10643 OO.ui.IndexLayout.prototype.focusFirstFocusable = function () {
10644 OO.ui.findFocusable( this.stackLayout.$element ).focus();
10645 };
10646
10647 /**
10648 * Handle tab widget select events.
10649 *
10650 * @private
10651 * @param {OO.ui.OptionWidget|null} item Selected item
10652 */
10653 OO.ui.IndexLayout.prototype.onTabSelectWidgetSelect = function ( item ) {
10654 if ( item ) {
10655 this.setCard( item.getData() );
10656 }
10657 };
10658
10659 /**
10660 * Get the card closest to the specified card.
10661 *
10662 * @param {OO.ui.CardLayout} card Card to use as a reference point
10663 * @return {OO.ui.CardLayout|null} Card closest to the specified card
10664 */
10665 OO.ui.IndexLayout.prototype.getClosestCard = function ( card ) {
10666 var next, prev, level,
10667 cards = this.stackLayout.getItems(),
10668 index = cards.indexOf( card );
10669
10670 if ( index !== -1 ) {
10671 next = cards[ index + 1 ];
10672 prev = cards[ index - 1 ];
10673 // Prefer adjacent cards at the same level
10674 level = this.tabSelectWidget.getItemFromData( card.getName() ).getLevel();
10675 if (
10676 prev &&
10677 level === this.tabSelectWidget.getItemFromData( prev.getName() ).getLevel()
10678 ) {
10679 return prev;
10680 }
10681 if (
10682 next &&
10683 level === this.tabSelectWidget.getItemFromData( next.getName() ).getLevel()
10684 ) {
10685 return next;
10686 }
10687 }
10688 return prev || next || null;
10689 };
10690
10691 /**
10692 * Get the tabs widget.
10693 *
10694 * @return {OO.ui.TabSelectWidget} Tabs widget
10695 */
10696 OO.ui.IndexLayout.prototype.getTabs = function () {
10697 return this.tabSelectWidget;
10698 };
10699
10700 /**
10701 * Get a card by its symbolic name.
10702 *
10703 * @param {string} name Symbolic name of card
10704 * @return {OO.ui.CardLayout|undefined} Card, if found
10705 */
10706 OO.ui.IndexLayout.prototype.getCard = function ( name ) {
10707 return this.cards[ name ];
10708 };
10709
10710 /**
10711 * Get the current card.
10712 *
10713 * @return {OO.ui.CardLayout|undefined} Current card, if found
10714 */
10715 OO.ui.IndexLayout.prototype.getCurrentCard = function () {
10716 var name = this.getCurrentCardName();
10717 return name ? this.getCard( name ) : undefined;
10718 };
10719
10720 /**
10721 * Get the symbolic name of the current card.
10722 *
10723 * @return {string|null} Symbolic name of the current card
10724 */
10725 OO.ui.IndexLayout.prototype.getCurrentCardName = function () {
10726 return this.currentCardName;
10727 };
10728
10729 /**
10730 * Add cards to the index layout
10731 *
10732 * When cards are added with the same names as existing cards, the existing cards will be
10733 * automatically removed before the new cards are added.
10734 *
10735 * @param {OO.ui.CardLayout[]} cards Cards to add
10736 * @param {number} index Index of the insertion point
10737 * @fires add
10738 * @chainable
10739 */
10740 OO.ui.IndexLayout.prototype.addCards = function ( cards, index ) {
10741 var i, len, name, card, item, currentIndex,
10742 stackLayoutCards = this.stackLayout.getItems(),
10743 remove = [],
10744 items = [];
10745
10746 // Remove cards with same names
10747 for ( i = 0, len = cards.length; i < len; i++ ) {
10748 card = cards[ i ];
10749 name = card.getName();
10750
10751 if ( Object.prototype.hasOwnProperty.call( this.cards, name ) ) {
10752 // Correct the insertion index
10753 currentIndex = stackLayoutCards.indexOf( this.cards[ name ] );
10754 if ( currentIndex !== -1 && currentIndex + 1 < index ) {
10755 index--;
10756 }
10757 remove.push( this.cards[ name ] );
10758 }
10759 }
10760 if ( remove.length ) {
10761 this.removeCards( remove );
10762 }
10763
10764 // Add new cards
10765 for ( i = 0, len = cards.length; i < len; i++ ) {
10766 card = cards[ i ];
10767 name = card.getName();
10768 this.cards[ card.getName() ] = card;
10769 item = new OO.ui.TabOptionWidget( { data: name } );
10770 card.setTabItem( item );
10771 items.push( item );
10772 }
10773
10774 if ( items.length ) {
10775 this.tabSelectWidget.addItems( items, index );
10776 this.selectFirstSelectableCard();
10777 }
10778 this.stackLayout.addItems( cards, index );
10779 this.emit( 'add', cards, index );
10780
10781 return this;
10782 };
10783
10784 /**
10785 * Remove the specified cards from the index layout.
10786 *
10787 * To remove all cards from the index, you may wish to use the #clearCards method instead.
10788 *
10789 * @param {OO.ui.CardLayout[]} cards An array of cards to remove
10790 * @fires remove
10791 * @chainable
10792 */
10793 OO.ui.IndexLayout.prototype.removeCards = function ( cards ) {
10794 var i, len, name, card,
10795 items = [];
10796
10797 for ( i = 0, len = cards.length; i < len; i++ ) {
10798 card = cards[ i ];
10799 name = card.getName();
10800 delete this.cards[ name ];
10801 items.push( this.tabSelectWidget.getItemFromData( name ) );
10802 card.setTabItem( null );
10803 }
10804 if ( items.length ) {
10805 this.tabSelectWidget.removeItems( items );
10806 this.selectFirstSelectableCard();
10807 }
10808 this.stackLayout.removeItems( cards );
10809 this.emit( 'remove', cards );
10810
10811 return this;
10812 };
10813
10814 /**
10815 * Clear all cards from the index layout.
10816 *
10817 * To remove only a subset of cards from the index, use the #removeCards method.
10818 *
10819 * @fires remove
10820 * @chainable
10821 */
10822 OO.ui.IndexLayout.prototype.clearCards = function () {
10823 var i, len,
10824 cards = this.stackLayout.getItems();
10825
10826 this.cards = {};
10827 this.currentCardName = null;
10828 this.tabSelectWidget.clearItems();
10829 for ( i = 0, len = cards.length; i < len; i++ ) {
10830 cards[ i ].setTabItem( null );
10831 }
10832 this.stackLayout.clearItems();
10833
10834 this.emit( 'remove', cards );
10835
10836 return this;
10837 };
10838
10839 /**
10840 * Set the current card by symbolic name.
10841 *
10842 * @fires set
10843 * @param {string} name Symbolic name of card
10844 */
10845 OO.ui.IndexLayout.prototype.setCard = function ( name ) {
10846 var selectedItem,
10847 $focused,
10848 card = this.cards[ name ],
10849 previousCard = this.currentCardName && this.cards[ this.currentCardName ];
10850
10851 if ( name !== this.currentCardName ) {
10852 selectedItem = this.tabSelectWidget.getSelectedItem();
10853 if ( selectedItem && selectedItem.getData() !== name ) {
10854 this.tabSelectWidget.selectItemByData( name );
10855 }
10856 if ( card ) {
10857 if ( previousCard ) {
10858 previousCard.setActive( false );
10859 // Blur anything focused if the next card doesn't have anything focusable.
10860 // This is not needed if the next card has something focusable (because once it is focused
10861 // this blur happens automatically). If the layout is non-continuous, this check is
10862 // meaningless because the next card is not visible yet and thus can't hold focus.
10863 if (
10864 this.autoFocus &&
10865 this.stackLayout.continuous &&
10866 OO.ui.findFocusable( card.$element ).length !== 0
10867 ) {
10868 $focused = previousCard.$element.find( ':focus' );
10869 if ( $focused.length ) {
10870 $focused[ 0 ].blur();
10871 }
10872 }
10873 }
10874 this.currentCardName = name;
10875 card.setActive( true );
10876 this.stackLayout.setItem( card );
10877 if ( !this.stackLayout.continuous && previousCard ) {
10878 // This should not be necessary, since any inputs on the previous card should have been
10879 // blurred when it was hidden, but browsers are not very consistent about this.
10880 $focused = previousCard.$element.find( ':focus' );
10881 if ( $focused.length ) {
10882 $focused[ 0 ].blur();
10883 }
10884 }
10885 this.emit( 'set', card );
10886 }
10887 }
10888 };
10889
10890 /**
10891 * Select the first selectable card.
10892 *
10893 * @chainable
10894 */
10895 OO.ui.IndexLayout.prototype.selectFirstSelectableCard = function () {
10896 if ( !this.tabSelectWidget.getSelectedItem() ) {
10897 this.tabSelectWidget.selectItem( this.tabSelectWidget.getFirstSelectableItem() );
10898 }
10899
10900 return this;
10901 };
10902
10903 /**
10904 * PanelLayouts expand to cover the entire area of their parent. They can be configured with scrolling, padding,
10905 * and a frame, and are often used together with {@link OO.ui.StackLayout StackLayouts}.
10906 *
10907 * @example
10908 * // Example of a panel layout
10909 * var panel = new OO.ui.PanelLayout( {
10910 * expanded: false,
10911 * framed: true,
10912 * padded: true,
10913 * $content: $( '<p>A panel layout with padding and a frame.</p>' )
10914 * } );
10915 * $( 'body' ).append( panel.$element );
10916 *
10917 * @class
10918 * @extends OO.ui.Layout
10919 *
10920 * @constructor
10921 * @param {Object} [config] Configuration options
10922 * @cfg {boolean} [scrollable=false] Allow vertical scrolling
10923 * @cfg {boolean} [padded=false] Add padding between the content and the edges of the panel.
10924 * @cfg {boolean} [expanded=true] Expand the panel to fill the entire parent element.
10925 * @cfg {boolean} [framed=false] Render the panel with a frame to visually separate it from outside content.
10926 */
10927 OO.ui.PanelLayout = function OoUiPanelLayout( config ) {
10928 // Configuration initialization
10929 config = $.extend( {
10930 scrollable: false,
10931 padded: false,
10932 expanded: true,
10933 framed: false
10934 }, config );
10935
10936 // Parent constructor
10937 OO.ui.PanelLayout.parent.call( this, config );
10938
10939 // Initialization
10940 this.$element.addClass( 'oo-ui-panelLayout' );
10941 if ( config.scrollable ) {
10942 this.$element.addClass( 'oo-ui-panelLayout-scrollable' );
10943 }
10944 if ( config.padded ) {
10945 this.$element.addClass( 'oo-ui-panelLayout-padded' );
10946 }
10947 if ( config.expanded ) {
10948 this.$element.addClass( 'oo-ui-panelLayout-expanded' );
10949 }
10950 if ( config.framed ) {
10951 this.$element.addClass( 'oo-ui-panelLayout-framed' );
10952 }
10953 };
10954
10955 /* Setup */
10956
10957 OO.inheritClass( OO.ui.PanelLayout, OO.ui.Layout );
10958
10959 /* Methods */
10960
10961 /**
10962 * Focus the panel layout
10963 *
10964 * The default implementation just focuses the first focusable element in the panel
10965 */
10966 OO.ui.PanelLayout.prototype.focus = function () {
10967 OO.ui.findFocusable( this.$element ).focus();
10968 };
10969
10970 /**
10971 * CardLayouts are used within {@link OO.ui.IndexLayout index layouts} to create cards that users can select and display
10972 * from the index's optional {@link OO.ui.TabSelectWidget tab} navigation. Cards are usually not instantiated directly,
10973 * rather extended to include the required content and functionality.
10974 *
10975 * Each card must have a unique symbolic name, which is passed to the constructor. In addition, the card's tab
10976 * item is customized (with a label) using the #setupTabItem method. See
10977 * {@link OO.ui.IndexLayout IndexLayout} for an example.
10978 *
10979 * @class
10980 * @extends OO.ui.PanelLayout
10981 *
10982 * @constructor
10983 * @param {string} name Unique symbolic name of card
10984 * @param {Object} [config] Configuration options
10985 * @cfg {jQuery|string|Function|OO.ui.HtmlSnippet} [label] Label for card's tab
10986 */
10987 OO.ui.CardLayout = function OoUiCardLayout( name, config ) {
10988 // Allow passing positional parameters inside the config object
10989 if ( OO.isPlainObject( name ) && config === undefined ) {
10990 config = name;
10991 name = config.name;
10992 }
10993
10994 // Configuration initialization
10995 config = $.extend( { scrollable: true }, config );
10996
10997 // Parent constructor
10998 OO.ui.CardLayout.parent.call( this, config );
10999
11000 // Properties
11001 this.name = name;
11002 this.label = config.label;
11003 this.tabItem = null;
11004 this.active = false;
11005
11006 // Initialization
11007 this.$element.addClass( 'oo-ui-cardLayout' );
11008 };
11009
11010 /* Setup */
11011
11012 OO.inheritClass( OO.ui.CardLayout, OO.ui.PanelLayout );
11013
11014 /* Events */
11015
11016 /**
11017 * An 'active' event is emitted when the card becomes active. Cards become active when they are
11018 * shown in a index layout that is configured to display only one card at a time.
11019 *
11020 * @event active
11021 * @param {boolean} active Card is active
11022 */
11023
11024 /* Methods */
11025
11026 /**
11027 * Get the symbolic name of the card.
11028 *
11029 * @return {string} Symbolic name of card
11030 */
11031 OO.ui.CardLayout.prototype.getName = function () {
11032 return this.name;
11033 };
11034
11035 /**
11036 * Check if card is active.
11037 *
11038 * Cards become active when they are shown in a {@link OO.ui.IndexLayout index layout} that is configured to display
11039 * only one card at a time. Additional CSS is applied to the card's tab item to reflect the active state.
11040 *
11041 * @return {boolean} Card is active
11042 */
11043 OO.ui.CardLayout.prototype.isActive = function () {
11044 return this.active;
11045 };
11046
11047 /**
11048 * Get tab item.
11049 *
11050 * The tab item allows users to access the card from the index's tab
11051 * navigation. The tab item itself can be customized (with a label, level, etc.) using the #setupTabItem method.
11052 *
11053 * @return {OO.ui.TabOptionWidget|null} Tab option widget
11054 */
11055 OO.ui.CardLayout.prototype.getTabItem = function () {
11056 return this.tabItem;
11057 };
11058
11059 /**
11060 * Set or unset the tab item.
11061 *
11062 * Specify a {@link OO.ui.TabOptionWidget tab option} to set it,
11063 * or `null` to clear the tab item. To customize the tab item itself (e.g., to set a label or tab
11064 * level), use #setupTabItem instead of this method.
11065 *
11066 * @param {OO.ui.TabOptionWidget|null} tabItem Tab option widget, null to clear
11067 * @chainable
11068 */
11069 OO.ui.CardLayout.prototype.setTabItem = function ( tabItem ) {
11070 this.tabItem = tabItem || null;
11071 if ( tabItem ) {
11072 this.setupTabItem();
11073 }
11074 return this;
11075 };
11076
11077 /**
11078 * Set up the tab item.
11079 *
11080 * Use this method to customize the tab item (e.g., to add a label or tab level). To set or unset
11081 * the tab item itself (with a {@link OO.ui.TabOptionWidget tab option} or `null`), use
11082 * the #setTabItem method instead.
11083 *
11084 * @param {OO.ui.TabOptionWidget} tabItem Tab option widget to set up
11085 * @chainable
11086 */
11087 OO.ui.CardLayout.prototype.setupTabItem = function () {
11088 if ( this.label ) {
11089 this.tabItem.setLabel( this.label );
11090 }
11091 return this;
11092 };
11093
11094 /**
11095 * Set the card to its 'active' state.
11096 *
11097 * Cards become active when they are shown in a index layout that is configured to display only one card at a time. Additional
11098 * CSS is applied to the tab item to reflect the card's active state. Outside of the index
11099 * context, setting the active state on a card does nothing.
11100 *
11101 * @param {boolean} value Card is active
11102 * @fires active
11103 */
11104 OO.ui.CardLayout.prototype.setActive = function ( active ) {
11105 active = !!active;
11106
11107 if ( active !== this.active ) {
11108 this.active = active;
11109 this.$element.toggleClass( 'oo-ui-cardLayout-active', this.active );
11110 this.emit( 'active', this.active );
11111 }
11112 };
11113
11114 /**
11115 * PageLayouts are used within {@link OO.ui.BookletLayout booklet layouts} to create pages that users can select and display
11116 * from the booklet's optional {@link OO.ui.OutlineSelectWidget outline} navigation. Pages are usually not instantiated directly,
11117 * rather extended to include the required content and functionality.
11118 *
11119 * Each page must have a unique symbolic name, which is passed to the constructor. In addition, the page's outline
11120 * item is customized (with a label, outline level, etc.) using the #setupOutlineItem method. See
11121 * {@link OO.ui.BookletLayout BookletLayout} for an example.
11122 *
11123 * @class
11124 * @extends OO.ui.PanelLayout
11125 *
11126 * @constructor
11127 * @param {string} name Unique symbolic name of page
11128 * @param {Object} [config] Configuration options
11129 */
11130 OO.ui.PageLayout = function OoUiPageLayout( name, config ) {
11131 // Allow passing positional parameters inside the config object
11132 if ( OO.isPlainObject( name ) && config === undefined ) {
11133 config = name;
11134 name = config.name;
11135 }
11136
11137 // Configuration initialization
11138 config = $.extend( { scrollable: true }, config );
11139
11140 // Parent constructor
11141 OO.ui.PageLayout.parent.call( this, config );
11142
11143 // Properties
11144 this.name = name;
11145 this.outlineItem = null;
11146 this.active = false;
11147
11148 // Initialization
11149 this.$element.addClass( 'oo-ui-pageLayout' );
11150 };
11151
11152 /* Setup */
11153
11154 OO.inheritClass( OO.ui.PageLayout, OO.ui.PanelLayout );
11155
11156 /* Events */
11157
11158 /**
11159 * An 'active' event is emitted when the page becomes active. Pages become active when they are
11160 * shown in a booklet layout that is configured to display only one page at a time.
11161 *
11162 * @event active
11163 * @param {boolean} active Page is active
11164 */
11165
11166 /* Methods */
11167
11168 /**
11169 * Get the symbolic name of the page.
11170 *
11171 * @return {string} Symbolic name of page
11172 */
11173 OO.ui.PageLayout.prototype.getName = function () {
11174 return this.name;
11175 };
11176
11177 /**
11178 * Check if page is active.
11179 *
11180 * Pages become active when they are shown in a {@link OO.ui.BookletLayout booklet layout} that is configured to display
11181 * only one page at a time. Additional CSS is applied to the page's outline item to reflect the active state.
11182 *
11183 * @return {boolean} Page is active
11184 */
11185 OO.ui.PageLayout.prototype.isActive = function () {
11186 return this.active;
11187 };
11188
11189 /**
11190 * Get outline item.
11191 *
11192 * The outline item allows users to access the page from the booklet's outline
11193 * navigation. The outline item itself can be customized (with a label, level, etc.) using the #setupOutlineItem method.
11194 *
11195 * @return {OO.ui.OutlineOptionWidget|null} Outline option widget
11196 */
11197 OO.ui.PageLayout.prototype.getOutlineItem = function () {
11198 return this.outlineItem;
11199 };
11200
11201 /**
11202 * Set or unset the outline item.
11203 *
11204 * Specify an {@link OO.ui.OutlineOptionWidget outline option} to set it,
11205 * or `null` to clear the outline item. To customize the outline item itself (e.g., to set a label or outline
11206 * level), use #setupOutlineItem instead of this method.
11207 *
11208 * @param {OO.ui.OutlineOptionWidget|null} outlineItem Outline option widget, null to clear
11209 * @chainable
11210 */
11211 OO.ui.PageLayout.prototype.setOutlineItem = function ( outlineItem ) {
11212 this.outlineItem = outlineItem || null;
11213 if ( outlineItem ) {
11214 this.setupOutlineItem();
11215 }
11216 return this;
11217 };
11218
11219 /**
11220 * Set up the outline item.
11221 *
11222 * Use this method to customize the outline item (e.g., to add a label or outline level). To set or unset
11223 * the outline item itself (with an {@link OO.ui.OutlineOptionWidget outline option} or `null`), use
11224 * the #setOutlineItem method instead.
11225 *
11226 * @param {OO.ui.OutlineOptionWidget} outlineItem Outline option widget to set up
11227 * @chainable
11228 */
11229 OO.ui.PageLayout.prototype.setupOutlineItem = function () {
11230 return this;
11231 };
11232
11233 /**
11234 * Set the page to its 'active' state.
11235 *
11236 * Pages become active when they are shown in a booklet layout that is configured to display only one page at a time. Additional
11237 * CSS is applied to the outline item to reflect the page's active state. Outside of the booklet
11238 * context, setting the active state on a page does nothing.
11239 *
11240 * @param {boolean} value Page is active
11241 * @fires active
11242 */
11243 OO.ui.PageLayout.prototype.setActive = function ( active ) {
11244 active = !!active;
11245
11246 if ( active !== this.active ) {
11247 this.active = active;
11248 this.$element.toggleClass( 'oo-ui-pageLayout-active', active );
11249 this.emit( 'active', this.active );
11250 }
11251 };
11252
11253 /**
11254 * StackLayouts contain a series of {@link OO.ui.PanelLayout panel layouts}. By default, only one panel is displayed
11255 * at a time, though the stack layout can also be configured to show all contained panels, one after another,
11256 * by setting the #continuous option to 'true'.
11257 *
11258 * @example
11259 * // A stack layout with two panels, configured to be displayed continously
11260 * var myStack = new OO.ui.StackLayout( {
11261 * items: [
11262 * new OO.ui.PanelLayout( {
11263 * $content: $( '<p>Panel One</p>' ),
11264 * padded: true,
11265 * framed: true
11266 * } ),
11267 * new OO.ui.PanelLayout( {
11268 * $content: $( '<p>Panel Two</p>' ),
11269 * padded: true,
11270 * framed: true
11271 * } )
11272 * ],
11273 * continuous: true
11274 * } );
11275 * $( 'body' ).append( myStack.$element );
11276 *
11277 * @class
11278 * @extends OO.ui.PanelLayout
11279 * @mixins OO.ui.mixin.GroupElement
11280 *
11281 * @constructor
11282 * @param {Object} [config] Configuration options
11283 * @cfg {boolean} [continuous=false] Show all panels, one after another. By default, only one panel is displayed at a time.
11284 * @cfg {OO.ui.Layout[]} [items] Panel layouts to add to the stack layout.
11285 */
11286 OO.ui.StackLayout = function OoUiStackLayout( config ) {
11287 // Configuration initialization
11288 config = $.extend( { scrollable: true }, config );
11289
11290 // Parent constructor
11291 OO.ui.StackLayout.parent.call( this, config );
11292
11293 // Mixin constructors
11294 OO.ui.mixin.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) );
11295
11296 // Properties
11297 this.currentItem = null;
11298 this.continuous = !!config.continuous;
11299
11300 // Initialization
11301 this.$element.addClass( 'oo-ui-stackLayout' );
11302 if ( this.continuous ) {
11303 this.$element.addClass( 'oo-ui-stackLayout-continuous' );
11304 this.$element.on( 'scroll', OO.ui.debounce( this.onScroll.bind( this ), 250 ) );
11305 }
11306 if ( Array.isArray( config.items ) ) {
11307 this.addItems( config.items );
11308 }
11309 };
11310
11311 /* Setup */
11312
11313 OO.inheritClass( OO.ui.StackLayout, OO.ui.PanelLayout );
11314 OO.mixinClass( OO.ui.StackLayout, OO.ui.mixin.GroupElement );
11315
11316 /* Events */
11317
11318 /**
11319 * A 'set' event is emitted when panels are {@link #addItems added}, {@link #removeItems removed},
11320 * {@link #clearItems cleared} or {@link #setItem displayed}.
11321 *
11322 * @event set
11323 * @param {OO.ui.Layout|null} item Current panel or `null` if no panel is shown
11324 */
11325
11326 /**
11327 * When used in continuous mode, this event is emitted when the user scrolls down
11328 * far enough such that currentItem is no longer visible.
11329 *
11330 * @event visibleItemChange
11331 * @param {OO.ui.PanelLayout} panel The next visible item in the layout
11332 */
11333
11334 /* Methods */
11335
11336 /**
11337 * Handle scroll events from the layout element
11338 *
11339 * @param {jQuery.Event} e
11340 * @fires visibleItemChange
11341 */
11342 OO.ui.StackLayout.prototype.onScroll = function () {
11343 var currentRect,
11344 len = this.items.length,
11345 currentIndex = this.items.indexOf( this.currentItem ),
11346 newIndex = currentIndex,
11347 containerRect = this.$element[ 0 ].getBoundingClientRect();
11348
11349 if ( !containerRect || ( !containerRect.top && !containerRect.bottom ) ) {
11350 // Can't get bounding rect, possibly not attached.
11351 return;
11352 }
11353
11354 function getRect( item ) {
11355 return item.$element[ 0 ].getBoundingClientRect();
11356 }
11357
11358 function isVisible( item ) {
11359 var rect = getRect( item );
11360 return rect.bottom > containerRect.top && rect.top < containerRect.bottom;
11361 }
11362
11363 currentRect = getRect( this.currentItem );
11364
11365 if ( currentRect.bottom < containerRect.top ) {
11366 // Scrolled down past current item
11367 while ( ++newIndex < len ) {
11368 if ( isVisible( this.items[ newIndex ] ) ) {
11369 break;
11370 }
11371 }
11372 } else if ( currentRect.top > containerRect.bottom ) {
11373 // Scrolled up past current item
11374 while ( --newIndex >= 0 ) {
11375 if ( isVisible( this.items[ newIndex ] ) ) {
11376 break;
11377 }
11378 }
11379 }
11380
11381 if ( newIndex !== currentIndex ) {
11382 this.emit( 'visibleItemChange', this.items[ newIndex ] );
11383 }
11384 };
11385
11386 /**
11387 * Get the current panel.
11388 *
11389 * @return {OO.ui.Layout|null}
11390 */
11391 OO.ui.StackLayout.prototype.getCurrentItem = function () {
11392 return this.currentItem;
11393 };
11394
11395 /**
11396 * Unset the current item.
11397 *
11398 * @private
11399 * @param {OO.ui.StackLayout} layout
11400 * @fires set
11401 */
11402 OO.ui.StackLayout.prototype.unsetCurrentItem = function () {
11403 var prevItem = this.currentItem;
11404 if ( prevItem === null ) {
11405 return;
11406 }
11407
11408 this.currentItem = null;
11409 this.emit( 'set', null );
11410 };
11411
11412 /**
11413 * Add panel layouts to the stack layout.
11414 *
11415 * Panels will be added to the end of the stack layout array unless the optional index parameter specifies a different
11416 * insertion point. Adding a panel that is already in the stack will move it to the end of the array or the point specified
11417 * by the index.
11418 *
11419 * @param {OO.ui.Layout[]} items Panels to add
11420 * @param {number} [index] Index of the insertion point
11421 * @chainable
11422 */
11423 OO.ui.StackLayout.prototype.addItems = function ( items, index ) {
11424 // Update the visibility
11425 this.updateHiddenState( items, this.currentItem );
11426
11427 // Mixin method
11428 OO.ui.mixin.GroupElement.prototype.addItems.call( this, items, index );
11429
11430 if ( !this.currentItem && items.length ) {
11431 this.setItem( items[ 0 ] );
11432 }
11433
11434 return this;
11435 };
11436
11437 /**
11438 * Remove the specified panels from the stack layout.
11439 *
11440 * Removed panels are detached from the DOM, not removed, so that they may be reused. To remove all panels,
11441 * you may wish to use the #clearItems method instead.
11442 *
11443 * @param {OO.ui.Layout[]} items Panels to remove
11444 * @chainable
11445 * @fires set
11446 */
11447 OO.ui.StackLayout.prototype.removeItems = function ( items ) {
11448 // Mixin method
11449 OO.ui.mixin.GroupElement.prototype.removeItems.call( this, items );
11450
11451 if ( items.indexOf( this.currentItem ) !== -1 ) {
11452 if ( this.items.length ) {
11453 this.setItem( this.items[ 0 ] );
11454 } else {
11455 this.unsetCurrentItem();
11456 }
11457 }
11458
11459 return this;
11460 };
11461
11462 /**
11463 * Clear all panels from the stack layout.
11464 *
11465 * Cleared panels are detached from the DOM, not removed, so that they may be reused. To remove only
11466 * a subset of panels, use the #removeItems method.
11467 *
11468 * @chainable
11469 * @fires set
11470 */
11471 OO.ui.StackLayout.prototype.clearItems = function () {
11472 this.unsetCurrentItem();
11473 OO.ui.mixin.GroupElement.prototype.clearItems.call( this );
11474
11475 return this;
11476 };
11477
11478 /**
11479 * Show the specified panel.
11480 *
11481 * If another panel is currently displayed, it will be hidden.
11482 *
11483 * @param {OO.ui.Layout} item Panel to show
11484 * @chainable
11485 * @fires set
11486 */
11487 OO.ui.StackLayout.prototype.setItem = function ( item ) {
11488 if ( item !== this.currentItem ) {
11489 this.updateHiddenState( this.items, item );
11490
11491 if ( this.items.indexOf( item ) !== -1 ) {
11492 this.currentItem = item;
11493 this.emit( 'set', item );
11494 } else {
11495 this.unsetCurrentItem();
11496 }
11497 }
11498
11499 return this;
11500 };
11501
11502 /**
11503 * Update the visibility of all items in case of non-continuous view.
11504 *
11505 * Ensure all items are hidden except for the selected one.
11506 * This method does nothing when the stack is continuous.
11507 *
11508 * @private
11509 * @param {OO.ui.Layout[]} items Item list iterate over
11510 * @param {OO.ui.Layout} [selectedItem] Selected item to show
11511 */
11512 OO.ui.StackLayout.prototype.updateHiddenState = function ( items, selectedItem ) {
11513 var i, len;
11514
11515 if ( !this.continuous ) {
11516 for ( i = 0, len = items.length; i < len; i++ ) {
11517 if ( !selectedItem || selectedItem !== items[ i ] ) {
11518 items[ i ].$element.addClass( 'oo-ui-element-hidden' );
11519 }
11520 }
11521 if ( selectedItem ) {
11522 selectedItem.$element.removeClass( 'oo-ui-element-hidden' );
11523 }
11524 }
11525 };
11526
11527 /**
11528 * HorizontalLayout arranges its contents in a single line (using `display: inline-block` for its
11529 * items), with small margins between them. Convenient when you need to put a number of block-level
11530 * widgets on a single line next to each other.
11531 *
11532 * Note that inline elements, such as OO.ui.ButtonWidgets, do not need this wrapper.
11533 *
11534 * @example
11535 * // HorizontalLayout with a text input and a label
11536 * var layout = new OO.ui.HorizontalLayout( {
11537 * items: [
11538 * new OO.ui.LabelWidget( { label: 'Label' } ),
11539 * new OO.ui.TextInputWidget( { value: 'Text' } )
11540 * ]
11541 * } );
11542 * $( 'body' ).append( layout.$element );
11543 *
11544 * @class
11545 * @extends OO.ui.Layout
11546 * @mixins OO.ui.mixin.GroupElement
11547 *
11548 * @constructor
11549 * @param {Object} [config] Configuration options
11550 * @cfg {OO.ui.Widget[]|OO.ui.Layout[]} [items] Widgets or other layouts to add to the layout.
11551 */
11552 OO.ui.HorizontalLayout = function OoUiHorizontalLayout( config ) {
11553 // Configuration initialization
11554 config = config || {};
11555
11556 // Parent constructor
11557 OO.ui.HorizontalLayout.parent.call( this, config );
11558
11559 // Mixin constructors
11560 OO.ui.mixin.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) );
11561
11562 // Initialization
11563 this.$element.addClass( 'oo-ui-horizontalLayout' );
11564 if ( Array.isArray( config.items ) ) {
11565 this.addItems( config.items );
11566 }
11567 };
11568
11569 /* Setup */
11570
11571 OO.inheritClass( OO.ui.HorizontalLayout, OO.ui.Layout );
11572 OO.mixinClass( OO.ui.HorizontalLayout, OO.ui.mixin.GroupElement );
11573
11574 /**
11575 * BarToolGroups are one of three types of {@link OO.ui.ToolGroup toolgroups} that are used to
11576 * create {@link OO.ui.Toolbar toolbars} (the other types of groups are {@link OO.ui.MenuToolGroup MenuToolGroup}
11577 * and {@link OO.ui.ListToolGroup ListToolGroup}). The {@link OO.ui.Tool tools} in a BarToolGroup are
11578 * displayed by icon in a single row. The title of the tool is displayed when users move the mouse over
11579 * the tool.
11580 *
11581 * BarToolGroups are created by a {@link OO.ui.ToolGroupFactory tool group factory} when the toolbar is
11582 * set up.
11583 *
11584 * @example
11585 * // Example of a BarToolGroup with two tools
11586 * var toolFactory = new OO.ui.ToolFactory();
11587 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
11588 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
11589 *
11590 * // We will be placing status text in this element when tools are used
11591 * var $area = $( '<p>' ).text( 'Example of a BarToolGroup with two tools.' );
11592 *
11593 * // Define the tools that we're going to place in our toolbar
11594 *
11595 * // Create a class inheriting from OO.ui.Tool
11596 * function SearchTool() {
11597 * SearchTool.parent.apply( this, arguments );
11598 * }
11599 * OO.inheritClass( SearchTool, OO.ui.Tool );
11600 * // Each tool must have a 'name' (used as an internal identifier, see later) and at least one
11601 * // of 'icon' and 'title' (displayed icon and text).
11602 * SearchTool.static.name = 'search';
11603 * SearchTool.static.icon = 'search';
11604 * SearchTool.static.title = 'Search...';
11605 * // Defines the action that will happen when this tool is selected (clicked).
11606 * SearchTool.prototype.onSelect = function () {
11607 * $area.text( 'Search tool clicked!' );
11608 * // Never display this tool as "active" (selected).
11609 * this.setActive( false );
11610 * };
11611 * SearchTool.prototype.onUpdateState = function () {};
11612 * // Make this tool available in our toolFactory and thus our toolbar
11613 * toolFactory.register( SearchTool );
11614 *
11615 * // This is a PopupTool. Rather than having a custom 'onSelect' action, it will display a
11616 * // little popup window (a PopupWidget).
11617 * function HelpTool( toolGroup, config ) {
11618 * OO.ui.PopupTool.call( this, toolGroup, $.extend( { popup: {
11619 * padded: true,
11620 * label: 'Help',
11621 * head: true
11622 * } }, config ) );
11623 * this.popup.$body.append( '<p>I am helpful!</p>' );
11624 * }
11625 * OO.inheritClass( HelpTool, OO.ui.PopupTool );
11626 * HelpTool.static.name = 'help';
11627 * HelpTool.static.icon = 'help';
11628 * HelpTool.static.title = 'Help';
11629 * toolFactory.register( HelpTool );
11630 *
11631 * // Finally define which tools and in what order appear in the toolbar. Each tool may only be
11632 * // used once (but not all defined tools must be used).
11633 * toolbar.setup( [
11634 * {
11635 * // 'bar' tool groups display tools by icon only
11636 * type: 'bar',
11637 * include: [ 'search', 'help' ]
11638 * }
11639 * ] );
11640 *
11641 * // Create some UI around the toolbar and place it in the document
11642 * var frame = new OO.ui.PanelLayout( {
11643 * expanded: false,
11644 * framed: true
11645 * } );
11646 * var contentFrame = new OO.ui.PanelLayout( {
11647 * expanded: false,
11648 * padded: true
11649 * } );
11650 * frame.$element.append(
11651 * toolbar.$element,
11652 * contentFrame.$element.append( $area )
11653 * );
11654 * $( 'body' ).append( frame.$element );
11655 *
11656 * // Here is where the toolbar is actually built. This must be done after inserting it into the
11657 * // document.
11658 * toolbar.initialize();
11659 *
11660 * For more information about how to add tools to a bar tool group, please see {@link OO.ui.ToolGroup toolgroup}.
11661 * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki][1].
11662 *
11663 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
11664 *
11665 * @class
11666 * @extends OO.ui.ToolGroup
11667 *
11668 * @constructor
11669 * @param {OO.ui.Toolbar} toolbar
11670 * @param {Object} [config] Configuration options
11671 */
11672 OO.ui.BarToolGroup = function OoUiBarToolGroup( toolbar, config ) {
11673 // Allow passing positional parameters inside the config object
11674 if ( OO.isPlainObject( toolbar ) && config === undefined ) {
11675 config = toolbar;
11676 toolbar = config.toolbar;
11677 }
11678
11679 // Parent constructor
11680 OO.ui.BarToolGroup.parent.call( this, toolbar, config );
11681
11682 // Initialization
11683 this.$element.addClass( 'oo-ui-barToolGroup' );
11684 };
11685
11686 /* Setup */
11687
11688 OO.inheritClass( OO.ui.BarToolGroup, OO.ui.ToolGroup );
11689
11690 /* Static Properties */
11691
11692 OO.ui.BarToolGroup.static.titleTooltips = true;
11693
11694 OO.ui.BarToolGroup.static.accelTooltips = true;
11695
11696 OO.ui.BarToolGroup.static.name = 'bar';
11697
11698 /**
11699 * PopupToolGroup is an abstract base class used by both {@link OO.ui.MenuToolGroup MenuToolGroup}
11700 * and {@link OO.ui.ListToolGroup ListToolGroup} to provide a popup--an overlaid menu or list of tools with an
11701 * optional icon and label. This class can be used for other base classes that also use this functionality.
11702 *
11703 * @abstract
11704 * @class
11705 * @extends OO.ui.ToolGroup
11706 * @mixins OO.ui.mixin.IconElement
11707 * @mixins OO.ui.mixin.IndicatorElement
11708 * @mixins OO.ui.mixin.LabelElement
11709 * @mixins OO.ui.mixin.TitledElement
11710 * @mixins OO.ui.mixin.ClippableElement
11711 * @mixins OO.ui.mixin.TabIndexedElement
11712 *
11713 * @constructor
11714 * @param {OO.ui.Toolbar} toolbar
11715 * @param {Object} [config] Configuration options
11716 * @cfg {string} [header] Text to display at the top of the popup
11717 */
11718 OO.ui.PopupToolGroup = function OoUiPopupToolGroup( toolbar, config ) {
11719 // Allow passing positional parameters inside the config object
11720 if ( OO.isPlainObject( toolbar ) && config === undefined ) {
11721 config = toolbar;
11722 toolbar = config.toolbar;
11723 }
11724
11725 // Configuration initialization
11726 config = config || {};
11727
11728 // Parent constructor
11729 OO.ui.PopupToolGroup.parent.call( this, toolbar, config );
11730
11731 // Properties
11732 this.active = false;
11733 this.dragging = false;
11734 this.onBlurHandler = this.onBlur.bind( this );
11735 this.$handle = $( '<span>' );
11736
11737 // Mixin constructors
11738 OO.ui.mixin.IconElement.call( this, config );
11739 OO.ui.mixin.IndicatorElement.call( this, config );
11740 OO.ui.mixin.LabelElement.call( this, config );
11741 OO.ui.mixin.TitledElement.call( this, config );
11742 OO.ui.mixin.ClippableElement.call( this, $.extend( {}, config, { $clippable: this.$group } ) );
11743 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$handle } ) );
11744
11745 // Events
11746 this.$handle.on( {
11747 keydown: this.onHandleMouseKeyDown.bind( this ),
11748 keyup: this.onHandleMouseKeyUp.bind( this ),
11749 mousedown: this.onHandleMouseKeyDown.bind( this ),
11750 mouseup: this.onHandleMouseKeyUp.bind( this )
11751 } );
11752
11753 // Initialization
11754 this.$handle
11755 .addClass( 'oo-ui-popupToolGroup-handle' )
11756 .append( this.$icon, this.$label, this.$indicator );
11757 // If the pop-up should have a header, add it to the top of the toolGroup.
11758 // Note: If this feature is useful for other widgets, we could abstract it into an
11759 // OO.ui.HeaderedElement mixin constructor.
11760 if ( config.header !== undefined ) {
11761 this.$group
11762 .prepend( $( '<span>' )
11763 .addClass( 'oo-ui-popupToolGroup-header' )
11764 .text( config.header )
11765 );
11766 }
11767 this.$element
11768 .addClass( 'oo-ui-popupToolGroup' )
11769 .prepend( this.$handle );
11770 };
11771
11772 /* Setup */
11773
11774 OO.inheritClass( OO.ui.PopupToolGroup, OO.ui.ToolGroup );
11775 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.mixin.IconElement );
11776 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.mixin.IndicatorElement );
11777 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.mixin.LabelElement );
11778 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.mixin.TitledElement );
11779 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.mixin.ClippableElement );
11780 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.mixin.TabIndexedElement );
11781
11782 /* Methods */
11783
11784 /**
11785 * @inheritdoc
11786 */
11787 OO.ui.PopupToolGroup.prototype.setDisabled = function () {
11788 // Parent method
11789 OO.ui.PopupToolGroup.parent.prototype.setDisabled.apply( this, arguments );
11790
11791 if ( this.isDisabled() && this.isElementAttached() ) {
11792 this.setActive( false );
11793 }
11794 };
11795
11796 /**
11797 * Handle focus being lost.
11798 *
11799 * The event is actually generated from a mouseup/keyup, so it is not a normal blur event object.
11800 *
11801 * @protected
11802 * @param {jQuery.Event} e Mouse up or key up event
11803 */
11804 OO.ui.PopupToolGroup.prototype.onBlur = function ( e ) {
11805 // Only deactivate when clicking outside the dropdown element
11806 if ( $( e.target ).closest( '.oo-ui-popupToolGroup' )[ 0 ] !== this.$element[ 0 ] ) {
11807 this.setActive( false );
11808 }
11809 };
11810
11811 /**
11812 * @inheritdoc
11813 */
11814 OO.ui.PopupToolGroup.prototype.onMouseKeyUp = function ( e ) {
11815 // Only close toolgroup when a tool was actually selected
11816 if (
11817 !this.isDisabled() && this.pressed && this.pressed === this.getTargetTool( e ) &&
11818 ( e.which === 1 || e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
11819 ) {
11820 this.setActive( false );
11821 }
11822 return OO.ui.PopupToolGroup.parent.prototype.onMouseKeyUp.call( this, e );
11823 };
11824
11825 /**
11826 * Handle mouse up and key up events.
11827 *
11828 * @protected
11829 * @param {jQuery.Event} e Mouse up or key up event
11830 */
11831 OO.ui.PopupToolGroup.prototype.onHandleMouseKeyUp = function ( e ) {
11832 if (
11833 !this.isDisabled() &&
11834 ( e.which === 1 || e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
11835 ) {
11836 return false;
11837 }
11838 };
11839
11840 /**
11841 * Handle mouse down and key down events.
11842 *
11843 * @protected
11844 * @param {jQuery.Event} e Mouse down or key down event
11845 */
11846 OO.ui.PopupToolGroup.prototype.onHandleMouseKeyDown = function ( e ) {
11847 if (
11848 !this.isDisabled() &&
11849 ( e.which === 1 || e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
11850 ) {
11851 this.setActive( !this.active );
11852 return false;
11853 }
11854 };
11855
11856 /**
11857 * Switch into 'active' mode.
11858 *
11859 * When active, the popup is visible. A mouseup event anywhere in the document will trigger
11860 * deactivation.
11861 */
11862 OO.ui.PopupToolGroup.prototype.setActive = function ( value ) {
11863 var containerWidth, containerLeft;
11864 value = !!value;
11865 if ( this.active !== value ) {
11866 this.active = value;
11867 if ( value ) {
11868 OO.ui.addCaptureEventListener( this.getElementDocument(), 'mouseup', this.onBlurHandler );
11869 OO.ui.addCaptureEventListener( this.getElementDocument(), 'keyup', this.onBlurHandler );
11870
11871 this.$clippable.css( 'left', '' );
11872 // Try anchoring the popup to the left first
11873 this.$element.addClass( 'oo-ui-popupToolGroup-active oo-ui-popupToolGroup-left' );
11874 this.toggleClipping( true );
11875 if ( this.isClippedHorizontally() ) {
11876 // Anchoring to the left caused the popup to clip, so anchor it to the right instead
11877 this.toggleClipping( false );
11878 this.$element
11879 .removeClass( 'oo-ui-popupToolGroup-left' )
11880 .addClass( 'oo-ui-popupToolGroup-right' );
11881 this.toggleClipping( true );
11882 }
11883 if ( this.isClippedHorizontally() ) {
11884 // Anchoring to the right also caused the popup to clip, so just make it fill the container
11885 containerWidth = this.$clippableScrollableContainer.width();
11886 containerLeft = this.$clippableScrollableContainer.offset().left;
11887
11888 this.toggleClipping( false );
11889 this.$element.removeClass( 'oo-ui-popupToolGroup-right' );
11890
11891 this.$clippable.css( {
11892 left: -( this.$element.offset().left - containerLeft ),
11893 width: containerWidth
11894 } );
11895 }
11896 } else {
11897 OO.ui.removeCaptureEventListener( this.getElementDocument(), 'mouseup', this.onBlurHandler );
11898 OO.ui.removeCaptureEventListener( this.getElementDocument(), 'keyup', this.onBlurHandler );
11899 this.$element.removeClass(
11900 'oo-ui-popupToolGroup-active oo-ui-popupToolGroup-left oo-ui-popupToolGroup-right'
11901 );
11902 this.toggleClipping( false );
11903 }
11904 }
11905 };
11906
11907 /**
11908 * ListToolGroups are one of three types of {@link OO.ui.ToolGroup toolgroups} that are used to
11909 * create {@link OO.ui.Toolbar toolbars} (the other types of groups are {@link OO.ui.MenuToolGroup MenuToolGroup}
11910 * and {@link OO.ui.BarToolGroup BarToolGroup}). The {@link OO.ui.Tool tools} in a ListToolGroup are displayed
11911 * by label in a dropdown menu. The title of the tool is used as the label text. The menu itself can be configured
11912 * with a label, icon, indicator, header, and title.
11913 *
11914 * ListToolGroups can be configured to be expanded and collapsed. Collapsed lists will have a ‘More’ option that
11915 * users can select to see the full list of tools. If a collapsed toolgroup is expanded, a ‘Fewer’ option permits
11916 * users to collapse the list again.
11917 *
11918 * ListToolGroups are created by a {@link OO.ui.ToolGroupFactory toolgroup factory} when the toolbar is set up. The factory
11919 * requires the ListToolGroup's symbolic name, 'list', which is specified along with the other configurations. For more
11920 * information about how to add tools to a ListToolGroup, please see {@link OO.ui.ToolGroup toolgroup}.
11921 *
11922 * @example
11923 * // Example of a ListToolGroup
11924 * var toolFactory = new OO.ui.ToolFactory();
11925 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
11926 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
11927 *
11928 * // Configure and register two tools
11929 * function SettingsTool() {
11930 * SettingsTool.parent.apply( this, arguments );
11931 * }
11932 * OO.inheritClass( SettingsTool, OO.ui.Tool );
11933 * SettingsTool.static.name = 'settings';
11934 * SettingsTool.static.icon = 'settings';
11935 * SettingsTool.static.title = 'Change settings';
11936 * SettingsTool.prototype.onSelect = function () {
11937 * this.setActive( false );
11938 * };
11939 * SettingsTool.prototype.onUpdateState = function () {};
11940 * toolFactory.register( SettingsTool );
11941 * // Register two more tools, nothing interesting here
11942 * function StuffTool() {
11943 * StuffTool.parent.apply( this, arguments );
11944 * }
11945 * OO.inheritClass( StuffTool, OO.ui.Tool );
11946 * StuffTool.static.name = 'stuff';
11947 * StuffTool.static.icon = 'search';
11948 * StuffTool.static.title = 'Change the world';
11949 * StuffTool.prototype.onSelect = function () {
11950 * this.setActive( false );
11951 * };
11952 * StuffTool.prototype.onUpdateState = function () {};
11953 * toolFactory.register( StuffTool );
11954 * toolbar.setup( [
11955 * {
11956 * // Configurations for list toolgroup.
11957 * type: 'list',
11958 * label: 'ListToolGroup',
11959 * indicator: 'down',
11960 * icon: 'ellipsis',
11961 * title: 'This is the title, displayed when user moves the mouse over the list toolgroup',
11962 * header: 'This is the header',
11963 * include: [ 'settings', 'stuff' ],
11964 * allowCollapse: ['stuff']
11965 * }
11966 * ] );
11967 *
11968 * // Create some UI around the toolbar and place it in the document
11969 * var frame = new OO.ui.PanelLayout( {
11970 * expanded: false,
11971 * framed: true
11972 * } );
11973 * frame.$element.append(
11974 * toolbar.$element
11975 * );
11976 * $( 'body' ).append( frame.$element );
11977 * // Build the toolbar. This must be done after the toolbar has been appended to the document.
11978 * toolbar.initialize();
11979 *
11980 * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki][1].
11981 *
11982 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
11983 *
11984 * @class
11985 * @extends OO.ui.PopupToolGroup
11986 *
11987 * @constructor
11988 * @param {OO.ui.Toolbar} toolbar
11989 * @param {Object} [config] Configuration options
11990 * @cfg {Array} [allowCollapse] Allow the specified tools to be collapsed. By default, collapsible tools
11991 * will only be displayed if users click the ‘More’ option displayed at the bottom of the list. If
11992 * the list is expanded, a ‘Fewer’ option permits users to collapse the list again. Any tools that
11993 * are included in the toolgroup, but are not designated as collapsible, will always be displayed.
11994 * To open a collapsible list in its expanded state, set #expanded to 'true'.
11995 * @cfg {Array} [forceExpand] Expand the specified tools. All other tools will be designated as collapsible.
11996 * Unless #expanded is set to true, the collapsible tools will be collapsed when the list is first opened.
11997 * @cfg {boolean} [expanded=false] Expand collapsible tools. This config is only relevant if tools have
11998 * been designated as collapsible. When expanded is set to true, all tools in the group will be displayed
11999 * when the list is first opened. Users can collapse the list with a ‘Fewer’ option at the bottom.
12000 */
12001 OO.ui.ListToolGroup = function OoUiListToolGroup( toolbar, config ) {
12002 // Allow passing positional parameters inside the config object
12003 if ( OO.isPlainObject( toolbar ) && config === undefined ) {
12004 config = toolbar;
12005 toolbar = config.toolbar;
12006 }
12007
12008 // Configuration initialization
12009 config = config || {};
12010
12011 // Properties (must be set before parent constructor, which calls #populate)
12012 this.allowCollapse = config.allowCollapse;
12013 this.forceExpand = config.forceExpand;
12014 this.expanded = config.expanded !== undefined ? config.expanded : false;
12015 this.collapsibleTools = [];
12016
12017 // Parent constructor
12018 OO.ui.ListToolGroup.parent.call( this, toolbar, config );
12019
12020 // Initialization
12021 this.$element.addClass( 'oo-ui-listToolGroup' );
12022 };
12023
12024 /* Setup */
12025
12026 OO.inheritClass( OO.ui.ListToolGroup, OO.ui.PopupToolGroup );
12027
12028 /* Static Properties */
12029
12030 OO.ui.ListToolGroup.static.name = 'list';
12031
12032 /* Methods */
12033
12034 /**
12035 * @inheritdoc
12036 */
12037 OO.ui.ListToolGroup.prototype.populate = function () {
12038 var i, len, allowCollapse = [];
12039
12040 OO.ui.ListToolGroup.parent.prototype.populate.call( this );
12041
12042 // Update the list of collapsible tools
12043 if ( this.allowCollapse !== undefined ) {
12044 allowCollapse = this.allowCollapse;
12045 } else if ( this.forceExpand !== undefined ) {
12046 allowCollapse = OO.simpleArrayDifference( Object.keys( this.tools ), this.forceExpand );
12047 }
12048
12049 this.collapsibleTools = [];
12050 for ( i = 0, len = allowCollapse.length; i < len; i++ ) {
12051 if ( this.tools[ allowCollapse[ i ] ] !== undefined ) {
12052 this.collapsibleTools.push( this.tools[ allowCollapse[ i ] ] );
12053 }
12054 }
12055
12056 // Keep at the end, even when tools are added
12057 this.$group.append( this.getExpandCollapseTool().$element );
12058
12059 this.getExpandCollapseTool().toggle( this.collapsibleTools.length !== 0 );
12060 this.updateCollapsibleState();
12061 };
12062
12063 OO.ui.ListToolGroup.prototype.getExpandCollapseTool = function () {
12064 var ExpandCollapseTool;
12065 if ( this.expandCollapseTool === undefined ) {
12066 ExpandCollapseTool = function () {
12067 ExpandCollapseTool.parent.apply( this, arguments );
12068 };
12069
12070 OO.inheritClass( ExpandCollapseTool, OO.ui.Tool );
12071
12072 ExpandCollapseTool.prototype.onSelect = function () {
12073 this.toolGroup.expanded = !this.toolGroup.expanded;
12074 this.toolGroup.updateCollapsibleState();
12075 this.setActive( false );
12076 };
12077 ExpandCollapseTool.prototype.onUpdateState = function () {
12078 // Do nothing. Tool interface requires an implementation of this function.
12079 };
12080
12081 ExpandCollapseTool.static.name = 'more-fewer';
12082
12083 this.expandCollapseTool = new ExpandCollapseTool( this );
12084 }
12085 return this.expandCollapseTool;
12086 };
12087
12088 /**
12089 * @inheritdoc
12090 */
12091 OO.ui.ListToolGroup.prototype.onMouseKeyUp = function ( e ) {
12092 // Do not close the popup when the user wants to show more/fewer tools
12093 if (
12094 $( e.target ).closest( '.oo-ui-tool-name-more-fewer' ).length &&
12095 ( e.which === 1 || e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
12096 ) {
12097 // HACK: Prevent the popup list from being hidden. Skip the PopupToolGroup implementation (which
12098 // hides the popup list when a tool is selected) and call ToolGroup's implementation directly.
12099 return OO.ui.ListToolGroup.parent.parent.prototype.onMouseKeyUp.call( this, e );
12100 } else {
12101 return OO.ui.ListToolGroup.parent.prototype.onMouseKeyUp.call( this, e );
12102 }
12103 };
12104
12105 OO.ui.ListToolGroup.prototype.updateCollapsibleState = function () {
12106 var i, len;
12107
12108 this.getExpandCollapseTool()
12109 .setIcon( this.expanded ? 'collapse' : 'expand' )
12110 .setTitle( OO.ui.msg( this.expanded ? 'ooui-toolgroup-collapse' : 'ooui-toolgroup-expand' ) );
12111
12112 for ( i = 0, len = this.collapsibleTools.length; i < len; i++ ) {
12113 this.collapsibleTools[ i ].toggle( this.expanded );
12114 }
12115 };
12116
12117 /**
12118 * MenuToolGroups are one of three types of {@link OO.ui.ToolGroup toolgroups} that are used to
12119 * create {@link OO.ui.Toolbar toolbars} (the other types of groups are {@link OO.ui.BarToolGroup BarToolGroup}
12120 * and {@link OO.ui.ListToolGroup ListToolGroup}). MenuToolGroups contain selectable {@link OO.ui.Tool tools},
12121 * which are displayed by label in a dropdown menu. The tool's title is used as the label text, and the
12122 * menu label is updated to reflect which tool or tools are currently selected. If no tools are selected,
12123 * the menu label is empty. The menu can be configured with an indicator, icon, title, and/or header.
12124 *
12125 * MenuToolGroups are created by a {@link OO.ui.ToolGroupFactory tool group factory} when the toolbar
12126 * is set up.
12127 *
12128 * @example
12129 * // Example of a MenuToolGroup
12130 * var toolFactory = new OO.ui.ToolFactory();
12131 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
12132 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
12133 *
12134 * // We will be placing status text in this element when tools are used
12135 * var $area = $( '<p>' ).text( 'An example of a MenuToolGroup. Select a tool from the dropdown menu.' );
12136 *
12137 * // Define the tools that we're going to place in our toolbar
12138 *
12139 * function SettingsTool() {
12140 * SettingsTool.parent.apply( this, arguments );
12141 * this.reallyActive = false;
12142 * }
12143 * OO.inheritClass( SettingsTool, OO.ui.Tool );
12144 * SettingsTool.static.name = 'settings';
12145 * SettingsTool.static.icon = 'settings';
12146 * SettingsTool.static.title = 'Change settings';
12147 * SettingsTool.prototype.onSelect = function () {
12148 * $area.text( 'Settings tool clicked!' );
12149 * // Toggle the active state on each click
12150 * this.reallyActive = !this.reallyActive;
12151 * this.setActive( this.reallyActive );
12152 * // To update the menu label
12153 * this.toolbar.emit( 'updateState' );
12154 * };
12155 * SettingsTool.prototype.onUpdateState = function () {};
12156 * toolFactory.register( SettingsTool );
12157 *
12158 * function StuffTool() {
12159 * StuffTool.parent.apply( this, arguments );
12160 * this.reallyActive = false;
12161 * }
12162 * OO.inheritClass( StuffTool, OO.ui.Tool );
12163 * StuffTool.static.name = 'stuff';
12164 * StuffTool.static.icon = 'ellipsis';
12165 * StuffTool.static.title = 'More stuff';
12166 * StuffTool.prototype.onSelect = function () {
12167 * $area.text( 'More stuff tool clicked!' );
12168 * // Toggle the active state on each click
12169 * this.reallyActive = !this.reallyActive;
12170 * this.setActive( this.reallyActive );
12171 * // To update the menu label
12172 * this.toolbar.emit( 'updateState' );
12173 * };
12174 * StuffTool.prototype.onUpdateState = function () {};
12175 * toolFactory.register( StuffTool );
12176 *
12177 * // Finally define which tools and in what order appear in the toolbar. Each tool may only be
12178 * // used once (but not all defined tools must be used).
12179 * toolbar.setup( [
12180 * {
12181 * type: 'menu',
12182 * header: 'This is the (optional) header',
12183 * title: 'This is the (optional) title',
12184 * indicator: 'down',
12185 * include: [ 'settings', 'stuff' ]
12186 * }
12187 * ] );
12188 *
12189 * // Create some UI around the toolbar and place it in the document
12190 * var frame = new OO.ui.PanelLayout( {
12191 * expanded: false,
12192 * framed: true
12193 * } );
12194 * var contentFrame = new OO.ui.PanelLayout( {
12195 * expanded: false,
12196 * padded: true
12197 * } );
12198 * frame.$element.append(
12199 * toolbar.$element,
12200 * contentFrame.$element.append( $area )
12201 * );
12202 * $( 'body' ).append( frame.$element );
12203 *
12204 * // Here is where the toolbar is actually built. This must be done after inserting it into the
12205 * // document.
12206 * toolbar.initialize();
12207 * toolbar.emit( 'updateState' );
12208 *
12209 * For more information about how to add tools to a MenuToolGroup, please see {@link OO.ui.ToolGroup toolgroup}.
12210 * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki] [1].
12211 *
12212 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
12213 *
12214 * @class
12215 * @extends OO.ui.PopupToolGroup
12216 *
12217 * @constructor
12218 * @param {OO.ui.Toolbar} toolbar
12219 * @param {Object} [config] Configuration options
12220 */
12221 OO.ui.MenuToolGroup = function OoUiMenuToolGroup( toolbar, config ) {
12222 // Allow passing positional parameters inside the config object
12223 if ( OO.isPlainObject( toolbar ) && config === undefined ) {
12224 config = toolbar;
12225 toolbar = config.toolbar;
12226 }
12227
12228 // Configuration initialization
12229 config = config || {};
12230
12231 // Parent constructor
12232 OO.ui.MenuToolGroup.parent.call( this, toolbar, config );
12233
12234 // Events
12235 this.toolbar.connect( this, { updateState: 'onUpdateState' } );
12236
12237 // Initialization
12238 this.$element.addClass( 'oo-ui-menuToolGroup' );
12239 };
12240
12241 /* Setup */
12242
12243 OO.inheritClass( OO.ui.MenuToolGroup, OO.ui.PopupToolGroup );
12244
12245 /* Static Properties */
12246
12247 OO.ui.MenuToolGroup.static.name = 'menu';
12248
12249 /* Methods */
12250
12251 /**
12252 * Handle the toolbar state being updated.
12253 *
12254 * When the state changes, the title of each active item in the menu will be joined together and
12255 * used as a label for the group. The label will be empty if none of the items are active.
12256 *
12257 * @private
12258 */
12259 OO.ui.MenuToolGroup.prototype.onUpdateState = function () {
12260 var name,
12261 labelTexts = [];
12262
12263 for ( name in this.tools ) {
12264 if ( this.tools[ name ].isActive() ) {
12265 labelTexts.push( this.tools[ name ].getTitle() );
12266 }
12267 }
12268
12269 this.setLabel( labelTexts.join( ', ' ) || ' ' );
12270 };
12271
12272 /**
12273 * Popup tools open a popup window when they are selected from the {@link OO.ui.Toolbar toolbar}. Each popup tool is configured
12274 * 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
12275 * an #onSelect or #onUpdateState method, as these methods have been implemented already.
12276 *
12277 * // Example of a popup tool. When selected, a popup tool displays
12278 * // a popup window.
12279 * function HelpTool( toolGroup, config ) {
12280 * OO.ui.PopupTool.call( this, toolGroup, $.extend( { popup: {
12281 * padded: true,
12282 * label: 'Help',
12283 * head: true
12284 * } }, config ) );
12285 * this.popup.$body.append( '<p>I am helpful!</p>' );
12286 * };
12287 * OO.inheritClass( HelpTool, OO.ui.PopupTool );
12288 * HelpTool.static.name = 'help';
12289 * HelpTool.static.icon = 'help';
12290 * HelpTool.static.title = 'Help';
12291 * toolFactory.register( HelpTool );
12292 *
12293 * For an example of a toolbar that contains a popup tool, see {@link OO.ui.Toolbar toolbars}. For more information about
12294 * toolbars in genreral, please see the [OOjs UI documentation on MediaWiki][1].
12295 *
12296 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
12297 *
12298 * @abstract
12299 * @class
12300 * @extends OO.ui.Tool
12301 * @mixins OO.ui.mixin.PopupElement
12302 *
12303 * @constructor
12304 * @param {OO.ui.ToolGroup} toolGroup
12305 * @param {Object} [config] Configuration options
12306 */
12307 OO.ui.PopupTool = function OoUiPopupTool( toolGroup, config ) {
12308 // Allow passing positional parameters inside the config object
12309 if ( OO.isPlainObject( toolGroup ) && config === undefined ) {
12310 config = toolGroup;
12311 toolGroup = config.toolGroup;
12312 }
12313
12314 // Parent constructor
12315 OO.ui.PopupTool.parent.call( this, toolGroup, config );
12316
12317 // Mixin constructors
12318 OO.ui.mixin.PopupElement.call( this, config );
12319
12320 // Initialization
12321 this.$element
12322 .addClass( 'oo-ui-popupTool' )
12323 .append( this.popup.$element );
12324 };
12325
12326 /* Setup */
12327
12328 OO.inheritClass( OO.ui.PopupTool, OO.ui.Tool );
12329 OO.mixinClass( OO.ui.PopupTool, OO.ui.mixin.PopupElement );
12330
12331 /* Methods */
12332
12333 /**
12334 * Handle the tool being selected.
12335 *
12336 * @inheritdoc
12337 */
12338 OO.ui.PopupTool.prototype.onSelect = function () {
12339 if ( !this.isDisabled() ) {
12340 this.popup.toggle();
12341 }
12342 this.setActive( false );
12343 return false;
12344 };
12345
12346 /**
12347 * Handle the toolbar state being updated.
12348 *
12349 * @inheritdoc
12350 */
12351 OO.ui.PopupTool.prototype.onUpdateState = function () {
12352 this.setActive( false );
12353 };
12354
12355 /**
12356 * A ToolGroupTool is a special sort of tool that can contain other {@link OO.ui.Tool tools}
12357 * and {@link OO.ui.ToolGroup toolgroups}. The ToolGroupTool was specifically designed to be used
12358 * inside a {@link OO.ui.BarToolGroup bar} toolgroup to provide access to additional tools from
12359 * the bar item. Included tools will be displayed in a dropdown {@link OO.ui.ListToolGroup list}
12360 * when the ToolGroupTool is selected.
12361 *
12362 * // Example: ToolGroupTool with two nested tools, 'setting1' and 'setting2', defined elsewhere.
12363 *
12364 * function SettingsTool() {
12365 * SettingsTool.parent.apply( this, arguments );
12366 * };
12367 * OO.inheritClass( SettingsTool, OO.ui.ToolGroupTool );
12368 * SettingsTool.static.name = 'settings';
12369 * SettingsTool.static.title = 'Change settings';
12370 * SettingsTool.static.groupConfig = {
12371 * icon: 'settings',
12372 * label: 'ToolGroupTool',
12373 * include: [ 'setting1', 'setting2' ]
12374 * };
12375 * toolFactory.register( SettingsTool );
12376 *
12377 * For more information, please see the [OOjs UI documentation on MediaWiki][1].
12378 *
12379 * Please note that this implementation is subject to change per [T74159] [2].
12380 *
12381 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars#ToolGroupTool
12382 * [2]: https://phabricator.wikimedia.org/T74159
12383 *
12384 * @abstract
12385 * @class
12386 * @extends OO.ui.Tool
12387 *
12388 * @constructor
12389 * @param {OO.ui.ToolGroup} toolGroup
12390 * @param {Object} [config] Configuration options
12391 */
12392 OO.ui.ToolGroupTool = function OoUiToolGroupTool( toolGroup, config ) {
12393 // Allow passing positional parameters inside the config object
12394 if ( OO.isPlainObject( toolGroup ) && config === undefined ) {
12395 config = toolGroup;
12396 toolGroup = config.toolGroup;
12397 }
12398
12399 // Parent constructor
12400 OO.ui.ToolGroupTool.parent.call( this, toolGroup, config );
12401
12402 // Properties
12403 this.innerToolGroup = this.createGroup( this.constructor.static.groupConfig );
12404
12405 // Events
12406 this.innerToolGroup.connect( this, { disable: 'onToolGroupDisable' } );
12407
12408 // Initialization
12409 this.$link.remove();
12410 this.$element
12411 .addClass( 'oo-ui-toolGroupTool' )
12412 .append( this.innerToolGroup.$element );
12413 };
12414
12415 /* Setup */
12416
12417 OO.inheritClass( OO.ui.ToolGroupTool, OO.ui.Tool );
12418
12419 /* Static Properties */
12420
12421 /**
12422 * Toolgroup configuration.
12423 *
12424 * The toolgroup configuration consists of the tools to include, as well as an icon and label
12425 * to use for the bar item. Tools can be included by symbolic name, group, or with the
12426 * wildcard selector. Please see {@link OO.ui.ToolGroup toolgroup} for more information.
12427 *
12428 * @property {Object.<string,Array>}
12429 */
12430 OO.ui.ToolGroupTool.static.groupConfig = {};
12431
12432 /* Methods */
12433
12434 /**
12435 * Handle the tool being selected.
12436 *
12437 * @inheritdoc
12438 */
12439 OO.ui.ToolGroupTool.prototype.onSelect = function () {
12440 this.innerToolGroup.setActive( !this.innerToolGroup.active );
12441 return false;
12442 };
12443
12444 /**
12445 * Synchronize disabledness state of the tool with the inner toolgroup.
12446 *
12447 * @private
12448 * @param {boolean} disabled Element is disabled
12449 */
12450 OO.ui.ToolGroupTool.prototype.onToolGroupDisable = function ( disabled ) {
12451 this.setDisabled( disabled );
12452 };
12453
12454 /**
12455 * Handle the toolbar state being updated.
12456 *
12457 * @inheritdoc
12458 */
12459 OO.ui.ToolGroupTool.prototype.onUpdateState = function () {
12460 this.setActive( false );
12461 };
12462
12463 /**
12464 * Build a {@link OO.ui.ToolGroup toolgroup} from the specified configuration.
12465 *
12466 * @param {Object.<string,Array>} group Toolgroup configuration. Please see {@link OO.ui.ToolGroup toolgroup} for
12467 * more information.
12468 * @return {OO.ui.ListToolGroup}
12469 */
12470 OO.ui.ToolGroupTool.prototype.createGroup = function ( group ) {
12471 if ( group.include === '*' ) {
12472 // Apply defaults to catch-all groups
12473 if ( group.label === undefined ) {
12474 group.label = OO.ui.msg( 'ooui-toolbar-more' );
12475 }
12476 }
12477
12478 return this.toolbar.getToolGroupFactory().create( 'list', this.toolbar, group );
12479 };
12480
12481 /**
12482 * Mixin for OO.ui.Widget subclasses to provide OO.ui.mixin.GroupElement.
12483 *
12484 * Use together with OO.ui.mixin.ItemWidget to make disabled state inheritable.
12485 *
12486 * @private
12487 * @abstract
12488 * @class
12489 * @extends OO.ui.mixin.GroupElement
12490 *
12491 * @constructor
12492 * @param {Object} [config] Configuration options
12493 */
12494 OO.ui.mixin.GroupWidget = function OoUiMixinGroupWidget( config ) {
12495 // Parent constructor
12496 OO.ui.mixin.GroupWidget.parent.call( this, config );
12497 };
12498
12499 /* Setup */
12500
12501 OO.inheritClass( OO.ui.mixin.GroupWidget, OO.ui.mixin.GroupElement );
12502
12503 /* Methods */
12504
12505 /**
12506 * Set the disabled state of the widget.
12507 *
12508 * This will also update the disabled state of child widgets.
12509 *
12510 * @param {boolean} disabled Disable widget
12511 * @chainable
12512 */
12513 OO.ui.mixin.GroupWidget.prototype.setDisabled = function ( disabled ) {
12514 var i, len;
12515
12516 // Parent method
12517 // Note: Calling #setDisabled this way assumes this is mixed into an OO.ui.Widget
12518 OO.ui.Widget.prototype.setDisabled.call( this, disabled );
12519
12520 // During construction, #setDisabled is called before the OO.ui.mixin.GroupElement constructor
12521 if ( this.items ) {
12522 for ( i = 0, len = this.items.length; i < len; i++ ) {
12523 this.items[ i ].updateDisabled();
12524 }
12525 }
12526
12527 return this;
12528 };
12529
12530 /**
12531 * Mixin for widgets used as items in widgets that mix in OO.ui.mixin.GroupWidget.
12532 *
12533 * Item widgets have a reference to a OO.ui.mixin.GroupWidget while they are attached to the group. This
12534 * allows bidirectional communication.
12535 *
12536 * Use together with OO.ui.mixin.GroupWidget to make disabled state inheritable.
12537 *
12538 * @private
12539 * @abstract
12540 * @class
12541 *
12542 * @constructor
12543 */
12544 OO.ui.mixin.ItemWidget = function OoUiMixinItemWidget() {
12545 //
12546 };
12547
12548 /* Methods */
12549
12550 /**
12551 * Check if widget is disabled.
12552 *
12553 * Checks parent if present, making disabled state inheritable.
12554 *
12555 * @return {boolean} Widget is disabled
12556 */
12557 OO.ui.mixin.ItemWidget.prototype.isDisabled = function () {
12558 return this.disabled ||
12559 ( this.elementGroup instanceof OO.ui.Widget && this.elementGroup.isDisabled() );
12560 };
12561
12562 /**
12563 * Set group element is in.
12564 *
12565 * @param {OO.ui.mixin.GroupElement|null} group Group element, null if none
12566 * @chainable
12567 */
12568 OO.ui.mixin.ItemWidget.prototype.setElementGroup = function ( group ) {
12569 // Parent method
12570 // Note: Calling #setElementGroup this way assumes this is mixed into an OO.ui.Element
12571 OO.ui.Element.prototype.setElementGroup.call( this, group );
12572
12573 // Initialize item disabled states
12574 this.updateDisabled();
12575
12576 return this;
12577 };
12578
12579 /**
12580 * OutlineControlsWidget is a set of controls for an {@link OO.ui.OutlineSelectWidget outline select widget}.
12581 * Controls include moving items up and down, removing items, and adding different kinds of items.
12582 *
12583 * **Currently, this class is only used by {@link OO.ui.BookletLayout booklet layouts}.**
12584 *
12585 * @class
12586 * @extends OO.ui.Widget
12587 * @mixins OO.ui.mixin.GroupElement
12588 * @mixins OO.ui.mixin.IconElement
12589 *
12590 * @constructor
12591 * @param {OO.ui.OutlineSelectWidget} outline Outline to control
12592 * @param {Object} [config] Configuration options
12593 * @cfg {Object} [abilities] List of abilties
12594 * @cfg {boolean} [abilities.move=true] Allow moving movable items
12595 * @cfg {boolean} [abilities.remove=true] Allow removing removable items
12596 */
12597 OO.ui.OutlineControlsWidget = function OoUiOutlineControlsWidget( outline, config ) {
12598 // Allow passing positional parameters inside the config object
12599 if ( OO.isPlainObject( outline ) && config === undefined ) {
12600 config = outline;
12601 outline = config.outline;
12602 }
12603
12604 // Configuration initialization
12605 config = $.extend( { icon: 'add' }, config );
12606
12607 // Parent constructor
12608 OO.ui.OutlineControlsWidget.parent.call( this, config );
12609
12610 // Mixin constructors
12611 OO.ui.mixin.GroupElement.call( this, config );
12612 OO.ui.mixin.IconElement.call( this, config );
12613
12614 // Properties
12615 this.outline = outline;
12616 this.$movers = $( '<div>' );
12617 this.upButton = new OO.ui.ButtonWidget( {
12618 framed: false,
12619 icon: 'collapse',
12620 title: OO.ui.msg( 'ooui-outline-control-move-up' )
12621 } );
12622 this.downButton = new OO.ui.ButtonWidget( {
12623 framed: false,
12624 icon: 'expand',
12625 title: OO.ui.msg( 'ooui-outline-control-move-down' )
12626 } );
12627 this.removeButton = new OO.ui.ButtonWidget( {
12628 framed: false,
12629 icon: 'remove',
12630 title: OO.ui.msg( 'ooui-outline-control-remove' )
12631 } );
12632 this.abilities = { move: true, remove: true };
12633
12634 // Events
12635 outline.connect( this, {
12636 select: 'onOutlineChange',
12637 add: 'onOutlineChange',
12638 remove: 'onOutlineChange'
12639 } );
12640 this.upButton.connect( this, { click: [ 'emit', 'move', -1 ] } );
12641 this.downButton.connect( this, { click: [ 'emit', 'move', 1 ] } );
12642 this.removeButton.connect( this, { click: [ 'emit', 'remove' ] } );
12643
12644 // Initialization
12645 this.$element.addClass( 'oo-ui-outlineControlsWidget' );
12646 this.$group.addClass( 'oo-ui-outlineControlsWidget-items' );
12647 this.$movers
12648 .addClass( 'oo-ui-outlineControlsWidget-movers' )
12649 .append( this.removeButton.$element, this.upButton.$element, this.downButton.$element );
12650 this.$element.append( this.$icon, this.$group, this.$movers );
12651 this.setAbilities( config.abilities || {} );
12652 };
12653
12654 /* Setup */
12655
12656 OO.inheritClass( OO.ui.OutlineControlsWidget, OO.ui.Widget );
12657 OO.mixinClass( OO.ui.OutlineControlsWidget, OO.ui.mixin.GroupElement );
12658 OO.mixinClass( OO.ui.OutlineControlsWidget, OO.ui.mixin.IconElement );
12659
12660 /* Events */
12661
12662 /**
12663 * @event move
12664 * @param {number} places Number of places to move
12665 */
12666
12667 /**
12668 * @event remove
12669 */
12670
12671 /* Methods */
12672
12673 /**
12674 * Set abilities.
12675 *
12676 * @param {Object} abilities List of abilties
12677 * @param {boolean} [abilities.move] Allow moving movable items
12678 * @param {boolean} [abilities.remove] Allow removing removable items
12679 */
12680 OO.ui.OutlineControlsWidget.prototype.setAbilities = function ( abilities ) {
12681 var ability;
12682
12683 for ( ability in this.abilities ) {
12684 if ( abilities[ ability ] !== undefined ) {
12685 this.abilities[ ability ] = !!abilities[ ability ];
12686 }
12687 }
12688
12689 this.onOutlineChange();
12690 };
12691
12692 /**
12693 * @private
12694 * Handle outline change events.
12695 */
12696 OO.ui.OutlineControlsWidget.prototype.onOutlineChange = function () {
12697 var i, len, firstMovable, lastMovable,
12698 items = this.outline.getItems(),
12699 selectedItem = this.outline.getSelectedItem(),
12700 movable = this.abilities.move && selectedItem && selectedItem.isMovable(),
12701 removable = this.abilities.remove && selectedItem && selectedItem.isRemovable();
12702
12703 if ( movable ) {
12704 i = -1;
12705 len = items.length;
12706 while ( ++i < len ) {
12707 if ( items[ i ].isMovable() ) {
12708 firstMovable = items[ i ];
12709 break;
12710 }
12711 }
12712 i = len;
12713 while ( i-- ) {
12714 if ( items[ i ].isMovable() ) {
12715 lastMovable = items[ i ];
12716 break;
12717 }
12718 }
12719 }
12720 this.upButton.setDisabled( !movable || selectedItem === firstMovable );
12721 this.downButton.setDisabled( !movable || selectedItem === lastMovable );
12722 this.removeButton.setDisabled( !removable );
12723 };
12724
12725 /**
12726 * ToggleWidget implements basic behavior of widgets with an on/off state.
12727 * Please see OO.ui.ToggleButtonWidget and OO.ui.ToggleSwitchWidget for examples.
12728 *
12729 * @abstract
12730 * @class
12731 * @extends OO.ui.Widget
12732 *
12733 * @constructor
12734 * @param {Object} [config] Configuration options
12735 * @cfg {boolean} [value=false] The toggle’s initial on/off state.
12736 * By default, the toggle is in the 'off' state.
12737 */
12738 OO.ui.ToggleWidget = function OoUiToggleWidget( config ) {
12739 // Configuration initialization
12740 config = config || {};
12741
12742 // Parent constructor
12743 OO.ui.ToggleWidget.parent.call( this, config );
12744
12745 // Properties
12746 this.value = null;
12747
12748 // Initialization
12749 this.$element.addClass( 'oo-ui-toggleWidget' );
12750 this.setValue( !!config.value );
12751 };
12752
12753 /* Setup */
12754
12755 OO.inheritClass( OO.ui.ToggleWidget, OO.ui.Widget );
12756
12757 /* Events */
12758
12759 /**
12760 * @event change
12761 *
12762 * A change event is emitted when the on/off state of the toggle changes.
12763 *
12764 * @param {boolean} value Value representing the new state of the toggle
12765 */
12766
12767 /* Methods */
12768
12769 /**
12770 * Get the value representing the toggle’s state.
12771 *
12772 * @return {boolean} The on/off state of the toggle
12773 */
12774 OO.ui.ToggleWidget.prototype.getValue = function () {
12775 return this.value;
12776 };
12777
12778 /**
12779 * Set the state of the toggle: `true` for 'on', `false' for 'off'.
12780 *
12781 * @param {boolean} value The state of the toggle
12782 * @fires change
12783 * @chainable
12784 */
12785 OO.ui.ToggleWidget.prototype.setValue = function ( value ) {
12786 value = !!value;
12787 if ( this.value !== value ) {
12788 this.value = value;
12789 this.emit( 'change', value );
12790 this.$element.toggleClass( 'oo-ui-toggleWidget-on', value );
12791 this.$element.toggleClass( 'oo-ui-toggleWidget-off', !value );
12792 this.$element.attr( 'aria-checked', value.toString() );
12793 }
12794 return this;
12795 };
12796
12797 /**
12798 * A ButtonGroupWidget groups related buttons and is used together with OO.ui.ButtonWidget and
12799 * its subclasses. Each button in a group is addressed by a unique reference. Buttons can be added,
12800 * removed, and cleared from the group.
12801 *
12802 * @example
12803 * // Example: A ButtonGroupWidget with two buttons
12804 * var button1 = new OO.ui.PopupButtonWidget( {
12805 * label: 'Select a category',
12806 * icon: 'menu',
12807 * popup: {
12808 * $content: $( '<p>List of categories...</p>' ),
12809 * padded: true,
12810 * align: 'left'
12811 * }
12812 * } );
12813 * var button2 = new OO.ui.ButtonWidget( {
12814 * label: 'Add item'
12815 * });
12816 * var buttonGroup = new OO.ui.ButtonGroupWidget( {
12817 * items: [button1, button2]
12818 * } );
12819 * $( 'body' ).append( buttonGroup.$element );
12820 *
12821 * @class
12822 * @extends OO.ui.Widget
12823 * @mixins OO.ui.mixin.GroupElement
12824 *
12825 * @constructor
12826 * @param {Object} [config] Configuration options
12827 * @cfg {OO.ui.ButtonWidget[]} [items] Buttons to add
12828 */
12829 OO.ui.ButtonGroupWidget = function OoUiButtonGroupWidget( config ) {
12830 // Configuration initialization
12831 config = config || {};
12832
12833 // Parent constructor
12834 OO.ui.ButtonGroupWidget.parent.call( this, config );
12835
12836 // Mixin constructors
12837 OO.ui.mixin.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) );
12838
12839 // Initialization
12840 this.$element.addClass( 'oo-ui-buttonGroupWidget' );
12841 if ( Array.isArray( config.items ) ) {
12842 this.addItems( config.items );
12843 }
12844 };
12845
12846 /* Setup */
12847
12848 OO.inheritClass( OO.ui.ButtonGroupWidget, OO.ui.Widget );
12849 OO.mixinClass( OO.ui.ButtonGroupWidget, OO.ui.mixin.GroupElement );
12850
12851 /**
12852 * ButtonWidget is a generic widget for buttons. A wide variety of looks,
12853 * feels, and functionality can be customized via the class’s configuration options
12854 * and methods. Please see the [OOjs UI documentation on MediaWiki] [1] for more information
12855 * and examples.
12856 *
12857 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches
12858 *
12859 * @example
12860 * // A button widget
12861 * var button = new OO.ui.ButtonWidget( {
12862 * label: 'Button with Icon',
12863 * icon: 'remove',
12864 * iconTitle: 'Remove'
12865 * } );
12866 * $( 'body' ).append( button.$element );
12867 *
12868 * NOTE: HTML form buttons should use the OO.ui.ButtonInputWidget class.
12869 *
12870 * @class
12871 * @extends OO.ui.Widget
12872 * @mixins OO.ui.mixin.ButtonElement
12873 * @mixins OO.ui.mixin.IconElement
12874 * @mixins OO.ui.mixin.IndicatorElement
12875 * @mixins OO.ui.mixin.LabelElement
12876 * @mixins OO.ui.mixin.TitledElement
12877 * @mixins OO.ui.mixin.FlaggedElement
12878 * @mixins OO.ui.mixin.TabIndexedElement
12879 * @mixins OO.ui.mixin.AccessKeyedElement
12880 *
12881 * @constructor
12882 * @param {Object} [config] Configuration options
12883 * @cfg {string} [href] Hyperlink to visit when the button is clicked.
12884 * @cfg {string} [target] The frame or window in which to open the hyperlink.
12885 * @cfg {boolean} [noFollow] Search engine traversal hint (default: true)
12886 */
12887 OO.ui.ButtonWidget = function OoUiButtonWidget( config ) {
12888 // Configuration initialization
12889 config = config || {};
12890
12891 // Parent constructor
12892 OO.ui.ButtonWidget.parent.call( this, config );
12893
12894 // Mixin constructors
12895 OO.ui.mixin.ButtonElement.call( this, config );
12896 OO.ui.mixin.IconElement.call( this, config );
12897 OO.ui.mixin.IndicatorElement.call( this, config );
12898 OO.ui.mixin.LabelElement.call( this, config );
12899 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$button } ) );
12900 OO.ui.mixin.FlaggedElement.call( this, config );
12901 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$button } ) );
12902 OO.ui.mixin.AccessKeyedElement.call( this, $.extend( {}, config, { $accessKeyed: this.$button } ) );
12903
12904 // Properties
12905 this.href = null;
12906 this.target = null;
12907 this.noFollow = false;
12908
12909 // Events
12910 this.connect( this, { disable: 'onDisable' } );
12911
12912 // Initialization
12913 this.$button.append( this.$icon, this.$label, this.$indicator );
12914 this.$element
12915 .addClass( 'oo-ui-buttonWidget' )
12916 .append( this.$button );
12917 this.setHref( config.href );
12918 this.setTarget( config.target );
12919 this.setNoFollow( config.noFollow );
12920 };
12921
12922 /* Setup */
12923
12924 OO.inheritClass( OO.ui.ButtonWidget, OO.ui.Widget );
12925 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.ButtonElement );
12926 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.IconElement );
12927 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.IndicatorElement );
12928 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.LabelElement );
12929 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.TitledElement );
12930 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.FlaggedElement );
12931 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.TabIndexedElement );
12932 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.AccessKeyedElement );
12933
12934 /* Methods */
12935
12936 /**
12937 * @inheritdoc
12938 */
12939 OO.ui.ButtonWidget.prototype.onMouseDown = function ( e ) {
12940 if ( !this.isDisabled() ) {
12941 // Remove the tab-index while the button is down to prevent the button from stealing focus
12942 this.$button.removeAttr( 'tabindex' );
12943 }
12944
12945 return OO.ui.mixin.ButtonElement.prototype.onMouseDown.call( this, e );
12946 };
12947
12948 /**
12949 * @inheritdoc
12950 */
12951 OO.ui.ButtonWidget.prototype.onMouseUp = function ( e ) {
12952 if ( !this.isDisabled() ) {
12953 // Restore the tab-index after the button is up to restore the button's accessibility
12954 this.$button.attr( 'tabindex', this.tabIndex );
12955 }
12956
12957 return OO.ui.mixin.ButtonElement.prototype.onMouseUp.call( this, e );
12958 };
12959
12960 /**
12961 * Get hyperlink location.
12962 *
12963 * @return {string} Hyperlink location
12964 */
12965 OO.ui.ButtonWidget.prototype.getHref = function () {
12966 return this.href;
12967 };
12968
12969 /**
12970 * Get hyperlink target.
12971 *
12972 * @return {string} Hyperlink target
12973 */
12974 OO.ui.ButtonWidget.prototype.getTarget = function () {
12975 return this.target;
12976 };
12977
12978 /**
12979 * Get search engine traversal hint.
12980 *
12981 * @return {boolean} Whether search engines should avoid traversing this hyperlink
12982 */
12983 OO.ui.ButtonWidget.prototype.getNoFollow = function () {
12984 return this.noFollow;
12985 };
12986
12987 /**
12988 * Set hyperlink location.
12989 *
12990 * @param {string|null} href Hyperlink location, null to remove
12991 */
12992 OO.ui.ButtonWidget.prototype.setHref = function ( href ) {
12993 href = typeof href === 'string' ? href : null;
12994 if ( href !== null ) {
12995 if ( !OO.ui.isSafeUrl( href ) ) {
12996 throw new Error( 'Potentially unsafe href provided: ' + href );
12997 }
12998
12999 }
13000
13001 if ( href !== this.href ) {
13002 this.href = href;
13003 this.updateHref();
13004 }
13005
13006 return this;
13007 };
13008
13009 /**
13010 * Update the `href` attribute, in case of changes to href or
13011 * disabled state.
13012 *
13013 * @private
13014 * @chainable
13015 */
13016 OO.ui.ButtonWidget.prototype.updateHref = function () {
13017 if ( this.href !== null && !this.isDisabled() ) {
13018 this.$button.attr( 'href', this.href );
13019 } else {
13020 this.$button.removeAttr( 'href' );
13021 }
13022
13023 return this;
13024 };
13025
13026 /**
13027 * Handle disable events.
13028 *
13029 * @private
13030 * @param {boolean} disabled Element is disabled
13031 */
13032 OO.ui.ButtonWidget.prototype.onDisable = function () {
13033 this.updateHref();
13034 };
13035
13036 /**
13037 * Set hyperlink target.
13038 *
13039 * @param {string|null} target Hyperlink target, null to remove
13040 */
13041 OO.ui.ButtonWidget.prototype.setTarget = function ( target ) {
13042 target = typeof target === 'string' ? target : null;
13043
13044 if ( target !== this.target ) {
13045 this.target = target;
13046 if ( target !== null ) {
13047 this.$button.attr( 'target', target );
13048 } else {
13049 this.$button.removeAttr( 'target' );
13050 }
13051 }
13052
13053 return this;
13054 };
13055
13056 /**
13057 * Set search engine traversal hint.
13058 *
13059 * @param {boolean} noFollow True if search engines should avoid traversing this hyperlink
13060 */
13061 OO.ui.ButtonWidget.prototype.setNoFollow = function ( noFollow ) {
13062 noFollow = typeof noFollow === 'boolean' ? noFollow : true;
13063
13064 if ( noFollow !== this.noFollow ) {
13065 this.noFollow = noFollow;
13066 if ( noFollow ) {
13067 this.$button.attr( 'rel', 'nofollow' );
13068 } else {
13069 this.$button.removeAttr( 'rel' );
13070 }
13071 }
13072
13073 return this;
13074 };
13075
13076 /**
13077 * An ActionWidget is a {@link OO.ui.ButtonWidget button widget} that executes an action.
13078 * Action widgets are used with OO.ui.ActionSet, which manages the behavior and availability
13079 * of the actions.
13080 *
13081 * Both actions and action sets are primarily used with {@link OO.ui.Dialog Dialogs}.
13082 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information
13083 * and examples.
13084 *
13085 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Action_sets
13086 *
13087 * @class
13088 * @extends OO.ui.ButtonWidget
13089 * @mixins OO.ui.mixin.PendingElement
13090 *
13091 * @constructor
13092 * @param {Object} [config] Configuration options
13093 * @cfg {string} [action] Symbolic name of the action (e.g., ‘continue’ or ‘cancel’).
13094 * @cfg {string[]} [modes] Symbolic names of the modes (e.g., ‘edit’ or ‘read’) in which the action
13095 * should be made available. See the action set's {@link OO.ui.ActionSet#setMode setMode} method
13096 * for more information about setting modes.
13097 * @cfg {boolean} [framed=false] Render the action button with a frame
13098 */
13099 OO.ui.ActionWidget = function OoUiActionWidget( config ) {
13100 // Configuration initialization
13101 config = $.extend( { framed: false }, config );
13102
13103 // Parent constructor
13104 OO.ui.ActionWidget.parent.call( this, config );
13105
13106 // Mixin constructors
13107 OO.ui.mixin.PendingElement.call( this, config );
13108
13109 // Properties
13110 this.action = config.action || '';
13111 this.modes = config.modes || [];
13112 this.width = 0;
13113 this.height = 0;
13114
13115 // Initialization
13116 this.$element.addClass( 'oo-ui-actionWidget' );
13117 };
13118
13119 /* Setup */
13120
13121 OO.inheritClass( OO.ui.ActionWidget, OO.ui.ButtonWidget );
13122 OO.mixinClass( OO.ui.ActionWidget, OO.ui.mixin.PendingElement );
13123
13124 /* Events */
13125
13126 /**
13127 * A resize event is emitted when the size of the widget changes.
13128 *
13129 * @event resize
13130 */
13131
13132 /* Methods */
13133
13134 /**
13135 * Check if the action is configured to be available in the specified `mode`.
13136 *
13137 * @param {string} mode Name of mode
13138 * @return {boolean} The action is configured with the mode
13139 */
13140 OO.ui.ActionWidget.prototype.hasMode = function ( mode ) {
13141 return this.modes.indexOf( mode ) !== -1;
13142 };
13143
13144 /**
13145 * Get the symbolic name of the action (e.g., ‘continue’ or ‘cancel’).
13146 *
13147 * @return {string}
13148 */
13149 OO.ui.ActionWidget.prototype.getAction = function () {
13150 return this.action;
13151 };
13152
13153 /**
13154 * Get the symbolic name of the mode or modes for which the action is configured to be available.
13155 *
13156 * The current mode is set with the action set's {@link OO.ui.ActionSet#setMode setMode} method.
13157 * Only actions that are configured to be avaiable in the current mode will be visible. All other actions
13158 * are hidden.
13159 *
13160 * @return {string[]}
13161 */
13162 OO.ui.ActionWidget.prototype.getModes = function () {
13163 return this.modes.slice();
13164 };
13165
13166 /**
13167 * Emit a resize event if the size has changed.
13168 *
13169 * @private
13170 * @chainable
13171 */
13172 OO.ui.ActionWidget.prototype.propagateResize = function () {
13173 var width, height;
13174
13175 if ( this.isElementAttached() ) {
13176 width = this.$element.width();
13177 height = this.$element.height();
13178
13179 if ( width !== this.width || height !== this.height ) {
13180 this.width = width;
13181 this.height = height;
13182 this.emit( 'resize' );
13183 }
13184 }
13185
13186 return this;
13187 };
13188
13189 /**
13190 * @inheritdoc
13191 */
13192 OO.ui.ActionWidget.prototype.setIcon = function () {
13193 // Mixin method
13194 OO.ui.mixin.IconElement.prototype.setIcon.apply( this, arguments );
13195 this.propagateResize();
13196
13197 return this;
13198 };
13199
13200 /**
13201 * @inheritdoc
13202 */
13203 OO.ui.ActionWidget.prototype.setLabel = function () {
13204 // Mixin method
13205 OO.ui.mixin.LabelElement.prototype.setLabel.apply( this, arguments );
13206 this.propagateResize();
13207
13208 return this;
13209 };
13210
13211 /**
13212 * @inheritdoc
13213 */
13214 OO.ui.ActionWidget.prototype.setFlags = function () {
13215 // Mixin method
13216 OO.ui.mixin.FlaggedElement.prototype.setFlags.apply( this, arguments );
13217 this.propagateResize();
13218
13219 return this;
13220 };
13221
13222 /**
13223 * @inheritdoc
13224 */
13225 OO.ui.ActionWidget.prototype.clearFlags = function () {
13226 // Mixin method
13227 OO.ui.mixin.FlaggedElement.prototype.clearFlags.apply( this, arguments );
13228 this.propagateResize();
13229
13230 return this;
13231 };
13232
13233 /**
13234 * Toggle the visibility of the action button.
13235 *
13236 * @param {boolean} [show] Show button, omit to toggle visibility
13237 * @chainable
13238 */
13239 OO.ui.ActionWidget.prototype.toggle = function () {
13240 // Parent method
13241 OO.ui.ActionWidget.parent.prototype.toggle.apply( this, arguments );
13242 this.propagateResize();
13243
13244 return this;
13245 };
13246
13247 /**
13248 * PopupButtonWidgets toggle the visibility of a contained {@link OO.ui.PopupWidget PopupWidget},
13249 * which is used to display additional information or options.
13250 *
13251 * @example
13252 * // Example of a popup button.
13253 * var popupButton = new OO.ui.PopupButtonWidget( {
13254 * label: 'Popup button with options',
13255 * icon: 'menu',
13256 * popup: {
13257 * $content: $( '<p>Additional options here.</p>' ),
13258 * padded: true,
13259 * align: 'force-left'
13260 * }
13261 * } );
13262 * // Append the button to the DOM.
13263 * $( 'body' ).append( popupButton.$element );
13264 *
13265 * @class
13266 * @extends OO.ui.ButtonWidget
13267 * @mixins OO.ui.mixin.PopupElement
13268 *
13269 * @constructor
13270 * @param {Object} [config] Configuration options
13271 */
13272 OO.ui.PopupButtonWidget = function OoUiPopupButtonWidget( config ) {
13273 // Parent constructor
13274 OO.ui.PopupButtonWidget.parent.call( this, config );
13275
13276 // Mixin constructors
13277 OO.ui.mixin.PopupElement.call( this, config );
13278
13279 // Events
13280 this.connect( this, { click: 'onAction' } );
13281
13282 // Initialization
13283 this.$element
13284 .addClass( 'oo-ui-popupButtonWidget' )
13285 .attr( 'aria-haspopup', 'true' )
13286 .append( this.popup.$element );
13287 };
13288
13289 /* Setup */
13290
13291 OO.inheritClass( OO.ui.PopupButtonWidget, OO.ui.ButtonWidget );
13292 OO.mixinClass( OO.ui.PopupButtonWidget, OO.ui.mixin.PopupElement );
13293
13294 /* Methods */
13295
13296 /**
13297 * Handle the button action being triggered.
13298 *
13299 * @private
13300 */
13301 OO.ui.PopupButtonWidget.prototype.onAction = function () {
13302 this.popup.toggle();
13303 };
13304
13305 /**
13306 * ToggleButtons are buttons that have a state (‘on’ or ‘off’) that is represented by a
13307 * Boolean value. Like other {@link OO.ui.ButtonWidget buttons}, toggle buttons can be
13308 * configured with {@link OO.ui.mixin.IconElement icons}, {@link OO.ui.mixin.IndicatorElement indicators},
13309 * {@link OO.ui.mixin.TitledElement titles}, {@link OO.ui.mixin.FlaggedElement styling flags},
13310 * and {@link OO.ui.mixin.LabelElement labels}. Please see
13311 * the [OOjs UI documentation][1] on MediaWiki for more information.
13312 *
13313 * @example
13314 * // Toggle buttons in the 'off' and 'on' state.
13315 * var toggleButton1 = new OO.ui.ToggleButtonWidget( {
13316 * label: 'Toggle Button off'
13317 * } );
13318 * var toggleButton2 = new OO.ui.ToggleButtonWidget( {
13319 * label: 'Toggle Button on',
13320 * value: true
13321 * } );
13322 * // Append the buttons to the DOM.
13323 * $( 'body' ).append( toggleButton1.$element, toggleButton2.$element );
13324 *
13325 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#Toggle_buttons
13326 *
13327 * @class
13328 * @extends OO.ui.ToggleWidget
13329 * @mixins OO.ui.mixin.ButtonElement
13330 * @mixins OO.ui.mixin.IconElement
13331 * @mixins OO.ui.mixin.IndicatorElement
13332 * @mixins OO.ui.mixin.LabelElement
13333 * @mixins OO.ui.mixin.TitledElement
13334 * @mixins OO.ui.mixin.FlaggedElement
13335 * @mixins OO.ui.mixin.TabIndexedElement
13336 *
13337 * @constructor
13338 * @param {Object} [config] Configuration options
13339 * @cfg {boolean} [value=false] The toggle button’s initial on/off
13340 * state. By default, the button is in the 'off' state.
13341 */
13342 OO.ui.ToggleButtonWidget = function OoUiToggleButtonWidget( config ) {
13343 // Configuration initialization
13344 config = config || {};
13345
13346 // Parent constructor
13347 OO.ui.ToggleButtonWidget.parent.call( this, config );
13348
13349 // Mixin constructors
13350 OO.ui.mixin.ButtonElement.call( this, config );
13351 OO.ui.mixin.IconElement.call( this, config );
13352 OO.ui.mixin.IndicatorElement.call( this, config );
13353 OO.ui.mixin.LabelElement.call( this, config );
13354 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$button } ) );
13355 OO.ui.mixin.FlaggedElement.call( this, config );
13356 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$button } ) );
13357
13358 // Events
13359 this.connect( this, { click: 'onAction' } );
13360
13361 // Initialization
13362 this.$button.append( this.$icon, this.$label, this.$indicator );
13363 this.$element
13364 .addClass( 'oo-ui-toggleButtonWidget' )
13365 .append( this.$button );
13366 };
13367
13368 /* Setup */
13369
13370 OO.inheritClass( OO.ui.ToggleButtonWidget, OO.ui.ToggleWidget );
13371 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.ButtonElement );
13372 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.IconElement );
13373 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.IndicatorElement );
13374 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.LabelElement );
13375 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.TitledElement );
13376 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.FlaggedElement );
13377 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.TabIndexedElement );
13378
13379 /* Methods */
13380
13381 /**
13382 * Handle the button action being triggered.
13383 *
13384 * @private
13385 */
13386 OO.ui.ToggleButtonWidget.prototype.onAction = function () {
13387 this.setValue( !this.value );
13388 };
13389
13390 /**
13391 * @inheritdoc
13392 */
13393 OO.ui.ToggleButtonWidget.prototype.setValue = function ( value ) {
13394 value = !!value;
13395 if ( value !== this.value ) {
13396 // Might be called from parent constructor before ButtonElement constructor
13397 if ( this.$button ) {
13398 this.$button.attr( 'aria-pressed', value.toString() );
13399 }
13400 this.setActive( value );
13401 }
13402
13403 // Parent method
13404 OO.ui.ToggleButtonWidget.parent.prototype.setValue.call( this, value );
13405
13406 return this;
13407 };
13408
13409 /**
13410 * @inheritdoc
13411 */
13412 OO.ui.ToggleButtonWidget.prototype.setButtonElement = function ( $button ) {
13413 if ( this.$button ) {
13414 this.$button.removeAttr( 'aria-pressed' );
13415 }
13416 OO.ui.mixin.ButtonElement.prototype.setButtonElement.call( this, $button );
13417 this.$button.attr( 'aria-pressed', this.value.toString() );
13418 };
13419
13420 /**
13421 * CapsuleMultiSelectWidgets are something like a {@link OO.ui.ComboBoxInputWidget combo box widget}
13422 * that allows for selecting multiple values.
13423 *
13424 * For more information about menus and options, please see the [OOjs UI documentation on MediaWiki][1].
13425 *
13426 * @example
13427 * // Example: A CapsuleMultiSelectWidget.
13428 * var capsule = new OO.ui.CapsuleMultiSelectWidget( {
13429 * label: 'CapsuleMultiSelectWidget',
13430 * selected: [ 'Option 1', 'Option 3' ],
13431 * menu: {
13432 * items: [
13433 * new OO.ui.MenuOptionWidget( {
13434 * data: 'Option 1',
13435 * label: 'Option One'
13436 * } ),
13437 * new OO.ui.MenuOptionWidget( {
13438 * data: 'Option 2',
13439 * label: 'Option Two'
13440 * } ),
13441 * new OO.ui.MenuOptionWidget( {
13442 * data: 'Option 3',
13443 * label: 'Option Three'
13444 * } ),
13445 * new OO.ui.MenuOptionWidget( {
13446 * data: 'Option 4',
13447 * label: 'Option Four'
13448 * } ),
13449 * new OO.ui.MenuOptionWidget( {
13450 * data: 'Option 5',
13451 * label: 'Option Five'
13452 * } )
13453 * ]
13454 * }
13455 * } );
13456 * $( 'body' ).append( capsule.$element );
13457 *
13458 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
13459 *
13460 * @class
13461 * @extends OO.ui.Widget
13462 * @mixins OO.ui.mixin.TabIndexedElement
13463 * @mixins OO.ui.mixin.GroupElement
13464 *
13465 * @constructor
13466 * @param {Object} [config] Configuration options
13467 * @cfg {boolean} [allowArbitrary=false] Allow data items to be added even if not present in the menu.
13468 * @cfg {Object} [menu] Configuration options to pass to the {@link OO.ui.MenuSelectWidget menu select widget}.
13469 * @cfg {Object} [popup] Configuration options to pass to the {@link OO.ui.PopupWidget popup widget}.
13470 * If specified, this popup will be shown instead of the menu (but the menu
13471 * will still be used for item labels and allowArbitrary=false). The widgets
13472 * in the popup should use this.addItemsFromData() or this.addItems() as necessary.
13473 * @cfg {jQuery} [$overlay] Render the menu or popup into a separate layer.
13474 * This configuration is useful in cases where the expanded menu is larger than
13475 * its containing `<div>`. The specified overlay layer is usually on top of
13476 * the containing `<div>` and has a larger area. By default, the menu uses
13477 * relative positioning.
13478 */
13479 OO.ui.CapsuleMultiSelectWidget = function OoUiCapsuleMultiSelectWidget( config ) {
13480 var $tabFocus;
13481
13482 // Configuration initialization
13483 config = config || {};
13484
13485 // Parent constructor
13486 OO.ui.CapsuleMultiSelectWidget.parent.call( this, config );
13487
13488 // Properties (must be set before mixin constructor calls)
13489 this.$input = config.popup ? null : $( '<input>' );
13490 this.$handle = $( '<div>' );
13491
13492 // Mixin constructors
13493 OO.ui.mixin.GroupElement.call( this, config );
13494 if ( config.popup ) {
13495 config.popup = $.extend( {}, config.popup, {
13496 align: 'forwards',
13497 anchor: false
13498 } );
13499 OO.ui.mixin.PopupElement.call( this, config );
13500 $tabFocus = $( '<span>' );
13501 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: $tabFocus } ) );
13502 } else {
13503 this.popup = null;
13504 $tabFocus = null;
13505 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$input } ) );
13506 }
13507 OO.ui.mixin.IndicatorElement.call( this, config );
13508 OO.ui.mixin.IconElement.call( this, config );
13509
13510 // Properties
13511 this.$content = $( '<div>' );
13512 this.allowArbitrary = !!config.allowArbitrary;
13513 this.$overlay = config.$overlay || this.$element;
13514 this.menu = new OO.ui.FloatingMenuSelectWidget( $.extend(
13515 {
13516 widget: this,
13517 $input: this.$input,
13518 $container: this.$element,
13519 filterFromInput: true,
13520 disabled: this.isDisabled()
13521 },
13522 config.menu
13523 ) );
13524
13525 // Events
13526 if ( this.popup ) {
13527 $tabFocus.on( {
13528 focus: this.onFocusForPopup.bind( this )
13529 } );
13530 this.popup.$element.on( 'focusout', this.onPopupFocusOut.bind( this ) );
13531 if ( this.popup.$autoCloseIgnore ) {
13532 this.popup.$autoCloseIgnore.on( 'focusout', this.onPopupFocusOut.bind( this ) );
13533 }
13534 this.popup.connect( this, {
13535 toggle: function ( visible ) {
13536 $tabFocus.toggle( !visible );
13537 }
13538 } );
13539 } else {
13540 this.$input.on( {
13541 focus: this.onInputFocus.bind( this ),
13542 blur: this.onInputBlur.bind( this ),
13543 'propertychange change click mouseup keydown keyup input cut paste select focus':
13544 OO.ui.debounce( this.updateInputSize.bind( this ) ),
13545 keydown: this.onKeyDown.bind( this ),
13546 keypress: this.onKeyPress.bind( this )
13547 } );
13548 }
13549 this.menu.connect( this, {
13550 choose: 'onMenuChoose',
13551 add: 'onMenuItemsChange',
13552 remove: 'onMenuItemsChange'
13553 } );
13554 this.$handle.on( {
13555 mousedown: this.onMouseDown.bind( this )
13556 } );
13557
13558 // Initialization
13559 if ( this.$input ) {
13560 this.$input.prop( 'disabled', this.isDisabled() );
13561 this.$input.attr( {
13562 role: 'combobox',
13563 'aria-autocomplete': 'list'
13564 } );
13565 this.updateInputSize();
13566 }
13567 if ( config.data ) {
13568 this.setItemsFromData( config.data );
13569 }
13570 this.$content.addClass( 'oo-ui-capsuleMultiSelectWidget-content' )
13571 .append( this.$group );
13572 this.$group.addClass( 'oo-ui-capsuleMultiSelectWidget-group' );
13573 this.$handle.addClass( 'oo-ui-capsuleMultiSelectWidget-handle' )
13574 .append( this.$indicator, this.$icon, this.$content );
13575 this.$element.addClass( 'oo-ui-capsuleMultiSelectWidget' )
13576 .append( this.$handle );
13577 if ( this.popup ) {
13578 this.$content.append( $tabFocus );
13579 this.$overlay.append( this.popup.$element );
13580 } else {
13581 this.$content.append( this.$input );
13582 this.$overlay.append( this.menu.$element );
13583 }
13584 this.onMenuItemsChange();
13585 };
13586
13587 /* Setup */
13588
13589 OO.inheritClass( OO.ui.CapsuleMultiSelectWidget, OO.ui.Widget );
13590 OO.mixinClass( OO.ui.CapsuleMultiSelectWidget, OO.ui.mixin.GroupElement );
13591 OO.mixinClass( OO.ui.CapsuleMultiSelectWidget, OO.ui.mixin.PopupElement );
13592 OO.mixinClass( OO.ui.CapsuleMultiSelectWidget, OO.ui.mixin.TabIndexedElement );
13593 OO.mixinClass( OO.ui.CapsuleMultiSelectWidget, OO.ui.mixin.IndicatorElement );
13594 OO.mixinClass( OO.ui.CapsuleMultiSelectWidget, OO.ui.mixin.IconElement );
13595
13596 /* Events */
13597
13598 /**
13599 * @event change
13600 *
13601 * A change event is emitted when the set of selected items changes.
13602 *
13603 * @param {Mixed[]} datas Data of the now-selected items
13604 */
13605
13606 /* Methods */
13607
13608 /**
13609 * Construct a OO.ui.CapsuleItemWidget (or a subclass thereof) from given label and data.
13610 *
13611 * @protected
13612 * @param {Mixed} data Custom data of any type.
13613 * @param {string} label The label text.
13614 * @return {OO.ui.CapsuleItemWidget}
13615 */
13616 OO.ui.CapsuleMultiSelectWidget.prototype.createItemWidget = function ( data, label ) {
13617 return new OO.ui.CapsuleItemWidget( { data: data, label: label } );
13618 };
13619
13620 /**
13621 * Get the data of the items in the capsule
13622 * @return {Mixed[]}
13623 */
13624 OO.ui.CapsuleMultiSelectWidget.prototype.getItemsData = function () {
13625 return $.map( this.getItems(), function ( e ) { return e.data; } );
13626 };
13627
13628 /**
13629 * Set the items in the capsule by providing data
13630 * @chainable
13631 * @param {Mixed[]} datas
13632 * @return {OO.ui.CapsuleMultiSelectWidget}
13633 */
13634 OO.ui.CapsuleMultiSelectWidget.prototype.setItemsFromData = function ( datas ) {
13635 var widget = this,
13636 menu = this.menu,
13637 items = this.getItems();
13638
13639 $.each( datas, function ( i, data ) {
13640 var j, label,
13641 item = menu.getItemFromData( data );
13642
13643 if ( item ) {
13644 label = item.label;
13645 } else if ( widget.allowArbitrary ) {
13646 label = String( data );
13647 } else {
13648 return;
13649 }
13650
13651 item = null;
13652 for ( j = 0; j < items.length; j++ ) {
13653 if ( items[ j ].data === data && items[ j ].label === label ) {
13654 item = items[ j ];
13655 items.splice( j, 1 );
13656 break;
13657 }
13658 }
13659 if ( !item ) {
13660 item = widget.createItemWidget( data, label );
13661 }
13662 widget.addItems( [ item ], i );
13663 } );
13664
13665 if ( items.length ) {
13666 widget.removeItems( items );
13667 }
13668
13669 return this;
13670 };
13671
13672 /**
13673 * Add items to the capsule by providing their data
13674 * @chainable
13675 * @param {Mixed[]} datas
13676 * @return {OO.ui.CapsuleMultiSelectWidget}
13677 */
13678 OO.ui.CapsuleMultiSelectWidget.prototype.addItemsFromData = function ( datas ) {
13679 var widget = this,
13680 menu = this.menu,
13681 items = [];
13682
13683 $.each( datas, function ( i, data ) {
13684 var item;
13685
13686 if ( !widget.getItemFromData( data ) ) {
13687 item = menu.getItemFromData( data );
13688 if ( item ) {
13689 items.push( widget.createItemWidget( data, item.label ) );
13690 } else if ( widget.allowArbitrary ) {
13691 items.push( widget.createItemWidget( data, String( data ) ) );
13692 }
13693 }
13694 } );
13695
13696 if ( items.length ) {
13697 this.addItems( items );
13698 }
13699
13700 return this;
13701 };
13702
13703 /**
13704 * Remove items by data
13705 * @chainable
13706 * @param {Mixed[]} datas
13707 * @return {OO.ui.CapsuleMultiSelectWidget}
13708 */
13709 OO.ui.CapsuleMultiSelectWidget.prototype.removeItemsFromData = function ( datas ) {
13710 var widget = this,
13711 items = [];
13712
13713 $.each( datas, function ( i, data ) {
13714 var item = widget.getItemFromData( data );
13715 if ( item ) {
13716 items.push( item );
13717 }
13718 } );
13719
13720 if ( items.length ) {
13721 this.removeItems( items );
13722 }
13723
13724 return this;
13725 };
13726
13727 /**
13728 * @inheritdoc
13729 */
13730 OO.ui.CapsuleMultiSelectWidget.prototype.addItems = function ( items ) {
13731 var same, i, l,
13732 oldItems = this.items.slice();
13733
13734 OO.ui.mixin.GroupElement.prototype.addItems.call( this, items );
13735
13736 if ( this.items.length !== oldItems.length ) {
13737 same = false;
13738 } else {
13739 same = true;
13740 for ( i = 0, l = oldItems.length; same && i < l; i++ ) {
13741 same = same && this.items[ i ] === oldItems[ i ];
13742 }
13743 }
13744 if ( !same ) {
13745 this.emit( 'change', this.getItemsData() );
13746 this.menu.position();
13747 }
13748
13749 return this;
13750 };
13751
13752 /**
13753 * @inheritdoc
13754 */
13755 OO.ui.CapsuleMultiSelectWidget.prototype.removeItems = function ( items ) {
13756 var same, i, l,
13757 oldItems = this.items.slice();
13758
13759 OO.ui.mixin.GroupElement.prototype.removeItems.call( this, items );
13760
13761 if ( this.items.length !== oldItems.length ) {
13762 same = false;
13763 } else {
13764 same = true;
13765 for ( i = 0, l = oldItems.length; same && i < l; i++ ) {
13766 same = same && this.items[ i ] === oldItems[ i ];
13767 }
13768 }
13769 if ( !same ) {
13770 this.emit( 'change', this.getItemsData() );
13771 this.menu.position();
13772 }
13773
13774 return this;
13775 };
13776
13777 /**
13778 * @inheritdoc
13779 */
13780 OO.ui.CapsuleMultiSelectWidget.prototype.clearItems = function () {
13781 if ( this.items.length ) {
13782 OO.ui.mixin.GroupElement.prototype.clearItems.call( this );
13783 this.emit( 'change', this.getItemsData() );
13784 this.menu.position();
13785 }
13786 return this;
13787 };
13788
13789 /**
13790 * Get the capsule widget's menu.
13791 * @return {OO.ui.MenuSelectWidget} Menu widget
13792 */
13793 OO.ui.CapsuleMultiSelectWidget.prototype.getMenu = function () {
13794 return this.menu;
13795 };
13796
13797 /**
13798 * Handle focus events
13799 *
13800 * @private
13801 * @param {jQuery.Event} event
13802 */
13803 OO.ui.CapsuleMultiSelectWidget.prototype.onInputFocus = function () {
13804 if ( !this.isDisabled() ) {
13805 this.menu.toggle( true );
13806 }
13807 };
13808
13809 /**
13810 * Handle blur events
13811 *
13812 * @private
13813 * @param {jQuery.Event} event
13814 */
13815 OO.ui.CapsuleMultiSelectWidget.prototype.onInputBlur = function () {
13816 if ( this.allowArbitrary && this.$input.val().trim() !== '' ) {
13817 this.addItemsFromData( [ this.$input.val() ] );
13818 }
13819 this.clearInput();
13820 };
13821
13822 /**
13823 * Handle focus events
13824 *
13825 * @private
13826 * @param {jQuery.Event} event
13827 */
13828 OO.ui.CapsuleMultiSelectWidget.prototype.onFocusForPopup = function () {
13829 if ( !this.isDisabled() ) {
13830 this.popup.setSize( this.$handle.width() );
13831 this.popup.toggle( true );
13832 this.popup.$element.find( '*' )
13833 .filter( function () { return OO.ui.isFocusableElement( $( this ), true ); } )
13834 .first()
13835 .focus();
13836 }
13837 };
13838
13839 /**
13840 * Handles popup focus out events.
13841 *
13842 * @private
13843 * @param {Event} e Focus out event
13844 */
13845 OO.ui.CapsuleMultiSelectWidget.prototype.onPopupFocusOut = function () {
13846 var widget = this.popup;
13847
13848 setTimeout( function () {
13849 if (
13850 widget.isVisible() &&
13851 !OO.ui.contains( widget.$element[ 0 ], document.activeElement, true ) &&
13852 ( !widget.$autoCloseIgnore || !widget.$autoCloseIgnore.has( document.activeElement ).length )
13853 ) {
13854 widget.toggle( false );
13855 }
13856 } );
13857 };
13858
13859 /**
13860 * Handle mouse down events.
13861 *
13862 * @private
13863 * @param {jQuery.Event} e Mouse down event
13864 */
13865 OO.ui.CapsuleMultiSelectWidget.prototype.onMouseDown = function ( e ) {
13866 if ( e.which === 1 ) {
13867 this.focus();
13868 return false;
13869 } else {
13870 this.updateInputSize();
13871 }
13872 };
13873
13874 /**
13875 * Handle key press events.
13876 *
13877 * @private
13878 * @param {jQuery.Event} e Key press event
13879 */
13880 OO.ui.CapsuleMultiSelectWidget.prototype.onKeyPress = function ( e ) {
13881 var item;
13882
13883 if ( !this.isDisabled() ) {
13884 if ( e.which === OO.ui.Keys.ESCAPE ) {
13885 this.clearInput();
13886 return false;
13887 }
13888
13889 if ( !this.popup ) {
13890 this.menu.toggle( true );
13891 if ( e.which === OO.ui.Keys.ENTER ) {
13892 item = this.menu.getItemFromLabel( this.$input.val(), true );
13893 if ( item ) {
13894 this.addItemsFromData( [ item.data ] );
13895 this.clearInput();
13896 } else if ( this.allowArbitrary && this.$input.val().trim() !== '' ) {
13897 this.addItemsFromData( [ this.$input.val() ] );
13898 this.clearInput();
13899 }
13900 return false;
13901 }
13902
13903 // Make sure the input gets resized.
13904 setTimeout( this.updateInputSize.bind( this ), 0 );
13905 }
13906 }
13907 };
13908
13909 /**
13910 * Handle key down events.
13911 *
13912 * @private
13913 * @param {jQuery.Event} e Key down event
13914 */
13915 OO.ui.CapsuleMultiSelectWidget.prototype.onKeyDown = function ( e ) {
13916 if ( !this.isDisabled() ) {
13917 // 'keypress' event is not triggered for Backspace
13918 if ( e.keyCode === OO.ui.Keys.BACKSPACE && this.$input.val() === '' ) {
13919 if ( this.items.length ) {
13920 this.removeItems( this.items.slice( -1 ) );
13921 }
13922 return false;
13923 }
13924 }
13925 };
13926
13927 /**
13928 * Update the dimensions of the text input field to encompass all available area.
13929 *
13930 * @private
13931 * @param {jQuery.Event} e Event of some sort
13932 */
13933 OO.ui.CapsuleMultiSelectWidget.prototype.updateInputSize = function () {
13934 var $lastItem, direction, contentWidth, currentWidth, bestWidth;
13935 if ( !this.isDisabled() ) {
13936 this.$input.css( 'width', '1em' );
13937 $lastItem = this.$group.children().last();
13938 direction = OO.ui.Element.static.getDir( this.$handle );
13939 contentWidth = this.$input[ 0 ].scrollWidth;
13940 currentWidth = this.$input.width();
13941
13942 if ( contentWidth < currentWidth ) {
13943 // All is fine, don't perform expensive calculations
13944 return;
13945 }
13946
13947 if ( !$lastItem.length ) {
13948 bestWidth = this.$content.innerWidth();
13949 } else {
13950 bestWidth = direction === 'ltr' ?
13951 this.$content.innerWidth() - $lastItem.position().left - $lastItem.outerWidth() :
13952 $lastItem.position().left;
13953 }
13954 // Some safety margin for sanity, because I *really* don't feel like finding out where the few
13955 // pixels this is off by are coming from.
13956 bestWidth -= 10;
13957 if ( contentWidth > bestWidth ) {
13958 // This will result in the input getting shifted to the next line
13959 bestWidth = this.$content.innerWidth() - 10;
13960 }
13961 this.$input.width( Math.floor( bestWidth ) );
13962
13963 this.menu.position();
13964 }
13965 };
13966
13967 /**
13968 * Handle menu choose events.
13969 *
13970 * @private
13971 * @param {OO.ui.OptionWidget} item Chosen item
13972 */
13973 OO.ui.CapsuleMultiSelectWidget.prototype.onMenuChoose = function ( item ) {
13974 if ( item && item.isVisible() ) {
13975 this.addItemsFromData( [ item.getData() ] );
13976 this.clearInput();
13977 }
13978 };
13979
13980 /**
13981 * Handle menu item change events.
13982 *
13983 * @private
13984 */
13985 OO.ui.CapsuleMultiSelectWidget.prototype.onMenuItemsChange = function () {
13986 this.setItemsFromData( this.getItemsData() );
13987 this.$element.toggleClass( 'oo-ui-capsuleMultiSelectWidget-empty', this.menu.isEmpty() );
13988 };
13989
13990 /**
13991 * Clear the input field
13992 * @private
13993 */
13994 OO.ui.CapsuleMultiSelectWidget.prototype.clearInput = function () {
13995 if ( this.$input ) {
13996 this.$input.val( '' );
13997 this.updateInputSize();
13998 }
13999 if ( this.popup ) {
14000 this.popup.toggle( false );
14001 }
14002 this.menu.toggle( false );
14003 this.menu.selectItem();
14004 this.menu.highlightItem();
14005 };
14006
14007 /**
14008 * @inheritdoc
14009 */
14010 OO.ui.CapsuleMultiSelectWidget.prototype.setDisabled = function ( disabled ) {
14011 var i, len;
14012
14013 // Parent method
14014 OO.ui.CapsuleMultiSelectWidget.parent.prototype.setDisabled.call( this, disabled );
14015
14016 if ( this.$input ) {
14017 this.$input.prop( 'disabled', this.isDisabled() );
14018 }
14019 if ( this.menu ) {
14020 this.menu.setDisabled( this.isDisabled() );
14021 }
14022 if ( this.popup ) {
14023 this.popup.setDisabled( this.isDisabled() );
14024 }
14025
14026 if ( this.items ) {
14027 for ( i = 0, len = this.items.length; i < len; i++ ) {
14028 this.items[ i ].updateDisabled();
14029 }
14030 }
14031
14032 return this;
14033 };
14034
14035 /**
14036 * Focus the widget
14037 * @chainable
14038 * @return {OO.ui.CapsuleMultiSelectWidget}
14039 */
14040 OO.ui.CapsuleMultiSelectWidget.prototype.focus = function () {
14041 if ( !this.isDisabled() ) {
14042 if ( this.popup ) {
14043 this.popup.setSize( this.$handle.width() );
14044 this.popup.toggle( true );
14045 this.popup.$element.find( '*' )
14046 .filter( function () { return OO.ui.isFocusableElement( $( this ), true ); } )
14047 .first()
14048 .focus();
14049 } else {
14050 this.updateInputSize();
14051 this.menu.toggle( true );
14052 this.$input.focus();
14053 }
14054 }
14055 return this;
14056 };
14057
14058 /**
14059 * CapsuleItemWidgets are used within a {@link OO.ui.CapsuleMultiSelectWidget
14060 * CapsuleMultiSelectWidget} to display the selected items.
14061 *
14062 * @class
14063 * @extends OO.ui.Widget
14064 * @mixins OO.ui.mixin.ItemWidget
14065 * @mixins OO.ui.mixin.IndicatorElement
14066 * @mixins OO.ui.mixin.LabelElement
14067 * @mixins OO.ui.mixin.FlaggedElement
14068 * @mixins OO.ui.mixin.TabIndexedElement
14069 *
14070 * @constructor
14071 * @param {Object} [config] Configuration options
14072 */
14073 OO.ui.CapsuleItemWidget = function OoUiCapsuleItemWidget( config ) {
14074 // Configuration initialization
14075 config = config || {};
14076
14077 // Parent constructor
14078 OO.ui.CapsuleItemWidget.parent.call( this, config );
14079
14080 // Properties (must be set before mixin constructor calls)
14081 this.$indicator = $( '<span>' );
14082
14083 // Mixin constructors
14084 OO.ui.mixin.ItemWidget.call( this );
14085 OO.ui.mixin.IndicatorElement.call( this, $.extend( {}, config, { $indicator: this.$indicator, indicator: 'clear' } ) );
14086 OO.ui.mixin.LabelElement.call( this, config );
14087 OO.ui.mixin.FlaggedElement.call( this, config );
14088 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$indicator } ) );
14089
14090 // Events
14091 this.$indicator.on( {
14092 keydown: this.onCloseKeyDown.bind( this ),
14093 click: this.onCloseClick.bind( this )
14094 } );
14095
14096 // Initialization
14097 this.$element
14098 .addClass( 'oo-ui-capsuleItemWidget' )
14099 .append( this.$indicator, this.$label );
14100 };
14101
14102 /* Setup */
14103
14104 OO.inheritClass( OO.ui.CapsuleItemWidget, OO.ui.Widget );
14105 OO.mixinClass( OO.ui.CapsuleItemWidget, OO.ui.mixin.ItemWidget );
14106 OO.mixinClass( OO.ui.CapsuleItemWidget, OO.ui.mixin.IndicatorElement );
14107 OO.mixinClass( OO.ui.CapsuleItemWidget, OO.ui.mixin.LabelElement );
14108 OO.mixinClass( OO.ui.CapsuleItemWidget, OO.ui.mixin.FlaggedElement );
14109 OO.mixinClass( OO.ui.CapsuleItemWidget, OO.ui.mixin.TabIndexedElement );
14110
14111 /* Methods */
14112
14113 /**
14114 * Handle close icon clicks
14115 * @param {jQuery.Event} event
14116 */
14117 OO.ui.CapsuleItemWidget.prototype.onCloseClick = function () {
14118 var element = this.getElementGroup();
14119
14120 if ( !this.isDisabled() && element && $.isFunction( element.removeItems ) ) {
14121 element.removeItems( [ this ] );
14122 element.focus();
14123 }
14124 };
14125
14126 /**
14127 * Handle close keyboard events
14128 * @param {jQuery.Event} event Key down event
14129 */
14130 OO.ui.CapsuleItemWidget.prototype.onCloseKeyDown = function ( e ) {
14131 if ( !this.isDisabled() && $.isFunction( this.getElementGroup().removeItems ) ) {
14132 switch ( e.which ) {
14133 case OO.ui.Keys.ENTER:
14134 case OO.ui.Keys.BACKSPACE:
14135 case OO.ui.Keys.SPACE:
14136 this.getElementGroup().removeItems( [ this ] );
14137 return false;
14138 }
14139 }
14140 };
14141
14142 /**
14143 * DropdownWidgets are not menus themselves, rather they contain a menu of options created with
14144 * OO.ui.MenuOptionWidget. The DropdownWidget takes care of opening and displaying the menu so that
14145 * users can interact with it.
14146 *
14147 * If you want to use this within a HTML form, such as a OO.ui.FormLayout, use
14148 * OO.ui.DropdownInputWidget instead.
14149 *
14150 * @example
14151 * // Example: A DropdownWidget with a menu that contains three options
14152 * var dropDown = new OO.ui.DropdownWidget( {
14153 * label: 'Dropdown menu: Select a menu option',
14154 * menu: {
14155 * items: [
14156 * new OO.ui.MenuOptionWidget( {
14157 * data: 'a',
14158 * label: 'First'
14159 * } ),
14160 * new OO.ui.MenuOptionWidget( {
14161 * data: 'b',
14162 * label: 'Second'
14163 * } ),
14164 * new OO.ui.MenuOptionWidget( {
14165 * data: 'c',
14166 * label: 'Third'
14167 * } )
14168 * ]
14169 * }
14170 * } );
14171 *
14172 * $( 'body' ).append( dropDown.$element );
14173 *
14174 * dropDown.getMenu().selectItemByData( 'b' );
14175 *
14176 * dropDown.getMenu().getSelectedItem().getData(); // returns 'b'
14177 *
14178 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
14179 *
14180 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
14181 *
14182 * @class
14183 * @extends OO.ui.Widget
14184 * @mixins OO.ui.mixin.IconElement
14185 * @mixins OO.ui.mixin.IndicatorElement
14186 * @mixins OO.ui.mixin.LabelElement
14187 * @mixins OO.ui.mixin.TitledElement
14188 * @mixins OO.ui.mixin.TabIndexedElement
14189 *
14190 * @constructor
14191 * @param {Object} [config] Configuration options
14192 * @cfg {Object} [menu] Configuration options to pass to {@link OO.ui.FloatingMenuSelectWidget menu select widget}
14193 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
14194 * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
14195 * containing `<div>` and has a larger area. By default, the menu uses relative positioning.
14196 */
14197 OO.ui.DropdownWidget = function OoUiDropdownWidget( config ) {
14198 // Configuration initialization
14199 config = $.extend( { indicator: 'down' }, config );
14200
14201 // Parent constructor
14202 OO.ui.DropdownWidget.parent.call( this, config );
14203
14204 // Properties (must be set before TabIndexedElement constructor call)
14205 this.$handle = this.$( '<span>' );
14206 this.$overlay = config.$overlay || this.$element;
14207
14208 // Mixin constructors
14209 OO.ui.mixin.IconElement.call( this, config );
14210 OO.ui.mixin.IndicatorElement.call( this, config );
14211 OO.ui.mixin.LabelElement.call( this, config );
14212 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$label } ) );
14213 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$handle } ) );
14214
14215 // Properties
14216 this.menu = new OO.ui.FloatingMenuSelectWidget( $.extend( {
14217 widget: this,
14218 $container: this.$element
14219 }, config.menu ) );
14220
14221 // Events
14222 this.$handle.on( {
14223 click: this.onClick.bind( this ),
14224 keypress: this.onKeyPress.bind( this )
14225 } );
14226 this.menu.connect( this, { select: 'onMenuSelect' } );
14227
14228 // Initialization
14229 this.$handle
14230 .addClass( 'oo-ui-dropdownWidget-handle' )
14231 .append( this.$icon, this.$label, this.$indicator );
14232 this.$element
14233 .addClass( 'oo-ui-dropdownWidget' )
14234 .append( this.$handle );
14235 this.$overlay.append( this.menu.$element );
14236 };
14237
14238 /* Setup */
14239
14240 OO.inheritClass( OO.ui.DropdownWidget, OO.ui.Widget );
14241 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.IconElement );
14242 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.IndicatorElement );
14243 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.LabelElement );
14244 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.TitledElement );
14245 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.TabIndexedElement );
14246
14247 /* Methods */
14248
14249 /**
14250 * Get the menu.
14251 *
14252 * @return {OO.ui.MenuSelectWidget} Menu of widget
14253 */
14254 OO.ui.DropdownWidget.prototype.getMenu = function () {
14255 return this.menu;
14256 };
14257
14258 /**
14259 * Handles menu select events.
14260 *
14261 * @private
14262 * @param {OO.ui.MenuOptionWidget} item Selected menu item
14263 */
14264 OO.ui.DropdownWidget.prototype.onMenuSelect = function ( item ) {
14265 var selectedLabel;
14266
14267 if ( !item ) {
14268 this.setLabel( null );
14269 return;
14270 }
14271
14272 selectedLabel = item.getLabel();
14273
14274 // If the label is a DOM element, clone it, because setLabel will append() it
14275 if ( selectedLabel instanceof jQuery ) {
14276 selectedLabel = selectedLabel.clone();
14277 }
14278
14279 this.setLabel( selectedLabel );
14280 };
14281
14282 /**
14283 * Handle mouse click events.
14284 *
14285 * @private
14286 * @param {jQuery.Event} e Mouse click event
14287 */
14288 OO.ui.DropdownWidget.prototype.onClick = function ( e ) {
14289 if ( !this.isDisabled() && e.which === 1 ) {
14290 this.menu.toggle();
14291 }
14292 return false;
14293 };
14294
14295 /**
14296 * Handle key press events.
14297 *
14298 * @private
14299 * @param {jQuery.Event} e Key press event
14300 */
14301 OO.ui.DropdownWidget.prototype.onKeyPress = function ( e ) {
14302 if ( !this.isDisabled() &&
14303 ( ( e.which === OO.ui.Keys.SPACE && !this.menu.isVisible() ) || e.which === OO.ui.Keys.ENTER )
14304 ) {
14305 this.menu.toggle();
14306 return false;
14307 }
14308 };
14309
14310 /**
14311 * SelectFileWidgets allow for selecting files, using the HTML5 File API. These
14312 * widgets can be configured with {@link OO.ui.mixin.IconElement icons} and {@link
14313 * OO.ui.mixin.IndicatorElement indicators}.
14314 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
14315 *
14316 * @example
14317 * // Example of a file select widget
14318 * var selectFile = new OO.ui.SelectFileWidget();
14319 * $( 'body' ).append( selectFile.$element );
14320 *
14321 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets
14322 *
14323 * @class
14324 * @extends OO.ui.Widget
14325 * @mixins OO.ui.mixin.IconElement
14326 * @mixins OO.ui.mixin.IndicatorElement
14327 * @mixins OO.ui.mixin.PendingElement
14328 * @mixins OO.ui.mixin.LabelElement
14329 *
14330 * @constructor
14331 * @param {Object} [config] Configuration options
14332 * @cfg {string[]|null} [accept=null] MIME types to accept. null accepts all types.
14333 * @cfg {string} [placeholder] Text to display when no file is selected.
14334 * @cfg {string} [notsupported] Text to display when file support is missing in the browser.
14335 * @cfg {boolean} [droppable=true] Whether to accept files by drag and drop.
14336 * @cfg {boolean} [showDropTarget=false] Whether to show a drop target. Requires droppable to be true.
14337 * @cfg {boolean} [dragDropUI=false] Deprecated alias for showDropTarget
14338 */
14339 OO.ui.SelectFileWidget = function OoUiSelectFileWidget( config ) {
14340 var dragHandler;
14341
14342 // TODO: Remove in next release
14343 if ( config && config.dragDropUI ) {
14344 config.showDropTarget = true;
14345 }
14346
14347 // Configuration initialization
14348 config = $.extend( {
14349 accept: null,
14350 placeholder: OO.ui.msg( 'ooui-selectfile-placeholder' ),
14351 notsupported: OO.ui.msg( 'ooui-selectfile-not-supported' ),
14352 droppable: true,
14353 showDropTarget: false
14354 }, config );
14355
14356 // Parent constructor
14357 OO.ui.SelectFileWidget.parent.call( this, config );
14358
14359 // Mixin constructors
14360 OO.ui.mixin.IconElement.call( this, config );
14361 OO.ui.mixin.IndicatorElement.call( this, config );
14362 OO.ui.mixin.PendingElement.call( this, $.extend( {}, config, { $pending: this.$info } ) );
14363 OO.ui.mixin.LabelElement.call( this, $.extend( {}, config, { autoFitLabel: true } ) );
14364
14365 // Properties
14366 this.$info = $( '<span>' );
14367
14368 // Properties
14369 this.showDropTarget = config.showDropTarget;
14370 this.isSupported = this.constructor.static.isSupported();
14371 this.currentFile = null;
14372 if ( Array.isArray( config.accept ) ) {
14373 this.accept = config.accept;
14374 } else {
14375 this.accept = null;
14376 }
14377 this.placeholder = config.placeholder;
14378 this.notsupported = config.notsupported;
14379 this.onFileSelectedHandler = this.onFileSelected.bind( this );
14380
14381 this.selectButton = new OO.ui.ButtonWidget( {
14382 classes: [ 'oo-ui-selectFileWidget-selectButton' ],
14383 label: OO.ui.msg( 'ooui-selectfile-button-select' ),
14384 disabled: this.disabled || !this.isSupported
14385 } );
14386
14387 this.clearButton = new OO.ui.ButtonWidget( {
14388 classes: [ 'oo-ui-selectFileWidget-clearButton' ],
14389 framed: false,
14390 icon: 'remove',
14391 disabled: this.disabled
14392 } );
14393
14394 // Events
14395 this.selectButton.$button.on( {
14396 keypress: this.onKeyPress.bind( this )
14397 } );
14398 this.clearButton.connect( this, {
14399 click: 'onClearClick'
14400 } );
14401 if ( config.droppable ) {
14402 dragHandler = this.onDragEnterOrOver.bind( this );
14403 this.$element.on( {
14404 dragenter: dragHandler,
14405 dragover: dragHandler,
14406 dragleave: this.onDragLeave.bind( this ),
14407 drop: this.onDrop.bind( this )
14408 } );
14409 }
14410
14411 // Initialization
14412 this.addInput();
14413 this.updateUI();
14414 this.$label.addClass( 'oo-ui-selectFileWidget-label' );
14415 this.$info
14416 .addClass( 'oo-ui-selectFileWidget-info' )
14417 .append( this.$icon, this.$label, this.clearButton.$element, this.$indicator );
14418 this.$element
14419 .addClass( 'oo-ui-selectFileWidget' )
14420 .append( this.$info, this.selectButton.$element );
14421 if ( config.droppable && config.showDropTarget ) {
14422 this.$dropTarget = $( '<div>' )
14423 .addClass( 'oo-ui-selectFileWidget-dropTarget' )
14424 .text( OO.ui.msg( 'ooui-selectfile-dragdrop-placeholder' ) )
14425 .on( {
14426 click: this.onDropTargetClick.bind( this )
14427 } );
14428 this.$element.prepend( this.$dropTarget );
14429 }
14430 };
14431
14432 /* Setup */
14433
14434 OO.inheritClass( OO.ui.SelectFileWidget, OO.ui.Widget );
14435 OO.mixinClass( OO.ui.SelectFileWidget, OO.ui.mixin.IconElement );
14436 OO.mixinClass( OO.ui.SelectFileWidget, OO.ui.mixin.IndicatorElement );
14437 OO.mixinClass( OO.ui.SelectFileWidget, OO.ui.mixin.PendingElement );
14438 OO.mixinClass( OO.ui.SelectFileWidget, OO.ui.mixin.LabelElement );
14439
14440 /* Static Properties */
14441
14442 /**
14443 * Check if this widget is supported
14444 *
14445 * @static
14446 * @return {boolean}
14447 */
14448 OO.ui.SelectFileWidget.static.isSupported = function () {
14449 var $input;
14450 if ( OO.ui.SelectFileWidget.static.isSupportedCache === null ) {
14451 $input = $( '<input type="file">' );
14452 OO.ui.SelectFileWidget.static.isSupportedCache = $input[ 0 ].files !== undefined;
14453 }
14454 return OO.ui.SelectFileWidget.static.isSupportedCache;
14455 };
14456
14457 OO.ui.SelectFileWidget.static.isSupportedCache = null;
14458
14459 /* Events */
14460
14461 /**
14462 * @event change
14463 *
14464 * A change event is emitted when the on/off state of the toggle changes.
14465 *
14466 * @param {File|null} value New value
14467 */
14468
14469 /* Methods */
14470
14471 /**
14472 * Get the current value of the field
14473 *
14474 * @return {File|null}
14475 */
14476 OO.ui.SelectFileWidget.prototype.getValue = function () {
14477 return this.currentFile;
14478 };
14479
14480 /**
14481 * Set the current value of the field
14482 *
14483 * @param {File|null} file File to select
14484 */
14485 OO.ui.SelectFileWidget.prototype.setValue = function ( file ) {
14486 if ( this.currentFile !== file ) {
14487 this.currentFile = file;
14488 this.updateUI();
14489 this.emit( 'change', this.currentFile );
14490 }
14491 };
14492
14493 /**
14494 * Focus the widget.
14495 *
14496 * Focusses the select file button.
14497 *
14498 * @chainable
14499 */
14500 OO.ui.SelectFileWidget.prototype.focus = function () {
14501 this.selectButton.$button[ 0 ].focus();
14502 return this;
14503 };
14504
14505 /**
14506 * Update the user interface when a file is selected or unselected
14507 *
14508 * @protected
14509 */
14510 OO.ui.SelectFileWidget.prototype.updateUI = function () {
14511 var $label;
14512 if ( !this.isSupported ) {
14513 this.$element.addClass( 'oo-ui-selectFileWidget-notsupported' );
14514 this.$element.removeClass( 'oo-ui-selectFileWidget-empty' );
14515 this.setLabel( this.notsupported );
14516 } else {
14517 this.$element.addClass( 'oo-ui-selectFileWidget-supported' );
14518 if ( this.currentFile ) {
14519 this.$element.removeClass( 'oo-ui-selectFileWidget-empty' );
14520 $label = $( [] );
14521 if ( this.currentFile.type !== '' ) {
14522 $label = $label.add( $( '<span>' ).addClass( 'oo-ui-selectFileWidget-fileType' ).text( this.currentFile.type ) );
14523 }
14524 $label = $label.add( $( '<span>' ).text( this.currentFile.name ) );
14525 this.setLabel( $label );
14526 } else {
14527 this.$element.addClass( 'oo-ui-selectFileWidget-empty' );
14528 this.setLabel( this.placeholder );
14529 }
14530 }
14531 };
14532
14533 /**
14534 * Add the input to the widget
14535 *
14536 * @private
14537 */
14538 OO.ui.SelectFileWidget.prototype.addInput = function () {
14539 if ( this.$input ) {
14540 this.$input.remove();
14541 }
14542
14543 if ( !this.isSupported ) {
14544 this.$input = null;
14545 return;
14546 }
14547
14548 this.$input = $( '<input type="file">' );
14549 this.$input.on( 'change', this.onFileSelectedHandler );
14550 this.$input.attr( {
14551 tabindex: -1
14552 } );
14553 if ( this.accept ) {
14554 this.$input.attr( 'accept', this.accept.join( ', ' ) );
14555 }
14556 this.selectButton.$button.append( this.$input );
14557 };
14558
14559 /**
14560 * Determine if we should accept this file
14561 *
14562 * @private
14563 * @param {string} File MIME type
14564 * @return {boolean}
14565 */
14566 OO.ui.SelectFileWidget.prototype.isAllowedType = function ( mimeType ) {
14567 var i, mimeTest;
14568
14569 if ( !this.accept || !mimeType ) {
14570 return true;
14571 }
14572
14573 for ( i = 0; i < this.accept.length; i++ ) {
14574 mimeTest = this.accept[ i ];
14575 if ( mimeTest === mimeType ) {
14576 return true;
14577 } else if ( mimeTest.substr( -2 ) === '/*' ) {
14578 mimeTest = mimeTest.substr( 0, mimeTest.length - 1 );
14579 if ( mimeType.substr( 0, mimeTest.length ) === mimeTest ) {
14580 return true;
14581 }
14582 }
14583 }
14584
14585 return false;
14586 };
14587
14588 /**
14589 * Handle file selection from the input
14590 *
14591 * @private
14592 * @param {jQuery.Event} e
14593 */
14594 OO.ui.SelectFileWidget.prototype.onFileSelected = function ( e ) {
14595 var file = OO.getProp( e.target, 'files', 0 ) || null;
14596
14597 if ( file && !this.isAllowedType( file.type ) ) {
14598 file = null;
14599 }
14600
14601 this.setValue( file );
14602 this.addInput();
14603 };
14604
14605 /**
14606 * Handle clear button click events.
14607 *
14608 * @private
14609 */
14610 OO.ui.SelectFileWidget.prototype.onClearClick = function () {
14611 this.setValue( null );
14612 return false;
14613 };
14614
14615 /**
14616 * Handle key press events.
14617 *
14618 * @private
14619 * @param {jQuery.Event} e Key press event
14620 */
14621 OO.ui.SelectFileWidget.prototype.onKeyPress = function ( e ) {
14622 if ( this.isSupported && !this.isDisabled() && this.$input &&
14623 ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
14624 ) {
14625 this.$input.click();
14626 return false;
14627 }
14628 };
14629
14630 /**
14631 * Handle drop target click events.
14632 *
14633 * @private
14634 * @param {jQuery.Event} e Key press event
14635 */
14636 OO.ui.SelectFileWidget.prototype.onDropTargetClick = function () {
14637 if ( this.isSupported && !this.isDisabled() && this.$input ) {
14638 this.$input.click();
14639 return false;
14640 }
14641 };
14642
14643 /**
14644 * Handle drag enter and over events
14645 *
14646 * @private
14647 * @param {jQuery.Event} e Drag event
14648 */
14649 OO.ui.SelectFileWidget.prototype.onDragEnterOrOver = function ( e ) {
14650 var itemOrFile,
14651 droppableFile = false,
14652 dt = e.originalEvent.dataTransfer;
14653
14654 e.preventDefault();
14655 e.stopPropagation();
14656
14657 if ( this.isDisabled() || !this.isSupported ) {
14658 this.$element.removeClass( 'oo-ui-selectFileWidget-canDrop' );
14659 dt.dropEffect = 'none';
14660 return false;
14661 }
14662
14663 // DataTransferItem and File both have a type property, but in Chrome files
14664 // have no information at this point.
14665 itemOrFile = OO.getProp( dt, 'items', 0 ) || OO.getProp( dt, 'files', 0 );
14666 if ( itemOrFile ) {
14667 if ( this.isAllowedType( itemOrFile.type ) ) {
14668 droppableFile = true;
14669 }
14670 // dt.types is Array-like, but not an Array
14671 } else if ( Array.prototype.indexOf.call( OO.getProp( dt, 'types' ) || [], 'Files' ) !== -1 ) {
14672 // File information is not available at this point for security so just assume
14673 // it is acceptable for now.
14674 // https://bugzilla.mozilla.org/show_bug.cgi?id=640534
14675 droppableFile = true;
14676 }
14677
14678 this.$element.toggleClass( 'oo-ui-selectFileWidget-canDrop', droppableFile );
14679 if ( !droppableFile ) {
14680 dt.dropEffect = 'none';
14681 }
14682
14683 return false;
14684 };
14685
14686 /**
14687 * Handle drag leave events
14688 *
14689 * @private
14690 * @param {jQuery.Event} e Drag event
14691 */
14692 OO.ui.SelectFileWidget.prototype.onDragLeave = function () {
14693 this.$element.removeClass( 'oo-ui-selectFileWidget-canDrop' );
14694 };
14695
14696 /**
14697 * Handle drop events
14698 *
14699 * @private
14700 * @param {jQuery.Event} e Drop event
14701 */
14702 OO.ui.SelectFileWidget.prototype.onDrop = function ( e ) {
14703 var file = null,
14704 dt = e.originalEvent.dataTransfer;
14705
14706 e.preventDefault();
14707 e.stopPropagation();
14708 this.$element.removeClass( 'oo-ui-selectFileWidget-canDrop' );
14709
14710 if ( this.isDisabled() || !this.isSupported ) {
14711 return false;
14712 }
14713
14714 file = OO.getProp( dt, 'files', 0 );
14715 if ( file && !this.isAllowedType( file.type ) ) {
14716 file = null;
14717 }
14718 if ( file ) {
14719 this.setValue( file );
14720 }
14721
14722 return false;
14723 };
14724
14725 /**
14726 * @inheritdoc
14727 */
14728 OO.ui.SelectFileWidget.prototype.setDisabled = function ( disabled ) {
14729 OO.ui.SelectFileWidget.parent.prototype.setDisabled.call( this, disabled );
14730 if ( this.selectButton ) {
14731 this.selectButton.setDisabled( disabled );
14732 }
14733 if ( this.clearButton ) {
14734 this.clearButton.setDisabled( disabled );
14735 }
14736 return this;
14737 };
14738
14739 /**
14740 * IconWidget is a generic widget for {@link OO.ui.mixin.IconElement icons}. In general, IconWidgets should be used with OO.ui.LabelWidget,
14741 * which creates a label that identifies the icon’s function. See the [OOjs UI documentation on MediaWiki] [1]
14742 * for a list of icons included in the library.
14743 *
14744 * @example
14745 * // An icon widget with a label
14746 * var myIcon = new OO.ui.IconWidget( {
14747 * icon: 'help',
14748 * iconTitle: 'Help'
14749 * } );
14750 * // Create a label.
14751 * var iconLabel = new OO.ui.LabelWidget( {
14752 * label: 'Help'
14753 * } );
14754 * $( 'body' ).append( myIcon.$element, iconLabel.$element );
14755 *
14756 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
14757 *
14758 * @class
14759 * @extends OO.ui.Widget
14760 * @mixins OO.ui.mixin.IconElement
14761 * @mixins OO.ui.mixin.TitledElement
14762 * @mixins OO.ui.mixin.FlaggedElement
14763 *
14764 * @constructor
14765 * @param {Object} [config] Configuration options
14766 */
14767 OO.ui.IconWidget = function OoUiIconWidget( config ) {
14768 // Configuration initialization
14769 config = config || {};
14770
14771 // Parent constructor
14772 OO.ui.IconWidget.parent.call( this, config );
14773
14774 // Mixin constructors
14775 OO.ui.mixin.IconElement.call( this, $.extend( {}, config, { $icon: this.$element } ) );
14776 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$element } ) );
14777 OO.ui.mixin.FlaggedElement.call( this, $.extend( {}, config, { $flagged: this.$element } ) );
14778
14779 // Initialization
14780 this.$element.addClass( 'oo-ui-iconWidget' );
14781 };
14782
14783 /* Setup */
14784
14785 OO.inheritClass( OO.ui.IconWidget, OO.ui.Widget );
14786 OO.mixinClass( OO.ui.IconWidget, OO.ui.mixin.IconElement );
14787 OO.mixinClass( OO.ui.IconWidget, OO.ui.mixin.TitledElement );
14788 OO.mixinClass( OO.ui.IconWidget, OO.ui.mixin.FlaggedElement );
14789
14790 /* Static Properties */
14791
14792 OO.ui.IconWidget.static.tagName = 'span';
14793
14794 /**
14795 * IndicatorWidgets create indicators, which are small graphics that are generally used to draw
14796 * attention to the status of an item or to clarify the function of a control. For a list of
14797 * indicators included in the library, please see the [OOjs UI documentation on MediaWiki][1].
14798 *
14799 * @example
14800 * // Example of an indicator widget
14801 * var indicator1 = new OO.ui.IndicatorWidget( {
14802 * indicator: 'alert'
14803 * } );
14804 *
14805 * // Create a fieldset layout to add a label
14806 * var fieldset = new OO.ui.FieldsetLayout();
14807 * fieldset.addItems( [
14808 * new OO.ui.FieldLayout( indicator1, { label: 'An alert indicator:' } )
14809 * ] );
14810 * $( 'body' ).append( fieldset.$element );
14811 *
14812 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
14813 *
14814 * @class
14815 * @extends OO.ui.Widget
14816 * @mixins OO.ui.mixin.IndicatorElement
14817 * @mixins OO.ui.mixin.TitledElement
14818 *
14819 * @constructor
14820 * @param {Object} [config] Configuration options
14821 */
14822 OO.ui.IndicatorWidget = function OoUiIndicatorWidget( config ) {
14823 // Configuration initialization
14824 config = config || {};
14825
14826 // Parent constructor
14827 OO.ui.IndicatorWidget.parent.call( this, config );
14828
14829 // Mixin constructors
14830 OO.ui.mixin.IndicatorElement.call( this, $.extend( {}, config, { $indicator: this.$element } ) );
14831 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$element } ) );
14832
14833 // Initialization
14834 this.$element.addClass( 'oo-ui-indicatorWidget' );
14835 };
14836
14837 /* Setup */
14838
14839 OO.inheritClass( OO.ui.IndicatorWidget, OO.ui.Widget );
14840 OO.mixinClass( OO.ui.IndicatorWidget, OO.ui.mixin.IndicatorElement );
14841 OO.mixinClass( OO.ui.IndicatorWidget, OO.ui.mixin.TitledElement );
14842
14843 /* Static Properties */
14844
14845 OO.ui.IndicatorWidget.static.tagName = 'span';
14846
14847 /**
14848 * InputWidget is the base class for all input widgets, which
14849 * include {@link OO.ui.TextInputWidget text inputs}, {@link OO.ui.CheckboxInputWidget checkbox inputs},
14850 * {@link OO.ui.RadioInputWidget radio inputs}, and {@link OO.ui.ButtonInputWidget button inputs}.
14851 * See the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
14852 *
14853 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
14854 *
14855 * @abstract
14856 * @class
14857 * @extends OO.ui.Widget
14858 * @mixins OO.ui.mixin.FlaggedElement
14859 * @mixins OO.ui.mixin.TabIndexedElement
14860 * @mixins OO.ui.mixin.TitledElement
14861 * @mixins OO.ui.mixin.AccessKeyedElement
14862 *
14863 * @constructor
14864 * @param {Object} [config] Configuration options
14865 * @cfg {string} [name=''] The value of the input’s HTML `name` attribute.
14866 * @cfg {string} [value=''] The value of the input.
14867 * @cfg {string} [dir] The directionality of the input (ltr/rtl).
14868 * @cfg {Function} [inputFilter] The name of an input filter function. Input filters modify the value of an input
14869 * before it is accepted.
14870 */
14871 OO.ui.InputWidget = function OoUiInputWidget( config ) {
14872 // Configuration initialization
14873 config = config || {};
14874
14875 // Parent constructor
14876 OO.ui.InputWidget.parent.call( this, config );
14877
14878 // Properties
14879 this.$input = this.getInputElement( config );
14880 this.value = '';
14881 this.inputFilter = config.inputFilter;
14882
14883 // Mixin constructors
14884 OO.ui.mixin.FlaggedElement.call( this, config );
14885 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$input } ) );
14886 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$input } ) );
14887 OO.ui.mixin.AccessKeyedElement.call( this, $.extend( {}, config, { $accessKeyed: this.$input } ) );
14888
14889 // Events
14890 this.$input.on( 'keydown mouseup cut paste change input select', this.onEdit.bind( this ) );
14891
14892 // Initialization
14893 this.$input
14894 .addClass( 'oo-ui-inputWidget-input' )
14895 .attr( 'name', config.name )
14896 .prop( 'disabled', this.isDisabled() );
14897 this.$element
14898 .addClass( 'oo-ui-inputWidget' )
14899 .append( this.$input );
14900 this.setValue( config.value );
14901 this.setAccessKey( config.accessKey );
14902 if ( config.dir ) {
14903 this.setDir( config.dir );
14904 }
14905 };
14906
14907 /* Setup */
14908
14909 OO.inheritClass( OO.ui.InputWidget, OO.ui.Widget );
14910 OO.mixinClass( OO.ui.InputWidget, OO.ui.mixin.FlaggedElement );
14911 OO.mixinClass( OO.ui.InputWidget, OO.ui.mixin.TabIndexedElement );
14912 OO.mixinClass( OO.ui.InputWidget, OO.ui.mixin.TitledElement );
14913 OO.mixinClass( OO.ui.InputWidget, OO.ui.mixin.AccessKeyedElement );
14914
14915 /* Static Properties */
14916
14917 OO.ui.InputWidget.static.supportsSimpleLabel = true;
14918
14919 /* Static Methods */
14920
14921 /**
14922 * @inheritdoc
14923 */
14924 OO.ui.InputWidget.static.reusePreInfuseDOM = function ( node, config ) {
14925 config = OO.ui.InputWidget.parent.static.reusePreInfuseDOM( node, config );
14926 // Reusing $input lets browsers preserve inputted values across page reloads (T114134)
14927 config.$input = $( node ).find( '.oo-ui-inputWidget-input' );
14928 return config;
14929 };
14930
14931 /**
14932 * @inheritdoc
14933 */
14934 OO.ui.InputWidget.static.gatherPreInfuseState = function ( node, config ) {
14935 var state = OO.ui.InputWidget.parent.static.gatherPreInfuseState( node, config );
14936 state.value = config.$input.val();
14937 // Might be better in TabIndexedElement, but it's awkward to do there because mixins are awkward
14938 state.focus = config.$input.is( ':focus' );
14939 return state;
14940 };
14941
14942 /* Events */
14943
14944 /**
14945 * @event change
14946 *
14947 * A change event is emitted when the value of the input changes.
14948 *
14949 * @param {string} value
14950 */
14951
14952 /* Methods */
14953
14954 /**
14955 * Get input element.
14956 *
14957 * Subclasses of OO.ui.InputWidget use the `config` parameter to produce different elements in
14958 * different circumstances. The element must have a `value` property (like form elements).
14959 *
14960 * @protected
14961 * @param {Object} config Configuration options
14962 * @return {jQuery} Input element
14963 */
14964 OO.ui.InputWidget.prototype.getInputElement = function ( config ) {
14965 // See #reusePreInfuseDOM about config.$input
14966 return config.$input || $( '<input>' );
14967 };
14968
14969 /**
14970 * Handle potentially value-changing events.
14971 *
14972 * @private
14973 * @param {jQuery.Event} e Key down, mouse up, cut, paste, change, input, or select event
14974 */
14975 OO.ui.InputWidget.prototype.onEdit = function () {
14976 var widget = this;
14977 if ( !this.isDisabled() ) {
14978 // Allow the stack to clear so the value will be updated
14979 setTimeout( function () {
14980 widget.setValue( widget.$input.val() );
14981 } );
14982 }
14983 };
14984
14985 /**
14986 * Get the value of the input.
14987 *
14988 * @return {string} Input value
14989 */
14990 OO.ui.InputWidget.prototype.getValue = function () {
14991 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
14992 // it, and we won't know unless they're kind enough to trigger a 'change' event.
14993 var value = this.$input.val();
14994 if ( this.value !== value ) {
14995 this.setValue( value );
14996 }
14997 return this.value;
14998 };
14999
15000 /**
15001 * Set the directionality of the input, either RTL (right-to-left) or LTR (left-to-right).
15002 *
15003 * @deprecated since v0.13.1, use #setDir directly
15004 * @param {boolean} isRTL Directionality is right-to-left
15005 * @chainable
15006 */
15007 OO.ui.InputWidget.prototype.setRTL = function ( isRTL ) {
15008 this.setDir( isRTL ? 'rtl' : 'ltr' );
15009 return this;
15010 };
15011
15012 /**
15013 * Set the directionality of the input.
15014 *
15015 * @param {string} dir Text directionality: 'ltr', 'rtl' or 'auto'
15016 * @chainable
15017 */
15018 OO.ui.InputWidget.prototype.setDir = function ( dir ) {
15019 this.$input.prop( 'dir', dir );
15020 return this;
15021 };
15022
15023 /**
15024 * Set the value of the input.
15025 *
15026 * @param {string} value New value
15027 * @fires change
15028 * @chainable
15029 */
15030 OO.ui.InputWidget.prototype.setValue = function ( value ) {
15031 value = this.cleanUpValue( value );
15032 // Update the DOM if it has changed. Note that with cleanUpValue, it
15033 // is possible for the DOM value to change without this.value changing.
15034 if ( this.$input.val() !== value ) {
15035 this.$input.val( value );
15036 }
15037 if ( this.value !== value ) {
15038 this.value = value;
15039 this.emit( 'change', this.value );
15040 }
15041 return this;
15042 };
15043
15044 /**
15045 * Set the input's access key.
15046 * FIXME: This is the same code as in OO.ui.mixin.ButtonElement, maybe find a better place for it?
15047 *
15048 * @param {string} accessKey Input's access key, use empty string to remove
15049 * @chainable
15050 */
15051 OO.ui.InputWidget.prototype.setAccessKey = function ( accessKey ) {
15052 accessKey = typeof accessKey === 'string' && accessKey.length ? accessKey : null;
15053
15054 if ( this.accessKey !== accessKey ) {
15055 if ( this.$input ) {
15056 if ( accessKey !== null ) {
15057 this.$input.attr( 'accesskey', accessKey );
15058 } else {
15059 this.$input.removeAttr( 'accesskey' );
15060 }
15061 }
15062 this.accessKey = accessKey;
15063 }
15064
15065 return this;
15066 };
15067
15068 /**
15069 * Clean up incoming value.
15070 *
15071 * Ensures value is a string, and converts undefined and null to empty string.
15072 *
15073 * @private
15074 * @param {string} value Original value
15075 * @return {string} Cleaned up value
15076 */
15077 OO.ui.InputWidget.prototype.cleanUpValue = function ( value ) {
15078 if ( value === undefined || value === null ) {
15079 return '';
15080 } else if ( this.inputFilter ) {
15081 return this.inputFilter( String( value ) );
15082 } else {
15083 return String( value );
15084 }
15085 };
15086
15087 /**
15088 * Simulate the behavior of clicking on a label bound to this input. This method is only called by
15089 * {@link OO.ui.LabelWidget LabelWidget} and {@link OO.ui.FieldLayout FieldLayout}. It should not be
15090 * called directly.
15091 */
15092 OO.ui.InputWidget.prototype.simulateLabelClick = function () {
15093 if ( !this.isDisabled() ) {
15094 if ( this.$input.is( ':checkbox, :radio' ) ) {
15095 this.$input.click();
15096 }
15097 if ( this.$input.is( ':input' ) ) {
15098 this.$input[ 0 ].focus();
15099 }
15100 }
15101 };
15102
15103 /**
15104 * @inheritdoc
15105 */
15106 OO.ui.InputWidget.prototype.setDisabled = function ( state ) {
15107 OO.ui.InputWidget.parent.prototype.setDisabled.call( this, state );
15108 if ( this.$input ) {
15109 this.$input.prop( 'disabled', this.isDisabled() );
15110 }
15111 return this;
15112 };
15113
15114 /**
15115 * Focus the input.
15116 *
15117 * @chainable
15118 */
15119 OO.ui.InputWidget.prototype.focus = function () {
15120 this.$input[ 0 ].focus();
15121 return this;
15122 };
15123
15124 /**
15125 * Blur the input.
15126 *
15127 * @chainable
15128 */
15129 OO.ui.InputWidget.prototype.blur = function () {
15130 this.$input[ 0 ].blur();
15131 return this;
15132 };
15133
15134 /**
15135 * @inheritdoc
15136 */
15137 OO.ui.InputWidget.prototype.restorePreInfuseState = function ( state ) {
15138 OO.ui.InputWidget.parent.prototype.restorePreInfuseState.call( this, state );
15139 if ( state.value !== undefined && state.value !== this.getValue() ) {
15140 this.setValue( state.value );
15141 }
15142 if ( state.focus ) {
15143 this.focus();
15144 }
15145 };
15146
15147 /**
15148 * ButtonInputWidget is used to submit HTML forms and is intended to be used within
15149 * a OO.ui.FormLayout. If you do not need the button to work with HTML forms, you probably
15150 * want to use OO.ui.ButtonWidget instead. Button input widgets can be rendered as either an
15151 * HTML `<button/>` (the default) or an HTML `<input/>` tags. See the
15152 * [OOjs UI documentation on MediaWiki] [1] for more information.
15153 *
15154 * @example
15155 * // A ButtonInputWidget rendered as an HTML button, the default.
15156 * var button = new OO.ui.ButtonInputWidget( {
15157 * label: 'Input button',
15158 * icon: 'check',
15159 * value: 'check'
15160 * } );
15161 * $( 'body' ).append( button.$element );
15162 *
15163 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs#Button_inputs
15164 *
15165 * @class
15166 * @extends OO.ui.InputWidget
15167 * @mixins OO.ui.mixin.ButtonElement
15168 * @mixins OO.ui.mixin.IconElement
15169 * @mixins OO.ui.mixin.IndicatorElement
15170 * @mixins OO.ui.mixin.LabelElement
15171 * @mixins OO.ui.mixin.TitledElement
15172 *
15173 * @constructor
15174 * @param {Object} [config] Configuration options
15175 * @cfg {string} [type='button'] The value of the HTML `'type'` attribute: 'button', 'submit' or 'reset'.
15176 * @cfg {boolean} [useInputTag=false] Use an `<input/>` tag instead of a `<button/>` tag, the default.
15177 * Widgets configured to be an `<input/>` do not support {@link #icon icons} and {@link #indicator indicators},
15178 * non-plaintext {@link #label labels}, or {@link #value values}. In general, useInputTag should only
15179 * be set to `true` when there’s need to support IE6 in a form with multiple buttons.
15180 */
15181 OO.ui.ButtonInputWidget = function OoUiButtonInputWidget( config ) {
15182 // Configuration initialization
15183 config = $.extend( { type: 'button', useInputTag: false }, config );
15184
15185 // Properties (must be set before parent constructor, which calls #setValue)
15186 this.useInputTag = config.useInputTag;
15187
15188 // Parent constructor
15189 OO.ui.ButtonInputWidget.parent.call( this, config );
15190
15191 // Mixin constructors
15192 OO.ui.mixin.ButtonElement.call( this, $.extend( {}, config, { $button: this.$input } ) );
15193 OO.ui.mixin.IconElement.call( this, config );
15194 OO.ui.mixin.IndicatorElement.call( this, config );
15195 OO.ui.mixin.LabelElement.call( this, config );
15196 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$input } ) );
15197
15198 // Initialization
15199 if ( !config.useInputTag ) {
15200 this.$input.append( this.$icon, this.$label, this.$indicator );
15201 }
15202 this.$element.addClass( 'oo-ui-buttonInputWidget' );
15203 };
15204
15205 /* Setup */
15206
15207 OO.inheritClass( OO.ui.ButtonInputWidget, OO.ui.InputWidget );
15208 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.ButtonElement );
15209 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.IconElement );
15210 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.IndicatorElement );
15211 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.LabelElement );
15212 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.TitledElement );
15213
15214 /* Static Properties */
15215
15216 /**
15217 * Disable generating `<label>` elements for buttons. One would very rarely need additional label
15218 * for a button, and it's already a big clickable target, and it causes unexpected rendering.
15219 */
15220 OO.ui.ButtonInputWidget.static.supportsSimpleLabel = false;
15221
15222 /* Methods */
15223
15224 /**
15225 * @inheritdoc
15226 * @protected
15227 */
15228 OO.ui.ButtonInputWidget.prototype.getInputElement = function ( config ) {
15229 var type;
15230 // See InputWidget#reusePreInfuseDOM about config.$input
15231 if ( config.$input ) {
15232 return config.$input.empty();
15233 }
15234 type = [ 'button', 'submit', 'reset' ].indexOf( config.type ) !== -1 ? config.type : 'button';
15235 return $( '<' + ( config.useInputTag ? 'input' : 'button' ) + ' type="' + type + '">' );
15236 };
15237
15238 /**
15239 * Set label value.
15240 *
15241 * If #useInputTag is `true`, the label is set as the `value` of the `<input/>` tag.
15242 *
15243 * @param {jQuery|string|Function|null} label Label nodes, text, a function that returns nodes or
15244 * text, or `null` for no label
15245 * @chainable
15246 */
15247 OO.ui.ButtonInputWidget.prototype.setLabel = function ( label ) {
15248 OO.ui.mixin.LabelElement.prototype.setLabel.call( this, label );
15249
15250 if ( this.useInputTag ) {
15251 if ( typeof label === 'function' ) {
15252 label = OO.ui.resolveMsg( label );
15253 }
15254 if ( label instanceof jQuery ) {
15255 label = label.text();
15256 }
15257 if ( !label ) {
15258 label = '';
15259 }
15260 this.$input.val( label );
15261 }
15262
15263 return this;
15264 };
15265
15266 /**
15267 * Set the value of the input.
15268 *
15269 * This method is disabled for button inputs configured as {@link #useInputTag <input/> tags}, as
15270 * they do not support {@link #value values}.
15271 *
15272 * @param {string} value New value
15273 * @chainable
15274 */
15275 OO.ui.ButtonInputWidget.prototype.setValue = function ( value ) {
15276 if ( !this.useInputTag ) {
15277 OO.ui.ButtonInputWidget.parent.prototype.setValue.call( this, value );
15278 }
15279 return this;
15280 };
15281
15282 /**
15283 * CheckboxInputWidgets, like HTML checkboxes, can be selected and/or configured with a value.
15284 * Note that these {@link OO.ui.InputWidget input widgets} are best laid out
15285 * in {@link OO.ui.FieldLayout field layouts} that use the {@link OO.ui.FieldLayout#align inline}
15286 * alignment. For more information, please see the [OOjs UI documentation on MediaWiki][1].
15287 *
15288 * This widget can be used inside a HTML form, such as a OO.ui.FormLayout.
15289 *
15290 * @example
15291 * // An example of selected, unselected, and disabled checkbox inputs
15292 * var checkbox1=new OO.ui.CheckboxInputWidget( {
15293 * value: 'a',
15294 * selected: true
15295 * } );
15296 * var checkbox2=new OO.ui.CheckboxInputWidget( {
15297 * value: 'b'
15298 * } );
15299 * var checkbox3=new OO.ui.CheckboxInputWidget( {
15300 * value:'c',
15301 * disabled: true
15302 * } );
15303 * // Create a fieldset layout with fields for each checkbox.
15304 * var fieldset = new OO.ui.FieldsetLayout( {
15305 * label: 'Checkboxes'
15306 * } );
15307 * fieldset.addItems( [
15308 * new OO.ui.FieldLayout( checkbox1, { label: 'Selected checkbox', align: 'inline' } ),
15309 * new OO.ui.FieldLayout( checkbox2, { label: 'Unselected checkbox', align: 'inline' } ),
15310 * new OO.ui.FieldLayout( checkbox3, { label: 'Disabled checkbox', align: 'inline' } ),
15311 * ] );
15312 * $( 'body' ).append( fieldset.$element );
15313 *
15314 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
15315 *
15316 * @class
15317 * @extends OO.ui.InputWidget
15318 *
15319 * @constructor
15320 * @param {Object} [config] Configuration options
15321 * @cfg {boolean} [selected=false] Select the checkbox initially. By default, the checkbox is not selected.
15322 */
15323 OO.ui.CheckboxInputWidget = function OoUiCheckboxInputWidget( config ) {
15324 // Configuration initialization
15325 config = config || {};
15326
15327 // Parent constructor
15328 OO.ui.CheckboxInputWidget.parent.call( this, config );
15329
15330 // Initialization
15331 this.$element
15332 .addClass( 'oo-ui-checkboxInputWidget' )
15333 // Required for pretty styling in MediaWiki theme
15334 .append( $( '<span>' ) );
15335 this.setSelected( config.selected !== undefined ? config.selected : false );
15336 };
15337
15338 /* Setup */
15339
15340 OO.inheritClass( OO.ui.CheckboxInputWidget, OO.ui.InputWidget );
15341
15342 /* Static Methods */
15343
15344 /**
15345 * @inheritdoc
15346 */
15347 OO.ui.CheckboxInputWidget.static.gatherPreInfuseState = function ( node, config ) {
15348 var state = OO.ui.CheckboxInputWidget.parent.static.gatherPreInfuseState( node, config );
15349 state.checked = config.$input.prop( 'checked' );
15350 return state;
15351 };
15352
15353 /* Methods */
15354
15355 /**
15356 * @inheritdoc
15357 * @protected
15358 */
15359 OO.ui.CheckboxInputWidget.prototype.getInputElement = function () {
15360 return $( '<input type="checkbox" />' );
15361 };
15362
15363 /**
15364 * @inheritdoc
15365 */
15366 OO.ui.CheckboxInputWidget.prototype.onEdit = function () {
15367 var widget = this;
15368 if ( !this.isDisabled() ) {
15369 // Allow the stack to clear so the value will be updated
15370 setTimeout( function () {
15371 widget.setSelected( widget.$input.prop( 'checked' ) );
15372 } );
15373 }
15374 };
15375
15376 /**
15377 * Set selection state of this checkbox.
15378 *
15379 * @param {boolean} state `true` for selected
15380 * @chainable
15381 */
15382 OO.ui.CheckboxInputWidget.prototype.setSelected = function ( state ) {
15383 state = !!state;
15384 if ( this.selected !== state ) {
15385 this.selected = state;
15386 this.$input.prop( 'checked', this.selected );
15387 this.emit( 'change', this.selected );
15388 }
15389 return this;
15390 };
15391
15392 /**
15393 * Check if this checkbox is selected.
15394 *
15395 * @return {boolean} Checkbox is selected
15396 */
15397 OO.ui.CheckboxInputWidget.prototype.isSelected = function () {
15398 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
15399 // it, and we won't know unless they're kind enough to trigger a 'change' event.
15400 var selected = this.$input.prop( 'checked' );
15401 if ( this.selected !== selected ) {
15402 this.setSelected( selected );
15403 }
15404 return this.selected;
15405 };
15406
15407 /**
15408 * @inheritdoc
15409 */
15410 OO.ui.CheckboxInputWidget.prototype.restorePreInfuseState = function ( state ) {
15411 OO.ui.CheckboxInputWidget.parent.prototype.restorePreInfuseState.call( this, state );
15412 if ( state.checked !== undefined && state.checked !== this.isSelected() ) {
15413 this.setSelected( state.checked );
15414 }
15415 };
15416
15417 /**
15418 * DropdownInputWidget is a {@link OO.ui.DropdownWidget DropdownWidget} intended to be used
15419 * within a HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with the value
15420 * of a hidden HTML `input` tag. Please see the [OOjs UI documentation on MediaWiki][1] for
15421 * more information about input widgets.
15422 *
15423 * A DropdownInputWidget always has a value (one of the options is always selected), unless there
15424 * are no options. If no `value` configuration option is provided, the first option is selected.
15425 * If you need a state representing no value (no option being selected), use a DropdownWidget.
15426 *
15427 * This and OO.ui.RadioSelectInputWidget support the same configuration options.
15428 *
15429 * @example
15430 * // Example: A DropdownInputWidget with three options
15431 * var dropdownInput = new OO.ui.DropdownInputWidget( {
15432 * options: [
15433 * { data: 'a', label: 'First' },
15434 * { data: 'b', label: 'Second'},
15435 * { data: 'c', label: 'Third' }
15436 * ]
15437 * } );
15438 * $( 'body' ).append( dropdownInput.$element );
15439 *
15440 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
15441 *
15442 * @class
15443 * @extends OO.ui.InputWidget
15444 * @mixins OO.ui.mixin.TitledElement
15445 *
15446 * @constructor
15447 * @param {Object} [config] Configuration options
15448 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
15449 * @cfg {Object} [dropdown] Configuration options for {@link OO.ui.DropdownWidget DropdownWidget}
15450 */
15451 OO.ui.DropdownInputWidget = function OoUiDropdownInputWidget( config ) {
15452 // Configuration initialization
15453 config = config || {};
15454
15455 // Properties (must be done before parent constructor which calls #setDisabled)
15456 this.dropdownWidget = new OO.ui.DropdownWidget( config.dropdown );
15457
15458 // Parent constructor
15459 OO.ui.DropdownInputWidget.parent.call( this, config );
15460
15461 // Mixin constructors
15462 OO.ui.mixin.TitledElement.call( this, config );
15463
15464 // Events
15465 this.dropdownWidget.getMenu().connect( this, { select: 'onMenuSelect' } );
15466
15467 // Initialization
15468 this.setOptions( config.options || [] );
15469 this.$element
15470 .addClass( 'oo-ui-dropdownInputWidget' )
15471 .append( this.dropdownWidget.$element );
15472 };
15473
15474 /* Setup */
15475
15476 OO.inheritClass( OO.ui.DropdownInputWidget, OO.ui.InputWidget );
15477 OO.mixinClass( OO.ui.DropdownInputWidget, OO.ui.mixin.TitledElement );
15478
15479 /* Methods */
15480
15481 /**
15482 * @inheritdoc
15483 * @protected
15484 */
15485 OO.ui.DropdownInputWidget.prototype.getInputElement = function ( config ) {
15486 // See InputWidget#reusePreInfuseDOM about config.$input
15487 if ( config.$input ) {
15488 return config.$input.addClass( 'oo-ui-element-hidden' );
15489 }
15490 return $( '<input type="hidden">' );
15491 };
15492
15493 /**
15494 * Handles menu select events.
15495 *
15496 * @private
15497 * @param {OO.ui.MenuOptionWidget} item Selected menu item
15498 */
15499 OO.ui.DropdownInputWidget.prototype.onMenuSelect = function ( item ) {
15500 this.setValue( item.getData() );
15501 };
15502
15503 /**
15504 * @inheritdoc
15505 */
15506 OO.ui.DropdownInputWidget.prototype.setValue = function ( value ) {
15507 value = this.cleanUpValue( value );
15508 this.dropdownWidget.getMenu().selectItemByData( value );
15509 OO.ui.DropdownInputWidget.parent.prototype.setValue.call( this, value );
15510 return this;
15511 };
15512
15513 /**
15514 * @inheritdoc
15515 */
15516 OO.ui.DropdownInputWidget.prototype.setDisabled = function ( state ) {
15517 this.dropdownWidget.setDisabled( state );
15518 OO.ui.DropdownInputWidget.parent.prototype.setDisabled.call( this, state );
15519 return this;
15520 };
15521
15522 /**
15523 * Set the options available for this input.
15524 *
15525 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
15526 * @chainable
15527 */
15528 OO.ui.DropdownInputWidget.prototype.setOptions = function ( options ) {
15529 var
15530 value = this.getValue(),
15531 widget = this;
15532
15533 // Rebuild the dropdown menu
15534 this.dropdownWidget.getMenu()
15535 .clearItems()
15536 .addItems( options.map( function ( opt ) {
15537 var optValue = widget.cleanUpValue( opt.data );
15538 return new OO.ui.MenuOptionWidget( {
15539 data: optValue,
15540 label: opt.label !== undefined ? opt.label : optValue
15541 } );
15542 } ) );
15543
15544 // Restore the previous value, or reset to something sensible
15545 if ( this.dropdownWidget.getMenu().getItemFromData( value ) ) {
15546 // Previous value is still available, ensure consistency with the dropdown
15547 this.setValue( value );
15548 } else {
15549 // No longer valid, reset
15550 if ( options.length ) {
15551 this.setValue( options[ 0 ].data );
15552 }
15553 }
15554
15555 return this;
15556 };
15557
15558 /**
15559 * @inheritdoc
15560 */
15561 OO.ui.DropdownInputWidget.prototype.focus = function () {
15562 this.dropdownWidget.getMenu().toggle( true );
15563 return this;
15564 };
15565
15566 /**
15567 * @inheritdoc
15568 */
15569 OO.ui.DropdownInputWidget.prototype.blur = function () {
15570 this.dropdownWidget.getMenu().toggle( false );
15571 return this;
15572 };
15573
15574 /**
15575 * RadioInputWidget creates a single radio button. Because radio buttons are usually used as a set,
15576 * in most cases you will want to use a {@link OO.ui.RadioSelectWidget radio select}
15577 * with {@link OO.ui.RadioOptionWidget radio options} instead of this class. For more information,
15578 * please see the [OOjs UI documentation on MediaWiki][1].
15579 *
15580 * This widget can be used inside a HTML form, such as a OO.ui.FormLayout.
15581 *
15582 * @example
15583 * // An example of selected, unselected, and disabled radio inputs
15584 * var radio1 = new OO.ui.RadioInputWidget( {
15585 * value: 'a',
15586 * selected: true
15587 * } );
15588 * var radio2 = new OO.ui.RadioInputWidget( {
15589 * value: 'b'
15590 * } );
15591 * var radio3 = new OO.ui.RadioInputWidget( {
15592 * value: 'c',
15593 * disabled: true
15594 * } );
15595 * // Create a fieldset layout with fields for each radio button.
15596 * var fieldset = new OO.ui.FieldsetLayout( {
15597 * label: 'Radio inputs'
15598 * } );
15599 * fieldset.addItems( [
15600 * new OO.ui.FieldLayout( radio1, { label: 'Selected', align: 'inline' } ),
15601 * new OO.ui.FieldLayout( radio2, { label: 'Unselected', align: 'inline' } ),
15602 * new OO.ui.FieldLayout( radio3, { label: 'Disabled', align: 'inline' } ),
15603 * ] );
15604 * $( 'body' ).append( fieldset.$element );
15605 *
15606 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
15607 *
15608 * @class
15609 * @extends OO.ui.InputWidget
15610 *
15611 * @constructor
15612 * @param {Object} [config] Configuration options
15613 * @cfg {boolean} [selected=false] Select the radio button initially. By default, the radio button is not selected.
15614 */
15615 OO.ui.RadioInputWidget = function OoUiRadioInputWidget( config ) {
15616 // Configuration initialization
15617 config = config || {};
15618
15619 // Parent constructor
15620 OO.ui.RadioInputWidget.parent.call( this, config );
15621
15622 // Initialization
15623 this.$element
15624 .addClass( 'oo-ui-radioInputWidget' )
15625 // Required for pretty styling in MediaWiki theme
15626 .append( $( '<span>' ) );
15627 this.setSelected( config.selected !== undefined ? config.selected : false );
15628 };
15629
15630 /* Setup */
15631
15632 OO.inheritClass( OO.ui.RadioInputWidget, OO.ui.InputWidget );
15633
15634 /* Static Methods */
15635
15636 /**
15637 * @inheritdoc
15638 */
15639 OO.ui.RadioInputWidget.static.gatherPreInfuseState = function ( node, config ) {
15640 var state = OO.ui.RadioInputWidget.parent.static.gatherPreInfuseState( node, config );
15641 state.checked = config.$input.prop( 'checked' );
15642 return state;
15643 };
15644
15645 /* Methods */
15646
15647 /**
15648 * @inheritdoc
15649 * @protected
15650 */
15651 OO.ui.RadioInputWidget.prototype.getInputElement = function () {
15652 return $( '<input type="radio" />' );
15653 };
15654
15655 /**
15656 * @inheritdoc
15657 */
15658 OO.ui.RadioInputWidget.prototype.onEdit = function () {
15659 // RadioInputWidget doesn't track its state.
15660 };
15661
15662 /**
15663 * Set selection state of this radio button.
15664 *
15665 * @param {boolean} state `true` for selected
15666 * @chainable
15667 */
15668 OO.ui.RadioInputWidget.prototype.setSelected = function ( state ) {
15669 // RadioInputWidget doesn't track its state.
15670 this.$input.prop( 'checked', state );
15671 return this;
15672 };
15673
15674 /**
15675 * Check if this radio button is selected.
15676 *
15677 * @return {boolean} Radio is selected
15678 */
15679 OO.ui.RadioInputWidget.prototype.isSelected = function () {
15680 return this.$input.prop( 'checked' );
15681 };
15682
15683 /**
15684 * @inheritdoc
15685 */
15686 OO.ui.RadioInputWidget.prototype.restorePreInfuseState = function ( state ) {
15687 OO.ui.RadioInputWidget.parent.prototype.restorePreInfuseState.call( this, state );
15688 if ( state.checked !== undefined && state.checked !== this.isSelected() ) {
15689 this.setSelected( state.checked );
15690 }
15691 };
15692
15693 /**
15694 * RadioSelectInputWidget is a {@link OO.ui.RadioSelectWidget RadioSelectWidget} intended to be used
15695 * within a HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with the value
15696 * of a hidden HTML `input` tag. Please see the [OOjs UI documentation on MediaWiki][1] for
15697 * more information about input widgets.
15698 *
15699 * This and OO.ui.DropdownInputWidget support the same configuration options.
15700 *
15701 * @example
15702 * // Example: A RadioSelectInputWidget with three options
15703 * var radioSelectInput = new OO.ui.RadioSelectInputWidget( {
15704 * options: [
15705 * { data: 'a', label: 'First' },
15706 * { data: 'b', label: 'Second'},
15707 * { data: 'c', label: 'Third' }
15708 * ]
15709 * } );
15710 * $( 'body' ).append( radioSelectInput.$element );
15711 *
15712 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
15713 *
15714 * @class
15715 * @extends OO.ui.InputWidget
15716 *
15717 * @constructor
15718 * @param {Object} [config] Configuration options
15719 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
15720 */
15721 OO.ui.RadioSelectInputWidget = function OoUiRadioSelectInputWidget( config ) {
15722 // Configuration initialization
15723 config = config || {};
15724
15725 // Properties (must be done before parent constructor which calls #setDisabled)
15726 this.radioSelectWidget = new OO.ui.RadioSelectWidget();
15727
15728 // Parent constructor
15729 OO.ui.RadioSelectInputWidget.parent.call( this, config );
15730
15731 // Events
15732 this.radioSelectWidget.connect( this, { select: 'onMenuSelect' } );
15733
15734 // Initialization
15735 this.setOptions( config.options || [] );
15736 this.$element
15737 .addClass( 'oo-ui-radioSelectInputWidget' )
15738 .append( this.radioSelectWidget.$element );
15739 };
15740
15741 /* Setup */
15742
15743 OO.inheritClass( OO.ui.RadioSelectInputWidget, OO.ui.InputWidget );
15744
15745 /* Static Properties */
15746
15747 OO.ui.RadioSelectInputWidget.static.supportsSimpleLabel = false;
15748
15749 /* Static Methods */
15750
15751 /**
15752 * @inheritdoc
15753 */
15754 OO.ui.RadioSelectInputWidget.static.gatherPreInfuseState = function ( node, config ) {
15755 var state = OO.ui.RadioSelectInputWidget.parent.static.gatherPreInfuseState( node, config );
15756 state.value = $( node ).find( '.oo-ui-radioInputWidget .oo-ui-inputWidget-input:checked' ).val();
15757 return state;
15758 };
15759
15760 /* Methods */
15761
15762 /**
15763 * @inheritdoc
15764 * @protected
15765 */
15766 OO.ui.RadioSelectInputWidget.prototype.getInputElement = function () {
15767 return $( '<input type="hidden">' );
15768 };
15769
15770 /**
15771 * Handles menu select events.
15772 *
15773 * @private
15774 * @param {OO.ui.RadioOptionWidget} item Selected menu item
15775 */
15776 OO.ui.RadioSelectInputWidget.prototype.onMenuSelect = function ( item ) {
15777 this.setValue( item.getData() );
15778 };
15779
15780 /**
15781 * @inheritdoc
15782 */
15783 OO.ui.RadioSelectInputWidget.prototype.setValue = function ( value ) {
15784 value = this.cleanUpValue( value );
15785 this.radioSelectWidget.selectItemByData( value );
15786 OO.ui.RadioSelectInputWidget.parent.prototype.setValue.call( this, value );
15787 return this;
15788 };
15789
15790 /**
15791 * @inheritdoc
15792 */
15793 OO.ui.RadioSelectInputWidget.prototype.setDisabled = function ( state ) {
15794 this.radioSelectWidget.setDisabled( state );
15795 OO.ui.RadioSelectInputWidget.parent.prototype.setDisabled.call( this, state );
15796 return this;
15797 };
15798
15799 /**
15800 * Set the options available for this input.
15801 *
15802 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
15803 * @chainable
15804 */
15805 OO.ui.RadioSelectInputWidget.prototype.setOptions = function ( options ) {
15806 var
15807 value = this.getValue(),
15808 widget = this;
15809
15810 // Rebuild the radioSelect menu
15811 this.radioSelectWidget
15812 .clearItems()
15813 .addItems( options.map( function ( opt ) {
15814 var optValue = widget.cleanUpValue( opt.data );
15815 return new OO.ui.RadioOptionWidget( {
15816 data: optValue,
15817 label: opt.label !== undefined ? opt.label : optValue
15818 } );
15819 } ) );
15820
15821 // Restore the previous value, or reset to something sensible
15822 if ( this.radioSelectWidget.getItemFromData( value ) ) {
15823 // Previous value is still available, ensure consistency with the radioSelect
15824 this.setValue( value );
15825 } else {
15826 // No longer valid, reset
15827 if ( options.length ) {
15828 this.setValue( options[ 0 ].data );
15829 }
15830 }
15831
15832 return this;
15833 };
15834
15835 /**
15836 * TextInputWidgets, like HTML text inputs, can be configured with options that customize the
15837 * size of the field as well as its presentation. In addition, these widgets can be configured
15838 * with {@link OO.ui.mixin.IconElement icons}, {@link OO.ui.mixin.IndicatorElement indicators}, an optional
15839 * validation-pattern (used to determine if an input value is valid or not) and an input filter,
15840 * which modifies incoming values rather than validating them.
15841 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
15842 *
15843 * This widget can be used inside a HTML form, such as a OO.ui.FormLayout.
15844 *
15845 * @example
15846 * // Example of a text input widget
15847 * var textInput = new OO.ui.TextInputWidget( {
15848 * value: 'Text input'
15849 * } )
15850 * $( 'body' ).append( textInput.$element );
15851 *
15852 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
15853 *
15854 * @class
15855 * @extends OO.ui.InputWidget
15856 * @mixins OO.ui.mixin.IconElement
15857 * @mixins OO.ui.mixin.IndicatorElement
15858 * @mixins OO.ui.mixin.PendingElement
15859 * @mixins OO.ui.mixin.LabelElement
15860 *
15861 * @constructor
15862 * @param {Object} [config] Configuration options
15863 * @cfg {string} [type='text'] The value of the HTML `type` attribute: 'text', 'password', 'search',
15864 * 'email' or 'url'. Ignored if `multiline` is true.
15865 *
15866 * Some values of `type` result in additional behaviors:
15867 *
15868 * - `search`: implies `icon: 'search'` and `indicator: 'clear'`; when clicked, the indicator
15869 * empties the text field
15870 * @cfg {string} [placeholder] Placeholder text
15871 * @cfg {boolean} [autofocus=false] Use an HTML `autofocus` attribute to
15872 * instruct the browser to focus this widget.
15873 * @cfg {boolean} [readOnly=false] Prevent changes to the value of the text input.
15874 * @cfg {number} [maxLength] Maximum number of characters allowed in the input.
15875 * @cfg {boolean} [multiline=false] Allow multiple lines of text
15876 * @cfg {number} [rows] If multiline, number of visible lines in textarea. If used with `autosize`,
15877 * specifies minimum number of rows to display.
15878 * @cfg {boolean} [autosize=false] Automatically resize the text input to fit its content.
15879 * Use the #maxRows config to specify a maximum number of displayed rows.
15880 * @cfg {boolean} [maxRows] Maximum number of rows to display when #autosize is set to true.
15881 * Defaults to the maximum of `10` and `2 * rows`, or `10` if `rows` isn't provided.
15882 * @cfg {string} [labelPosition='after'] The position of the inline label relative to that of
15883 * the value or placeholder text: `'before'` or `'after'`
15884 * @cfg {boolean} [required=false] Mark the field as required. Implies `indicator: 'required'`.
15885 * @cfg {boolean} [autocomplete=true] Should the browser support autocomplete for this field
15886 * @cfg {RegExp|Function|string} [validate] Validation pattern: when string, a symbolic name of a
15887 * pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer'
15888 * (the value must contain only numbers); when RegExp, a regular expression that must match the
15889 * value for it to be considered valid; when Function, a function receiving the value as parameter
15890 * that must return true, or promise resolving to true, for it to be considered valid.
15891 */
15892 OO.ui.TextInputWidget = function OoUiTextInputWidget( config ) {
15893 // Configuration initialization
15894 config = $.extend( {
15895 type: 'text',
15896 labelPosition: 'after'
15897 }, config );
15898 if ( config.type === 'search' ) {
15899 if ( config.icon === undefined ) {
15900 config.icon = 'search';
15901 }
15902 // indicator: 'clear' is set dynamically later, depending on value
15903 }
15904 if ( config.required ) {
15905 if ( config.indicator === undefined ) {
15906 config.indicator = 'required';
15907 }
15908 }
15909
15910 // Parent constructor
15911 OO.ui.TextInputWidget.parent.call( this, config );
15912
15913 // Mixin constructors
15914 OO.ui.mixin.IconElement.call( this, config );
15915 OO.ui.mixin.IndicatorElement.call( this, config );
15916 OO.ui.mixin.PendingElement.call( this, $.extend( {}, config, { $pending: this.$input } ) );
15917 OO.ui.mixin.LabelElement.call( this, config );
15918
15919 // Properties
15920 this.type = this.getSaneType( config );
15921 this.readOnly = false;
15922 this.multiline = !!config.multiline;
15923 this.autosize = !!config.autosize;
15924 this.minRows = config.rows !== undefined ? config.rows : '';
15925 this.maxRows = config.maxRows || Math.max( 2 * ( this.minRows || 0 ), 10 );
15926 this.validate = null;
15927 this.styleHeight = null;
15928 this.scrollWidth = null;
15929
15930 // Clone for resizing
15931 if ( this.autosize ) {
15932 this.$clone = this.$input
15933 .clone()
15934 .insertAfter( this.$input )
15935 .attr( 'aria-hidden', 'true' )
15936 .addClass( 'oo-ui-element-hidden' );
15937 }
15938
15939 this.setValidation( config.validate );
15940 this.setLabelPosition( config.labelPosition );
15941
15942 // Events
15943 this.$input.on( {
15944 keypress: this.onKeyPress.bind( this ),
15945 blur: this.onBlur.bind( this )
15946 } );
15947 this.$input.one( {
15948 focus: this.onElementAttach.bind( this )
15949 } );
15950 this.$icon.on( 'mousedown', this.onIconMouseDown.bind( this ) );
15951 this.$indicator.on( 'mousedown', this.onIndicatorMouseDown.bind( this ) );
15952 this.on( 'labelChange', this.updatePosition.bind( this ) );
15953 this.connect( this, {
15954 change: 'onChange',
15955 disable: 'onDisable'
15956 } );
15957
15958 // Initialization
15959 this.$element
15960 .addClass( 'oo-ui-textInputWidget oo-ui-textInputWidget-type-' + this.type )
15961 .append( this.$icon, this.$indicator );
15962 this.setReadOnly( !!config.readOnly );
15963 this.updateSearchIndicator();
15964 if ( config.placeholder ) {
15965 this.$input.attr( 'placeholder', config.placeholder );
15966 }
15967 if ( config.maxLength !== undefined ) {
15968 this.$input.attr( 'maxlength', config.maxLength );
15969 }
15970 if ( config.autofocus ) {
15971 this.$input.attr( 'autofocus', 'autofocus' );
15972 }
15973 if ( config.required ) {
15974 this.$input.attr( 'required', 'required' );
15975 this.$input.attr( 'aria-required', 'true' );
15976 }
15977 if ( config.autocomplete === false ) {
15978 this.$input.attr( 'autocomplete', 'off' );
15979 // Turning off autocompletion also disables "form caching" when the user navigates to a
15980 // different page and then clicks "Back". Re-enable it when leaving. Borrowed from jQuery UI.
15981 $( window ).on( {
15982 beforeunload: function () {
15983 this.$input.removeAttr( 'autocomplete' );
15984 }.bind( this ),
15985 pageshow: function () {
15986 // Browsers don't seem to actually fire this event on "Back", they instead just reload the
15987 // whole page... it shouldn't hurt, though.
15988 this.$input.attr( 'autocomplete', 'off' );
15989 }.bind( this )
15990 } );
15991 }
15992 if ( this.multiline && config.rows ) {
15993 this.$input.attr( 'rows', config.rows );
15994 }
15995 if ( this.label || config.autosize ) {
15996 this.installParentChangeDetector();
15997 }
15998 };
15999
16000 /* Setup */
16001
16002 OO.inheritClass( OO.ui.TextInputWidget, OO.ui.InputWidget );
16003 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.mixin.IconElement );
16004 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.mixin.IndicatorElement );
16005 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.mixin.PendingElement );
16006 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.mixin.LabelElement );
16007
16008 /* Static Properties */
16009
16010 OO.ui.TextInputWidget.static.validationPatterns = {
16011 'non-empty': /.+/,
16012 integer: /^\d+$/
16013 };
16014
16015 /* Static Methods */
16016
16017 /**
16018 * @inheritdoc
16019 */
16020 OO.ui.TextInputWidget.static.gatherPreInfuseState = function ( node, config ) {
16021 var state = OO.ui.TextInputWidget.parent.static.gatherPreInfuseState( node, config );
16022 if ( config.multiline ) {
16023 state.scrollTop = config.$input.scrollTop();
16024 }
16025 return state;
16026 };
16027
16028 /* Events */
16029
16030 /**
16031 * An `enter` event is emitted when the user presses 'enter' inside the text box.
16032 *
16033 * Not emitted if the input is multiline.
16034 *
16035 * @event enter
16036 */
16037
16038 /**
16039 * A `resize` event is emitted when autosize is set and the widget resizes
16040 *
16041 * @event resize
16042 */
16043
16044 /* Methods */
16045
16046 /**
16047 * Handle icon mouse down events.
16048 *
16049 * @private
16050 * @param {jQuery.Event} e Mouse down event
16051 * @fires icon
16052 */
16053 OO.ui.TextInputWidget.prototype.onIconMouseDown = function ( e ) {
16054 if ( e.which === 1 ) {
16055 this.$input[ 0 ].focus();
16056 return false;
16057 }
16058 };
16059
16060 /**
16061 * Handle indicator mouse down events.
16062 *
16063 * @private
16064 * @param {jQuery.Event} e Mouse down event
16065 * @fires indicator
16066 */
16067 OO.ui.TextInputWidget.prototype.onIndicatorMouseDown = function ( e ) {
16068 if ( e.which === 1 ) {
16069 if ( this.type === 'search' ) {
16070 // Clear the text field
16071 this.setValue( '' );
16072 }
16073 this.$input[ 0 ].focus();
16074 return false;
16075 }
16076 };
16077
16078 /**
16079 * Handle key press events.
16080 *
16081 * @private
16082 * @param {jQuery.Event} e Key press event
16083 * @fires enter If enter key is pressed and input is not multiline
16084 */
16085 OO.ui.TextInputWidget.prototype.onKeyPress = function ( e ) {
16086 if ( e.which === OO.ui.Keys.ENTER && !this.multiline ) {
16087 this.emit( 'enter', e );
16088 }
16089 };
16090
16091 /**
16092 * Handle blur events.
16093 *
16094 * @private
16095 * @param {jQuery.Event} e Blur event
16096 */
16097 OO.ui.TextInputWidget.prototype.onBlur = function () {
16098 this.setValidityFlag();
16099 };
16100
16101 /**
16102 * Handle element attach events.
16103 *
16104 * @private
16105 * @param {jQuery.Event} e Element attach event
16106 */
16107 OO.ui.TextInputWidget.prototype.onElementAttach = function () {
16108 // Any previously calculated size is now probably invalid if we reattached elsewhere
16109 this.valCache = null;
16110 this.adjustSize();
16111 this.positionLabel();
16112 };
16113
16114 /**
16115 * Handle change events.
16116 *
16117 * @param {string} value
16118 * @private
16119 */
16120 OO.ui.TextInputWidget.prototype.onChange = function () {
16121 this.updateSearchIndicator();
16122 this.setValidityFlag();
16123 this.adjustSize();
16124 };
16125
16126 /**
16127 * Handle disable events.
16128 *
16129 * @param {boolean} disabled Element is disabled
16130 * @private
16131 */
16132 OO.ui.TextInputWidget.prototype.onDisable = function () {
16133 this.updateSearchIndicator();
16134 };
16135
16136 /**
16137 * Check if the input is {@link #readOnly read-only}.
16138 *
16139 * @return {boolean}
16140 */
16141 OO.ui.TextInputWidget.prototype.isReadOnly = function () {
16142 return this.readOnly;
16143 };
16144
16145 /**
16146 * Set the {@link #readOnly read-only} state of the input.
16147 *
16148 * @param {boolean} state Make input read-only
16149 * @chainable
16150 */
16151 OO.ui.TextInputWidget.prototype.setReadOnly = function ( state ) {
16152 this.readOnly = !!state;
16153 this.$input.prop( 'readOnly', this.readOnly );
16154 this.updateSearchIndicator();
16155 return this;
16156 };
16157
16158 /**
16159 * Support function for making #onElementAttach work across browsers.
16160 *
16161 * This whole function could be replaced with one line of code using the DOMNodeInsertedIntoDocument
16162 * event, but it's not supported by Firefox and allegedly deprecated, so we only use it as fallback.
16163 *
16164 * Due to MutationObserver performance woes, #onElementAttach is only somewhat reliably called the
16165 * first time that the element gets attached to the documented.
16166 */
16167 OO.ui.TextInputWidget.prototype.installParentChangeDetector = function () {
16168 var mutationObserver, onRemove, topmostNode, fakeParentNode,
16169 MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver,
16170 widget = this;
16171
16172 if ( MutationObserver ) {
16173 // The new way. If only it wasn't so ugly.
16174
16175 if ( this.$element.closest( 'html' ).length ) {
16176 // Widget is attached already, do nothing. This breaks the functionality of this function when
16177 // the widget is detached and reattached. Alas, doing this correctly with MutationObserver
16178 // would require observation of the whole document, which would hurt performance of other,
16179 // more important code.
16180 return;
16181 }
16182
16183 // Find topmost node in the tree
16184 topmostNode = this.$element[ 0 ];
16185 while ( topmostNode.parentNode ) {
16186 topmostNode = topmostNode.parentNode;
16187 }
16188
16189 // We have no way to detect the $element being attached somewhere without observing the entire
16190 // DOM with subtree modifications, which would hurt performance. So we cheat: we hook to the
16191 // parent node of $element, and instead detect when $element is removed from it (and thus
16192 // probably attached somewhere else). If there is no parent, we create a "fake" one. If it
16193 // doesn't get attached, we end up back here and create the parent.
16194
16195 mutationObserver = new MutationObserver( function ( mutations ) {
16196 var i, j, removedNodes;
16197 for ( i = 0; i < mutations.length; i++ ) {
16198 removedNodes = mutations[ i ].removedNodes;
16199 for ( j = 0; j < removedNodes.length; j++ ) {
16200 if ( removedNodes[ j ] === topmostNode ) {
16201 setTimeout( onRemove, 0 );
16202 return;
16203 }
16204 }
16205 }
16206 } );
16207
16208 onRemove = function () {
16209 // If the node was attached somewhere else, report it
16210 if ( widget.$element.closest( 'html' ).length ) {
16211 widget.onElementAttach();
16212 }
16213 mutationObserver.disconnect();
16214 widget.installParentChangeDetector();
16215 };
16216
16217 // Create a fake parent and observe it
16218 fakeParentNode = $( '<div>' ).append( topmostNode )[ 0 ];
16219 mutationObserver.observe( fakeParentNode, { childList: true } );
16220 } else {
16221 // Using the DOMNodeInsertedIntoDocument event is much nicer and less magical, and works for
16222 // detachment and reattachment, but it's not supported by Firefox and allegedly deprecated.
16223 this.$element.on( 'DOMNodeInsertedIntoDocument', this.onElementAttach.bind( this ) );
16224 }
16225 };
16226
16227 /**
16228 * Automatically adjust the size of the text input.
16229 *
16230 * This only affects #multiline inputs that are {@link #autosize autosized}.
16231 *
16232 * @chainable
16233 * @fires resize
16234 */
16235 OO.ui.TextInputWidget.prototype.adjustSize = function () {
16236 var scrollHeight, innerHeight, outerHeight, maxInnerHeight, measurementError,
16237 idealHeight, newHeight, scrollWidth, property;
16238
16239 if ( this.multiline && this.$input.val() !== this.valCache ) {
16240 if ( this.autosize ) {
16241 this.$clone
16242 .val( this.$input.val() )
16243 .attr( 'rows', this.minRows )
16244 // Set inline height property to 0 to measure scroll height
16245 .css( 'height', 0 );
16246
16247 this.$clone.removeClass( 'oo-ui-element-hidden' );
16248
16249 this.valCache = this.$input.val();
16250
16251 scrollHeight = this.$clone[ 0 ].scrollHeight;
16252
16253 // Remove inline height property to measure natural heights
16254 this.$clone.css( 'height', '' );
16255 innerHeight = this.$clone.innerHeight();
16256 outerHeight = this.$clone.outerHeight();
16257
16258 // Measure max rows height
16259 this.$clone
16260 .attr( 'rows', this.maxRows )
16261 .css( 'height', 'auto' )
16262 .val( '' );
16263 maxInnerHeight = this.$clone.innerHeight();
16264
16265 // Difference between reported innerHeight and scrollHeight with no scrollbars present
16266 // Equals 1 on Blink-based browsers and 0 everywhere else
16267 measurementError = maxInnerHeight - this.$clone[ 0 ].scrollHeight;
16268 idealHeight = Math.min( maxInnerHeight, scrollHeight + measurementError );
16269
16270 this.$clone.addClass( 'oo-ui-element-hidden' );
16271
16272 // Only apply inline height when expansion beyond natural height is needed
16273 // Use the difference between the inner and outer height as a buffer
16274 newHeight = idealHeight > innerHeight ? idealHeight + ( outerHeight - innerHeight ) : '';
16275 if ( newHeight !== this.styleHeight ) {
16276 this.$input.css( 'height', newHeight );
16277 this.styleHeight = newHeight;
16278 this.emit( 'resize' );
16279 }
16280 }
16281 scrollWidth = this.$input[ 0 ].offsetWidth - this.$input[ 0 ].clientWidth;
16282 if ( scrollWidth !== this.scrollWidth ) {
16283 property = this.$element.css( 'direction' ) === 'rtl' ? 'left' : 'right';
16284 // Reset
16285 this.$label.css( { right: '', left: '' } );
16286 this.$indicator.css( { right: '', left: '' } );
16287
16288 if ( scrollWidth ) {
16289 this.$indicator.css( property, scrollWidth );
16290 if ( this.labelPosition === 'after' ) {
16291 this.$label.css( property, scrollWidth );
16292 }
16293 }
16294
16295 this.scrollWidth = scrollWidth;
16296 this.positionLabel();
16297 }
16298 }
16299 return this;
16300 };
16301
16302 /**
16303 * @inheritdoc
16304 * @protected
16305 */
16306 OO.ui.TextInputWidget.prototype.getInputElement = function ( config ) {
16307 return config.multiline ?
16308 $( '<textarea>' ) :
16309 $( '<input type="' + this.getSaneType( config ) + '" />' );
16310 };
16311
16312 /**
16313 * Get sanitized value for 'type' for given config.
16314 *
16315 * @param {Object} config Configuration options
16316 * @return {string|null}
16317 * @private
16318 */
16319 OO.ui.TextInputWidget.prototype.getSaneType = function ( config ) {
16320 var type = [ 'text', 'password', 'search', 'email', 'url' ].indexOf( config.type ) !== -1 ?
16321 config.type :
16322 'text';
16323 return config.multiline ? 'multiline' : type;
16324 };
16325
16326 /**
16327 * Check if the input supports multiple lines.
16328 *
16329 * @return {boolean}
16330 */
16331 OO.ui.TextInputWidget.prototype.isMultiline = function () {
16332 return !!this.multiline;
16333 };
16334
16335 /**
16336 * Check if the input automatically adjusts its size.
16337 *
16338 * @return {boolean}
16339 */
16340 OO.ui.TextInputWidget.prototype.isAutosizing = function () {
16341 return !!this.autosize;
16342 };
16343
16344 /**
16345 * Focus the input and select a specified range within the text.
16346 *
16347 * @param {number} from Select from offset
16348 * @param {number} [to] Select to offset, defaults to from
16349 * @chainable
16350 */
16351 OO.ui.TextInputWidget.prototype.selectRange = function ( from, to ) {
16352 var textRange, isBackwards, start, end,
16353 input = this.$input[ 0 ];
16354
16355 to = to || from;
16356
16357 isBackwards = to < from;
16358 start = isBackwards ? to : from;
16359 end = isBackwards ? from : to;
16360
16361 this.focus();
16362
16363 if ( input.setSelectionRange ) {
16364 input.setSelectionRange( start, end, isBackwards ? 'backward' : 'forward' );
16365 } else if ( input.createTextRange ) {
16366 // IE 8 and below
16367 textRange = input.createTextRange();
16368 textRange.collapse( true );
16369 textRange.moveStart( 'character', start );
16370 textRange.moveEnd( 'character', end - start );
16371 textRange.select();
16372 }
16373 return this;
16374 };
16375
16376 /**
16377 * Get an object describing the current selection range in a directional manner
16378 *
16379 * @return {Object} Object containing 'from' and 'to' offsets
16380 */
16381 OO.ui.TextInputWidget.prototype.getRange = function () {
16382 var input = this.$input[ 0 ],
16383 start = input.selectionStart,
16384 end = input.selectionEnd,
16385 isBackwards = input.selectionDirection === 'backward';
16386
16387 return {
16388 from: isBackwards ? end : start,
16389 to: isBackwards ? start : end
16390 };
16391 };
16392
16393 /**
16394 * Get the length of the text input value.
16395 *
16396 * This could differ from the length of #getValue if the
16397 * value gets filtered
16398 *
16399 * @return {number} Input length
16400 */
16401 OO.ui.TextInputWidget.prototype.getInputLength = function () {
16402 return this.$input[ 0 ].value.length;
16403 };
16404
16405 /**
16406 * Focus the input and select the entire text.
16407 *
16408 * @chainable
16409 */
16410 OO.ui.TextInputWidget.prototype.select = function () {
16411 return this.selectRange( 0, this.getInputLength() );
16412 };
16413
16414 /**
16415 * Focus the input and move the cursor to the start.
16416 *
16417 * @chainable
16418 */
16419 OO.ui.TextInputWidget.prototype.moveCursorToStart = function () {
16420 return this.selectRange( 0 );
16421 };
16422
16423 /**
16424 * Focus the input and move the cursor to the end.
16425 *
16426 * @chainable
16427 */
16428 OO.ui.TextInputWidget.prototype.moveCursorToEnd = function () {
16429 return this.selectRange( this.getInputLength() );
16430 };
16431
16432 /**
16433 * Insert new content into the input.
16434 *
16435 * @param {string} content Content to be inserted
16436 * @chainable
16437 */
16438 OO.ui.TextInputWidget.prototype.insertContent = function ( content ) {
16439 var start, end,
16440 range = this.getRange(),
16441 value = this.getValue();
16442
16443 start = Math.min( range.from, range.to );
16444 end = Math.max( range.from, range.to );
16445
16446 this.setValue( value.slice( 0, start ) + content + value.slice( end ) );
16447 this.selectRange( start + content.length );
16448 return this;
16449 };
16450
16451 /**
16452 * Insert new content either side of a selection.
16453 *
16454 * @param {string} pre Content to be inserted before the selection
16455 * @param {string} post Content to be inserted after the selection
16456 * @chainable
16457 */
16458 OO.ui.TextInputWidget.prototype.encapsulateContent = function ( pre, post ) {
16459 var start, end,
16460 range = this.getRange(),
16461 offset = pre.length;
16462
16463 start = Math.min( range.from, range.to );
16464 end = Math.max( range.from, range.to );
16465
16466 this.selectRange( start ).insertContent( pre );
16467 this.selectRange( offset + end ).insertContent( post );
16468
16469 this.selectRange( offset + start, offset + end );
16470 return this;
16471 };
16472
16473 /**
16474 * Set the validation pattern.
16475 *
16476 * The validation pattern is either a regular expression, a function, or the symbolic name of a
16477 * pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer' (the
16478 * value must contain only numbers).
16479 *
16480 * @param {RegExp|Function|string|null} validate Regular expression, function, or the symbolic name
16481 * of a pattern (either ‘integer’ or ‘non-empty’) defined by the class.
16482 */
16483 OO.ui.TextInputWidget.prototype.setValidation = function ( validate ) {
16484 if ( validate instanceof RegExp || validate instanceof Function ) {
16485 this.validate = validate;
16486 } else {
16487 this.validate = this.constructor.static.validationPatterns[ validate ] || /.*/;
16488 }
16489 };
16490
16491 /**
16492 * Sets the 'invalid' flag appropriately.
16493 *
16494 * @param {boolean} [isValid] Optionally override validation result
16495 */
16496 OO.ui.TextInputWidget.prototype.setValidityFlag = function ( isValid ) {
16497 var widget = this,
16498 setFlag = function ( valid ) {
16499 if ( !valid ) {
16500 widget.$input.attr( 'aria-invalid', 'true' );
16501 } else {
16502 widget.$input.removeAttr( 'aria-invalid' );
16503 }
16504 widget.setFlags( { invalid: !valid } );
16505 };
16506
16507 if ( isValid !== undefined ) {
16508 setFlag( isValid );
16509 } else {
16510 this.getValidity().then( function () {
16511 setFlag( true );
16512 }, function () {
16513 setFlag( false );
16514 } );
16515 }
16516 };
16517
16518 /**
16519 * Check if a value is valid.
16520 *
16521 * This method returns a promise that resolves with a boolean `true` if the current value is
16522 * considered valid according to the supplied {@link #validate validation pattern}.
16523 *
16524 * @deprecated
16525 * @return {jQuery.Promise} A promise that resolves to a boolean `true` if the value is valid.
16526 */
16527 OO.ui.TextInputWidget.prototype.isValid = function () {
16528 var result;
16529
16530 if ( this.validate instanceof Function ) {
16531 result = this.validate( this.getValue() );
16532 if ( $.isFunction( result.promise ) ) {
16533 return result.promise();
16534 } else {
16535 return $.Deferred().resolve( !!result ).promise();
16536 }
16537 } else {
16538 return $.Deferred().resolve( !!this.getValue().match( this.validate ) ).promise();
16539 }
16540 };
16541
16542 /**
16543 * Get the validity of current value.
16544 *
16545 * This method returns a promise that resolves if the value is valid and rejects if
16546 * it isn't. Uses the {@link #validate validation pattern} to check for validity.
16547 *
16548 * @return {jQuery.Promise} A promise that resolves if the value is valid, rejects if not.
16549 */
16550 OO.ui.TextInputWidget.prototype.getValidity = function () {
16551 var result, promise;
16552
16553 function rejectOrResolve( valid ) {
16554 if ( valid ) {
16555 return $.Deferred().resolve().promise();
16556 } else {
16557 return $.Deferred().reject().promise();
16558 }
16559 }
16560
16561 if ( this.validate instanceof Function ) {
16562 result = this.validate( this.getValue() );
16563
16564 if ( $.isFunction( result.promise ) ) {
16565 promise = $.Deferred();
16566
16567 result.then( function ( valid ) {
16568 if ( valid ) {
16569 promise.resolve();
16570 } else {
16571 promise.reject();
16572 }
16573 }, function () {
16574 promise.reject();
16575 } );
16576
16577 return promise.promise();
16578 } else {
16579 return rejectOrResolve( result );
16580 }
16581 } else {
16582 return rejectOrResolve( this.getValue().match( this.validate ) );
16583 }
16584 };
16585
16586 /**
16587 * Set the position of the inline label relative to that of the value: `‘before’` or `‘after’`.
16588 *
16589 * @param {string} labelPosition Label position, 'before' or 'after'
16590 * @chainable
16591 */
16592 OO.ui.TextInputWidget.prototype.setLabelPosition = function ( labelPosition ) {
16593 this.labelPosition = labelPosition;
16594 this.updatePosition();
16595 return this;
16596 };
16597
16598 /**
16599 * Update the position of the inline label.
16600 *
16601 * This method is called by #setLabelPosition, and can also be called on its own if
16602 * something causes the label to be mispositioned.
16603 *
16604 * @chainable
16605 */
16606 OO.ui.TextInputWidget.prototype.updatePosition = function () {
16607 var after = this.labelPosition === 'after';
16608
16609 this.$element
16610 .toggleClass( 'oo-ui-textInputWidget-labelPosition-after', !!this.label && after )
16611 .toggleClass( 'oo-ui-textInputWidget-labelPosition-before', !!this.label && !after );
16612
16613 this.valCache = null;
16614 this.scrollWidth = null;
16615 this.adjustSize();
16616 this.positionLabel();
16617
16618 return this;
16619 };
16620
16621 /**
16622 * Update the 'clear' indicator displayed on type: 'search' text fields, hiding it when the field is
16623 * already empty or when it's not editable.
16624 */
16625 OO.ui.TextInputWidget.prototype.updateSearchIndicator = function () {
16626 if ( this.type === 'search' ) {
16627 if ( this.getValue() === '' || this.isDisabled() || this.isReadOnly() ) {
16628 this.setIndicator( null );
16629 } else {
16630 this.setIndicator( 'clear' );
16631 }
16632 }
16633 };
16634
16635 /**
16636 * Position the label by setting the correct padding on the input.
16637 *
16638 * @private
16639 * @chainable
16640 */
16641 OO.ui.TextInputWidget.prototype.positionLabel = function () {
16642 var after, rtl, property;
16643 // Clear old values
16644 this.$input
16645 // Clear old values if present
16646 .css( {
16647 'padding-right': '',
16648 'padding-left': ''
16649 } );
16650
16651 if ( this.label ) {
16652 this.$element.append( this.$label );
16653 } else {
16654 this.$label.detach();
16655 return;
16656 }
16657
16658 after = this.labelPosition === 'after';
16659 rtl = this.$element.css( 'direction' ) === 'rtl';
16660 property = after === rtl ? 'padding-left' : 'padding-right';
16661
16662 this.$input.css( property, this.$label.outerWidth( true ) + ( after ? this.scrollWidth : 0 ) );
16663
16664 return this;
16665 };
16666
16667 /**
16668 * @inheritdoc
16669 */
16670 OO.ui.TextInputWidget.prototype.restorePreInfuseState = function ( state ) {
16671 OO.ui.TextInputWidget.parent.prototype.restorePreInfuseState.call( this, state );
16672 if ( state.scrollTop !== undefined ) {
16673 this.$input.scrollTop( state.scrollTop );
16674 }
16675 };
16676
16677 /**
16678 * ComboBoxInputWidgets combine a {@link OO.ui.TextInputWidget text input} (where a value
16679 * can be entered manually) and a {@link OO.ui.MenuSelectWidget menu of options} (from which
16680 * a value can be chosen instead). Users can choose options from the combo box in one of two ways:
16681 *
16682 * - by typing a value in the text input field. If the value exactly matches the value of a menu
16683 * option, that option will appear to be selected.
16684 * - by choosing a value from the menu. The value of the chosen option will then appear in the text
16685 * input field.
16686 *
16687 * This widget can be used inside a HTML form, such as a OO.ui.FormLayout.
16688 *
16689 * For more information about menus and options, please see the [OOjs UI documentation on MediaWiki][1].
16690 *
16691 * @example
16692 * // Example: A ComboBoxInputWidget.
16693 * var comboBox = new OO.ui.ComboBoxInputWidget( {
16694 * label: 'ComboBoxInputWidget',
16695 * value: 'Option 1',
16696 * menu: {
16697 * items: [
16698 * new OO.ui.MenuOptionWidget( {
16699 * data: 'Option 1',
16700 * label: 'Option One'
16701 * } ),
16702 * new OO.ui.MenuOptionWidget( {
16703 * data: 'Option 2',
16704 * label: 'Option Two'
16705 * } ),
16706 * new OO.ui.MenuOptionWidget( {
16707 * data: 'Option 3',
16708 * label: 'Option Three'
16709 * } ),
16710 * new OO.ui.MenuOptionWidget( {
16711 * data: 'Option 4',
16712 * label: 'Option Four'
16713 * } ),
16714 * new OO.ui.MenuOptionWidget( {
16715 * data: 'Option 5',
16716 * label: 'Option Five'
16717 * } )
16718 * ]
16719 * }
16720 * } );
16721 * $( 'body' ).append( comboBox.$element );
16722 *
16723 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
16724 *
16725 * @class
16726 * @extends OO.ui.TextInputWidget
16727 *
16728 * @constructor
16729 * @param {Object} [config] Configuration options
16730 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
16731 * @cfg {Object} [menu] Configuration options to pass to the {@link OO.ui.FloatingMenuSelectWidget menu select widget}.
16732 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
16733 * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
16734 * containing `<div>` and has a larger area. By default, the menu uses relative positioning.
16735 */
16736 OO.ui.ComboBoxInputWidget = function OoUiComboBoxInputWidget( config ) {
16737 // Configuration initialization
16738 config = $.extend( {
16739 indicator: 'down'
16740 }, config );
16741 // For backwards-compatibility with ComboBoxWidget config
16742 $.extend( config, config.input );
16743
16744 // Parent constructor
16745 OO.ui.ComboBoxInputWidget.parent.call( this, config );
16746
16747 // Properties
16748 this.$overlay = config.$overlay || this.$element;
16749 this.menu = new OO.ui.FloatingMenuSelectWidget( $.extend(
16750 {
16751 widget: this,
16752 input: this,
16753 $container: this.$element,
16754 disabled: this.isDisabled()
16755 },
16756 config.menu
16757 ) );
16758 // For backwards-compatibility with ComboBoxWidget
16759 this.input = this;
16760
16761 // Events
16762 this.$indicator.on( {
16763 click: this.onIndicatorClick.bind( this ),
16764 keypress: this.onIndicatorKeyPress.bind( this )
16765 } );
16766 this.connect( this, {
16767 change: 'onInputChange',
16768 enter: 'onInputEnter'
16769 } );
16770 this.menu.connect( this, {
16771 choose: 'onMenuChoose',
16772 add: 'onMenuItemsChange',
16773 remove: 'onMenuItemsChange'
16774 } );
16775
16776 // Initialization
16777 this.$input.attr( {
16778 role: 'combobox',
16779 'aria-autocomplete': 'list'
16780 } );
16781 // Do not override options set via config.menu.items
16782 if ( config.options !== undefined ) {
16783 this.setOptions( config.options );
16784 }
16785 // Extra class for backwards-compatibility with ComboBoxWidget
16786 this.$element.addClass( 'oo-ui-comboBoxInputWidget oo-ui-comboBoxWidget' );
16787 this.$overlay.append( this.menu.$element );
16788 this.onMenuItemsChange();
16789 };
16790
16791 /* Setup */
16792
16793 OO.inheritClass( OO.ui.ComboBoxInputWidget, OO.ui.TextInputWidget );
16794
16795 /* Methods */
16796
16797 /**
16798 * Get the combobox's menu.
16799 * @return {OO.ui.FloatingMenuSelectWidget} Menu widget
16800 */
16801 OO.ui.ComboBoxInputWidget.prototype.getMenu = function () {
16802 return this.menu;
16803 };
16804
16805 /**
16806 * Get the combobox's text input widget.
16807 * @return {OO.ui.TextInputWidget} Text input widget
16808 */
16809 OO.ui.ComboBoxInputWidget.prototype.getInput = function () {
16810 return this;
16811 };
16812
16813 /**
16814 * Handle input change events.
16815 *
16816 * @private
16817 * @param {string} value New value
16818 */
16819 OO.ui.ComboBoxInputWidget.prototype.onInputChange = function ( value ) {
16820 var match = this.menu.getItemFromData( value );
16821
16822 this.menu.selectItem( match );
16823 if ( this.menu.getHighlightedItem() ) {
16824 this.menu.highlightItem( match );
16825 }
16826
16827 if ( !this.isDisabled() ) {
16828 this.menu.toggle( true );
16829 }
16830 };
16831
16832 /**
16833 * Handle mouse click events.
16834 *
16835 * @private
16836 * @param {jQuery.Event} e Mouse click event
16837 */
16838 OO.ui.ComboBoxInputWidget.prototype.onIndicatorClick = function ( e ) {
16839 if ( !this.isDisabled() && e.which === 1 ) {
16840 this.menu.toggle();
16841 this.$input[ 0 ].focus();
16842 }
16843 return false;
16844 };
16845
16846 /**
16847 * Handle key press events.
16848 *
16849 * @private
16850 * @param {jQuery.Event} e Key press event
16851 */
16852 OO.ui.ComboBoxInputWidget.prototype.onIndicatorKeyPress = function ( e ) {
16853 if ( !this.isDisabled() && ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER ) ) {
16854 this.menu.toggle();
16855 this.$input[ 0 ].focus();
16856 return false;
16857 }
16858 };
16859
16860 /**
16861 * Handle input enter events.
16862 *
16863 * @private
16864 */
16865 OO.ui.ComboBoxInputWidget.prototype.onInputEnter = function () {
16866 if ( !this.isDisabled() ) {
16867 this.menu.toggle( false );
16868 }
16869 };
16870
16871 /**
16872 * Handle menu choose events.
16873 *
16874 * @private
16875 * @param {OO.ui.OptionWidget} item Chosen item
16876 */
16877 OO.ui.ComboBoxInputWidget.prototype.onMenuChoose = function ( item ) {
16878 this.setValue( item.getData() );
16879 };
16880
16881 /**
16882 * Handle menu item change events.
16883 *
16884 * @private
16885 */
16886 OO.ui.ComboBoxInputWidget.prototype.onMenuItemsChange = function () {
16887 var match = this.menu.getItemFromData( this.getValue() );
16888 this.menu.selectItem( match );
16889 if ( this.menu.getHighlightedItem() ) {
16890 this.menu.highlightItem( match );
16891 }
16892 this.$element.toggleClass( 'oo-ui-comboBoxInputWidget-empty', this.menu.isEmpty() );
16893 };
16894
16895 /**
16896 * @inheritdoc
16897 */
16898 OO.ui.ComboBoxInputWidget.prototype.setDisabled = function ( disabled ) {
16899 // Parent method
16900 OO.ui.ComboBoxInputWidget.parent.prototype.setDisabled.call( this, disabled );
16901
16902 if ( this.menu ) {
16903 this.menu.setDisabled( this.isDisabled() );
16904 }
16905
16906 return this;
16907 };
16908
16909 /**
16910 * Set the options available for this input.
16911 *
16912 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
16913 * @chainable
16914 */
16915 OO.ui.ComboBoxInputWidget.prototype.setOptions = function ( options ) {
16916 this.getMenu()
16917 .clearItems()
16918 .addItems( options.map( function ( opt ) {
16919 return new OO.ui.MenuOptionWidget( {
16920 data: opt.data,
16921 label: opt.label !== undefined ? opt.label : opt.data
16922 } );
16923 } ) );
16924
16925 return this;
16926 };
16927
16928 /**
16929 * @class
16930 * @deprecated Use OO.ui.ComboBoxInputWidget instead.
16931 */
16932 OO.ui.ComboBoxWidget = OO.ui.ComboBoxInputWidget;
16933
16934 /**
16935 * LabelWidgets help identify the function of interface elements. Each LabelWidget can
16936 * be configured with a `label` option that is set to a string, a label node, or a function:
16937 *
16938 * - String: a plaintext string
16939 * - jQuery selection: a jQuery selection, used for anything other than a plaintext label, e.g., a
16940 * label that includes a link or special styling, such as a gray color or additional graphical elements.
16941 * - Function: a function that will produce a string in the future. Functions are used
16942 * in cases where the value of the label is not currently defined.
16943 *
16944 * In addition, the LabelWidget can be associated with an {@link OO.ui.InputWidget input widget}, which
16945 * will come into focus when the label is clicked.
16946 *
16947 * @example
16948 * // Examples of LabelWidgets
16949 * var label1 = new OO.ui.LabelWidget( {
16950 * label: 'plaintext label'
16951 * } );
16952 * var label2 = new OO.ui.LabelWidget( {
16953 * label: $( '<a href="default.html">jQuery label</a>' )
16954 * } );
16955 * // Create a fieldset layout with fields for each example
16956 * var fieldset = new OO.ui.FieldsetLayout();
16957 * fieldset.addItems( [
16958 * new OO.ui.FieldLayout( label1 ),
16959 * new OO.ui.FieldLayout( label2 )
16960 * ] );
16961 * $( 'body' ).append( fieldset.$element );
16962 *
16963 * @class
16964 * @extends OO.ui.Widget
16965 * @mixins OO.ui.mixin.LabelElement
16966 *
16967 * @constructor
16968 * @param {Object} [config] Configuration options
16969 * @cfg {OO.ui.InputWidget} [input] {@link OO.ui.InputWidget Input widget} that uses the label.
16970 * Clicking the label will focus the specified input field.
16971 */
16972 OO.ui.LabelWidget = function OoUiLabelWidget( config ) {
16973 // Configuration initialization
16974 config = config || {};
16975
16976 // Parent constructor
16977 OO.ui.LabelWidget.parent.call( this, config );
16978
16979 // Mixin constructors
16980 OO.ui.mixin.LabelElement.call( this, $.extend( {}, config, { $label: this.$element } ) );
16981 OO.ui.mixin.TitledElement.call( this, config );
16982
16983 // Properties
16984 this.input = config.input;
16985
16986 // Events
16987 if ( this.input instanceof OO.ui.InputWidget ) {
16988 this.$element.on( 'click', this.onClick.bind( this ) );
16989 }
16990
16991 // Initialization
16992 this.$element.addClass( 'oo-ui-labelWidget' );
16993 };
16994
16995 /* Setup */
16996
16997 OO.inheritClass( OO.ui.LabelWidget, OO.ui.Widget );
16998 OO.mixinClass( OO.ui.LabelWidget, OO.ui.mixin.LabelElement );
16999 OO.mixinClass( OO.ui.LabelWidget, OO.ui.mixin.TitledElement );
17000
17001 /* Static Properties */
17002
17003 OO.ui.LabelWidget.static.tagName = 'span';
17004
17005 /* Methods */
17006
17007 /**
17008 * Handles label mouse click events.
17009 *
17010 * @private
17011 * @param {jQuery.Event} e Mouse click event
17012 */
17013 OO.ui.LabelWidget.prototype.onClick = function () {
17014 this.input.simulateLabelClick();
17015 return false;
17016 };
17017
17018 /**
17019 * OptionWidgets are special elements that can be selected and configured with data. The
17020 * data is often unique for each option, but it does not have to be. OptionWidgets are used
17021 * with OO.ui.SelectWidget to create a selection of mutually exclusive options. For more information
17022 * and examples, please see the [OOjs UI documentation on MediaWiki][1].
17023 *
17024 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
17025 *
17026 * @class
17027 * @extends OO.ui.Widget
17028 * @mixins OO.ui.mixin.LabelElement
17029 * @mixins OO.ui.mixin.FlaggedElement
17030 *
17031 * @constructor
17032 * @param {Object} [config] Configuration options
17033 */
17034 OO.ui.OptionWidget = function OoUiOptionWidget( config ) {
17035 // Configuration initialization
17036 config = config || {};
17037
17038 // Parent constructor
17039 OO.ui.OptionWidget.parent.call( this, config );
17040
17041 // Mixin constructors
17042 OO.ui.mixin.ItemWidget.call( this );
17043 OO.ui.mixin.LabelElement.call( this, config );
17044 OO.ui.mixin.FlaggedElement.call( this, config );
17045
17046 // Properties
17047 this.selected = false;
17048 this.highlighted = false;
17049 this.pressed = false;
17050
17051 // Initialization
17052 this.$element
17053 .data( 'oo-ui-optionWidget', this )
17054 .attr( 'role', 'option' )
17055 .attr( 'aria-selected', 'false' )
17056 .addClass( 'oo-ui-optionWidget' )
17057 .append( this.$label );
17058 };
17059
17060 /* Setup */
17061
17062 OO.inheritClass( OO.ui.OptionWidget, OO.ui.Widget );
17063 OO.mixinClass( OO.ui.OptionWidget, OO.ui.mixin.ItemWidget );
17064 OO.mixinClass( OO.ui.OptionWidget, OO.ui.mixin.LabelElement );
17065 OO.mixinClass( OO.ui.OptionWidget, OO.ui.mixin.FlaggedElement );
17066
17067 /* Static Properties */
17068
17069 OO.ui.OptionWidget.static.selectable = true;
17070
17071 OO.ui.OptionWidget.static.highlightable = true;
17072
17073 OO.ui.OptionWidget.static.pressable = true;
17074
17075 OO.ui.OptionWidget.static.scrollIntoViewOnSelect = false;
17076
17077 /* Methods */
17078
17079 /**
17080 * Check if the option can be selected.
17081 *
17082 * @return {boolean} Item is selectable
17083 */
17084 OO.ui.OptionWidget.prototype.isSelectable = function () {
17085 return this.constructor.static.selectable && !this.isDisabled() && this.isVisible();
17086 };
17087
17088 /**
17089 * Check if the option can be highlighted. A highlight indicates that the option
17090 * may be selected when a user presses enter or clicks. Disabled items cannot
17091 * be highlighted.
17092 *
17093 * @return {boolean} Item is highlightable
17094 */
17095 OO.ui.OptionWidget.prototype.isHighlightable = function () {
17096 return this.constructor.static.highlightable && !this.isDisabled() && this.isVisible();
17097 };
17098
17099 /**
17100 * Check if the option can be pressed. The pressed state occurs when a user mouses
17101 * down on an item, but has not yet let go of the mouse.
17102 *
17103 * @return {boolean} Item is pressable
17104 */
17105 OO.ui.OptionWidget.prototype.isPressable = function () {
17106 return this.constructor.static.pressable && !this.isDisabled() && this.isVisible();
17107 };
17108
17109 /**
17110 * Check if the option is selected.
17111 *
17112 * @return {boolean} Item is selected
17113 */
17114 OO.ui.OptionWidget.prototype.isSelected = function () {
17115 return this.selected;
17116 };
17117
17118 /**
17119 * Check if the option is highlighted. A highlight indicates that the
17120 * item may be selected when a user presses enter or clicks.
17121 *
17122 * @return {boolean} Item is highlighted
17123 */
17124 OO.ui.OptionWidget.prototype.isHighlighted = function () {
17125 return this.highlighted;
17126 };
17127
17128 /**
17129 * Check if the option is pressed. The pressed state occurs when a user mouses
17130 * down on an item, but has not yet let go of the mouse. The item may appear
17131 * selected, but it will not be selected until the user releases the mouse.
17132 *
17133 * @return {boolean} Item is pressed
17134 */
17135 OO.ui.OptionWidget.prototype.isPressed = function () {
17136 return this.pressed;
17137 };
17138
17139 /**
17140 * Set the option’s selected state. In general, all modifications to the selection
17141 * should be handled by the SelectWidget’s {@link OO.ui.SelectWidget#selectItem selectItem( [item] )}
17142 * method instead of this method.
17143 *
17144 * @param {boolean} [state=false] Select option
17145 * @chainable
17146 */
17147 OO.ui.OptionWidget.prototype.setSelected = function ( state ) {
17148 if ( this.constructor.static.selectable ) {
17149 this.selected = !!state;
17150 this.$element
17151 .toggleClass( 'oo-ui-optionWidget-selected', state )
17152 .attr( 'aria-selected', state.toString() );
17153 if ( state && this.constructor.static.scrollIntoViewOnSelect ) {
17154 this.scrollElementIntoView();
17155 }
17156 this.updateThemeClasses();
17157 }
17158 return this;
17159 };
17160
17161 /**
17162 * Set the option’s highlighted state. In general, all programmatic
17163 * modifications to the highlight should be handled by the
17164 * SelectWidget’s {@link OO.ui.SelectWidget#highlightItem highlightItem( [item] )}
17165 * method instead of this method.
17166 *
17167 * @param {boolean} [state=false] Highlight option
17168 * @chainable
17169 */
17170 OO.ui.OptionWidget.prototype.setHighlighted = function ( state ) {
17171 if ( this.constructor.static.highlightable ) {
17172 this.highlighted = !!state;
17173 this.$element.toggleClass( 'oo-ui-optionWidget-highlighted', state );
17174 this.updateThemeClasses();
17175 }
17176 return this;
17177 };
17178
17179 /**
17180 * Set the option’s pressed state. In general, all
17181 * programmatic modifications to the pressed state should be handled by the
17182 * SelectWidget’s {@link OO.ui.SelectWidget#pressItem pressItem( [item] )}
17183 * method instead of this method.
17184 *
17185 * @param {boolean} [state=false] Press option
17186 * @chainable
17187 */
17188 OO.ui.OptionWidget.prototype.setPressed = function ( state ) {
17189 if ( this.constructor.static.pressable ) {
17190 this.pressed = !!state;
17191 this.$element.toggleClass( 'oo-ui-optionWidget-pressed', state );
17192 this.updateThemeClasses();
17193 }
17194 return this;
17195 };
17196
17197 /**
17198 * DecoratedOptionWidgets are {@link OO.ui.OptionWidget options} that can be configured
17199 * with an {@link OO.ui.mixin.IconElement icon} and/or {@link OO.ui.mixin.IndicatorElement indicator}.
17200 * This class is used with OO.ui.SelectWidget to create a selection of mutually exclusive
17201 * options. For more information about options and selects, please see the
17202 * [OOjs UI documentation on MediaWiki][1].
17203 *
17204 * @example
17205 * // Decorated options in a select widget
17206 * var select = new OO.ui.SelectWidget( {
17207 * items: [
17208 * new OO.ui.DecoratedOptionWidget( {
17209 * data: 'a',
17210 * label: 'Option with icon',
17211 * icon: 'help'
17212 * } ),
17213 * new OO.ui.DecoratedOptionWidget( {
17214 * data: 'b',
17215 * label: 'Option with indicator',
17216 * indicator: 'next'
17217 * } )
17218 * ]
17219 * } );
17220 * $( 'body' ).append( select.$element );
17221 *
17222 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
17223 *
17224 * @class
17225 * @extends OO.ui.OptionWidget
17226 * @mixins OO.ui.mixin.IconElement
17227 * @mixins OO.ui.mixin.IndicatorElement
17228 *
17229 * @constructor
17230 * @param {Object} [config] Configuration options
17231 */
17232 OO.ui.DecoratedOptionWidget = function OoUiDecoratedOptionWidget( config ) {
17233 // Parent constructor
17234 OO.ui.DecoratedOptionWidget.parent.call( this, config );
17235
17236 // Mixin constructors
17237 OO.ui.mixin.IconElement.call( this, config );
17238 OO.ui.mixin.IndicatorElement.call( this, config );
17239
17240 // Initialization
17241 this.$element
17242 .addClass( 'oo-ui-decoratedOptionWidget' )
17243 .prepend( this.$icon )
17244 .append( this.$indicator );
17245 };
17246
17247 /* Setup */
17248
17249 OO.inheritClass( OO.ui.DecoratedOptionWidget, OO.ui.OptionWidget );
17250 OO.mixinClass( OO.ui.DecoratedOptionWidget, OO.ui.mixin.IconElement );
17251 OO.mixinClass( OO.ui.DecoratedOptionWidget, OO.ui.mixin.IndicatorElement );
17252
17253 /**
17254 * ButtonOptionWidget is a special type of {@link OO.ui.mixin.ButtonElement button element} that
17255 * can be selected and configured with data. The class is
17256 * used with OO.ui.ButtonSelectWidget to create a selection of button options. Please see the
17257 * [OOjs UI documentation on MediaWiki] [1] for more information.
17258 *
17259 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Button_selects_and_options
17260 *
17261 * @class
17262 * @extends OO.ui.DecoratedOptionWidget
17263 * @mixins OO.ui.mixin.ButtonElement
17264 * @mixins OO.ui.mixin.TabIndexedElement
17265 * @mixins OO.ui.mixin.TitledElement
17266 *
17267 * @constructor
17268 * @param {Object} [config] Configuration options
17269 */
17270 OO.ui.ButtonOptionWidget = function OoUiButtonOptionWidget( config ) {
17271 // Configuration initialization
17272 config = config || {};
17273
17274 // Parent constructor
17275 OO.ui.ButtonOptionWidget.parent.call( this, config );
17276
17277 // Mixin constructors
17278 OO.ui.mixin.ButtonElement.call( this, config );
17279 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$button } ) );
17280 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, {
17281 $tabIndexed: this.$button,
17282 tabIndex: -1
17283 } ) );
17284
17285 // Initialization
17286 this.$element.addClass( 'oo-ui-buttonOptionWidget' );
17287 this.$button.append( this.$element.contents() );
17288 this.$element.append( this.$button );
17289 };
17290
17291 /* Setup */
17292
17293 OO.inheritClass( OO.ui.ButtonOptionWidget, OO.ui.DecoratedOptionWidget );
17294 OO.mixinClass( OO.ui.ButtonOptionWidget, OO.ui.mixin.ButtonElement );
17295 OO.mixinClass( OO.ui.ButtonOptionWidget, OO.ui.mixin.TitledElement );
17296 OO.mixinClass( OO.ui.ButtonOptionWidget, OO.ui.mixin.TabIndexedElement );
17297
17298 /* Static Properties */
17299
17300 // Allow button mouse down events to pass through so they can be handled by the parent select widget
17301 OO.ui.ButtonOptionWidget.static.cancelButtonMouseDownEvents = false;
17302
17303 OO.ui.ButtonOptionWidget.static.highlightable = false;
17304
17305 /* Methods */
17306
17307 /**
17308 * @inheritdoc
17309 */
17310 OO.ui.ButtonOptionWidget.prototype.setSelected = function ( state ) {
17311 OO.ui.ButtonOptionWidget.parent.prototype.setSelected.call( this, state );
17312
17313 if ( this.constructor.static.selectable ) {
17314 this.setActive( state );
17315 }
17316
17317 return this;
17318 };
17319
17320 /**
17321 * RadioOptionWidget is an option widget that looks like a radio button.
17322 * The class is used with OO.ui.RadioSelectWidget to create a selection of radio options.
17323 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information.
17324 *
17325 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Button_selects_and_option
17326 *
17327 * @class
17328 * @extends OO.ui.OptionWidget
17329 *
17330 * @constructor
17331 * @param {Object} [config] Configuration options
17332 */
17333 OO.ui.RadioOptionWidget = function OoUiRadioOptionWidget( config ) {
17334 // Configuration initialization
17335 config = config || {};
17336
17337 // Properties (must be done before parent constructor which calls #setDisabled)
17338 this.radio = new OO.ui.RadioInputWidget( { value: config.data, tabIndex: -1 } );
17339
17340 // Parent constructor
17341 OO.ui.RadioOptionWidget.parent.call( this, config );
17342
17343 // Events
17344 this.radio.$input.on( 'focus', this.onInputFocus.bind( this ) );
17345
17346 // Initialization
17347 // Remove implicit role, we're handling it ourselves
17348 this.radio.$input.attr( 'role', 'presentation' );
17349 this.$element
17350 .addClass( 'oo-ui-radioOptionWidget' )
17351 .attr( 'role', 'radio' )
17352 .attr( 'aria-checked', 'false' )
17353 .removeAttr( 'aria-selected' )
17354 .prepend( this.radio.$element );
17355 };
17356
17357 /* Setup */
17358
17359 OO.inheritClass( OO.ui.RadioOptionWidget, OO.ui.OptionWidget );
17360
17361 /* Static Properties */
17362
17363 OO.ui.RadioOptionWidget.static.highlightable = false;
17364
17365 OO.ui.RadioOptionWidget.static.scrollIntoViewOnSelect = true;
17366
17367 OO.ui.RadioOptionWidget.static.pressable = false;
17368
17369 OO.ui.RadioOptionWidget.static.tagName = 'label';
17370
17371 /* Methods */
17372
17373 /**
17374 * @param {jQuery.Event} e Focus event
17375 * @private
17376 */
17377 OO.ui.RadioOptionWidget.prototype.onInputFocus = function () {
17378 this.radio.$input.blur();
17379 this.$element.parent().focus();
17380 };
17381
17382 /**
17383 * @inheritdoc
17384 */
17385 OO.ui.RadioOptionWidget.prototype.setSelected = function ( state ) {
17386 OO.ui.RadioOptionWidget.parent.prototype.setSelected.call( this, state );
17387
17388 this.radio.setSelected( state );
17389 this.$element
17390 .attr( 'aria-checked', state.toString() )
17391 .removeAttr( 'aria-selected' );
17392
17393 return this;
17394 };
17395
17396 /**
17397 * @inheritdoc
17398 */
17399 OO.ui.RadioOptionWidget.prototype.setDisabled = function ( disabled ) {
17400 OO.ui.RadioOptionWidget.parent.prototype.setDisabled.call( this, disabled );
17401
17402 this.radio.setDisabled( this.isDisabled() );
17403
17404 return this;
17405 };
17406
17407 /**
17408 * MenuOptionWidget is an option widget that looks like a menu item. The class is used with
17409 * OO.ui.MenuSelectWidget to create a menu of mutually exclusive options. Please see
17410 * the [OOjs UI documentation on MediaWiki] [1] for more information.
17411 *
17412 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
17413 *
17414 * @class
17415 * @extends OO.ui.DecoratedOptionWidget
17416 *
17417 * @constructor
17418 * @param {Object} [config] Configuration options
17419 */
17420 OO.ui.MenuOptionWidget = function OoUiMenuOptionWidget( config ) {
17421 // Configuration initialization
17422 config = $.extend( { icon: 'check' }, config );
17423
17424 // Parent constructor
17425 OO.ui.MenuOptionWidget.parent.call( this, config );
17426
17427 // Initialization
17428 this.$element
17429 .attr( 'role', 'menuitem' )
17430 .addClass( 'oo-ui-menuOptionWidget' );
17431 };
17432
17433 /* Setup */
17434
17435 OO.inheritClass( OO.ui.MenuOptionWidget, OO.ui.DecoratedOptionWidget );
17436
17437 /* Static Properties */
17438
17439 OO.ui.MenuOptionWidget.static.scrollIntoViewOnSelect = true;
17440
17441 /**
17442 * MenuSectionOptionWidgets are used inside {@link OO.ui.MenuSelectWidget menu select widgets} to group one or more related
17443 * {@link OO.ui.MenuOptionWidget menu options}. MenuSectionOptionWidgets cannot be highlighted or selected.
17444 *
17445 * @example
17446 * var myDropdown = new OO.ui.DropdownWidget( {
17447 * menu: {
17448 * items: [
17449 * new OO.ui.MenuSectionOptionWidget( {
17450 * label: 'Dogs'
17451 * } ),
17452 * new OO.ui.MenuOptionWidget( {
17453 * data: 'corgi',
17454 * label: 'Welsh Corgi'
17455 * } ),
17456 * new OO.ui.MenuOptionWidget( {
17457 * data: 'poodle',
17458 * label: 'Standard Poodle'
17459 * } ),
17460 * new OO.ui.MenuSectionOptionWidget( {
17461 * label: 'Cats'
17462 * } ),
17463 * new OO.ui.MenuOptionWidget( {
17464 * data: 'lion',
17465 * label: 'Lion'
17466 * } )
17467 * ]
17468 * }
17469 * } );
17470 * $( 'body' ).append( myDropdown.$element );
17471 *
17472 * @class
17473 * @extends OO.ui.DecoratedOptionWidget
17474 *
17475 * @constructor
17476 * @param {Object} [config] Configuration options
17477 */
17478 OO.ui.MenuSectionOptionWidget = function OoUiMenuSectionOptionWidget( config ) {
17479 // Parent constructor
17480 OO.ui.MenuSectionOptionWidget.parent.call( this, config );
17481
17482 // Initialization
17483 this.$element.addClass( 'oo-ui-menuSectionOptionWidget' );
17484 };
17485
17486 /* Setup */
17487
17488 OO.inheritClass( OO.ui.MenuSectionOptionWidget, OO.ui.DecoratedOptionWidget );
17489
17490 /* Static Properties */
17491
17492 OO.ui.MenuSectionOptionWidget.static.selectable = false;
17493
17494 OO.ui.MenuSectionOptionWidget.static.highlightable = false;
17495
17496 /**
17497 * OutlineOptionWidget is an item in an {@link OO.ui.OutlineSelectWidget OutlineSelectWidget}.
17498 *
17499 * Currently, this class is only used by {@link OO.ui.BookletLayout booklet layouts}, which contain
17500 * {@link OO.ui.PageLayout page layouts}. See {@link OO.ui.BookletLayout BookletLayout}
17501 * for an example.
17502 *
17503 * @class
17504 * @extends OO.ui.DecoratedOptionWidget
17505 *
17506 * @constructor
17507 * @param {Object} [config] Configuration options
17508 * @cfg {number} [level] Indentation level
17509 * @cfg {boolean} [movable] Allow modification from {@link OO.ui.OutlineControlsWidget outline controls}.
17510 */
17511 OO.ui.OutlineOptionWidget = function OoUiOutlineOptionWidget( config ) {
17512 // Configuration initialization
17513 config = config || {};
17514
17515 // Parent constructor
17516 OO.ui.OutlineOptionWidget.parent.call( this, config );
17517
17518 // Properties
17519 this.level = 0;
17520 this.movable = !!config.movable;
17521 this.removable = !!config.removable;
17522
17523 // Initialization
17524 this.$element.addClass( 'oo-ui-outlineOptionWidget' );
17525 this.setLevel( config.level );
17526 };
17527
17528 /* Setup */
17529
17530 OO.inheritClass( OO.ui.OutlineOptionWidget, OO.ui.DecoratedOptionWidget );
17531
17532 /* Static Properties */
17533
17534 OO.ui.OutlineOptionWidget.static.highlightable = false;
17535
17536 OO.ui.OutlineOptionWidget.static.scrollIntoViewOnSelect = true;
17537
17538 OO.ui.OutlineOptionWidget.static.levelClass = 'oo-ui-outlineOptionWidget-level-';
17539
17540 OO.ui.OutlineOptionWidget.static.levels = 3;
17541
17542 /* Methods */
17543
17544 /**
17545 * Check if item is movable.
17546 *
17547 * Movability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
17548 *
17549 * @return {boolean} Item is movable
17550 */
17551 OO.ui.OutlineOptionWidget.prototype.isMovable = function () {
17552 return this.movable;
17553 };
17554
17555 /**
17556 * Check if item is removable.
17557 *
17558 * Removability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
17559 *
17560 * @return {boolean} Item is removable
17561 */
17562 OO.ui.OutlineOptionWidget.prototype.isRemovable = function () {
17563 return this.removable;
17564 };
17565
17566 /**
17567 * Get indentation level.
17568 *
17569 * @return {number} Indentation level
17570 */
17571 OO.ui.OutlineOptionWidget.prototype.getLevel = function () {
17572 return this.level;
17573 };
17574
17575 /**
17576 * Set movability.
17577 *
17578 * Movability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
17579 *
17580 * @param {boolean} movable Item is movable
17581 * @chainable
17582 */
17583 OO.ui.OutlineOptionWidget.prototype.setMovable = function ( movable ) {
17584 this.movable = !!movable;
17585 this.updateThemeClasses();
17586 return this;
17587 };
17588
17589 /**
17590 * Set removability.
17591 *
17592 * Removability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
17593 *
17594 * @param {boolean} movable Item is removable
17595 * @chainable
17596 */
17597 OO.ui.OutlineOptionWidget.prototype.setRemovable = function ( removable ) {
17598 this.removable = !!removable;
17599 this.updateThemeClasses();
17600 return this;
17601 };
17602
17603 /**
17604 * Set indentation level.
17605 *
17606 * @param {number} [level=0] Indentation level, in the range of [0,#maxLevel]
17607 * @chainable
17608 */
17609 OO.ui.OutlineOptionWidget.prototype.setLevel = function ( level ) {
17610 var levels = this.constructor.static.levels,
17611 levelClass = this.constructor.static.levelClass,
17612 i = levels;
17613
17614 this.level = level ? Math.max( 0, Math.min( levels - 1, level ) ) : 0;
17615 while ( i-- ) {
17616 if ( this.level === i ) {
17617 this.$element.addClass( levelClass + i );
17618 } else {
17619 this.$element.removeClass( levelClass + i );
17620 }
17621 }
17622 this.updateThemeClasses();
17623
17624 return this;
17625 };
17626
17627 /**
17628 * TabOptionWidget is an item in a {@link OO.ui.TabSelectWidget TabSelectWidget}.
17629 *
17630 * Currently, this class is only used by {@link OO.ui.IndexLayout index layouts}, which contain
17631 * {@link OO.ui.CardLayout card layouts}. See {@link OO.ui.IndexLayout IndexLayout}
17632 * for an example.
17633 *
17634 * @class
17635 * @extends OO.ui.OptionWidget
17636 *
17637 * @constructor
17638 * @param {Object} [config] Configuration options
17639 */
17640 OO.ui.TabOptionWidget = function OoUiTabOptionWidget( config ) {
17641 // Configuration initialization
17642 config = config || {};
17643
17644 // Parent constructor
17645 OO.ui.TabOptionWidget.parent.call( this, config );
17646
17647 // Initialization
17648 this.$element.addClass( 'oo-ui-tabOptionWidget' );
17649 };
17650
17651 /* Setup */
17652
17653 OO.inheritClass( OO.ui.TabOptionWidget, OO.ui.OptionWidget );
17654
17655 /* Static Properties */
17656
17657 OO.ui.TabOptionWidget.static.highlightable = false;
17658
17659 /**
17660 * PopupWidget is a container for content. The popup is overlaid and positioned absolutely.
17661 * By default, each popup has an anchor that points toward its origin.
17662 * Please see the [OOjs UI documentation on Mediawiki] [1] for more information and examples.
17663 *
17664 * @example
17665 * // A popup widget.
17666 * var popup = new OO.ui.PopupWidget( {
17667 * $content: $( '<p>Hi there!</p>' ),
17668 * padded: true,
17669 * width: 300
17670 * } );
17671 *
17672 * $( 'body' ).append( popup.$element );
17673 * // To display the popup, toggle the visibility to 'true'.
17674 * popup.toggle( true );
17675 *
17676 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups
17677 *
17678 * @class
17679 * @extends OO.ui.Widget
17680 * @mixins OO.ui.mixin.LabelElement
17681 * @mixins OO.ui.mixin.ClippableElement
17682 *
17683 * @constructor
17684 * @param {Object} [config] Configuration options
17685 * @cfg {number} [width=320] Width of popup in pixels
17686 * @cfg {number} [height] Height of popup in pixels. Omit to use the automatic height.
17687 * @cfg {boolean} [anchor=true] Show anchor pointing to origin of popup
17688 * @cfg {string} [align='center'] Alignment of the popup: `center`, `force-left`, `force-right`, `backwards` or `forwards`.
17689 * If the popup is forced-left the popup body is leaning towards the left. For force-right alignment, the body of the
17690 * popup is leaning towards the right of the screen.
17691 * Using 'backwards' is a logical direction which will result in the popup leaning towards the beginning of the sentence
17692 * in the given language, which means it will flip to the correct positioning in right-to-left languages.
17693 * Using 'forward' will also result in a logical alignment where the body of the popup leans towards the end of the
17694 * sentence in the given language.
17695 * @cfg {jQuery} [$container] Constrain the popup to the boundaries of the specified container.
17696 * See the [OOjs UI docs on MediaWiki][3] for an example.
17697 * [3]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups#containerExample
17698 * @cfg {number} [containerPadding=10] Padding between the popup and its container, specified as a number of pixels.
17699 * @cfg {jQuery} [$content] Content to append to the popup's body
17700 * @cfg {jQuery} [$footer] Content to append to the popup's footer
17701 * @cfg {boolean} [autoClose=false] Automatically close the popup when it loses focus.
17702 * @cfg {jQuery} [$autoCloseIgnore] Elements that will not close the popup when clicked.
17703 * This config option is only relevant if #autoClose is set to `true`. See the [OOjs UI docs on MediaWiki][2]
17704 * for an example.
17705 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups#autocloseExample
17706 * @cfg {boolean} [head] Show a popup header that contains a #label (if specified) and close
17707 * button.
17708 * @cfg {boolean} [padded] Add padding to the popup's body
17709 */
17710 OO.ui.PopupWidget = function OoUiPopupWidget( config ) {
17711 // Configuration initialization
17712 config = config || {};
17713
17714 // Parent constructor
17715 OO.ui.PopupWidget.parent.call( this, config );
17716
17717 // Properties (must be set before ClippableElement constructor call)
17718 this.$body = $( '<div>' );
17719 this.$popup = $( '<div>' );
17720
17721 // Mixin constructors
17722 OO.ui.mixin.LabelElement.call( this, config );
17723 OO.ui.mixin.ClippableElement.call( this, $.extend( {}, config, {
17724 $clippable: this.$body,
17725 $clippableContainer: this.$popup
17726 } ) );
17727
17728 // Properties
17729 this.$head = $( '<div>' );
17730 this.$footer = $( '<div>' );
17731 this.$anchor = $( '<div>' );
17732 // If undefined, will be computed lazily in updateDimensions()
17733 this.$container = config.$container;
17734 this.containerPadding = config.containerPadding !== undefined ? config.containerPadding : 10;
17735 this.autoClose = !!config.autoClose;
17736 this.$autoCloseIgnore = config.$autoCloseIgnore;
17737 this.transitionTimeout = null;
17738 this.anchor = null;
17739 this.width = config.width !== undefined ? config.width : 320;
17740 this.height = config.height !== undefined ? config.height : null;
17741 this.setAlignment( config.align );
17742 this.closeButton = new OO.ui.ButtonWidget( { framed: false, icon: 'close' } );
17743 this.onMouseDownHandler = this.onMouseDown.bind( this );
17744 this.onDocumentKeyDownHandler = this.onDocumentKeyDown.bind( this );
17745
17746 // Events
17747 this.closeButton.connect( this, { click: 'onCloseButtonClick' } );
17748
17749 // Initialization
17750 this.toggleAnchor( config.anchor === undefined || config.anchor );
17751 this.$body.addClass( 'oo-ui-popupWidget-body' );
17752 this.$anchor.addClass( 'oo-ui-popupWidget-anchor' );
17753 this.$head
17754 .addClass( 'oo-ui-popupWidget-head' )
17755 .append( this.$label, this.closeButton.$element );
17756 this.$footer.addClass( 'oo-ui-popupWidget-footer' );
17757 if ( !config.head ) {
17758 this.$head.addClass( 'oo-ui-element-hidden' );
17759 }
17760 if ( !config.$footer ) {
17761 this.$footer.addClass( 'oo-ui-element-hidden' );
17762 }
17763 this.$popup
17764 .addClass( 'oo-ui-popupWidget-popup' )
17765 .append( this.$head, this.$body, this.$footer );
17766 this.$element
17767 .addClass( 'oo-ui-popupWidget' )
17768 .append( this.$popup, this.$anchor );
17769 // Move content, which was added to #$element by OO.ui.Widget, to the body
17770 if ( config.$content instanceof jQuery ) {
17771 this.$body.append( config.$content );
17772 }
17773 if ( config.$footer instanceof jQuery ) {
17774 this.$footer.append( config.$footer );
17775 }
17776 if ( config.padded ) {
17777 this.$body.addClass( 'oo-ui-popupWidget-body-padded' );
17778 }
17779
17780 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
17781 // that reference properties not initialized at that time of parent class construction
17782 // TODO: Find a better way to handle post-constructor setup
17783 this.visible = false;
17784 this.$element.addClass( 'oo-ui-element-hidden' );
17785 };
17786
17787 /* Setup */
17788
17789 OO.inheritClass( OO.ui.PopupWidget, OO.ui.Widget );
17790 OO.mixinClass( OO.ui.PopupWidget, OO.ui.mixin.LabelElement );
17791 OO.mixinClass( OO.ui.PopupWidget, OO.ui.mixin.ClippableElement );
17792
17793 /* Methods */
17794
17795 /**
17796 * Handles mouse down events.
17797 *
17798 * @private
17799 * @param {MouseEvent} e Mouse down event
17800 */
17801 OO.ui.PopupWidget.prototype.onMouseDown = function ( e ) {
17802 if (
17803 this.isVisible() &&
17804 !$.contains( this.$element[ 0 ], e.target ) &&
17805 ( !this.$autoCloseIgnore || !this.$autoCloseIgnore.has( e.target ).length )
17806 ) {
17807 this.toggle( false );
17808 }
17809 };
17810
17811 /**
17812 * Bind mouse down listener.
17813 *
17814 * @private
17815 */
17816 OO.ui.PopupWidget.prototype.bindMouseDownListener = function () {
17817 // Capture clicks outside popup
17818 OO.ui.addCaptureEventListener( this.getElementWindow(), 'mousedown', this.onMouseDownHandler );
17819 };
17820
17821 /**
17822 * Handles close button click events.
17823 *
17824 * @private
17825 */
17826 OO.ui.PopupWidget.prototype.onCloseButtonClick = function () {
17827 if ( this.isVisible() ) {
17828 this.toggle( false );
17829 }
17830 };
17831
17832 /**
17833 * Unbind mouse down listener.
17834 *
17835 * @private
17836 */
17837 OO.ui.PopupWidget.prototype.unbindMouseDownListener = function () {
17838 OO.ui.removeCaptureEventListener( this.getElementWindow(), 'mousedown', this.onMouseDownHandler );
17839 };
17840
17841 /**
17842 * Handles key down events.
17843 *
17844 * @private
17845 * @param {KeyboardEvent} e Key down event
17846 */
17847 OO.ui.PopupWidget.prototype.onDocumentKeyDown = function ( e ) {
17848 if (
17849 e.which === OO.ui.Keys.ESCAPE &&
17850 this.isVisible()
17851 ) {
17852 this.toggle( false );
17853 e.preventDefault();
17854 e.stopPropagation();
17855 }
17856 };
17857
17858 /**
17859 * Bind key down listener.
17860 *
17861 * @private
17862 */
17863 OO.ui.PopupWidget.prototype.bindKeyDownListener = function () {
17864 OO.ui.addCaptureEventListener( this.getElementWindow(), 'keydown', this.onDocumentKeyDownHandler );
17865 };
17866
17867 /**
17868 * Unbind key down listener.
17869 *
17870 * @private
17871 */
17872 OO.ui.PopupWidget.prototype.unbindKeyDownListener = function () {
17873 OO.ui.removeCaptureEventListener( this.getElementWindow(), 'keydown', this.onDocumentKeyDownHandler );
17874 };
17875
17876 /**
17877 * Show, hide, or toggle the visibility of the anchor.
17878 *
17879 * @param {boolean} [show] Show anchor, omit to toggle
17880 */
17881 OO.ui.PopupWidget.prototype.toggleAnchor = function ( show ) {
17882 show = show === undefined ? !this.anchored : !!show;
17883
17884 if ( this.anchored !== show ) {
17885 if ( show ) {
17886 this.$element.addClass( 'oo-ui-popupWidget-anchored' );
17887 } else {
17888 this.$element.removeClass( 'oo-ui-popupWidget-anchored' );
17889 }
17890 this.anchored = show;
17891 }
17892 };
17893
17894 /**
17895 * Check if the anchor is visible.
17896 *
17897 * @return {boolean} Anchor is visible
17898 */
17899 OO.ui.PopupWidget.prototype.hasAnchor = function () {
17900 return this.anchor;
17901 };
17902
17903 /**
17904 * @inheritdoc
17905 */
17906 OO.ui.PopupWidget.prototype.toggle = function ( show ) {
17907 var change;
17908 show = show === undefined ? !this.isVisible() : !!show;
17909
17910 change = show !== this.isVisible();
17911
17912 // Parent method
17913 OO.ui.PopupWidget.parent.prototype.toggle.call( this, show );
17914
17915 if ( change ) {
17916 if ( show ) {
17917 if ( this.autoClose ) {
17918 this.bindMouseDownListener();
17919 this.bindKeyDownListener();
17920 }
17921 this.updateDimensions();
17922 this.toggleClipping( true );
17923 } else {
17924 this.toggleClipping( false );
17925 if ( this.autoClose ) {
17926 this.unbindMouseDownListener();
17927 this.unbindKeyDownListener();
17928 }
17929 }
17930 }
17931
17932 return this;
17933 };
17934
17935 /**
17936 * Set the size of the popup.
17937 *
17938 * Changing the size may also change the popup's position depending on the alignment.
17939 *
17940 * @param {number} width Width in pixels
17941 * @param {number} height Height in pixels
17942 * @param {boolean} [transition=false] Use a smooth transition
17943 * @chainable
17944 */
17945 OO.ui.PopupWidget.prototype.setSize = function ( width, height, transition ) {
17946 this.width = width;
17947 this.height = height !== undefined ? height : null;
17948 if ( this.isVisible() ) {
17949 this.updateDimensions( transition );
17950 }
17951 };
17952
17953 /**
17954 * Update the size and position.
17955 *
17956 * Only use this to keep the popup properly anchored. Use #setSize to change the size, and this will
17957 * be called automatically.
17958 *
17959 * @param {boolean} [transition=false] Use a smooth transition
17960 * @chainable
17961 */
17962 OO.ui.PopupWidget.prototype.updateDimensions = function ( transition ) {
17963 var popupOffset, originOffset, containerLeft, containerWidth, containerRight,
17964 popupLeft, popupRight, overlapLeft, overlapRight, anchorWidth,
17965 align = this.align,
17966 widget = this;
17967
17968 if ( !this.$container ) {
17969 // Lazy-initialize $container if not specified in constructor
17970 this.$container = $( this.getClosestScrollableElementContainer() );
17971 }
17972
17973 // Set height and width before measuring things, since it might cause our measurements
17974 // to change (e.g. due to scrollbars appearing or disappearing)
17975 this.$popup.css( {
17976 width: this.width,
17977 height: this.height !== null ? this.height : 'auto'
17978 } );
17979
17980 // If we are in RTL, we need to flip the alignment, unless it is center
17981 if ( align === 'forwards' || align === 'backwards' ) {
17982 if ( this.$container.css( 'direction' ) === 'rtl' ) {
17983 align = ( { forwards: 'force-left', backwards: 'force-right' } )[ this.align ];
17984 } else {
17985 align = ( { forwards: 'force-right', backwards: 'force-left' } )[ this.align ];
17986 }
17987
17988 }
17989
17990 // Compute initial popupOffset based on alignment
17991 popupOffset = this.width * ( { 'force-left': -1, center: -0.5, 'force-right': 0 } )[ align ];
17992
17993 // Figure out if this will cause the popup to go beyond the edge of the container
17994 originOffset = this.$element.offset().left;
17995 containerLeft = this.$container.offset().left;
17996 containerWidth = this.$container.innerWidth();
17997 containerRight = containerLeft + containerWidth;
17998 popupLeft = popupOffset - this.containerPadding;
17999 popupRight = popupOffset + this.containerPadding + this.width + this.containerPadding;
18000 overlapLeft = ( originOffset + popupLeft ) - containerLeft;
18001 overlapRight = containerRight - ( originOffset + popupRight );
18002
18003 // Adjust offset to make the popup not go beyond the edge, if needed
18004 if ( overlapRight < 0 ) {
18005 popupOffset += overlapRight;
18006 } else if ( overlapLeft < 0 ) {
18007 popupOffset -= overlapLeft;
18008 }
18009
18010 // Adjust offset to avoid anchor being rendered too close to the edge
18011 // $anchor.width() doesn't work with the pure CSS anchor (returns 0)
18012 // TODO: Find a measurement that works for CSS anchors and image anchors
18013 anchorWidth = this.$anchor[ 0 ].scrollWidth * 2;
18014 if ( popupOffset + this.width < anchorWidth ) {
18015 popupOffset = anchorWidth - this.width;
18016 } else if ( -popupOffset < anchorWidth ) {
18017 popupOffset = -anchorWidth;
18018 }
18019
18020 // Prevent transition from being interrupted
18021 clearTimeout( this.transitionTimeout );
18022 if ( transition ) {
18023 // Enable transition
18024 this.$element.addClass( 'oo-ui-popupWidget-transitioning' );
18025 }
18026
18027 // Position body relative to anchor
18028 this.$popup.css( 'margin-left', popupOffset );
18029
18030 if ( transition ) {
18031 // Prevent transitioning after transition is complete
18032 this.transitionTimeout = setTimeout( function () {
18033 widget.$element.removeClass( 'oo-ui-popupWidget-transitioning' );
18034 }, 200 );
18035 } else {
18036 // Prevent transitioning immediately
18037 this.$element.removeClass( 'oo-ui-popupWidget-transitioning' );
18038 }
18039
18040 // Reevaluate clipping state since we've relocated and resized the popup
18041 this.clip();
18042
18043 return this;
18044 };
18045
18046 /**
18047 * Set popup alignment
18048 * @param {string} align Alignment of the popup, `center`, `force-left`, `force-right`,
18049 * `backwards` or `forwards`.
18050 */
18051 OO.ui.PopupWidget.prototype.setAlignment = function ( align ) {
18052 // Validate alignment and transform deprecated values
18053 if ( [ 'left', 'right', 'force-left', 'force-right', 'backwards', 'forwards', 'center' ].indexOf( align ) > -1 ) {
18054 this.align = { left: 'force-right', right: 'force-left' }[ align ] || align;
18055 } else {
18056 this.align = 'center';
18057 }
18058 };
18059
18060 /**
18061 * Get popup alignment
18062 * @return {string} align Alignment of the popup, `center`, `force-left`, `force-right`,
18063 * `backwards` or `forwards`.
18064 */
18065 OO.ui.PopupWidget.prototype.getAlignment = function () {
18066 return this.align;
18067 };
18068
18069 /**
18070 * Progress bars visually display the status of an operation, such as a download,
18071 * and can be either determinate or indeterminate:
18072 *
18073 * - **determinate** process bars show the percent of an operation that is complete.
18074 *
18075 * - **indeterminate** process bars use a visual display of motion to indicate that an operation
18076 * is taking place. Because the extent of an indeterminate operation is unknown, the bar does
18077 * not use percentages.
18078 *
18079 * The value of the `progress` configuration determines whether the bar is determinate or indeterminate.
18080 *
18081 * @example
18082 * // Examples of determinate and indeterminate progress bars.
18083 * var progressBar1 = new OO.ui.ProgressBarWidget( {
18084 * progress: 33
18085 * } );
18086 * var progressBar2 = new OO.ui.ProgressBarWidget();
18087 *
18088 * // Create a FieldsetLayout to layout progress bars
18089 * var fieldset = new OO.ui.FieldsetLayout;
18090 * fieldset.addItems( [
18091 * new OO.ui.FieldLayout( progressBar1, {label: 'Determinate', align: 'top'}),
18092 * new OO.ui.FieldLayout( progressBar2, {label: 'Indeterminate', align: 'top'})
18093 * ] );
18094 * $( 'body' ).append( fieldset.$element );
18095 *
18096 * @class
18097 * @extends OO.ui.Widget
18098 *
18099 * @constructor
18100 * @param {Object} [config] Configuration options
18101 * @cfg {number|boolean} [progress=false] The type of progress bar (determinate or indeterminate).
18102 * To create a determinate progress bar, specify a number that reflects the initial percent complete.
18103 * By default, the progress bar is indeterminate.
18104 */
18105 OO.ui.ProgressBarWidget = function OoUiProgressBarWidget( config ) {
18106 // Configuration initialization
18107 config = config || {};
18108
18109 // Parent constructor
18110 OO.ui.ProgressBarWidget.parent.call( this, config );
18111
18112 // Properties
18113 this.$bar = $( '<div>' );
18114 this.progress = null;
18115
18116 // Initialization
18117 this.setProgress( config.progress !== undefined ? config.progress : false );
18118 this.$bar.addClass( 'oo-ui-progressBarWidget-bar' );
18119 this.$element
18120 .attr( {
18121 role: 'progressbar',
18122 'aria-valuemin': 0,
18123 'aria-valuemax': 100
18124 } )
18125 .addClass( 'oo-ui-progressBarWidget' )
18126 .append( this.$bar );
18127 };
18128
18129 /* Setup */
18130
18131 OO.inheritClass( OO.ui.ProgressBarWidget, OO.ui.Widget );
18132
18133 /* Static Properties */
18134
18135 OO.ui.ProgressBarWidget.static.tagName = 'div';
18136
18137 /* Methods */
18138
18139 /**
18140 * Get the percent of the progress that has been completed. Indeterminate progresses will return `false`.
18141 *
18142 * @return {number|boolean} Progress percent
18143 */
18144 OO.ui.ProgressBarWidget.prototype.getProgress = function () {
18145 return this.progress;
18146 };
18147
18148 /**
18149 * Set the percent of the process completed or `false` for an indeterminate process.
18150 *
18151 * @param {number|boolean} progress Progress percent or `false` for indeterminate
18152 */
18153 OO.ui.ProgressBarWidget.prototype.setProgress = function ( progress ) {
18154 this.progress = progress;
18155
18156 if ( progress !== false ) {
18157 this.$bar.css( 'width', this.progress + '%' );
18158 this.$element.attr( 'aria-valuenow', this.progress );
18159 } else {
18160 this.$bar.css( 'width', '' );
18161 this.$element.removeAttr( 'aria-valuenow' );
18162 }
18163 this.$element.toggleClass( 'oo-ui-progressBarWidget-indeterminate', !progress );
18164 };
18165
18166 /**
18167 * SearchWidgets combine a {@link OO.ui.TextInputWidget text input field}, where users can type a search query,
18168 * and a menu of search results, which is displayed beneath the query
18169 * field. Unlike {@link OO.ui.mixin.LookupElement lookup menus}, search result menus are always visible to the user.
18170 * Users can choose an item from the menu or type a query into the text field to search for a matching result item.
18171 * In general, search widgets are used inside a separate {@link OO.ui.Dialog dialog} window.
18172 *
18173 * Each time the query is changed, the search result menu is cleared and repopulated. Please see
18174 * the [OOjs UI demos][1] for an example.
18175 *
18176 * [1]: https://tools.wmflabs.org/oojs-ui/oojs-ui/demos/#dialogs-mediawiki-vector-ltr
18177 *
18178 * @class
18179 * @extends OO.ui.Widget
18180 *
18181 * @constructor
18182 * @param {Object} [config] Configuration options
18183 * @cfg {string|jQuery} [placeholder] Placeholder text for query input
18184 * @cfg {string} [value] Initial query value
18185 */
18186 OO.ui.SearchWidget = function OoUiSearchWidget( config ) {
18187 // Configuration initialization
18188 config = config || {};
18189
18190 // Parent constructor
18191 OO.ui.SearchWidget.parent.call( this, config );
18192
18193 // Properties
18194 this.query = new OO.ui.TextInputWidget( {
18195 icon: 'search',
18196 placeholder: config.placeholder,
18197 value: config.value
18198 } );
18199 this.results = new OO.ui.SelectWidget();
18200 this.$query = $( '<div>' );
18201 this.$results = $( '<div>' );
18202
18203 // Events
18204 this.query.connect( this, {
18205 change: 'onQueryChange',
18206 enter: 'onQueryEnter'
18207 } );
18208 this.query.$input.on( 'keydown', this.onQueryKeydown.bind( this ) );
18209
18210 // Initialization
18211 this.$query
18212 .addClass( 'oo-ui-searchWidget-query' )
18213 .append( this.query.$element );
18214 this.$results
18215 .addClass( 'oo-ui-searchWidget-results' )
18216 .append( this.results.$element );
18217 this.$element
18218 .addClass( 'oo-ui-searchWidget' )
18219 .append( this.$results, this.$query );
18220 };
18221
18222 /* Setup */
18223
18224 OO.inheritClass( OO.ui.SearchWidget, OO.ui.Widget );
18225
18226 /* Methods */
18227
18228 /**
18229 * Handle query key down events.
18230 *
18231 * @private
18232 * @param {jQuery.Event} e Key down event
18233 */
18234 OO.ui.SearchWidget.prototype.onQueryKeydown = function ( e ) {
18235 var highlightedItem, nextItem,
18236 dir = e.which === OO.ui.Keys.DOWN ? 1 : ( e.which === OO.ui.Keys.UP ? -1 : 0 );
18237
18238 if ( dir ) {
18239 highlightedItem = this.results.getHighlightedItem();
18240 if ( !highlightedItem ) {
18241 highlightedItem = this.results.getSelectedItem();
18242 }
18243 nextItem = this.results.getRelativeSelectableItem( highlightedItem, dir );
18244 this.results.highlightItem( nextItem );
18245 nextItem.scrollElementIntoView();
18246 }
18247 };
18248
18249 /**
18250 * Handle select widget select events.
18251 *
18252 * Clears existing results. Subclasses should repopulate items according to new query.
18253 *
18254 * @private
18255 * @param {string} value New value
18256 */
18257 OO.ui.SearchWidget.prototype.onQueryChange = function () {
18258 // Reset
18259 this.results.clearItems();
18260 };
18261
18262 /**
18263 * Handle select widget enter key events.
18264 *
18265 * Chooses highlighted item.
18266 *
18267 * @private
18268 * @param {string} value New value
18269 */
18270 OO.ui.SearchWidget.prototype.onQueryEnter = function () {
18271 var highlightedItem = this.results.getHighlightedItem();
18272 if ( highlightedItem ) {
18273 this.results.chooseItem( highlightedItem );
18274 }
18275 };
18276
18277 /**
18278 * Get the query input.
18279 *
18280 * @return {OO.ui.TextInputWidget} Query input
18281 */
18282 OO.ui.SearchWidget.prototype.getQuery = function () {
18283 return this.query;
18284 };
18285
18286 /**
18287 * Get the search results menu.
18288 *
18289 * @return {OO.ui.SelectWidget} Menu of search results
18290 */
18291 OO.ui.SearchWidget.prototype.getResults = function () {
18292 return this.results;
18293 };
18294
18295 /**
18296 * A SelectWidget is of a generic selection of options. The OOjs UI library contains several types of
18297 * select widgets, including {@link OO.ui.ButtonSelectWidget button selects},
18298 * {@link OO.ui.RadioSelectWidget radio selects}, and {@link OO.ui.MenuSelectWidget
18299 * menu selects}.
18300 *
18301 * This class should be used together with OO.ui.OptionWidget or OO.ui.DecoratedOptionWidget. For more
18302 * information, please see the [OOjs UI documentation on MediaWiki][1].
18303 *
18304 * @example
18305 * // Example of a select widget with three options
18306 * var select = new OO.ui.SelectWidget( {
18307 * items: [
18308 * new OO.ui.OptionWidget( {
18309 * data: 'a',
18310 * label: 'Option One',
18311 * } ),
18312 * new OO.ui.OptionWidget( {
18313 * data: 'b',
18314 * label: 'Option Two',
18315 * } ),
18316 * new OO.ui.OptionWidget( {
18317 * data: 'c',
18318 * label: 'Option Three',
18319 * } )
18320 * ]
18321 * } );
18322 * $( 'body' ).append( select.$element );
18323 *
18324 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
18325 *
18326 * @abstract
18327 * @class
18328 * @extends OO.ui.Widget
18329 * @mixins OO.ui.mixin.GroupWidget
18330 *
18331 * @constructor
18332 * @param {Object} [config] Configuration options
18333 * @cfg {OO.ui.OptionWidget[]} [items] An array of options to add to the select.
18334 * Options are created with {@link OO.ui.OptionWidget OptionWidget} classes. See
18335 * the [OOjs UI documentation on MediaWiki] [2] for examples.
18336 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
18337 */
18338 OO.ui.SelectWidget = function OoUiSelectWidget( config ) {
18339 // Configuration initialization
18340 config = config || {};
18341
18342 // Parent constructor
18343 OO.ui.SelectWidget.parent.call( this, config );
18344
18345 // Mixin constructors
18346 OO.ui.mixin.GroupWidget.call( this, $.extend( {}, config, { $group: this.$element } ) );
18347
18348 // Properties
18349 this.pressed = false;
18350 this.selecting = null;
18351 this.onMouseUpHandler = this.onMouseUp.bind( this );
18352 this.onMouseMoveHandler = this.onMouseMove.bind( this );
18353 this.onKeyDownHandler = this.onKeyDown.bind( this );
18354 this.onKeyPressHandler = this.onKeyPress.bind( this );
18355 this.keyPressBuffer = '';
18356 this.keyPressBufferTimer = null;
18357
18358 // Events
18359 this.connect( this, {
18360 toggle: 'onToggle'
18361 } );
18362 this.$element.on( {
18363 mousedown: this.onMouseDown.bind( this ),
18364 mouseover: this.onMouseOver.bind( this ),
18365 mouseleave: this.onMouseLeave.bind( this )
18366 } );
18367
18368 // Initialization
18369 this.$element
18370 .addClass( 'oo-ui-selectWidget oo-ui-selectWidget-depressed' )
18371 .attr( 'role', 'listbox' );
18372 if ( Array.isArray( config.items ) ) {
18373 this.addItems( config.items );
18374 }
18375 };
18376
18377 /* Setup */
18378
18379 OO.inheritClass( OO.ui.SelectWidget, OO.ui.Widget );
18380
18381 // Need to mixin base class as well
18382 OO.mixinClass( OO.ui.SelectWidget, OO.ui.mixin.GroupElement );
18383 OO.mixinClass( OO.ui.SelectWidget, OO.ui.mixin.GroupWidget );
18384
18385 /* Static */
18386 OO.ui.SelectWidget.static.passAllFilter = function () {
18387 return true;
18388 };
18389
18390 /* Events */
18391
18392 /**
18393 * @event highlight
18394 *
18395 * A `highlight` event is emitted when the highlight is changed with the #highlightItem method.
18396 *
18397 * @param {OO.ui.OptionWidget|null} item Highlighted item
18398 */
18399
18400 /**
18401 * @event press
18402 *
18403 * A `press` event is emitted when the #pressItem method is used to programmatically modify the
18404 * pressed state of an option.
18405 *
18406 * @param {OO.ui.OptionWidget|null} item Pressed item
18407 */
18408
18409 /**
18410 * @event select
18411 *
18412 * A `select` event is emitted when the selection is modified programmatically with the #selectItem method.
18413 *
18414 * @param {OO.ui.OptionWidget|null} item Selected item
18415 */
18416
18417 /**
18418 * @event choose
18419 * A `choose` event is emitted when an item is chosen with the #chooseItem method.
18420 * @param {OO.ui.OptionWidget} item Chosen item
18421 */
18422
18423 /**
18424 * @event add
18425 *
18426 * An `add` event is emitted when options are added to the select with the #addItems method.
18427 *
18428 * @param {OO.ui.OptionWidget[]} items Added items
18429 * @param {number} index Index of insertion point
18430 */
18431
18432 /**
18433 * @event remove
18434 *
18435 * A `remove` event is emitted when options are removed from the select with the #clearItems
18436 * or #removeItems methods.
18437 *
18438 * @param {OO.ui.OptionWidget[]} items Removed items
18439 */
18440
18441 /* Methods */
18442
18443 /**
18444 * Handle mouse down events.
18445 *
18446 * @private
18447 * @param {jQuery.Event} e Mouse down event
18448 */
18449 OO.ui.SelectWidget.prototype.onMouseDown = function ( e ) {
18450 var item;
18451
18452 if ( !this.isDisabled() && e.which === 1 ) {
18453 this.togglePressed( true );
18454 item = this.getTargetItem( e );
18455 if ( item && item.isSelectable() ) {
18456 this.pressItem( item );
18457 this.selecting = item;
18458 OO.ui.addCaptureEventListener(
18459 this.getElementDocument(),
18460 'mouseup',
18461 this.onMouseUpHandler
18462 );
18463 OO.ui.addCaptureEventListener(
18464 this.getElementDocument(),
18465 'mousemove',
18466 this.onMouseMoveHandler
18467 );
18468 }
18469 }
18470 return false;
18471 };
18472
18473 /**
18474 * Handle mouse up events.
18475 *
18476 * @private
18477 * @param {jQuery.Event} e Mouse up event
18478 */
18479 OO.ui.SelectWidget.prototype.onMouseUp = function ( e ) {
18480 var item;
18481
18482 this.togglePressed( false );
18483 if ( !this.selecting ) {
18484 item = this.getTargetItem( e );
18485 if ( item && item.isSelectable() ) {
18486 this.selecting = item;
18487 }
18488 }
18489 if ( !this.isDisabled() && e.which === 1 && this.selecting ) {
18490 this.pressItem( null );
18491 this.chooseItem( this.selecting );
18492 this.selecting = null;
18493 }
18494
18495 OO.ui.removeCaptureEventListener( this.getElementDocument(), 'mouseup',
18496 this.onMouseUpHandler );
18497 OO.ui.removeCaptureEventListener( this.getElementDocument(), 'mousemove',
18498 this.onMouseMoveHandler );
18499
18500 return false;
18501 };
18502
18503 /**
18504 * Handle mouse move events.
18505 *
18506 * @private
18507 * @param {jQuery.Event} e Mouse move event
18508 */
18509 OO.ui.SelectWidget.prototype.onMouseMove = function ( e ) {
18510 var item;
18511
18512 if ( !this.isDisabled() && this.pressed ) {
18513 item = this.getTargetItem( e );
18514 if ( item && item !== this.selecting && item.isSelectable() ) {
18515 this.pressItem( item );
18516 this.selecting = item;
18517 }
18518 }
18519 return false;
18520 };
18521
18522 /**
18523 * Handle mouse over events.
18524 *
18525 * @private
18526 * @param {jQuery.Event} e Mouse over event
18527 */
18528 OO.ui.SelectWidget.prototype.onMouseOver = function ( e ) {
18529 var item;
18530
18531 if ( !this.isDisabled() ) {
18532 item = this.getTargetItem( e );
18533 this.highlightItem( item && item.isHighlightable() ? item : null );
18534 }
18535 return false;
18536 };
18537
18538 /**
18539 * Handle mouse leave events.
18540 *
18541 * @private
18542 * @param {jQuery.Event} e Mouse over event
18543 */
18544 OO.ui.SelectWidget.prototype.onMouseLeave = function () {
18545 if ( !this.isDisabled() ) {
18546 this.highlightItem( null );
18547 }
18548 return false;
18549 };
18550
18551 /**
18552 * Handle key down events.
18553 *
18554 * @protected
18555 * @param {jQuery.Event} e Key down event
18556 */
18557 OO.ui.SelectWidget.prototype.onKeyDown = function ( e ) {
18558 var nextItem,
18559 handled = false,
18560 currentItem = this.getHighlightedItem() || this.getSelectedItem();
18561
18562 if ( !this.isDisabled() && this.isVisible() ) {
18563 switch ( e.keyCode ) {
18564 case OO.ui.Keys.ENTER:
18565 if ( currentItem && currentItem.constructor.static.highlightable ) {
18566 // Was only highlighted, now let's select it. No-op if already selected.
18567 this.chooseItem( currentItem );
18568 handled = true;
18569 }
18570 break;
18571 case OO.ui.Keys.UP:
18572 case OO.ui.Keys.LEFT:
18573 this.clearKeyPressBuffer();
18574 nextItem = this.getRelativeSelectableItem( currentItem, -1 );
18575 handled = true;
18576 break;
18577 case OO.ui.Keys.DOWN:
18578 case OO.ui.Keys.RIGHT:
18579 this.clearKeyPressBuffer();
18580 nextItem = this.getRelativeSelectableItem( currentItem, 1 );
18581 handled = true;
18582 break;
18583 case OO.ui.Keys.ESCAPE:
18584 case OO.ui.Keys.TAB:
18585 if ( currentItem && currentItem.constructor.static.highlightable ) {
18586 currentItem.setHighlighted( false );
18587 }
18588 this.unbindKeyDownListener();
18589 this.unbindKeyPressListener();
18590 // Don't prevent tabbing away / defocusing
18591 handled = false;
18592 break;
18593 }
18594
18595 if ( nextItem ) {
18596 if ( nextItem.constructor.static.highlightable ) {
18597 this.highlightItem( nextItem );
18598 } else {
18599 this.chooseItem( nextItem );
18600 }
18601 nextItem.scrollElementIntoView();
18602 }
18603
18604 if ( handled ) {
18605 // Can't just return false, because e is not always a jQuery event
18606 e.preventDefault();
18607 e.stopPropagation();
18608 }
18609 }
18610 };
18611
18612 /**
18613 * Bind key down listener.
18614 *
18615 * @protected
18616 */
18617 OO.ui.SelectWidget.prototype.bindKeyDownListener = function () {
18618 OO.ui.addCaptureEventListener( this.getElementWindow(), 'keydown', this.onKeyDownHandler );
18619 };
18620
18621 /**
18622 * Unbind key down listener.
18623 *
18624 * @protected
18625 */
18626 OO.ui.SelectWidget.prototype.unbindKeyDownListener = function () {
18627 OO.ui.removeCaptureEventListener( this.getElementWindow(), 'keydown', this.onKeyDownHandler );
18628 };
18629
18630 /**
18631 * Clear the key-press buffer
18632 *
18633 * @protected
18634 */
18635 OO.ui.SelectWidget.prototype.clearKeyPressBuffer = function () {
18636 if ( this.keyPressBufferTimer ) {
18637 clearTimeout( this.keyPressBufferTimer );
18638 this.keyPressBufferTimer = null;
18639 }
18640 this.keyPressBuffer = '';
18641 };
18642
18643 /**
18644 * Handle key press events.
18645 *
18646 * @protected
18647 * @param {jQuery.Event} e Key press event
18648 */
18649 OO.ui.SelectWidget.prototype.onKeyPress = function ( e ) {
18650 var c, filter, item;
18651
18652 if ( !e.charCode ) {
18653 if ( e.keyCode === OO.ui.Keys.BACKSPACE && this.keyPressBuffer !== '' ) {
18654 this.keyPressBuffer = this.keyPressBuffer.substr( 0, this.keyPressBuffer.length - 1 );
18655 return false;
18656 }
18657 return;
18658 }
18659 if ( String.fromCodePoint ) {
18660 c = String.fromCodePoint( e.charCode );
18661 } else {
18662 c = String.fromCharCode( e.charCode );
18663 }
18664
18665 if ( this.keyPressBufferTimer ) {
18666 clearTimeout( this.keyPressBufferTimer );
18667 }
18668 this.keyPressBufferTimer = setTimeout( this.clearKeyPressBuffer.bind( this ), 1500 );
18669
18670 item = this.getHighlightedItem() || this.getSelectedItem();
18671
18672 if ( this.keyPressBuffer === c ) {
18673 // Common (if weird) special case: typing "xxxx" will cycle through all
18674 // the items beginning with "x".
18675 if ( item ) {
18676 item = this.getRelativeSelectableItem( item, 1 );
18677 }
18678 } else {
18679 this.keyPressBuffer += c;
18680 }
18681
18682 filter = this.getItemMatcher( this.keyPressBuffer, false );
18683 if ( !item || !filter( item ) ) {
18684 item = this.getRelativeSelectableItem( item, 1, filter );
18685 }
18686 if ( item ) {
18687 if ( item.constructor.static.highlightable ) {
18688 this.highlightItem( item );
18689 } else {
18690 this.chooseItem( item );
18691 }
18692 item.scrollElementIntoView();
18693 }
18694
18695 return false;
18696 };
18697
18698 /**
18699 * Get a matcher for the specific string
18700 *
18701 * @protected
18702 * @param {string} s String to match against items
18703 * @param {boolean} [exact=false] Only accept exact matches
18704 * @return {Function} function ( OO.ui.OptionItem ) => boolean
18705 */
18706 OO.ui.SelectWidget.prototype.getItemMatcher = function ( s, exact ) {
18707 var re;
18708
18709 if ( s.normalize ) {
18710 s = s.normalize();
18711 }
18712 s = exact ? s.trim() : s.replace( /^\s+/, '' );
18713 re = '^\\s*' + s.replace( /([\\{}()|.?*+\-\^$\[\]])/g, '\\$1' ).replace( /\s+/g, '\\s+' );
18714 if ( exact ) {
18715 re += '\\s*$';
18716 }
18717 re = new RegExp( re, 'i' );
18718 return function ( item ) {
18719 var l = item.getLabel();
18720 if ( typeof l !== 'string' ) {
18721 l = item.$label.text();
18722 }
18723 if ( l.normalize ) {
18724 l = l.normalize();
18725 }
18726 return re.test( l );
18727 };
18728 };
18729
18730 /**
18731 * Bind key press listener.
18732 *
18733 * @protected
18734 */
18735 OO.ui.SelectWidget.prototype.bindKeyPressListener = function () {
18736 OO.ui.addCaptureEventListener( this.getElementWindow(), 'keypress', this.onKeyPressHandler );
18737 };
18738
18739 /**
18740 * Unbind key down listener.
18741 *
18742 * If you override this, be sure to call this.clearKeyPressBuffer() from your
18743 * implementation.
18744 *
18745 * @protected
18746 */
18747 OO.ui.SelectWidget.prototype.unbindKeyPressListener = function () {
18748 OO.ui.removeCaptureEventListener( this.getElementWindow(), 'keypress', this.onKeyPressHandler );
18749 this.clearKeyPressBuffer();
18750 };
18751
18752 /**
18753 * Visibility change handler
18754 *
18755 * @protected
18756 * @param {boolean} visible
18757 */
18758 OO.ui.SelectWidget.prototype.onToggle = function ( visible ) {
18759 if ( !visible ) {
18760 this.clearKeyPressBuffer();
18761 }
18762 };
18763
18764 /**
18765 * Get the closest item to a jQuery.Event.
18766 *
18767 * @private
18768 * @param {jQuery.Event} e
18769 * @return {OO.ui.OptionWidget|null} Outline item widget, `null` if none was found
18770 */
18771 OO.ui.SelectWidget.prototype.getTargetItem = function ( e ) {
18772 return $( e.target ).closest( '.oo-ui-optionWidget' ).data( 'oo-ui-optionWidget' ) || null;
18773 };
18774
18775 /**
18776 * Get selected item.
18777 *
18778 * @return {OO.ui.OptionWidget|null} Selected item, `null` if no item is selected
18779 */
18780 OO.ui.SelectWidget.prototype.getSelectedItem = function () {
18781 var i, len;
18782
18783 for ( i = 0, len = this.items.length; i < len; i++ ) {
18784 if ( this.items[ i ].isSelected() ) {
18785 return this.items[ i ];
18786 }
18787 }
18788 return null;
18789 };
18790
18791 /**
18792 * Get highlighted item.
18793 *
18794 * @return {OO.ui.OptionWidget|null} Highlighted item, `null` if no item is highlighted
18795 */
18796 OO.ui.SelectWidget.prototype.getHighlightedItem = function () {
18797 var i, len;
18798
18799 for ( i = 0, len = this.items.length; i < len; i++ ) {
18800 if ( this.items[ i ].isHighlighted() ) {
18801 return this.items[ i ];
18802 }
18803 }
18804 return null;
18805 };
18806
18807 /**
18808 * Toggle pressed state.
18809 *
18810 * Press is a state that occurs when a user mouses down on an item, but
18811 * has not yet let go of the mouse. The item may appear selected, but it will not be selected
18812 * until the user releases the mouse.
18813 *
18814 * @param {boolean} pressed An option is being pressed
18815 */
18816 OO.ui.SelectWidget.prototype.togglePressed = function ( pressed ) {
18817 if ( pressed === undefined ) {
18818 pressed = !this.pressed;
18819 }
18820 if ( pressed !== this.pressed ) {
18821 this.$element
18822 .toggleClass( 'oo-ui-selectWidget-pressed', pressed )
18823 .toggleClass( 'oo-ui-selectWidget-depressed', !pressed );
18824 this.pressed = pressed;
18825 }
18826 };
18827
18828 /**
18829 * Highlight an option. If the `item` param is omitted, no options will be highlighted
18830 * and any existing highlight will be removed. The highlight is mutually exclusive.
18831 *
18832 * @param {OO.ui.OptionWidget} [item] Item to highlight, omit for no highlight
18833 * @fires highlight
18834 * @chainable
18835 */
18836 OO.ui.SelectWidget.prototype.highlightItem = function ( item ) {
18837 var i, len, highlighted,
18838 changed = false;
18839
18840 for ( i = 0, len = this.items.length; i < len; i++ ) {
18841 highlighted = this.items[ i ] === item;
18842 if ( this.items[ i ].isHighlighted() !== highlighted ) {
18843 this.items[ i ].setHighlighted( highlighted );
18844 changed = true;
18845 }
18846 }
18847 if ( changed ) {
18848 this.emit( 'highlight', item );
18849 }
18850
18851 return this;
18852 };
18853
18854 /**
18855 * Fetch an item by its label.
18856 *
18857 * @param {string} label Label of the item to select.
18858 * @param {boolean} [prefix=false] Allow a prefix match, if only a single item matches
18859 * @return {OO.ui.Element|null} Item with equivalent label, `null` if none exists
18860 */
18861 OO.ui.SelectWidget.prototype.getItemFromLabel = function ( label, prefix ) {
18862 var i, item, found,
18863 len = this.items.length,
18864 filter = this.getItemMatcher( label, true );
18865
18866 for ( i = 0; i < len; i++ ) {
18867 item = this.items[ i ];
18868 if ( item instanceof OO.ui.OptionWidget && item.isSelectable() && filter( item ) ) {
18869 return item;
18870 }
18871 }
18872
18873 if ( prefix ) {
18874 found = null;
18875 filter = this.getItemMatcher( label, false );
18876 for ( i = 0; i < len; i++ ) {
18877 item = this.items[ i ];
18878 if ( item instanceof OO.ui.OptionWidget && item.isSelectable() && filter( item ) ) {
18879 if ( found ) {
18880 return null;
18881 }
18882 found = item;
18883 }
18884 }
18885 if ( found ) {
18886 return found;
18887 }
18888 }
18889
18890 return null;
18891 };
18892
18893 /**
18894 * Programmatically select an option by its label. If the item does not exist,
18895 * all options will be deselected.
18896 *
18897 * @param {string} [label] Label of the item to select.
18898 * @param {boolean} [prefix=false] Allow a prefix match, if only a single item matches
18899 * @fires select
18900 * @chainable
18901 */
18902 OO.ui.SelectWidget.prototype.selectItemByLabel = function ( label, prefix ) {
18903 var itemFromLabel = this.getItemFromLabel( label, !!prefix );
18904 if ( label === undefined || !itemFromLabel ) {
18905 return this.selectItem();
18906 }
18907 return this.selectItem( itemFromLabel );
18908 };
18909
18910 /**
18911 * Programmatically select an option by its data. If the `data` parameter is omitted,
18912 * or if the item does not exist, all options will be deselected.
18913 *
18914 * @param {Object|string} [data] Value of the item to select, omit to deselect all
18915 * @fires select
18916 * @chainable
18917 */
18918 OO.ui.SelectWidget.prototype.selectItemByData = function ( data ) {
18919 var itemFromData = this.getItemFromData( data );
18920 if ( data === undefined || !itemFromData ) {
18921 return this.selectItem();
18922 }
18923 return this.selectItem( itemFromData );
18924 };
18925
18926 /**
18927 * Programmatically select an option by its reference. If the `item` parameter is omitted,
18928 * all options will be deselected.
18929 *
18930 * @param {OO.ui.OptionWidget} [item] Item to select, omit to deselect all
18931 * @fires select
18932 * @chainable
18933 */
18934 OO.ui.SelectWidget.prototype.selectItem = function ( item ) {
18935 var i, len, selected,
18936 changed = false;
18937
18938 for ( i = 0, len = this.items.length; i < len; i++ ) {
18939 selected = this.items[ i ] === item;
18940 if ( this.items[ i ].isSelected() !== selected ) {
18941 this.items[ i ].setSelected( selected );
18942 changed = true;
18943 }
18944 }
18945 if ( changed ) {
18946 this.emit( 'select', item );
18947 }
18948
18949 return this;
18950 };
18951
18952 /**
18953 * Press an item.
18954 *
18955 * Press is a state that occurs when a user mouses down on an item, but has not
18956 * yet let go of the mouse. The item may appear selected, but it will not be selected until the user
18957 * releases the mouse.
18958 *
18959 * @param {OO.ui.OptionWidget} [item] Item to press, omit to depress all
18960 * @fires press
18961 * @chainable
18962 */
18963 OO.ui.SelectWidget.prototype.pressItem = function ( item ) {
18964 var i, len, pressed,
18965 changed = false;
18966
18967 for ( i = 0, len = this.items.length; i < len; i++ ) {
18968 pressed = this.items[ i ] === item;
18969 if ( this.items[ i ].isPressed() !== pressed ) {
18970 this.items[ i ].setPressed( pressed );
18971 changed = true;
18972 }
18973 }
18974 if ( changed ) {
18975 this.emit( 'press', item );
18976 }
18977
18978 return this;
18979 };
18980
18981 /**
18982 * Choose an item.
18983 *
18984 * Note that ‘choose’ should never be modified programmatically. A user can choose
18985 * an option with the keyboard or mouse and it becomes selected. To select an item programmatically,
18986 * use the #selectItem method.
18987 *
18988 * This method is identical to #selectItem, but may vary in subclasses that take additional action
18989 * when users choose an item with the keyboard or mouse.
18990 *
18991 * @param {OO.ui.OptionWidget} item Item to choose
18992 * @fires choose
18993 * @chainable
18994 */
18995 OO.ui.SelectWidget.prototype.chooseItem = function ( item ) {
18996 if ( item ) {
18997 this.selectItem( item );
18998 this.emit( 'choose', item );
18999 }
19000
19001 return this;
19002 };
19003
19004 /**
19005 * Get an option by its position relative to the specified item (or to the start of the option array,
19006 * if item is `null`). The direction in which to search through the option array is specified with a
19007 * number: -1 for reverse (the default) or 1 for forward. The method will return an option, or
19008 * `null` if there are no options in the array.
19009 *
19010 * @param {OO.ui.OptionWidget|null} item Item to describe the start position, or `null` to start at the beginning of the array.
19011 * @param {number} direction Direction to move in: -1 to move backward, 1 to move forward
19012 * @param {Function} filter Only consider items for which this function returns
19013 * true. Function takes an OO.ui.OptionWidget and returns a boolean.
19014 * @return {OO.ui.OptionWidget|null} Item at position, `null` if there are no items in the select
19015 */
19016 OO.ui.SelectWidget.prototype.getRelativeSelectableItem = function ( item, direction, filter ) {
19017 var currentIndex, nextIndex, i,
19018 increase = direction > 0 ? 1 : -1,
19019 len = this.items.length;
19020
19021 if ( !$.isFunction( filter ) ) {
19022 filter = OO.ui.SelectWidget.static.passAllFilter;
19023 }
19024
19025 if ( item instanceof OO.ui.OptionWidget ) {
19026 currentIndex = this.items.indexOf( item );
19027 nextIndex = ( currentIndex + increase + len ) % len;
19028 } else {
19029 // If no item is selected and moving forward, start at the beginning.
19030 // If moving backward, start at the end.
19031 nextIndex = direction > 0 ? 0 : len - 1;
19032 }
19033
19034 for ( i = 0; i < len; i++ ) {
19035 item = this.items[ nextIndex ];
19036 if ( item instanceof OO.ui.OptionWidget && item.isSelectable() && filter( item ) ) {
19037 return item;
19038 }
19039 nextIndex = ( nextIndex + increase + len ) % len;
19040 }
19041 return null;
19042 };
19043
19044 /**
19045 * Get the next selectable item or `null` if there are no selectable items.
19046 * Disabled options and menu-section markers and breaks are not selectable.
19047 *
19048 * @return {OO.ui.OptionWidget|null} Item, `null` if there aren't any selectable items
19049 */
19050 OO.ui.SelectWidget.prototype.getFirstSelectableItem = function () {
19051 var i, len, item;
19052
19053 for ( i = 0, len = this.items.length; i < len; i++ ) {
19054 item = this.items[ i ];
19055 if ( item instanceof OO.ui.OptionWidget && item.isSelectable() ) {
19056 return item;
19057 }
19058 }
19059
19060 return null;
19061 };
19062
19063 /**
19064 * Add an array of options to the select. Optionally, an index number can be used to
19065 * specify an insertion point.
19066 *
19067 * @param {OO.ui.OptionWidget[]} items Items to add
19068 * @param {number} [index] Index to insert items after
19069 * @fires add
19070 * @chainable
19071 */
19072 OO.ui.SelectWidget.prototype.addItems = function ( items, index ) {
19073 // Mixin method
19074 OO.ui.mixin.GroupWidget.prototype.addItems.call( this, items, index );
19075
19076 // Always provide an index, even if it was omitted
19077 this.emit( 'add', items, index === undefined ? this.items.length - items.length - 1 : index );
19078
19079 return this;
19080 };
19081
19082 /**
19083 * Remove the specified array of options from the select. Options will be detached
19084 * from the DOM, not removed, so they can be reused later. To remove all options from
19085 * the select, you may wish to use the #clearItems method instead.
19086 *
19087 * @param {OO.ui.OptionWidget[]} items Items to remove
19088 * @fires remove
19089 * @chainable
19090 */
19091 OO.ui.SelectWidget.prototype.removeItems = function ( items ) {
19092 var i, len, item;
19093
19094 // Deselect items being removed
19095 for ( i = 0, len = items.length; i < len; i++ ) {
19096 item = items[ i ];
19097 if ( item.isSelected() ) {
19098 this.selectItem( null );
19099 }
19100 }
19101
19102 // Mixin method
19103 OO.ui.mixin.GroupWidget.prototype.removeItems.call( this, items );
19104
19105 this.emit( 'remove', items );
19106
19107 return this;
19108 };
19109
19110 /**
19111 * Clear all options from the select. Options will be detached from the DOM, not removed,
19112 * so that they can be reused later. To remove a subset of options from the select, use
19113 * the #removeItems method.
19114 *
19115 * @fires remove
19116 * @chainable
19117 */
19118 OO.ui.SelectWidget.prototype.clearItems = function () {
19119 var items = this.items.slice();
19120
19121 // Mixin method
19122 OO.ui.mixin.GroupWidget.prototype.clearItems.call( this );
19123
19124 // Clear selection
19125 this.selectItem( null );
19126
19127 this.emit( 'remove', items );
19128
19129 return this;
19130 };
19131
19132 /**
19133 * ButtonSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains
19134 * button options and is used together with
19135 * OO.ui.ButtonOptionWidget. The ButtonSelectWidget provides an interface for
19136 * highlighting, choosing, and selecting mutually exclusive options. Please see
19137 * the [OOjs UI documentation on MediaWiki] [1] for more information.
19138 *
19139 * @example
19140 * // Example: A ButtonSelectWidget that contains three ButtonOptionWidgets
19141 * var option1 = new OO.ui.ButtonOptionWidget( {
19142 * data: 1,
19143 * label: 'Option 1',
19144 * title: 'Button option 1'
19145 * } );
19146 *
19147 * var option2 = new OO.ui.ButtonOptionWidget( {
19148 * data: 2,
19149 * label: 'Option 2',
19150 * title: 'Button option 2'
19151 * } );
19152 *
19153 * var option3 = new OO.ui.ButtonOptionWidget( {
19154 * data: 3,
19155 * label: 'Option 3',
19156 * title: 'Button option 3'
19157 * } );
19158 *
19159 * var buttonSelect=new OO.ui.ButtonSelectWidget( {
19160 * items: [ option1, option2, option3 ]
19161 * } );
19162 * $( 'body' ).append( buttonSelect.$element );
19163 *
19164 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
19165 *
19166 * @class
19167 * @extends OO.ui.SelectWidget
19168 * @mixins OO.ui.mixin.TabIndexedElement
19169 *
19170 * @constructor
19171 * @param {Object} [config] Configuration options
19172 */
19173 OO.ui.ButtonSelectWidget = function OoUiButtonSelectWidget( config ) {
19174 // Parent constructor
19175 OO.ui.ButtonSelectWidget.parent.call( this, config );
19176
19177 // Mixin constructors
19178 OO.ui.mixin.TabIndexedElement.call( this, config );
19179
19180 // Events
19181 this.$element.on( {
19182 focus: this.bindKeyDownListener.bind( this ),
19183 blur: this.unbindKeyDownListener.bind( this )
19184 } );
19185
19186 // Initialization
19187 this.$element.addClass( 'oo-ui-buttonSelectWidget' );
19188 };
19189
19190 /* Setup */
19191
19192 OO.inheritClass( OO.ui.ButtonSelectWidget, OO.ui.SelectWidget );
19193 OO.mixinClass( OO.ui.ButtonSelectWidget, OO.ui.mixin.TabIndexedElement );
19194
19195 /**
19196 * RadioSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains radio
19197 * options and is used together with OO.ui.RadioOptionWidget. The RadioSelectWidget provides
19198 * an interface for adding, removing and selecting options.
19199 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
19200 *
19201 * If you want to use this within a HTML form, such as a OO.ui.FormLayout, use
19202 * OO.ui.RadioSelectInputWidget instead.
19203 *
19204 * @example
19205 * // A RadioSelectWidget with RadioOptions.
19206 * var option1 = new OO.ui.RadioOptionWidget( {
19207 * data: 'a',
19208 * label: 'Selected radio option'
19209 * } );
19210 *
19211 * var option2 = new OO.ui.RadioOptionWidget( {
19212 * data: 'b',
19213 * label: 'Unselected radio option'
19214 * } );
19215 *
19216 * var radioSelect=new OO.ui.RadioSelectWidget( {
19217 * items: [ option1, option2 ]
19218 * } );
19219 *
19220 * // Select 'option 1' using the RadioSelectWidget's selectItem() method.
19221 * radioSelect.selectItem( option1 );
19222 *
19223 * $( 'body' ).append( radioSelect.$element );
19224 *
19225 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
19226
19227 *
19228 * @class
19229 * @extends OO.ui.SelectWidget
19230 * @mixins OO.ui.mixin.TabIndexedElement
19231 *
19232 * @constructor
19233 * @param {Object} [config] Configuration options
19234 */
19235 OO.ui.RadioSelectWidget = function OoUiRadioSelectWidget( config ) {
19236 // Parent constructor
19237 OO.ui.RadioSelectWidget.parent.call( this, config );
19238
19239 // Mixin constructors
19240 OO.ui.mixin.TabIndexedElement.call( this, config );
19241
19242 // Events
19243 this.$element.on( {
19244 focus: this.bindKeyDownListener.bind( this ),
19245 blur: this.unbindKeyDownListener.bind( this )
19246 } );
19247
19248 // Initialization
19249 this.$element
19250 .addClass( 'oo-ui-radioSelectWidget' )
19251 .attr( 'role', 'radiogroup' );
19252 };
19253
19254 /* Setup */
19255
19256 OO.inheritClass( OO.ui.RadioSelectWidget, OO.ui.SelectWidget );
19257 OO.mixinClass( OO.ui.RadioSelectWidget, OO.ui.mixin.TabIndexedElement );
19258
19259 /**
19260 * MenuSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains options and
19261 * is used together with OO.ui.MenuOptionWidget. It is designed be used as part of another widget.
19262 * See {@link OO.ui.DropdownWidget DropdownWidget}, {@link OO.ui.ComboBoxInputWidget ComboBoxInputWidget},
19263 * and {@link OO.ui.mixin.LookupElement LookupElement} for examples of widgets that contain menus.
19264 * MenuSelectWidgets themselves are not instantiated directly, rather subclassed
19265 * and customized to be opened, closed, and displayed as needed.
19266 *
19267 * By default, menus are clipped to the visible viewport and are not visible when a user presses the
19268 * mouse outside the menu.
19269 *
19270 * Menus also have support for keyboard interaction:
19271 *
19272 * - Enter/Return key: choose and select a menu option
19273 * - Up-arrow key: highlight the previous menu option
19274 * - Down-arrow key: highlight the next menu option
19275 * - Esc key: hide the menu
19276 *
19277 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
19278 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
19279 *
19280 * @class
19281 * @extends OO.ui.SelectWidget
19282 * @mixins OO.ui.mixin.ClippableElement
19283 *
19284 * @constructor
19285 * @param {Object} [config] Configuration options
19286 * @cfg {OO.ui.TextInputWidget} [input] Text input used to implement option highlighting for menu items that match
19287 * the text the user types. This config is used by {@link OO.ui.ComboBoxInputWidget ComboBoxInputWidget}
19288 * and {@link OO.ui.mixin.LookupElement LookupElement}
19289 * @cfg {jQuery} [$input] Text input used to implement option highlighting for menu items that match
19290 * the text the user types. This config is used by {@link OO.ui.CapsuleMultiSelectWidget CapsuleMultiSelectWidget}
19291 * @cfg {OO.ui.Widget} [widget] Widget associated with the menu's active state. If the user clicks the mouse
19292 * anywhere on the page outside of this widget, the menu is hidden. For example, if there is a button
19293 * that toggles the menu's visibility on click, the menu will be hidden then re-shown when the user clicks
19294 * that button, unless the button (or its parent widget) is passed in here.
19295 * @cfg {boolean} [autoHide=true] Hide the menu when the mouse is pressed outside the menu.
19296 * @cfg {boolean} [filterFromInput=false] Filter the displayed options from the input
19297 */
19298 OO.ui.MenuSelectWidget = function OoUiMenuSelectWidget( config ) {
19299 // Configuration initialization
19300 config = config || {};
19301
19302 // Parent constructor
19303 OO.ui.MenuSelectWidget.parent.call( this, config );
19304
19305 // Mixin constructors
19306 OO.ui.mixin.ClippableElement.call( this, $.extend( {}, config, { $clippable: this.$group } ) );
19307
19308 // Properties
19309 this.newItems = null;
19310 this.autoHide = config.autoHide === undefined || !!config.autoHide;
19311 this.filterFromInput = !!config.filterFromInput;
19312 this.$input = config.$input ? config.$input : config.input ? config.input.$input : null;
19313 this.$widget = config.widget ? config.widget.$element : null;
19314 this.onDocumentMouseDownHandler = this.onDocumentMouseDown.bind( this );
19315 this.onInputEditHandler = OO.ui.debounce( this.updateItemVisibility.bind( this ), 100 );
19316
19317 // Initialization
19318 this.$element
19319 .addClass( 'oo-ui-menuSelectWidget' )
19320 .attr( 'role', 'menu' );
19321
19322 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
19323 // that reference properties not initialized at that time of parent class construction
19324 // TODO: Find a better way to handle post-constructor setup
19325 this.visible = false;
19326 this.$element.addClass( 'oo-ui-element-hidden' );
19327 };
19328
19329 /* Setup */
19330
19331 OO.inheritClass( OO.ui.MenuSelectWidget, OO.ui.SelectWidget );
19332 OO.mixinClass( OO.ui.MenuSelectWidget, OO.ui.mixin.ClippableElement );
19333
19334 /* Methods */
19335
19336 /**
19337 * Handles document mouse down events.
19338 *
19339 * @protected
19340 * @param {jQuery.Event} e Key down event
19341 */
19342 OO.ui.MenuSelectWidget.prototype.onDocumentMouseDown = function ( e ) {
19343 if (
19344 !OO.ui.contains( this.$element[ 0 ], e.target, true ) &&
19345 ( !this.$widget || !OO.ui.contains( this.$widget[ 0 ], e.target, true ) )
19346 ) {
19347 this.toggle( false );
19348 }
19349 };
19350
19351 /**
19352 * @inheritdoc
19353 */
19354 OO.ui.MenuSelectWidget.prototype.onKeyDown = function ( e ) {
19355 var currentItem = this.getHighlightedItem() || this.getSelectedItem();
19356
19357 if ( !this.isDisabled() && this.isVisible() ) {
19358 switch ( e.keyCode ) {
19359 case OO.ui.Keys.LEFT:
19360 case OO.ui.Keys.RIGHT:
19361 // Do nothing if a text field is associated, arrow keys will be handled natively
19362 if ( !this.$input ) {
19363 OO.ui.MenuSelectWidget.parent.prototype.onKeyDown.call( this, e );
19364 }
19365 break;
19366 case OO.ui.Keys.ESCAPE:
19367 case OO.ui.Keys.TAB:
19368 if ( currentItem ) {
19369 currentItem.setHighlighted( false );
19370 }
19371 this.toggle( false );
19372 // Don't prevent tabbing away, prevent defocusing
19373 if ( e.keyCode === OO.ui.Keys.ESCAPE ) {
19374 e.preventDefault();
19375 e.stopPropagation();
19376 }
19377 break;
19378 default:
19379 OO.ui.MenuSelectWidget.parent.prototype.onKeyDown.call( this, e );
19380 return;
19381 }
19382 }
19383 };
19384
19385 /**
19386 * Update menu item visibility after input changes.
19387 * @protected
19388 */
19389 OO.ui.MenuSelectWidget.prototype.updateItemVisibility = function () {
19390 var i, item,
19391 len = this.items.length,
19392 showAll = !this.isVisible(),
19393 filter = showAll ? null : this.getItemMatcher( this.$input.val() );
19394
19395 for ( i = 0; i < len; i++ ) {
19396 item = this.items[ i ];
19397 if ( item instanceof OO.ui.OptionWidget ) {
19398 item.toggle( showAll || filter( item ) );
19399 }
19400 }
19401
19402 // Reevaluate clipping
19403 this.clip();
19404 };
19405
19406 /**
19407 * @inheritdoc
19408 */
19409 OO.ui.MenuSelectWidget.prototype.bindKeyDownListener = function () {
19410 if ( this.$input ) {
19411 this.$input.on( 'keydown', this.onKeyDownHandler );
19412 } else {
19413 OO.ui.MenuSelectWidget.parent.prototype.bindKeyDownListener.call( this );
19414 }
19415 };
19416
19417 /**
19418 * @inheritdoc
19419 */
19420 OO.ui.MenuSelectWidget.prototype.unbindKeyDownListener = function () {
19421 if ( this.$input ) {
19422 this.$input.off( 'keydown', this.onKeyDownHandler );
19423 } else {
19424 OO.ui.MenuSelectWidget.parent.prototype.unbindKeyDownListener.call( this );
19425 }
19426 };
19427
19428 /**
19429 * @inheritdoc
19430 */
19431 OO.ui.MenuSelectWidget.prototype.bindKeyPressListener = function () {
19432 if ( this.$input ) {
19433 if ( this.filterFromInput ) {
19434 this.$input.on( 'keydown mouseup cut paste change input select', this.onInputEditHandler );
19435 }
19436 } else {
19437 OO.ui.MenuSelectWidget.parent.prototype.bindKeyPressListener.call( this );
19438 }
19439 };
19440
19441 /**
19442 * @inheritdoc
19443 */
19444 OO.ui.MenuSelectWidget.prototype.unbindKeyPressListener = function () {
19445 if ( this.$input ) {
19446 if ( this.filterFromInput ) {
19447 this.$input.off( 'keydown mouseup cut paste change input select', this.onInputEditHandler );
19448 this.updateItemVisibility();
19449 }
19450 } else {
19451 OO.ui.MenuSelectWidget.parent.prototype.unbindKeyPressListener.call( this );
19452 }
19453 };
19454
19455 /**
19456 * Choose an item.
19457 *
19458 * When a user chooses an item, the menu is closed.
19459 *
19460 * Note that ‘choose’ should never be modified programmatically. A user can choose an option with the keyboard
19461 * or mouse and it becomes selected. To select an item programmatically, use the #selectItem method.
19462 * @param {OO.ui.OptionWidget} item Item to choose
19463 * @chainable
19464 */
19465 OO.ui.MenuSelectWidget.prototype.chooseItem = function ( item ) {
19466 OO.ui.MenuSelectWidget.parent.prototype.chooseItem.call( this, item );
19467 this.toggle( false );
19468 return this;
19469 };
19470
19471 /**
19472 * @inheritdoc
19473 */
19474 OO.ui.MenuSelectWidget.prototype.addItems = function ( items, index ) {
19475 var i, len, item;
19476
19477 // Parent method
19478 OO.ui.MenuSelectWidget.parent.prototype.addItems.call( this, items, index );
19479
19480 // Auto-initialize
19481 if ( !this.newItems ) {
19482 this.newItems = [];
19483 }
19484
19485 for ( i = 0, len = items.length; i < len; i++ ) {
19486 item = items[ i ];
19487 if ( this.isVisible() ) {
19488 // Defer fitting label until item has been attached
19489 item.fitLabel();
19490 } else {
19491 this.newItems.push( item );
19492 }
19493 }
19494
19495 // Reevaluate clipping
19496 this.clip();
19497
19498 return this;
19499 };
19500
19501 /**
19502 * @inheritdoc
19503 */
19504 OO.ui.MenuSelectWidget.prototype.removeItems = function ( items ) {
19505 // Parent method
19506 OO.ui.MenuSelectWidget.parent.prototype.removeItems.call( this, items );
19507
19508 // Reevaluate clipping
19509 this.clip();
19510
19511 return this;
19512 };
19513
19514 /**
19515 * @inheritdoc
19516 */
19517 OO.ui.MenuSelectWidget.prototype.clearItems = function () {
19518 // Parent method
19519 OO.ui.MenuSelectWidget.parent.prototype.clearItems.call( this );
19520
19521 // Reevaluate clipping
19522 this.clip();
19523
19524 return this;
19525 };
19526
19527 /**
19528 * @inheritdoc
19529 */
19530 OO.ui.MenuSelectWidget.prototype.toggle = function ( visible ) {
19531 var i, len, change;
19532
19533 visible = ( visible === undefined ? !this.visible : !!visible ) && !!this.items.length;
19534 change = visible !== this.isVisible();
19535
19536 // Parent method
19537 OO.ui.MenuSelectWidget.parent.prototype.toggle.call( this, visible );
19538
19539 if ( change ) {
19540 if ( visible ) {
19541 this.bindKeyDownListener();
19542 this.bindKeyPressListener();
19543
19544 if ( this.newItems && this.newItems.length ) {
19545 for ( i = 0, len = this.newItems.length; i < len; i++ ) {
19546 this.newItems[ i ].fitLabel();
19547 }
19548 this.newItems = null;
19549 }
19550 this.toggleClipping( true );
19551
19552 // Auto-hide
19553 if ( this.autoHide ) {
19554 OO.ui.addCaptureEventListener( this.getElementDocument(), 'mousedown', this.onDocumentMouseDownHandler );
19555 }
19556 } else {
19557 this.unbindKeyDownListener();
19558 this.unbindKeyPressListener();
19559 OO.ui.removeCaptureEventListener( this.getElementDocument(), 'mousedown', this.onDocumentMouseDownHandler );
19560 this.toggleClipping( false );
19561 }
19562 }
19563
19564 return this;
19565 };
19566
19567 /**
19568 * FloatingMenuSelectWidget is a menu that will stick under a specified
19569 * container, even when it is inserted elsewhere in the document (for example,
19570 * in a OO.ui.Window's $overlay). This is sometimes necessary to prevent the
19571 * menu from being clipped too aggresively.
19572 *
19573 * The menu's position is automatically calculated and maintained when the menu
19574 * is toggled or the window is resized.
19575 *
19576 * See OO.ui.ComboBoxInputWidget for an example of a widget that uses this class.
19577 *
19578 * @class
19579 * @extends OO.ui.MenuSelectWidget
19580 * @mixins OO.ui.mixin.FloatableElement
19581 *
19582 * @constructor
19583 * @param {OO.ui.Widget} [inputWidget] Widget to provide the menu for.
19584 * Deprecated, omit this parameter and specify `$container` instead.
19585 * @param {Object} [config] Configuration options
19586 * @cfg {jQuery} [$container=inputWidget.$element] Element to render menu under
19587 */
19588 OO.ui.FloatingMenuSelectWidget = function OoUiFloatingMenuSelectWidget( inputWidget, config ) {
19589 // Allow 'inputWidget' parameter and config for backwards compatibility
19590 if ( OO.isPlainObject( inputWidget ) && config === undefined ) {
19591 config = inputWidget;
19592 inputWidget = config.inputWidget;
19593 }
19594
19595 // Configuration initialization
19596 config = config || {};
19597
19598 // Parent constructor
19599 OO.ui.FloatingMenuSelectWidget.parent.call( this, config );
19600
19601 // Properties (must be set before mixin constructors)
19602 this.inputWidget = inputWidget; // For backwards compatibility
19603 this.$container = config.$container || this.inputWidget.$element;
19604
19605 // Mixins constructors
19606 OO.ui.mixin.FloatableElement.call( this, $.extend( {}, config, { $floatableContainer: this.$container } ) );
19607
19608 // Initialization
19609 this.$element.addClass( 'oo-ui-floatingMenuSelectWidget' );
19610 // For backwards compatibility
19611 this.$element.addClass( 'oo-ui-textInputMenuSelectWidget' );
19612 };
19613
19614 /* Setup */
19615
19616 OO.inheritClass( OO.ui.FloatingMenuSelectWidget, OO.ui.MenuSelectWidget );
19617 OO.mixinClass( OO.ui.FloatingMenuSelectWidget, OO.ui.mixin.FloatableElement );
19618
19619 // For backwards compatibility
19620 OO.ui.TextInputMenuSelectWidget = OO.ui.FloatingMenuSelectWidget;
19621
19622 /* Methods */
19623
19624 /**
19625 * @inheritdoc
19626 */
19627 OO.ui.FloatingMenuSelectWidget.prototype.toggle = function ( visible ) {
19628 var change;
19629 visible = visible === undefined ? !this.isVisible() : !!visible;
19630 change = visible !== this.isVisible();
19631
19632 if ( change && visible ) {
19633 // Make sure the width is set before the parent method runs.
19634 this.setIdealSize( this.$container.width() );
19635 }
19636
19637 // Parent method
19638 // This will call this.clip(), which is nonsensical since we're not positioned yet...
19639 OO.ui.FloatingMenuSelectWidget.parent.prototype.toggle.call( this, visible );
19640
19641 if ( change ) {
19642 this.togglePositioning( this.isVisible() );
19643 }
19644
19645 return this;
19646 };
19647
19648 /**
19649 * OutlineSelectWidget is a structured list that contains {@link OO.ui.OutlineOptionWidget outline options}
19650 * A set of controls can be provided with an {@link OO.ui.OutlineControlsWidget outline controls} widget.
19651 *
19652 * **Currently, this class is only used by {@link OO.ui.BookletLayout booklet layouts}.**
19653 *
19654 * @class
19655 * @extends OO.ui.SelectWidget
19656 * @mixins OO.ui.mixin.TabIndexedElement
19657 *
19658 * @constructor
19659 * @param {Object} [config] Configuration options
19660 */
19661 OO.ui.OutlineSelectWidget = function OoUiOutlineSelectWidget( config ) {
19662 // Parent constructor
19663 OO.ui.OutlineSelectWidget.parent.call( this, config );
19664
19665 // Mixin constructors
19666 OO.ui.mixin.TabIndexedElement.call( this, config );
19667
19668 // Events
19669 this.$element.on( {
19670 focus: this.bindKeyDownListener.bind( this ),
19671 blur: this.unbindKeyDownListener.bind( this )
19672 } );
19673
19674 // Initialization
19675 this.$element.addClass( 'oo-ui-outlineSelectWidget' );
19676 };
19677
19678 /* Setup */
19679
19680 OO.inheritClass( OO.ui.OutlineSelectWidget, OO.ui.SelectWidget );
19681 OO.mixinClass( OO.ui.OutlineSelectWidget, OO.ui.mixin.TabIndexedElement );
19682
19683 /**
19684 * TabSelectWidget is a list that contains {@link OO.ui.TabOptionWidget tab options}
19685 *
19686 * **Currently, this class is only used by {@link OO.ui.IndexLayout index layouts}.**
19687 *
19688 * @class
19689 * @extends OO.ui.SelectWidget
19690 * @mixins OO.ui.mixin.TabIndexedElement
19691 *
19692 * @constructor
19693 * @param {Object} [config] Configuration options
19694 */
19695 OO.ui.TabSelectWidget = function OoUiTabSelectWidget( config ) {
19696 // Parent constructor
19697 OO.ui.TabSelectWidget.parent.call( this, config );
19698
19699 // Mixin constructors
19700 OO.ui.mixin.TabIndexedElement.call( this, config );
19701
19702 // Events
19703 this.$element.on( {
19704 focus: this.bindKeyDownListener.bind( this ),
19705 blur: this.unbindKeyDownListener.bind( this )
19706 } );
19707
19708 // Initialization
19709 this.$element.addClass( 'oo-ui-tabSelectWidget' );
19710 };
19711
19712 /* Setup */
19713
19714 OO.inheritClass( OO.ui.TabSelectWidget, OO.ui.SelectWidget );
19715 OO.mixinClass( OO.ui.TabSelectWidget, OO.ui.mixin.TabIndexedElement );
19716
19717 /**
19718 * NumberInputWidgets combine a {@link OO.ui.TextInputWidget text input} (where a value
19719 * can be entered manually) and two {@link OO.ui.ButtonWidget button widgets}
19720 * (to adjust the value in increments) to allow the user to enter a number.
19721 *
19722 * @example
19723 * // Example: A NumberInputWidget.
19724 * var numberInput = new OO.ui.NumberInputWidget( {
19725 * label: 'NumberInputWidget',
19726 * input: { value: 5, min: 1, max: 10 }
19727 * } );
19728 * $( 'body' ).append( numberInput.$element );
19729 *
19730 * @class
19731 * @extends OO.ui.Widget
19732 *
19733 * @constructor
19734 * @param {Object} [config] Configuration options
19735 * @cfg {Object} [input] Configuration options to pass to the {@link OO.ui.TextInputWidget text input widget}.
19736 * @cfg {Object} [minusButton] Configuration options to pass to the {@link OO.ui.ButtonWidget decrementing button widget}.
19737 * @cfg {Object} [plusButton] Configuration options to pass to the {@link OO.ui.ButtonWidget incrementing button widget}.
19738 * @cfg {boolean} [isInteger=false] Whether the field accepts only integer values.
19739 * @cfg {number} [min=-Infinity] Minimum allowed value
19740 * @cfg {number} [max=Infinity] Maximum allowed value
19741 * @cfg {number} [step=1] Delta when using the buttons or up/down arrow keys
19742 * @cfg {number|null} [pageStep] Delta when using the page-up/page-down keys. Defaults to 10 times #step.
19743 */
19744 OO.ui.NumberInputWidget = function OoUiNumberInputWidget( config ) {
19745 // Configuration initialization
19746 config = $.extend( {
19747 isInteger: false,
19748 min: -Infinity,
19749 max: Infinity,
19750 step: 1,
19751 pageStep: null
19752 }, config );
19753
19754 // Parent constructor
19755 OO.ui.NumberInputWidget.parent.call( this, config );
19756
19757 // Properties
19758 this.input = new OO.ui.TextInputWidget( $.extend(
19759 {
19760 disabled: this.isDisabled()
19761 },
19762 config.input
19763 ) );
19764 this.minusButton = new OO.ui.ButtonWidget( $.extend(
19765 {
19766 disabled: this.isDisabled(),
19767 tabIndex: -1
19768 },
19769 config.minusButton,
19770 {
19771 classes: [ 'oo-ui-numberInputWidget-minusButton' ],
19772 label: '−'
19773 }
19774 ) );
19775 this.plusButton = new OO.ui.ButtonWidget( $.extend(
19776 {
19777 disabled: this.isDisabled(),
19778 tabIndex: -1
19779 },
19780 config.plusButton,
19781 {
19782 classes: [ 'oo-ui-numberInputWidget-plusButton' ],
19783 label: '+'
19784 }
19785 ) );
19786
19787 // Events
19788 this.input.connect( this, {
19789 change: this.emit.bind( this, 'change' ),
19790 enter: this.emit.bind( this, 'enter' )
19791 } );
19792 this.input.$input.on( {
19793 keydown: this.onKeyDown.bind( this ),
19794 'wheel mousewheel DOMMouseScroll': this.onWheel.bind( this )
19795 } );
19796 this.plusButton.connect( this, {
19797 click: [ 'onButtonClick', +1 ]
19798 } );
19799 this.minusButton.connect( this, {
19800 click: [ 'onButtonClick', -1 ]
19801 } );
19802
19803 // Initialization
19804 this.setIsInteger( !!config.isInteger );
19805 this.setRange( config.min, config.max );
19806 this.setStep( config.step, config.pageStep );
19807
19808 this.$field = $( '<div>' ).addClass( 'oo-ui-numberInputWidget-field' )
19809 .append(
19810 this.minusButton.$element,
19811 this.input.$element,
19812 this.plusButton.$element
19813 );
19814 this.$element.addClass( 'oo-ui-numberInputWidget' ).append( this.$field );
19815 this.input.setValidation( this.validateNumber.bind( this ) );
19816 };
19817
19818 /* Setup */
19819
19820 OO.inheritClass( OO.ui.NumberInputWidget, OO.ui.Widget );
19821
19822 /* Events */
19823
19824 /**
19825 * A `change` event is emitted when the value of the input changes.
19826 *
19827 * @event change
19828 */
19829
19830 /**
19831 * An `enter` event is emitted when the user presses 'enter' inside the text box.
19832 *
19833 * @event enter
19834 */
19835
19836 /* Methods */
19837
19838 /**
19839 * Set whether only integers are allowed
19840 * @param {boolean} flag
19841 */
19842 OO.ui.NumberInputWidget.prototype.setIsInteger = function ( flag ) {
19843 this.isInteger = !!flag;
19844 this.input.setValidityFlag();
19845 };
19846
19847 /**
19848 * Get whether only integers are allowed
19849 * @return {boolean} Flag value
19850 */
19851 OO.ui.NumberInputWidget.prototype.getIsInteger = function () {
19852 return this.isInteger;
19853 };
19854
19855 /**
19856 * Set the range of allowed values
19857 * @param {number} min Minimum allowed value
19858 * @param {number} max Maximum allowed value
19859 */
19860 OO.ui.NumberInputWidget.prototype.setRange = function ( min, max ) {
19861 if ( min > max ) {
19862 throw new Error( 'Minimum (' + min + ') must not be greater than maximum (' + max + ')' );
19863 }
19864 this.min = min;
19865 this.max = max;
19866 this.input.setValidityFlag();
19867 };
19868
19869 /**
19870 * Get the current range
19871 * @return {number[]} Minimum and maximum values
19872 */
19873 OO.ui.NumberInputWidget.prototype.getRange = function () {
19874 return [ this.min, this.max ];
19875 };
19876
19877 /**
19878 * Set the stepping deltas
19879 * @param {number} step Normal step
19880 * @param {number|null} pageStep Page step. If null, 10 * step will be used.
19881 */
19882 OO.ui.NumberInputWidget.prototype.setStep = function ( step, pageStep ) {
19883 if ( step <= 0 ) {
19884 throw new Error( 'Step value must be positive' );
19885 }
19886 if ( pageStep === null ) {
19887 pageStep = step * 10;
19888 } else if ( pageStep <= 0 ) {
19889 throw new Error( 'Page step value must be positive' );
19890 }
19891 this.step = step;
19892 this.pageStep = pageStep;
19893 };
19894
19895 /**
19896 * Get the current stepping values
19897 * @return {number[]} Step and page step
19898 */
19899 OO.ui.NumberInputWidget.prototype.getStep = function () {
19900 return [ this.step, this.pageStep ];
19901 };
19902
19903 /**
19904 * Get the current value of the widget
19905 * @return {string}
19906 */
19907 OO.ui.NumberInputWidget.prototype.getValue = function () {
19908 return this.input.getValue();
19909 };
19910
19911 /**
19912 * Get the current value of the widget as a number
19913 * @return {number} May be NaN, or an invalid number
19914 */
19915 OO.ui.NumberInputWidget.prototype.getNumericValue = function () {
19916 return +this.input.getValue();
19917 };
19918
19919 /**
19920 * Set the value of the widget
19921 * @param {string} value Invalid values are allowed
19922 */
19923 OO.ui.NumberInputWidget.prototype.setValue = function ( value ) {
19924 this.input.setValue( value );
19925 };
19926
19927 /**
19928 * Adjust the value of the widget
19929 * @param {number} delta Adjustment amount
19930 */
19931 OO.ui.NumberInputWidget.prototype.adjustValue = function ( delta ) {
19932 var n, v = this.getNumericValue();
19933
19934 delta = +delta;
19935 if ( isNaN( delta ) || !isFinite( delta ) ) {
19936 throw new Error( 'Delta must be a finite number' );
19937 }
19938
19939 if ( isNaN( v ) ) {
19940 n = 0;
19941 } else {
19942 n = v + delta;
19943 n = Math.max( Math.min( n, this.max ), this.min );
19944 if ( this.isInteger ) {
19945 n = Math.round( n );
19946 }
19947 }
19948
19949 if ( n !== v ) {
19950 this.setValue( n );
19951 }
19952 };
19953
19954 /**
19955 * Validate input
19956 * @private
19957 * @param {string} value Field value
19958 * @return {boolean}
19959 */
19960 OO.ui.NumberInputWidget.prototype.validateNumber = function ( value ) {
19961 var n = +value;
19962 if ( isNaN( n ) || !isFinite( n ) ) {
19963 return false;
19964 }
19965
19966 /*jshint bitwise: false */
19967 if ( this.isInteger && ( n | 0 ) !== n ) {
19968 return false;
19969 }
19970 /*jshint bitwise: true */
19971
19972 if ( n < this.min || n > this.max ) {
19973 return false;
19974 }
19975
19976 return true;
19977 };
19978
19979 /**
19980 * Handle mouse click events.
19981 *
19982 * @private
19983 * @param {number} dir +1 or -1
19984 */
19985 OO.ui.NumberInputWidget.prototype.onButtonClick = function ( dir ) {
19986 this.adjustValue( dir * this.step );
19987 };
19988
19989 /**
19990 * Handle mouse wheel events.
19991 *
19992 * @private
19993 * @param {jQuery.Event} event
19994 */
19995 OO.ui.NumberInputWidget.prototype.onWheel = function ( event ) {
19996 var delta = 0;
19997
19998 // Standard 'wheel' event
19999 if ( event.originalEvent.deltaMode !== undefined ) {
20000 this.sawWheelEvent = true;
20001 }
20002 if ( event.originalEvent.deltaY ) {
20003 delta = -event.originalEvent.deltaY;
20004 } else if ( event.originalEvent.deltaX ) {
20005 delta = event.originalEvent.deltaX;
20006 }
20007
20008 // Non-standard events
20009 if ( !this.sawWheelEvent ) {
20010 if ( event.originalEvent.wheelDeltaX ) {
20011 delta = -event.originalEvent.wheelDeltaX;
20012 } else if ( event.originalEvent.wheelDeltaY ) {
20013 delta = event.originalEvent.wheelDeltaY;
20014 } else if ( event.originalEvent.wheelDelta ) {
20015 delta = event.originalEvent.wheelDelta;
20016 } else if ( event.originalEvent.detail ) {
20017 delta = -event.originalEvent.detail;
20018 }
20019 }
20020
20021 if ( delta ) {
20022 delta = delta < 0 ? -1 : 1;
20023 this.adjustValue( delta * this.step );
20024 }
20025
20026 return false;
20027 };
20028
20029 /**
20030 * Handle key down events.
20031 *
20032 * @private
20033 * @param {jQuery.Event} e Key down event
20034 */
20035 OO.ui.NumberInputWidget.prototype.onKeyDown = function ( e ) {
20036 if ( !this.isDisabled() ) {
20037 switch ( e.which ) {
20038 case OO.ui.Keys.UP:
20039 this.adjustValue( this.step );
20040 return false;
20041 case OO.ui.Keys.DOWN:
20042 this.adjustValue( -this.step );
20043 return false;
20044 case OO.ui.Keys.PAGEUP:
20045 this.adjustValue( this.pageStep );
20046 return false;
20047 case OO.ui.Keys.PAGEDOWN:
20048 this.adjustValue( -this.pageStep );
20049 return false;
20050 }
20051 }
20052 };
20053
20054 /**
20055 * @inheritdoc
20056 */
20057 OO.ui.NumberInputWidget.prototype.setDisabled = function ( disabled ) {
20058 // Parent method
20059 OO.ui.NumberInputWidget.parent.prototype.setDisabled.call( this, disabled );
20060
20061 if ( this.input ) {
20062 this.input.setDisabled( this.isDisabled() );
20063 }
20064 if ( this.minusButton ) {
20065 this.minusButton.setDisabled( this.isDisabled() );
20066 }
20067 if ( this.plusButton ) {
20068 this.plusButton.setDisabled( this.isDisabled() );
20069 }
20070
20071 return this;
20072 };
20073
20074 /**
20075 * ToggleSwitches are switches that slide on and off. Their state is represented by a Boolean
20076 * value (`true` for ‘on’, and `false` otherwise, the default). The ‘off’ state is represented
20077 * visually by a slider in the leftmost position.
20078 *
20079 * @example
20080 * // Toggle switches in the 'off' and 'on' position.
20081 * var toggleSwitch1 = new OO.ui.ToggleSwitchWidget();
20082 * var toggleSwitch2 = new OO.ui.ToggleSwitchWidget( {
20083 * value: true
20084 * } );
20085 *
20086 * // Create a FieldsetLayout to layout and label switches
20087 * var fieldset = new OO.ui.FieldsetLayout( {
20088 * label: 'Toggle switches'
20089 * } );
20090 * fieldset.addItems( [
20091 * new OO.ui.FieldLayout( toggleSwitch1, { label: 'Off', align: 'top' } ),
20092 * new OO.ui.FieldLayout( toggleSwitch2, { label: 'On', align: 'top' } )
20093 * ] );
20094 * $( 'body' ).append( fieldset.$element );
20095 *
20096 * @class
20097 * @extends OO.ui.ToggleWidget
20098 * @mixins OO.ui.mixin.TabIndexedElement
20099 *
20100 * @constructor
20101 * @param {Object} [config] Configuration options
20102 * @cfg {boolean} [value=false] The toggle switch’s initial on/off state.
20103 * By default, the toggle switch is in the 'off' position.
20104 */
20105 OO.ui.ToggleSwitchWidget = function OoUiToggleSwitchWidget( config ) {
20106 // Parent constructor
20107 OO.ui.ToggleSwitchWidget.parent.call( this, config );
20108
20109 // Mixin constructors
20110 OO.ui.mixin.TabIndexedElement.call( this, config );
20111
20112 // Properties
20113 this.dragging = false;
20114 this.dragStart = null;
20115 this.sliding = false;
20116 this.$glow = $( '<span>' );
20117 this.$grip = $( '<span>' );
20118
20119 // Events
20120 this.$element.on( {
20121 click: this.onClick.bind( this ),
20122 keypress: this.onKeyPress.bind( this )
20123 } );
20124
20125 // Initialization
20126 this.$glow.addClass( 'oo-ui-toggleSwitchWidget-glow' );
20127 this.$grip.addClass( 'oo-ui-toggleSwitchWidget-grip' );
20128 this.$element
20129 .addClass( 'oo-ui-toggleSwitchWidget' )
20130 .attr( 'role', 'checkbox' )
20131 .append( this.$glow, this.$grip );
20132 };
20133
20134 /* Setup */
20135
20136 OO.inheritClass( OO.ui.ToggleSwitchWidget, OO.ui.ToggleWidget );
20137 OO.mixinClass( OO.ui.ToggleSwitchWidget, OO.ui.mixin.TabIndexedElement );
20138
20139 /* Methods */
20140
20141 /**
20142 * Handle mouse click events.
20143 *
20144 * @private
20145 * @param {jQuery.Event} e Mouse click event
20146 */
20147 OO.ui.ToggleSwitchWidget.prototype.onClick = function ( e ) {
20148 if ( !this.isDisabled() && e.which === 1 ) {
20149 this.setValue( !this.value );
20150 }
20151 return false;
20152 };
20153
20154 /**
20155 * Handle key press events.
20156 *
20157 * @private
20158 * @param {jQuery.Event} e Key press event
20159 */
20160 OO.ui.ToggleSwitchWidget.prototype.onKeyPress = function ( e ) {
20161 if ( !this.isDisabled() && ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER ) ) {
20162 this.setValue( !this.value );
20163 return false;
20164 }
20165 };
20166
20167 }( OO ) );