Update OOjs UI to v0.13.1
[lhc/web/wiklou.git] / resources / lib / oojs-ui / oojs-ui.js
1 /*!
2 * OOjs UI v0.13.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-11-03T21:42:20Z
10 */
11 ( function ( OO ) {
12
13 'use strict';
14
15 /**
16 * Namespace for all classes, static methods and static properties.
17 *
18 * @class
19 * @singleton
20 */
21 OO.ui = {};
22
23 OO.ui.bind = $.proxy;
24
25 /**
26 * @property {Object}
27 */
28 OO.ui.Keys = {
29 UNDEFINED: 0,
30 BACKSPACE: 8,
31 DELETE: 46,
32 LEFT: 37,
33 RIGHT: 39,
34 UP: 38,
35 DOWN: 40,
36 ENTER: 13,
37 END: 35,
38 HOME: 36,
39 TAB: 9,
40 PAGEUP: 33,
41 PAGEDOWN: 34,
42 ESCAPE: 27,
43 SHIFT: 16,
44 SPACE: 32
45 };
46
47 /**
48 * @property {Number}
49 */
50 OO.ui.elementId = 0;
51
52 /**
53 * Generate a unique ID for element
54 *
55 * @return {String} [id]
56 */
57 OO.ui.generateElementId = function () {
58 OO.ui.elementId += 1;
59 return 'oojsui-' + OO.ui.elementId;
60 };
61
62 /**
63 * Check if an element is focusable.
64 * Inspired from :focusable in jQueryUI v1.11.4 - 2015-04-14
65 *
66 * @param {jQuery} element Element to test
67 * @return {boolean}
68 */
69 OO.ui.isFocusableElement = function ( $element ) {
70 var nodeName,
71 element = $element[ 0 ];
72
73 // Anything disabled is not focusable
74 if ( element.disabled ) {
75 return false;
76 }
77
78 // Check if the element is visible
79 if ( !(
80 // This is quicker than calling $element.is( ':visible' )
81 $.expr.filters.visible( element ) &&
82 // Check that all parents are visible
83 !$element.parents().addBack().filter( function () {
84 return $.css( this, 'visibility' ) === 'hidden';
85 } ).length
86 ) ) {
87 return false;
88 }
89
90 // Check if the element is ContentEditable, which is the string 'true'
91 if ( element.contentEditable === 'true' ) {
92 return true;
93 }
94
95 // Anything with a non-negative numeric tabIndex is focusable.
96 // Use .prop to avoid browser bugs
97 if ( $element.prop( 'tabIndex' ) >= 0 ) {
98 return true;
99 }
100
101 // Some element types are naturally focusable
102 // (indexOf is much faster than regex in Chrome and about the
103 // same in FF: https://jsperf.com/regex-vs-indexof-array2)
104 nodeName = element.nodeName.toLowerCase();
105 if ( [ 'input', 'select', 'textarea', 'button', 'object' ].indexOf( nodeName ) !== -1 ) {
106 return true;
107 }
108
109 // Links and areas are focusable if they have an href
110 if ( ( nodeName === 'a' || nodeName === 'area' ) && $element.attr( 'href' ) !== undefined ) {
111 return true;
112 }
113
114 return false;
115 };
116
117 /**
118 * Find a focusable child
119 *
120 * @param {jQuery} $container Container to search in
121 * @param {boolean} [backwards] Search backwards
122 * @return {jQuery} Focusable child, an empty jQuery object if none found
123 */
124 OO.ui.findFocusable = function ( $container, backwards ) {
125 var $focusable = $( [] ),
126 // $focusableCandidates is a superset of things that
127 // could get matched by isFocusableElement
128 $focusableCandidates = $container
129 .find( 'input, select, textarea, button, object, a, area, [contenteditable], [tabindex]' );
130
131 if ( backwards ) {
132 $focusableCandidates = Array.prototype.reverse.call( $focusableCandidates );
133 }
134
135 $focusableCandidates.each( function () {
136 var $this = $( this );
137 if ( OO.ui.isFocusableElement( $this ) ) {
138 $focusable = $this;
139 return false;
140 }
141 } );
142 return $focusable;
143 };
144
145 /**
146 * Get the user's language and any fallback languages.
147 *
148 * These language codes are used to localize user interface elements in the user's language.
149 *
150 * In environments that provide a localization system, this function should be overridden to
151 * return the user's language(s). The default implementation returns English (en) only.
152 *
153 * @return {string[]} Language codes, in descending order of priority
154 */
155 OO.ui.getUserLanguages = function () {
156 return [ 'en' ];
157 };
158
159 /**
160 * Get a value in an object keyed by language code.
161 *
162 * @param {Object.<string,Mixed>} obj Object keyed by language code
163 * @param {string|null} [lang] Language code, if omitted or null defaults to any user language
164 * @param {string} [fallback] Fallback code, used if no matching language can be found
165 * @return {Mixed} Local value
166 */
167 OO.ui.getLocalValue = function ( obj, lang, fallback ) {
168 var i, len, langs;
169
170 // Requested language
171 if ( obj[ lang ] ) {
172 return obj[ lang ];
173 }
174 // Known user language
175 langs = OO.ui.getUserLanguages();
176 for ( i = 0, len = langs.length; i < len; i++ ) {
177 lang = langs[ i ];
178 if ( obj[ lang ] ) {
179 return obj[ lang ];
180 }
181 }
182 // Fallback language
183 if ( obj[ fallback ] ) {
184 return obj[ fallback ];
185 }
186 // First existing language
187 for ( lang in obj ) {
188 return obj[ lang ];
189 }
190
191 return undefined;
192 };
193
194 /**
195 * Check if a node is contained within another node
196 *
197 * Similar to jQuery#contains except a list of containers can be supplied
198 * and a boolean argument allows you to include the container in the match list
199 *
200 * @param {HTMLElement|HTMLElement[]} containers Container node(s) to search in
201 * @param {HTMLElement} contained Node to find
202 * @param {boolean} [matchContainers] Include the container(s) in the list of nodes to match, otherwise only match descendants
203 * @return {boolean} The node is in the list of target nodes
204 */
205 OO.ui.contains = function ( containers, contained, matchContainers ) {
206 var i;
207 if ( !Array.isArray( containers ) ) {
208 containers = [ containers ];
209 }
210 for ( i = containers.length - 1; i >= 0; i-- ) {
211 if ( ( matchContainers && contained === containers[ i ] ) || $.contains( containers[ i ], contained ) ) {
212 return true;
213 }
214 }
215 return false;
216 };
217
218 /**
219 * Return a function, that, as long as it continues to be invoked, will not
220 * be triggered. The function will be called after it stops being called for
221 * N milliseconds. If `immediate` is passed, trigger the function on the
222 * leading edge, instead of the trailing.
223 *
224 * Ported from: http://underscorejs.org/underscore.js
225 *
226 * @param {Function} func
227 * @param {number} wait
228 * @param {boolean} immediate
229 * @return {Function}
230 */
231 OO.ui.debounce = function ( func, wait, immediate ) {
232 var timeout;
233 return function () {
234 var context = this,
235 args = arguments,
236 later = function () {
237 timeout = null;
238 if ( !immediate ) {
239 func.apply( context, args );
240 }
241 };
242 if ( immediate && !timeout ) {
243 func.apply( context, args );
244 }
245 clearTimeout( timeout );
246 timeout = setTimeout( later, wait );
247 };
248 };
249
250 /**
251 * Proxy for `node.addEventListener( eventName, handler, true )`, if the browser supports it.
252 * Otherwise falls back to non-capturing event listeners.
253 *
254 * @param {HTMLElement} node
255 * @param {string} eventName
256 * @param {Function} handler
257 */
258 OO.ui.addCaptureEventListener = function ( node, eventName, handler ) {
259 if ( node.addEventListener ) {
260 node.addEventListener( eventName, handler, true );
261 } else {
262 node.attachEvent( 'on' + eventName, handler );
263 }
264 };
265
266 /**
267 * Proxy for `node.removeEventListener( eventName, handler, true )`, if the browser supports it.
268 * Otherwise falls back to non-capturing event listeners.
269 *
270 * @param {HTMLElement} node
271 * @param {string} eventName
272 * @param {Function} handler
273 */
274 OO.ui.removeCaptureEventListener = function ( node, eventName, handler ) {
275 if ( node.addEventListener ) {
276 node.removeEventListener( eventName, handler, true );
277 } else {
278 node.detachEvent( 'on' + eventName, handler );
279 }
280 };
281
282 /**
283 * Reconstitute a JavaScript object corresponding to a widget created by
284 * the PHP implementation.
285 *
286 * This is an alias for `OO.ui.Element.static.infuse()`.
287 *
288 * @param {string|HTMLElement|jQuery} idOrNode
289 * A DOM id (if a string) or node for the widget to infuse.
290 * @return {OO.ui.Element}
291 * The `OO.ui.Element` corresponding to this (infusable) document node.
292 */
293 OO.ui.infuse = function ( idOrNode ) {
294 return OO.ui.Element.static.infuse( idOrNode );
295 };
296
297 ( function () {
298 /**
299 * Message store for the default implementation of OO.ui.msg
300 *
301 * Environments that provide a localization system should not use this, but should override
302 * OO.ui.msg altogether.
303 *
304 * @private
305 */
306 var messages = {
307 // Tool tip for a button that moves items in a list down one place
308 'ooui-outline-control-move-down': 'Move item down',
309 // Tool tip for a button that moves items in a list up one place
310 'ooui-outline-control-move-up': 'Move item up',
311 // Tool tip for a button that removes items from a list
312 'ooui-outline-control-remove': 'Remove item',
313 // Label for the toolbar group that contains a list of all other available tools
314 'ooui-toolbar-more': 'More',
315 // Label for the fake tool that expands the full list of tools in a toolbar group
316 'ooui-toolgroup-expand': 'More',
317 // Label for the fake tool that collapses the full list of tools in a toolbar group
318 'ooui-toolgroup-collapse': 'Fewer',
319 // Default label for the accept button of a confirmation dialog
320 'ooui-dialog-message-accept': 'OK',
321 // Default label for the reject button of a confirmation dialog
322 'ooui-dialog-message-reject': 'Cancel',
323 // Title for process dialog error description
324 'ooui-dialog-process-error': 'Something went wrong',
325 // Label for process dialog dismiss error button, visible when describing errors
326 'ooui-dialog-process-dismiss': 'Dismiss',
327 // Label for process dialog retry action button, visible when describing only recoverable errors
328 'ooui-dialog-process-retry': 'Try again',
329 // Label for process dialog retry action button, visible when describing only warnings
330 'ooui-dialog-process-continue': 'Continue',
331 // Label for the file selection widget's select file button
332 'ooui-selectfile-button-select': 'Select a file',
333 // Label for the file selection widget if file selection is not supported
334 'ooui-selectfile-not-supported': 'File selection is not supported',
335 // Label for the file selection widget when no file is currently selected
336 'ooui-selectfile-placeholder': 'No file is selected',
337 // Label for the file selection widget's drop target
338 'ooui-selectfile-dragdrop-placeholder': 'Drop file here'
339 };
340
341 /**
342 * Get a localized message.
343 *
344 * In environments that provide a localization system, this function should be overridden to
345 * return the message translated in the user's language. The default implementation always returns
346 * English messages.
347 *
348 * After the message key, message parameters may optionally be passed. In the default implementation,
349 * any occurrences of $1 are replaced with the first parameter, $2 with the second parameter, etc.
350 * Alternative implementations of OO.ui.msg may use any substitution system they like, as long as
351 * they support unnamed, ordered message parameters.
352 *
353 * @abstract
354 * @param {string} key Message key
355 * @param {Mixed...} [params] Message parameters
356 * @return {string} Translated message with parameters substituted
357 */
358 OO.ui.msg = function ( key ) {
359 var message = messages[ key ],
360 params = Array.prototype.slice.call( arguments, 1 );
361 if ( typeof message === 'string' ) {
362 // Perform $1 substitution
363 message = message.replace( /\$(\d+)/g, function ( unused, n ) {
364 var i = parseInt( n, 10 );
365 return params[ i - 1 ] !== undefined ? params[ i - 1 ] : '$' + n;
366 } );
367 } else {
368 // Return placeholder if message not found
369 message = '[' + key + ']';
370 }
371 return message;
372 };
373
374 /**
375 * Package a message and arguments for deferred resolution.
376 *
377 * Use this when you are statically specifying a message and the message may not yet be present.
378 *
379 * @param {string} key Message key
380 * @param {Mixed...} [params] Message parameters
381 * @return {Function} Function that returns the resolved message when executed
382 */
383 OO.ui.deferMsg = function () {
384 var args = arguments;
385 return function () {
386 return OO.ui.msg.apply( OO.ui, args );
387 };
388 };
389
390 /**
391 * Resolve a message.
392 *
393 * If the message is a function it will be executed, otherwise it will pass through directly.
394 *
395 * @param {Function|string} msg Deferred message, or message text
396 * @return {string} Resolved message
397 */
398 OO.ui.resolveMsg = function ( msg ) {
399 if ( $.isFunction( msg ) ) {
400 return msg();
401 }
402 return msg;
403 };
404
405 /**
406 * @param {string} url
407 * @return {boolean}
408 */
409 OO.ui.isSafeUrl = function ( url ) {
410 var protocol,
411 // Keep in sync with php/Tag.php
412 whitelist = [
413 'bitcoin:', 'ftp:', 'ftps:', 'geo:', 'git:', 'gopher:', 'http:', 'https:', 'irc:', 'ircs:',
414 'magnet:', 'mailto:', 'mms:', 'news:', 'nntp:', 'redis:', 'sftp:', 'sip:', 'sips:', 'sms:', 'ssh:',
415 'svn:', 'tel:', 'telnet:', 'urn:', 'worldwind:', 'xmpp:'
416 ];
417
418 if ( url.indexOf( ':' ) === -1 ) {
419 // No protocol, safe
420 return true;
421 }
422
423 protocol = url.split( ':', 1 )[ 0 ] + ':';
424 if ( !protocol.match( /^([A-za-z0-9\+\.\-])+:/ ) ) {
425 // Not a valid protocol, safe
426 return true;
427 }
428
429 // Safe if in the whitelist
430 return whitelist.indexOf( protocol ) !== -1;
431 };
432
433 } )();
434
435 /*!
436 * Mixin namespace.
437 */
438
439 /**
440 * Namespace for OOjs UI mixins.
441 *
442 * Mixins are named according to the type of object they are intended to
443 * be mixed in to. For example, OO.ui.mixin.GroupElement is intended to be
444 * mixed in to an instance of OO.ui.Element, and OO.ui.mixin.GroupWidget
445 * is intended to be mixed in to an instance of OO.ui.Widget.
446 *
447 * @class
448 * @singleton
449 */
450 OO.ui.mixin = {};
451
452 /**
453 * PendingElement is a mixin that is used to create elements that notify users that something is happening
454 * and that they should wait before proceeding. The pending state is visually represented with a pending
455 * texture that appears in the head of a pending {@link OO.ui.ProcessDialog process dialog} or in the input
456 * field of a {@link OO.ui.TextInputWidget text input widget}.
457 *
458 * Currently, {@link OO.ui.ActionWidget Action widgets}, which mix in this class, can also be marked as pending, but only when
459 * used in {@link OO.ui.MessageDialog message dialogs}. The behavior is not currently supported for action widgets used
460 * in process dialogs.
461 *
462 * @example
463 * function MessageDialog( config ) {
464 * MessageDialog.parent.call( this, config );
465 * }
466 * OO.inheritClass( MessageDialog, OO.ui.MessageDialog );
467 *
468 * MessageDialog.static.actions = [
469 * { action: 'save', label: 'Done', flags: 'primary' },
470 * { label: 'Cancel', flags: 'safe' }
471 * ];
472 *
473 * MessageDialog.prototype.initialize = function () {
474 * MessageDialog.parent.prototype.initialize.apply( this, arguments );
475 * this.content = new OO.ui.PanelLayout( { $: this.$, padded: true } );
476 * this.content.$element.append( '<p>Click the \'Done\' action widget to see its pending state. Note that action widgets can be marked pending in message dialogs but not process dialogs.</p>' );
477 * this.$body.append( this.content.$element );
478 * };
479 * MessageDialog.prototype.getBodyHeight = function () {
480 * return 100;
481 * }
482 * MessageDialog.prototype.getActionProcess = function ( action ) {
483 * var dialog = this;
484 * if ( action === 'save' ) {
485 * dialog.getActions().get({actions: 'save'})[0].pushPending();
486 * return new OO.ui.Process()
487 * .next( 1000 )
488 * .next( function () {
489 * dialog.getActions().get({actions: 'save'})[0].popPending();
490 * } );
491 * }
492 * return MessageDialog.parent.prototype.getActionProcess.call( this, action );
493 * };
494 *
495 * var windowManager = new OO.ui.WindowManager();
496 * $( 'body' ).append( windowManager.$element );
497 *
498 * var dialog = new MessageDialog();
499 * windowManager.addWindows( [ dialog ] );
500 * windowManager.openWindow( dialog );
501 *
502 * @abstract
503 * @class
504 *
505 * @constructor
506 * @param {Object} [config] Configuration options
507 * @cfg {jQuery} [$pending] Element to mark as pending, defaults to this.$element
508 */
509 OO.ui.mixin.PendingElement = function OoUiMixinPendingElement( config ) {
510 // Configuration initialization
511 config = config || {};
512
513 // Properties
514 this.pending = 0;
515 this.$pending = null;
516
517 // Initialisation
518 this.setPendingElement( config.$pending || this.$element );
519 };
520
521 /* Setup */
522
523 OO.initClass( OO.ui.mixin.PendingElement );
524
525 /* Methods */
526
527 /**
528 * Set the pending element (and clean up any existing one).
529 *
530 * @param {jQuery} $pending The element to set to pending.
531 */
532 OO.ui.mixin.PendingElement.prototype.setPendingElement = function ( $pending ) {
533 if ( this.$pending ) {
534 this.$pending.removeClass( 'oo-ui-pendingElement-pending' );
535 }
536
537 this.$pending = $pending;
538 if ( this.pending > 0 ) {
539 this.$pending.addClass( 'oo-ui-pendingElement-pending' );
540 }
541 };
542
543 /**
544 * Check if an element is pending.
545 *
546 * @return {boolean} Element is pending
547 */
548 OO.ui.mixin.PendingElement.prototype.isPending = function () {
549 return !!this.pending;
550 };
551
552 /**
553 * Increase the pending counter. The pending state will remain active until the counter is zero
554 * (i.e., the number of calls to #pushPending and #popPending is the same).
555 *
556 * @chainable
557 */
558 OO.ui.mixin.PendingElement.prototype.pushPending = function () {
559 if ( this.pending === 0 ) {
560 this.$pending.addClass( 'oo-ui-pendingElement-pending' );
561 this.updateThemeClasses();
562 }
563 this.pending++;
564
565 return this;
566 };
567
568 /**
569 * Decrease the pending counter. The pending state will remain active until the counter is zero
570 * (i.e., the number of calls to #pushPending and #popPending is the same).
571 *
572 * @chainable
573 */
574 OO.ui.mixin.PendingElement.prototype.popPending = function () {
575 if ( this.pending === 1 ) {
576 this.$pending.removeClass( 'oo-ui-pendingElement-pending' );
577 this.updateThemeClasses();
578 }
579 this.pending = Math.max( 0, this.pending - 1 );
580
581 return this;
582 };
583
584 /**
585 * ActionSets manage the behavior of the {@link OO.ui.ActionWidget action widgets} that comprise them.
586 * Actions can be made available for specific contexts (modes) and circumstances
587 * (abilities). Action sets are primarily used with {@link OO.ui.Dialog Dialogs}.
588 *
589 * ActionSets contain two types of actions:
590 *
591 * - Special: Special actions are the first visible actions with special flags, such as 'safe' and 'primary', the default special flags. Additional special flags can be configured in subclasses with the static #specialFlags property.
592 * - Other: Other actions include all non-special visible actions.
593 *
594 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
595 *
596 * @example
597 * // Example: An action set used in a process dialog
598 * function MyProcessDialog( config ) {
599 * MyProcessDialog.parent.call( this, config );
600 * }
601 * OO.inheritClass( MyProcessDialog, OO.ui.ProcessDialog );
602 * MyProcessDialog.static.title = 'An action set in a process dialog';
603 * // An action set that uses modes ('edit' and 'help' mode, in this example).
604 * MyProcessDialog.static.actions = [
605 * { action: 'continue', modes: 'edit', label: 'Continue', flags: [ 'primary', 'constructive' ] },
606 * { action: 'help', modes: 'edit', label: 'Help' },
607 * { modes: 'edit', label: 'Cancel', flags: 'safe' },
608 * { action: 'back', modes: 'help', label: 'Back', flags: 'safe' }
609 * ];
610 *
611 * MyProcessDialog.prototype.initialize = function () {
612 * MyProcessDialog.parent.prototype.initialize.apply( this, arguments );
613 * this.panel1 = new OO.ui.PanelLayout( { padded: true, expanded: false } );
614 * this.panel1.$element.append( '<p>This dialog uses an action set (continue, help, cancel, back) configured with modes. This is edit mode. Click \'help\' to see help mode.</p>' );
615 * this.panel2 = new OO.ui.PanelLayout( { padded: true, expanded: false } );
616 * this.panel2.$element.append( '<p>This is help mode. Only the \'back\' action widget is configured to be visible here. Click \'back\' to return to \'edit\' mode.</p>' );
617 * this.stackLayout = new OO.ui.StackLayout( {
618 * items: [ this.panel1, this.panel2 ]
619 * } );
620 * this.$body.append( this.stackLayout.$element );
621 * };
622 * MyProcessDialog.prototype.getSetupProcess = function ( data ) {
623 * return MyProcessDialog.parent.prototype.getSetupProcess.call( this, data )
624 * .next( function () {
625 * this.actions.setMode( 'edit' );
626 * }, this );
627 * };
628 * MyProcessDialog.prototype.getActionProcess = function ( action ) {
629 * if ( action === 'help' ) {
630 * this.actions.setMode( 'help' );
631 * this.stackLayout.setItem( this.panel2 );
632 * } else if ( action === 'back' ) {
633 * this.actions.setMode( 'edit' );
634 * this.stackLayout.setItem( this.panel1 );
635 * } else if ( action === 'continue' ) {
636 * var dialog = this;
637 * return new OO.ui.Process( function () {
638 * dialog.close();
639 * } );
640 * }
641 * return MyProcessDialog.parent.prototype.getActionProcess.call( this, action );
642 * };
643 * MyProcessDialog.prototype.getBodyHeight = function () {
644 * return this.panel1.$element.outerHeight( true );
645 * };
646 * var windowManager = new OO.ui.WindowManager();
647 * $( 'body' ).append( windowManager.$element );
648 * var dialog = new MyProcessDialog( {
649 * size: 'medium'
650 * } );
651 * windowManager.addWindows( [ dialog ] );
652 * windowManager.openWindow( dialog );
653 *
654 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Action_sets
655 *
656 * @abstract
657 * @class
658 * @mixins OO.EventEmitter
659 *
660 * @constructor
661 * @param {Object} [config] Configuration options
662 */
663 OO.ui.ActionSet = function OoUiActionSet( config ) {
664 // Configuration initialization
665 config = config || {};
666
667 // Mixin constructors
668 OO.EventEmitter.call( this );
669
670 // Properties
671 this.list = [];
672 this.categories = {
673 actions: 'getAction',
674 flags: 'getFlags',
675 modes: 'getModes'
676 };
677 this.categorized = {};
678 this.special = {};
679 this.others = [];
680 this.organized = false;
681 this.changing = false;
682 this.changed = false;
683 };
684
685 /* Setup */
686
687 OO.mixinClass( OO.ui.ActionSet, OO.EventEmitter );
688
689 /* Static Properties */
690
691 /**
692 * Symbolic name of the flags used to identify special actions. Special actions are displayed in the
693 * header of a {@link OO.ui.ProcessDialog process dialog}.
694 * See the [OOjs UI documentation on MediaWiki][2] for more information and examples.
695 *
696 * [2]:https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs
697 *
698 * @abstract
699 * @static
700 * @inheritable
701 * @property {string}
702 */
703 OO.ui.ActionSet.static.specialFlags = [ 'safe', 'primary' ];
704
705 /* Events */
706
707 /**
708 * @event click
709 *
710 * A 'click' event is emitted when an action is clicked.
711 *
712 * @param {OO.ui.ActionWidget} action Action that was clicked
713 */
714
715 /**
716 * @event resize
717 *
718 * A 'resize' event is emitted when an action widget is resized.
719 *
720 * @param {OO.ui.ActionWidget} action Action that was resized
721 */
722
723 /**
724 * @event add
725 *
726 * An 'add' event is emitted when actions are {@link #method-add added} to the action set.
727 *
728 * @param {OO.ui.ActionWidget[]} added Actions added
729 */
730
731 /**
732 * @event remove
733 *
734 * A 'remove' event is emitted when actions are {@link #method-remove removed}
735 * or {@link #clear cleared}.
736 *
737 * @param {OO.ui.ActionWidget[]} added Actions removed
738 */
739
740 /**
741 * @event change
742 *
743 * A 'change' event is emitted when actions are {@link #method-add added}, {@link #clear cleared},
744 * or {@link #method-remove removed} from the action set or when the {@link #setMode mode} is changed.
745 *
746 */
747
748 /* Methods */
749
750 /**
751 * Handle action change events.
752 *
753 * @private
754 * @fires change
755 */
756 OO.ui.ActionSet.prototype.onActionChange = function () {
757 this.organized = false;
758 if ( this.changing ) {
759 this.changed = true;
760 } else {
761 this.emit( 'change' );
762 }
763 };
764
765 /**
766 * Check if an action is one of the special actions.
767 *
768 * @param {OO.ui.ActionWidget} action Action to check
769 * @return {boolean} Action is special
770 */
771 OO.ui.ActionSet.prototype.isSpecial = function ( action ) {
772 var flag;
773
774 for ( flag in this.special ) {
775 if ( action === this.special[ flag ] ) {
776 return true;
777 }
778 }
779
780 return false;
781 };
782
783 /**
784 * Get action widgets based on the specified filter: ‘actions’, ‘flags’, ‘modes’, ‘visible’,
785 * or ‘disabled’.
786 *
787 * @param {Object} [filters] Filters to use, omit to get all actions
788 * @param {string|string[]} [filters.actions] Actions that action widgets must have
789 * @param {string|string[]} [filters.flags] Flags that action widgets must have (e.g., 'safe')
790 * @param {string|string[]} [filters.modes] Modes that action widgets must have
791 * @param {boolean} [filters.visible] Action widgets must be visible
792 * @param {boolean} [filters.disabled] Action widgets must be disabled
793 * @return {OO.ui.ActionWidget[]} Action widgets matching all criteria
794 */
795 OO.ui.ActionSet.prototype.get = function ( filters ) {
796 var i, len, list, category, actions, index, match, matches;
797
798 if ( filters ) {
799 this.organize();
800
801 // Collect category candidates
802 matches = [];
803 for ( category in this.categorized ) {
804 list = filters[ category ];
805 if ( list ) {
806 if ( !Array.isArray( list ) ) {
807 list = [ list ];
808 }
809 for ( i = 0, len = list.length; i < len; i++ ) {
810 actions = this.categorized[ category ][ list[ i ] ];
811 if ( Array.isArray( actions ) ) {
812 matches.push.apply( matches, actions );
813 }
814 }
815 }
816 }
817 // Remove by boolean filters
818 for ( i = 0, len = matches.length; i < len; i++ ) {
819 match = matches[ i ];
820 if (
821 ( filters.visible !== undefined && match.isVisible() !== filters.visible ) ||
822 ( filters.disabled !== undefined && match.isDisabled() !== filters.disabled )
823 ) {
824 matches.splice( i, 1 );
825 len--;
826 i--;
827 }
828 }
829 // Remove duplicates
830 for ( i = 0, len = matches.length; i < len; i++ ) {
831 match = matches[ i ];
832 index = matches.lastIndexOf( match );
833 while ( index !== i ) {
834 matches.splice( index, 1 );
835 len--;
836 index = matches.lastIndexOf( match );
837 }
838 }
839 return matches;
840 }
841 return this.list.slice();
842 };
843
844 /**
845 * Get 'special' actions.
846 *
847 * Special actions are the first visible action widgets with special flags, such as 'safe' and 'primary'.
848 * Special flags can be configured in subclasses by changing the static #specialFlags property.
849 *
850 * @return {OO.ui.ActionWidget[]|null} 'Special' action widgets.
851 */
852 OO.ui.ActionSet.prototype.getSpecial = function () {
853 this.organize();
854 return $.extend( {}, this.special );
855 };
856
857 /**
858 * Get 'other' actions.
859 *
860 * Other actions include all non-special visible action widgets.
861 *
862 * @return {OO.ui.ActionWidget[]} 'Other' action widgets
863 */
864 OO.ui.ActionSet.prototype.getOthers = function () {
865 this.organize();
866 return this.others.slice();
867 };
868
869 /**
870 * Set the mode (e.g., ‘edit’ or ‘view’). Only {@link OO.ui.ActionWidget#modes actions} configured
871 * to be available in the specified mode will be made visible. All other actions will be hidden.
872 *
873 * @param {string} mode The mode. Only actions configured to be available in the specified
874 * mode will be made visible.
875 * @chainable
876 * @fires toggle
877 * @fires change
878 */
879 OO.ui.ActionSet.prototype.setMode = function ( mode ) {
880 var i, len, action;
881
882 this.changing = true;
883 for ( i = 0, len = this.list.length; i < len; i++ ) {
884 action = this.list[ i ];
885 action.toggle( action.hasMode( mode ) );
886 }
887
888 this.organized = false;
889 this.changing = false;
890 this.emit( 'change' );
891
892 return this;
893 };
894
895 /**
896 * Set the abilities of the specified actions.
897 *
898 * Action widgets that are configured with the specified actions will be enabled
899 * or disabled based on the boolean values specified in the `actions`
900 * parameter.
901 *
902 * @param {Object.<string,boolean>} actions A list keyed by action name with boolean
903 * values that indicate whether or not the action should be enabled.
904 * @chainable
905 */
906 OO.ui.ActionSet.prototype.setAbilities = function ( actions ) {
907 var i, len, action, item;
908
909 for ( i = 0, len = this.list.length; i < len; i++ ) {
910 item = this.list[ i ];
911 action = item.getAction();
912 if ( actions[ action ] !== undefined ) {
913 item.setDisabled( !actions[ action ] );
914 }
915 }
916
917 return this;
918 };
919
920 /**
921 * Executes a function once per action.
922 *
923 * When making changes to multiple actions, use this method instead of iterating over the actions
924 * manually to defer emitting a #change event until after all actions have been changed.
925 *
926 * @param {Object|null} actions Filters to use to determine which actions to iterate over; see #get
927 * @param {Function} callback Callback to run for each action; callback is invoked with three
928 * arguments: the action, the action's index, the list of actions being iterated over
929 * @chainable
930 */
931 OO.ui.ActionSet.prototype.forEach = function ( filter, callback ) {
932 this.changed = false;
933 this.changing = true;
934 this.get( filter ).forEach( callback );
935 this.changing = false;
936 if ( this.changed ) {
937 this.emit( 'change' );
938 }
939
940 return this;
941 };
942
943 /**
944 * Add action widgets to the action set.
945 *
946 * @param {OO.ui.ActionWidget[]} actions Action widgets to add
947 * @chainable
948 * @fires add
949 * @fires change
950 */
951 OO.ui.ActionSet.prototype.add = function ( actions ) {
952 var i, len, action;
953
954 this.changing = true;
955 for ( i = 0, len = actions.length; i < len; i++ ) {
956 action = actions[ i ];
957 action.connect( this, {
958 click: [ 'emit', 'click', action ],
959 resize: [ 'emit', 'resize', action ],
960 toggle: [ 'onActionChange' ]
961 } );
962 this.list.push( action );
963 }
964 this.organized = false;
965 this.emit( 'add', actions );
966 this.changing = false;
967 this.emit( 'change' );
968
969 return this;
970 };
971
972 /**
973 * Remove action widgets from the set.
974 *
975 * To remove all actions, you may wish to use the #clear method instead.
976 *
977 * @param {OO.ui.ActionWidget[]} actions Action widgets to remove
978 * @chainable
979 * @fires remove
980 * @fires change
981 */
982 OO.ui.ActionSet.prototype.remove = function ( actions ) {
983 var i, len, index, action;
984
985 this.changing = true;
986 for ( i = 0, len = actions.length; i < len; i++ ) {
987 action = actions[ i ];
988 index = this.list.indexOf( action );
989 if ( index !== -1 ) {
990 action.disconnect( this );
991 this.list.splice( index, 1 );
992 }
993 }
994 this.organized = false;
995 this.emit( 'remove', actions );
996 this.changing = false;
997 this.emit( 'change' );
998
999 return this;
1000 };
1001
1002 /**
1003 * Remove all action widets from the set.
1004 *
1005 * To remove only specified actions, use the {@link #method-remove remove} method instead.
1006 *
1007 * @chainable
1008 * @fires remove
1009 * @fires change
1010 */
1011 OO.ui.ActionSet.prototype.clear = function () {
1012 var i, len, action,
1013 removed = this.list.slice();
1014
1015 this.changing = true;
1016 for ( i = 0, len = this.list.length; i < len; i++ ) {
1017 action = this.list[ i ];
1018 action.disconnect( this );
1019 }
1020
1021 this.list = [];
1022
1023 this.organized = false;
1024 this.emit( 'remove', removed );
1025 this.changing = false;
1026 this.emit( 'change' );
1027
1028 return this;
1029 };
1030
1031 /**
1032 * Organize actions.
1033 *
1034 * This is called whenever organized information is requested. It will only reorganize the actions
1035 * if something has changed since the last time it ran.
1036 *
1037 * @private
1038 * @chainable
1039 */
1040 OO.ui.ActionSet.prototype.organize = function () {
1041 var i, iLen, j, jLen, flag, action, category, list, item, special,
1042 specialFlags = this.constructor.static.specialFlags;
1043
1044 if ( !this.organized ) {
1045 this.categorized = {};
1046 this.special = {};
1047 this.others = [];
1048 for ( i = 0, iLen = this.list.length; i < iLen; i++ ) {
1049 action = this.list[ i ];
1050 if ( action.isVisible() ) {
1051 // Populate categories
1052 for ( category in this.categories ) {
1053 if ( !this.categorized[ category ] ) {
1054 this.categorized[ category ] = {};
1055 }
1056 list = action[ this.categories[ category ] ]();
1057 if ( !Array.isArray( list ) ) {
1058 list = [ list ];
1059 }
1060 for ( j = 0, jLen = list.length; j < jLen; j++ ) {
1061 item = list[ j ];
1062 if ( !this.categorized[ category ][ item ] ) {
1063 this.categorized[ category ][ item ] = [];
1064 }
1065 this.categorized[ category ][ item ].push( action );
1066 }
1067 }
1068 // Populate special/others
1069 special = false;
1070 for ( j = 0, jLen = specialFlags.length; j < jLen; j++ ) {
1071 flag = specialFlags[ j ];
1072 if ( !this.special[ flag ] && action.hasFlag( flag ) ) {
1073 this.special[ flag ] = action;
1074 special = true;
1075 break;
1076 }
1077 }
1078 if ( !special ) {
1079 this.others.push( action );
1080 }
1081 }
1082 }
1083 this.organized = true;
1084 }
1085
1086 return this;
1087 };
1088
1089 /**
1090 * Each Element represents a rendering in the DOM—a button or an icon, for example, or anything
1091 * that is visible to a user. Unlike {@link OO.ui.Widget widgets}, plain elements usually do not have events
1092 * connected to them and can't be interacted with.
1093 *
1094 * @abstract
1095 * @class
1096 *
1097 * @constructor
1098 * @param {Object} [config] Configuration options
1099 * @cfg {string[]} [classes] The names of the CSS classes to apply to the element. CSS styles are added
1100 * to the top level (e.g., the outermost div) of the element. See the [OOjs UI documentation on MediaWiki][2]
1101 * for an example.
1102 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#cssExample
1103 * @cfg {string} [id] The HTML id attribute used in the rendered tag.
1104 * @cfg {string} [text] Text to insert
1105 * @cfg {Array} [content] An array of content elements to append (after #text).
1106 * Strings will be html-escaped; use an OO.ui.HtmlSnippet to append raw HTML.
1107 * Instances of OO.ui.Element will have their $element appended.
1108 * @cfg {jQuery} [$content] Content elements to append (after #text).
1109 * @cfg {jQuery} [$element] Wrapper element. Defaults to a new element with #getTagName.
1110 * @cfg {Mixed} [data] Custom data of any type or combination of types (e.g., string, number, array, object).
1111 * Data can also be specified with the #setData method.
1112 */
1113 OO.ui.Element = function OoUiElement( config ) {
1114 // Configuration initialization
1115 config = config || {};
1116
1117 // Properties
1118 this.$ = $;
1119 this.visible = true;
1120 this.data = config.data;
1121 this.$element = config.$element ||
1122 $( document.createElement( this.getTagName() ) );
1123 this.elementGroup = null;
1124 this.debouncedUpdateThemeClassesHandler = OO.ui.debounce( this.debouncedUpdateThemeClasses );
1125
1126 // Initialization
1127 if ( Array.isArray( config.classes ) ) {
1128 this.$element.addClass( config.classes.join( ' ' ) );
1129 }
1130 if ( config.id ) {
1131 this.$element.attr( 'id', config.id );
1132 }
1133 if ( config.text ) {
1134 this.$element.text( config.text );
1135 }
1136 if ( config.content ) {
1137 // The `content` property treats plain strings as text; use an
1138 // HtmlSnippet to append HTML content. `OO.ui.Element`s get their
1139 // appropriate $element appended.
1140 this.$element.append( config.content.map( function ( v ) {
1141 if ( typeof v === 'string' ) {
1142 // Escape string so it is properly represented in HTML.
1143 return document.createTextNode( v );
1144 } else if ( v instanceof OO.ui.HtmlSnippet ) {
1145 // Bypass escaping.
1146 return v.toString();
1147 } else if ( v instanceof OO.ui.Element ) {
1148 return v.$element;
1149 }
1150 return v;
1151 } ) );
1152 }
1153 if ( config.$content ) {
1154 // The `$content` property treats plain strings as HTML.
1155 this.$element.append( config.$content );
1156 }
1157 };
1158
1159 /* Setup */
1160
1161 OO.initClass( OO.ui.Element );
1162
1163 /* Static Properties */
1164
1165 /**
1166 * The name of the HTML tag used by the element.
1167 *
1168 * The static value may be ignored if the #getTagName method is overridden.
1169 *
1170 * @static
1171 * @inheritable
1172 * @property {string}
1173 */
1174 OO.ui.Element.static.tagName = 'div';
1175
1176 /* Static Methods */
1177
1178 /**
1179 * Reconstitute a JavaScript object corresponding to a widget created
1180 * by the PHP implementation.
1181 *
1182 * @param {string|HTMLElement|jQuery} idOrNode
1183 * A DOM id (if a string) or node for the widget to infuse.
1184 * @return {OO.ui.Element}
1185 * The `OO.ui.Element` corresponding to this (infusable) document node.
1186 * For `Tag` objects emitted on the HTML side (used occasionally for content)
1187 * the value returned is a newly-created Element wrapping around the existing
1188 * DOM node.
1189 */
1190 OO.ui.Element.static.infuse = function ( idOrNode ) {
1191 var obj = OO.ui.Element.static.unsafeInfuse( idOrNode, false );
1192 // Verify that the type matches up.
1193 // FIXME: uncomment after T89721 is fixed (see T90929)
1194 /*
1195 if ( !( obj instanceof this['class'] ) ) {
1196 throw new Error( 'Infusion type mismatch!' );
1197 }
1198 */
1199 return obj;
1200 };
1201
1202 /**
1203 * Implementation helper for `infuse`; skips the type check and has an
1204 * extra property so that only the top-level invocation touches the DOM.
1205 * @private
1206 * @param {string|HTMLElement|jQuery} idOrNode
1207 * @param {jQuery.Promise|boolean} domPromise A promise that will be resolved
1208 * when the top-level widget of this infusion is inserted into DOM,
1209 * replacing the original node; or false for top-level invocation.
1210 * @return {OO.ui.Element}
1211 */
1212 OO.ui.Element.static.unsafeInfuse = function ( idOrNode, domPromise ) {
1213 // look for a cached result of a previous infusion.
1214 var id, $elem, data, cls, parts, parent, obj, top, state;
1215 if ( typeof idOrNode === 'string' ) {
1216 id = idOrNode;
1217 $elem = $( document.getElementById( id ) );
1218 } else {
1219 $elem = $( idOrNode );
1220 id = $elem.attr( 'id' );
1221 }
1222 if ( !$elem.length ) {
1223 throw new Error( 'Widget not found: ' + id );
1224 }
1225 data = $elem.data( 'ooui-infused' ) || $elem[ 0 ].oouiInfused;
1226 if ( data ) {
1227 // cached!
1228 if ( data === true ) {
1229 throw new Error( 'Circular dependency! ' + id );
1230 }
1231 return data;
1232 }
1233 data = $elem.attr( 'data-ooui' );
1234 if ( !data ) {
1235 throw new Error( 'No infusion data found: ' + id );
1236 }
1237 try {
1238 data = $.parseJSON( data );
1239 } catch ( _ ) {
1240 data = null;
1241 }
1242 if ( !( data && data._ ) ) {
1243 throw new Error( 'No valid infusion data found: ' + id );
1244 }
1245 if ( data._ === 'Tag' ) {
1246 // Special case: this is a raw Tag; wrap existing node, don't rebuild.
1247 return new OO.ui.Element( { $element: $elem } );
1248 }
1249 parts = data._.split( '.' );
1250 cls = OO.getProp.apply( OO, [ window ].concat( parts ) );
1251 if ( cls === undefined ) {
1252 // The PHP output might be old and not including the "OO.ui" prefix
1253 // TODO: Remove this back-compat after next major release
1254 cls = OO.getProp.apply( OO, [ OO.ui ].concat( parts ) );
1255 if ( cls === undefined ) {
1256 throw new Error( 'Unknown widget type: id: ' + id + ', class: ' + data._ );
1257 }
1258 }
1259
1260 // Verify that we're creating an OO.ui.Element instance
1261 parent = cls.parent;
1262
1263 while ( parent !== undefined ) {
1264 if ( parent === OO.ui.Element ) {
1265 // Safe
1266 break;
1267 }
1268
1269 parent = parent.parent;
1270 }
1271
1272 if ( parent !== OO.ui.Element ) {
1273 throw new Error( 'Unknown widget type: id: ' + id + ', class: ' + data._ );
1274 }
1275
1276 if ( domPromise === false ) {
1277 top = $.Deferred();
1278 domPromise = top.promise();
1279 }
1280 $elem.data( 'ooui-infused', true ); // prevent loops
1281 data.id = id; // implicit
1282 data = OO.copy( data, null, function deserialize( value ) {
1283 if ( OO.isPlainObject( value ) ) {
1284 if ( value.tag ) {
1285 return OO.ui.Element.static.unsafeInfuse( value.tag, domPromise );
1286 }
1287 if ( value.html ) {
1288 return new OO.ui.HtmlSnippet( value.html );
1289 }
1290 }
1291 } );
1292 // allow widgets to reuse parts of the DOM
1293 data = cls.static.reusePreInfuseDOM( $elem[ 0 ], data );
1294 // pick up dynamic state, like focus, value of form inputs, scroll position, etc.
1295 state = cls.static.gatherPreInfuseState( $elem[ 0 ], data );
1296 // rebuild widget
1297 // jscs:disable requireCapitalizedConstructors
1298 obj = new cls( data );
1299 // jscs:enable requireCapitalizedConstructors
1300 // now replace old DOM with this new DOM.
1301 if ( top ) {
1302 // An efficient constructor might be able to reuse the entire DOM tree of the original element,
1303 // so only mutate the DOM if we need to.
1304 if ( $elem[ 0 ] !== obj.$element[ 0 ] ) {
1305 $elem.replaceWith( obj.$element );
1306 // This element is now gone from the DOM, but if anyone is holding a reference to it,
1307 // let's allow them to OO.ui.infuse() it and do what they expect (T105828).
1308 // Do not use jQuery.data(), as using it on detached nodes leaks memory in 1.x line by design.
1309 $elem[ 0 ].oouiInfused = obj;
1310 }
1311 top.resolve();
1312 }
1313 obj.$element.data( 'ooui-infused', obj );
1314 // set the 'data-ooui' attribute so we can identify infused widgets
1315 obj.$element.attr( 'data-ooui', '' );
1316 // restore dynamic state after the new element is inserted into DOM
1317 domPromise.done( obj.restorePreInfuseState.bind( obj, state ) );
1318 return obj;
1319 };
1320
1321 /**
1322 * Pick out parts of `node`'s DOM to be reused when infusing a widget.
1323 *
1324 * This method **must not** make any changes to the DOM, only find interesting pieces and add them
1325 * to `config` (which should then be returned). Actual DOM juggling should then be done by the
1326 * constructor, which will be given the enhanced config.
1327 *
1328 * @protected
1329 * @param {HTMLElement} node
1330 * @param {Object} config
1331 * @return {Object}
1332 */
1333 OO.ui.Element.static.reusePreInfuseDOM = function ( node, config ) {
1334 return config;
1335 };
1336
1337 /**
1338 * Gather the dynamic state (focus, value of form inputs, scroll position, etc.) of a HTML DOM node
1339 * (and its children) that represent an Element of the same class and the given configuration,
1340 * generated by the PHP implementation.
1341 *
1342 * This method is called just before `node` is detached from the DOM. The return value of this
1343 * function will be passed to #restorePreInfuseState after the newly created widget's #$element
1344 * is inserted into DOM to replace `node`.
1345 *
1346 * @protected
1347 * @param {HTMLElement} node
1348 * @param {Object} config
1349 * @return {Object}
1350 */
1351 OO.ui.Element.static.gatherPreInfuseState = function () {
1352 return {};
1353 };
1354
1355 /**
1356 * Get a jQuery function within a specific document.
1357 *
1358 * @static
1359 * @param {jQuery|HTMLElement|HTMLDocument|Window} context Context to bind the function to
1360 * @param {jQuery} [$iframe] HTML iframe element that contains the document, omit if document is
1361 * not in an iframe
1362 * @return {Function} Bound jQuery function
1363 */
1364 OO.ui.Element.static.getJQuery = function ( context, $iframe ) {
1365 function wrapper( selector ) {
1366 return $( selector, wrapper.context );
1367 }
1368
1369 wrapper.context = this.getDocument( context );
1370
1371 if ( $iframe ) {
1372 wrapper.$iframe = $iframe;
1373 }
1374
1375 return wrapper;
1376 };
1377
1378 /**
1379 * Get the document of an element.
1380 *
1381 * @static
1382 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Object to get the document for
1383 * @return {HTMLDocument|null} Document object
1384 */
1385 OO.ui.Element.static.getDocument = function ( obj ) {
1386 // jQuery - selections created "offscreen" won't have a context, so .context isn't reliable
1387 return ( obj[ 0 ] && obj[ 0 ].ownerDocument ) ||
1388 // Empty jQuery selections might have a context
1389 obj.context ||
1390 // HTMLElement
1391 obj.ownerDocument ||
1392 // Window
1393 obj.document ||
1394 // HTMLDocument
1395 ( obj.nodeType === 9 && obj ) ||
1396 null;
1397 };
1398
1399 /**
1400 * Get the window of an element or document.
1401 *
1402 * @static
1403 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the window for
1404 * @return {Window} Window object
1405 */
1406 OO.ui.Element.static.getWindow = function ( obj ) {
1407 var doc = this.getDocument( obj );
1408 // Support: IE 8
1409 // Standard Document.defaultView is IE9+
1410 return doc.parentWindow || doc.defaultView;
1411 };
1412
1413 /**
1414 * Get the direction of an element or document.
1415 *
1416 * @static
1417 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the direction for
1418 * @return {string} Text direction, either 'ltr' or 'rtl'
1419 */
1420 OO.ui.Element.static.getDir = function ( obj ) {
1421 var isDoc, isWin;
1422
1423 if ( obj instanceof jQuery ) {
1424 obj = obj[ 0 ];
1425 }
1426 isDoc = obj.nodeType === 9;
1427 isWin = obj.document !== undefined;
1428 if ( isDoc || isWin ) {
1429 if ( isWin ) {
1430 obj = obj.document;
1431 }
1432 obj = obj.body;
1433 }
1434 return $( obj ).css( 'direction' );
1435 };
1436
1437 /**
1438 * Get the offset between two frames.
1439 *
1440 * TODO: Make this function not use recursion.
1441 *
1442 * @static
1443 * @param {Window} from Window of the child frame
1444 * @param {Window} [to=window] Window of the parent frame
1445 * @param {Object} [offset] Offset to start with, used internally
1446 * @return {Object} Offset object, containing left and top properties
1447 */
1448 OO.ui.Element.static.getFrameOffset = function ( from, to, offset ) {
1449 var i, len, frames, frame, rect;
1450
1451 if ( !to ) {
1452 to = window;
1453 }
1454 if ( !offset ) {
1455 offset = { top: 0, left: 0 };
1456 }
1457 if ( from.parent === from ) {
1458 return offset;
1459 }
1460
1461 // Get iframe element
1462 frames = from.parent.document.getElementsByTagName( 'iframe' );
1463 for ( i = 0, len = frames.length; i < len; i++ ) {
1464 if ( frames[ i ].contentWindow === from ) {
1465 frame = frames[ i ];
1466 break;
1467 }
1468 }
1469
1470 // Recursively accumulate offset values
1471 if ( frame ) {
1472 rect = frame.getBoundingClientRect();
1473 offset.left += rect.left;
1474 offset.top += rect.top;
1475 if ( from !== to ) {
1476 this.getFrameOffset( from.parent, offset );
1477 }
1478 }
1479 return offset;
1480 };
1481
1482 /**
1483 * Get the offset between two elements.
1484 *
1485 * The two elements may be in a different frame, but in that case the frame $element is in must
1486 * be contained in the frame $anchor is in.
1487 *
1488 * @static
1489 * @param {jQuery} $element Element whose position to get
1490 * @param {jQuery} $anchor Element to get $element's position relative to
1491 * @return {Object} Translated position coordinates, containing top and left properties
1492 */
1493 OO.ui.Element.static.getRelativePosition = function ( $element, $anchor ) {
1494 var iframe, iframePos,
1495 pos = $element.offset(),
1496 anchorPos = $anchor.offset(),
1497 elementDocument = this.getDocument( $element ),
1498 anchorDocument = this.getDocument( $anchor );
1499
1500 // If $element isn't in the same document as $anchor, traverse up
1501 while ( elementDocument !== anchorDocument ) {
1502 iframe = elementDocument.defaultView.frameElement;
1503 if ( !iframe ) {
1504 throw new Error( '$element frame is not contained in $anchor frame' );
1505 }
1506 iframePos = $( iframe ).offset();
1507 pos.left += iframePos.left;
1508 pos.top += iframePos.top;
1509 elementDocument = iframe.ownerDocument;
1510 }
1511 pos.left -= anchorPos.left;
1512 pos.top -= anchorPos.top;
1513 return pos;
1514 };
1515
1516 /**
1517 * Get element border sizes.
1518 *
1519 * @static
1520 * @param {HTMLElement} el Element to measure
1521 * @return {Object} Dimensions object with `top`, `left`, `bottom` and `right` properties
1522 */
1523 OO.ui.Element.static.getBorders = function ( el ) {
1524 var doc = el.ownerDocument,
1525 // Support: IE 8
1526 // Standard Document.defaultView is IE9+
1527 win = doc.parentWindow || doc.defaultView,
1528 style = win && win.getComputedStyle ?
1529 win.getComputedStyle( el, null ) :
1530 // Support: IE 8
1531 // Standard getComputedStyle() is IE9+
1532 el.currentStyle,
1533 $el = $( el ),
1534 top = parseFloat( style ? style.borderTopWidth : $el.css( 'borderTopWidth' ) ) || 0,
1535 left = parseFloat( style ? style.borderLeftWidth : $el.css( 'borderLeftWidth' ) ) || 0,
1536 bottom = parseFloat( style ? style.borderBottomWidth : $el.css( 'borderBottomWidth' ) ) || 0,
1537 right = parseFloat( style ? style.borderRightWidth : $el.css( 'borderRightWidth' ) ) || 0;
1538
1539 return {
1540 top: top,
1541 left: left,
1542 bottom: bottom,
1543 right: right
1544 };
1545 };
1546
1547 /**
1548 * Get dimensions of an element or window.
1549 *
1550 * @static
1551 * @param {HTMLElement|Window} el Element to measure
1552 * @return {Object} Dimensions object with `borders`, `scroll`, `scrollbar` and `rect` properties
1553 */
1554 OO.ui.Element.static.getDimensions = function ( el ) {
1555 var $el, $win,
1556 doc = el.ownerDocument || el.document,
1557 // Support: IE 8
1558 // Standard Document.defaultView is IE9+
1559 win = doc.parentWindow || doc.defaultView;
1560
1561 if ( win === el || el === doc.documentElement ) {
1562 $win = $( win );
1563 return {
1564 borders: { top: 0, left: 0, bottom: 0, right: 0 },
1565 scroll: {
1566 top: $win.scrollTop(),
1567 left: $win.scrollLeft()
1568 },
1569 scrollbar: { right: 0, bottom: 0 },
1570 rect: {
1571 top: 0,
1572 left: 0,
1573 bottom: $win.innerHeight(),
1574 right: $win.innerWidth()
1575 }
1576 };
1577 } else {
1578 $el = $( el );
1579 return {
1580 borders: this.getBorders( el ),
1581 scroll: {
1582 top: $el.scrollTop(),
1583 left: $el.scrollLeft()
1584 },
1585 scrollbar: {
1586 right: $el.innerWidth() - el.clientWidth,
1587 bottom: $el.innerHeight() - el.clientHeight
1588 },
1589 rect: el.getBoundingClientRect()
1590 };
1591 }
1592 };
1593
1594 /**
1595 * Get scrollable object parent
1596 *
1597 * documentElement can't be used to get or set the scrollTop
1598 * property on Blink. Changing and testing its value lets us
1599 * use 'body' or 'documentElement' based on what is working.
1600 *
1601 * https://code.google.com/p/chromium/issues/detail?id=303131
1602 *
1603 * @static
1604 * @param {HTMLElement} el Element to find scrollable parent for
1605 * @return {HTMLElement} Scrollable parent
1606 */
1607 OO.ui.Element.static.getRootScrollableElement = function ( el ) {
1608 var scrollTop, body;
1609
1610 if ( OO.ui.scrollableElement === undefined ) {
1611 body = el.ownerDocument.body;
1612 scrollTop = body.scrollTop;
1613 body.scrollTop = 1;
1614
1615 if ( body.scrollTop === 1 ) {
1616 body.scrollTop = scrollTop;
1617 OO.ui.scrollableElement = 'body';
1618 } else {
1619 OO.ui.scrollableElement = 'documentElement';
1620 }
1621 }
1622
1623 return el.ownerDocument[ OO.ui.scrollableElement ];
1624 };
1625
1626 /**
1627 * Get closest scrollable container.
1628 *
1629 * Traverses up until either a scrollable element or the root is reached, in which case the window
1630 * will be returned.
1631 *
1632 * @static
1633 * @param {HTMLElement} el Element to find scrollable container for
1634 * @param {string} [dimension] Dimension of scrolling to look for; `x`, `y` or omit for either
1635 * @return {HTMLElement} Closest scrollable container
1636 */
1637 OO.ui.Element.static.getClosestScrollableContainer = function ( el, dimension ) {
1638 var i, val,
1639 // props = [ 'overflow' ] doesn't work due to https://bugzilla.mozilla.org/show_bug.cgi?id=889091
1640 props = [ 'overflow-x', 'overflow-y' ],
1641 $parent = $( el ).parent();
1642
1643 if ( dimension === 'x' || dimension === 'y' ) {
1644 props = [ 'overflow-' + dimension ];
1645 }
1646
1647 while ( $parent.length ) {
1648 if ( $parent[ 0 ] === this.getRootScrollableElement( el ) ) {
1649 return $parent[ 0 ];
1650 }
1651 i = props.length;
1652 while ( i-- ) {
1653 val = $parent.css( props[ i ] );
1654 if ( val === 'auto' || val === 'scroll' ) {
1655 return $parent[ 0 ];
1656 }
1657 }
1658 $parent = $parent.parent();
1659 }
1660 return this.getDocument( el ).body;
1661 };
1662
1663 /**
1664 * Scroll element into view.
1665 *
1666 * @static
1667 * @param {HTMLElement} el Element to scroll into view
1668 * @param {Object} [config] Configuration options
1669 * @param {string} [config.duration] jQuery animation duration value
1670 * @param {string} [config.direction] Scroll in only one direction, e.g. 'x' or 'y', omit
1671 * to scroll in both directions
1672 * @param {Function} [config.complete] Function to call when scrolling completes
1673 */
1674 OO.ui.Element.static.scrollIntoView = function ( el, config ) {
1675 var rel, anim, callback, sc, $sc, eld, scd, $win;
1676
1677 // Configuration initialization
1678 config = config || {};
1679
1680 anim = {};
1681 callback = typeof config.complete === 'function' && config.complete;
1682 sc = this.getClosestScrollableContainer( el, config.direction );
1683 $sc = $( sc );
1684 eld = this.getDimensions( el );
1685 scd = this.getDimensions( sc );
1686 $win = $( this.getWindow( el ) );
1687
1688 // Compute the distances between the edges of el and the edges of the scroll viewport
1689 if ( $sc.is( 'html, body' ) ) {
1690 // If the scrollable container is the root, this is easy
1691 rel = {
1692 top: eld.rect.top,
1693 bottom: $win.innerHeight() - eld.rect.bottom,
1694 left: eld.rect.left,
1695 right: $win.innerWidth() - eld.rect.right
1696 };
1697 } else {
1698 // Otherwise, we have to subtract el's coordinates from sc's coordinates
1699 rel = {
1700 top: eld.rect.top - ( scd.rect.top + scd.borders.top ),
1701 bottom: scd.rect.bottom - scd.borders.bottom - scd.scrollbar.bottom - eld.rect.bottom,
1702 left: eld.rect.left - ( scd.rect.left + scd.borders.left ),
1703 right: scd.rect.right - scd.borders.right - scd.scrollbar.right - eld.rect.right
1704 };
1705 }
1706
1707 if ( !config.direction || config.direction === 'y' ) {
1708 if ( rel.top < 0 ) {
1709 anim.scrollTop = scd.scroll.top + rel.top;
1710 } else if ( rel.top > 0 && rel.bottom < 0 ) {
1711 anim.scrollTop = scd.scroll.top + Math.min( rel.top, -rel.bottom );
1712 }
1713 }
1714 if ( !config.direction || config.direction === 'x' ) {
1715 if ( rel.left < 0 ) {
1716 anim.scrollLeft = scd.scroll.left + rel.left;
1717 } else if ( rel.left > 0 && rel.right < 0 ) {
1718 anim.scrollLeft = scd.scroll.left + Math.min( rel.left, -rel.right );
1719 }
1720 }
1721 if ( !$.isEmptyObject( anim ) ) {
1722 $sc.stop( true ).animate( anim, config.duration || 'fast' );
1723 if ( callback ) {
1724 $sc.queue( function ( next ) {
1725 callback();
1726 next();
1727 } );
1728 }
1729 } else {
1730 if ( callback ) {
1731 callback();
1732 }
1733 }
1734 };
1735
1736 /**
1737 * Force the browser to reconsider whether it really needs to render scrollbars inside the element
1738 * and reserve space for them, because it probably doesn't.
1739 *
1740 * Workaround primarily for <https://code.google.com/p/chromium/issues/detail?id=387290>, but also
1741 * similar bugs in other browsers. "Just" forcing a reflow is not sufficient in all cases, we need
1742 * to first actually detach (or hide, but detaching is simpler) all children, *then* force a reflow,
1743 * and then reattach (or show) them back.
1744 *
1745 * @static
1746 * @param {HTMLElement} el Element to reconsider the scrollbars on
1747 */
1748 OO.ui.Element.static.reconsiderScrollbars = function ( el ) {
1749 var i, len, scrollLeft, scrollTop, nodes = [];
1750 // Save scroll position
1751 scrollLeft = el.scrollLeft;
1752 scrollTop = el.scrollTop;
1753 // Detach all children
1754 while ( el.firstChild ) {
1755 nodes.push( el.firstChild );
1756 el.removeChild( el.firstChild );
1757 }
1758 // Force reflow
1759 void el.offsetHeight;
1760 // Reattach all children
1761 for ( i = 0, len = nodes.length; i < len; i++ ) {
1762 el.appendChild( nodes[ i ] );
1763 }
1764 // Restore scroll position (no-op if scrollbars disappeared)
1765 el.scrollLeft = scrollLeft;
1766 el.scrollTop = scrollTop;
1767 };
1768
1769 /* Methods */
1770
1771 /**
1772 * Toggle visibility of an element.
1773 *
1774 * @param {boolean} [show] Make element visible, omit to toggle visibility
1775 * @fires visible
1776 * @chainable
1777 */
1778 OO.ui.Element.prototype.toggle = function ( show ) {
1779 show = show === undefined ? !this.visible : !!show;
1780
1781 if ( show !== this.isVisible() ) {
1782 this.visible = show;
1783 this.$element.toggleClass( 'oo-ui-element-hidden', !this.visible );
1784 this.emit( 'toggle', show );
1785 }
1786
1787 return this;
1788 };
1789
1790 /**
1791 * Check if element is visible.
1792 *
1793 * @return {boolean} element is visible
1794 */
1795 OO.ui.Element.prototype.isVisible = function () {
1796 return this.visible;
1797 };
1798
1799 /**
1800 * Get element data.
1801 *
1802 * @return {Mixed} Element data
1803 */
1804 OO.ui.Element.prototype.getData = function () {
1805 return this.data;
1806 };
1807
1808 /**
1809 * Set element data.
1810 *
1811 * @param {Mixed} Element data
1812 * @chainable
1813 */
1814 OO.ui.Element.prototype.setData = function ( data ) {
1815 this.data = data;
1816 return this;
1817 };
1818
1819 /**
1820 * Check if element supports one or more methods.
1821 *
1822 * @param {string|string[]} methods Method or list of methods to check
1823 * @return {boolean} All methods are supported
1824 */
1825 OO.ui.Element.prototype.supports = function ( methods ) {
1826 var i, len,
1827 support = 0;
1828
1829 methods = Array.isArray( methods ) ? methods : [ methods ];
1830 for ( i = 0, len = methods.length; i < len; i++ ) {
1831 if ( $.isFunction( this[ methods[ i ] ] ) ) {
1832 support++;
1833 }
1834 }
1835
1836 return methods.length === support;
1837 };
1838
1839 /**
1840 * Update the theme-provided classes.
1841 *
1842 * @localdoc This is called in element mixins and widget classes any time state changes.
1843 * Updating is debounced, minimizing overhead of changing multiple attributes and
1844 * guaranteeing that theme updates do not occur within an element's constructor
1845 */
1846 OO.ui.Element.prototype.updateThemeClasses = function () {
1847 this.debouncedUpdateThemeClassesHandler();
1848 };
1849
1850 /**
1851 * @private
1852 * @localdoc This method is called directly from the QUnit tests instead of #updateThemeClasses, to
1853 * make them synchronous.
1854 */
1855 OO.ui.Element.prototype.debouncedUpdateThemeClasses = function () {
1856 OO.ui.theme.updateElementClasses( this );
1857 };
1858
1859 /**
1860 * Get the HTML tag name.
1861 *
1862 * Override this method to base the result on instance information.
1863 *
1864 * @return {string} HTML tag name
1865 */
1866 OO.ui.Element.prototype.getTagName = function () {
1867 return this.constructor.static.tagName;
1868 };
1869
1870 /**
1871 * Check if the element is attached to the DOM
1872 * @return {boolean} The element is attached to the DOM
1873 */
1874 OO.ui.Element.prototype.isElementAttached = function () {
1875 return $.contains( this.getElementDocument(), this.$element[ 0 ] );
1876 };
1877
1878 /**
1879 * Get the DOM document.
1880 *
1881 * @return {HTMLDocument} Document object
1882 */
1883 OO.ui.Element.prototype.getElementDocument = function () {
1884 // Don't cache this in other ways either because subclasses could can change this.$element
1885 return OO.ui.Element.static.getDocument( this.$element );
1886 };
1887
1888 /**
1889 * Get the DOM window.
1890 *
1891 * @return {Window} Window object
1892 */
1893 OO.ui.Element.prototype.getElementWindow = function () {
1894 return OO.ui.Element.static.getWindow( this.$element );
1895 };
1896
1897 /**
1898 * Get closest scrollable container.
1899 */
1900 OO.ui.Element.prototype.getClosestScrollableElementContainer = function () {
1901 return OO.ui.Element.static.getClosestScrollableContainer( this.$element[ 0 ] );
1902 };
1903
1904 /**
1905 * Get group element is in.
1906 *
1907 * @return {OO.ui.mixin.GroupElement|null} Group element, null if none
1908 */
1909 OO.ui.Element.prototype.getElementGroup = function () {
1910 return this.elementGroup;
1911 };
1912
1913 /**
1914 * Set group element is in.
1915 *
1916 * @param {OO.ui.mixin.GroupElement|null} group Group element, null if none
1917 * @chainable
1918 */
1919 OO.ui.Element.prototype.setElementGroup = function ( group ) {
1920 this.elementGroup = group;
1921 return this;
1922 };
1923
1924 /**
1925 * Scroll element into view.
1926 *
1927 * @param {Object} [config] Configuration options
1928 */
1929 OO.ui.Element.prototype.scrollElementIntoView = function ( config ) {
1930 return OO.ui.Element.static.scrollIntoView( this.$element[ 0 ], config );
1931 };
1932
1933 /**
1934 * Restore the pre-infusion dynamic state for this widget.
1935 *
1936 * This method is called after #$element has been inserted into DOM. The parameter is the return
1937 * value of #gatherPreInfuseState.
1938 *
1939 * @protected
1940 * @param {Object} state
1941 */
1942 OO.ui.Element.prototype.restorePreInfuseState = function () {
1943 };
1944
1945 /**
1946 * Layouts are containers for elements and are used to arrange other widgets of arbitrary type in a way
1947 * that is centrally controlled and can be updated dynamically. Layouts can be, and usually are, combined.
1948 * See {@link OO.ui.FieldsetLayout FieldsetLayout}, {@link OO.ui.FieldLayout FieldLayout}, {@link OO.ui.FormLayout FormLayout},
1949 * {@link OO.ui.PanelLayout PanelLayout}, {@link OO.ui.StackLayout StackLayout}, {@link OO.ui.PageLayout PageLayout},
1950 * {@link OO.ui.HorizontalLayout HorizontalLayout}, and {@link OO.ui.BookletLayout BookletLayout} for more information and examples.
1951 *
1952 * @abstract
1953 * @class
1954 * @extends OO.ui.Element
1955 * @mixins OO.EventEmitter
1956 *
1957 * @constructor
1958 * @param {Object} [config] Configuration options
1959 */
1960 OO.ui.Layout = function OoUiLayout( config ) {
1961 // Configuration initialization
1962 config = config || {};
1963
1964 // Parent constructor
1965 OO.ui.Layout.parent.call( this, config );
1966
1967 // Mixin constructors
1968 OO.EventEmitter.call( this );
1969
1970 // Initialization
1971 this.$element.addClass( 'oo-ui-layout' );
1972 };
1973
1974 /* Setup */
1975
1976 OO.inheritClass( OO.ui.Layout, OO.ui.Element );
1977 OO.mixinClass( OO.ui.Layout, OO.EventEmitter );
1978
1979 /**
1980 * Widgets are compositions of one or more OOjs UI elements that users can both view
1981 * and interact with. All widgets can be configured and modified via a standard API,
1982 * and their state can change dynamically according to a model.
1983 *
1984 * @abstract
1985 * @class
1986 * @extends OO.ui.Element
1987 * @mixins OO.EventEmitter
1988 *
1989 * @constructor
1990 * @param {Object} [config] Configuration options
1991 * @cfg {boolean} [disabled=false] Disable the widget. Disabled widgets cannot be used and their
1992 * appearance reflects this state.
1993 */
1994 OO.ui.Widget = function OoUiWidget( config ) {
1995 // Initialize config
1996 config = $.extend( { disabled: false }, config );
1997
1998 // Parent constructor
1999 OO.ui.Widget.parent.call( this, config );
2000
2001 // Mixin constructors
2002 OO.EventEmitter.call( this );
2003
2004 // Properties
2005 this.disabled = null;
2006 this.wasDisabled = null;
2007
2008 // Initialization
2009 this.$element.addClass( 'oo-ui-widget' );
2010 this.setDisabled( !!config.disabled );
2011 };
2012
2013 /* Setup */
2014
2015 OO.inheritClass( OO.ui.Widget, OO.ui.Element );
2016 OO.mixinClass( OO.ui.Widget, OO.EventEmitter );
2017
2018 /* Static Properties */
2019
2020 /**
2021 * Whether this widget will behave reasonably when wrapped in a HTML `<label>`. If this is true,
2022 * wrappers such as OO.ui.FieldLayout may use a `<label>` instead of implementing own label click
2023 * handling.
2024 *
2025 * @static
2026 * @inheritable
2027 * @property {boolean}
2028 */
2029 OO.ui.Widget.static.supportsSimpleLabel = false;
2030
2031 /* Events */
2032
2033 /**
2034 * @event disable
2035 *
2036 * A 'disable' event is emitted when the disabled state of the widget changes
2037 * (i.e. on disable **and** enable).
2038 *
2039 * @param {boolean} disabled Widget is disabled
2040 */
2041
2042 /**
2043 * @event toggle
2044 *
2045 * A 'toggle' event is emitted when the visibility of the widget changes.
2046 *
2047 * @param {boolean} visible Widget is visible
2048 */
2049
2050 /* Methods */
2051
2052 /**
2053 * Check if the widget is disabled.
2054 *
2055 * @return {boolean} Widget is disabled
2056 */
2057 OO.ui.Widget.prototype.isDisabled = function () {
2058 return this.disabled;
2059 };
2060
2061 /**
2062 * Set the 'disabled' state of the widget.
2063 *
2064 * When a widget is disabled, it cannot be used and its appearance is updated to reflect this state.
2065 *
2066 * @param {boolean} disabled Disable widget
2067 * @chainable
2068 */
2069 OO.ui.Widget.prototype.setDisabled = function ( disabled ) {
2070 var isDisabled;
2071
2072 this.disabled = !!disabled;
2073 isDisabled = this.isDisabled();
2074 if ( isDisabled !== this.wasDisabled ) {
2075 this.$element.toggleClass( 'oo-ui-widget-disabled', isDisabled );
2076 this.$element.toggleClass( 'oo-ui-widget-enabled', !isDisabled );
2077 this.$element.attr( 'aria-disabled', isDisabled.toString() );
2078 this.emit( 'disable', isDisabled );
2079 this.updateThemeClasses();
2080 }
2081 this.wasDisabled = isDisabled;
2082
2083 return this;
2084 };
2085
2086 /**
2087 * Update the disabled state, in case of changes in parent widget.
2088 *
2089 * @chainable
2090 */
2091 OO.ui.Widget.prototype.updateDisabled = function () {
2092 this.setDisabled( this.disabled );
2093 return this;
2094 };
2095
2096 /**
2097 * A window is a container for elements that are in a child frame. They are used with
2098 * a window manager (OO.ui.WindowManager), which is used to open and close the window and control
2099 * its presentation. The size of a window is specified using a symbolic name (e.g., ‘small’, ‘medium’,
2100 * ‘large’), which is interpreted by the window manager. If the requested size is not recognized,
2101 * the window manager will choose a sensible fallback.
2102 *
2103 * The lifecycle of a window has three primary stages (opening, opened, and closing) in which
2104 * different processes are executed:
2105 *
2106 * **opening**: The opening stage begins when the window manager's {@link OO.ui.WindowManager#openWindow
2107 * openWindow} or the window's {@link #open open} methods are used, and the window manager begins to open
2108 * the window.
2109 *
2110 * - {@link #getSetupProcess} method is called and its result executed
2111 * - {@link #getReadyProcess} method is called and its result executed
2112 *
2113 * **opened**: The window is now open
2114 *
2115 * **closing**: The closing stage begins when the window manager's
2116 * {@link OO.ui.WindowManager#closeWindow closeWindow}
2117 * or the window's {@link #close} methods are used, and the window manager begins to close the window.
2118 *
2119 * - {@link #getHoldProcess} method is called and its result executed
2120 * - {@link #getTeardownProcess} method is called and its result executed. The window is now closed
2121 *
2122 * Each of the window's processes (setup, ready, hold, and teardown) can be extended in subclasses
2123 * by overriding the window's #getSetupProcess, #getReadyProcess, #getHoldProcess and #getTeardownProcess
2124 * methods. Note that each {@link OO.ui.Process process} is executed in series, so asynchronous
2125 * processing can complete. Always assume window processes are executed asynchronously.
2126 *
2127 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
2128 *
2129 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows
2130 *
2131 * @abstract
2132 * @class
2133 * @extends OO.ui.Element
2134 * @mixins OO.EventEmitter
2135 *
2136 * @constructor
2137 * @param {Object} [config] Configuration options
2138 * @cfg {string} [size] Symbolic name of the dialog size: `small`, `medium`, `large`, `larger` or
2139 * `full`. If omitted, the value of the {@link #static-size static size} property will be used.
2140 */
2141 OO.ui.Window = function OoUiWindow( config ) {
2142 // Configuration initialization
2143 config = config || {};
2144
2145 // Parent constructor
2146 OO.ui.Window.parent.call( this, config );
2147
2148 // Mixin constructors
2149 OO.EventEmitter.call( this );
2150
2151 // Properties
2152 this.manager = null;
2153 this.size = config.size || this.constructor.static.size;
2154 this.$frame = $( '<div>' );
2155 this.$overlay = $( '<div>' );
2156 this.$content = $( '<div>' );
2157
2158 this.$focusTrapBefore = $( '<div>' ).prop( 'tabIndex', 0 );
2159 this.$focusTrapAfter = $( '<div>' ).prop( 'tabIndex', 0 );
2160 this.$focusTraps = this.$focusTrapBefore.add( this.$focusTrapAfter );
2161
2162 // Initialization
2163 this.$overlay.addClass( 'oo-ui-window-overlay' );
2164 this.$content
2165 .addClass( 'oo-ui-window-content' )
2166 .attr( 'tabindex', 0 );
2167 this.$frame
2168 .addClass( 'oo-ui-window-frame' )
2169 .append( this.$focusTrapBefore, this.$content, this.$focusTrapAfter );
2170
2171 this.$element
2172 .addClass( 'oo-ui-window' )
2173 .append( this.$frame, this.$overlay );
2174
2175 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
2176 // that reference properties not initialized at that time of parent class construction
2177 // TODO: Find a better way to handle post-constructor setup
2178 this.visible = false;
2179 this.$element.addClass( 'oo-ui-element-hidden' );
2180 };
2181
2182 /* Setup */
2183
2184 OO.inheritClass( OO.ui.Window, OO.ui.Element );
2185 OO.mixinClass( OO.ui.Window, OO.EventEmitter );
2186
2187 /* Static Properties */
2188
2189 /**
2190 * Symbolic name of the window size: `small`, `medium`, `large`, `larger` or `full`.
2191 *
2192 * The static size is used if no #size is configured during construction.
2193 *
2194 * @static
2195 * @inheritable
2196 * @property {string}
2197 */
2198 OO.ui.Window.static.size = 'medium';
2199
2200 /* Methods */
2201
2202 /**
2203 * Handle mouse down events.
2204 *
2205 * @private
2206 * @param {jQuery.Event} e Mouse down event
2207 */
2208 OO.ui.Window.prototype.onMouseDown = function ( e ) {
2209 // Prevent clicking on the click-block from stealing focus
2210 if ( e.target === this.$element[ 0 ] ) {
2211 return false;
2212 }
2213 };
2214
2215 /**
2216 * Check if the window has been initialized.
2217 *
2218 * Initialization occurs when a window is added to a manager.
2219 *
2220 * @return {boolean} Window has been initialized
2221 */
2222 OO.ui.Window.prototype.isInitialized = function () {
2223 return !!this.manager;
2224 };
2225
2226 /**
2227 * Check if the window is visible.
2228 *
2229 * @return {boolean} Window is visible
2230 */
2231 OO.ui.Window.prototype.isVisible = function () {
2232 return this.visible;
2233 };
2234
2235 /**
2236 * Check if the window is opening.
2237 *
2238 * This method is a wrapper around the window manager's {@link OO.ui.WindowManager#isOpening isOpening}
2239 * method.
2240 *
2241 * @return {boolean} Window is opening
2242 */
2243 OO.ui.Window.prototype.isOpening = function () {
2244 return this.manager.isOpening( this );
2245 };
2246
2247 /**
2248 * Check if the window is closing.
2249 *
2250 * This method is a wrapper around the window manager's {@link OO.ui.WindowManager#isClosing isClosing} method.
2251 *
2252 * @return {boolean} Window is closing
2253 */
2254 OO.ui.Window.prototype.isClosing = function () {
2255 return this.manager.isClosing( this );
2256 };
2257
2258 /**
2259 * Check if the window is opened.
2260 *
2261 * This method is a wrapper around the window manager's {@link OO.ui.WindowManager#isOpened isOpened} method.
2262 *
2263 * @return {boolean} Window is opened
2264 */
2265 OO.ui.Window.prototype.isOpened = function () {
2266 return this.manager.isOpened( this );
2267 };
2268
2269 /**
2270 * Get the window manager.
2271 *
2272 * All windows must be attached to a window manager, which is used to open
2273 * and close the window and control its presentation.
2274 *
2275 * @return {OO.ui.WindowManager} Manager of window
2276 */
2277 OO.ui.Window.prototype.getManager = function () {
2278 return this.manager;
2279 };
2280
2281 /**
2282 * Get the symbolic name of the window size (e.g., `small` or `medium`).
2283 *
2284 * @return {string} Symbolic name of the size: `small`, `medium`, `large`, `larger`, `full`
2285 */
2286 OO.ui.Window.prototype.getSize = function () {
2287 var viewport = OO.ui.Element.static.getDimensions( this.getElementWindow() ),
2288 sizes = this.manager.constructor.static.sizes,
2289 size = this.size;
2290
2291 if ( !sizes[ size ] ) {
2292 size = this.manager.constructor.static.defaultSize;
2293 }
2294 if ( size !== 'full' && viewport.rect.right - viewport.rect.left < sizes[ size ].width ) {
2295 size = 'full';
2296 }
2297
2298 return size;
2299 };
2300
2301 /**
2302 * Get the size properties associated with the current window size
2303 *
2304 * @return {Object} Size properties
2305 */
2306 OO.ui.Window.prototype.getSizeProperties = function () {
2307 return this.manager.constructor.static.sizes[ this.getSize() ];
2308 };
2309
2310 /**
2311 * Disable transitions on window's frame for the duration of the callback function, then enable them
2312 * back.
2313 *
2314 * @private
2315 * @param {Function} callback Function to call while transitions are disabled
2316 */
2317 OO.ui.Window.prototype.withoutSizeTransitions = function ( callback ) {
2318 // Temporarily resize the frame so getBodyHeight() can use scrollHeight measurements.
2319 // Disable transitions first, otherwise we'll get values from when the window was animating.
2320 var oldTransition,
2321 styleObj = this.$frame[ 0 ].style;
2322 oldTransition = styleObj.transition || styleObj.OTransition || styleObj.MsTransition ||
2323 styleObj.MozTransition || styleObj.WebkitTransition;
2324 styleObj.transition = styleObj.OTransition = styleObj.MsTransition =
2325 styleObj.MozTransition = styleObj.WebkitTransition = 'none';
2326 callback();
2327 // Force reflow to make sure the style changes done inside callback really are not transitioned
2328 this.$frame.height();
2329 styleObj.transition = styleObj.OTransition = styleObj.MsTransition =
2330 styleObj.MozTransition = styleObj.WebkitTransition = oldTransition;
2331 };
2332
2333 /**
2334 * Get the height of the full window contents (i.e., the window head, body and foot together).
2335 *
2336 * What consistitutes the head, body, and foot varies depending on the window type.
2337 * A {@link OO.ui.MessageDialog message dialog} displays a title and message in its body,
2338 * and any actions in the foot. A {@link OO.ui.ProcessDialog process dialog} displays a title
2339 * and special actions in the head, and dialog content in the body.
2340 *
2341 * To get just the height of the dialog body, use the #getBodyHeight method.
2342 *
2343 * @return {number} The height of the window contents (the dialog head, body and foot) in pixels
2344 */
2345 OO.ui.Window.prototype.getContentHeight = function () {
2346 var bodyHeight,
2347 win = this,
2348 bodyStyleObj = this.$body[ 0 ].style,
2349 frameStyleObj = this.$frame[ 0 ].style;
2350
2351 // Temporarily resize the frame so getBodyHeight() can use scrollHeight measurements.
2352 // Disable transitions first, otherwise we'll get values from when the window was animating.
2353 this.withoutSizeTransitions( function () {
2354 var oldHeight = frameStyleObj.height,
2355 oldPosition = bodyStyleObj.position;
2356 frameStyleObj.height = '1px';
2357 // Force body to resize to new width
2358 bodyStyleObj.position = 'relative';
2359 bodyHeight = win.getBodyHeight();
2360 frameStyleObj.height = oldHeight;
2361 bodyStyleObj.position = oldPosition;
2362 } );
2363
2364 return (
2365 // Add buffer for border
2366 ( this.$frame.outerHeight() - this.$frame.innerHeight() ) +
2367 // Use combined heights of children
2368 ( this.$head.outerHeight( true ) + bodyHeight + this.$foot.outerHeight( true ) )
2369 );
2370 };
2371
2372 /**
2373 * Get the height of the window body.
2374 *
2375 * To get the height of the full window contents (the window body, head, and foot together),
2376 * use #getContentHeight.
2377 *
2378 * When this function is called, the window will temporarily have been resized
2379 * to height=1px, so .scrollHeight measurements can be taken accurately.
2380 *
2381 * @return {number} Height of the window body in pixels
2382 */
2383 OO.ui.Window.prototype.getBodyHeight = function () {
2384 return this.$body[ 0 ].scrollHeight;
2385 };
2386
2387 /**
2388 * Get the directionality of the frame (right-to-left or left-to-right).
2389 *
2390 * @return {string} Directionality: `'ltr'` or `'rtl'`
2391 */
2392 OO.ui.Window.prototype.getDir = function () {
2393 return OO.ui.Element.static.getDir( this.$content ) || 'ltr';
2394 };
2395
2396 /**
2397 * Get the 'setup' process.
2398 *
2399 * The setup process is used to set up a window for use in a particular context,
2400 * based on the `data` argument. This method is called during the opening phase of the window’s
2401 * lifecycle.
2402 *
2403 * Override this method to add additional steps to the ‘setup’ process the parent method provides
2404 * using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next} methods
2405 * of OO.ui.Process.
2406 *
2407 * To add window content that persists between openings, you may wish to use the #initialize method
2408 * instead.
2409 *
2410 * @abstract
2411 * @param {Object} [data] Window opening data
2412 * @return {OO.ui.Process} Setup process
2413 */
2414 OO.ui.Window.prototype.getSetupProcess = function () {
2415 return new OO.ui.Process();
2416 };
2417
2418 /**
2419 * Get the ‘ready’ process.
2420 *
2421 * The ready process is used to ready a window for use in a particular
2422 * context, based on the `data` argument. This method is called during the opening phase of
2423 * the window’s lifecycle, after the window has been {@link #getSetupProcess setup}.
2424 *
2425 * Override this method to add additional steps to the ‘ready’ process the parent method
2426 * provides using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next}
2427 * methods of OO.ui.Process.
2428 *
2429 * @abstract
2430 * @param {Object} [data] Window opening data
2431 * @return {OO.ui.Process} Ready process
2432 */
2433 OO.ui.Window.prototype.getReadyProcess = function () {
2434 return new OO.ui.Process();
2435 };
2436
2437 /**
2438 * Get the 'hold' process.
2439 *
2440 * The hold proccess is used to keep a window from being used in a particular context,
2441 * based on the `data` argument. This method is called during the closing phase of the window’s
2442 * lifecycle.
2443 *
2444 * Override this method to add additional steps to the 'hold' process the parent method provides
2445 * using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next} methods
2446 * of OO.ui.Process.
2447 *
2448 * @abstract
2449 * @param {Object} [data] Window closing data
2450 * @return {OO.ui.Process} Hold process
2451 */
2452 OO.ui.Window.prototype.getHoldProcess = function () {
2453 return new OO.ui.Process();
2454 };
2455
2456 /**
2457 * Get the ‘teardown’ process.
2458 *
2459 * The teardown process is used to teardown a window after use. During teardown,
2460 * user interactions within the window are conveyed and the window is closed, based on the `data`
2461 * argument. This method is called during the closing phase of the window’s lifecycle.
2462 *
2463 * Override this method to add additional steps to the ‘teardown’ process the parent method provides
2464 * using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next} methods
2465 * of OO.ui.Process.
2466 *
2467 * @abstract
2468 * @param {Object} [data] Window closing data
2469 * @return {OO.ui.Process} Teardown process
2470 */
2471 OO.ui.Window.prototype.getTeardownProcess = function () {
2472 return new OO.ui.Process();
2473 };
2474
2475 /**
2476 * Set the window manager.
2477 *
2478 * This will cause the window to initialize. Calling it more than once will cause an error.
2479 *
2480 * @param {OO.ui.WindowManager} manager Manager for this window
2481 * @throws {Error} An error is thrown if the method is called more than once
2482 * @chainable
2483 */
2484 OO.ui.Window.prototype.setManager = function ( manager ) {
2485 if ( this.manager ) {
2486 throw new Error( 'Cannot set window manager, window already has a manager' );
2487 }
2488
2489 this.manager = manager;
2490 this.initialize();
2491
2492 return this;
2493 };
2494
2495 /**
2496 * Set the window size by symbolic name (e.g., 'small' or 'medium')
2497 *
2498 * @param {string} size Symbolic name of size: `small`, `medium`, `large`, `larger` or
2499 * `full`
2500 * @chainable
2501 */
2502 OO.ui.Window.prototype.setSize = function ( size ) {
2503 this.size = size;
2504 this.updateSize();
2505 return this;
2506 };
2507
2508 /**
2509 * Update the window size.
2510 *
2511 * @throws {Error} An error is thrown if the window is not attached to a window manager
2512 * @chainable
2513 */
2514 OO.ui.Window.prototype.updateSize = function () {
2515 if ( !this.manager ) {
2516 throw new Error( 'Cannot update window size, must be attached to a manager' );
2517 }
2518
2519 this.manager.updateWindowSize( this );
2520
2521 return this;
2522 };
2523
2524 /**
2525 * Set window dimensions. This method is called by the {@link OO.ui.WindowManager window manager}
2526 * when the window is opening. In general, setDimensions should not be called directly.
2527 *
2528 * To set the size of the window, use the #setSize method.
2529 *
2530 * @param {Object} dim CSS dimension properties
2531 * @param {string|number} [dim.width] Width
2532 * @param {string|number} [dim.minWidth] Minimum width
2533 * @param {string|number} [dim.maxWidth] Maximum width
2534 * @param {string|number} [dim.width] Height, omit to set based on height of contents
2535 * @param {string|number} [dim.minWidth] Minimum height
2536 * @param {string|number} [dim.maxWidth] Maximum height
2537 * @chainable
2538 */
2539 OO.ui.Window.prototype.setDimensions = function ( dim ) {
2540 var height,
2541 win = this,
2542 styleObj = this.$frame[ 0 ].style;
2543
2544 // Calculate the height we need to set using the correct width
2545 if ( dim.height === undefined ) {
2546 this.withoutSizeTransitions( function () {
2547 var oldWidth = styleObj.width;
2548 win.$frame.css( 'width', dim.width || '' );
2549 height = win.getContentHeight();
2550 styleObj.width = oldWidth;
2551 } );
2552 } else {
2553 height = dim.height;
2554 }
2555
2556 this.$frame.css( {
2557 width: dim.width || '',
2558 minWidth: dim.minWidth || '',
2559 maxWidth: dim.maxWidth || '',
2560 height: height || '',
2561 minHeight: dim.minHeight || '',
2562 maxHeight: dim.maxHeight || ''
2563 } );
2564
2565 return this;
2566 };
2567
2568 /**
2569 * Initialize window contents.
2570 *
2571 * Before the window is opened for the first time, #initialize is called so that content that
2572 * persists between openings can be added to the window.
2573 *
2574 * To set up a window with new content each time the window opens, use #getSetupProcess.
2575 *
2576 * @throws {Error} An error is thrown if the window is not attached to a window manager
2577 * @chainable
2578 */
2579 OO.ui.Window.prototype.initialize = function () {
2580 if ( !this.manager ) {
2581 throw new Error( 'Cannot initialize window, must be attached to a manager' );
2582 }
2583
2584 // Properties
2585 this.$head = $( '<div>' );
2586 this.$body = $( '<div>' );
2587 this.$foot = $( '<div>' );
2588 this.$document = $( this.getElementDocument() );
2589
2590 // Events
2591 this.$element.on( 'mousedown', this.onMouseDown.bind( this ) );
2592
2593 // Initialization
2594 this.$head.addClass( 'oo-ui-window-head' );
2595 this.$body.addClass( 'oo-ui-window-body' );
2596 this.$foot.addClass( 'oo-ui-window-foot' );
2597 this.$content.append( this.$head, this.$body, this.$foot );
2598
2599 return this;
2600 };
2601
2602 /**
2603 * Called when someone tries to focus the hidden element at the end of the dialog.
2604 * Sends focus back to the start of the dialog.
2605 *
2606 * @param {jQuery.Event} event Focus event
2607 */
2608 OO.ui.Window.prototype.onFocusTrapFocused = function ( event ) {
2609 if ( this.$focusTrapBefore.is( event.target ) ) {
2610 OO.ui.findFocusable( this.$content, true ).focus();
2611 } else {
2612 // this.$content is the part of the focus cycle, and is the first focusable element
2613 this.$content.focus();
2614 }
2615 };
2616
2617 /**
2618 * Open the window.
2619 *
2620 * This method is a wrapper around a call to the window manager’s {@link OO.ui.WindowManager#openWindow openWindow}
2621 * method, which returns a promise resolved when the window is done opening.
2622 *
2623 * To customize the window each time it opens, use #getSetupProcess or #getReadyProcess.
2624 *
2625 * @param {Object} [data] Window opening data
2626 * @return {jQuery.Promise} Promise resolved with a value when the window is opened, or rejected
2627 * if the window fails to open. When the promise is resolved successfully, the first argument of the
2628 * value is a new promise, which is resolved when the window begins closing.
2629 * @throws {Error} An error is thrown if the window is not attached to a window manager
2630 */
2631 OO.ui.Window.prototype.open = function ( data ) {
2632 if ( !this.manager ) {
2633 throw new Error( 'Cannot open window, must be attached to a manager' );
2634 }
2635
2636 return this.manager.openWindow( this, data );
2637 };
2638
2639 /**
2640 * Close the window.
2641 *
2642 * This method is a wrapper around a call to the window
2643 * manager’s {@link OO.ui.WindowManager#closeWindow closeWindow} method,
2644 * which returns a closing promise resolved when the window is done closing.
2645 *
2646 * The window's #getHoldProcess and #getTeardownProcess methods are called during the closing
2647 * phase of the window’s lifecycle and can be used to specify closing behavior each time
2648 * the window closes.
2649 *
2650 * @param {Object} [data] Window closing data
2651 * @return {jQuery.Promise} Promise resolved when window is closed
2652 * @throws {Error} An error is thrown if the window is not attached to a window manager
2653 */
2654 OO.ui.Window.prototype.close = function ( data ) {
2655 if ( !this.manager ) {
2656 throw new Error( 'Cannot close window, must be attached to a manager' );
2657 }
2658
2659 return this.manager.closeWindow( this, data );
2660 };
2661
2662 /**
2663 * Setup window.
2664 *
2665 * This is called by OO.ui.WindowManager during window opening, and should not be called directly
2666 * by other systems.
2667 *
2668 * @param {Object} [data] Window opening data
2669 * @return {jQuery.Promise} Promise resolved when window is setup
2670 */
2671 OO.ui.Window.prototype.setup = function ( data ) {
2672 var win = this,
2673 deferred = $.Deferred();
2674
2675 this.toggle( true );
2676
2677 this.focusTrapHandler = OO.ui.bind( this.onFocusTrapFocused, this );
2678 this.$focusTraps.on( 'focus', this.focusTrapHandler );
2679
2680 this.getSetupProcess( data ).execute().done( function () {
2681 // Force redraw by asking the browser to measure the elements' widths
2682 win.$element.addClass( 'oo-ui-window-active oo-ui-window-setup' ).width();
2683 win.$content.addClass( 'oo-ui-window-content-setup' ).width();
2684 deferred.resolve();
2685 } );
2686
2687 return deferred.promise();
2688 };
2689
2690 /**
2691 * Ready window.
2692 *
2693 * This is called by OO.ui.WindowManager during window opening, and should not be called directly
2694 * by other systems.
2695 *
2696 * @param {Object} [data] Window opening data
2697 * @return {jQuery.Promise} Promise resolved when window is ready
2698 */
2699 OO.ui.Window.prototype.ready = function ( data ) {
2700 var win = this,
2701 deferred = $.Deferred();
2702
2703 this.$content.focus();
2704 this.getReadyProcess( data ).execute().done( function () {
2705 // Force redraw by asking the browser to measure the elements' widths
2706 win.$element.addClass( 'oo-ui-window-ready' ).width();
2707 win.$content.addClass( 'oo-ui-window-content-ready' ).width();
2708 deferred.resolve();
2709 } );
2710
2711 return deferred.promise();
2712 };
2713
2714 /**
2715 * Hold window.
2716 *
2717 * This is called by OO.ui.WindowManager during window closing, and should not be called directly
2718 * by other systems.
2719 *
2720 * @param {Object} [data] Window closing data
2721 * @return {jQuery.Promise} Promise resolved when window is held
2722 */
2723 OO.ui.Window.prototype.hold = function ( data ) {
2724 var win = this,
2725 deferred = $.Deferred();
2726
2727 this.getHoldProcess( data ).execute().done( function () {
2728 // Get the focused element within the window's content
2729 var $focus = win.$content.find( OO.ui.Element.static.getDocument( win.$content ).activeElement );
2730
2731 // Blur the focused element
2732 if ( $focus.length ) {
2733 $focus[ 0 ].blur();
2734 }
2735
2736 // Force redraw by asking the browser to measure the elements' widths
2737 win.$element.removeClass( 'oo-ui-window-ready' ).width();
2738 win.$content.removeClass( 'oo-ui-window-content-ready' ).width();
2739 deferred.resolve();
2740 } );
2741
2742 return deferred.promise();
2743 };
2744
2745 /**
2746 * Teardown window.
2747 *
2748 * This is called by OO.ui.WindowManager during window closing, and should not be called directly
2749 * by other systems.
2750 *
2751 * @param {Object} [data] Window closing data
2752 * @return {jQuery.Promise} Promise resolved when window is torn down
2753 */
2754 OO.ui.Window.prototype.teardown = function ( data ) {
2755 var win = this;
2756
2757 return this.getTeardownProcess( data ).execute()
2758 .done( function () {
2759 // Force redraw by asking the browser to measure the elements' widths
2760 win.$element.removeClass( 'oo-ui-window-active oo-ui-window-setup' ).width();
2761 win.$content.removeClass( 'oo-ui-window-content-setup' ).width();
2762 win.$focusTraps.off( 'focus', win.focusTrapHandler );
2763 win.toggle( false );
2764 } );
2765 };
2766
2767 /**
2768 * The Dialog class serves as the base class for the other types of dialogs.
2769 * Unless extended to include controls, the rendered dialog box is a simple window
2770 * that users can close by hitting the ‘Esc’ key. Dialog windows are used with OO.ui.WindowManager,
2771 * which opens, closes, and controls the presentation of the window. See the
2772 * [OOjs UI documentation on MediaWiki] [1] for more information.
2773 *
2774 * @example
2775 * // A simple dialog window.
2776 * function MyDialog( config ) {
2777 * MyDialog.parent.call( this, config );
2778 * }
2779 * OO.inheritClass( MyDialog, OO.ui.Dialog );
2780 * MyDialog.prototype.initialize = function () {
2781 * MyDialog.parent.prototype.initialize.call( this );
2782 * this.content = new OO.ui.PanelLayout( { padded: true, expanded: false } );
2783 * this.content.$element.append( '<p>A simple dialog window. Press \'Esc\' to close.</p>' );
2784 * this.$body.append( this.content.$element );
2785 * };
2786 * MyDialog.prototype.getBodyHeight = function () {
2787 * return this.content.$element.outerHeight( true );
2788 * };
2789 * var myDialog = new MyDialog( {
2790 * size: 'medium'
2791 * } );
2792 * // Create and append a window manager, which opens and closes the window.
2793 * var windowManager = new OO.ui.WindowManager();
2794 * $( 'body' ).append( windowManager.$element );
2795 * windowManager.addWindows( [ myDialog ] );
2796 * // Open the window!
2797 * windowManager.openWindow( myDialog );
2798 *
2799 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Dialogs
2800 *
2801 * @abstract
2802 * @class
2803 * @extends OO.ui.Window
2804 * @mixins OO.ui.mixin.PendingElement
2805 *
2806 * @constructor
2807 * @param {Object} [config] Configuration options
2808 */
2809 OO.ui.Dialog = function OoUiDialog( config ) {
2810 // Parent constructor
2811 OO.ui.Dialog.parent.call( this, config );
2812
2813 // Mixin constructors
2814 OO.ui.mixin.PendingElement.call( this );
2815
2816 // Properties
2817 this.actions = new OO.ui.ActionSet();
2818 this.attachedActions = [];
2819 this.currentAction = null;
2820 this.onDialogKeyDownHandler = this.onDialogKeyDown.bind( this );
2821
2822 // Events
2823 this.actions.connect( this, {
2824 click: 'onActionClick',
2825 resize: 'onActionResize',
2826 change: 'onActionsChange'
2827 } );
2828
2829 // Initialization
2830 this.$element
2831 .addClass( 'oo-ui-dialog' )
2832 .attr( 'role', 'dialog' );
2833 };
2834
2835 /* Setup */
2836
2837 OO.inheritClass( OO.ui.Dialog, OO.ui.Window );
2838 OO.mixinClass( OO.ui.Dialog, OO.ui.mixin.PendingElement );
2839
2840 /* Static Properties */
2841
2842 /**
2843 * Symbolic name of dialog.
2844 *
2845 * The dialog class must have a symbolic name in order to be registered with OO.Factory.
2846 * Please see the [OOjs UI documentation on MediaWiki] [3] for more information.
2847 *
2848 * [3]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
2849 *
2850 * @abstract
2851 * @static
2852 * @inheritable
2853 * @property {string}
2854 */
2855 OO.ui.Dialog.static.name = '';
2856
2857 /**
2858 * The dialog title.
2859 *
2860 * The title can be specified as a plaintext string, a {@link OO.ui.mixin.LabelElement Label} node, or a function
2861 * that will produce a Label node or string. The title can also be specified with data passed to the
2862 * constructor (see #getSetupProcess). In this case, the static value will be overriden.
2863 *
2864 * @abstract
2865 * @static
2866 * @inheritable
2867 * @property {jQuery|string|Function}
2868 */
2869 OO.ui.Dialog.static.title = '';
2870
2871 /**
2872 * An array of configured {@link OO.ui.ActionWidget action widgets}.
2873 *
2874 * Actions can also be specified with data passed to the constructor (see #getSetupProcess). In this case, the static
2875 * value will be overriden.
2876 *
2877 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Action_sets
2878 *
2879 * @static
2880 * @inheritable
2881 * @property {Object[]}
2882 */
2883 OO.ui.Dialog.static.actions = [];
2884
2885 /**
2886 * Close the dialog when the 'Esc' key is pressed.
2887 *
2888 * @static
2889 * @abstract
2890 * @inheritable
2891 * @property {boolean}
2892 */
2893 OO.ui.Dialog.static.escapable = true;
2894
2895 /* Methods */
2896
2897 /**
2898 * Handle frame document key down events.
2899 *
2900 * @private
2901 * @param {jQuery.Event} e Key down event
2902 */
2903 OO.ui.Dialog.prototype.onDialogKeyDown = function ( e ) {
2904 if ( e.which === OO.ui.Keys.ESCAPE ) {
2905 this.close();
2906 e.preventDefault();
2907 e.stopPropagation();
2908 }
2909 };
2910
2911 /**
2912 * Handle action resized events.
2913 *
2914 * @private
2915 * @param {OO.ui.ActionWidget} action Action that was resized
2916 */
2917 OO.ui.Dialog.prototype.onActionResize = function () {
2918 // Override in subclass
2919 };
2920
2921 /**
2922 * Handle action click events.
2923 *
2924 * @private
2925 * @param {OO.ui.ActionWidget} action Action that was clicked
2926 */
2927 OO.ui.Dialog.prototype.onActionClick = function ( action ) {
2928 if ( !this.isPending() ) {
2929 this.executeAction( action.getAction() );
2930 }
2931 };
2932
2933 /**
2934 * Handle actions change event.
2935 *
2936 * @private
2937 */
2938 OO.ui.Dialog.prototype.onActionsChange = function () {
2939 this.detachActions();
2940 if ( !this.isClosing() ) {
2941 this.attachActions();
2942 }
2943 };
2944
2945 /**
2946 * Get the set of actions used by the dialog.
2947 *
2948 * @return {OO.ui.ActionSet}
2949 */
2950 OO.ui.Dialog.prototype.getActions = function () {
2951 return this.actions;
2952 };
2953
2954 /**
2955 * Get a process for taking action.
2956 *
2957 * When you override this method, you can create a new OO.ui.Process and return it, or add additional
2958 * accept steps to the process the parent method provides using the {@link OO.ui.Process#first 'first'}
2959 * and {@link OO.ui.Process#next 'next'} methods of OO.ui.Process.
2960 *
2961 * @abstract
2962 * @param {string} [action] Symbolic name of action
2963 * @return {OO.ui.Process} Action process
2964 */
2965 OO.ui.Dialog.prototype.getActionProcess = function ( action ) {
2966 return new OO.ui.Process()
2967 .next( function () {
2968 if ( !action ) {
2969 // An empty action always closes the dialog without data, which should always be
2970 // safe and make no changes
2971 this.close();
2972 }
2973 }, this );
2974 };
2975
2976 /**
2977 * @inheritdoc
2978 *
2979 * @param {Object} [data] Dialog opening data
2980 * @param {jQuery|string|Function|null} [data.title] Dialog title, omit to use
2981 * the {@link #static-title static title}
2982 * @param {Object[]} [data.actions] List of configuration options for each
2983 * {@link OO.ui.ActionWidget action widget}, omit to use {@link #static-actions static actions}.
2984 */
2985 OO.ui.Dialog.prototype.getSetupProcess = function ( data ) {
2986 data = data || {};
2987
2988 // Parent method
2989 return OO.ui.Dialog.parent.prototype.getSetupProcess.call( this, data )
2990 .next( function () {
2991 var config = this.constructor.static,
2992 actions = data.actions !== undefined ? data.actions : config.actions;
2993
2994 this.title.setLabel(
2995 data.title !== undefined ? data.title : this.constructor.static.title
2996 );
2997 this.actions.add( this.getActionWidgets( actions ) );
2998
2999 if ( this.constructor.static.escapable ) {
3000 this.$element.on( 'keydown', this.onDialogKeyDownHandler );
3001 }
3002 }, this );
3003 };
3004
3005 /**
3006 * @inheritdoc
3007 */
3008 OO.ui.Dialog.prototype.getTeardownProcess = function ( data ) {
3009 // Parent method
3010 return OO.ui.Dialog.parent.prototype.getTeardownProcess.call( this, data )
3011 .first( function () {
3012 if ( this.constructor.static.escapable ) {
3013 this.$element.off( 'keydown', this.onDialogKeyDownHandler );
3014 }
3015
3016 this.actions.clear();
3017 this.currentAction = null;
3018 }, this );
3019 };
3020
3021 /**
3022 * @inheritdoc
3023 */
3024 OO.ui.Dialog.prototype.initialize = function () {
3025 var titleId;
3026
3027 // Parent method
3028 OO.ui.Dialog.parent.prototype.initialize.call( this );
3029
3030 titleId = OO.ui.generateElementId();
3031
3032 // Properties
3033 this.title = new OO.ui.LabelWidget( {
3034 id: titleId
3035 } );
3036
3037 // Initialization
3038 this.$content.addClass( 'oo-ui-dialog-content' );
3039 this.$element.attr( 'aria-labelledby', titleId );
3040 this.setPendingElement( this.$head );
3041 };
3042
3043 /**
3044 * Get action widgets from a list of configs
3045 *
3046 * @param {Object[]} actions Action widget configs
3047 * @return {OO.ui.ActionWidget[]} Action widgets
3048 */
3049 OO.ui.Dialog.prototype.getActionWidgets = function ( actions ) {
3050 var i, len, widgets = [];
3051 for ( i = 0, len = actions.length; i < len; i++ ) {
3052 widgets.push(
3053 new OO.ui.ActionWidget( actions[ i ] )
3054 );
3055 }
3056 return widgets;
3057 };
3058
3059 /**
3060 * Attach action actions.
3061 *
3062 * @protected
3063 */
3064 OO.ui.Dialog.prototype.attachActions = function () {
3065 // Remember the list of potentially attached actions
3066 this.attachedActions = this.actions.get();
3067 };
3068
3069 /**
3070 * Detach action actions.
3071 *
3072 * @protected
3073 * @chainable
3074 */
3075 OO.ui.Dialog.prototype.detachActions = function () {
3076 var i, len;
3077
3078 // Detach all actions that may have been previously attached
3079 for ( i = 0, len = this.attachedActions.length; i < len; i++ ) {
3080 this.attachedActions[ i ].$element.detach();
3081 }
3082 this.attachedActions = [];
3083 };
3084
3085 /**
3086 * Execute an action.
3087 *
3088 * @param {string} action Symbolic name of action to execute
3089 * @return {jQuery.Promise} Promise resolved when action completes, rejected if it fails
3090 */
3091 OO.ui.Dialog.prototype.executeAction = function ( action ) {
3092 this.pushPending();
3093 this.currentAction = action;
3094 return this.getActionProcess( action ).execute()
3095 .always( this.popPending.bind( this ) );
3096 };
3097
3098 /**
3099 * Window managers are used to open and close {@link OO.ui.Window windows} and control their presentation.
3100 * Managed windows are mutually exclusive. If a new window is opened while a current window is opening
3101 * or is opened, the current window will be closed and any ongoing {@link OO.ui.Process process} will be cancelled. Windows
3102 * themselves are persistent and—rather than being torn down when closed—can be repopulated with the
3103 * pertinent data and reused.
3104 *
3105 * Over the lifecycle of a window, the window manager makes available three promises: `opening`,
3106 * `opened`, and `closing`, which represent the primary stages of the cycle:
3107 *
3108 * **Opening**: the opening stage begins when the window manager’s #openWindow or a window’s
3109 * {@link OO.ui.Window#open open} method is used, and the window manager begins to open the window.
3110 *
3111 * - an `opening` event is emitted with an `opening` promise
3112 * - the #getSetupDelay method is called and the returned value is used to time a pause in execution before
3113 * the window’s {@link OO.ui.Window#getSetupProcess getSetupProcess} method is called on the
3114 * window and its result executed
3115 * - a `setup` progress notification is emitted from the `opening` promise
3116 * - the #getReadyDelay method is called the returned value is used to time a pause in execution before
3117 * the window’s {@link OO.ui.Window#getReadyProcess getReadyProcess} method is called on the
3118 * window and its result executed
3119 * - a `ready` progress notification is emitted from the `opening` promise
3120 * - the `opening` promise is resolved with an `opened` promise
3121 *
3122 * **Opened**: the window is now open.
3123 *
3124 * **Closing**: the closing stage begins when the window manager's #closeWindow or the
3125 * window's {@link OO.ui.Window#close close} methods is used, and the window manager begins
3126 * to close the window.
3127 *
3128 * - the `opened` promise is resolved with `closing` promise and a `closing` event is emitted
3129 * - the #getHoldDelay method is called and the returned value is used to time a pause in execution before
3130 * the window's {@link OO.ui.Window#getHoldProcess getHoldProces} method is called on the
3131 * window and its result executed
3132 * - a `hold` progress notification is emitted from the `closing` promise
3133 * - the #getTeardownDelay() method is called and the returned value is used to time a pause in execution before
3134 * the window's {@link OO.ui.Window#getTeardownProcess getTeardownProcess} method is called on the
3135 * window and its result executed
3136 * - a `teardown` progress notification is emitted from the `closing` promise
3137 * - the `closing` promise is resolved. The window is now closed
3138 *
3139 * See the [OOjs UI documentation on MediaWiki][1] for more information.
3140 *
3141 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
3142 *
3143 * @class
3144 * @extends OO.ui.Element
3145 * @mixins OO.EventEmitter
3146 *
3147 * @constructor
3148 * @param {Object} [config] Configuration options
3149 * @cfg {OO.Factory} [factory] Window factory to use for automatic instantiation
3150 * Note that window classes that are instantiated with a factory must have
3151 * a {@link OO.ui.Dialog#static-name static name} property that specifies a symbolic name.
3152 * @cfg {boolean} [modal=true] Prevent interaction outside the dialog
3153 */
3154 OO.ui.WindowManager = function OoUiWindowManager( config ) {
3155 // Configuration initialization
3156 config = config || {};
3157
3158 // Parent constructor
3159 OO.ui.WindowManager.parent.call( this, config );
3160
3161 // Mixin constructors
3162 OO.EventEmitter.call( this );
3163
3164 // Properties
3165 this.factory = config.factory;
3166 this.modal = config.modal === undefined || !!config.modal;
3167 this.windows = {};
3168 this.opening = null;
3169 this.opened = null;
3170 this.closing = null;
3171 this.preparingToOpen = null;
3172 this.preparingToClose = null;
3173 this.currentWindow = null;
3174 this.globalEvents = false;
3175 this.$ariaHidden = null;
3176 this.onWindowResizeTimeout = null;
3177 this.onWindowResizeHandler = this.onWindowResize.bind( this );
3178 this.afterWindowResizeHandler = this.afterWindowResize.bind( this );
3179
3180 // Initialization
3181 this.$element
3182 .addClass( 'oo-ui-windowManager' )
3183 .toggleClass( 'oo-ui-windowManager-modal', this.modal );
3184 };
3185
3186 /* Setup */
3187
3188 OO.inheritClass( OO.ui.WindowManager, OO.ui.Element );
3189 OO.mixinClass( OO.ui.WindowManager, OO.EventEmitter );
3190
3191 /* Events */
3192
3193 /**
3194 * An 'opening' event is emitted when the window begins to be opened.
3195 *
3196 * @event opening
3197 * @param {OO.ui.Window} win Window that's being opened
3198 * @param {jQuery.Promise} opening An `opening` promise resolved with a value when the window is opened successfully.
3199 * When the `opening` promise is resolved, the first argument of the value is an 'opened' promise, the second argument
3200 * is the opening data. The `opening` promise emits `setup` and `ready` notifications when those processes are complete.
3201 * @param {Object} data Window opening data
3202 */
3203
3204 /**
3205 * A 'closing' event is emitted when the window begins to be closed.
3206 *
3207 * @event closing
3208 * @param {OO.ui.Window} win Window that's being closed
3209 * @param {jQuery.Promise} closing A `closing` promise is resolved with a value when the window
3210 * is closed successfully. The promise emits `hold` and `teardown` notifications when those
3211 * processes are complete. When the `closing` promise is resolved, the first argument of its value
3212 * is the closing data.
3213 * @param {Object} data Window closing data
3214 */
3215
3216 /**
3217 * A 'resize' event is emitted when a window is resized.
3218 *
3219 * @event resize
3220 * @param {OO.ui.Window} win Window that was resized
3221 */
3222
3223 /* Static Properties */
3224
3225 /**
3226 * Map of the symbolic name of each window size and its CSS properties.
3227 *
3228 * @static
3229 * @inheritable
3230 * @property {Object}
3231 */
3232 OO.ui.WindowManager.static.sizes = {
3233 small: {
3234 width: 300
3235 },
3236 medium: {
3237 width: 500
3238 },
3239 large: {
3240 width: 700
3241 },
3242 larger: {
3243 width: 900
3244 },
3245 full: {
3246 // These can be non-numeric because they are never used in calculations
3247 width: '100%',
3248 height: '100%'
3249 }
3250 };
3251
3252 /**
3253 * Symbolic name of the default window size.
3254 *
3255 * The default size is used if the window's requested size is not recognized.
3256 *
3257 * @static
3258 * @inheritable
3259 * @property {string}
3260 */
3261 OO.ui.WindowManager.static.defaultSize = 'medium';
3262
3263 /* Methods */
3264
3265 /**
3266 * Handle window resize events.
3267 *
3268 * @private
3269 * @param {jQuery.Event} e Window resize event
3270 */
3271 OO.ui.WindowManager.prototype.onWindowResize = function () {
3272 clearTimeout( this.onWindowResizeTimeout );
3273 this.onWindowResizeTimeout = setTimeout( this.afterWindowResizeHandler, 200 );
3274 };
3275
3276 /**
3277 * Handle window resize events.
3278 *
3279 * @private
3280 * @param {jQuery.Event} e Window resize event
3281 */
3282 OO.ui.WindowManager.prototype.afterWindowResize = function () {
3283 if ( this.currentWindow ) {
3284 this.updateWindowSize( this.currentWindow );
3285 }
3286 };
3287
3288 /**
3289 * Check if window is opening.
3290 *
3291 * @return {boolean} Window is opening
3292 */
3293 OO.ui.WindowManager.prototype.isOpening = function ( win ) {
3294 return win === this.currentWindow && !!this.opening && this.opening.state() === 'pending';
3295 };
3296
3297 /**
3298 * Check if window is closing.
3299 *
3300 * @return {boolean} Window is closing
3301 */
3302 OO.ui.WindowManager.prototype.isClosing = function ( win ) {
3303 return win === this.currentWindow && !!this.closing && this.closing.state() === 'pending';
3304 };
3305
3306 /**
3307 * Check if window is opened.
3308 *
3309 * @return {boolean} Window is opened
3310 */
3311 OO.ui.WindowManager.prototype.isOpened = function ( win ) {
3312 return win === this.currentWindow && !!this.opened && this.opened.state() === 'pending';
3313 };
3314
3315 /**
3316 * Check if a window is being managed.
3317 *
3318 * @param {OO.ui.Window} win Window to check
3319 * @return {boolean} Window is being managed
3320 */
3321 OO.ui.WindowManager.prototype.hasWindow = function ( win ) {
3322 var name;
3323
3324 for ( name in this.windows ) {
3325 if ( this.windows[ name ] === win ) {
3326 return true;
3327 }
3328 }
3329
3330 return false;
3331 };
3332
3333 /**
3334 * Get the number of milliseconds to wait after opening begins before executing the ‘setup’ process.
3335 *
3336 * @param {OO.ui.Window} win Window being opened
3337 * @param {Object} [data] Window opening data
3338 * @return {number} Milliseconds to wait
3339 */
3340 OO.ui.WindowManager.prototype.getSetupDelay = function () {
3341 return 0;
3342 };
3343
3344 /**
3345 * Get the number of milliseconds to wait after setup has finished before executing the ‘ready’ process.
3346 *
3347 * @param {OO.ui.Window} win Window being opened
3348 * @param {Object} [data] Window opening data
3349 * @return {number} Milliseconds to wait
3350 */
3351 OO.ui.WindowManager.prototype.getReadyDelay = function () {
3352 return 0;
3353 };
3354
3355 /**
3356 * Get the number of milliseconds to wait after closing has begun before executing the 'hold' process.
3357 *
3358 * @param {OO.ui.Window} win Window being closed
3359 * @param {Object} [data] Window closing data
3360 * @return {number} Milliseconds to wait
3361 */
3362 OO.ui.WindowManager.prototype.getHoldDelay = function () {
3363 return 0;
3364 };
3365
3366 /**
3367 * Get the number of milliseconds to wait after the ‘hold’ process has finished before
3368 * executing the ‘teardown’ process.
3369 *
3370 * @param {OO.ui.Window} win Window being closed
3371 * @param {Object} [data] Window closing data
3372 * @return {number} Milliseconds to wait
3373 */
3374 OO.ui.WindowManager.prototype.getTeardownDelay = function () {
3375 return this.modal ? 250 : 0;
3376 };
3377
3378 /**
3379 * Get a window by its symbolic name.
3380 *
3381 * If the window is not yet instantiated and its symbolic name is recognized by a factory, it will be
3382 * instantiated and added to the window manager automatically. Please see the [OOjs UI documentation on MediaWiki][3]
3383 * for more information about using factories.
3384 * [3]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
3385 *
3386 * @param {string} name Symbolic name of the window
3387 * @return {jQuery.Promise} Promise resolved with matching window, or rejected with an OO.ui.Error
3388 * @throws {Error} An error is thrown if the symbolic name is not recognized by the factory.
3389 * @throws {Error} An error is thrown if the named window is not recognized as a managed window.
3390 */
3391 OO.ui.WindowManager.prototype.getWindow = function ( name ) {
3392 var deferred = $.Deferred(),
3393 win = this.windows[ name ];
3394
3395 if ( !( win instanceof OO.ui.Window ) ) {
3396 if ( this.factory ) {
3397 if ( !this.factory.lookup( name ) ) {
3398 deferred.reject( new OO.ui.Error(
3399 'Cannot auto-instantiate window: symbolic name is unrecognized by the factory'
3400 ) );
3401 } else {
3402 win = this.factory.create( name );
3403 this.addWindows( [ win ] );
3404 deferred.resolve( win );
3405 }
3406 } else {
3407 deferred.reject( new OO.ui.Error(
3408 'Cannot get unmanaged window: symbolic name unrecognized as a managed window'
3409 ) );
3410 }
3411 } else {
3412 deferred.resolve( win );
3413 }
3414
3415 return deferred.promise();
3416 };
3417
3418 /**
3419 * Get current window.
3420 *
3421 * @return {OO.ui.Window|null} Currently opening/opened/closing window
3422 */
3423 OO.ui.WindowManager.prototype.getCurrentWindow = function () {
3424 return this.currentWindow;
3425 };
3426
3427 /**
3428 * Open a window.
3429 *
3430 * @param {OO.ui.Window|string} win Window object or symbolic name of window to open
3431 * @param {Object} [data] Window opening data
3432 * @return {jQuery.Promise} An `opening` promise resolved when the window is done opening.
3433 * See {@link #event-opening 'opening' event} for more information about `opening` promises.
3434 * @fires opening
3435 */
3436 OO.ui.WindowManager.prototype.openWindow = function ( win, data ) {
3437 var manager = this,
3438 opening = $.Deferred();
3439
3440 // Argument handling
3441 if ( typeof win === 'string' ) {
3442 return this.getWindow( win ).then( function ( win ) {
3443 return manager.openWindow( win, data );
3444 } );
3445 }
3446
3447 // Error handling
3448 if ( !this.hasWindow( win ) ) {
3449 opening.reject( new OO.ui.Error(
3450 'Cannot open window: window is not attached to manager'
3451 ) );
3452 } else if ( this.preparingToOpen || this.opening || this.opened ) {
3453 opening.reject( new OO.ui.Error(
3454 'Cannot open window: another window is opening or open'
3455 ) );
3456 }
3457
3458 // Window opening
3459 if ( opening.state() !== 'rejected' ) {
3460 // If a window is currently closing, wait for it to complete
3461 this.preparingToOpen = $.when( this.closing );
3462 // Ensure handlers get called after preparingToOpen is set
3463 this.preparingToOpen.done( function () {
3464 if ( manager.modal ) {
3465 manager.toggleGlobalEvents( true );
3466 manager.toggleAriaIsolation( true );
3467 }
3468 manager.currentWindow = win;
3469 manager.opening = opening;
3470 manager.preparingToOpen = null;
3471 manager.emit( 'opening', win, opening, data );
3472 setTimeout( function () {
3473 win.setup( data ).then( function () {
3474 manager.updateWindowSize( win );
3475 manager.opening.notify( { state: 'setup' } );
3476 setTimeout( function () {
3477 win.ready( data ).then( function () {
3478 manager.opening.notify( { state: 'ready' } );
3479 manager.opening = null;
3480 manager.opened = $.Deferred();
3481 opening.resolve( manager.opened.promise(), data );
3482 } );
3483 }, manager.getReadyDelay() );
3484 } );
3485 }, manager.getSetupDelay() );
3486 } );
3487 }
3488
3489 return opening.promise();
3490 };
3491
3492 /**
3493 * Close a window.
3494 *
3495 * @param {OO.ui.Window|string} win Window object or symbolic name of window to close
3496 * @param {Object} [data] Window closing data
3497 * @return {jQuery.Promise} A `closing` promise resolved when the window is done closing.
3498 * See {@link #event-closing 'closing' event} for more information about closing promises.
3499 * @throws {Error} An error is thrown if the window is not managed by the window manager.
3500 * @fires closing
3501 */
3502 OO.ui.WindowManager.prototype.closeWindow = function ( win, data ) {
3503 var manager = this,
3504 closing = $.Deferred(),
3505 opened;
3506
3507 // Argument handling
3508 if ( typeof win === 'string' ) {
3509 win = this.windows[ win ];
3510 } else if ( !this.hasWindow( win ) ) {
3511 win = null;
3512 }
3513
3514 // Error handling
3515 if ( !win ) {
3516 closing.reject( new OO.ui.Error(
3517 'Cannot close window: window is not attached to manager'
3518 ) );
3519 } else if ( win !== this.currentWindow ) {
3520 closing.reject( new OO.ui.Error(
3521 'Cannot close window: window already closed with different data'
3522 ) );
3523 } else if ( this.preparingToClose || this.closing ) {
3524 closing.reject( new OO.ui.Error(
3525 'Cannot close window: window already closing with different data'
3526 ) );
3527 }
3528
3529 // Window closing
3530 if ( closing.state() !== 'rejected' ) {
3531 // If the window is currently opening, close it when it's done
3532 this.preparingToClose = $.when( this.opening );
3533 // Ensure handlers get called after preparingToClose is set
3534 this.preparingToClose.done( function () {
3535 manager.closing = closing;
3536 manager.preparingToClose = null;
3537 manager.emit( 'closing', win, closing, data );
3538 opened = manager.opened;
3539 manager.opened = null;
3540 opened.resolve( closing.promise(), data );
3541 setTimeout( function () {
3542 win.hold( data ).then( function () {
3543 closing.notify( { state: 'hold' } );
3544 setTimeout( function () {
3545 win.teardown( data ).then( function () {
3546 closing.notify( { state: 'teardown' } );
3547 if ( manager.modal ) {
3548 manager.toggleGlobalEvents( false );
3549 manager.toggleAriaIsolation( false );
3550 }
3551 manager.closing = null;
3552 manager.currentWindow = null;
3553 closing.resolve( data );
3554 } );
3555 }, manager.getTeardownDelay() );
3556 } );
3557 }, manager.getHoldDelay() );
3558 } );
3559 }
3560
3561 return closing.promise();
3562 };
3563
3564 /**
3565 * Add windows to the window manager.
3566 *
3567 * Windows can be added by reference, symbolic name, or explicitly defined symbolic names.
3568 * See the [OOjs ui documentation on MediaWiki] [2] for examples.
3569 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
3570 *
3571 * @param {Object.<string,OO.ui.Window>|OO.ui.Window[]} windows An array of window objects specified
3572 * by reference, symbolic name, or explicitly defined symbolic names.
3573 * @throws {Error} An error is thrown if a window is added by symbolic name, but has neither an
3574 * explicit nor a statically configured symbolic name.
3575 */
3576 OO.ui.WindowManager.prototype.addWindows = function ( windows ) {
3577 var i, len, win, name, list;
3578
3579 if ( Array.isArray( windows ) ) {
3580 // Convert to map of windows by looking up symbolic names from static configuration
3581 list = {};
3582 for ( i = 0, len = windows.length; i < len; i++ ) {
3583 name = windows[ i ].constructor.static.name;
3584 if ( typeof name !== 'string' ) {
3585 throw new Error( 'Cannot add window' );
3586 }
3587 list[ name ] = windows[ i ];
3588 }
3589 } else if ( OO.isPlainObject( windows ) ) {
3590 list = windows;
3591 }
3592
3593 // Add windows
3594 for ( name in list ) {
3595 win = list[ name ];
3596 this.windows[ name ] = win.toggle( false );
3597 this.$element.append( win.$element );
3598 win.setManager( this );
3599 }
3600 };
3601
3602 /**
3603 * Remove the specified windows from the windows manager.
3604 *
3605 * Windows will be closed before they are removed. If you wish to remove all windows, you may wish to use
3606 * the #clearWindows method instead. If you no longer need the window manager and want to ensure that it no
3607 * longer listens to events, use the #destroy method.
3608 *
3609 * @param {string[]} names Symbolic names of windows to remove
3610 * @return {jQuery.Promise} Promise resolved when window is closed and removed
3611 * @throws {Error} An error is thrown if the named windows are not managed by the window manager.
3612 */
3613 OO.ui.WindowManager.prototype.removeWindows = function ( names ) {
3614 var i, len, win, name, cleanupWindow,
3615 manager = this,
3616 promises = [],
3617 cleanup = function ( name, win ) {
3618 delete manager.windows[ name ];
3619 win.$element.detach();
3620 };
3621
3622 for ( i = 0, len = names.length; i < len; i++ ) {
3623 name = names[ i ];
3624 win = this.windows[ name ];
3625 if ( !win ) {
3626 throw new Error( 'Cannot remove window' );
3627 }
3628 cleanupWindow = cleanup.bind( null, name, win );
3629 promises.push( this.closeWindow( name ).then( cleanupWindow, cleanupWindow ) );
3630 }
3631
3632 return $.when.apply( $, promises );
3633 };
3634
3635 /**
3636 * Remove all windows from the window manager.
3637 *
3638 * Windows will be closed before they are removed. Note that the window manager, though not in use, will still
3639 * listen to events. If the window manager will not be used again, you may wish to use the #destroy method instead.
3640 * To remove just a subset of windows, use the #removeWindows method.
3641 *
3642 * @return {jQuery.Promise} Promise resolved when all windows are closed and removed
3643 */
3644 OO.ui.WindowManager.prototype.clearWindows = function () {
3645 return this.removeWindows( Object.keys( this.windows ) );
3646 };
3647
3648 /**
3649 * Set dialog size. In general, this method should not be called directly.
3650 *
3651 * Fullscreen mode will be used if the dialog is too wide to fit in the screen.
3652 *
3653 * @chainable
3654 */
3655 OO.ui.WindowManager.prototype.updateWindowSize = function ( win ) {
3656 var isFullscreen;
3657
3658 // Bypass for non-current, and thus invisible, windows
3659 if ( win !== this.currentWindow ) {
3660 return;
3661 }
3662
3663 isFullscreen = win.getSize() === 'full';
3664
3665 this.$element.toggleClass( 'oo-ui-windowManager-fullscreen', isFullscreen );
3666 this.$element.toggleClass( 'oo-ui-windowManager-floating', !isFullscreen );
3667 win.setDimensions( win.getSizeProperties() );
3668
3669 this.emit( 'resize', win );
3670
3671 return this;
3672 };
3673
3674 /**
3675 * Bind or unbind global events for scrolling.
3676 *
3677 * @private
3678 * @param {boolean} [on] Bind global events
3679 * @chainable
3680 */
3681 OO.ui.WindowManager.prototype.toggleGlobalEvents = function ( on ) {
3682 var scrollWidth, bodyMargin,
3683 $body = $( this.getElementDocument().body ),
3684 // We could have multiple window managers open so only modify
3685 // the body css at the bottom of the stack
3686 stackDepth = $body.data( 'windowManagerGlobalEvents' ) || 0 ;
3687
3688 on = on === undefined ? !!this.globalEvents : !!on;
3689
3690 if ( on ) {
3691 if ( !this.globalEvents ) {
3692 $( this.getElementWindow() ).on( {
3693 // Start listening for top-level window dimension changes
3694 'orientationchange resize': this.onWindowResizeHandler
3695 } );
3696 if ( stackDepth === 0 ) {
3697 scrollWidth = window.innerWidth - document.documentElement.clientWidth;
3698 bodyMargin = parseFloat( $body.css( 'margin-right' ) ) || 0;
3699 $body.css( {
3700 overflow: 'hidden',
3701 'margin-right': bodyMargin + scrollWidth
3702 } );
3703 }
3704 stackDepth++;
3705 this.globalEvents = true;
3706 }
3707 } else if ( this.globalEvents ) {
3708 $( this.getElementWindow() ).off( {
3709 // Stop listening for top-level window dimension changes
3710 'orientationchange resize': this.onWindowResizeHandler
3711 } );
3712 stackDepth--;
3713 if ( stackDepth === 0 ) {
3714 $body.css( {
3715 overflow: '',
3716 'margin-right': ''
3717 } );
3718 }
3719 this.globalEvents = false;
3720 }
3721 $body.data( 'windowManagerGlobalEvents', stackDepth );
3722
3723 return this;
3724 };
3725
3726 /**
3727 * Toggle screen reader visibility of content other than the window manager.
3728 *
3729 * @private
3730 * @param {boolean} [isolate] Make only the window manager visible to screen readers
3731 * @chainable
3732 */
3733 OO.ui.WindowManager.prototype.toggleAriaIsolation = function ( isolate ) {
3734 isolate = isolate === undefined ? !this.$ariaHidden : !!isolate;
3735
3736 if ( isolate ) {
3737 if ( !this.$ariaHidden ) {
3738 // Hide everything other than the window manager from screen readers
3739 this.$ariaHidden = $( 'body' )
3740 .children()
3741 .not( this.$element.parentsUntil( 'body' ).last() )
3742 .attr( 'aria-hidden', '' );
3743 }
3744 } else if ( this.$ariaHidden ) {
3745 // Restore screen reader visibility
3746 this.$ariaHidden.removeAttr( 'aria-hidden' );
3747 this.$ariaHidden = null;
3748 }
3749
3750 return this;
3751 };
3752
3753 /**
3754 * Destroy the window manager.
3755 *
3756 * Destroying the window manager ensures that it will no longer listen to events. If you would like to
3757 * continue using the window manager, but wish to remove all windows from it, use the #clearWindows method
3758 * instead.
3759 */
3760 OO.ui.WindowManager.prototype.destroy = function () {
3761 this.toggleGlobalEvents( false );
3762 this.toggleAriaIsolation( false );
3763 this.clearWindows();
3764 this.$element.remove();
3765 };
3766
3767 /**
3768 * Errors contain a required message (either a string or jQuery selection) that is used to describe what went wrong
3769 * in a {@link OO.ui.Process process}. The error's #recoverable and #warning configurations are used to customize the
3770 * appearance and functionality of the error interface.
3771 *
3772 * The basic error interface contains a formatted error message as well as two buttons: 'Dismiss' and 'Try again' (i.e., the error
3773 * is 'recoverable' by default). If the error is not recoverable, the 'Try again' button will not be rendered and the widget
3774 * that initiated the failed process will be disabled.
3775 *
3776 * If the error is a warning, the error interface will include a 'Dismiss' and a 'Continue' button, which will try the
3777 * process again.
3778 *
3779 * For an example of error interfaces, please see the [OOjs UI documentation on MediaWiki][1].
3780 *
3781 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Processes_and_errors
3782 *
3783 * @class
3784 *
3785 * @constructor
3786 * @param {string|jQuery} message Description of error
3787 * @param {Object} [config] Configuration options
3788 * @cfg {boolean} [recoverable=true] Error is recoverable.
3789 * By default, errors are recoverable, and users can try the process again.
3790 * @cfg {boolean} [warning=false] Error is a warning.
3791 * If the error is a warning, the error interface will include a
3792 * 'Dismiss' and a 'Continue' button. It is the responsibility of the developer to ensure that the warning
3793 * is not triggered a second time if the user chooses to continue.
3794 */
3795 OO.ui.Error = function OoUiError( message, config ) {
3796 // Allow passing positional parameters inside the config object
3797 if ( OO.isPlainObject( message ) && config === undefined ) {
3798 config = message;
3799 message = config.message;
3800 }
3801
3802 // Configuration initialization
3803 config = config || {};
3804
3805 // Properties
3806 this.message = message instanceof jQuery ? message : String( message );
3807 this.recoverable = config.recoverable === undefined || !!config.recoverable;
3808 this.warning = !!config.warning;
3809 };
3810
3811 /* Setup */
3812
3813 OO.initClass( OO.ui.Error );
3814
3815 /* Methods */
3816
3817 /**
3818 * Check if the error is recoverable.
3819 *
3820 * If the error is recoverable, users are able to try the process again.
3821 *
3822 * @return {boolean} Error is recoverable
3823 */
3824 OO.ui.Error.prototype.isRecoverable = function () {
3825 return this.recoverable;
3826 };
3827
3828 /**
3829 * Check if the error is a warning.
3830 *
3831 * If the error is a warning, the error interface will include a 'Dismiss' and a 'Continue' button.
3832 *
3833 * @return {boolean} Error is warning
3834 */
3835 OO.ui.Error.prototype.isWarning = function () {
3836 return this.warning;
3837 };
3838
3839 /**
3840 * Get error message as DOM nodes.
3841 *
3842 * @return {jQuery} Error message in DOM nodes
3843 */
3844 OO.ui.Error.prototype.getMessage = function () {
3845 return this.message instanceof jQuery ?
3846 this.message.clone() :
3847 $( '<div>' ).text( this.message ).contents();
3848 };
3849
3850 /**
3851 * Get the error message text.
3852 *
3853 * @return {string} Error message
3854 */
3855 OO.ui.Error.prototype.getMessageText = function () {
3856 return this.message instanceof jQuery ? this.message.text() : this.message;
3857 };
3858
3859 /**
3860 * Wraps an HTML snippet for use with configuration values which default
3861 * to strings. This bypasses the default html-escaping done to string
3862 * values.
3863 *
3864 * @class
3865 *
3866 * @constructor
3867 * @param {string} [content] HTML content
3868 */
3869 OO.ui.HtmlSnippet = function OoUiHtmlSnippet( content ) {
3870 // Properties
3871 this.content = content;
3872 };
3873
3874 /* Setup */
3875
3876 OO.initClass( OO.ui.HtmlSnippet );
3877
3878 /* Methods */
3879
3880 /**
3881 * Render into HTML.
3882 *
3883 * @return {string} Unchanged HTML snippet.
3884 */
3885 OO.ui.HtmlSnippet.prototype.toString = function () {
3886 return this.content;
3887 };
3888
3889 /**
3890 * A Process is a list of steps that are called in sequence. The step can be a number, a jQuery promise,
3891 * or a function:
3892 *
3893 * - **number**: the process will wait for the specified number of milliseconds before proceeding.
3894 * - **promise**: the process will continue to the next step when the promise is successfully resolved
3895 * or stop if the promise is rejected.
3896 * - **function**: the process will execute the function. The process will stop if the function returns
3897 * either a boolean `false` or a promise that is rejected; if the function returns a number, the process
3898 * will wait for that number of milliseconds before proceeding.
3899 *
3900 * If the process fails, an {@link OO.ui.Error error} is generated. Depending on how the error is
3901 * configured, users can dismiss the error and try the process again, or not. If a process is stopped,
3902 * its remaining steps will not be performed.
3903 *
3904 * @class
3905 *
3906 * @constructor
3907 * @param {number|jQuery.Promise|Function} step Number of miliseconds to wait before proceeding, promise
3908 * that must be resolved before proceeding, or a function to execute. See #createStep for more information. see #createStep for more information
3909 * @param {Object} [context=null] Execution context of the function. The context is ignored if the step is
3910 * a number or promise.
3911 * @return {Object} Step object, with `callback` and `context` properties
3912 */
3913 OO.ui.Process = function ( step, context ) {
3914 // Properties
3915 this.steps = [];
3916
3917 // Initialization
3918 if ( step !== undefined ) {
3919 this.next( step, context );
3920 }
3921 };
3922
3923 /* Setup */
3924
3925 OO.initClass( OO.ui.Process );
3926
3927 /* Methods */
3928
3929 /**
3930 * Start the process.
3931 *
3932 * @return {jQuery.Promise} Promise that is resolved when all steps have successfully completed.
3933 * If any of the steps return a promise that is rejected or a boolean false, this promise is rejected
3934 * and any remaining steps are not performed.
3935 */
3936 OO.ui.Process.prototype.execute = function () {
3937 var i, len, promise;
3938
3939 /**
3940 * Continue execution.
3941 *
3942 * @ignore
3943 * @param {Array} step A function and the context it should be called in
3944 * @return {Function} Function that continues the process
3945 */
3946 function proceed( step ) {
3947 return function () {
3948 // Execute step in the correct context
3949 var deferred,
3950 result = step.callback.call( step.context );
3951
3952 if ( result === false ) {
3953 // Use rejected promise for boolean false results
3954 return $.Deferred().reject( [] ).promise();
3955 }
3956 if ( typeof result === 'number' ) {
3957 if ( result < 0 ) {
3958 throw new Error( 'Cannot go back in time: flux capacitor is out of service' );
3959 }
3960 // Use a delayed promise for numbers, expecting them to be in milliseconds
3961 deferred = $.Deferred();
3962 setTimeout( deferred.resolve, result );
3963 return deferred.promise();
3964 }
3965 if ( result instanceof OO.ui.Error ) {
3966 // Use rejected promise for error
3967 return $.Deferred().reject( [ result ] ).promise();
3968 }
3969 if ( Array.isArray( result ) && result.length && result[ 0 ] instanceof OO.ui.Error ) {
3970 // Use rejected promise for list of errors
3971 return $.Deferred().reject( result ).promise();
3972 }
3973 // Duck-type the object to see if it can produce a promise
3974 if ( result && $.isFunction( result.promise ) ) {
3975 // Use a promise generated from the result
3976 return result.promise();
3977 }
3978 // Use resolved promise for other results
3979 return $.Deferred().resolve().promise();
3980 };
3981 }
3982
3983 if ( this.steps.length ) {
3984 // Generate a chain reaction of promises
3985 promise = proceed( this.steps[ 0 ] )();
3986 for ( i = 1, len = this.steps.length; i < len; i++ ) {
3987 promise = promise.then( proceed( this.steps[ i ] ) );
3988 }
3989 } else {
3990 promise = $.Deferred().resolve().promise();
3991 }
3992
3993 return promise;
3994 };
3995
3996 /**
3997 * Create a process step.
3998 *
3999 * @private
4000 * @param {number|jQuery.Promise|Function} step
4001 *
4002 * - Number of milliseconds to wait before proceeding
4003 * - Promise that must be resolved before proceeding
4004 * - Function to execute
4005 * - If the function returns a boolean false the process will stop
4006 * - If the function returns a promise, the process will continue to the next
4007 * step when the promise is resolved or stop if the promise is rejected
4008 * - If the function returns a number, the process will wait for that number of
4009 * milliseconds before proceeding
4010 * @param {Object} [context=null] Execution context of the function. The context is
4011 * ignored if the step is a number or promise.
4012 * @return {Object} Step object, with `callback` and `context` properties
4013 */
4014 OO.ui.Process.prototype.createStep = function ( step, context ) {
4015 if ( typeof step === 'number' || $.isFunction( step.promise ) ) {
4016 return {
4017 callback: function () {
4018 return step;
4019 },
4020 context: null
4021 };
4022 }
4023 if ( $.isFunction( step ) ) {
4024 return {
4025 callback: step,
4026 context: context
4027 };
4028 }
4029 throw new Error( 'Cannot create process step: number, promise or function expected' );
4030 };
4031
4032 /**
4033 * Add step to the beginning of the process.
4034 *
4035 * @inheritdoc #createStep
4036 * @return {OO.ui.Process} this
4037 * @chainable
4038 */
4039 OO.ui.Process.prototype.first = function ( step, context ) {
4040 this.steps.unshift( this.createStep( step, context ) );
4041 return this;
4042 };
4043
4044 /**
4045 * Add step to the end of the process.
4046 *
4047 * @inheritdoc #createStep
4048 * @return {OO.ui.Process} this
4049 * @chainable
4050 */
4051 OO.ui.Process.prototype.next = function ( step, context ) {
4052 this.steps.push( this.createStep( step, context ) );
4053 return this;
4054 };
4055
4056 /**
4057 * A ToolFactory creates tools on demand. All tools ({@link OO.ui.Tool Tools}, {@link OO.ui.PopupTool PopupTools},
4058 * and {@link OO.ui.ToolGroupTool ToolGroupTools}) must be registered with a tool factory. Tools are
4059 * registered by their symbolic name. See {@link OO.ui.Toolbar toolbars} for an example.
4060 *
4061 * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki][1].
4062 *
4063 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
4064 *
4065 * @class
4066 * @extends OO.Factory
4067 * @constructor
4068 */
4069 OO.ui.ToolFactory = function OoUiToolFactory() {
4070 // Parent constructor
4071 OO.ui.ToolFactory.parent.call( this );
4072 };
4073
4074 /* Setup */
4075
4076 OO.inheritClass( OO.ui.ToolFactory, OO.Factory );
4077
4078 /* Methods */
4079
4080 /**
4081 * Get tools from the factory
4082 *
4083 * @param {Array} include Included tools
4084 * @param {Array} exclude Excluded tools
4085 * @param {Array} promote Promoted tools
4086 * @param {Array} demote Demoted tools
4087 * @return {string[]} List of tools
4088 */
4089 OO.ui.ToolFactory.prototype.getTools = function ( include, exclude, promote, demote ) {
4090 var i, len, included, promoted, demoted,
4091 auto = [],
4092 used = {};
4093
4094 // Collect included and not excluded tools
4095 included = OO.simpleArrayDifference( this.extract( include ), this.extract( exclude ) );
4096
4097 // Promotion
4098 promoted = this.extract( promote, used );
4099 demoted = this.extract( demote, used );
4100
4101 // Auto
4102 for ( i = 0, len = included.length; i < len; i++ ) {
4103 if ( !used[ included[ i ] ] ) {
4104 auto.push( included[ i ] );
4105 }
4106 }
4107
4108 return promoted.concat( auto ).concat( demoted );
4109 };
4110
4111 /**
4112 * Get a flat list of names from a list of names or groups.
4113 *
4114 * Tools can be specified in the following ways:
4115 *
4116 * - A specific tool: `{ name: 'tool-name' }` or `'tool-name'`
4117 * - All tools in a group: `{ group: 'group-name' }`
4118 * - All tools: `'*'`
4119 *
4120 * @private
4121 * @param {Array|string} collection List of tools
4122 * @param {Object} [used] Object with names that should be skipped as properties; extracted
4123 * names will be added as properties
4124 * @return {string[]} List of extracted names
4125 */
4126 OO.ui.ToolFactory.prototype.extract = function ( collection, used ) {
4127 var i, len, item, name, tool,
4128 names = [];
4129
4130 if ( collection === '*' ) {
4131 for ( name in this.registry ) {
4132 tool = this.registry[ name ];
4133 if (
4134 // Only add tools by group name when auto-add is enabled
4135 tool.static.autoAddToCatchall &&
4136 // Exclude already used tools
4137 ( !used || !used[ name ] )
4138 ) {
4139 names.push( name );
4140 if ( used ) {
4141 used[ name ] = true;
4142 }
4143 }
4144 }
4145 } else if ( Array.isArray( collection ) ) {
4146 for ( i = 0, len = collection.length; i < len; i++ ) {
4147 item = collection[ i ];
4148 // Allow plain strings as shorthand for named tools
4149 if ( typeof item === 'string' ) {
4150 item = { name: item };
4151 }
4152 if ( OO.isPlainObject( item ) ) {
4153 if ( item.group ) {
4154 for ( name in this.registry ) {
4155 tool = this.registry[ name ];
4156 if (
4157 // Include tools with matching group
4158 tool.static.group === item.group &&
4159 // Only add tools by group name when auto-add is enabled
4160 tool.static.autoAddToGroup &&
4161 // Exclude already used tools
4162 ( !used || !used[ name ] )
4163 ) {
4164 names.push( name );
4165 if ( used ) {
4166 used[ name ] = true;
4167 }
4168 }
4169 }
4170 // Include tools with matching name and exclude already used tools
4171 } else if ( item.name && ( !used || !used[ item.name ] ) ) {
4172 names.push( item.name );
4173 if ( used ) {
4174 used[ item.name ] = true;
4175 }
4176 }
4177 }
4178 }
4179 }
4180 return names;
4181 };
4182
4183 /**
4184 * ToolGroupFactories create {@link OO.ui.ToolGroup toolgroups} on demand. The toolgroup classes must
4185 * specify a symbolic name and be registered with the factory. The following classes are registered by
4186 * default:
4187 *
4188 * - {@link OO.ui.BarToolGroup BarToolGroups} (‘bar’)
4189 * - {@link OO.ui.MenuToolGroup MenuToolGroups} (‘menu’)
4190 * - {@link OO.ui.ListToolGroup ListToolGroups} (‘list’)
4191 *
4192 * See {@link OO.ui.Toolbar toolbars} for an example.
4193 *
4194 * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki][1].
4195 *
4196 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
4197 * @class
4198 * @extends OO.Factory
4199 * @constructor
4200 */
4201 OO.ui.ToolGroupFactory = function OoUiToolGroupFactory() {
4202 var i, l, defaultClasses;
4203 // Parent constructor
4204 OO.Factory.call( this );
4205
4206 defaultClasses = this.constructor.static.getDefaultClasses();
4207
4208 // Register default toolgroups
4209 for ( i = 0, l = defaultClasses.length; i < l; i++ ) {
4210 this.register( defaultClasses[ i ] );
4211 }
4212 };
4213
4214 /* Setup */
4215
4216 OO.inheritClass( OO.ui.ToolGroupFactory, OO.Factory );
4217
4218 /* Static Methods */
4219
4220 /**
4221 * Get a default set of classes to be registered on construction.
4222 *
4223 * @return {Function[]} Default classes
4224 */
4225 OO.ui.ToolGroupFactory.static.getDefaultClasses = function () {
4226 return [
4227 OO.ui.BarToolGroup,
4228 OO.ui.ListToolGroup,
4229 OO.ui.MenuToolGroup
4230 ];
4231 };
4232
4233 /**
4234 * Theme logic.
4235 *
4236 * @abstract
4237 * @class
4238 *
4239 * @constructor
4240 * @param {Object} [config] Configuration options
4241 */
4242 OO.ui.Theme = function OoUiTheme( config ) {
4243 // Configuration initialization
4244 config = config || {};
4245 };
4246
4247 /* Setup */
4248
4249 OO.initClass( OO.ui.Theme );
4250
4251 /* Methods */
4252
4253 /**
4254 * Get a list of classes to be applied to a widget.
4255 *
4256 * The 'on' and 'off' lists combined MUST contain keys for all classes the theme adds or removes,
4257 * otherwise state transitions will not work properly.
4258 *
4259 * @param {OO.ui.Element} element Element for which to get classes
4260 * @return {Object.<string,string[]>} Categorized class names with `on` and `off` lists
4261 */
4262 OO.ui.Theme.prototype.getElementClasses = function () {
4263 return { on: [], off: [] };
4264 };
4265
4266 /**
4267 * Update CSS classes provided by the theme.
4268 *
4269 * For elements with theme logic hooks, this should be called any time there's a state change.
4270 *
4271 * @param {OO.ui.Element} element Element for which to update classes
4272 * @return {Object.<string,string[]>} Categorized class names with `on` and `off` lists
4273 */
4274 OO.ui.Theme.prototype.updateElementClasses = function ( element ) {
4275 var $elements = $( [] ),
4276 classes = this.getElementClasses( element );
4277
4278 if ( element.$icon ) {
4279 $elements = $elements.add( element.$icon );
4280 }
4281 if ( element.$indicator ) {
4282 $elements = $elements.add( element.$indicator );
4283 }
4284
4285 $elements
4286 .removeClass( classes.off.join( ' ' ) )
4287 .addClass( classes.on.join( ' ' ) );
4288 };
4289
4290 /**
4291 * The TabIndexedElement class is an attribute mixin used to add additional functionality to an
4292 * element created by another class. The mixin provides a ‘tabIndex’ property, which specifies the
4293 * order in which users will navigate through the focusable elements via the "tab" key.
4294 *
4295 * @example
4296 * // TabIndexedElement is mixed into the ButtonWidget class
4297 * // to provide a tabIndex property.
4298 * var button1 = new OO.ui.ButtonWidget( {
4299 * label: 'fourth',
4300 * tabIndex: 4
4301 * } );
4302 * var button2 = new OO.ui.ButtonWidget( {
4303 * label: 'second',
4304 * tabIndex: 2
4305 * } );
4306 * var button3 = new OO.ui.ButtonWidget( {
4307 * label: 'third',
4308 * tabIndex: 3
4309 * } );
4310 * var button4 = new OO.ui.ButtonWidget( {
4311 * label: 'first',
4312 * tabIndex: 1
4313 * } );
4314 * $( 'body' ).append( button1.$element, button2.$element, button3.$element, button4.$element );
4315 *
4316 * @abstract
4317 * @class
4318 *
4319 * @constructor
4320 * @param {Object} [config] Configuration options
4321 * @cfg {jQuery} [$tabIndexed] The element that should use the tabindex functionality. By default,
4322 * the functionality is applied to the element created by the class ($element). If a different element is specified, the tabindex
4323 * functionality will be applied to it instead.
4324 * @cfg {number|null} [tabIndex=0] Number that specifies the element’s position in the tab-navigation
4325 * order (e.g., 1 for the first focusable element). Use 0 to use the default navigation order; use -1
4326 * to remove the element from the tab-navigation flow.
4327 */
4328 OO.ui.mixin.TabIndexedElement = function OoUiMixinTabIndexedElement( config ) {
4329 // Configuration initialization
4330 config = $.extend( { tabIndex: 0 }, config );
4331
4332 // Properties
4333 this.$tabIndexed = null;
4334 this.tabIndex = null;
4335
4336 // Events
4337 this.connect( this, { disable: 'onTabIndexedElementDisable' } );
4338
4339 // Initialization
4340 this.setTabIndex( config.tabIndex );
4341 this.setTabIndexedElement( config.$tabIndexed || this.$element );
4342 };
4343
4344 /* Setup */
4345
4346 OO.initClass( OO.ui.mixin.TabIndexedElement );
4347
4348 /* Methods */
4349
4350 /**
4351 * Set the element that should use the tabindex functionality.
4352 *
4353 * This method is used to retarget a tabindex mixin so that its functionality applies
4354 * to the specified element. If an element is currently using the functionality, the mixin’s
4355 * effect on that element is removed before the new element is set up.
4356 *
4357 * @param {jQuery} $tabIndexed Element that should use the tabindex functionality
4358 * @chainable
4359 */
4360 OO.ui.mixin.TabIndexedElement.prototype.setTabIndexedElement = function ( $tabIndexed ) {
4361 var tabIndex = this.tabIndex;
4362 // Remove attributes from old $tabIndexed
4363 this.setTabIndex( null );
4364 // Force update of new $tabIndexed
4365 this.$tabIndexed = $tabIndexed;
4366 this.tabIndex = tabIndex;
4367 return this.updateTabIndex();
4368 };
4369
4370 /**
4371 * Set the value of the tabindex.
4372 *
4373 * @param {number|null} tabIndex Tabindex value, or `null` for no tabindex
4374 * @chainable
4375 */
4376 OO.ui.mixin.TabIndexedElement.prototype.setTabIndex = function ( tabIndex ) {
4377 tabIndex = typeof tabIndex === 'number' ? tabIndex : null;
4378
4379 if ( this.tabIndex !== tabIndex ) {
4380 this.tabIndex = tabIndex;
4381 this.updateTabIndex();
4382 }
4383
4384 return this;
4385 };
4386
4387 /**
4388 * Update the `tabindex` attribute, in case of changes to tab index or
4389 * disabled state.
4390 *
4391 * @private
4392 * @chainable
4393 */
4394 OO.ui.mixin.TabIndexedElement.prototype.updateTabIndex = function () {
4395 if ( this.$tabIndexed ) {
4396 if ( this.tabIndex !== null ) {
4397 // Do not index over disabled elements
4398 this.$tabIndexed.attr( {
4399 tabindex: this.isDisabled() ? -1 : this.tabIndex,
4400 // Support: ChromeVox and NVDA
4401 // These do not seem to inherit aria-disabled from parent elements
4402 'aria-disabled': this.isDisabled().toString()
4403 } );
4404 } else {
4405 this.$tabIndexed.removeAttr( 'tabindex aria-disabled' );
4406 }
4407 }
4408 return this;
4409 };
4410
4411 /**
4412 * Handle disable events.
4413 *
4414 * @private
4415 * @param {boolean} disabled Element is disabled
4416 */
4417 OO.ui.mixin.TabIndexedElement.prototype.onTabIndexedElementDisable = function () {
4418 this.updateTabIndex();
4419 };
4420
4421 /**
4422 * Get the value of the tabindex.
4423 *
4424 * @return {number|null} Tabindex value
4425 */
4426 OO.ui.mixin.TabIndexedElement.prototype.getTabIndex = function () {
4427 return this.tabIndex;
4428 };
4429
4430 /**
4431 * ButtonElement is often mixed into other classes to generate a button, which is a clickable
4432 * interface element that can be configured with access keys for accessibility.
4433 * See the [OOjs UI documentation on MediaWiki] [1] for examples.
4434 *
4435 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#Buttons
4436 * @abstract
4437 * @class
4438 *
4439 * @constructor
4440 * @param {Object} [config] Configuration options
4441 * @cfg {jQuery} [$button] The button element created by the class.
4442 * If this configuration is omitted, the button element will use a generated `<a>`.
4443 * @cfg {boolean} [framed=true] Render the button with a frame
4444 */
4445 OO.ui.mixin.ButtonElement = function OoUiMixinButtonElement( config ) {
4446 // Configuration initialization
4447 config = config || {};
4448
4449 // Properties
4450 this.$button = null;
4451 this.framed = null;
4452 this.active = false;
4453 this.onMouseUpHandler = this.onMouseUp.bind( this );
4454 this.onMouseDownHandler = this.onMouseDown.bind( this );
4455 this.onKeyDownHandler = this.onKeyDown.bind( this );
4456 this.onKeyUpHandler = this.onKeyUp.bind( this );
4457 this.onClickHandler = this.onClick.bind( this );
4458 this.onKeyPressHandler = this.onKeyPress.bind( this );
4459
4460 // Initialization
4461 this.$element.addClass( 'oo-ui-buttonElement' );
4462 this.toggleFramed( config.framed === undefined || config.framed );
4463 this.setButtonElement( config.$button || $( '<a>' ) );
4464 };
4465
4466 /* Setup */
4467
4468 OO.initClass( OO.ui.mixin.ButtonElement );
4469
4470 /* Static Properties */
4471
4472 /**
4473 * Cancel mouse down events.
4474 *
4475 * This property is usually set to `true` to prevent the focus from changing when the button is clicked.
4476 * Classes such as {@link OO.ui.mixin.DraggableElement DraggableElement} and {@link OO.ui.ButtonOptionWidget ButtonOptionWidget}
4477 * use a value of `false` so that dragging behavior is possible and mousedown events can be handled by a
4478 * parent widget.
4479 *
4480 * @static
4481 * @inheritable
4482 * @property {boolean}
4483 */
4484 OO.ui.mixin.ButtonElement.static.cancelButtonMouseDownEvents = true;
4485
4486 /* Events */
4487
4488 /**
4489 * A 'click' event is emitted when the button element is clicked.
4490 *
4491 * @event click
4492 */
4493
4494 /* Methods */
4495
4496 /**
4497 * Set the button element.
4498 *
4499 * This method is used to retarget a button mixin so that its functionality applies to
4500 * the specified button element instead of the one created by the class. If a button element
4501 * is already set, the method will remove the mixin’s effect on that element.
4502 *
4503 * @param {jQuery} $button Element to use as button
4504 */
4505 OO.ui.mixin.ButtonElement.prototype.setButtonElement = function ( $button ) {
4506 if ( this.$button ) {
4507 this.$button
4508 .removeClass( 'oo-ui-buttonElement-button' )
4509 .removeAttr( 'role accesskey' )
4510 .off( {
4511 mousedown: this.onMouseDownHandler,
4512 keydown: this.onKeyDownHandler,
4513 click: this.onClickHandler,
4514 keypress: this.onKeyPressHandler
4515 } );
4516 }
4517
4518 this.$button = $button
4519 .addClass( 'oo-ui-buttonElement-button' )
4520 .attr( { role: 'button' } )
4521 .on( {
4522 mousedown: this.onMouseDownHandler,
4523 keydown: this.onKeyDownHandler,
4524 click: this.onClickHandler,
4525 keypress: this.onKeyPressHandler
4526 } );
4527 };
4528
4529 /**
4530 * Handles mouse down events.
4531 *
4532 * @protected
4533 * @param {jQuery.Event} e Mouse down event
4534 */
4535 OO.ui.mixin.ButtonElement.prototype.onMouseDown = function ( e ) {
4536 if ( this.isDisabled() || e.which !== 1 ) {
4537 return;
4538 }
4539 this.$element.addClass( 'oo-ui-buttonElement-pressed' );
4540 // Run the mouseup handler no matter where the mouse is when the button is let go, so we can
4541 // reliably remove the pressed class
4542 OO.ui.addCaptureEventListener( this.getElementDocument(), 'mouseup', this.onMouseUpHandler );
4543 // Prevent change of focus unless specifically configured otherwise
4544 if ( this.constructor.static.cancelButtonMouseDownEvents ) {
4545 return false;
4546 }
4547 };
4548
4549 /**
4550 * Handles mouse up events.
4551 *
4552 * @protected
4553 * @param {jQuery.Event} e Mouse up event
4554 */
4555 OO.ui.mixin.ButtonElement.prototype.onMouseUp = function ( e ) {
4556 if ( this.isDisabled() || e.which !== 1 ) {
4557 return;
4558 }
4559 this.$element.removeClass( 'oo-ui-buttonElement-pressed' );
4560 // Stop listening for mouseup, since we only needed this once
4561 OO.ui.removeCaptureEventListener( this.getElementDocument(), 'mouseup', this.onMouseUpHandler );
4562 };
4563
4564 /**
4565 * Handles mouse click events.
4566 *
4567 * @protected
4568 * @param {jQuery.Event} e Mouse click event
4569 * @fires click
4570 */
4571 OO.ui.mixin.ButtonElement.prototype.onClick = function ( e ) {
4572 if ( !this.isDisabled() && e.which === 1 ) {
4573 if ( this.emit( 'click' ) ) {
4574 return false;
4575 }
4576 }
4577 };
4578
4579 /**
4580 * Handles key down events.
4581 *
4582 * @protected
4583 * @param {jQuery.Event} e Key down event
4584 */
4585 OO.ui.mixin.ButtonElement.prototype.onKeyDown = function ( e ) {
4586 if ( this.isDisabled() || ( e.which !== OO.ui.Keys.SPACE && e.which !== OO.ui.Keys.ENTER ) ) {
4587 return;
4588 }
4589 this.$element.addClass( 'oo-ui-buttonElement-pressed' );
4590 // Run the keyup handler no matter where the key is when the button is let go, so we can
4591 // reliably remove the pressed class
4592 OO.ui.addCaptureEventListener( this.getElementDocument(), 'keyup', this.onKeyUpHandler );
4593 };
4594
4595 /**
4596 * Handles key up events.
4597 *
4598 * @protected
4599 * @param {jQuery.Event} e Key up event
4600 */
4601 OO.ui.mixin.ButtonElement.prototype.onKeyUp = function ( e ) {
4602 if ( this.isDisabled() || ( e.which !== OO.ui.Keys.SPACE && e.which !== OO.ui.Keys.ENTER ) ) {
4603 return;
4604 }
4605 this.$element.removeClass( 'oo-ui-buttonElement-pressed' );
4606 // Stop listening for keyup, since we only needed this once
4607 OO.ui.removeCaptureEventListener( this.getElementDocument(), 'keyup', this.onKeyUpHandler );
4608 };
4609
4610 /**
4611 * Handles key press events.
4612 *
4613 * @protected
4614 * @param {jQuery.Event} e Key press event
4615 * @fires click
4616 */
4617 OO.ui.mixin.ButtonElement.prototype.onKeyPress = function ( e ) {
4618 if ( !this.isDisabled() && ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER ) ) {
4619 if ( this.emit( 'click' ) ) {
4620 return false;
4621 }
4622 }
4623 };
4624
4625 /**
4626 * Check if button has a frame.
4627 *
4628 * @return {boolean} Button is framed
4629 */
4630 OO.ui.mixin.ButtonElement.prototype.isFramed = function () {
4631 return this.framed;
4632 };
4633
4634 /**
4635 * Render the button with or without a frame. Omit the `framed` parameter to toggle the button frame on and off.
4636 *
4637 * @param {boolean} [framed] Make button framed, omit to toggle
4638 * @chainable
4639 */
4640 OO.ui.mixin.ButtonElement.prototype.toggleFramed = function ( framed ) {
4641 framed = framed === undefined ? !this.framed : !!framed;
4642 if ( framed !== this.framed ) {
4643 this.framed = framed;
4644 this.$element
4645 .toggleClass( 'oo-ui-buttonElement-frameless', !framed )
4646 .toggleClass( 'oo-ui-buttonElement-framed', framed );
4647 this.updateThemeClasses();
4648 }
4649
4650 return this;
4651 };
4652
4653 /**
4654 * Set the button's active state.
4655 *
4656 * The active state occurs when a {@link OO.ui.ButtonOptionWidget ButtonOptionWidget} or
4657 * a {@link OO.ui.ToggleButtonWidget ToggleButtonWidget} is pressed. This method does nothing
4658 * for other button types.
4659 *
4660 * @param {boolean} value Make button active
4661 * @chainable
4662 */
4663 OO.ui.mixin.ButtonElement.prototype.setActive = function ( value ) {
4664 this.active = !!value;
4665 this.$element.toggleClass( 'oo-ui-buttonElement-active', this.active );
4666 return this;
4667 };
4668
4669 /**
4670 * Check if the button is active
4671 *
4672 * @return {boolean} The button is active
4673 */
4674 OO.ui.mixin.ButtonElement.prototype.isActive = function () {
4675 return this.active;
4676 };
4677
4678 /**
4679 * Any OOjs UI widget that contains other widgets (such as {@link OO.ui.ButtonWidget buttons} or
4680 * {@link OO.ui.OptionWidget options}) mixes in GroupElement. Adding, removing, and clearing
4681 * items from the group is done through the interface the class provides.
4682 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
4683 *
4684 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Groups
4685 *
4686 * @abstract
4687 * @class
4688 *
4689 * @constructor
4690 * @param {Object} [config] Configuration options
4691 * @cfg {jQuery} [$group] The container element created by the class. If this configuration
4692 * is omitted, the group element will use a generated `<div>`.
4693 */
4694 OO.ui.mixin.GroupElement = function OoUiMixinGroupElement( config ) {
4695 // Configuration initialization
4696 config = config || {};
4697
4698 // Properties
4699 this.$group = null;
4700 this.items = [];
4701 this.aggregateItemEvents = {};
4702
4703 // Initialization
4704 this.setGroupElement( config.$group || $( '<div>' ) );
4705 };
4706
4707 /* Methods */
4708
4709 /**
4710 * Set the group element.
4711 *
4712 * If an element is already set, items will be moved to the new element.
4713 *
4714 * @param {jQuery} $group Element to use as group
4715 */
4716 OO.ui.mixin.GroupElement.prototype.setGroupElement = function ( $group ) {
4717 var i, len;
4718
4719 this.$group = $group;
4720 for ( i = 0, len = this.items.length; i < len; i++ ) {
4721 this.$group.append( this.items[ i ].$element );
4722 }
4723 };
4724
4725 /**
4726 * Check if a group contains no items.
4727 *
4728 * @return {boolean} Group is empty
4729 */
4730 OO.ui.mixin.GroupElement.prototype.isEmpty = function () {
4731 return !this.items.length;
4732 };
4733
4734 /**
4735 * Get all items in the group.
4736 *
4737 * The method returns an array of item references (e.g., [button1, button2, button3]) and is useful
4738 * when synchronizing groups of items, or whenever the references are required (e.g., when removing items
4739 * from a group).
4740 *
4741 * @return {OO.ui.Element[]} An array of items.
4742 */
4743 OO.ui.mixin.GroupElement.prototype.getItems = function () {
4744 return this.items.slice( 0 );
4745 };
4746
4747 /**
4748 * Get an item by its data.
4749 *
4750 * Only the first item with matching data will be returned. To return all matching items,
4751 * use the #getItemsFromData method.
4752 *
4753 * @param {Object} data Item data to search for
4754 * @return {OO.ui.Element|null} Item with equivalent data, `null` if none exists
4755 */
4756 OO.ui.mixin.GroupElement.prototype.getItemFromData = function ( data ) {
4757 var i, len, item,
4758 hash = OO.getHash( data );
4759
4760 for ( i = 0, len = this.items.length; i < len; i++ ) {
4761 item = this.items[ i ];
4762 if ( hash === OO.getHash( item.getData() ) ) {
4763 return item;
4764 }
4765 }
4766
4767 return null;
4768 };
4769
4770 /**
4771 * Get items by their data.
4772 *
4773 * All items with matching data will be returned. To return only the first match, use the #getItemFromData method instead.
4774 *
4775 * @param {Object} data Item data to search for
4776 * @return {OO.ui.Element[]} Items with equivalent data
4777 */
4778 OO.ui.mixin.GroupElement.prototype.getItemsFromData = function ( data ) {
4779 var i, len, item,
4780 hash = OO.getHash( data ),
4781 items = [];
4782
4783 for ( i = 0, len = this.items.length; i < len; i++ ) {
4784 item = this.items[ i ];
4785 if ( hash === OO.getHash( item.getData() ) ) {
4786 items.push( item );
4787 }
4788 }
4789
4790 return items;
4791 };
4792
4793 /**
4794 * Aggregate the events emitted by the group.
4795 *
4796 * When events are aggregated, the group will listen to all contained items for the event,
4797 * and then emit the event under a new name. The new event will contain an additional leading
4798 * parameter containing the item that emitted the original event. Other arguments emitted from
4799 * the original event are passed through.
4800 *
4801 * @param {Object.<string,string|null>} events An object keyed by the name of the event that should be
4802 * aggregated (e.g., ‘click’) and the value of the new name to use (e.g., ‘groupClick’).
4803 * A `null` value will remove aggregated events.
4804
4805 * @throws {Error} An error is thrown if aggregation already exists.
4806 */
4807 OO.ui.mixin.GroupElement.prototype.aggregate = function ( events ) {
4808 var i, len, item, add, remove, itemEvent, groupEvent;
4809
4810 for ( itemEvent in events ) {
4811 groupEvent = events[ itemEvent ];
4812
4813 // Remove existing aggregated event
4814 if ( Object.prototype.hasOwnProperty.call( this.aggregateItemEvents, itemEvent ) ) {
4815 // Don't allow duplicate aggregations
4816 if ( groupEvent ) {
4817 throw new Error( 'Duplicate item event aggregation for ' + itemEvent );
4818 }
4819 // Remove event aggregation from existing items
4820 for ( i = 0, len = this.items.length; i < len; i++ ) {
4821 item = this.items[ i ];
4822 if ( item.connect && item.disconnect ) {
4823 remove = {};
4824 remove[ itemEvent ] = [ 'emit', this.aggregateItemEvents[ itemEvent ], item ];
4825 item.disconnect( this, remove );
4826 }
4827 }
4828 // Prevent future items from aggregating event
4829 delete this.aggregateItemEvents[ itemEvent ];
4830 }
4831
4832 // Add new aggregate event
4833 if ( groupEvent ) {
4834 // Make future items aggregate event
4835 this.aggregateItemEvents[ itemEvent ] = groupEvent;
4836 // Add event aggregation to existing items
4837 for ( i = 0, len = this.items.length; i < len; i++ ) {
4838 item = this.items[ i ];
4839 if ( item.connect && item.disconnect ) {
4840 add = {};
4841 add[ itemEvent ] = [ 'emit', groupEvent, item ];
4842 item.connect( this, add );
4843 }
4844 }
4845 }
4846 }
4847 };
4848
4849 /**
4850 * Add items to the group.
4851 *
4852 * Items will be added to the end of the group array unless the optional `index` parameter specifies
4853 * a different insertion point. Adding an existing item will move it to the end of the array or the point specified by the `index`.
4854 *
4855 * @param {OO.ui.Element[]} items An array of items to add to the group
4856 * @param {number} [index] Index of the insertion point
4857 * @chainable
4858 */
4859 OO.ui.mixin.GroupElement.prototype.addItems = function ( items, index ) {
4860 var i, len, item, event, events, currentIndex,
4861 itemElements = [];
4862
4863 for ( i = 0, len = items.length; i < len; i++ ) {
4864 item = items[ i ];
4865
4866 // Check if item exists then remove it first, effectively "moving" it
4867 currentIndex = this.items.indexOf( item );
4868 if ( currentIndex >= 0 ) {
4869 this.removeItems( [ item ] );
4870 // Adjust index to compensate for removal
4871 if ( currentIndex < index ) {
4872 index--;
4873 }
4874 }
4875 // Add the item
4876 if ( item.connect && item.disconnect && !$.isEmptyObject( this.aggregateItemEvents ) ) {
4877 events = {};
4878 for ( event in this.aggregateItemEvents ) {
4879 events[ event ] = [ 'emit', this.aggregateItemEvents[ event ], item ];
4880 }
4881 item.connect( this, events );
4882 }
4883 item.setElementGroup( this );
4884 itemElements.push( item.$element.get( 0 ) );
4885 }
4886
4887 if ( index === undefined || index < 0 || index >= this.items.length ) {
4888 this.$group.append( itemElements );
4889 this.items.push.apply( this.items, items );
4890 } else if ( index === 0 ) {
4891 this.$group.prepend( itemElements );
4892 this.items.unshift.apply( this.items, items );
4893 } else {
4894 this.items[ index ].$element.before( itemElements );
4895 this.items.splice.apply( this.items, [ index, 0 ].concat( items ) );
4896 }
4897
4898 return this;
4899 };
4900
4901 /**
4902 * Remove the specified items from a group.
4903 *
4904 * Removed items are detached (not removed) from the DOM so that they may be reused.
4905 * To remove all items from a group, you may wish to use the #clearItems method instead.
4906 *
4907 * @param {OO.ui.Element[]} items An array of items to remove
4908 * @chainable
4909 */
4910 OO.ui.mixin.GroupElement.prototype.removeItems = function ( items ) {
4911 var i, len, item, index, remove, itemEvent;
4912
4913 // Remove specific items
4914 for ( i = 0, len = items.length; i < len; i++ ) {
4915 item = items[ i ];
4916 index = this.items.indexOf( item );
4917 if ( index !== -1 ) {
4918 if (
4919 item.connect && item.disconnect &&
4920 !$.isEmptyObject( this.aggregateItemEvents )
4921 ) {
4922 remove = {};
4923 if ( Object.prototype.hasOwnProperty.call( this.aggregateItemEvents, itemEvent ) ) {
4924 remove[ itemEvent ] = [ 'emit', this.aggregateItemEvents[ itemEvent ], item ];
4925 }
4926 item.disconnect( this, remove );
4927 }
4928 item.setElementGroup( null );
4929 this.items.splice( index, 1 );
4930 item.$element.detach();
4931 }
4932 }
4933
4934 return this;
4935 };
4936
4937 /**
4938 * Clear all items from the group.
4939 *
4940 * Cleared items are detached from the DOM, not removed, so that they may be reused.
4941 * To remove only a subset of items from a group, use the #removeItems method.
4942 *
4943 * @chainable
4944 */
4945 OO.ui.mixin.GroupElement.prototype.clearItems = function () {
4946 var i, len, item, remove, itemEvent;
4947
4948 // Remove all items
4949 for ( i = 0, len = this.items.length; i < len; i++ ) {
4950 item = this.items[ i ];
4951 if (
4952 item.connect && item.disconnect &&
4953 !$.isEmptyObject( this.aggregateItemEvents )
4954 ) {
4955 remove = {};
4956 if ( Object.prototype.hasOwnProperty.call( this.aggregateItemEvents, itemEvent ) ) {
4957 remove[ itemEvent ] = [ 'emit', this.aggregateItemEvents[ itemEvent ], item ];
4958 }
4959 item.disconnect( this, remove );
4960 }
4961 item.setElementGroup( null );
4962 item.$element.detach();
4963 }
4964
4965 this.items = [];
4966 return this;
4967 };
4968
4969 /**
4970 * DraggableElement is a mixin class used to create elements that can be clicked
4971 * and dragged by a mouse to a new position within a group. This class must be used
4972 * in conjunction with OO.ui.mixin.DraggableGroupElement, which provides a container for
4973 * the draggable elements.
4974 *
4975 * @abstract
4976 * @class
4977 *
4978 * @constructor
4979 */
4980 OO.ui.mixin.DraggableElement = function OoUiMixinDraggableElement() {
4981 // Properties
4982 this.index = null;
4983
4984 // Initialize and events
4985 this.$element
4986 .attr( 'draggable', true )
4987 .addClass( 'oo-ui-draggableElement' )
4988 .on( {
4989 dragstart: this.onDragStart.bind( this ),
4990 dragover: this.onDragOver.bind( this ),
4991 dragend: this.onDragEnd.bind( this ),
4992 drop: this.onDrop.bind( this )
4993 } );
4994 };
4995
4996 OO.initClass( OO.ui.mixin.DraggableElement );
4997
4998 /* Events */
4999
5000 /**
5001 * @event dragstart
5002 *
5003 * A dragstart event is emitted when the user clicks and begins dragging an item.
5004 * @param {OO.ui.mixin.DraggableElement} item The item the user has clicked and is dragging with the mouse.
5005 */
5006
5007 /**
5008 * @event dragend
5009 * A dragend event is emitted when the user drags an item and releases the mouse,
5010 * thus terminating the drag operation.
5011 */
5012
5013 /**
5014 * @event drop
5015 * A drop event is emitted when the user drags an item and then releases the mouse button
5016 * over a valid target.
5017 */
5018
5019 /* Static Properties */
5020
5021 /**
5022 * @inheritdoc OO.ui.mixin.ButtonElement
5023 */
5024 OO.ui.mixin.DraggableElement.static.cancelButtonMouseDownEvents = false;
5025
5026 /* Methods */
5027
5028 /**
5029 * Respond to dragstart event.
5030 *
5031 * @private
5032 * @param {jQuery.Event} event jQuery event
5033 * @fires dragstart
5034 */
5035 OO.ui.mixin.DraggableElement.prototype.onDragStart = function ( e ) {
5036 var dataTransfer = e.originalEvent.dataTransfer;
5037 // Define drop effect
5038 dataTransfer.dropEffect = 'none';
5039 dataTransfer.effectAllowed = 'move';
5040 // Support: Firefox
5041 // We must set up a dataTransfer data property or Firefox seems to
5042 // ignore the fact the element is draggable.
5043 try {
5044 dataTransfer.setData( 'application-x/OOjs-UI-draggable', this.getIndex() );
5045 } catch ( err ) {
5046 // The above is only for Firefox. Move on if it fails.
5047 }
5048 // Add dragging class
5049 this.$element.addClass( 'oo-ui-draggableElement-dragging' );
5050 // Emit event
5051 this.emit( 'dragstart', this );
5052 return true;
5053 };
5054
5055 /**
5056 * Respond to dragend event.
5057 *
5058 * @private
5059 * @fires dragend
5060 */
5061 OO.ui.mixin.DraggableElement.prototype.onDragEnd = function () {
5062 this.$element.removeClass( 'oo-ui-draggableElement-dragging' );
5063 this.emit( 'dragend' );
5064 };
5065
5066 /**
5067 * Handle drop event.
5068 *
5069 * @private
5070 * @param {jQuery.Event} event jQuery event
5071 * @fires drop
5072 */
5073 OO.ui.mixin.DraggableElement.prototype.onDrop = function ( e ) {
5074 e.preventDefault();
5075 this.emit( 'drop', e );
5076 };
5077
5078 /**
5079 * In order for drag/drop to work, the dragover event must
5080 * return false and stop propogation.
5081 *
5082 * @private
5083 */
5084 OO.ui.mixin.DraggableElement.prototype.onDragOver = function ( e ) {
5085 e.preventDefault();
5086 };
5087
5088 /**
5089 * Set item index.
5090 * Store it in the DOM so we can access from the widget drag event
5091 *
5092 * @private
5093 * @param {number} Item index
5094 */
5095 OO.ui.mixin.DraggableElement.prototype.setIndex = function ( index ) {
5096 if ( this.index !== index ) {
5097 this.index = index;
5098 this.$element.data( 'index', index );
5099 }
5100 };
5101
5102 /**
5103 * Get item index
5104 *
5105 * @private
5106 * @return {number} Item index
5107 */
5108 OO.ui.mixin.DraggableElement.prototype.getIndex = function () {
5109 return this.index;
5110 };
5111
5112 /**
5113 * DraggableGroupElement is a mixin class used to create a group element to
5114 * contain draggable elements, which are items that can be clicked and dragged by a mouse.
5115 * The class is used with OO.ui.mixin.DraggableElement.
5116 *
5117 * @abstract
5118 * @class
5119 * @mixins OO.ui.mixin.GroupElement
5120 *
5121 * @constructor
5122 * @param {Object} [config] Configuration options
5123 * @cfg {string} [orientation] Item orientation: 'horizontal' or 'vertical'. The orientation
5124 * should match the layout of the items. Items displayed in a single row
5125 * or in several rows should use horizontal orientation. The vertical orientation should only be
5126 * used when the items are displayed in a single column. Defaults to 'vertical'
5127 */
5128 OO.ui.mixin.DraggableGroupElement = function OoUiMixinDraggableGroupElement( config ) {
5129 // Configuration initialization
5130 config = config || {};
5131
5132 // Parent constructor
5133 OO.ui.mixin.GroupElement.call( this, config );
5134
5135 // Properties
5136 this.orientation = config.orientation || 'vertical';
5137 this.dragItem = null;
5138 this.itemDragOver = null;
5139 this.itemKeys = {};
5140 this.sideInsertion = '';
5141
5142 // Events
5143 this.aggregate( {
5144 dragstart: 'itemDragStart',
5145 dragend: 'itemDragEnd',
5146 drop: 'itemDrop'
5147 } );
5148 this.connect( this, {
5149 itemDragStart: 'onItemDragStart',
5150 itemDrop: 'onItemDrop',
5151 itemDragEnd: 'onItemDragEnd'
5152 } );
5153 this.$element.on( {
5154 dragover: this.onDragOver.bind( this ),
5155 dragleave: this.onDragLeave.bind( this )
5156 } );
5157
5158 // Initialize
5159 if ( Array.isArray( config.items ) ) {
5160 this.addItems( config.items );
5161 }
5162 this.$placeholder = $( '<div>' )
5163 .addClass( 'oo-ui-draggableGroupElement-placeholder' );
5164 this.$element
5165 .addClass( 'oo-ui-draggableGroupElement' )
5166 .append( this.$status )
5167 .toggleClass( 'oo-ui-draggableGroupElement-horizontal', this.orientation === 'horizontal' )
5168 .prepend( this.$placeholder );
5169 };
5170
5171 /* Setup */
5172 OO.mixinClass( OO.ui.mixin.DraggableGroupElement, OO.ui.mixin.GroupElement );
5173
5174 /* Events */
5175
5176 /**
5177 * A 'reorder' event is emitted when the order of items in the group changes.
5178 *
5179 * @event reorder
5180 * @param {OO.ui.mixin.DraggableElement} item Reordered item
5181 * @param {number} [newIndex] New index for the item
5182 */
5183
5184 /* Methods */
5185
5186 /**
5187 * Respond to item drag start event
5188 *
5189 * @private
5190 * @param {OO.ui.mixin.DraggableElement} item Dragged item
5191 */
5192 OO.ui.mixin.DraggableGroupElement.prototype.onItemDragStart = function ( item ) {
5193 var i, len;
5194
5195 // Map the index of each object
5196 for ( i = 0, len = this.items.length; i < len; i++ ) {
5197 this.items[ i ].setIndex( i );
5198 }
5199
5200 if ( this.orientation === 'horizontal' ) {
5201 // Set the height of the indicator
5202 this.$placeholder.css( {
5203 height: item.$element.outerHeight(),
5204 width: 2
5205 } );
5206 } else {
5207 // Set the width of the indicator
5208 this.$placeholder.css( {
5209 height: 2,
5210 width: item.$element.outerWidth()
5211 } );
5212 }
5213 this.setDragItem( item );
5214 };
5215
5216 /**
5217 * Respond to item drag end event
5218 *
5219 * @private
5220 */
5221 OO.ui.mixin.DraggableGroupElement.prototype.onItemDragEnd = function () {
5222 this.unsetDragItem();
5223 return false;
5224 };
5225
5226 /**
5227 * Handle drop event and switch the order of the items accordingly
5228 *
5229 * @private
5230 * @param {OO.ui.mixin.DraggableElement} item Dropped item
5231 * @fires reorder
5232 */
5233 OO.ui.mixin.DraggableGroupElement.prototype.onItemDrop = function ( item ) {
5234 var toIndex = item.getIndex();
5235 // Check if the dropped item is from the current group
5236 // TODO: Figure out a way to configure a list of legally droppable
5237 // elements even if they are not yet in the list
5238 if ( this.getDragItem() ) {
5239 // If the insertion point is 'after', the insertion index
5240 // is shifted to the right (or to the left in RTL, hence 'after')
5241 if ( this.sideInsertion === 'after' ) {
5242 toIndex++;
5243 }
5244 // Emit change event
5245 this.emit( 'reorder', this.getDragItem(), toIndex );
5246 }
5247 this.unsetDragItem();
5248 // Return false to prevent propogation
5249 return false;
5250 };
5251
5252 /**
5253 * Handle dragleave event.
5254 *
5255 * @private
5256 */
5257 OO.ui.mixin.DraggableGroupElement.prototype.onDragLeave = function () {
5258 // This means the item was dragged outside the widget
5259 this.$placeholder
5260 .css( 'left', 0 )
5261 .addClass( 'oo-ui-element-hidden' );
5262 };
5263
5264 /**
5265 * Respond to dragover event
5266 *
5267 * @private
5268 * @param {jQuery.Event} event Event details
5269 */
5270 OO.ui.mixin.DraggableGroupElement.prototype.onDragOver = function ( e ) {
5271 var dragOverObj, $optionWidget, itemOffset, itemMidpoint, itemBoundingRect,
5272 itemSize, cssOutput, dragPosition, itemIndex, itemPosition,
5273 clientX = e.originalEvent.clientX,
5274 clientY = e.originalEvent.clientY;
5275
5276 // Get the OptionWidget item we are dragging over
5277 dragOverObj = this.getElementDocument().elementFromPoint( clientX, clientY );
5278 $optionWidget = $( dragOverObj ).closest( '.oo-ui-draggableElement' );
5279 if ( $optionWidget[ 0 ] ) {
5280 itemOffset = $optionWidget.offset();
5281 itemBoundingRect = $optionWidget[ 0 ].getBoundingClientRect();
5282 itemPosition = $optionWidget.position();
5283 itemIndex = $optionWidget.data( 'index' );
5284 }
5285
5286 if (
5287 itemOffset &&
5288 this.isDragging() &&
5289 itemIndex !== this.getDragItem().getIndex()
5290 ) {
5291 if ( this.orientation === 'horizontal' ) {
5292 // Calculate where the mouse is relative to the item width
5293 itemSize = itemBoundingRect.width;
5294 itemMidpoint = itemBoundingRect.left + itemSize / 2;
5295 dragPosition = clientX;
5296 // Which side of the item we hover over will dictate
5297 // where the placeholder will appear, on the left or
5298 // on the right
5299 cssOutput = {
5300 left: dragPosition < itemMidpoint ? itemPosition.left : itemPosition.left + itemSize,
5301 top: itemPosition.top
5302 };
5303 } else {
5304 // Calculate where the mouse is relative to the item height
5305 itemSize = itemBoundingRect.height;
5306 itemMidpoint = itemBoundingRect.top + itemSize / 2;
5307 dragPosition = clientY;
5308 // Which side of the item we hover over will dictate
5309 // where the placeholder will appear, on the top or
5310 // on the bottom
5311 cssOutput = {
5312 top: dragPosition < itemMidpoint ? itemPosition.top : itemPosition.top + itemSize,
5313 left: itemPosition.left
5314 };
5315 }
5316 // Store whether we are before or after an item to rearrange
5317 // For horizontal layout, we need to account for RTL, as this is flipped
5318 if ( this.orientation === 'horizontal' && this.$element.css( 'direction' ) === 'rtl' ) {
5319 this.sideInsertion = dragPosition < itemMidpoint ? 'after' : 'before';
5320 } else {
5321 this.sideInsertion = dragPosition < itemMidpoint ? 'before' : 'after';
5322 }
5323 // Add drop indicator between objects
5324 this.$placeholder
5325 .css( cssOutput )
5326 .removeClass( 'oo-ui-element-hidden' );
5327 } else {
5328 // This means the item was dragged outside the widget
5329 this.$placeholder
5330 .css( 'left', 0 )
5331 .addClass( 'oo-ui-element-hidden' );
5332 }
5333 // Prevent default
5334 e.preventDefault();
5335 };
5336
5337 /**
5338 * Set a dragged item
5339 *
5340 * @param {OO.ui.mixin.DraggableElement} item Dragged item
5341 */
5342 OO.ui.mixin.DraggableGroupElement.prototype.setDragItem = function ( item ) {
5343 this.dragItem = item;
5344 };
5345
5346 /**
5347 * Unset the current dragged item
5348 */
5349 OO.ui.mixin.DraggableGroupElement.prototype.unsetDragItem = function () {
5350 this.dragItem = null;
5351 this.itemDragOver = null;
5352 this.$placeholder.addClass( 'oo-ui-element-hidden' );
5353 this.sideInsertion = '';
5354 };
5355
5356 /**
5357 * Get the item that is currently being dragged.
5358 *
5359 * @return {OO.ui.mixin.DraggableElement|null} The currently dragged item, or `null` if no item is being dragged
5360 */
5361 OO.ui.mixin.DraggableGroupElement.prototype.getDragItem = function () {
5362 return this.dragItem;
5363 };
5364
5365 /**
5366 * Check if an item in the group is currently being dragged.
5367 *
5368 * @return {Boolean} Item is being dragged
5369 */
5370 OO.ui.mixin.DraggableGroupElement.prototype.isDragging = function () {
5371 return this.getDragItem() !== null;
5372 };
5373
5374 /**
5375 * IconElement is often mixed into other classes to generate an icon.
5376 * Icons are graphics, about the size of normal text. They are used to aid the user
5377 * in locating a control or to convey information in a space-efficient way. See the
5378 * [OOjs UI documentation on MediaWiki] [1] for a list of icons
5379 * included in the library.
5380 *
5381 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
5382 *
5383 * @abstract
5384 * @class
5385 *
5386 * @constructor
5387 * @param {Object} [config] Configuration options
5388 * @cfg {jQuery} [$icon] The icon element created by the class. If this configuration is omitted,
5389 * the icon element will use a generated `<span>`. To use a different HTML tag, or to specify that
5390 * the icon element be set to an existing icon instead of the one generated by this class, set a
5391 * value using a jQuery selection. For example:
5392 *
5393 * // Use a <div> tag instead of a <span>
5394 * $icon: $("<div>")
5395 * // Use an existing icon element instead of the one generated by the class
5396 * $icon: this.$element
5397 * // Use an icon element from a child widget
5398 * $icon: this.childwidget.$element
5399 * @cfg {Object|string} [icon=''] The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of
5400 * symbolic names. A map is used for i18n purposes and contains a `default` icon
5401 * name and additional names keyed by language code. The `default` name is used when no icon is keyed
5402 * by the user's language.
5403 *
5404 * Example of an i18n map:
5405 *
5406 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
5407 * See the [OOjs UI documentation on MediaWiki] [2] for a list of icons included in the library.
5408 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
5409 * @cfg {string|Function} [iconTitle] A text string used as the icon title, or a function that returns title
5410 * text. The icon title is displayed when users move the mouse over the icon.
5411 */
5412 OO.ui.mixin.IconElement = function OoUiMixinIconElement( config ) {
5413 // Configuration initialization
5414 config = config || {};
5415
5416 // Properties
5417 this.$icon = null;
5418 this.icon = null;
5419 this.iconTitle = null;
5420
5421 // Initialization
5422 this.setIcon( config.icon || this.constructor.static.icon );
5423 this.setIconTitle( config.iconTitle || this.constructor.static.iconTitle );
5424 this.setIconElement( config.$icon || $( '<span>' ) );
5425 };
5426
5427 /* Setup */
5428
5429 OO.initClass( OO.ui.mixin.IconElement );
5430
5431 /* Static Properties */
5432
5433 /**
5434 * The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of symbolic names. A map is used
5435 * for i18n purposes and contains a `default` icon name and additional names keyed by
5436 * language code. The `default` name is used when no icon is keyed by the user's language.
5437 *
5438 * Example of an i18n map:
5439 *
5440 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
5441 *
5442 * Note: the static property will be overridden if the #icon configuration is used.
5443 *
5444 * @static
5445 * @inheritable
5446 * @property {Object|string}
5447 */
5448 OO.ui.mixin.IconElement.static.icon = null;
5449
5450 /**
5451 * The icon title, displayed when users move the mouse over the icon. The value can be text, a
5452 * function that returns title text, or `null` for no title.
5453 *
5454 * The static property will be overridden if the #iconTitle configuration is used.
5455 *
5456 * @static
5457 * @inheritable
5458 * @property {string|Function|null}
5459 */
5460 OO.ui.mixin.IconElement.static.iconTitle = null;
5461
5462 /* Methods */
5463
5464 /**
5465 * Set the icon element. This method is used to retarget an icon mixin so that its functionality
5466 * applies to the specified icon element instead of the one created by the class. If an icon
5467 * element is already set, the mixin’s effect on that element is removed. Generated CSS classes
5468 * and mixin methods will no longer affect the element.
5469 *
5470 * @param {jQuery} $icon Element to use as icon
5471 */
5472 OO.ui.mixin.IconElement.prototype.setIconElement = function ( $icon ) {
5473 if ( this.$icon ) {
5474 this.$icon
5475 .removeClass( 'oo-ui-iconElement-icon oo-ui-icon-' + this.icon )
5476 .removeAttr( 'title' );
5477 }
5478
5479 this.$icon = $icon
5480 .addClass( 'oo-ui-iconElement-icon' )
5481 .toggleClass( 'oo-ui-icon-' + this.icon, !!this.icon );
5482 if ( this.iconTitle !== null ) {
5483 this.$icon.attr( 'title', this.iconTitle );
5484 }
5485
5486 this.updateThemeClasses();
5487 };
5488
5489 /**
5490 * Set icon by symbolic name (e.g., ‘remove’ or ‘menu’). Use `null` to remove an icon.
5491 * The icon parameter can also be set to a map of icon names. See the #icon config setting
5492 * for an example.
5493 *
5494 * @param {Object|string|null} icon A symbolic icon name, a {@link #icon map of icon names} keyed
5495 * by language code, or `null` to remove the icon.
5496 * @chainable
5497 */
5498 OO.ui.mixin.IconElement.prototype.setIcon = function ( icon ) {
5499 icon = OO.isPlainObject( icon ) ? OO.ui.getLocalValue( icon, null, 'default' ) : icon;
5500 icon = typeof icon === 'string' && icon.trim().length ? icon.trim() : null;
5501
5502 if ( this.icon !== icon ) {
5503 if ( this.$icon ) {
5504 if ( this.icon !== null ) {
5505 this.$icon.removeClass( 'oo-ui-icon-' + this.icon );
5506 }
5507 if ( icon !== null ) {
5508 this.$icon.addClass( 'oo-ui-icon-' + icon );
5509 }
5510 }
5511 this.icon = icon;
5512 }
5513
5514 this.$element.toggleClass( 'oo-ui-iconElement', !!this.icon );
5515 this.updateThemeClasses();
5516
5517 return this;
5518 };
5519
5520 /**
5521 * Set the icon title. Use `null` to remove the title.
5522 *
5523 * @param {string|Function|null} iconTitle A text string used as the icon title,
5524 * a function that returns title text, or `null` for no title.
5525 * @chainable
5526 */
5527 OO.ui.mixin.IconElement.prototype.setIconTitle = function ( iconTitle ) {
5528 iconTitle = typeof iconTitle === 'function' ||
5529 ( typeof iconTitle === 'string' && iconTitle.length ) ?
5530 OO.ui.resolveMsg( iconTitle ) : null;
5531
5532 if ( this.iconTitle !== iconTitle ) {
5533 this.iconTitle = iconTitle;
5534 if ( this.$icon ) {
5535 if ( this.iconTitle !== null ) {
5536 this.$icon.attr( 'title', iconTitle );
5537 } else {
5538 this.$icon.removeAttr( 'title' );
5539 }
5540 }
5541 }
5542
5543 return this;
5544 };
5545
5546 /**
5547 * Get the symbolic name of the icon.
5548 *
5549 * @return {string} Icon name
5550 */
5551 OO.ui.mixin.IconElement.prototype.getIcon = function () {
5552 return this.icon;
5553 };
5554
5555 /**
5556 * Get the icon title. The title text is displayed when a user moves the mouse over the icon.
5557 *
5558 * @return {string} Icon title text
5559 */
5560 OO.ui.mixin.IconElement.prototype.getIconTitle = function () {
5561 return this.iconTitle;
5562 };
5563
5564 /**
5565 * IndicatorElement is often mixed into other classes to generate an indicator.
5566 * Indicators are small graphics that are generally used in two ways:
5567 *
5568 * - To draw attention to the status of an item. For example, an indicator might be
5569 * used to show that an item in a list has errors that need to be resolved.
5570 * - To clarify the function of a control that acts in an exceptional way (a button
5571 * that opens a menu instead of performing an action directly, for example).
5572 *
5573 * For a list of indicators included in the library, please see the
5574 * [OOjs UI documentation on MediaWiki] [1].
5575 *
5576 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
5577 *
5578 * @abstract
5579 * @class
5580 *
5581 * @constructor
5582 * @param {Object} [config] Configuration options
5583 * @cfg {jQuery} [$indicator] The indicator element created by the class. If this
5584 * configuration is omitted, the indicator element will use a generated `<span>`.
5585 * @cfg {string} [indicator] Symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
5586 * See the [OOjs UI documentation on MediaWiki][2] for a list of indicators included
5587 * in the library.
5588 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
5589 * @cfg {string|Function} [indicatorTitle] A text string used as the indicator title,
5590 * or a function that returns title text. The indicator title is displayed when users move
5591 * the mouse over the indicator.
5592 */
5593 OO.ui.mixin.IndicatorElement = function OoUiMixinIndicatorElement( config ) {
5594 // Configuration initialization
5595 config = config || {};
5596
5597 // Properties
5598 this.$indicator = null;
5599 this.indicator = null;
5600 this.indicatorTitle = null;
5601
5602 // Initialization
5603 this.setIndicator( config.indicator || this.constructor.static.indicator );
5604 this.setIndicatorTitle( config.indicatorTitle || this.constructor.static.indicatorTitle );
5605 this.setIndicatorElement( config.$indicator || $( '<span>' ) );
5606 };
5607
5608 /* Setup */
5609
5610 OO.initClass( OO.ui.mixin.IndicatorElement );
5611
5612 /* Static Properties */
5613
5614 /**
5615 * Symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
5616 * The static property will be overridden if the #indicator configuration is used.
5617 *
5618 * @static
5619 * @inheritable
5620 * @property {string|null}
5621 */
5622 OO.ui.mixin.IndicatorElement.static.indicator = null;
5623
5624 /**
5625 * A text string used as the indicator title, a function that returns title text, or `null`
5626 * for no title. The static property will be overridden if the #indicatorTitle configuration is used.
5627 *
5628 * @static
5629 * @inheritable
5630 * @property {string|Function|null}
5631 */
5632 OO.ui.mixin.IndicatorElement.static.indicatorTitle = null;
5633
5634 /* Methods */
5635
5636 /**
5637 * Set the indicator element.
5638 *
5639 * If an element is already set, it will be cleaned up before setting up the new element.
5640 *
5641 * @param {jQuery} $indicator Element to use as indicator
5642 */
5643 OO.ui.mixin.IndicatorElement.prototype.setIndicatorElement = function ( $indicator ) {
5644 if ( this.$indicator ) {
5645 this.$indicator
5646 .removeClass( 'oo-ui-indicatorElement-indicator oo-ui-indicator-' + this.indicator )
5647 .removeAttr( 'title' );
5648 }
5649
5650 this.$indicator = $indicator
5651 .addClass( 'oo-ui-indicatorElement-indicator' )
5652 .toggleClass( 'oo-ui-indicator-' + this.indicator, !!this.indicator );
5653 if ( this.indicatorTitle !== null ) {
5654 this.$indicator.attr( 'title', this.indicatorTitle );
5655 }
5656
5657 this.updateThemeClasses();
5658 };
5659
5660 /**
5661 * Set the indicator by its symbolic name: ‘alert’, ‘down’, ‘next’, ‘previous’, ‘required’, ‘up’. Use `null` to remove the indicator.
5662 *
5663 * @param {string|null} indicator Symbolic name of indicator, or `null` for no indicator
5664 * @chainable
5665 */
5666 OO.ui.mixin.IndicatorElement.prototype.setIndicator = function ( indicator ) {
5667 indicator = typeof indicator === 'string' && indicator.length ? indicator.trim() : null;
5668
5669 if ( this.indicator !== indicator ) {
5670 if ( this.$indicator ) {
5671 if ( this.indicator !== null ) {
5672 this.$indicator.removeClass( 'oo-ui-indicator-' + this.indicator );
5673 }
5674 if ( indicator !== null ) {
5675 this.$indicator.addClass( 'oo-ui-indicator-' + indicator );
5676 }
5677 }
5678 this.indicator = indicator;
5679 }
5680
5681 this.$element.toggleClass( 'oo-ui-indicatorElement', !!this.indicator );
5682 this.updateThemeClasses();
5683
5684 return this;
5685 };
5686
5687 /**
5688 * Set the indicator title.
5689 *
5690 * The title is displayed when a user moves the mouse over the indicator.
5691 *
5692 * @param {string|Function|null} indicator Indicator title text, a function that returns text, or
5693 * `null` for no indicator title
5694 * @chainable
5695 */
5696 OO.ui.mixin.IndicatorElement.prototype.setIndicatorTitle = function ( indicatorTitle ) {
5697 indicatorTitle = typeof indicatorTitle === 'function' ||
5698 ( typeof indicatorTitle === 'string' && indicatorTitle.length ) ?
5699 OO.ui.resolveMsg( indicatorTitle ) : null;
5700
5701 if ( this.indicatorTitle !== indicatorTitle ) {
5702 this.indicatorTitle = indicatorTitle;
5703 if ( this.$indicator ) {
5704 if ( this.indicatorTitle !== null ) {
5705 this.$indicator.attr( 'title', indicatorTitle );
5706 } else {
5707 this.$indicator.removeAttr( 'title' );
5708 }
5709 }
5710 }
5711
5712 return this;
5713 };
5714
5715 /**
5716 * Get the symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
5717 *
5718 * @return {string} Symbolic name of indicator
5719 */
5720 OO.ui.mixin.IndicatorElement.prototype.getIndicator = function () {
5721 return this.indicator;
5722 };
5723
5724 /**
5725 * Get the indicator title.
5726 *
5727 * The title is displayed when a user moves the mouse over the indicator.
5728 *
5729 * @return {string} Indicator title text
5730 */
5731 OO.ui.mixin.IndicatorElement.prototype.getIndicatorTitle = function () {
5732 return this.indicatorTitle;
5733 };
5734
5735 /**
5736 * LabelElement is often mixed into other classes to generate a label, which
5737 * helps identify the function of an interface element.
5738 * See the [OOjs UI documentation on MediaWiki] [1] for more information.
5739 *
5740 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Labels
5741 *
5742 * @abstract
5743 * @class
5744 *
5745 * @constructor
5746 * @param {Object} [config] Configuration options
5747 * @cfg {jQuery} [$label] The label element created by the class. If this
5748 * configuration is omitted, the label element will use a generated `<span>`.
5749 * @cfg {jQuery|string|Function|OO.ui.HtmlSnippet} [label] The label text. The label can be specified
5750 * as a plaintext string, a jQuery selection of elements, or a function that will produce a string
5751 * in the future. See the [OOjs UI documentation on MediaWiki] [2] for examples.
5752 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Labels
5753 * @cfg {boolean} [autoFitLabel=true] Fit the label to the width of the parent element.
5754 * The label will be truncated to fit if necessary.
5755 */
5756 OO.ui.mixin.LabelElement = function OoUiMixinLabelElement( config ) {
5757 // Configuration initialization
5758 config = config || {};
5759
5760 // Properties
5761 this.$label = null;
5762 this.label = null;
5763 this.autoFitLabel = config.autoFitLabel === undefined || !!config.autoFitLabel;
5764
5765 // Initialization
5766 this.setLabel( config.label || this.constructor.static.label );
5767 this.setLabelElement( config.$label || $( '<span>' ) );
5768 };
5769
5770 /* Setup */
5771
5772 OO.initClass( OO.ui.mixin.LabelElement );
5773
5774 /* Events */
5775
5776 /**
5777 * @event labelChange
5778 * @param {string} value
5779 */
5780
5781 /* Static Properties */
5782
5783 /**
5784 * The label text. The label can be specified as a plaintext string, a function that will
5785 * produce a string in the future, or `null` for no label. The static value will
5786 * be overridden if a label is specified with the #label config option.
5787 *
5788 * @static
5789 * @inheritable
5790 * @property {string|Function|null}
5791 */
5792 OO.ui.mixin.LabelElement.static.label = null;
5793
5794 /* Methods */
5795
5796 /**
5797 * Set the label element.
5798 *
5799 * If an element is already set, it will be cleaned up before setting up the new element.
5800 *
5801 * @param {jQuery} $label Element to use as label
5802 */
5803 OO.ui.mixin.LabelElement.prototype.setLabelElement = function ( $label ) {
5804 if ( this.$label ) {
5805 this.$label.removeClass( 'oo-ui-labelElement-label' ).empty();
5806 }
5807
5808 this.$label = $label.addClass( 'oo-ui-labelElement-label' );
5809 this.setLabelContent( this.label );
5810 };
5811
5812 /**
5813 * Set the label.
5814 *
5815 * An empty string will result in the label being hidden. A string containing only whitespace will
5816 * be converted to a single `&nbsp;`.
5817 *
5818 * @param {jQuery|string|OO.ui.HtmlSnippet|Function|null} label Label nodes; text; a function that returns nodes or
5819 * text; or null for no label
5820 * @chainable
5821 */
5822 OO.ui.mixin.LabelElement.prototype.setLabel = function ( label ) {
5823 label = typeof label === 'function' ? OO.ui.resolveMsg( label ) : label;
5824 label = ( ( typeof label === 'string' && label.length ) || label instanceof jQuery || label instanceof OO.ui.HtmlSnippet ) ? label : null;
5825
5826 this.$element.toggleClass( 'oo-ui-labelElement', !!label );
5827
5828 if ( this.label !== label ) {
5829 if ( this.$label ) {
5830 this.setLabelContent( label );
5831 }
5832 this.label = label;
5833 this.emit( 'labelChange' );
5834 }
5835
5836 return this;
5837 };
5838
5839 /**
5840 * Get the label.
5841 *
5842 * @return {jQuery|string|Function|null} Label nodes; text; a function that returns nodes or
5843 * text; or null for no label
5844 */
5845 OO.ui.mixin.LabelElement.prototype.getLabel = function () {
5846 return this.label;
5847 };
5848
5849 /**
5850 * Fit the label.
5851 *
5852 * @chainable
5853 */
5854 OO.ui.mixin.LabelElement.prototype.fitLabel = function () {
5855 if ( this.$label && this.$label.autoEllipsis && this.autoFitLabel ) {
5856 this.$label.autoEllipsis( { hasSpan: false, tooltip: true } );
5857 }
5858
5859 return this;
5860 };
5861
5862 /**
5863 * Set the content of the label.
5864 *
5865 * Do not call this method until after the label element has been set by #setLabelElement.
5866 *
5867 * @private
5868 * @param {jQuery|string|Function|null} label Label nodes; text; a function that returns nodes or
5869 * text; or null for no label
5870 */
5871 OO.ui.mixin.LabelElement.prototype.setLabelContent = function ( label ) {
5872 if ( typeof label === 'string' ) {
5873 if ( label.match( /^\s*$/ ) ) {
5874 // Convert whitespace only string to a single non-breaking space
5875 this.$label.html( '&nbsp;' );
5876 } else {
5877 this.$label.text( label );
5878 }
5879 } else if ( label instanceof OO.ui.HtmlSnippet ) {
5880 this.$label.html( label.toString() );
5881 } else if ( label instanceof jQuery ) {
5882 this.$label.empty().append( label );
5883 } else {
5884 this.$label.empty();
5885 }
5886 };
5887
5888 /**
5889 * LookupElement is a mixin that creates a {@link OO.ui.FloatingMenuSelectWidget menu} of suggested values for
5890 * a {@link OO.ui.TextInputWidget text input widget}. Suggested values are based on the characters the user types
5891 * into the text input field and, in general, the menu is only displayed when the user types. If a suggested value is chosen
5892 * from the lookup menu, that value becomes the value of the input field.
5893 *
5894 * Note that a new menu of suggested items is displayed when a value is chosen from the lookup menu. If this is
5895 * not the desired behavior, disable lookup menus with the #setLookupsDisabled method, then set the value, then
5896 * re-enable lookups.
5897 *
5898 * See the [OOjs UI demos][1] for an example.
5899 *
5900 * [1]: https://tools.wmflabs.org/oojs-ui/oojs-ui/demos/index.html#widgets-apex-vector-ltr
5901 *
5902 * @class
5903 * @abstract
5904 *
5905 * @constructor
5906 * @param {Object} [config] Configuration options
5907 * @cfg {jQuery} [$overlay] Overlay for the lookup menu; defaults to relative positioning
5908 * @cfg {jQuery} [$container=this.$element] The container element. The lookup menu is rendered beneath the specified element.
5909 * @cfg {boolean} [allowSuggestionsWhenEmpty=false] Request and display a lookup menu when the text input is empty.
5910 * By default, the lookup menu is not generated and displayed until the user begins to type.
5911 */
5912 OO.ui.mixin.LookupElement = function OoUiMixinLookupElement( config ) {
5913 // Configuration initialization
5914 config = config || {};
5915
5916 // Properties
5917 this.$overlay = config.$overlay || this.$element;
5918 this.lookupMenu = new OO.ui.FloatingMenuSelectWidget( {
5919 widget: this,
5920 input: this,
5921 $container: config.$container || this.$element
5922 } );
5923
5924 this.allowSuggestionsWhenEmpty = config.allowSuggestionsWhenEmpty || false;
5925
5926 this.lookupCache = {};
5927 this.lookupQuery = null;
5928 this.lookupRequest = null;
5929 this.lookupsDisabled = false;
5930 this.lookupInputFocused = false;
5931
5932 // Events
5933 this.$input.on( {
5934 focus: this.onLookupInputFocus.bind( this ),
5935 blur: this.onLookupInputBlur.bind( this ),
5936 mousedown: this.onLookupInputMouseDown.bind( this )
5937 } );
5938 this.connect( this, { change: 'onLookupInputChange' } );
5939 this.lookupMenu.connect( this, {
5940 toggle: 'onLookupMenuToggle',
5941 choose: 'onLookupMenuItemChoose'
5942 } );
5943
5944 // Initialization
5945 this.$element.addClass( 'oo-ui-lookupElement' );
5946 this.lookupMenu.$element.addClass( 'oo-ui-lookupElement-menu' );
5947 this.$overlay.append( this.lookupMenu.$element );
5948 };
5949
5950 /* Methods */
5951
5952 /**
5953 * Handle input focus event.
5954 *
5955 * @protected
5956 * @param {jQuery.Event} e Input focus event
5957 */
5958 OO.ui.mixin.LookupElement.prototype.onLookupInputFocus = function () {
5959 this.lookupInputFocused = true;
5960 this.populateLookupMenu();
5961 };
5962
5963 /**
5964 * Handle input blur event.
5965 *
5966 * @protected
5967 * @param {jQuery.Event} e Input blur event
5968 */
5969 OO.ui.mixin.LookupElement.prototype.onLookupInputBlur = function () {
5970 this.closeLookupMenu();
5971 this.lookupInputFocused = false;
5972 };
5973
5974 /**
5975 * Handle input mouse down event.
5976 *
5977 * @protected
5978 * @param {jQuery.Event} e Input mouse down event
5979 */
5980 OO.ui.mixin.LookupElement.prototype.onLookupInputMouseDown = function () {
5981 // Only open the menu if the input was already focused.
5982 // This way we allow the user to open the menu again after closing it with Esc
5983 // by clicking in the input. Opening (and populating) the menu when initially
5984 // clicking into the input is handled by the focus handler.
5985 if ( this.lookupInputFocused && !this.lookupMenu.isVisible() ) {
5986 this.populateLookupMenu();
5987 }
5988 };
5989
5990 /**
5991 * Handle input change event.
5992 *
5993 * @protected
5994 * @param {string} value New input value
5995 */
5996 OO.ui.mixin.LookupElement.prototype.onLookupInputChange = function () {
5997 if ( this.lookupInputFocused ) {
5998 this.populateLookupMenu();
5999 }
6000 };
6001
6002 /**
6003 * Handle the lookup menu being shown/hidden.
6004 *
6005 * @protected
6006 * @param {boolean} visible Whether the lookup menu is now visible.
6007 */
6008 OO.ui.mixin.LookupElement.prototype.onLookupMenuToggle = function ( visible ) {
6009 if ( !visible ) {
6010 // When the menu is hidden, abort any active request and clear the menu.
6011 // This has to be done here in addition to closeLookupMenu(), because
6012 // MenuSelectWidget will close itself when the user presses Esc.
6013 this.abortLookupRequest();
6014 this.lookupMenu.clearItems();
6015 }
6016 };
6017
6018 /**
6019 * Handle menu item 'choose' event, updating the text input value to the value of the clicked item.
6020 *
6021 * @protected
6022 * @param {OO.ui.MenuOptionWidget} item Selected item
6023 */
6024 OO.ui.mixin.LookupElement.prototype.onLookupMenuItemChoose = function ( item ) {
6025 this.setValue( item.getData() );
6026 };
6027
6028 /**
6029 * Get lookup menu.
6030 *
6031 * @private
6032 * @return {OO.ui.FloatingMenuSelectWidget}
6033 */
6034 OO.ui.mixin.LookupElement.prototype.getLookupMenu = function () {
6035 return this.lookupMenu;
6036 };
6037
6038 /**
6039 * Disable or re-enable lookups.
6040 *
6041 * When lookups are disabled, calls to #populateLookupMenu will be ignored.
6042 *
6043 * @param {boolean} disabled Disable lookups
6044 */
6045 OO.ui.mixin.LookupElement.prototype.setLookupsDisabled = function ( disabled ) {
6046 this.lookupsDisabled = !!disabled;
6047 };
6048
6049 /**
6050 * Open the menu. If there are no entries in the menu, this does nothing.
6051 *
6052 * @private
6053 * @chainable
6054 */
6055 OO.ui.mixin.LookupElement.prototype.openLookupMenu = function () {
6056 if ( !this.lookupMenu.isEmpty() ) {
6057 this.lookupMenu.toggle( true );
6058 }
6059 return this;
6060 };
6061
6062 /**
6063 * Close the menu, empty it, and abort any pending request.
6064 *
6065 * @private
6066 * @chainable
6067 */
6068 OO.ui.mixin.LookupElement.prototype.closeLookupMenu = function () {
6069 this.lookupMenu.toggle( false );
6070 this.abortLookupRequest();
6071 this.lookupMenu.clearItems();
6072 return this;
6073 };
6074
6075 /**
6076 * Request menu items based on the input's current value, and when they arrive,
6077 * populate the menu with these items and show the menu.
6078 *
6079 * If lookups have been disabled with #setLookupsDisabled, this function does nothing.
6080 *
6081 * @private
6082 * @chainable
6083 */
6084 OO.ui.mixin.LookupElement.prototype.populateLookupMenu = function () {
6085 var widget = this,
6086 value = this.getValue();
6087
6088 if ( this.lookupsDisabled || this.isReadOnly() ) {
6089 return;
6090 }
6091
6092 // If the input is empty, clear the menu, unless suggestions when empty are allowed.
6093 if ( !this.allowSuggestionsWhenEmpty && value === '' ) {
6094 this.closeLookupMenu();
6095 // Skip population if there is already a request pending for the current value
6096 } else if ( value !== this.lookupQuery ) {
6097 this.getLookupMenuItems()
6098 .done( function ( items ) {
6099 widget.lookupMenu.clearItems();
6100 if ( items.length ) {
6101 widget.lookupMenu
6102 .addItems( items )
6103 .toggle( true );
6104 widget.initializeLookupMenuSelection();
6105 } else {
6106 widget.lookupMenu.toggle( false );
6107 }
6108 } )
6109 .fail( function () {
6110 widget.lookupMenu.clearItems();
6111 } );
6112 }
6113
6114 return this;
6115 };
6116
6117 /**
6118 * Highlight the first selectable item in the menu.
6119 *
6120 * @private
6121 * @chainable
6122 */
6123 OO.ui.mixin.LookupElement.prototype.initializeLookupMenuSelection = function () {
6124 if ( !this.lookupMenu.getSelectedItem() ) {
6125 this.lookupMenu.highlightItem( this.lookupMenu.getFirstSelectableItem() );
6126 }
6127 };
6128
6129 /**
6130 * Get lookup menu items for the current query.
6131 *
6132 * @private
6133 * @return {jQuery.Promise} Promise object which will be passed menu items as the first argument of
6134 * the done event. If the request was aborted to make way for a subsequent request, this promise
6135 * will not be rejected: it will remain pending forever.
6136 */
6137 OO.ui.mixin.LookupElement.prototype.getLookupMenuItems = function () {
6138 var widget = this,
6139 value = this.getValue(),
6140 deferred = $.Deferred(),
6141 ourRequest;
6142
6143 this.abortLookupRequest();
6144 if ( Object.prototype.hasOwnProperty.call( this.lookupCache, value ) ) {
6145 deferred.resolve( this.getLookupMenuOptionsFromData( this.lookupCache[ value ] ) );
6146 } else {
6147 this.pushPending();
6148 this.lookupQuery = value;
6149 ourRequest = this.lookupRequest = this.getLookupRequest();
6150 ourRequest
6151 .always( function () {
6152 // We need to pop pending even if this is an old request, otherwise
6153 // the widget will remain pending forever.
6154 // TODO: this assumes that an aborted request will fail or succeed soon after
6155 // being aborted, or at least eventually. It would be nice if we could popPending()
6156 // at abort time, but only if we knew that we hadn't already called popPending()
6157 // for that request.
6158 widget.popPending();
6159 } )
6160 .done( function ( response ) {
6161 // If this is an old request (and aborting it somehow caused it to still succeed),
6162 // ignore its success completely
6163 if ( ourRequest === widget.lookupRequest ) {
6164 widget.lookupQuery = null;
6165 widget.lookupRequest = null;
6166 widget.lookupCache[ value ] = widget.getLookupCacheDataFromResponse( response );
6167 deferred.resolve( widget.getLookupMenuOptionsFromData( widget.lookupCache[ value ] ) );
6168 }
6169 } )
6170 .fail( function () {
6171 // If this is an old request (or a request failing because it's being aborted),
6172 // ignore its failure completely
6173 if ( ourRequest === widget.lookupRequest ) {
6174 widget.lookupQuery = null;
6175 widget.lookupRequest = null;
6176 deferred.reject();
6177 }
6178 } );
6179 }
6180 return deferred.promise();
6181 };
6182
6183 /**
6184 * Abort the currently pending lookup request, if any.
6185 *
6186 * @private
6187 */
6188 OO.ui.mixin.LookupElement.prototype.abortLookupRequest = function () {
6189 var oldRequest = this.lookupRequest;
6190 if ( oldRequest ) {
6191 // First unset this.lookupRequest to the fail handler will notice
6192 // that the request is no longer current
6193 this.lookupRequest = null;
6194 this.lookupQuery = null;
6195 oldRequest.abort();
6196 }
6197 };
6198
6199 /**
6200 * Get a new request object of the current lookup query value.
6201 *
6202 * @protected
6203 * @abstract
6204 * @return {jQuery.Promise} jQuery AJAX object, or promise object with an .abort() method
6205 */
6206 OO.ui.mixin.LookupElement.prototype.getLookupRequest = function () {
6207 // Stub, implemented in subclass
6208 return null;
6209 };
6210
6211 /**
6212 * Pre-process data returned by the request from #getLookupRequest.
6213 *
6214 * The return value of this function will be cached, and any further queries for the given value
6215 * will use the cache rather than doing API requests.
6216 *
6217 * @protected
6218 * @abstract
6219 * @param {Mixed} response Response from server
6220 * @return {Mixed} Cached result data
6221 */
6222 OO.ui.mixin.LookupElement.prototype.getLookupCacheDataFromResponse = function () {
6223 // Stub, implemented in subclass
6224 return [];
6225 };
6226
6227 /**
6228 * Get a list of menu option widgets from the (possibly cached) data returned by
6229 * #getLookupCacheDataFromResponse.
6230 *
6231 * @protected
6232 * @abstract
6233 * @param {Mixed} data Cached result data, usually an array
6234 * @return {OO.ui.MenuOptionWidget[]} Menu items
6235 */
6236 OO.ui.mixin.LookupElement.prototype.getLookupMenuOptionsFromData = function () {
6237 // Stub, implemented in subclass
6238 return [];
6239 };
6240
6241 /**
6242 * Set the read-only state of the widget.
6243 *
6244 * This will also disable/enable the lookups functionality.
6245 *
6246 * @param {boolean} readOnly Make input read-only
6247 * @chainable
6248 */
6249 OO.ui.mixin.LookupElement.prototype.setReadOnly = function ( readOnly ) {
6250 // Parent method
6251 // Note: Calling #setReadOnly this way assumes this is mixed into an OO.ui.TextInputWidget
6252 OO.ui.TextInputWidget.prototype.setReadOnly.call( this, readOnly );
6253
6254 // During construction, #setReadOnly is called before the OO.ui.mixin.LookupElement constructor
6255 if ( this.isReadOnly() && this.lookupMenu ) {
6256 this.closeLookupMenu();
6257 }
6258
6259 return this;
6260 };
6261
6262 /**
6263 * PopupElement is mixed into other classes to generate a {@link OO.ui.PopupWidget popup widget}.
6264 * A popup is a container for content. It is overlaid and positioned absolutely. By default, each
6265 * popup has an anchor, which is an arrow-like protrusion that points toward the popup’s origin.
6266 * See {@link OO.ui.PopupWidget PopupWidget} for an example.
6267 *
6268 * @abstract
6269 * @class
6270 *
6271 * @constructor
6272 * @param {Object} [config] Configuration options
6273 * @cfg {Object} [popup] Configuration to pass to popup
6274 * @cfg {boolean} [popup.autoClose=true] Popup auto-closes when it loses focus
6275 */
6276 OO.ui.mixin.PopupElement = function OoUiMixinPopupElement( config ) {
6277 // Configuration initialization
6278 config = config || {};
6279
6280 // Properties
6281 this.popup = new OO.ui.PopupWidget( $.extend(
6282 { autoClose: true },
6283 config.popup,
6284 { $autoCloseIgnore: this.$element }
6285 ) );
6286 };
6287
6288 /* Methods */
6289
6290 /**
6291 * Get popup.
6292 *
6293 * @return {OO.ui.PopupWidget} Popup widget
6294 */
6295 OO.ui.mixin.PopupElement.prototype.getPopup = function () {
6296 return this.popup;
6297 };
6298
6299 /**
6300 * The FlaggedElement class is an attribute mixin, meaning that it is used to add
6301 * additional functionality to an element created by another class. The class provides
6302 * a ‘flags’ property assigned the name (or an array of names) of styling flags,
6303 * which are used to customize the look and feel of a widget to better describe its
6304 * importance and functionality.
6305 *
6306 * The library currently contains the following styling flags for general use:
6307 *
6308 * - **progressive**: Progressive styling is applied to convey that the widget will move the user forward in a process.
6309 * - **destructive**: Destructive styling is applied to convey that the widget will remove something.
6310 * - **constructive**: Constructive styling is applied to convey that the widget will create something.
6311 *
6312 * The flags affect the appearance of the buttons:
6313 *
6314 * @example
6315 * // FlaggedElement is mixed into ButtonWidget to provide styling flags
6316 * var button1 = new OO.ui.ButtonWidget( {
6317 * label: 'Constructive',
6318 * flags: 'constructive'
6319 * } );
6320 * var button2 = new OO.ui.ButtonWidget( {
6321 * label: 'Destructive',
6322 * flags: 'destructive'
6323 * } );
6324 * var button3 = new OO.ui.ButtonWidget( {
6325 * label: 'Progressive',
6326 * flags: 'progressive'
6327 * } );
6328 * $( 'body' ).append( button1.$element, button2.$element, button3.$element );
6329 *
6330 * {@link OO.ui.ActionWidget ActionWidgets}, which are a special kind of button that execute an action, use these flags: **primary** and **safe**.
6331 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information.
6332 *
6333 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Flagged
6334 *
6335 * @abstract
6336 * @class
6337 *
6338 * @constructor
6339 * @param {Object} [config] Configuration options
6340 * @cfg {string|string[]} [flags] The name or names of the flags (e.g., 'constructive' or 'primary') to apply.
6341 * Please see the [OOjs UI documentation on MediaWiki] [2] for more information about available flags.
6342 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Flagged
6343 * @cfg {jQuery} [$flagged] The flagged element. By default,
6344 * the flagged functionality is applied to the element created by the class ($element).
6345 * If a different element is specified, the flagged functionality will be applied to it instead.
6346 */
6347 OO.ui.mixin.FlaggedElement = function OoUiMixinFlaggedElement( config ) {
6348 // Configuration initialization
6349 config = config || {};
6350
6351 // Properties
6352 this.flags = {};
6353 this.$flagged = null;
6354
6355 // Initialization
6356 this.setFlags( config.flags );
6357 this.setFlaggedElement( config.$flagged || this.$element );
6358 };
6359
6360 /* Events */
6361
6362 /**
6363 * @event flag
6364 * A flag event is emitted when the #clearFlags or #setFlags methods are used. The `changes`
6365 * parameter contains the name of each modified flag and indicates whether it was
6366 * added or removed.
6367 *
6368 * @param {Object.<string,boolean>} changes Object keyed by flag name. A Boolean `true` indicates
6369 * that the flag was added, `false` that the flag was removed.
6370 */
6371
6372 /* Methods */
6373
6374 /**
6375 * Set the flagged element.
6376 *
6377 * This method is used to retarget a flagged mixin so that its functionality applies to the specified element.
6378 * If an element is already set, the method will remove the mixin’s effect on that element.
6379 *
6380 * @param {jQuery} $flagged Element that should be flagged
6381 */
6382 OO.ui.mixin.FlaggedElement.prototype.setFlaggedElement = function ( $flagged ) {
6383 var classNames = Object.keys( this.flags ).map( function ( flag ) {
6384 return 'oo-ui-flaggedElement-' + flag;
6385 } ).join( ' ' );
6386
6387 if ( this.$flagged ) {
6388 this.$flagged.removeClass( classNames );
6389 }
6390
6391 this.$flagged = $flagged.addClass( classNames );
6392 };
6393
6394 /**
6395 * Check if the specified flag is set.
6396 *
6397 * @param {string} flag Name of flag
6398 * @return {boolean} The flag is set
6399 */
6400 OO.ui.mixin.FlaggedElement.prototype.hasFlag = function ( flag ) {
6401 // This may be called before the constructor, thus before this.flags is set
6402 return this.flags && ( flag in this.flags );
6403 };
6404
6405 /**
6406 * Get the names of all flags set.
6407 *
6408 * @return {string[]} Flag names
6409 */
6410 OO.ui.mixin.FlaggedElement.prototype.getFlags = function () {
6411 // This may be called before the constructor, thus before this.flags is set
6412 return Object.keys( this.flags || {} );
6413 };
6414
6415 /**
6416 * Clear all flags.
6417 *
6418 * @chainable
6419 * @fires flag
6420 */
6421 OO.ui.mixin.FlaggedElement.prototype.clearFlags = function () {
6422 var flag, className,
6423 changes = {},
6424 remove = [],
6425 classPrefix = 'oo-ui-flaggedElement-';
6426
6427 for ( flag in this.flags ) {
6428 className = classPrefix + flag;
6429 changes[ flag ] = false;
6430 delete this.flags[ flag ];
6431 remove.push( className );
6432 }
6433
6434 if ( this.$flagged ) {
6435 this.$flagged.removeClass( remove.join( ' ' ) );
6436 }
6437
6438 this.updateThemeClasses();
6439 this.emit( 'flag', changes );
6440
6441 return this;
6442 };
6443
6444 /**
6445 * Add one or more flags.
6446 *
6447 * @param {string|string[]|Object.<string, boolean>} flags A flag name, an array of flag names,
6448 * or an object keyed by flag name with a boolean value that indicates whether the flag should
6449 * be added (`true`) or removed (`false`).
6450 * @chainable
6451 * @fires flag
6452 */
6453 OO.ui.mixin.FlaggedElement.prototype.setFlags = function ( flags ) {
6454 var i, len, flag, className,
6455 changes = {},
6456 add = [],
6457 remove = [],
6458 classPrefix = 'oo-ui-flaggedElement-';
6459
6460 if ( typeof flags === 'string' ) {
6461 className = classPrefix + flags;
6462 // Set
6463 if ( !this.flags[ flags ] ) {
6464 this.flags[ flags ] = true;
6465 add.push( className );
6466 }
6467 } else if ( Array.isArray( flags ) ) {
6468 for ( i = 0, len = flags.length; i < len; i++ ) {
6469 flag = flags[ i ];
6470 className = classPrefix + flag;
6471 // Set
6472 if ( !this.flags[ flag ] ) {
6473 changes[ flag ] = true;
6474 this.flags[ flag ] = true;
6475 add.push( className );
6476 }
6477 }
6478 } else if ( OO.isPlainObject( flags ) ) {
6479 for ( flag in flags ) {
6480 className = classPrefix + flag;
6481 if ( flags[ flag ] ) {
6482 // Set
6483 if ( !this.flags[ flag ] ) {
6484 changes[ flag ] = true;
6485 this.flags[ flag ] = true;
6486 add.push( className );
6487 }
6488 } else {
6489 // Remove
6490 if ( this.flags[ flag ] ) {
6491 changes[ flag ] = false;
6492 delete this.flags[ flag ];
6493 remove.push( className );
6494 }
6495 }
6496 }
6497 }
6498
6499 if ( this.$flagged ) {
6500 this.$flagged
6501 .addClass( add.join( ' ' ) )
6502 .removeClass( remove.join( ' ' ) );
6503 }
6504
6505 this.updateThemeClasses();
6506 this.emit( 'flag', changes );
6507
6508 return this;
6509 };
6510
6511 /**
6512 * TitledElement is mixed into other classes to provide a `title` attribute.
6513 * Titles are rendered by the browser and are made visible when the user moves
6514 * the mouse over the element. Titles are not visible on touch devices.
6515 *
6516 * @example
6517 * // TitledElement provides a 'title' attribute to the
6518 * // ButtonWidget class
6519 * var button = new OO.ui.ButtonWidget( {
6520 * label: 'Button with Title',
6521 * title: 'I am a button'
6522 * } );
6523 * $( 'body' ).append( button.$element );
6524 *
6525 * @abstract
6526 * @class
6527 *
6528 * @constructor
6529 * @param {Object} [config] Configuration options
6530 * @cfg {jQuery} [$titled] The element to which the `title` attribute is applied.
6531 * If this config is omitted, the title functionality is applied to $element, the
6532 * element created by the class.
6533 * @cfg {string|Function} [title] The title text or a function that returns text. If
6534 * this config is omitted, the value of the {@link #static-title static title} property is used.
6535 */
6536 OO.ui.mixin.TitledElement = function OoUiMixinTitledElement( config ) {
6537 // Configuration initialization
6538 config = config || {};
6539
6540 // Properties
6541 this.$titled = null;
6542 this.title = null;
6543
6544 // Initialization
6545 this.setTitle( config.title || this.constructor.static.title );
6546 this.setTitledElement( config.$titled || this.$element );
6547 };
6548
6549 /* Setup */
6550
6551 OO.initClass( OO.ui.mixin.TitledElement );
6552
6553 /* Static Properties */
6554
6555 /**
6556 * The title text, a function that returns text, or `null` for no title. The value of the static property
6557 * is overridden if the #title config option is used.
6558 *
6559 * @static
6560 * @inheritable
6561 * @property {string|Function|null}
6562 */
6563 OO.ui.mixin.TitledElement.static.title = null;
6564
6565 /* Methods */
6566
6567 /**
6568 * Set the titled element.
6569 *
6570 * This method is used to retarget a titledElement mixin so that its functionality applies to the specified element.
6571 * If an element is already set, the mixin’s effect on that element is removed before the new element is set up.
6572 *
6573 * @param {jQuery} $titled Element that should use the 'titled' functionality
6574 */
6575 OO.ui.mixin.TitledElement.prototype.setTitledElement = function ( $titled ) {
6576 if ( this.$titled ) {
6577 this.$titled.removeAttr( 'title' );
6578 }
6579
6580 this.$titled = $titled;
6581 if ( this.title ) {
6582 this.$titled.attr( 'title', this.title );
6583 }
6584 };
6585
6586 /**
6587 * Set title.
6588 *
6589 * @param {string|Function|null} title Title text, a function that returns text, or `null` for no title
6590 * @chainable
6591 */
6592 OO.ui.mixin.TitledElement.prototype.setTitle = function ( title ) {
6593 title = typeof title === 'string' ? OO.ui.resolveMsg( title ) : null;
6594
6595 if ( this.title !== title ) {
6596 if ( this.$titled ) {
6597 if ( title !== null ) {
6598 this.$titled.attr( 'title', title );
6599 } else {
6600 this.$titled.removeAttr( 'title' );
6601 }
6602 }
6603 this.title = title;
6604 }
6605
6606 return this;
6607 };
6608
6609 /**
6610 * Get title.
6611 *
6612 * @return {string} Title string
6613 */
6614 OO.ui.mixin.TitledElement.prototype.getTitle = function () {
6615 return this.title;
6616 };
6617
6618 /**
6619 * Element that can be automatically clipped to visible boundaries.
6620 *
6621 * Whenever the element's natural height changes, you have to call
6622 * {@link OO.ui.mixin.ClippableElement#clip} to make sure it's still
6623 * clipping correctly.
6624 *
6625 * The dimensions of #$clippableContainer will be compared to the boundaries of the
6626 * nearest scrollable container. If #$clippableContainer is too tall and/or too wide,
6627 * then #$clippable will be given a fixed reduced height and/or width and will be made
6628 * scrollable. By default, #$clippable and #$clippableContainer are the same element,
6629 * but you can build a static footer by setting #$clippableContainer to an element that contains
6630 * #$clippable and the footer.
6631 *
6632 * @abstract
6633 * @class
6634 *
6635 * @constructor
6636 * @param {Object} [config] Configuration options
6637 * @cfg {jQuery} [$clippable] Node to clip, assigned to #$clippable, omit to use #$element
6638 * @cfg {jQuery} [$clippableContainer] Node to keep visible, assigned to #$clippableContainer,
6639 * omit to use #$clippable
6640 */
6641 OO.ui.mixin.ClippableElement = function OoUiMixinClippableElement( config ) {
6642 // Configuration initialization
6643 config = config || {};
6644
6645 // Properties
6646 this.$clippable = null;
6647 this.$clippableContainer = null;
6648 this.clipping = false;
6649 this.clippedHorizontally = false;
6650 this.clippedVertically = false;
6651 this.$clippableScrollableContainer = null;
6652 this.$clippableScroller = null;
6653 this.$clippableWindow = null;
6654 this.idealWidth = null;
6655 this.idealHeight = null;
6656 this.onClippableScrollHandler = this.clip.bind( this );
6657 this.onClippableWindowResizeHandler = this.clip.bind( this );
6658
6659 // Initialization
6660 if ( config.$clippableContainer ) {
6661 this.setClippableContainer( config.$clippableContainer );
6662 }
6663 this.setClippableElement( config.$clippable || this.$element );
6664 };
6665
6666 /* Methods */
6667
6668 /**
6669 * Set clippable element.
6670 *
6671 * If an element is already set, it will be cleaned up before setting up the new element.
6672 *
6673 * @param {jQuery} $clippable Element to make clippable
6674 */
6675 OO.ui.mixin.ClippableElement.prototype.setClippableElement = function ( $clippable ) {
6676 if ( this.$clippable ) {
6677 this.$clippable.removeClass( 'oo-ui-clippableElement-clippable' );
6678 this.$clippable.css( { width: '', height: '', overflowX: '', overflowY: '' } );
6679 OO.ui.Element.static.reconsiderScrollbars( this.$clippable[ 0 ] );
6680 }
6681
6682 this.$clippable = $clippable.addClass( 'oo-ui-clippableElement-clippable' );
6683 this.clip();
6684 };
6685
6686 /**
6687 * Set clippable container.
6688 *
6689 * This is the container that will be measured when deciding whether to clip. When clipping,
6690 * #$clippable will be resized in order to keep the clippable container fully visible.
6691 *
6692 * If the clippable container is unset, #$clippable will be used.
6693 *
6694 * @param {jQuery|null} $clippableContainer Container to keep visible, or null to unset
6695 */
6696 OO.ui.mixin.ClippableElement.prototype.setClippableContainer = function ( $clippableContainer ) {
6697 this.$clippableContainer = $clippableContainer;
6698 if ( this.$clippable ) {
6699 this.clip();
6700 }
6701 };
6702
6703 /**
6704 * Toggle clipping.
6705 *
6706 * Do not turn clipping on until after the element is attached to the DOM and visible.
6707 *
6708 * @param {boolean} [clipping] Enable clipping, omit to toggle
6709 * @chainable
6710 */
6711 OO.ui.mixin.ClippableElement.prototype.toggleClipping = function ( clipping ) {
6712 clipping = clipping === undefined ? !this.clipping : !!clipping;
6713
6714 if ( this.clipping !== clipping ) {
6715 this.clipping = clipping;
6716 if ( clipping ) {
6717 this.$clippableScrollableContainer = $( this.getClosestScrollableElementContainer() );
6718 // If the clippable container is the root, we have to listen to scroll events and check
6719 // jQuery.scrollTop on the window because of browser inconsistencies
6720 this.$clippableScroller = this.$clippableScrollableContainer.is( 'html, body' ) ?
6721 $( OO.ui.Element.static.getWindow( this.$clippableScrollableContainer ) ) :
6722 this.$clippableScrollableContainer;
6723 this.$clippableScroller.on( 'scroll', this.onClippableScrollHandler );
6724 this.$clippableWindow = $( this.getElementWindow() )
6725 .on( 'resize', this.onClippableWindowResizeHandler );
6726 // Initial clip after visible
6727 this.clip();
6728 } else {
6729 this.$clippable.css( { width: '', height: '', overflowX: '', overflowY: '' } );
6730 OO.ui.Element.static.reconsiderScrollbars( this.$clippable[ 0 ] );
6731
6732 this.$clippableScrollableContainer = null;
6733 this.$clippableScroller.off( 'scroll', this.onClippableScrollHandler );
6734 this.$clippableScroller = null;
6735 this.$clippableWindow.off( 'resize', this.onClippableWindowResizeHandler );
6736 this.$clippableWindow = null;
6737 }
6738 }
6739
6740 return this;
6741 };
6742
6743 /**
6744 * Check if the element will be clipped to fit the visible area of the nearest scrollable container.
6745 *
6746 * @return {boolean} Element will be clipped to the visible area
6747 */
6748 OO.ui.mixin.ClippableElement.prototype.isClipping = function () {
6749 return this.clipping;
6750 };
6751
6752 /**
6753 * Check if the bottom or right of the element is being clipped by the nearest scrollable container.
6754 *
6755 * @return {boolean} Part of the element is being clipped
6756 */
6757 OO.ui.mixin.ClippableElement.prototype.isClipped = function () {
6758 return this.clippedHorizontally || this.clippedVertically;
6759 };
6760
6761 /**
6762 * Check if the right of the element is being clipped by the nearest scrollable container.
6763 *
6764 * @return {boolean} Part of the element is being clipped
6765 */
6766 OO.ui.mixin.ClippableElement.prototype.isClippedHorizontally = function () {
6767 return this.clippedHorizontally;
6768 };
6769
6770 /**
6771 * Check if the bottom of the element is being clipped by the nearest scrollable container.
6772 *
6773 * @return {boolean} Part of the element is being clipped
6774 */
6775 OO.ui.mixin.ClippableElement.prototype.isClippedVertically = function () {
6776 return this.clippedVertically;
6777 };
6778
6779 /**
6780 * Set the ideal size. These are the dimensions the element will have when it's not being clipped.
6781 *
6782 * @param {number|string} [width] Width as a number of pixels or CSS string with unit suffix
6783 * @param {number|string} [height] Height as a number of pixels or CSS string with unit suffix
6784 */
6785 OO.ui.mixin.ClippableElement.prototype.setIdealSize = function ( width, height ) {
6786 this.idealWidth = width;
6787 this.idealHeight = height;
6788
6789 if ( !this.clipping ) {
6790 // Update dimensions
6791 this.$clippable.css( { width: width, height: height } );
6792 }
6793 // While clipping, idealWidth and idealHeight are not considered
6794 };
6795
6796 /**
6797 * Clip element to visible boundaries and allow scrolling when needed. Call this method when
6798 * the element's natural height changes.
6799 *
6800 * Element will be clipped the bottom or right of the element is within 10px of the edge of, or
6801 * overlapped by, the visible area of the nearest scrollable container.
6802 *
6803 * @chainable
6804 */
6805 OO.ui.mixin.ClippableElement.prototype.clip = function () {
6806 var $container, extraHeight, extraWidth, ccOffset,
6807 $scrollableContainer, scOffset, scHeight, scWidth,
6808 ccWidth, scrollerIsWindow, scrollTop, scrollLeft,
6809 desiredWidth, desiredHeight, allotedWidth, allotedHeight,
6810 naturalWidth, naturalHeight, clipWidth, clipHeight,
6811 buffer = 7; // Chosen by fair dice roll
6812
6813 if ( !this.clipping ) {
6814 // this.$clippableScrollableContainer and this.$clippableWindow are null, so the below will fail
6815 return this;
6816 }
6817
6818 $container = this.$clippableContainer || this.$clippable;
6819 extraHeight = $container.outerHeight() - this.$clippable.outerHeight();
6820 extraWidth = $container.outerWidth() - this.$clippable.outerWidth();
6821 ccOffset = $container.offset();
6822 $scrollableContainer = this.$clippableScrollableContainer.is( 'html, body' ) ?
6823 this.$clippableWindow : this.$clippableScrollableContainer;
6824 scOffset = $scrollableContainer.offset() || { top: 0, left: 0 };
6825 scHeight = $scrollableContainer.innerHeight() - buffer;
6826 scWidth = $scrollableContainer.innerWidth() - buffer;
6827 ccWidth = $container.outerWidth() + buffer;
6828 scrollerIsWindow = this.$clippableScroller[ 0 ] === this.$clippableWindow[ 0 ];
6829 scrollTop = scrollerIsWindow ? this.$clippableScroller.scrollTop() : 0;
6830 scrollLeft = scrollerIsWindow ? this.$clippableScroller.scrollLeft() : 0;
6831 desiredWidth = ccOffset.left < 0 ?
6832 ccWidth + ccOffset.left :
6833 ( scOffset.left + scrollLeft + scWidth ) - ccOffset.left;
6834 desiredHeight = ( scOffset.top + scrollTop + scHeight ) - ccOffset.top;
6835 allotedWidth = desiredWidth - extraWidth;
6836 allotedHeight = desiredHeight - extraHeight;
6837 naturalWidth = this.$clippable.prop( 'scrollWidth' );
6838 naturalHeight = this.$clippable.prop( 'scrollHeight' );
6839 clipWidth = allotedWidth < naturalWidth;
6840 clipHeight = allotedHeight < naturalHeight;
6841
6842 if ( clipWidth ) {
6843 this.$clippable.css( { overflowX: 'scroll', width: Math.max( 0, allotedWidth ) } );
6844 } else {
6845 this.$clippable.css( { width: this.idealWidth ? this.idealWidth - extraWidth : '', overflowX: '' } );
6846 }
6847 if ( clipHeight ) {
6848 this.$clippable.css( { overflowY: 'scroll', height: Math.max( 0, allotedHeight ) } );
6849 } else {
6850 this.$clippable.css( { height: this.idealHeight ? this.idealHeight - extraHeight : '', overflowY: '' } );
6851 }
6852
6853 // If we stopped clipping in at least one of the dimensions
6854 if ( ( this.clippedHorizontally && !clipWidth ) || ( this.clippedVertically && !clipHeight ) ) {
6855 OO.ui.Element.static.reconsiderScrollbars( this.$clippable[ 0 ] );
6856 }
6857
6858 this.clippedHorizontally = clipWidth;
6859 this.clippedVertically = clipHeight;
6860
6861 return this;
6862 };
6863
6864 /**
6865 * Element that will stick under a specified container, even when it is inserted elsewhere in the
6866 * document (for example, in a OO.ui.Window's $overlay).
6867 *
6868 * The elements's position is automatically calculated and maintained when window is resized or the
6869 * page is scrolled. If you reposition the container manually, you have to call #position to make
6870 * sure the element is still placed correctly.
6871 *
6872 * As positioning is only possible when both the element and the container are attached to the DOM
6873 * and visible, it's only done after you call #togglePositioning. You might want to do this inside
6874 * the #toggle method to display a floating popup, for example.
6875 *
6876 * @abstract
6877 * @class
6878 *
6879 * @constructor
6880 * @param {Object} [config] Configuration options
6881 * @cfg {jQuery} [$floatable] Node to position, assigned to #$floatable, omit to use #$element
6882 * @cfg {jQuery} [$floatableContainer] Node to position below
6883 */
6884 OO.ui.mixin.FloatableElement = function OoUiMixinFloatableElement( config ) {
6885 // Configuration initialization
6886 config = config || {};
6887
6888 // Properties
6889 this.$floatable = null;
6890 this.$floatableContainer = null;
6891 this.$floatableWindow = null;
6892 this.$floatableClosestScrollable = null;
6893 this.onFloatableScrollHandler = this.position.bind( this );
6894 this.onFloatableWindowResizeHandler = this.position.bind( this );
6895
6896 // Initialization
6897 this.setFloatableContainer( config.$floatableContainer );
6898 this.setFloatableElement( config.$floatable || this.$element );
6899 };
6900
6901 /* Methods */
6902
6903 /**
6904 * Set floatable element.
6905 *
6906 * If an element is already set, it will be cleaned up before setting up the new element.
6907 *
6908 * @param {jQuery} $floatable Element to make floatable
6909 */
6910 OO.ui.mixin.FloatableElement.prototype.setFloatableElement = function ( $floatable ) {
6911 if ( this.$floatable ) {
6912 this.$floatable.removeClass( 'oo-ui-floatableElement-floatable' );
6913 this.$floatable.css( { left: '', top: '' } );
6914 }
6915
6916 this.$floatable = $floatable.addClass( 'oo-ui-floatableElement-floatable' );
6917 this.position();
6918 };
6919
6920 /**
6921 * Set floatable container.
6922 *
6923 * The element will be always positioned under the specified container.
6924 *
6925 * @param {jQuery|null} $floatableContainer Container to keep visible, or null to unset
6926 */
6927 OO.ui.mixin.FloatableElement.prototype.setFloatableContainer = function ( $floatableContainer ) {
6928 this.$floatableContainer = $floatableContainer;
6929 if ( this.$floatable ) {
6930 this.position();
6931 }
6932 };
6933
6934 /**
6935 * Toggle positioning.
6936 *
6937 * Do not turn positioning on until after the element is attached to the DOM and visible.
6938 *
6939 * @param {boolean} [positioning] Enable positioning, omit to toggle
6940 * @chainable
6941 */
6942 OO.ui.mixin.FloatableElement.prototype.togglePositioning = function ( positioning ) {
6943 var closestScrollableOfContainer, closestScrollableOfFloatable;
6944
6945 positioning = positioning === undefined ? !this.positioning : !!positioning;
6946
6947 if ( this.positioning !== positioning ) {
6948 this.positioning = positioning;
6949
6950 closestScrollableOfContainer = OO.ui.Element.static.getClosestScrollableContainer( this.$floatableContainer[ 0 ] );
6951 closestScrollableOfFloatable = OO.ui.Element.static.getClosestScrollableContainer( this.$floatable[ 0 ] );
6952 if ( closestScrollableOfContainer !== closestScrollableOfFloatable ) {
6953 // If the scrollable is the root, we have to listen to scroll events
6954 // on the window because of browser inconsistencies (or do we? someone should verify this)
6955 if ( $( closestScrollableOfContainer ).is( 'html, body' ) ) {
6956 closestScrollableOfContainer = OO.ui.Element.static.getWindow( closestScrollableOfContainer );
6957 }
6958 }
6959
6960 if ( positioning ) {
6961 this.$floatableWindow = $( this.getElementWindow() );
6962 this.$floatableWindow.on( 'resize', this.onFloatableWindowResizeHandler );
6963
6964 if ( closestScrollableOfContainer !== closestScrollableOfFloatable ) {
6965 this.$floatableClosestScrollable = $( closestScrollableOfContainer );
6966 this.$floatableClosestScrollable.on( 'scroll', this.onFloatableScrollHandler );
6967 }
6968
6969 // Initial position after visible
6970 this.position();
6971 } else {
6972 if ( this.$floatableWindow ) {
6973 this.$floatableWindow.off( 'resize', this.onFloatableWindowResizeHandler );
6974 this.$floatableWindow = null;
6975 }
6976
6977 if ( this.$floatableClosestScrollable ) {
6978 this.$floatableClosestScrollable.off( 'scroll', this.onFloatableScrollHandler );
6979 this.$floatableClosestScrollable = null;
6980 }
6981
6982 this.$floatable.css( { left: '', top: '' } );
6983 }
6984 }
6985
6986 return this;
6987 };
6988
6989 /**
6990 * Position the floatable below its container.
6991 *
6992 * This should only be done when both of them are attached to the DOM and visible.
6993 *
6994 * @chainable
6995 */
6996 OO.ui.mixin.FloatableElement.prototype.position = function () {
6997 var pos;
6998
6999 if ( !this.positioning ) {
7000 return this;
7001 }
7002
7003 pos = OO.ui.Element.static.getRelativePosition( this.$floatableContainer, this.$floatable.offsetParent() );
7004
7005 // Position under container
7006 pos.top += this.$floatableContainer.height();
7007 this.$floatable.css( pos );
7008
7009 // We updated the position, so re-evaluate the clipping state.
7010 // (ClippableElement does not listen to 'scroll' events on $floatableContainer's parent, and so
7011 // will not notice the need to update itself.)
7012 // TODO: This is terrible, we shouldn't need to know about ClippableElement at all here. Why does
7013 // it not listen to the right events in the right places?
7014 if ( this.clip ) {
7015 this.clip();
7016 }
7017
7018 return this;
7019 };
7020
7021 /**
7022 * AccessKeyedElement is mixed into other classes to provide an `accesskey` attribute.
7023 * Accesskeys allow an user to go to a specific element by using
7024 * a shortcut combination of a browser specific keys + the key
7025 * set to the field.
7026 *
7027 * @example
7028 * // AccessKeyedElement provides an 'accesskey' attribute to the
7029 * // ButtonWidget class
7030 * var button = new OO.ui.ButtonWidget( {
7031 * label: 'Button with Accesskey',
7032 * accessKey: 'k'
7033 * } );
7034 * $( 'body' ).append( button.$element );
7035 *
7036 * @abstract
7037 * @class
7038 *
7039 * @constructor
7040 * @param {Object} [config] Configuration options
7041 * @cfg {jQuery} [$accessKeyed] The element to which the `accesskey` attribute is applied.
7042 * If this config is omitted, the accesskey functionality is applied to $element, the
7043 * element created by the class.
7044 * @cfg {string|Function} [accessKey] The key or a function that returns the key. If
7045 * this config is omitted, no accesskey will be added.
7046 */
7047 OO.ui.mixin.AccessKeyedElement = function OoUiMixinAccessKeyedElement( config ) {
7048 // Configuration initialization
7049 config = config || {};
7050
7051 // Properties
7052 this.$accessKeyed = null;
7053 this.accessKey = null;
7054
7055 // Initialization
7056 this.setAccessKey( config.accessKey || null );
7057 this.setAccessKeyedElement( config.$accessKeyed || this.$element );
7058 };
7059
7060 /* Setup */
7061
7062 OO.initClass( OO.ui.mixin.AccessKeyedElement );
7063
7064 /* Static Properties */
7065
7066 /**
7067 * The access key, a function that returns a key, or `null` for no accesskey.
7068 *
7069 * @static
7070 * @inheritable
7071 * @property {string|Function|null}
7072 */
7073 OO.ui.mixin.AccessKeyedElement.static.accessKey = null;
7074
7075 /* Methods */
7076
7077 /**
7078 * Set the accesskeyed element.
7079 *
7080 * This method is used to retarget a AccessKeyedElement mixin so that its functionality applies to the specified element.
7081 * If an element is already set, the mixin's effect on that element is removed before the new element is set up.
7082 *
7083 * @param {jQuery} $accessKeyed Element that should use the 'accesskeyes' functionality
7084 */
7085 OO.ui.mixin.AccessKeyedElement.prototype.setAccessKeyedElement = function ( $accessKeyed ) {
7086 if ( this.$accessKeyed ) {
7087 this.$accessKeyed.removeAttr( 'accesskey' );
7088 }
7089
7090 this.$accessKeyed = $accessKeyed;
7091 if ( this.accessKey ) {
7092 this.$accessKeyed.attr( 'accesskey', this.accessKey );
7093 }
7094 };
7095
7096 /**
7097 * Set accesskey.
7098 *
7099 * @param {string|Function|null} accesskey Key, a function that returns a key, or `null` for no accesskey
7100 * @chainable
7101 */
7102 OO.ui.mixin.AccessKeyedElement.prototype.setAccessKey = function ( accessKey ) {
7103 accessKey = typeof accessKey === 'string' ? OO.ui.resolveMsg( accessKey ) : null;
7104
7105 if ( this.accessKey !== accessKey ) {
7106 if ( this.$accessKeyed ) {
7107 if ( accessKey !== null ) {
7108 this.$accessKeyed.attr( 'accesskey', accessKey );
7109 } else {
7110 this.$accessKeyed.removeAttr( 'accesskey' );
7111 }
7112 }
7113 this.accessKey = accessKey;
7114 }
7115
7116 return this;
7117 };
7118
7119 /**
7120 * Get accesskey.
7121 *
7122 * @return {string} accessKey string
7123 */
7124 OO.ui.mixin.AccessKeyedElement.prototype.getAccessKey = function () {
7125 return this.accessKey;
7126 };
7127
7128 /**
7129 * Tools, together with {@link OO.ui.ToolGroup toolgroups}, constitute {@link OO.ui.Toolbar toolbars}.
7130 * Each tool is configured with a static name, title, and icon and is customized with the command to carry
7131 * out when the tool is selected. Tools must also be registered with a {@link OO.ui.ToolFactory tool factory},
7132 * which creates the tools on demand.
7133 *
7134 * Tools are added to toolgroups ({@link OO.ui.ListToolGroup ListToolGroup},
7135 * {@link OO.ui.BarToolGroup BarToolGroup}, or {@link OO.ui.MenuToolGroup MenuToolGroup}), which determine how
7136 * the tool is displayed in the toolbar. See {@link OO.ui.Toolbar toolbars} for an example.
7137 *
7138 * For more information, please see the [OOjs UI documentation on MediaWiki][1].
7139 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
7140 *
7141 * @abstract
7142 * @class
7143 * @extends OO.ui.Widget
7144 * @mixins OO.ui.mixin.IconElement
7145 * @mixins OO.ui.mixin.FlaggedElement
7146 * @mixins OO.ui.mixin.TabIndexedElement
7147 *
7148 * @constructor
7149 * @param {OO.ui.ToolGroup} toolGroup
7150 * @param {Object} [config] Configuration options
7151 * @cfg {string|Function} [title] Title text or a function that returns text. If this config is omitted, the value of
7152 * the {@link #static-title static title} property is used.
7153 *
7154 * The title is used in different ways depending on the type of toolgroup that contains the tool. The
7155 * 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
7156 * part of a {@link OO.ui.ListToolGroup list} or {@link OO.ui.MenuToolGroup menu} toolgroup.
7157 *
7158 * For bar toolgroups, a description of the accelerator key is appended to the title if an accelerator key
7159 * is associated with an action by the same name as the tool and accelerator functionality has been added to the application.
7160 * To add accelerator key functionality, you must subclass OO.ui.Toolbar and override the {@link OO.ui.Toolbar#getToolAccelerator getToolAccelerator} method.
7161 */
7162 OO.ui.Tool = function OoUiTool( toolGroup, config ) {
7163 // Allow passing positional parameters inside the config object
7164 if ( OO.isPlainObject( toolGroup ) && config === undefined ) {
7165 config = toolGroup;
7166 toolGroup = config.toolGroup;
7167 }
7168
7169 // Configuration initialization
7170 config = config || {};
7171
7172 // Parent constructor
7173 OO.ui.Tool.parent.call( this, config );
7174
7175 // Properties
7176 this.toolGroup = toolGroup;
7177 this.toolbar = this.toolGroup.getToolbar();
7178 this.active = false;
7179 this.$title = $( '<span>' );
7180 this.$accel = $( '<span>' );
7181 this.$link = $( '<a>' );
7182 this.title = null;
7183
7184 // Mixin constructors
7185 OO.ui.mixin.IconElement.call( this, config );
7186 OO.ui.mixin.FlaggedElement.call( this, config );
7187 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$link } ) );
7188
7189 // Events
7190 this.toolbar.connect( this, { updateState: 'onUpdateState' } );
7191
7192 // Initialization
7193 this.$title.addClass( 'oo-ui-tool-title' );
7194 this.$accel
7195 .addClass( 'oo-ui-tool-accel' )
7196 .prop( {
7197 // This may need to be changed if the key names are ever localized,
7198 // but for now they are essentially written in English
7199 dir: 'ltr',
7200 lang: 'en'
7201 } );
7202 this.$link
7203 .addClass( 'oo-ui-tool-link' )
7204 .append( this.$icon, this.$title, this.$accel )
7205 .attr( 'role', 'button' );
7206 this.$element
7207 .data( 'oo-ui-tool', this )
7208 .addClass(
7209 'oo-ui-tool ' + 'oo-ui-tool-name-' +
7210 this.constructor.static.name.replace( /^([^\/]+)\/([^\/]+).*$/, '$1-$2' )
7211 )
7212 .toggleClass( 'oo-ui-tool-with-label', this.constructor.static.displayBothIconAndLabel )
7213 .append( this.$link );
7214 this.setTitle( config.title || this.constructor.static.title );
7215 };
7216
7217 /* Setup */
7218
7219 OO.inheritClass( OO.ui.Tool, OO.ui.Widget );
7220 OO.mixinClass( OO.ui.Tool, OO.ui.mixin.IconElement );
7221 OO.mixinClass( OO.ui.Tool, OO.ui.mixin.FlaggedElement );
7222 OO.mixinClass( OO.ui.Tool, OO.ui.mixin.TabIndexedElement );
7223
7224 /* Static Properties */
7225
7226 /**
7227 * @static
7228 * @inheritdoc
7229 */
7230 OO.ui.Tool.static.tagName = 'span';
7231
7232 /**
7233 * Symbolic name of tool.
7234 *
7235 * The symbolic name is used internally to register the tool with a {@link OO.ui.ToolFactory ToolFactory}. It can
7236 * also be used when adding tools to toolgroups.
7237 *
7238 * @abstract
7239 * @static
7240 * @inheritable
7241 * @property {string}
7242 */
7243 OO.ui.Tool.static.name = '';
7244
7245 /**
7246 * Symbolic name of the group.
7247 *
7248 * The group name is used to associate tools with each other so that they can be selected later by
7249 * a {@link OO.ui.ToolGroup toolgroup}.
7250 *
7251 * @abstract
7252 * @static
7253 * @inheritable
7254 * @property {string}
7255 */
7256 OO.ui.Tool.static.group = '';
7257
7258 /**
7259 * 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.
7260 *
7261 * @abstract
7262 * @static
7263 * @inheritable
7264 * @property {string|Function}
7265 */
7266 OO.ui.Tool.static.title = '';
7267
7268 /**
7269 * Display both icon and label when the tool is used in a {@link OO.ui.BarToolGroup bar} toolgroup.
7270 * Normally only the icon is displayed, or only the label if no icon is given.
7271 *
7272 * @static
7273 * @inheritable
7274 * @property {boolean}
7275 */
7276 OO.ui.Tool.static.displayBothIconAndLabel = false;
7277
7278 /**
7279 * Add tool to catch-all groups automatically.
7280 *
7281 * A catch-all group, which contains all tools that do not currently belong to a toolgroup,
7282 * can be included in a toolgroup using the wildcard selector, an asterisk (*).
7283 *
7284 * @static
7285 * @inheritable
7286 * @property {boolean}
7287 */
7288 OO.ui.Tool.static.autoAddToCatchall = true;
7289
7290 /**
7291 * Add tool to named groups automatically.
7292 *
7293 * By default, tools that are configured with a static ‘group’ property are added
7294 * to that group and will be selected when the symbolic name of the group is specified (e.g., when
7295 * toolgroups include tools by group name).
7296 *
7297 * @static
7298 * @property {boolean}
7299 * @inheritable
7300 */
7301 OO.ui.Tool.static.autoAddToGroup = true;
7302
7303 /**
7304 * Check if this tool is compatible with given data.
7305 *
7306 * This is a stub that can be overriden to provide support for filtering tools based on an
7307 * arbitrary piece of information (e.g., where the cursor is in a document). The implementation
7308 * must also call this method so that the compatibility check can be performed.
7309 *
7310 * @static
7311 * @inheritable
7312 * @param {Mixed} data Data to check
7313 * @return {boolean} Tool can be used with data
7314 */
7315 OO.ui.Tool.static.isCompatibleWith = function () {
7316 return false;
7317 };
7318
7319 /* Methods */
7320
7321 /**
7322 * Handle the toolbar state being updated.
7323 *
7324 * This is an abstract method that must be overridden in a concrete subclass.
7325 *
7326 * @protected
7327 * @abstract
7328 */
7329 OO.ui.Tool.prototype.onUpdateState = function () {
7330 throw new Error(
7331 'OO.ui.Tool.onUpdateState not implemented in this subclass:' + this.constructor
7332 );
7333 };
7334
7335 /**
7336 * Handle the tool being selected.
7337 *
7338 * This is an abstract method that must be overridden in a concrete subclass.
7339 *
7340 * @protected
7341 * @abstract
7342 */
7343 OO.ui.Tool.prototype.onSelect = function () {
7344 throw new Error(
7345 'OO.ui.Tool.onSelect not implemented in this subclass:' + this.constructor
7346 );
7347 };
7348
7349 /**
7350 * Check if the tool is active.
7351 *
7352 * Tools become active when their #onSelect or #onUpdateState handlers change them to appear pressed
7353 * with the #setActive method. Additional CSS is applied to the tool to reflect the active state.
7354 *
7355 * @return {boolean} Tool is active
7356 */
7357 OO.ui.Tool.prototype.isActive = function () {
7358 return this.active;
7359 };
7360
7361 /**
7362 * Make the tool appear active or inactive.
7363 *
7364 * This method should be called within #onSelect or #onUpdateState event handlers to make the tool
7365 * appear pressed or not.
7366 *
7367 * @param {boolean} state Make tool appear active
7368 */
7369 OO.ui.Tool.prototype.setActive = function ( state ) {
7370 this.active = !!state;
7371 if ( this.active ) {
7372 this.$element.addClass( 'oo-ui-tool-active' );
7373 } else {
7374 this.$element.removeClass( 'oo-ui-tool-active' );
7375 }
7376 };
7377
7378 /**
7379 * Set the tool #title.
7380 *
7381 * @param {string|Function} title Title text or a function that returns text
7382 * @chainable
7383 */
7384 OO.ui.Tool.prototype.setTitle = function ( title ) {
7385 this.title = OO.ui.resolveMsg( title );
7386 this.updateTitle();
7387 return this;
7388 };
7389
7390 /**
7391 * Get the tool #title.
7392 *
7393 * @return {string} Title text
7394 */
7395 OO.ui.Tool.prototype.getTitle = function () {
7396 return this.title;
7397 };
7398
7399 /**
7400 * Get the tool's symbolic name.
7401 *
7402 * @return {string} Symbolic name of tool
7403 */
7404 OO.ui.Tool.prototype.getName = function () {
7405 return this.constructor.static.name;
7406 };
7407
7408 /**
7409 * Update the title.
7410 */
7411 OO.ui.Tool.prototype.updateTitle = function () {
7412 var titleTooltips = this.toolGroup.constructor.static.titleTooltips,
7413 accelTooltips = this.toolGroup.constructor.static.accelTooltips,
7414 accel = this.toolbar.getToolAccelerator( this.constructor.static.name ),
7415 tooltipParts = [];
7416
7417 this.$title.text( this.title );
7418 this.$accel.text( accel );
7419
7420 if ( titleTooltips && typeof this.title === 'string' && this.title.length ) {
7421 tooltipParts.push( this.title );
7422 }
7423 if ( accelTooltips && typeof accel === 'string' && accel.length ) {
7424 tooltipParts.push( accel );
7425 }
7426 if ( tooltipParts.length ) {
7427 this.$link.attr( 'title', tooltipParts.join( ' ' ) );
7428 } else {
7429 this.$link.removeAttr( 'title' );
7430 }
7431 };
7432
7433 /**
7434 * Destroy tool.
7435 *
7436 * Destroying the tool removes all event handlers and the tool’s DOM elements.
7437 * Call this method whenever you are done using a tool.
7438 */
7439 OO.ui.Tool.prototype.destroy = function () {
7440 this.toolbar.disconnect( this );
7441 this.$element.remove();
7442 };
7443
7444 /**
7445 * Toolbars are complex interface components that permit users to easily access a variety
7446 * of {@link OO.ui.Tool tools} (e.g., formatting commands) and actions, which are additional commands that are
7447 * part of the toolbar, but not configured as tools.
7448 *
7449 * Individual tools are customized and then registered with a {@link OO.ui.ToolFactory tool factory}, which creates
7450 * the tools on demand. Each tool has a symbolic name (used when registering the tool), a title (e.g., ‘Insert
7451 * picture’), and an icon.
7452 *
7453 * Individual tools are organized in {@link OO.ui.ToolGroup toolgroups}, which can be {@link OO.ui.MenuToolGroup menus}
7454 * of tools, {@link OO.ui.ListToolGroup lists} of tools, or a single {@link OO.ui.BarToolGroup bar} of tools.
7455 * The arrangement and order of the toolgroups is customized when the toolbar is set up. Tools can be presented in
7456 * any order, but each can only appear once in the toolbar.
7457 *
7458 * The following is an example of a basic toolbar.
7459 *
7460 * @example
7461 * // Example of a toolbar
7462 * // Create the toolbar
7463 * var toolFactory = new OO.ui.ToolFactory();
7464 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
7465 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
7466 *
7467 * // We will be placing status text in this element when tools are used
7468 * var $area = $( '<p>' ).text( 'Toolbar example' );
7469 *
7470 * // Define the tools that we're going to place in our toolbar
7471 *
7472 * // Create a class inheriting from OO.ui.Tool
7473 * function PictureTool() {
7474 * PictureTool.parent.apply( this, arguments );
7475 * }
7476 * OO.inheritClass( PictureTool, OO.ui.Tool );
7477 * // Each tool must have a 'name' (used as an internal identifier, see later) and at least one
7478 * // of 'icon' and 'title' (displayed icon and text).
7479 * PictureTool.static.name = 'picture';
7480 * PictureTool.static.icon = 'picture';
7481 * PictureTool.static.title = 'Insert picture';
7482 * // Defines the action that will happen when this tool is selected (clicked).
7483 * PictureTool.prototype.onSelect = function () {
7484 * $area.text( 'Picture tool clicked!' );
7485 * // Never display this tool as "active" (selected).
7486 * this.setActive( false );
7487 * };
7488 * // Make this tool available in our toolFactory and thus our toolbar
7489 * toolFactory.register( PictureTool );
7490 *
7491 * // Register two more tools, nothing interesting here
7492 * function SettingsTool() {
7493 * SettingsTool.parent.apply( this, arguments );
7494 * }
7495 * OO.inheritClass( SettingsTool, OO.ui.Tool );
7496 * SettingsTool.static.name = 'settings';
7497 * SettingsTool.static.icon = 'settings';
7498 * SettingsTool.static.title = 'Change settings';
7499 * SettingsTool.prototype.onSelect = function () {
7500 * $area.text( 'Settings tool clicked!' );
7501 * this.setActive( false );
7502 * };
7503 * toolFactory.register( SettingsTool );
7504 *
7505 * // Register two more tools, nothing interesting here
7506 * function StuffTool() {
7507 * StuffTool.parent.apply( this, arguments );
7508 * }
7509 * OO.inheritClass( StuffTool, OO.ui.Tool );
7510 * StuffTool.static.name = 'stuff';
7511 * StuffTool.static.icon = 'ellipsis';
7512 * StuffTool.static.title = 'More stuff';
7513 * StuffTool.prototype.onSelect = function () {
7514 * $area.text( 'More stuff tool clicked!' );
7515 * this.setActive( false );
7516 * };
7517 * toolFactory.register( StuffTool );
7518 *
7519 * // This is a PopupTool. Rather than having a custom 'onSelect' action, it will display a
7520 * // little popup window (a PopupWidget).
7521 * function HelpTool( toolGroup, config ) {
7522 * OO.ui.PopupTool.call( this, toolGroup, $.extend( { popup: {
7523 * padded: true,
7524 * label: 'Help',
7525 * head: true
7526 * } }, config ) );
7527 * this.popup.$body.append( '<p>I am helpful!</p>' );
7528 * }
7529 * OO.inheritClass( HelpTool, OO.ui.PopupTool );
7530 * HelpTool.static.name = 'help';
7531 * HelpTool.static.icon = 'help';
7532 * HelpTool.static.title = 'Help';
7533 * toolFactory.register( HelpTool );
7534 *
7535 * // Finally define which tools and in what order appear in the toolbar. Each tool may only be
7536 * // used once (but not all defined tools must be used).
7537 * toolbar.setup( [
7538 * {
7539 * // 'bar' tool groups display tools' icons only, side-by-side.
7540 * type: 'bar',
7541 * include: [ 'picture', 'help' ]
7542 * },
7543 * {
7544 * // 'list' tool groups display both the titles and icons, in a dropdown list.
7545 * type: 'list',
7546 * indicator: 'down',
7547 * label: 'More',
7548 * include: [ 'settings', 'stuff' ]
7549 * }
7550 * // Note how the tools themselves are toolgroup-agnostic - the same tool can be displayed
7551 * // either in a 'list' or a 'bar'. There is a 'menu' tool group too, not showcased here,
7552 * // since it's more complicated to use. (See the next example snippet on this page.)
7553 * ] );
7554 *
7555 * // Create some UI around the toolbar and place it in the document
7556 * var frame = new OO.ui.PanelLayout( {
7557 * expanded: false,
7558 * framed: true
7559 * } );
7560 * var contentFrame = new OO.ui.PanelLayout( {
7561 * expanded: false,
7562 * padded: true
7563 * } );
7564 * frame.$element.append(
7565 * toolbar.$element,
7566 * contentFrame.$element.append( $area )
7567 * );
7568 * $( 'body' ).append( frame.$element );
7569 *
7570 * // Here is where the toolbar is actually built. This must be done after inserting it into the
7571 * // document.
7572 * toolbar.initialize();
7573 *
7574 * The following example extends the previous one to illustrate 'menu' toolgroups and the usage of
7575 * 'updateState' event.
7576 *
7577 * @example
7578 * // Create the toolbar
7579 * var toolFactory = new OO.ui.ToolFactory();
7580 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
7581 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
7582 *
7583 * // We will be placing status text in this element when tools are used
7584 * var $area = $( '<p>' ).text( 'Toolbar example' );
7585 *
7586 * // Define the tools that we're going to place in our toolbar
7587 *
7588 * // Create a class inheriting from OO.ui.Tool
7589 * function PictureTool() {
7590 * PictureTool.parent.apply( this, arguments );
7591 * }
7592 * OO.inheritClass( PictureTool, OO.ui.Tool );
7593 * // Each tool must have a 'name' (used as an internal identifier, see later) and at least one
7594 * // of 'icon' and 'title' (displayed icon and text).
7595 * PictureTool.static.name = 'picture';
7596 * PictureTool.static.icon = 'picture';
7597 * PictureTool.static.title = 'Insert picture';
7598 * // Defines the action that will happen when this tool is selected (clicked).
7599 * PictureTool.prototype.onSelect = function () {
7600 * $area.text( 'Picture tool clicked!' );
7601 * // Never display this tool as "active" (selected).
7602 * this.setActive( false );
7603 * };
7604 * // The toolbar can be synchronized with the state of some external stuff, like a text
7605 * // editor's editing area, highlighting the tools (e.g. a 'bold' tool would be shown as active
7606 * // when the text cursor was inside bolded text). Here we simply disable this feature.
7607 * PictureTool.prototype.onUpdateState = function () {
7608 * };
7609 * // Make this tool available in our toolFactory and thus our toolbar
7610 * toolFactory.register( PictureTool );
7611 *
7612 * // Register two more tools, nothing interesting here
7613 * function SettingsTool() {
7614 * SettingsTool.parent.apply( this, arguments );
7615 * this.reallyActive = false;
7616 * }
7617 * OO.inheritClass( SettingsTool, OO.ui.Tool );
7618 * SettingsTool.static.name = 'settings';
7619 * SettingsTool.static.icon = 'settings';
7620 * SettingsTool.static.title = 'Change settings';
7621 * SettingsTool.prototype.onSelect = function () {
7622 * $area.text( 'Settings tool clicked!' );
7623 * // Toggle the active state on each click
7624 * this.reallyActive = !this.reallyActive;
7625 * this.setActive( this.reallyActive );
7626 * // To update the menu label
7627 * this.toolbar.emit( 'updateState' );
7628 * };
7629 * SettingsTool.prototype.onUpdateState = function () {
7630 * };
7631 * toolFactory.register( SettingsTool );
7632 *
7633 * // Register two more tools, nothing interesting here
7634 * function StuffTool() {
7635 * StuffTool.parent.apply( this, arguments );
7636 * this.reallyActive = false;
7637 * }
7638 * OO.inheritClass( StuffTool, OO.ui.Tool );
7639 * StuffTool.static.name = 'stuff';
7640 * StuffTool.static.icon = 'ellipsis';
7641 * StuffTool.static.title = 'More stuff';
7642 * StuffTool.prototype.onSelect = function () {
7643 * $area.text( 'More stuff tool clicked!' );
7644 * // Toggle the active state on each click
7645 * this.reallyActive = !this.reallyActive;
7646 * this.setActive( this.reallyActive );
7647 * // To update the menu label
7648 * this.toolbar.emit( 'updateState' );
7649 * };
7650 * StuffTool.prototype.onUpdateState = function () {
7651 * };
7652 * toolFactory.register( StuffTool );
7653 *
7654 * // This is a PopupTool. Rather than having a custom 'onSelect' action, it will display a
7655 * // little popup window (a PopupWidget). 'onUpdateState' is also already implemented.
7656 * function HelpTool( toolGroup, config ) {
7657 * OO.ui.PopupTool.call( this, toolGroup, $.extend( { popup: {
7658 * padded: true,
7659 * label: 'Help',
7660 * head: true
7661 * } }, config ) );
7662 * this.popup.$body.append( '<p>I am helpful!</p>' );
7663 * }
7664 * OO.inheritClass( HelpTool, OO.ui.PopupTool );
7665 * HelpTool.static.name = 'help';
7666 * HelpTool.static.icon = 'help';
7667 * HelpTool.static.title = 'Help';
7668 * toolFactory.register( HelpTool );
7669 *
7670 * // Finally define which tools and in what order appear in the toolbar. Each tool may only be
7671 * // used once (but not all defined tools must be used).
7672 * toolbar.setup( [
7673 * {
7674 * // 'bar' tool groups display tools' icons only, side-by-side.
7675 * type: 'bar',
7676 * include: [ 'picture', 'help' ]
7677 * },
7678 * {
7679 * // 'menu' tool groups display both the titles and icons, in a dropdown menu.
7680 * // Menu label indicates which items are selected.
7681 * type: 'menu',
7682 * indicator: 'down',
7683 * include: [ 'settings', 'stuff' ]
7684 * }
7685 * ] );
7686 *
7687 * // Create some UI around the toolbar and place it in the document
7688 * var frame = new OO.ui.PanelLayout( {
7689 * expanded: false,
7690 * framed: true
7691 * } );
7692 * var contentFrame = new OO.ui.PanelLayout( {
7693 * expanded: false,
7694 * padded: true
7695 * } );
7696 * frame.$element.append(
7697 * toolbar.$element,
7698 * contentFrame.$element.append( $area )
7699 * );
7700 * $( 'body' ).append( frame.$element );
7701 *
7702 * // Here is where the toolbar is actually built. This must be done after inserting it into the
7703 * // document.
7704 * toolbar.initialize();
7705 * toolbar.emit( 'updateState' );
7706 *
7707 * @class
7708 * @extends OO.ui.Element
7709 * @mixins OO.EventEmitter
7710 * @mixins OO.ui.mixin.GroupElement
7711 *
7712 * @constructor
7713 * @param {OO.ui.ToolFactory} toolFactory Factory for creating tools
7714 * @param {OO.ui.ToolGroupFactory} toolGroupFactory Factory for creating toolgroups
7715 * @param {Object} [config] Configuration options
7716 * @cfg {boolean} [actions] Add an actions section to the toolbar. Actions are commands that are included
7717 * in the toolbar, but are not configured as tools. By default, actions are displayed on the right side of
7718 * the toolbar.
7719 * @cfg {boolean} [shadow] Add a shadow below the toolbar.
7720 */
7721 OO.ui.Toolbar = function OoUiToolbar( toolFactory, toolGroupFactory, config ) {
7722 // Allow passing positional parameters inside the config object
7723 if ( OO.isPlainObject( toolFactory ) && config === undefined ) {
7724 config = toolFactory;
7725 toolFactory = config.toolFactory;
7726 toolGroupFactory = config.toolGroupFactory;
7727 }
7728
7729 // Configuration initialization
7730 config = config || {};
7731
7732 // Parent constructor
7733 OO.ui.Toolbar.parent.call( this, config );
7734
7735 // Mixin constructors
7736 OO.EventEmitter.call( this );
7737 OO.ui.mixin.GroupElement.call( this, config );
7738
7739 // Properties
7740 this.toolFactory = toolFactory;
7741 this.toolGroupFactory = toolGroupFactory;
7742 this.groups = [];
7743 this.tools = {};
7744 this.$bar = $( '<div>' );
7745 this.$actions = $( '<div>' );
7746 this.initialized = false;
7747 this.onWindowResizeHandler = this.onWindowResize.bind( this );
7748
7749 // Events
7750 this.$element
7751 .add( this.$bar ).add( this.$group ).add( this.$actions )
7752 .on( 'mousedown keydown', this.onPointerDown.bind( this ) );
7753
7754 // Initialization
7755 this.$group.addClass( 'oo-ui-toolbar-tools' );
7756 if ( config.actions ) {
7757 this.$bar.append( this.$actions.addClass( 'oo-ui-toolbar-actions' ) );
7758 }
7759 this.$bar
7760 .addClass( 'oo-ui-toolbar-bar' )
7761 .append( this.$group, '<div style="clear:both"></div>' );
7762 if ( config.shadow ) {
7763 this.$bar.append( '<div class="oo-ui-toolbar-shadow"></div>' );
7764 }
7765 this.$element.addClass( 'oo-ui-toolbar' ).append( this.$bar );
7766 };
7767
7768 /* Setup */
7769
7770 OO.inheritClass( OO.ui.Toolbar, OO.ui.Element );
7771 OO.mixinClass( OO.ui.Toolbar, OO.EventEmitter );
7772 OO.mixinClass( OO.ui.Toolbar, OO.ui.mixin.GroupElement );
7773
7774 /* Methods */
7775
7776 /**
7777 * Get the tool factory.
7778 *
7779 * @return {OO.ui.ToolFactory} Tool factory
7780 */
7781 OO.ui.Toolbar.prototype.getToolFactory = function () {
7782 return this.toolFactory;
7783 };
7784
7785 /**
7786 * Get the toolgroup factory.
7787 *
7788 * @return {OO.Factory} Toolgroup factory
7789 */
7790 OO.ui.Toolbar.prototype.getToolGroupFactory = function () {
7791 return this.toolGroupFactory;
7792 };
7793
7794 /**
7795 * Handles mouse down events.
7796 *
7797 * @private
7798 * @param {jQuery.Event} e Mouse down event
7799 */
7800 OO.ui.Toolbar.prototype.onPointerDown = function ( e ) {
7801 var $closestWidgetToEvent = $( e.target ).closest( '.oo-ui-widget' ),
7802 $closestWidgetToToolbar = this.$element.closest( '.oo-ui-widget' );
7803 if ( !$closestWidgetToEvent.length || $closestWidgetToEvent[ 0 ] === $closestWidgetToToolbar[ 0 ] ) {
7804 return false;
7805 }
7806 };
7807
7808 /**
7809 * Handle window resize event.
7810 *
7811 * @private
7812 * @param {jQuery.Event} e Window resize event
7813 */
7814 OO.ui.Toolbar.prototype.onWindowResize = function () {
7815 this.$element.toggleClass(
7816 'oo-ui-toolbar-narrow',
7817 this.$bar.width() <= this.narrowThreshold
7818 );
7819 };
7820
7821 /**
7822 * Sets up handles and preloads required information for the toolbar to work.
7823 * This must be called after it is attached to a visible document and before doing anything else.
7824 */
7825 OO.ui.Toolbar.prototype.initialize = function () {
7826 if ( !this.initialized ) {
7827 this.initialized = true;
7828 this.narrowThreshold = this.$group.width() + this.$actions.width();
7829 $( this.getElementWindow() ).on( 'resize', this.onWindowResizeHandler );
7830 this.onWindowResize();
7831 }
7832 };
7833
7834 /**
7835 * Set up the toolbar.
7836 *
7837 * The toolbar is set up with a list of toolgroup configurations that specify the type of
7838 * toolgroup ({@link OO.ui.BarToolGroup bar}, {@link OO.ui.MenuToolGroup menu}, or {@link OO.ui.ListToolGroup list})
7839 * to add and which tools to include, exclude, promote, or demote within that toolgroup. Please
7840 * see {@link OO.ui.ToolGroup toolgroups} for more information about including tools in toolgroups.
7841 *
7842 * @param {Object.<string,Array>} groups List of toolgroup configurations
7843 * @param {Array|string} [groups.include] Tools to include in the toolgroup
7844 * @param {Array|string} [groups.exclude] Tools to exclude from the toolgroup
7845 * @param {Array|string} [groups.promote] Tools to promote to the beginning of the toolgroup
7846 * @param {Array|string} [groups.demote] Tools to demote to the end of the toolgroup
7847 */
7848 OO.ui.Toolbar.prototype.setup = function ( groups ) {
7849 var i, len, type, group,
7850 items = [],
7851 defaultType = 'bar';
7852
7853 // Cleanup previous groups
7854 this.reset();
7855
7856 // Build out new groups
7857 for ( i = 0, len = groups.length; i < len; i++ ) {
7858 group = groups[ i ];
7859 if ( group.include === '*' ) {
7860 // Apply defaults to catch-all groups
7861 if ( group.type === undefined ) {
7862 group.type = 'list';
7863 }
7864 if ( group.label === undefined ) {
7865 group.label = OO.ui.msg( 'ooui-toolbar-more' );
7866 }
7867 }
7868 // Check type has been registered
7869 type = this.getToolGroupFactory().lookup( group.type ) ? group.type : defaultType;
7870 items.push(
7871 this.getToolGroupFactory().create( type, this, group )
7872 );
7873 }
7874 this.addItems( items );
7875 };
7876
7877 /**
7878 * Remove all tools and toolgroups from the toolbar.
7879 */
7880 OO.ui.Toolbar.prototype.reset = function () {
7881 var i, len;
7882
7883 this.groups = [];
7884 this.tools = {};
7885 for ( i = 0, len = this.items.length; i < len; i++ ) {
7886 this.items[ i ].destroy();
7887 }
7888 this.clearItems();
7889 };
7890
7891 /**
7892 * Destroy the toolbar.
7893 *
7894 * Destroying the toolbar removes all event handlers and DOM elements that constitute the toolbar. Call
7895 * this method whenever you are done using a toolbar.
7896 */
7897 OO.ui.Toolbar.prototype.destroy = function () {
7898 $( this.getElementWindow() ).off( 'resize', this.onWindowResizeHandler );
7899 this.reset();
7900 this.$element.remove();
7901 };
7902
7903 /**
7904 * Check if the tool is available.
7905 *
7906 * Available tools are ones that have not yet been added to the toolbar.
7907 *
7908 * @param {string} name Symbolic name of tool
7909 * @return {boolean} Tool is available
7910 */
7911 OO.ui.Toolbar.prototype.isToolAvailable = function ( name ) {
7912 return !this.tools[ name ];
7913 };
7914
7915 /**
7916 * Prevent tool from being used again.
7917 *
7918 * @param {OO.ui.Tool} tool Tool to reserve
7919 */
7920 OO.ui.Toolbar.prototype.reserveTool = function ( tool ) {
7921 this.tools[ tool.getName() ] = tool;
7922 };
7923
7924 /**
7925 * Allow tool to be used again.
7926 *
7927 * @param {OO.ui.Tool} tool Tool to release
7928 */
7929 OO.ui.Toolbar.prototype.releaseTool = function ( tool ) {
7930 delete this.tools[ tool.getName() ];
7931 };
7932
7933 /**
7934 * Get accelerator label for tool.
7935 *
7936 * The OOjs UI library does not contain an accelerator system, but this is the hook for one. To
7937 * use an accelerator system, subclass the toolbar and override this method, which is meant to return a label
7938 * that describes the accelerator keys for the tool passed (by symbolic name) to the method.
7939 *
7940 * @param {string} name Symbolic name of tool
7941 * @return {string|undefined} Tool accelerator label if available
7942 */
7943 OO.ui.Toolbar.prototype.getToolAccelerator = function () {
7944 return undefined;
7945 };
7946
7947 /**
7948 * ToolGroups are collections of {@link OO.ui.Tool tools} that are used in a {@link OO.ui.Toolbar toolbar}.
7949 * The type of toolgroup ({@link OO.ui.ListToolGroup list}, {@link OO.ui.BarToolGroup bar}, or {@link OO.ui.MenuToolGroup menu})
7950 * to which a tool belongs determines how the tool is arranged and displayed in the toolbar. Toolgroups
7951 * themselves are created on demand with a {@link OO.ui.ToolGroupFactory toolgroup factory}.
7952 *
7953 * Toolgroups can contain individual tools, groups of tools, or all available tools:
7954 *
7955 * To include an individual tool (or array of individual tools), specify tools by symbolic name:
7956 *
7957 * include: [ 'tool-name' ] or [ { name: 'tool-name' }]
7958 *
7959 * To include a group of tools, specify the group name. (The tool's static ‘group’ config is used to assign the tool to a group.)
7960 *
7961 * include: [ { group: 'group-name' } ]
7962 *
7963 * To include all tools that are not yet assigned to a toolgroup, use the catch-all selector, an asterisk (*):
7964 *
7965 * include: '*'
7966 *
7967 * See {@link OO.ui.Toolbar toolbars} for a full example. For more information about toolbars in general,
7968 * please see the [OOjs UI documentation on MediaWiki][1].
7969 *
7970 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
7971 *
7972 * @abstract
7973 * @class
7974 * @extends OO.ui.Widget
7975 * @mixins OO.ui.mixin.GroupElement
7976 *
7977 * @constructor
7978 * @param {OO.ui.Toolbar} toolbar
7979 * @param {Object} [config] Configuration options
7980 * @cfg {Array|string} [include=[]] List of tools to include in the toolgroup.
7981 * @cfg {Array|string} [exclude=[]] List of tools to exclude from the toolgroup.
7982 * @cfg {Array|string} [promote=[]] List of tools to promote to the beginning of the toolgroup.
7983 * @cfg {Array|string} [demote=[]] List of tools to demote to the end of the toolgroup.
7984 * This setting is particularly useful when tools have been added to the toolgroup
7985 * en masse (e.g., via the catch-all selector).
7986 */
7987 OO.ui.ToolGroup = function OoUiToolGroup( toolbar, config ) {
7988 // Allow passing positional parameters inside the config object
7989 if ( OO.isPlainObject( toolbar ) && config === undefined ) {
7990 config = toolbar;
7991 toolbar = config.toolbar;
7992 }
7993
7994 // Configuration initialization
7995 config = config || {};
7996
7997 // Parent constructor
7998 OO.ui.ToolGroup.parent.call( this, config );
7999
8000 // Mixin constructors
8001 OO.ui.mixin.GroupElement.call( this, config );
8002
8003 // Properties
8004 this.toolbar = toolbar;
8005 this.tools = {};
8006 this.pressed = null;
8007 this.autoDisabled = false;
8008 this.include = config.include || [];
8009 this.exclude = config.exclude || [];
8010 this.promote = config.promote || [];
8011 this.demote = config.demote || [];
8012 this.onCapturedMouseKeyUpHandler = this.onCapturedMouseKeyUp.bind( this );
8013
8014 // Events
8015 this.$element.on( {
8016 mousedown: this.onMouseKeyDown.bind( this ),
8017 mouseup: this.onMouseKeyUp.bind( this ),
8018 keydown: this.onMouseKeyDown.bind( this ),
8019 keyup: this.onMouseKeyUp.bind( this ),
8020 focus: this.onMouseOverFocus.bind( this ),
8021 blur: this.onMouseOutBlur.bind( this ),
8022 mouseover: this.onMouseOverFocus.bind( this ),
8023 mouseout: this.onMouseOutBlur.bind( this )
8024 } );
8025 this.toolbar.getToolFactory().connect( this, { register: 'onToolFactoryRegister' } );
8026 this.aggregate( { disable: 'itemDisable' } );
8027 this.connect( this, { itemDisable: 'updateDisabled' } );
8028
8029 // Initialization
8030 this.$group.addClass( 'oo-ui-toolGroup-tools' );
8031 this.$element
8032 .addClass( 'oo-ui-toolGroup' )
8033 .append( this.$group );
8034 this.populate();
8035 };
8036
8037 /* Setup */
8038
8039 OO.inheritClass( OO.ui.ToolGroup, OO.ui.Widget );
8040 OO.mixinClass( OO.ui.ToolGroup, OO.ui.mixin.GroupElement );
8041
8042 /* Events */
8043
8044 /**
8045 * @event update
8046 */
8047
8048 /* Static Properties */
8049
8050 /**
8051 * Show labels in tooltips.
8052 *
8053 * @static
8054 * @inheritable
8055 * @property {boolean}
8056 */
8057 OO.ui.ToolGroup.static.titleTooltips = false;
8058
8059 /**
8060 * Show acceleration labels in tooltips.
8061 *
8062 * Note: The OOjs UI library does not include an accelerator system, but does contain
8063 * a hook for one. To use an accelerator system, subclass the {@link OO.ui.Toolbar toolbar} and
8064 * override the {@link OO.ui.Toolbar#getToolAccelerator getToolAccelerator} method, which is
8065 * meant to return a label that describes the accelerator keys for a given tool (e.g., 'Ctrl + M').
8066 *
8067 * @static
8068 * @inheritable
8069 * @property {boolean}
8070 */
8071 OO.ui.ToolGroup.static.accelTooltips = false;
8072
8073 /**
8074 * Automatically disable the toolgroup when all tools are disabled
8075 *
8076 * @static
8077 * @inheritable
8078 * @property {boolean}
8079 */
8080 OO.ui.ToolGroup.static.autoDisable = true;
8081
8082 /* Methods */
8083
8084 /**
8085 * @inheritdoc
8086 */
8087 OO.ui.ToolGroup.prototype.isDisabled = function () {
8088 return this.autoDisabled || OO.ui.ToolGroup.parent.prototype.isDisabled.apply( this, arguments );
8089 };
8090
8091 /**
8092 * @inheritdoc
8093 */
8094 OO.ui.ToolGroup.prototype.updateDisabled = function () {
8095 var i, item, allDisabled = true;
8096
8097 if ( this.constructor.static.autoDisable ) {
8098 for ( i = this.items.length - 1; i >= 0; i-- ) {
8099 item = this.items[ i ];
8100 if ( !item.isDisabled() ) {
8101 allDisabled = false;
8102 break;
8103 }
8104 }
8105 this.autoDisabled = allDisabled;
8106 }
8107 OO.ui.ToolGroup.parent.prototype.updateDisabled.apply( this, arguments );
8108 };
8109
8110 /**
8111 * Handle mouse down and key down events.
8112 *
8113 * @protected
8114 * @param {jQuery.Event} e Mouse down or key down event
8115 */
8116 OO.ui.ToolGroup.prototype.onMouseKeyDown = function ( e ) {
8117 if (
8118 !this.isDisabled() &&
8119 ( e.which === 1 || e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
8120 ) {
8121 this.pressed = this.getTargetTool( e );
8122 if ( this.pressed ) {
8123 this.pressed.setActive( true );
8124 OO.ui.addCaptureEventListener( this.getElementDocument(), 'mouseup', this.onCapturedMouseKeyUpHandler );
8125 OO.ui.addCaptureEventListener( this.getElementDocument(), 'keyup', this.onCapturedMouseKeyUpHandler );
8126 }
8127 return false;
8128 }
8129 };
8130
8131 /**
8132 * Handle captured mouse up and key up events.
8133 *
8134 * @protected
8135 * @param {Event} e Mouse up or key up event
8136 */
8137 OO.ui.ToolGroup.prototype.onCapturedMouseKeyUp = function ( e ) {
8138 OO.ui.removeCaptureEventListener( this.getElementDocument(), 'mouseup', this.onCapturedMouseKeyUpHandler );
8139 OO.ui.removeCaptureEventListener( this.getElementDocument(), 'keyup', this.onCapturedMouseKeyUpHandler );
8140 // onMouseKeyUp may be called a second time, depending on where the mouse is when the button is
8141 // released, but since `this.pressed` will no longer be true, the second call will be ignored.
8142 this.onMouseKeyUp( e );
8143 };
8144
8145 /**
8146 * Handle mouse up and key up events.
8147 *
8148 * @protected
8149 * @param {jQuery.Event} e Mouse up or key up event
8150 */
8151 OO.ui.ToolGroup.prototype.onMouseKeyUp = function ( e ) {
8152 var tool = this.getTargetTool( e );
8153
8154 if (
8155 !this.isDisabled() && this.pressed && this.pressed === tool &&
8156 ( e.which === 1 || e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
8157 ) {
8158 this.pressed.onSelect();
8159 this.pressed = null;
8160 return false;
8161 }
8162
8163 this.pressed = null;
8164 };
8165
8166 /**
8167 * Handle mouse over and focus events.
8168 *
8169 * @protected
8170 * @param {jQuery.Event} e Mouse over or focus event
8171 */
8172 OO.ui.ToolGroup.prototype.onMouseOverFocus = function ( e ) {
8173 var tool = this.getTargetTool( e );
8174
8175 if ( this.pressed && this.pressed === tool ) {
8176 this.pressed.setActive( true );
8177 }
8178 };
8179
8180 /**
8181 * Handle mouse out and blur events.
8182 *
8183 * @protected
8184 * @param {jQuery.Event} e Mouse out or blur event
8185 */
8186 OO.ui.ToolGroup.prototype.onMouseOutBlur = function ( e ) {
8187 var tool = this.getTargetTool( e );
8188
8189 if ( this.pressed && this.pressed === tool ) {
8190 this.pressed.setActive( false );
8191 }
8192 };
8193
8194 /**
8195 * Get the closest tool to a jQuery.Event.
8196 *
8197 * Only tool links are considered, which prevents other elements in the tool such as popups from
8198 * triggering tool group interactions.
8199 *
8200 * @private
8201 * @param {jQuery.Event} e
8202 * @return {OO.ui.Tool|null} Tool, `null` if none was found
8203 */
8204 OO.ui.ToolGroup.prototype.getTargetTool = function ( e ) {
8205 var tool,
8206 $item = $( e.target ).closest( '.oo-ui-tool-link' );
8207
8208 if ( $item.length ) {
8209 tool = $item.parent().data( 'oo-ui-tool' );
8210 }
8211
8212 return tool && !tool.isDisabled() ? tool : null;
8213 };
8214
8215 /**
8216 * Handle tool registry register events.
8217 *
8218 * If a tool is registered after the group is created, we must repopulate the list to account for:
8219 *
8220 * - a tool being added that may be included
8221 * - a tool already included being overridden
8222 *
8223 * @protected
8224 * @param {string} name Symbolic name of tool
8225 */
8226 OO.ui.ToolGroup.prototype.onToolFactoryRegister = function () {
8227 this.populate();
8228 };
8229
8230 /**
8231 * Get the toolbar that contains the toolgroup.
8232 *
8233 * @return {OO.ui.Toolbar} Toolbar that contains the toolgroup
8234 */
8235 OO.ui.ToolGroup.prototype.getToolbar = function () {
8236 return this.toolbar;
8237 };
8238
8239 /**
8240 * Add and remove tools based on configuration.
8241 */
8242 OO.ui.ToolGroup.prototype.populate = function () {
8243 var i, len, name, tool,
8244 toolFactory = this.toolbar.getToolFactory(),
8245 names = {},
8246 add = [],
8247 remove = [],
8248 list = this.toolbar.getToolFactory().getTools(
8249 this.include, this.exclude, this.promote, this.demote
8250 );
8251
8252 // Build a list of needed tools
8253 for ( i = 0, len = list.length; i < len; i++ ) {
8254 name = list[ i ];
8255 if (
8256 // Tool exists
8257 toolFactory.lookup( name ) &&
8258 // Tool is available or is already in this group
8259 ( this.toolbar.isToolAvailable( name ) || this.tools[ name ] )
8260 ) {
8261 // Hack to prevent infinite recursion via ToolGroupTool. We need to reserve the tool before
8262 // creating it, but we can't call reserveTool() yet because we haven't created the tool.
8263 this.toolbar.tools[ name ] = true;
8264 tool = this.tools[ name ];
8265 if ( !tool ) {
8266 // Auto-initialize tools on first use
8267 this.tools[ name ] = tool = toolFactory.create( name, this );
8268 tool.updateTitle();
8269 }
8270 this.toolbar.reserveTool( tool );
8271 add.push( tool );
8272 names[ name ] = true;
8273 }
8274 }
8275 // Remove tools that are no longer needed
8276 for ( name in this.tools ) {
8277 if ( !names[ name ] ) {
8278 this.tools[ name ].destroy();
8279 this.toolbar.releaseTool( this.tools[ name ] );
8280 remove.push( this.tools[ name ] );
8281 delete this.tools[ name ];
8282 }
8283 }
8284 if ( remove.length ) {
8285 this.removeItems( remove );
8286 }
8287 // Update emptiness state
8288 if ( add.length ) {
8289 this.$element.removeClass( 'oo-ui-toolGroup-empty' );
8290 } else {
8291 this.$element.addClass( 'oo-ui-toolGroup-empty' );
8292 }
8293 // Re-add tools (moving existing ones to new locations)
8294 this.addItems( add );
8295 // Disabled state may depend on items
8296 this.updateDisabled();
8297 };
8298
8299 /**
8300 * Destroy toolgroup.
8301 */
8302 OO.ui.ToolGroup.prototype.destroy = function () {
8303 var name;
8304
8305 this.clearItems();
8306 this.toolbar.getToolFactory().disconnect( this );
8307 for ( name in this.tools ) {
8308 this.toolbar.releaseTool( this.tools[ name ] );
8309 this.tools[ name ].disconnect( this ).destroy();
8310 delete this.tools[ name ];
8311 }
8312 this.$element.remove();
8313 };
8314
8315 /**
8316 * MessageDialogs display a confirmation or alert message. By default, the rendered dialog box
8317 * consists of a header that contains the dialog title, a body with the message, and a footer that
8318 * contains any {@link OO.ui.ActionWidget action widgets}. The MessageDialog class is the only type
8319 * of {@link OO.ui.Dialog dialog} that is usually instantiated directly.
8320 *
8321 * There are two basic types of message dialogs, confirmation and alert:
8322 *
8323 * - **confirmation**: the dialog title describes what a progressive action will do and the message provides
8324 * more details about the consequences.
8325 * - **alert**: the dialog title describes which event occurred and the message provides more information
8326 * about why the event occurred.
8327 *
8328 * The MessageDialog class specifies two actions: ‘accept’, the primary
8329 * action (e.g., ‘ok’) and ‘reject,’ the safe action (e.g., ‘cancel’). Both will close the window,
8330 * passing along the selected action.
8331 *
8332 * For more information and examples, please see the [OOjs UI documentation on MediaWiki][1].
8333 *
8334 * @example
8335 * // Example: Creating and opening a message dialog window.
8336 * var messageDialog = new OO.ui.MessageDialog();
8337 *
8338 * // Create and append a window manager.
8339 * var windowManager = new OO.ui.WindowManager();
8340 * $( 'body' ).append( windowManager.$element );
8341 * windowManager.addWindows( [ messageDialog ] );
8342 * // Open the window.
8343 * windowManager.openWindow( messageDialog, {
8344 * title: 'Basic message dialog',
8345 * message: 'This is the message'
8346 * } );
8347 *
8348 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Message_Dialogs
8349 *
8350 * @class
8351 * @extends OO.ui.Dialog
8352 *
8353 * @constructor
8354 * @param {Object} [config] Configuration options
8355 */
8356 OO.ui.MessageDialog = function OoUiMessageDialog( config ) {
8357 // Parent constructor
8358 OO.ui.MessageDialog.parent.call( this, config );
8359
8360 // Properties
8361 this.verticalActionLayout = null;
8362
8363 // Initialization
8364 this.$element.addClass( 'oo-ui-messageDialog' );
8365 };
8366
8367 /* Setup */
8368
8369 OO.inheritClass( OO.ui.MessageDialog, OO.ui.Dialog );
8370
8371 /* Static Properties */
8372
8373 OO.ui.MessageDialog.static.name = 'message';
8374
8375 OO.ui.MessageDialog.static.size = 'small';
8376
8377 OO.ui.MessageDialog.static.verbose = false;
8378
8379 /**
8380 * Dialog title.
8381 *
8382 * The title of a confirmation dialog describes what a progressive action will do. The
8383 * title of an alert dialog describes which event occurred.
8384 *
8385 * @static
8386 * @inheritable
8387 * @property {jQuery|string|Function|null}
8388 */
8389 OO.ui.MessageDialog.static.title = null;
8390
8391 /**
8392 * The message displayed in the dialog body.
8393 *
8394 * A confirmation message describes the consequences of a progressive action. An alert
8395 * message describes why an event occurred.
8396 *
8397 * @static
8398 * @inheritable
8399 * @property {jQuery|string|Function|null}
8400 */
8401 OO.ui.MessageDialog.static.message = null;
8402
8403 OO.ui.MessageDialog.static.actions = [
8404 { action: 'accept', label: OO.ui.deferMsg( 'ooui-dialog-message-accept' ), flags: 'primary' },
8405 { action: 'reject', label: OO.ui.deferMsg( 'ooui-dialog-message-reject' ), flags: 'safe' }
8406 ];
8407
8408 /* Methods */
8409
8410 /**
8411 * @inheritdoc
8412 */
8413 OO.ui.MessageDialog.prototype.setManager = function ( manager ) {
8414 OO.ui.MessageDialog.parent.prototype.setManager.call( this, manager );
8415
8416 // Events
8417 this.manager.connect( this, {
8418 resize: 'onResize'
8419 } );
8420
8421 return this;
8422 };
8423
8424 /**
8425 * @inheritdoc
8426 */
8427 OO.ui.MessageDialog.prototype.onActionResize = function ( action ) {
8428 this.fitActions();
8429 return OO.ui.MessageDialog.parent.prototype.onActionResize.call( this, action );
8430 };
8431
8432 /**
8433 * Handle window resized events.
8434 *
8435 * @private
8436 */
8437 OO.ui.MessageDialog.prototype.onResize = function () {
8438 var dialog = this;
8439 dialog.fitActions();
8440 // Wait for CSS transition to finish and do it again :(
8441 setTimeout( function () {
8442 dialog.fitActions();
8443 }, 300 );
8444 };
8445
8446 /**
8447 * Toggle action layout between vertical and horizontal.
8448 *
8449 * @private
8450 * @param {boolean} [value] Layout actions vertically, omit to toggle
8451 * @chainable
8452 */
8453 OO.ui.MessageDialog.prototype.toggleVerticalActionLayout = function ( value ) {
8454 value = value === undefined ? !this.verticalActionLayout : !!value;
8455
8456 if ( value !== this.verticalActionLayout ) {
8457 this.verticalActionLayout = value;
8458 this.$actions
8459 .toggleClass( 'oo-ui-messageDialog-actions-vertical', value )
8460 .toggleClass( 'oo-ui-messageDialog-actions-horizontal', !value );
8461 }
8462
8463 return this;
8464 };
8465
8466 /**
8467 * @inheritdoc
8468 */
8469 OO.ui.MessageDialog.prototype.getActionProcess = function ( action ) {
8470 if ( action ) {
8471 return new OO.ui.Process( function () {
8472 this.close( { action: action } );
8473 }, this );
8474 }
8475 return OO.ui.MessageDialog.parent.prototype.getActionProcess.call( this, action );
8476 };
8477
8478 /**
8479 * @inheritdoc
8480 *
8481 * @param {Object} [data] Dialog opening data
8482 * @param {jQuery|string|Function|null} [data.title] Description of the action being confirmed
8483 * @param {jQuery|string|Function|null} [data.message] Description of the action's consequence
8484 * @param {boolean} [data.verbose] Message is verbose and should be styled as a long message
8485 * @param {Object[]} [data.actions] List of OO.ui.ActionOptionWidget configuration options for each
8486 * action item
8487 */
8488 OO.ui.MessageDialog.prototype.getSetupProcess = function ( data ) {
8489 data = data || {};
8490
8491 // Parent method
8492 return OO.ui.MessageDialog.parent.prototype.getSetupProcess.call( this, data )
8493 .next( function () {
8494 this.title.setLabel(
8495 data.title !== undefined ? data.title : this.constructor.static.title
8496 );
8497 this.message.setLabel(
8498 data.message !== undefined ? data.message : this.constructor.static.message
8499 );
8500 this.message.$element.toggleClass(
8501 'oo-ui-messageDialog-message-verbose',
8502 data.verbose !== undefined ? data.verbose : this.constructor.static.verbose
8503 );
8504 }, this );
8505 };
8506
8507 /**
8508 * @inheritdoc
8509 */
8510 OO.ui.MessageDialog.prototype.getReadyProcess = function ( data ) {
8511 data = data || {};
8512
8513 // Parent method
8514 return OO.ui.MessageDialog.parent.prototype.getReadyProcess.call( this, data )
8515 .next( function () {
8516 // Focus the primary action button
8517 var actions = this.actions.get();
8518 actions = actions.filter( function ( action ) {
8519 return action.getFlags().indexOf( 'primary' ) > -1;
8520 } );
8521 if ( actions.length > 0 ) {
8522 actions[ 0 ].$button.focus();
8523 }
8524 }, this );
8525 };
8526
8527 /**
8528 * @inheritdoc
8529 */
8530 OO.ui.MessageDialog.prototype.getBodyHeight = function () {
8531 var bodyHeight, oldOverflow,
8532 $scrollable = this.container.$element;
8533
8534 oldOverflow = $scrollable[ 0 ].style.overflow;
8535 $scrollable[ 0 ].style.overflow = 'hidden';
8536
8537 OO.ui.Element.static.reconsiderScrollbars( $scrollable[ 0 ] );
8538
8539 bodyHeight = this.text.$element.outerHeight( true );
8540 $scrollable[ 0 ].style.overflow = oldOverflow;
8541
8542 return bodyHeight;
8543 };
8544
8545 /**
8546 * @inheritdoc
8547 */
8548 OO.ui.MessageDialog.prototype.setDimensions = function ( dim ) {
8549 var $scrollable = this.container.$element;
8550 OO.ui.MessageDialog.parent.prototype.setDimensions.call( this, dim );
8551
8552 // Twiddle the overflow property, otherwise an unnecessary scrollbar will be produced.
8553 // Need to do it after transition completes (250ms), add 50ms just in case.
8554 setTimeout( function () {
8555 var oldOverflow = $scrollable[ 0 ].style.overflow;
8556 $scrollable[ 0 ].style.overflow = 'hidden';
8557
8558 OO.ui.Element.static.reconsiderScrollbars( $scrollable[ 0 ] );
8559
8560 $scrollable[ 0 ].style.overflow = oldOverflow;
8561 }, 300 );
8562
8563 return this;
8564 };
8565
8566 /**
8567 * @inheritdoc
8568 */
8569 OO.ui.MessageDialog.prototype.initialize = function () {
8570 // Parent method
8571 OO.ui.MessageDialog.parent.prototype.initialize.call( this );
8572
8573 // Properties
8574 this.$actions = $( '<div>' );
8575 this.container = new OO.ui.PanelLayout( {
8576 scrollable: true, classes: [ 'oo-ui-messageDialog-container' ]
8577 } );
8578 this.text = new OO.ui.PanelLayout( {
8579 padded: true, expanded: false, classes: [ 'oo-ui-messageDialog-text' ]
8580 } );
8581 this.message = new OO.ui.LabelWidget( {
8582 classes: [ 'oo-ui-messageDialog-message' ]
8583 } );
8584
8585 // Initialization
8586 this.title.$element.addClass( 'oo-ui-messageDialog-title' );
8587 this.$content.addClass( 'oo-ui-messageDialog-content' );
8588 this.container.$element.append( this.text.$element );
8589 this.text.$element.append( this.title.$element, this.message.$element );
8590 this.$body.append( this.container.$element );
8591 this.$actions.addClass( 'oo-ui-messageDialog-actions' );
8592 this.$foot.append( this.$actions );
8593 };
8594
8595 /**
8596 * @inheritdoc
8597 */
8598 OO.ui.MessageDialog.prototype.attachActions = function () {
8599 var i, len, other, special, others;
8600
8601 // Parent method
8602 OO.ui.MessageDialog.parent.prototype.attachActions.call( this );
8603
8604 special = this.actions.getSpecial();
8605 others = this.actions.getOthers();
8606
8607 if ( special.safe ) {
8608 this.$actions.append( special.safe.$element );
8609 special.safe.toggleFramed( false );
8610 }
8611 if ( others.length ) {
8612 for ( i = 0, len = others.length; i < len; i++ ) {
8613 other = others[ i ];
8614 this.$actions.append( other.$element );
8615 other.toggleFramed( false );
8616 }
8617 }
8618 if ( special.primary ) {
8619 this.$actions.append( special.primary.$element );
8620 special.primary.toggleFramed( false );
8621 }
8622
8623 if ( !this.isOpening() ) {
8624 // If the dialog is currently opening, this will be called automatically soon.
8625 // This also calls #fitActions.
8626 this.updateSize();
8627 }
8628 };
8629
8630 /**
8631 * Fit action actions into columns or rows.
8632 *
8633 * Columns will be used if all labels can fit without overflow, otherwise rows will be used.
8634 *
8635 * @private
8636 */
8637 OO.ui.MessageDialog.prototype.fitActions = function () {
8638 var i, len, action,
8639 previous = this.verticalActionLayout,
8640 actions = this.actions.get();
8641
8642 // Detect clipping
8643 this.toggleVerticalActionLayout( false );
8644 for ( i = 0, len = actions.length; i < len; i++ ) {
8645 action = actions[ i ];
8646 if ( action.$element.innerWidth() < action.$label.outerWidth( true ) ) {
8647 this.toggleVerticalActionLayout( true );
8648 break;
8649 }
8650 }
8651
8652 // Move the body out of the way of the foot
8653 this.$body.css( 'bottom', this.$foot.outerHeight( true ) );
8654
8655 if ( this.verticalActionLayout !== previous ) {
8656 // We changed the layout, window height might need to be updated.
8657 this.updateSize();
8658 }
8659 };
8660
8661 /**
8662 * ProcessDialog windows encapsulate a {@link OO.ui.Process process} and all of the code necessary
8663 * to complete it. If the process terminates with an error, a customizable {@link OO.ui.Error error
8664 * interface} alerts users to the trouble, permitting the user to dismiss the error and try again when
8665 * relevant. The ProcessDialog class is always extended and customized with the actions and content
8666 * required for each process.
8667 *
8668 * The process dialog box consists of a header that visually represents the ‘working’ state of long
8669 * processes with an animation. The header contains the dialog title as well as
8670 * two {@link OO.ui.ActionWidget action widgets}: a ‘safe’ action on the left (e.g., ‘Cancel’) and
8671 * a ‘primary’ action on the right (e.g., ‘Done’).
8672 *
8673 * Like other windows, the process dialog is managed by a {@link OO.ui.WindowManager window manager}.
8674 * Please see the [OOjs UI documentation on MediaWiki][1] for more information and examples.
8675 *
8676 * @example
8677 * // Example: Creating and opening a process dialog window.
8678 * function MyProcessDialog( config ) {
8679 * MyProcessDialog.parent.call( this, config );
8680 * }
8681 * OO.inheritClass( MyProcessDialog, OO.ui.ProcessDialog );
8682 *
8683 * MyProcessDialog.static.title = 'Process dialog';
8684 * MyProcessDialog.static.actions = [
8685 * { action: 'save', label: 'Done', flags: 'primary' },
8686 * { label: 'Cancel', flags: 'safe' }
8687 * ];
8688 *
8689 * MyProcessDialog.prototype.initialize = function () {
8690 * MyProcessDialog.parent.prototype.initialize.apply( this, arguments );
8691 * this.content = new OO.ui.PanelLayout( { padded: true, expanded: false } );
8692 * 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>' );
8693 * this.$body.append( this.content.$element );
8694 * };
8695 * MyProcessDialog.prototype.getActionProcess = function ( action ) {
8696 * var dialog = this;
8697 * if ( action ) {
8698 * return new OO.ui.Process( function () {
8699 * dialog.close( { action: action } );
8700 * } );
8701 * }
8702 * return MyProcessDialog.parent.prototype.getActionProcess.call( this, action );
8703 * };
8704 *
8705 * var windowManager = new OO.ui.WindowManager();
8706 * $( 'body' ).append( windowManager.$element );
8707 *
8708 * var dialog = new MyProcessDialog();
8709 * windowManager.addWindows( [ dialog ] );
8710 * windowManager.openWindow( dialog );
8711 *
8712 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs
8713 *
8714 * @abstract
8715 * @class
8716 * @extends OO.ui.Dialog
8717 *
8718 * @constructor
8719 * @param {Object} [config] Configuration options
8720 */
8721 OO.ui.ProcessDialog = function OoUiProcessDialog( config ) {
8722 // Parent constructor
8723 OO.ui.ProcessDialog.parent.call( this, config );
8724
8725 // Properties
8726 this.fitOnOpen = false;
8727
8728 // Initialization
8729 this.$element.addClass( 'oo-ui-processDialog' );
8730 };
8731
8732 /* Setup */
8733
8734 OO.inheritClass( OO.ui.ProcessDialog, OO.ui.Dialog );
8735
8736 /* Methods */
8737
8738 /**
8739 * Handle dismiss button click events.
8740 *
8741 * Hides errors.
8742 *
8743 * @private
8744 */
8745 OO.ui.ProcessDialog.prototype.onDismissErrorButtonClick = function () {
8746 this.hideErrors();
8747 };
8748
8749 /**
8750 * Handle retry button click events.
8751 *
8752 * Hides errors and then tries again.
8753 *
8754 * @private
8755 */
8756 OO.ui.ProcessDialog.prototype.onRetryButtonClick = function () {
8757 this.hideErrors();
8758 this.executeAction( this.currentAction );
8759 };
8760
8761 /**
8762 * @inheritdoc
8763 */
8764 OO.ui.ProcessDialog.prototype.onActionResize = function ( action ) {
8765 if ( this.actions.isSpecial( action ) ) {
8766 this.fitLabel();
8767 }
8768 return OO.ui.ProcessDialog.parent.prototype.onActionResize.call( this, action );
8769 };
8770
8771 /**
8772 * @inheritdoc
8773 */
8774 OO.ui.ProcessDialog.prototype.initialize = function () {
8775 // Parent method
8776 OO.ui.ProcessDialog.parent.prototype.initialize.call( this );
8777
8778 // Properties
8779 this.$navigation = $( '<div>' );
8780 this.$location = $( '<div>' );
8781 this.$safeActions = $( '<div>' );
8782 this.$primaryActions = $( '<div>' );
8783 this.$otherActions = $( '<div>' );
8784 this.dismissButton = new OO.ui.ButtonWidget( {
8785 label: OO.ui.msg( 'ooui-dialog-process-dismiss' )
8786 } );
8787 this.retryButton = new OO.ui.ButtonWidget();
8788 this.$errors = $( '<div>' );
8789 this.$errorsTitle = $( '<div>' );
8790
8791 // Events
8792 this.dismissButton.connect( this, { click: 'onDismissErrorButtonClick' } );
8793 this.retryButton.connect( this, { click: 'onRetryButtonClick' } );
8794
8795 // Initialization
8796 this.title.$element.addClass( 'oo-ui-processDialog-title' );
8797 this.$location
8798 .append( this.title.$element )
8799 .addClass( 'oo-ui-processDialog-location' );
8800 this.$safeActions.addClass( 'oo-ui-processDialog-actions-safe' );
8801 this.$primaryActions.addClass( 'oo-ui-processDialog-actions-primary' );
8802 this.$otherActions.addClass( 'oo-ui-processDialog-actions-other' );
8803 this.$errorsTitle
8804 .addClass( 'oo-ui-processDialog-errors-title' )
8805 .text( OO.ui.msg( 'ooui-dialog-process-error' ) );
8806 this.$errors
8807 .addClass( 'oo-ui-processDialog-errors oo-ui-element-hidden' )
8808 .append( this.$errorsTitle, this.dismissButton.$element, this.retryButton.$element );
8809 this.$content
8810 .addClass( 'oo-ui-processDialog-content' )
8811 .append( this.$errors );
8812 this.$navigation
8813 .addClass( 'oo-ui-processDialog-navigation' )
8814 .append( this.$safeActions, this.$location, this.$primaryActions );
8815 this.$head.append( this.$navigation );
8816 this.$foot.append( this.$otherActions );
8817 };
8818
8819 /**
8820 * @inheritdoc
8821 */
8822 OO.ui.ProcessDialog.prototype.getActionWidgets = function ( actions ) {
8823 var i, len, widgets = [];
8824 for ( i = 0, len = actions.length; i < len; i++ ) {
8825 widgets.push(
8826 new OO.ui.ActionWidget( $.extend( { framed: true }, actions[ i ] ) )
8827 );
8828 }
8829 return widgets;
8830 };
8831
8832 /**
8833 * @inheritdoc
8834 */
8835 OO.ui.ProcessDialog.prototype.attachActions = function () {
8836 var i, len, other, special, others;
8837
8838 // Parent method
8839 OO.ui.ProcessDialog.parent.prototype.attachActions.call( this );
8840
8841 special = this.actions.getSpecial();
8842 others = this.actions.getOthers();
8843 if ( special.primary ) {
8844 this.$primaryActions.append( special.primary.$element );
8845 }
8846 for ( i = 0, len = others.length; i < len; i++ ) {
8847 other = others[ i ];
8848 this.$otherActions.append( other.$element );
8849 }
8850 if ( special.safe ) {
8851 this.$safeActions.append( special.safe.$element );
8852 }
8853
8854 this.fitLabel();
8855 this.$body.css( 'bottom', this.$foot.outerHeight( true ) );
8856 };
8857
8858 /**
8859 * @inheritdoc
8860 */
8861 OO.ui.ProcessDialog.prototype.executeAction = function ( action ) {
8862 var process = this;
8863 return OO.ui.ProcessDialog.parent.prototype.executeAction.call( this, action )
8864 .fail( function ( errors ) {
8865 process.showErrors( errors || [] );
8866 } );
8867 };
8868
8869 /**
8870 * @inheritdoc
8871 */
8872 OO.ui.ProcessDialog.prototype.setDimensions = function () {
8873 // Parent method
8874 OO.ui.ProcessDialog.parent.prototype.setDimensions.apply( this, arguments );
8875
8876 this.fitLabel();
8877 };
8878
8879 /**
8880 * Fit label between actions.
8881 *
8882 * @private
8883 * @chainable
8884 */
8885 OO.ui.ProcessDialog.prototype.fitLabel = function () {
8886 var safeWidth, primaryWidth, biggerWidth, labelWidth, navigationWidth, leftWidth, rightWidth,
8887 size = this.getSizeProperties();
8888
8889 if ( typeof size.width !== 'number' ) {
8890 if ( this.isOpened() ) {
8891 navigationWidth = this.$head.width() - 20;
8892 } else if ( this.isOpening() ) {
8893 if ( !this.fitOnOpen ) {
8894 // Size is relative and the dialog isn't open yet, so wait.
8895 this.manager.opening.done( this.fitLabel.bind( this ) );
8896 this.fitOnOpen = true;
8897 }
8898 return;
8899 } else {
8900 return;
8901 }
8902 } else {
8903 navigationWidth = size.width - 20;
8904 }
8905
8906 safeWidth = this.$safeActions.is( ':visible' ) ? this.$safeActions.width() : 0;
8907 primaryWidth = this.$primaryActions.is( ':visible' ) ? this.$primaryActions.width() : 0;
8908 biggerWidth = Math.max( safeWidth, primaryWidth );
8909
8910 labelWidth = this.title.$element.width();
8911
8912 if ( 2 * biggerWidth + labelWidth < navigationWidth ) {
8913 // We have enough space to center the label
8914 leftWidth = rightWidth = biggerWidth;
8915 } else {
8916 // Let's hope we at least have enough space not to overlap, because we can't wrap the label…
8917 if ( this.getDir() === 'ltr' ) {
8918 leftWidth = safeWidth;
8919 rightWidth = primaryWidth;
8920 } else {
8921 leftWidth = primaryWidth;
8922 rightWidth = safeWidth;
8923 }
8924 }
8925
8926 this.$location.css( { paddingLeft: leftWidth, paddingRight: rightWidth } );
8927
8928 return this;
8929 };
8930
8931 /**
8932 * Handle errors that occurred during accept or reject processes.
8933 *
8934 * @private
8935 * @param {OO.ui.Error[]|OO.ui.Error} errors Errors to be handled
8936 */
8937 OO.ui.ProcessDialog.prototype.showErrors = function ( errors ) {
8938 var i, len, $item, actions,
8939 items = [],
8940 abilities = {},
8941 recoverable = true,
8942 warning = false;
8943
8944 if ( errors instanceof OO.ui.Error ) {
8945 errors = [ errors ];
8946 }
8947
8948 for ( i = 0, len = errors.length; i < len; i++ ) {
8949 if ( !errors[ i ].isRecoverable() ) {
8950 recoverable = false;
8951 }
8952 if ( errors[ i ].isWarning() ) {
8953 warning = true;
8954 }
8955 $item = $( '<div>' )
8956 .addClass( 'oo-ui-processDialog-error' )
8957 .append( errors[ i ].getMessage() );
8958 items.push( $item[ 0 ] );
8959 }
8960 this.$errorItems = $( items );
8961 if ( recoverable ) {
8962 abilities[ this.currentAction ] = true;
8963 // Copy the flags from the first matching action
8964 actions = this.actions.get( { actions: this.currentAction } );
8965 if ( actions.length ) {
8966 this.retryButton.clearFlags().setFlags( actions[ 0 ].getFlags() );
8967 }
8968 } else {
8969 abilities[ this.currentAction ] = false;
8970 this.actions.setAbilities( abilities );
8971 }
8972 if ( warning ) {
8973 this.retryButton.setLabel( OO.ui.msg( 'ooui-dialog-process-continue' ) );
8974 } else {
8975 this.retryButton.setLabel( OO.ui.msg( 'ooui-dialog-process-retry' ) );
8976 }
8977 this.retryButton.toggle( recoverable );
8978 this.$errorsTitle.after( this.$errorItems );
8979 this.$errors.removeClass( 'oo-ui-element-hidden' ).scrollTop( 0 );
8980 };
8981
8982 /**
8983 * Hide errors.
8984 *
8985 * @private
8986 */
8987 OO.ui.ProcessDialog.prototype.hideErrors = function () {
8988 this.$errors.addClass( 'oo-ui-element-hidden' );
8989 if ( this.$errorItems ) {
8990 this.$errorItems.remove();
8991 this.$errorItems = null;
8992 }
8993 };
8994
8995 /**
8996 * @inheritdoc
8997 */
8998 OO.ui.ProcessDialog.prototype.getTeardownProcess = function ( data ) {
8999 // Parent method
9000 return OO.ui.ProcessDialog.parent.prototype.getTeardownProcess.call( this, data )
9001 .first( function () {
9002 // Make sure to hide errors
9003 this.hideErrors();
9004 this.fitOnOpen = false;
9005 }, this );
9006 };
9007
9008 /**
9009 * FieldLayouts are used with OO.ui.FieldsetLayout. Each FieldLayout requires a field-widget,
9010 * which is a widget that is specified by reference before any optional configuration settings.
9011 *
9012 * Field layouts can be configured with help text and/or labels. Labels are aligned in one of four ways:
9013 *
9014 * - **left**: The label is placed before the field-widget and aligned with the left margin.
9015 * A left-alignment is used for forms with many fields.
9016 * - **right**: The label is placed before the field-widget and aligned to the right margin.
9017 * A right-alignment is used for long but familiar forms which users tab through,
9018 * verifying the current field with a quick glance at the label.
9019 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
9020 * that users fill out from top to bottom.
9021 * - **inline**: The label is placed after the field-widget and aligned to the left.
9022 * An inline-alignment is best used with checkboxes or radio buttons.
9023 *
9024 * Help text is accessed via a help icon that appears in the upper right corner of the rendered field layout.
9025 * Please see the [OOjs UI documentation on MediaWiki] [1] for examples and more information.
9026 *
9027 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Fields_and_Fieldsets
9028 * @class
9029 * @extends OO.ui.Layout
9030 * @mixins OO.ui.mixin.LabelElement
9031 * @mixins OO.ui.mixin.TitledElement
9032 *
9033 * @constructor
9034 * @param {OO.ui.Widget} fieldWidget Field widget
9035 * @param {Object} [config] Configuration options
9036 * @cfg {string} [align='left'] Alignment of the label: 'left', 'right', 'top' or 'inline'
9037 * @cfg {Array} [errors] Error messages about the widget, which will be displayed below the widget.
9038 * The array may contain strings or OO.ui.HtmlSnippet instances.
9039 * @cfg {Array} [notices] Notices about the widget, which will be displayed below the widget.
9040 * The array may contain strings or OO.ui.HtmlSnippet instances.
9041 * @cfg {string|OO.ui.HtmlSnippet} [help] Help text. When help text is specified, a "help" icon will appear
9042 * in the upper-right corner of the rendered field; clicking it will display the text in a popup.
9043 * For important messages, you are advised to use `notices`, as they are always shown.
9044 *
9045 * @throws {Error} An error is thrown if no widget is specified
9046 */
9047 OO.ui.FieldLayout = function OoUiFieldLayout( fieldWidget, config ) {
9048 var hasInputWidget, div;
9049
9050 // Allow passing positional parameters inside the config object
9051 if ( OO.isPlainObject( fieldWidget ) && config === undefined ) {
9052 config = fieldWidget;
9053 fieldWidget = config.fieldWidget;
9054 }
9055
9056 // Make sure we have required constructor arguments
9057 if ( fieldWidget === undefined ) {
9058 throw new Error( 'Widget not found' );
9059 }
9060
9061 hasInputWidget = fieldWidget.constructor.static.supportsSimpleLabel;
9062
9063 // Configuration initialization
9064 config = $.extend( { align: 'left' }, config );
9065
9066 // Parent constructor
9067 OO.ui.FieldLayout.parent.call( this, config );
9068
9069 // Mixin constructors
9070 OO.ui.mixin.LabelElement.call( this, config );
9071 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$label } ) );
9072
9073 // Properties
9074 this.fieldWidget = fieldWidget;
9075 this.errors = [];
9076 this.notices = [];
9077 this.$field = $( '<div>' );
9078 this.$messages = $( '<ul>' );
9079 this.$body = $( '<' + ( hasInputWidget ? 'label' : 'div' ) + '>' );
9080 this.align = null;
9081 if ( config.help ) {
9082 this.popupButtonWidget = new OO.ui.PopupButtonWidget( {
9083 classes: [ 'oo-ui-fieldLayout-help' ],
9084 framed: false,
9085 icon: 'info'
9086 } );
9087
9088 div = $( '<div>' );
9089 if ( config.help instanceof OO.ui.HtmlSnippet ) {
9090 div.html( config.help.toString() );
9091 } else {
9092 div.text( config.help );
9093 }
9094 this.popupButtonWidget.getPopup().$body.append(
9095 div.addClass( 'oo-ui-fieldLayout-help-content' )
9096 );
9097 this.$help = this.popupButtonWidget.$element;
9098 } else {
9099 this.$help = $( [] );
9100 }
9101
9102 // Events
9103 if ( hasInputWidget ) {
9104 this.$label.on( 'click', this.onLabelClick.bind( this ) );
9105 }
9106 this.fieldWidget.connect( this, { disable: 'onFieldDisable' } );
9107
9108 // Initialization
9109 this.$element
9110 .addClass( 'oo-ui-fieldLayout' )
9111 .append( this.$help, this.$body );
9112 this.$body.addClass( 'oo-ui-fieldLayout-body' );
9113 this.$messages.addClass( 'oo-ui-fieldLayout-messages' );
9114 this.$field
9115 .addClass( 'oo-ui-fieldLayout-field' )
9116 .toggleClass( 'oo-ui-fieldLayout-disable', this.fieldWidget.isDisabled() )
9117 .append( this.fieldWidget.$element );
9118
9119 this.setErrors( config.errors || [] );
9120 this.setNotices( config.notices || [] );
9121 this.setAlignment( config.align );
9122 };
9123
9124 /* Setup */
9125
9126 OO.inheritClass( OO.ui.FieldLayout, OO.ui.Layout );
9127 OO.mixinClass( OO.ui.FieldLayout, OO.ui.mixin.LabelElement );
9128 OO.mixinClass( OO.ui.FieldLayout, OO.ui.mixin.TitledElement );
9129
9130 /* Methods */
9131
9132 /**
9133 * Handle field disable events.
9134 *
9135 * @private
9136 * @param {boolean} value Field is disabled
9137 */
9138 OO.ui.FieldLayout.prototype.onFieldDisable = function ( value ) {
9139 this.$element.toggleClass( 'oo-ui-fieldLayout-disabled', value );
9140 };
9141
9142 /**
9143 * Handle label mouse click events.
9144 *
9145 * @private
9146 * @param {jQuery.Event} e Mouse click event
9147 */
9148 OO.ui.FieldLayout.prototype.onLabelClick = function () {
9149 this.fieldWidget.simulateLabelClick();
9150 return false;
9151 };
9152
9153 /**
9154 * Get the widget contained by the field.
9155 *
9156 * @return {OO.ui.Widget} Field widget
9157 */
9158 OO.ui.FieldLayout.prototype.getField = function () {
9159 return this.fieldWidget;
9160 };
9161
9162 /**
9163 * @protected
9164 * @param {string} kind 'error' or 'notice'
9165 * @param {string|OO.ui.HtmlSnippet} text
9166 * @return {jQuery}
9167 */
9168 OO.ui.FieldLayout.prototype.makeMessage = function ( kind, text ) {
9169 var $listItem, $icon, message;
9170 $listItem = $( '<li>' );
9171 if ( kind === 'error' ) {
9172 $icon = new OO.ui.IconWidget( { icon: 'alert', flags: [ 'warning' ] } ).$element;
9173 } else if ( kind === 'notice' ) {
9174 $icon = new OO.ui.IconWidget( { icon: 'info' } ).$element;
9175 } else {
9176 $icon = '';
9177 }
9178 message = new OO.ui.LabelWidget( { label: text } );
9179 $listItem
9180 .append( $icon, message.$element )
9181 .addClass( 'oo-ui-fieldLayout-messages-' + kind );
9182 return $listItem;
9183 };
9184
9185 /**
9186 * Set the field alignment mode.
9187 *
9188 * @private
9189 * @param {string} value Alignment mode, either 'left', 'right', 'top' or 'inline'
9190 * @chainable
9191 */
9192 OO.ui.FieldLayout.prototype.setAlignment = function ( value ) {
9193 if ( value !== this.align ) {
9194 // Default to 'left'
9195 if ( [ 'left', 'right', 'top', 'inline' ].indexOf( value ) === -1 ) {
9196 value = 'left';
9197 }
9198 // Reorder elements
9199 if ( value === 'inline' ) {
9200 this.$body.append( this.$field, this.$label );
9201 } else {
9202 this.$body.append( this.$label, this.$field );
9203 }
9204 // Set classes. The following classes can be used here:
9205 // * oo-ui-fieldLayout-align-left
9206 // * oo-ui-fieldLayout-align-right
9207 // * oo-ui-fieldLayout-align-top
9208 // * oo-ui-fieldLayout-align-inline
9209 if ( this.align ) {
9210 this.$element.removeClass( 'oo-ui-fieldLayout-align-' + this.align );
9211 }
9212 this.$element.addClass( 'oo-ui-fieldLayout-align-' + value );
9213 this.align = value;
9214 }
9215
9216 return this;
9217 };
9218
9219 /**
9220 * Set the list of error messages.
9221 *
9222 * @param {Array} errors Error messages about the widget, which will be displayed below the widget.
9223 * The array may contain strings or OO.ui.HtmlSnippet instances.
9224 * @chainable
9225 */
9226 OO.ui.FieldLayout.prototype.setErrors = function ( errors ) {
9227 this.errors = errors.slice();
9228 this.updateMessages();
9229 return this;
9230 };
9231
9232 /**
9233 * Set the list of notice messages.
9234 *
9235 * @param {Array} notices Notices about the widget, which will be displayed below the widget.
9236 * The array may contain strings or OO.ui.HtmlSnippet instances.
9237 * @chainable
9238 */
9239 OO.ui.FieldLayout.prototype.setNotices = function ( notices ) {
9240 this.notices = notices.slice();
9241 this.updateMessages();
9242 return this;
9243 };
9244
9245 /**
9246 * Update the rendering of error and notice messages.
9247 *
9248 * @private
9249 */
9250 OO.ui.FieldLayout.prototype.updateMessages = function () {
9251 var i;
9252 this.$messages.empty();
9253
9254 if ( this.errors.length || this.notices.length ) {
9255 this.$body.after( this.$messages );
9256 } else {
9257 this.$messages.remove();
9258 return;
9259 }
9260
9261 for ( i = 0; i < this.notices.length; i++ ) {
9262 this.$messages.append( this.makeMessage( 'notice', this.notices[ i ] ) );
9263 }
9264 for ( i = 0; i < this.errors.length; i++ ) {
9265 this.$messages.append( this.makeMessage( 'error', this.errors[ i ] ) );
9266 }
9267 };
9268
9269 /**
9270 * ActionFieldLayouts are used with OO.ui.FieldsetLayout. The layout consists of a field-widget, a button,
9271 * and an optional label and/or help text. The field-widget (e.g., a {@link OO.ui.TextInputWidget TextInputWidget}),
9272 * is required and is specified before any optional configuration settings.
9273 *
9274 * Labels can be aligned in one of four ways:
9275 *
9276 * - **left**: The label is placed before the field-widget and aligned with the left margin.
9277 * A left-alignment is used for forms with many fields.
9278 * - **right**: The label is placed before the field-widget and aligned to the right margin.
9279 * A right-alignment is used for long but familiar forms which users tab through,
9280 * verifying the current field with a quick glance at the label.
9281 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
9282 * that users fill out from top to bottom.
9283 * - **inline**: The label is placed after the field-widget and aligned to the left.
9284 * An inline-alignment is best used with checkboxes or radio buttons.
9285 *
9286 * Help text is accessed via a help icon that appears in the upper right corner of the rendered field layout when help
9287 * text is specified.
9288 *
9289 * @example
9290 * // Example of an ActionFieldLayout
9291 * var actionFieldLayout = new OO.ui.ActionFieldLayout(
9292 * new OO.ui.TextInputWidget( {
9293 * placeholder: 'Field widget'
9294 * } ),
9295 * new OO.ui.ButtonWidget( {
9296 * label: 'Button'
9297 * } ),
9298 * {
9299 * label: 'An ActionFieldLayout. This label is aligned top',
9300 * align: 'top',
9301 * help: 'This is help text'
9302 * }
9303 * );
9304 *
9305 * $( 'body' ).append( actionFieldLayout.$element );
9306 *
9307 * @class
9308 * @extends OO.ui.FieldLayout
9309 *
9310 * @constructor
9311 * @param {OO.ui.Widget} fieldWidget Field widget
9312 * @param {OO.ui.ButtonWidget} buttonWidget Button widget
9313 */
9314 OO.ui.ActionFieldLayout = function OoUiActionFieldLayout( fieldWidget, buttonWidget, config ) {
9315 // Allow passing positional parameters inside the config object
9316 if ( OO.isPlainObject( fieldWidget ) && config === undefined ) {
9317 config = fieldWidget;
9318 fieldWidget = config.fieldWidget;
9319 buttonWidget = config.buttonWidget;
9320 }
9321
9322 // Parent constructor
9323 OO.ui.ActionFieldLayout.parent.call( this, fieldWidget, config );
9324
9325 // Properties
9326 this.buttonWidget = buttonWidget;
9327 this.$button = $( '<div>' );
9328 this.$input = $( '<div>' );
9329
9330 // Initialization
9331 this.$element
9332 .addClass( 'oo-ui-actionFieldLayout' );
9333 this.$button
9334 .addClass( 'oo-ui-actionFieldLayout-button' )
9335 .append( this.buttonWidget.$element );
9336 this.$input
9337 .addClass( 'oo-ui-actionFieldLayout-input' )
9338 .append( this.fieldWidget.$element );
9339 this.$field
9340 .append( this.$input, this.$button );
9341 };
9342
9343 /* Setup */
9344
9345 OO.inheritClass( OO.ui.ActionFieldLayout, OO.ui.FieldLayout );
9346
9347 /**
9348 * FieldsetLayouts are composed of one or more {@link OO.ui.FieldLayout FieldLayouts},
9349 * which each contain an individual widget and, optionally, a label. Each Fieldset can be
9350 * configured with a label as well. For more information and examples,
9351 * please see the [OOjs UI documentation on MediaWiki][1].
9352 *
9353 * @example
9354 * // Example of a fieldset layout
9355 * var input1 = new OO.ui.TextInputWidget( {
9356 * placeholder: 'A text input field'
9357 * } );
9358 *
9359 * var input2 = new OO.ui.TextInputWidget( {
9360 * placeholder: 'A text input field'
9361 * } );
9362 *
9363 * var fieldset = new OO.ui.FieldsetLayout( {
9364 * label: 'Example of a fieldset layout'
9365 * } );
9366 *
9367 * fieldset.addItems( [
9368 * new OO.ui.FieldLayout( input1, {
9369 * label: 'Field One'
9370 * } ),
9371 * new OO.ui.FieldLayout( input2, {
9372 * label: 'Field Two'
9373 * } )
9374 * ] );
9375 * $( 'body' ).append( fieldset.$element );
9376 *
9377 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Fields_and_Fieldsets
9378 *
9379 * @class
9380 * @extends OO.ui.Layout
9381 * @mixins OO.ui.mixin.IconElement
9382 * @mixins OO.ui.mixin.LabelElement
9383 * @mixins OO.ui.mixin.GroupElement
9384 *
9385 * @constructor
9386 * @param {Object} [config] Configuration options
9387 * @cfg {OO.ui.FieldLayout[]} [items] An array of fields to add to the fieldset. See OO.ui.FieldLayout for more information about fields.
9388 */
9389 OO.ui.FieldsetLayout = function OoUiFieldsetLayout( config ) {
9390 // Configuration initialization
9391 config = config || {};
9392
9393 // Parent constructor
9394 OO.ui.FieldsetLayout.parent.call( this, config );
9395
9396 // Mixin constructors
9397 OO.ui.mixin.IconElement.call( this, config );
9398 OO.ui.mixin.LabelElement.call( this, config );
9399 OO.ui.mixin.GroupElement.call( this, config );
9400
9401 if ( config.help ) {
9402 this.popupButtonWidget = new OO.ui.PopupButtonWidget( {
9403 classes: [ 'oo-ui-fieldsetLayout-help' ],
9404 framed: false,
9405 icon: 'info'
9406 } );
9407
9408 this.popupButtonWidget.getPopup().$body.append(
9409 $( '<div>' )
9410 .text( config.help )
9411 .addClass( 'oo-ui-fieldsetLayout-help-content' )
9412 );
9413 this.$help = this.popupButtonWidget.$element;
9414 } else {
9415 this.$help = $( [] );
9416 }
9417
9418 // Initialization
9419 this.$element
9420 .addClass( 'oo-ui-fieldsetLayout' )
9421 .prepend( this.$help, this.$icon, this.$label, this.$group );
9422 if ( Array.isArray( config.items ) ) {
9423 this.addItems( config.items );
9424 }
9425 };
9426
9427 /* Setup */
9428
9429 OO.inheritClass( OO.ui.FieldsetLayout, OO.ui.Layout );
9430 OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.mixin.IconElement );
9431 OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.mixin.LabelElement );
9432 OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.mixin.GroupElement );
9433
9434 /**
9435 * FormLayouts are used to wrap {@link OO.ui.FieldsetLayout FieldsetLayouts} when you intend to use browser-based
9436 * form submission for the fields instead of handling them in JavaScript. Form layouts can be configured with an
9437 * HTML form action, an encoding type, and a method using the #action, #enctype, and #method configs, respectively.
9438 * See the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
9439 *
9440 * Only widgets from the {@link OO.ui.InputWidget InputWidget} family support form submission. It
9441 * includes standard form elements like {@link OO.ui.CheckboxInputWidget checkboxes}, {@link
9442 * OO.ui.RadioInputWidget radio buttons} and {@link OO.ui.TextInputWidget text fields}, as well as
9443 * some fancier controls. Some controls have both regular and InputWidget variants, for example
9444 * OO.ui.DropdownWidget and OO.ui.DropdownInputWidget – only the latter support form submission and
9445 * often have simplified APIs to match the capabilities of HTML forms.
9446 * See the [OOjs UI Inputs documentation on MediaWiki] [2] for more information about InputWidgets.
9447 *
9448 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Forms
9449 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
9450 *
9451 * @example
9452 * // Example of a form layout that wraps a fieldset layout
9453 * var input1 = new OO.ui.TextInputWidget( {
9454 * placeholder: 'Username'
9455 * } );
9456 * var input2 = new OO.ui.TextInputWidget( {
9457 * placeholder: 'Password',
9458 * type: 'password'
9459 * } );
9460 * var submit = new OO.ui.ButtonInputWidget( {
9461 * label: 'Submit'
9462 * } );
9463 *
9464 * var fieldset = new OO.ui.FieldsetLayout( {
9465 * label: 'A form layout'
9466 * } );
9467 * fieldset.addItems( [
9468 * new OO.ui.FieldLayout( input1, {
9469 * label: 'Username',
9470 * align: 'top'
9471 * } ),
9472 * new OO.ui.FieldLayout( input2, {
9473 * label: 'Password',
9474 * align: 'top'
9475 * } ),
9476 * new OO.ui.FieldLayout( submit )
9477 * ] );
9478 * var form = new OO.ui.FormLayout( {
9479 * items: [ fieldset ],
9480 * action: '/api/formhandler',
9481 * method: 'get'
9482 * } )
9483 * $( 'body' ).append( form.$element );
9484 *
9485 * @class
9486 * @extends OO.ui.Layout
9487 * @mixins OO.ui.mixin.GroupElement
9488 *
9489 * @constructor
9490 * @param {Object} [config] Configuration options
9491 * @cfg {string} [method] HTML form `method` attribute
9492 * @cfg {string} [action] HTML form `action` attribute
9493 * @cfg {string} [enctype] HTML form `enctype` attribute
9494 * @cfg {OO.ui.FieldsetLayout[]} [items] Fieldset layouts to add to the form layout.
9495 */
9496 OO.ui.FormLayout = function OoUiFormLayout( config ) {
9497 // Configuration initialization
9498 config = config || {};
9499
9500 // Parent constructor
9501 OO.ui.FormLayout.parent.call( this, config );
9502
9503 // Mixin constructors
9504 OO.ui.mixin.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) );
9505
9506 // Events
9507 this.$element.on( 'submit', this.onFormSubmit.bind( this ) );
9508
9509 // Make sure the action is safe
9510 if ( config.action !== undefined && !OO.ui.isSafeUrl( config.action ) ) {
9511 throw new Error( 'Potentially unsafe action provided: ' + config.action );
9512 }
9513
9514 // Initialization
9515 this.$element
9516 .addClass( 'oo-ui-formLayout' )
9517 .attr( {
9518 method: config.method,
9519 action: config.action,
9520 enctype: config.enctype
9521 } );
9522 if ( Array.isArray( config.items ) ) {
9523 this.addItems( config.items );
9524 }
9525 };
9526
9527 /* Setup */
9528
9529 OO.inheritClass( OO.ui.FormLayout, OO.ui.Layout );
9530 OO.mixinClass( OO.ui.FormLayout, OO.ui.mixin.GroupElement );
9531
9532 /* Events */
9533
9534 /**
9535 * A 'submit' event is emitted when the form is submitted.
9536 *
9537 * @event submit
9538 */
9539
9540 /* Static Properties */
9541
9542 OO.ui.FormLayout.static.tagName = 'form';
9543
9544 /* Methods */
9545
9546 /**
9547 * Handle form submit events.
9548 *
9549 * @private
9550 * @param {jQuery.Event} e Submit event
9551 * @fires submit
9552 */
9553 OO.ui.FormLayout.prototype.onFormSubmit = function () {
9554 if ( this.emit( 'submit' ) ) {
9555 return false;
9556 }
9557 };
9558
9559 /**
9560 * 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)
9561 * and its size is customized with the #menuSize config. The content area will fill all remaining space.
9562 *
9563 * @example
9564 * var menuLayout = new OO.ui.MenuLayout( {
9565 * position: 'top'
9566 * } ),
9567 * menuPanel = new OO.ui.PanelLayout( { padded: true, expanded: true, scrollable: true } ),
9568 * contentPanel = new OO.ui.PanelLayout( { padded: true, expanded: true, scrollable: true } ),
9569 * select = new OO.ui.SelectWidget( {
9570 * items: [
9571 * new OO.ui.OptionWidget( {
9572 * data: 'before',
9573 * label: 'Before',
9574 * } ),
9575 * new OO.ui.OptionWidget( {
9576 * data: 'after',
9577 * label: 'After',
9578 * } ),
9579 * new OO.ui.OptionWidget( {
9580 * data: 'top',
9581 * label: 'Top',
9582 * } ),
9583 * new OO.ui.OptionWidget( {
9584 * data: 'bottom',
9585 * label: 'Bottom',
9586 * } )
9587 * ]
9588 * } ).on( 'select', function ( item ) {
9589 * menuLayout.setMenuPosition( item.getData() );
9590 * } );
9591 *
9592 * menuLayout.$menu.append(
9593 * menuPanel.$element.append( '<b>Menu panel</b>', select.$element )
9594 * );
9595 * menuLayout.$content.append(
9596 * contentPanel.$element.append( '<b>Content panel</b>', '<p>Note that the menu is positioned relative to the content panel: top, bottom, after, before.</p>')
9597 * );
9598 * $( 'body' ).append( menuLayout.$element );
9599 *
9600 * If menu size needs to be overridden, it can be accomplished using CSS similar to the snippet
9601 * below. MenuLayout's CSS will override the appropriate values with 'auto' or '0' to display the
9602 * menu correctly. If `menuPosition` is known beforehand, CSS rules corresponding to other positions
9603 * may be omitted.
9604 *
9605 * .oo-ui-menuLayout-menu {
9606 * height: 200px;
9607 * width: 200px;
9608 * }
9609 * .oo-ui-menuLayout-content {
9610 * top: 200px;
9611 * left: 200px;
9612 * right: 200px;
9613 * bottom: 200px;
9614 * }
9615 *
9616 * @class
9617 * @extends OO.ui.Layout
9618 *
9619 * @constructor
9620 * @param {Object} [config] Configuration options
9621 * @cfg {boolean} [showMenu=true] Show menu
9622 * @cfg {string} [menuPosition='before'] Position of menu: `top`, `after`, `bottom` or `before`
9623 */
9624 OO.ui.MenuLayout = function OoUiMenuLayout( config ) {
9625 // Configuration initialization
9626 config = $.extend( {
9627 showMenu: true,
9628 menuPosition: 'before'
9629 }, config );
9630
9631 // Parent constructor
9632 OO.ui.MenuLayout.parent.call( this, config );
9633
9634 /**
9635 * Menu DOM node
9636 *
9637 * @property {jQuery}
9638 */
9639 this.$menu = $( '<div>' );
9640 /**
9641 * Content DOM node
9642 *
9643 * @property {jQuery}
9644 */
9645 this.$content = $( '<div>' );
9646
9647 // Initialization
9648 this.$menu
9649 .addClass( 'oo-ui-menuLayout-menu' );
9650 this.$content.addClass( 'oo-ui-menuLayout-content' );
9651 this.$element
9652 .addClass( 'oo-ui-menuLayout' )
9653 .append( this.$content, this.$menu );
9654 this.setMenuPosition( config.menuPosition );
9655 this.toggleMenu( config.showMenu );
9656 };
9657
9658 /* Setup */
9659
9660 OO.inheritClass( OO.ui.MenuLayout, OO.ui.Layout );
9661
9662 /* Methods */
9663
9664 /**
9665 * Toggle menu.
9666 *
9667 * @param {boolean} showMenu Show menu, omit to toggle
9668 * @chainable
9669 */
9670 OO.ui.MenuLayout.prototype.toggleMenu = function ( showMenu ) {
9671 showMenu = showMenu === undefined ? !this.showMenu : !!showMenu;
9672
9673 if ( this.showMenu !== showMenu ) {
9674 this.showMenu = showMenu;
9675 this.$element
9676 .toggleClass( 'oo-ui-menuLayout-showMenu', this.showMenu )
9677 .toggleClass( 'oo-ui-menuLayout-hideMenu', !this.showMenu );
9678 }
9679
9680 return this;
9681 };
9682
9683 /**
9684 * Check if menu is visible
9685 *
9686 * @return {boolean} Menu is visible
9687 */
9688 OO.ui.MenuLayout.prototype.isMenuVisible = function () {
9689 return this.showMenu;
9690 };
9691
9692 /**
9693 * Set menu position.
9694 *
9695 * @param {string} position Position of menu, either `top`, `after`, `bottom` or `before`
9696 * @throws {Error} If position value is not supported
9697 * @chainable
9698 */
9699 OO.ui.MenuLayout.prototype.setMenuPosition = function ( position ) {
9700 this.$element.removeClass( 'oo-ui-menuLayout-' + this.menuPosition );
9701 this.menuPosition = position;
9702 this.$element.addClass( 'oo-ui-menuLayout-' + position );
9703
9704 return this;
9705 };
9706
9707 /**
9708 * Get menu position.
9709 *
9710 * @return {string} Menu position
9711 */
9712 OO.ui.MenuLayout.prototype.getMenuPosition = function () {
9713 return this.menuPosition;
9714 };
9715
9716 /**
9717 * BookletLayouts contain {@link OO.ui.PageLayout page layouts} as well as
9718 * an {@link OO.ui.OutlineSelectWidget outline} that allows users to easily navigate
9719 * through the pages and select which one to display. By default, only one page is
9720 * displayed at a time and the outline is hidden. When a user navigates to a new page,
9721 * the booklet layout automatically focuses on the first focusable element, unless the
9722 * default setting is changed. Optionally, booklets can be configured to show
9723 * {@link OO.ui.OutlineControlsWidget controls} for adding, moving, and removing items.
9724 *
9725 * @example
9726 * // Example of a BookletLayout that contains two PageLayouts.
9727 *
9728 * function PageOneLayout( name, config ) {
9729 * PageOneLayout.parent.call( this, name, config );
9730 * this.$element.append( '<p>First page</p><p>(This booklet has an outline, displayed on the left)</p>' );
9731 * }
9732 * OO.inheritClass( PageOneLayout, OO.ui.PageLayout );
9733 * PageOneLayout.prototype.setupOutlineItem = function () {
9734 * this.outlineItem.setLabel( 'Page One' );
9735 * };
9736 *
9737 * function PageTwoLayout( name, config ) {
9738 * PageTwoLayout.parent.call( this, name, config );
9739 * this.$element.append( '<p>Second page</p>' );
9740 * }
9741 * OO.inheritClass( PageTwoLayout, OO.ui.PageLayout );
9742 * PageTwoLayout.prototype.setupOutlineItem = function () {
9743 * this.outlineItem.setLabel( 'Page Two' );
9744 * };
9745 *
9746 * var page1 = new PageOneLayout( 'one' ),
9747 * page2 = new PageTwoLayout( 'two' );
9748 *
9749 * var booklet = new OO.ui.BookletLayout( {
9750 * outlined: true
9751 * } );
9752 *
9753 * booklet.addPages ( [ page1, page2 ] );
9754 * $( 'body' ).append( booklet.$element );
9755 *
9756 * @class
9757 * @extends OO.ui.MenuLayout
9758 *
9759 * @constructor
9760 * @param {Object} [config] Configuration options
9761 * @cfg {boolean} [continuous=false] Show all pages, one after another
9762 * @cfg {boolean} [autoFocus=true] Focus on the first focusable element when a new page is displayed.
9763 * @cfg {boolean} [outlined=false] Show the outline. The outline is used to navigate through the pages of the booklet.
9764 * @cfg {boolean} [editable=false] Show controls for adding, removing and reordering pages
9765 */
9766 OO.ui.BookletLayout = function OoUiBookletLayout( config ) {
9767 // Configuration initialization
9768 config = config || {};
9769
9770 // Parent constructor
9771 OO.ui.BookletLayout.parent.call( this, config );
9772
9773 // Properties
9774 this.currentPageName = null;
9775 this.pages = {};
9776 this.ignoreFocus = false;
9777 this.stackLayout = new OO.ui.StackLayout( { continuous: !!config.continuous } );
9778 this.$content.append( this.stackLayout.$element );
9779 this.autoFocus = config.autoFocus === undefined || !!config.autoFocus;
9780 this.outlineVisible = false;
9781 this.outlined = !!config.outlined;
9782 if ( this.outlined ) {
9783 this.editable = !!config.editable;
9784 this.outlineControlsWidget = null;
9785 this.outlineSelectWidget = new OO.ui.OutlineSelectWidget();
9786 this.outlinePanel = new OO.ui.PanelLayout( { scrollable: true } );
9787 this.$menu.append( this.outlinePanel.$element );
9788 this.outlineVisible = true;
9789 if ( this.editable ) {
9790 this.outlineControlsWidget = new OO.ui.OutlineControlsWidget(
9791 this.outlineSelectWidget
9792 );
9793 }
9794 }
9795 this.toggleMenu( this.outlined );
9796
9797 // Events
9798 this.stackLayout.connect( this, { set: 'onStackLayoutSet' } );
9799 if ( this.outlined ) {
9800 this.outlineSelectWidget.connect( this, { select: 'onOutlineSelectWidgetSelect' } );
9801 this.scrolling = false;
9802 this.stackLayout.connect( this, { visibleItemChange: 'onStackLayoutVisibleItemChange' } );
9803 }
9804 if ( this.autoFocus ) {
9805 // Event 'focus' does not bubble, but 'focusin' does
9806 this.stackLayout.$element.on( 'focusin', this.onStackLayoutFocus.bind( this ) );
9807 }
9808
9809 // Initialization
9810 this.$element.addClass( 'oo-ui-bookletLayout' );
9811 this.stackLayout.$element.addClass( 'oo-ui-bookletLayout-stackLayout' );
9812 if ( this.outlined ) {
9813 this.outlinePanel.$element
9814 .addClass( 'oo-ui-bookletLayout-outlinePanel' )
9815 .append( this.outlineSelectWidget.$element );
9816 if ( this.editable ) {
9817 this.outlinePanel.$element
9818 .addClass( 'oo-ui-bookletLayout-outlinePanel-editable' )
9819 .append( this.outlineControlsWidget.$element );
9820 }
9821 }
9822 };
9823
9824 /* Setup */
9825
9826 OO.inheritClass( OO.ui.BookletLayout, OO.ui.MenuLayout );
9827
9828 /* Events */
9829
9830 /**
9831 * A 'set' event is emitted when a page is {@link #setPage set} to be displayed by the booklet layout.
9832 * @event set
9833 * @param {OO.ui.PageLayout} page Current page
9834 */
9835
9836 /**
9837 * An 'add' event is emitted when pages are {@link #addPages added} to the booklet layout.
9838 *
9839 * @event add
9840 * @param {OO.ui.PageLayout[]} page Added pages
9841 * @param {number} index Index pages were added at
9842 */
9843
9844 /**
9845 * A 'remove' event is emitted when pages are {@link #clearPages cleared} or
9846 * {@link #removePages removed} from the booklet.
9847 *
9848 * @event remove
9849 * @param {OO.ui.PageLayout[]} pages Removed pages
9850 */
9851
9852 /* Methods */
9853
9854 /**
9855 * Handle stack layout focus.
9856 *
9857 * @private
9858 * @param {jQuery.Event} e Focusin event
9859 */
9860 OO.ui.BookletLayout.prototype.onStackLayoutFocus = function ( e ) {
9861 var name, $target;
9862
9863 // Find the page that an element was focused within
9864 $target = $( e.target ).closest( '.oo-ui-pageLayout' );
9865 for ( name in this.pages ) {
9866 // Check for page match, exclude current page to find only page changes
9867 if ( this.pages[ name ].$element[ 0 ] === $target[ 0 ] && name !== this.currentPageName ) {
9868 this.setPage( name );
9869 break;
9870 }
9871 }
9872 };
9873
9874 /**
9875 * Handle visibleItemChange events from the stackLayout
9876 *
9877 * The next visible page is set as the current page by selecting it
9878 * in the outline
9879 *
9880 * @param {OO.ui.PageLayout} page The next visible page in the layout
9881 */
9882 OO.ui.BookletLayout.prototype.onStackLayoutVisibleItemChange = function ( page ) {
9883 // Set a flag to so that the resulting call to #onStackLayoutSet doesn't
9884 // try and scroll the item into view again.
9885 this.scrolling = true;
9886 this.outlineSelectWidget.selectItemByData( page.getName() );
9887 this.scrolling = false;
9888 };
9889
9890 /**
9891 * Handle stack layout set events.
9892 *
9893 * @private
9894 * @param {OO.ui.PanelLayout|null} page The page panel that is now the current panel
9895 */
9896 OO.ui.BookletLayout.prototype.onStackLayoutSet = function ( page ) {
9897 var layout = this;
9898 if ( !this.scrolling && page ) {
9899 page.scrollElementIntoView( { complete: function () {
9900 if ( layout.autoFocus ) {
9901 layout.focus();
9902 }
9903 } } );
9904 }
9905 };
9906
9907 /**
9908 * Focus the first input in the current page.
9909 *
9910 * If no page is selected, the first selectable page will be selected.
9911 * If the focus is already in an element on the current page, nothing will happen.
9912 * @param {number} [itemIndex] A specific item to focus on
9913 */
9914 OO.ui.BookletLayout.prototype.focus = function ( itemIndex ) {
9915 var page,
9916 items = this.stackLayout.getItems();
9917
9918 if ( itemIndex !== undefined && items[ itemIndex ] ) {
9919 page = items[ itemIndex ];
9920 } else {
9921 page = this.stackLayout.getCurrentItem();
9922 }
9923
9924 if ( !page && this.outlined ) {
9925 this.selectFirstSelectablePage();
9926 page = this.stackLayout.getCurrentItem();
9927 }
9928 if ( !page ) {
9929 return;
9930 }
9931 // Only change the focus if is not already in the current page
9932 if ( !OO.ui.contains( page.$element[ 0 ], this.getElementDocument().activeElement, true ) ) {
9933 page.focus();
9934 }
9935 };
9936
9937 /**
9938 * Find the first focusable input in the booklet layout and focus
9939 * on it.
9940 */
9941 OO.ui.BookletLayout.prototype.focusFirstFocusable = function () {
9942 OO.ui.findFocusable( this.stackLayout.$element ).focus();
9943 };
9944
9945 /**
9946 * Handle outline widget select events.
9947 *
9948 * @private
9949 * @param {OO.ui.OptionWidget|null} item Selected item
9950 */
9951 OO.ui.BookletLayout.prototype.onOutlineSelectWidgetSelect = function ( item ) {
9952 if ( item ) {
9953 this.setPage( item.getData() );
9954 }
9955 };
9956
9957 /**
9958 * Check if booklet has an outline.
9959 *
9960 * @return {boolean} Booklet has an outline
9961 */
9962 OO.ui.BookletLayout.prototype.isOutlined = function () {
9963 return this.outlined;
9964 };
9965
9966 /**
9967 * Check if booklet has editing controls.
9968 *
9969 * @return {boolean} Booklet is editable
9970 */
9971 OO.ui.BookletLayout.prototype.isEditable = function () {
9972 return this.editable;
9973 };
9974
9975 /**
9976 * Check if booklet has a visible outline.
9977 *
9978 * @return {boolean} Outline is visible
9979 */
9980 OO.ui.BookletLayout.prototype.isOutlineVisible = function () {
9981 return this.outlined && this.outlineVisible;
9982 };
9983
9984 /**
9985 * Hide or show the outline.
9986 *
9987 * @param {boolean} [show] Show outline, omit to invert current state
9988 * @chainable
9989 */
9990 OO.ui.BookletLayout.prototype.toggleOutline = function ( show ) {
9991 if ( this.outlined ) {
9992 show = show === undefined ? !this.outlineVisible : !!show;
9993 this.outlineVisible = show;
9994 this.toggleMenu( show );
9995 }
9996
9997 return this;
9998 };
9999
10000 /**
10001 * Get the page closest to the specified page.
10002 *
10003 * @param {OO.ui.PageLayout} page Page to use as a reference point
10004 * @return {OO.ui.PageLayout|null} Page closest to the specified page
10005 */
10006 OO.ui.BookletLayout.prototype.getClosestPage = function ( page ) {
10007 var next, prev, level,
10008 pages = this.stackLayout.getItems(),
10009 index = pages.indexOf( page );
10010
10011 if ( index !== -1 ) {
10012 next = pages[ index + 1 ];
10013 prev = pages[ index - 1 ];
10014 // Prefer adjacent pages at the same level
10015 if ( this.outlined ) {
10016 level = this.outlineSelectWidget.getItemFromData( page.getName() ).getLevel();
10017 if (
10018 prev &&
10019 level === this.outlineSelectWidget.getItemFromData( prev.getName() ).getLevel()
10020 ) {
10021 return prev;
10022 }
10023 if (
10024 next &&
10025 level === this.outlineSelectWidget.getItemFromData( next.getName() ).getLevel()
10026 ) {
10027 return next;
10028 }
10029 }
10030 }
10031 return prev || next || null;
10032 };
10033
10034 /**
10035 * Get the outline widget.
10036 *
10037 * If the booklet is not outlined, the method will return `null`.
10038 *
10039 * @return {OO.ui.OutlineSelectWidget|null} Outline widget, or null if the booklet is not outlined
10040 */
10041 OO.ui.BookletLayout.prototype.getOutline = function () {
10042 return this.outlineSelectWidget;
10043 };
10044
10045 /**
10046 * Get the outline controls widget.
10047 *
10048 * If the outline is not editable, the method will return `null`.
10049 *
10050 * @return {OO.ui.OutlineControlsWidget|null} The outline controls widget.
10051 */
10052 OO.ui.BookletLayout.prototype.getOutlineControls = function () {
10053 return this.outlineControlsWidget;
10054 };
10055
10056 /**
10057 * Get a page by its symbolic name.
10058 *
10059 * @param {string} name Symbolic name of page
10060 * @return {OO.ui.PageLayout|undefined} Page, if found
10061 */
10062 OO.ui.BookletLayout.prototype.getPage = function ( name ) {
10063 return this.pages[ name ];
10064 };
10065
10066 /**
10067 * Get the current page.
10068 *
10069 * @return {OO.ui.PageLayout|undefined} Current page, if found
10070 */
10071 OO.ui.BookletLayout.prototype.getCurrentPage = function () {
10072 var name = this.getCurrentPageName();
10073 return name ? this.getPage( name ) : undefined;
10074 };
10075
10076 /**
10077 * Get the symbolic name of the current page.
10078 *
10079 * @return {string|null} Symbolic name of the current page
10080 */
10081 OO.ui.BookletLayout.prototype.getCurrentPageName = function () {
10082 return this.currentPageName;
10083 };
10084
10085 /**
10086 * Add pages to the booklet layout
10087 *
10088 * When pages are added with the same names as existing pages, the existing pages will be
10089 * automatically removed before the new pages are added.
10090 *
10091 * @param {OO.ui.PageLayout[]} pages Pages to add
10092 * @param {number} index Index of the insertion point
10093 * @fires add
10094 * @chainable
10095 */
10096 OO.ui.BookletLayout.prototype.addPages = function ( pages, index ) {
10097 var i, len, name, page, item, currentIndex,
10098 stackLayoutPages = this.stackLayout.getItems(),
10099 remove = [],
10100 items = [];
10101
10102 // Remove pages with same names
10103 for ( i = 0, len = pages.length; i < len; i++ ) {
10104 page = pages[ i ];
10105 name = page.getName();
10106
10107 if ( Object.prototype.hasOwnProperty.call( this.pages, name ) ) {
10108 // Correct the insertion index
10109 currentIndex = stackLayoutPages.indexOf( this.pages[ name ] );
10110 if ( currentIndex !== -1 && currentIndex + 1 < index ) {
10111 index--;
10112 }
10113 remove.push( this.pages[ name ] );
10114 }
10115 }
10116 if ( remove.length ) {
10117 this.removePages( remove );
10118 }
10119
10120 // Add new pages
10121 for ( i = 0, len = pages.length; i < len; i++ ) {
10122 page = pages[ i ];
10123 name = page.getName();
10124 this.pages[ page.getName() ] = page;
10125 if ( this.outlined ) {
10126 item = new OO.ui.OutlineOptionWidget( { data: name } );
10127 page.setOutlineItem( item );
10128 items.push( item );
10129 }
10130 }
10131
10132 if ( this.outlined && items.length ) {
10133 this.outlineSelectWidget.addItems( items, index );
10134 this.selectFirstSelectablePage();
10135 }
10136 this.stackLayout.addItems( pages, index );
10137 this.emit( 'add', pages, index );
10138
10139 return this;
10140 };
10141
10142 /**
10143 * Remove the specified pages from the booklet layout.
10144 *
10145 * To remove all pages from the booklet, you may wish to use the #clearPages method instead.
10146 *
10147 * @param {OO.ui.PageLayout[]} pages An array of pages to remove
10148 * @fires remove
10149 * @chainable
10150 */
10151 OO.ui.BookletLayout.prototype.removePages = function ( pages ) {
10152 var i, len, name, page,
10153 items = [];
10154
10155 for ( i = 0, len = pages.length; i < len; i++ ) {
10156 page = pages[ i ];
10157 name = page.getName();
10158 delete this.pages[ name ];
10159 if ( this.outlined ) {
10160 items.push( this.outlineSelectWidget.getItemFromData( name ) );
10161 page.setOutlineItem( null );
10162 }
10163 }
10164 if ( this.outlined && items.length ) {
10165 this.outlineSelectWidget.removeItems( items );
10166 this.selectFirstSelectablePage();
10167 }
10168 this.stackLayout.removeItems( pages );
10169 this.emit( 'remove', pages );
10170
10171 return this;
10172 };
10173
10174 /**
10175 * Clear all pages from the booklet layout.
10176 *
10177 * To remove only a subset of pages from the booklet, use the #removePages method.
10178 *
10179 * @fires remove
10180 * @chainable
10181 */
10182 OO.ui.BookletLayout.prototype.clearPages = function () {
10183 var i, len,
10184 pages = this.stackLayout.getItems();
10185
10186 this.pages = {};
10187 this.currentPageName = null;
10188 if ( this.outlined ) {
10189 this.outlineSelectWidget.clearItems();
10190 for ( i = 0, len = pages.length; i < len; i++ ) {
10191 pages[ i ].setOutlineItem( null );
10192 }
10193 }
10194 this.stackLayout.clearItems();
10195
10196 this.emit( 'remove', pages );
10197
10198 return this;
10199 };
10200
10201 /**
10202 * Set the current page by symbolic name.
10203 *
10204 * @fires set
10205 * @param {string} name Symbolic name of page
10206 */
10207 OO.ui.BookletLayout.prototype.setPage = function ( name ) {
10208 var selectedItem,
10209 $focused,
10210 page = this.pages[ name ],
10211 previousPage = this.currentPageName && this.pages[ this.currentPageName ];
10212
10213 if ( name !== this.currentPageName ) {
10214 if ( this.outlined ) {
10215 selectedItem = this.outlineSelectWidget.getSelectedItem();
10216 if ( selectedItem && selectedItem.getData() !== name ) {
10217 this.outlineSelectWidget.selectItemByData( name );
10218 }
10219 }
10220 if ( page ) {
10221 if ( previousPage ) {
10222 previousPage.setActive( false );
10223 // Blur anything focused if the next page doesn't have anything focusable.
10224 // This is not needed if the next page has something focusable (because once it is focused
10225 // this blur happens automatically). If the layout is non-continuous, this check is
10226 // meaningless because the next page is not visible yet and thus can't hold focus.
10227 if (
10228 this.autoFocus &&
10229 this.stackLayout.continuous &&
10230 OO.ui.findFocusable( page.$element ).length !== 0
10231 ) {
10232 $focused = previousPage.$element.find( ':focus' );
10233 if ( $focused.length ) {
10234 $focused[ 0 ].blur();
10235 }
10236 }
10237 }
10238 this.currentPageName = name;
10239 page.setActive( true );
10240 this.stackLayout.setItem( page );
10241 if ( !this.stackLayout.continuous && previousPage ) {
10242 // This should not be necessary, since any inputs on the previous page should have been
10243 // blurred when it was hidden, but browsers are not very consistent about this.
10244 $focused = previousPage.$element.find( ':focus' );
10245 if ( $focused.length ) {
10246 $focused[ 0 ].blur();
10247 }
10248 }
10249 this.emit( 'set', page );
10250 }
10251 }
10252 };
10253
10254 /**
10255 * Select the first selectable page.
10256 *
10257 * @chainable
10258 */
10259 OO.ui.BookletLayout.prototype.selectFirstSelectablePage = function () {
10260 if ( !this.outlineSelectWidget.getSelectedItem() ) {
10261 this.outlineSelectWidget.selectItem( this.outlineSelectWidget.getFirstSelectableItem() );
10262 }
10263
10264 return this;
10265 };
10266
10267 /**
10268 * IndexLayouts contain {@link OO.ui.CardLayout card layouts} as well as
10269 * {@link OO.ui.TabSelectWidget tabs} that allow users to easily navigate through the cards and
10270 * select which one to display. By default, only one card is displayed at a time. When a user
10271 * navigates to a new card, the index layout automatically focuses on the first focusable element,
10272 * unless the default setting is changed.
10273 *
10274 * TODO: This class is similar to BookletLayout, we may want to refactor to reduce duplication
10275 *
10276 * @example
10277 * // Example of a IndexLayout that contains two CardLayouts.
10278 *
10279 * function CardOneLayout( name, config ) {
10280 * CardOneLayout.parent.call( this, name, config );
10281 * this.$element.append( '<p>First card</p>' );
10282 * }
10283 * OO.inheritClass( CardOneLayout, OO.ui.CardLayout );
10284 * CardOneLayout.prototype.setupTabItem = function () {
10285 * this.tabItem.setLabel( 'Card one' );
10286 * };
10287 *
10288 * var card1 = new CardOneLayout( 'one' ),
10289 * card2 = new CardLayout( 'two', { label: 'Card two' } );
10290 *
10291 * card2.$element.append( '<p>Second card</p>' );
10292 *
10293 * var index = new OO.ui.IndexLayout();
10294 *
10295 * index.addCards ( [ card1, card2 ] );
10296 * $( 'body' ).append( index.$element );
10297 *
10298 * @class
10299 * @extends OO.ui.MenuLayout
10300 *
10301 * @constructor
10302 * @param {Object} [config] Configuration options
10303 * @cfg {boolean} [continuous=false] Show all cards, one after another
10304 * @cfg {boolean} [expanded=true] Expand the content panel to fill the entire parent element.
10305 * @cfg {boolean} [autoFocus=true] Focus on the first focusable element when a new card is displayed.
10306 */
10307 OO.ui.IndexLayout = function OoUiIndexLayout( config ) {
10308 // Configuration initialization
10309 config = $.extend( {}, config, { menuPosition: 'top' } );
10310
10311 // Parent constructor
10312 OO.ui.IndexLayout.parent.call( this, config );
10313
10314 // Properties
10315 this.currentCardName = null;
10316 this.cards = {};
10317 this.ignoreFocus = false;
10318 this.stackLayout = new OO.ui.StackLayout( {
10319 continuous: !!config.continuous,
10320 expanded: config.expanded
10321 } );
10322 this.$content.append( this.stackLayout.$element );
10323 this.autoFocus = config.autoFocus === undefined || !!config.autoFocus;
10324
10325 this.tabSelectWidget = new OO.ui.TabSelectWidget();
10326 this.tabPanel = new OO.ui.PanelLayout();
10327 this.$menu.append( this.tabPanel.$element );
10328
10329 this.toggleMenu( true );
10330
10331 // Events
10332 this.stackLayout.connect( this, { set: 'onStackLayoutSet' } );
10333 this.tabSelectWidget.connect( this, { select: 'onTabSelectWidgetSelect' } );
10334 if ( this.autoFocus ) {
10335 // Event 'focus' does not bubble, but 'focusin' does
10336 this.stackLayout.$element.on( 'focusin', this.onStackLayoutFocus.bind( this ) );
10337 }
10338
10339 // Initialization
10340 this.$element.addClass( 'oo-ui-indexLayout' );
10341 this.stackLayout.$element.addClass( 'oo-ui-indexLayout-stackLayout' );
10342 this.tabPanel.$element
10343 .addClass( 'oo-ui-indexLayout-tabPanel' )
10344 .append( this.tabSelectWidget.$element );
10345 };
10346
10347 /* Setup */
10348
10349 OO.inheritClass( OO.ui.IndexLayout, OO.ui.MenuLayout );
10350
10351 /* Events */
10352
10353 /**
10354 * A 'set' event is emitted when a card is {@link #setCard set} to be displayed by the index layout.
10355 * @event set
10356 * @param {OO.ui.CardLayout} card Current card
10357 */
10358
10359 /**
10360 * An 'add' event is emitted when cards are {@link #addCards added} to the index layout.
10361 *
10362 * @event add
10363 * @param {OO.ui.CardLayout[]} card Added cards
10364 * @param {number} index Index cards were added at
10365 */
10366
10367 /**
10368 * A 'remove' event is emitted when cards are {@link #clearCards cleared} or
10369 * {@link #removeCards removed} from the index.
10370 *
10371 * @event remove
10372 * @param {OO.ui.CardLayout[]} cards Removed cards
10373 */
10374
10375 /* Methods */
10376
10377 /**
10378 * Handle stack layout focus.
10379 *
10380 * @private
10381 * @param {jQuery.Event} e Focusin event
10382 */
10383 OO.ui.IndexLayout.prototype.onStackLayoutFocus = function ( e ) {
10384 var name, $target;
10385
10386 // Find the card that an element was focused within
10387 $target = $( e.target ).closest( '.oo-ui-cardLayout' );
10388 for ( name in this.cards ) {
10389 // Check for card match, exclude current card to find only card changes
10390 if ( this.cards[ name ].$element[ 0 ] === $target[ 0 ] && name !== this.currentCardName ) {
10391 this.setCard( name );
10392 break;
10393 }
10394 }
10395 };
10396
10397 /**
10398 * Handle stack layout set events.
10399 *
10400 * @private
10401 * @param {OO.ui.PanelLayout|null} card The card panel that is now the current panel
10402 */
10403 OO.ui.IndexLayout.prototype.onStackLayoutSet = function ( card ) {
10404 var layout = this;
10405 if ( card ) {
10406 card.scrollElementIntoView( { complete: function () {
10407 if ( layout.autoFocus ) {
10408 layout.focus();
10409 }
10410 } } );
10411 }
10412 };
10413
10414 /**
10415 * Focus the first input in the current card.
10416 *
10417 * If no card is selected, the first selectable card will be selected.
10418 * If the focus is already in an element on the current card, nothing will happen.
10419 * @param {number} [itemIndex] A specific item to focus on
10420 */
10421 OO.ui.IndexLayout.prototype.focus = function ( itemIndex ) {
10422 var card,
10423 items = this.stackLayout.getItems();
10424
10425 if ( itemIndex !== undefined && items[ itemIndex ] ) {
10426 card = items[ itemIndex ];
10427 } else {
10428 card = this.stackLayout.getCurrentItem();
10429 }
10430
10431 if ( !card ) {
10432 this.selectFirstSelectableCard();
10433 card = this.stackLayout.getCurrentItem();
10434 }
10435 if ( !card ) {
10436 return;
10437 }
10438 // Only change the focus if is not already in the current page
10439 if ( !OO.ui.contains( card.$element[ 0 ], this.getElementDocument().activeElement, true ) ) {
10440 card.focus();
10441 }
10442 };
10443
10444 /**
10445 * Find the first focusable input in the index layout and focus
10446 * on it.
10447 */
10448 OO.ui.IndexLayout.prototype.focusFirstFocusable = function () {
10449 OO.ui.findFocusable( this.stackLayout.$element ).focus();
10450 };
10451
10452 /**
10453 * Handle tab widget select events.
10454 *
10455 * @private
10456 * @param {OO.ui.OptionWidget|null} item Selected item
10457 */
10458 OO.ui.IndexLayout.prototype.onTabSelectWidgetSelect = function ( item ) {
10459 if ( item ) {
10460 this.setCard( item.getData() );
10461 }
10462 };
10463
10464 /**
10465 * Get the card closest to the specified card.
10466 *
10467 * @param {OO.ui.CardLayout} card Card to use as a reference point
10468 * @return {OO.ui.CardLayout|null} Card closest to the specified card
10469 */
10470 OO.ui.IndexLayout.prototype.getClosestCard = function ( card ) {
10471 var next, prev, level,
10472 cards = this.stackLayout.getItems(),
10473 index = cards.indexOf( card );
10474
10475 if ( index !== -1 ) {
10476 next = cards[ index + 1 ];
10477 prev = cards[ index - 1 ];
10478 // Prefer adjacent cards at the same level
10479 level = this.tabSelectWidget.getItemFromData( card.getName() ).getLevel();
10480 if (
10481 prev &&
10482 level === this.tabSelectWidget.getItemFromData( prev.getName() ).getLevel()
10483 ) {
10484 return prev;
10485 }
10486 if (
10487 next &&
10488 level === this.tabSelectWidget.getItemFromData( next.getName() ).getLevel()
10489 ) {
10490 return next;
10491 }
10492 }
10493 return prev || next || null;
10494 };
10495
10496 /**
10497 * Get the tabs widget.
10498 *
10499 * @return {OO.ui.TabSelectWidget} Tabs widget
10500 */
10501 OO.ui.IndexLayout.prototype.getTabs = function () {
10502 return this.tabSelectWidget;
10503 };
10504
10505 /**
10506 * Get a card by its symbolic name.
10507 *
10508 * @param {string} name Symbolic name of card
10509 * @return {OO.ui.CardLayout|undefined} Card, if found
10510 */
10511 OO.ui.IndexLayout.prototype.getCard = function ( name ) {
10512 return this.cards[ name ];
10513 };
10514
10515 /**
10516 * Get the current card.
10517 *
10518 * @return {OO.ui.CardLayout|undefined} Current card, if found
10519 */
10520 OO.ui.IndexLayout.prototype.getCurrentCard = function () {
10521 var name = this.getCurrentCardName();
10522 return name ? this.getCard( name ) : undefined;
10523 };
10524
10525 /**
10526 * Get the symbolic name of the current card.
10527 *
10528 * @return {string|null} Symbolic name of the current card
10529 */
10530 OO.ui.IndexLayout.prototype.getCurrentCardName = function () {
10531 return this.currentCardName;
10532 };
10533
10534 /**
10535 * Add cards to the index layout
10536 *
10537 * When cards are added with the same names as existing cards, the existing cards will be
10538 * automatically removed before the new cards are added.
10539 *
10540 * @param {OO.ui.CardLayout[]} cards Cards to add
10541 * @param {number} index Index of the insertion point
10542 * @fires add
10543 * @chainable
10544 */
10545 OO.ui.IndexLayout.prototype.addCards = function ( cards, index ) {
10546 var i, len, name, card, item, currentIndex,
10547 stackLayoutCards = this.stackLayout.getItems(),
10548 remove = [],
10549 items = [];
10550
10551 // Remove cards with same names
10552 for ( i = 0, len = cards.length; i < len; i++ ) {
10553 card = cards[ i ];
10554 name = card.getName();
10555
10556 if ( Object.prototype.hasOwnProperty.call( this.cards, name ) ) {
10557 // Correct the insertion index
10558 currentIndex = stackLayoutCards.indexOf( this.cards[ name ] );
10559 if ( currentIndex !== -1 && currentIndex + 1 < index ) {
10560 index--;
10561 }
10562 remove.push( this.cards[ name ] );
10563 }
10564 }
10565 if ( remove.length ) {
10566 this.removeCards( remove );
10567 }
10568
10569 // Add new cards
10570 for ( i = 0, len = cards.length; i < len; i++ ) {
10571 card = cards[ i ];
10572 name = card.getName();
10573 this.cards[ card.getName() ] = card;
10574 item = new OO.ui.TabOptionWidget( { data: name } );
10575 card.setTabItem( item );
10576 items.push( item );
10577 }
10578
10579 if ( items.length ) {
10580 this.tabSelectWidget.addItems( items, index );
10581 this.selectFirstSelectableCard();
10582 }
10583 this.stackLayout.addItems( cards, index );
10584 this.emit( 'add', cards, index );
10585
10586 return this;
10587 };
10588
10589 /**
10590 * Remove the specified cards from the index layout.
10591 *
10592 * To remove all cards from the index, you may wish to use the #clearCards method instead.
10593 *
10594 * @param {OO.ui.CardLayout[]} cards An array of cards to remove
10595 * @fires remove
10596 * @chainable
10597 */
10598 OO.ui.IndexLayout.prototype.removeCards = function ( cards ) {
10599 var i, len, name, card,
10600 items = [];
10601
10602 for ( i = 0, len = cards.length; i < len; i++ ) {
10603 card = cards[ i ];
10604 name = card.getName();
10605 delete this.cards[ name ];
10606 items.push( this.tabSelectWidget.getItemFromData( name ) );
10607 card.setTabItem( null );
10608 }
10609 if ( items.length ) {
10610 this.tabSelectWidget.removeItems( items );
10611 this.selectFirstSelectableCard();
10612 }
10613 this.stackLayout.removeItems( cards );
10614 this.emit( 'remove', cards );
10615
10616 return this;
10617 };
10618
10619 /**
10620 * Clear all cards from the index layout.
10621 *
10622 * To remove only a subset of cards from the index, use the #removeCards method.
10623 *
10624 * @fires remove
10625 * @chainable
10626 */
10627 OO.ui.IndexLayout.prototype.clearCards = function () {
10628 var i, len,
10629 cards = this.stackLayout.getItems();
10630
10631 this.cards = {};
10632 this.currentCardName = null;
10633 this.tabSelectWidget.clearItems();
10634 for ( i = 0, len = cards.length; i < len; i++ ) {
10635 cards[ i ].setTabItem( null );
10636 }
10637 this.stackLayout.clearItems();
10638
10639 this.emit( 'remove', cards );
10640
10641 return this;
10642 };
10643
10644 /**
10645 * Set the current card by symbolic name.
10646 *
10647 * @fires set
10648 * @param {string} name Symbolic name of card
10649 */
10650 OO.ui.IndexLayout.prototype.setCard = function ( name ) {
10651 var selectedItem,
10652 $focused,
10653 card = this.cards[ name ],
10654 previousCard = this.currentCardName && this.cards[ this.currentCardName ];
10655
10656 if ( name !== this.currentCardName ) {
10657 selectedItem = this.tabSelectWidget.getSelectedItem();
10658 if ( selectedItem && selectedItem.getData() !== name ) {
10659 this.tabSelectWidget.selectItemByData( name );
10660 }
10661 if ( card ) {
10662 if ( previousCard ) {
10663 previousCard.setActive( false );
10664 // Blur anything focused if the next card doesn't have anything focusable.
10665 // This is not needed if the next card has something focusable (because once it is focused
10666 // this blur happens automatically). If the layout is non-continuous, this check is
10667 // meaningless because the next card is not visible yet and thus can't hold focus.
10668 if (
10669 this.autoFocus &&
10670 this.stackLayout.continuous &&
10671 OO.ui.findFocusable( card.$element ).length !== 0
10672 ) {
10673 $focused = previousCard.$element.find( ':focus' );
10674 if ( $focused.length ) {
10675 $focused[ 0 ].blur();
10676 }
10677 }
10678 }
10679 this.currentCardName = name;
10680 card.setActive( true );
10681 this.stackLayout.setItem( card );
10682 if ( !this.stackLayout.continuous && previousCard ) {
10683 // This should not be necessary, since any inputs on the previous card should have been
10684 // blurred when it was hidden, but browsers are not very consistent about this.
10685 $focused = previousCard.$element.find( ':focus' );
10686 if ( $focused.length ) {
10687 $focused[ 0 ].blur();
10688 }
10689 }
10690 this.emit( 'set', card );
10691 }
10692 }
10693 };
10694
10695 /**
10696 * Select the first selectable card.
10697 *
10698 * @chainable
10699 */
10700 OO.ui.IndexLayout.prototype.selectFirstSelectableCard = function () {
10701 if ( !this.tabSelectWidget.getSelectedItem() ) {
10702 this.tabSelectWidget.selectItem( this.tabSelectWidget.getFirstSelectableItem() );
10703 }
10704
10705 return this;
10706 };
10707
10708 /**
10709 * PanelLayouts expand to cover the entire area of their parent. They can be configured with scrolling, padding,
10710 * and a frame, and are often used together with {@link OO.ui.StackLayout StackLayouts}.
10711 *
10712 * @example
10713 * // Example of a panel layout
10714 * var panel = new OO.ui.PanelLayout( {
10715 * expanded: false,
10716 * framed: true,
10717 * padded: true,
10718 * $content: $( '<p>A panel layout with padding and a frame.</p>' )
10719 * } );
10720 * $( 'body' ).append( panel.$element );
10721 *
10722 * @class
10723 * @extends OO.ui.Layout
10724 *
10725 * @constructor
10726 * @param {Object} [config] Configuration options
10727 * @cfg {boolean} [scrollable=false] Allow vertical scrolling
10728 * @cfg {boolean} [padded=false] Add padding between the content and the edges of the panel.
10729 * @cfg {boolean} [expanded=true] Expand the panel to fill the entire parent element.
10730 * @cfg {boolean} [framed=false] Render the panel with a frame to visually separate it from outside content.
10731 */
10732 OO.ui.PanelLayout = function OoUiPanelLayout( config ) {
10733 // Configuration initialization
10734 config = $.extend( {
10735 scrollable: false,
10736 padded: false,
10737 expanded: true,
10738 framed: false
10739 }, config );
10740
10741 // Parent constructor
10742 OO.ui.PanelLayout.parent.call( this, config );
10743
10744 // Initialization
10745 this.$element.addClass( 'oo-ui-panelLayout' );
10746 if ( config.scrollable ) {
10747 this.$element.addClass( 'oo-ui-panelLayout-scrollable' );
10748 }
10749 if ( config.padded ) {
10750 this.$element.addClass( 'oo-ui-panelLayout-padded' );
10751 }
10752 if ( config.expanded ) {
10753 this.$element.addClass( 'oo-ui-panelLayout-expanded' );
10754 }
10755 if ( config.framed ) {
10756 this.$element.addClass( 'oo-ui-panelLayout-framed' );
10757 }
10758 };
10759
10760 /* Setup */
10761
10762 OO.inheritClass( OO.ui.PanelLayout, OO.ui.Layout );
10763
10764 /* Methods */
10765
10766 /**
10767 * Focus the panel layout
10768 *
10769 * The default implementation just focuses the first focusable element in the panel
10770 */
10771 OO.ui.PanelLayout.prototype.focus = function () {
10772 OO.ui.findFocusable( this.$element ).focus();
10773 };
10774
10775 /**
10776 * CardLayouts are used within {@link OO.ui.IndexLayout index layouts} to create cards that users can select and display
10777 * from the index's optional {@link OO.ui.TabSelectWidget tab} navigation. Cards are usually not instantiated directly,
10778 * rather extended to include the required content and functionality.
10779 *
10780 * Each card must have a unique symbolic name, which is passed to the constructor. In addition, the card's tab
10781 * item is customized (with a label) using the #setupTabItem method. See
10782 * {@link OO.ui.IndexLayout IndexLayout} for an example.
10783 *
10784 * @class
10785 * @extends OO.ui.PanelLayout
10786 *
10787 * @constructor
10788 * @param {string} name Unique symbolic name of card
10789 * @param {Object} [config] Configuration options
10790 * @cfg {jQuery|string|Function|OO.ui.HtmlSnippet} [label] Label for card's tab
10791 */
10792 OO.ui.CardLayout = function OoUiCardLayout( name, config ) {
10793 // Allow passing positional parameters inside the config object
10794 if ( OO.isPlainObject( name ) && config === undefined ) {
10795 config = name;
10796 name = config.name;
10797 }
10798
10799 // Configuration initialization
10800 config = $.extend( { scrollable: true }, config );
10801
10802 // Parent constructor
10803 OO.ui.CardLayout.parent.call( this, config );
10804
10805 // Properties
10806 this.name = name;
10807 this.label = config.label;
10808 this.tabItem = null;
10809 this.active = false;
10810
10811 // Initialization
10812 this.$element.addClass( 'oo-ui-cardLayout' );
10813 };
10814
10815 /* Setup */
10816
10817 OO.inheritClass( OO.ui.CardLayout, OO.ui.PanelLayout );
10818
10819 /* Events */
10820
10821 /**
10822 * An 'active' event is emitted when the card becomes active. Cards become active when they are
10823 * shown in a index layout that is configured to display only one card at a time.
10824 *
10825 * @event active
10826 * @param {boolean} active Card is active
10827 */
10828
10829 /* Methods */
10830
10831 /**
10832 * Get the symbolic name of the card.
10833 *
10834 * @return {string} Symbolic name of card
10835 */
10836 OO.ui.CardLayout.prototype.getName = function () {
10837 return this.name;
10838 };
10839
10840 /**
10841 * Check if card is active.
10842 *
10843 * Cards become active when they are shown in a {@link OO.ui.IndexLayout index layout} that is configured to display
10844 * only one card at a time. Additional CSS is applied to the card's tab item to reflect the active state.
10845 *
10846 * @return {boolean} Card is active
10847 */
10848 OO.ui.CardLayout.prototype.isActive = function () {
10849 return this.active;
10850 };
10851
10852 /**
10853 * Get tab item.
10854 *
10855 * The tab item allows users to access the card from the index's tab
10856 * navigation. The tab item itself can be customized (with a label, level, etc.) using the #setupTabItem method.
10857 *
10858 * @return {OO.ui.TabOptionWidget|null} Tab option widget
10859 */
10860 OO.ui.CardLayout.prototype.getTabItem = function () {
10861 return this.tabItem;
10862 };
10863
10864 /**
10865 * Set or unset the tab item.
10866 *
10867 * Specify a {@link OO.ui.TabOptionWidget tab option} to set it,
10868 * or `null` to clear the tab item. To customize the tab item itself (e.g., to set a label or tab
10869 * level), use #setupTabItem instead of this method.
10870 *
10871 * @param {OO.ui.TabOptionWidget|null} tabItem Tab option widget, null to clear
10872 * @chainable
10873 */
10874 OO.ui.CardLayout.prototype.setTabItem = function ( tabItem ) {
10875 this.tabItem = tabItem || null;
10876 if ( tabItem ) {
10877 this.setupTabItem();
10878 }
10879 return this;
10880 };
10881
10882 /**
10883 * Set up the tab item.
10884 *
10885 * Use this method to customize the tab item (e.g., to add a label or tab level). To set or unset
10886 * the tab item itself (with a {@link OO.ui.TabOptionWidget tab option} or `null`), use
10887 * the #setTabItem method instead.
10888 *
10889 * @param {OO.ui.TabOptionWidget} tabItem Tab option widget to set up
10890 * @chainable
10891 */
10892 OO.ui.CardLayout.prototype.setupTabItem = function () {
10893 if ( this.label ) {
10894 this.tabItem.setLabel( this.label );
10895 }
10896 return this;
10897 };
10898
10899 /**
10900 * Set the card to its 'active' state.
10901 *
10902 * Cards become active when they are shown in a index layout that is configured to display only one card at a time. Additional
10903 * CSS is applied to the tab item to reflect the card's active state. Outside of the index
10904 * context, setting the active state on a card does nothing.
10905 *
10906 * @param {boolean} value Card is active
10907 * @fires active
10908 */
10909 OO.ui.CardLayout.prototype.setActive = function ( active ) {
10910 active = !!active;
10911
10912 if ( active !== this.active ) {
10913 this.active = active;
10914 this.$element.toggleClass( 'oo-ui-cardLayout-active', this.active );
10915 this.emit( 'active', this.active );
10916 }
10917 };
10918
10919 /**
10920 * PageLayouts are used within {@link OO.ui.BookletLayout booklet layouts} to create pages that users can select and display
10921 * from the booklet's optional {@link OO.ui.OutlineSelectWidget outline} navigation. Pages are usually not instantiated directly,
10922 * rather extended to include the required content and functionality.
10923 *
10924 * Each page must have a unique symbolic name, which is passed to the constructor. In addition, the page's outline
10925 * item is customized (with a label, outline level, etc.) using the #setupOutlineItem method. See
10926 * {@link OO.ui.BookletLayout BookletLayout} for an example.
10927 *
10928 * @class
10929 * @extends OO.ui.PanelLayout
10930 *
10931 * @constructor
10932 * @param {string} name Unique symbolic name of page
10933 * @param {Object} [config] Configuration options
10934 */
10935 OO.ui.PageLayout = function OoUiPageLayout( name, config ) {
10936 // Allow passing positional parameters inside the config object
10937 if ( OO.isPlainObject( name ) && config === undefined ) {
10938 config = name;
10939 name = config.name;
10940 }
10941
10942 // Configuration initialization
10943 config = $.extend( { scrollable: true }, config );
10944
10945 // Parent constructor
10946 OO.ui.PageLayout.parent.call( this, config );
10947
10948 // Properties
10949 this.name = name;
10950 this.outlineItem = null;
10951 this.active = false;
10952
10953 // Initialization
10954 this.$element.addClass( 'oo-ui-pageLayout' );
10955 };
10956
10957 /* Setup */
10958
10959 OO.inheritClass( OO.ui.PageLayout, OO.ui.PanelLayout );
10960
10961 /* Events */
10962
10963 /**
10964 * An 'active' event is emitted when the page becomes active. Pages become active when they are
10965 * shown in a booklet layout that is configured to display only one page at a time.
10966 *
10967 * @event active
10968 * @param {boolean} active Page is active
10969 */
10970
10971 /* Methods */
10972
10973 /**
10974 * Get the symbolic name of the page.
10975 *
10976 * @return {string} Symbolic name of page
10977 */
10978 OO.ui.PageLayout.prototype.getName = function () {
10979 return this.name;
10980 };
10981
10982 /**
10983 * Check if page is active.
10984 *
10985 * Pages become active when they are shown in a {@link OO.ui.BookletLayout booklet layout} that is configured to display
10986 * only one page at a time. Additional CSS is applied to the page's outline item to reflect the active state.
10987 *
10988 * @return {boolean} Page is active
10989 */
10990 OO.ui.PageLayout.prototype.isActive = function () {
10991 return this.active;
10992 };
10993
10994 /**
10995 * Get outline item.
10996 *
10997 * The outline item allows users to access the page from the booklet's outline
10998 * navigation. The outline item itself can be customized (with a label, level, etc.) using the #setupOutlineItem method.
10999 *
11000 * @return {OO.ui.OutlineOptionWidget|null} Outline option widget
11001 */
11002 OO.ui.PageLayout.prototype.getOutlineItem = function () {
11003 return this.outlineItem;
11004 };
11005
11006 /**
11007 * Set or unset the outline item.
11008 *
11009 * Specify an {@link OO.ui.OutlineOptionWidget outline option} to set it,
11010 * or `null` to clear the outline item. To customize the outline item itself (e.g., to set a label or outline
11011 * level), use #setupOutlineItem instead of this method.
11012 *
11013 * @param {OO.ui.OutlineOptionWidget|null} outlineItem Outline option widget, null to clear
11014 * @chainable
11015 */
11016 OO.ui.PageLayout.prototype.setOutlineItem = function ( outlineItem ) {
11017 this.outlineItem = outlineItem || null;
11018 if ( outlineItem ) {
11019 this.setupOutlineItem();
11020 }
11021 return this;
11022 };
11023
11024 /**
11025 * Set up the outline item.
11026 *
11027 * Use this method to customize the outline item (e.g., to add a label or outline level). To set or unset
11028 * the outline item itself (with an {@link OO.ui.OutlineOptionWidget outline option} or `null`), use
11029 * the #setOutlineItem method instead.
11030 *
11031 * @param {OO.ui.OutlineOptionWidget} outlineItem Outline option widget to set up
11032 * @chainable
11033 */
11034 OO.ui.PageLayout.prototype.setupOutlineItem = function () {
11035 return this;
11036 };
11037
11038 /**
11039 * Set the page to its 'active' state.
11040 *
11041 * Pages become active when they are shown in a booklet layout that is configured to display only one page at a time. Additional
11042 * CSS is applied to the outline item to reflect the page's active state. Outside of the booklet
11043 * context, setting the active state on a page does nothing.
11044 *
11045 * @param {boolean} value Page is active
11046 * @fires active
11047 */
11048 OO.ui.PageLayout.prototype.setActive = function ( active ) {
11049 active = !!active;
11050
11051 if ( active !== this.active ) {
11052 this.active = active;
11053 this.$element.toggleClass( 'oo-ui-pageLayout-active', active );
11054 this.emit( 'active', this.active );
11055 }
11056 };
11057
11058 /**
11059 * StackLayouts contain a series of {@link OO.ui.PanelLayout panel layouts}. By default, only one panel is displayed
11060 * at a time, though the stack layout can also be configured to show all contained panels, one after another,
11061 * by setting the #continuous option to 'true'.
11062 *
11063 * @example
11064 * // A stack layout with two panels, configured to be displayed continously
11065 * var myStack = new OO.ui.StackLayout( {
11066 * items: [
11067 * new OO.ui.PanelLayout( {
11068 * $content: $( '<p>Panel One</p>' ),
11069 * padded: true,
11070 * framed: true
11071 * } ),
11072 * new OO.ui.PanelLayout( {
11073 * $content: $( '<p>Panel Two</p>' ),
11074 * padded: true,
11075 * framed: true
11076 * } )
11077 * ],
11078 * continuous: true
11079 * } );
11080 * $( 'body' ).append( myStack.$element );
11081 *
11082 * @class
11083 * @extends OO.ui.PanelLayout
11084 * @mixins OO.ui.mixin.GroupElement
11085 *
11086 * @constructor
11087 * @param {Object} [config] Configuration options
11088 * @cfg {boolean} [continuous=false] Show all panels, one after another. By default, only one panel is displayed at a time.
11089 * @cfg {OO.ui.Layout[]} [items] Panel layouts to add to the stack layout.
11090 */
11091 OO.ui.StackLayout = function OoUiStackLayout( config ) {
11092 // Configuration initialization
11093 config = $.extend( { scrollable: true }, config );
11094
11095 // Parent constructor
11096 OO.ui.StackLayout.parent.call( this, config );
11097
11098 // Mixin constructors
11099 OO.ui.mixin.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) );
11100
11101 // Properties
11102 this.currentItem = null;
11103 this.continuous = !!config.continuous;
11104
11105 // Initialization
11106 this.$element.addClass( 'oo-ui-stackLayout' );
11107 if ( this.continuous ) {
11108 this.$element.addClass( 'oo-ui-stackLayout-continuous' );
11109 this.$element.on( 'scroll', OO.ui.debounce( this.onScroll.bind( this ), 250 ) );
11110 }
11111 if ( Array.isArray( config.items ) ) {
11112 this.addItems( config.items );
11113 }
11114 };
11115
11116 /* Setup */
11117
11118 OO.inheritClass( OO.ui.StackLayout, OO.ui.PanelLayout );
11119 OO.mixinClass( OO.ui.StackLayout, OO.ui.mixin.GroupElement );
11120
11121 /* Events */
11122
11123 /**
11124 * A 'set' event is emitted when panels are {@link #addItems added}, {@link #removeItems removed},
11125 * {@link #clearItems cleared} or {@link #setItem displayed}.
11126 *
11127 * @event set
11128 * @param {OO.ui.Layout|null} item Current panel or `null` if no panel is shown
11129 */
11130
11131 /**
11132 * When used in continuous mode, this event is emitted when the user scrolls down
11133 * far enough such that currentItem is no longer visible.
11134 *
11135 * @event visibleItemChange
11136 * @param {OO.ui.PanelLayout} panel The next visible item in the layout
11137 */
11138
11139 /* Methods */
11140
11141 /**
11142 * Handle scroll events from the layout element
11143 *
11144 * @param {jQuery.Event} e
11145 * @fires visibleItemChange
11146 */
11147 OO.ui.StackLayout.prototype.onScroll = function () {
11148 var currentRect,
11149 len = this.items.length,
11150 currentIndex = this.items.indexOf( this.currentItem ),
11151 newIndex = currentIndex,
11152 containerRect = this.$element[ 0 ].getBoundingClientRect();
11153
11154 if ( !containerRect || ( !containerRect.top && !containerRect.bottom ) ) {
11155 // Can't get bounding rect, possibly not attached.
11156 return;
11157 }
11158
11159 function getRect( item ) {
11160 return item.$element[ 0 ].getBoundingClientRect();
11161 }
11162
11163 function isVisible( item ) {
11164 var rect = getRect( item );
11165 return rect.bottom > containerRect.top && rect.top < containerRect.bottom;
11166 }
11167
11168 currentRect = getRect( this.currentItem );
11169
11170 if ( currentRect.bottom < containerRect.top ) {
11171 // Scrolled down past current item
11172 while ( ++newIndex < len ) {
11173 if ( isVisible( this.items[ newIndex ] ) ) {
11174 break;
11175 }
11176 }
11177 } else if ( currentRect.top > containerRect.bottom ) {
11178 // Scrolled up past current item
11179 while ( --newIndex >= 0 ) {
11180 if ( isVisible( this.items[ newIndex ] ) ) {
11181 break;
11182 }
11183 }
11184 }
11185
11186 if ( newIndex !== currentIndex ) {
11187 this.emit( 'visibleItemChange', this.items[ newIndex ] );
11188 }
11189 };
11190
11191 /**
11192 * Get the current panel.
11193 *
11194 * @return {OO.ui.Layout|null}
11195 */
11196 OO.ui.StackLayout.prototype.getCurrentItem = function () {
11197 return this.currentItem;
11198 };
11199
11200 /**
11201 * Unset the current item.
11202 *
11203 * @private
11204 * @param {OO.ui.StackLayout} layout
11205 * @fires set
11206 */
11207 OO.ui.StackLayout.prototype.unsetCurrentItem = function () {
11208 var prevItem = this.currentItem;
11209 if ( prevItem === null ) {
11210 return;
11211 }
11212
11213 this.currentItem = null;
11214 this.emit( 'set', null );
11215 };
11216
11217 /**
11218 * Add panel layouts to the stack layout.
11219 *
11220 * Panels will be added to the end of the stack layout array unless the optional index parameter specifies a different
11221 * insertion point. Adding a panel that is already in the stack will move it to the end of the array or the point specified
11222 * by the index.
11223 *
11224 * @param {OO.ui.Layout[]} items Panels to add
11225 * @param {number} [index] Index of the insertion point
11226 * @chainable
11227 */
11228 OO.ui.StackLayout.prototype.addItems = function ( items, index ) {
11229 // Update the visibility
11230 this.updateHiddenState( items, this.currentItem );
11231
11232 // Mixin method
11233 OO.ui.mixin.GroupElement.prototype.addItems.call( this, items, index );
11234
11235 if ( !this.currentItem && items.length ) {
11236 this.setItem( items[ 0 ] );
11237 }
11238
11239 return this;
11240 };
11241
11242 /**
11243 * Remove the specified panels from the stack layout.
11244 *
11245 * Removed panels are detached from the DOM, not removed, so that they may be reused. To remove all panels,
11246 * you may wish to use the #clearItems method instead.
11247 *
11248 * @param {OO.ui.Layout[]} items Panels to remove
11249 * @chainable
11250 * @fires set
11251 */
11252 OO.ui.StackLayout.prototype.removeItems = function ( items ) {
11253 // Mixin method
11254 OO.ui.mixin.GroupElement.prototype.removeItems.call( this, items );
11255
11256 if ( items.indexOf( this.currentItem ) !== -1 ) {
11257 if ( this.items.length ) {
11258 this.setItem( this.items[ 0 ] );
11259 } else {
11260 this.unsetCurrentItem();
11261 }
11262 }
11263
11264 return this;
11265 };
11266
11267 /**
11268 * Clear all panels from the stack layout.
11269 *
11270 * Cleared panels are detached from the DOM, not removed, so that they may be reused. To remove only
11271 * a subset of panels, use the #removeItems method.
11272 *
11273 * @chainable
11274 * @fires set
11275 */
11276 OO.ui.StackLayout.prototype.clearItems = function () {
11277 this.unsetCurrentItem();
11278 OO.ui.mixin.GroupElement.prototype.clearItems.call( this );
11279
11280 return this;
11281 };
11282
11283 /**
11284 * Show the specified panel.
11285 *
11286 * If another panel is currently displayed, it will be hidden.
11287 *
11288 * @param {OO.ui.Layout} item Panel to show
11289 * @chainable
11290 * @fires set
11291 */
11292 OO.ui.StackLayout.prototype.setItem = function ( item ) {
11293 if ( item !== this.currentItem ) {
11294 this.updateHiddenState( this.items, item );
11295
11296 if ( this.items.indexOf( item ) !== -1 ) {
11297 this.currentItem = item;
11298 this.emit( 'set', item );
11299 } else {
11300 this.unsetCurrentItem();
11301 }
11302 }
11303
11304 return this;
11305 };
11306
11307 /**
11308 * Update the visibility of all items in case of non-continuous view.
11309 *
11310 * Ensure all items are hidden except for the selected one.
11311 * This method does nothing when the stack is continuous.
11312 *
11313 * @private
11314 * @param {OO.ui.Layout[]} items Item list iterate over
11315 * @param {OO.ui.Layout} [selectedItem] Selected item to show
11316 */
11317 OO.ui.StackLayout.prototype.updateHiddenState = function ( items, selectedItem ) {
11318 var i, len;
11319
11320 if ( !this.continuous ) {
11321 for ( i = 0, len = items.length; i < len; i++ ) {
11322 if ( !selectedItem || selectedItem !== items[ i ] ) {
11323 items[ i ].$element.addClass( 'oo-ui-element-hidden' );
11324 }
11325 }
11326 if ( selectedItem ) {
11327 selectedItem.$element.removeClass( 'oo-ui-element-hidden' );
11328 }
11329 }
11330 };
11331
11332 /**
11333 * HorizontalLayout arranges its contents in a single line (using `display: inline-block` for its
11334 * items), with small margins between them. Convenient when you need to put a number of block-level
11335 * widgets on a single line next to each other.
11336 *
11337 * Note that inline elements, such as OO.ui.ButtonWidgets, do not need this wrapper.
11338 *
11339 * @example
11340 * // HorizontalLayout with a text input and a label
11341 * var layout = new OO.ui.HorizontalLayout( {
11342 * items: [
11343 * new OO.ui.LabelWidget( { label: 'Label' } ),
11344 * new OO.ui.TextInputWidget( { value: 'Text' } )
11345 * ]
11346 * } );
11347 * $( 'body' ).append( layout.$element );
11348 *
11349 * @class
11350 * @extends OO.ui.Layout
11351 * @mixins OO.ui.mixin.GroupElement
11352 *
11353 * @constructor
11354 * @param {Object} [config] Configuration options
11355 * @cfg {OO.ui.Widget[]|OO.ui.Layout[]} [items] Widgets or other layouts to add to the layout.
11356 */
11357 OO.ui.HorizontalLayout = function OoUiHorizontalLayout( config ) {
11358 // Configuration initialization
11359 config = config || {};
11360
11361 // Parent constructor
11362 OO.ui.HorizontalLayout.parent.call( this, config );
11363
11364 // Mixin constructors
11365 OO.ui.mixin.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) );
11366
11367 // Initialization
11368 this.$element.addClass( 'oo-ui-horizontalLayout' );
11369 if ( Array.isArray( config.items ) ) {
11370 this.addItems( config.items );
11371 }
11372 };
11373
11374 /* Setup */
11375
11376 OO.inheritClass( OO.ui.HorizontalLayout, OO.ui.Layout );
11377 OO.mixinClass( OO.ui.HorizontalLayout, OO.ui.mixin.GroupElement );
11378
11379 /**
11380 * BarToolGroups are one of three types of {@link OO.ui.ToolGroup toolgroups} that are used to
11381 * create {@link OO.ui.Toolbar toolbars} (the other types of groups are {@link OO.ui.MenuToolGroup MenuToolGroup}
11382 * and {@link OO.ui.ListToolGroup ListToolGroup}). The {@link OO.ui.Tool tools} in a BarToolGroup are
11383 * displayed by icon in a single row. The title of the tool is displayed when users move the mouse over
11384 * the tool.
11385 *
11386 * BarToolGroups are created by a {@link OO.ui.ToolGroupFactory tool group factory} when the toolbar is
11387 * set up.
11388 *
11389 * @example
11390 * // Example of a BarToolGroup with two tools
11391 * var toolFactory = new OO.ui.ToolFactory();
11392 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
11393 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
11394 *
11395 * // We will be placing status text in this element when tools are used
11396 * var $area = $( '<p>' ).text( 'Example of a BarToolGroup with two tools.' );
11397 *
11398 * // Define the tools that we're going to place in our toolbar
11399 *
11400 * // Create a class inheriting from OO.ui.Tool
11401 * function PictureTool() {
11402 * PictureTool.parent.apply( this, arguments );
11403 * }
11404 * OO.inheritClass( PictureTool, OO.ui.Tool );
11405 * // Each tool must have a 'name' (used as an internal identifier, see later) and at least one
11406 * // of 'icon' and 'title' (displayed icon and text).
11407 * PictureTool.static.name = 'picture';
11408 * PictureTool.static.icon = 'picture';
11409 * PictureTool.static.title = 'Insert picture';
11410 * // Defines the action that will happen when this tool is selected (clicked).
11411 * PictureTool.prototype.onSelect = function () {
11412 * $area.text( 'Picture tool clicked!' );
11413 * // Never display this tool as "active" (selected).
11414 * this.setActive( false );
11415 * };
11416 * // Make this tool available in our toolFactory and thus our toolbar
11417 * toolFactory.register( PictureTool );
11418 *
11419 * // This is a PopupTool. Rather than having a custom 'onSelect' action, it will display a
11420 * // little popup window (a PopupWidget).
11421 * function HelpTool( toolGroup, config ) {
11422 * OO.ui.PopupTool.call( this, toolGroup, $.extend( { popup: {
11423 * padded: true,
11424 * label: 'Help',
11425 * head: true
11426 * } }, config ) );
11427 * this.popup.$body.append( '<p>I am helpful!</p>' );
11428 * }
11429 * OO.inheritClass( HelpTool, OO.ui.PopupTool );
11430 * HelpTool.static.name = 'help';
11431 * HelpTool.static.icon = 'help';
11432 * HelpTool.static.title = 'Help';
11433 * toolFactory.register( HelpTool );
11434 *
11435 * // Finally define which tools and in what order appear in the toolbar. Each tool may only be
11436 * // used once (but not all defined tools must be used).
11437 * toolbar.setup( [
11438 * {
11439 * // 'bar' tool groups display tools by icon only
11440 * type: 'bar',
11441 * include: [ 'picture', 'help' ]
11442 * }
11443 * ] );
11444 *
11445 * // Create some UI around the toolbar and place it in the document
11446 * var frame = new OO.ui.PanelLayout( {
11447 * expanded: false,
11448 * framed: true
11449 * } );
11450 * var contentFrame = new OO.ui.PanelLayout( {
11451 * expanded: false,
11452 * padded: true
11453 * } );
11454 * frame.$element.append(
11455 * toolbar.$element,
11456 * contentFrame.$element.append( $area )
11457 * );
11458 * $( 'body' ).append( frame.$element );
11459 *
11460 * // Here is where the toolbar is actually built. This must be done after inserting it into the
11461 * // document.
11462 * toolbar.initialize();
11463 *
11464 * For more information about how to add tools to a bar tool group, please see {@link OO.ui.ToolGroup toolgroup}.
11465 * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki][1].
11466 *
11467 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
11468 *
11469 * @class
11470 * @extends OO.ui.ToolGroup
11471 *
11472 * @constructor
11473 * @param {OO.ui.Toolbar} toolbar
11474 * @param {Object} [config] Configuration options
11475 */
11476 OO.ui.BarToolGroup = function OoUiBarToolGroup( toolbar, config ) {
11477 // Allow passing positional parameters inside the config object
11478 if ( OO.isPlainObject( toolbar ) && config === undefined ) {
11479 config = toolbar;
11480 toolbar = config.toolbar;
11481 }
11482
11483 // Parent constructor
11484 OO.ui.BarToolGroup.parent.call( this, toolbar, config );
11485
11486 // Initialization
11487 this.$element.addClass( 'oo-ui-barToolGroup' );
11488 };
11489
11490 /* Setup */
11491
11492 OO.inheritClass( OO.ui.BarToolGroup, OO.ui.ToolGroup );
11493
11494 /* Static Properties */
11495
11496 OO.ui.BarToolGroup.static.titleTooltips = true;
11497
11498 OO.ui.BarToolGroup.static.accelTooltips = true;
11499
11500 OO.ui.BarToolGroup.static.name = 'bar';
11501
11502 /**
11503 * PopupToolGroup is an abstract base class used by both {@link OO.ui.MenuToolGroup MenuToolGroup}
11504 * and {@link OO.ui.ListToolGroup ListToolGroup} to provide a popup--an overlaid menu or list of tools with an
11505 * optional icon and label. This class can be used for other base classes that also use this functionality.
11506 *
11507 * @abstract
11508 * @class
11509 * @extends OO.ui.ToolGroup
11510 * @mixins OO.ui.mixin.IconElement
11511 * @mixins OO.ui.mixin.IndicatorElement
11512 * @mixins OO.ui.mixin.LabelElement
11513 * @mixins OO.ui.mixin.TitledElement
11514 * @mixins OO.ui.mixin.ClippableElement
11515 * @mixins OO.ui.mixin.TabIndexedElement
11516 *
11517 * @constructor
11518 * @param {OO.ui.Toolbar} toolbar
11519 * @param {Object} [config] Configuration options
11520 * @cfg {string} [header] Text to display at the top of the popup
11521 */
11522 OO.ui.PopupToolGroup = function OoUiPopupToolGroup( toolbar, config ) {
11523 // Allow passing positional parameters inside the config object
11524 if ( OO.isPlainObject( toolbar ) && config === undefined ) {
11525 config = toolbar;
11526 toolbar = config.toolbar;
11527 }
11528
11529 // Configuration initialization
11530 config = config || {};
11531
11532 // Parent constructor
11533 OO.ui.PopupToolGroup.parent.call( this, toolbar, config );
11534
11535 // Properties
11536 this.active = false;
11537 this.dragging = false;
11538 this.onBlurHandler = this.onBlur.bind( this );
11539 this.$handle = $( '<span>' );
11540
11541 // Mixin constructors
11542 OO.ui.mixin.IconElement.call( this, config );
11543 OO.ui.mixin.IndicatorElement.call( this, config );
11544 OO.ui.mixin.LabelElement.call( this, config );
11545 OO.ui.mixin.TitledElement.call( this, config );
11546 OO.ui.mixin.ClippableElement.call( this, $.extend( {}, config, { $clippable: this.$group } ) );
11547 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$handle } ) );
11548
11549 // Events
11550 this.$handle.on( {
11551 keydown: this.onHandleMouseKeyDown.bind( this ),
11552 keyup: this.onHandleMouseKeyUp.bind( this ),
11553 mousedown: this.onHandleMouseKeyDown.bind( this ),
11554 mouseup: this.onHandleMouseKeyUp.bind( this )
11555 } );
11556
11557 // Initialization
11558 this.$handle
11559 .addClass( 'oo-ui-popupToolGroup-handle' )
11560 .append( this.$icon, this.$label, this.$indicator );
11561 // If the pop-up should have a header, add it to the top of the toolGroup.
11562 // Note: If this feature is useful for other widgets, we could abstract it into an
11563 // OO.ui.HeaderedElement mixin constructor.
11564 if ( config.header !== undefined ) {
11565 this.$group
11566 .prepend( $( '<span>' )
11567 .addClass( 'oo-ui-popupToolGroup-header' )
11568 .text( config.header )
11569 );
11570 }
11571 this.$element
11572 .addClass( 'oo-ui-popupToolGroup' )
11573 .prepend( this.$handle );
11574 };
11575
11576 /* Setup */
11577
11578 OO.inheritClass( OO.ui.PopupToolGroup, OO.ui.ToolGroup );
11579 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.mixin.IconElement );
11580 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.mixin.IndicatorElement );
11581 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.mixin.LabelElement );
11582 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.mixin.TitledElement );
11583 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.mixin.ClippableElement );
11584 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.mixin.TabIndexedElement );
11585
11586 /* Methods */
11587
11588 /**
11589 * @inheritdoc
11590 */
11591 OO.ui.PopupToolGroup.prototype.setDisabled = function () {
11592 // Parent method
11593 OO.ui.PopupToolGroup.parent.prototype.setDisabled.apply( this, arguments );
11594
11595 if ( this.isDisabled() && this.isElementAttached() ) {
11596 this.setActive( false );
11597 }
11598 };
11599
11600 /**
11601 * Handle focus being lost.
11602 *
11603 * The event is actually generated from a mouseup/keyup, so it is not a normal blur event object.
11604 *
11605 * @protected
11606 * @param {jQuery.Event} e Mouse up or key up event
11607 */
11608 OO.ui.PopupToolGroup.prototype.onBlur = function ( e ) {
11609 // Only deactivate when clicking outside the dropdown element
11610 if ( $( e.target ).closest( '.oo-ui-popupToolGroup' )[ 0 ] !== this.$element[ 0 ] ) {
11611 this.setActive( false );
11612 }
11613 };
11614
11615 /**
11616 * @inheritdoc
11617 */
11618 OO.ui.PopupToolGroup.prototype.onMouseKeyUp = function ( e ) {
11619 // Only close toolgroup when a tool was actually selected
11620 if (
11621 !this.isDisabled() && this.pressed && this.pressed === this.getTargetTool( e ) &&
11622 ( e.which === 1 || e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
11623 ) {
11624 this.setActive( false );
11625 }
11626 return OO.ui.PopupToolGroup.parent.prototype.onMouseKeyUp.call( this, e );
11627 };
11628
11629 /**
11630 * Handle mouse up and key up events.
11631 *
11632 * @protected
11633 * @param {jQuery.Event} e Mouse up or key up event
11634 */
11635 OO.ui.PopupToolGroup.prototype.onHandleMouseKeyUp = function ( e ) {
11636 if (
11637 !this.isDisabled() &&
11638 ( e.which === 1 || e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
11639 ) {
11640 return false;
11641 }
11642 };
11643
11644 /**
11645 * Handle mouse down and key down events.
11646 *
11647 * @protected
11648 * @param {jQuery.Event} e Mouse down or key down event
11649 */
11650 OO.ui.PopupToolGroup.prototype.onHandleMouseKeyDown = function ( e ) {
11651 if (
11652 !this.isDisabled() &&
11653 ( e.which === 1 || e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
11654 ) {
11655 this.setActive( !this.active );
11656 return false;
11657 }
11658 };
11659
11660 /**
11661 * Switch into 'active' mode.
11662 *
11663 * When active, the popup is visible. A mouseup event anywhere in the document will trigger
11664 * deactivation.
11665 */
11666 OO.ui.PopupToolGroup.prototype.setActive = function ( value ) {
11667 var containerWidth, containerLeft;
11668 value = !!value;
11669 if ( this.active !== value ) {
11670 this.active = value;
11671 if ( value ) {
11672 OO.ui.addCaptureEventListener( this.getElementDocument(), 'mouseup', this.onBlurHandler );
11673 OO.ui.addCaptureEventListener( this.getElementDocument(), 'keyup', this.onBlurHandler );
11674
11675 this.$clippable.css( 'left', '' );
11676 // Try anchoring the popup to the left first
11677 this.$element.addClass( 'oo-ui-popupToolGroup-active oo-ui-popupToolGroup-left' );
11678 this.toggleClipping( true );
11679 if ( this.isClippedHorizontally() ) {
11680 // Anchoring to the left caused the popup to clip, so anchor it to the right instead
11681 this.toggleClipping( false );
11682 this.$element
11683 .removeClass( 'oo-ui-popupToolGroup-left' )
11684 .addClass( 'oo-ui-popupToolGroup-right' );
11685 this.toggleClipping( true );
11686 }
11687 if ( this.isClippedHorizontally() ) {
11688 // Anchoring to the right also caused the popup to clip, so just make it fill the container
11689 containerWidth = this.$clippableScrollableContainer.width();
11690 containerLeft = this.$clippableScrollableContainer.offset().left;
11691
11692 this.toggleClipping( false );
11693 this.$element.removeClass( 'oo-ui-popupToolGroup-right' );
11694
11695 this.$clippable.css( {
11696 left: -( this.$element.offset().left - containerLeft ),
11697 width: containerWidth
11698 } );
11699 }
11700 } else {
11701 OO.ui.removeCaptureEventListener( this.getElementDocument(), 'mouseup', this.onBlurHandler );
11702 OO.ui.removeCaptureEventListener( this.getElementDocument(), 'keyup', this.onBlurHandler );
11703 this.$element.removeClass(
11704 'oo-ui-popupToolGroup-active oo-ui-popupToolGroup-left oo-ui-popupToolGroup-right'
11705 );
11706 this.toggleClipping( false );
11707 }
11708 }
11709 };
11710
11711 /**
11712 * ListToolGroups are one of three types of {@link OO.ui.ToolGroup toolgroups} that are used to
11713 * create {@link OO.ui.Toolbar toolbars} (the other types of groups are {@link OO.ui.MenuToolGroup MenuToolGroup}
11714 * and {@link OO.ui.BarToolGroup BarToolGroup}). The {@link OO.ui.Tool tools} in a ListToolGroup are displayed
11715 * by label in a dropdown menu. The title of the tool is used as the label text. The menu itself can be configured
11716 * with a label, icon, indicator, header, and title.
11717 *
11718 * ListToolGroups can be configured to be expanded and collapsed. Collapsed lists will have a ‘More’ option that
11719 * users can select to see the full list of tools. If a collapsed toolgroup is expanded, a ‘Fewer’ option permits
11720 * users to collapse the list again.
11721 *
11722 * ListToolGroups are created by a {@link OO.ui.ToolGroupFactory toolgroup factory} when the toolbar is set up. The factory
11723 * requires the ListToolGroup's symbolic name, 'list', which is specified along with the other configurations. For more
11724 * information about how to add tools to a ListToolGroup, please see {@link OO.ui.ToolGroup toolgroup}.
11725 *
11726 * @example
11727 * // Example of a ListToolGroup
11728 * var toolFactory = new OO.ui.ToolFactory();
11729 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
11730 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
11731 *
11732 * // Configure and register two tools
11733 * function SettingsTool() {
11734 * SettingsTool.parent.apply( this, arguments );
11735 * }
11736 * OO.inheritClass( SettingsTool, OO.ui.Tool );
11737 * SettingsTool.static.name = 'settings';
11738 * SettingsTool.static.icon = 'settings';
11739 * SettingsTool.static.title = 'Change settings';
11740 * SettingsTool.prototype.onSelect = function () {
11741 * this.setActive( false );
11742 * };
11743 * toolFactory.register( SettingsTool );
11744 * // Register two more tools, nothing interesting here
11745 * function StuffTool() {
11746 * StuffTool.parent.apply( this, arguments );
11747 * }
11748 * OO.inheritClass( StuffTool, OO.ui.Tool );
11749 * StuffTool.static.name = 'stuff';
11750 * StuffTool.static.icon = 'ellipsis';
11751 * StuffTool.static.title = 'Change the world';
11752 * StuffTool.prototype.onSelect = function () {
11753 * this.setActive( false );
11754 * };
11755 * toolFactory.register( StuffTool );
11756 * toolbar.setup( [
11757 * {
11758 * // Configurations for list toolgroup.
11759 * type: 'list',
11760 * label: 'ListToolGroup',
11761 * indicator: 'down',
11762 * icon: 'picture',
11763 * title: 'This is the title, displayed when user moves the mouse over the list toolgroup',
11764 * header: 'This is the header',
11765 * include: [ 'settings', 'stuff' ],
11766 * allowCollapse: ['stuff']
11767 * }
11768 * ] );
11769 *
11770 * // Create some UI around the toolbar and place it in the document
11771 * var frame = new OO.ui.PanelLayout( {
11772 * expanded: false,
11773 * framed: true
11774 * } );
11775 * frame.$element.append(
11776 * toolbar.$element
11777 * );
11778 * $( 'body' ).append( frame.$element );
11779 * // Build the toolbar. This must be done after the toolbar has been appended to the document.
11780 * toolbar.initialize();
11781 *
11782 * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki][1].
11783 *
11784 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
11785 *
11786 * @class
11787 * @extends OO.ui.PopupToolGroup
11788 *
11789 * @constructor
11790 * @param {OO.ui.Toolbar} toolbar
11791 * @param {Object} [config] Configuration options
11792 * @cfg {Array} [allowCollapse] Allow the specified tools to be collapsed. By default, collapsible tools
11793 * will only be displayed if users click the ‘More’ option displayed at the bottom of the list. If
11794 * the list is expanded, a ‘Fewer’ option permits users to collapse the list again. Any tools that
11795 * are included in the toolgroup, but are not designated as collapsible, will always be displayed.
11796 * To open a collapsible list in its expanded state, set #expanded to 'true'.
11797 * @cfg {Array} [forceExpand] Expand the specified tools. All other tools will be designated as collapsible.
11798 * Unless #expanded is set to true, the collapsible tools will be collapsed when the list is first opened.
11799 * @cfg {boolean} [expanded=false] Expand collapsible tools. This config is only relevant if tools have
11800 * been designated as collapsible. When expanded is set to true, all tools in the group will be displayed
11801 * when the list is first opened. Users can collapse the list with a ‘Fewer’ option at the bottom.
11802 */
11803 OO.ui.ListToolGroup = function OoUiListToolGroup( toolbar, config ) {
11804 // Allow passing positional parameters inside the config object
11805 if ( OO.isPlainObject( toolbar ) && config === undefined ) {
11806 config = toolbar;
11807 toolbar = config.toolbar;
11808 }
11809
11810 // Configuration initialization
11811 config = config || {};
11812
11813 // Properties (must be set before parent constructor, which calls #populate)
11814 this.allowCollapse = config.allowCollapse;
11815 this.forceExpand = config.forceExpand;
11816 this.expanded = config.expanded !== undefined ? config.expanded : false;
11817 this.collapsibleTools = [];
11818
11819 // Parent constructor
11820 OO.ui.ListToolGroup.parent.call( this, toolbar, config );
11821
11822 // Initialization
11823 this.$element.addClass( 'oo-ui-listToolGroup' );
11824 };
11825
11826 /* Setup */
11827
11828 OO.inheritClass( OO.ui.ListToolGroup, OO.ui.PopupToolGroup );
11829
11830 /* Static Properties */
11831
11832 OO.ui.ListToolGroup.static.name = 'list';
11833
11834 /* Methods */
11835
11836 /**
11837 * @inheritdoc
11838 */
11839 OO.ui.ListToolGroup.prototype.populate = function () {
11840 var i, len, allowCollapse = [];
11841
11842 OO.ui.ListToolGroup.parent.prototype.populate.call( this );
11843
11844 // Update the list of collapsible tools
11845 if ( this.allowCollapse !== undefined ) {
11846 allowCollapse = this.allowCollapse;
11847 } else if ( this.forceExpand !== undefined ) {
11848 allowCollapse = OO.simpleArrayDifference( Object.keys( this.tools ), this.forceExpand );
11849 }
11850
11851 this.collapsibleTools = [];
11852 for ( i = 0, len = allowCollapse.length; i < len; i++ ) {
11853 if ( this.tools[ allowCollapse[ i ] ] !== undefined ) {
11854 this.collapsibleTools.push( this.tools[ allowCollapse[ i ] ] );
11855 }
11856 }
11857
11858 // Keep at the end, even when tools are added
11859 this.$group.append( this.getExpandCollapseTool().$element );
11860
11861 this.getExpandCollapseTool().toggle( this.collapsibleTools.length !== 0 );
11862 this.updateCollapsibleState();
11863 };
11864
11865 OO.ui.ListToolGroup.prototype.getExpandCollapseTool = function () {
11866 var ExpandCollapseTool;
11867 if ( this.expandCollapseTool === undefined ) {
11868 ExpandCollapseTool = function () {
11869 ExpandCollapseTool.parent.apply( this, arguments );
11870 };
11871
11872 OO.inheritClass( ExpandCollapseTool, OO.ui.Tool );
11873
11874 ExpandCollapseTool.prototype.onSelect = function () {
11875 this.toolGroup.expanded = !this.toolGroup.expanded;
11876 this.toolGroup.updateCollapsibleState();
11877 this.setActive( false );
11878 };
11879 ExpandCollapseTool.prototype.onUpdateState = function () {
11880 // Do nothing. Tool interface requires an implementation of this function.
11881 };
11882
11883 ExpandCollapseTool.static.name = 'more-fewer';
11884
11885 this.expandCollapseTool = new ExpandCollapseTool( this );
11886 }
11887 return this.expandCollapseTool;
11888 };
11889
11890 /**
11891 * @inheritdoc
11892 */
11893 OO.ui.ListToolGroup.prototype.onMouseKeyUp = function ( e ) {
11894 // Do not close the popup when the user wants to show more/fewer tools
11895 if (
11896 $( e.target ).closest( '.oo-ui-tool-name-more-fewer' ).length &&
11897 ( e.which === 1 || e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
11898 ) {
11899 // HACK: Prevent the popup list from being hidden. Skip the PopupToolGroup implementation (which
11900 // hides the popup list when a tool is selected) and call ToolGroup's implementation directly.
11901 return OO.ui.ListToolGroup.parent.parent.prototype.onMouseKeyUp.call( this, e );
11902 } else {
11903 return OO.ui.ListToolGroup.parent.prototype.onMouseKeyUp.call( this, e );
11904 }
11905 };
11906
11907 OO.ui.ListToolGroup.prototype.updateCollapsibleState = function () {
11908 var i, len;
11909
11910 this.getExpandCollapseTool()
11911 .setIcon( this.expanded ? 'collapse' : 'expand' )
11912 .setTitle( OO.ui.msg( this.expanded ? 'ooui-toolgroup-collapse' : 'ooui-toolgroup-expand' ) );
11913
11914 for ( i = 0, len = this.collapsibleTools.length; i < len; i++ ) {
11915 this.collapsibleTools[ i ].toggle( this.expanded );
11916 }
11917 };
11918
11919 /**
11920 * MenuToolGroups are one of three types of {@link OO.ui.ToolGroup toolgroups} that are used to
11921 * create {@link OO.ui.Toolbar toolbars} (the other types of groups are {@link OO.ui.BarToolGroup BarToolGroup}
11922 * and {@link OO.ui.ListToolGroup ListToolGroup}). MenuToolGroups contain selectable {@link OO.ui.Tool tools},
11923 * which are displayed by label in a dropdown menu. The tool's title is used as the label text, and the
11924 * menu label is updated to reflect which tool or tools are currently selected. If no tools are selected,
11925 * the menu label is empty. The menu can be configured with an indicator, icon, title, and/or header.
11926 *
11927 * MenuToolGroups are created by a {@link OO.ui.ToolGroupFactory tool group factory} when the toolbar
11928 * is set up. Note that all tools must define an {@link OO.ui.Tool#onUpdateState onUpdateState} method if
11929 * a MenuToolGroup is used.
11930 *
11931 * @example
11932 * // Example of a MenuToolGroup
11933 * var toolFactory = new OO.ui.ToolFactory();
11934 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
11935 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
11936 *
11937 * // We will be placing status text in this element when tools are used
11938 * var $area = $( '<p>' ).text( 'An example of a MenuToolGroup. Select a tool from the dropdown menu.' );
11939 *
11940 * // Define the tools that we're going to place in our toolbar
11941 *
11942 * function SettingsTool() {
11943 * SettingsTool.parent.apply( this, arguments );
11944 * this.reallyActive = false;
11945 * }
11946 * OO.inheritClass( SettingsTool, OO.ui.Tool );
11947 * SettingsTool.static.name = 'settings';
11948 * SettingsTool.static.icon = 'settings';
11949 * SettingsTool.static.title = 'Change settings';
11950 * SettingsTool.prototype.onSelect = function () {
11951 * $area.text( 'Settings tool clicked!' );
11952 * // Toggle the active state on each click
11953 * this.reallyActive = !this.reallyActive;
11954 * this.setActive( this.reallyActive );
11955 * // To update the menu label
11956 * this.toolbar.emit( 'updateState' );
11957 * };
11958 * SettingsTool.prototype.onUpdateState = function () {
11959 * };
11960 * toolFactory.register( SettingsTool );
11961 *
11962 * function StuffTool() {
11963 * StuffTool.parent.apply( this, arguments );
11964 * this.reallyActive = false;
11965 * }
11966 * OO.inheritClass( StuffTool, OO.ui.Tool );
11967 * StuffTool.static.name = 'stuff';
11968 * StuffTool.static.icon = 'ellipsis';
11969 * StuffTool.static.title = 'More stuff';
11970 * StuffTool.prototype.onSelect = function () {
11971 * $area.text( 'More stuff tool clicked!' );
11972 * // Toggle the active state on each click
11973 * this.reallyActive = !this.reallyActive;
11974 * this.setActive( this.reallyActive );
11975 * // To update the menu label
11976 * this.toolbar.emit( 'updateState' );
11977 * };
11978 * StuffTool.prototype.onUpdateState = function () {
11979 * };
11980 * toolFactory.register( StuffTool );
11981 *
11982 * // Finally define which tools and in what order appear in the toolbar. Each tool may only be
11983 * // used once (but not all defined tools must be used).
11984 * toolbar.setup( [
11985 * {
11986 * type: 'menu',
11987 * header: 'This is the (optional) header',
11988 * title: 'This is the (optional) title',
11989 * indicator: 'down',
11990 * include: [ 'settings', 'stuff' ]
11991 * }
11992 * ] );
11993 *
11994 * // Create some UI around the toolbar and place it in the document
11995 * var frame = new OO.ui.PanelLayout( {
11996 * expanded: false,
11997 * framed: true
11998 * } );
11999 * var contentFrame = new OO.ui.PanelLayout( {
12000 * expanded: false,
12001 * padded: true
12002 * } );
12003 * frame.$element.append(
12004 * toolbar.$element,
12005 * contentFrame.$element.append( $area )
12006 * );
12007 * $( 'body' ).append( frame.$element );
12008 *
12009 * // Here is where the toolbar is actually built. This must be done after inserting it into the
12010 * // document.
12011 * toolbar.initialize();
12012 * toolbar.emit( 'updateState' );
12013 *
12014 * For more information about how to add tools to a MenuToolGroup, please see {@link OO.ui.ToolGroup toolgroup}.
12015 * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki] [1].
12016 *
12017 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
12018 *
12019 * @class
12020 * @extends OO.ui.PopupToolGroup
12021 *
12022 * @constructor
12023 * @param {OO.ui.Toolbar} toolbar
12024 * @param {Object} [config] Configuration options
12025 */
12026 OO.ui.MenuToolGroup = function OoUiMenuToolGroup( toolbar, config ) {
12027 // Allow passing positional parameters inside the config object
12028 if ( OO.isPlainObject( toolbar ) && config === undefined ) {
12029 config = toolbar;
12030 toolbar = config.toolbar;
12031 }
12032
12033 // Configuration initialization
12034 config = config || {};
12035
12036 // Parent constructor
12037 OO.ui.MenuToolGroup.parent.call( this, toolbar, config );
12038
12039 // Events
12040 this.toolbar.connect( this, { updateState: 'onUpdateState' } );
12041
12042 // Initialization
12043 this.$element.addClass( 'oo-ui-menuToolGroup' );
12044 };
12045
12046 /* Setup */
12047
12048 OO.inheritClass( OO.ui.MenuToolGroup, OO.ui.PopupToolGroup );
12049
12050 /* Static Properties */
12051
12052 OO.ui.MenuToolGroup.static.name = 'menu';
12053
12054 /* Methods */
12055
12056 /**
12057 * Handle the toolbar state being updated.
12058 *
12059 * When the state changes, the title of each active item in the menu will be joined together and
12060 * used as a label for the group. The label will be empty if none of the items are active.
12061 *
12062 * @private
12063 */
12064 OO.ui.MenuToolGroup.prototype.onUpdateState = function () {
12065 var name,
12066 labelTexts = [];
12067
12068 for ( name in this.tools ) {
12069 if ( this.tools[ name ].isActive() ) {
12070 labelTexts.push( this.tools[ name ].getTitle() );
12071 }
12072 }
12073
12074 this.setLabel( labelTexts.join( ', ' ) || ' ' );
12075 };
12076
12077 /**
12078 * Popup tools open a popup window when they are selected from the {@link OO.ui.Toolbar toolbar}. Each popup tool is configured
12079 * 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
12080 * an #onSelect or #onUpdateState method, as these methods have been implemented already.
12081 *
12082 * // Example of a popup tool. When selected, a popup tool displays
12083 * // a popup window.
12084 * function HelpTool( toolGroup, config ) {
12085 * OO.ui.PopupTool.call( this, toolGroup, $.extend( { popup: {
12086 * padded: true,
12087 * label: 'Help',
12088 * head: true
12089 * } }, config ) );
12090 * this.popup.$body.append( '<p>I am helpful!</p>' );
12091 * };
12092 * OO.inheritClass( HelpTool, OO.ui.PopupTool );
12093 * HelpTool.static.name = 'help';
12094 * HelpTool.static.icon = 'help';
12095 * HelpTool.static.title = 'Help';
12096 * toolFactory.register( HelpTool );
12097 *
12098 * For an example of a toolbar that contains a popup tool, see {@link OO.ui.Toolbar toolbars}. For more information about
12099 * toolbars in genreral, please see the [OOjs UI documentation on MediaWiki][1].
12100 *
12101 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
12102 *
12103 * @abstract
12104 * @class
12105 * @extends OO.ui.Tool
12106 * @mixins OO.ui.mixin.PopupElement
12107 *
12108 * @constructor
12109 * @param {OO.ui.ToolGroup} toolGroup
12110 * @param {Object} [config] Configuration options
12111 */
12112 OO.ui.PopupTool = function OoUiPopupTool( toolGroup, config ) {
12113 // Allow passing positional parameters inside the config object
12114 if ( OO.isPlainObject( toolGroup ) && config === undefined ) {
12115 config = toolGroup;
12116 toolGroup = config.toolGroup;
12117 }
12118
12119 // Parent constructor
12120 OO.ui.PopupTool.parent.call( this, toolGroup, config );
12121
12122 // Mixin constructors
12123 OO.ui.mixin.PopupElement.call( this, config );
12124
12125 // Initialization
12126 this.$element
12127 .addClass( 'oo-ui-popupTool' )
12128 .append( this.popup.$element );
12129 };
12130
12131 /* Setup */
12132
12133 OO.inheritClass( OO.ui.PopupTool, OO.ui.Tool );
12134 OO.mixinClass( OO.ui.PopupTool, OO.ui.mixin.PopupElement );
12135
12136 /* Methods */
12137
12138 /**
12139 * Handle the tool being selected.
12140 *
12141 * @inheritdoc
12142 */
12143 OO.ui.PopupTool.prototype.onSelect = function () {
12144 if ( !this.isDisabled() ) {
12145 this.popup.toggle();
12146 }
12147 this.setActive( false );
12148 return false;
12149 };
12150
12151 /**
12152 * Handle the toolbar state being updated.
12153 *
12154 * @inheritdoc
12155 */
12156 OO.ui.PopupTool.prototype.onUpdateState = function () {
12157 this.setActive( false );
12158 };
12159
12160 /**
12161 * A ToolGroupTool is a special sort of tool that can contain other {@link OO.ui.Tool tools}
12162 * and {@link OO.ui.ToolGroup toolgroups}. The ToolGroupTool was specifically designed to be used
12163 * inside a {@link OO.ui.BarToolGroup bar} toolgroup to provide access to additional tools from
12164 * the bar item. Included tools will be displayed in a dropdown {@link OO.ui.ListToolGroup list}
12165 * when the ToolGroupTool is selected.
12166 *
12167 * // Example: ToolGroupTool with two nested tools, 'setting1' and 'setting2', defined elsewhere.
12168 *
12169 * function SettingsTool() {
12170 * SettingsTool.parent.apply( this, arguments );
12171 * };
12172 * OO.inheritClass( SettingsTool, OO.ui.ToolGroupTool );
12173 * SettingsTool.static.name = 'settings';
12174 * SettingsTool.static.title = 'Change settings';
12175 * SettingsTool.static.groupConfig = {
12176 * icon: 'settings',
12177 * label: 'ToolGroupTool',
12178 * include: [ 'setting1', 'setting2' ]
12179 * };
12180 * toolFactory.register( SettingsTool );
12181 *
12182 * For more information, please see the [OOjs UI documentation on MediaWiki][1].
12183 *
12184 * Please note that this implementation is subject to change per [T74159] [2].
12185 *
12186 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars#ToolGroupTool
12187 * [2]: https://phabricator.wikimedia.org/T74159
12188 *
12189 * @abstract
12190 * @class
12191 * @extends OO.ui.Tool
12192 *
12193 * @constructor
12194 * @param {OO.ui.ToolGroup} toolGroup
12195 * @param {Object} [config] Configuration options
12196 */
12197 OO.ui.ToolGroupTool = function OoUiToolGroupTool( toolGroup, config ) {
12198 // Allow passing positional parameters inside the config object
12199 if ( OO.isPlainObject( toolGroup ) && config === undefined ) {
12200 config = toolGroup;
12201 toolGroup = config.toolGroup;
12202 }
12203
12204 // Parent constructor
12205 OO.ui.ToolGroupTool.parent.call( this, toolGroup, config );
12206
12207 // Properties
12208 this.innerToolGroup = this.createGroup( this.constructor.static.groupConfig );
12209
12210 // Events
12211 this.innerToolGroup.connect( this, { disable: 'onToolGroupDisable' } );
12212
12213 // Initialization
12214 this.$link.remove();
12215 this.$element
12216 .addClass( 'oo-ui-toolGroupTool' )
12217 .append( this.innerToolGroup.$element );
12218 };
12219
12220 /* Setup */
12221
12222 OO.inheritClass( OO.ui.ToolGroupTool, OO.ui.Tool );
12223
12224 /* Static Properties */
12225
12226 /**
12227 * Toolgroup configuration.
12228 *
12229 * The toolgroup configuration consists of the tools to include, as well as an icon and label
12230 * to use for the bar item. Tools can be included by symbolic name, group, or with the
12231 * wildcard selector. Please see {@link OO.ui.ToolGroup toolgroup} for more information.
12232 *
12233 * @property {Object.<string,Array>}
12234 */
12235 OO.ui.ToolGroupTool.static.groupConfig = {};
12236
12237 /* Methods */
12238
12239 /**
12240 * Handle the tool being selected.
12241 *
12242 * @inheritdoc
12243 */
12244 OO.ui.ToolGroupTool.prototype.onSelect = function () {
12245 this.innerToolGroup.setActive( !this.innerToolGroup.active );
12246 return false;
12247 };
12248
12249 /**
12250 * Synchronize disabledness state of the tool with the inner toolgroup.
12251 *
12252 * @private
12253 * @param {boolean} disabled Element is disabled
12254 */
12255 OO.ui.ToolGroupTool.prototype.onToolGroupDisable = function ( disabled ) {
12256 this.setDisabled( disabled );
12257 };
12258
12259 /**
12260 * Handle the toolbar state being updated.
12261 *
12262 * @inheritdoc
12263 */
12264 OO.ui.ToolGroupTool.prototype.onUpdateState = function () {
12265 this.setActive( false );
12266 };
12267
12268 /**
12269 * Build a {@link OO.ui.ToolGroup toolgroup} from the specified configuration.
12270 *
12271 * @param {Object.<string,Array>} group Toolgroup configuration. Please see {@link OO.ui.ToolGroup toolgroup} for
12272 * more information.
12273 * @return {OO.ui.ListToolGroup}
12274 */
12275 OO.ui.ToolGroupTool.prototype.createGroup = function ( group ) {
12276 if ( group.include === '*' ) {
12277 // Apply defaults to catch-all groups
12278 if ( group.label === undefined ) {
12279 group.label = OO.ui.msg( 'ooui-toolbar-more' );
12280 }
12281 }
12282
12283 return this.toolbar.getToolGroupFactory().create( 'list', this.toolbar, group );
12284 };
12285
12286 /**
12287 * Mixin for OO.ui.Widget subclasses to provide OO.ui.mixin.GroupElement.
12288 *
12289 * Use together with OO.ui.mixin.ItemWidget to make disabled state inheritable.
12290 *
12291 * @private
12292 * @abstract
12293 * @class
12294 * @extends OO.ui.mixin.GroupElement
12295 *
12296 * @constructor
12297 * @param {Object} [config] Configuration options
12298 */
12299 OO.ui.mixin.GroupWidget = function OoUiMixinGroupWidget( config ) {
12300 // Parent constructor
12301 OO.ui.mixin.GroupWidget.parent.call( this, config );
12302 };
12303
12304 /* Setup */
12305
12306 OO.inheritClass( OO.ui.mixin.GroupWidget, OO.ui.mixin.GroupElement );
12307
12308 /* Methods */
12309
12310 /**
12311 * Set the disabled state of the widget.
12312 *
12313 * This will also update the disabled state of child widgets.
12314 *
12315 * @param {boolean} disabled Disable widget
12316 * @chainable
12317 */
12318 OO.ui.mixin.GroupWidget.prototype.setDisabled = function ( disabled ) {
12319 var i, len;
12320
12321 // Parent method
12322 // Note: Calling #setDisabled this way assumes this is mixed into an OO.ui.Widget
12323 OO.ui.Widget.prototype.setDisabled.call( this, disabled );
12324
12325 // During construction, #setDisabled is called before the OO.ui.mixin.GroupElement constructor
12326 if ( this.items ) {
12327 for ( i = 0, len = this.items.length; i < len; i++ ) {
12328 this.items[ i ].updateDisabled();
12329 }
12330 }
12331
12332 return this;
12333 };
12334
12335 /**
12336 * Mixin for widgets used as items in widgets that mix in OO.ui.mixin.GroupWidget.
12337 *
12338 * Item widgets have a reference to a OO.ui.mixin.GroupWidget while they are attached to the group. This
12339 * allows bidirectional communication.
12340 *
12341 * Use together with OO.ui.mixin.GroupWidget to make disabled state inheritable.
12342 *
12343 * @private
12344 * @abstract
12345 * @class
12346 *
12347 * @constructor
12348 */
12349 OO.ui.mixin.ItemWidget = function OoUiMixinItemWidget() {
12350 //
12351 };
12352
12353 /* Methods */
12354
12355 /**
12356 * Check if widget is disabled.
12357 *
12358 * Checks parent if present, making disabled state inheritable.
12359 *
12360 * @return {boolean} Widget is disabled
12361 */
12362 OO.ui.mixin.ItemWidget.prototype.isDisabled = function () {
12363 return this.disabled ||
12364 ( this.elementGroup instanceof OO.ui.Widget && this.elementGroup.isDisabled() );
12365 };
12366
12367 /**
12368 * Set group element is in.
12369 *
12370 * @param {OO.ui.mixin.GroupElement|null} group Group element, null if none
12371 * @chainable
12372 */
12373 OO.ui.mixin.ItemWidget.prototype.setElementGroup = function ( group ) {
12374 // Parent method
12375 // Note: Calling #setElementGroup this way assumes this is mixed into an OO.ui.Element
12376 OO.ui.Element.prototype.setElementGroup.call( this, group );
12377
12378 // Initialize item disabled states
12379 this.updateDisabled();
12380
12381 return this;
12382 };
12383
12384 /**
12385 * OutlineControlsWidget is a set of controls for an {@link OO.ui.OutlineSelectWidget outline select widget}.
12386 * Controls include moving items up and down, removing items, and adding different kinds of items.
12387 *
12388 * **Currently, this class is only used by {@link OO.ui.BookletLayout booklet layouts}.**
12389 *
12390 * @class
12391 * @extends OO.ui.Widget
12392 * @mixins OO.ui.mixin.GroupElement
12393 * @mixins OO.ui.mixin.IconElement
12394 *
12395 * @constructor
12396 * @param {OO.ui.OutlineSelectWidget} outline Outline to control
12397 * @param {Object} [config] Configuration options
12398 * @cfg {Object} [abilities] List of abilties
12399 * @cfg {boolean} [abilities.move=true] Allow moving movable items
12400 * @cfg {boolean} [abilities.remove=true] Allow removing removable items
12401 */
12402 OO.ui.OutlineControlsWidget = function OoUiOutlineControlsWidget( outline, config ) {
12403 // Allow passing positional parameters inside the config object
12404 if ( OO.isPlainObject( outline ) && config === undefined ) {
12405 config = outline;
12406 outline = config.outline;
12407 }
12408
12409 // Configuration initialization
12410 config = $.extend( { icon: 'add' }, config );
12411
12412 // Parent constructor
12413 OO.ui.OutlineControlsWidget.parent.call( this, config );
12414
12415 // Mixin constructors
12416 OO.ui.mixin.GroupElement.call( this, config );
12417 OO.ui.mixin.IconElement.call( this, config );
12418
12419 // Properties
12420 this.outline = outline;
12421 this.$movers = $( '<div>' );
12422 this.upButton = new OO.ui.ButtonWidget( {
12423 framed: false,
12424 icon: 'collapse',
12425 title: OO.ui.msg( 'ooui-outline-control-move-up' )
12426 } );
12427 this.downButton = new OO.ui.ButtonWidget( {
12428 framed: false,
12429 icon: 'expand',
12430 title: OO.ui.msg( 'ooui-outline-control-move-down' )
12431 } );
12432 this.removeButton = new OO.ui.ButtonWidget( {
12433 framed: false,
12434 icon: 'remove',
12435 title: OO.ui.msg( 'ooui-outline-control-remove' )
12436 } );
12437 this.abilities = { move: true, remove: true };
12438
12439 // Events
12440 outline.connect( this, {
12441 select: 'onOutlineChange',
12442 add: 'onOutlineChange',
12443 remove: 'onOutlineChange'
12444 } );
12445 this.upButton.connect( this, { click: [ 'emit', 'move', -1 ] } );
12446 this.downButton.connect( this, { click: [ 'emit', 'move', 1 ] } );
12447 this.removeButton.connect( this, { click: [ 'emit', 'remove' ] } );
12448
12449 // Initialization
12450 this.$element.addClass( 'oo-ui-outlineControlsWidget' );
12451 this.$group.addClass( 'oo-ui-outlineControlsWidget-items' );
12452 this.$movers
12453 .addClass( 'oo-ui-outlineControlsWidget-movers' )
12454 .append( this.removeButton.$element, this.upButton.$element, this.downButton.$element );
12455 this.$element.append( this.$icon, this.$group, this.$movers );
12456 this.setAbilities( config.abilities || {} );
12457 };
12458
12459 /* Setup */
12460
12461 OO.inheritClass( OO.ui.OutlineControlsWidget, OO.ui.Widget );
12462 OO.mixinClass( OO.ui.OutlineControlsWidget, OO.ui.mixin.GroupElement );
12463 OO.mixinClass( OO.ui.OutlineControlsWidget, OO.ui.mixin.IconElement );
12464
12465 /* Events */
12466
12467 /**
12468 * @event move
12469 * @param {number} places Number of places to move
12470 */
12471
12472 /**
12473 * @event remove
12474 */
12475
12476 /* Methods */
12477
12478 /**
12479 * Set abilities.
12480 *
12481 * @param {Object} abilities List of abilties
12482 * @param {boolean} [abilities.move] Allow moving movable items
12483 * @param {boolean} [abilities.remove] Allow removing removable items
12484 */
12485 OO.ui.OutlineControlsWidget.prototype.setAbilities = function ( abilities ) {
12486 var ability;
12487
12488 for ( ability in this.abilities ) {
12489 if ( abilities[ ability ] !== undefined ) {
12490 this.abilities[ ability ] = !!abilities[ ability ];
12491 }
12492 }
12493
12494 this.onOutlineChange();
12495 };
12496
12497 /**
12498 * @private
12499 * Handle outline change events.
12500 */
12501 OO.ui.OutlineControlsWidget.prototype.onOutlineChange = function () {
12502 var i, len, firstMovable, lastMovable,
12503 items = this.outline.getItems(),
12504 selectedItem = this.outline.getSelectedItem(),
12505 movable = this.abilities.move && selectedItem && selectedItem.isMovable(),
12506 removable = this.abilities.remove && selectedItem && selectedItem.isRemovable();
12507
12508 if ( movable ) {
12509 i = -1;
12510 len = items.length;
12511 while ( ++i < len ) {
12512 if ( items[ i ].isMovable() ) {
12513 firstMovable = items[ i ];
12514 break;
12515 }
12516 }
12517 i = len;
12518 while ( i-- ) {
12519 if ( items[ i ].isMovable() ) {
12520 lastMovable = items[ i ];
12521 break;
12522 }
12523 }
12524 }
12525 this.upButton.setDisabled( !movable || selectedItem === firstMovable );
12526 this.downButton.setDisabled( !movable || selectedItem === lastMovable );
12527 this.removeButton.setDisabled( !removable );
12528 };
12529
12530 /**
12531 * ToggleWidget implements basic behavior of widgets with an on/off state.
12532 * Please see OO.ui.ToggleButtonWidget and OO.ui.ToggleSwitchWidget for examples.
12533 *
12534 * @abstract
12535 * @class
12536 * @extends OO.ui.Widget
12537 *
12538 * @constructor
12539 * @param {Object} [config] Configuration options
12540 * @cfg {boolean} [value=false] The toggle’s initial on/off state.
12541 * By default, the toggle is in the 'off' state.
12542 */
12543 OO.ui.ToggleWidget = function OoUiToggleWidget( config ) {
12544 // Configuration initialization
12545 config = config || {};
12546
12547 // Parent constructor
12548 OO.ui.ToggleWidget.parent.call( this, config );
12549
12550 // Properties
12551 this.value = null;
12552
12553 // Initialization
12554 this.$element.addClass( 'oo-ui-toggleWidget' );
12555 this.setValue( !!config.value );
12556 };
12557
12558 /* Setup */
12559
12560 OO.inheritClass( OO.ui.ToggleWidget, OO.ui.Widget );
12561
12562 /* Events */
12563
12564 /**
12565 * @event change
12566 *
12567 * A change event is emitted when the on/off state of the toggle changes.
12568 *
12569 * @param {boolean} value Value representing the new state of the toggle
12570 */
12571
12572 /* Methods */
12573
12574 /**
12575 * Get the value representing the toggle’s state.
12576 *
12577 * @return {boolean} The on/off state of the toggle
12578 */
12579 OO.ui.ToggleWidget.prototype.getValue = function () {
12580 return this.value;
12581 };
12582
12583 /**
12584 * Set the state of the toggle: `true` for 'on', `false' for 'off'.
12585 *
12586 * @param {boolean} value The state of the toggle
12587 * @fires change
12588 * @chainable
12589 */
12590 OO.ui.ToggleWidget.prototype.setValue = function ( value ) {
12591 value = !!value;
12592 if ( this.value !== value ) {
12593 this.value = value;
12594 this.emit( 'change', value );
12595 this.$element.toggleClass( 'oo-ui-toggleWidget-on', value );
12596 this.$element.toggleClass( 'oo-ui-toggleWidget-off', !value );
12597 this.$element.attr( 'aria-checked', value.toString() );
12598 }
12599 return this;
12600 };
12601
12602 /**
12603 * A ButtonGroupWidget groups related buttons and is used together with OO.ui.ButtonWidget and
12604 * its subclasses. Each button in a group is addressed by a unique reference. Buttons can be added,
12605 * removed, and cleared from the group.
12606 *
12607 * @example
12608 * // Example: A ButtonGroupWidget with two buttons
12609 * var button1 = new OO.ui.PopupButtonWidget( {
12610 * label: 'Select a category',
12611 * icon: 'menu',
12612 * popup: {
12613 * $content: $( '<p>List of categories...</p>' ),
12614 * padded: true,
12615 * align: 'left'
12616 * }
12617 * } );
12618 * var button2 = new OO.ui.ButtonWidget( {
12619 * label: 'Add item'
12620 * });
12621 * var buttonGroup = new OO.ui.ButtonGroupWidget( {
12622 * items: [button1, button2]
12623 * } );
12624 * $( 'body' ).append( buttonGroup.$element );
12625 *
12626 * @class
12627 * @extends OO.ui.Widget
12628 * @mixins OO.ui.mixin.GroupElement
12629 *
12630 * @constructor
12631 * @param {Object} [config] Configuration options
12632 * @cfg {OO.ui.ButtonWidget[]} [items] Buttons to add
12633 */
12634 OO.ui.ButtonGroupWidget = function OoUiButtonGroupWidget( config ) {
12635 // Configuration initialization
12636 config = config || {};
12637
12638 // Parent constructor
12639 OO.ui.ButtonGroupWidget.parent.call( this, config );
12640
12641 // Mixin constructors
12642 OO.ui.mixin.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) );
12643
12644 // Initialization
12645 this.$element.addClass( 'oo-ui-buttonGroupWidget' );
12646 if ( Array.isArray( config.items ) ) {
12647 this.addItems( config.items );
12648 }
12649 };
12650
12651 /* Setup */
12652
12653 OO.inheritClass( OO.ui.ButtonGroupWidget, OO.ui.Widget );
12654 OO.mixinClass( OO.ui.ButtonGroupWidget, OO.ui.mixin.GroupElement );
12655
12656 /**
12657 * ButtonWidget is a generic widget for buttons. A wide variety of looks,
12658 * feels, and functionality can be customized via the class’s configuration options
12659 * and methods. Please see the [OOjs UI documentation on MediaWiki] [1] for more information
12660 * and examples.
12661 *
12662 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches
12663 *
12664 * @example
12665 * // A button widget
12666 * var button = new OO.ui.ButtonWidget( {
12667 * label: 'Button with Icon',
12668 * icon: 'remove',
12669 * iconTitle: 'Remove'
12670 * } );
12671 * $( 'body' ).append( button.$element );
12672 *
12673 * NOTE: HTML form buttons should use the OO.ui.ButtonInputWidget class.
12674 *
12675 * @class
12676 * @extends OO.ui.Widget
12677 * @mixins OO.ui.mixin.ButtonElement
12678 * @mixins OO.ui.mixin.IconElement
12679 * @mixins OO.ui.mixin.IndicatorElement
12680 * @mixins OO.ui.mixin.LabelElement
12681 * @mixins OO.ui.mixin.TitledElement
12682 * @mixins OO.ui.mixin.FlaggedElement
12683 * @mixins OO.ui.mixin.TabIndexedElement
12684 * @mixins OO.ui.mixin.AccessKeyedElement
12685 *
12686 * @constructor
12687 * @param {Object} [config] Configuration options
12688 * @cfg {string} [href] Hyperlink to visit when the button is clicked.
12689 * @cfg {string} [target] The frame or window in which to open the hyperlink.
12690 * @cfg {boolean} [noFollow] Search engine traversal hint (default: true)
12691 */
12692 OO.ui.ButtonWidget = function OoUiButtonWidget( config ) {
12693 // Configuration initialization
12694 config = config || {};
12695
12696 // Parent constructor
12697 OO.ui.ButtonWidget.parent.call( this, config );
12698
12699 // Mixin constructors
12700 OO.ui.mixin.ButtonElement.call( this, config );
12701 OO.ui.mixin.IconElement.call( this, config );
12702 OO.ui.mixin.IndicatorElement.call( this, config );
12703 OO.ui.mixin.LabelElement.call( this, config );
12704 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$button } ) );
12705 OO.ui.mixin.FlaggedElement.call( this, config );
12706 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$button } ) );
12707 OO.ui.mixin.AccessKeyedElement.call( this, $.extend( {}, config, { $accessKeyed: this.$button } ) );
12708
12709 // Properties
12710 this.href = null;
12711 this.target = null;
12712 this.noFollow = false;
12713
12714 // Events
12715 this.connect( this, { disable: 'onDisable' } );
12716
12717 // Initialization
12718 this.$button.append( this.$icon, this.$label, this.$indicator );
12719 this.$element
12720 .addClass( 'oo-ui-buttonWidget' )
12721 .append( this.$button );
12722 this.setHref( config.href );
12723 this.setTarget( config.target );
12724 this.setNoFollow( config.noFollow );
12725 };
12726
12727 /* Setup */
12728
12729 OO.inheritClass( OO.ui.ButtonWidget, OO.ui.Widget );
12730 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.ButtonElement );
12731 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.IconElement );
12732 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.IndicatorElement );
12733 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.LabelElement );
12734 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.TitledElement );
12735 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.FlaggedElement );
12736 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.TabIndexedElement );
12737 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.AccessKeyedElement );
12738
12739 /* Methods */
12740
12741 /**
12742 * @inheritdoc
12743 */
12744 OO.ui.ButtonWidget.prototype.onMouseDown = function ( e ) {
12745 if ( !this.isDisabled() ) {
12746 // Remove the tab-index while the button is down to prevent the button from stealing focus
12747 this.$button.removeAttr( 'tabindex' );
12748 }
12749
12750 return OO.ui.mixin.ButtonElement.prototype.onMouseDown.call( this, e );
12751 };
12752
12753 /**
12754 * @inheritdoc
12755 */
12756 OO.ui.ButtonWidget.prototype.onMouseUp = function ( e ) {
12757 if ( !this.isDisabled() ) {
12758 // Restore the tab-index after the button is up to restore the button's accessibility
12759 this.$button.attr( 'tabindex', this.tabIndex );
12760 }
12761
12762 return OO.ui.mixin.ButtonElement.prototype.onMouseUp.call( this, e );
12763 };
12764
12765 /**
12766 * Get hyperlink location.
12767 *
12768 * @return {string} Hyperlink location
12769 */
12770 OO.ui.ButtonWidget.prototype.getHref = function () {
12771 return this.href;
12772 };
12773
12774 /**
12775 * Get hyperlink target.
12776 *
12777 * @return {string} Hyperlink target
12778 */
12779 OO.ui.ButtonWidget.prototype.getTarget = function () {
12780 return this.target;
12781 };
12782
12783 /**
12784 * Get search engine traversal hint.
12785 *
12786 * @return {boolean} Whether search engines should avoid traversing this hyperlink
12787 */
12788 OO.ui.ButtonWidget.prototype.getNoFollow = function () {
12789 return this.noFollow;
12790 };
12791
12792 /**
12793 * Set hyperlink location.
12794 *
12795 * @param {string|null} href Hyperlink location, null to remove
12796 */
12797 OO.ui.ButtonWidget.prototype.setHref = function ( href ) {
12798 href = typeof href === 'string' ? href : null;
12799 if ( href !== null ) {
12800 if ( !OO.ui.isSafeUrl( href ) ) {
12801 throw new Error( 'Potentially unsafe href provided: ' + href );
12802 }
12803
12804 }
12805
12806 if ( href !== this.href ) {
12807 this.href = href;
12808 this.updateHref();
12809 }
12810
12811 return this;
12812 };
12813
12814 /**
12815 * Update the `href` attribute, in case of changes to href or
12816 * disabled state.
12817 *
12818 * @private
12819 * @chainable
12820 */
12821 OO.ui.ButtonWidget.prototype.updateHref = function () {
12822 if ( this.href !== null && !this.isDisabled() ) {
12823 this.$button.attr( 'href', this.href );
12824 } else {
12825 this.$button.removeAttr( 'href' );
12826 }
12827
12828 return this;
12829 };
12830
12831 /**
12832 * Handle disable events.
12833 *
12834 * @private
12835 * @param {boolean} disabled Element is disabled
12836 */
12837 OO.ui.ButtonWidget.prototype.onDisable = function () {
12838 this.updateHref();
12839 };
12840
12841 /**
12842 * Set hyperlink target.
12843 *
12844 * @param {string|null} target Hyperlink target, null to remove
12845 */
12846 OO.ui.ButtonWidget.prototype.setTarget = function ( target ) {
12847 target = typeof target === 'string' ? target : null;
12848
12849 if ( target !== this.target ) {
12850 this.target = target;
12851 if ( target !== null ) {
12852 this.$button.attr( 'target', target );
12853 } else {
12854 this.$button.removeAttr( 'target' );
12855 }
12856 }
12857
12858 return this;
12859 };
12860
12861 /**
12862 * Set search engine traversal hint.
12863 *
12864 * @param {boolean} noFollow True if search engines should avoid traversing this hyperlink
12865 */
12866 OO.ui.ButtonWidget.prototype.setNoFollow = function ( noFollow ) {
12867 noFollow = typeof noFollow === 'boolean' ? noFollow : true;
12868
12869 if ( noFollow !== this.noFollow ) {
12870 this.noFollow = noFollow;
12871 if ( noFollow ) {
12872 this.$button.attr( 'rel', 'nofollow' );
12873 } else {
12874 this.$button.removeAttr( 'rel' );
12875 }
12876 }
12877
12878 return this;
12879 };
12880
12881 /**
12882 * An ActionWidget is a {@link OO.ui.ButtonWidget button widget} that executes an action.
12883 * Action widgets are used with OO.ui.ActionSet, which manages the behavior and availability
12884 * of the actions.
12885 *
12886 * Both actions and action sets are primarily used with {@link OO.ui.Dialog Dialogs}.
12887 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information
12888 * and examples.
12889 *
12890 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Action_sets
12891 *
12892 * @class
12893 * @extends OO.ui.ButtonWidget
12894 * @mixins OO.ui.mixin.PendingElement
12895 *
12896 * @constructor
12897 * @param {Object} [config] Configuration options
12898 * @cfg {string} [action] Symbolic name of the action (e.g., ‘continue’ or ‘cancel’).
12899 * @cfg {string[]} [modes] Symbolic names of the modes (e.g., ‘edit’ or ‘read’) in which the action
12900 * should be made available. See the action set's {@link OO.ui.ActionSet#setMode setMode} method
12901 * for more information about setting modes.
12902 * @cfg {boolean} [framed=false] Render the action button with a frame
12903 */
12904 OO.ui.ActionWidget = function OoUiActionWidget( config ) {
12905 // Configuration initialization
12906 config = $.extend( { framed: false }, config );
12907
12908 // Parent constructor
12909 OO.ui.ActionWidget.parent.call( this, config );
12910
12911 // Mixin constructors
12912 OO.ui.mixin.PendingElement.call( this, config );
12913
12914 // Properties
12915 this.action = config.action || '';
12916 this.modes = config.modes || [];
12917 this.width = 0;
12918 this.height = 0;
12919
12920 // Initialization
12921 this.$element.addClass( 'oo-ui-actionWidget' );
12922 };
12923
12924 /* Setup */
12925
12926 OO.inheritClass( OO.ui.ActionWidget, OO.ui.ButtonWidget );
12927 OO.mixinClass( OO.ui.ActionWidget, OO.ui.mixin.PendingElement );
12928
12929 /* Events */
12930
12931 /**
12932 * A resize event is emitted when the size of the widget changes.
12933 *
12934 * @event resize
12935 */
12936
12937 /* Methods */
12938
12939 /**
12940 * Check if the action is configured to be available in the specified `mode`.
12941 *
12942 * @param {string} mode Name of mode
12943 * @return {boolean} The action is configured with the mode
12944 */
12945 OO.ui.ActionWidget.prototype.hasMode = function ( mode ) {
12946 return this.modes.indexOf( mode ) !== -1;
12947 };
12948
12949 /**
12950 * Get the symbolic name of the action (e.g., ‘continue’ or ‘cancel’).
12951 *
12952 * @return {string}
12953 */
12954 OO.ui.ActionWidget.prototype.getAction = function () {
12955 return this.action;
12956 };
12957
12958 /**
12959 * Get the symbolic name of the mode or modes for which the action is configured to be available.
12960 *
12961 * The current mode is set with the action set's {@link OO.ui.ActionSet#setMode setMode} method.
12962 * Only actions that are configured to be avaiable in the current mode will be visible. All other actions
12963 * are hidden.
12964 *
12965 * @return {string[]}
12966 */
12967 OO.ui.ActionWidget.prototype.getModes = function () {
12968 return this.modes.slice();
12969 };
12970
12971 /**
12972 * Emit a resize event if the size has changed.
12973 *
12974 * @private
12975 * @chainable
12976 */
12977 OO.ui.ActionWidget.prototype.propagateResize = function () {
12978 var width, height;
12979
12980 if ( this.isElementAttached() ) {
12981 width = this.$element.width();
12982 height = this.$element.height();
12983
12984 if ( width !== this.width || height !== this.height ) {
12985 this.width = width;
12986 this.height = height;
12987 this.emit( 'resize' );
12988 }
12989 }
12990
12991 return this;
12992 };
12993
12994 /**
12995 * @inheritdoc
12996 */
12997 OO.ui.ActionWidget.prototype.setIcon = function () {
12998 // Mixin method
12999 OO.ui.mixin.IconElement.prototype.setIcon.apply( this, arguments );
13000 this.propagateResize();
13001
13002 return this;
13003 };
13004
13005 /**
13006 * @inheritdoc
13007 */
13008 OO.ui.ActionWidget.prototype.setLabel = function () {
13009 // Mixin method
13010 OO.ui.mixin.LabelElement.prototype.setLabel.apply( this, arguments );
13011 this.propagateResize();
13012
13013 return this;
13014 };
13015
13016 /**
13017 * @inheritdoc
13018 */
13019 OO.ui.ActionWidget.prototype.setFlags = function () {
13020 // Mixin method
13021 OO.ui.mixin.FlaggedElement.prototype.setFlags.apply( this, arguments );
13022 this.propagateResize();
13023
13024 return this;
13025 };
13026
13027 /**
13028 * @inheritdoc
13029 */
13030 OO.ui.ActionWidget.prototype.clearFlags = function () {
13031 // Mixin method
13032 OO.ui.mixin.FlaggedElement.prototype.clearFlags.apply( this, arguments );
13033 this.propagateResize();
13034
13035 return this;
13036 };
13037
13038 /**
13039 * Toggle the visibility of the action button.
13040 *
13041 * @param {boolean} [show] Show button, omit to toggle visibility
13042 * @chainable
13043 */
13044 OO.ui.ActionWidget.prototype.toggle = function () {
13045 // Parent method
13046 OO.ui.ActionWidget.parent.prototype.toggle.apply( this, arguments );
13047 this.propagateResize();
13048
13049 return this;
13050 };
13051
13052 /**
13053 * PopupButtonWidgets toggle the visibility of a contained {@link OO.ui.PopupWidget PopupWidget},
13054 * which is used to display additional information or options.
13055 *
13056 * @example
13057 * // Example of a popup button.
13058 * var popupButton = new OO.ui.PopupButtonWidget( {
13059 * label: 'Popup button with options',
13060 * icon: 'menu',
13061 * popup: {
13062 * $content: $( '<p>Additional options here.</p>' ),
13063 * padded: true,
13064 * align: 'force-left'
13065 * }
13066 * } );
13067 * // Append the button to the DOM.
13068 * $( 'body' ).append( popupButton.$element );
13069 *
13070 * @class
13071 * @extends OO.ui.ButtonWidget
13072 * @mixins OO.ui.mixin.PopupElement
13073 *
13074 * @constructor
13075 * @param {Object} [config] Configuration options
13076 */
13077 OO.ui.PopupButtonWidget = function OoUiPopupButtonWidget( config ) {
13078 // Parent constructor
13079 OO.ui.PopupButtonWidget.parent.call( this, config );
13080
13081 // Mixin constructors
13082 OO.ui.mixin.PopupElement.call( this, config );
13083
13084 // Events
13085 this.connect( this, { click: 'onAction' } );
13086
13087 // Initialization
13088 this.$element
13089 .addClass( 'oo-ui-popupButtonWidget' )
13090 .attr( 'aria-haspopup', 'true' )
13091 .append( this.popup.$element );
13092 };
13093
13094 /* Setup */
13095
13096 OO.inheritClass( OO.ui.PopupButtonWidget, OO.ui.ButtonWidget );
13097 OO.mixinClass( OO.ui.PopupButtonWidget, OO.ui.mixin.PopupElement );
13098
13099 /* Methods */
13100
13101 /**
13102 * Handle the button action being triggered.
13103 *
13104 * @private
13105 */
13106 OO.ui.PopupButtonWidget.prototype.onAction = function () {
13107 this.popup.toggle();
13108 };
13109
13110 /**
13111 * ToggleButtons are buttons that have a state (‘on’ or ‘off’) that is represented by a
13112 * Boolean value. Like other {@link OO.ui.ButtonWidget buttons}, toggle buttons can be
13113 * configured with {@link OO.ui.mixin.IconElement icons}, {@link OO.ui.mixin.IndicatorElement indicators},
13114 * {@link OO.ui.mixin.TitledElement titles}, {@link OO.ui.mixin.FlaggedElement styling flags},
13115 * and {@link OO.ui.mixin.LabelElement labels}. Please see
13116 * the [OOjs UI documentation][1] on MediaWiki for more information.
13117 *
13118 * @example
13119 * // Toggle buttons in the 'off' and 'on' state.
13120 * var toggleButton1 = new OO.ui.ToggleButtonWidget( {
13121 * label: 'Toggle Button off'
13122 * } );
13123 * var toggleButton2 = new OO.ui.ToggleButtonWidget( {
13124 * label: 'Toggle Button on',
13125 * value: true
13126 * } );
13127 * // Append the buttons to the DOM.
13128 * $( 'body' ).append( toggleButton1.$element, toggleButton2.$element );
13129 *
13130 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#Toggle_buttons
13131 *
13132 * @class
13133 * @extends OO.ui.ToggleWidget
13134 * @mixins OO.ui.mixin.ButtonElement
13135 * @mixins OO.ui.mixin.IconElement
13136 * @mixins OO.ui.mixin.IndicatorElement
13137 * @mixins OO.ui.mixin.LabelElement
13138 * @mixins OO.ui.mixin.TitledElement
13139 * @mixins OO.ui.mixin.FlaggedElement
13140 * @mixins OO.ui.mixin.TabIndexedElement
13141 *
13142 * @constructor
13143 * @param {Object} [config] Configuration options
13144 * @cfg {boolean} [value=false] The toggle button’s initial on/off
13145 * state. By default, the button is in the 'off' state.
13146 */
13147 OO.ui.ToggleButtonWidget = function OoUiToggleButtonWidget( config ) {
13148 // Configuration initialization
13149 config = config || {};
13150
13151 // Parent constructor
13152 OO.ui.ToggleButtonWidget.parent.call( this, config );
13153
13154 // Mixin constructors
13155 OO.ui.mixin.ButtonElement.call( this, config );
13156 OO.ui.mixin.IconElement.call( this, config );
13157 OO.ui.mixin.IndicatorElement.call( this, config );
13158 OO.ui.mixin.LabelElement.call( this, config );
13159 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$button } ) );
13160 OO.ui.mixin.FlaggedElement.call( this, config );
13161 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$button } ) );
13162
13163 // Events
13164 this.connect( this, { click: 'onAction' } );
13165
13166 // Initialization
13167 this.$button.append( this.$icon, this.$label, this.$indicator );
13168 this.$element
13169 .addClass( 'oo-ui-toggleButtonWidget' )
13170 .append( this.$button );
13171 };
13172
13173 /* Setup */
13174
13175 OO.inheritClass( OO.ui.ToggleButtonWidget, OO.ui.ToggleWidget );
13176 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.ButtonElement );
13177 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.IconElement );
13178 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.IndicatorElement );
13179 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.LabelElement );
13180 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.TitledElement );
13181 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.FlaggedElement );
13182 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.TabIndexedElement );
13183
13184 /* Methods */
13185
13186 /**
13187 * Handle the button action being triggered.
13188 *
13189 * @private
13190 */
13191 OO.ui.ToggleButtonWidget.prototype.onAction = function () {
13192 this.setValue( !this.value );
13193 };
13194
13195 /**
13196 * @inheritdoc
13197 */
13198 OO.ui.ToggleButtonWidget.prototype.setValue = function ( value ) {
13199 value = !!value;
13200 if ( value !== this.value ) {
13201 // Might be called from parent constructor before ButtonElement constructor
13202 if ( this.$button ) {
13203 this.$button.attr( 'aria-pressed', value.toString() );
13204 }
13205 this.setActive( value );
13206 }
13207
13208 // Parent method
13209 OO.ui.ToggleButtonWidget.parent.prototype.setValue.call( this, value );
13210
13211 return this;
13212 };
13213
13214 /**
13215 * @inheritdoc
13216 */
13217 OO.ui.ToggleButtonWidget.prototype.setButtonElement = function ( $button ) {
13218 if ( this.$button ) {
13219 this.$button.removeAttr( 'aria-pressed' );
13220 }
13221 OO.ui.mixin.ButtonElement.prototype.setButtonElement.call( this, $button );
13222 this.$button.attr( 'aria-pressed', this.value.toString() );
13223 };
13224
13225 /**
13226 * CapsuleMultiSelectWidgets are something like a {@link OO.ui.ComboBoxWidget combo box widget}
13227 * that allows for selecting multiple values.
13228 *
13229 * For more information about menus and options, please see the [OOjs UI documentation on MediaWiki][1].
13230 *
13231 * @example
13232 * // Example: A CapsuleMultiSelectWidget.
13233 * var capsule = new OO.ui.CapsuleMultiSelectWidget( {
13234 * label: 'CapsuleMultiSelectWidget',
13235 * selected: [ 'Option 1', 'Option 3' ],
13236 * menu: {
13237 * items: [
13238 * new OO.ui.MenuOptionWidget( {
13239 * data: 'Option 1',
13240 * label: 'Option One'
13241 * } ),
13242 * new OO.ui.MenuOptionWidget( {
13243 * data: 'Option 2',
13244 * label: 'Option Two'
13245 * } ),
13246 * new OO.ui.MenuOptionWidget( {
13247 * data: 'Option 3',
13248 * label: 'Option Three'
13249 * } ),
13250 * new OO.ui.MenuOptionWidget( {
13251 * data: 'Option 4',
13252 * label: 'Option Four'
13253 * } ),
13254 * new OO.ui.MenuOptionWidget( {
13255 * data: 'Option 5',
13256 * label: 'Option Five'
13257 * } )
13258 * ]
13259 * }
13260 * } );
13261 * $( 'body' ).append( capsule.$element );
13262 *
13263 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
13264 *
13265 * @class
13266 * @extends OO.ui.Widget
13267 * @mixins OO.ui.mixin.TabIndexedElement
13268 * @mixins OO.ui.mixin.GroupElement
13269 *
13270 * @constructor
13271 * @param {Object} [config] Configuration options
13272 * @cfg {boolean} [allowArbitrary=false] Allow data items to be added even if not present in the menu.
13273 * @cfg {Object} [menu] Configuration options to pass to the {@link OO.ui.MenuSelectWidget menu select widget}.
13274 * @cfg {Object} [popup] Configuration options to pass to the {@link OO.ui.PopupWidget popup widget}.
13275 * If specified, this popup will be shown instead of the menu (but the menu
13276 * will still be used for item labels and allowArbitrary=false). The widgets
13277 * in the popup should use this.addItemsFromData() or this.addItems() as necessary.
13278 * @cfg {jQuery} [$overlay] Render the menu or popup into a separate layer.
13279 * This configuration is useful in cases where the expanded menu is larger than
13280 * its containing `<div>`. The specified overlay layer is usually on top of
13281 * the containing `<div>` and has a larger area. By default, the menu uses
13282 * relative positioning.
13283 */
13284 OO.ui.CapsuleMultiSelectWidget = function OoUiCapsuleMultiSelectWidget( config ) {
13285 var $tabFocus;
13286
13287 // Configuration initialization
13288 config = config || {};
13289
13290 // Parent constructor
13291 OO.ui.CapsuleMultiSelectWidget.parent.call( this, config );
13292
13293 // Properties (must be set before mixin constructor calls)
13294 this.$input = config.popup ? null : $( '<input>' );
13295 this.$handle = $( '<div>' );
13296
13297 // Mixin constructors
13298 OO.ui.mixin.GroupElement.call( this, config );
13299 if ( config.popup ) {
13300 config.popup = $.extend( {}, config.popup, {
13301 align: 'forwards',
13302 anchor: false
13303 } );
13304 OO.ui.mixin.PopupElement.call( this, config );
13305 $tabFocus = $( '<span>' );
13306 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: $tabFocus } ) );
13307 } else {
13308 this.popup = null;
13309 $tabFocus = null;
13310 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$input } ) );
13311 }
13312 OO.ui.mixin.IndicatorElement.call( this, config );
13313 OO.ui.mixin.IconElement.call( this, config );
13314
13315 // Properties
13316 this.allowArbitrary = !!config.allowArbitrary;
13317 this.$overlay = config.$overlay || this.$element;
13318 this.menu = new OO.ui.FloatingMenuSelectWidget( $.extend(
13319 {
13320 widget: this,
13321 $input: this.$input,
13322 $container: this.$element,
13323 filterFromInput: true,
13324 disabled: this.isDisabled()
13325 },
13326 config.menu
13327 ) );
13328
13329 // Events
13330 if ( this.popup ) {
13331 $tabFocus.on( {
13332 focus: this.onFocusForPopup.bind( this )
13333 } );
13334 this.popup.$element.on( 'focusout', this.onPopupFocusOut.bind( this ) );
13335 if ( this.popup.$autoCloseIgnore ) {
13336 this.popup.$autoCloseIgnore.on( 'focusout', this.onPopupFocusOut.bind( this ) );
13337 }
13338 this.popup.connect( this, {
13339 toggle: function ( visible ) {
13340 $tabFocus.toggle( !visible );
13341 }
13342 } );
13343 } else {
13344 this.$input.on( {
13345 focus: this.onInputFocus.bind( this ),
13346 blur: this.onInputBlur.bind( this ),
13347 'propertychange change click mouseup keydown keyup input cut paste select': this.onInputChange.bind( this ),
13348 keydown: this.onKeyDown.bind( this ),
13349 keypress: this.onKeyPress.bind( this )
13350 } );
13351 }
13352 this.menu.connect( this, {
13353 choose: 'onMenuChoose',
13354 add: 'onMenuItemsChange',
13355 remove: 'onMenuItemsChange'
13356 } );
13357 this.$handle.on( {
13358 click: this.onClick.bind( this )
13359 } );
13360
13361 // Initialization
13362 if ( this.$input ) {
13363 this.$input.prop( 'disabled', this.isDisabled() );
13364 this.$input.attr( {
13365 role: 'combobox',
13366 'aria-autocomplete': 'list'
13367 } );
13368 this.$input.width( '1em' );
13369 }
13370 if ( config.data ) {
13371 this.setItemsFromData( config.data );
13372 }
13373 this.$group.addClass( 'oo-ui-capsuleMultiSelectWidget-group' );
13374 this.$handle.addClass( 'oo-ui-capsuleMultiSelectWidget-handle' )
13375 .append( this.$indicator, this.$icon, this.$group );
13376 this.$element.addClass( 'oo-ui-capsuleMultiSelectWidget' )
13377 .append( this.$handle );
13378 if ( this.popup ) {
13379 this.$handle.append( $tabFocus );
13380 this.$overlay.append( this.popup.$element );
13381 } else {
13382 this.$handle.append( this.$input );
13383 this.$overlay.append( this.menu.$element );
13384 }
13385 this.onMenuItemsChange();
13386 };
13387
13388 /* Setup */
13389
13390 OO.inheritClass( OO.ui.CapsuleMultiSelectWidget, OO.ui.Widget );
13391 OO.mixinClass( OO.ui.CapsuleMultiSelectWidget, OO.ui.mixin.GroupElement );
13392 OO.mixinClass( OO.ui.CapsuleMultiSelectWidget, OO.ui.mixin.PopupElement );
13393 OO.mixinClass( OO.ui.CapsuleMultiSelectWidget, OO.ui.mixin.TabIndexedElement );
13394 OO.mixinClass( OO.ui.CapsuleMultiSelectWidget, OO.ui.mixin.IndicatorElement );
13395 OO.mixinClass( OO.ui.CapsuleMultiSelectWidget, OO.ui.mixin.IconElement );
13396
13397 /* Events */
13398
13399 /**
13400 * @event change
13401 *
13402 * A change event is emitted when the set of selected items changes.
13403 *
13404 * @param {Mixed[]} datas Data of the now-selected items
13405 */
13406
13407 /* Methods */
13408
13409 /**
13410 * Construct a OO.ui.CapsuleItemWidget (or a subclass thereof) from given label and data.
13411 *
13412 * @protected
13413 * @param {Mixed} data Custom data of any type.
13414 * @param {string} label The label text.
13415 * @return {OO.ui.CapsuleItemWidget}
13416 */
13417 OO.ui.CapsuleMultiSelectWidget.prototype.createItemWidget = function ( data, label ) {
13418 return new OO.ui.CapsuleItemWidget( { data: data, label: label } );
13419 };
13420
13421 /**
13422 * Get the data of the items in the capsule
13423 * @return {Mixed[]}
13424 */
13425 OO.ui.CapsuleMultiSelectWidget.prototype.getItemsData = function () {
13426 return $.map( this.getItems(), function ( e ) { return e.data; } );
13427 };
13428
13429 /**
13430 * Set the items in the capsule by providing data
13431 * @chainable
13432 * @param {Mixed[]} datas
13433 * @return {OO.ui.CapsuleMultiSelectWidget}
13434 */
13435 OO.ui.CapsuleMultiSelectWidget.prototype.setItemsFromData = function ( datas ) {
13436 var widget = this,
13437 menu = this.menu,
13438 items = this.getItems();
13439
13440 $.each( datas, function ( i, data ) {
13441 var j, label,
13442 item = menu.getItemFromData( data );
13443
13444 if ( item ) {
13445 label = item.label;
13446 } else if ( widget.allowArbitrary ) {
13447 label = String( data );
13448 } else {
13449 return;
13450 }
13451
13452 item = null;
13453 for ( j = 0; j < items.length; j++ ) {
13454 if ( items[ j ].data === data && items[ j ].label === label ) {
13455 item = items[ j ];
13456 items.splice( j, 1 );
13457 break;
13458 }
13459 }
13460 if ( !item ) {
13461 item = widget.createItemWidget( data, label );
13462 }
13463 widget.addItems( [ item ], i );
13464 } );
13465
13466 if ( items.length ) {
13467 widget.removeItems( items );
13468 }
13469
13470 return this;
13471 };
13472
13473 /**
13474 * Add items to the capsule by providing their data
13475 * @chainable
13476 * @param {Mixed[]} datas
13477 * @return {OO.ui.CapsuleMultiSelectWidget}
13478 */
13479 OO.ui.CapsuleMultiSelectWidget.prototype.addItemsFromData = function ( datas ) {
13480 var widget = this,
13481 menu = this.menu,
13482 items = [];
13483
13484 $.each( datas, function ( i, data ) {
13485 var item;
13486
13487 if ( !widget.getItemFromData( data ) ) {
13488 item = menu.getItemFromData( data );
13489 if ( item ) {
13490 items.push( widget.createItemWidget( data, item.label ) );
13491 } else if ( widget.allowArbitrary ) {
13492 items.push( widget.createItemWidget( data, String( data ) ) );
13493 }
13494 }
13495 } );
13496
13497 if ( items.length ) {
13498 this.addItems( items );
13499 }
13500
13501 return this;
13502 };
13503
13504 /**
13505 * Remove items by data
13506 * @chainable
13507 * @param {Mixed[]} datas
13508 * @return {OO.ui.CapsuleMultiSelectWidget}
13509 */
13510 OO.ui.CapsuleMultiSelectWidget.prototype.removeItemsFromData = function ( datas ) {
13511 var widget = this,
13512 items = [];
13513
13514 $.each( datas, function ( i, data ) {
13515 var item = widget.getItemFromData( data );
13516 if ( item ) {
13517 items.push( item );
13518 }
13519 } );
13520
13521 if ( items.length ) {
13522 this.removeItems( items );
13523 }
13524
13525 return this;
13526 };
13527
13528 /**
13529 * @inheritdoc
13530 */
13531 OO.ui.CapsuleMultiSelectWidget.prototype.addItems = function ( items ) {
13532 var same, i, l,
13533 oldItems = this.items.slice();
13534
13535 OO.ui.mixin.GroupElement.prototype.addItems.call( this, items );
13536
13537 if ( this.items.length !== oldItems.length ) {
13538 same = false;
13539 } else {
13540 same = true;
13541 for ( i = 0, l = oldItems.length; same && i < l; i++ ) {
13542 same = same && this.items[ i ] === oldItems[ i ];
13543 }
13544 }
13545 if ( !same ) {
13546 this.emit( 'change', this.getItemsData() );
13547 }
13548
13549 return this;
13550 };
13551
13552 /**
13553 * @inheritdoc
13554 */
13555 OO.ui.CapsuleMultiSelectWidget.prototype.removeItems = function ( items ) {
13556 var same, i, l,
13557 oldItems = this.items.slice();
13558
13559 OO.ui.mixin.GroupElement.prototype.removeItems.call( this, items );
13560
13561 if ( this.items.length !== oldItems.length ) {
13562 same = false;
13563 } else {
13564 same = true;
13565 for ( i = 0, l = oldItems.length; same && i < l; i++ ) {
13566 same = same && this.items[ i ] === oldItems[ i ];
13567 }
13568 }
13569 if ( !same ) {
13570 this.emit( 'change', this.getItemsData() );
13571 }
13572
13573 return this;
13574 };
13575
13576 /**
13577 * @inheritdoc
13578 */
13579 OO.ui.CapsuleMultiSelectWidget.prototype.clearItems = function () {
13580 if ( this.items.length ) {
13581 OO.ui.mixin.GroupElement.prototype.clearItems.call( this );
13582 this.emit( 'change', this.getItemsData() );
13583 }
13584 return this;
13585 };
13586
13587 /**
13588 * Get the capsule widget's menu.
13589 * @return {OO.ui.MenuSelectWidget} Menu widget
13590 */
13591 OO.ui.CapsuleMultiSelectWidget.prototype.getMenu = function () {
13592 return this.menu;
13593 };
13594
13595 /**
13596 * Handle focus events
13597 *
13598 * @private
13599 * @param {jQuery.Event} event
13600 */
13601 OO.ui.CapsuleMultiSelectWidget.prototype.onInputFocus = function () {
13602 if ( !this.isDisabled() ) {
13603 this.menu.toggle( true );
13604 }
13605 };
13606
13607 /**
13608 * Handle blur events
13609 *
13610 * @private
13611 * @param {jQuery.Event} event
13612 */
13613 OO.ui.CapsuleMultiSelectWidget.prototype.onInputBlur = function () {
13614 if ( this.allowArbitrary && this.$input.val().trim() !== '' ) {
13615 this.addItemsFromData( [ this.$input.val() ] );
13616 }
13617 this.clearInput();
13618 };
13619
13620 /**
13621 * Handle focus events
13622 *
13623 * @private
13624 * @param {jQuery.Event} event
13625 */
13626 OO.ui.CapsuleMultiSelectWidget.prototype.onFocusForPopup = function () {
13627 if ( !this.isDisabled() ) {
13628 this.popup.setSize( this.$handle.width() );
13629 this.popup.toggle( true );
13630 this.popup.$element.find( '*' )
13631 .filter( function () { return OO.ui.isFocusableElement( $( this ), true ); } )
13632 .first()
13633 .focus();
13634 }
13635 };
13636
13637 /**
13638 * Handles popup focus out events.
13639 *
13640 * @private
13641 * @param {Event} e Focus out event
13642 */
13643 OO.ui.CapsuleMultiSelectWidget.prototype.onPopupFocusOut = function () {
13644 var widget = this.popup;
13645
13646 setTimeout( function () {
13647 if (
13648 widget.isVisible() &&
13649 !OO.ui.contains( widget.$element[ 0 ], document.activeElement, true ) &&
13650 ( !widget.$autoCloseIgnore || !widget.$autoCloseIgnore.has( document.activeElement ).length )
13651 ) {
13652 widget.toggle( false );
13653 }
13654 } );
13655 };
13656
13657 /**
13658 * Handle mouse click events.
13659 *
13660 * @private
13661 * @param {jQuery.Event} e Mouse click event
13662 */
13663 OO.ui.CapsuleMultiSelectWidget.prototype.onClick = function ( e ) {
13664 if ( e.which === 1 ) {
13665 this.focus();
13666 return false;
13667 }
13668 };
13669
13670 /**
13671 * Handle key press events.
13672 *
13673 * @private
13674 * @param {jQuery.Event} e Key press event
13675 */
13676 OO.ui.CapsuleMultiSelectWidget.prototype.onKeyPress = function ( e ) {
13677 var item;
13678
13679 if ( !this.isDisabled() ) {
13680 if ( e.which === OO.ui.Keys.ESCAPE ) {
13681 this.clearInput();
13682 return false;
13683 }
13684
13685 if ( !this.popup ) {
13686 this.menu.toggle( true );
13687 if ( e.which === OO.ui.Keys.ENTER ) {
13688 item = this.menu.getItemFromLabel( this.$input.val(), true );
13689 if ( item ) {
13690 this.addItemsFromData( [ item.data ] );
13691 this.clearInput();
13692 } else if ( this.allowArbitrary && this.$input.val().trim() !== '' ) {
13693 this.addItemsFromData( [ this.$input.val() ] );
13694 this.clearInput();
13695 }
13696 return false;
13697 }
13698
13699 // Make sure the input gets resized.
13700 setTimeout( this.onInputChange.bind( this ), 0 );
13701 }
13702 }
13703 };
13704
13705 /**
13706 * Handle key down events.
13707 *
13708 * @private
13709 * @param {jQuery.Event} e Key down event
13710 */
13711 OO.ui.CapsuleMultiSelectWidget.prototype.onKeyDown = function ( e ) {
13712 if ( !this.isDisabled() ) {
13713 // 'keypress' event is not triggered for Backspace
13714 if ( e.keyCode === OO.ui.Keys.BACKSPACE && this.$input.val() === '' ) {
13715 if ( this.items.length ) {
13716 this.removeItems( this.items.slice( -1 ) );
13717 }
13718 return false;
13719 }
13720 }
13721 };
13722
13723 /**
13724 * Handle input change events.
13725 *
13726 * @private
13727 * @param {jQuery.Event} e Event of some sort
13728 */
13729 OO.ui.CapsuleMultiSelectWidget.prototype.onInputChange = function () {
13730 if ( !this.isDisabled() ) {
13731 this.$input.width( this.$input.val().length + 'em' );
13732 }
13733 };
13734
13735 /**
13736 * Handle menu choose events.
13737 *
13738 * @private
13739 * @param {OO.ui.OptionWidget} item Chosen item
13740 */
13741 OO.ui.CapsuleMultiSelectWidget.prototype.onMenuChoose = function ( item ) {
13742 if ( item && item.isVisible() ) {
13743 this.addItemsFromData( [ item.getData() ] );
13744 this.clearInput();
13745 }
13746 };
13747
13748 /**
13749 * Handle menu item change events.
13750 *
13751 * @private
13752 */
13753 OO.ui.CapsuleMultiSelectWidget.prototype.onMenuItemsChange = function () {
13754 this.setItemsFromData( this.getItemsData() );
13755 this.$element.toggleClass( 'oo-ui-capsuleMultiSelectWidget-empty', this.menu.isEmpty() );
13756 };
13757
13758 /**
13759 * Clear the input field
13760 * @private
13761 */
13762 OO.ui.CapsuleMultiSelectWidget.prototype.clearInput = function () {
13763 if ( this.$input ) {
13764 this.$input.val( '' );
13765 this.$input.width( '1em' );
13766 }
13767 if ( this.popup ) {
13768 this.popup.toggle( false );
13769 }
13770 this.menu.toggle( false );
13771 this.menu.selectItem();
13772 this.menu.highlightItem();
13773 };
13774
13775 /**
13776 * @inheritdoc
13777 */
13778 OO.ui.CapsuleMultiSelectWidget.prototype.setDisabled = function ( disabled ) {
13779 var i, len;
13780
13781 // Parent method
13782 OO.ui.CapsuleMultiSelectWidget.parent.prototype.setDisabled.call( this, disabled );
13783
13784 if ( this.$input ) {
13785 this.$input.prop( 'disabled', this.isDisabled() );
13786 }
13787 if ( this.menu ) {
13788 this.menu.setDisabled( this.isDisabled() );
13789 }
13790 if ( this.popup ) {
13791 this.popup.setDisabled( this.isDisabled() );
13792 }
13793
13794 if ( this.items ) {
13795 for ( i = 0, len = this.items.length; i < len; i++ ) {
13796 this.items[ i ].updateDisabled();
13797 }
13798 }
13799
13800 return this;
13801 };
13802
13803 /**
13804 * Focus the widget
13805 * @chainable
13806 * @return {OO.ui.CapsuleMultiSelectWidget}
13807 */
13808 OO.ui.CapsuleMultiSelectWidget.prototype.focus = function () {
13809 if ( !this.isDisabled() ) {
13810 if ( this.popup ) {
13811 this.popup.setSize( this.$handle.width() );
13812 this.popup.toggle( true );
13813 this.popup.$element.find( '*' )
13814 .filter( function () { return OO.ui.isFocusableElement( $( this ), true ); } )
13815 .first()
13816 .focus();
13817 } else {
13818 this.menu.toggle( true );
13819 this.$input.focus();
13820 }
13821 }
13822 return this;
13823 };
13824
13825 /**
13826 * CapsuleItemWidgets are used within a {@link OO.ui.CapsuleMultiSelectWidget
13827 * CapsuleMultiSelectWidget} to display the selected items.
13828 *
13829 * @class
13830 * @extends OO.ui.Widget
13831 * @mixins OO.ui.mixin.ItemWidget
13832 * @mixins OO.ui.mixin.IndicatorElement
13833 * @mixins OO.ui.mixin.LabelElement
13834 * @mixins OO.ui.mixin.FlaggedElement
13835 * @mixins OO.ui.mixin.TabIndexedElement
13836 *
13837 * @constructor
13838 * @param {Object} [config] Configuration options
13839 */
13840 OO.ui.CapsuleItemWidget = function OoUiCapsuleItemWidget( config ) {
13841 // Configuration initialization
13842 config = config || {};
13843
13844 // Parent constructor
13845 OO.ui.CapsuleItemWidget.parent.call( this, config );
13846
13847 // Properties (must be set before mixin constructor calls)
13848 this.$indicator = $( '<span>' );
13849
13850 // Mixin constructors
13851 OO.ui.mixin.ItemWidget.call( this );
13852 OO.ui.mixin.IndicatorElement.call( this, $.extend( {}, config, { $indicator: this.$indicator, indicator: 'clear' } ) );
13853 OO.ui.mixin.LabelElement.call( this, config );
13854 OO.ui.mixin.FlaggedElement.call( this, config );
13855 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$indicator } ) );
13856
13857 // Events
13858 this.$indicator.on( {
13859 keydown: this.onCloseKeyDown.bind( this ),
13860 click: this.onCloseClick.bind( this )
13861 } );
13862
13863 // Initialization
13864 this.$element
13865 .addClass( 'oo-ui-capsuleItemWidget' )
13866 .append( this.$indicator, this.$label );
13867 };
13868
13869 /* Setup */
13870
13871 OO.inheritClass( OO.ui.CapsuleItemWidget, OO.ui.Widget );
13872 OO.mixinClass( OO.ui.CapsuleItemWidget, OO.ui.mixin.ItemWidget );
13873 OO.mixinClass( OO.ui.CapsuleItemWidget, OO.ui.mixin.IndicatorElement );
13874 OO.mixinClass( OO.ui.CapsuleItemWidget, OO.ui.mixin.LabelElement );
13875 OO.mixinClass( OO.ui.CapsuleItemWidget, OO.ui.mixin.FlaggedElement );
13876 OO.mixinClass( OO.ui.CapsuleItemWidget, OO.ui.mixin.TabIndexedElement );
13877
13878 /* Methods */
13879
13880 /**
13881 * Handle close icon clicks
13882 * @param {jQuery.Event} event
13883 */
13884 OO.ui.CapsuleItemWidget.prototype.onCloseClick = function () {
13885 var element = this.getElementGroup();
13886
13887 if ( !this.isDisabled() && element && $.isFunction( element.removeItems ) ) {
13888 element.removeItems( [ this ] );
13889 element.focus();
13890 }
13891 };
13892
13893 /**
13894 * Handle close keyboard events
13895 * @param {jQuery.Event} event Key down event
13896 */
13897 OO.ui.CapsuleItemWidget.prototype.onCloseKeyDown = function ( e ) {
13898 if ( !this.isDisabled() && $.isFunction( this.getElementGroup().removeItems ) ) {
13899 switch ( e.which ) {
13900 case OO.ui.Keys.ENTER:
13901 case OO.ui.Keys.BACKSPACE:
13902 case OO.ui.Keys.SPACE:
13903 this.getElementGroup().removeItems( [ this ] );
13904 return false;
13905 }
13906 }
13907 };
13908
13909 /**
13910 * DropdownWidgets are not menus themselves, rather they contain a menu of options created with
13911 * OO.ui.MenuOptionWidget. The DropdownWidget takes care of opening and displaying the menu so that
13912 * users can interact with it.
13913 *
13914 * If you want to use this within a HTML form, such as a OO.ui.FormLayout, use
13915 * OO.ui.DropdownInputWidget instead.
13916 *
13917 * @example
13918 * // Example: A DropdownWidget with a menu that contains three options
13919 * var dropDown = new OO.ui.DropdownWidget( {
13920 * label: 'Dropdown menu: Select a menu option',
13921 * menu: {
13922 * items: [
13923 * new OO.ui.MenuOptionWidget( {
13924 * data: 'a',
13925 * label: 'First'
13926 * } ),
13927 * new OO.ui.MenuOptionWidget( {
13928 * data: 'b',
13929 * label: 'Second'
13930 * } ),
13931 * new OO.ui.MenuOptionWidget( {
13932 * data: 'c',
13933 * label: 'Third'
13934 * } )
13935 * ]
13936 * }
13937 * } );
13938 *
13939 * $( 'body' ).append( dropDown.$element );
13940 *
13941 * dropDown.getMenu().selectItemByData( 'b' );
13942 *
13943 * dropDown.getMenu().getSelectedItem().getData(); // returns 'b'
13944 *
13945 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
13946 *
13947 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
13948 *
13949 * @class
13950 * @extends OO.ui.Widget
13951 * @mixins OO.ui.mixin.IconElement
13952 * @mixins OO.ui.mixin.IndicatorElement
13953 * @mixins OO.ui.mixin.LabelElement
13954 * @mixins OO.ui.mixin.TitledElement
13955 * @mixins OO.ui.mixin.TabIndexedElement
13956 *
13957 * @constructor
13958 * @param {Object} [config] Configuration options
13959 * @cfg {Object} [menu] Configuration options to pass to {@link OO.ui.FloatingMenuSelectWidget menu select widget}
13960 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
13961 * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
13962 * containing `<div>` and has a larger area. By default, the menu uses relative positioning.
13963 */
13964 OO.ui.DropdownWidget = function OoUiDropdownWidget( config ) {
13965 // Configuration initialization
13966 config = $.extend( { indicator: 'down' }, config );
13967
13968 // Parent constructor
13969 OO.ui.DropdownWidget.parent.call( this, config );
13970
13971 // Properties (must be set before TabIndexedElement constructor call)
13972 this.$handle = this.$( '<span>' );
13973 this.$overlay = config.$overlay || this.$element;
13974
13975 // Mixin constructors
13976 OO.ui.mixin.IconElement.call( this, config );
13977 OO.ui.mixin.IndicatorElement.call( this, config );
13978 OO.ui.mixin.LabelElement.call( this, config );
13979 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$label } ) );
13980 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$handle } ) );
13981
13982 // Properties
13983 this.menu = new OO.ui.FloatingMenuSelectWidget( $.extend( {
13984 widget: this,
13985 $container: this.$element
13986 }, config.menu ) );
13987
13988 // Events
13989 this.$handle.on( {
13990 click: this.onClick.bind( this ),
13991 keypress: this.onKeyPress.bind( this )
13992 } );
13993 this.menu.connect( this, { select: 'onMenuSelect' } );
13994
13995 // Initialization
13996 this.$handle
13997 .addClass( 'oo-ui-dropdownWidget-handle' )
13998 .append( this.$icon, this.$label, this.$indicator );
13999 this.$element
14000 .addClass( 'oo-ui-dropdownWidget' )
14001 .append( this.$handle );
14002 this.$overlay.append( this.menu.$element );
14003 };
14004
14005 /* Setup */
14006
14007 OO.inheritClass( OO.ui.DropdownWidget, OO.ui.Widget );
14008 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.IconElement );
14009 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.IndicatorElement );
14010 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.LabelElement );
14011 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.TitledElement );
14012 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.TabIndexedElement );
14013
14014 /* Methods */
14015
14016 /**
14017 * Get the menu.
14018 *
14019 * @return {OO.ui.MenuSelectWidget} Menu of widget
14020 */
14021 OO.ui.DropdownWidget.prototype.getMenu = function () {
14022 return this.menu;
14023 };
14024
14025 /**
14026 * Handles menu select events.
14027 *
14028 * @private
14029 * @param {OO.ui.MenuOptionWidget} item Selected menu item
14030 */
14031 OO.ui.DropdownWidget.prototype.onMenuSelect = function ( item ) {
14032 var selectedLabel;
14033
14034 if ( !item ) {
14035 this.setLabel( null );
14036 return;
14037 }
14038
14039 selectedLabel = item.getLabel();
14040
14041 // If the label is a DOM element, clone it, because setLabel will append() it
14042 if ( selectedLabel instanceof jQuery ) {
14043 selectedLabel = selectedLabel.clone();
14044 }
14045
14046 this.setLabel( selectedLabel );
14047 };
14048
14049 /**
14050 * Handle mouse click events.
14051 *
14052 * @private
14053 * @param {jQuery.Event} e Mouse click event
14054 */
14055 OO.ui.DropdownWidget.prototype.onClick = function ( e ) {
14056 if ( !this.isDisabled() && e.which === 1 ) {
14057 this.menu.toggle();
14058 }
14059 return false;
14060 };
14061
14062 /**
14063 * Handle key press events.
14064 *
14065 * @private
14066 * @param {jQuery.Event} e Key press event
14067 */
14068 OO.ui.DropdownWidget.prototype.onKeyPress = function ( e ) {
14069 if ( !this.isDisabled() &&
14070 ( ( e.which === OO.ui.Keys.SPACE && !this.menu.isVisible() ) || e.which === OO.ui.Keys.ENTER )
14071 ) {
14072 this.menu.toggle();
14073 return false;
14074 }
14075 };
14076
14077 /**
14078 * SelectFileWidgets allow for selecting files, using the HTML5 File API. These
14079 * widgets can be configured with {@link OO.ui.mixin.IconElement icons} and {@link
14080 * OO.ui.mixin.IndicatorElement indicators}.
14081 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
14082 *
14083 * @example
14084 * // Example of a file select widget
14085 * var selectFile = new OO.ui.SelectFileWidget();
14086 * $( 'body' ).append( selectFile.$element );
14087 *
14088 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets
14089 *
14090 * @class
14091 * @extends OO.ui.Widget
14092 * @mixins OO.ui.mixin.IconElement
14093 * @mixins OO.ui.mixin.IndicatorElement
14094 * @mixins OO.ui.mixin.PendingElement
14095 * @mixins OO.ui.mixin.LabelElement
14096 *
14097 * @constructor
14098 * @param {Object} [config] Configuration options
14099 * @cfg {string[]|null} [accept=null] MIME types to accept. null accepts all types.
14100 * @cfg {string} [placeholder] Text to display when no file is selected.
14101 * @cfg {string} [notsupported] Text to display when file support is missing in the browser.
14102 * @cfg {boolean} [droppable=true] Whether to accept files by drag and drop.
14103 * @cfg {boolean} [showDropTarget=false] Whether to show a drop target. Requires droppable to be true.
14104 * @cfg {boolean} [dragDropUI=false] Deprecated alias for showDropTarget
14105 */
14106 OO.ui.SelectFileWidget = function OoUiSelectFileWidget( config ) {
14107 var dragHandler;
14108
14109 // TODO: Remove in next release
14110 if ( config && config.dragDropUI ) {
14111 config.showDropTarget = true;
14112 }
14113
14114 // Configuration initialization
14115 config = $.extend( {
14116 accept: null,
14117 placeholder: OO.ui.msg( 'ooui-selectfile-placeholder' ),
14118 notsupported: OO.ui.msg( 'ooui-selectfile-not-supported' ),
14119 droppable: true,
14120 showDropTarget: false
14121 }, config );
14122
14123 // Parent constructor
14124 OO.ui.SelectFileWidget.parent.call( this, config );
14125
14126 // Mixin constructors
14127 OO.ui.mixin.IconElement.call( this, config );
14128 OO.ui.mixin.IndicatorElement.call( this, config );
14129 OO.ui.mixin.PendingElement.call( this, $.extend( {}, config, { $pending: this.$info } ) );
14130 OO.ui.mixin.LabelElement.call( this, $.extend( {}, config, { autoFitLabel: true } ) );
14131
14132 // Properties
14133 this.$info = $( '<span>' );
14134
14135 // Properties
14136 this.showDropTarget = config.showDropTarget;
14137 this.isSupported = this.constructor.static.isSupported();
14138 this.currentFile = null;
14139 if ( Array.isArray( config.accept ) ) {
14140 this.accept = config.accept;
14141 } else {
14142 this.accept = null;
14143 }
14144 this.placeholder = config.placeholder;
14145 this.notsupported = config.notsupported;
14146 this.onFileSelectedHandler = this.onFileSelected.bind( this );
14147
14148 this.selectButton = new OO.ui.ButtonWidget( {
14149 classes: [ 'oo-ui-selectFileWidget-selectButton' ],
14150 label: 'Select a file',
14151 disabled: this.disabled || !this.isSupported
14152 } );
14153
14154 this.clearButton = new OO.ui.ButtonWidget( {
14155 classes: [ 'oo-ui-selectFileWidget-clearButton' ],
14156 framed: false,
14157 icon: 'remove',
14158 disabled: this.disabled
14159 } );
14160
14161 // Events
14162 this.selectButton.$button.on( {
14163 keypress: this.onKeyPress.bind( this )
14164 } );
14165 this.clearButton.connect( this, {
14166 click: 'onClearClick'
14167 } );
14168 if ( config.droppable ) {
14169 dragHandler = this.onDragEnterOrOver.bind( this );
14170 this.$element.on( {
14171 dragenter: dragHandler,
14172 dragover: dragHandler,
14173 dragleave: this.onDragLeave.bind( this ),
14174 drop: this.onDrop.bind( this )
14175 } );
14176 }
14177
14178 // Initialization
14179 this.addInput();
14180 this.updateUI();
14181 this.$label.addClass( 'oo-ui-selectFileWidget-label' );
14182 this.$info
14183 .addClass( 'oo-ui-selectFileWidget-info' )
14184 .append( this.$icon, this.$label, this.clearButton.$element, this.$indicator );
14185 this.$element
14186 .addClass( 'oo-ui-selectFileWidget' )
14187 .append( this.$info, this.selectButton.$element );
14188 if ( config.droppable && config.showDropTarget ) {
14189 this.$dropTarget = $( '<div>' )
14190 .addClass( 'oo-ui-selectFileWidget-dropTarget' )
14191 .text( OO.ui.msg( 'ooui-selectfile-dragdrop-placeholder' ) )
14192 .on( {
14193 click: this.onDropTargetClick.bind( this )
14194 } );
14195 this.$element.prepend( this.$dropTarget );
14196 }
14197 };
14198
14199 /* Setup */
14200
14201 OO.inheritClass( OO.ui.SelectFileWidget, OO.ui.Widget );
14202 OO.mixinClass( OO.ui.SelectFileWidget, OO.ui.mixin.IconElement );
14203 OO.mixinClass( OO.ui.SelectFileWidget, OO.ui.mixin.IndicatorElement );
14204 OO.mixinClass( OO.ui.SelectFileWidget, OO.ui.mixin.PendingElement );
14205 OO.mixinClass( OO.ui.SelectFileWidget, OO.ui.mixin.LabelElement );
14206
14207 /* Static Properties */
14208
14209 /**
14210 * Check if this widget is supported
14211 *
14212 * @static
14213 * @return {boolean}
14214 */
14215 OO.ui.SelectFileWidget.static.isSupported = function () {
14216 var $input;
14217 if ( OO.ui.SelectFileWidget.static.isSupportedCache === null ) {
14218 $input = $( '<input type="file">' );
14219 OO.ui.SelectFileWidget.static.isSupportedCache = $input[ 0 ].files !== undefined;
14220 }
14221 return OO.ui.SelectFileWidget.static.isSupportedCache;
14222 };
14223
14224 OO.ui.SelectFileWidget.static.isSupportedCache = null;
14225
14226 /* Events */
14227
14228 /**
14229 * @event change
14230 *
14231 * A change event is emitted when the on/off state of the toggle changes.
14232 *
14233 * @param {File|null} value New value
14234 */
14235
14236 /* Methods */
14237
14238 /**
14239 * Get the current value of the field
14240 *
14241 * @return {File|null}
14242 */
14243 OO.ui.SelectFileWidget.prototype.getValue = function () {
14244 return this.currentFile;
14245 };
14246
14247 /**
14248 * Set the current value of the field
14249 *
14250 * @param {File|null} file File to select
14251 */
14252 OO.ui.SelectFileWidget.prototype.setValue = function ( file ) {
14253 if ( this.currentFile !== file ) {
14254 this.currentFile = file;
14255 this.updateUI();
14256 this.emit( 'change', this.currentFile );
14257 }
14258 };
14259
14260 /**
14261 * Focus the widget.
14262 *
14263 * Focusses the select file button.
14264 *
14265 * @chainable
14266 */
14267 OO.ui.SelectFileWidget.prototype.focus = function () {
14268 this.selectButton.$button[ 0 ].focus();
14269 return this;
14270 };
14271
14272 /**
14273 * Update the user interface when a file is selected or unselected
14274 *
14275 * @protected
14276 */
14277 OO.ui.SelectFileWidget.prototype.updateUI = function () {
14278 var $label;
14279 if ( !this.isSupported ) {
14280 this.$element.addClass( 'oo-ui-selectFileWidget-notsupported' );
14281 this.$element.removeClass( 'oo-ui-selectFileWidget-empty' );
14282 this.setLabel( this.notsupported );
14283 } else {
14284 this.$element.addClass( 'oo-ui-selectFileWidget-supported' );
14285 if ( this.currentFile ) {
14286 this.$element.removeClass( 'oo-ui-selectFileWidget-empty' );
14287 $label = $( [] );
14288 if ( this.currentFile.type !== '' ) {
14289 $label = $label.add( $( '<span>' ).addClass( 'oo-ui-selectFileWidget-fileType' ).text( this.currentFile.type ) );
14290 }
14291 $label = $label.add( $( '<span>' ).text( this.currentFile.name ) );
14292 this.setLabel( $label );
14293 } else {
14294 this.$element.addClass( 'oo-ui-selectFileWidget-empty' );
14295 this.setLabel( this.placeholder );
14296 }
14297 }
14298
14299 if ( this.$input ) {
14300 this.$input.attr( 'title', this.getLabel() );
14301 }
14302 };
14303
14304 /**
14305 * Add the input to the widget
14306 *
14307 * @private
14308 */
14309 OO.ui.SelectFileWidget.prototype.addInput = function () {
14310 if ( this.$input ) {
14311 this.$input.remove();
14312 }
14313
14314 if ( !this.isSupported ) {
14315 this.$input = null;
14316 return;
14317 }
14318
14319 this.$input = $( '<input type="file">' );
14320 this.$input.on( 'change', this.onFileSelectedHandler );
14321 this.$input.attr( {
14322 tabindex: -1,
14323 title: this.getLabel()
14324 } );
14325 if ( this.accept ) {
14326 this.$input.attr( 'accept', this.accept.join( ', ' ) );
14327 }
14328 this.selectButton.$button.append( this.$input );
14329 };
14330
14331 /**
14332 * Determine if we should accept this file
14333 *
14334 * @private
14335 * @param {string} File MIME type
14336 * @return {boolean}
14337 */
14338 OO.ui.SelectFileWidget.prototype.isAllowedType = function ( mimeType ) {
14339 var i, mimeTest;
14340
14341 if ( !this.accept || !mimeType ) {
14342 return true;
14343 }
14344
14345 for ( i = 0; i < this.accept.length; i++ ) {
14346 mimeTest = this.accept[ i ];
14347 if ( mimeTest === mimeType ) {
14348 return true;
14349 } else if ( mimeTest.substr( -2 ) === '/*' ) {
14350 mimeTest = mimeTest.substr( 0, mimeTest.length - 1 );
14351 if ( mimeType.substr( 0, mimeTest.length ) === mimeTest ) {
14352 return true;
14353 }
14354 }
14355 }
14356
14357 return false;
14358 };
14359
14360 /**
14361 * Handle file selection from the input
14362 *
14363 * @private
14364 * @param {jQuery.Event} e
14365 */
14366 OO.ui.SelectFileWidget.prototype.onFileSelected = function ( e ) {
14367 var file = OO.getProp( e.target, 'files', 0 ) || null;
14368
14369 if ( file && !this.isAllowedType( file.type ) ) {
14370 file = null;
14371 }
14372
14373 this.setValue( file );
14374 this.addInput();
14375 };
14376
14377 /**
14378 * Handle clear button click events.
14379 *
14380 * @private
14381 */
14382 OO.ui.SelectFileWidget.prototype.onClearClick = function () {
14383 this.setValue( null );
14384 return false;
14385 };
14386
14387 /**
14388 * Handle key press events.
14389 *
14390 * @private
14391 * @param {jQuery.Event} e Key press event
14392 */
14393 OO.ui.SelectFileWidget.prototype.onKeyPress = function ( e ) {
14394 if ( this.isSupported && !this.isDisabled() && this.$input &&
14395 ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
14396 ) {
14397 this.$input.click();
14398 return false;
14399 }
14400 };
14401
14402 /**
14403 * Handle drop target click events.
14404 *
14405 * @private
14406 * @param {jQuery.Event} e Key press event
14407 */
14408 OO.ui.SelectFileWidget.prototype.onDropTargetClick = function () {
14409 if ( this.isSupported && !this.isDisabled() && this.$input ) {
14410 this.$input.click();
14411 return false;
14412 }
14413 };
14414
14415 /**
14416 * Handle drag enter and over events
14417 *
14418 * @private
14419 * @param {jQuery.Event} e Drag event
14420 */
14421 OO.ui.SelectFileWidget.prototype.onDragEnterOrOver = function ( e ) {
14422 var itemOrFile,
14423 droppableFile = false,
14424 dt = e.originalEvent.dataTransfer;
14425
14426 e.preventDefault();
14427 e.stopPropagation();
14428
14429 if ( this.isDisabled() || !this.isSupported ) {
14430 this.$element.removeClass( 'oo-ui-selectFileWidget-canDrop' );
14431 dt.dropEffect = 'none';
14432 return false;
14433 }
14434
14435 // DataTransferItem and File both have a type property, but in Chrome files
14436 // have no information at this point.
14437 itemOrFile = OO.getProp( dt, 'items', 0 ) || OO.getProp( dt, 'files', 0 );
14438 if ( itemOrFile ) {
14439 if ( this.isAllowedType( itemOrFile.type ) ) {
14440 droppableFile = true;
14441 }
14442 // dt.types is Array-like, but not an Array
14443 } else if ( Array.prototype.indexOf.call( OO.getProp( dt, 'types' ) || [], 'Files' ) !== -1 ) {
14444 // File information is not available at this point for security so just assume
14445 // it is acceptable for now.
14446 // https://bugzilla.mozilla.org/show_bug.cgi?id=640534
14447 droppableFile = true;
14448 }
14449
14450 this.$element.toggleClass( 'oo-ui-selectFileWidget-canDrop', droppableFile );
14451 if ( !droppableFile ) {
14452 dt.dropEffect = 'none';
14453 }
14454
14455 return false;
14456 };
14457
14458 /**
14459 * Handle drag leave events
14460 *
14461 * @private
14462 * @param {jQuery.Event} e Drag event
14463 */
14464 OO.ui.SelectFileWidget.prototype.onDragLeave = function () {
14465 this.$element.removeClass( 'oo-ui-selectFileWidget-canDrop' );
14466 };
14467
14468 /**
14469 * Handle drop events
14470 *
14471 * @private
14472 * @param {jQuery.Event} e Drop event
14473 */
14474 OO.ui.SelectFileWidget.prototype.onDrop = function ( e ) {
14475 var file = null,
14476 dt = e.originalEvent.dataTransfer;
14477
14478 e.preventDefault();
14479 e.stopPropagation();
14480 this.$element.removeClass( 'oo-ui-selectFileWidget-canDrop' );
14481
14482 if ( this.isDisabled() || !this.isSupported ) {
14483 return false;
14484 }
14485
14486 file = OO.getProp( dt, 'files', 0 );
14487 if ( file && !this.isAllowedType( file.type ) ) {
14488 file = null;
14489 }
14490 if ( file ) {
14491 this.setValue( file );
14492 }
14493
14494 return false;
14495 };
14496
14497 /**
14498 * @inheritdoc
14499 */
14500 OO.ui.SelectFileWidget.prototype.setDisabled = function ( disabled ) {
14501 OO.ui.SelectFileWidget.parent.prototype.setDisabled.call( this, disabled );
14502 if ( this.selectButton ) {
14503 this.selectButton.setDisabled( disabled );
14504 }
14505 if ( this.clearButton ) {
14506 this.clearButton.setDisabled( disabled );
14507 }
14508 return this;
14509 };
14510
14511 /**
14512 * IconWidget is a generic widget for {@link OO.ui.mixin.IconElement icons}. In general, IconWidgets should be used with OO.ui.LabelWidget,
14513 * which creates a label that identifies the icon’s function. See the [OOjs UI documentation on MediaWiki] [1]
14514 * for a list of icons included in the library.
14515 *
14516 * @example
14517 * // An icon widget with a label
14518 * var myIcon = new OO.ui.IconWidget( {
14519 * icon: 'help',
14520 * iconTitle: 'Help'
14521 * } );
14522 * // Create a label.
14523 * var iconLabel = new OO.ui.LabelWidget( {
14524 * label: 'Help'
14525 * } );
14526 * $( 'body' ).append( myIcon.$element, iconLabel.$element );
14527 *
14528 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
14529 *
14530 * @class
14531 * @extends OO.ui.Widget
14532 * @mixins OO.ui.mixin.IconElement
14533 * @mixins OO.ui.mixin.TitledElement
14534 * @mixins OO.ui.mixin.FlaggedElement
14535 *
14536 * @constructor
14537 * @param {Object} [config] Configuration options
14538 */
14539 OO.ui.IconWidget = function OoUiIconWidget( config ) {
14540 // Configuration initialization
14541 config = config || {};
14542
14543 // Parent constructor
14544 OO.ui.IconWidget.parent.call( this, config );
14545
14546 // Mixin constructors
14547 OO.ui.mixin.IconElement.call( this, $.extend( {}, config, { $icon: this.$element } ) );
14548 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$element } ) );
14549 OO.ui.mixin.FlaggedElement.call( this, $.extend( {}, config, { $flagged: this.$element } ) );
14550
14551 // Initialization
14552 this.$element.addClass( 'oo-ui-iconWidget' );
14553 };
14554
14555 /* Setup */
14556
14557 OO.inheritClass( OO.ui.IconWidget, OO.ui.Widget );
14558 OO.mixinClass( OO.ui.IconWidget, OO.ui.mixin.IconElement );
14559 OO.mixinClass( OO.ui.IconWidget, OO.ui.mixin.TitledElement );
14560 OO.mixinClass( OO.ui.IconWidget, OO.ui.mixin.FlaggedElement );
14561
14562 /* Static Properties */
14563
14564 OO.ui.IconWidget.static.tagName = 'span';
14565
14566 /**
14567 * IndicatorWidgets create indicators, which are small graphics that are generally used to draw
14568 * attention to the status of an item or to clarify the function of a control. For a list of
14569 * indicators included in the library, please see the [OOjs UI documentation on MediaWiki][1].
14570 *
14571 * @example
14572 * // Example of an indicator widget
14573 * var indicator1 = new OO.ui.IndicatorWidget( {
14574 * indicator: 'alert'
14575 * } );
14576 *
14577 * // Create a fieldset layout to add a label
14578 * var fieldset = new OO.ui.FieldsetLayout();
14579 * fieldset.addItems( [
14580 * new OO.ui.FieldLayout( indicator1, { label: 'An alert indicator:' } )
14581 * ] );
14582 * $( 'body' ).append( fieldset.$element );
14583 *
14584 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
14585 *
14586 * @class
14587 * @extends OO.ui.Widget
14588 * @mixins OO.ui.mixin.IndicatorElement
14589 * @mixins OO.ui.mixin.TitledElement
14590 *
14591 * @constructor
14592 * @param {Object} [config] Configuration options
14593 */
14594 OO.ui.IndicatorWidget = function OoUiIndicatorWidget( config ) {
14595 // Configuration initialization
14596 config = config || {};
14597
14598 // Parent constructor
14599 OO.ui.IndicatorWidget.parent.call( this, config );
14600
14601 // Mixin constructors
14602 OO.ui.mixin.IndicatorElement.call( this, $.extend( {}, config, { $indicator: this.$element } ) );
14603 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$element } ) );
14604
14605 // Initialization
14606 this.$element.addClass( 'oo-ui-indicatorWidget' );
14607 };
14608
14609 /* Setup */
14610
14611 OO.inheritClass( OO.ui.IndicatorWidget, OO.ui.Widget );
14612 OO.mixinClass( OO.ui.IndicatorWidget, OO.ui.mixin.IndicatorElement );
14613 OO.mixinClass( OO.ui.IndicatorWidget, OO.ui.mixin.TitledElement );
14614
14615 /* Static Properties */
14616
14617 OO.ui.IndicatorWidget.static.tagName = 'span';
14618
14619 /**
14620 * InputWidget is the base class for all input widgets, which
14621 * include {@link OO.ui.TextInputWidget text inputs}, {@link OO.ui.CheckboxInputWidget checkbox inputs},
14622 * {@link OO.ui.RadioInputWidget radio inputs}, and {@link OO.ui.ButtonInputWidget button inputs}.
14623 * See the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
14624 *
14625 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
14626 *
14627 * @abstract
14628 * @class
14629 * @extends OO.ui.Widget
14630 * @mixins OO.ui.mixin.FlaggedElement
14631 * @mixins OO.ui.mixin.TabIndexedElement
14632 * @mixins OO.ui.mixin.TitledElement
14633 * @mixins OO.ui.mixin.AccessKeyedElement
14634 *
14635 * @constructor
14636 * @param {Object} [config] Configuration options
14637 * @cfg {string} [name=''] The value of the input’s HTML `name` attribute.
14638 * @cfg {string} [value=''] The value of the input.
14639 * @cfg {string} [dir] The directionality of the input (ltr/rtl).
14640 * @cfg {Function} [inputFilter] The name of an input filter function. Input filters modify the value of an input
14641 * before it is accepted.
14642 */
14643 OO.ui.InputWidget = function OoUiInputWidget( config ) {
14644 // Configuration initialization
14645 config = config || {};
14646
14647 // Parent constructor
14648 OO.ui.InputWidget.parent.call( this, config );
14649
14650 // Properties
14651 this.$input = this.getInputElement( config );
14652 this.value = '';
14653 this.inputFilter = config.inputFilter;
14654
14655 // Mixin constructors
14656 OO.ui.mixin.FlaggedElement.call( this, config );
14657 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$input } ) );
14658 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$input } ) );
14659 OO.ui.mixin.AccessKeyedElement.call( this, $.extend( {}, config, { $accessKeyed: this.$input } ) );
14660
14661 // Events
14662 this.$input.on( 'keydown mouseup cut paste change input select', this.onEdit.bind( this ) );
14663
14664 // Initialization
14665 this.$input
14666 .addClass( 'oo-ui-inputWidget-input' )
14667 .attr( 'name', config.name )
14668 .prop( 'disabled', this.isDisabled() );
14669 this.$element
14670 .addClass( 'oo-ui-inputWidget' )
14671 .append( this.$input );
14672 this.setValue( config.value );
14673 this.setAccessKey( config.accessKey );
14674 if ( config.dir ) {
14675 this.setDir( config.dir );
14676 }
14677 };
14678
14679 /* Setup */
14680
14681 OO.inheritClass( OO.ui.InputWidget, OO.ui.Widget );
14682 OO.mixinClass( OO.ui.InputWidget, OO.ui.mixin.FlaggedElement );
14683 OO.mixinClass( OO.ui.InputWidget, OO.ui.mixin.TabIndexedElement );
14684 OO.mixinClass( OO.ui.InputWidget, OO.ui.mixin.TitledElement );
14685 OO.mixinClass( OO.ui.InputWidget, OO.ui.mixin.AccessKeyedElement );
14686
14687 /* Static Properties */
14688
14689 OO.ui.InputWidget.static.supportsSimpleLabel = true;
14690
14691 /* Static Methods */
14692
14693 /**
14694 * @inheritdoc
14695 */
14696 OO.ui.InputWidget.static.reusePreInfuseDOM = function ( node, config ) {
14697 config = OO.ui.InputWidget.parent.static.reusePreInfuseDOM( node, config );
14698 // Reusing $input lets browsers preserve inputted values across page reloads (T114134)
14699 config.$input = $( node ).find( '.oo-ui-inputWidget-input' );
14700 return config;
14701 };
14702
14703 /**
14704 * @inheritdoc
14705 */
14706 OO.ui.InputWidget.static.gatherPreInfuseState = function ( node, config ) {
14707 var state = OO.ui.InputWidget.parent.static.gatherPreInfuseState( node, config );
14708 state.value = config.$input.val();
14709 // Might be better in TabIndexedElement, but it's awkward to do there because mixins are awkward
14710 state.focus = config.$input.is( ':focus' );
14711 return state;
14712 };
14713
14714 /* Events */
14715
14716 /**
14717 * @event change
14718 *
14719 * A change event is emitted when the value of the input changes.
14720 *
14721 * @param {string} value
14722 */
14723
14724 /* Methods */
14725
14726 /**
14727 * Get input element.
14728 *
14729 * Subclasses of OO.ui.InputWidget use the `config` parameter to produce different elements in
14730 * different circumstances. The element must have a `value` property (like form elements).
14731 *
14732 * @protected
14733 * @param {Object} config Configuration options
14734 * @return {jQuery} Input element
14735 */
14736 OO.ui.InputWidget.prototype.getInputElement = function ( config ) {
14737 // See #reusePreInfuseDOM about config.$input
14738 return config.$input || $( '<input>' );
14739 };
14740
14741 /**
14742 * Handle potentially value-changing events.
14743 *
14744 * @private
14745 * @param {jQuery.Event} e Key down, mouse up, cut, paste, change, input, or select event
14746 */
14747 OO.ui.InputWidget.prototype.onEdit = function () {
14748 var widget = this;
14749 if ( !this.isDisabled() ) {
14750 // Allow the stack to clear so the value will be updated
14751 setTimeout( function () {
14752 widget.setValue( widget.$input.val() );
14753 } );
14754 }
14755 };
14756
14757 /**
14758 * Get the value of the input.
14759 *
14760 * @return {string} Input value
14761 */
14762 OO.ui.InputWidget.prototype.getValue = function () {
14763 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
14764 // it, and we won't know unless they're kind enough to trigger a 'change' event.
14765 var value = this.$input.val();
14766 if ( this.value !== value ) {
14767 this.setValue( value );
14768 }
14769 return this.value;
14770 };
14771
14772 /**
14773 * Set the directionality of the input, either RTL (right-to-left) or LTR (left-to-right).
14774 *
14775 * @deprecated since v0.13.1, use #setDir directly
14776 * @param {boolean} isRTL Directionality is right-to-left
14777 * @chainable
14778 */
14779 OO.ui.InputWidget.prototype.setRTL = function ( isRTL ) {
14780 this.setDir( isRTL ? 'rtl' : 'ltr' );
14781 return this;
14782 };
14783
14784 /**
14785 * Set the directionality of the input.
14786 *
14787 * @param {string} dir Text directionality: 'ltr', 'rtl' or 'auto'
14788 * @chainable
14789 */
14790 OO.ui.InputWidget.prototype.setDir = function ( dir ) {
14791 this.$input.prop( 'dir', dir );
14792 return this;
14793 };
14794
14795 /**
14796 * Set the value of the input.
14797 *
14798 * @param {string} value New value
14799 * @fires change
14800 * @chainable
14801 */
14802 OO.ui.InputWidget.prototype.setValue = function ( value ) {
14803 value = this.cleanUpValue( value );
14804 // Update the DOM if it has changed. Note that with cleanUpValue, it
14805 // is possible for the DOM value to change without this.value changing.
14806 if ( this.$input.val() !== value ) {
14807 this.$input.val( value );
14808 }
14809 if ( this.value !== value ) {
14810 this.value = value;
14811 this.emit( 'change', this.value );
14812 }
14813 return this;
14814 };
14815
14816 /**
14817 * Set the input's access key.
14818 * FIXME: This is the same code as in OO.ui.mixin.ButtonElement, maybe find a better place for it?
14819 *
14820 * @param {string} accessKey Input's access key, use empty string to remove
14821 * @chainable
14822 */
14823 OO.ui.InputWidget.prototype.setAccessKey = function ( accessKey ) {
14824 accessKey = typeof accessKey === 'string' && accessKey.length ? accessKey : null;
14825
14826 if ( this.accessKey !== accessKey ) {
14827 if ( this.$input ) {
14828 if ( accessKey !== null ) {
14829 this.$input.attr( 'accesskey', accessKey );
14830 } else {
14831 this.$input.removeAttr( 'accesskey' );
14832 }
14833 }
14834 this.accessKey = accessKey;
14835 }
14836
14837 return this;
14838 };
14839
14840 /**
14841 * Clean up incoming value.
14842 *
14843 * Ensures value is a string, and converts undefined and null to empty string.
14844 *
14845 * @private
14846 * @param {string} value Original value
14847 * @return {string} Cleaned up value
14848 */
14849 OO.ui.InputWidget.prototype.cleanUpValue = function ( value ) {
14850 if ( value === undefined || value === null ) {
14851 return '';
14852 } else if ( this.inputFilter ) {
14853 return this.inputFilter( String( value ) );
14854 } else {
14855 return String( value );
14856 }
14857 };
14858
14859 /**
14860 * Simulate the behavior of clicking on a label bound to this input. This method is only called by
14861 * {@link OO.ui.LabelWidget LabelWidget} and {@link OO.ui.FieldLayout FieldLayout}. It should not be
14862 * called directly.
14863 */
14864 OO.ui.InputWidget.prototype.simulateLabelClick = function () {
14865 if ( !this.isDisabled() ) {
14866 if ( this.$input.is( ':checkbox, :radio' ) ) {
14867 this.$input.click();
14868 }
14869 if ( this.$input.is( ':input' ) ) {
14870 this.$input[ 0 ].focus();
14871 }
14872 }
14873 };
14874
14875 /**
14876 * @inheritdoc
14877 */
14878 OO.ui.InputWidget.prototype.setDisabled = function ( state ) {
14879 OO.ui.InputWidget.parent.prototype.setDisabled.call( this, state );
14880 if ( this.$input ) {
14881 this.$input.prop( 'disabled', this.isDisabled() );
14882 }
14883 return this;
14884 };
14885
14886 /**
14887 * Focus the input.
14888 *
14889 * @chainable
14890 */
14891 OO.ui.InputWidget.prototype.focus = function () {
14892 this.$input[ 0 ].focus();
14893 return this;
14894 };
14895
14896 /**
14897 * Blur the input.
14898 *
14899 * @chainable
14900 */
14901 OO.ui.InputWidget.prototype.blur = function () {
14902 this.$input[ 0 ].blur();
14903 return this;
14904 };
14905
14906 /**
14907 * @inheritdoc
14908 */
14909 OO.ui.InputWidget.prototype.restorePreInfuseState = function ( state ) {
14910 OO.ui.InputWidget.parent.prototype.restorePreInfuseState.call( this, state );
14911 if ( state.value !== undefined && state.value !== this.getValue() ) {
14912 this.setValue( state.value );
14913 }
14914 if ( state.focus ) {
14915 this.focus();
14916 }
14917 };
14918
14919 /**
14920 * ButtonInputWidget is used to submit HTML forms and is intended to be used within
14921 * a OO.ui.FormLayout. If you do not need the button to work with HTML forms, you probably
14922 * want to use OO.ui.ButtonWidget instead. Button input widgets can be rendered as either an
14923 * HTML `<button/>` (the default) or an HTML `<input/>` tags. See the
14924 * [OOjs UI documentation on MediaWiki] [1] for more information.
14925 *
14926 * @example
14927 * // A ButtonInputWidget rendered as an HTML button, the default.
14928 * var button = new OO.ui.ButtonInputWidget( {
14929 * label: 'Input button',
14930 * icon: 'check',
14931 * value: 'check'
14932 * } );
14933 * $( 'body' ).append( button.$element );
14934 *
14935 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs#Button_inputs
14936 *
14937 * @class
14938 * @extends OO.ui.InputWidget
14939 * @mixins OO.ui.mixin.ButtonElement
14940 * @mixins OO.ui.mixin.IconElement
14941 * @mixins OO.ui.mixin.IndicatorElement
14942 * @mixins OO.ui.mixin.LabelElement
14943 * @mixins OO.ui.mixin.TitledElement
14944 *
14945 * @constructor
14946 * @param {Object} [config] Configuration options
14947 * @cfg {string} [type='button'] The value of the HTML `'type'` attribute: 'button', 'submit' or 'reset'.
14948 * @cfg {boolean} [useInputTag=false] Use an `<input/>` tag instead of a `<button/>` tag, the default.
14949 * Widgets configured to be an `<input/>` do not support {@link #icon icons} and {@link #indicator indicators},
14950 * non-plaintext {@link #label labels}, or {@link #value values}. In general, useInputTag should only
14951 * be set to `true` when there’s need to support IE6 in a form with multiple buttons.
14952 */
14953 OO.ui.ButtonInputWidget = function OoUiButtonInputWidget( config ) {
14954 // Configuration initialization
14955 config = $.extend( { type: 'button', useInputTag: false }, config );
14956
14957 // Properties (must be set before parent constructor, which calls #setValue)
14958 this.useInputTag = config.useInputTag;
14959
14960 // Parent constructor
14961 OO.ui.ButtonInputWidget.parent.call( this, config );
14962
14963 // Mixin constructors
14964 OO.ui.mixin.ButtonElement.call( this, $.extend( {}, config, { $button: this.$input } ) );
14965 OO.ui.mixin.IconElement.call( this, config );
14966 OO.ui.mixin.IndicatorElement.call( this, config );
14967 OO.ui.mixin.LabelElement.call( this, config );
14968 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$input } ) );
14969
14970 // Initialization
14971 if ( !config.useInputTag ) {
14972 this.$input.append( this.$icon, this.$label, this.$indicator );
14973 }
14974 this.$element.addClass( 'oo-ui-buttonInputWidget' );
14975 };
14976
14977 /* Setup */
14978
14979 OO.inheritClass( OO.ui.ButtonInputWidget, OO.ui.InputWidget );
14980 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.ButtonElement );
14981 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.IconElement );
14982 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.IndicatorElement );
14983 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.LabelElement );
14984 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.TitledElement );
14985
14986 /* Static Properties */
14987
14988 /**
14989 * Disable generating `<label>` elements for buttons. One would very rarely need additional label
14990 * for a button, and it's already a big clickable target, and it causes unexpected rendering.
14991 */
14992 OO.ui.ButtonInputWidget.static.supportsSimpleLabel = false;
14993
14994 /* Methods */
14995
14996 /**
14997 * @inheritdoc
14998 * @protected
14999 */
15000 OO.ui.ButtonInputWidget.prototype.getInputElement = function ( config ) {
15001 var type;
15002 // See InputWidget#reusePreInfuseDOM about config.$input
15003 if ( config.$input ) {
15004 return config.$input.empty();
15005 }
15006 type = [ 'button', 'submit', 'reset' ].indexOf( config.type ) !== -1 ? config.type : 'button';
15007 return $( '<' + ( config.useInputTag ? 'input' : 'button' ) + ' type="' + type + '">' );
15008 };
15009
15010 /**
15011 * Set label value.
15012 *
15013 * If #useInputTag is `true`, the label is set as the `value` of the `<input/>` tag.
15014 *
15015 * @param {jQuery|string|Function|null} label Label nodes, text, a function that returns nodes or
15016 * text, or `null` for no label
15017 * @chainable
15018 */
15019 OO.ui.ButtonInputWidget.prototype.setLabel = function ( label ) {
15020 OO.ui.mixin.LabelElement.prototype.setLabel.call( this, label );
15021
15022 if ( this.useInputTag ) {
15023 if ( typeof label === 'function' ) {
15024 label = OO.ui.resolveMsg( label );
15025 }
15026 if ( label instanceof jQuery ) {
15027 label = label.text();
15028 }
15029 if ( !label ) {
15030 label = '';
15031 }
15032 this.$input.val( label );
15033 }
15034
15035 return this;
15036 };
15037
15038 /**
15039 * Set the value of the input.
15040 *
15041 * This method is disabled for button inputs configured as {@link #useInputTag <input/> tags}, as
15042 * they do not support {@link #value values}.
15043 *
15044 * @param {string} value New value
15045 * @chainable
15046 */
15047 OO.ui.ButtonInputWidget.prototype.setValue = function ( value ) {
15048 if ( !this.useInputTag ) {
15049 OO.ui.ButtonInputWidget.parent.prototype.setValue.call( this, value );
15050 }
15051 return this;
15052 };
15053
15054 /**
15055 * CheckboxInputWidgets, like HTML checkboxes, can be selected and/or configured with a value.
15056 * Note that these {@link OO.ui.InputWidget input widgets} are best laid out
15057 * in {@link OO.ui.FieldLayout field layouts} that use the {@link OO.ui.FieldLayout#align inline}
15058 * alignment. For more information, please see the [OOjs UI documentation on MediaWiki][1].
15059 *
15060 * This widget can be used inside a HTML form, such as a OO.ui.FormLayout.
15061 *
15062 * @example
15063 * // An example of selected, unselected, and disabled checkbox inputs
15064 * var checkbox1=new OO.ui.CheckboxInputWidget( {
15065 * value: 'a',
15066 * selected: true
15067 * } );
15068 * var checkbox2=new OO.ui.CheckboxInputWidget( {
15069 * value: 'b'
15070 * } );
15071 * var checkbox3=new OO.ui.CheckboxInputWidget( {
15072 * value:'c',
15073 * disabled: true
15074 * } );
15075 * // Create a fieldset layout with fields for each checkbox.
15076 * var fieldset = new OO.ui.FieldsetLayout( {
15077 * label: 'Checkboxes'
15078 * } );
15079 * fieldset.addItems( [
15080 * new OO.ui.FieldLayout( checkbox1, { label: 'Selected checkbox', align: 'inline' } ),
15081 * new OO.ui.FieldLayout( checkbox2, { label: 'Unselected checkbox', align: 'inline' } ),
15082 * new OO.ui.FieldLayout( checkbox3, { label: 'Disabled checkbox', align: 'inline' } ),
15083 * ] );
15084 * $( 'body' ).append( fieldset.$element );
15085 *
15086 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
15087 *
15088 * @class
15089 * @extends OO.ui.InputWidget
15090 *
15091 * @constructor
15092 * @param {Object} [config] Configuration options
15093 * @cfg {boolean} [selected=false] Select the checkbox initially. By default, the checkbox is not selected.
15094 */
15095 OO.ui.CheckboxInputWidget = function OoUiCheckboxInputWidget( config ) {
15096 // Configuration initialization
15097 config = config || {};
15098
15099 // Parent constructor
15100 OO.ui.CheckboxInputWidget.parent.call( this, config );
15101
15102 // Initialization
15103 this.$element
15104 .addClass( 'oo-ui-checkboxInputWidget' )
15105 // Required for pretty styling in MediaWiki theme
15106 .append( $( '<span>' ) );
15107 this.setSelected( config.selected !== undefined ? config.selected : false );
15108 };
15109
15110 /* Setup */
15111
15112 OO.inheritClass( OO.ui.CheckboxInputWidget, OO.ui.InputWidget );
15113
15114 /* Static Methods */
15115
15116 /**
15117 * @inheritdoc
15118 */
15119 OO.ui.CheckboxInputWidget.static.gatherPreInfuseState = function ( node, config ) {
15120 var state = OO.ui.CheckboxInputWidget.parent.static.gatherPreInfuseState( node, config );
15121 state.checked = config.$input.prop( 'checked' );
15122 return state;
15123 };
15124
15125 /* Methods */
15126
15127 /**
15128 * @inheritdoc
15129 * @protected
15130 */
15131 OO.ui.CheckboxInputWidget.prototype.getInputElement = function () {
15132 return $( '<input type="checkbox" />' );
15133 };
15134
15135 /**
15136 * @inheritdoc
15137 */
15138 OO.ui.CheckboxInputWidget.prototype.onEdit = function () {
15139 var widget = this;
15140 if ( !this.isDisabled() ) {
15141 // Allow the stack to clear so the value will be updated
15142 setTimeout( function () {
15143 widget.setSelected( widget.$input.prop( 'checked' ) );
15144 } );
15145 }
15146 };
15147
15148 /**
15149 * Set selection state of this checkbox.
15150 *
15151 * @param {boolean} state `true` for selected
15152 * @chainable
15153 */
15154 OO.ui.CheckboxInputWidget.prototype.setSelected = function ( state ) {
15155 state = !!state;
15156 if ( this.selected !== state ) {
15157 this.selected = state;
15158 this.$input.prop( 'checked', this.selected );
15159 this.emit( 'change', this.selected );
15160 }
15161 return this;
15162 };
15163
15164 /**
15165 * Check if this checkbox is selected.
15166 *
15167 * @return {boolean} Checkbox is selected
15168 */
15169 OO.ui.CheckboxInputWidget.prototype.isSelected = function () {
15170 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
15171 // it, and we won't know unless they're kind enough to trigger a 'change' event.
15172 var selected = this.$input.prop( 'checked' );
15173 if ( this.selected !== selected ) {
15174 this.setSelected( selected );
15175 }
15176 return this.selected;
15177 };
15178
15179 /**
15180 * @inheritdoc
15181 */
15182 OO.ui.CheckboxInputWidget.prototype.restorePreInfuseState = function ( state ) {
15183 OO.ui.CheckboxInputWidget.parent.prototype.restorePreInfuseState.call( this, state );
15184 if ( state.checked !== undefined && state.checked !== this.isSelected() ) {
15185 this.setSelected( state.checked );
15186 }
15187 };
15188
15189 /**
15190 * DropdownInputWidget is a {@link OO.ui.DropdownWidget DropdownWidget} intended to be used
15191 * within a HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with the value
15192 * of a hidden HTML `input` tag. Please see the [OOjs UI documentation on MediaWiki][1] for
15193 * more information about input widgets.
15194 *
15195 * A DropdownInputWidget always has a value (one of the options is always selected), unless there
15196 * are no options. If no `value` configuration option is provided, the first option is selected.
15197 * If you need a state representing no value (no option being selected), use a DropdownWidget.
15198 *
15199 * This and OO.ui.RadioSelectInputWidget support the same configuration options.
15200 *
15201 * @example
15202 * // Example: A DropdownInputWidget with three options
15203 * var dropdownInput = new OO.ui.DropdownInputWidget( {
15204 * options: [
15205 * { data: 'a', label: 'First' },
15206 * { data: 'b', label: 'Second'},
15207 * { data: 'c', label: 'Third' }
15208 * ]
15209 * } );
15210 * $( 'body' ).append( dropdownInput.$element );
15211 *
15212 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
15213 *
15214 * @class
15215 * @extends OO.ui.InputWidget
15216 * @mixins OO.ui.mixin.TitledElement
15217 *
15218 * @constructor
15219 * @param {Object} [config] Configuration options
15220 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
15221 * @cfg {Object} [dropdown] Configuration options for {@link OO.ui.DropdownWidget DropdownWidget}
15222 */
15223 OO.ui.DropdownInputWidget = function OoUiDropdownInputWidget( config ) {
15224 // Configuration initialization
15225 config = config || {};
15226
15227 // Properties (must be done before parent constructor which calls #setDisabled)
15228 this.dropdownWidget = new OO.ui.DropdownWidget( config.dropdown );
15229
15230 // Parent constructor
15231 OO.ui.DropdownInputWidget.parent.call( this, config );
15232
15233 // Mixin constructors
15234 OO.ui.mixin.TitledElement.call( this, config );
15235
15236 // Events
15237 this.dropdownWidget.getMenu().connect( this, { select: 'onMenuSelect' } );
15238
15239 // Initialization
15240 this.setOptions( config.options || [] );
15241 this.$element
15242 .addClass( 'oo-ui-dropdownInputWidget' )
15243 .append( this.dropdownWidget.$element );
15244 };
15245
15246 /* Setup */
15247
15248 OO.inheritClass( OO.ui.DropdownInputWidget, OO.ui.InputWidget );
15249 OO.mixinClass( OO.ui.DropdownInputWidget, OO.ui.mixin.TitledElement );
15250
15251 /* Methods */
15252
15253 /**
15254 * @inheritdoc
15255 * @protected
15256 */
15257 OO.ui.DropdownInputWidget.prototype.getInputElement = function ( config ) {
15258 // See InputWidget#reusePreInfuseDOM about config.$input
15259 if ( config.$input ) {
15260 return config.$input.addClass( 'oo-ui-element-hidden' );
15261 }
15262 return $( '<input type="hidden">' );
15263 };
15264
15265 /**
15266 * Handles menu select events.
15267 *
15268 * @private
15269 * @param {OO.ui.MenuOptionWidget} item Selected menu item
15270 */
15271 OO.ui.DropdownInputWidget.prototype.onMenuSelect = function ( item ) {
15272 this.setValue( item.getData() );
15273 };
15274
15275 /**
15276 * @inheritdoc
15277 */
15278 OO.ui.DropdownInputWidget.prototype.setValue = function ( value ) {
15279 value = this.cleanUpValue( value );
15280 this.dropdownWidget.getMenu().selectItemByData( value );
15281 OO.ui.DropdownInputWidget.parent.prototype.setValue.call( this, value );
15282 return this;
15283 };
15284
15285 /**
15286 * @inheritdoc
15287 */
15288 OO.ui.DropdownInputWidget.prototype.setDisabled = function ( state ) {
15289 this.dropdownWidget.setDisabled( state );
15290 OO.ui.DropdownInputWidget.parent.prototype.setDisabled.call( this, state );
15291 return this;
15292 };
15293
15294 /**
15295 * Set the options available for this input.
15296 *
15297 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
15298 * @chainable
15299 */
15300 OO.ui.DropdownInputWidget.prototype.setOptions = function ( options ) {
15301 var
15302 value = this.getValue(),
15303 widget = this;
15304
15305 // Rebuild the dropdown menu
15306 this.dropdownWidget.getMenu()
15307 .clearItems()
15308 .addItems( options.map( function ( opt ) {
15309 var optValue = widget.cleanUpValue( opt.data );
15310 return new OO.ui.MenuOptionWidget( {
15311 data: optValue,
15312 label: opt.label !== undefined ? opt.label : optValue
15313 } );
15314 } ) );
15315
15316 // Restore the previous value, or reset to something sensible
15317 if ( this.dropdownWidget.getMenu().getItemFromData( value ) ) {
15318 // Previous value is still available, ensure consistency with the dropdown
15319 this.setValue( value );
15320 } else {
15321 // No longer valid, reset
15322 if ( options.length ) {
15323 this.setValue( options[ 0 ].data );
15324 }
15325 }
15326
15327 return this;
15328 };
15329
15330 /**
15331 * @inheritdoc
15332 */
15333 OO.ui.DropdownInputWidget.prototype.focus = function () {
15334 this.dropdownWidget.getMenu().toggle( true );
15335 return this;
15336 };
15337
15338 /**
15339 * @inheritdoc
15340 */
15341 OO.ui.DropdownInputWidget.prototype.blur = function () {
15342 this.dropdownWidget.getMenu().toggle( false );
15343 return this;
15344 };
15345
15346 /**
15347 * RadioInputWidget creates a single radio button. Because radio buttons are usually used as a set,
15348 * in most cases you will want to use a {@link OO.ui.RadioSelectWidget radio select}
15349 * with {@link OO.ui.RadioOptionWidget radio options} instead of this class. For more information,
15350 * please see the [OOjs UI documentation on MediaWiki][1].
15351 *
15352 * This widget can be used inside a HTML form, such as a OO.ui.FormLayout.
15353 *
15354 * @example
15355 * // An example of selected, unselected, and disabled radio inputs
15356 * var radio1 = new OO.ui.RadioInputWidget( {
15357 * value: 'a',
15358 * selected: true
15359 * } );
15360 * var radio2 = new OO.ui.RadioInputWidget( {
15361 * value: 'b'
15362 * } );
15363 * var radio3 = new OO.ui.RadioInputWidget( {
15364 * value: 'c',
15365 * disabled: true
15366 * } );
15367 * // Create a fieldset layout with fields for each radio button.
15368 * var fieldset = new OO.ui.FieldsetLayout( {
15369 * label: 'Radio inputs'
15370 * } );
15371 * fieldset.addItems( [
15372 * new OO.ui.FieldLayout( radio1, { label: 'Selected', align: 'inline' } ),
15373 * new OO.ui.FieldLayout( radio2, { label: 'Unselected', align: 'inline' } ),
15374 * new OO.ui.FieldLayout( radio3, { label: 'Disabled', align: 'inline' } ),
15375 * ] );
15376 * $( 'body' ).append( fieldset.$element );
15377 *
15378 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
15379 *
15380 * @class
15381 * @extends OO.ui.InputWidget
15382 *
15383 * @constructor
15384 * @param {Object} [config] Configuration options
15385 * @cfg {boolean} [selected=false] Select the radio button initially. By default, the radio button is not selected.
15386 */
15387 OO.ui.RadioInputWidget = function OoUiRadioInputWidget( config ) {
15388 // Configuration initialization
15389 config = config || {};
15390
15391 // Parent constructor
15392 OO.ui.RadioInputWidget.parent.call( this, config );
15393
15394 // Initialization
15395 this.$element
15396 .addClass( 'oo-ui-radioInputWidget' )
15397 // Required for pretty styling in MediaWiki theme
15398 .append( $( '<span>' ) );
15399 this.setSelected( config.selected !== undefined ? config.selected : false );
15400 };
15401
15402 /* Setup */
15403
15404 OO.inheritClass( OO.ui.RadioInputWidget, OO.ui.InputWidget );
15405
15406 /* Static Methods */
15407
15408 /**
15409 * @inheritdoc
15410 */
15411 OO.ui.RadioInputWidget.static.gatherPreInfuseState = function ( node, config ) {
15412 var state = OO.ui.RadioInputWidget.parent.static.gatherPreInfuseState( node, config );
15413 state.checked = config.$input.prop( 'checked' );
15414 return state;
15415 };
15416
15417 /* Methods */
15418
15419 /**
15420 * @inheritdoc
15421 * @protected
15422 */
15423 OO.ui.RadioInputWidget.prototype.getInputElement = function () {
15424 return $( '<input type="radio" />' );
15425 };
15426
15427 /**
15428 * @inheritdoc
15429 */
15430 OO.ui.RadioInputWidget.prototype.onEdit = function () {
15431 // RadioInputWidget doesn't track its state.
15432 };
15433
15434 /**
15435 * Set selection state of this radio button.
15436 *
15437 * @param {boolean} state `true` for selected
15438 * @chainable
15439 */
15440 OO.ui.RadioInputWidget.prototype.setSelected = function ( state ) {
15441 // RadioInputWidget doesn't track its state.
15442 this.$input.prop( 'checked', state );
15443 return this;
15444 };
15445
15446 /**
15447 * Check if this radio button is selected.
15448 *
15449 * @return {boolean} Radio is selected
15450 */
15451 OO.ui.RadioInputWidget.prototype.isSelected = function () {
15452 return this.$input.prop( 'checked' );
15453 };
15454
15455 /**
15456 * @inheritdoc
15457 */
15458 OO.ui.RadioInputWidget.prototype.restorePreInfuseState = function ( state ) {
15459 OO.ui.RadioInputWidget.parent.prototype.restorePreInfuseState.call( this, state );
15460 if ( state.checked !== undefined && state.checked !== this.isSelected() ) {
15461 this.setSelected( state.checked );
15462 }
15463 };
15464
15465 /**
15466 * RadioSelectInputWidget is a {@link OO.ui.RadioSelectWidget RadioSelectWidget} intended to be used
15467 * within a HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with the value
15468 * of a hidden HTML `input` tag. Please see the [OOjs UI documentation on MediaWiki][1] for
15469 * more information about input widgets.
15470 *
15471 * This and OO.ui.DropdownInputWidget support the same configuration options.
15472 *
15473 * @example
15474 * // Example: A RadioSelectInputWidget with three options
15475 * var radioSelectInput = new OO.ui.RadioSelectInputWidget( {
15476 * options: [
15477 * { data: 'a', label: 'First' },
15478 * { data: 'b', label: 'Second'},
15479 * { data: 'c', label: 'Third' }
15480 * ]
15481 * } );
15482 * $( 'body' ).append( radioSelectInput.$element );
15483 *
15484 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
15485 *
15486 * @class
15487 * @extends OO.ui.InputWidget
15488 *
15489 * @constructor
15490 * @param {Object} [config] Configuration options
15491 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
15492 */
15493 OO.ui.RadioSelectInputWidget = function OoUiRadioSelectInputWidget( config ) {
15494 // Configuration initialization
15495 config = config || {};
15496
15497 // Properties (must be done before parent constructor which calls #setDisabled)
15498 this.radioSelectWidget = new OO.ui.RadioSelectWidget();
15499
15500 // Parent constructor
15501 OO.ui.RadioSelectInputWidget.parent.call( this, config );
15502
15503 // Events
15504 this.radioSelectWidget.connect( this, { select: 'onMenuSelect' } );
15505
15506 // Initialization
15507 this.setOptions( config.options || [] );
15508 this.$element
15509 .addClass( 'oo-ui-radioSelectInputWidget' )
15510 .append( this.radioSelectWidget.$element );
15511 };
15512
15513 /* Setup */
15514
15515 OO.inheritClass( OO.ui.RadioSelectInputWidget, OO.ui.InputWidget );
15516
15517 /* Static Properties */
15518
15519 OO.ui.RadioSelectInputWidget.static.supportsSimpleLabel = false;
15520
15521 /* Static Methods */
15522
15523 /**
15524 * @inheritdoc
15525 */
15526 OO.ui.RadioSelectInputWidget.static.gatherPreInfuseState = function ( node, config ) {
15527 var state = OO.ui.RadioSelectInputWidget.parent.static.gatherPreInfuseState( node, config );
15528 state.value = $( node ).find( '.oo-ui-radioInputWidget .oo-ui-inputWidget-input:checked' ).val();
15529 return state;
15530 };
15531
15532 /* Methods */
15533
15534 /**
15535 * @inheritdoc
15536 * @protected
15537 */
15538 OO.ui.RadioSelectInputWidget.prototype.getInputElement = function () {
15539 return $( '<input type="hidden">' );
15540 };
15541
15542 /**
15543 * Handles menu select events.
15544 *
15545 * @private
15546 * @param {OO.ui.RadioOptionWidget} item Selected menu item
15547 */
15548 OO.ui.RadioSelectInputWidget.prototype.onMenuSelect = function ( item ) {
15549 this.setValue( item.getData() );
15550 };
15551
15552 /**
15553 * @inheritdoc
15554 */
15555 OO.ui.RadioSelectInputWidget.prototype.setValue = function ( value ) {
15556 value = this.cleanUpValue( value );
15557 this.radioSelectWidget.selectItemByData( value );
15558 OO.ui.RadioSelectInputWidget.parent.prototype.setValue.call( this, value );
15559 return this;
15560 };
15561
15562 /**
15563 * @inheritdoc
15564 */
15565 OO.ui.RadioSelectInputWidget.prototype.setDisabled = function ( state ) {
15566 this.radioSelectWidget.setDisabled( state );
15567 OO.ui.RadioSelectInputWidget.parent.prototype.setDisabled.call( this, state );
15568 return this;
15569 };
15570
15571 /**
15572 * Set the options available for this input.
15573 *
15574 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
15575 * @chainable
15576 */
15577 OO.ui.RadioSelectInputWidget.prototype.setOptions = function ( options ) {
15578 var
15579 value = this.getValue(),
15580 widget = this;
15581
15582 // Rebuild the radioSelect menu
15583 this.radioSelectWidget
15584 .clearItems()
15585 .addItems( options.map( function ( opt ) {
15586 var optValue = widget.cleanUpValue( opt.data );
15587 return new OO.ui.RadioOptionWidget( {
15588 data: optValue,
15589 label: opt.label !== undefined ? opt.label : optValue
15590 } );
15591 } ) );
15592
15593 // Restore the previous value, or reset to something sensible
15594 if ( this.radioSelectWidget.getItemFromData( value ) ) {
15595 // Previous value is still available, ensure consistency with the radioSelect
15596 this.setValue( value );
15597 } else {
15598 // No longer valid, reset
15599 if ( options.length ) {
15600 this.setValue( options[ 0 ].data );
15601 }
15602 }
15603
15604 return this;
15605 };
15606
15607 /**
15608 * TextInputWidgets, like HTML text inputs, can be configured with options that customize the
15609 * size of the field as well as its presentation. In addition, these widgets can be configured
15610 * with {@link OO.ui.mixin.IconElement icons}, {@link OO.ui.mixin.IndicatorElement indicators}, an optional
15611 * validation-pattern (used to determine if an input value is valid or not) and an input filter,
15612 * which modifies incoming values rather than validating them.
15613 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
15614 *
15615 * This widget can be used inside a HTML form, such as a OO.ui.FormLayout.
15616 *
15617 * @example
15618 * // Example of a text input widget
15619 * var textInput = new OO.ui.TextInputWidget( {
15620 * value: 'Text input'
15621 * } )
15622 * $( 'body' ).append( textInput.$element );
15623 *
15624 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
15625 *
15626 * @class
15627 * @extends OO.ui.InputWidget
15628 * @mixins OO.ui.mixin.IconElement
15629 * @mixins OO.ui.mixin.IndicatorElement
15630 * @mixins OO.ui.mixin.PendingElement
15631 * @mixins OO.ui.mixin.LabelElement
15632 *
15633 * @constructor
15634 * @param {Object} [config] Configuration options
15635 * @cfg {string} [type='text'] The value of the HTML `type` attribute: 'text', 'password', 'search',
15636 * 'email' or 'url'. Ignored if `multiline` is true.
15637 *
15638 * Some values of `type` result in additional behaviors:
15639 *
15640 * - `search`: implies `icon: 'search'` and `indicator: 'clear'`; when clicked, the indicator
15641 * empties the text field
15642 * @cfg {string} [placeholder] Placeholder text
15643 * @cfg {boolean} [autofocus=false] Use an HTML `autofocus` attribute to
15644 * instruct the browser to focus this widget.
15645 * @cfg {boolean} [readOnly=false] Prevent changes to the value of the text input.
15646 * @cfg {number} [maxLength] Maximum number of characters allowed in the input.
15647 * @cfg {boolean} [multiline=false] Allow multiple lines of text
15648 * @cfg {number} [rows] If multiline, number of visible lines in textarea. If used with `autosize`,
15649 * specifies minimum number of rows to display.
15650 * @cfg {boolean} [autosize=false] Automatically resize the text input to fit its content.
15651 * Use the #maxRows config to specify a maximum number of displayed rows.
15652 * @cfg {boolean} [maxRows] Maximum number of rows to display when #autosize is set to true.
15653 * Defaults to the maximum of `10` and `2 * rows`, or `10` if `rows` isn't provided.
15654 * @cfg {string} [labelPosition='after'] The position of the inline label relative to that of
15655 * the value or placeholder text: `'before'` or `'after'`
15656 * @cfg {boolean} [required=false] Mark the field as required. Implies `indicator: 'required'`.
15657 * @cfg {boolean} [autocomplete=true] Should the browser support autocomplete for this field
15658 * @cfg {RegExp|Function|string} [validate] Validation pattern: when string, a symbolic name of a
15659 * pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer'
15660 * (the value must contain only numbers); when RegExp, a regular expression that must match the
15661 * value for it to be considered valid; when Function, a function receiving the value as parameter
15662 * that must return true, or promise resolving to true, for it to be considered valid.
15663 */
15664 OO.ui.TextInputWidget = function OoUiTextInputWidget( config ) {
15665 // Configuration initialization
15666 config = $.extend( {
15667 type: 'text',
15668 labelPosition: 'after'
15669 }, config );
15670 if ( config.type === 'search' ) {
15671 if ( config.icon === undefined ) {
15672 config.icon = 'search';
15673 }
15674 // indicator: 'clear' is set dynamically later, depending on value
15675 }
15676 if ( config.required ) {
15677 if ( config.indicator === undefined ) {
15678 config.indicator = 'required';
15679 }
15680 }
15681
15682 // Parent constructor
15683 OO.ui.TextInputWidget.parent.call( this, config );
15684
15685 // Mixin constructors
15686 OO.ui.mixin.IconElement.call( this, config );
15687 OO.ui.mixin.IndicatorElement.call( this, config );
15688 OO.ui.mixin.PendingElement.call( this, $.extend( {}, config, { $pending: this.$input } ) );
15689 OO.ui.mixin.LabelElement.call( this, config );
15690
15691 // Properties
15692 this.type = this.getSaneType( config );
15693 this.readOnly = false;
15694 this.multiline = !!config.multiline;
15695 this.autosize = !!config.autosize;
15696 this.minRows = config.rows !== undefined ? config.rows : '';
15697 this.maxRows = config.maxRows || Math.max( 2 * ( this.minRows || 0 ), 10 );
15698 this.validate = null;
15699 this.styleHeight = null;
15700 this.scrollWidth = null;
15701
15702 // Clone for resizing
15703 if ( this.autosize ) {
15704 this.$clone = this.$input
15705 .clone()
15706 .insertAfter( this.$input )
15707 .attr( 'aria-hidden', 'true' )
15708 .addClass( 'oo-ui-element-hidden' );
15709 }
15710
15711 this.setValidation( config.validate );
15712 this.setLabelPosition( config.labelPosition );
15713
15714 // Events
15715 this.$input.on( {
15716 keypress: this.onKeyPress.bind( this ),
15717 blur: this.onBlur.bind( this )
15718 } );
15719 this.$input.one( {
15720 focus: this.onElementAttach.bind( this )
15721 } );
15722 this.$icon.on( 'mousedown', this.onIconMouseDown.bind( this ) );
15723 this.$indicator.on( 'mousedown', this.onIndicatorMouseDown.bind( this ) );
15724 this.on( 'labelChange', this.updatePosition.bind( this ) );
15725 this.connect( this, {
15726 change: 'onChange',
15727 disable: 'onDisable'
15728 } );
15729
15730 // Initialization
15731 this.$element
15732 .addClass( 'oo-ui-textInputWidget oo-ui-textInputWidget-type-' + this.type )
15733 .append( this.$icon, this.$indicator );
15734 this.setReadOnly( !!config.readOnly );
15735 this.updateSearchIndicator();
15736 if ( config.placeholder ) {
15737 this.$input.attr( 'placeholder', config.placeholder );
15738 }
15739 if ( config.maxLength !== undefined ) {
15740 this.$input.attr( 'maxlength', config.maxLength );
15741 }
15742 if ( config.autofocus ) {
15743 this.$input.attr( 'autofocus', 'autofocus' );
15744 }
15745 if ( config.required ) {
15746 this.$input.attr( 'required', 'required' );
15747 this.$input.attr( 'aria-required', 'true' );
15748 }
15749 if ( config.autocomplete === false ) {
15750 this.$input.attr( 'autocomplete', 'off' );
15751 // Turning off autocompletion also disables "form caching" when the user navigates to a
15752 // different page and then clicks "Back". Re-enable it when leaving. Borrowed from jQuery UI.
15753 $( window ).on( {
15754 beforeunload: function () {
15755 this.$input.removeAttr( 'autocomplete' );
15756 }.bind( this ),
15757 pageshow: function () {
15758 // Browsers don't seem to actually fire this event on "Back", they instead just reload the
15759 // whole page... it shouldn't hurt, though.
15760 this.$input.attr( 'autocomplete', 'off' );
15761 }.bind( this )
15762 } );
15763 }
15764 if ( this.multiline && config.rows ) {
15765 this.$input.attr( 'rows', config.rows );
15766 }
15767 if ( this.label || config.autosize ) {
15768 this.installParentChangeDetector();
15769 }
15770 };
15771
15772 /* Setup */
15773
15774 OO.inheritClass( OO.ui.TextInputWidget, OO.ui.InputWidget );
15775 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.mixin.IconElement );
15776 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.mixin.IndicatorElement );
15777 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.mixin.PendingElement );
15778 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.mixin.LabelElement );
15779
15780 /* Static Properties */
15781
15782 OO.ui.TextInputWidget.static.validationPatterns = {
15783 'non-empty': /.+/,
15784 integer: /^\d+$/
15785 };
15786
15787 /* Static Methods */
15788
15789 /**
15790 * @inheritdoc
15791 */
15792 OO.ui.TextInputWidget.static.gatherPreInfuseState = function ( node, config ) {
15793 var state = OO.ui.TextInputWidget.parent.static.gatherPreInfuseState( node, config );
15794 if ( config.multiline ) {
15795 state.scrollTop = config.$input.scrollTop();
15796 }
15797 return state;
15798 };
15799
15800 /* Events */
15801
15802 /**
15803 * An `enter` event is emitted when the user presses 'enter' inside the text box.
15804 *
15805 * Not emitted if the input is multiline.
15806 *
15807 * @event enter
15808 */
15809
15810 /**
15811 * A `resize` event is emitted when autosize is set and the widget resizes
15812 *
15813 * @event resize
15814 */
15815
15816 /* Methods */
15817
15818 /**
15819 * Handle icon mouse down events.
15820 *
15821 * @private
15822 * @param {jQuery.Event} e Mouse down event
15823 * @fires icon
15824 */
15825 OO.ui.TextInputWidget.prototype.onIconMouseDown = function ( e ) {
15826 if ( e.which === 1 ) {
15827 this.$input[ 0 ].focus();
15828 return false;
15829 }
15830 };
15831
15832 /**
15833 * Handle indicator mouse down events.
15834 *
15835 * @private
15836 * @param {jQuery.Event} e Mouse down event
15837 * @fires indicator
15838 */
15839 OO.ui.TextInputWidget.prototype.onIndicatorMouseDown = function ( e ) {
15840 if ( e.which === 1 ) {
15841 if ( this.type === 'search' ) {
15842 // Clear the text field
15843 this.setValue( '' );
15844 }
15845 this.$input[ 0 ].focus();
15846 return false;
15847 }
15848 };
15849
15850 /**
15851 * Handle key press events.
15852 *
15853 * @private
15854 * @param {jQuery.Event} e Key press event
15855 * @fires enter If enter key is pressed and input is not multiline
15856 */
15857 OO.ui.TextInputWidget.prototype.onKeyPress = function ( e ) {
15858 if ( e.which === OO.ui.Keys.ENTER && !this.multiline ) {
15859 this.emit( 'enter', e );
15860 }
15861 };
15862
15863 /**
15864 * Handle blur events.
15865 *
15866 * @private
15867 * @param {jQuery.Event} e Blur event
15868 */
15869 OO.ui.TextInputWidget.prototype.onBlur = function () {
15870 this.setValidityFlag();
15871 };
15872
15873 /**
15874 * Handle element attach events.
15875 *
15876 * @private
15877 * @param {jQuery.Event} e Element attach event
15878 */
15879 OO.ui.TextInputWidget.prototype.onElementAttach = function () {
15880 // Any previously calculated size is now probably invalid if we reattached elsewhere
15881 this.valCache = null;
15882 this.adjustSize();
15883 this.positionLabel();
15884 };
15885
15886 /**
15887 * Handle change events.
15888 *
15889 * @param {string} value
15890 * @private
15891 */
15892 OO.ui.TextInputWidget.prototype.onChange = function () {
15893 this.updateSearchIndicator();
15894 this.setValidityFlag();
15895 this.adjustSize();
15896 };
15897
15898 /**
15899 * Handle disable events.
15900 *
15901 * @param {boolean} disabled Element is disabled
15902 * @private
15903 */
15904 OO.ui.TextInputWidget.prototype.onDisable = function () {
15905 this.updateSearchIndicator();
15906 };
15907
15908 /**
15909 * Check if the input is {@link #readOnly read-only}.
15910 *
15911 * @return {boolean}
15912 */
15913 OO.ui.TextInputWidget.prototype.isReadOnly = function () {
15914 return this.readOnly;
15915 };
15916
15917 /**
15918 * Set the {@link #readOnly read-only} state of the input.
15919 *
15920 * @param {boolean} state Make input read-only
15921 * @chainable
15922 */
15923 OO.ui.TextInputWidget.prototype.setReadOnly = function ( state ) {
15924 this.readOnly = !!state;
15925 this.$input.prop( 'readOnly', this.readOnly );
15926 this.updateSearchIndicator();
15927 return this;
15928 };
15929
15930 /**
15931 * Support function for making #onElementAttach work across browsers.
15932 *
15933 * This whole function could be replaced with one line of code using the DOMNodeInsertedIntoDocument
15934 * event, but it's not supported by Firefox and allegedly deprecated, so we only use it as fallback.
15935 *
15936 * Due to MutationObserver performance woes, #onElementAttach is only somewhat reliably called the
15937 * first time that the element gets attached to the documented.
15938 */
15939 OO.ui.TextInputWidget.prototype.installParentChangeDetector = function () {
15940 var mutationObserver, onRemove, topmostNode, fakeParentNode,
15941 MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver,
15942 widget = this;
15943
15944 if ( MutationObserver ) {
15945 // The new way. If only it wasn't so ugly.
15946
15947 if ( this.$element.closest( 'html' ).length ) {
15948 // Widget is attached already, do nothing. This breaks the functionality of this function when
15949 // the widget is detached and reattached. Alas, doing this correctly with MutationObserver
15950 // would require observation of the whole document, which would hurt performance of other,
15951 // more important code.
15952 return;
15953 }
15954
15955 // Find topmost node in the tree
15956 topmostNode = this.$element[ 0 ];
15957 while ( topmostNode.parentNode ) {
15958 topmostNode = topmostNode.parentNode;
15959 }
15960
15961 // We have no way to detect the $element being attached somewhere without observing the entire
15962 // DOM with subtree modifications, which would hurt performance. So we cheat: we hook to the
15963 // parent node of $element, and instead detect when $element is removed from it (and thus
15964 // probably attached somewhere else). If there is no parent, we create a "fake" one. If it
15965 // doesn't get attached, we end up back here and create the parent.
15966
15967 mutationObserver = new MutationObserver( function ( mutations ) {
15968 var i, j, removedNodes;
15969 for ( i = 0; i < mutations.length; i++ ) {
15970 removedNodes = mutations[ i ].removedNodes;
15971 for ( j = 0; j < removedNodes.length; j++ ) {
15972 if ( removedNodes[ j ] === topmostNode ) {
15973 setTimeout( onRemove, 0 );
15974 return;
15975 }
15976 }
15977 }
15978 } );
15979
15980 onRemove = function () {
15981 // If the node was attached somewhere else, report it
15982 if ( widget.$element.closest( 'html' ).length ) {
15983 widget.onElementAttach();
15984 }
15985 mutationObserver.disconnect();
15986 widget.installParentChangeDetector();
15987 };
15988
15989 // Create a fake parent and observe it
15990 fakeParentNode = $( '<div>' ).append( topmostNode )[ 0 ];
15991 mutationObserver.observe( fakeParentNode, { childList: true } );
15992 } else {
15993 // Using the DOMNodeInsertedIntoDocument event is much nicer and less magical, and works for
15994 // detachment and reattachment, but it's not supported by Firefox and allegedly deprecated.
15995 this.$element.on( 'DOMNodeInsertedIntoDocument', this.onElementAttach.bind( this ) );
15996 }
15997 };
15998
15999 /**
16000 * Automatically adjust the size of the text input.
16001 *
16002 * This only affects #multiline inputs that are {@link #autosize autosized}.
16003 *
16004 * @chainable
16005 * @fires resize
16006 */
16007 OO.ui.TextInputWidget.prototype.adjustSize = function () {
16008 var scrollHeight, innerHeight, outerHeight, maxInnerHeight, measurementError,
16009 idealHeight, newHeight, scrollWidth, property;
16010
16011 if ( this.multiline && this.$input.val() !== this.valCache ) {
16012 if ( this.autosize ) {
16013 this.$clone
16014 .val( this.$input.val() )
16015 .attr( 'rows', this.minRows )
16016 // Set inline height property to 0 to measure scroll height
16017 .css( 'height', 0 );
16018
16019 this.$clone.removeClass( 'oo-ui-element-hidden' );
16020
16021 this.valCache = this.$input.val();
16022
16023 scrollHeight = this.$clone[ 0 ].scrollHeight;
16024
16025 // Remove inline height property to measure natural heights
16026 this.$clone.css( 'height', '' );
16027 innerHeight = this.$clone.innerHeight();
16028 outerHeight = this.$clone.outerHeight();
16029
16030 // Measure max rows height
16031 this.$clone
16032 .attr( 'rows', this.maxRows )
16033 .css( 'height', 'auto' )
16034 .val( '' );
16035 maxInnerHeight = this.$clone.innerHeight();
16036
16037 // Difference between reported innerHeight and scrollHeight with no scrollbars present
16038 // Equals 1 on Blink-based browsers and 0 everywhere else
16039 measurementError = maxInnerHeight - this.$clone[ 0 ].scrollHeight;
16040 idealHeight = Math.min( maxInnerHeight, scrollHeight + measurementError );
16041
16042 this.$clone.addClass( 'oo-ui-element-hidden' );
16043
16044 // Only apply inline height when expansion beyond natural height is needed
16045 // Use the difference between the inner and outer height as a buffer
16046 newHeight = idealHeight > innerHeight ? idealHeight + ( outerHeight - innerHeight ) : '';
16047 if ( newHeight !== this.styleHeight ) {
16048 this.$input.css( 'height', newHeight );
16049 this.styleHeight = newHeight;
16050 this.emit( 'resize' );
16051 }
16052 }
16053 scrollWidth = this.$input[ 0 ].offsetWidth - this.$input[ 0 ].clientWidth;
16054 if ( scrollWidth !== this.scrollWidth ) {
16055 property = this.$element.css( 'direction' ) === 'rtl' ? 'left' : 'right';
16056 // Reset
16057 this.$label.css( { right: '', left: '' } );
16058 this.$indicator.css( { right: '', left: '' } );
16059
16060 if ( scrollWidth ) {
16061 this.$indicator.css( property, scrollWidth );
16062 if ( this.labelPosition === 'after' ) {
16063 this.$label.css( property, scrollWidth );
16064 }
16065 }
16066
16067 this.scrollWidth = scrollWidth;
16068 this.positionLabel();
16069 }
16070 }
16071 return this;
16072 };
16073
16074 /**
16075 * @inheritdoc
16076 * @protected
16077 */
16078 OO.ui.TextInputWidget.prototype.getInputElement = function ( config ) {
16079 return config.multiline ?
16080 $( '<textarea>' ) :
16081 $( '<input type="' + this.getSaneType( config ) + '" />' );
16082 };
16083
16084 /**
16085 * Get sanitized value for 'type' for given config.
16086 *
16087 * @param {Object} config Configuration options
16088 * @return {string|null}
16089 * @private
16090 */
16091 OO.ui.TextInputWidget.prototype.getSaneType = function ( config ) {
16092 var type = [ 'text', 'password', 'search', 'email', 'url' ].indexOf( config.type ) !== -1 ?
16093 config.type :
16094 'text';
16095 return config.multiline ? 'multiline' : type;
16096 };
16097
16098 /**
16099 * Check if the input supports multiple lines.
16100 *
16101 * @return {boolean}
16102 */
16103 OO.ui.TextInputWidget.prototype.isMultiline = function () {
16104 return !!this.multiline;
16105 };
16106
16107 /**
16108 * Check if the input automatically adjusts its size.
16109 *
16110 * @return {boolean}
16111 */
16112 OO.ui.TextInputWidget.prototype.isAutosizing = function () {
16113 return !!this.autosize;
16114 };
16115
16116 /**
16117 * Focus the input and select a specified range within the text.
16118 *
16119 * @param {number} from Select from offset
16120 * @param {number} [to] Select to offset, defaults to from
16121 * @chainable
16122 */
16123 OO.ui.TextInputWidget.prototype.selectRange = function ( from, to ) {
16124 var textRange, isBackwards, start, end,
16125 element = this.$input[ 0 ];
16126
16127 to = to || from;
16128
16129 isBackwards = to < from;
16130 start = isBackwards ? to : from;
16131 end = isBackwards ? from : to;
16132
16133 this.focus();
16134
16135 if ( element.setSelectionRange ) {
16136 element.setSelectionRange( start, end, isBackwards ? 'backward' : 'forward' );
16137 } else if ( element.createTextRange ) {
16138 // IE 8 and below
16139 textRange = element.createTextRange();
16140 textRange.collapse( true );
16141 textRange.moveStart( 'character', start );
16142 textRange.moveEnd( 'character', end - start );
16143 textRange.select();
16144 }
16145 return this;
16146 };
16147
16148 /**
16149 * Get the length of the text input value.
16150 *
16151 * This could differ from the length of #getValue if the
16152 * value gets filtered
16153 *
16154 * @return {number} Input length
16155 */
16156 OO.ui.TextInputWidget.prototype.getInputLength = function () {
16157 return this.$input[ 0 ].value.length;
16158 };
16159
16160 /**
16161 * Focus the input and select the entire text.
16162 *
16163 * @chainable
16164 */
16165 OO.ui.TextInputWidget.prototype.select = function () {
16166 return this.selectRange( 0, this.getInputLength() );
16167 };
16168
16169 /**
16170 * Focus the input and move the cursor to the start.
16171 *
16172 * @chainable
16173 */
16174 OO.ui.TextInputWidget.prototype.moveCursorToStart = function () {
16175 return this.selectRange( 0 );
16176 };
16177
16178 /**
16179 * Focus the input and move the cursor to the end.
16180 *
16181 * @chainable
16182 */
16183 OO.ui.TextInputWidget.prototype.moveCursorToEnd = function () {
16184 return this.selectRange( this.getInputLength() );
16185 };
16186
16187 /**
16188 * Set the validation pattern.
16189 *
16190 * The validation pattern is either a regular expression, a function, or the symbolic name of a
16191 * pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer' (the
16192 * value must contain only numbers).
16193 *
16194 * @param {RegExp|Function|string|null} validate Regular expression, function, or the symbolic name
16195 * of a pattern (either ‘integer’ or ‘non-empty’) defined by the class.
16196 */
16197 OO.ui.TextInputWidget.prototype.setValidation = function ( validate ) {
16198 if ( validate instanceof RegExp || validate instanceof Function ) {
16199 this.validate = validate;
16200 } else {
16201 this.validate = this.constructor.static.validationPatterns[ validate ] || /.*/;
16202 }
16203 };
16204
16205 /**
16206 * Sets the 'invalid' flag appropriately.
16207 *
16208 * @param {boolean} [isValid] Optionally override validation result
16209 */
16210 OO.ui.TextInputWidget.prototype.setValidityFlag = function ( isValid ) {
16211 var widget = this,
16212 setFlag = function ( valid ) {
16213 if ( !valid ) {
16214 widget.$input.attr( 'aria-invalid', 'true' );
16215 } else {
16216 widget.$input.removeAttr( 'aria-invalid' );
16217 }
16218 widget.setFlags( { invalid: !valid } );
16219 };
16220
16221 if ( isValid !== undefined ) {
16222 setFlag( isValid );
16223 } else {
16224 this.getValidity().then( function () {
16225 setFlag( true );
16226 }, function () {
16227 setFlag( false );
16228 } );
16229 }
16230 };
16231
16232 /**
16233 * Check if a value is valid.
16234 *
16235 * This method returns a promise that resolves with a boolean `true` if the current value is
16236 * considered valid according to the supplied {@link #validate validation pattern}.
16237 *
16238 * @deprecated
16239 * @return {jQuery.Promise} A promise that resolves to a boolean `true` if the value is valid.
16240 */
16241 OO.ui.TextInputWidget.prototype.isValid = function () {
16242 var result;
16243
16244 if ( this.validate instanceof Function ) {
16245 result = this.validate( this.getValue() );
16246 if ( $.isFunction( result.promise ) ) {
16247 return result.promise();
16248 } else {
16249 return $.Deferred().resolve( !!result ).promise();
16250 }
16251 } else {
16252 return $.Deferred().resolve( !!this.getValue().match( this.validate ) ).promise();
16253 }
16254 };
16255
16256 /**
16257 * Get the validity of current value.
16258 *
16259 * This method returns a promise that resolves if the value is valid and rejects if
16260 * it isn't. Uses the {@link #validate validation pattern} to check for validity.
16261 *
16262 * @return {jQuery.Promise} A promise that resolves if the value is valid, rejects if not.
16263 */
16264 OO.ui.TextInputWidget.prototype.getValidity = function () {
16265 var result, promise;
16266
16267 function rejectOrResolve( valid ) {
16268 if ( valid ) {
16269 return $.Deferred().resolve().promise();
16270 } else {
16271 return $.Deferred().reject().promise();
16272 }
16273 }
16274
16275 if ( this.validate instanceof Function ) {
16276 result = this.validate( this.getValue() );
16277
16278 if ( $.isFunction( result.promise ) ) {
16279 promise = $.Deferred();
16280
16281 result.then( function ( valid ) {
16282 if ( valid ) {
16283 promise.resolve();
16284 } else {
16285 promise.reject();
16286 }
16287 }, function () {
16288 promise.reject();
16289 } );
16290
16291 return promise.promise();
16292 } else {
16293 return rejectOrResolve( result );
16294 }
16295 } else {
16296 return rejectOrResolve( this.getValue().match( this.validate ) );
16297 }
16298 };
16299
16300 /**
16301 * Set the position of the inline label relative to that of the value: `‘before’` or `‘after’`.
16302 *
16303 * @param {string} labelPosition Label position, 'before' or 'after'
16304 * @chainable
16305 */
16306 OO.ui.TextInputWidget.prototype.setLabelPosition = function ( labelPosition ) {
16307 this.labelPosition = labelPosition;
16308 this.updatePosition();
16309 return this;
16310 };
16311
16312 /**
16313 * Deprecated alias of #setLabelPosition
16314 *
16315 * @deprecated Use setLabelPosition instead.
16316 */
16317 OO.ui.TextInputWidget.prototype.setPosition =
16318 OO.ui.TextInputWidget.prototype.setLabelPosition;
16319
16320 /**
16321 * Update the position of the inline label.
16322 *
16323 * This method is called by #setLabelPosition, and can also be called on its own if
16324 * something causes the label to be mispositioned.
16325 *
16326 * @chainable
16327 */
16328 OO.ui.TextInputWidget.prototype.updatePosition = function () {
16329 var after = this.labelPosition === 'after';
16330
16331 this.$element
16332 .toggleClass( 'oo-ui-textInputWidget-labelPosition-after', !!this.label && after )
16333 .toggleClass( 'oo-ui-textInputWidget-labelPosition-before', !!this.label && !after );
16334
16335 this.valCache = null;
16336 this.scrollWidth = null;
16337 this.adjustSize();
16338 this.positionLabel();
16339
16340 return this;
16341 };
16342
16343 /**
16344 * Update the 'clear' indicator displayed on type: 'search' text fields, hiding it when the field is
16345 * already empty or when it's not editable.
16346 */
16347 OO.ui.TextInputWidget.prototype.updateSearchIndicator = function () {
16348 if ( this.type === 'search' ) {
16349 if ( this.getValue() === '' || this.isDisabled() || this.isReadOnly() ) {
16350 this.setIndicator( null );
16351 } else {
16352 this.setIndicator( 'clear' );
16353 }
16354 }
16355 };
16356
16357 /**
16358 * Position the label by setting the correct padding on the input.
16359 *
16360 * @private
16361 * @chainable
16362 */
16363 OO.ui.TextInputWidget.prototype.positionLabel = function () {
16364 var after, rtl, property;
16365 // Clear old values
16366 this.$input
16367 // Clear old values if present
16368 .css( {
16369 'padding-right': '',
16370 'padding-left': ''
16371 } );
16372
16373 if ( this.label ) {
16374 this.$element.append( this.$label );
16375 } else {
16376 this.$label.detach();
16377 return;
16378 }
16379
16380 after = this.labelPosition === 'after';
16381 rtl = this.$element.css( 'direction' ) === 'rtl';
16382 property = after === rtl ? 'padding-left' : 'padding-right';
16383
16384 this.$input.css( property, this.$label.outerWidth( true ) + ( after ? this.scrollWidth : 0 ) );
16385
16386 return this;
16387 };
16388
16389 /**
16390 * @inheritdoc
16391 */
16392 OO.ui.TextInputWidget.prototype.restorePreInfuseState = function ( state ) {
16393 OO.ui.TextInputWidget.parent.prototype.restorePreInfuseState.call( this, state );
16394 if ( state.scrollTop !== undefined ) {
16395 this.$input.scrollTop( state.scrollTop );
16396 }
16397 };
16398
16399 /**
16400 * ComboBoxWidgets combine a {@link OO.ui.TextInputWidget text input} (where a value
16401 * can be entered manually) and a {@link OO.ui.MenuSelectWidget menu of options} (from which
16402 * a value can be chosen instead). Users can choose options from the combo box in one of two ways:
16403 *
16404 * - by typing a value in the text input field. If the value exactly matches the value of a menu
16405 * option, that option will appear to be selected.
16406 * - by choosing a value from the menu. The value of the chosen option will then appear in the text
16407 * input field.
16408 *
16409 * For more information about menus and options, please see the [OOjs UI documentation on MediaWiki][1].
16410 *
16411 * @example
16412 * // Example: A ComboBoxWidget.
16413 * var comboBox = new OO.ui.ComboBoxWidget( {
16414 * label: 'ComboBoxWidget',
16415 * input: { value: 'Option One' },
16416 * menu: {
16417 * items: [
16418 * new OO.ui.MenuOptionWidget( {
16419 * data: 'Option 1',
16420 * label: 'Option One'
16421 * } ),
16422 * new OO.ui.MenuOptionWidget( {
16423 * data: 'Option 2',
16424 * label: 'Option Two'
16425 * } ),
16426 * new OO.ui.MenuOptionWidget( {
16427 * data: 'Option 3',
16428 * label: 'Option Three'
16429 * } ),
16430 * new OO.ui.MenuOptionWidget( {
16431 * data: 'Option 4',
16432 * label: 'Option Four'
16433 * } ),
16434 * new OO.ui.MenuOptionWidget( {
16435 * data: 'Option 5',
16436 * label: 'Option Five'
16437 * } )
16438 * ]
16439 * }
16440 * } );
16441 * $( 'body' ).append( comboBox.$element );
16442 *
16443 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
16444 *
16445 * @class
16446 * @extends OO.ui.Widget
16447 * @mixins OO.ui.mixin.TabIndexedElement
16448 *
16449 * @constructor
16450 * @param {Object} [config] Configuration options
16451 * @cfg {Object} [menu] Configuration options to pass to the {@link OO.ui.FloatingMenuSelectWidget menu select widget}.
16452 * @cfg {Object} [input] Configuration options to pass to the {@link OO.ui.TextInputWidget text input widget}.
16453 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
16454 * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
16455 * containing `<div>` and has a larger area. By default, the menu uses relative positioning.
16456 */
16457 OO.ui.ComboBoxWidget = function OoUiComboBoxWidget( config ) {
16458 // Configuration initialization
16459 config = config || {};
16460
16461 // Parent constructor
16462 OO.ui.ComboBoxWidget.parent.call( this, config );
16463
16464 // Properties (must be set before TabIndexedElement constructor call)
16465 this.$indicator = this.$( '<span>' );
16466
16467 // Mixin constructors
16468 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$indicator } ) );
16469
16470 // Properties
16471 this.$overlay = config.$overlay || this.$element;
16472 this.input = new OO.ui.TextInputWidget( $.extend(
16473 {
16474 indicator: 'down',
16475 $indicator: this.$indicator,
16476 disabled: this.isDisabled()
16477 },
16478 config.input
16479 ) );
16480 this.input.$input.eq( 0 ).attr( {
16481 role: 'combobox',
16482 'aria-autocomplete': 'list'
16483 } );
16484 this.menu = new OO.ui.FloatingMenuSelectWidget( $.extend(
16485 {
16486 widget: this,
16487 input: this.input,
16488 $container: this.input.$element,
16489 disabled: this.isDisabled()
16490 },
16491 config.menu
16492 ) );
16493
16494 // Events
16495 this.$indicator.on( {
16496 click: this.onClick.bind( this ),
16497 keypress: this.onKeyPress.bind( this )
16498 } );
16499 this.input.connect( this, {
16500 change: 'onInputChange',
16501 enter: 'onInputEnter'
16502 } );
16503 this.menu.connect( this, {
16504 choose: 'onMenuChoose',
16505 add: 'onMenuItemsChange',
16506 remove: 'onMenuItemsChange'
16507 } );
16508
16509 // Initialization
16510 this.$element.addClass( 'oo-ui-comboBoxWidget' ).append( this.input.$element );
16511 this.$overlay.append( this.menu.$element );
16512 this.onMenuItemsChange();
16513 };
16514
16515 /* Setup */
16516
16517 OO.inheritClass( OO.ui.ComboBoxWidget, OO.ui.Widget );
16518 OO.mixinClass( OO.ui.ComboBoxWidget, OO.ui.mixin.TabIndexedElement );
16519
16520 /* Methods */
16521
16522 /**
16523 * Get the combobox's menu.
16524 * @return {OO.ui.FloatingMenuSelectWidget} Menu widget
16525 */
16526 OO.ui.ComboBoxWidget.prototype.getMenu = function () {
16527 return this.menu;
16528 };
16529
16530 /**
16531 * Get the combobox's text input widget.
16532 * @return {OO.ui.TextInputWidget} Text input widget
16533 */
16534 OO.ui.ComboBoxWidget.prototype.getInput = function () {
16535 return this.input;
16536 };
16537
16538 /**
16539 * Handle input change events.
16540 *
16541 * @private
16542 * @param {string} value New value
16543 */
16544 OO.ui.ComboBoxWidget.prototype.onInputChange = function ( value ) {
16545 var match = this.menu.getItemFromData( value );
16546
16547 this.menu.selectItem( match );
16548 if ( this.menu.getHighlightedItem() ) {
16549 this.menu.highlightItem( match );
16550 }
16551
16552 if ( !this.isDisabled() ) {
16553 this.menu.toggle( true );
16554 }
16555 };
16556
16557 /**
16558 * Handle mouse click events.
16559 *
16560 * @private
16561 * @param {jQuery.Event} e Mouse click event
16562 */
16563 OO.ui.ComboBoxWidget.prototype.onClick = function ( e ) {
16564 if ( !this.isDisabled() && e.which === 1 ) {
16565 this.menu.toggle();
16566 this.input.$input[ 0 ].focus();
16567 }
16568 return false;
16569 };
16570
16571 /**
16572 * Handle key press events.
16573 *
16574 * @private
16575 * @param {jQuery.Event} e Key press event
16576 */
16577 OO.ui.ComboBoxWidget.prototype.onKeyPress = function ( e ) {
16578 if ( !this.isDisabled() && ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER ) ) {
16579 this.menu.toggle();
16580 this.input.$input[ 0 ].focus();
16581 return false;
16582 }
16583 };
16584
16585 /**
16586 * Handle input enter events.
16587 *
16588 * @private
16589 */
16590 OO.ui.ComboBoxWidget.prototype.onInputEnter = function () {
16591 if ( !this.isDisabled() ) {
16592 this.menu.toggle( false );
16593 }
16594 };
16595
16596 /**
16597 * Handle menu choose events.
16598 *
16599 * @private
16600 * @param {OO.ui.OptionWidget} item Chosen item
16601 */
16602 OO.ui.ComboBoxWidget.prototype.onMenuChoose = function ( item ) {
16603 this.input.setValue( item.getData() );
16604 };
16605
16606 /**
16607 * Handle menu item change events.
16608 *
16609 * @private
16610 */
16611 OO.ui.ComboBoxWidget.prototype.onMenuItemsChange = function () {
16612 var match = this.menu.getItemFromData( this.input.getValue() );
16613 this.menu.selectItem( match );
16614 if ( this.menu.getHighlightedItem() ) {
16615 this.menu.highlightItem( match );
16616 }
16617 this.$element.toggleClass( 'oo-ui-comboBoxWidget-empty', this.menu.isEmpty() );
16618 };
16619
16620 /**
16621 * @inheritdoc
16622 */
16623 OO.ui.ComboBoxWidget.prototype.setDisabled = function ( disabled ) {
16624 // Parent method
16625 OO.ui.ComboBoxWidget.parent.prototype.setDisabled.call( this, disabled );
16626
16627 if ( this.input ) {
16628 this.input.setDisabled( this.isDisabled() );
16629 }
16630 if ( this.menu ) {
16631 this.menu.setDisabled( this.isDisabled() );
16632 }
16633
16634 return this;
16635 };
16636
16637 /**
16638 * LabelWidgets help identify the function of interface elements. Each LabelWidget can
16639 * be configured with a `label` option that is set to a string, a label node, or a function:
16640 *
16641 * - String: a plaintext string
16642 * - jQuery selection: a jQuery selection, used for anything other than a plaintext label, e.g., a
16643 * label that includes a link or special styling, such as a gray color or additional graphical elements.
16644 * - Function: a function that will produce a string in the future. Functions are used
16645 * in cases where the value of the label is not currently defined.
16646 *
16647 * In addition, the LabelWidget can be associated with an {@link OO.ui.InputWidget input widget}, which
16648 * will come into focus when the label is clicked.
16649 *
16650 * @example
16651 * // Examples of LabelWidgets
16652 * var label1 = new OO.ui.LabelWidget( {
16653 * label: 'plaintext label'
16654 * } );
16655 * var label2 = new OO.ui.LabelWidget( {
16656 * label: $( '<a href="default.html">jQuery label</a>' )
16657 * } );
16658 * // Create a fieldset layout with fields for each example
16659 * var fieldset = new OO.ui.FieldsetLayout();
16660 * fieldset.addItems( [
16661 * new OO.ui.FieldLayout( label1 ),
16662 * new OO.ui.FieldLayout( label2 )
16663 * ] );
16664 * $( 'body' ).append( fieldset.$element );
16665 *
16666 * @class
16667 * @extends OO.ui.Widget
16668 * @mixins OO.ui.mixin.LabelElement
16669 *
16670 * @constructor
16671 * @param {Object} [config] Configuration options
16672 * @cfg {OO.ui.InputWidget} [input] {@link OO.ui.InputWidget Input widget} that uses the label.
16673 * Clicking the label will focus the specified input field.
16674 */
16675 OO.ui.LabelWidget = function OoUiLabelWidget( config ) {
16676 // Configuration initialization
16677 config = config || {};
16678
16679 // Parent constructor
16680 OO.ui.LabelWidget.parent.call( this, config );
16681
16682 // Mixin constructors
16683 OO.ui.mixin.LabelElement.call( this, $.extend( {}, config, { $label: this.$element } ) );
16684 OO.ui.mixin.TitledElement.call( this, config );
16685
16686 // Properties
16687 this.input = config.input;
16688
16689 // Events
16690 if ( this.input instanceof OO.ui.InputWidget ) {
16691 this.$element.on( 'click', this.onClick.bind( this ) );
16692 }
16693
16694 // Initialization
16695 this.$element.addClass( 'oo-ui-labelWidget' );
16696 };
16697
16698 /* Setup */
16699
16700 OO.inheritClass( OO.ui.LabelWidget, OO.ui.Widget );
16701 OO.mixinClass( OO.ui.LabelWidget, OO.ui.mixin.LabelElement );
16702 OO.mixinClass( OO.ui.LabelWidget, OO.ui.mixin.TitledElement );
16703
16704 /* Static Properties */
16705
16706 OO.ui.LabelWidget.static.tagName = 'span';
16707
16708 /* Methods */
16709
16710 /**
16711 * Handles label mouse click events.
16712 *
16713 * @private
16714 * @param {jQuery.Event} e Mouse click event
16715 */
16716 OO.ui.LabelWidget.prototype.onClick = function () {
16717 this.input.simulateLabelClick();
16718 return false;
16719 };
16720
16721 /**
16722 * OptionWidgets are special elements that can be selected and configured with data. The
16723 * data is often unique for each option, but it does not have to be. OptionWidgets are used
16724 * with OO.ui.SelectWidget to create a selection of mutually exclusive options. For more information
16725 * and examples, please see the [OOjs UI documentation on MediaWiki][1].
16726 *
16727 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
16728 *
16729 * @class
16730 * @extends OO.ui.Widget
16731 * @mixins OO.ui.mixin.LabelElement
16732 * @mixins OO.ui.mixin.FlaggedElement
16733 *
16734 * @constructor
16735 * @param {Object} [config] Configuration options
16736 */
16737 OO.ui.OptionWidget = function OoUiOptionWidget( config ) {
16738 // Configuration initialization
16739 config = config || {};
16740
16741 // Parent constructor
16742 OO.ui.OptionWidget.parent.call( this, config );
16743
16744 // Mixin constructors
16745 OO.ui.mixin.ItemWidget.call( this );
16746 OO.ui.mixin.LabelElement.call( this, config );
16747 OO.ui.mixin.FlaggedElement.call( this, config );
16748
16749 // Properties
16750 this.selected = false;
16751 this.highlighted = false;
16752 this.pressed = false;
16753
16754 // Initialization
16755 this.$element
16756 .data( 'oo-ui-optionWidget', this )
16757 .attr( 'role', 'option' )
16758 .attr( 'aria-selected', 'false' )
16759 .addClass( 'oo-ui-optionWidget' )
16760 .append( this.$label );
16761 };
16762
16763 /* Setup */
16764
16765 OO.inheritClass( OO.ui.OptionWidget, OO.ui.Widget );
16766 OO.mixinClass( OO.ui.OptionWidget, OO.ui.mixin.ItemWidget );
16767 OO.mixinClass( OO.ui.OptionWidget, OO.ui.mixin.LabelElement );
16768 OO.mixinClass( OO.ui.OptionWidget, OO.ui.mixin.FlaggedElement );
16769
16770 /* Static Properties */
16771
16772 OO.ui.OptionWidget.static.selectable = true;
16773
16774 OO.ui.OptionWidget.static.highlightable = true;
16775
16776 OO.ui.OptionWidget.static.pressable = true;
16777
16778 OO.ui.OptionWidget.static.scrollIntoViewOnSelect = false;
16779
16780 /* Methods */
16781
16782 /**
16783 * Check if the option can be selected.
16784 *
16785 * @return {boolean} Item is selectable
16786 */
16787 OO.ui.OptionWidget.prototype.isSelectable = function () {
16788 return this.constructor.static.selectable && !this.isDisabled() && this.isVisible();
16789 };
16790
16791 /**
16792 * Check if the option can be highlighted. A highlight indicates that the option
16793 * may be selected when a user presses enter or clicks. Disabled items cannot
16794 * be highlighted.
16795 *
16796 * @return {boolean} Item is highlightable
16797 */
16798 OO.ui.OptionWidget.prototype.isHighlightable = function () {
16799 return this.constructor.static.highlightable && !this.isDisabled() && this.isVisible();
16800 };
16801
16802 /**
16803 * Check if the option can be pressed. The pressed state occurs when a user mouses
16804 * down on an item, but has not yet let go of the mouse.
16805 *
16806 * @return {boolean} Item is pressable
16807 */
16808 OO.ui.OptionWidget.prototype.isPressable = function () {
16809 return this.constructor.static.pressable && !this.isDisabled() && this.isVisible();
16810 };
16811
16812 /**
16813 * Check if the option is selected.
16814 *
16815 * @return {boolean} Item is selected
16816 */
16817 OO.ui.OptionWidget.prototype.isSelected = function () {
16818 return this.selected;
16819 };
16820
16821 /**
16822 * Check if the option is highlighted. A highlight indicates that the
16823 * item may be selected when a user presses enter or clicks.
16824 *
16825 * @return {boolean} Item is highlighted
16826 */
16827 OO.ui.OptionWidget.prototype.isHighlighted = function () {
16828 return this.highlighted;
16829 };
16830
16831 /**
16832 * Check if the option is pressed. The pressed state occurs when a user mouses
16833 * down on an item, but has not yet let go of the mouse. The item may appear
16834 * selected, but it will not be selected until the user releases the mouse.
16835 *
16836 * @return {boolean} Item is pressed
16837 */
16838 OO.ui.OptionWidget.prototype.isPressed = function () {
16839 return this.pressed;
16840 };
16841
16842 /**
16843 * Set the option’s selected state. In general, all modifications to the selection
16844 * should be handled by the SelectWidget’s {@link OO.ui.SelectWidget#selectItem selectItem( [item] )}
16845 * method instead of this method.
16846 *
16847 * @param {boolean} [state=false] Select option
16848 * @chainable
16849 */
16850 OO.ui.OptionWidget.prototype.setSelected = function ( state ) {
16851 if ( this.constructor.static.selectable ) {
16852 this.selected = !!state;
16853 this.$element
16854 .toggleClass( 'oo-ui-optionWidget-selected', state )
16855 .attr( 'aria-selected', state.toString() );
16856 if ( state && this.constructor.static.scrollIntoViewOnSelect ) {
16857 this.scrollElementIntoView();
16858 }
16859 this.updateThemeClasses();
16860 }
16861 return this;
16862 };
16863
16864 /**
16865 * Set the option’s highlighted state. In general, all programmatic
16866 * modifications to the highlight should be handled by the
16867 * SelectWidget’s {@link OO.ui.SelectWidget#highlightItem highlightItem( [item] )}
16868 * method instead of this method.
16869 *
16870 * @param {boolean} [state=false] Highlight option
16871 * @chainable
16872 */
16873 OO.ui.OptionWidget.prototype.setHighlighted = function ( state ) {
16874 if ( this.constructor.static.highlightable ) {
16875 this.highlighted = !!state;
16876 this.$element.toggleClass( 'oo-ui-optionWidget-highlighted', state );
16877 this.updateThemeClasses();
16878 }
16879 return this;
16880 };
16881
16882 /**
16883 * Set the option’s pressed state. In general, all
16884 * programmatic modifications to the pressed state should be handled by the
16885 * SelectWidget’s {@link OO.ui.SelectWidget#pressItem pressItem( [item] )}
16886 * method instead of this method.
16887 *
16888 * @param {boolean} [state=false] Press option
16889 * @chainable
16890 */
16891 OO.ui.OptionWidget.prototype.setPressed = function ( state ) {
16892 if ( this.constructor.static.pressable ) {
16893 this.pressed = !!state;
16894 this.$element.toggleClass( 'oo-ui-optionWidget-pressed', state );
16895 this.updateThemeClasses();
16896 }
16897 return this;
16898 };
16899
16900 /**
16901 * DecoratedOptionWidgets are {@link OO.ui.OptionWidget options} that can be configured
16902 * with an {@link OO.ui.mixin.IconElement icon} and/or {@link OO.ui.mixin.IndicatorElement indicator}.
16903 * This class is used with OO.ui.SelectWidget to create a selection of mutually exclusive
16904 * options. For more information about options and selects, please see the
16905 * [OOjs UI documentation on MediaWiki][1].
16906 *
16907 * @example
16908 * // Decorated options in a select widget
16909 * var select = new OO.ui.SelectWidget( {
16910 * items: [
16911 * new OO.ui.DecoratedOptionWidget( {
16912 * data: 'a',
16913 * label: 'Option with icon',
16914 * icon: 'help'
16915 * } ),
16916 * new OO.ui.DecoratedOptionWidget( {
16917 * data: 'b',
16918 * label: 'Option with indicator',
16919 * indicator: 'next'
16920 * } )
16921 * ]
16922 * } );
16923 * $( 'body' ).append( select.$element );
16924 *
16925 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
16926 *
16927 * @class
16928 * @extends OO.ui.OptionWidget
16929 * @mixins OO.ui.mixin.IconElement
16930 * @mixins OO.ui.mixin.IndicatorElement
16931 *
16932 * @constructor
16933 * @param {Object} [config] Configuration options
16934 */
16935 OO.ui.DecoratedOptionWidget = function OoUiDecoratedOptionWidget( config ) {
16936 // Parent constructor
16937 OO.ui.DecoratedOptionWidget.parent.call( this, config );
16938
16939 // Mixin constructors
16940 OO.ui.mixin.IconElement.call( this, config );
16941 OO.ui.mixin.IndicatorElement.call( this, config );
16942
16943 // Initialization
16944 this.$element
16945 .addClass( 'oo-ui-decoratedOptionWidget' )
16946 .prepend( this.$icon )
16947 .append( this.$indicator );
16948 };
16949
16950 /* Setup */
16951
16952 OO.inheritClass( OO.ui.DecoratedOptionWidget, OO.ui.OptionWidget );
16953 OO.mixinClass( OO.ui.DecoratedOptionWidget, OO.ui.mixin.IconElement );
16954 OO.mixinClass( OO.ui.DecoratedOptionWidget, OO.ui.mixin.IndicatorElement );
16955
16956 /**
16957 * ButtonOptionWidget is a special type of {@link OO.ui.mixin.ButtonElement button element} that
16958 * can be selected and configured with data. The class is
16959 * used with OO.ui.ButtonSelectWidget to create a selection of button options. Please see the
16960 * [OOjs UI documentation on MediaWiki] [1] for more information.
16961 *
16962 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Button_selects_and_options
16963 *
16964 * @class
16965 * @extends OO.ui.DecoratedOptionWidget
16966 * @mixins OO.ui.mixin.ButtonElement
16967 * @mixins OO.ui.mixin.TabIndexedElement
16968 * @mixins OO.ui.mixin.TitledElement
16969 *
16970 * @constructor
16971 * @param {Object} [config] Configuration options
16972 */
16973 OO.ui.ButtonOptionWidget = function OoUiButtonOptionWidget( config ) {
16974 // Configuration initialization
16975 config = config || {};
16976
16977 // Parent constructor
16978 OO.ui.ButtonOptionWidget.parent.call( this, config );
16979
16980 // Mixin constructors
16981 OO.ui.mixin.ButtonElement.call( this, config );
16982 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$button } ) );
16983 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, {
16984 $tabIndexed: this.$button,
16985 tabIndex: -1
16986 } ) );
16987
16988 // Initialization
16989 this.$element.addClass( 'oo-ui-buttonOptionWidget' );
16990 this.$button.append( this.$element.contents() );
16991 this.$element.append( this.$button );
16992 };
16993
16994 /* Setup */
16995
16996 OO.inheritClass( OO.ui.ButtonOptionWidget, OO.ui.DecoratedOptionWidget );
16997 OO.mixinClass( OO.ui.ButtonOptionWidget, OO.ui.mixin.ButtonElement );
16998 OO.mixinClass( OO.ui.ButtonOptionWidget, OO.ui.mixin.TitledElement );
16999 OO.mixinClass( OO.ui.ButtonOptionWidget, OO.ui.mixin.TabIndexedElement );
17000
17001 /* Static Properties */
17002
17003 // Allow button mouse down events to pass through so they can be handled by the parent select widget
17004 OO.ui.ButtonOptionWidget.static.cancelButtonMouseDownEvents = false;
17005
17006 OO.ui.ButtonOptionWidget.static.highlightable = false;
17007
17008 /* Methods */
17009
17010 /**
17011 * @inheritdoc
17012 */
17013 OO.ui.ButtonOptionWidget.prototype.setSelected = function ( state ) {
17014 OO.ui.ButtonOptionWidget.parent.prototype.setSelected.call( this, state );
17015
17016 if ( this.constructor.static.selectable ) {
17017 this.setActive( state );
17018 }
17019
17020 return this;
17021 };
17022
17023 /**
17024 * RadioOptionWidget is an option widget that looks like a radio button.
17025 * The class is used with OO.ui.RadioSelectWidget to create a selection of radio options.
17026 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information.
17027 *
17028 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Button_selects_and_option
17029 *
17030 * @class
17031 * @extends OO.ui.OptionWidget
17032 *
17033 * @constructor
17034 * @param {Object} [config] Configuration options
17035 */
17036 OO.ui.RadioOptionWidget = function OoUiRadioOptionWidget( config ) {
17037 // Configuration initialization
17038 config = config || {};
17039
17040 // Properties (must be done before parent constructor which calls #setDisabled)
17041 this.radio = new OO.ui.RadioInputWidget( { value: config.data, tabIndex: -1 } );
17042
17043 // Parent constructor
17044 OO.ui.RadioOptionWidget.parent.call( this, config );
17045
17046 // Events
17047 this.radio.$input.on( 'focus', this.onInputFocus.bind( this ) );
17048
17049 // Initialization
17050 // Remove implicit role, we're handling it ourselves
17051 this.radio.$input.attr( 'role', 'presentation' );
17052 this.$element
17053 .addClass( 'oo-ui-radioOptionWidget' )
17054 .attr( 'role', 'radio' )
17055 .attr( 'aria-checked', 'false' )
17056 .removeAttr( 'aria-selected' )
17057 .prepend( this.radio.$element );
17058 };
17059
17060 /* Setup */
17061
17062 OO.inheritClass( OO.ui.RadioOptionWidget, OO.ui.OptionWidget );
17063
17064 /* Static Properties */
17065
17066 OO.ui.RadioOptionWidget.static.highlightable = false;
17067
17068 OO.ui.RadioOptionWidget.static.scrollIntoViewOnSelect = true;
17069
17070 OO.ui.RadioOptionWidget.static.pressable = false;
17071
17072 OO.ui.RadioOptionWidget.static.tagName = 'label';
17073
17074 /* Methods */
17075
17076 /**
17077 * @param {jQuery.Event} e Focus event
17078 * @private
17079 */
17080 OO.ui.RadioOptionWidget.prototype.onInputFocus = function () {
17081 this.radio.$input.blur();
17082 this.$element.parent().focus();
17083 };
17084
17085 /**
17086 * @inheritdoc
17087 */
17088 OO.ui.RadioOptionWidget.prototype.setSelected = function ( state ) {
17089 OO.ui.RadioOptionWidget.parent.prototype.setSelected.call( this, state );
17090
17091 this.radio.setSelected( state );
17092 this.$element
17093 .attr( 'aria-checked', state.toString() )
17094 .removeAttr( 'aria-selected' );
17095
17096 return this;
17097 };
17098
17099 /**
17100 * @inheritdoc
17101 */
17102 OO.ui.RadioOptionWidget.prototype.setDisabled = function ( disabled ) {
17103 OO.ui.RadioOptionWidget.parent.prototype.setDisabled.call( this, disabled );
17104
17105 this.radio.setDisabled( this.isDisabled() );
17106
17107 return this;
17108 };
17109
17110 /**
17111 * MenuOptionWidget is an option widget that looks like a menu item. The class is used with
17112 * OO.ui.MenuSelectWidget to create a menu of mutually exclusive options. Please see
17113 * the [OOjs UI documentation on MediaWiki] [1] for more information.
17114 *
17115 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
17116 *
17117 * @class
17118 * @extends OO.ui.DecoratedOptionWidget
17119 *
17120 * @constructor
17121 * @param {Object} [config] Configuration options
17122 */
17123 OO.ui.MenuOptionWidget = function OoUiMenuOptionWidget( config ) {
17124 // Configuration initialization
17125 config = $.extend( { icon: 'check' }, config );
17126
17127 // Parent constructor
17128 OO.ui.MenuOptionWidget.parent.call( this, config );
17129
17130 // Initialization
17131 this.$element
17132 .attr( 'role', 'menuitem' )
17133 .addClass( 'oo-ui-menuOptionWidget' );
17134 };
17135
17136 /* Setup */
17137
17138 OO.inheritClass( OO.ui.MenuOptionWidget, OO.ui.DecoratedOptionWidget );
17139
17140 /* Static Properties */
17141
17142 OO.ui.MenuOptionWidget.static.scrollIntoViewOnSelect = true;
17143
17144 /**
17145 * MenuSectionOptionWidgets are used inside {@link OO.ui.MenuSelectWidget menu select widgets} to group one or more related
17146 * {@link OO.ui.MenuOptionWidget menu options}. MenuSectionOptionWidgets cannot be highlighted or selected.
17147 *
17148 * @example
17149 * var myDropdown = new OO.ui.DropdownWidget( {
17150 * menu: {
17151 * items: [
17152 * new OO.ui.MenuSectionOptionWidget( {
17153 * label: 'Dogs'
17154 * } ),
17155 * new OO.ui.MenuOptionWidget( {
17156 * data: 'corgi',
17157 * label: 'Welsh Corgi'
17158 * } ),
17159 * new OO.ui.MenuOptionWidget( {
17160 * data: 'poodle',
17161 * label: 'Standard Poodle'
17162 * } ),
17163 * new OO.ui.MenuSectionOptionWidget( {
17164 * label: 'Cats'
17165 * } ),
17166 * new OO.ui.MenuOptionWidget( {
17167 * data: 'lion',
17168 * label: 'Lion'
17169 * } )
17170 * ]
17171 * }
17172 * } );
17173 * $( 'body' ).append( myDropdown.$element );
17174 *
17175 * @class
17176 * @extends OO.ui.DecoratedOptionWidget
17177 *
17178 * @constructor
17179 * @param {Object} [config] Configuration options
17180 */
17181 OO.ui.MenuSectionOptionWidget = function OoUiMenuSectionOptionWidget( config ) {
17182 // Parent constructor
17183 OO.ui.MenuSectionOptionWidget.parent.call( this, config );
17184
17185 // Initialization
17186 this.$element.addClass( 'oo-ui-menuSectionOptionWidget' );
17187 };
17188
17189 /* Setup */
17190
17191 OO.inheritClass( OO.ui.MenuSectionOptionWidget, OO.ui.DecoratedOptionWidget );
17192
17193 /* Static Properties */
17194
17195 OO.ui.MenuSectionOptionWidget.static.selectable = false;
17196
17197 OO.ui.MenuSectionOptionWidget.static.highlightable = false;
17198
17199 /**
17200 * OutlineOptionWidget is an item in an {@link OO.ui.OutlineSelectWidget OutlineSelectWidget}.
17201 *
17202 * Currently, this class is only used by {@link OO.ui.BookletLayout booklet layouts}, which contain
17203 * {@link OO.ui.PageLayout page layouts}. See {@link OO.ui.BookletLayout BookletLayout}
17204 * for an example.
17205 *
17206 * @class
17207 * @extends OO.ui.DecoratedOptionWidget
17208 *
17209 * @constructor
17210 * @param {Object} [config] Configuration options
17211 * @cfg {number} [level] Indentation level
17212 * @cfg {boolean} [movable] Allow modification from {@link OO.ui.OutlineControlsWidget outline controls}.
17213 */
17214 OO.ui.OutlineOptionWidget = function OoUiOutlineOptionWidget( config ) {
17215 // Configuration initialization
17216 config = config || {};
17217
17218 // Parent constructor
17219 OO.ui.OutlineOptionWidget.parent.call( this, config );
17220
17221 // Properties
17222 this.level = 0;
17223 this.movable = !!config.movable;
17224 this.removable = !!config.removable;
17225
17226 // Initialization
17227 this.$element.addClass( 'oo-ui-outlineOptionWidget' );
17228 this.setLevel( config.level );
17229 };
17230
17231 /* Setup */
17232
17233 OO.inheritClass( OO.ui.OutlineOptionWidget, OO.ui.DecoratedOptionWidget );
17234
17235 /* Static Properties */
17236
17237 OO.ui.OutlineOptionWidget.static.highlightable = false;
17238
17239 OO.ui.OutlineOptionWidget.static.scrollIntoViewOnSelect = true;
17240
17241 OO.ui.OutlineOptionWidget.static.levelClass = 'oo-ui-outlineOptionWidget-level-';
17242
17243 OO.ui.OutlineOptionWidget.static.levels = 3;
17244
17245 /* Methods */
17246
17247 /**
17248 * Check if item is movable.
17249 *
17250 * Movability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
17251 *
17252 * @return {boolean} Item is movable
17253 */
17254 OO.ui.OutlineOptionWidget.prototype.isMovable = function () {
17255 return this.movable;
17256 };
17257
17258 /**
17259 * Check if item is removable.
17260 *
17261 * Removability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
17262 *
17263 * @return {boolean} Item is removable
17264 */
17265 OO.ui.OutlineOptionWidget.prototype.isRemovable = function () {
17266 return this.removable;
17267 };
17268
17269 /**
17270 * Get indentation level.
17271 *
17272 * @return {number} Indentation level
17273 */
17274 OO.ui.OutlineOptionWidget.prototype.getLevel = function () {
17275 return this.level;
17276 };
17277
17278 /**
17279 * Set movability.
17280 *
17281 * Movability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
17282 *
17283 * @param {boolean} movable Item is movable
17284 * @chainable
17285 */
17286 OO.ui.OutlineOptionWidget.prototype.setMovable = function ( movable ) {
17287 this.movable = !!movable;
17288 this.updateThemeClasses();
17289 return this;
17290 };
17291
17292 /**
17293 * Set removability.
17294 *
17295 * Removability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
17296 *
17297 * @param {boolean} movable Item is removable
17298 * @chainable
17299 */
17300 OO.ui.OutlineOptionWidget.prototype.setRemovable = function ( removable ) {
17301 this.removable = !!removable;
17302 this.updateThemeClasses();
17303 return this;
17304 };
17305
17306 /**
17307 * Set indentation level.
17308 *
17309 * @param {number} [level=0] Indentation level, in the range of [0,#maxLevel]
17310 * @chainable
17311 */
17312 OO.ui.OutlineOptionWidget.prototype.setLevel = function ( level ) {
17313 var levels = this.constructor.static.levels,
17314 levelClass = this.constructor.static.levelClass,
17315 i = levels;
17316
17317 this.level = level ? Math.max( 0, Math.min( levels - 1, level ) ) : 0;
17318 while ( i-- ) {
17319 if ( this.level === i ) {
17320 this.$element.addClass( levelClass + i );
17321 } else {
17322 this.$element.removeClass( levelClass + i );
17323 }
17324 }
17325 this.updateThemeClasses();
17326
17327 return this;
17328 };
17329
17330 /**
17331 * TabOptionWidget is an item in a {@link OO.ui.TabSelectWidget TabSelectWidget}.
17332 *
17333 * Currently, this class is only used by {@link OO.ui.IndexLayout index layouts}, which contain
17334 * {@link OO.ui.CardLayout card layouts}. See {@link OO.ui.IndexLayout IndexLayout}
17335 * for an example.
17336 *
17337 * @class
17338 * @extends OO.ui.OptionWidget
17339 *
17340 * @constructor
17341 * @param {Object} [config] Configuration options
17342 */
17343 OO.ui.TabOptionWidget = function OoUiTabOptionWidget( config ) {
17344 // Configuration initialization
17345 config = config || {};
17346
17347 // Parent constructor
17348 OO.ui.TabOptionWidget.parent.call( this, config );
17349
17350 // Initialization
17351 this.$element.addClass( 'oo-ui-tabOptionWidget' );
17352 };
17353
17354 /* Setup */
17355
17356 OO.inheritClass( OO.ui.TabOptionWidget, OO.ui.OptionWidget );
17357
17358 /* Static Properties */
17359
17360 OO.ui.TabOptionWidget.static.highlightable = false;
17361
17362 /**
17363 * PopupWidget is a container for content. The popup is overlaid and positioned absolutely.
17364 * By default, each popup has an anchor that points toward its origin.
17365 * Please see the [OOjs UI documentation on Mediawiki] [1] for more information and examples.
17366 *
17367 * @example
17368 * // A popup widget.
17369 * var popup = new OO.ui.PopupWidget( {
17370 * $content: $( '<p>Hi there!</p>' ),
17371 * padded: true,
17372 * width: 300
17373 * } );
17374 *
17375 * $( 'body' ).append( popup.$element );
17376 * // To display the popup, toggle the visibility to 'true'.
17377 * popup.toggle( true );
17378 *
17379 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups
17380 *
17381 * @class
17382 * @extends OO.ui.Widget
17383 * @mixins OO.ui.mixin.LabelElement
17384 * @mixins OO.ui.mixin.ClippableElement
17385 *
17386 * @constructor
17387 * @param {Object} [config] Configuration options
17388 * @cfg {number} [width=320] Width of popup in pixels
17389 * @cfg {number} [height] Height of popup in pixels. Omit to use the automatic height.
17390 * @cfg {boolean} [anchor=true] Show anchor pointing to origin of popup
17391 * @cfg {string} [align='center'] Alignment of the popup: `center`, `force-left`, `force-right`, `backwards` or `forwards`.
17392 * If the popup is forced-left the popup body is leaning towards the left. For force-right alignment, the body of the
17393 * popup is leaning towards the right of the screen.
17394 * Using 'backwards' is a logical direction which will result in the popup leaning towards the beginning of the sentence
17395 * in the given language, which means it will flip to the correct positioning in right-to-left languages.
17396 * Using 'forward' will also result in a logical alignment where the body of the popup leans towards the end of the
17397 * sentence in the given language.
17398 * @cfg {jQuery} [$container] Constrain the popup to the boundaries of the specified container.
17399 * See the [OOjs UI docs on MediaWiki][3] for an example.
17400 * [3]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups#containerExample
17401 * @cfg {number} [containerPadding=10] Padding between the popup and its container, specified as a number of pixels.
17402 * @cfg {jQuery} [$content] Content to append to the popup's body
17403 * @cfg {jQuery} [$footer] Content to append to the popup's footer
17404 * @cfg {boolean} [autoClose=false] Automatically close the popup when it loses focus.
17405 * @cfg {jQuery} [$autoCloseIgnore] Elements that will not close the popup when clicked.
17406 * This config option is only relevant if #autoClose is set to `true`. See the [OOjs UI docs on MediaWiki][2]
17407 * for an example.
17408 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups#autocloseExample
17409 * @cfg {boolean} [head] Show a popup header that contains a #label (if specified) and close
17410 * button.
17411 * @cfg {boolean} [padded] Add padding to the popup's body
17412 */
17413 OO.ui.PopupWidget = function OoUiPopupWidget( config ) {
17414 // Configuration initialization
17415 config = config || {};
17416
17417 // Parent constructor
17418 OO.ui.PopupWidget.parent.call( this, config );
17419
17420 // Properties (must be set before ClippableElement constructor call)
17421 this.$body = $( '<div>' );
17422 this.$popup = $( '<div>' );
17423
17424 // Mixin constructors
17425 OO.ui.mixin.LabelElement.call( this, config );
17426 OO.ui.mixin.ClippableElement.call( this, $.extend( {}, config, {
17427 $clippable: this.$body,
17428 $clippableContainer: this.$popup
17429 } ) );
17430
17431 // Properties
17432 this.$head = $( '<div>' );
17433 this.$footer = $( '<div>' );
17434 this.$anchor = $( '<div>' );
17435 // If undefined, will be computed lazily in updateDimensions()
17436 this.$container = config.$container;
17437 this.containerPadding = config.containerPadding !== undefined ? config.containerPadding : 10;
17438 this.autoClose = !!config.autoClose;
17439 this.$autoCloseIgnore = config.$autoCloseIgnore;
17440 this.transitionTimeout = null;
17441 this.anchor = null;
17442 this.width = config.width !== undefined ? config.width : 320;
17443 this.height = config.height !== undefined ? config.height : null;
17444 this.setAlignment( config.align );
17445 this.closeButton = new OO.ui.ButtonWidget( { framed: false, icon: 'close' } );
17446 this.onMouseDownHandler = this.onMouseDown.bind( this );
17447 this.onDocumentKeyDownHandler = this.onDocumentKeyDown.bind( this );
17448
17449 // Events
17450 this.closeButton.connect( this, { click: 'onCloseButtonClick' } );
17451
17452 // Initialization
17453 this.toggleAnchor( config.anchor === undefined || config.anchor );
17454 this.$body.addClass( 'oo-ui-popupWidget-body' );
17455 this.$anchor.addClass( 'oo-ui-popupWidget-anchor' );
17456 this.$head
17457 .addClass( 'oo-ui-popupWidget-head' )
17458 .append( this.$label, this.closeButton.$element );
17459 this.$footer.addClass( 'oo-ui-popupWidget-footer' );
17460 if ( !config.head ) {
17461 this.$head.addClass( 'oo-ui-element-hidden' );
17462 }
17463 if ( !config.$footer ) {
17464 this.$footer.addClass( 'oo-ui-element-hidden' );
17465 }
17466 this.$popup
17467 .addClass( 'oo-ui-popupWidget-popup' )
17468 .append( this.$head, this.$body, this.$footer );
17469 this.$element
17470 .addClass( 'oo-ui-popupWidget' )
17471 .append( this.$popup, this.$anchor );
17472 // Move content, which was added to #$element by OO.ui.Widget, to the body
17473 if ( config.$content instanceof jQuery ) {
17474 this.$body.append( config.$content );
17475 }
17476 if ( config.$footer instanceof jQuery ) {
17477 this.$footer.append( config.$footer );
17478 }
17479 if ( config.padded ) {
17480 this.$body.addClass( 'oo-ui-popupWidget-body-padded' );
17481 }
17482
17483 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
17484 // that reference properties not initialized at that time of parent class construction
17485 // TODO: Find a better way to handle post-constructor setup
17486 this.visible = false;
17487 this.$element.addClass( 'oo-ui-element-hidden' );
17488 };
17489
17490 /* Setup */
17491
17492 OO.inheritClass( OO.ui.PopupWidget, OO.ui.Widget );
17493 OO.mixinClass( OO.ui.PopupWidget, OO.ui.mixin.LabelElement );
17494 OO.mixinClass( OO.ui.PopupWidget, OO.ui.mixin.ClippableElement );
17495
17496 /* Methods */
17497
17498 /**
17499 * Handles mouse down events.
17500 *
17501 * @private
17502 * @param {MouseEvent} e Mouse down event
17503 */
17504 OO.ui.PopupWidget.prototype.onMouseDown = function ( e ) {
17505 if (
17506 this.isVisible() &&
17507 !$.contains( this.$element[ 0 ], e.target ) &&
17508 ( !this.$autoCloseIgnore || !this.$autoCloseIgnore.has( e.target ).length )
17509 ) {
17510 this.toggle( false );
17511 }
17512 };
17513
17514 /**
17515 * Bind mouse down listener.
17516 *
17517 * @private
17518 */
17519 OO.ui.PopupWidget.prototype.bindMouseDownListener = function () {
17520 // Capture clicks outside popup
17521 OO.ui.addCaptureEventListener( this.getElementWindow(), 'mousedown', this.onMouseDownHandler );
17522 };
17523
17524 /**
17525 * Handles close button click events.
17526 *
17527 * @private
17528 */
17529 OO.ui.PopupWidget.prototype.onCloseButtonClick = function () {
17530 if ( this.isVisible() ) {
17531 this.toggle( false );
17532 }
17533 };
17534
17535 /**
17536 * Unbind mouse down listener.
17537 *
17538 * @private
17539 */
17540 OO.ui.PopupWidget.prototype.unbindMouseDownListener = function () {
17541 OO.ui.removeCaptureEventListener( this.getElementWindow(), 'mousedown', this.onMouseDownHandler );
17542 };
17543
17544 /**
17545 * Handles key down events.
17546 *
17547 * @private
17548 * @param {KeyboardEvent} e Key down event
17549 */
17550 OO.ui.PopupWidget.prototype.onDocumentKeyDown = function ( e ) {
17551 if (
17552 e.which === OO.ui.Keys.ESCAPE &&
17553 this.isVisible()
17554 ) {
17555 this.toggle( false );
17556 e.preventDefault();
17557 e.stopPropagation();
17558 }
17559 };
17560
17561 /**
17562 * Bind key down listener.
17563 *
17564 * @private
17565 */
17566 OO.ui.PopupWidget.prototype.bindKeyDownListener = function () {
17567 OO.ui.addCaptureEventListener( this.getElementWindow(), 'keydown', this.onDocumentKeyDownHandler );
17568 };
17569
17570 /**
17571 * Unbind key down listener.
17572 *
17573 * @private
17574 */
17575 OO.ui.PopupWidget.prototype.unbindKeyDownListener = function () {
17576 OO.ui.removeCaptureEventListener( this.getElementWindow(), 'keydown', this.onDocumentKeyDownHandler );
17577 };
17578
17579 /**
17580 * Show, hide, or toggle the visibility of the anchor.
17581 *
17582 * @param {boolean} [show] Show anchor, omit to toggle
17583 */
17584 OO.ui.PopupWidget.prototype.toggleAnchor = function ( show ) {
17585 show = show === undefined ? !this.anchored : !!show;
17586
17587 if ( this.anchored !== show ) {
17588 if ( show ) {
17589 this.$element.addClass( 'oo-ui-popupWidget-anchored' );
17590 } else {
17591 this.$element.removeClass( 'oo-ui-popupWidget-anchored' );
17592 }
17593 this.anchored = show;
17594 }
17595 };
17596
17597 /**
17598 * Check if the anchor is visible.
17599 *
17600 * @return {boolean} Anchor is visible
17601 */
17602 OO.ui.PopupWidget.prototype.hasAnchor = function () {
17603 return this.anchor;
17604 };
17605
17606 /**
17607 * @inheritdoc
17608 */
17609 OO.ui.PopupWidget.prototype.toggle = function ( show ) {
17610 var change;
17611 show = show === undefined ? !this.isVisible() : !!show;
17612
17613 change = show !== this.isVisible();
17614
17615 // Parent method
17616 OO.ui.PopupWidget.parent.prototype.toggle.call( this, show );
17617
17618 if ( change ) {
17619 if ( show ) {
17620 if ( this.autoClose ) {
17621 this.bindMouseDownListener();
17622 this.bindKeyDownListener();
17623 }
17624 this.updateDimensions();
17625 this.toggleClipping( true );
17626 } else {
17627 this.toggleClipping( false );
17628 if ( this.autoClose ) {
17629 this.unbindMouseDownListener();
17630 this.unbindKeyDownListener();
17631 }
17632 }
17633 }
17634
17635 return this;
17636 };
17637
17638 /**
17639 * Set the size of the popup.
17640 *
17641 * Changing the size may also change the popup's position depending on the alignment.
17642 *
17643 * @param {number} width Width in pixels
17644 * @param {number} height Height in pixels
17645 * @param {boolean} [transition=false] Use a smooth transition
17646 * @chainable
17647 */
17648 OO.ui.PopupWidget.prototype.setSize = function ( width, height, transition ) {
17649 this.width = width;
17650 this.height = height !== undefined ? height : null;
17651 if ( this.isVisible() ) {
17652 this.updateDimensions( transition );
17653 }
17654 };
17655
17656 /**
17657 * Update the size and position.
17658 *
17659 * Only use this to keep the popup properly anchored. Use #setSize to change the size, and this will
17660 * be called automatically.
17661 *
17662 * @param {boolean} [transition=false] Use a smooth transition
17663 * @chainable
17664 */
17665 OO.ui.PopupWidget.prototype.updateDimensions = function ( transition ) {
17666 var popupOffset, originOffset, containerLeft, containerWidth, containerRight,
17667 popupLeft, popupRight, overlapLeft, overlapRight, anchorWidth,
17668 align = this.align,
17669 widget = this;
17670
17671 if ( !this.$container ) {
17672 // Lazy-initialize $container if not specified in constructor
17673 this.$container = $( this.getClosestScrollableElementContainer() );
17674 }
17675
17676 // Set height and width before measuring things, since it might cause our measurements
17677 // to change (e.g. due to scrollbars appearing or disappearing)
17678 this.$popup.css( {
17679 width: this.width,
17680 height: this.height !== null ? this.height : 'auto'
17681 } );
17682
17683 // If we are in RTL, we need to flip the alignment, unless it is center
17684 if ( align === 'forwards' || align === 'backwards' ) {
17685 if ( this.$container.css( 'direction' ) === 'rtl' ) {
17686 align = ( { forwards: 'force-left', backwards: 'force-right' } )[ this.align ];
17687 } else {
17688 align = ( { forwards: 'force-right', backwards: 'force-left' } )[ this.align ];
17689 }
17690
17691 }
17692
17693 // Compute initial popupOffset based on alignment
17694 popupOffset = this.width * ( { 'force-left': -1, center: -0.5, 'force-right': 0 } )[ align ];
17695
17696 // Figure out if this will cause the popup to go beyond the edge of the container
17697 originOffset = this.$element.offset().left;
17698 containerLeft = this.$container.offset().left;
17699 containerWidth = this.$container.innerWidth();
17700 containerRight = containerLeft + containerWidth;
17701 popupLeft = popupOffset - this.containerPadding;
17702 popupRight = popupOffset + this.containerPadding + this.width + this.containerPadding;
17703 overlapLeft = ( originOffset + popupLeft ) - containerLeft;
17704 overlapRight = containerRight - ( originOffset + popupRight );
17705
17706 // Adjust offset to make the popup not go beyond the edge, if needed
17707 if ( overlapRight < 0 ) {
17708 popupOffset += overlapRight;
17709 } else if ( overlapLeft < 0 ) {
17710 popupOffset -= overlapLeft;
17711 }
17712
17713 // Adjust offset to avoid anchor being rendered too close to the edge
17714 // $anchor.width() doesn't work with the pure CSS anchor (returns 0)
17715 // TODO: Find a measurement that works for CSS anchors and image anchors
17716 anchorWidth = this.$anchor[ 0 ].scrollWidth * 2;
17717 if ( popupOffset + this.width < anchorWidth ) {
17718 popupOffset = anchorWidth - this.width;
17719 } else if ( -popupOffset < anchorWidth ) {
17720 popupOffset = -anchorWidth;
17721 }
17722
17723 // Prevent transition from being interrupted
17724 clearTimeout( this.transitionTimeout );
17725 if ( transition ) {
17726 // Enable transition
17727 this.$element.addClass( 'oo-ui-popupWidget-transitioning' );
17728 }
17729
17730 // Position body relative to anchor
17731 this.$popup.css( 'margin-left', popupOffset );
17732
17733 if ( transition ) {
17734 // Prevent transitioning after transition is complete
17735 this.transitionTimeout = setTimeout( function () {
17736 widget.$element.removeClass( 'oo-ui-popupWidget-transitioning' );
17737 }, 200 );
17738 } else {
17739 // Prevent transitioning immediately
17740 this.$element.removeClass( 'oo-ui-popupWidget-transitioning' );
17741 }
17742
17743 // Reevaluate clipping state since we've relocated and resized the popup
17744 this.clip();
17745
17746 return this;
17747 };
17748
17749 /**
17750 * Set popup alignment
17751 * @param {string} align Alignment of the popup, `center`, `force-left`, `force-right`,
17752 * `backwards` or `forwards`.
17753 */
17754 OO.ui.PopupWidget.prototype.setAlignment = function ( align ) {
17755 // Validate alignment and transform deprecated values
17756 if ( [ 'left', 'right', 'force-left', 'force-right', 'backwards', 'forwards', 'center' ].indexOf( align ) > -1 ) {
17757 this.align = { left: 'force-right', right: 'force-left' }[ align ] || align;
17758 } else {
17759 this.align = 'center';
17760 }
17761 };
17762
17763 /**
17764 * Get popup alignment
17765 * @return {string} align Alignment of the popup, `center`, `force-left`, `force-right`,
17766 * `backwards` or `forwards`.
17767 */
17768 OO.ui.PopupWidget.prototype.getAlignment = function () {
17769 return this.align;
17770 };
17771
17772 /**
17773 * Progress bars visually display the status of an operation, such as a download,
17774 * and can be either determinate or indeterminate:
17775 *
17776 * - **determinate** process bars show the percent of an operation that is complete.
17777 *
17778 * - **indeterminate** process bars use a visual display of motion to indicate that an operation
17779 * is taking place. Because the extent of an indeterminate operation is unknown, the bar does
17780 * not use percentages.
17781 *
17782 * The value of the `progress` configuration determines whether the bar is determinate or indeterminate.
17783 *
17784 * @example
17785 * // Examples of determinate and indeterminate progress bars.
17786 * var progressBar1 = new OO.ui.ProgressBarWidget( {
17787 * progress: 33
17788 * } );
17789 * var progressBar2 = new OO.ui.ProgressBarWidget();
17790 *
17791 * // Create a FieldsetLayout to layout progress bars
17792 * var fieldset = new OO.ui.FieldsetLayout;
17793 * fieldset.addItems( [
17794 * new OO.ui.FieldLayout( progressBar1, {label: 'Determinate', align: 'top'}),
17795 * new OO.ui.FieldLayout( progressBar2, {label: 'Indeterminate', align: 'top'})
17796 * ] );
17797 * $( 'body' ).append( fieldset.$element );
17798 *
17799 * @class
17800 * @extends OO.ui.Widget
17801 *
17802 * @constructor
17803 * @param {Object} [config] Configuration options
17804 * @cfg {number|boolean} [progress=false] The type of progress bar (determinate or indeterminate).
17805 * To create a determinate progress bar, specify a number that reflects the initial percent complete.
17806 * By default, the progress bar is indeterminate.
17807 */
17808 OO.ui.ProgressBarWidget = function OoUiProgressBarWidget( config ) {
17809 // Configuration initialization
17810 config = config || {};
17811
17812 // Parent constructor
17813 OO.ui.ProgressBarWidget.parent.call( this, config );
17814
17815 // Properties
17816 this.$bar = $( '<div>' );
17817 this.progress = null;
17818
17819 // Initialization
17820 this.setProgress( config.progress !== undefined ? config.progress : false );
17821 this.$bar.addClass( 'oo-ui-progressBarWidget-bar' );
17822 this.$element
17823 .attr( {
17824 role: 'progressbar',
17825 'aria-valuemin': 0,
17826 'aria-valuemax': 100
17827 } )
17828 .addClass( 'oo-ui-progressBarWidget' )
17829 .append( this.$bar );
17830 };
17831
17832 /* Setup */
17833
17834 OO.inheritClass( OO.ui.ProgressBarWidget, OO.ui.Widget );
17835
17836 /* Static Properties */
17837
17838 OO.ui.ProgressBarWidget.static.tagName = 'div';
17839
17840 /* Methods */
17841
17842 /**
17843 * Get the percent of the progress that has been completed. Indeterminate progresses will return `false`.
17844 *
17845 * @return {number|boolean} Progress percent
17846 */
17847 OO.ui.ProgressBarWidget.prototype.getProgress = function () {
17848 return this.progress;
17849 };
17850
17851 /**
17852 * Set the percent of the process completed or `false` for an indeterminate process.
17853 *
17854 * @param {number|boolean} progress Progress percent or `false` for indeterminate
17855 */
17856 OO.ui.ProgressBarWidget.prototype.setProgress = function ( progress ) {
17857 this.progress = progress;
17858
17859 if ( progress !== false ) {
17860 this.$bar.css( 'width', this.progress + '%' );
17861 this.$element.attr( 'aria-valuenow', this.progress );
17862 } else {
17863 this.$bar.css( 'width', '' );
17864 this.$element.removeAttr( 'aria-valuenow' );
17865 }
17866 this.$element.toggleClass( 'oo-ui-progressBarWidget-indeterminate', !progress );
17867 };
17868
17869 /**
17870 * SearchWidgets combine a {@link OO.ui.TextInputWidget text input field}, where users can type a search query,
17871 * and a menu of search results, which is displayed beneath the query
17872 * field. Unlike {@link OO.ui.mixin.LookupElement lookup menus}, search result menus are always visible to the user.
17873 * Users can choose an item from the menu or type a query into the text field to search for a matching result item.
17874 * In general, search widgets are used inside a separate {@link OO.ui.Dialog dialog} window.
17875 *
17876 * Each time the query is changed, the search result menu is cleared and repopulated. Please see
17877 * the [OOjs UI demos][1] for an example.
17878 *
17879 * [1]: https://tools.wmflabs.org/oojs-ui/oojs-ui/demos/#dialogs-mediawiki-vector-ltr
17880 *
17881 * @class
17882 * @extends OO.ui.Widget
17883 *
17884 * @constructor
17885 * @param {Object} [config] Configuration options
17886 * @cfg {string|jQuery} [placeholder] Placeholder text for query input
17887 * @cfg {string} [value] Initial query value
17888 */
17889 OO.ui.SearchWidget = function OoUiSearchWidget( config ) {
17890 // Configuration initialization
17891 config = config || {};
17892
17893 // Parent constructor
17894 OO.ui.SearchWidget.parent.call( this, config );
17895
17896 // Properties
17897 this.query = new OO.ui.TextInputWidget( {
17898 icon: 'search',
17899 placeholder: config.placeholder,
17900 value: config.value
17901 } );
17902 this.results = new OO.ui.SelectWidget();
17903 this.$query = $( '<div>' );
17904 this.$results = $( '<div>' );
17905
17906 // Events
17907 this.query.connect( this, {
17908 change: 'onQueryChange',
17909 enter: 'onQueryEnter'
17910 } );
17911 this.query.$input.on( 'keydown', this.onQueryKeydown.bind( this ) );
17912
17913 // Initialization
17914 this.$query
17915 .addClass( 'oo-ui-searchWidget-query' )
17916 .append( this.query.$element );
17917 this.$results
17918 .addClass( 'oo-ui-searchWidget-results' )
17919 .append( this.results.$element );
17920 this.$element
17921 .addClass( 'oo-ui-searchWidget' )
17922 .append( this.$results, this.$query );
17923 };
17924
17925 /* Setup */
17926
17927 OO.inheritClass( OO.ui.SearchWidget, OO.ui.Widget );
17928
17929 /* Methods */
17930
17931 /**
17932 * Handle query key down events.
17933 *
17934 * @private
17935 * @param {jQuery.Event} e Key down event
17936 */
17937 OO.ui.SearchWidget.prototype.onQueryKeydown = function ( e ) {
17938 var highlightedItem, nextItem,
17939 dir = e.which === OO.ui.Keys.DOWN ? 1 : ( e.which === OO.ui.Keys.UP ? -1 : 0 );
17940
17941 if ( dir ) {
17942 highlightedItem = this.results.getHighlightedItem();
17943 if ( !highlightedItem ) {
17944 highlightedItem = this.results.getSelectedItem();
17945 }
17946 nextItem = this.results.getRelativeSelectableItem( highlightedItem, dir );
17947 this.results.highlightItem( nextItem );
17948 nextItem.scrollElementIntoView();
17949 }
17950 };
17951
17952 /**
17953 * Handle select widget select events.
17954 *
17955 * Clears existing results. Subclasses should repopulate items according to new query.
17956 *
17957 * @private
17958 * @param {string} value New value
17959 */
17960 OO.ui.SearchWidget.prototype.onQueryChange = function () {
17961 // Reset
17962 this.results.clearItems();
17963 };
17964
17965 /**
17966 * Handle select widget enter key events.
17967 *
17968 * Chooses highlighted item.
17969 *
17970 * @private
17971 * @param {string} value New value
17972 */
17973 OO.ui.SearchWidget.prototype.onQueryEnter = function () {
17974 var highlightedItem = this.results.getHighlightedItem();
17975 if ( highlightedItem ) {
17976 this.results.chooseItem( highlightedItem );
17977 }
17978 };
17979
17980 /**
17981 * Get the query input.
17982 *
17983 * @return {OO.ui.TextInputWidget} Query input
17984 */
17985 OO.ui.SearchWidget.prototype.getQuery = function () {
17986 return this.query;
17987 };
17988
17989 /**
17990 * Get the search results menu.
17991 *
17992 * @return {OO.ui.SelectWidget} Menu of search results
17993 */
17994 OO.ui.SearchWidget.prototype.getResults = function () {
17995 return this.results;
17996 };
17997
17998 /**
17999 * A SelectWidget is of a generic selection of options. The OOjs UI library contains several types of
18000 * select widgets, including {@link OO.ui.ButtonSelectWidget button selects},
18001 * {@link OO.ui.RadioSelectWidget radio selects}, and {@link OO.ui.MenuSelectWidget
18002 * menu selects}.
18003 *
18004 * This class should be used together with OO.ui.OptionWidget or OO.ui.DecoratedOptionWidget. For more
18005 * information, please see the [OOjs UI documentation on MediaWiki][1].
18006 *
18007 * @example
18008 * // Example of a select widget with three options
18009 * var select = new OO.ui.SelectWidget( {
18010 * items: [
18011 * new OO.ui.OptionWidget( {
18012 * data: 'a',
18013 * label: 'Option One',
18014 * } ),
18015 * new OO.ui.OptionWidget( {
18016 * data: 'b',
18017 * label: 'Option Two',
18018 * } ),
18019 * new OO.ui.OptionWidget( {
18020 * data: 'c',
18021 * label: 'Option Three',
18022 * } )
18023 * ]
18024 * } );
18025 * $( 'body' ).append( select.$element );
18026 *
18027 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
18028 *
18029 * @abstract
18030 * @class
18031 * @extends OO.ui.Widget
18032 * @mixins OO.ui.mixin.GroupWidget
18033 *
18034 * @constructor
18035 * @param {Object} [config] Configuration options
18036 * @cfg {OO.ui.OptionWidget[]} [items] An array of options to add to the select.
18037 * Options are created with {@link OO.ui.OptionWidget OptionWidget} classes. See
18038 * the [OOjs UI documentation on MediaWiki] [2] for examples.
18039 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
18040 */
18041 OO.ui.SelectWidget = function OoUiSelectWidget( config ) {
18042 // Configuration initialization
18043 config = config || {};
18044
18045 // Parent constructor
18046 OO.ui.SelectWidget.parent.call( this, config );
18047
18048 // Mixin constructors
18049 OO.ui.mixin.GroupWidget.call( this, $.extend( {}, config, { $group: this.$element } ) );
18050
18051 // Properties
18052 this.pressed = false;
18053 this.selecting = null;
18054 this.onMouseUpHandler = this.onMouseUp.bind( this );
18055 this.onMouseMoveHandler = this.onMouseMove.bind( this );
18056 this.onKeyDownHandler = this.onKeyDown.bind( this );
18057 this.onKeyPressHandler = this.onKeyPress.bind( this );
18058 this.keyPressBuffer = '';
18059 this.keyPressBufferTimer = null;
18060
18061 // Events
18062 this.connect( this, {
18063 toggle: 'onToggle'
18064 } );
18065 this.$element.on( {
18066 mousedown: this.onMouseDown.bind( this ),
18067 mouseover: this.onMouseOver.bind( this ),
18068 mouseleave: this.onMouseLeave.bind( this )
18069 } );
18070
18071 // Initialization
18072 this.$element
18073 .addClass( 'oo-ui-selectWidget oo-ui-selectWidget-depressed' )
18074 .attr( 'role', 'listbox' );
18075 if ( Array.isArray( config.items ) ) {
18076 this.addItems( config.items );
18077 }
18078 };
18079
18080 /* Setup */
18081
18082 OO.inheritClass( OO.ui.SelectWidget, OO.ui.Widget );
18083
18084 // Need to mixin base class as well
18085 OO.mixinClass( OO.ui.SelectWidget, OO.ui.mixin.GroupElement );
18086 OO.mixinClass( OO.ui.SelectWidget, OO.ui.mixin.GroupWidget );
18087
18088 /* Static */
18089 OO.ui.SelectWidget.static.passAllFilter = function () {
18090 return true;
18091 };
18092
18093 /* Events */
18094
18095 /**
18096 * @event highlight
18097 *
18098 * A `highlight` event is emitted when the highlight is changed with the #highlightItem method.
18099 *
18100 * @param {OO.ui.OptionWidget|null} item Highlighted item
18101 */
18102
18103 /**
18104 * @event press
18105 *
18106 * A `press` event is emitted when the #pressItem method is used to programmatically modify the
18107 * pressed state of an option.
18108 *
18109 * @param {OO.ui.OptionWidget|null} item Pressed item
18110 */
18111
18112 /**
18113 * @event select
18114 *
18115 * A `select` event is emitted when the selection is modified programmatically with the #selectItem method.
18116 *
18117 * @param {OO.ui.OptionWidget|null} item Selected item
18118 */
18119
18120 /**
18121 * @event choose
18122 * A `choose` event is emitted when an item is chosen with the #chooseItem method.
18123 * @param {OO.ui.OptionWidget} item Chosen item
18124 */
18125
18126 /**
18127 * @event add
18128 *
18129 * An `add` event is emitted when options are added to the select with the #addItems method.
18130 *
18131 * @param {OO.ui.OptionWidget[]} items Added items
18132 * @param {number} index Index of insertion point
18133 */
18134
18135 /**
18136 * @event remove
18137 *
18138 * A `remove` event is emitted when options are removed from the select with the #clearItems
18139 * or #removeItems methods.
18140 *
18141 * @param {OO.ui.OptionWidget[]} items Removed items
18142 */
18143
18144 /* Methods */
18145
18146 /**
18147 * Handle mouse down events.
18148 *
18149 * @private
18150 * @param {jQuery.Event} e Mouse down event
18151 */
18152 OO.ui.SelectWidget.prototype.onMouseDown = function ( e ) {
18153 var item;
18154
18155 if ( !this.isDisabled() && e.which === 1 ) {
18156 this.togglePressed( true );
18157 item = this.getTargetItem( e );
18158 if ( item && item.isSelectable() ) {
18159 this.pressItem( item );
18160 this.selecting = item;
18161 OO.ui.addCaptureEventListener(
18162 this.getElementDocument(),
18163 'mouseup',
18164 this.onMouseUpHandler
18165 );
18166 OO.ui.addCaptureEventListener(
18167 this.getElementDocument(),
18168 'mousemove',
18169 this.onMouseMoveHandler
18170 );
18171 }
18172 }
18173 return false;
18174 };
18175
18176 /**
18177 * Handle mouse up events.
18178 *
18179 * @private
18180 * @param {jQuery.Event} e Mouse up event
18181 */
18182 OO.ui.SelectWidget.prototype.onMouseUp = function ( e ) {
18183 var item;
18184
18185 this.togglePressed( false );
18186 if ( !this.selecting ) {
18187 item = this.getTargetItem( e );
18188 if ( item && item.isSelectable() ) {
18189 this.selecting = item;
18190 }
18191 }
18192 if ( !this.isDisabled() && e.which === 1 && this.selecting ) {
18193 this.pressItem( null );
18194 this.chooseItem( this.selecting );
18195 this.selecting = null;
18196 }
18197
18198 OO.ui.removeCaptureEventListener( this.getElementDocument(), 'mouseup',
18199 this.onMouseUpHandler );
18200 OO.ui.removeCaptureEventListener( this.getElementDocument(), 'mousemove',
18201 this.onMouseMoveHandler );
18202
18203 return false;
18204 };
18205
18206 /**
18207 * Handle mouse move events.
18208 *
18209 * @private
18210 * @param {jQuery.Event} e Mouse move event
18211 */
18212 OO.ui.SelectWidget.prototype.onMouseMove = function ( e ) {
18213 var item;
18214
18215 if ( !this.isDisabled() && this.pressed ) {
18216 item = this.getTargetItem( e );
18217 if ( item && item !== this.selecting && item.isSelectable() ) {
18218 this.pressItem( item );
18219 this.selecting = item;
18220 }
18221 }
18222 return false;
18223 };
18224
18225 /**
18226 * Handle mouse over events.
18227 *
18228 * @private
18229 * @param {jQuery.Event} e Mouse over event
18230 */
18231 OO.ui.SelectWidget.prototype.onMouseOver = function ( e ) {
18232 var item;
18233
18234 if ( !this.isDisabled() ) {
18235 item = this.getTargetItem( e );
18236 this.highlightItem( item && item.isHighlightable() ? item : null );
18237 }
18238 return false;
18239 };
18240
18241 /**
18242 * Handle mouse leave events.
18243 *
18244 * @private
18245 * @param {jQuery.Event} e Mouse over event
18246 */
18247 OO.ui.SelectWidget.prototype.onMouseLeave = function () {
18248 if ( !this.isDisabled() ) {
18249 this.highlightItem( null );
18250 }
18251 return false;
18252 };
18253
18254 /**
18255 * Handle key down events.
18256 *
18257 * @protected
18258 * @param {jQuery.Event} e Key down event
18259 */
18260 OO.ui.SelectWidget.prototype.onKeyDown = function ( e ) {
18261 var nextItem,
18262 handled = false,
18263 currentItem = this.getHighlightedItem() || this.getSelectedItem();
18264
18265 if ( !this.isDisabled() && this.isVisible() ) {
18266 switch ( e.keyCode ) {
18267 case OO.ui.Keys.ENTER:
18268 if ( currentItem && currentItem.constructor.static.highlightable ) {
18269 // Was only highlighted, now let's select it. No-op if already selected.
18270 this.chooseItem( currentItem );
18271 handled = true;
18272 }
18273 break;
18274 case OO.ui.Keys.UP:
18275 case OO.ui.Keys.LEFT:
18276 this.clearKeyPressBuffer();
18277 nextItem = this.getRelativeSelectableItem( currentItem, -1 );
18278 handled = true;
18279 break;
18280 case OO.ui.Keys.DOWN:
18281 case OO.ui.Keys.RIGHT:
18282 this.clearKeyPressBuffer();
18283 nextItem = this.getRelativeSelectableItem( currentItem, 1 );
18284 handled = true;
18285 break;
18286 case OO.ui.Keys.ESCAPE:
18287 case OO.ui.Keys.TAB:
18288 if ( currentItem && currentItem.constructor.static.highlightable ) {
18289 currentItem.setHighlighted( false );
18290 }
18291 this.unbindKeyDownListener();
18292 this.unbindKeyPressListener();
18293 // Don't prevent tabbing away / defocusing
18294 handled = false;
18295 break;
18296 }
18297
18298 if ( nextItem ) {
18299 if ( nextItem.constructor.static.highlightable ) {
18300 this.highlightItem( nextItem );
18301 } else {
18302 this.chooseItem( nextItem );
18303 }
18304 nextItem.scrollElementIntoView();
18305 }
18306
18307 if ( handled ) {
18308 // Can't just return false, because e is not always a jQuery event
18309 e.preventDefault();
18310 e.stopPropagation();
18311 }
18312 }
18313 };
18314
18315 /**
18316 * Bind key down listener.
18317 *
18318 * @protected
18319 */
18320 OO.ui.SelectWidget.prototype.bindKeyDownListener = function () {
18321 OO.ui.addCaptureEventListener( this.getElementWindow(), 'keydown', this.onKeyDownHandler );
18322 };
18323
18324 /**
18325 * Unbind key down listener.
18326 *
18327 * @protected
18328 */
18329 OO.ui.SelectWidget.prototype.unbindKeyDownListener = function () {
18330 OO.ui.removeCaptureEventListener( this.getElementWindow(), 'keydown', this.onKeyDownHandler );
18331 };
18332
18333 /**
18334 * Clear the key-press buffer
18335 *
18336 * @protected
18337 */
18338 OO.ui.SelectWidget.prototype.clearKeyPressBuffer = function () {
18339 if ( this.keyPressBufferTimer ) {
18340 clearTimeout( this.keyPressBufferTimer );
18341 this.keyPressBufferTimer = null;
18342 }
18343 this.keyPressBuffer = '';
18344 };
18345
18346 /**
18347 * Handle key press events.
18348 *
18349 * @protected
18350 * @param {jQuery.Event} e Key press event
18351 */
18352 OO.ui.SelectWidget.prototype.onKeyPress = function ( e ) {
18353 var c, filter, item;
18354
18355 if ( !e.charCode ) {
18356 if ( e.keyCode === OO.ui.Keys.BACKSPACE && this.keyPressBuffer !== '' ) {
18357 this.keyPressBuffer = this.keyPressBuffer.substr( 0, this.keyPressBuffer.length - 1 );
18358 return false;
18359 }
18360 return;
18361 }
18362 if ( String.fromCodePoint ) {
18363 c = String.fromCodePoint( e.charCode );
18364 } else {
18365 c = String.fromCharCode( e.charCode );
18366 }
18367
18368 if ( this.keyPressBufferTimer ) {
18369 clearTimeout( this.keyPressBufferTimer );
18370 }
18371 this.keyPressBufferTimer = setTimeout( this.clearKeyPressBuffer.bind( this ), 1500 );
18372
18373 item = this.getHighlightedItem() || this.getSelectedItem();
18374
18375 if ( this.keyPressBuffer === c ) {
18376 // Common (if weird) special case: typing "xxxx" will cycle through all
18377 // the items beginning with "x".
18378 if ( item ) {
18379 item = this.getRelativeSelectableItem( item, 1 );
18380 }
18381 } else {
18382 this.keyPressBuffer += c;
18383 }
18384
18385 filter = this.getItemMatcher( this.keyPressBuffer, false );
18386 if ( !item || !filter( item ) ) {
18387 item = this.getRelativeSelectableItem( item, 1, filter );
18388 }
18389 if ( item ) {
18390 if ( item.constructor.static.highlightable ) {
18391 this.highlightItem( item );
18392 } else {
18393 this.chooseItem( item );
18394 }
18395 item.scrollElementIntoView();
18396 }
18397
18398 return false;
18399 };
18400
18401 /**
18402 * Get a matcher for the specific string
18403 *
18404 * @protected
18405 * @param {string} s String to match against items
18406 * @param {boolean} [exact=false] Only accept exact matches
18407 * @return {Function} function ( OO.ui.OptionItem ) => boolean
18408 */
18409 OO.ui.SelectWidget.prototype.getItemMatcher = function ( s, exact ) {
18410 var re;
18411
18412 if ( s.normalize ) {
18413 s = s.normalize();
18414 }
18415 s = exact ? s.trim() : s.replace( /^\s+/, '' );
18416 re = '^\\s*' + s.replace( /([\\{}()|.?*+\-\^$\[\]])/g, '\\$1' ).replace( /\s+/g, '\\s+' );
18417 if ( exact ) {
18418 re += '\\s*$';
18419 }
18420 re = new RegExp( re, 'i' );
18421 return function ( item ) {
18422 var l = item.getLabel();
18423 if ( typeof l !== 'string' ) {
18424 l = item.$label.text();
18425 }
18426 if ( l.normalize ) {
18427 l = l.normalize();
18428 }
18429 return re.test( l );
18430 };
18431 };
18432
18433 /**
18434 * Bind key press listener.
18435 *
18436 * @protected
18437 */
18438 OO.ui.SelectWidget.prototype.bindKeyPressListener = function () {
18439 OO.ui.addCaptureEventListener( this.getElementWindow(), 'keypress', this.onKeyPressHandler );
18440 };
18441
18442 /**
18443 * Unbind key down listener.
18444 *
18445 * If you override this, be sure to call this.clearKeyPressBuffer() from your
18446 * implementation.
18447 *
18448 * @protected
18449 */
18450 OO.ui.SelectWidget.prototype.unbindKeyPressListener = function () {
18451 OO.ui.removeCaptureEventListener( this.getElementWindow(), 'keypress', this.onKeyPressHandler );
18452 this.clearKeyPressBuffer();
18453 };
18454
18455 /**
18456 * Visibility change handler
18457 *
18458 * @protected
18459 * @param {boolean} visible
18460 */
18461 OO.ui.SelectWidget.prototype.onToggle = function ( visible ) {
18462 if ( !visible ) {
18463 this.clearKeyPressBuffer();
18464 }
18465 };
18466
18467 /**
18468 * Get the closest item to a jQuery.Event.
18469 *
18470 * @private
18471 * @param {jQuery.Event} e
18472 * @return {OO.ui.OptionWidget|null} Outline item widget, `null` if none was found
18473 */
18474 OO.ui.SelectWidget.prototype.getTargetItem = function ( e ) {
18475 return $( e.target ).closest( '.oo-ui-optionWidget' ).data( 'oo-ui-optionWidget' ) || null;
18476 };
18477
18478 /**
18479 * Get selected item.
18480 *
18481 * @return {OO.ui.OptionWidget|null} Selected item, `null` if no item is selected
18482 */
18483 OO.ui.SelectWidget.prototype.getSelectedItem = function () {
18484 var i, len;
18485
18486 for ( i = 0, len = this.items.length; i < len; i++ ) {
18487 if ( this.items[ i ].isSelected() ) {
18488 return this.items[ i ];
18489 }
18490 }
18491 return null;
18492 };
18493
18494 /**
18495 * Get highlighted item.
18496 *
18497 * @return {OO.ui.OptionWidget|null} Highlighted item, `null` if no item is highlighted
18498 */
18499 OO.ui.SelectWidget.prototype.getHighlightedItem = function () {
18500 var i, len;
18501
18502 for ( i = 0, len = this.items.length; i < len; i++ ) {
18503 if ( this.items[ i ].isHighlighted() ) {
18504 return this.items[ i ];
18505 }
18506 }
18507 return null;
18508 };
18509
18510 /**
18511 * Toggle pressed state.
18512 *
18513 * Press is a state that occurs when a user mouses down on an item, but
18514 * has not yet let go of the mouse. The item may appear selected, but it will not be selected
18515 * until the user releases the mouse.
18516 *
18517 * @param {boolean} pressed An option is being pressed
18518 */
18519 OO.ui.SelectWidget.prototype.togglePressed = function ( pressed ) {
18520 if ( pressed === undefined ) {
18521 pressed = !this.pressed;
18522 }
18523 if ( pressed !== this.pressed ) {
18524 this.$element
18525 .toggleClass( 'oo-ui-selectWidget-pressed', pressed )
18526 .toggleClass( 'oo-ui-selectWidget-depressed', !pressed );
18527 this.pressed = pressed;
18528 }
18529 };
18530
18531 /**
18532 * Highlight an option. If the `item` param is omitted, no options will be highlighted
18533 * and any existing highlight will be removed. The highlight is mutually exclusive.
18534 *
18535 * @param {OO.ui.OptionWidget} [item] Item to highlight, omit for no highlight
18536 * @fires highlight
18537 * @chainable
18538 */
18539 OO.ui.SelectWidget.prototype.highlightItem = function ( item ) {
18540 var i, len, highlighted,
18541 changed = false;
18542
18543 for ( i = 0, len = this.items.length; i < len; i++ ) {
18544 highlighted = this.items[ i ] === item;
18545 if ( this.items[ i ].isHighlighted() !== highlighted ) {
18546 this.items[ i ].setHighlighted( highlighted );
18547 changed = true;
18548 }
18549 }
18550 if ( changed ) {
18551 this.emit( 'highlight', item );
18552 }
18553
18554 return this;
18555 };
18556
18557 /**
18558 * Fetch an item by its label.
18559 *
18560 * @param {string} label Label of the item to select.
18561 * @param {boolean} [prefix=false] Allow a prefix match, if only a single item matches
18562 * @return {OO.ui.Element|null} Item with equivalent label, `null` if none exists
18563 */
18564 OO.ui.SelectWidget.prototype.getItemFromLabel = function ( label, prefix ) {
18565 var i, item, found,
18566 len = this.items.length,
18567 filter = this.getItemMatcher( label, true );
18568
18569 for ( i = 0; i < len; i++ ) {
18570 item = this.items[ i ];
18571 if ( item instanceof OO.ui.OptionWidget && item.isSelectable() && filter( item ) ) {
18572 return item;
18573 }
18574 }
18575
18576 if ( prefix ) {
18577 found = null;
18578 filter = this.getItemMatcher( label, false );
18579 for ( i = 0; i < len; i++ ) {
18580 item = this.items[ i ];
18581 if ( item instanceof OO.ui.OptionWidget && item.isSelectable() && filter( item ) ) {
18582 if ( found ) {
18583 return null;
18584 }
18585 found = item;
18586 }
18587 }
18588 if ( found ) {
18589 return found;
18590 }
18591 }
18592
18593 return null;
18594 };
18595
18596 /**
18597 * Programmatically select an option by its label. If the item does not exist,
18598 * all options will be deselected.
18599 *
18600 * @param {string} [label] Label of the item to select.
18601 * @param {boolean} [prefix=false] Allow a prefix match, if only a single item matches
18602 * @fires select
18603 * @chainable
18604 */
18605 OO.ui.SelectWidget.prototype.selectItemByLabel = function ( label, prefix ) {
18606 var itemFromLabel = this.getItemFromLabel( label, !!prefix );
18607 if ( label === undefined || !itemFromLabel ) {
18608 return this.selectItem();
18609 }
18610 return this.selectItem( itemFromLabel );
18611 };
18612
18613 /**
18614 * Programmatically select an option by its data. If the `data` parameter is omitted,
18615 * or if the item does not exist, all options will be deselected.
18616 *
18617 * @param {Object|string} [data] Value of the item to select, omit to deselect all
18618 * @fires select
18619 * @chainable
18620 */
18621 OO.ui.SelectWidget.prototype.selectItemByData = function ( data ) {
18622 var itemFromData = this.getItemFromData( data );
18623 if ( data === undefined || !itemFromData ) {
18624 return this.selectItem();
18625 }
18626 return this.selectItem( itemFromData );
18627 };
18628
18629 /**
18630 * Programmatically select an option by its reference. If the `item` parameter is omitted,
18631 * all options will be deselected.
18632 *
18633 * @param {OO.ui.OptionWidget} [item] Item to select, omit to deselect all
18634 * @fires select
18635 * @chainable
18636 */
18637 OO.ui.SelectWidget.prototype.selectItem = function ( item ) {
18638 var i, len, selected,
18639 changed = false;
18640
18641 for ( i = 0, len = this.items.length; i < len; i++ ) {
18642 selected = this.items[ i ] === item;
18643 if ( this.items[ i ].isSelected() !== selected ) {
18644 this.items[ i ].setSelected( selected );
18645 changed = true;
18646 }
18647 }
18648 if ( changed ) {
18649 this.emit( 'select', item );
18650 }
18651
18652 return this;
18653 };
18654
18655 /**
18656 * Press an item.
18657 *
18658 * Press is a state that occurs when a user mouses down on an item, but has not
18659 * yet let go of the mouse. The item may appear selected, but it will not be selected until the user
18660 * releases the mouse.
18661 *
18662 * @param {OO.ui.OptionWidget} [item] Item to press, omit to depress all
18663 * @fires press
18664 * @chainable
18665 */
18666 OO.ui.SelectWidget.prototype.pressItem = function ( item ) {
18667 var i, len, pressed,
18668 changed = false;
18669
18670 for ( i = 0, len = this.items.length; i < len; i++ ) {
18671 pressed = this.items[ i ] === item;
18672 if ( this.items[ i ].isPressed() !== pressed ) {
18673 this.items[ i ].setPressed( pressed );
18674 changed = true;
18675 }
18676 }
18677 if ( changed ) {
18678 this.emit( 'press', item );
18679 }
18680
18681 return this;
18682 };
18683
18684 /**
18685 * Choose an item.
18686 *
18687 * Note that ‘choose’ should never be modified programmatically. A user can choose
18688 * an option with the keyboard or mouse and it becomes selected. To select an item programmatically,
18689 * use the #selectItem method.
18690 *
18691 * This method is identical to #selectItem, but may vary in subclasses that take additional action
18692 * when users choose an item with the keyboard or mouse.
18693 *
18694 * @param {OO.ui.OptionWidget} item Item to choose
18695 * @fires choose
18696 * @chainable
18697 */
18698 OO.ui.SelectWidget.prototype.chooseItem = function ( item ) {
18699 if ( item ) {
18700 this.selectItem( item );
18701 this.emit( 'choose', item );
18702 }
18703
18704 return this;
18705 };
18706
18707 /**
18708 * Get an option by its position relative to the specified item (or to the start of the option array,
18709 * if item is `null`). The direction in which to search through the option array is specified with a
18710 * number: -1 for reverse (the default) or 1 for forward. The method will return an option, or
18711 * `null` if there are no options in the array.
18712 *
18713 * @param {OO.ui.OptionWidget|null} item Item to describe the start position, or `null` to start at the beginning of the array.
18714 * @param {number} direction Direction to move in: -1 to move backward, 1 to move forward
18715 * @param {Function} filter Only consider items for which this function returns
18716 * true. Function takes an OO.ui.OptionWidget and returns a boolean.
18717 * @return {OO.ui.OptionWidget|null} Item at position, `null` if there are no items in the select
18718 */
18719 OO.ui.SelectWidget.prototype.getRelativeSelectableItem = function ( item, direction, filter ) {
18720 var currentIndex, nextIndex, i,
18721 increase = direction > 0 ? 1 : -1,
18722 len = this.items.length;
18723
18724 if ( !$.isFunction( filter ) ) {
18725 filter = OO.ui.SelectWidget.static.passAllFilter;
18726 }
18727
18728 if ( item instanceof OO.ui.OptionWidget ) {
18729 currentIndex = this.items.indexOf( item );
18730 nextIndex = ( currentIndex + increase + len ) % len;
18731 } else {
18732 // If no item is selected and moving forward, start at the beginning.
18733 // If moving backward, start at the end.
18734 nextIndex = direction > 0 ? 0 : len - 1;
18735 }
18736
18737 for ( i = 0; i < len; i++ ) {
18738 item = this.items[ nextIndex ];
18739 if ( item instanceof OO.ui.OptionWidget && item.isSelectable() && filter( item ) ) {
18740 return item;
18741 }
18742 nextIndex = ( nextIndex + increase + len ) % len;
18743 }
18744 return null;
18745 };
18746
18747 /**
18748 * Get the next selectable item or `null` if there are no selectable items.
18749 * Disabled options and menu-section markers and breaks are not selectable.
18750 *
18751 * @return {OO.ui.OptionWidget|null} Item, `null` if there aren't any selectable items
18752 */
18753 OO.ui.SelectWidget.prototype.getFirstSelectableItem = function () {
18754 var i, len, item;
18755
18756 for ( i = 0, len = this.items.length; i < len; i++ ) {
18757 item = this.items[ i ];
18758 if ( item instanceof OO.ui.OptionWidget && item.isSelectable() ) {
18759 return item;
18760 }
18761 }
18762
18763 return null;
18764 };
18765
18766 /**
18767 * Add an array of options to the select. Optionally, an index number can be used to
18768 * specify an insertion point.
18769 *
18770 * @param {OO.ui.OptionWidget[]} items Items to add
18771 * @param {number} [index] Index to insert items after
18772 * @fires add
18773 * @chainable
18774 */
18775 OO.ui.SelectWidget.prototype.addItems = function ( items, index ) {
18776 // Mixin method
18777 OO.ui.mixin.GroupWidget.prototype.addItems.call( this, items, index );
18778
18779 // Always provide an index, even if it was omitted
18780 this.emit( 'add', items, index === undefined ? this.items.length - items.length - 1 : index );
18781
18782 return this;
18783 };
18784
18785 /**
18786 * Remove the specified array of options from the select. Options will be detached
18787 * from the DOM, not removed, so they can be reused later. To remove all options from
18788 * the select, you may wish to use the #clearItems method instead.
18789 *
18790 * @param {OO.ui.OptionWidget[]} items Items to remove
18791 * @fires remove
18792 * @chainable
18793 */
18794 OO.ui.SelectWidget.prototype.removeItems = function ( items ) {
18795 var i, len, item;
18796
18797 // Deselect items being removed
18798 for ( i = 0, len = items.length; i < len; i++ ) {
18799 item = items[ i ];
18800 if ( item.isSelected() ) {
18801 this.selectItem( null );
18802 }
18803 }
18804
18805 // Mixin method
18806 OO.ui.mixin.GroupWidget.prototype.removeItems.call( this, items );
18807
18808 this.emit( 'remove', items );
18809
18810 return this;
18811 };
18812
18813 /**
18814 * Clear all options from the select. Options will be detached from the DOM, not removed,
18815 * so that they can be reused later. To remove a subset of options from the select, use
18816 * the #removeItems method.
18817 *
18818 * @fires remove
18819 * @chainable
18820 */
18821 OO.ui.SelectWidget.prototype.clearItems = function () {
18822 var items = this.items.slice();
18823
18824 // Mixin method
18825 OO.ui.mixin.GroupWidget.prototype.clearItems.call( this );
18826
18827 // Clear selection
18828 this.selectItem( null );
18829
18830 this.emit( 'remove', items );
18831
18832 return this;
18833 };
18834
18835 /**
18836 * ButtonSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains
18837 * button options and is used together with
18838 * OO.ui.ButtonOptionWidget. The ButtonSelectWidget provides an interface for
18839 * highlighting, choosing, and selecting mutually exclusive options. Please see
18840 * the [OOjs UI documentation on MediaWiki] [1] for more information.
18841 *
18842 * @example
18843 * // Example: A ButtonSelectWidget that contains three ButtonOptionWidgets
18844 * var option1 = new OO.ui.ButtonOptionWidget( {
18845 * data: 1,
18846 * label: 'Option 1',
18847 * title: 'Button option 1'
18848 * } );
18849 *
18850 * var option2 = new OO.ui.ButtonOptionWidget( {
18851 * data: 2,
18852 * label: 'Option 2',
18853 * title: 'Button option 2'
18854 * } );
18855 *
18856 * var option3 = new OO.ui.ButtonOptionWidget( {
18857 * data: 3,
18858 * label: 'Option 3',
18859 * title: 'Button option 3'
18860 * } );
18861 *
18862 * var buttonSelect=new OO.ui.ButtonSelectWidget( {
18863 * items: [ option1, option2, option3 ]
18864 * } );
18865 * $( 'body' ).append( buttonSelect.$element );
18866 *
18867 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
18868 *
18869 * @class
18870 * @extends OO.ui.SelectWidget
18871 * @mixins OO.ui.mixin.TabIndexedElement
18872 *
18873 * @constructor
18874 * @param {Object} [config] Configuration options
18875 */
18876 OO.ui.ButtonSelectWidget = function OoUiButtonSelectWidget( config ) {
18877 // Parent constructor
18878 OO.ui.ButtonSelectWidget.parent.call( this, config );
18879
18880 // Mixin constructors
18881 OO.ui.mixin.TabIndexedElement.call( this, config );
18882
18883 // Events
18884 this.$element.on( {
18885 focus: this.bindKeyDownListener.bind( this ),
18886 blur: this.unbindKeyDownListener.bind( this )
18887 } );
18888
18889 // Initialization
18890 this.$element.addClass( 'oo-ui-buttonSelectWidget' );
18891 };
18892
18893 /* Setup */
18894
18895 OO.inheritClass( OO.ui.ButtonSelectWidget, OO.ui.SelectWidget );
18896 OO.mixinClass( OO.ui.ButtonSelectWidget, OO.ui.mixin.TabIndexedElement );
18897
18898 /**
18899 * RadioSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains radio
18900 * options and is used together with OO.ui.RadioOptionWidget. The RadioSelectWidget provides
18901 * an interface for adding, removing and selecting options.
18902 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
18903 *
18904 * If you want to use this within a HTML form, such as a OO.ui.FormLayout, use
18905 * OO.ui.RadioSelectInputWidget instead.
18906 *
18907 * @example
18908 * // A RadioSelectWidget with RadioOptions.
18909 * var option1 = new OO.ui.RadioOptionWidget( {
18910 * data: 'a',
18911 * label: 'Selected radio option'
18912 * } );
18913 *
18914 * var option2 = new OO.ui.RadioOptionWidget( {
18915 * data: 'b',
18916 * label: 'Unselected radio option'
18917 * } );
18918 *
18919 * var radioSelect=new OO.ui.RadioSelectWidget( {
18920 * items: [ option1, option2 ]
18921 * } );
18922 *
18923 * // Select 'option 1' using the RadioSelectWidget's selectItem() method.
18924 * radioSelect.selectItem( option1 );
18925 *
18926 * $( 'body' ).append( radioSelect.$element );
18927 *
18928 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
18929
18930 *
18931 * @class
18932 * @extends OO.ui.SelectWidget
18933 * @mixins OO.ui.mixin.TabIndexedElement
18934 *
18935 * @constructor
18936 * @param {Object} [config] Configuration options
18937 */
18938 OO.ui.RadioSelectWidget = function OoUiRadioSelectWidget( config ) {
18939 // Parent constructor
18940 OO.ui.RadioSelectWidget.parent.call( this, config );
18941
18942 // Mixin constructors
18943 OO.ui.mixin.TabIndexedElement.call( this, config );
18944
18945 // Events
18946 this.$element.on( {
18947 focus: this.bindKeyDownListener.bind( this ),
18948 blur: this.unbindKeyDownListener.bind( this )
18949 } );
18950
18951 // Initialization
18952 this.$element
18953 .addClass( 'oo-ui-radioSelectWidget' )
18954 .attr( 'role', 'radiogroup' );
18955 };
18956
18957 /* Setup */
18958
18959 OO.inheritClass( OO.ui.RadioSelectWidget, OO.ui.SelectWidget );
18960 OO.mixinClass( OO.ui.RadioSelectWidget, OO.ui.mixin.TabIndexedElement );
18961
18962 /**
18963 * MenuSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains options and
18964 * is used together with OO.ui.MenuOptionWidget. It is designed be used as part of another widget.
18965 * See {@link OO.ui.DropdownWidget DropdownWidget}, {@link OO.ui.ComboBoxWidget ComboBoxWidget},
18966 * and {@link OO.ui.mixin.LookupElement LookupElement} for examples of widgets that contain menus.
18967 * MenuSelectWidgets themselves are not instantiated directly, rather subclassed
18968 * and customized to be opened, closed, and displayed as needed.
18969 *
18970 * By default, menus are clipped to the visible viewport and are not visible when a user presses the
18971 * mouse outside the menu.
18972 *
18973 * Menus also have support for keyboard interaction:
18974 *
18975 * - Enter/Return key: choose and select a menu option
18976 * - Up-arrow key: highlight the previous menu option
18977 * - Down-arrow key: highlight the next menu option
18978 * - Esc key: hide the menu
18979 *
18980 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
18981 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
18982 *
18983 * @class
18984 * @extends OO.ui.SelectWidget
18985 * @mixins OO.ui.mixin.ClippableElement
18986 *
18987 * @constructor
18988 * @param {Object} [config] Configuration options
18989 * @cfg {OO.ui.TextInputWidget} [input] Text input used to implement option highlighting for menu items that match
18990 * the text the user types. This config is used by {@link OO.ui.ComboBoxWidget ComboBoxWidget}
18991 * and {@link OO.ui.mixin.LookupElement LookupElement}
18992 * @cfg {jQuery} [$input] Text input used to implement option highlighting for menu items that match
18993 * the text the user types. This config is used by {@link OO.ui.CapsuleMultiSelectWidget CapsuleMultiSelectWidget}
18994 * @cfg {OO.ui.Widget} [widget] Widget associated with the menu's active state. If the user clicks the mouse
18995 * anywhere on the page outside of this widget, the menu is hidden. For example, if there is a button
18996 * that toggles the menu's visibility on click, the menu will be hidden then re-shown when the user clicks
18997 * that button, unless the button (or its parent widget) is passed in here.
18998 * @cfg {boolean} [autoHide=true] Hide the menu when the mouse is pressed outside the menu.
18999 * @cfg {boolean} [filterFromInput=false] Filter the displayed options from the input
19000 */
19001 OO.ui.MenuSelectWidget = function OoUiMenuSelectWidget( config ) {
19002 // Configuration initialization
19003 config = config || {};
19004
19005 // Parent constructor
19006 OO.ui.MenuSelectWidget.parent.call( this, config );
19007
19008 // Mixin constructors
19009 OO.ui.mixin.ClippableElement.call( this, $.extend( {}, config, { $clippable: this.$group } ) );
19010
19011 // Properties
19012 this.newItems = null;
19013 this.autoHide = config.autoHide === undefined || !!config.autoHide;
19014 this.filterFromInput = !!config.filterFromInput;
19015 this.$input = config.$input ? config.$input : config.input ? config.input.$input : null;
19016 this.$widget = config.widget ? config.widget.$element : null;
19017 this.onDocumentMouseDownHandler = this.onDocumentMouseDown.bind( this );
19018 this.onInputEditHandler = OO.ui.debounce( this.updateItemVisibility.bind( this ), 100 );
19019
19020 // Initialization
19021 this.$element
19022 .addClass( 'oo-ui-menuSelectWidget' )
19023 .attr( 'role', 'menu' );
19024
19025 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
19026 // that reference properties not initialized at that time of parent class construction
19027 // TODO: Find a better way to handle post-constructor setup
19028 this.visible = false;
19029 this.$element.addClass( 'oo-ui-element-hidden' );
19030 };
19031
19032 /* Setup */
19033
19034 OO.inheritClass( OO.ui.MenuSelectWidget, OO.ui.SelectWidget );
19035 OO.mixinClass( OO.ui.MenuSelectWidget, OO.ui.mixin.ClippableElement );
19036
19037 /* Methods */
19038
19039 /**
19040 * Handles document mouse down events.
19041 *
19042 * @protected
19043 * @param {jQuery.Event} e Key down event
19044 */
19045 OO.ui.MenuSelectWidget.prototype.onDocumentMouseDown = function ( e ) {
19046 if (
19047 !OO.ui.contains( this.$element[ 0 ], e.target, true ) &&
19048 ( !this.$widget || !OO.ui.contains( this.$widget[ 0 ], e.target, true ) )
19049 ) {
19050 this.toggle( false );
19051 }
19052 };
19053
19054 /**
19055 * @inheritdoc
19056 */
19057 OO.ui.MenuSelectWidget.prototype.onKeyDown = function ( e ) {
19058 var currentItem = this.getHighlightedItem() || this.getSelectedItem();
19059
19060 if ( !this.isDisabled() && this.isVisible() ) {
19061 switch ( e.keyCode ) {
19062 case OO.ui.Keys.LEFT:
19063 case OO.ui.Keys.RIGHT:
19064 // Do nothing if a text field is associated, arrow keys will be handled natively
19065 if ( !this.$input ) {
19066 OO.ui.MenuSelectWidget.parent.prototype.onKeyDown.call( this, e );
19067 }
19068 break;
19069 case OO.ui.Keys.ESCAPE:
19070 case OO.ui.Keys.TAB:
19071 if ( currentItem ) {
19072 currentItem.setHighlighted( false );
19073 }
19074 this.toggle( false );
19075 // Don't prevent tabbing away, prevent defocusing
19076 if ( e.keyCode === OO.ui.Keys.ESCAPE ) {
19077 e.preventDefault();
19078 e.stopPropagation();
19079 }
19080 break;
19081 default:
19082 OO.ui.MenuSelectWidget.parent.prototype.onKeyDown.call( this, e );
19083 return;
19084 }
19085 }
19086 };
19087
19088 /**
19089 * Update menu item visibility after input changes.
19090 * @protected
19091 */
19092 OO.ui.MenuSelectWidget.prototype.updateItemVisibility = function () {
19093 var i, item,
19094 len = this.items.length,
19095 showAll = !this.isVisible(),
19096 filter = showAll ? null : this.getItemMatcher( this.$input.val() );
19097
19098 for ( i = 0; i < len; i++ ) {
19099 item = this.items[ i ];
19100 if ( item instanceof OO.ui.OptionWidget ) {
19101 item.toggle( showAll || filter( item ) );
19102 }
19103 }
19104
19105 // Reevaluate clipping
19106 this.clip();
19107 };
19108
19109 /**
19110 * @inheritdoc
19111 */
19112 OO.ui.MenuSelectWidget.prototype.bindKeyDownListener = function () {
19113 if ( this.$input ) {
19114 this.$input.on( 'keydown', this.onKeyDownHandler );
19115 } else {
19116 OO.ui.MenuSelectWidget.parent.prototype.bindKeyDownListener.call( this );
19117 }
19118 };
19119
19120 /**
19121 * @inheritdoc
19122 */
19123 OO.ui.MenuSelectWidget.prototype.unbindKeyDownListener = function () {
19124 if ( this.$input ) {
19125 this.$input.off( 'keydown', this.onKeyDownHandler );
19126 } else {
19127 OO.ui.MenuSelectWidget.parent.prototype.unbindKeyDownListener.call( this );
19128 }
19129 };
19130
19131 /**
19132 * @inheritdoc
19133 */
19134 OO.ui.MenuSelectWidget.prototype.bindKeyPressListener = function () {
19135 if ( this.$input ) {
19136 if ( this.filterFromInput ) {
19137 this.$input.on( 'keydown mouseup cut paste change input select', this.onInputEditHandler );
19138 }
19139 } else {
19140 OO.ui.MenuSelectWidget.parent.prototype.bindKeyPressListener.call( this );
19141 }
19142 };
19143
19144 /**
19145 * @inheritdoc
19146 */
19147 OO.ui.MenuSelectWidget.prototype.unbindKeyPressListener = function () {
19148 if ( this.$input ) {
19149 if ( this.filterFromInput ) {
19150 this.$input.off( 'keydown mouseup cut paste change input select', this.onInputEditHandler );
19151 this.updateItemVisibility();
19152 }
19153 } else {
19154 OO.ui.MenuSelectWidget.parent.prototype.unbindKeyPressListener.call( this );
19155 }
19156 };
19157
19158 /**
19159 * Choose an item.
19160 *
19161 * When a user chooses an item, the menu is closed.
19162 *
19163 * Note that ‘choose’ should never be modified programmatically. A user can choose an option with the keyboard
19164 * or mouse and it becomes selected. To select an item programmatically, use the #selectItem method.
19165 * @param {OO.ui.OptionWidget} item Item to choose
19166 * @chainable
19167 */
19168 OO.ui.MenuSelectWidget.prototype.chooseItem = function ( item ) {
19169 OO.ui.MenuSelectWidget.parent.prototype.chooseItem.call( this, item );
19170 this.toggle( false );
19171 return this;
19172 };
19173
19174 /**
19175 * @inheritdoc
19176 */
19177 OO.ui.MenuSelectWidget.prototype.addItems = function ( items, index ) {
19178 var i, len, item;
19179
19180 // Parent method
19181 OO.ui.MenuSelectWidget.parent.prototype.addItems.call( this, items, index );
19182
19183 // Auto-initialize
19184 if ( !this.newItems ) {
19185 this.newItems = [];
19186 }
19187
19188 for ( i = 0, len = items.length; i < len; i++ ) {
19189 item = items[ i ];
19190 if ( this.isVisible() ) {
19191 // Defer fitting label until item has been attached
19192 item.fitLabel();
19193 } else {
19194 this.newItems.push( item );
19195 }
19196 }
19197
19198 // Reevaluate clipping
19199 this.clip();
19200
19201 return this;
19202 };
19203
19204 /**
19205 * @inheritdoc
19206 */
19207 OO.ui.MenuSelectWidget.prototype.removeItems = function ( items ) {
19208 // Parent method
19209 OO.ui.MenuSelectWidget.parent.prototype.removeItems.call( this, items );
19210
19211 // Reevaluate clipping
19212 this.clip();
19213
19214 return this;
19215 };
19216
19217 /**
19218 * @inheritdoc
19219 */
19220 OO.ui.MenuSelectWidget.prototype.clearItems = function () {
19221 // Parent method
19222 OO.ui.MenuSelectWidget.parent.prototype.clearItems.call( this );
19223
19224 // Reevaluate clipping
19225 this.clip();
19226
19227 return this;
19228 };
19229
19230 /**
19231 * @inheritdoc
19232 */
19233 OO.ui.MenuSelectWidget.prototype.toggle = function ( visible ) {
19234 var i, len, change;
19235
19236 visible = ( visible === undefined ? !this.visible : !!visible ) && !!this.items.length;
19237 change = visible !== this.isVisible();
19238
19239 // Parent method
19240 OO.ui.MenuSelectWidget.parent.prototype.toggle.call( this, visible );
19241
19242 if ( change ) {
19243 if ( visible ) {
19244 this.bindKeyDownListener();
19245 this.bindKeyPressListener();
19246
19247 if ( this.newItems && this.newItems.length ) {
19248 for ( i = 0, len = this.newItems.length; i < len; i++ ) {
19249 this.newItems[ i ].fitLabel();
19250 }
19251 this.newItems = null;
19252 }
19253 this.toggleClipping( true );
19254
19255 // Auto-hide
19256 if ( this.autoHide ) {
19257 OO.ui.addCaptureEventListener( this.getElementDocument(), 'mousedown', this.onDocumentMouseDownHandler );
19258 }
19259 } else {
19260 this.unbindKeyDownListener();
19261 this.unbindKeyPressListener();
19262 OO.ui.removeCaptureEventListener( this.getElementDocument(), 'mousedown', this.onDocumentMouseDownHandler );
19263 this.toggleClipping( false );
19264 }
19265 }
19266
19267 return this;
19268 };
19269
19270 /**
19271 * FloatingMenuSelectWidget is a menu that will stick under a specified
19272 * container, even when it is inserted elsewhere in the document (for example,
19273 * in a OO.ui.Window's $overlay). This is sometimes necessary to prevent the
19274 * menu from being clipped too aggresively.
19275 *
19276 * The menu's position is automatically calculated and maintained when the menu
19277 * is toggled or the window is resized.
19278 *
19279 * See OO.ui.ComboBoxWidget for an example of a widget that uses this class.
19280 *
19281 * @class
19282 * @extends OO.ui.MenuSelectWidget
19283 * @mixins OO.ui.mixin.FloatableElement
19284 *
19285 * @constructor
19286 * @param {OO.ui.Widget} [inputWidget] Widget to provide the menu for.
19287 * Deprecated, omit this parameter and specify `$container` instead.
19288 * @param {Object} [config] Configuration options
19289 * @cfg {jQuery} [$container=inputWidget.$element] Element to render menu under
19290 */
19291 OO.ui.FloatingMenuSelectWidget = function OoUiFloatingMenuSelectWidget( inputWidget, config ) {
19292 // Allow 'inputWidget' parameter and config for backwards compatibility
19293 if ( OO.isPlainObject( inputWidget ) && config === undefined ) {
19294 config = inputWidget;
19295 inputWidget = config.inputWidget;
19296 }
19297
19298 // Configuration initialization
19299 config = config || {};
19300
19301 // Parent constructor
19302 OO.ui.FloatingMenuSelectWidget.parent.call( this, config );
19303
19304 // Properties (must be set before mixin constructors)
19305 this.inputWidget = inputWidget; // For backwards compatibility
19306 this.$container = config.$container || this.inputWidget.$element;
19307
19308 // Mixins constructors
19309 OO.ui.mixin.FloatableElement.call( this, $.extend( {}, config, { $floatableContainer: this.$container } ) );
19310
19311 // Initialization
19312 this.$element.addClass( 'oo-ui-floatingMenuSelectWidget' );
19313 // For backwards compatibility
19314 this.$element.addClass( 'oo-ui-textInputMenuSelectWidget' );
19315 };
19316
19317 /* Setup */
19318
19319 OO.inheritClass( OO.ui.FloatingMenuSelectWidget, OO.ui.MenuSelectWidget );
19320 OO.mixinClass( OO.ui.FloatingMenuSelectWidget, OO.ui.mixin.FloatableElement );
19321
19322 // For backwards compatibility
19323 OO.ui.TextInputMenuSelectWidget = OO.ui.FloatingMenuSelectWidget;
19324
19325 /* Methods */
19326
19327 /**
19328 * @inheritdoc
19329 */
19330 OO.ui.FloatingMenuSelectWidget.prototype.toggle = function ( visible ) {
19331 var change;
19332 visible = visible === undefined ? !this.isVisible() : !!visible;
19333 change = visible !== this.isVisible();
19334
19335 if ( change && visible ) {
19336 // Make sure the width is set before the parent method runs.
19337 this.setIdealSize( this.$container.width() );
19338 }
19339
19340 // Parent method
19341 // This will call this.clip(), which is nonsensical since we're not positioned yet...
19342 OO.ui.FloatingMenuSelectWidget.parent.prototype.toggle.call( this, visible );
19343
19344 if ( change ) {
19345 this.togglePositioning( this.isVisible() );
19346 }
19347
19348 return this;
19349 };
19350
19351 /**
19352 * OutlineSelectWidget is a structured list that contains {@link OO.ui.OutlineOptionWidget outline options}
19353 * A set of controls can be provided with an {@link OO.ui.OutlineControlsWidget outline controls} widget.
19354 *
19355 * **Currently, this class is only used by {@link OO.ui.BookletLayout booklet layouts}.**
19356 *
19357 * @class
19358 * @extends OO.ui.SelectWidget
19359 * @mixins OO.ui.mixin.TabIndexedElement
19360 *
19361 * @constructor
19362 * @param {Object} [config] Configuration options
19363 */
19364 OO.ui.OutlineSelectWidget = function OoUiOutlineSelectWidget( config ) {
19365 // Parent constructor
19366 OO.ui.OutlineSelectWidget.parent.call( this, config );
19367
19368 // Mixin constructors
19369 OO.ui.mixin.TabIndexedElement.call( this, config );
19370
19371 // Events
19372 this.$element.on( {
19373 focus: this.bindKeyDownListener.bind( this ),
19374 blur: this.unbindKeyDownListener.bind( this )
19375 } );
19376
19377 // Initialization
19378 this.$element.addClass( 'oo-ui-outlineSelectWidget' );
19379 };
19380
19381 /* Setup */
19382
19383 OO.inheritClass( OO.ui.OutlineSelectWidget, OO.ui.SelectWidget );
19384 OO.mixinClass( OO.ui.OutlineSelectWidget, OO.ui.mixin.TabIndexedElement );
19385
19386 /**
19387 * TabSelectWidget is a list that contains {@link OO.ui.TabOptionWidget tab options}
19388 *
19389 * **Currently, this class is only used by {@link OO.ui.IndexLayout index layouts}.**
19390 *
19391 * @class
19392 * @extends OO.ui.SelectWidget
19393 * @mixins OO.ui.mixin.TabIndexedElement
19394 *
19395 * @constructor
19396 * @param {Object} [config] Configuration options
19397 */
19398 OO.ui.TabSelectWidget = function OoUiTabSelectWidget( config ) {
19399 // Parent constructor
19400 OO.ui.TabSelectWidget.parent.call( this, config );
19401
19402 // Mixin constructors
19403 OO.ui.mixin.TabIndexedElement.call( this, config );
19404
19405 // Events
19406 this.$element.on( {
19407 focus: this.bindKeyDownListener.bind( this ),
19408 blur: this.unbindKeyDownListener.bind( this )
19409 } );
19410
19411 // Initialization
19412 this.$element.addClass( 'oo-ui-tabSelectWidget' );
19413 };
19414
19415 /* Setup */
19416
19417 OO.inheritClass( OO.ui.TabSelectWidget, OO.ui.SelectWidget );
19418 OO.mixinClass( OO.ui.TabSelectWidget, OO.ui.mixin.TabIndexedElement );
19419
19420 /**
19421 * NumberInputWidgets combine a {@link OO.ui.TextInputWidget text input} (where a value
19422 * can be entered manually) and two {@link OO.ui.ButtonWidget button widgets}
19423 * (to adjust the value in increments) to allow the user to enter a number.
19424 *
19425 * @example
19426 * // Example: A NumberInputWidget.
19427 * var numberInput = new OO.ui.NumberInputWidget( {
19428 * label: 'NumberInputWidget',
19429 * input: { value: 5, min: 1, max: 10 }
19430 * } );
19431 * $( 'body' ).append( numberInput.$element );
19432 *
19433 * @class
19434 * @extends OO.ui.Widget
19435 *
19436 * @constructor
19437 * @param {Object} [config] Configuration options
19438 * @cfg {Object} [input] Configuration options to pass to the {@link OO.ui.TextInputWidget text input widget}.
19439 * @cfg {Object} [minusButton] Configuration options to pass to the {@link OO.ui.ButtonWidget decrementing button widget}.
19440 * @cfg {Object} [plusButton] Configuration options to pass to the {@link OO.ui.ButtonWidget incrementing button widget}.
19441 * @cfg {boolean} [isInteger=false] Whether the field accepts only integer values.
19442 * @cfg {number} [min=-Infinity] Minimum allowed value
19443 * @cfg {number} [max=Infinity] Maximum allowed value
19444 * @cfg {number} [step=1] Delta when using the buttons or up/down arrow keys
19445 * @cfg {number|null} [pageStep] Delta when using the page-up/page-down keys. Defaults to 10 times #step.
19446 */
19447 OO.ui.NumberInputWidget = function OoUiNumberInputWidget( config ) {
19448 // Configuration initialization
19449 config = $.extend( {
19450 isInteger: false,
19451 min: -Infinity,
19452 max: Infinity,
19453 step: 1,
19454 pageStep: null
19455 }, config );
19456
19457 // Parent constructor
19458 OO.ui.NumberInputWidget.parent.call( this, config );
19459
19460 // Properties
19461 this.input = new OO.ui.TextInputWidget( $.extend(
19462 {
19463 disabled: this.isDisabled()
19464 },
19465 config.input
19466 ) );
19467 this.minusButton = new OO.ui.ButtonWidget( $.extend(
19468 {
19469 disabled: this.isDisabled(),
19470 tabIndex: -1
19471 },
19472 config.minusButton,
19473 {
19474 classes: [ 'oo-ui-numberInputWidget-minusButton' ],
19475 label: '−'
19476 }
19477 ) );
19478 this.plusButton = new OO.ui.ButtonWidget( $.extend(
19479 {
19480 disabled: this.isDisabled(),
19481 tabIndex: -1
19482 },
19483 config.plusButton,
19484 {
19485 classes: [ 'oo-ui-numberInputWidget-plusButton' ],
19486 label: '+'
19487 }
19488 ) );
19489
19490 // Events
19491 this.input.connect( this, {
19492 change: this.emit.bind( this, 'change' ),
19493 enter: this.emit.bind( this, 'enter' )
19494 } );
19495 this.input.$input.on( {
19496 keydown: this.onKeyDown.bind( this ),
19497 'wheel mousewheel DOMMouseScroll': this.onWheel.bind( this )
19498 } );
19499 this.plusButton.connect( this, {
19500 click: [ 'onButtonClick', +1 ]
19501 } );
19502 this.minusButton.connect( this, {
19503 click: [ 'onButtonClick', -1 ]
19504 } );
19505
19506 // Initialization
19507 this.setIsInteger( !!config.isInteger );
19508 this.setRange( config.min, config.max );
19509 this.setStep( config.step, config.pageStep );
19510
19511 this.$field = $( '<div>' ).addClass( 'oo-ui-numberInputWidget-field' )
19512 .append(
19513 this.minusButton.$element,
19514 this.input.$element,
19515 this.plusButton.$element
19516 );
19517 this.$element.addClass( 'oo-ui-numberInputWidget' ).append( this.$field );
19518 this.input.setValidation( this.validateNumber.bind( this ) );
19519 };
19520
19521 /* Setup */
19522
19523 OO.inheritClass( OO.ui.NumberInputWidget, OO.ui.Widget );
19524
19525 /* Events */
19526
19527 /**
19528 * A `change` event is emitted when the value of the input changes.
19529 *
19530 * @event change
19531 */
19532
19533 /**
19534 * An `enter` event is emitted when the user presses 'enter' inside the text box.
19535 *
19536 * @event enter
19537 */
19538
19539 /* Methods */
19540
19541 /**
19542 * Set whether only integers are allowed
19543 * @param {boolean} flag
19544 */
19545 OO.ui.NumberInputWidget.prototype.setIsInteger = function ( flag ) {
19546 this.isInteger = !!flag;
19547 this.input.setValidityFlag();
19548 };
19549
19550 /**
19551 * Get whether only integers are allowed
19552 * @return {boolean} Flag value
19553 */
19554 OO.ui.NumberInputWidget.prototype.getIsInteger = function () {
19555 return this.isInteger;
19556 };
19557
19558 /**
19559 * Set the range of allowed values
19560 * @param {number} min Minimum allowed value
19561 * @param {number} max Maximum allowed value
19562 */
19563 OO.ui.NumberInputWidget.prototype.setRange = function ( min, max ) {
19564 if ( min > max ) {
19565 throw new Error( 'Minimum (' + min + ') must not be greater than maximum (' + max + ')' );
19566 }
19567 this.min = min;
19568 this.max = max;
19569 this.input.setValidityFlag();
19570 };
19571
19572 /**
19573 * Get the current range
19574 * @return {number[]} Minimum and maximum values
19575 */
19576 OO.ui.NumberInputWidget.prototype.getRange = function () {
19577 return [ this.min, this.max ];
19578 };
19579
19580 /**
19581 * Set the stepping deltas
19582 * @param {number} step Normal step
19583 * @param {number|null} pageStep Page step. If null, 10 * step will be used.
19584 */
19585 OO.ui.NumberInputWidget.prototype.setStep = function ( step, pageStep ) {
19586 if ( step <= 0 ) {
19587 throw new Error( 'Step value must be positive' );
19588 }
19589 if ( pageStep === null ) {
19590 pageStep = step * 10;
19591 } else if ( pageStep <= 0 ) {
19592 throw new Error( 'Page step value must be positive' );
19593 }
19594 this.step = step;
19595 this.pageStep = pageStep;
19596 };
19597
19598 /**
19599 * Get the current stepping values
19600 * @return {number[]} Step and page step
19601 */
19602 OO.ui.NumberInputWidget.prototype.getStep = function () {
19603 return [ this.step, this.pageStep ];
19604 };
19605
19606 /**
19607 * Get the current value of the widget
19608 * @return {string}
19609 */
19610 OO.ui.NumberInputWidget.prototype.getValue = function () {
19611 return this.input.getValue();
19612 };
19613
19614 /**
19615 * Get the current value of the widget as a number
19616 * @return {number} May be NaN, or an invalid number
19617 */
19618 OO.ui.NumberInputWidget.prototype.getNumericValue = function () {
19619 return +this.input.getValue();
19620 };
19621
19622 /**
19623 * Set the value of the widget
19624 * @param {string} value Invalid values are allowed
19625 */
19626 OO.ui.NumberInputWidget.prototype.setValue = function ( value ) {
19627 this.input.setValue( value );
19628 };
19629
19630 /**
19631 * Adjust the value of the widget
19632 * @param {number} delta Adjustment amount
19633 */
19634 OO.ui.NumberInputWidget.prototype.adjustValue = function ( delta ) {
19635 var n, v = this.getNumericValue();
19636
19637 delta = +delta;
19638 if ( isNaN( delta ) || !isFinite( delta ) ) {
19639 throw new Error( 'Delta must be a finite number' );
19640 }
19641
19642 if ( isNaN( v ) ) {
19643 n = 0;
19644 } else {
19645 n = v + delta;
19646 n = Math.max( Math.min( n, this.max ), this.min );
19647 if ( this.isInteger ) {
19648 n = Math.round( n );
19649 }
19650 }
19651
19652 if ( n !== v ) {
19653 this.setValue( n );
19654 }
19655 };
19656
19657 /**
19658 * Validate input
19659 * @private
19660 * @param {string} value Field value
19661 * @return {boolean}
19662 */
19663 OO.ui.NumberInputWidget.prototype.validateNumber = function ( value ) {
19664 var n = +value;
19665 if ( isNaN( n ) || !isFinite( n ) ) {
19666 return false;
19667 }
19668
19669 /*jshint bitwise: false */
19670 if ( this.isInteger && ( n | 0 ) !== n ) {
19671 return false;
19672 }
19673 /*jshint bitwise: true */
19674
19675 if ( n < this.min || n > this.max ) {
19676 return false;
19677 }
19678
19679 return true;
19680 };
19681
19682 /**
19683 * Handle mouse click events.
19684 *
19685 * @private
19686 * @param {number} dir +1 or -1
19687 */
19688 OO.ui.NumberInputWidget.prototype.onButtonClick = function ( dir ) {
19689 this.adjustValue( dir * this.step );
19690 };
19691
19692 /**
19693 * Handle mouse wheel events.
19694 *
19695 * @private
19696 * @param {jQuery.Event} event
19697 */
19698 OO.ui.NumberInputWidget.prototype.onWheel = function ( event ) {
19699 var delta = 0;
19700
19701 // Standard 'wheel' event
19702 if ( event.originalEvent.deltaMode !== undefined ) {
19703 this.sawWheelEvent = true;
19704 }
19705 if ( event.originalEvent.deltaY ) {
19706 delta = -event.originalEvent.deltaY;
19707 } else if ( event.originalEvent.deltaX ) {
19708 delta = event.originalEvent.deltaX;
19709 }
19710
19711 // Non-standard events
19712 if ( !this.sawWheelEvent ) {
19713 if ( event.originalEvent.wheelDeltaX ) {
19714 delta = -event.originalEvent.wheelDeltaX;
19715 } else if ( event.originalEvent.wheelDeltaY ) {
19716 delta = event.originalEvent.wheelDeltaY;
19717 } else if ( event.originalEvent.wheelDelta ) {
19718 delta = event.originalEvent.wheelDelta;
19719 } else if ( event.originalEvent.detail ) {
19720 delta = -event.originalEvent.detail;
19721 }
19722 }
19723
19724 if ( delta ) {
19725 delta = delta < 0 ? -1 : 1;
19726 this.adjustValue( delta * this.step );
19727 }
19728
19729 return false;
19730 };
19731
19732 /**
19733 * Handle key down events.
19734 *
19735 * @private
19736 * @param {jQuery.Event} e Key down event
19737 */
19738 OO.ui.NumberInputWidget.prototype.onKeyDown = function ( e ) {
19739 if ( !this.isDisabled() ) {
19740 switch ( e.which ) {
19741 case OO.ui.Keys.UP:
19742 this.adjustValue( this.step );
19743 return false;
19744 case OO.ui.Keys.DOWN:
19745 this.adjustValue( -this.step );
19746 return false;
19747 case OO.ui.Keys.PAGEUP:
19748 this.adjustValue( this.pageStep );
19749 return false;
19750 case OO.ui.Keys.PAGEDOWN:
19751 this.adjustValue( -this.pageStep );
19752 return false;
19753 }
19754 }
19755 };
19756
19757 /**
19758 * @inheritdoc
19759 */
19760 OO.ui.NumberInputWidget.prototype.setDisabled = function ( disabled ) {
19761 // Parent method
19762 OO.ui.NumberInputWidget.parent.prototype.setDisabled.call( this, disabled );
19763
19764 if ( this.input ) {
19765 this.input.setDisabled( this.isDisabled() );
19766 }
19767 if ( this.minusButton ) {
19768 this.minusButton.setDisabled( this.isDisabled() );
19769 }
19770 if ( this.plusButton ) {
19771 this.plusButton.setDisabled( this.isDisabled() );
19772 }
19773
19774 return this;
19775 };
19776
19777 /**
19778 * ToggleSwitches are switches that slide on and off. Their state is represented by a Boolean
19779 * value (`true` for ‘on’, and `false` otherwise, the default). The ‘off’ state is represented
19780 * visually by a slider in the leftmost position.
19781 *
19782 * @example
19783 * // Toggle switches in the 'off' and 'on' position.
19784 * var toggleSwitch1 = new OO.ui.ToggleSwitchWidget();
19785 * var toggleSwitch2 = new OO.ui.ToggleSwitchWidget( {
19786 * value: true
19787 * } );
19788 *
19789 * // Create a FieldsetLayout to layout and label switches
19790 * var fieldset = new OO.ui.FieldsetLayout( {
19791 * label: 'Toggle switches'
19792 * } );
19793 * fieldset.addItems( [
19794 * new OO.ui.FieldLayout( toggleSwitch1, { label: 'Off', align: 'top' } ),
19795 * new OO.ui.FieldLayout( toggleSwitch2, { label: 'On', align: 'top' } )
19796 * ] );
19797 * $( 'body' ).append( fieldset.$element );
19798 *
19799 * @class
19800 * @extends OO.ui.ToggleWidget
19801 * @mixins OO.ui.mixin.TabIndexedElement
19802 *
19803 * @constructor
19804 * @param {Object} [config] Configuration options
19805 * @cfg {boolean} [value=false] The toggle switch’s initial on/off state.
19806 * By default, the toggle switch is in the 'off' position.
19807 */
19808 OO.ui.ToggleSwitchWidget = function OoUiToggleSwitchWidget( config ) {
19809 // Parent constructor
19810 OO.ui.ToggleSwitchWidget.parent.call( this, config );
19811
19812 // Mixin constructors
19813 OO.ui.mixin.TabIndexedElement.call( this, config );
19814
19815 // Properties
19816 this.dragging = false;
19817 this.dragStart = null;
19818 this.sliding = false;
19819 this.$glow = $( '<span>' );
19820 this.$grip = $( '<span>' );
19821
19822 // Events
19823 this.$element.on( {
19824 click: this.onClick.bind( this ),
19825 keypress: this.onKeyPress.bind( this )
19826 } );
19827
19828 // Initialization
19829 this.$glow.addClass( 'oo-ui-toggleSwitchWidget-glow' );
19830 this.$grip.addClass( 'oo-ui-toggleSwitchWidget-grip' );
19831 this.$element
19832 .addClass( 'oo-ui-toggleSwitchWidget' )
19833 .attr( 'role', 'checkbox' )
19834 .append( this.$glow, this.$grip );
19835 };
19836
19837 /* Setup */
19838
19839 OO.inheritClass( OO.ui.ToggleSwitchWidget, OO.ui.ToggleWidget );
19840 OO.mixinClass( OO.ui.ToggleSwitchWidget, OO.ui.mixin.TabIndexedElement );
19841
19842 /* Methods */
19843
19844 /**
19845 * Handle mouse click events.
19846 *
19847 * @private
19848 * @param {jQuery.Event} e Mouse click event
19849 */
19850 OO.ui.ToggleSwitchWidget.prototype.onClick = function ( e ) {
19851 if ( !this.isDisabled() && e.which === 1 ) {
19852 this.setValue( !this.value );
19853 }
19854 return false;
19855 };
19856
19857 /**
19858 * Handle key press events.
19859 *
19860 * @private
19861 * @param {jQuery.Event} e Key press event
19862 */
19863 OO.ui.ToggleSwitchWidget.prototype.onKeyPress = function ( e ) {
19864 if ( !this.isDisabled() && ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER ) ) {
19865 this.setValue( !this.value );
19866 return false;
19867 }
19868 };
19869
19870 }( OO ) );