Merge "Fix hook documentation for UploadFormSourceDescriptors"
[lhc/web/wiklou.git] / resources / lib / oojs-ui / oojs-ui.js
1 /*!
2 * OOjs UI v0.12.9
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-09-22T20:09:51Z
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 {Mixed} [data] Custom data of any type or combination of types (e.g., string, number, array, object).
1110 * Data can also be specified with the #setData method.
1111 */
1112 OO.ui.Element = function OoUiElement( config ) {
1113 // Configuration initialization
1114 config = config || {};
1115
1116 // Properties
1117 this.$ = $;
1118 this.visible = true;
1119 this.data = config.data;
1120 this.$element = config.$element ||
1121 $( document.createElement( this.getTagName() ) );
1122 this.elementGroup = null;
1123 this.debouncedUpdateThemeClassesHandler = OO.ui.debounce( this.debouncedUpdateThemeClasses );
1124
1125 // Initialization
1126 if ( Array.isArray( config.classes ) ) {
1127 this.$element.addClass( config.classes.join( ' ' ) );
1128 }
1129 if ( config.id ) {
1130 this.$element.attr( 'id', config.id );
1131 }
1132 if ( config.text ) {
1133 this.$element.text( config.text );
1134 }
1135 if ( config.content ) {
1136 // The `content` property treats plain strings as text; use an
1137 // HtmlSnippet to append HTML content. `OO.ui.Element`s get their
1138 // appropriate $element appended.
1139 this.$element.append( config.content.map( function ( v ) {
1140 if ( typeof v === 'string' ) {
1141 // Escape string so it is properly represented in HTML.
1142 return document.createTextNode( v );
1143 } else if ( v instanceof OO.ui.HtmlSnippet ) {
1144 // Bypass escaping.
1145 return v.toString();
1146 } else if ( v instanceof OO.ui.Element ) {
1147 return v.$element;
1148 }
1149 return v;
1150 } ) );
1151 }
1152 if ( config.$content ) {
1153 // The `$content` property treats plain strings as HTML.
1154 this.$element.append( config.$content );
1155 }
1156 };
1157
1158 /* Setup */
1159
1160 OO.initClass( OO.ui.Element );
1161
1162 /* Static Properties */
1163
1164 /**
1165 * The name of the HTML tag used by the element.
1166 *
1167 * The static value may be ignored if the #getTagName method is overridden.
1168 *
1169 * @static
1170 * @inheritable
1171 * @property {string}
1172 */
1173 OO.ui.Element.static.tagName = 'div';
1174
1175 /* Static Methods */
1176
1177 /**
1178 * Reconstitute a JavaScript object corresponding to a widget created
1179 * by the PHP implementation.
1180 *
1181 * @param {string|HTMLElement|jQuery} idOrNode
1182 * A DOM id (if a string) or node for the widget to infuse.
1183 * @return {OO.ui.Element}
1184 * The `OO.ui.Element` corresponding to this (infusable) document node.
1185 * For `Tag` objects emitted on the HTML side (used occasionally for content)
1186 * the value returned is a newly-created Element wrapping around the existing
1187 * DOM node.
1188 */
1189 OO.ui.Element.static.infuse = function ( idOrNode ) {
1190 var obj = OO.ui.Element.static.unsafeInfuse( idOrNode, false );
1191 // Verify that the type matches up.
1192 // FIXME: uncomment after T89721 is fixed (see T90929)
1193 /*
1194 if ( !( obj instanceof this['class'] ) ) {
1195 throw new Error( 'Infusion type mismatch!' );
1196 }
1197 */
1198 return obj;
1199 };
1200
1201 /**
1202 * Implementation helper for `infuse`; skips the type check and has an
1203 * extra property so that only the top-level invocation touches the DOM.
1204 * @private
1205 * @param {string|HTMLElement|jQuery} idOrNode
1206 * @param {jQuery.Promise|boolean} domPromise A promise that will be resolved
1207 * when the top-level widget of this infusion is inserted into DOM,
1208 * replacing the original node; or false for top-level invocation.
1209 * @return {OO.ui.Element}
1210 */
1211 OO.ui.Element.static.unsafeInfuse = function ( idOrNode, domPromise ) {
1212 // look for a cached result of a previous infusion.
1213 var id, $elem, data, cls, parts, parent, obj, top, state;
1214 if ( typeof idOrNode === 'string' ) {
1215 id = idOrNode;
1216 $elem = $( document.getElementById( id ) );
1217 } else {
1218 $elem = $( idOrNode );
1219 id = $elem.attr( 'id' );
1220 }
1221 if ( !$elem.length ) {
1222 throw new Error( 'Widget not found: ' + id );
1223 }
1224 data = $elem.data( 'ooui-infused' ) || $elem[ 0 ].oouiInfused;
1225 if ( data ) {
1226 // cached!
1227 if ( data === true ) {
1228 throw new Error( 'Circular dependency! ' + id );
1229 }
1230 return data;
1231 }
1232 data = $elem.attr( 'data-ooui' );
1233 if ( !data ) {
1234 throw new Error( 'No infusion data found: ' + id );
1235 }
1236 try {
1237 data = $.parseJSON( data );
1238 } catch ( _ ) {
1239 data = null;
1240 }
1241 if ( !( data && data._ ) ) {
1242 throw new Error( 'No valid infusion data found: ' + id );
1243 }
1244 if ( data._ === 'Tag' ) {
1245 // Special case: this is a raw Tag; wrap existing node, don't rebuild.
1246 return new OO.ui.Element( { $element: $elem } );
1247 }
1248 parts = data._.split( '.' );
1249 cls = OO.getProp.apply( OO, [ window ].concat( parts ) );
1250 if ( cls === undefined ) {
1251 // The PHP output might be old and not including the "OO.ui" prefix
1252 // TODO: Remove this back-compat after next major release
1253 cls = OO.getProp.apply( OO, [ OO.ui ].concat( parts ) );
1254 if ( cls === undefined ) {
1255 throw new Error( 'Unknown widget type: id: ' + id + ', class: ' + data._ );
1256 }
1257 }
1258
1259 // Verify that we're creating an OO.ui.Element instance
1260 parent = cls.parent;
1261
1262 while ( parent !== undefined ) {
1263 if ( parent === OO.ui.Element ) {
1264 // Safe
1265 break;
1266 }
1267
1268 parent = parent.parent;
1269 }
1270
1271 if ( parent !== OO.ui.Element ) {
1272 throw new Error( 'Unknown widget type: id: ' + id + ', class: ' + data._ );
1273 }
1274
1275 if ( domPromise === false ) {
1276 top = $.Deferred();
1277 domPromise = top.promise();
1278 }
1279 $elem.data( 'ooui-infused', true ); // prevent loops
1280 data.id = id; // implicit
1281 data = OO.copy( data, null, function deserialize( value ) {
1282 if ( OO.isPlainObject( value ) ) {
1283 if ( value.tag ) {
1284 return OO.ui.Element.static.unsafeInfuse( value.tag, domPromise );
1285 }
1286 if ( value.html ) {
1287 return new OO.ui.HtmlSnippet( value.html );
1288 }
1289 }
1290 } );
1291 // jscs:disable requireCapitalizedConstructors
1292 obj = new cls( data ); // rebuild widget
1293 // pick up dynamic state, like focus, value of form inputs, scroll position, etc.
1294 state = obj.gatherPreInfuseState( $elem );
1295 // now replace old DOM with this new DOM.
1296 if ( top ) {
1297 $elem.replaceWith( obj.$element );
1298 // This element is now gone from the DOM, but if anyone is holding a reference to it,
1299 // let's allow them to OO.ui.infuse() it and do what they expect (T105828).
1300 // Do not use jQuery.data(), as using it on detached nodes leaks memory in 1.x line by design.
1301 $elem[ 0 ].oouiInfused = obj;
1302 top.resolve();
1303 }
1304 obj.$element.data( 'ooui-infused', obj );
1305 // set the 'data-ooui' attribute so we can identify infused widgets
1306 obj.$element.attr( 'data-ooui', '' );
1307 // restore dynamic state after the new element is inserted into DOM
1308 domPromise.done( obj.restorePreInfuseState.bind( obj, state ) );
1309 return obj;
1310 };
1311
1312 /**
1313 * Get a jQuery function within a specific document.
1314 *
1315 * @static
1316 * @param {jQuery|HTMLElement|HTMLDocument|Window} context Context to bind the function to
1317 * @param {jQuery} [$iframe] HTML iframe element that contains the document, omit if document is
1318 * not in an iframe
1319 * @return {Function} Bound jQuery function
1320 */
1321 OO.ui.Element.static.getJQuery = function ( context, $iframe ) {
1322 function wrapper( selector ) {
1323 return $( selector, wrapper.context );
1324 }
1325
1326 wrapper.context = this.getDocument( context );
1327
1328 if ( $iframe ) {
1329 wrapper.$iframe = $iframe;
1330 }
1331
1332 return wrapper;
1333 };
1334
1335 /**
1336 * Get the document of an element.
1337 *
1338 * @static
1339 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Object to get the document for
1340 * @return {HTMLDocument|null} Document object
1341 */
1342 OO.ui.Element.static.getDocument = function ( obj ) {
1343 // jQuery - selections created "offscreen" won't have a context, so .context isn't reliable
1344 return ( obj[ 0 ] && obj[ 0 ].ownerDocument ) ||
1345 // Empty jQuery selections might have a context
1346 obj.context ||
1347 // HTMLElement
1348 obj.ownerDocument ||
1349 // Window
1350 obj.document ||
1351 // HTMLDocument
1352 ( obj.nodeType === 9 && obj ) ||
1353 null;
1354 };
1355
1356 /**
1357 * Get the window of an element or document.
1358 *
1359 * @static
1360 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the window for
1361 * @return {Window} Window object
1362 */
1363 OO.ui.Element.static.getWindow = function ( obj ) {
1364 var doc = this.getDocument( obj );
1365 // Support: IE 8
1366 // Standard Document.defaultView is IE9+
1367 return doc.parentWindow || doc.defaultView;
1368 };
1369
1370 /**
1371 * Get the direction of an element or document.
1372 *
1373 * @static
1374 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the direction for
1375 * @return {string} Text direction, either 'ltr' or 'rtl'
1376 */
1377 OO.ui.Element.static.getDir = function ( obj ) {
1378 var isDoc, isWin;
1379
1380 if ( obj instanceof jQuery ) {
1381 obj = obj[ 0 ];
1382 }
1383 isDoc = obj.nodeType === 9;
1384 isWin = obj.document !== undefined;
1385 if ( isDoc || isWin ) {
1386 if ( isWin ) {
1387 obj = obj.document;
1388 }
1389 obj = obj.body;
1390 }
1391 return $( obj ).css( 'direction' );
1392 };
1393
1394 /**
1395 * Get the offset between two frames.
1396 *
1397 * TODO: Make this function not use recursion.
1398 *
1399 * @static
1400 * @param {Window} from Window of the child frame
1401 * @param {Window} [to=window] Window of the parent frame
1402 * @param {Object} [offset] Offset to start with, used internally
1403 * @return {Object} Offset object, containing left and top properties
1404 */
1405 OO.ui.Element.static.getFrameOffset = function ( from, to, offset ) {
1406 var i, len, frames, frame, rect;
1407
1408 if ( !to ) {
1409 to = window;
1410 }
1411 if ( !offset ) {
1412 offset = { top: 0, left: 0 };
1413 }
1414 if ( from.parent === from ) {
1415 return offset;
1416 }
1417
1418 // Get iframe element
1419 frames = from.parent.document.getElementsByTagName( 'iframe' );
1420 for ( i = 0, len = frames.length; i < len; i++ ) {
1421 if ( frames[ i ].contentWindow === from ) {
1422 frame = frames[ i ];
1423 break;
1424 }
1425 }
1426
1427 // Recursively accumulate offset values
1428 if ( frame ) {
1429 rect = frame.getBoundingClientRect();
1430 offset.left += rect.left;
1431 offset.top += rect.top;
1432 if ( from !== to ) {
1433 this.getFrameOffset( from.parent, offset );
1434 }
1435 }
1436 return offset;
1437 };
1438
1439 /**
1440 * Get the offset between two elements.
1441 *
1442 * The two elements may be in a different frame, but in that case the frame $element is in must
1443 * be contained in the frame $anchor is in.
1444 *
1445 * @static
1446 * @param {jQuery} $element Element whose position to get
1447 * @param {jQuery} $anchor Element to get $element's position relative to
1448 * @return {Object} Translated position coordinates, containing top and left properties
1449 */
1450 OO.ui.Element.static.getRelativePosition = function ( $element, $anchor ) {
1451 var iframe, iframePos,
1452 pos = $element.offset(),
1453 anchorPos = $anchor.offset(),
1454 elementDocument = this.getDocument( $element ),
1455 anchorDocument = this.getDocument( $anchor );
1456
1457 // If $element isn't in the same document as $anchor, traverse up
1458 while ( elementDocument !== anchorDocument ) {
1459 iframe = elementDocument.defaultView.frameElement;
1460 if ( !iframe ) {
1461 throw new Error( '$element frame is not contained in $anchor frame' );
1462 }
1463 iframePos = $( iframe ).offset();
1464 pos.left += iframePos.left;
1465 pos.top += iframePos.top;
1466 elementDocument = iframe.ownerDocument;
1467 }
1468 pos.left -= anchorPos.left;
1469 pos.top -= anchorPos.top;
1470 return pos;
1471 };
1472
1473 /**
1474 * Get element border sizes.
1475 *
1476 * @static
1477 * @param {HTMLElement} el Element to measure
1478 * @return {Object} Dimensions object with `top`, `left`, `bottom` and `right` properties
1479 */
1480 OO.ui.Element.static.getBorders = function ( el ) {
1481 var doc = el.ownerDocument,
1482 // Support: IE 8
1483 // Standard Document.defaultView is IE9+
1484 win = doc.parentWindow || doc.defaultView,
1485 style = win && win.getComputedStyle ?
1486 win.getComputedStyle( el, null ) :
1487 // Support: IE 8
1488 // Standard getComputedStyle() is IE9+
1489 el.currentStyle,
1490 $el = $( el ),
1491 top = parseFloat( style ? style.borderTopWidth : $el.css( 'borderTopWidth' ) ) || 0,
1492 left = parseFloat( style ? style.borderLeftWidth : $el.css( 'borderLeftWidth' ) ) || 0,
1493 bottom = parseFloat( style ? style.borderBottomWidth : $el.css( 'borderBottomWidth' ) ) || 0,
1494 right = parseFloat( style ? style.borderRightWidth : $el.css( 'borderRightWidth' ) ) || 0;
1495
1496 return {
1497 top: top,
1498 left: left,
1499 bottom: bottom,
1500 right: right
1501 };
1502 };
1503
1504 /**
1505 * Get dimensions of an element or window.
1506 *
1507 * @static
1508 * @param {HTMLElement|Window} el Element to measure
1509 * @return {Object} Dimensions object with `borders`, `scroll`, `scrollbar` and `rect` properties
1510 */
1511 OO.ui.Element.static.getDimensions = function ( el ) {
1512 var $el, $win,
1513 doc = el.ownerDocument || el.document,
1514 // Support: IE 8
1515 // Standard Document.defaultView is IE9+
1516 win = doc.parentWindow || doc.defaultView;
1517
1518 if ( win === el || el === doc.documentElement ) {
1519 $win = $( win );
1520 return {
1521 borders: { top: 0, left: 0, bottom: 0, right: 0 },
1522 scroll: {
1523 top: $win.scrollTop(),
1524 left: $win.scrollLeft()
1525 },
1526 scrollbar: { right: 0, bottom: 0 },
1527 rect: {
1528 top: 0,
1529 left: 0,
1530 bottom: $win.innerHeight(),
1531 right: $win.innerWidth()
1532 }
1533 };
1534 } else {
1535 $el = $( el );
1536 return {
1537 borders: this.getBorders( el ),
1538 scroll: {
1539 top: $el.scrollTop(),
1540 left: $el.scrollLeft()
1541 },
1542 scrollbar: {
1543 right: $el.innerWidth() - el.clientWidth,
1544 bottom: $el.innerHeight() - el.clientHeight
1545 },
1546 rect: el.getBoundingClientRect()
1547 };
1548 }
1549 };
1550
1551 /**
1552 * Get scrollable object parent
1553 *
1554 * documentElement can't be used to get or set the scrollTop
1555 * property on Blink. Changing and testing its value lets us
1556 * use 'body' or 'documentElement' based on what is working.
1557 *
1558 * https://code.google.com/p/chromium/issues/detail?id=303131
1559 *
1560 * @static
1561 * @param {HTMLElement} el Element to find scrollable parent for
1562 * @return {HTMLElement} Scrollable parent
1563 */
1564 OO.ui.Element.static.getRootScrollableElement = function ( el ) {
1565 var scrollTop, body;
1566
1567 if ( OO.ui.scrollableElement === undefined ) {
1568 body = el.ownerDocument.body;
1569 scrollTop = body.scrollTop;
1570 body.scrollTop = 1;
1571
1572 if ( body.scrollTop === 1 ) {
1573 body.scrollTop = scrollTop;
1574 OO.ui.scrollableElement = 'body';
1575 } else {
1576 OO.ui.scrollableElement = 'documentElement';
1577 }
1578 }
1579
1580 return el.ownerDocument[ OO.ui.scrollableElement ];
1581 };
1582
1583 /**
1584 * Get closest scrollable container.
1585 *
1586 * Traverses up until either a scrollable element or the root is reached, in which case the window
1587 * will be returned.
1588 *
1589 * @static
1590 * @param {HTMLElement} el Element to find scrollable container for
1591 * @param {string} [dimension] Dimension of scrolling to look for; `x`, `y` or omit for either
1592 * @return {HTMLElement} Closest scrollable container
1593 */
1594 OO.ui.Element.static.getClosestScrollableContainer = function ( el, dimension ) {
1595 var i, val,
1596 // props = [ 'overflow' ] doesn't work due to https://bugzilla.mozilla.org/show_bug.cgi?id=889091
1597 props = [ 'overflow-x', 'overflow-y' ],
1598 $parent = $( el ).parent();
1599
1600 if ( dimension === 'x' || dimension === 'y' ) {
1601 props = [ 'overflow-' + dimension ];
1602 }
1603
1604 while ( $parent.length ) {
1605 if ( $parent[ 0 ] === this.getRootScrollableElement( el ) ) {
1606 return $parent[ 0 ];
1607 }
1608 i = props.length;
1609 while ( i-- ) {
1610 val = $parent.css( props[ i ] );
1611 if ( val === 'auto' || val === 'scroll' ) {
1612 return $parent[ 0 ];
1613 }
1614 }
1615 $parent = $parent.parent();
1616 }
1617 return this.getDocument( el ).body;
1618 };
1619
1620 /**
1621 * Scroll element into view.
1622 *
1623 * @static
1624 * @param {HTMLElement} el Element to scroll into view
1625 * @param {Object} [config] Configuration options
1626 * @param {string} [config.duration] jQuery animation duration value
1627 * @param {string} [config.direction] Scroll in only one direction, e.g. 'x' or 'y', omit
1628 * to scroll in both directions
1629 * @param {Function} [config.complete] Function to call when scrolling completes
1630 */
1631 OO.ui.Element.static.scrollIntoView = function ( el, config ) {
1632 var rel, anim, callback, sc, $sc, eld, scd, $win;
1633
1634 // Configuration initialization
1635 config = config || {};
1636
1637 anim = {};
1638 callback = typeof config.complete === 'function' && config.complete;
1639 sc = this.getClosestScrollableContainer( el, config.direction );
1640 $sc = $( sc );
1641 eld = this.getDimensions( el );
1642 scd = this.getDimensions( sc );
1643 $win = $( this.getWindow( el ) );
1644
1645 // Compute the distances between the edges of el and the edges of the scroll viewport
1646 if ( $sc.is( 'html, body' ) ) {
1647 // If the scrollable container is the root, this is easy
1648 rel = {
1649 top: eld.rect.top,
1650 bottom: $win.innerHeight() - eld.rect.bottom,
1651 left: eld.rect.left,
1652 right: $win.innerWidth() - eld.rect.right
1653 };
1654 } else {
1655 // Otherwise, we have to subtract el's coordinates from sc's coordinates
1656 rel = {
1657 top: eld.rect.top - ( scd.rect.top + scd.borders.top ),
1658 bottom: scd.rect.bottom - scd.borders.bottom - scd.scrollbar.bottom - eld.rect.bottom,
1659 left: eld.rect.left - ( scd.rect.left + scd.borders.left ),
1660 right: scd.rect.right - scd.borders.right - scd.scrollbar.right - eld.rect.right
1661 };
1662 }
1663
1664 if ( !config.direction || config.direction === 'y' ) {
1665 if ( rel.top < 0 ) {
1666 anim.scrollTop = scd.scroll.top + rel.top;
1667 } else if ( rel.top > 0 && rel.bottom < 0 ) {
1668 anim.scrollTop = scd.scroll.top + Math.min( rel.top, -rel.bottom );
1669 }
1670 }
1671 if ( !config.direction || config.direction === 'x' ) {
1672 if ( rel.left < 0 ) {
1673 anim.scrollLeft = scd.scroll.left + rel.left;
1674 } else if ( rel.left > 0 && rel.right < 0 ) {
1675 anim.scrollLeft = scd.scroll.left + Math.min( rel.left, -rel.right );
1676 }
1677 }
1678 if ( !$.isEmptyObject( anim ) ) {
1679 $sc.stop( true ).animate( anim, config.duration || 'fast' );
1680 if ( callback ) {
1681 $sc.queue( function ( next ) {
1682 callback();
1683 next();
1684 } );
1685 }
1686 } else {
1687 if ( callback ) {
1688 callback();
1689 }
1690 }
1691 };
1692
1693 /**
1694 * Force the browser to reconsider whether it really needs to render scrollbars inside the element
1695 * and reserve space for them, because it probably doesn't.
1696 *
1697 * Workaround primarily for <https://code.google.com/p/chromium/issues/detail?id=387290>, but also
1698 * similar bugs in other browsers. "Just" forcing a reflow is not sufficient in all cases, we need
1699 * to first actually detach (or hide, but detaching is simpler) all children, *then* force a reflow,
1700 * and then reattach (or show) them back.
1701 *
1702 * @static
1703 * @param {HTMLElement} el Element to reconsider the scrollbars on
1704 */
1705 OO.ui.Element.static.reconsiderScrollbars = function ( el ) {
1706 var i, len, scrollLeft, scrollTop, nodes = [];
1707 // Save scroll position
1708 scrollLeft = el.scrollLeft;
1709 scrollTop = el.scrollTop;
1710 // Detach all children
1711 while ( el.firstChild ) {
1712 nodes.push( el.firstChild );
1713 el.removeChild( el.firstChild );
1714 }
1715 // Force reflow
1716 void el.offsetHeight;
1717 // Reattach all children
1718 for ( i = 0, len = nodes.length; i < len; i++ ) {
1719 el.appendChild( nodes[ i ] );
1720 }
1721 // Restore scroll position (no-op if scrollbars disappeared)
1722 el.scrollLeft = scrollLeft;
1723 el.scrollTop = scrollTop;
1724 };
1725
1726 /* Methods */
1727
1728 /**
1729 * Toggle visibility of an element.
1730 *
1731 * @param {boolean} [show] Make element visible, omit to toggle visibility
1732 * @fires visible
1733 * @chainable
1734 */
1735 OO.ui.Element.prototype.toggle = function ( show ) {
1736 show = show === undefined ? !this.visible : !!show;
1737
1738 if ( show !== this.isVisible() ) {
1739 this.visible = show;
1740 this.$element.toggleClass( 'oo-ui-element-hidden', !this.visible );
1741 this.emit( 'toggle', show );
1742 }
1743
1744 return this;
1745 };
1746
1747 /**
1748 * Check if element is visible.
1749 *
1750 * @return {boolean} element is visible
1751 */
1752 OO.ui.Element.prototype.isVisible = function () {
1753 return this.visible;
1754 };
1755
1756 /**
1757 * Get element data.
1758 *
1759 * @return {Mixed} Element data
1760 */
1761 OO.ui.Element.prototype.getData = function () {
1762 return this.data;
1763 };
1764
1765 /**
1766 * Set element data.
1767 *
1768 * @param {Mixed} Element data
1769 * @chainable
1770 */
1771 OO.ui.Element.prototype.setData = function ( data ) {
1772 this.data = data;
1773 return this;
1774 };
1775
1776 /**
1777 * Check if element supports one or more methods.
1778 *
1779 * @param {string|string[]} methods Method or list of methods to check
1780 * @return {boolean} All methods are supported
1781 */
1782 OO.ui.Element.prototype.supports = function ( methods ) {
1783 var i, len,
1784 support = 0;
1785
1786 methods = Array.isArray( methods ) ? methods : [ methods ];
1787 for ( i = 0, len = methods.length; i < len; i++ ) {
1788 if ( $.isFunction( this[ methods[ i ] ] ) ) {
1789 support++;
1790 }
1791 }
1792
1793 return methods.length === support;
1794 };
1795
1796 /**
1797 * Update the theme-provided classes.
1798 *
1799 * @localdoc This is called in element mixins and widget classes any time state changes.
1800 * Updating is debounced, minimizing overhead of changing multiple attributes and
1801 * guaranteeing that theme updates do not occur within an element's constructor
1802 */
1803 OO.ui.Element.prototype.updateThemeClasses = function () {
1804 this.debouncedUpdateThemeClassesHandler();
1805 };
1806
1807 /**
1808 * @private
1809 * @localdoc This method is called directly from the QUnit tests instead of #updateThemeClasses, to
1810 * make them synchronous.
1811 */
1812 OO.ui.Element.prototype.debouncedUpdateThemeClasses = function () {
1813 OO.ui.theme.updateElementClasses( this );
1814 };
1815
1816 /**
1817 * Get the HTML tag name.
1818 *
1819 * Override this method to base the result on instance information.
1820 *
1821 * @return {string} HTML tag name
1822 */
1823 OO.ui.Element.prototype.getTagName = function () {
1824 return this.constructor.static.tagName;
1825 };
1826
1827 /**
1828 * Check if the element is attached to the DOM
1829 * @return {boolean} The element is attached to the DOM
1830 */
1831 OO.ui.Element.prototype.isElementAttached = function () {
1832 return $.contains( this.getElementDocument(), this.$element[ 0 ] );
1833 };
1834
1835 /**
1836 * Get the DOM document.
1837 *
1838 * @return {HTMLDocument} Document object
1839 */
1840 OO.ui.Element.prototype.getElementDocument = function () {
1841 // Don't cache this in other ways either because subclasses could can change this.$element
1842 return OO.ui.Element.static.getDocument( this.$element );
1843 };
1844
1845 /**
1846 * Get the DOM window.
1847 *
1848 * @return {Window} Window object
1849 */
1850 OO.ui.Element.prototype.getElementWindow = function () {
1851 return OO.ui.Element.static.getWindow( this.$element );
1852 };
1853
1854 /**
1855 * Get closest scrollable container.
1856 */
1857 OO.ui.Element.prototype.getClosestScrollableElementContainer = function () {
1858 return OO.ui.Element.static.getClosestScrollableContainer( this.$element[ 0 ] );
1859 };
1860
1861 /**
1862 * Get group element is in.
1863 *
1864 * @return {OO.ui.mixin.GroupElement|null} Group element, null if none
1865 */
1866 OO.ui.Element.prototype.getElementGroup = function () {
1867 return this.elementGroup;
1868 };
1869
1870 /**
1871 * Set group element is in.
1872 *
1873 * @param {OO.ui.mixin.GroupElement|null} group Group element, null if none
1874 * @chainable
1875 */
1876 OO.ui.Element.prototype.setElementGroup = function ( group ) {
1877 this.elementGroup = group;
1878 return this;
1879 };
1880
1881 /**
1882 * Scroll element into view.
1883 *
1884 * @param {Object} [config] Configuration options
1885 */
1886 OO.ui.Element.prototype.scrollElementIntoView = function ( config ) {
1887 return OO.ui.Element.static.scrollIntoView( this.$element[ 0 ], config );
1888 };
1889
1890 /**
1891 * Gather the dynamic state (focus, value of form inputs, scroll position, etc.) of a HTML DOM node
1892 * (and its children) that represent an Element of the same type and configuration as the current
1893 * one, generated by the PHP implementation.
1894 *
1895 * This method is called just before `node` is detached from the DOM. The return value of this
1896 * function will be passed to #restorePreInfuseState after this widget's #$element is inserted into
1897 * DOM to replace `node`.
1898 *
1899 * @protected
1900 * @param {HTMLElement} node
1901 * @return {Object}
1902 */
1903 OO.ui.Element.prototype.gatherPreInfuseState = function () {
1904 return {};
1905 };
1906
1907 /**
1908 * Restore the pre-infusion dynamic state for this widget.
1909 *
1910 * This method is called after #$element has been inserted into DOM. The parameter is the return
1911 * value of #gatherPreInfuseState.
1912 *
1913 * @protected
1914 * @param {Object} state
1915 */
1916 OO.ui.Element.prototype.restorePreInfuseState = function () {
1917 };
1918
1919 /**
1920 * Layouts are containers for elements and are used to arrange other widgets of arbitrary type in a way
1921 * that is centrally controlled and can be updated dynamically. Layouts can be, and usually are, combined.
1922 * See {@link OO.ui.FieldsetLayout FieldsetLayout}, {@link OO.ui.FieldLayout FieldLayout}, {@link OO.ui.FormLayout FormLayout},
1923 * {@link OO.ui.PanelLayout PanelLayout}, {@link OO.ui.StackLayout StackLayout}, {@link OO.ui.PageLayout PageLayout},
1924 * {@link OO.ui.HorizontalLayout HorizontalLayout}, and {@link OO.ui.BookletLayout BookletLayout} for more information and examples.
1925 *
1926 * @abstract
1927 * @class
1928 * @extends OO.ui.Element
1929 * @mixins OO.EventEmitter
1930 *
1931 * @constructor
1932 * @param {Object} [config] Configuration options
1933 */
1934 OO.ui.Layout = function OoUiLayout( config ) {
1935 // Configuration initialization
1936 config = config || {};
1937
1938 // Parent constructor
1939 OO.ui.Layout.parent.call( this, config );
1940
1941 // Mixin constructors
1942 OO.EventEmitter.call( this );
1943
1944 // Initialization
1945 this.$element.addClass( 'oo-ui-layout' );
1946 };
1947
1948 /* Setup */
1949
1950 OO.inheritClass( OO.ui.Layout, OO.ui.Element );
1951 OO.mixinClass( OO.ui.Layout, OO.EventEmitter );
1952
1953 /**
1954 * Widgets are compositions of one or more OOjs UI elements that users can both view
1955 * and interact with. All widgets can be configured and modified via a standard API,
1956 * and their state can change dynamically according to a model.
1957 *
1958 * @abstract
1959 * @class
1960 * @extends OO.ui.Element
1961 * @mixins OO.EventEmitter
1962 *
1963 * @constructor
1964 * @param {Object} [config] Configuration options
1965 * @cfg {boolean} [disabled=false] Disable the widget. Disabled widgets cannot be used and their
1966 * appearance reflects this state.
1967 */
1968 OO.ui.Widget = function OoUiWidget( config ) {
1969 // Initialize config
1970 config = $.extend( { disabled: false }, config );
1971
1972 // Parent constructor
1973 OO.ui.Widget.parent.call( this, config );
1974
1975 // Mixin constructors
1976 OO.EventEmitter.call( this );
1977
1978 // Properties
1979 this.disabled = null;
1980 this.wasDisabled = null;
1981
1982 // Initialization
1983 this.$element.addClass( 'oo-ui-widget' );
1984 this.setDisabled( !!config.disabled );
1985 };
1986
1987 /* Setup */
1988
1989 OO.inheritClass( OO.ui.Widget, OO.ui.Element );
1990 OO.mixinClass( OO.ui.Widget, OO.EventEmitter );
1991
1992 /* Static Properties */
1993
1994 /**
1995 * Whether this widget will behave reasonably when wrapped in a HTML `<label>`. If this is true,
1996 * wrappers such as OO.ui.FieldLayout may use a `<label>` instead of implementing own label click
1997 * handling.
1998 *
1999 * @static
2000 * @inheritable
2001 * @property {boolean}
2002 */
2003 OO.ui.Widget.static.supportsSimpleLabel = false;
2004
2005 /* Events */
2006
2007 /**
2008 * @event disable
2009 *
2010 * A 'disable' event is emitted when the disabled state of the widget changes
2011 * (i.e. on disable **and** enable).
2012 *
2013 * @param {boolean} disabled Widget is disabled
2014 */
2015
2016 /**
2017 * @event toggle
2018 *
2019 * A 'toggle' event is emitted when the visibility of the widget changes.
2020 *
2021 * @param {boolean} visible Widget is visible
2022 */
2023
2024 /* Methods */
2025
2026 /**
2027 * Check if the widget is disabled.
2028 *
2029 * @return {boolean} Widget is disabled
2030 */
2031 OO.ui.Widget.prototype.isDisabled = function () {
2032 return this.disabled;
2033 };
2034
2035 /**
2036 * Set the 'disabled' state of the widget.
2037 *
2038 * When a widget is disabled, it cannot be used and its appearance is updated to reflect this state.
2039 *
2040 * @param {boolean} disabled Disable widget
2041 * @chainable
2042 */
2043 OO.ui.Widget.prototype.setDisabled = function ( disabled ) {
2044 var isDisabled;
2045
2046 this.disabled = !!disabled;
2047 isDisabled = this.isDisabled();
2048 if ( isDisabled !== this.wasDisabled ) {
2049 this.$element.toggleClass( 'oo-ui-widget-disabled', isDisabled );
2050 this.$element.toggleClass( 'oo-ui-widget-enabled', !isDisabled );
2051 this.$element.attr( 'aria-disabled', isDisabled.toString() );
2052 this.emit( 'disable', isDisabled );
2053 this.updateThemeClasses();
2054 }
2055 this.wasDisabled = isDisabled;
2056
2057 return this;
2058 };
2059
2060 /**
2061 * Update the disabled state, in case of changes in parent widget.
2062 *
2063 * @chainable
2064 */
2065 OO.ui.Widget.prototype.updateDisabled = function () {
2066 this.setDisabled( this.disabled );
2067 return this;
2068 };
2069
2070 /**
2071 * A window is a container for elements that are in a child frame. They are used with
2072 * a window manager (OO.ui.WindowManager), which is used to open and close the window and control
2073 * its presentation. The size of a window is specified using a symbolic name (e.g., ‘small’, ‘medium’,
2074 * ‘large’), which is interpreted by the window manager. If the requested size is not recognized,
2075 * the window manager will choose a sensible fallback.
2076 *
2077 * The lifecycle of a window has three primary stages (opening, opened, and closing) in which
2078 * different processes are executed:
2079 *
2080 * **opening**: The opening stage begins when the window manager's {@link OO.ui.WindowManager#openWindow
2081 * openWindow} or the window's {@link #open open} methods are used, and the window manager begins to open
2082 * the window.
2083 *
2084 * - {@link #getSetupProcess} method is called and its result executed
2085 * - {@link #getReadyProcess} method is called and its result executed
2086 *
2087 * **opened**: The window is now open
2088 *
2089 * **closing**: The closing stage begins when the window manager's
2090 * {@link OO.ui.WindowManager#closeWindow closeWindow}
2091 * or the window's {@link #close} methods are used, and the window manager begins to close the window.
2092 *
2093 * - {@link #getHoldProcess} method is called and its result executed
2094 * - {@link #getTeardownProcess} method is called and its result executed. The window is now closed
2095 *
2096 * Each of the window's processes (setup, ready, hold, and teardown) can be extended in subclasses
2097 * by overriding the window's #getSetupProcess, #getReadyProcess, #getHoldProcess and #getTeardownProcess
2098 * methods. Note that each {@link OO.ui.Process process} is executed in series, so asynchronous
2099 * processing can complete. Always assume window processes are executed asynchronously.
2100 *
2101 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
2102 *
2103 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows
2104 *
2105 * @abstract
2106 * @class
2107 * @extends OO.ui.Element
2108 * @mixins OO.EventEmitter
2109 *
2110 * @constructor
2111 * @param {Object} [config] Configuration options
2112 * @cfg {string} [size] Symbolic name of the dialog size: `small`, `medium`, `large`, `larger` or
2113 * `full`. If omitted, the value of the {@link #static-size static size} property will be used.
2114 */
2115 OO.ui.Window = function OoUiWindow( config ) {
2116 // Configuration initialization
2117 config = config || {};
2118
2119 // Parent constructor
2120 OO.ui.Window.parent.call( this, config );
2121
2122 // Mixin constructors
2123 OO.EventEmitter.call( this );
2124
2125 // Properties
2126 this.manager = null;
2127 this.size = config.size || this.constructor.static.size;
2128 this.$frame = $( '<div>' );
2129 this.$overlay = $( '<div>' );
2130 this.$content = $( '<div>' );
2131
2132 this.$focusTrapBefore = $( '<div>' ).prop( 'tabIndex', 0 );
2133 this.$focusTrapAfter = $( '<div>' ).prop( 'tabIndex', 0 );
2134 this.$focusTraps = this.$focusTrapBefore.add( this.$focusTrapAfter );
2135
2136 // Initialization
2137 this.$overlay.addClass( 'oo-ui-window-overlay' );
2138 this.$content
2139 .addClass( 'oo-ui-window-content' )
2140 .attr( 'tabindex', 0 );
2141 this.$frame
2142 .addClass( 'oo-ui-window-frame' )
2143 .append( this.$focusTrapBefore, this.$content, this.$focusTrapAfter );
2144
2145 this.$element
2146 .addClass( 'oo-ui-window' )
2147 .append( this.$frame, this.$overlay );
2148
2149 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
2150 // that reference properties not initialized at that time of parent class construction
2151 // TODO: Find a better way to handle post-constructor setup
2152 this.visible = false;
2153 this.$element.addClass( 'oo-ui-element-hidden' );
2154 };
2155
2156 /* Setup */
2157
2158 OO.inheritClass( OO.ui.Window, OO.ui.Element );
2159 OO.mixinClass( OO.ui.Window, OO.EventEmitter );
2160
2161 /* Static Properties */
2162
2163 /**
2164 * Symbolic name of the window size: `small`, `medium`, `large`, `larger` or `full`.
2165 *
2166 * The static size is used if no #size is configured during construction.
2167 *
2168 * @static
2169 * @inheritable
2170 * @property {string}
2171 */
2172 OO.ui.Window.static.size = 'medium';
2173
2174 /* Methods */
2175
2176 /**
2177 * Handle mouse down events.
2178 *
2179 * @private
2180 * @param {jQuery.Event} e Mouse down event
2181 */
2182 OO.ui.Window.prototype.onMouseDown = function ( e ) {
2183 // Prevent clicking on the click-block from stealing focus
2184 if ( e.target === this.$element[ 0 ] ) {
2185 return false;
2186 }
2187 };
2188
2189 /**
2190 * Check if the window has been initialized.
2191 *
2192 * Initialization occurs when a window is added to a manager.
2193 *
2194 * @return {boolean} Window has been initialized
2195 */
2196 OO.ui.Window.prototype.isInitialized = function () {
2197 return !!this.manager;
2198 };
2199
2200 /**
2201 * Check if the window is visible.
2202 *
2203 * @return {boolean} Window is visible
2204 */
2205 OO.ui.Window.prototype.isVisible = function () {
2206 return this.visible;
2207 };
2208
2209 /**
2210 * Check if the window is opening.
2211 *
2212 * This method is a wrapper around the window manager's {@link OO.ui.WindowManager#isOpening isOpening}
2213 * method.
2214 *
2215 * @return {boolean} Window is opening
2216 */
2217 OO.ui.Window.prototype.isOpening = function () {
2218 return this.manager.isOpening( this );
2219 };
2220
2221 /**
2222 * Check if the window is closing.
2223 *
2224 * This method is a wrapper around the window manager's {@link OO.ui.WindowManager#isClosing isClosing} method.
2225 *
2226 * @return {boolean} Window is closing
2227 */
2228 OO.ui.Window.prototype.isClosing = function () {
2229 return this.manager.isClosing( this );
2230 };
2231
2232 /**
2233 * Check if the window is opened.
2234 *
2235 * This method is a wrapper around the window manager's {@link OO.ui.WindowManager#isOpened isOpened} method.
2236 *
2237 * @return {boolean} Window is opened
2238 */
2239 OO.ui.Window.prototype.isOpened = function () {
2240 return this.manager.isOpened( this );
2241 };
2242
2243 /**
2244 * Get the window manager.
2245 *
2246 * All windows must be attached to a window manager, which is used to open
2247 * and close the window and control its presentation.
2248 *
2249 * @return {OO.ui.WindowManager} Manager of window
2250 */
2251 OO.ui.Window.prototype.getManager = function () {
2252 return this.manager;
2253 };
2254
2255 /**
2256 * Get the symbolic name of the window size (e.g., `small` or `medium`).
2257 *
2258 * @return {string} Symbolic name of the size: `small`, `medium`, `large`, `larger`, `full`
2259 */
2260 OO.ui.Window.prototype.getSize = function () {
2261 var viewport = OO.ui.Element.static.getDimensions( this.getElementWindow() ),
2262 sizes = this.manager.constructor.static.sizes,
2263 size = this.size;
2264
2265 if ( !sizes[ size ] ) {
2266 size = this.manager.constructor.static.defaultSize;
2267 }
2268 if ( size !== 'full' && viewport.rect.right - viewport.rect.left < sizes[ size ].width ) {
2269 size = 'full';
2270 }
2271
2272 return size;
2273 };
2274
2275 /**
2276 * Get the size properties associated with the current window size
2277 *
2278 * @return {Object} Size properties
2279 */
2280 OO.ui.Window.prototype.getSizeProperties = function () {
2281 return this.manager.constructor.static.sizes[ this.getSize() ];
2282 };
2283
2284 /**
2285 * Disable transitions on window's frame for the duration of the callback function, then enable them
2286 * back.
2287 *
2288 * @private
2289 * @param {Function} callback Function to call while transitions are disabled
2290 */
2291 OO.ui.Window.prototype.withoutSizeTransitions = function ( callback ) {
2292 // Temporarily resize the frame so getBodyHeight() can use scrollHeight measurements.
2293 // Disable transitions first, otherwise we'll get values from when the window was animating.
2294 var oldTransition,
2295 styleObj = this.$frame[ 0 ].style;
2296 oldTransition = styleObj.transition || styleObj.OTransition || styleObj.MsTransition ||
2297 styleObj.MozTransition || styleObj.WebkitTransition;
2298 styleObj.transition = styleObj.OTransition = styleObj.MsTransition =
2299 styleObj.MozTransition = styleObj.WebkitTransition = 'none';
2300 callback();
2301 // Force reflow to make sure the style changes done inside callback really are not transitioned
2302 this.$frame.height();
2303 styleObj.transition = styleObj.OTransition = styleObj.MsTransition =
2304 styleObj.MozTransition = styleObj.WebkitTransition = oldTransition;
2305 };
2306
2307 /**
2308 * Get the height of the full window contents (i.e., the window head, body and foot together).
2309 *
2310 * What consistitutes the head, body, and foot varies depending on the window type.
2311 * A {@link OO.ui.MessageDialog message dialog} displays a title and message in its body,
2312 * and any actions in the foot. A {@link OO.ui.ProcessDialog process dialog} displays a title
2313 * and special actions in the head, and dialog content in the body.
2314 *
2315 * To get just the height of the dialog body, use the #getBodyHeight method.
2316 *
2317 * @return {number} The height of the window contents (the dialog head, body and foot) in pixels
2318 */
2319 OO.ui.Window.prototype.getContentHeight = function () {
2320 var bodyHeight,
2321 win = this,
2322 bodyStyleObj = this.$body[ 0 ].style,
2323 frameStyleObj = this.$frame[ 0 ].style;
2324
2325 // Temporarily resize the frame so getBodyHeight() can use scrollHeight measurements.
2326 // Disable transitions first, otherwise we'll get values from when the window was animating.
2327 this.withoutSizeTransitions( function () {
2328 var oldHeight = frameStyleObj.height,
2329 oldPosition = bodyStyleObj.position;
2330 frameStyleObj.height = '1px';
2331 // Force body to resize to new width
2332 bodyStyleObj.position = 'relative';
2333 bodyHeight = win.getBodyHeight();
2334 frameStyleObj.height = oldHeight;
2335 bodyStyleObj.position = oldPosition;
2336 } );
2337
2338 return (
2339 // Add buffer for border
2340 ( this.$frame.outerHeight() - this.$frame.innerHeight() ) +
2341 // Use combined heights of children
2342 ( this.$head.outerHeight( true ) + bodyHeight + this.$foot.outerHeight( true ) )
2343 );
2344 };
2345
2346 /**
2347 * Get the height of the window body.
2348 *
2349 * To get the height of the full window contents (the window body, head, and foot together),
2350 * use #getContentHeight.
2351 *
2352 * When this function is called, the window will temporarily have been resized
2353 * to height=1px, so .scrollHeight measurements can be taken accurately.
2354 *
2355 * @return {number} Height of the window body in pixels
2356 */
2357 OO.ui.Window.prototype.getBodyHeight = function () {
2358 return this.$body[ 0 ].scrollHeight;
2359 };
2360
2361 /**
2362 * Get the directionality of the frame (right-to-left or left-to-right).
2363 *
2364 * @return {string} Directionality: `'ltr'` or `'rtl'`
2365 */
2366 OO.ui.Window.prototype.getDir = function () {
2367 return OO.ui.Element.static.getDir( this.$content ) || 'ltr';
2368 };
2369
2370 /**
2371 * Get the 'setup' process.
2372 *
2373 * The setup process is used to set up a window for use in a particular context,
2374 * based on the `data` argument. This method is called during the opening phase of the window’s
2375 * lifecycle.
2376 *
2377 * Override this method to add additional steps to the ‘setup’ process the parent method provides
2378 * using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next} methods
2379 * of OO.ui.Process.
2380 *
2381 * To add window content that persists between openings, you may wish to use the #initialize method
2382 * instead.
2383 *
2384 * @abstract
2385 * @param {Object} [data] Window opening data
2386 * @return {OO.ui.Process} Setup process
2387 */
2388 OO.ui.Window.prototype.getSetupProcess = function () {
2389 return new OO.ui.Process();
2390 };
2391
2392 /**
2393 * Get the ‘ready’ process.
2394 *
2395 * The ready process is used to ready a window for use in a particular
2396 * context, based on the `data` argument. This method is called during the opening phase of
2397 * the window’s lifecycle, after the window has been {@link #getSetupProcess setup}.
2398 *
2399 * Override this method to add additional steps to the ‘ready’ process the parent method
2400 * provides using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next}
2401 * methods of OO.ui.Process.
2402 *
2403 * @abstract
2404 * @param {Object} [data] Window opening data
2405 * @return {OO.ui.Process} Ready process
2406 */
2407 OO.ui.Window.prototype.getReadyProcess = function () {
2408 return new OO.ui.Process();
2409 };
2410
2411 /**
2412 * Get the 'hold' process.
2413 *
2414 * The hold proccess is used to keep a window from being used in a particular context,
2415 * based on the `data` argument. This method is called during the closing phase of the window’s
2416 * lifecycle.
2417 *
2418 * Override this method to add additional steps to the 'hold' process the parent method provides
2419 * using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next} methods
2420 * of OO.ui.Process.
2421 *
2422 * @abstract
2423 * @param {Object} [data] Window closing data
2424 * @return {OO.ui.Process} Hold process
2425 */
2426 OO.ui.Window.prototype.getHoldProcess = function () {
2427 return new OO.ui.Process();
2428 };
2429
2430 /**
2431 * Get the ‘teardown’ process.
2432 *
2433 * The teardown process is used to teardown a window after use. During teardown,
2434 * user interactions within the window are conveyed and the window is closed, based on the `data`
2435 * argument. This method is called during the closing phase of the window’s lifecycle.
2436 *
2437 * Override this method to add additional steps to the ‘teardown’ process the parent method provides
2438 * using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next} methods
2439 * of OO.ui.Process.
2440 *
2441 * @abstract
2442 * @param {Object} [data] Window closing data
2443 * @return {OO.ui.Process} Teardown process
2444 */
2445 OO.ui.Window.prototype.getTeardownProcess = function () {
2446 return new OO.ui.Process();
2447 };
2448
2449 /**
2450 * Set the window manager.
2451 *
2452 * This will cause the window to initialize. Calling it more than once will cause an error.
2453 *
2454 * @param {OO.ui.WindowManager} manager Manager for this window
2455 * @throws {Error} An error is thrown if the method is called more than once
2456 * @chainable
2457 */
2458 OO.ui.Window.prototype.setManager = function ( manager ) {
2459 if ( this.manager ) {
2460 throw new Error( 'Cannot set window manager, window already has a manager' );
2461 }
2462
2463 this.manager = manager;
2464 this.initialize();
2465
2466 return this;
2467 };
2468
2469 /**
2470 * Set the window size by symbolic name (e.g., 'small' or 'medium')
2471 *
2472 * @param {string} size Symbolic name of size: `small`, `medium`, `large`, `larger` or
2473 * `full`
2474 * @chainable
2475 */
2476 OO.ui.Window.prototype.setSize = function ( size ) {
2477 this.size = size;
2478 this.updateSize();
2479 return this;
2480 };
2481
2482 /**
2483 * Update the window size.
2484 *
2485 * @throws {Error} An error is thrown if the window is not attached to a window manager
2486 * @chainable
2487 */
2488 OO.ui.Window.prototype.updateSize = function () {
2489 if ( !this.manager ) {
2490 throw new Error( 'Cannot update window size, must be attached to a manager' );
2491 }
2492
2493 this.manager.updateWindowSize( this );
2494
2495 return this;
2496 };
2497
2498 /**
2499 * Set window dimensions. This method is called by the {@link OO.ui.WindowManager window manager}
2500 * when the window is opening. In general, setDimensions should not be called directly.
2501 *
2502 * To set the size of the window, use the #setSize method.
2503 *
2504 * @param {Object} dim CSS dimension properties
2505 * @param {string|number} [dim.width] Width
2506 * @param {string|number} [dim.minWidth] Minimum width
2507 * @param {string|number} [dim.maxWidth] Maximum width
2508 * @param {string|number} [dim.width] Height, omit to set based on height of contents
2509 * @param {string|number} [dim.minWidth] Minimum height
2510 * @param {string|number} [dim.maxWidth] Maximum height
2511 * @chainable
2512 */
2513 OO.ui.Window.prototype.setDimensions = function ( dim ) {
2514 var height,
2515 win = this,
2516 styleObj = this.$frame[ 0 ].style;
2517
2518 // Calculate the height we need to set using the correct width
2519 if ( dim.height === undefined ) {
2520 this.withoutSizeTransitions( function () {
2521 var oldWidth = styleObj.width;
2522 win.$frame.css( 'width', dim.width || '' );
2523 height = win.getContentHeight();
2524 styleObj.width = oldWidth;
2525 } );
2526 } else {
2527 height = dim.height;
2528 }
2529
2530 this.$frame.css( {
2531 width: dim.width || '',
2532 minWidth: dim.minWidth || '',
2533 maxWidth: dim.maxWidth || '',
2534 height: height || '',
2535 minHeight: dim.minHeight || '',
2536 maxHeight: dim.maxHeight || ''
2537 } );
2538
2539 return this;
2540 };
2541
2542 /**
2543 * Initialize window contents.
2544 *
2545 * Before the window is opened for the first time, #initialize is called so that content that
2546 * persists between openings can be added to the window.
2547 *
2548 * To set up a window with new content each time the window opens, use #getSetupProcess.
2549 *
2550 * @throws {Error} An error is thrown if the window is not attached to a window manager
2551 * @chainable
2552 */
2553 OO.ui.Window.prototype.initialize = function () {
2554 if ( !this.manager ) {
2555 throw new Error( 'Cannot initialize window, must be attached to a manager' );
2556 }
2557
2558 // Properties
2559 this.$head = $( '<div>' );
2560 this.$body = $( '<div>' );
2561 this.$foot = $( '<div>' );
2562 this.$document = $( this.getElementDocument() );
2563
2564 // Events
2565 this.$element.on( 'mousedown', this.onMouseDown.bind( this ) );
2566
2567 // Initialization
2568 this.$head.addClass( 'oo-ui-window-head' );
2569 this.$body.addClass( 'oo-ui-window-body' );
2570 this.$foot.addClass( 'oo-ui-window-foot' );
2571 this.$content.append( this.$head, this.$body, this.$foot );
2572
2573 return this;
2574 };
2575
2576 /**
2577 * Called when someone tries to focus the hidden element at the end of the dialog.
2578 * Sends focus back to the start of the dialog.
2579 *
2580 * @param {jQuery.Event} event Focus event
2581 */
2582 OO.ui.Window.prototype.onFocusTrapFocused = function ( event ) {
2583 if ( this.$focusTrapBefore.is( event.target ) ) {
2584 OO.ui.findFocusable( this.$content, true ).focus();
2585 } else {
2586 // this.$content is the part of the focus cycle, and is the first focusable element
2587 this.$content.focus();
2588 }
2589 };
2590
2591 /**
2592 * Open the window.
2593 *
2594 * This method is a wrapper around a call to the window manager’s {@link OO.ui.WindowManager#openWindow openWindow}
2595 * method, which returns a promise resolved when the window is done opening.
2596 *
2597 * To customize the window each time it opens, use #getSetupProcess or #getReadyProcess.
2598 *
2599 * @param {Object} [data] Window opening data
2600 * @return {jQuery.Promise} Promise resolved with a value when the window is opened, or rejected
2601 * if the window fails to open. When the promise is resolved successfully, the first argument of the
2602 * value is a new promise, which is resolved when the window begins closing.
2603 * @throws {Error} An error is thrown if the window is not attached to a window manager
2604 */
2605 OO.ui.Window.prototype.open = function ( data ) {
2606 if ( !this.manager ) {
2607 throw new Error( 'Cannot open window, must be attached to a manager' );
2608 }
2609
2610 return this.manager.openWindow( this, data );
2611 };
2612
2613 /**
2614 * Close the window.
2615 *
2616 * This method is a wrapper around a call to the window
2617 * manager’s {@link OO.ui.WindowManager#closeWindow closeWindow} method,
2618 * which returns a closing promise resolved when the window is done closing.
2619 *
2620 * The window's #getHoldProcess and #getTeardownProcess methods are called during the closing
2621 * phase of the window’s lifecycle and can be used to specify closing behavior each time
2622 * the window closes.
2623 *
2624 * @param {Object} [data] Window closing data
2625 * @return {jQuery.Promise} Promise resolved when window is closed
2626 * @throws {Error} An error is thrown if the window is not attached to a window manager
2627 */
2628 OO.ui.Window.prototype.close = function ( data ) {
2629 if ( !this.manager ) {
2630 throw new Error( 'Cannot close window, must be attached to a manager' );
2631 }
2632
2633 return this.manager.closeWindow( this, data );
2634 };
2635
2636 /**
2637 * Setup window.
2638 *
2639 * This is called by OO.ui.WindowManager during window opening, and should not be called directly
2640 * by other systems.
2641 *
2642 * @param {Object} [data] Window opening data
2643 * @return {jQuery.Promise} Promise resolved when window is setup
2644 */
2645 OO.ui.Window.prototype.setup = function ( data ) {
2646 var win = this,
2647 deferred = $.Deferred();
2648
2649 this.toggle( true );
2650
2651 this.focusTrapHandler = OO.ui.bind( this.onFocusTrapFocused, this );
2652 this.$focusTraps.on( 'focus', this.focusTrapHandler );
2653
2654 this.getSetupProcess( data ).execute().done( function () {
2655 // Force redraw by asking the browser to measure the elements' widths
2656 win.$element.addClass( 'oo-ui-window-active oo-ui-window-setup' ).width();
2657 win.$content.addClass( 'oo-ui-window-content-setup' ).width();
2658 deferred.resolve();
2659 } );
2660
2661 return deferred.promise();
2662 };
2663
2664 /**
2665 * Ready window.
2666 *
2667 * This is called by OO.ui.WindowManager during window opening, and should not be called directly
2668 * by other systems.
2669 *
2670 * @param {Object} [data] Window opening data
2671 * @return {jQuery.Promise} Promise resolved when window is ready
2672 */
2673 OO.ui.Window.prototype.ready = function ( data ) {
2674 var win = this,
2675 deferred = $.Deferred();
2676
2677 this.$content.focus();
2678 this.getReadyProcess( data ).execute().done( function () {
2679 // Force redraw by asking the browser to measure the elements' widths
2680 win.$element.addClass( 'oo-ui-window-ready' ).width();
2681 win.$content.addClass( 'oo-ui-window-content-ready' ).width();
2682 deferred.resolve();
2683 } );
2684
2685 return deferred.promise();
2686 };
2687
2688 /**
2689 * Hold window.
2690 *
2691 * This is called by OO.ui.WindowManager during window closing, and should not be called directly
2692 * by other systems.
2693 *
2694 * @param {Object} [data] Window closing data
2695 * @return {jQuery.Promise} Promise resolved when window is held
2696 */
2697 OO.ui.Window.prototype.hold = function ( data ) {
2698 var win = this,
2699 deferred = $.Deferred();
2700
2701 this.getHoldProcess( data ).execute().done( function () {
2702 // Get the focused element within the window's content
2703 var $focus = win.$content.find( OO.ui.Element.static.getDocument( win.$content ).activeElement );
2704
2705 // Blur the focused element
2706 if ( $focus.length ) {
2707 $focus[ 0 ].blur();
2708 }
2709
2710 // Force redraw by asking the browser to measure the elements' widths
2711 win.$element.removeClass( 'oo-ui-window-ready' ).width();
2712 win.$content.removeClass( 'oo-ui-window-content-ready' ).width();
2713 deferred.resolve();
2714 } );
2715
2716 return deferred.promise();
2717 };
2718
2719 /**
2720 * Teardown window.
2721 *
2722 * This is called by OO.ui.WindowManager during window closing, and should not be called directly
2723 * by other systems.
2724 *
2725 * @param {Object} [data] Window closing data
2726 * @return {jQuery.Promise} Promise resolved when window is torn down
2727 */
2728 OO.ui.Window.prototype.teardown = function ( data ) {
2729 var win = this;
2730
2731 return this.getTeardownProcess( data ).execute()
2732 .done( function () {
2733 // Force redraw by asking the browser to measure the elements' widths
2734 win.$element.removeClass( 'oo-ui-window-active oo-ui-window-setup' ).width();
2735 win.$content.removeClass( 'oo-ui-window-content-setup' ).width();
2736 win.$focusTraps.off( 'focus', win.focusTrapHandler );
2737 win.toggle( false );
2738 } );
2739 };
2740
2741 /**
2742 * The Dialog class serves as the base class for the other types of dialogs.
2743 * Unless extended to include controls, the rendered dialog box is a simple window
2744 * that users can close by hitting the ‘Esc’ key. Dialog windows are used with OO.ui.WindowManager,
2745 * which opens, closes, and controls the presentation of the window. See the
2746 * [OOjs UI documentation on MediaWiki] [1] for more information.
2747 *
2748 * @example
2749 * // A simple dialog window.
2750 * function MyDialog( config ) {
2751 * MyDialog.parent.call( this, config );
2752 * }
2753 * OO.inheritClass( MyDialog, OO.ui.Dialog );
2754 * MyDialog.prototype.initialize = function () {
2755 * MyDialog.parent.prototype.initialize.call( this );
2756 * this.content = new OO.ui.PanelLayout( { padded: true, expanded: false } );
2757 * this.content.$element.append( '<p>A simple dialog window. Press \'Esc\' to close.</p>' );
2758 * this.$body.append( this.content.$element );
2759 * };
2760 * MyDialog.prototype.getBodyHeight = function () {
2761 * return this.content.$element.outerHeight( true );
2762 * };
2763 * var myDialog = new MyDialog( {
2764 * size: 'medium'
2765 * } );
2766 * // Create and append a window manager, which opens and closes the window.
2767 * var windowManager = new OO.ui.WindowManager();
2768 * $( 'body' ).append( windowManager.$element );
2769 * windowManager.addWindows( [ myDialog ] );
2770 * // Open the window!
2771 * windowManager.openWindow( myDialog );
2772 *
2773 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Dialogs
2774 *
2775 * @abstract
2776 * @class
2777 * @extends OO.ui.Window
2778 * @mixins OO.ui.mixin.PendingElement
2779 *
2780 * @constructor
2781 * @param {Object} [config] Configuration options
2782 */
2783 OO.ui.Dialog = function OoUiDialog( config ) {
2784 // Parent constructor
2785 OO.ui.Dialog.parent.call( this, config );
2786
2787 // Mixin constructors
2788 OO.ui.mixin.PendingElement.call( this );
2789
2790 // Properties
2791 this.actions = new OO.ui.ActionSet();
2792 this.attachedActions = [];
2793 this.currentAction = null;
2794 this.onDialogKeyDownHandler = this.onDialogKeyDown.bind( this );
2795
2796 // Events
2797 this.actions.connect( this, {
2798 click: 'onActionClick',
2799 resize: 'onActionResize',
2800 change: 'onActionsChange'
2801 } );
2802
2803 // Initialization
2804 this.$element
2805 .addClass( 'oo-ui-dialog' )
2806 .attr( 'role', 'dialog' );
2807 };
2808
2809 /* Setup */
2810
2811 OO.inheritClass( OO.ui.Dialog, OO.ui.Window );
2812 OO.mixinClass( OO.ui.Dialog, OO.ui.mixin.PendingElement );
2813
2814 /* Static Properties */
2815
2816 /**
2817 * Symbolic name of dialog.
2818 *
2819 * The dialog class must have a symbolic name in order to be registered with OO.Factory.
2820 * Please see the [OOjs UI documentation on MediaWiki] [3] for more information.
2821 *
2822 * [3]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
2823 *
2824 * @abstract
2825 * @static
2826 * @inheritable
2827 * @property {string}
2828 */
2829 OO.ui.Dialog.static.name = '';
2830
2831 /**
2832 * The dialog title.
2833 *
2834 * The title can be specified as a plaintext string, a {@link OO.ui.mixin.LabelElement Label} node, or a function
2835 * that will produce a Label node or string. The title can also be specified with data passed to the
2836 * constructor (see #getSetupProcess). In this case, the static value will be overriden.
2837 *
2838 * @abstract
2839 * @static
2840 * @inheritable
2841 * @property {jQuery|string|Function}
2842 */
2843 OO.ui.Dialog.static.title = '';
2844
2845 /**
2846 * An array of configured {@link OO.ui.ActionWidget action widgets}.
2847 *
2848 * Actions can also be specified with data passed to the constructor (see #getSetupProcess). In this case, the static
2849 * value will be overriden.
2850 *
2851 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Action_sets
2852 *
2853 * @static
2854 * @inheritable
2855 * @property {Object[]}
2856 */
2857 OO.ui.Dialog.static.actions = [];
2858
2859 /**
2860 * Close the dialog when the 'Esc' key is pressed.
2861 *
2862 * @static
2863 * @abstract
2864 * @inheritable
2865 * @property {boolean}
2866 */
2867 OO.ui.Dialog.static.escapable = true;
2868
2869 /* Methods */
2870
2871 /**
2872 * Handle frame document key down events.
2873 *
2874 * @private
2875 * @param {jQuery.Event} e Key down event
2876 */
2877 OO.ui.Dialog.prototype.onDialogKeyDown = function ( e ) {
2878 if ( e.which === OO.ui.Keys.ESCAPE ) {
2879 this.close();
2880 e.preventDefault();
2881 e.stopPropagation();
2882 }
2883 };
2884
2885 /**
2886 * Handle action resized events.
2887 *
2888 * @private
2889 * @param {OO.ui.ActionWidget} action Action that was resized
2890 */
2891 OO.ui.Dialog.prototype.onActionResize = function () {
2892 // Override in subclass
2893 };
2894
2895 /**
2896 * Handle action click events.
2897 *
2898 * @private
2899 * @param {OO.ui.ActionWidget} action Action that was clicked
2900 */
2901 OO.ui.Dialog.prototype.onActionClick = function ( action ) {
2902 if ( !this.isPending() ) {
2903 this.executeAction( action.getAction() );
2904 }
2905 };
2906
2907 /**
2908 * Handle actions change event.
2909 *
2910 * @private
2911 */
2912 OO.ui.Dialog.prototype.onActionsChange = function () {
2913 this.detachActions();
2914 if ( !this.isClosing() ) {
2915 this.attachActions();
2916 }
2917 };
2918
2919 /**
2920 * Get the set of actions used by the dialog.
2921 *
2922 * @return {OO.ui.ActionSet}
2923 */
2924 OO.ui.Dialog.prototype.getActions = function () {
2925 return this.actions;
2926 };
2927
2928 /**
2929 * Get a process for taking action.
2930 *
2931 * When you override this method, you can create a new OO.ui.Process and return it, or add additional
2932 * accept steps to the process the parent method provides using the {@link OO.ui.Process#first 'first'}
2933 * and {@link OO.ui.Process#next 'next'} methods of OO.ui.Process.
2934 *
2935 * @abstract
2936 * @param {string} [action] Symbolic name of action
2937 * @return {OO.ui.Process} Action process
2938 */
2939 OO.ui.Dialog.prototype.getActionProcess = function ( action ) {
2940 return new OO.ui.Process()
2941 .next( function () {
2942 if ( !action ) {
2943 // An empty action always closes the dialog without data, which should always be
2944 // safe and make no changes
2945 this.close();
2946 }
2947 }, this );
2948 };
2949
2950 /**
2951 * @inheritdoc
2952 *
2953 * @param {Object} [data] Dialog opening data
2954 * @param {jQuery|string|Function|null} [data.title] Dialog title, omit to use
2955 * the {@link #static-title static title}
2956 * @param {Object[]} [data.actions] List of configuration options for each
2957 * {@link OO.ui.ActionWidget action widget}, omit to use {@link #static-actions static actions}.
2958 */
2959 OO.ui.Dialog.prototype.getSetupProcess = function ( data ) {
2960 data = data || {};
2961
2962 // Parent method
2963 return OO.ui.Dialog.parent.prototype.getSetupProcess.call( this, data )
2964 .next( function () {
2965 var config = this.constructor.static,
2966 actions = data.actions !== undefined ? data.actions : config.actions;
2967
2968 this.title.setLabel(
2969 data.title !== undefined ? data.title : this.constructor.static.title
2970 );
2971 this.actions.add( this.getActionWidgets( actions ) );
2972
2973 if ( this.constructor.static.escapable ) {
2974 this.$element.on( 'keydown', this.onDialogKeyDownHandler );
2975 }
2976 }, this );
2977 };
2978
2979 /**
2980 * @inheritdoc
2981 */
2982 OO.ui.Dialog.prototype.getTeardownProcess = function ( data ) {
2983 // Parent method
2984 return OO.ui.Dialog.parent.prototype.getTeardownProcess.call( this, data )
2985 .first( function () {
2986 if ( this.constructor.static.escapable ) {
2987 this.$element.off( 'keydown', this.onDialogKeyDownHandler );
2988 }
2989
2990 this.actions.clear();
2991 this.currentAction = null;
2992 }, this );
2993 };
2994
2995 /**
2996 * @inheritdoc
2997 */
2998 OO.ui.Dialog.prototype.initialize = function () {
2999 var titleId;
3000
3001 // Parent method
3002 OO.ui.Dialog.parent.prototype.initialize.call( this );
3003
3004 titleId = OO.ui.generateElementId();
3005
3006 // Properties
3007 this.title = new OO.ui.LabelWidget( {
3008 id: titleId
3009 } );
3010
3011 // Initialization
3012 this.$content.addClass( 'oo-ui-dialog-content' );
3013 this.$element.attr( 'aria-labelledby', titleId );
3014 this.setPendingElement( this.$head );
3015 };
3016
3017 /**
3018 * Get action widgets from a list of configs
3019 *
3020 * @param {Object[]} actions Action widget configs
3021 * @return {OO.ui.ActionWidget[]} Action widgets
3022 */
3023 OO.ui.Dialog.prototype.getActionWidgets = function ( actions ) {
3024 var i, len, widgets = [];
3025 for ( i = 0, len = actions.length; i < len; i++ ) {
3026 widgets.push(
3027 new OO.ui.ActionWidget( actions[ i ] )
3028 );
3029 }
3030 return widgets;
3031 };
3032
3033 /**
3034 * Attach action actions.
3035 *
3036 * @protected
3037 */
3038 OO.ui.Dialog.prototype.attachActions = function () {
3039 // Remember the list of potentially attached actions
3040 this.attachedActions = this.actions.get();
3041 };
3042
3043 /**
3044 * Detach action actions.
3045 *
3046 * @protected
3047 * @chainable
3048 */
3049 OO.ui.Dialog.prototype.detachActions = function () {
3050 var i, len;
3051
3052 // Detach all actions that may have been previously attached
3053 for ( i = 0, len = this.attachedActions.length; i < len; i++ ) {
3054 this.attachedActions[ i ].$element.detach();
3055 }
3056 this.attachedActions = [];
3057 };
3058
3059 /**
3060 * Execute an action.
3061 *
3062 * @param {string} action Symbolic name of action to execute
3063 * @return {jQuery.Promise} Promise resolved when action completes, rejected if it fails
3064 */
3065 OO.ui.Dialog.prototype.executeAction = function ( action ) {
3066 this.pushPending();
3067 this.currentAction = action;
3068 return this.getActionProcess( action ).execute()
3069 .always( this.popPending.bind( this ) );
3070 };
3071
3072 /**
3073 * Window managers are used to open and close {@link OO.ui.Window windows} and control their presentation.
3074 * Managed windows are mutually exclusive. If a new window is opened while a current window is opening
3075 * or is opened, the current window will be closed and any ongoing {@link OO.ui.Process process} will be cancelled. Windows
3076 * themselves are persistent and—rather than being torn down when closed—can be repopulated with the
3077 * pertinent data and reused.
3078 *
3079 * Over the lifecycle of a window, the window manager makes available three promises: `opening`,
3080 * `opened`, and `closing`, which represent the primary stages of the cycle:
3081 *
3082 * **Opening**: the opening stage begins when the window manager’s #openWindow or a window’s
3083 * {@link OO.ui.Window#open open} method is used, and the window manager begins to open the window.
3084 *
3085 * - an `opening` event is emitted with an `opening` promise
3086 * - the #getSetupDelay method is called and the returned value is used to time a pause in execution before
3087 * the window’s {@link OO.ui.Window#getSetupProcess getSetupProcess} method is called on the
3088 * window and its result executed
3089 * - a `setup` progress notification is emitted from the `opening` promise
3090 * - the #getReadyDelay method is called the returned value is used to time a pause in execution before
3091 * the window’s {@link OO.ui.Window#getReadyProcess getReadyProcess} method is called on the
3092 * window and its result executed
3093 * - a `ready` progress notification is emitted from the `opening` promise
3094 * - the `opening` promise is resolved with an `opened` promise
3095 *
3096 * **Opened**: the window is now open.
3097 *
3098 * **Closing**: the closing stage begins when the window manager's #closeWindow or the
3099 * window's {@link OO.ui.Window#close close} methods is used, and the window manager begins
3100 * to close the window.
3101 *
3102 * - the `opened` promise is resolved with `closing` promise and a `closing` event is emitted
3103 * - the #getHoldDelay method is called and the returned value is used to time a pause in execution before
3104 * the window's {@link OO.ui.Window#getHoldProcess getHoldProces} method is called on the
3105 * window and its result executed
3106 * - a `hold` progress notification is emitted from the `closing` promise
3107 * - the #getTeardownDelay() method is called and the returned value is used to time a pause in execution before
3108 * the window's {@link OO.ui.Window#getTeardownProcess getTeardownProcess} method is called on the
3109 * window and its result executed
3110 * - a `teardown` progress notification is emitted from the `closing` promise
3111 * - the `closing` promise is resolved. The window is now closed
3112 *
3113 * See the [OOjs UI documentation on MediaWiki][1] for more information.
3114 *
3115 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
3116 *
3117 * @class
3118 * @extends OO.ui.Element
3119 * @mixins OO.EventEmitter
3120 *
3121 * @constructor
3122 * @param {Object} [config] Configuration options
3123 * @cfg {OO.Factory} [factory] Window factory to use for automatic instantiation
3124 * Note that window classes that are instantiated with a factory must have
3125 * a {@link OO.ui.Dialog#static-name static name} property that specifies a symbolic name.
3126 * @cfg {boolean} [modal=true] Prevent interaction outside the dialog
3127 */
3128 OO.ui.WindowManager = function OoUiWindowManager( config ) {
3129 // Configuration initialization
3130 config = config || {};
3131
3132 // Parent constructor
3133 OO.ui.WindowManager.parent.call( this, config );
3134
3135 // Mixin constructors
3136 OO.EventEmitter.call( this );
3137
3138 // Properties
3139 this.factory = config.factory;
3140 this.modal = config.modal === undefined || !!config.modal;
3141 this.windows = {};
3142 this.opening = null;
3143 this.opened = null;
3144 this.closing = null;
3145 this.preparingToOpen = null;
3146 this.preparingToClose = null;
3147 this.currentWindow = null;
3148 this.globalEvents = false;
3149 this.$ariaHidden = null;
3150 this.onWindowResizeTimeout = null;
3151 this.onWindowResizeHandler = this.onWindowResize.bind( this );
3152 this.afterWindowResizeHandler = this.afterWindowResize.bind( this );
3153
3154 // Initialization
3155 this.$element
3156 .addClass( 'oo-ui-windowManager' )
3157 .toggleClass( 'oo-ui-windowManager-modal', this.modal );
3158 };
3159
3160 /* Setup */
3161
3162 OO.inheritClass( OO.ui.WindowManager, OO.ui.Element );
3163 OO.mixinClass( OO.ui.WindowManager, OO.EventEmitter );
3164
3165 /* Events */
3166
3167 /**
3168 * An 'opening' event is emitted when the window begins to be opened.
3169 *
3170 * @event opening
3171 * @param {OO.ui.Window} win Window that's being opened
3172 * @param {jQuery.Promise} opening An `opening` promise resolved with a value when the window is opened successfully.
3173 * When the `opening` promise is resolved, the first argument of the value is an 'opened' promise, the second argument
3174 * is the opening data. The `opening` promise emits `setup` and `ready` notifications when those processes are complete.
3175 * @param {Object} data Window opening data
3176 */
3177
3178 /**
3179 * A 'closing' event is emitted when the window begins to be closed.
3180 *
3181 * @event closing
3182 * @param {OO.ui.Window} win Window that's being closed
3183 * @param {jQuery.Promise} closing A `closing` promise is resolved with a value when the window
3184 * is closed successfully. The promise emits `hold` and `teardown` notifications when those
3185 * processes are complete. When the `closing` promise is resolved, the first argument of its value
3186 * is the closing data.
3187 * @param {Object} data Window closing data
3188 */
3189
3190 /**
3191 * A 'resize' event is emitted when a window is resized.
3192 *
3193 * @event resize
3194 * @param {OO.ui.Window} win Window that was resized
3195 */
3196
3197 /* Static Properties */
3198
3199 /**
3200 * Map of the symbolic name of each window size and its CSS properties.
3201 *
3202 * @static
3203 * @inheritable
3204 * @property {Object}
3205 */
3206 OO.ui.WindowManager.static.sizes = {
3207 small: {
3208 width: 300
3209 },
3210 medium: {
3211 width: 500
3212 },
3213 large: {
3214 width: 700
3215 },
3216 larger: {
3217 width: 900
3218 },
3219 full: {
3220 // These can be non-numeric because they are never used in calculations
3221 width: '100%',
3222 height: '100%'
3223 }
3224 };
3225
3226 /**
3227 * Symbolic name of the default window size.
3228 *
3229 * The default size is used if the window's requested size is not recognized.
3230 *
3231 * @static
3232 * @inheritable
3233 * @property {string}
3234 */
3235 OO.ui.WindowManager.static.defaultSize = 'medium';
3236
3237 /* Methods */
3238
3239 /**
3240 * Handle window resize events.
3241 *
3242 * @private
3243 * @param {jQuery.Event} e Window resize event
3244 */
3245 OO.ui.WindowManager.prototype.onWindowResize = function () {
3246 clearTimeout( this.onWindowResizeTimeout );
3247 this.onWindowResizeTimeout = setTimeout( this.afterWindowResizeHandler, 200 );
3248 };
3249
3250 /**
3251 * Handle window resize events.
3252 *
3253 * @private
3254 * @param {jQuery.Event} e Window resize event
3255 */
3256 OO.ui.WindowManager.prototype.afterWindowResize = function () {
3257 if ( this.currentWindow ) {
3258 this.updateWindowSize( this.currentWindow );
3259 }
3260 };
3261
3262 /**
3263 * Check if window is opening.
3264 *
3265 * @return {boolean} Window is opening
3266 */
3267 OO.ui.WindowManager.prototype.isOpening = function ( win ) {
3268 return win === this.currentWindow && !!this.opening && this.opening.state() === 'pending';
3269 };
3270
3271 /**
3272 * Check if window is closing.
3273 *
3274 * @return {boolean} Window is closing
3275 */
3276 OO.ui.WindowManager.prototype.isClosing = function ( win ) {
3277 return win === this.currentWindow && !!this.closing && this.closing.state() === 'pending';
3278 };
3279
3280 /**
3281 * Check if window is opened.
3282 *
3283 * @return {boolean} Window is opened
3284 */
3285 OO.ui.WindowManager.prototype.isOpened = function ( win ) {
3286 return win === this.currentWindow && !!this.opened && this.opened.state() === 'pending';
3287 };
3288
3289 /**
3290 * Check if a window is being managed.
3291 *
3292 * @param {OO.ui.Window} win Window to check
3293 * @return {boolean} Window is being managed
3294 */
3295 OO.ui.WindowManager.prototype.hasWindow = function ( win ) {
3296 var name;
3297
3298 for ( name in this.windows ) {
3299 if ( this.windows[ name ] === win ) {
3300 return true;
3301 }
3302 }
3303
3304 return false;
3305 };
3306
3307 /**
3308 * Get the number of milliseconds to wait after opening begins before executing the ‘setup’ process.
3309 *
3310 * @param {OO.ui.Window} win Window being opened
3311 * @param {Object} [data] Window opening data
3312 * @return {number} Milliseconds to wait
3313 */
3314 OO.ui.WindowManager.prototype.getSetupDelay = function () {
3315 return 0;
3316 };
3317
3318 /**
3319 * Get the number of milliseconds to wait after setup has finished before executing the ‘ready’ process.
3320 *
3321 * @param {OO.ui.Window} win Window being opened
3322 * @param {Object} [data] Window opening data
3323 * @return {number} Milliseconds to wait
3324 */
3325 OO.ui.WindowManager.prototype.getReadyDelay = function () {
3326 return 0;
3327 };
3328
3329 /**
3330 * Get the number of milliseconds to wait after closing has begun before executing the 'hold' process.
3331 *
3332 * @param {OO.ui.Window} win Window being closed
3333 * @param {Object} [data] Window closing data
3334 * @return {number} Milliseconds to wait
3335 */
3336 OO.ui.WindowManager.prototype.getHoldDelay = function () {
3337 return 0;
3338 };
3339
3340 /**
3341 * Get the number of milliseconds to wait after the ‘hold’ process has finished before
3342 * executing the ‘teardown’ process.
3343 *
3344 * @param {OO.ui.Window} win Window being closed
3345 * @param {Object} [data] Window closing data
3346 * @return {number} Milliseconds to wait
3347 */
3348 OO.ui.WindowManager.prototype.getTeardownDelay = function () {
3349 return this.modal ? 250 : 0;
3350 };
3351
3352 /**
3353 * Get a window by its symbolic name.
3354 *
3355 * If the window is not yet instantiated and its symbolic name is recognized by a factory, it will be
3356 * instantiated and added to the window manager automatically. Please see the [OOjs UI documentation on MediaWiki][3]
3357 * for more information about using factories.
3358 * [3]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
3359 *
3360 * @param {string} name Symbolic name of the window
3361 * @return {jQuery.Promise} Promise resolved with matching window, or rejected with an OO.ui.Error
3362 * @throws {Error} An error is thrown if the symbolic name is not recognized by the factory.
3363 * @throws {Error} An error is thrown if the named window is not recognized as a managed window.
3364 */
3365 OO.ui.WindowManager.prototype.getWindow = function ( name ) {
3366 var deferred = $.Deferred(),
3367 win = this.windows[ name ];
3368
3369 if ( !( win instanceof OO.ui.Window ) ) {
3370 if ( this.factory ) {
3371 if ( !this.factory.lookup( name ) ) {
3372 deferred.reject( new OO.ui.Error(
3373 'Cannot auto-instantiate window: symbolic name is unrecognized by the factory'
3374 ) );
3375 } else {
3376 win = this.factory.create( name );
3377 this.addWindows( [ win ] );
3378 deferred.resolve( win );
3379 }
3380 } else {
3381 deferred.reject( new OO.ui.Error(
3382 'Cannot get unmanaged window: symbolic name unrecognized as a managed window'
3383 ) );
3384 }
3385 } else {
3386 deferred.resolve( win );
3387 }
3388
3389 return deferred.promise();
3390 };
3391
3392 /**
3393 * Get current window.
3394 *
3395 * @return {OO.ui.Window|null} Currently opening/opened/closing window
3396 */
3397 OO.ui.WindowManager.prototype.getCurrentWindow = function () {
3398 return this.currentWindow;
3399 };
3400
3401 /**
3402 * Open a window.
3403 *
3404 * @param {OO.ui.Window|string} win Window object or symbolic name of window to open
3405 * @param {Object} [data] Window opening data
3406 * @return {jQuery.Promise} An `opening` promise resolved when the window is done opening.
3407 * See {@link #event-opening 'opening' event} for more information about `opening` promises.
3408 * @fires opening
3409 */
3410 OO.ui.WindowManager.prototype.openWindow = function ( win, data ) {
3411 var manager = this,
3412 opening = $.Deferred();
3413
3414 // Argument handling
3415 if ( typeof win === 'string' ) {
3416 return this.getWindow( win ).then( function ( win ) {
3417 return manager.openWindow( win, data );
3418 } );
3419 }
3420
3421 // Error handling
3422 if ( !this.hasWindow( win ) ) {
3423 opening.reject( new OO.ui.Error(
3424 'Cannot open window: window is not attached to manager'
3425 ) );
3426 } else if ( this.preparingToOpen || this.opening || this.opened ) {
3427 opening.reject( new OO.ui.Error(
3428 'Cannot open window: another window is opening or open'
3429 ) );
3430 }
3431
3432 // Window opening
3433 if ( opening.state() !== 'rejected' ) {
3434 // If a window is currently closing, wait for it to complete
3435 this.preparingToOpen = $.when( this.closing );
3436 // Ensure handlers get called after preparingToOpen is set
3437 this.preparingToOpen.done( function () {
3438 if ( manager.modal ) {
3439 manager.toggleGlobalEvents( true );
3440 manager.toggleAriaIsolation( true );
3441 }
3442 manager.currentWindow = win;
3443 manager.opening = opening;
3444 manager.preparingToOpen = null;
3445 manager.emit( 'opening', win, opening, data );
3446 setTimeout( function () {
3447 win.setup( data ).then( function () {
3448 manager.updateWindowSize( win );
3449 manager.opening.notify( { state: 'setup' } );
3450 setTimeout( function () {
3451 win.ready( data ).then( function () {
3452 manager.opening.notify( { state: 'ready' } );
3453 manager.opening = null;
3454 manager.opened = $.Deferred();
3455 opening.resolve( manager.opened.promise(), data );
3456 } );
3457 }, manager.getReadyDelay() );
3458 } );
3459 }, manager.getSetupDelay() );
3460 } );
3461 }
3462
3463 return opening.promise();
3464 };
3465
3466 /**
3467 * Close a window.
3468 *
3469 * @param {OO.ui.Window|string} win Window object or symbolic name of window to close
3470 * @param {Object} [data] Window closing data
3471 * @return {jQuery.Promise} A `closing` promise resolved when the window is done closing.
3472 * See {@link #event-closing 'closing' event} for more information about closing promises.
3473 * @throws {Error} An error is thrown if the window is not managed by the window manager.
3474 * @fires closing
3475 */
3476 OO.ui.WindowManager.prototype.closeWindow = function ( win, data ) {
3477 var manager = this,
3478 closing = $.Deferred(),
3479 opened;
3480
3481 // Argument handling
3482 if ( typeof win === 'string' ) {
3483 win = this.windows[ win ];
3484 } else if ( !this.hasWindow( win ) ) {
3485 win = null;
3486 }
3487
3488 // Error handling
3489 if ( !win ) {
3490 closing.reject( new OO.ui.Error(
3491 'Cannot close window: window is not attached to manager'
3492 ) );
3493 } else if ( win !== this.currentWindow ) {
3494 closing.reject( new OO.ui.Error(
3495 'Cannot close window: window already closed with different data'
3496 ) );
3497 } else if ( this.preparingToClose || this.closing ) {
3498 closing.reject( new OO.ui.Error(
3499 'Cannot close window: window already closing with different data'
3500 ) );
3501 }
3502
3503 // Window closing
3504 if ( closing.state() !== 'rejected' ) {
3505 // If the window is currently opening, close it when it's done
3506 this.preparingToClose = $.when( this.opening );
3507 // Ensure handlers get called after preparingToClose is set
3508 this.preparingToClose.done( function () {
3509 manager.closing = closing;
3510 manager.preparingToClose = null;
3511 manager.emit( 'closing', win, closing, data );
3512 opened = manager.opened;
3513 manager.opened = null;
3514 opened.resolve( closing.promise(), data );
3515 setTimeout( function () {
3516 win.hold( data ).then( function () {
3517 closing.notify( { state: 'hold' } );
3518 setTimeout( function () {
3519 win.teardown( data ).then( function () {
3520 closing.notify( { state: 'teardown' } );
3521 if ( manager.modal ) {
3522 manager.toggleGlobalEvents( false );
3523 manager.toggleAriaIsolation( false );
3524 }
3525 manager.closing = null;
3526 manager.currentWindow = null;
3527 closing.resolve( data );
3528 } );
3529 }, manager.getTeardownDelay() );
3530 } );
3531 }, manager.getHoldDelay() );
3532 } );
3533 }
3534
3535 return closing.promise();
3536 };
3537
3538 /**
3539 * Add windows to the window manager.
3540 *
3541 * Windows can be added by reference, symbolic name, or explicitly defined symbolic names.
3542 * See the [OOjs ui documentation on MediaWiki] [2] for examples.
3543 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
3544 *
3545 * @param {Object.<string,OO.ui.Window>|OO.ui.Window[]} windows An array of window objects specified
3546 * by reference, symbolic name, or explicitly defined symbolic names.
3547 * @throws {Error} An error is thrown if a window is added by symbolic name, but has neither an
3548 * explicit nor a statically configured symbolic name.
3549 */
3550 OO.ui.WindowManager.prototype.addWindows = function ( windows ) {
3551 var i, len, win, name, list;
3552
3553 if ( Array.isArray( windows ) ) {
3554 // Convert to map of windows by looking up symbolic names from static configuration
3555 list = {};
3556 for ( i = 0, len = windows.length; i < len; i++ ) {
3557 name = windows[ i ].constructor.static.name;
3558 if ( typeof name !== 'string' ) {
3559 throw new Error( 'Cannot add window' );
3560 }
3561 list[ name ] = windows[ i ];
3562 }
3563 } else if ( OO.isPlainObject( windows ) ) {
3564 list = windows;
3565 }
3566
3567 // Add windows
3568 for ( name in list ) {
3569 win = list[ name ];
3570 this.windows[ name ] = win.toggle( false );
3571 this.$element.append( win.$element );
3572 win.setManager( this );
3573 }
3574 };
3575
3576 /**
3577 * Remove the specified windows from the windows manager.
3578 *
3579 * Windows will be closed before they are removed. If you wish to remove all windows, you may wish to use
3580 * the #clearWindows method instead. If you no longer need the window manager and want to ensure that it no
3581 * longer listens to events, use the #destroy method.
3582 *
3583 * @param {string[]} names Symbolic names of windows to remove
3584 * @return {jQuery.Promise} Promise resolved when window is closed and removed
3585 * @throws {Error} An error is thrown if the named windows are not managed by the window manager.
3586 */
3587 OO.ui.WindowManager.prototype.removeWindows = function ( names ) {
3588 var i, len, win, name, cleanupWindow,
3589 manager = this,
3590 promises = [],
3591 cleanup = function ( name, win ) {
3592 delete manager.windows[ name ];
3593 win.$element.detach();
3594 };
3595
3596 for ( i = 0, len = names.length; i < len; i++ ) {
3597 name = names[ i ];
3598 win = this.windows[ name ];
3599 if ( !win ) {
3600 throw new Error( 'Cannot remove window' );
3601 }
3602 cleanupWindow = cleanup.bind( null, name, win );
3603 promises.push( this.closeWindow( name ).then( cleanupWindow, cleanupWindow ) );
3604 }
3605
3606 return $.when.apply( $, promises );
3607 };
3608
3609 /**
3610 * Remove all windows from the window manager.
3611 *
3612 * Windows will be closed before they are removed. Note that the window manager, though not in use, will still
3613 * listen to events. If the window manager will not be used again, you may wish to use the #destroy method instead.
3614 * To remove just a subset of windows, use the #removeWindows method.
3615 *
3616 * @return {jQuery.Promise} Promise resolved when all windows are closed and removed
3617 */
3618 OO.ui.WindowManager.prototype.clearWindows = function () {
3619 return this.removeWindows( Object.keys( this.windows ) );
3620 };
3621
3622 /**
3623 * Set dialog size. In general, this method should not be called directly.
3624 *
3625 * Fullscreen mode will be used if the dialog is too wide to fit in the screen.
3626 *
3627 * @chainable
3628 */
3629 OO.ui.WindowManager.prototype.updateWindowSize = function ( win ) {
3630 var isFullscreen;
3631
3632 // Bypass for non-current, and thus invisible, windows
3633 if ( win !== this.currentWindow ) {
3634 return;
3635 }
3636
3637 isFullscreen = win.getSize() === 'full';
3638
3639 this.$element.toggleClass( 'oo-ui-windowManager-fullscreen', isFullscreen );
3640 this.$element.toggleClass( 'oo-ui-windowManager-floating', !isFullscreen );
3641 win.setDimensions( win.getSizeProperties() );
3642
3643 this.emit( 'resize', win );
3644
3645 return this;
3646 };
3647
3648 /**
3649 * Bind or unbind global events for scrolling.
3650 *
3651 * @private
3652 * @param {boolean} [on] Bind global events
3653 * @chainable
3654 */
3655 OO.ui.WindowManager.prototype.toggleGlobalEvents = function ( on ) {
3656 var scrollWidth, bodyMargin,
3657 $body = $( this.getElementDocument().body ),
3658 // We could have multiple window managers open so only modify
3659 // the body css at the bottom of the stack
3660 stackDepth = $body.data( 'windowManagerGlobalEvents' ) || 0 ;
3661
3662 on = on === undefined ? !!this.globalEvents : !!on;
3663
3664 if ( on ) {
3665 if ( !this.globalEvents ) {
3666 $( this.getElementWindow() ).on( {
3667 // Start listening for top-level window dimension changes
3668 'orientationchange resize': this.onWindowResizeHandler
3669 } );
3670 if ( stackDepth === 0 ) {
3671 scrollWidth = window.innerWidth - document.documentElement.clientWidth;
3672 bodyMargin = parseFloat( $body.css( 'margin-right' ) ) || 0;
3673 $body.css( {
3674 overflow: 'hidden',
3675 'margin-right': bodyMargin + scrollWidth
3676 } );
3677 }
3678 stackDepth++;
3679 this.globalEvents = true;
3680 }
3681 } else if ( this.globalEvents ) {
3682 $( this.getElementWindow() ).off( {
3683 // Stop listening for top-level window dimension changes
3684 'orientationchange resize': this.onWindowResizeHandler
3685 } );
3686 stackDepth--;
3687 if ( stackDepth === 0 ) {
3688 $body.css( {
3689 overflow: '',
3690 'margin-right': ''
3691 } );
3692 }
3693 this.globalEvents = false;
3694 }
3695 $body.data( 'windowManagerGlobalEvents', stackDepth );
3696
3697 return this;
3698 };
3699
3700 /**
3701 * Toggle screen reader visibility of content other than the window manager.
3702 *
3703 * @private
3704 * @param {boolean} [isolate] Make only the window manager visible to screen readers
3705 * @chainable
3706 */
3707 OO.ui.WindowManager.prototype.toggleAriaIsolation = function ( isolate ) {
3708 isolate = isolate === undefined ? !this.$ariaHidden : !!isolate;
3709
3710 if ( isolate ) {
3711 if ( !this.$ariaHidden ) {
3712 // Hide everything other than the window manager from screen readers
3713 this.$ariaHidden = $( 'body' )
3714 .children()
3715 .not( this.$element.parentsUntil( 'body' ).last() )
3716 .attr( 'aria-hidden', '' );
3717 }
3718 } else if ( this.$ariaHidden ) {
3719 // Restore screen reader visibility
3720 this.$ariaHidden.removeAttr( 'aria-hidden' );
3721 this.$ariaHidden = null;
3722 }
3723
3724 return this;
3725 };
3726
3727 /**
3728 * Destroy the window manager.
3729 *
3730 * Destroying the window manager ensures that it will no longer listen to events. If you would like to
3731 * continue using the window manager, but wish to remove all windows from it, use the #clearWindows method
3732 * instead.
3733 */
3734 OO.ui.WindowManager.prototype.destroy = function () {
3735 this.toggleGlobalEvents( false );
3736 this.toggleAriaIsolation( false );
3737 this.clearWindows();
3738 this.$element.remove();
3739 };
3740
3741 /**
3742 * Errors contain a required message (either a string or jQuery selection) that is used to describe what went wrong
3743 * in a {@link OO.ui.Process process}. The error's #recoverable and #warning configurations are used to customize the
3744 * appearance and functionality of the error interface.
3745 *
3746 * The basic error interface contains a formatted error message as well as two buttons: 'Dismiss' and 'Try again' (i.e., the error
3747 * is 'recoverable' by default). If the error is not recoverable, the 'Try again' button will not be rendered and the widget
3748 * that initiated the failed process will be disabled.
3749 *
3750 * If the error is a warning, the error interface will include a 'Dismiss' and a 'Continue' button, which will try the
3751 * process again.
3752 *
3753 * For an example of error interfaces, please see the [OOjs UI documentation on MediaWiki][1].
3754 *
3755 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Processes_and_errors
3756 *
3757 * @class
3758 *
3759 * @constructor
3760 * @param {string|jQuery} message Description of error
3761 * @param {Object} [config] Configuration options
3762 * @cfg {boolean} [recoverable=true] Error is recoverable.
3763 * By default, errors are recoverable, and users can try the process again.
3764 * @cfg {boolean} [warning=false] Error is a warning.
3765 * If the error is a warning, the error interface will include a
3766 * 'Dismiss' and a 'Continue' button. It is the responsibility of the developer to ensure that the warning
3767 * is not triggered a second time if the user chooses to continue.
3768 */
3769 OO.ui.Error = function OoUiError( message, config ) {
3770 // Allow passing positional parameters inside the config object
3771 if ( OO.isPlainObject( message ) && config === undefined ) {
3772 config = message;
3773 message = config.message;
3774 }
3775
3776 // Configuration initialization
3777 config = config || {};
3778
3779 // Properties
3780 this.message = message instanceof jQuery ? message : String( message );
3781 this.recoverable = config.recoverable === undefined || !!config.recoverable;
3782 this.warning = !!config.warning;
3783 };
3784
3785 /* Setup */
3786
3787 OO.initClass( OO.ui.Error );
3788
3789 /* Methods */
3790
3791 /**
3792 * Check if the error is recoverable.
3793 *
3794 * If the error is recoverable, users are able to try the process again.
3795 *
3796 * @return {boolean} Error is recoverable
3797 */
3798 OO.ui.Error.prototype.isRecoverable = function () {
3799 return this.recoverable;
3800 };
3801
3802 /**
3803 * Check if the error is a warning.
3804 *
3805 * If the error is a warning, the error interface will include a 'Dismiss' and a 'Continue' button.
3806 *
3807 * @return {boolean} Error is warning
3808 */
3809 OO.ui.Error.prototype.isWarning = function () {
3810 return this.warning;
3811 };
3812
3813 /**
3814 * Get error message as DOM nodes.
3815 *
3816 * @return {jQuery} Error message in DOM nodes
3817 */
3818 OO.ui.Error.prototype.getMessage = function () {
3819 return this.message instanceof jQuery ?
3820 this.message.clone() :
3821 $( '<div>' ).text( this.message ).contents();
3822 };
3823
3824 /**
3825 * Get the error message text.
3826 *
3827 * @return {string} Error message
3828 */
3829 OO.ui.Error.prototype.getMessageText = function () {
3830 return this.message instanceof jQuery ? this.message.text() : this.message;
3831 };
3832
3833 /**
3834 * Wraps an HTML snippet for use with configuration values which default
3835 * to strings. This bypasses the default html-escaping done to string
3836 * values.
3837 *
3838 * @class
3839 *
3840 * @constructor
3841 * @param {string} [content] HTML content
3842 */
3843 OO.ui.HtmlSnippet = function OoUiHtmlSnippet( content ) {
3844 // Properties
3845 this.content = content;
3846 };
3847
3848 /* Setup */
3849
3850 OO.initClass( OO.ui.HtmlSnippet );
3851
3852 /* Methods */
3853
3854 /**
3855 * Render into HTML.
3856 *
3857 * @return {string} Unchanged HTML snippet.
3858 */
3859 OO.ui.HtmlSnippet.prototype.toString = function () {
3860 return this.content;
3861 };
3862
3863 /**
3864 * A Process is a list of steps that are called in sequence. The step can be a number, a jQuery promise,
3865 * or a function:
3866 *
3867 * - **number**: the process will wait for the specified number of milliseconds before proceeding.
3868 * - **promise**: the process will continue to the next step when the promise is successfully resolved
3869 * or stop if the promise is rejected.
3870 * - **function**: the process will execute the function. The process will stop if the function returns
3871 * either a boolean `false` or a promise that is rejected; if the function returns a number, the process
3872 * will wait for that number of milliseconds before proceeding.
3873 *
3874 * If the process fails, an {@link OO.ui.Error error} is generated. Depending on how the error is
3875 * configured, users can dismiss the error and try the process again, or not. If a process is stopped,
3876 * its remaining steps will not be performed.
3877 *
3878 * @class
3879 *
3880 * @constructor
3881 * @param {number|jQuery.Promise|Function} step Number of miliseconds to wait before proceeding, promise
3882 * that must be resolved before proceeding, or a function to execute. See #createStep for more information. see #createStep for more information
3883 * @param {Object} [context=null] Execution context of the function. The context is ignored if the step is
3884 * a number or promise.
3885 * @return {Object} Step object, with `callback` and `context` properties
3886 */
3887 OO.ui.Process = function ( step, context ) {
3888 // Properties
3889 this.steps = [];
3890
3891 // Initialization
3892 if ( step !== undefined ) {
3893 this.next( step, context );
3894 }
3895 };
3896
3897 /* Setup */
3898
3899 OO.initClass( OO.ui.Process );
3900
3901 /* Methods */
3902
3903 /**
3904 * Start the process.
3905 *
3906 * @return {jQuery.Promise} Promise that is resolved when all steps have successfully completed.
3907 * If any of the steps return a promise that is rejected or a boolean false, this promise is rejected
3908 * and any remaining steps are not performed.
3909 */
3910 OO.ui.Process.prototype.execute = function () {
3911 var i, len, promise;
3912
3913 /**
3914 * Continue execution.
3915 *
3916 * @ignore
3917 * @param {Array} step A function and the context it should be called in
3918 * @return {Function} Function that continues the process
3919 */
3920 function proceed( step ) {
3921 return function () {
3922 // Execute step in the correct context
3923 var deferred,
3924 result = step.callback.call( step.context );
3925
3926 if ( result === false ) {
3927 // Use rejected promise for boolean false results
3928 return $.Deferred().reject( [] ).promise();
3929 }
3930 if ( typeof result === 'number' ) {
3931 if ( result < 0 ) {
3932 throw new Error( 'Cannot go back in time: flux capacitor is out of service' );
3933 }
3934 // Use a delayed promise for numbers, expecting them to be in milliseconds
3935 deferred = $.Deferred();
3936 setTimeout( deferred.resolve, result );
3937 return deferred.promise();
3938 }
3939 if ( result instanceof OO.ui.Error ) {
3940 // Use rejected promise for error
3941 return $.Deferred().reject( [ result ] ).promise();
3942 }
3943 if ( Array.isArray( result ) && result.length && result[ 0 ] instanceof OO.ui.Error ) {
3944 // Use rejected promise for list of errors
3945 return $.Deferred().reject( result ).promise();
3946 }
3947 // Duck-type the object to see if it can produce a promise
3948 if ( result && $.isFunction( result.promise ) ) {
3949 // Use a promise generated from the result
3950 return result.promise();
3951 }
3952 // Use resolved promise for other results
3953 return $.Deferred().resolve().promise();
3954 };
3955 }
3956
3957 if ( this.steps.length ) {
3958 // Generate a chain reaction of promises
3959 promise = proceed( this.steps[ 0 ] )();
3960 for ( i = 1, len = this.steps.length; i < len; i++ ) {
3961 promise = promise.then( proceed( this.steps[ i ] ) );
3962 }
3963 } else {
3964 promise = $.Deferred().resolve().promise();
3965 }
3966
3967 return promise;
3968 };
3969
3970 /**
3971 * Create a process step.
3972 *
3973 * @private
3974 * @param {number|jQuery.Promise|Function} step
3975 *
3976 * - Number of milliseconds to wait before proceeding
3977 * - Promise that must be resolved before proceeding
3978 * - Function to execute
3979 * - If the function returns a boolean false the process will stop
3980 * - If the function returns a promise, the process will continue to the next
3981 * step when the promise is resolved or stop if the promise is rejected
3982 * - If the function returns a number, the process will wait for that number of
3983 * milliseconds before proceeding
3984 * @param {Object} [context=null] Execution context of the function. The context is
3985 * ignored if the step is a number or promise.
3986 * @return {Object} Step object, with `callback` and `context` properties
3987 */
3988 OO.ui.Process.prototype.createStep = function ( step, context ) {
3989 if ( typeof step === 'number' || $.isFunction( step.promise ) ) {
3990 return {
3991 callback: function () {
3992 return step;
3993 },
3994 context: null
3995 };
3996 }
3997 if ( $.isFunction( step ) ) {
3998 return {
3999 callback: step,
4000 context: context
4001 };
4002 }
4003 throw new Error( 'Cannot create process step: number, promise or function expected' );
4004 };
4005
4006 /**
4007 * Add step to the beginning of the process.
4008 *
4009 * @inheritdoc #createStep
4010 * @return {OO.ui.Process} this
4011 * @chainable
4012 */
4013 OO.ui.Process.prototype.first = function ( step, context ) {
4014 this.steps.unshift( this.createStep( step, context ) );
4015 return this;
4016 };
4017
4018 /**
4019 * Add step to the end of the process.
4020 *
4021 * @inheritdoc #createStep
4022 * @return {OO.ui.Process} this
4023 * @chainable
4024 */
4025 OO.ui.Process.prototype.next = function ( step, context ) {
4026 this.steps.push( this.createStep( step, context ) );
4027 return this;
4028 };
4029
4030 /**
4031 * A ToolFactory creates tools on demand. All tools ({@link OO.ui.Tool Tools}, {@link OO.ui.PopupTool PopupTools},
4032 * and {@link OO.ui.ToolGroupTool ToolGroupTools}) must be registered with a tool factory. Tools are
4033 * registered by their symbolic name. See {@link OO.ui.Toolbar toolbars} for an example.
4034 *
4035 * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki][1].
4036 *
4037 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
4038 *
4039 * @class
4040 * @extends OO.Factory
4041 * @constructor
4042 */
4043 OO.ui.ToolFactory = function OoUiToolFactory() {
4044 // Parent constructor
4045 OO.ui.ToolFactory.parent.call( this );
4046 };
4047
4048 /* Setup */
4049
4050 OO.inheritClass( OO.ui.ToolFactory, OO.Factory );
4051
4052 /* Methods */
4053
4054 /**
4055 * Get tools from the factory
4056 *
4057 * @param {Array} include Included tools
4058 * @param {Array} exclude Excluded tools
4059 * @param {Array} promote Promoted tools
4060 * @param {Array} demote Demoted tools
4061 * @return {string[]} List of tools
4062 */
4063 OO.ui.ToolFactory.prototype.getTools = function ( include, exclude, promote, demote ) {
4064 var i, len, included, promoted, demoted,
4065 auto = [],
4066 used = {};
4067
4068 // Collect included and not excluded tools
4069 included = OO.simpleArrayDifference( this.extract( include ), this.extract( exclude ) );
4070
4071 // Promotion
4072 promoted = this.extract( promote, used );
4073 demoted = this.extract( demote, used );
4074
4075 // Auto
4076 for ( i = 0, len = included.length; i < len; i++ ) {
4077 if ( !used[ included[ i ] ] ) {
4078 auto.push( included[ i ] );
4079 }
4080 }
4081
4082 return promoted.concat( auto ).concat( demoted );
4083 };
4084
4085 /**
4086 * Get a flat list of names from a list of names or groups.
4087 *
4088 * Tools can be specified in the following ways:
4089 *
4090 * - A specific tool: `{ name: 'tool-name' }` or `'tool-name'`
4091 * - All tools in a group: `{ group: 'group-name' }`
4092 * - All tools: `'*'`
4093 *
4094 * @private
4095 * @param {Array|string} collection List of tools
4096 * @param {Object} [used] Object with names that should be skipped as properties; extracted
4097 * names will be added as properties
4098 * @return {string[]} List of extracted names
4099 */
4100 OO.ui.ToolFactory.prototype.extract = function ( collection, used ) {
4101 var i, len, item, name, tool,
4102 names = [];
4103
4104 if ( collection === '*' ) {
4105 for ( name in this.registry ) {
4106 tool = this.registry[ name ];
4107 if (
4108 // Only add tools by group name when auto-add is enabled
4109 tool.static.autoAddToCatchall &&
4110 // Exclude already used tools
4111 ( !used || !used[ name ] )
4112 ) {
4113 names.push( name );
4114 if ( used ) {
4115 used[ name ] = true;
4116 }
4117 }
4118 }
4119 } else if ( Array.isArray( collection ) ) {
4120 for ( i = 0, len = collection.length; i < len; i++ ) {
4121 item = collection[ i ];
4122 // Allow plain strings as shorthand for named tools
4123 if ( typeof item === 'string' ) {
4124 item = { name: item };
4125 }
4126 if ( OO.isPlainObject( item ) ) {
4127 if ( item.group ) {
4128 for ( name in this.registry ) {
4129 tool = this.registry[ name ];
4130 if (
4131 // Include tools with matching group
4132 tool.static.group === item.group &&
4133 // Only add tools by group name when auto-add is enabled
4134 tool.static.autoAddToGroup &&
4135 // Exclude already used tools
4136 ( !used || !used[ name ] )
4137 ) {
4138 names.push( name );
4139 if ( used ) {
4140 used[ name ] = true;
4141 }
4142 }
4143 }
4144 // Include tools with matching name and exclude already used tools
4145 } else if ( item.name && ( !used || !used[ item.name ] ) ) {
4146 names.push( item.name );
4147 if ( used ) {
4148 used[ item.name ] = true;
4149 }
4150 }
4151 }
4152 }
4153 }
4154 return names;
4155 };
4156
4157 /**
4158 * ToolGroupFactories create {@link OO.ui.ToolGroup toolgroups} on demand. The toolgroup classes must
4159 * specify a symbolic name and be registered with the factory. The following classes are registered by
4160 * default:
4161 *
4162 * - {@link OO.ui.BarToolGroup BarToolGroups} (‘bar’)
4163 * - {@link OO.ui.MenuToolGroup MenuToolGroups} (‘menu’)
4164 * - {@link OO.ui.ListToolGroup ListToolGroups} (‘list’)
4165 *
4166 * See {@link OO.ui.Toolbar toolbars} for an example.
4167 *
4168 * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki][1].
4169 *
4170 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
4171 * @class
4172 * @extends OO.Factory
4173 * @constructor
4174 */
4175 OO.ui.ToolGroupFactory = function OoUiToolGroupFactory() {
4176 var i, l, defaultClasses;
4177 // Parent constructor
4178 OO.Factory.call( this );
4179
4180 defaultClasses = this.constructor.static.getDefaultClasses();
4181
4182 // Register default toolgroups
4183 for ( i = 0, l = defaultClasses.length; i < l; i++ ) {
4184 this.register( defaultClasses[ i ] );
4185 }
4186 };
4187
4188 /* Setup */
4189
4190 OO.inheritClass( OO.ui.ToolGroupFactory, OO.Factory );
4191
4192 /* Static Methods */
4193
4194 /**
4195 * Get a default set of classes to be registered on construction.
4196 *
4197 * @return {Function[]} Default classes
4198 */
4199 OO.ui.ToolGroupFactory.static.getDefaultClasses = function () {
4200 return [
4201 OO.ui.BarToolGroup,
4202 OO.ui.ListToolGroup,
4203 OO.ui.MenuToolGroup
4204 ];
4205 };
4206
4207 /**
4208 * Theme logic.
4209 *
4210 * @abstract
4211 * @class
4212 *
4213 * @constructor
4214 * @param {Object} [config] Configuration options
4215 */
4216 OO.ui.Theme = function OoUiTheme( config ) {
4217 // Configuration initialization
4218 config = config || {};
4219 };
4220
4221 /* Setup */
4222
4223 OO.initClass( OO.ui.Theme );
4224
4225 /* Methods */
4226
4227 /**
4228 * Get a list of classes to be applied to a widget.
4229 *
4230 * The 'on' and 'off' lists combined MUST contain keys for all classes the theme adds or removes,
4231 * otherwise state transitions will not work properly.
4232 *
4233 * @param {OO.ui.Element} element Element for which to get classes
4234 * @return {Object.<string,string[]>} Categorized class names with `on` and `off` lists
4235 */
4236 OO.ui.Theme.prototype.getElementClasses = function ( /* element */ ) {
4237 return { on: [], off: [] };
4238 };
4239
4240 /**
4241 * Update CSS classes provided by the theme.
4242 *
4243 * For elements with theme logic hooks, this should be called any time there's a state change.
4244 *
4245 * @param {OO.ui.Element} element Element for which to update classes
4246 * @return {Object.<string,string[]>} Categorized class names with `on` and `off` lists
4247 */
4248 OO.ui.Theme.prototype.updateElementClasses = function ( element ) {
4249 var $elements = $( [] ),
4250 classes = this.getElementClasses( element );
4251
4252 if ( element.$icon ) {
4253 $elements = $elements.add( element.$icon );
4254 }
4255 if ( element.$indicator ) {
4256 $elements = $elements.add( element.$indicator );
4257 }
4258
4259 $elements
4260 .removeClass( classes.off.join( ' ' ) )
4261 .addClass( classes.on.join( ' ' ) );
4262 };
4263
4264 /**
4265 * The TabIndexedElement class is an attribute mixin used to add additional functionality to an
4266 * element created by another class. The mixin provides a ‘tabIndex’ property, which specifies the
4267 * order in which users will navigate through the focusable elements via the "tab" key.
4268 *
4269 * @example
4270 * // TabIndexedElement is mixed into the ButtonWidget class
4271 * // to provide a tabIndex property.
4272 * var button1 = new OO.ui.ButtonWidget( {
4273 * label: 'fourth',
4274 * tabIndex: 4
4275 * } );
4276 * var button2 = new OO.ui.ButtonWidget( {
4277 * label: 'second',
4278 * tabIndex: 2
4279 * } );
4280 * var button3 = new OO.ui.ButtonWidget( {
4281 * label: 'third',
4282 * tabIndex: 3
4283 * } );
4284 * var button4 = new OO.ui.ButtonWidget( {
4285 * label: 'first',
4286 * tabIndex: 1
4287 * } );
4288 * $( 'body' ).append( button1.$element, button2.$element, button3.$element, button4.$element );
4289 *
4290 * @abstract
4291 * @class
4292 *
4293 * @constructor
4294 * @param {Object} [config] Configuration options
4295 * @cfg {jQuery} [$tabIndexed] The element that should use the tabindex functionality. By default,
4296 * the functionality is applied to the element created by the class ($element). If a different element is specified, the tabindex
4297 * functionality will be applied to it instead.
4298 * @cfg {number|null} [tabIndex=0] Number that specifies the element’s position in the tab-navigation
4299 * order (e.g., 1 for the first focusable element). Use 0 to use the default navigation order; use -1
4300 * to remove the element from the tab-navigation flow.
4301 */
4302 OO.ui.mixin.TabIndexedElement = function OoUiMixinTabIndexedElement( config ) {
4303 // Configuration initialization
4304 config = $.extend( { tabIndex: 0 }, config );
4305
4306 // Properties
4307 this.$tabIndexed = null;
4308 this.tabIndex = null;
4309
4310 // Events
4311 this.connect( this, { disable: 'onTabIndexedElementDisable' } );
4312
4313 // Initialization
4314 this.setTabIndex( config.tabIndex );
4315 this.setTabIndexedElement( config.$tabIndexed || this.$element );
4316 };
4317
4318 /* Setup */
4319
4320 OO.initClass( OO.ui.mixin.TabIndexedElement );
4321
4322 /* Methods */
4323
4324 /**
4325 * Set the element that should use the tabindex functionality.
4326 *
4327 * This method is used to retarget a tabindex mixin so that its functionality applies
4328 * to the specified element. If an element is currently using the functionality, the mixin’s
4329 * effect on that element is removed before the new element is set up.
4330 *
4331 * @param {jQuery} $tabIndexed Element that should use the tabindex functionality
4332 * @chainable
4333 */
4334 OO.ui.mixin.TabIndexedElement.prototype.setTabIndexedElement = function ( $tabIndexed ) {
4335 var tabIndex = this.tabIndex;
4336 // Remove attributes from old $tabIndexed
4337 this.setTabIndex( null );
4338 // Force update of new $tabIndexed
4339 this.$tabIndexed = $tabIndexed;
4340 this.tabIndex = tabIndex;
4341 return this.updateTabIndex();
4342 };
4343
4344 /**
4345 * Set the value of the tabindex.
4346 *
4347 * @param {number|null} tabIndex Tabindex value, or `null` for no tabindex
4348 * @chainable
4349 */
4350 OO.ui.mixin.TabIndexedElement.prototype.setTabIndex = function ( tabIndex ) {
4351 tabIndex = typeof tabIndex === 'number' ? tabIndex : null;
4352
4353 if ( this.tabIndex !== tabIndex ) {
4354 this.tabIndex = tabIndex;
4355 this.updateTabIndex();
4356 }
4357
4358 return this;
4359 };
4360
4361 /**
4362 * Update the `tabindex` attribute, in case of changes to tab index or
4363 * disabled state.
4364 *
4365 * @private
4366 * @chainable
4367 */
4368 OO.ui.mixin.TabIndexedElement.prototype.updateTabIndex = function () {
4369 if ( this.$tabIndexed ) {
4370 if ( this.tabIndex !== null ) {
4371 // Do not index over disabled elements
4372 this.$tabIndexed.attr( {
4373 tabindex: this.isDisabled() ? -1 : this.tabIndex,
4374 // Support: ChromeVox and NVDA
4375 // These do not seem to inherit aria-disabled from parent elements
4376 'aria-disabled': this.isDisabled().toString()
4377 } );
4378 } else {
4379 this.$tabIndexed.removeAttr( 'tabindex aria-disabled' );
4380 }
4381 }
4382 return this;
4383 };
4384
4385 /**
4386 * Handle disable events.
4387 *
4388 * @private
4389 * @param {boolean} disabled Element is disabled
4390 */
4391 OO.ui.mixin.TabIndexedElement.prototype.onTabIndexedElementDisable = function () {
4392 this.updateTabIndex();
4393 };
4394
4395 /**
4396 * Get the value of the tabindex.
4397 *
4398 * @return {number|null} Tabindex value
4399 */
4400 OO.ui.mixin.TabIndexedElement.prototype.getTabIndex = function () {
4401 return this.tabIndex;
4402 };
4403
4404 /**
4405 * ButtonElement is often mixed into other classes to generate a button, which is a clickable
4406 * interface element that can be configured with access keys for accessibility.
4407 * See the [OOjs UI documentation on MediaWiki] [1] for examples.
4408 *
4409 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#Buttons
4410 * @abstract
4411 * @class
4412 *
4413 * @constructor
4414 * @param {Object} [config] Configuration options
4415 * @cfg {jQuery} [$button] The button element created by the class.
4416 * If this configuration is omitted, the button element will use a generated `<a>`.
4417 * @cfg {boolean} [framed=true] Render the button with a frame
4418 */
4419 OO.ui.mixin.ButtonElement = function OoUiMixinButtonElement( config ) {
4420 // Configuration initialization
4421 config = config || {};
4422
4423 // Properties
4424 this.$button = null;
4425 this.framed = null;
4426 this.active = false;
4427 this.onMouseUpHandler = this.onMouseUp.bind( this );
4428 this.onMouseDownHandler = this.onMouseDown.bind( this );
4429 this.onKeyDownHandler = this.onKeyDown.bind( this );
4430 this.onKeyUpHandler = this.onKeyUp.bind( this );
4431 this.onClickHandler = this.onClick.bind( this );
4432 this.onKeyPressHandler = this.onKeyPress.bind( this );
4433
4434 // Initialization
4435 this.$element.addClass( 'oo-ui-buttonElement' );
4436 this.toggleFramed( config.framed === undefined || config.framed );
4437 this.setButtonElement( config.$button || $( '<a>' ) );
4438 };
4439
4440 /* Setup */
4441
4442 OO.initClass( OO.ui.mixin.ButtonElement );
4443
4444 /* Static Properties */
4445
4446 /**
4447 * Cancel mouse down events.
4448 *
4449 * This property is usually set to `true` to prevent the focus from changing when the button is clicked.
4450 * Classes such as {@link OO.ui.mixin.DraggableElement DraggableElement} and {@link OO.ui.ButtonOptionWidget ButtonOptionWidget}
4451 * use a value of `false` so that dragging behavior is possible and mousedown events can be handled by a
4452 * parent widget.
4453 *
4454 * @static
4455 * @inheritable
4456 * @property {boolean}
4457 */
4458 OO.ui.mixin.ButtonElement.static.cancelButtonMouseDownEvents = true;
4459
4460 /* Events */
4461
4462 /**
4463 * A 'click' event is emitted when the button element is clicked.
4464 *
4465 * @event click
4466 */
4467
4468 /* Methods */
4469
4470 /**
4471 * Set the button element.
4472 *
4473 * This method is used to retarget a button mixin so that its functionality applies to
4474 * the specified button element instead of the one created by the class. If a button element
4475 * is already set, the method will remove the mixin’s effect on that element.
4476 *
4477 * @param {jQuery} $button Element to use as button
4478 */
4479 OO.ui.mixin.ButtonElement.prototype.setButtonElement = function ( $button ) {
4480 if ( this.$button ) {
4481 this.$button
4482 .removeClass( 'oo-ui-buttonElement-button' )
4483 .removeAttr( 'role accesskey' )
4484 .off( {
4485 mousedown: this.onMouseDownHandler,
4486 keydown: this.onKeyDownHandler,
4487 click: this.onClickHandler,
4488 keypress: this.onKeyPressHandler
4489 } );
4490 }
4491
4492 this.$button = $button
4493 .addClass( 'oo-ui-buttonElement-button' )
4494 .attr( { role: 'button' } )
4495 .on( {
4496 mousedown: this.onMouseDownHandler,
4497 keydown: this.onKeyDownHandler,
4498 click: this.onClickHandler,
4499 keypress: this.onKeyPressHandler
4500 } );
4501 };
4502
4503 /**
4504 * Handles mouse down events.
4505 *
4506 * @protected
4507 * @param {jQuery.Event} e Mouse down event
4508 */
4509 OO.ui.mixin.ButtonElement.prototype.onMouseDown = function ( e ) {
4510 if ( this.isDisabled() || e.which !== 1 ) {
4511 return;
4512 }
4513 this.$element.addClass( 'oo-ui-buttonElement-pressed' );
4514 // Run the mouseup handler no matter where the mouse is when the button is let go, so we can
4515 // reliably remove the pressed class
4516 OO.ui.addCaptureEventListener( this.getElementDocument(), 'mouseup', this.onMouseUpHandler );
4517 // Prevent change of focus unless specifically configured otherwise
4518 if ( this.constructor.static.cancelButtonMouseDownEvents ) {
4519 return false;
4520 }
4521 };
4522
4523 /**
4524 * Handles mouse up events.
4525 *
4526 * @protected
4527 * @param {jQuery.Event} e Mouse up event
4528 */
4529 OO.ui.mixin.ButtonElement.prototype.onMouseUp = function ( e ) {
4530 if ( this.isDisabled() || e.which !== 1 ) {
4531 return;
4532 }
4533 this.$element.removeClass( 'oo-ui-buttonElement-pressed' );
4534 // Stop listening for mouseup, since we only needed this once
4535 OO.ui.removeCaptureEventListener( this.getElementDocument(), 'mouseup', this.onMouseUpHandler );
4536 };
4537
4538 /**
4539 * Handles mouse click events.
4540 *
4541 * @protected
4542 * @param {jQuery.Event} e Mouse click event
4543 * @fires click
4544 */
4545 OO.ui.mixin.ButtonElement.prototype.onClick = function ( e ) {
4546 if ( !this.isDisabled() && e.which === 1 ) {
4547 if ( this.emit( 'click' ) ) {
4548 return false;
4549 }
4550 }
4551 };
4552
4553 /**
4554 * Handles key down events.
4555 *
4556 * @protected
4557 * @param {jQuery.Event} e Key down event
4558 */
4559 OO.ui.mixin.ButtonElement.prototype.onKeyDown = function ( e ) {
4560 if ( this.isDisabled() || ( e.which !== OO.ui.Keys.SPACE && e.which !== OO.ui.Keys.ENTER ) ) {
4561 return;
4562 }
4563 this.$element.addClass( 'oo-ui-buttonElement-pressed' );
4564 // Run the keyup handler no matter where the key is when the button is let go, so we can
4565 // reliably remove the pressed class
4566 OO.ui.addCaptureEventListener( this.getElementDocument(), 'keyup', this.onKeyUpHandler );
4567 };
4568
4569 /**
4570 * Handles key up events.
4571 *
4572 * @protected
4573 * @param {jQuery.Event} e Key up event
4574 */
4575 OO.ui.mixin.ButtonElement.prototype.onKeyUp = function ( e ) {
4576 if ( this.isDisabled() || ( e.which !== OO.ui.Keys.SPACE && e.which !== OO.ui.Keys.ENTER ) ) {
4577 return;
4578 }
4579 this.$element.removeClass( 'oo-ui-buttonElement-pressed' );
4580 // Stop listening for keyup, since we only needed this once
4581 OO.ui.removeCaptureEventListener( this.getElementDocument(), 'keyup', this.onKeyUpHandler );
4582 };
4583
4584 /**
4585 * Handles key press events.
4586 *
4587 * @protected
4588 * @param {jQuery.Event} e Key press event
4589 * @fires click
4590 */
4591 OO.ui.mixin.ButtonElement.prototype.onKeyPress = function ( e ) {
4592 if ( !this.isDisabled() && ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER ) ) {
4593 if ( this.emit( 'click' ) ) {
4594 return false;
4595 }
4596 }
4597 };
4598
4599 /**
4600 * Check if button has a frame.
4601 *
4602 * @return {boolean} Button is framed
4603 */
4604 OO.ui.mixin.ButtonElement.prototype.isFramed = function () {
4605 return this.framed;
4606 };
4607
4608 /**
4609 * Render the button with or without a frame. Omit the `framed` parameter to toggle the button frame on and off.
4610 *
4611 * @param {boolean} [framed] Make button framed, omit to toggle
4612 * @chainable
4613 */
4614 OO.ui.mixin.ButtonElement.prototype.toggleFramed = function ( framed ) {
4615 framed = framed === undefined ? !this.framed : !!framed;
4616 if ( framed !== this.framed ) {
4617 this.framed = framed;
4618 this.$element
4619 .toggleClass( 'oo-ui-buttonElement-frameless', !framed )
4620 .toggleClass( 'oo-ui-buttonElement-framed', framed );
4621 this.updateThemeClasses();
4622 }
4623
4624 return this;
4625 };
4626
4627 /**
4628 * Set the button to its 'active' state.
4629 *
4630 * The active state occurs when a {@link OO.ui.ButtonOptionWidget ButtonOptionWidget} or
4631 * a {@link OO.ui.ToggleButtonWidget ToggleButtonWidget} is pressed. This method does nothing
4632 * for other button types.
4633 *
4634 * @param {boolean} [value] Make button active
4635 * @chainable
4636 */
4637 OO.ui.mixin.ButtonElement.prototype.setActive = function ( value ) {
4638 this.$element.toggleClass( 'oo-ui-buttonElement-active', !!value );
4639 return this;
4640 };
4641
4642 /**
4643 * Any OOjs UI widget that contains other widgets (such as {@link OO.ui.ButtonWidget buttons} or
4644 * {@link OO.ui.OptionWidget options}) mixes in GroupElement. Adding, removing, and clearing
4645 * items from the group is done through the interface the class provides.
4646 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
4647 *
4648 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Groups
4649 *
4650 * @abstract
4651 * @class
4652 *
4653 * @constructor
4654 * @param {Object} [config] Configuration options
4655 * @cfg {jQuery} [$group] The container element created by the class. If this configuration
4656 * is omitted, the group element will use a generated `<div>`.
4657 */
4658 OO.ui.mixin.GroupElement = function OoUiMixinGroupElement( config ) {
4659 // Configuration initialization
4660 config = config || {};
4661
4662 // Properties
4663 this.$group = null;
4664 this.items = [];
4665 this.aggregateItemEvents = {};
4666
4667 // Initialization
4668 this.setGroupElement( config.$group || $( '<div>' ) );
4669 };
4670
4671 /* Methods */
4672
4673 /**
4674 * Set the group element.
4675 *
4676 * If an element is already set, items will be moved to the new element.
4677 *
4678 * @param {jQuery} $group Element to use as group
4679 */
4680 OO.ui.mixin.GroupElement.prototype.setGroupElement = function ( $group ) {
4681 var i, len;
4682
4683 this.$group = $group;
4684 for ( i = 0, len = this.items.length; i < len; i++ ) {
4685 this.$group.append( this.items[ i ].$element );
4686 }
4687 };
4688
4689 /**
4690 * Check if a group contains no items.
4691 *
4692 * @return {boolean} Group is empty
4693 */
4694 OO.ui.mixin.GroupElement.prototype.isEmpty = function () {
4695 return !this.items.length;
4696 };
4697
4698 /**
4699 * Get all items in the group.
4700 *
4701 * The method returns an array of item references (e.g., [button1, button2, button3]) and is useful
4702 * when synchronizing groups of items, or whenever the references are required (e.g., when removing items
4703 * from a group).
4704 *
4705 * @return {OO.ui.Element[]} An array of items.
4706 */
4707 OO.ui.mixin.GroupElement.prototype.getItems = function () {
4708 return this.items.slice( 0 );
4709 };
4710
4711 /**
4712 * Get an item by its data.
4713 *
4714 * Only the first item with matching data will be returned. To return all matching items,
4715 * use the #getItemsFromData method.
4716 *
4717 * @param {Object} data Item data to search for
4718 * @return {OO.ui.Element|null} Item with equivalent data, `null` if none exists
4719 */
4720 OO.ui.mixin.GroupElement.prototype.getItemFromData = function ( data ) {
4721 var i, len, item,
4722 hash = OO.getHash( data );
4723
4724 for ( i = 0, len = this.items.length; i < len; i++ ) {
4725 item = this.items[ i ];
4726 if ( hash === OO.getHash( item.getData() ) ) {
4727 return item;
4728 }
4729 }
4730
4731 return null;
4732 };
4733
4734 /**
4735 * Get items by their data.
4736 *
4737 * All items with matching data will be returned. To return only the first match, use the #getItemFromData method instead.
4738 *
4739 * @param {Object} data Item data to search for
4740 * @return {OO.ui.Element[]} Items with equivalent data
4741 */
4742 OO.ui.mixin.GroupElement.prototype.getItemsFromData = function ( data ) {
4743 var i, len, item,
4744 hash = OO.getHash( data ),
4745 items = [];
4746
4747 for ( i = 0, len = this.items.length; i < len; i++ ) {
4748 item = this.items[ i ];
4749 if ( hash === OO.getHash( item.getData() ) ) {
4750 items.push( item );
4751 }
4752 }
4753
4754 return items;
4755 };
4756
4757 /**
4758 * Aggregate the events emitted by the group.
4759 *
4760 * When events are aggregated, the group will listen to all contained items for the event,
4761 * and then emit the event under a new name. The new event will contain an additional leading
4762 * parameter containing the item that emitted the original event. Other arguments emitted from
4763 * the original event are passed through.
4764 *
4765 * @param {Object.<string,string|null>} events An object keyed by the name of the event that should be
4766 * aggregated (e.g., ‘click’) and the value of the new name to use (e.g., ‘groupClick’).
4767 * A `null` value will remove aggregated events.
4768
4769 * @throws {Error} An error is thrown if aggregation already exists.
4770 */
4771 OO.ui.mixin.GroupElement.prototype.aggregate = function ( events ) {
4772 var i, len, item, add, remove, itemEvent, groupEvent;
4773
4774 for ( itemEvent in events ) {
4775 groupEvent = events[ itemEvent ];
4776
4777 // Remove existing aggregated event
4778 if ( Object.prototype.hasOwnProperty.call( this.aggregateItemEvents, itemEvent ) ) {
4779 // Don't allow duplicate aggregations
4780 if ( groupEvent ) {
4781 throw new Error( 'Duplicate item event aggregation for ' + itemEvent );
4782 }
4783 // Remove event aggregation from existing items
4784 for ( i = 0, len = this.items.length; i < len; i++ ) {
4785 item = this.items[ i ];
4786 if ( item.connect && item.disconnect ) {
4787 remove = {};
4788 remove[ itemEvent ] = [ 'emit', this.aggregateItemEvents[ itemEvent ], item ];
4789 item.disconnect( this, remove );
4790 }
4791 }
4792 // Prevent future items from aggregating event
4793 delete this.aggregateItemEvents[ itemEvent ];
4794 }
4795
4796 // Add new aggregate event
4797 if ( groupEvent ) {
4798 // Make future items aggregate event
4799 this.aggregateItemEvents[ itemEvent ] = groupEvent;
4800 // Add event aggregation to existing items
4801 for ( i = 0, len = this.items.length; i < len; i++ ) {
4802 item = this.items[ i ];
4803 if ( item.connect && item.disconnect ) {
4804 add = {};
4805 add[ itemEvent ] = [ 'emit', groupEvent, item ];
4806 item.connect( this, add );
4807 }
4808 }
4809 }
4810 }
4811 };
4812
4813 /**
4814 * Add items to the group.
4815 *
4816 * Items will be added to the end of the group array unless the optional `index` parameter specifies
4817 * a different insertion point. Adding an existing item will move it to the end of the array or the point specified by the `index`.
4818 *
4819 * @param {OO.ui.Element[]} items An array of items to add to the group
4820 * @param {number} [index] Index of the insertion point
4821 * @chainable
4822 */
4823 OO.ui.mixin.GroupElement.prototype.addItems = function ( items, index ) {
4824 var i, len, item, event, events, currentIndex,
4825 itemElements = [];
4826
4827 for ( i = 0, len = items.length; i < len; i++ ) {
4828 item = items[ i ];
4829
4830 // Check if item exists then remove it first, effectively "moving" it
4831 currentIndex = this.items.indexOf( item );
4832 if ( currentIndex >= 0 ) {
4833 this.removeItems( [ item ] );
4834 // Adjust index to compensate for removal
4835 if ( currentIndex < index ) {
4836 index--;
4837 }
4838 }
4839 // Add the item
4840 if ( item.connect && item.disconnect && !$.isEmptyObject( this.aggregateItemEvents ) ) {
4841 events = {};
4842 for ( event in this.aggregateItemEvents ) {
4843 events[ event ] = [ 'emit', this.aggregateItemEvents[ event ], item ];
4844 }
4845 item.connect( this, events );
4846 }
4847 item.setElementGroup( this );
4848 itemElements.push( item.$element.get( 0 ) );
4849 }
4850
4851 if ( index === undefined || index < 0 || index >= this.items.length ) {
4852 this.$group.append( itemElements );
4853 this.items.push.apply( this.items, items );
4854 } else if ( index === 0 ) {
4855 this.$group.prepend( itemElements );
4856 this.items.unshift.apply( this.items, items );
4857 } else {
4858 this.items[ index ].$element.before( itemElements );
4859 this.items.splice.apply( this.items, [ index, 0 ].concat( items ) );
4860 }
4861
4862 return this;
4863 };
4864
4865 /**
4866 * Remove the specified items from a group.
4867 *
4868 * Removed items are detached (not removed) from the DOM so that they may be reused.
4869 * To remove all items from a group, you may wish to use the #clearItems method instead.
4870 *
4871 * @param {OO.ui.Element[]} items An array of items to remove
4872 * @chainable
4873 */
4874 OO.ui.mixin.GroupElement.prototype.removeItems = function ( items ) {
4875 var i, len, item, index, remove, itemEvent;
4876
4877 // Remove specific items
4878 for ( i = 0, len = items.length; i < len; i++ ) {
4879 item = items[ i ];
4880 index = this.items.indexOf( item );
4881 if ( index !== -1 ) {
4882 if (
4883 item.connect && item.disconnect &&
4884 !$.isEmptyObject( this.aggregateItemEvents )
4885 ) {
4886 remove = {};
4887 if ( Object.prototype.hasOwnProperty.call( this.aggregateItemEvents, itemEvent ) ) {
4888 remove[ itemEvent ] = [ 'emit', this.aggregateItemEvents[ itemEvent ], item ];
4889 }
4890 item.disconnect( this, remove );
4891 }
4892 item.setElementGroup( null );
4893 this.items.splice( index, 1 );
4894 item.$element.detach();
4895 }
4896 }
4897
4898 return this;
4899 };
4900
4901 /**
4902 * Clear all items from the group.
4903 *
4904 * Cleared items are detached from the DOM, not removed, so that they may be reused.
4905 * To remove only a subset of items from a group, use the #removeItems method.
4906 *
4907 * @chainable
4908 */
4909 OO.ui.mixin.GroupElement.prototype.clearItems = function () {
4910 var i, len, item, remove, itemEvent;
4911
4912 // Remove all items
4913 for ( i = 0, len = this.items.length; i < len; i++ ) {
4914 item = this.items[ i ];
4915 if (
4916 item.connect && item.disconnect &&
4917 !$.isEmptyObject( this.aggregateItemEvents )
4918 ) {
4919 remove = {};
4920 if ( Object.prototype.hasOwnProperty.call( this.aggregateItemEvents, itemEvent ) ) {
4921 remove[ itemEvent ] = [ 'emit', this.aggregateItemEvents[ itemEvent ], item ];
4922 }
4923 item.disconnect( this, remove );
4924 }
4925 item.setElementGroup( null );
4926 item.$element.detach();
4927 }
4928
4929 this.items = [];
4930 return this;
4931 };
4932
4933 /**
4934 * DraggableElement is a mixin class used to create elements that can be clicked
4935 * and dragged by a mouse to a new position within a group. This class must be used
4936 * in conjunction with OO.ui.mixin.DraggableGroupElement, which provides a container for
4937 * the draggable elements.
4938 *
4939 * @abstract
4940 * @class
4941 *
4942 * @constructor
4943 */
4944 OO.ui.mixin.DraggableElement = function OoUiMixinDraggableElement() {
4945 // Properties
4946 this.index = null;
4947
4948 // Initialize and events
4949 this.$element
4950 .attr( 'draggable', true )
4951 .addClass( 'oo-ui-draggableElement' )
4952 .on( {
4953 dragstart: this.onDragStart.bind( this ),
4954 dragover: this.onDragOver.bind( this ),
4955 dragend: this.onDragEnd.bind( this ),
4956 drop: this.onDrop.bind( this )
4957 } );
4958 };
4959
4960 OO.initClass( OO.ui.mixin.DraggableElement );
4961
4962 /* Events */
4963
4964 /**
4965 * @event dragstart
4966 *
4967 * A dragstart event is emitted when the user clicks and begins dragging an item.
4968 * @param {OO.ui.mixin.DraggableElement} item The item the user has clicked and is dragging with the mouse.
4969 */
4970
4971 /**
4972 * @event dragend
4973 * A dragend event is emitted when the user drags an item and releases the mouse,
4974 * thus terminating the drag operation.
4975 */
4976
4977 /**
4978 * @event drop
4979 * A drop event is emitted when the user drags an item and then releases the mouse button
4980 * over a valid target.
4981 */
4982
4983 /* Static Properties */
4984
4985 /**
4986 * @inheritdoc OO.ui.mixin.ButtonElement
4987 */
4988 OO.ui.mixin.DraggableElement.static.cancelButtonMouseDownEvents = false;
4989
4990 /* Methods */
4991
4992 /**
4993 * Respond to dragstart event.
4994 *
4995 * @private
4996 * @param {jQuery.Event} event jQuery event
4997 * @fires dragstart
4998 */
4999 OO.ui.mixin.DraggableElement.prototype.onDragStart = function ( e ) {
5000 var dataTransfer = e.originalEvent.dataTransfer;
5001 // Define drop effect
5002 dataTransfer.dropEffect = 'none';
5003 dataTransfer.effectAllowed = 'move';
5004 // Support: Firefox
5005 // We must set up a dataTransfer data property or Firefox seems to
5006 // ignore the fact the element is draggable.
5007 try {
5008 dataTransfer.setData( 'application-x/OOjs-UI-draggable', this.getIndex() );
5009 } catch ( err ) {
5010 // The above is only for Firefox. Move on if it fails.
5011 }
5012 // Add dragging class
5013 this.$element.addClass( 'oo-ui-draggableElement-dragging' );
5014 // Emit event
5015 this.emit( 'dragstart', this );
5016 return true;
5017 };
5018
5019 /**
5020 * Respond to dragend event.
5021 *
5022 * @private
5023 * @fires dragend
5024 */
5025 OO.ui.mixin.DraggableElement.prototype.onDragEnd = function () {
5026 this.$element.removeClass( 'oo-ui-draggableElement-dragging' );
5027 this.emit( 'dragend' );
5028 };
5029
5030 /**
5031 * Handle drop event.
5032 *
5033 * @private
5034 * @param {jQuery.Event} event jQuery event
5035 * @fires drop
5036 */
5037 OO.ui.mixin.DraggableElement.prototype.onDrop = function ( e ) {
5038 e.preventDefault();
5039 this.emit( 'drop', e );
5040 };
5041
5042 /**
5043 * In order for drag/drop to work, the dragover event must
5044 * return false and stop propogation.
5045 *
5046 * @private
5047 */
5048 OO.ui.mixin.DraggableElement.prototype.onDragOver = function ( e ) {
5049 e.preventDefault();
5050 };
5051
5052 /**
5053 * Set item index.
5054 * Store it in the DOM so we can access from the widget drag event
5055 *
5056 * @private
5057 * @param {number} Item index
5058 */
5059 OO.ui.mixin.DraggableElement.prototype.setIndex = function ( index ) {
5060 if ( this.index !== index ) {
5061 this.index = index;
5062 this.$element.data( 'index', index );
5063 }
5064 };
5065
5066 /**
5067 * Get item index
5068 *
5069 * @private
5070 * @return {number} Item index
5071 */
5072 OO.ui.mixin.DraggableElement.prototype.getIndex = function () {
5073 return this.index;
5074 };
5075
5076 /**
5077 * DraggableGroupElement is a mixin class used to create a group element to
5078 * contain draggable elements, which are items that can be clicked and dragged by a mouse.
5079 * The class is used with OO.ui.mixin.DraggableElement.
5080 *
5081 * @abstract
5082 * @class
5083 * @mixins OO.ui.mixin.GroupElement
5084 *
5085 * @constructor
5086 * @param {Object} [config] Configuration options
5087 * @cfg {string} [orientation] Item orientation: 'horizontal' or 'vertical'. The orientation
5088 * should match the layout of the items. Items displayed in a single row
5089 * or in several rows should use horizontal orientation. The vertical orientation should only be
5090 * used when the items are displayed in a single column. Defaults to 'vertical'
5091 */
5092 OO.ui.mixin.DraggableGroupElement = function OoUiMixinDraggableGroupElement( config ) {
5093 // Configuration initialization
5094 config = config || {};
5095
5096 // Parent constructor
5097 OO.ui.mixin.GroupElement.call( this, config );
5098
5099 // Properties
5100 this.orientation = config.orientation || 'vertical';
5101 this.dragItem = null;
5102 this.itemDragOver = null;
5103 this.itemKeys = {};
5104 this.sideInsertion = '';
5105
5106 // Events
5107 this.aggregate( {
5108 dragstart: 'itemDragStart',
5109 dragend: 'itemDragEnd',
5110 drop: 'itemDrop'
5111 } );
5112 this.connect( this, {
5113 itemDragStart: 'onItemDragStart',
5114 itemDrop: 'onItemDrop',
5115 itemDragEnd: 'onItemDragEnd'
5116 } );
5117 this.$element.on( {
5118 dragover: this.onDragOver.bind( this ),
5119 dragleave: this.onDragLeave.bind( this )
5120 } );
5121
5122 // Initialize
5123 if ( Array.isArray( config.items ) ) {
5124 this.addItems( config.items );
5125 }
5126 this.$placeholder = $( '<div>' )
5127 .addClass( 'oo-ui-draggableGroupElement-placeholder' );
5128 this.$element
5129 .addClass( 'oo-ui-draggableGroupElement' )
5130 .append( this.$status )
5131 .toggleClass( 'oo-ui-draggableGroupElement-horizontal', this.orientation === 'horizontal' )
5132 .prepend( this.$placeholder );
5133 };
5134
5135 /* Setup */
5136 OO.mixinClass( OO.ui.mixin.DraggableGroupElement, OO.ui.mixin.GroupElement );
5137
5138 /* Events */
5139
5140 /**
5141 * A 'reorder' event is emitted when the order of items in the group changes.
5142 *
5143 * @event reorder
5144 * @param {OO.ui.mixin.DraggableElement} item Reordered item
5145 * @param {number} [newIndex] New index for the item
5146 */
5147
5148 /* Methods */
5149
5150 /**
5151 * Respond to item drag start event
5152 *
5153 * @private
5154 * @param {OO.ui.mixin.DraggableElement} item Dragged item
5155 */
5156 OO.ui.mixin.DraggableGroupElement.prototype.onItemDragStart = function ( item ) {
5157 var i, len;
5158
5159 // Map the index of each object
5160 for ( i = 0, len = this.items.length; i < len; i++ ) {
5161 this.items[ i ].setIndex( i );
5162 }
5163
5164 if ( this.orientation === 'horizontal' ) {
5165 // Set the height of the indicator
5166 this.$placeholder.css( {
5167 height: item.$element.outerHeight(),
5168 width: 2
5169 } );
5170 } else {
5171 // Set the width of the indicator
5172 this.$placeholder.css( {
5173 height: 2,
5174 width: item.$element.outerWidth()
5175 } );
5176 }
5177 this.setDragItem( item );
5178 };
5179
5180 /**
5181 * Respond to item drag end event
5182 *
5183 * @private
5184 */
5185 OO.ui.mixin.DraggableGroupElement.prototype.onItemDragEnd = function () {
5186 this.unsetDragItem();
5187 return false;
5188 };
5189
5190 /**
5191 * Handle drop event and switch the order of the items accordingly
5192 *
5193 * @private
5194 * @param {OO.ui.mixin.DraggableElement} item Dropped item
5195 * @fires reorder
5196 */
5197 OO.ui.mixin.DraggableGroupElement.prototype.onItemDrop = function ( item ) {
5198 var toIndex = item.getIndex();
5199 // Check if the dropped item is from the current group
5200 // TODO: Figure out a way to configure a list of legally droppable
5201 // elements even if they are not yet in the list
5202 if ( this.getDragItem() ) {
5203 // If the insertion point is 'after', the insertion index
5204 // is shifted to the right (or to the left in RTL, hence 'after')
5205 if ( this.sideInsertion === 'after' ) {
5206 toIndex++;
5207 }
5208 // Emit change event
5209 this.emit( 'reorder', this.getDragItem(), toIndex );
5210 }
5211 this.unsetDragItem();
5212 // Return false to prevent propogation
5213 return false;
5214 };
5215
5216 /**
5217 * Handle dragleave event.
5218 *
5219 * @private
5220 */
5221 OO.ui.mixin.DraggableGroupElement.prototype.onDragLeave = function () {
5222 // This means the item was dragged outside the widget
5223 this.$placeholder
5224 .css( 'left', 0 )
5225 .addClass( 'oo-ui-element-hidden' );
5226 };
5227
5228 /**
5229 * Respond to dragover event
5230 *
5231 * @private
5232 * @param {jQuery.Event} event Event details
5233 */
5234 OO.ui.mixin.DraggableGroupElement.prototype.onDragOver = function ( e ) {
5235 var dragOverObj, $optionWidget, itemOffset, itemMidpoint, itemBoundingRect,
5236 itemSize, cssOutput, dragPosition, itemIndex, itemPosition,
5237 clientX = e.originalEvent.clientX,
5238 clientY = e.originalEvent.clientY;
5239
5240 // Get the OptionWidget item we are dragging over
5241 dragOverObj = this.getElementDocument().elementFromPoint( clientX, clientY );
5242 $optionWidget = $( dragOverObj ).closest( '.oo-ui-draggableElement' );
5243 if ( $optionWidget[ 0 ] ) {
5244 itemOffset = $optionWidget.offset();
5245 itemBoundingRect = $optionWidget[ 0 ].getBoundingClientRect();
5246 itemPosition = $optionWidget.position();
5247 itemIndex = $optionWidget.data( 'index' );
5248 }
5249
5250 if (
5251 itemOffset &&
5252 this.isDragging() &&
5253 itemIndex !== this.getDragItem().getIndex()
5254 ) {
5255 if ( this.orientation === 'horizontal' ) {
5256 // Calculate where the mouse is relative to the item width
5257 itemSize = itemBoundingRect.width;
5258 itemMidpoint = itemBoundingRect.left + itemSize / 2;
5259 dragPosition = clientX;
5260 // Which side of the item we hover over will dictate
5261 // where the placeholder will appear, on the left or
5262 // on the right
5263 cssOutput = {
5264 left: dragPosition < itemMidpoint ? itemPosition.left : itemPosition.left + itemSize,
5265 top: itemPosition.top
5266 };
5267 } else {
5268 // Calculate where the mouse is relative to the item height
5269 itemSize = itemBoundingRect.height;
5270 itemMidpoint = itemBoundingRect.top + itemSize / 2;
5271 dragPosition = clientY;
5272 // Which side of the item we hover over will dictate
5273 // where the placeholder will appear, on the top or
5274 // on the bottom
5275 cssOutput = {
5276 top: dragPosition < itemMidpoint ? itemPosition.top : itemPosition.top + itemSize,
5277 left: itemPosition.left
5278 };
5279 }
5280 // Store whether we are before or after an item to rearrange
5281 // For horizontal layout, we need to account for RTL, as this is flipped
5282 if ( this.orientation === 'horizontal' && this.$element.css( 'direction' ) === 'rtl' ) {
5283 this.sideInsertion = dragPosition < itemMidpoint ? 'after' : 'before';
5284 } else {
5285 this.sideInsertion = dragPosition < itemMidpoint ? 'before' : 'after';
5286 }
5287 // Add drop indicator between objects
5288 this.$placeholder
5289 .css( cssOutput )
5290 .removeClass( 'oo-ui-element-hidden' );
5291 } else {
5292 // This means the item was dragged outside the widget
5293 this.$placeholder
5294 .css( 'left', 0 )
5295 .addClass( 'oo-ui-element-hidden' );
5296 }
5297 // Prevent default
5298 e.preventDefault();
5299 };
5300
5301 /**
5302 * Set a dragged item
5303 *
5304 * @param {OO.ui.mixin.DraggableElement} item Dragged item
5305 */
5306 OO.ui.mixin.DraggableGroupElement.prototype.setDragItem = function ( item ) {
5307 this.dragItem = item;
5308 };
5309
5310 /**
5311 * Unset the current dragged item
5312 */
5313 OO.ui.mixin.DraggableGroupElement.prototype.unsetDragItem = function () {
5314 this.dragItem = null;
5315 this.itemDragOver = null;
5316 this.$placeholder.addClass( 'oo-ui-element-hidden' );
5317 this.sideInsertion = '';
5318 };
5319
5320 /**
5321 * Get the item that is currently being dragged.
5322 *
5323 * @return {OO.ui.mixin.DraggableElement|null} The currently dragged item, or `null` if no item is being dragged
5324 */
5325 OO.ui.mixin.DraggableGroupElement.prototype.getDragItem = function () {
5326 return this.dragItem;
5327 };
5328
5329 /**
5330 * Check if an item in the group is currently being dragged.
5331 *
5332 * @return {Boolean} Item is being dragged
5333 */
5334 OO.ui.mixin.DraggableGroupElement.prototype.isDragging = function () {
5335 return this.getDragItem() !== null;
5336 };
5337
5338 /**
5339 * IconElement is often mixed into other classes to generate an icon.
5340 * Icons are graphics, about the size of normal text. They are used to aid the user
5341 * in locating a control or to convey information in a space-efficient way. See the
5342 * [OOjs UI documentation on MediaWiki] [1] for a list of icons
5343 * included in the library.
5344 *
5345 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
5346 *
5347 * @abstract
5348 * @class
5349 *
5350 * @constructor
5351 * @param {Object} [config] Configuration options
5352 * @cfg {jQuery} [$icon] The icon element created by the class. If this configuration is omitted,
5353 * the icon element will use a generated `<span>`. To use a different HTML tag, or to specify that
5354 * the icon element be set to an existing icon instead of the one generated by this class, set a
5355 * value using a jQuery selection. For example:
5356 *
5357 * // Use a <div> tag instead of a <span>
5358 * $icon: $("<div>")
5359 * // Use an existing icon element instead of the one generated by the class
5360 * $icon: this.$element
5361 * // Use an icon element from a child widget
5362 * $icon: this.childwidget.$element
5363 * @cfg {Object|string} [icon=''] The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of
5364 * symbolic names. A map is used for i18n purposes and contains a `default` icon
5365 * name and additional names keyed by language code. The `default` name is used when no icon is keyed
5366 * by the user's language.
5367 *
5368 * Example of an i18n map:
5369 *
5370 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
5371 * See the [OOjs UI documentation on MediaWiki] [2] for a list of icons included in the library.
5372 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
5373 * @cfg {string|Function} [iconTitle] A text string used as the icon title, or a function that returns title
5374 * text. The icon title is displayed when users move the mouse over the icon.
5375 */
5376 OO.ui.mixin.IconElement = function OoUiMixinIconElement( config ) {
5377 // Configuration initialization
5378 config = config || {};
5379
5380 // Properties
5381 this.$icon = null;
5382 this.icon = null;
5383 this.iconTitle = null;
5384
5385 // Initialization
5386 this.setIcon( config.icon || this.constructor.static.icon );
5387 this.setIconTitle( config.iconTitle || this.constructor.static.iconTitle );
5388 this.setIconElement( config.$icon || $( '<span>' ) );
5389 };
5390
5391 /* Setup */
5392
5393 OO.initClass( OO.ui.mixin.IconElement );
5394
5395 /* Static Properties */
5396
5397 /**
5398 * The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of symbolic names. A map is used
5399 * for i18n purposes and contains a `default` icon name and additional names keyed by
5400 * language code. The `default` name is used when no icon is keyed by the user's language.
5401 *
5402 * Example of an i18n map:
5403 *
5404 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
5405 *
5406 * Note: the static property will be overridden if the #icon configuration is used.
5407 *
5408 * @static
5409 * @inheritable
5410 * @property {Object|string}
5411 */
5412 OO.ui.mixin.IconElement.static.icon = null;
5413
5414 /**
5415 * The icon title, displayed when users move the mouse over the icon. The value can be text, a
5416 * function that returns title text, or `null` for no title.
5417 *
5418 * The static property will be overridden if the #iconTitle configuration is used.
5419 *
5420 * @static
5421 * @inheritable
5422 * @property {string|Function|null}
5423 */
5424 OO.ui.mixin.IconElement.static.iconTitle = null;
5425
5426 /* Methods */
5427
5428 /**
5429 * Set the icon element. This method is used to retarget an icon mixin so that its functionality
5430 * applies to the specified icon element instead of the one created by the class. If an icon
5431 * element is already set, the mixin’s effect on that element is removed. Generated CSS classes
5432 * and mixin methods will no longer affect the element.
5433 *
5434 * @param {jQuery} $icon Element to use as icon
5435 */
5436 OO.ui.mixin.IconElement.prototype.setIconElement = function ( $icon ) {
5437 if ( this.$icon ) {
5438 this.$icon
5439 .removeClass( 'oo-ui-iconElement-icon oo-ui-icon-' + this.icon )
5440 .removeAttr( 'title' );
5441 }
5442
5443 this.$icon = $icon
5444 .addClass( 'oo-ui-iconElement-icon' )
5445 .toggleClass( 'oo-ui-icon-' + this.icon, !!this.icon );
5446 if ( this.iconTitle !== null ) {
5447 this.$icon.attr( 'title', this.iconTitle );
5448 }
5449
5450 this.updateThemeClasses();
5451 };
5452
5453 /**
5454 * Set icon by symbolic name (e.g., ‘remove’ or ‘menu’). Use `null` to remove an icon.
5455 * The icon parameter can also be set to a map of icon names. See the #icon config setting
5456 * for an example.
5457 *
5458 * @param {Object|string|null} icon A symbolic icon name, a {@link #icon map of icon names} keyed
5459 * by language code, or `null` to remove the icon.
5460 * @chainable
5461 */
5462 OO.ui.mixin.IconElement.prototype.setIcon = function ( icon ) {
5463 icon = OO.isPlainObject( icon ) ? OO.ui.getLocalValue( icon, null, 'default' ) : icon;
5464 icon = typeof icon === 'string' && icon.trim().length ? icon.trim() : null;
5465
5466 if ( this.icon !== icon ) {
5467 if ( this.$icon ) {
5468 if ( this.icon !== null ) {
5469 this.$icon.removeClass( 'oo-ui-icon-' + this.icon );
5470 }
5471 if ( icon !== null ) {
5472 this.$icon.addClass( 'oo-ui-icon-' + icon );
5473 }
5474 }
5475 this.icon = icon;
5476 }
5477
5478 this.$element.toggleClass( 'oo-ui-iconElement', !!this.icon );
5479 this.updateThemeClasses();
5480
5481 return this;
5482 };
5483
5484 /**
5485 * Set the icon title. Use `null` to remove the title.
5486 *
5487 * @param {string|Function|null} iconTitle A text string used as the icon title,
5488 * a function that returns title text, or `null` for no title.
5489 * @chainable
5490 */
5491 OO.ui.mixin.IconElement.prototype.setIconTitle = function ( iconTitle ) {
5492 iconTitle = typeof iconTitle === 'function' ||
5493 ( typeof iconTitle === 'string' && iconTitle.length ) ?
5494 OO.ui.resolveMsg( iconTitle ) : null;
5495
5496 if ( this.iconTitle !== iconTitle ) {
5497 this.iconTitle = iconTitle;
5498 if ( this.$icon ) {
5499 if ( this.iconTitle !== null ) {
5500 this.$icon.attr( 'title', iconTitle );
5501 } else {
5502 this.$icon.removeAttr( 'title' );
5503 }
5504 }
5505 }
5506
5507 return this;
5508 };
5509
5510 /**
5511 * Get the symbolic name of the icon.
5512 *
5513 * @return {string} Icon name
5514 */
5515 OO.ui.mixin.IconElement.prototype.getIcon = function () {
5516 return this.icon;
5517 };
5518
5519 /**
5520 * Get the icon title. The title text is displayed when a user moves the mouse over the icon.
5521 *
5522 * @return {string} Icon title text
5523 */
5524 OO.ui.mixin.IconElement.prototype.getIconTitle = function () {
5525 return this.iconTitle;
5526 };
5527
5528 /**
5529 * IndicatorElement is often mixed into other classes to generate an indicator.
5530 * Indicators are small graphics that are generally used in two ways:
5531 *
5532 * - To draw attention to the status of an item. For example, an indicator might be
5533 * used to show that an item in a list has errors that need to be resolved.
5534 * - To clarify the function of a control that acts in an exceptional way (a button
5535 * that opens a menu instead of performing an action directly, for example).
5536 *
5537 * For a list of indicators included in the library, please see the
5538 * [OOjs UI documentation on MediaWiki] [1].
5539 *
5540 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
5541 *
5542 * @abstract
5543 * @class
5544 *
5545 * @constructor
5546 * @param {Object} [config] Configuration options
5547 * @cfg {jQuery} [$indicator] The indicator element created by the class. If this
5548 * configuration is omitted, the indicator element will use a generated `<span>`.
5549 * @cfg {string} [indicator] Symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
5550 * See the [OOjs UI documentation on MediaWiki][2] for a list of indicators included
5551 * in the library.
5552 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
5553 * @cfg {string|Function} [indicatorTitle] A text string used as the indicator title,
5554 * or a function that returns title text. The indicator title is displayed when users move
5555 * the mouse over the indicator.
5556 */
5557 OO.ui.mixin.IndicatorElement = function OoUiMixinIndicatorElement( config ) {
5558 // Configuration initialization
5559 config = config || {};
5560
5561 // Properties
5562 this.$indicator = null;
5563 this.indicator = null;
5564 this.indicatorTitle = null;
5565
5566 // Initialization
5567 this.setIndicator( config.indicator || this.constructor.static.indicator );
5568 this.setIndicatorTitle( config.indicatorTitle || this.constructor.static.indicatorTitle );
5569 this.setIndicatorElement( config.$indicator || $( '<span>' ) );
5570 };
5571
5572 /* Setup */
5573
5574 OO.initClass( OO.ui.mixin.IndicatorElement );
5575
5576 /* Static Properties */
5577
5578 /**
5579 * Symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
5580 * The static property will be overridden if the #indicator configuration is used.
5581 *
5582 * @static
5583 * @inheritable
5584 * @property {string|null}
5585 */
5586 OO.ui.mixin.IndicatorElement.static.indicator = null;
5587
5588 /**
5589 * A text string used as the indicator title, a function that returns title text, or `null`
5590 * for no title. The static property will be overridden if the #indicatorTitle configuration is used.
5591 *
5592 * @static
5593 * @inheritable
5594 * @property {string|Function|null}
5595 */
5596 OO.ui.mixin.IndicatorElement.static.indicatorTitle = null;
5597
5598 /* Methods */
5599
5600 /**
5601 * Set the indicator element.
5602 *
5603 * If an element is already set, it will be cleaned up before setting up the new element.
5604 *
5605 * @param {jQuery} $indicator Element to use as indicator
5606 */
5607 OO.ui.mixin.IndicatorElement.prototype.setIndicatorElement = function ( $indicator ) {
5608 if ( this.$indicator ) {
5609 this.$indicator
5610 .removeClass( 'oo-ui-indicatorElement-indicator oo-ui-indicator-' + this.indicator )
5611 .removeAttr( 'title' );
5612 }
5613
5614 this.$indicator = $indicator
5615 .addClass( 'oo-ui-indicatorElement-indicator' )
5616 .toggleClass( 'oo-ui-indicator-' + this.indicator, !!this.indicator );
5617 if ( this.indicatorTitle !== null ) {
5618 this.$indicator.attr( 'title', this.indicatorTitle );
5619 }
5620
5621 this.updateThemeClasses();
5622 };
5623
5624 /**
5625 * Set the indicator by its symbolic name: ‘alert’, ‘down’, ‘next’, ‘previous’, ‘required’, ‘up’. Use `null` to remove the indicator.
5626 *
5627 * @param {string|null} indicator Symbolic name of indicator, or `null` for no indicator
5628 * @chainable
5629 */
5630 OO.ui.mixin.IndicatorElement.prototype.setIndicator = function ( indicator ) {
5631 indicator = typeof indicator === 'string' && indicator.length ? indicator.trim() : null;
5632
5633 if ( this.indicator !== indicator ) {
5634 if ( this.$indicator ) {
5635 if ( this.indicator !== null ) {
5636 this.$indicator.removeClass( 'oo-ui-indicator-' + this.indicator );
5637 }
5638 if ( indicator !== null ) {
5639 this.$indicator.addClass( 'oo-ui-indicator-' + indicator );
5640 }
5641 }
5642 this.indicator = indicator;
5643 }
5644
5645 this.$element.toggleClass( 'oo-ui-indicatorElement', !!this.indicator );
5646 this.updateThemeClasses();
5647
5648 return this;
5649 };
5650
5651 /**
5652 * Set the indicator title.
5653 *
5654 * The title is displayed when a user moves the mouse over the indicator.
5655 *
5656 * @param {string|Function|null} indicator Indicator title text, a function that returns text, or
5657 * `null` for no indicator title
5658 * @chainable
5659 */
5660 OO.ui.mixin.IndicatorElement.prototype.setIndicatorTitle = function ( indicatorTitle ) {
5661 indicatorTitle = typeof indicatorTitle === 'function' ||
5662 ( typeof indicatorTitle === 'string' && indicatorTitle.length ) ?
5663 OO.ui.resolveMsg( indicatorTitle ) : null;
5664
5665 if ( this.indicatorTitle !== indicatorTitle ) {
5666 this.indicatorTitle = indicatorTitle;
5667 if ( this.$indicator ) {
5668 if ( this.indicatorTitle !== null ) {
5669 this.$indicator.attr( 'title', indicatorTitle );
5670 } else {
5671 this.$indicator.removeAttr( 'title' );
5672 }
5673 }
5674 }
5675
5676 return this;
5677 };
5678
5679 /**
5680 * Get the symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
5681 *
5682 * @return {string} Symbolic name of indicator
5683 */
5684 OO.ui.mixin.IndicatorElement.prototype.getIndicator = function () {
5685 return this.indicator;
5686 };
5687
5688 /**
5689 * Get the indicator title.
5690 *
5691 * The title is displayed when a user moves the mouse over the indicator.
5692 *
5693 * @return {string} Indicator title text
5694 */
5695 OO.ui.mixin.IndicatorElement.prototype.getIndicatorTitle = function () {
5696 return this.indicatorTitle;
5697 };
5698
5699 /**
5700 * LabelElement is often mixed into other classes to generate a label, which
5701 * helps identify the function of an interface element.
5702 * See the [OOjs UI documentation on MediaWiki] [1] for more information.
5703 *
5704 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Labels
5705 *
5706 * @abstract
5707 * @class
5708 *
5709 * @constructor
5710 * @param {Object} [config] Configuration options
5711 * @cfg {jQuery} [$label] The label element created by the class. If this
5712 * configuration is omitted, the label element will use a generated `<span>`.
5713 * @cfg {jQuery|string|Function|OO.ui.HtmlSnippet} [label] The label text. The label can be specified
5714 * as a plaintext string, a jQuery selection of elements, or a function that will produce a string
5715 * in the future. See the [OOjs UI documentation on MediaWiki] [2] for examples.
5716 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Labels
5717 * @cfg {boolean} [autoFitLabel=true] Fit the label to the width of the parent element.
5718 * The label will be truncated to fit if necessary.
5719 */
5720 OO.ui.mixin.LabelElement = function OoUiMixinLabelElement( config ) {
5721 // Configuration initialization
5722 config = config || {};
5723
5724 // Properties
5725 this.$label = null;
5726 this.label = null;
5727 this.autoFitLabel = config.autoFitLabel === undefined || !!config.autoFitLabel;
5728
5729 // Initialization
5730 this.setLabel( config.label || this.constructor.static.label );
5731 this.setLabelElement( config.$label || $( '<span>' ) );
5732 };
5733
5734 /* Setup */
5735
5736 OO.initClass( OO.ui.mixin.LabelElement );
5737
5738 /* Events */
5739
5740 /**
5741 * @event labelChange
5742 * @param {string} value
5743 */
5744
5745 /* Static Properties */
5746
5747 /**
5748 * The label text. The label can be specified as a plaintext string, a function that will
5749 * produce a string in the future, or `null` for no label. The static value will
5750 * be overridden if a label is specified with the #label config option.
5751 *
5752 * @static
5753 * @inheritable
5754 * @property {string|Function|null}
5755 */
5756 OO.ui.mixin.LabelElement.static.label = null;
5757
5758 /* Methods */
5759
5760 /**
5761 * Set the label element.
5762 *
5763 * If an element is already set, it will be cleaned up before setting up the new element.
5764 *
5765 * @param {jQuery} $label Element to use as label
5766 */
5767 OO.ui.mixin.LabelElement.prototype.setLabelElement = function ( $label ) {
5768 if ( this.$label ) {
5769 this.$label.removeClass( 'oo-ui-labelElement-label' ).empty();
5770 }
5771
5772 this.$label = $label.addClass( 'oo-ui-labelElement-label' );
5773 this.setLabelContent( this.label );
5774 };
5775
5776 /**
5777 * Set the label.
5778 *
5779 * An empty string will result in the label being hidden. A string containing only whitespace will
5780 * be converted to a single `&nbsp;`.
5781 *
5782 * @param {jQuery|string|OO.ui.HtmlSnippet|Function|null} label Label nodes; text; a function that returns nodes or
5783 * text; or null for no label
5784 * @chainable
5785 */
5786 OO.ui.mixin.LabelElement.prototype.setLabel = function ( label ) {
5787 label = typeof label === 'function' ? OO.ui.resolveMsg( label ) : label;
5788 label = ( ( typeof label === 'string' && label.length ) || label instanceof jQuery || label instanceof OO.ui.HtmlSnippet ) ? label : null;
5789
5790 this.$element.toggleClass( 'oo-ui-labelElement', !!label );
5791
5792 if ( this.label !== label ) {
5793 if ( this.$label ) {
5794 this.setLabelContent( label );
5795 }
5796 this.label = label;
5797 this.emit( 'labelChange' );
5798 }
5799
5800 return this;
5801 };
5802
5803 /**
5804 * Get the label.
5805 *
5806 * @return {jQuery|string|Function|null} Label nodes; text; a function that returns nodes or
5807 * text; or null for no label
5808 */
5809 OO.ui.mixin.LabelElement.prototype.getLabel = function () {
5810 return this.label;
5811 };
5812
5813 /**
5814 * Fit the label.
5815 *
5816 * @chainable
5817 */
5818 OO.ui.mixin.LabelElement.prototype.fitLabel = function () {
5819 if ( this.$label && this.$label.autoEllipsis && this.autoFitLabel ) {
5820 this.$label.autoEllipsis( { hasSpan: false, tooltip: true } );
5821 }
5822
5823 return this;
5824 };
5825
5826 /**
5827 * Set the content of the label.
5828 *
5829 * Do not call this method until after the label element has been set by #setLabelElement.
5830 *
5831 * @private
5832 * @param {jQuery|string|Function|null} label Label nodes; text; a function that returns nodes or
5833 * text; or null for no label
5834 */
5835 OO.ui.mixin.LabelElement.prototype.setLabelContent = function ( label ) {
5836 if ( typeof label === 'string' ) {
5837 if ( label.match( /^\s*$/ ) ) {
5838 // Convert whitespace only string to a single non-breaking space
5839 this.$label.html( '&nbsp;' );
5840 } else {
5841 this.$label.text( label );
5842 }
5843 } else if ( label instanceof OO.ui.HtmlSnippet ) {
5844 this.$label.html( label.toString() );
5845 } else if ( label instanceof jQuery ) {
5846 this.$label.empty().append( label );
5847 } else {
5848 this.$label.empty();
5849 }
5850 };
5851
5852 /**
5853 * LookupElement is a mixin that creates a {@link OO.ui.FloatingMenuSelectWidget menu} of suggested values for
5854 * a {@link OO.ui.TextInputWidget text input widget}. Suggested values are based on the characters the user types
5855 * into the text input field and, in general, the menu is only displayed when the user types. If a suggested value is chosen
5856 * from the lookup menu, that value becomes the value of the input field.
5857 *
5858 * Note that a new menu of suggested items is displayed when a value is chosen from the lookup menu. If this is
5859 * not the desired behavior, disable lookup menus with the #setLookupsDisabled method, then set the value, then
5860 * re-enable lookups.
5861 *
5862 * See the [OOjs UI demos][1] for an example.
5863 *
5864 * [1]: https://tools.wmflabs.org/oojs-ui/oojs-ui/demos/index.html#widgets-apex-vector-ltr
5865 *
5866 * @class
5867 * @abstract
5868 *
5869 * @constructor
5870 * @param {Object} [config] Configuration options
5871 * @cfg {jQuery} [$overlay] Overlay for the lookup menu; defaults to relative positioning
5872 * @cfg {jQuery} [$container=this.$element] The container element. The lookup menu is rendered beneath the specified element.
5873 * @cfg {boolean} [allowSuggestionsWhenEmpty=false] Request and display a lookup menu when the text input is empty.
5874 * By default, the lookup menu is not generated and displayed until the user begins to type.
5875 */
5876 OO.ui.mixin.LookupElement = function OoUiMixinLookupElement( config ) {
5877 // Configuration initialization
5878 config = config || {};
5879
5880 // Properties
5881 this.$overlay = config.$overlay || this.$element;
5882 this.lookupMenu = new OO.ui.FloatingMenuSelectWidget( {
5883 widget: this,
5884 input: this,
5885 $container: config.$container || this.$element
5886 } );
5887
5888 this.allowSuggestionsWhenEmpty = config.allowSuggestionsWhenEmpty || false;
5889
5890 this.lookupCache = {};
5891 this.lookupQuery = null;
5892 this.lookupRequest = null;
5893 this.lookupsDisabled = false;
5894 this.lookupInputFocused = false;
5895
5896 // Events
5897 this.$input.on( {
5898 focus: this.onLookupInputFocus.bind( this ),
5899 blur: this.onLookupInputBlur.bind( this ),
5900 mousedown: this.onLookupInputMouseDown.bind( this )
5901 } );
5902 this.connect( this, { change: 'onLookupInputChange' } );
5903 this.lookupMenu.connect( this, {
5904 toggle: 'onLookupMenuToggle',
5905 choose: 'onLookupMenuItemChoose'
5906 } );
5907
5908 // Initialization
5909 this.$element.addClass( 'oo-ui-lookupElement' );
5910 this.lookupMenu.$element.addClass( 'oo-ui-lookupElement-menu' );
5911 this.$overlay.append( this.lookupMenu.$element );
5912 };
5913
5914 /* Methods */
5915
5916 /**
5917 * Handle input focus event.
5918 *
5919 * @protected
5920 * @param {jQuery.Event} e Input focus event
5921 */
5922 OO.ui.mixin.LookupElement.prototype.onLookupInputFocus = function () {
5923 this.lookupInputFocused = true;
5924 this.populateLookupMenu();
5925 };
5926
5927 /**
5928 * Handle input blur event.
5929 *
5930 * @protected
5931 * @param {jQuery.Event} e Input blur event
5932 */
5933 OO.ui.mixin.LookupElement.prototype.onLookupInputBlur = function () {
5934 this.closeLookupMenu();
5935 this.lookupInputFocused = false;
5936 };
5937
5938 /**
5939 * Handle input mouse down event.
5940 *
5941 * @protected
5942 * @param {jQuery.Event} e Input mouse down event
5943 */
5944 OO.ui.mixin.LookupElement.prototype.onLookupInputMouseDown = function () {
5945 // Only open the menu if the input was already focused.
5946 // This way we allow the user to open the menu again after closing it with Esc
5947 // by clicking in the input. Opening (and populating) the menu when initially
5948 // clicking into the input is handled by the focus handler.
5949 if ( this.lookupInputFocused && !this.lookupMenu.isVisible() ) {
5950 this.populateLookupMenu();
5951 }
5952 };
5953
5954 /**
5955 * Handle input change event.
5956 *
5957 * @protected
5958 * @param {string} value New input value
5959 */
5960 OO.ui.mixin.LookupElement.prototype.onLookupInputChange = function () {
5961 if ( this.lookupInputFocused ) {
5962 this.populateLookupMenu();
5963 }
5964 };
5965
5966 /**
5967 * Handle the lookup menu being shown/hidden.
5968 *
5969 * @protected
5970 * @param {boolean} visible Whether the lookup menu is now visible.
5971 */
5972 OO.ui.mixin.LookupElement.prototype.onLookupMenuToggle = function ( visible ) {
5973 if ( !visible ) {
5974 // When the menu is hidden, abort any active request and clear the menu.
5975 // This has to be done here in addition to closeLookupMenu(), because
5976 // MenuSelectWidget will close itself when the user presses Esc.
5977 this.abortLookupRequest();
5978 this.lookupMenu.clearItems();
5979 }
5980 };
5981
5982 /**
5983 * Handle menu item 'choose' event, updating the text input value to the value of the clicked item.
5984 *
5985 * @protected
5986 * @param {OO.ui.MenuOptionWidget} item Selected item
5987 */
5988 OO.ui.mixin.LookupElement.prototype.onLookupMenuItemChoose = function ( item ) {
5989 this.setValue( item.getData() );
5990 };
5991
5992 /**
5993 * Get lookup menu.
5994 *
5995 * @private
5996 * @return {OO.ui.FloatingMenuSelectWidget}
5997 */
5998 OO.ui.mixin.LookupElement.prototype.getLookupMenu = function () {
5999 return this.lookupMenu;
6000 };
6001
6002 /**
6003 * Disable or re-enable lookups.
6004 *
6005 * When lookups are disabled, calls to #populateLookupMenu will be ignored.
6006 *
6007 * @param {boolean} disabled Disable lookups
6008 */
6009 OO.ui.mixin.LookupElement.prototype.setLookupsDisabled = function ( disabled ) {
6010 this.lookupsDisabled = !!disabled;
6011 };
6012
6013 /**
6014 * Open the menu. If there are no entries in the menu, this does nothing.
6015 *
6016 * @private
6017 * @chainable
6018 */
6019 OO.ui.mixin.LookupElement.prototype.openLookupMenu = function () {
6020 if ( !this.lookupMenu.isEmpty() ) {
6021 this.lookupMenu.toggle( true );
6022 }
6023 return this;
6024 };
6025
6026 /**
6027 * Close the menu, empty it, and abort any pending request.
6028 *
6029 * @private
6030 * @chainable
6031 */
6032 OO.ui.mixin.LookupElement.prototype.closeLookupMenu = function () {
6033 this.lookupMenu.toggle( false );
6034 this.abortLookupRequest();
6035 this.lookupMenu.clearItems();
6036 return this;
6037 };
6038
6039 /**
6040 * Request menu items based on the input's current value, and when they arrive,
6041 * populate the menu with these items and show the menu.
6042 *
6043 * If lookups have been disabled with #setLookupsDisabled, this function does nothing.
6044 *
6045 * @private
6046 * @chainable
6047 */
6048 OO.ui.mixin.LookupElement.prototype.populateLookupMenu = function () {
6049 var widget = this,
6050 value = this.getValue();
6051
6052 if ( this.lookupsDisabled || this.isReadOnly() ) {
6053 return;
6054 }
6055
6056 // If the input is empty, clear the menu, unless suggestions when empty are allowed.
6057 if ( !this.allowSuggestionsWhenEmpty && value === '' ) {
6058 this.closeLookupMenu();
6059 // Skip population if there is already a request pending for the current value
6060 } else if ( value !== this.lookupQuery ) {
6061 this.getLookupMenuItems()
6062 .done( function ( items ) {
6063 widget.lookupMenu.clearItems();
6064 if ( items.length ) {
6065 widget.lookupMenu
6066 .addItems( items )
6067 .toggle( true );
6068 widget.initializeLookupMenuSelection();
6069 } else {
6070 widget.lookupMenu.toggle( false );
6071 }
6072 } )
6073 .fail( function () {
6074 widget.lookupMenu.clearItems();
6075 } );
6076 }
6077
6078 return this;
6079 };
6080
6081 /**
6082 * Highlight the first selectable item in the menu.
6083 *
6084 * @private
6085 * @chainable
6086 */
6087 OO.ui.mixin.LookupElement.prototype.initializeLookupMenuSelection = function () {
6088 if ( !this.lookupMenu.getSelectedItem() ) {
6089 this.lookupMenu.highlightItem( this.lookupMenu.getFirstSelectableItem() );
6090 }
6091 };
6092
6093 /**
6094 * Get lookup menu items for the current query.
6095 *
6096 * @private
6097 * @return {jQuery.Promise} Promise object which will be passed menu items as the first argument of
6098 * the done event. If the request was aborted to make way for a subsequent request, this promise
6099 * will not be rejected: it will remain pending forever.
6100 */
6101 OO.ui.mixin.LookupElement.prototype.getLookupMenuItems = function () {
6102 var widget = this,
6103 value = this.getValue(),
6104 deferred = $.Deferred(),
6105 ourRequest;
6106
6107 this.abortLookupRequest();
6108 if ( Object.prototype.hasOwnProperty.call( this.lookupCache, value ) ) {
6109 deferred.resolve( this.getLookupMenuOptionsFromData( this.lookupCache[ value ] ) );
6110 } else {
6111 this.pushPending();
6112 this.lookupQuery = value;
6113 ourRequest = this.lookupRequest = this.getLookupRequest();
6114 ourRequest
6115 .always( function () {
6116 // We need to pop pending even if this is an old request, otherwise
6117 // the widget will remain pending forever.
6118 // TODO: this assumes that an aborted request will fail or succeed soon after
6119 // being aborted, or at least eventually. It would be nice if we could popPending()
6120 // at abort time, but only if we knew that we hadn't already called popPending()
6121 // for that request.
6122 widget.popPending();
6123 } )
6124 .done( function ( response ) {
6125 // If this is an old request (and aborting it somehow caused it to still succeed),
6126 // ignore its success completely
6127 if ( ourRequest === widget.lookupRequest ) {
6128 widget.lookupQuery = null;
6129 widget.lookupRequest = null;
6130 widget.lookupCache[ value ] = widget.getLookupCacheDataFromResponse( response );
6131 deferred.resolve( widget.getLookupMenuOptionsFromData( widget.lookupCache[ value ] ) );
6132 }
6133 } )
6134 .fail( function () {
6135 // If this is an old request (or a request failing because it's being aborted),
6136 // ignore its failure completely
6137 if ( ourRequest === widget.lookupRequest ) {
6138 widget.lookupQuery = null;
6139 widget.lookupRequest = null;
6140 deferred.reject();
6141 }
6142 } );
6143 }
6144 return deferred.promise();
6145 };
6146
6147 /**
6148 * Abort the currently pending lookup request, if any.
6149 *
6150 * @private
6151 */
6152 OO.ui.mixin.LookupElement.prototype.abortLookupRequest = function () {
6153 var oldRequest = this.lookupRequest;
6154 if ( oldRequest ) {
6155 // First unset this.lookupRequest to the fail handler will notice
6156 // that the request is no longer current
6157 this.lookupRequest = null;
6158 this.lookupQuery = null;
6159 oldRequest.abort();
6160 }
6161 };
6162
6163 /**
6164 * Get a new request object of the current lookup query value.
6165 *
6166 * @protected
6167 * @abstract
6168 * @return {jQuery.Promise} jQuery AJAX object, or promise object with an .abort() method
6169 */
6170 OO.ui.mixin.LookupElement.prototype.getLookupRequest = function () {
6171 // Stub, implemented in subclass
6172 return null;
6173 };
6174
6175 /**
6176 * Pre-process data returned by the request from #getLookupRequest.
6177 *
6178 * The return value of this function will be cached, and any further queries for the given value
6179 * will use the cache rather than doing API requests.
6180 *
6181 * @protected
6182 * @abstract
6183 * @param {Mixed} response Response from server
6184 * @return {Mixed} Cached result data
6185 */
6186 OO.ui.mixin.LookupElement.prototype.getLookupCacheDataFromResponse = function () {
6187 // Stub, implemented in subclass
6188 return [];
6189 };
6190
6191 /**
6192 * Get a list of menu option widgets from the (possibly cached) data returned by
6193 * #getLookupCacheDataFromResponse.
6194 *
6195 * @protected
6196 * @abstract
6197 * @param {Mixed} data Cached result data, usually an array
6198 * @return {OO.ui.MenuOptionWidget[]} Menu items
6199 */
6200 OO.ui.mixin.LookupElement.prototype.getLookupMenuOptionsFromData = function () {
6201 // Stub, implemented in subclass
6202 return [];
6203 };
6204
6205 /**
6206 * Set the read-only state of the widget.
6207 *
6208 * This will also disable/enable the lookups functionality.
6209 *
6210 * @param {boolean} readOnly Make input read-only
6211 * @chainable
6212 */
6213 OO.ui.mixin.LookupElement.prototype.setReadOnly = function ( readOnly ) {
6214 // Parent method
6215 // Note: Calling #setReadOnly this way assumes this is mixed into an OO.ui.TextInputWidget
6216 OO.ui.TextInputWidget.prototype.setReadOnly.call( this, readOnly );
6217
6218 // During construction, #setReadOnly is called before the OO.ui.mixin.LookupElement constructor
6219 if ( this.isReadOnly() && this.lookupMenu ) {
6220 this.closeLookupMenu();
6221 }
6222
6223 return this;
6224 };
6225
6226 /**
6227 * PopupElement is mixed into other classes to generate a {@link OO.ui.PopupWidget popup widget}.
6228 * A popup is a container for content. It is overlaid and positioned absolutely. By default, each
6229 * popup has an anchor, which is an arrow-like protrusion that points toward the popup’s origin.
6230 * See {@link OO.ui.PopupWidget PopupWidget} for an example.
6231 *
6232 * @abstract
6233 * @class
6234 *
6235 * @constructor
6236 * @param {Object} [config] Configuration options
6237 * @cfg {Object} [popup] Configuration to pass to popup
6238 * @cfg {boolean} [popup.autoClose=true] Popup auto-closes when it loses focus
6239 */
6240 OO.ui.mixin.PopupElement = function OoUiMixinPopupElement( config ) {
6241 // Configuration initialization
6242 config = config || {};
6243
6244 // Properties
6245 this.popup = new OO.ui.PopupWidget( $.extend(
6246 { autoClose: true },
6247 config.popup,
6248 { $autoCloseIgnore: this.$element }
6249 ) );
6250 };
6251
6252 /* Methods */
6253
6254 /**
6255 * Get popup.
6256 *
6257 * @return {OO.ui.PopupWidget} Popup widget
6258 */
6259 OO.ui.mixin.PopupElement.prototype.getPopup = function () {
6260 return this.popup;
6261 };
6262
6263 /**
6264 * The FlaggedElement class is an attribute mixin, meaning that it is used to add
6265 * additional functionality to an element created by another class. The class provides
6266 * a ‘flags’ property assigned the name (or an array of names) of styling flags,
6267 * which are used to customize the look and feel of a widget to better describe its
6268 * importance and functionality.
6269 *
6270 * The library currently contains the following styling flags for general use:
6271 *
6272 * - **progressive**: Progressive styling is applied to convey that the widget will move the user forward in a process.
6273 * - **destructive**: Destructive styling is applied to convey that the widget will remove something.
6274 * - **constructive**: Constructive styling is applied to convey that the widget will create something.
6275 *
6276 * The flags affect the appearance of the buttons:
6277 *
6278 * @example
6279 * // FlaggedElement is mixed into ButtonWidget to provide styling flags
6280 * var button1 = new OO.ui.ButtonWidget( {
6281 * label: 'Constructive',
6282 * flags: 'constructive'
6283 * } );
6284 * var button2 = new OO.ui.ButtonWidget( {
6285 * label: 'Destructive',
6286 * flags: 'destructive'
6287 * } );
6288 * var button3 = new OO.ui.ButtonWidget( {
6289 * label: 'Progressive',
6290 * flags: 'progressive'
6291 * } );
6292 * $( 'body' ).append( button1.$element, button2.$element, button3.$element );
6293 *
6294 * {@link OO.ui.ActionWidget ActionWidgets}, which are a special kind of button that execute an action, use these flags: **primary** and **safe**.
6295 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information.
6296 *
6297 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Flagged
6298 *
6299 * @abstract
6300 * @class
6301 *
6302 * @constructor
6303 * @param {Object} [config] Configuration options
6304 * @cfg {string|string[]} [flags] The name or names of the flags (e.g., 'constructive' or 'primary') to apply.
6305 * Please see the [OOjs UI documentation on MediaWiki] [2] for more information about available flags.
6306 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Flagged
6307 * @cfg {jQuery} [$flagged] The flagged element. By default,
6308 * the flagged functionality is applied to the element created by the class ($element).
6309 * If a different element is specified, the flagged functionality will be applied to it instead.
6310 */
6311 OO.ui.mixin.FlaggedElement = function OoUiMixinFlaggedElement( config ) {
6312 // Configuration initialization
6313 config = config || {};
6314
6315 // Properties
6316 this.flags = {};
6317 this.$flagged = null;
6318
6319 // Initialization
6320 this.setFlags( config.flags );
6321 this.setFlaggedElement( config.$flagged || this.$element );
6322 };
6323
6324 /* Events */
6325
6326 /**
6327 * @event flag
6328 * A flag event is emitted when the #clearFlags or #setFlags methods are used. The `changes`
6329 * parameter contains the name of each modified flag and indicates whether it was
6330 * added or removed.
6331 *
6332 * @param {Object.<string,boolean>} changes Object keyed by flag name. A Boolean `true` indicates
6333 * that the flag was added, `false` that the flag was removed.
6334 */
6335
6336 /* Methods */
6337
6338 /**
6339 * Set the flagged element.
6340 *
6341 * This method is used to retarget a flagged mixin so that its functionality applies to the specified element.
6342 * If an element is already set, the method will remove the mixin’s effect on that element.
6343 *
6344 * @param {jQuery} $flagged Element that should be flagged
6345 */
6346 OO.ui.mixin.FlaggedElement.prototype.setFlaggedElement = function ( $flagged ) {
6347 var classNames = Object.keys( this.flags ).map( function ( flag ) {
6348 return 'oo-ui-flaggedElement-' + flag;
6349 } ).join( ' ' );
6350
6351 if ( this.$flagged ) {
6352 this.$flagged.removeClass( classNames );
6353 }
6354
6355 this.$flagged = $flagged.addClass( classNames );
6356 };
6357
6358 /**
6359 * Check if the specified flag is set.
6360 *
6361 * @param {string} flag Name of flag
6362 * @return {boolean} The flag is set
6363 */
6364 OO.ui.mixin.FlaggedElement.prototype.hasFlag = function ( flag ) {
6365 // This may be called before the constructor, thus before this.flags is set
6366 return this.flags && ( flag in this.flags );
6367 };
6368
6369 /**
6370 * Get the names of all flags set.
6371 *
6372 * @return {string[]} Flag names
6373 */
6374 OO.ui.mixin.FlaggedElement.prototype.getFlags = function () {
6375 // This may be called before the constructor, thus before this.flags is set
6376 return Object.keys( this.flags || {} );
6377 };
6378
6379 /**
6380 * Clear all flags.
6381 *
6382 * @chainable
6383 * @fires flag
6384 */
6385 OO.ui.mixin.FlaggedElement.prototype.clearFlags = function () {
6386 var flag, className,
6387 changes = {},
6388 remove = [],
6389 classPrefix = 'oo-ui-flaggedElement-';
6390
6391 for ( flag in this.flags ) {
6392 className = classPrefix + flag;
6393 changes[ flag ] = false;
6394 delete this.flags[ flag ];
6395 remove.push( className );
6396 }
6397
6398 if ( this.$flagged ) {
6399 this.$flagged.removeClass( remove.join( ' ' ) );
6400 }
6401
6402 this.updateThemeClasses();
6403 this.emit( 'flag', changes );
6404
6405 return this;
6406 };
6407
6408 /**
6409 * Add one or more flags.
6410 *
6411 * @param {string|string[]|Object.<string, boolean>} flags A flag name, an array of flag names,
6412 * or an object keyed by flag name with a boolean value that indicates whether the flag should
6413 * be added (`true`) or removed (`false`).
6414 * @chainable
6415 * @fires flag
6416 */
6417 OO.ui.mixin.FlaggedElement.prototype.setFlags = function ( flags ) {
6418 var i, len, flag, className,
6419 changes = {},
6420 add = [],
6421 remove = [],
6422 classPrefix = 'oo-ui-flaggedElement-';
6423
6424 if ( typeof flags === 'string' ) {
6425 className = classPrefix + flags;
6426 // Set
6427 if ( !this.flags[ flags ] ) {
6428 this.flags[ flags ] = true;
6429 add.push( className );
6430 }
6431 } else if ( Array.isArray( flags ) ) {
6432 for ( i = 0, len = flags.length; i < len; i++ ) {
6433 flag = flags[ i ];
6434 className = classPrefix + flag;
6435 // Set
6436 if ( !this.flags[ flag ] ) {
6437 changes[ flag ] = true;
6438 this.flags[ flag ] = true;
6439 add.push( className );
6440 }
6441 }
6442 } else if ( OO.isPlainObject( flags ) ) {
6443 for ( flag in flags ) {
6444 className = classPrefix + flag;
6445 if ( flags[ flag ] ) {
6446 // Set
6447 if ( !this.flags[ flag ] ) {
6448 changes[ flag ] = true;
6449 this.flags[ flag ] = true;
6450 add.push( className );
6451 }
6452 } else {
6453 // Remove
6454 if ( this.flags[ flag ] ) {
6455 changes[ flag ] = false;
6456 delete this.flags[ flag ];
6457 remove.push( className );
6458 }
6459 }
6460 }
6461 }
6462
6463 if ( this.$flagged ) {
6464 this.$flagged
6465 .addClass( add.join( ' ' ) )
6466 .removeClass( remove.join( ' ' ) );
6467 }
6468
6469 this.updateThemeClasses();
6470 this.emit( 'flag', changes );
6471
6472 return this;
6473 };
6474
6475 /**
6476 * TitledElement is mixed into other classes to provide a `title` attribute.
6477 * Titles are rendered by the browser and are made visible when the user moves
6478 * the mouse over the element. Titles are not visible on touch devices.
6479 *
6480 * @example
6481 * // TitledElement provides a 'title' attribute to the
6482 * // ButtonWidget class
6483 * var button = new OO.ui.ButtonWidget( {
6484 * label: 'Button with Title',
6485 * title: 'I am a button'
6486 * } );
6487 * $( 'body' ).append( button.$element );
6488 *
6489 * @abstract
6490 * @class
6491 *
6492 * @constructor
6493 * @param {Object} [config] Configuration options
6494 * @cfg {jQuery} [$titled] The element to which the `title` attribute is applied.
6495 * If this config is omitted, the title functionality is applied to $element, the
6496 * element created by the class.
6497 * @cfg {string|Function} [title] The title text or a function that returns text. If
6498 * this config is omitted, the value of the {@link #static-title static title} property is used.
6499 */
6500 OO.ui.mixin.TitledElement = function OoUiMixinTitledElement( config ) {
6501 // Configuration initialization
6502 config = config || {};
6503
6504 // Properties
6505 this.$titled = null;
6506 this.title = null;
6507
6508 // Initialization
6509 this.setTitle( config.title || this.constructor.static.title );
6510 this.setTitledElement( config.$titled || this.$element );
6511 };
6512
6513 /* Setup */
6514
6515 OO.initClass( OO.ui.mixin.TitledElement );
6516
6517 /* Static Properties */
6518
6519 /**
6520 * The title text, a function that returns text, or `null` for no title. The value of the static property
6521 * is overridden if the #title config option is used.
6522 *
6523 * @static
6524 * @inheritable
6525 * @property {string|Function|null}
6526 */
6527 OO.ui.mixin.TitledElement.static.title = null;
6528
6529 /* Methods */
6530
6531 /**
6532 * Set the titled element.
6533 *
6534 * This method is used to retarget a titledElement mixin so that its functionality applies to the specified element.
6535 * If an element is already set, the mixin’s effect on that element is removed before the new element is set up.
6536 *
6537 * @param {jQuery} $titled Element that should use the 'titled' functionality
6538 */
6539 OO.ui.mixin.TitledElement.prototype.setTitledElement = function ( $titled ) {
6540 if ( this.$titled ) {
6541 this.$titled.removeAttr( 'title' );
6542 }
6543
6544 this.$titled = $titled;
6545 if ( this.title ) {
6546 this.$titled.attr( 'title', this.title );
6547 }
6548 };
6549
6550 /**
6551 * Set title.
6552 *
6553 * @param {string|Function|null} title Title text, a function that returns text, or `null` for no title
6554 * @chainable
6555 */
6556 OO.ui.mixin.TitledElement.prototype.setTitle = function ( title ) {
6557 title = typeof title === 'string' ? OO.ui.resolveMsg( title ) : null;
6558
6559 if ( this.title !== title ) {
6560 if ( this.$titled ) {
6561 if ( title !== null ) {
6562 this.$titled.attr( 'title', title );
6563 } else {
6564 this.$titled.removeAttr( 'title' );
6565 }
6566 }
6567 this.title = title;
6568 }
6569
6570 return this;
6571 };
6572
6573 /**
6574 * Get title.
6575 *
6576 * @return {string} Title string
6577 */
6578 OO.ui.mixin.TitledElement.prototype.getTitle = function () {
6579 return this.title;
6580 };
6581
6582 /**
6583 * Element that can be automatically clipped to visible boundaries.
6584 *
6585 * Whenever the element's natural height changes, you have to call
6586 * {@link OO.ui.mixin.ClippableElement#clip} to make sure it's still
6587 * clipping correctly.
6588 *
6589 * The dimensions of #$clippableContainer will be compared to the boundaries of the
6590 * nearest scrollable container. If #$clippableContainer is too tall and/or too wide,
6591 * then #$clippable will be given a fixed reduced height and/or width and will be made
6592 * scrollable. By default, #$clippable and #$clippableContainer are the same element,
6593 * but you can build a static footer by setting #$clippableContainer to an element that contains
6594 * #$clippable and the footer.
6595 *
6596 * @abstract
6597 * @class
6598 *
6599 * @constructor
6600 * @param {Object} [config] Configuration options
6601 * @cfg {jQuery} [$clippable] Node to clip, assigned to #$clippable, omit to use #$element
6602 * @cfg {jQuery} [$clippableContainer] Node to keep visible, assigned to #$clippableContainer,
6603 * omit to use #$clippable
6604 */
6605 OO.ui.mixin.ClippableElement = function OoUiMixinClippableElement( config ) {
6606 // Configuration initialization
6607 config = config || {};
6608
6609 // Properties
6610 this.$clippable = null;
6611 this.$clippableContainer = null;
6612 this.clipping = false;
6613 this.clippedHorizontally = false;
6614 this.clippedVertically = false;
6615 this.$clippableScrollableContainer = null;
6616 this.$clippableScroller = null;
6617 this.$clippableWindow = null;
6618 this.idealWidth = null;
6619 this.idealHeight = null;
6620 this.onClippableScrollHandler = this.clip.bind( this );
6621 this.onClippableWindowResizeHandler = this.clip.bind( this );
6622
6623 // Initialization
6624 if ( config.$clippableContainer ) {
6625 this.setClippableContainer( config.$clippableContainer );
6626 }
6627 this.setClippableElement( config.$clippable || this.$element );
6628 };
6629
6630 /* Methods */
6631
6632 /**
6633 * Set clippable element.
6634 *
6635 * If an element is already set, it will be cleaned up before setting up the new element.
6636 *
6637 * @param {jQuery} $clippable Element to make clippable
6638 */
6639 OO.ui.mixin.ClippableElement.prototype.setClippableElement = function ( $clippable ) {
6640 if ( this.$clippable ) {
6641 this.$clippable.removeClass( 'oo-ui-clippableElement-clippable' );
6642 this.$clippable.css( { width: '', height: '', overflowX: '', overflowY: '' } );
6643 OO.ui.Element.static.reconsiderScrollbars( this.$clippable[ 0 ] );
6644 }
6645
6646 this.$clippable = $clippable.addClass( 'oo-ui-clippableElement-clippable' );
6647 this.clip();
6648 };
6649
6650 /**
6651 * Set clippable container.
6652 *
6653 * This is the container that will be measured when deciding whether to clip. When clipping,
6654 * #$clippable will be resized in order to keep the clippable container fully visible.
6655 *
6656 * If the clippable container is unset, #$clippable will be used.
6657 *
6658 * @param {jQuery|null} $clippableContainer Container to keep visible, or null to unset
6659 */
6660 OO.ui.mixin.ClippableElement.prototype.setClippableContainer = function ( $clippableContainer ) {
6661 this.$clippableContainer = $clippableContainer;
6662 if ( this.$clippable ) {
6663 this.clip();
6664 }
6665 };
6666
6667 /**
6668 * Toggle clipping.
6669 *
6670 * Do not turn clipping on until after the element is attached to the DOM and visible.
6671 *
6672 * @param {boolean} [clipping] Enable clipping, omit to toggle
6673 * @chainable
6674 */
6675 OO.ui.mixin.ClippableElement.prototype.toggleClipping = function ( clipping ) {
6676 clipping = clipping === undefined ? !this.clipping : !!clipping;
6677
6678 if ( this.clipping !== clipping ) {
6679 this.clipping = clipping;
6680 if ( clipping ) {
6681 this.$clippableScrollableContainer = $( this.getClosestScrollableElementContainer() );
6682 // If the clippable container is the root, we have to listen to scroll events and check
6683 // jQuery.scrollTop on the window because of browser inconsistencies
6684 this.$clippableScroller = this.$clippableScrollableContainer.is( 'html, body' ) ?
6685 $( OO.ui.Element.static.getWindow( this.$clippableScrollableContainer ) ) :
6686 this.$clippableScrollableContainer;
6687 this.$clippableScroller.on( 'scroll', this.onClippableScrollHandler );
6688 this.$clippableWindow = $( this.getElementWindow() )
6689 .on( 'resize', this.onClippableWindowResizeHandler );
6690 // Initial clip after visible
6691 this.clip();
6692 } else {
6693 this.$clippable.css( { width: '', height: '', overflowX: '', overflowY: '' } );
6694 OO.ui.Element.static.reconsiderScrollbars( this.$clippable[ 0 ] );
6695
6696 this.$clippableScrollableContainer = null;
6697 this.$clippableScroller.off( 'scroll', this.onClippableScrollHandler );
6698 this.$clippableScroller = null;
6699 this.$clippableWindow.off( 'resize', this.onClippableWindowResizeHandler );
6700 this.$clippableWindow = null;
6701 }
6702 }
6703
6704 return this;
6705 };
6706
6707 /**
6708 * Check if the element will be clipped to fit the visible area of the nearest scrollable container.
6709 *
6710 * @return {boolean} Element will be clipped to the visible area
6711 */
6712 OO.ui.mixin.ClippableElement.prototype.isClipping = function () {
6713 return this.clipping;
6714 };
6715
6716 /**
6717 * Check if the bottom or right of the element is being clipped by the nearest scrollable container.
6718 *
6719 * @return {boolean} Part of the element is being clipped
6720 */
6721 OO.ui.mixin.ClippableElement.prototype.isClipped = function () {
6722 return this.clippedHorizontally || this.clippedVertically;
6723 };
6724
6725 /**
6726 * Check if the right of the element is being clipped by the nearest scrollable container.
6727 *
6728 * @return {boolean} Part of the element is being clipped
6729 */
6730 OO.ui.mixin.ClippableElement.prototype.isClippedHorizontally = function () {
6731 return this.clippedHorizontally;
6732 };
6733
6734 /**
6735 * Check if the bottom of the element is being clipped by the nearest scrollable container.
6736 *
6737 * @return {boolean} Part of the element is being clipped
6738 */
6739 OO.ui.mixin.ClippableElement.prototype.isClippedVertically = function () {
6740 return this.clippedVertically;
6741 };
6742
6743 /**
6744 * Set the ideal size. These are the dimensions the element will have when it's not being clipped.
6745 *
6746 * @param {number|string} [width] Width as a number of pixels or CSS string with unit suffix
6747 * @param {number|string} [height] Height as a number of pixels or CSS string with unit suffix
6748 */
6749 OO.ui.mixin.ClippableElement.prototype.setIdealSize = function ( width, height ) {
6750 this.idealWidth = width;
6751 this.idealHeight = height;
6752
6753 if ( !this.clipping ) {
6754 // Update dimensions
6755 this.$clippable.css( { width: width, height: height } );
6756 }
6757 // While clipping, idealWidth and idealHeight are not considered
6758 };
6759
6760 /**
6761 * Clip element to visible boundaries and allow scrolling when needed. Call this method when
6762 * the element's natural height changes.
6763 *
6764 * Element will be clipped the bottom or right of the element is within 10px of the edge of, or
6765 * overlapped by, the visible area of the nearest scrollable container.
6766 *
6767 * @chainable
6768 */
6769 OO.ui.mixin.ClippableElement.prototype.clip = function () {
6770 var $container, extraHeight, extraWidth, ccOffset,
6771 $scrollableContainer, scOffset, scHeight, scWidth,
6772 ccWidth, scrollerIsWindow, scrollTop, scrollLeft,
6773 desiredWidth, desiredHeight, allotedWidth, allotedHeight,
6774 naturalWidth, naturalHeight, clipWidth, clipHeight,
6775 buffer = 7; // Chosen by fair dice roll
6776
6777 if ( !this.clipping ) {
6778 // this.$clippableScrollableContainer and this.$clippableWindow are null, so the below will fail
6779 return this;
6780 }
6781
6782 $container = this.$clippableContainer || this.$clippable;
6783 extraHeight = $container.outerHeight() - this.$clippable.outerHeight();
6784 extraWidth = $container.outerWidth() - this.$clippable.outerWidth();
6785 ccOffset = $container.offset();
6786 $scrollableContainer = this.$clippableScrollableContainer.is( 'html, body' ) ?
6787 this.$clippableWindow : this.$clippableScrollableContainer;
6788 scOffset = $scrollableContainer.offset() || { top: 0, left: 0 };
6789 scHeight = $scrollableContainer.innerHeight() - buffer;
6790 scWidth = $scrollableContainer.innerWidth() - buffer;
6791 ccWidth = $container.outerWidth() + buffer;
6792 scrollerIsWindow = this.$clippableScroller[ 0 ] === this.$clippableWindow[ 0 ];
6793 scrollTop = scrollerIsWindow ? this.$clippableScroller.scrollTop() : 0;
6794 scrollLeft = scrollerIsWindow ? this.$clippableScroller.scrollLeft() : 0;
6795 desiredWidth = ccOffset.left < 0 ?
6796 ccWidth + ccOffset.left :
6797 ( scOffset.left + scrollLeft + scWidth ) - ccOffset.left;
6798 desiredHeight = ( scOffset.top + scrollTop + scHeight ) - ccOffset.top;
6799 allotedWidth = desiredWidth - extraWidth;
6800 allotedHeight = desiredHeight - extraHeight;
6801 naturalWidth = this.$clippable.prop( 'scrollWidth' );
6802 naturalHeight = this.$clippable.prop( 'scrollHeight' );
6803 clipWidth = allotedWidth < naturalWidth;
6804 clipHeight = allotedHeight < naturalHeight;
6805
6806 if ( clipWidth ) {
6807 this.$clippable.css( { overflowX: 'scroll', width: Math.max( 0, allotedWidth ) } );
6808 } else {
6809 this.$clippable.css( { width: this.idealWidth ? this.idealWidth - extraWidth : '', overflowX: '' } );
6810 }
6811 if ( clipHeight ) {
6812 this.$clippable.css( { overflowY: 'scroll', height: Math.max( 0, allotedHeight ) } );
6813 } else {
6814 this.$clippable.css( { height: this.idealHeight ? this.idealHeight - extraHeight : '', overflowY: '' } );
6815 }
6816
6817 // If we stopped clipping in at least one of the dimensions
6818 if ( ( this.clippedHorizontally && !clipWidth ) || ( this.clippedVertically && !clipHeight ) ) {
6819 OO.ui.Element.static.reconsiderScrollbars( this.$clippable[ 0 ] );
6820 }
6821
6822 this.clippedHorizontally = clipWidth;
6823 this.clippedVertically = clipHeight;
6824
6825 return this;
6826 };
6827
6828 /**
6829 * Element that will stick under a specified container, even when it is inserted elsewhere in the
6830 * document (for example, in a OO.ui.Window's $overlay).
6831 *
6832 * The elements's position is automatically calculated and maintained when window is resized or the
6833 * page is scrolled. If you reposition the container manually, you have to call #position to make
6834 * sure the element is still placed correctly.
6835 *
6836 * As positioning is only possible when both the element and the container are attached to the DOM
6837 * and visible, it's only done after you call #togglePositioning. You might want to do this inside
6838 * the #toggle method to display a floating popup, for example.
6839 *
6840 * @abstract
6841 * @class
6842 *
6843 * @constructor
6844 * @param {Object} [config] Configuration options
6845 * @cfg {jQuery} [$floatable] Node to position, assigned to #$floatable, omit to use #$element
6846 * @cfg {jQuery} [$floatableContainer] Node to position below
6847 */
6848 OO.ui.mixin.FloatableElement = function OoUiMixinFloatableElement( config ) {
6849 // Configuration initialization
6850 config = config || {};
6851
6852 // Properties
6853 this.$floatable = null;
6854 this.$floatableContainer = null;
6855 this.$floatableWindow = null;
6856 this.$floatableClosestScrollable = null;
6857 this.onFloatableScrollHandler = this.position.bind( this );
6858 this.onFloatableWindowResizeHandler = this.position.bind( this );
6859
6860 // Initialization
6861 this.setFloatableContainer( config.$floatableContainer );
6862 this.setFloatableElement( config.$floatable || this.$element );
6863 };
6864
6865 /* Methods */
6866
6867 /**
6868 * Set floatable element.
6869 *
6870 * If an element is already set, it will be cleaned up before setting up the new element.
6871 *
6872 * @param {jQuery} $floatable Element to make floatable
6873 */
6874 OO.ui.mixin.FloatableElement.prototype.setFloatableElement = function ( $floatable ) {
6875 if ( this.$floatable ) {
6876 this.$floatable.removeClass( 'oo-ui-floatableElement-floatable' );
6877 this.$floatable.css( { left: '', top: '' } );
6878 }
6879
6880 this.$floatable = $floatable.addClass( 'oo-ui-floatableElement-floatable' );
6881 this.position();
6882 };
6883
6884 /**
6885 * Set floatable container.
6886 *
6887 * The element will be always positioned under the specified container.
6888 *
6889 * @param {jQuery|null} $floatableContainer Container to keep visible, or null to unset
6890 */
6891 OO.ui.mixin.FloatableElement.prototype.setFloatableContainer = function ( $floatableContainer ) {
6892 this.$floatableContainer = $floatableContainer;
6893 if ( this.$floatable ) {
6894 this.position();
6895 }
6896 };
6897
6898 /**
6899 * Toggle positioning.
6900 *
6901 * Do not turn positioning on until after the element is attached to the DOM and visible.
6902 *
6903 * @param {boolean} [positioning] Enable positioning, omit to toggle
6904 * @chainable
6905 */
6906 OO.ui.mixin.FloatableElement.prototype.togglePositioning = function ( positioning ) {
6907 var closestScrollableOfContainer, closestScrollableOfFloatable;
6908
6909 positioning = positioning === undefined ? !this.positioning : !!positioning;
6910
6911 if ( this.positioning !== positioning ) {
6912 this.positioning = positioning;
6913
6914 closestScrollableOfContainer = OO.ui.Element.static.getClosestScrollableContainer( this.$floatableContainer[ 0 ] );
6915 closestScrollableOfFloatable = OO.ui.Element.static.getClosestScrollableContainer( this.$floatable[ 0 ] );
6916 if ( closestScrollableOfContainer !== closestScrollableOfFloatable ) {
6917 // If the scrollable is the root, we have to listen to scroll events
6918 // on the window because of browser inconsistencies (or do we? someone should verify this)
6919 if ( $( closestScrollableOfContainer ).is( 'html, body' ) ) {
6920 closestScrollableOfContainer = OO.ui.Element.static.getWindow( closestScrollableOfContainer );
6921 }
6922 }
6923
6924 if ( positioning ) {
6925 this.$floatableWindow = $( this.getElementWindow() );
6926 this.$floatableWindow.on( 'resize', this.onFloatableWindowResizeHandler );
6927
6928 if ( closestScrollableOfContainer !== closestScrollableOfFloatable ) {
6929 this.$floatableClosestScrollable = $( closestScrollableOfContainer );
6930 this.$floatableClosestScrollable.on( 'scroll', this.onFloatableScrollHandler );
6931 }
6932
6933 // Initial position after visible
6934 this.position();
6935 } else {
6936 this.$floatableWindow.off( 'resize', this.onFloatableWindowResizeHandler );
6937 this.$floatableWindow = null;
6938
6939 if ( this.$floatableClosestScrollable ) {
6940 this.$floatableClosestScrollable.off( 'scroll', this.onFloatableScrollHandler );
6941 this.$floatableClosestScrollable = null;
6942 }
6943
6944 this.$floatable.css( { left: '', top: '' } );
6945 }
6946 }
6947
6948 return this;
6949 };
6950
6951 /**
6952 * Position the floatable below its container.
6953 *
6954 * This should only be done when both of them are attached to the DOM and visible.
6955 *
6956 * @chainable
6957 */
6958 OO.ui.mixin.FloatableElement.prototype.position = function () {
6959 var pos;
6960
6961 if ( !this.positioning ) {
6962 return this;
6963 }
6964
6965 pos = OO.ui.Element.static.getRelativePosition( this.$floatableContainer, this.$floatable.offsetParent() );
6966
6967 // Position under container
6968 pos.top += this.$floatableContainer.height();
6969 this.$floatable.css( pos );
6970
6971 // We updated the position, so re-evaluate the clipping state.
6972 // (ClippableElement does not listen to 'scroll' events on $floatableContainer's parent, and so
6973 // will not notice the need to update itself.)
6974 // TODO: This is terrible, we shouldn't need to know about ClippableElement at all here. Why does
6975 // it not listen to the right events in the right places?
6976 if ( this.clip ) {
6977 this.clip();
6978 }
6979
6980 return this;
6981 };
6982
6983 /**
6984 * AccessKeyedElement is mixed into other classes to provide an `accesskey` attribute.
6985 * Accesskeys allow an user to go to a specific element by using
6986 * a shortcut combination of a browser specific keys + the key
6987 * set to the field.
6988 *
6989 * @example
6990 * // AccessKeyedElement provides an 'accesskey' attribute to the
6991 * // ButtonWidget class
6992 * var button = new OO.ui.ButtonWidget( {
6993 * label: 'Button with Accesskey',
6994 * accessKey: 'k'
6995 * } );
6996 * $( 'body' ).append( button.$element );
6997 *
6998 * @abstract
6999 * @class
7000 *
7001 * @constructor
7002 * @param {Object} [config] Configuration options
7003 * @cfg {jQuery} [$accessKeyed] The element to which the `accesskey` attribute is applied.
7004 * If this config is omitted, the accesskey functionality is applied to $element, the
7005 * element created by the class.
7006 * @cfg {string|Function} [accessKey] The key or a function that returns the key. If
7007 * this config is omitted, no accesskey will be added.
7008 */
7009 OO.ui.mixin.AccessKeyedElement = function OoUiMixinAccessKeyedElement( config ) {
7010 // Configuration initialization
7011 config = config || {};
7012
7013 // Properties
7014 this.$accessKeyed = null;
7015 this.accessKey = null;
7016
7017 // Initialization
7018 this.setAccessKey( config.accessKey || null );
7019 this.setAccessKeyedElement( config.$accessKeyed || this.$element );
7020 };
7021
7022 /* Setup */
7023
7024 OO.initClass( OO.ui.mixin.AccessKeyedElement );
7025
7026 /* Static Properties */
7027
7028 /**
7029 * The access key, a function that returns a key, or `null` for no accesskey.
7030 *
7031 * @static
7032 * @inheritable
7033 * @property {string|Function|null}
7034 */
7035 OO.ui.mixin.AccessKeyedElement.static.accessKey = null;
7036
7037 /* Methods */
7038
7039 /**
7040 * Set the accesskeyed element.
7041 *
7042 * This method is used to retarget a AccessKeyedElement mixin so that its functionality applies to the specified element.
7043 * If an element is already set, the mixin's effect on that element is removed before the new element is set up.
7044 *
7045 * @param {jQuery} $accessKeyed Element that should use the 'accesskeyes' functionality
7046 */
7047 OO.ui.mixin.AccessKeyedElement.prototype.setAccessKeyedElement = function ( $accessKeyed ) {
7048 if ( this.$accessKeyed ) {
7049 this.$accessKeyed.removeAttr( 'accesskey' );
7050 }
7051
7052 this.$accessKeyed = $accessKeyed;
7053 if ( this.accessKey ) {
7054 this.$accessKeyed.attr( 'accesskey', this.accessKey );
7055 }
7056 };
7057
7058 /**
7059 * Set accesskey.
7060 *
7061 * @param {string|Function|null} accesskey Key, a function that returns a key, or `null` for no accesskey
7062 * @chainable
7063 */
7064 OO.ui.mixin.AccessKeyedElement.prototype.setAccessKey = function ( accessKey ) {
7065 accessKey = typeof accessKey === 'string' ? OO.ui.resolveMsg( accessKey ) : null;
7066
7067 if ( this.accessKey !== accessKey ) {
7068 if ( this.$accessKeyed ) {
7069 if ( accessKey !== null ) {
7070 this.$accessKeyed.attr( 'accesskey', accessKey );
7071 } else {
7072 this.$accessKeyed.removeAttr( 'accesskey' );
7073 }
7074 }
7075 this.accessKey = accessKey;
7076 }
7077
7078 return this;
7079 };
7080
7081 /**
7082 * Get accesskey.
7083 *
7084 * @return {string} accessKey string
7085 */
7086 OO.ui.mixin.AccessKeyedElement.prototype.getAccessKey = function () {
7087 return this.accessKey;
7088 };
7089
7090 /**
7091 * Tools, together with {@link OO.ui.ToolGroup toolgroups}, constitute {@link OO.ui.Toolbar toolbars}.
7092 * Each tool is configured with a static name, title, and icon and is customized with the command to carry
7093 * out when the tool is selected. Tools must also be registered with a {@link OO.ui.ToolFactory tool factory},
7094 * which creates the tools on demand.
7095 *
7096 * Tools are added to toolgroups ({@link OO.ui.ListToolGroup ListToolGroup},
7097 * {@link OO.ui.BarToolGroup BarToolGroup}, or {@link OO.ui.MenuToolGroup MenuToolGroup}), which determine how
7098 * the tool is displayed in the toolbar. See {@link OO.ui.Toolbar toolbars} for an example.
7099 *
7100 * For more information, please see the [OOjs UI documentation on MediaWiki][1].
7101 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
7102 *
7103 * @abstract
7104 * @class
7105 * @extends OO.ui.Widget
7106 * @mixins OO.ui.mixin.IconElement
7107 * @mixins OO.ui.mixin.FlaggedElement
7108 * @mixins OO.ui.mixin.TabIndexedElement
7109 *
7110 * @constructor
7111 * @param {OO.ui.ToolGroup} toolGroup
7112 * @param {Object} [config] Configuration options
7113 * @cfg {string|Function} [title] Title text or a function that returns text. If this config is omitted, the value of
7114 * the {@link #static-title static title} property is used.
7115 *
7116 * The title is used in different ways depending on the type of toolgroup that contains the tool. The
7117 * 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
7118 * part of a {@link OO.ui.ListToolGroup list} or {@link OO.ui.MenuToolGroup menu} toolgroup.
7119 *
7120 * For bar toolgroups, a description of the accelerator key is appended to the title if an accelerator key
7121 * is associated with an action by the same name as the tool and accelerator functionality has been added to the application.
7122 * To add accelerator key functionality, you must subclass OO.ui.Toolbar and override the {@link OO.ui.Toolbar#getToolAccelerator getToolAccelerator} method.
7123 */
7124 OO.ui.Tool = function OoUiTool( toolGroup, config ) {
7125 // Allow passing positional parameters inside the config object
7126 if ( OO.isPlainObject( toolGroup ) && config === undefined ) {
7127 config = toolGroup;
7128 toolGroup = config.toolGroup;
7129 }
7130
7131 // Configuration initialization
7132 config = config || {};
7133
7134 // Parent constructor
7135 OO.ui.Tool.parent.call( this, config );
7136
7137 // Properties
7138 this.toolGroup = toolGroup;
7139 this.toolbar = this.toolGroup.getToolbar();
7140 this.active = false;
7141 this.$title = $( '<span>' );
7142 this.$accel = $( '<span>' );
7143 this.$link = $( '<a>' );
7144 this.title = null;
7145
7146 // Mixin constructors
7147 OO.ui.mixin.IconElement.call( this, config );
7148 OO.ui.mixin.FlaggedElement.call( this, config );
7149 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$link } ) );
7150
7151 // Events
7152 this.toolbar.connect( this, { updateState: 'onUpdateState' } );
7153
7154 // Initialization
7155 this.$title.addClass( 'oo-ui-tool-title' );
7156 this.$accel
7157 .addClass( 'oo-ui-tool-accel' )
7158 .prop( {
7159 // This may need to be changed if the key names are ever localized,
7160 // but for now they are essentially written in English
7161 dir: 'ltr',
7162 lang: 'en'
7163 } );
7164 this.$link
7165 .addClass( 'oo-ui-tool-link' )
7166 .append( this.$icon, this.$title, this.$accel )
7167 .attr( 'role', 'button' );
7168 this.$element
7169 .data( 'oo-ui-tool', this )
7170 .addClass(
7171 'oo-ui-tool ' + 'oo-ui-tool-name-' +
7172 this.constructor.static.name.replace( /^([^\/]+)\/([^\/]+).*$/, '$1-$2' )
7173 )
7174 .toggleClass( 'oo-ui-tool-with-label', this.constructor.static.displayBothIconAndLabel )
7175 .append( this.$link );
7176 this.setTitle( config.title || this.constructor.static.title );
7177 };
7178
7179 /* Setup */
7180
7181 OO.inheritClass( OO.ui.Tool, OO.ui.Widget );
7182 OO.mixinClass( OO.ui.Tool, OO.ui.mixin.IconElement );
7183 OO.mixinClass( OO.ui.Tool, OO.ui.mixin.FlaggedElement );
7184 OO.mixinClass( OO.ui.Tool, OO.ui.mixin.TabIndexedElement );
7185
7186 /* Static Properties */
7187
7188 /**
7189 * @static
7190 * @inheritdoc
7191 */
7192 OO.ui.Tool.static.tagName = 'span';
7193
7194 /**
7195 * Symbolic name of tool.
7196 *
7197 * The symbolic name is used internally to register the tool with a {@link OO.ui.ToolFactory ToolFactory}. It can
7198 * also be used when adding tools to toolgroups.
7199 *
7200 * @abstract
7201 * @static
7202 * @inheritable
7203 * @property {string}
7204 */
7205 OO.ui.Tool.static.name = '';
7206
7207 /**
7208 * Symbolic name of the group.
7209 *
7210 * The group name is used to associate tools with each other so that they can be selected later by
7211 * a {@link OO.ui.ToolGroup toolgroup}.
7212 *
7213 * @abstract
7214 * @static
7215 * @inheritable
7216 * @property {string}
7217 */
7218 OO.ui.Tool.static.group = '';
7219
7220 /**
7221 * 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.
7222 *
7223 * @abstract
7224 * @static
7225 * @inheritable
7226 * @property {string|Function}
7227 */
7228 OO.ui.Tool.static.title = '';
7229
7230 /**
7231 * Display both icon and label when the tool is used in a {@link OO.ui.BarToolGroup bar} toolgroup.
7232 * Normally only the icon is displayed, or only the label if no icon is given.
7233 *
7234 * @static
7235 * @inheritable
7236 * @property {boolean}
7237 */
7238 OO.ui.Tool.static.displayBothIconAndLabel = false;
7239
7240 /**
7241 * Add tool to catch-all groups automatically.
7242 *
7243 * A catch-all group, which contains all tools that do not currently belong to a toolgroup,
7244 * can be included in a toolgroup using the wildcard selector, an asterisk (*).
7245 *
7246 * @static
7247 * @inheritable
7248 * @property {boolean}
7249 */
7250 OO.ui.Tool.static.autoAddToCatchall = true;
7251
7252 /**
7253 * Add tool to named groups automatically.
7254 *
7255 * By default, tools that are configured with a static ‘group’ property are added
7256 * to that group and will be selected when the symbolic name of the group is specified (e.g., when
7257 * toolgroups include tools by group name).
7258 *
7259 * @static
7260 * @property {boolean}
7261 * @inheritable
7262 */
7263 OO.ui.Tool.static.autoAddToGroup = true;
7264
7265 /**
7266 * Check if this tool is compatible with given data.
7267 *
7268 * This is a stub that can be overriden to provide support for filtering tools based on an
7269 * arbitrary piece of information (e.g., where the cursor is in a document). The implementation
7270 * must also call this method so that the compatibility check can be performed.
7271 *
7272 * @static
7273 * @inheritable
7274 * @param {Mixed} data Data to check
7275 * @return {boolean} Tool can be used with data
7276 */
7277 OO.ui.Tool.static.isCompatibleWith = function () {
7278 return false;
7279 };
7280
7281 /* Methods */
7282
7283 /**
7284 * Handle the toolbar state being updated.
7285 *
7286 * This is an abstract method that must be overridden in a concrete subclass.
7287 *
7288 * @protected
7289 * @abstract
7290 */
7291 OO.ui.Tool.prototype.onUpdateState = function () {
7292 throw new Error(
7293 'OO.ui.Tool.onUpdateState not implemented in this subclass:' + this.constructor
7294 );
7295 };
7296
7297 /**
7298 * Handle the tool being selected.
7299 *
7300 * This is an abstract method that must be overridden in a concrete subclass.
7301 *
7302 * @protected
7303 * @abstract
7304 */
7305 OO.ui.Tool.prototype.onSelect = function () {
7306 throw new Error(
7307 'OO.ui.Tool.onSelect not implemented in this subclass:' + this.constructor
7308 );
7309 };
7310
7311 /**
7312 * Check if the tool is active.
7313 *
7314 * Tools become active when their #onSelect or #onUpdateState handlers change them to appear pressed
7315 * with the #setActive method. Additional CSS is applied to the tool to reflect the active state.
7316 *
7317 * @return {boolean} Tool is active
7318 */
7319 OO.ui.Tool.prototype.isActive = function () {
7320 return this.active;
7321 };
7322
7323 /**
7324 * Make the tool appear active or inactive.
7325 *
7326 * This method should be called within #onSelect or #onUpdateState event handlers to make the tool
7327 * appear pressed or not.
7328 *
7329 * @param {boolean} state Make tool appear active
7330 */
7331 OO.ui.Tool.prototype.setActive = function ( state ) {
7332 this.active = !!state;
7333 if ( this.active ) {
7334 this.$element.addClass( 'oo-ui-tool-active' );
7335 } else {
7336 this.$element.removeClass( 'oo-ui-tool-active' );
7337 }
7338 };
7339
7340 /**
7341 * Set the tool #title.
7342 *
7343 * @param {string|Function} title Title text or a function that returns text
7344 * @chainable
7345 */
7346 OO.ui.Tool.prototype.setTitle = function ( title ) {
7347 this.title = OO.ui.resolveMsg( title );
7348 this.updateTitle();
7349 return this;
7350 };
7351
7352 /**
7353 * Get the tool #title.
7354 *
7355 * @return {string} Title text
7356 */
7357 OO.ui.Tool.prototype.getTitle = function () {
7358 return this.title;
7359 };
7360
7361 /**
7362 * Get the tool's symbolic name.
7363 *
7364 * @return {string} Symbolic name of tool
7365 */
7366 OO.ui.Tool.prototype.getName = function () {
7367 return this.constructor.static.name;
7368 };
7369
7370 /**
7371 * Update the title.
7372 */
7373 OO.ui.Tool.prototype.updateTitle = function () {
7374 var titleTooltips = this.toolGroup.constructor.static.titleTooltips,
7375 accelTooltips = this.toolGroup.constructor.static.accelTooltips,
7376 accel = this.toolbar.getToolAccelerator( this.constructor.static.name ),
7377 tooltipParts = [];
7378
7379 this.$title.text( this.title );
7380 this.$accel.text( accel );
7381
7382 if ( titleTooltips && typeof this.title === 'string' && this.title.length ) {
7383 tooltipParts.push( this.title );
7384 }
7385 if ( accelTooltips && typeof accel === 'string' && accel.length ) {
7386 tooltipParts.push( accel );
7387 }
7388 if ( tooltipParts.length ) {
7389 this.$link.attr( 'title', tooltipParts.join( ' ' ) );
7390 } else {
7391 this.$link.removeAttr( 'title' );
7392 }
7393 };
7394
7395 /**
7396 * Destroy tool.
7397 *
7398 * Destroying the tool removes all event handlers and the tool’s DOM elements.
7399 * Call this method whenever you are done using a tool.
7400 */
7401 OO.ui.Tool.prototype.destroy = function () {
7402 this.toolbar.disconnect( this );
7403 this.$element.remove();
7404 };
7405
7406 /**
7407 * Toolbars are complex interface components that permit users to easily access a variety
7408 * of {@link OO.ui.Tool tools} (e.g., formatting commands) and actions, which are additional commands that are
7409 * part of the toolbar, but not configured as tools.
7410 *
7411 * Individual tools are customized and then registered with a {@link OO.ui.ToolFactory tool factory}, which creates
7412 * the tools on demand. Each tool has a symbolic name (used when registering the tool), a title (e.g., ‘Insert
7413 * picture’), and an icon.
7414 *
7415 * Individual tools are organized in {@link OO.ui.ToolGroup toolgroups}, which can be {@link OO.ui.MenuToolGroup menus}
7416 * of tools, {@link OO.ui.ListToolGroup lists} of tools, or a single {@link OO.ui.BarToolGroup bar} of tools.
7417 * The arrangement and order of the toolgroups is customized when the toolbar is set up. Tools can be presented in
7418 * any order, but each can only appear once in the toolbar.
7419 *
7420 * The following is an example of a basic toolbar.
7421 *
7422 * @example
7423 * // Example of a toolbar
7424 * // Create the toolbar
7425 * var toolFactory = new OO.ui.ToolFactory();
7426 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
7427 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
7428 *
7429 * // We will be placing status text in this element when tools are used
7430 * var $area = $( '<p>' ).text( 'Toolbar example' );
7431 *
7432 * // Define the tools that we're going to place in our toolbar
7433 *
7434 * // Create a class inheriting from OO.ui.Tool
7435 * function PictureTool() {
7436 * PictureTool.parent.apply( this, arguments );
7437 * }
7438 * OO.inheritClass( PictureTool, OO.ui.Tool );
7439 * // Each tool must have a 'name' (used as an internal identifier, see later) and at least one
7440 * // of 'icon' and 'title' (displayed icon and text).
7441 * PictureTool.static.name = 'picture';
7442 * PictureTool.static.icon = 'picture';
7443 * PictureTool.static.title = 'Insert picture';
7444 * // Defines the action that will happen when this tool is selected (clicked).
7445 * PictureTool.prototype.onSelect = function () {
7446 * $area.text( 'Picture tool clicked!' );
7447 * // Never display this tool as "active" (selected).
7448 * this.setActive( false );
7449 * };
7450 * // Make this tool available in our toolFactory and thus our toolbar
7451 * toolFactory.register( PictureTool );
7452 *
7453 * // Register two more tools, nothing interesting here
7454 * function SettingsTool() {
7455 * SettingsTool.parent.apply( this, arguments );
7456 * }
7457 * OO.inheritClass( SettingsTool, OO.ui.Tool );
7458 * SettingsTool.static.name = 'settings';
7459 * SettingsTool.static.icon = 'settings';
7460 * SettingsTool.static.title = 'Change settings';
7461 * SettingsTool.prototype.onSelect = function () {
7462 * $area.text( 'Settings tool clicked!' );
7463 * this.setActive( false );
7464 * };
7465 * toolFactory.register( SettingsTool );
7466 *
7467 * // Register two more tools, nothing interesting here
7468 * function StuffTool() {
7469 * StuffTool.parent.apply( this, arguments );
7470 * }
7471 * OO.inheritClass( StuffTool, OO.ui.Tool );
7472 * StuffTool.static.name = 'stuff';
7473 * StuffTool.static.icon = 'ellipsis';
7474 * StuffTool.static.title = 'More stuff';
7475 * StuffTool.prototype.onSelect = function () {
7476 * $area.text( 'More stuff tool clicked!' );
7477 * this.setActive( false );
7478 * };
7479 * toolFactory.register( StuffTool );
7480 *
7481 * // This is a PopupTool. Rather than having a custom 'onSelect' action, it will display a
7482 * // little popup window (a PopupWidget).
7483 * function HelpTool( toolGroup, config ) {
7484 * OO.ui.PopupTool.call( this, toolGroup, $.extend( { popup: {
7485 * padded: true,
7486 * label: 'Help',
7487 * head: true
7488 * } }, config ) );
7489 * this.popup.$body.append( '<p>I am helpful!</p>' );
7490 * }
7491 * OO.inheritClass( HelpTool, OO.ui.PopupTool );
7492 * HelpTool.static.name = 'help';
7493 * HelpTool.static.icon = 'help';
7494 * HelpTool.static.title = 'Help';
7495 * toolFactory.register( HelpTool );
7496 *
7497 * // Finally define which tools and in what order appear in the toolbar. Each tool may only be
7498 * // used once (but not all defined tools must be used).
7499 * toolbar.setup( [
7500 * {
7501 * // 'bar' tool groups display tools' icons only, side-by-side.
7502 * type: 'bar',
7503 * include: [ 'picture', 'help' ]
7504 * },
7505 * {
7506 * // 'list' tool groups display both the titles and icons, in a dropdown list.
7507 * type: 'list',
7508 * indicator: 'down',
7509 * label: 'More',
7510 * include: [ 'settings', 'stuff' ]
7511 * }
7512 * // Note how the tools themselves are toolgroup-agnostic - the same tool can be displayed
7513 * // either in a 'list' or a 'bar'. There is a 'menu' tool group too, not showcased here,
7514 * // since it's more complicated to use. (See the next example snippet on this page.)
7515 * ] );
7516 *
7517 * // Create some UI around the toolbar and place it in the document
7518 * var frame = new OO.ui.PanelLayout( {
7519 * expanded: false,
7520 * framed: true
7521 * } );
7522 * var contentFrame = new OO.ui.PanelLayout( {
7523 * expanded: false,
7524 * padded: true
7525 * } );
7526 * frame.$element.append(
7527 * toolbar.$element,
7528 * contentFrame.$element.append( $area )
7529 * );
7530 * $( 'body' ).append( frame.$element );
7531 *
7532 * // Here is where the toolbar is actually built. This must be done after inserting it into the
7533 * // document.
7534 * toolbar.initialize();
7535 *
7536 * The following example extends the previous one to illustrate 'menu' toolgroups and the usage of
7537 * 'updateState' event.
7538 *
7539 * @example
7540 * // Create the toolbar
7541 * var toolFactory = new OO.ui.ToolFactory();
7542 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
7543 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
7544 *
7545 * // We will be placing status text in this element when tools are used
7546 * var $area = $( '<p>' ).text( 'Toolbar example' );
7547 *
7548 * // Define the tools that we're going to place in our toolbar
7549 *
7550 * // Create a class inheriting from OO.ui.Tool
7551 * function PictureTool() {
7552 * PictureTool.parent.apply( this, arguments );
7553 * }
7554 * OO.inheritClass( PictureTool, OO.ui.Tool );
7555 * // Each tool must have a 'name' (used as an internal identifier, see later) and at least one
7556 * // of 'icon' and 'title' (displayed icon and text).
7557 * PictureTool.static.name = 'picture';
7558 * PictureTool.static.icon = 'picture';
7559 * PictureTool.static.title = 'Insert picture';
7560 * // Defines the action that will happen when this tool is selected (clicked).
7561 * PictureTool.prototype.onSelect = function () {
7562 * $area.text( 'Picture tool clicked!' );
7563 * // Never display this tool as "active" (selected).
7564 * this.setActive( false );
7565 * };
7566 * // The toolbar can be synchronized with the state of some external stuff, like a text
7567 * // editor's editing area, highlighting the tools (e.g. a 'bold' tool would be shown as active
7568 * // when the text cursor was inside bolded text). Here we simply disable this feature.
7569 * PictureTool.prototype.onUpdateState = function () {
7570 * };
7571 * // Make this tool available in our toolFactory and thus our toolbar
7572 * toolFactory.register( PictureTool );
7573 *
7574 * // Register two more tools, nothing interesting here
7575 * function SettingsTool() {
7576 * SettingsTool.parent.apply( this, arguments );
7577 * this.reallyActive = false;
7578 * }
7579 * OO.inheritClass( SettingsTool, OO.ui.Tool );
7580 * SettingsTool.static.name = 'settings';
7581 * SettingsTool.static.icon = 'settings';
7582 * SettingsTool.static.title = 'Change settings';
7583 * SettingsTool.prototype.onSelect = function () {
7584 * $area.text( 'Settings tool clicked!' );
7585 * // Toggle the active state on each click
7586 * this.reallyActive = !this.reallyActive;
7587 * this.setActive( this.reallyActive );
7588 * // To update the menu label
7589 * this.toolbar.emit( 'updateState' );
7590 * };
7591 * SettingsTool.prototype.onUpdateState = function () {
7592 * };
7593 * toolFactory.register( SettingsTool );
7594 *
7595 * // Register two more tools, nothing interesting here
7596 * function StuffTool() {
7597 * StuffTool.parent.apply( this, arguments );
7598 * this.reallyActive = false;
7599 * }
7600 * OO.inheritClass( StuffTool, OO.ui.Tool );
7601 * StuffTool.static.name = 'stuff';
7602 * StuffTool.static.icon = 'ellipsis';
7603 * StuffTool.static.title = 'More stuff';
7604 * StuffTool.prototype.onSelect = function () {
7605 * $area.text( 'More stuff tool clicked!' );
7606 * // Toggle the active state on each click
7607 * this.reallyActive = !this.reallyActive;
7608 * this.setActive( this.reallyActive );
7609 * // To update the menu label
7610 * this.toolbar.emit( 'updateState' );
7611 * };
7612 * StuffTool.prototype.onUpdateState = function () {
7613 * };
7614 * toolFactory.register( StuffTool );
7615 *
7616 * // This is a PopupTool. Rather than having a custom 'onSelect' action, it will display a
7617 * // little popup window (a PopupWidget). 'onUpdateState' is also already implemented.
7618 * function HelpTool( toolGroup, config ) {
7619 * OO.ui.PopupTool.call( this, toolGroup, $.extend( { popup: {
7620 * padded: true,
7621 * label: 'Help',
7622 * head: true
7623 * } }, config ) );
7624 * this.popup.$body.append( '<p>I am helpful!</p>' );
7625 * }
7626 * OO.inheritClass( HelpTool, OO.ui.PopupTool );
7627 * HelpTool.static.name = 'help';
7628 * HelpTool.static.icon = 'help';
7629 * HelpTool.static.title = 'Help';
7630 * toolFactory.register( HelpTool );
7631 *
7632 * // Finally define which tools and in what order appear in the toolbar. Each tool may only be
7633 * // used once (but not all defined tools must be used).
7634 * toolbar.setup( [
7635 * {
7636 * // 'bar' tool groups display tools' icons only, side-by-side.
7637 * type: 'bar',
7638 * include: [ 'picture', 'help' ]
7639 * },
7640 * {
7641 * // 'menu' tool groups display both the titles and icons, in a dropdown menu.
7642 * // Menu label indicates which items are selected.
7643 * type: 'menu',
7644 * indicator: 'down',
7645 * include: [ 'settings', 'stuff' ]
7646 * }
7647 * ] );
7648 *
7649 * // Create some UI around the toolbar and place it in the document
7650 * var frame = new OO.ui.PanelLayout( {
7651 * expanded: false,
7652 * framed: true
7653 * } );
7654 * var contentFrame = new OO.ui.PanelLayout( {
7655 * expanded: false,
7656 * padded: true
7657 * } );
7658 * frame.$element.append(
7659 * toolbar.$element,
7660 * contentFrame.$element.append( $area )
7661 * );
7662 * $( 'body' ).append( frame.$element );
7663 *
7664 * // Here is where the toolbar is actually built. This must be done after inserting it into the
7665 * // document.
7666 * toolbar.initialize();
7667 * toolbar.emit( 'updateState' );
7668 *
7669 * @class
7670 * @extends OO.ui.Element
7671 * @mixins OO.EventEmitter
7672 * @mixins OO.ui.mixin.GroupElement
7673 *
7674 * @constructor
7675 * @param {OO.ui.ToolFactory} toolFactory Factory for creating tools
7676 * @param {OO.ui.ToolGroupFactory} toolGroupFactory Factory for creating toolgroups
7677 * @param {Object} [config] Configuration options
7678 * @cfg {boolean} [actions] Add an actions section to the toolbar. Actions are commands that are included
7679 * in the toolbar, but are not configured as tools. By default, actions are displayed on the right side of
7680 * the toolbar.
7681 * @cfg {boolean} [shadow] Add a shadow below the toolbar.
7682 */
7683 OO.ui.Toolbar = function OoUiToolbar( toolFactory, toolGroupFactory, config ) {
7684 // Allow passing positional parameters inside the config object
7685 if ( OO.isPlainObject( toolFactory ) && config === undefined ) {
7686 config = toolFactory;
7687 toolFactory = config.toolFactory;
7688 toolGroupFactory = config.toolGroupFactory;
7689 }
7690
7691 // Configuration initialization
7692 config = config || {};
7693
7694 // Parent constructor
7695 OO.ui.Toolbar.parent.call( this, config );
7696
7697 // Mixin constructors
7698 OO.EventEmitter.call( this );
7699 OO.ui.mixin.GroupElement.call( this, config );
7700
7701 // Properties
7702 this.toolFactory = toolFactory;
7703 this.toolGroupFactory = toolGroupFactory;
7704 this.groups = [];
7705 this.tools = {};
7706 this.$bar = $( '<div>' );
7707 this.$actions = $( '<div>' );
7708 this.initialized = false;
7709 this.onWindowResizeHandler = this.onWindowResize.bind( this );
7710
7711 // Events
7712 this.$element
7713 .add( this.$bar ).add( this.$group ).add( this.$actions )
7714 .on( 'mousedown keydown', this.onPointerDown.bind( this ) );
7715
7716 // Initialization
7717 this.$group.addClass( 'oo-ui-toolbar-tools' );
7718 if ( config.actions ) {
7719 this.$bar.append( this.$actions.addClass( 'oo-ui-toolbar-actions' ) );
7720 }
7721 this.$bar
7722 .addClass( 'oo-ui-toolbar-bar' )
7723 .append( this.$group, '<div style="clear:both"></div>' );
7724 if ( config.shadow ) {
7725 this.$bar.append( '<div class="oo-ui-toolbar-shadow"></div>' );
7726 }
7727 this.$element.addClass( 'oo-ui-toolbar' ).append( this.$bar );
7728 };
7729
7730 /* Setup */
7731
7732 OO.inheritClass( OO.ui.Toolbar, OO.ui.Element );
7733 OO.mixinClass( OO.ui.Toolbar, OO.EventEmitter );
7734 OO.mixinClass( OO.ui.Toolbar, OO.ui.mixin.GroupElement );
7735
7736 /* Methods */
7737
7738 /**
7739 * Get the tool factory.
7740 *
7741 * @return {OO.ui.ToolFactory} Tool factory
7742 */
7743 OO.ui.Toolbar.prototype.getToolFactory = function () {
7744 return this.toolFactory;
7745 };
7746
7747 /**
7748 * Get the toolgroup factory.
7749 *
7750 * @return {OO.Factory} Toolgroup factory
7751 */
7752 OO.ui.Toolbar.prototype.getToolGroupFactory = function () {
7753 return this.toolGroupFactory;
7754 };
7755
7756 /**
7757 * Handles mouse down events.
7758 *
7759 * @private
7760 * @param {jQuery.Event} e Mouse down event
7761 */
7762 OO.ui.Toolbar.prototype.onPointerDown = function ( e ) {
7763 var $closestWidgetToEvent = $( e.target ).closest( '.oo-ui-widget' ),
7764 $closestWidgetToToolbar = this.$element.closest( '.oo-ui-widget' );
7765 if ( !$closestWidgetToEvent.length || $closestWidgetToEvent[ 0 ] === $closestWidgetToToolbar[ 0 ] ) {
7766 return false;
7767 }
7768 };
7769
7770 /**
7771 * Handle window resize event.
7772 *
7773 * @private
7774 * @param {jQuery.Event} e Window resize event
7775 */
7776 OO.ui.Toolbar.prototype.onWindowResize = function () {
7777 this.$element.toggleClass(
7778 'oo-ui-toolbar-narrow',
7779 this.$bar.width() <= this.narrowThreshold
7780 );
7781 };
7782
7783 /**
7784 * Sets up handles and preloads required information for the toolbar to work.
7785 * This must be called after it is attached to a visible document and before doing anything else.
7786 */
7787 OO.ui.Toolbar.prototype.initialize = function () {
7788 if ( !this.initialized ) {
7789 this.initialized = true;
7790 this.narrowThreshold = this.$group.width() + this.$actions.width();
7791 $( this.getElementWindow() ).on( 'resize', this.onWindowResizeHandler );
7792 this.onWindowResize();
7793 }
7794 };
7795
7796 /**
7797 * Set up the toolbar.
7798 *
7799 * The toolbar is set up with a list of toolgroup configurations that specify the type of
7800 * toolgroup ({@link OO.ui.BarToolGroup bar}, {@link OO.ui.MenuToolGroup menu}, or {@link OO.ui.ListToolGroup list})
7801 * to add and which tools to include, exclude, promote, or demote within that toolgroup. Please
7802 * see {@link OO.ui.ToolGroup toolgroups} for more information about including tools in toolgroups.
7803 *
7804 * @param {Object.<string,Array>} groups List of toolgroup configurations
7805 * @param {Array|string} [groups.include] Tools to include in the toolgroup
7806 * @param {Array|string} [groups.exclude] Tools to exclude from the toolgroup
7807 * @param {Array|string} [groups.promote] Tools to promote to the beginning of the toolgroup
7808 * @param {Array|string} [groups.demote] Tools to demote to the end of the toolgroup
7809 */
7810 OO.ui.Toolbar.prototype.setup = function ( groups ) {
7811 var i, len, type, group,
7812 items = [],
7813 defaultType = 'bar';
7814
7815 // Cleanup previous groups
7816 this.reset();
7817
7818 // Build out new groups
7819 for ( i = 0, len = groups.length; i < len; i++ ) {
7820 group = groups[ i ];
7821 if ( group.include === '*' ) {
7822 // Apply defaults to catch-all groups
7823 if ( group.type === undefined ) {
7824 group.type = 'list';
7825 }
7826 if ( group.label === undefined ) {
7827 group.label = OO.ui.msg( 'ooui-toolbar-more' );
7828 }
7829 }
7830 // Check type has been registered
7831 type = this.getToolGroupFactory().lookup( group.type ) ? group.type : defaultType;
7832 items.push(
7833 this.getToolGroupFactory().create( type, this, group )
7834 );
7835 }
7836 this.addItems( items );
7837 };
7838
7839 /**
7840 * Remove all tools and toolgroups from the toolbar.
7841 */
7842 OO.ui.Toolbar.prototype.reset = function () {
7843 var i, len;
7844
7845 this.groups = [];
7846 this.tools = {};
7847 for ( i = 0, len = this.items.length; i < len; i++ ) {
7848 this.items[ i ].destroy();
7849 }
7850 this.clearItems();
7851 };
7852
7853 /**
7854 * Destroy the toolbar.
7855 *
7856 * Destroying the toolbar removes all event handlers and DOM elements that constitute the toolbar. Call
7857 * this method whenever you are done using a toolbar.
7858 */
7859 OO.ui.Toolbar.prototype.destroy = function () {
7860 $( this.getElementWindow() ).off( 'resize', this.onWindowResizeHandler );
7861 this.reset();
7862 this.$element.remove();
7863 };
7864
7865 /**
7866 * Check if the tool is available.
7867 *
7868 * Available tools are ones that have not yet been added to the toolbar.
7869 *
7870 * @param {string} name Symbolic name of tool
7871 * @return {boolean} Tool is available
7872 */
7873 OO.ui.Toolbar.prototype.isToolAvailable = function ( name ) {
7874 return !this.tools[ name ];
7875 };
7876
7877 /**
7878 * Prevent tool from being used again.
7879 *
7880 * @param {OO.ui.Tool} tool Tool to reserve
7881 */
7882 OO.ui.Toolbar.prototype.reserveTool = function ( tool ) {
7883 this.tools[ tool.getName() ] = tool;
7884 };
7885
7886 /**
7887 * Allow tool to be used again.
7888 *
7889 * @param {OO.ui.Tool} tool Tool to release
7890 */
7891 OO.ui.Toolbar.prototype.releaseTool = function ( tool ) {
7892 delete this.tools[ tool.getName() ];
7893 };
7894
7895 /**
7896 * Get accelerator label for tool.
7897 *
7898 * The OOjs UI library does not contain an accelerator system, but this is the hook for one. To
7899 * use an accelerator system, subclass the toolbar and override this method, which is meant to return a label
7900 * that describes the accelerator keys for the tool passed (by symbolic name) to the method.
7901 *
7902 * @param {string} name Symbolic name of tool
7903 * @return {string|undefined} Tool accelerator label if available
7904 */
7905 OO.ui.Toolbar.prototype.getToolAccelerator = function () {
7906 return undefined;
7907 };
7908
7909 /**
7910 * ToolGroups are collections of {@link OO.ui.Tool tools} that are used in a {@link OO.ui.Toolbar toolbar}.
7911 * The type of toolgroup ({@link OO.ui.ListToolGroup list}, {@link OO.ui.BarToolGroup bar}, or {@link OO.ui.MenuToolGroup menu})
7912 * to which a tool belongs determines how the tool is arranged and displayed in the toolbar. Toolgroups
7913 * themselves are created on demand with a {@link OO.ui.ToolGroupFactory toolgroup factory}.
7914 *
7915 * Toolgroups can contain individual tools, groups of tools, or all available tools:
7916 *
7917 * To include an individual tool (or array of individual tools), specify tools by symbolic name:
7918 *
7919 * include: [ 'tool-name' ] or [ { name: 'tool-name' }]
7920 *
7921 * 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.)
7922 *
7923 * include: [ { group: 'group-name' } ]
7924 *
7925 * To include all tools that are not yet assigned to a toolgroup, use the catch-all selector, an asterisk (*):
7926 *
7927 * include: '*'
7928 *
7929 * See {@link OO.ui.Toolbar toolbars} for a full example. For more information about toolbars in general,
7930 * please see the [OOjs UI documentation on MediaWiki][1].
7931 *
7932 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
7933 *
7934 * @abstract
7935 * @class
7936 * @extends OO.ui.Widget
7937 * @mixins OO.ui.mixin.GroupElement
7938 *
7939 * @constructor
7940 * @param {OO.ui.Toolbar} toolbar
7941 * @param {Object} [config] Configuration options
7942 * @cfg {Array|string} [include=[]] List of tools to include in the toolgroup.
7943 * @cfg {Array|string} [exclude=[]] List of tools to exclude from the toolgroup.
7944 * @cfg {Array|string} [promote=[]] List of tools to promote to the beginning of the toolgroup.
7945 * @cfg {Array|string} [demote=[]] List of tools to demote to the end of the toolgroup.
7946 * This setting is particularly useful when tools have been added to the toolgroup
7947 * en masse (e.g., via the catch-all selector).
7948 */
7949 OO.ui.ToolGroup = function OoUiToolGroup( toolbar, config ) {
7950 // Allow passing positional parameters inside the config object
7951 if ( OO.isPlainObject( toolbar ) && config === undefined ) {
7952 config = toolbar;
7953 toolbar = config.toolbar;
7954 }
7955
7956 // Configuration initialization
7957 config = config || {};
7958
7959 // Parent constructor
7960 OO.ui.ToolGroup.parent.call( this, config );
7961
7962 // Mixin constructors
7963 OO.ui.mixin.GroupElement.call( this, config );
7964
7965 // Properties
7966 this.toolbar = toolbar;
7967 this.tools = {};
7968 this.pressed = null;
7969 this.autoDisabled = false;
7970 this.include = config.include || [];
7971 this.exclude = config.exclude || [];
7972 this.promote = config.promote || [];
7973 this.demote = config.demote || [];
7974 this.onCapturedMouseKeyUpHandler = this.onCapturedMouseKeyUp.bind( this );
7975
7976 // Events
7977 this.$element.on( {
7978 mousedown: this.onMouseKeyDown.bind( this ),
7979 mouseup: this.onMouseKeyUp.bind( this ),
7980 keydown: this.onMouseKeyDown.bind( this ),
7981 keyup: this.onMouseKeyUp.bind( this ),
7982 focus: this.onMouseOverFocus.bind( this ),
7983 blur: this.onMouseOutBlur.bind( this ),
7984 mouseover: this.onMouseOverFocus.bind( this ),
7985 mouseout: this.onMouseOutBlur.bind( this )
7986 } );
7987 this.toolbar.getToolFactory().connect( this, { register: 'onToolFactoryRegister' } );
7988 this.aggregate( { disable: 'itemDisable' } );
7989 this.connect( this, { itemDisable: 'updateDisabled' } );
7990
7991 // Initialization
7992 this.$group.addClass( 'oo-ui-toolGroup-tools' );
7993 this.$element
7994 .addClass( 'oo-ui-toolGroup' )
7995 .append( this.$group );
7996 this.populate();
7997 };
7998
7999 /* Setup */
8000
8001 OO.inheritClass( OO.ui.ToolGroup, OO.ui.Widget );
8002 OO.mixinClass( OO.ui.ToolGroup, OO.ui.mixin.GroupElement );
8003
8004 /* Events */
8005
8006 /**
8007 * @event update
8008 */
8009
8010 /* Static Properties */
8011
8012 /**
8013 * Show labels in tooltips.
8014 *
8015 * @static
8016 * @inheritable
8017 * @property {boolean}
8018 */
8019 OO.ui.ToolGroup.static.titleTooltips = false;
8020
8021 /**
8022 * Show acceleration labels in tooltips.
8023 *
8024 * Note: The OOjs UI library does not include an accelerator system, but does contain
8025 * a hook for one. To use an accelerator system, subclass the {@link OO.ui.Toolbar toolbar} and
8026 * override the {@link OO.ui.Toolbar#getToolAccelerator getToolAccelerator} method, which is
8027 * meant to return a label that describes the accelerator keys for a given tool (e.g., 'Ctrl + M').
8028 *
8029 * @static
8030 * @inheritable
8031 * @property {boolean}
8032 */
8033 OO.ui.ToolGroup.static.accelTooltips = false;
8034
8035 /**
8036 * Automatically disable the toolgroup when all tools are disabled
8037 *
8038 * @static
8039 * @inheritable
8040 * @property {boolean}
8041 */
8042 OO.ui.ToolGroup.static.autoDisable = true;
8043
8044 /* Methods */
8045
8046 /**
8047 * @inheritdoc
8048 */
8049 OO.ui.ToolGroup.prototype.isDisabled = function () {
8050 return this.autoDisabled || OO.ui.ToolGroup.parent.prototype.isDisabled.apply( this, arguments );
8051 };
8052
8053 /**
8054 * @inheritdoc
8055 */
8056 OO.ui.ToolGroup.prototype.updateDisabled = function () {
8057 var i, item, allDisabled = true;
8058
8059 if ( this.constructor.static.autoDisable ) {
8060 for ( i = this.items.length - 1; i >= 0; i-- ) {
8061 item = this.items[ i ];
8062 if ( !item.isDisabled() ) {
8063 allDisabled = false;
8064 break;
8065 }
8066 }
8067 this.autoDisabled = allDisabled;
8068 }
8069 OO.ui.ToolGroup.parent.prototype.updateDisabled.apply( this, arguments );
8070 };
8071
8072 /**
8073 * Handle mouse down and key down events.
8074 *
8075 * @protected
8076 * @param {jQuery.Event} e Mouse down or key down event
8077 */
8078 OO.ui.ToolGroup.prototype.onMouseKeyDown = function ( e ) {
8079 if (
8080 !this.isDisabled() &&
8081 ( e.which === 1 || e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
8082 ) {
8083 this.pressed = this.getTargetTool( e );
8084 if ( this.pressed ) {
8085 this.pressed.setActive( true );
8086 OO.ui.addCaptureEventListener( this.getElementDocument(), 'mouseup', this.onCapturedMouseKeyUpHandler );
8087 OO.ui.addCaptureEventListener( this.getElementDocument(), 'keyup', this.onCapturedMouseKeyUpHandler );
8088 }
8089 return false;
8090 }
8091 };
8092
8093 /**
8094 * Handle captured mouse up and key up events.
8095 *
8096 * @protected
8097 * @param {Event} e Mouse up or key up event
8098 */
8099 OO.ui.ToolGroup.prototype.onCapturedMouseKeyUp = function ( e ) {
8100 OO.ui.removeCaptureEventListener( this.getElementDocument(), 'mouseup', this.onCapturedMouseKeyUpHandler );
8101 OO.ui.removeCaptureEventListener( this.getElementDocument(), 'keyup', this.onCapturedMouseKeyUpHandler );
8102 // onMouseKeyUp may be called a second time, depending on where the mouse is when the button is
8103 // released, but since `this.pressed` will no longer be true, the second call will be ignored.
8104 this.onMouseKeyUp( e );
8105 };
8106
8107 /**
8108 * Handle mouse up and key up events.
8109 *
8110 * @protected
8111 * @param {jQuery.Event} e Mouse up or key up event
8112 */
8113 OO.ui.ToolGroup.prototype.onMouseKeyUp = function ( e ) {
8114 var tool = this.getTargetTool( e );
8115
8116 if (
8117 !this.isDisabled() && this.pressed && this.pressed === tool &&
8118 ( e.which === 1 || e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
8119 ) {
8120 this.pressed.onSelect();
8121 this.pressed = null;
8122 return false;
8123 }
8124
8125 this.pressed = null;
8126 };
8127
8128 /**
8129 * Handle mouse over and focus events.
8130 *
8131 * @protected
8132 * @param {jQuery.Event} e Mouse over or focus event
8133 */
8134 OO.ui.ToolGroup.prototype.onMouseOverFocus = function ( e ) {
8135 var tool = this.getTargetTool( e );
8136
8137 if ( this.pressed && this.pressed === tool ) {
8138 this.pressed.setActive( true );
8139 }
8140 };
8141
8142 /**
8143 * Handle mouse out and blur events.
8144 *
8145 * @protected
8146 * @param {jQuery.Event} e Mouse out or blur event
8147 */
8148 OO.ui.ToolGroup.prototype.onMouseOutBlur = function ( e ) {
8149 var tool = this.getTargetTool( e );
8150
8151 if ( this.pressed && this.pressed === tool ) {
8152 this.pressed.setActive( false );
8153 }
8154 };
8155
8156 /**
8157 * Get the closest tool to a jQuery.Event.
8158 *
8159 * Only tool links are considered, which prevents other elements in the tool such as popups from
8160 * triggering tool group interactions.
8161 *
8162 * @private
8163 * @param {jQuery.Event} e
8164 * @return {OO.ui.Tool|null} Tool, `null` if none was found
8165 */
8166 OO.ui.ToolGroup.prototype.getTargetTool = function ( e ) {
8167 var tool,
8168 $item = $( e.target ).closest( '.oo-ui-tool-link' );
8169
8170 if ( $item.length ) {
8171 tool = $item.parent().data( 'oo-ui-tool' );
8172 }
8173
8174 return tool && !tool.isDisabled() ? tool : null;
8175 };
8176
8177 /**
8178 * Handle tool registry register events.
8179 *
8180 * If a tool is registered after the group is created, we must repopulate the list to account for:
8181 *
8182 * - a tool being added that may be included
8183 * - a tool already included being overridden
8184 *
8185 * @protected
8186 * @param {string} name Symbolic name of tool
8187 */
8188 OO.ui.ToolGroup.prototype.onToolFactoryRegister = function () {
8189 this.populate();
8190 };
8191
8192 /**
8193 * Get the toolbar that contains the toolgroup.
8194 *
8195 * @return {OO.ui.Toolbar} Toolbar that contains the toolgroup
8196 */
8197 OO.ui.ToolGroup.prototype.getToolbar = function () {
8198 return this.toolbar;
8199 };
8200
8201 /**
8202 * Add and remove tools based on configuration.
8203 */
8204 OO.ui.ToolGroup.prototype.populate = function () {
8205 var i, len, name, tool,
8206 toolFactory = this.toolbar.getToolFactory(),
8207 names = {},
8208 add = [],
8209 remove = [],
8210 list = this.toolbar.getToolFactory().getTools(
8211 this.include, this.exclude, this.promote, this.demote
8212 );
8213
8214 // Build a list of needed tools
8215 for ( i = 0, len = list.length; i < len; i++ ) {
8216 name = list[ i ];
8217 if (
8218 // Tool exists
8219 toolFactory.lookup( name ) &&
8220 // Tool is available or is already in this group
8221 ( this.toolbar.isToolAvailable( name ) || this.tools[ name ] )
8222 ) {
8223 // Hack to prevent infinite recursion via ToolGroupTool. We need to reserve the tool before
8224 // creating it, but we can't call reserveTool() yet because we haven't created the tool.
8225 this.toolbar.tools[ name ] = true;
8226 tool = this.tools[ name ];
8227 if ( !tool ) {
8228 // Auto-initialize tools on first use
8229 this.tools[ name ] = tool = toolFactory.create( name, this );
8230 tool.updateTitle();
8231 }
8232 this.toolbar.reserveTool( tool );
8233 add.push( tool );
8234 names[ name ] = true;
8235 }
8236 }
8237 // Remove tools that are no longer needed
8238 for ( name in this.tools ) {
8239 if ( !names[ name ] ) {
8240 this.tools[ name ].destroy();
8241 this.toolbar.releaseTool( this.tools[ name ] );
8242 remove.push( this.tools[ name ] );
8243 delete this.tools[ name ];
8244 }
8245 }
8246 if ( remove.length ) {
8247 this.removeItems( remove );
8248 }
8249 // Update emptiness state
8250 if ( add.length ) {
8251 this.$element.removeClass( 'oo-ui-toolGroup-empty' );
8252 } else {
8253 this.$element.addClass( 'oo-ui-toolGroup-empty' );
8254 }
8255 // Re-add tools (moving existing ones to new locations)
8256 this.addItems( add );
8257 // Disabled state may depend on items
8258 this.updateDisabled();
8259 };
8260
8261 /**
8262 * Destroy toolgroup.
8263 */
8264 OO.ui.ToolGroup.prototype.destroy = function () {
8265 var name;
8266
8267 this.clearItems();
8268 this.toolbar.getToolFactory().disconnect( this );
8269 for ( name in this.tools ) {
8270 this.toolbar.releaseTool( this.tools[ name ] );
8271 this.tools[ name ].disconnect( this ).destroy();
8272 delete this.tools[ name ];
8273 }
8274 this.$element.remove();
8275 };
8276
8277 /**
8278 * MessageDialogs display a confirmation or alert message. By default, the rendered dialog box
8279 * consists of a header that contains the dialog title, a body with the message, and a footer that
8280 * contains any {@link OO.ui.ActionWidget action widgets}. The MessageDialog class is the only type
8281 * of {@link OO.ui.Dialog dialog} that is usually instantiated directly.
8282 *
8283 * There are two basic types of message dialogs, confirmation and alert:
8284 *
8285 * - **confirmation**: the dialog title describes what a progressive action will do and the message provides
8286 * more details about the consequences.
8287 * - **alert**: the dialog title describes which event occurred and the message provides more information
8288 * about why the event occurred.
8289 *
8290 * The MessageDialog class specifies two actions: ‘accept’, the primary
8291 * action (e.g., ‘ok’) and ‘reject,’ the safe action (e.g., ‘cancel’). Both will close the window,
8292 * passing along the selected action.
8293 *
8294 * For more information and examples, please see the [OOjs UI documentation on MediaWiki][1].
8295 *
8296 * @example
8297 * // Example: Creating and opening a message dialog window.
8298 * var messageDialog = new OO.ui.MessageDialog();
8299 *
8300 * // Create and append a window manager.
8301 * var windowManager = new OO.ui.WindowManager();
8302 * $( 'body' ).append( windowManager.$element );
8303 * windowManager.addWindows( [ messageDialog ] );
8304 * // Open the window.
8305 * windowManager.openWindow( messageDialog, {
8306 * title: 'Basic message dialog',
8307 * message: 'This is the message'
8308 * } );
8309 *
8310 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Message_Dialogs
8311 *
8312 * @class
8313 * @extends OO.ui.Dialog
8314 *
8315 * @constructor
8316 * @param {Object} [config] Configuration options
8317 */
8318 OO.ui.MessageDialog = function OoUiMessageDialog( config ) {
8319 // Parent constructor
8320 OO.ui.MessageDialog.parent.call( this, config );
8321
8322 // Properties
8323 this.verticalActionLayout = null;
8324
8325 // Initialization
8326 this.$element.addClass( 'oo-ui-messageDialog' );
8327 };
8328
8329 /* Setup */
8330
8331 OO.inheritClass( OO.ui.MessageDialog, OO.ui.Dialog );
8332
8333 /* Static Properties */
8334
8335 OO.ui.MessageDialog.static.name = 'message';
8336
8337 OO.ui.MessageDialog.static.size = 'small';
8338
8339 OO.ui.MessageDialog.static.verbose = false;
8340
8341 /**
8342 * Dialog title.
8343 *
8344 * The title of a confirmation dialog describes what a progressive action will do. The
8345 * title of an alert dialog describes which event occurred.
8346 *
8347 * @static
8348 * @inheritable
8349 * @property {jQuery|string|Function|null}
8350 */
8351 OO.ui.MessageDialog.static.title = null;
8352
8353 /**
8354 * The message displayed in the dialog body.
8355 *
8356 * A confirmation message describes the consequences of a progressive action. An alert
8357 * message describes why an event occurred.
8358 *
8359 * @static
8360 * @inheritable
8361 * @property {jQuery|string|Function|null}
8362 */
8363 OO.ui.MessageDialog.static.message = null;
8364
8365 OO.ui.MessageDialog.static.actions = [
8366 { action: 'accept', label: OO.ui.deferMsg( 'ooui-dialog-message-accept' ), flags: 'primary' },
8367 { action: 'reject', label: OO.ui.deferMsg( 'ooui-dialog-message-reject' ), flags: 'safe' }
8368 ];
8369
8370 /* Methods */
8371
8372 /**
8373 * @inheritdoc
8374 */
8375 OO.ui.MessageDialog.prototype.setManager = function ( manager ) {
8376 OO.ui.MessageDialog.parent.prototype.setManager.call( this, manager );
8377
8378 // Events
8379 this.manager.connect( this, {
8380 resize: 'onResize'
8381 } );
8382
8383 return this;
8384 };
8385
8386 /**
8387 * @inheritdoc
8388 */
8389 OO.ui.MessageDialog.prototype.onActionResize = function ( action ) {
8390 this.fitActions();
8391 return OO.ui.MessageDialog.parent.prototype.onActionResize.call( this, action );
8392 };
8393
8394 /**
8395 * Handle window resized events.
8396 *
8397 * @private
8398 */
8399 OO.ui.MessageDialog.prototype.onResize = function () {
8400 var dialog = this;
8401 dialog.fitActions();
8402 // Wait for CSS transition to finish and do it again :(
8403 setTimeout( function () {
8404 dialog.fitActions();
8405 }, 300 );
8406 };
8407
8408 /**
8409 * Toggle action layout between vertical and horizontal.
8410 *
8411 * @private
8412 * @param {boolean} [value] Layout actions vertically, omit to toggle
8413 * @chainable
8414 */
8415 OO.ui.MessageDialog.prototype.toggleVerticalActionLayout = function ( value ) {
8416 value = value === undefined ? !this.verticalActionLayout : !!value;
8417
8418 if ( value !== this.verticalActionLayout ) {
8419 this.verticalActionLayout = value;
8420 this.$actions
8421 .toggleClass( 'oo-ui-messageDialog-actions-vertical', value )
8422 .toggleClass( 'oo-ui-messageDialog-actions-horizontal', !value );
8423 }
8424
8425 return this;
8426 };
8427
8428 /**
8429 * @inheritdoc
8430 */
8431 OO.ui.MessageDialog.prototype.getActionProcess = function ( action ) {
8432 if ( action ) {
8433 return new OO.ui.Process( function () {
8434 this.close( { action: action } );
8435 }, this );
8436 }
8437 return OO.ui.MessageDialog.parent.prototype.getActionProcess.call( this, action );
8438 };
8439
8440 /**
8441 * @inheritdoc
8442 *
8443 * @param {Object} [data] Dialog opening data
8444 * @param {jQuery|string|Function|null} [data.title] Description of the action being confirmed
8445 * @param {jQuery|string|Function|null} [data.message] Description of the action's consequence
8446 * @param {boolean} [data.verbose] Message is verbose and should be styled as a long message
8447 * @param {Object[]} [data.actions] List of OO.ui.ActionOptionWidget configuration options for each
8448 * action item
8449 */
8450 OO.ui.MessageDialog.prototype.getSetupProcess = function ( data ) {
8451 data = data || {};
8452
8453 // Parent method
8454 return OO.ui.MessageDialog.parent.prototype.getSetupProcess.call( this, data )
8455 .next( function () {
8456 this.title.setLabel(
8457 data.title !== undefined ? data.title : this.constructor.static.title
8458 );
8459 this.message.setLabel(
8460 data.message !== undefined ? data.message : this.constructor.static.message
8461 );
8462 this.message.$element.toggleClass(
8463 'oo-ui-messageDialog-message-verbose',
8464 data.verbose !== undefined ? data.verbose : this.constructor.static.verbose
8465 );
8466 }, this );
8467 };
8468
8469 /**
8470 * @inheritdoc
8471 */
8472 OO.ui.MessageDialog.prototype.getReadyProcess = function ( data ) {
8473 data = data || {};
8474
8475 // Parent method
8476 return OO.ui.MessageDialog.parent.prototype.getReadyProcess.call( this, data )
8477 .next( function () {
8478 // Focus the primary action button
8479 var actions = this.actions.get();
8480 actions = actions.filter( function ( action ) {
8481 return action.getFlags().indexOf( 'primary' ) > -1;
8482 } );
8483 if ( actions.length > 0 ) {
8484 actions[ 0 ].$button.focus();
8485 }
8486 }, this );
8487 };
8488
8489 /**
8490 * @inheritdoc
8491 */
8492 OO.ui.MessageDialog.prototype.getBodyHeight = function () {
8493 var bodyHeight, oldOverflow,
8494 $scrollable = this.container.$element;
8495
8496 oldOverflow = $scrollable[ 0 ].style.overflow;
8497 $scrollable[ 0 ].style.overflow = 'hidden';
8498
8499 OO.ui.Element.static.reconsiderScrollbars( $scrollable[ 0 ] );
8500
8501 bodyHeight = this.text.$element.outerHeight( true );
8502 $scrollable[ 0 ].style.overflow = oldOverflow;
8503
8504 return bodyHeight;
8505 };
8506
8507 /**
8508 * @inheritdoc
8509 */
8510 OO.ui.MessageDialog.prototype.setDimensions = function ( dim ) {
8511 var $scrollable = this.container.$element;
8512 OO.ui.MessageDialog.parent.prototype.setDimensions.call( this, dim );
8513
8514 // Twiddle the overflow property, otherwise an unnecessary scrollbar will be produced.
8515 // Need to do it after transition completes (250ms), add 50ms just in case.
8516 setTimeout( function () {
8517 var oldOverflow = $scrollable[ 0 ].style.overflow;
8518 $scrollable[ 0 ].style.overflow = 'hidden';
8519
8520 OO.ui.Element.static.reconsiderScrollbars( $scrollable[ 0 ] );
8521
8522 $scrollable[ 0 ].style.overflow = oldOverflow;
8523 }, 300 );
8524
8525 return this;
8526 };
8527
8528 /**
8529 * @inheritdoc
8530 */
8531 OO.ui.MessageDialog.prototype.initialize = function () {
8532 // Parent method
8533 OO.ui.MessageDialog.parent.prototype.initialize.call( this );
8534
8535 // Properties
8536 this.$actions = $( '<div>' );
8537 this.container = new OO.ui.PanelLayout( {
8538 scrollable: true, classes: [ 'oo-ui-messageDialog-container' ]
8539 } );
8540 this.text = new OO.ui.PanelLayout( {
8541 padded: true, expanded: false, classes: [ 'oo-ui-messageDialog-text' ]
8542 } );
8543 this.message = new OO.ui.LabelWidget( {
8544 classes: [ 'oo-ui-messageDialog-message' ]
8545 } );
8546
8547 // Initialization
8548 this.title.$element.addClass( 'oo-ui-messageDialog-title' );
8549 this.$content.addClass( 'oo-ui-messageDialog-content' );
8550 this.container.$element.append( this.text.$element );
8551 this.text.$element.append( this.title.$element, this.message.$element );
8552 this.$body.append( this.container.$element );
8553 this.$actions.addClass( 'oo-ui-messageDialog-actions' );
8554 this.$foot.append( this.$actions );
8555 };
8556
8557 /**
8558 * @inheritdoc
8559 */
8560 OO.ui.MessageDialog.prototype.attachActions = function () {
8561 var i, len, other, special, others;
8562
8563 // Parent method
8564 OO.ui.MessageDialog.parent.prototype.attachActions.call( this );
8565
8566 special = this.actions.getSpecial();
8567 others = this.actions.getOthers();
8568
8569 if ( special.safe ) {
8570 this.$actions.append( special.safe.$element );
8571 special.safe.toggleFramed( false );
8572 }
8573 if ( others.length ) {
8574 for ( i = 0, len = others.length; i < len; i++ ) {
8575 other = others[ i ];
8576 this.$actions.append( other.$element );
8577 other.toggleFramed( false );
8578 }
8579 }
8580 if ( special.primary ) {
8581 this.$actions.append( special.primary.$element );
8582 special.primary.toggleFramed( false );
8583 }
8584
8585 if ( !this.isOpening() ) {
8586 // If the dialog is currently opening, this will be called automatically soon.
8587 // This also calls #fitActions.
8588 this.updateSize();
8589 }
8590 };
8591
8592 /**
8593 * Fit action actions into columns or rows.
8594 *
8595 * Columns will be used if all labels can fit without overflow, otherwise rows will be used.
8596 *
8597 * @private
8598 */
8599 OO.ui.MessageDialog.prototype.fitActions = function () {
8600 var i, len, action,
8601 previous = this.verticalActionLayout,
8602 actions = this.actions.get();
8603
8604 // Detect clipping
8605 this.toggleVerticalActionLayout( false );
8606 for ( i = 0, len = actions.length; i < len; i++ ) {
8607 action = actions[ i ];
8608 if ( action.$element.innerWidth() < action.$label.outerWidth( true ) ) {
8609 this.toggleVerticalActionLayout( true );
8610 break;
8611 }
8612 }
8613
8614 // Move the body out of the way of the foot
8615 this.$body.css( 'bottom', this.$foot.outerHeight( true ) );
8616
8617 if ( this.verticalActionLayout !== previous ) {
8618 // We changed the layout, window height might need to be updated.
8619 this.updateSize();
8620 }
8621 };
8622
8623 /**
8624 * ProcessDialog windows encapsulate a {@link OO.ui.Process process} and all of the code necessary
8625 * to complete it. If the process terminates with an error, a customizable {@link OO.ui.Error error
8626 * interface} alerts users to the trouble, permitting the user to dismiss the error and try again when
8627 * relevant. The ProcessDialog class is always extended and customized with the actions and content
8628 * required for each process.
8629 *
8630 * The process dialog box consists of a header that visually represents the ‘working’ state of long
8631 * processes with an animation. The header contains the dialog title as well as
8632 * two {@link OO.ui.ActionWidget action widgets}: a ‘safe’ action on the left (e.g., ‘Cancel’) and
8633 * a ‘primary’ action on the right (e.g., ‘Done’).
8634 *
8635 * Like other windows, the process dialog is managed by a {@link OO.ui.WindowManager window manager}.
8636 * Please see the [OOjs UI documentation on MediaWiki][1] for more information and examples.
8637 *
8638 * @example
8639 * // Example: Creating and opening a process dialog window.
8640 * function MyProcessDialog( config ) {
8641 * MyProcessDialog.parent.call( this, config );
8642 * }
8643 * OO.inheritClass( MyProcessDialog, OO.ui.ProcessDialog );
8644 *
8645 * MyProcessDialog.static.title = 'Process dialog';
8646 * MyProcessDialog.static.actions = [
8647 * { action: 'save', label: 'Done', flags: 'primary' },
8648 * { label: 'Cancel', flags: 'safe' }
8649 * ];
8650 *
8651 * MyProcessDialog.prototype.initialize = function () {
8652 * MyProcessDialog.parent.prototype.initialize.apply( this, arguments );
8653 * this.content = new OO.ui.PanelLayout( { padded: true, expanded: false } );
8654 * 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>' );
8655 * this.$body.append( this.content.$element );
8656 * };
8657 * MyProcessDialog.prototype.getActionProcess = function ( action ) {
8658 * var dialog = this;
8659 * if ( action ) {
8660 * return new OO.ui.Process( function () {
8661 * dialog.close( { action: action } );
8662 * } );
8663 * }
8664 * return MyProcessDialog.parent.prototype.getActionProcess.call( this, action );
8665 * };
8666 *
8667 * var windowManager = new OO.ui.WindowManager();
8668 * $( 'body' ).append( windowManager.$element );
8669 *
8670 * var dialog = new MyProcessDialog();
8671 * windowManager.addWindows( [ dialog ] );
8672 * windowManager.openWindow( dialog );
8673 *
8674 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs
8675 *
8676 * @abstract
8677 * @class
8678 * @extends OO.ui.Dialog
8679 *
8680 * @constructor
8681 * @param {Object} [config] Configuration options
8682 */
8683 OO.ui.ProcessDialog = function OoUiProcessDialog( config ) {
8684 // Parent constructor
8685 OO.ui.ProcessDialog.parent.call( this, config );
8686
8687 // Properties
8688 this.fitOnOpen = false;
8689
8690 // Initialization
8691 this.$element.addClass( 'oo-ui-processDialog' );
8692 };
8693
8694 /* Setup */
8695
8696 OO.inheritClass( OO.ui.ProcessDialog, OO.ui.Dialog );
8697
8698 /* Methods */
8699
8700 /**
8701 * Handle dismiss button click events.
8702 *
8703 * Hides errors.
8704 *
8705 * @private
8706 */
8707 OO.ui.ProcessDialog.prototype.onDismissErrorButtonClick = function () {
8708 this.hideErrors();
8709 };
8710
8711 /**
8712 * Handle retry button click events.
8713 *
8714 * Hides errors and then tries again.
8715 *
8716 * @private
8717 */
8718 OO.ui.ProcessDialog.prototype.onRetryButtonClick = function () {
8719 this.hideErrors();
8720 this.executeAction( this.currentAction );
8721 };
8722
8723 /**
8724 * @inheritdoc
8725 */
8726 OO.ui.ProcessDialog.prototype.onActionResize = function ( action ) {
8727 if ( this.actions.isSpecial( action ) ) {
8728 this.fitLabel();
8729 }
8730 return OO.ui.ProcessDialog.parent.prototype.onActionResize.call( this, action );
8731 };
8732
8733 /**
8734 * @inheritdoc
8735 */
8736 OO.ui.ProcessDialog.prototype.initialize = function () {
8737 // Parent method
8738 OO.ui.ProcessDialog.parent.prototype.initialize.call( this );
8739
8740 // Properties
8741 this.$navigation = $( '<div>' );
8742 this.$location = $( '<div>' );
8743 this.$safeActions = $( '<div>' );
8744 this.$primaryActions = $( '<div>' );
8745 this.$otherActions = $( '<div>' );
8746 this.dismissButton = new OO.ui.ButtonWidget( {
8747 label: OO.ui.msg( 'ooui-dialog-process-dismiss' )
8748 } );
8749 this.retryButton = new OO.ui.ButtonWidget();
8750 this.$errors = $( '<div>' );
8751 this.$errorsTitle = $( '<div>' );
8752
8753 // Events
8754 this.dismissButton.connect( this, { click: 'onDismissErrorButtonClick' } );
8755 this.retryButton.connect( this, { click: 'onRetryButtonClick' } );
8756
8757 // Initialization
8758 this.title.$element.addClass( 'oo-ui-processDialog-title' );
8759 this.$location
8760 .append( this.title.$element )
8761 .addClass( 'oo-ui-processDialog-location' );
8762 this.$safeActions.addClass( 'oo-ui-processDialog-actions-safe' );
8763 this.$primaryActions.addClass( 'oo-ui-processDialog-actions-primary' );
8764 this.$otherActions.addClass( 'oo-ui-processDialog-actions-other' );
8765 this.$errorsTitle
8766 .addClass( 'oo-ui-processDialog-errors-title' )
8767 .text( OO.ui.msg( 'ooui-dialog-process-error' ) );
8768 this.$errors
8769 .addClass( 'oo-ui-processDialog-errors oo-ui-element-hidden' )
8770 .append( this.$errorsTitle, this.dismissButton.$element, this.retryButton.$element );
8771 this.$content
8772 .addClass( 'oo-ui-processDialog-content' )
8773 .append( this.$errors );
8774 this.$navigation
8775 .addClass( 'oo-ui-processDialog-navigation' )
8776 .append( this.$safeActions, this.$location, this.$primaryActions );
8777 this.$head.append( this.$navigation );
8778 this.$foot.append( this.$otherActions );
8779 };
8780
8781 /**
8782 * @inheritdoc
8783 */
8784 OO.ui.ProcessDialog.prototype.getActionWidgets = function ( actions ) {
8785 var i, len, widgets = [];
8786 for ( i = 0, len = actions.length; i < len; i++ ) {
8787 widgets.push(
8788 new OO.ui.ActionWidget( $.extend( { framed: true }, actions[ i ] ) )
8789 );
8790 }
8791 return widgets;
8792 };
8793
8794 /**
8795 * @inheritdoc
8796 */
8797 OO.ui.ProcessDialog.prototype.attachActions = function () {
8798 var i, len, other, special, others;
8799
8800 // Parent method
8801 OO.ui.ProcessDialog.parent.prototype.attachActions.call( this );
8802
8803 special = this.actions.getSpecial();
8804 others = this.actions.getOthers();
8805 if ( special.primary ) {
8806 this.$primaryActions.append( special.primary.$element );
8807 }
8808 for ( i = 0, len = others.length; i < len; i++ ) {
8809 other = others[ i ];
8810 this.$otherActions.append( other.$element );
8811 }
8812 if ( special.safe ) {
8813 this.$safeActions.append( special.safe.$element );
8814 }
8815
8816 this.fitLabel();
8817 this.$body.css( 'bottom', this.$foot.outerHeight( true ) );
8818 };
8819
8820 /**
8821 * @inheritdoc
8822 */
8823 OO.ui.ProcessDialog.prototype.executeAction = function ( action ) {
8824 var process = this;
8825 return OO.ui.ProcessDialog.parent.prototype.executeAction.call( this, action )
8826 .fail( function ( errors ) {
8827 process.showErrors( errors || [] );
8828 } );
8829 };
8830
8831 /**
8832 * @inheritdoc
8833 */
8834 OO.ui.ProcessDialog.prototype.setDimensions = function () {
8835 // Parent method
8836 OO.ui.ProcessDialog.parent.prototype.setDimensions.apply( this, arguments );
8837
8838 this.fitLabel();
8839 };
8840
8841 /**
8842 * Fit label between actions.
8843 *
8844 * @private
8845 * @chainable
8846 */
8847 OO.ui.ProcessDialog.prototype.fitLabel = function () {
8848 var safeWidth, primaryWidth, biggerWidth, labelWidth, navigationWidth, leftWidth, rightWidth,
8849 size = this.getSizeProperties();
8850
8851 if ( typeof size.width !== 'number' ) {
8852 if ( this.isOpened() ) {
8853 navigationWidth = this.$head.width() - 20;
8854 } else if ( this.isOpening() ) {
8855 if ( !this.fitOnOpen ) {
8856 // Size is relative and the dialog isn't open yet, so wait.
8857 this.manager.opening.done( this.fitLabel.bind( this ) );
8858 this.fitOnOpen = true;
8859 }
8860 return;
8861 } else {
8862 return;
8863 }
8864 } else {
8865 navigationWidth = size.width - 20;
8866 }
8867
8868 safeWidth = this.$safeActions.is( ':visible' ) ? this.$safeActions.width() : 0;
8869 primaryWidth = this.$primaryActions.is( ':visible' ) ? this.$primaryActions.width() : 0;
8870 biggerWidth = Math.max( safeWidth, primaryWidth );
8871
8872 labelWidth = this.title.$element.width();
8873
8874 if ( 2 * biggerWidth + labelWidth < navigationWidth ) {
8875 // We have enough space to center the label
8876 leftWidth = rightWidth = biggerWidth;
8877 } else {
8878 // Let's hope we at least have enough space not to overlap, because we can't wrap the label…
8879 if ( this.getDir() === 'ltr' ) {
8880 leftWidth = safeWidth;
8881 rightWidth = primaryWidth;
8882 } else {
8883 leftWidth = primaryWidth;
8884 rightWidth = safeWidth;
8885 }
8886 }
8887
8888 this.$location.css( { paddingLeft: leftWidth, paddingRight: rightWidth } );
8889
8890 return this;
8891 };
8892
8893 /**
8894 * Handle errors that occurred during accept or reject processes.
8895 *
8896 * @private
8897 * @param {OO.ui.Error[]|OO.ui.Error} errors Errors to be handled
8898 */
8899 OO.ui.ProcessDialog.prototype.showErrors = function ( errors ) {
8900 var i, len, $item, actions,
8901 items = [],
8902 abilities = {},
8903 recoverable = true,
8904 warning = false;
8905
8906 if ( errors instanceof OO.ui.Error ) {
8907 errors = [ errors ];
8908 }
8909
8910 for ( i = 0, len = errors.length; i < len; i++ ) {
8911 if ( !errors[ i ].isRecoverable() ) {
8912 recoverable = false;
8913 }
8914 if ( errors[ i ].isWarning() ) {
8915 warning = true;
8916 }
8917 $item = $( '<div>' )
8918 .addClass( 'oo-ui-processDialog-error' )
8919 .append( errors[ i ].getMessage() );
8920 items.push( $item[ 0 ] );
8921 }
8922 this.$errorItems = $( items );
8923 if ( recoverable ) {
8924 abilities[ this.currentAction ] = true;
8925 // Copy the flags from the first matching action
8926 actions = this.actions.get( { actions: this.currentAction } );
8927 if ( actions.length ) {
8928 this.retryButton.clearFlags().setFlags( actions[ 0 ].getFlags() );
8929 }
8930 } else {
8931 abilities[ this.currentAction ] = false;
8932 this.actions.setAbilities( abilities );
8933 }
8934 if ( warning ) {
8935 this.retryButton.setLabel( OO.ui.msg( 'ooui-dialog-process-continue' ) );
8936 } else {
8937 this.retryButton.setLabel( OO.ui.msg( 'ooui-dialog-process-retry' ) );
8938 }
8939 this.retryButton.toggle( recoverable );
8940 this.$errorsTitle.after( this.$errorItems );
8941 this.$errors.removeClass( 'oo-ui-element-hidden' ).scrollTop( 0 );
8942 };
8943
8944 /**
8945 * Hide errors.
8946 *
8947 * @private
8948 */
8949 OO.ui.ProcessDialog.prototype.hideErrors = function () {
8950 this.$errors.addClass( 'oo-ui-element-hidden' );
8951 if ( this.$errorItems ) {
8952 this.$errorItems.remove();
8953 this.$errorItems = null;
8954 }
8955 };
8956
8957 /**
8958 * @inheritdoc
8959 */
8960 OO.ui.ProcessDialog.prototype.getTeardownProcess = function ( data ) {
8961 // Parent method
8962 return OO.ui.ProcessDialog.parent.prototype.getTeardownProcess.call( this, data )
8963 .first( function () {
8964 // Make sure to hide errors
8965 this.hideErrors();
8966 this.fitOnOpen = false;
8967 }, this );
8968 };
8969
8970 /**
8971 * FieldLayouts are used with OO.ui.FieldsetLayout. Each FieldLayout requires a field-widget,
8972 * which is a widget that is specified by reference before any optional configuration settings.
8973 *
8974 * Field layouts can be configured with help text and/or labels. Labels are aligned in one of four ways:
8975 *
8976 * - **left**: The label is placed before the field-widget and aligned with the left margin.
8977 * A left-alignment is used for forms with many fields.
8978 * - **right**: The label is placed before the field-widget and aligned to the right margin.
8979 * A right-alignment is used for long but familiar forms which users tab through,
8980 * verifying the current field with a quick glance at the label.
8981 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
8982 * that users fill out from top to bottom.
8983 * - **inline**: The label is placed after the field-widget and aligned to the left.
8984 * An inline-alignment is best used with checkboxes or radio buttons.
8985 *
8986 * Help text is accessed via a help icon that appears in the upper right corner of the rendered field layout.
8987 * Please see the [OOjs UI documentation on MediaWiki] [1] for examples and more information.
8988 *
8989 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Fields_and_Fieldsets
8990 * @class
8991 * @extends OO.ui.Layout
8992 * @mixins OO.ui.mixin.LabelElement
8993 * @mixins OO.ui.mixin.TitledElement
8994 *
8995 * @constructor
8996 * @param {OO.ui.Widget} fieldWidget Field widget
8997 * @param {Object} [config] Configuration options
8998 * @cfg {string} [align='left'] Alignment of the label: 'left', 'right', 'top' or 'inline'
8999 * @cfg {Array} [errors] Error messages about the widget, which will be displayed below the widget.
9000 * The array may contain strings or OO.ui.HtmlSnippet instances.
9001 * @cfg {Array} [notices] Notices about the widget, which will be displayed below the widget.
9002 * The array may contain strings or OO.ui.HtmlSnippet instances.
9003 * @cfg {string|OO.ui.HtmlSnippet} [help] Help text. When help text is specified, a "help" icon will appear
9004 * in the upper-right corner of the rendered field; clicking it will display the text in a popup.
9005 * For important messages, you are advised to use `notices`, as they are always shown.
9006 *
9007 * @throws {Error} An error is thrown if no widget is specified
9008 */
9009 OO.ui.FieldLayout = function OoUiFieldLayout( fieldWidget, config ) {
9010 var hasInputWidget, div, i;
9011
9012 // Allow passing positional parameters inside the config object
9013 if ( OO.isPlainObject( fieldWidget ) && config === undefined ) {
9014 config = fieldWidget;
9015 fieldWidget = config.fieldWidget;
9016 }
9017
9018 // Make sure we have required constructor arguments
9019 if ( fieldWidget === undefined ) {
9020 throw new Error( 'Widget not found' );
9021 }
9022
9023 hasInputWidget = fieldWidget.constructor.static.supportsSimpleLabel;
9024
9025 // Configuration initialization
9026 config = $.extend( { align: 'left' }, config );
9027
9028 // Parent constructor
9029 OO.ui.FieldLayout.parent.call( this, config );
9030
9031 // Mixin constructors
9032 OO.ui.mixin.LabelElement.call( this, config );
9033 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$label } ) );
9034
9035 // Properties
9036 this.fieldWidget = fieldWidget;
9037 this.errors = config.errors || [];
9038 this.notices = config.notices || [];
9039 this.$field = $( '<div>' );
9040 this.$messages = $( '<ul>' );
9041 this.$body = $( '<' + ( hasInputWidget ? 'label' : 'div' ) + '>' );
9042 this.align = null;
9043 if ( config.help ) {
9044 this.popupButtonWidget = new OO.ui.PopupButtonWidget( {
9045 classes: [ 'oo-ui-fieldLayout-help' ],
9046 framed: false,
9047 icon: 'info'
9048 } );
9049
9050 div = $( '<div>' );
9051 if ( config.help instanceof OO.ui.HtmlSnippet ) {
9052 div.html( config.help.toString() );
9053 } else {
9054 div.text( config.help );
9055 }
9056 this.popupButtonWidget.getPopup().$body.append(
9057 div.addClass( 'oo-ui-fieldLayout-help-content' )
9058 );
9059 this.$help = this.popupButtonWidget.$element;
9060 } else {
9061 this.$help = $( [] );
9062 }
9063
9064 // Events
9065 if ( hasInputWidget ) {
9066 this.$label.on( 'click', this.onLabelClick.bind( this ) );
9067 }
9068 this.fieldWidget.connect( this, { disable: 'onFieldDisable' } );
9069
9070 // Initialization
9071 this.$element
9072 .addClass( 'oo-ui-fieldLayout' )
9073 .append( this.$help, this.$body );
9074 if ( this.errors.length || this.notices.length ) {
9075 this.$element.append( this.$messages );
9076 }
9077 this.$body.addClass( 'oo-ui-fieldLayout-body' );
9078 this.$messages.addClass( 'oo-ui-fieldLayout-messages' );
9079 this.$field
9080 .addClass( 'oo-ui-fieldLayout-field' )
9081 .toggleClass( 'oo-ui-fieldLayout-disable', this.fieldWidget.isDisabled() )
9082 .append( this.fieldWidget.$element );
9083
9084 for ( i = 0; i < this.notices.length; i++ ) {
9085 this.$messages.append( this.makeMessage( 'notice', this.notices[ i ] ) );
9086 }
9087 for ( i = 0; i < this.errors.length; i++ ) {
9088 this.$messages.append( this.makeMessage( 'error', this.errors[ i ] ) );
9089 }
9090
9091 this.setAlignment( config.align );
9092 };
9093
9094 /* Setup */
9095
9096 OO.inheritClass( OO.ui.FieldLayout, OO.ui.Layout );
9097 OO.mixinClass( OO.ui.FieldLayout, OO.ui.mixin.LabelElement );
9098 OO.mixinClass( OO.ui.FieldLayout, OO.ui.mixin.TitledElement );
9099
9100 /* Methods */
9101
9102 /**
9103 * Handle field disable events.
9104 *
9105 * @private
9106 * @param {boolean} value Field is disabled
9107 */
9108 OO.ui.FieldLayout.prototype.onFieldDisable = function ( value ) {
9109 this.$element.toggleClass( 'oo-ui-fieldLayout-disabled', value );
9110 };
9111
9112 /**
9113 * Handle label mouse click events.
9114 *
9115 * @private
9116 * @param {jQuery.Event} e Mouse click event
9117 */
9118 OO.ui.FieldLayout.prototype.onLabelClick = function () {
9119 this.fieldWidget.simulateLabelClick();
9120 return false;
9121 };
9122
9123 /**
9124 * Get the widget contained by the field.
9125 *
9126 * @return {OO.ui.Widget} Field widget
9127 */
9128 OO.ui.FieldLayout.prototype.getField = function () {
9129 return this.fieldWidget;
9130 };
9131
9132 /**
9133 * @param {string} kind 'error' or 'notice'
9134 * @param {string|OO.ui.HtmlSnippet} text
9135 * @return {jQuery}
9136 */
9137 OO.ui.FieldLayout.prototype.makeMessage = function ( kind, text ) {
9138 var $listItem, $icon, message;
9139 $listItem = $( '<li>' );
9140 if ( kind === 'error' ) {
9141 $icon = new OO.ui.IconWidget( { icon: 'alert', flags: [ 'warning' ] } ).$element;
9142 } else if ( kind === 'notice' ) {
9143 $icon = new OO.ui.IconWidget( { icon: 'info' } ).$element;
9144 } else {
9145 $icon = '';
9146 }
9147 message = new OO.ui.LabelWidget( { label: text } );
9148 $listItem
9149 .append( $icon, message.$element )
9150 .addClass( 'oo-ui-fieldLayout-messages-' + kind );
9151 return $listItem;
9152 };
9153
9154 /**
9155 * Set the field alignment mode.
9156 *
9157 * @private
9158 * @param {string} value Alignment mode, either 'left', 'right', 'top' or 'inline'
9159 * @chainable
9160 */
9161 OO.ui.FieldLayout.prototype.setAlignment = function ( value ) {
9162 if ( value !== this.align ) {
9163 // Default to 'left'
9164 if ( [ 'left', 'right', 'top', 'inline' ].indexOf( value ) === -1 ) {
9165 value = 'left';
9166 }
9167 // Reorder elements
9168 if ( value === 'inline' ) {
9169 this.$body.append( this.$field, this.$label );
9170 } else {
9171 this.$body.append( this.$label, this.$field );
9172 }
9173 // Set classes. The following classes can be used here:
9174 // * oo-ui-fieldLayout-align-left
9175 // * oo-ui-fieldLayout-align-right
9176 // * oo-ui-fieldLayout-align-top
9177 // * oo-ui-fieldLayout-align-inline
9178 if ( this.align ) {
9179 this.$element.removeClass( 'oo-ui-fieldLayout-align-' + this.align );
9180 }
9181 this.$element.addClass( 'oo-ui-fieldLayout-align-' + value );
9182 this.align = value;
9183 }
9184
9185 return this;
9186 };
9187
9188 /**
9189 * ActionFieldLayouts are used with OO.ui.FieldsetLayout. The layout consists of a field-widget, a button,
9190 * and an optional label and/or help text. The field-widget (e.g., a {@link OO.ui.TextInputWidget TextInputWidget}),
9191 * is required and is specified before any optional configuration settings.
9192 *
9193 * Labels can be aligned in one of four ways:
9194 *
9195 * - **left**: The label is placed before the field-widget and aligned with the left margin.
9196 * A left-alignment is used for forms with many fields.
9197 * - **right**: The label is placed before the field-widget and aligned to the right margin.
9198 * A right-alignment is used for long but familiar forms which users tab through,
9199 * verifying the current field with a quick glance at the label.
9200 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
9201 * that users fill out from top to bottom.
9202 * - **inline**: The label is placed after the field-widget and aligned to the left.
9203 * An inline-alignment is best used with checkboxes or radio buttons.
9204 *
9205 * Help text is accessed via a help icon that appears in the upper right corner of the rendered field layout when help
9206 * text is specified.
9207 *
9208 * @example
9209 * // Example of an ActionFieldLayout
9210 * var actionFieldLayout = new OO.ui.ActionFieldLayout(
9211 * new OO.ui.TextInputWidget( {
9212 * placeholder: 'Field widget'
9213 * } ),
9214 * new OO.ui.ButtonWidget( {
9215 * label: 'Button'
9216 * } ),
9217 * {
9218 * label: 'An ActionFieldLayout. This label is aligned top',
9219 * align: 'top',
9220 * help: 'This is help text'
9221 * }
9222 * );
9223 *
9224 * $( 'body' ).append( actionFieldLayout.$element );
9225 *
9226 * @class
9227 * @extends OO.ui.FieldLayout
9228 *
9229 * @constructor
9230 * @param {OO.ui.Widget} fieldWidget Field widget
9231 * @param {OO.ui.ButtonWidget} buttonWidget Button widget
9232 */
9233 OO.ui.ActionFieldLayout = function OoUiActionFieldLayout( fieldWidget, buttonWidget, config ) {
9234 // Allow passing positional parameters inside the config object
9235 if ( OO.isPlainObject( fieldWidget ) && config === undefined ) {
9236 config = fieldWidget;
9237 fieldWidget = config.fieldWidget;
9238 buttonWidget = config.buttonWidget;
9239 }
9240
9241 // Parent constructor
9242 OO.ui.ActionFieldLayout.parent.call( this, fieldWidget, config );
9243
9244 // Properties
9245 this.buttonWidget = buttonWidget;
9246 this.$button = $( '<div>' );
9247 this.$input = $( '<div>' );
9248
9249 // Initialization
9250 this.$element
9251 .addClass( 'oo-ui-actionFieldLayout' );
9252 this.$button
9253 .addClass( 'oo-ui-actionFieldLayout-button' )
9254 .append( this.buttonWidget.$element );
9255 this.$input
9256 .addClass( 'oo-ui-actionFieldLayout-input' )
9257 .append( this.fieldWidget.$element );
9258 this.$field
9259 .append( this.$input, this.$button );
9260 };
9261
9262 /* Setup */
9263
9264 OO.inheritClass( OO.ui.ActionFieldLayout, OO.ui.FieldLayout );
9265
9266 /**
9267 * FieldsetLayouts are composed of one or more {@link OO.ui.FieldLayout FieldLayouts},
9268 * which each contain an individual widget and, optionally, a label. Each Fieldset can be
9269 * configured with a label as well. For more information and examples,
9270 * please see the [OOjs UI documentation on MediaWiki][1].
9271 *
9272 * @example
9273 * // Example of a fieldset layout
9274 * var input1 = new OO.ui.TextInputWidget( {
9275 * placeholder: 'A text input field'
9276 * } );
9277 *
9278 * var input2 = new OO.ui.TextInputWidget( {
9279 * placeholder: 'A text input field'
9280 * } );
9281 *
9282 * var fieldset = new OO.ui.FieldsetLayout( {
9283 * label: 'Example of a fieldset layout'
9284 * } );
9285 *
9286 * fieldset.addItems( [
9287 * new OO.ui.FieldLayout( input1, {
9288 * label: 'Field One'
9289 * } ),
9290 * new OO.ui.FieldLayout( input2, {
9291 * label: 'Field Two'
9292 * } )
9293 * ] );
9294 * $( 'body' ).append( fieldset.$element );
9295 *
9296 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Fields_and_Fieldsets
9297 *
9298 * @class
9299 * @extends OO.ui.Layout
9300 * @mixins OO.ui.mixin.IconElement
9301 * @mixins OO.ui.mixin.LabelElement
9302 * @mixins OO.ui.mixin.GroupElement
9303 *
9304 * @constructor
9305 * @param {Object} [config] Configuration options
9306 * @cfg {OO.ui.FieldLayout[]} [items] An array of fields to add to the fieldset. See OO.ui.FieldLayout for more information about fields.
9307 */
9308 OO.ui.FieldsetLayout = function OoUiFieldsetLayout( config ) {
9309 // Configuration initialization
9310 config = config || {};
9311
9312 // Parent constructor
9313 OO.ui.FieldsetLayout.parent.call( this, config );
9314
9315 // Mixin constructors
9316 OO.ui.mixin.IconElement.call( this, config );
9317 OO.ui.mixin.LabelElement.call( this, config );
9318 OO.ui.mixin.GroupElement.call( this, config );
9319
9320 if ( config.help ) {
9321 this.popupButtonWidget = new OO.ui.PopupButtonWidget( {
9322 classes: [ 'oo-ui-fieldsetLayout-help' ],
9323 framed: false,
9324 icon: 'info'
9325 } );
9326
9327 this.popupButtonWidget.getPopup().$body.append(
9328 $( '<div>' )
9329 .text( config.help )
9330 .addClass( 'oo-ui-fieldsetLayout-help-content' )
9331 );
9332 this.$help = this.popupButtonWidget.$element;
9333 } else {
9334 this.$help = $( [] );
9335 }
9336
9337 // Initialization
9338 this.$element
9339 .addClass( 'oo-ui-fieldsetLayout' )
9340 .prepend( this.$help, this.$icon, this.$label, this.$group );
9341 if ( Array.isArray( config.items ) ) {
9342 this.addItems( config.items );
9343 }
9344 };
9345
9346 /* Setup */
9347
9348 OO.inheritClass( OO.ui.FieldsetLayout, OO.ui.Layout );
9349 OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.mixin.IconElement );
9350 OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.mixin.LabelElement );
9351 OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.mixin.GroupElement );
9352
9353 /**
9354 * FormLayouts are used to wrap {@link OO.ui.FieldsetLayout FieldsetLayouts} when you intend to use browser-based
9355 * form submission for the fields instead of handling them in JavaScript. Form layouts can be configured with an
9356 * HTML form action, an encoding type, and a method using the #action, #enctype, and #method configs, respectively.
9357 * See the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
9358 *
9359 * Only widgets from the {@link OO.ui.InputWidget InputWidget} family support form submission. It
9360 * includes standard form elements like {@link OO.ui.CheckboxInputWidget checkboxes}, {@link
9361 * OO.ui.RadioInputWidget radio buttons} and {@link OO.ui.TextInputWidget text fields}, as well as
9362 * some fancier controls. Some controls have both regular and InputWidget variants, for example
9363 * OO.ui.DropdownWidget and OO.ui.DropdownInputWidget – only the latter support form submission and
9364 * often have simplified APIs to match the capabilities of HTML forms.
9365 * See the [OOjs UI Inputs documentation on MediaWiki] [2] for more information about InputWidgets.
9366 *
9367 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Forms
9368 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
9369 *
9370 * @example
9371 * // Example of a form layout that wraps a fieldset layout
9372 * var input1 = new OO.ui.TextInputWidget( {
9373 * placeholder: 'Username'
9374 * } );
9375 * var input2 = new OO.ui.TextInputWidget( {
9376 * placeholder: 'Password',
9377 * type: 'password'
9378 * } );
9379 * var submit = new OO.ui.ButtonInputWidget( {
9380 * label: 'Submit'
9381 * } );
9382 *
9383 * var fieldset = new OO.ui.FieldsetLayout( {
9384 * label: 'A form layout'
9385 * } );
9386 * fieldset.addItems( [
9387 * new OO.ui.FieldLayout( input1, {
9388 * label: 'Username',
9389 * align: 'top'
9390 * } ),
9391 * new OO.ui.FieldLayout( input2, {
9392 * label: 'Password',
9393 * align: 'top'
9394 * } ),
9395 * new OO.ui.FieldLayout( submit )
9396 * ] );
9397 * var form = new OO.ui.FormLayout( {
9398 * items: [ fieldset ],
9399 * action: '/api/formhandler',
9400 * method: 'get'
9401 * } )
9402 * $( 'body' ).append( form.$element );
9403 *
9404 * @class
9405 * @extends OO.ui.Layout
9406 * @mixins OO.ui.mixin.GroupElement
9407 *
9408 * @constructor
9409 * @param {Object} [config] Configuration options
9410 * @cfg {string} [method] HTML form `method` attribute
9411 * @cfg {string} [action] HTML form `action` attribute
9412 * @cfg {string} [enctype] HTML form `enctype` attribute
9413 * @cfg {OO.ui.FieldsetLayout[]} [items] Fieldset layouts to add to the form layout.
9414 */
9415 OO.ui.FormLayout = function OoUiFormLayout( config ) {
9416 // Configuration initialization
9417 config = config || {};
9418
9419 // Parent constructor
9420 OO.ui.FormLayout.parent.call( this, config );
9421
9422 // Mixin constructors
9423 OO.ui.mixin.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) );
9424
9425 // Events
9426 this.$element.on( 'submit', this.onFormSubmit.bind( this ) );
9427
9428 // Make sure the action is safe
9429 if ( config.action !== undefined && !OO.ui.isSafeUrl( config.action ) ) {
9430 throw new Error( 'Potentially unsafe action provided: ' + config.action );
9431 }
9432
9433 // Initialization
9434 this.$element
9435 .addClass( 'oo-ui-formLayout' )
9436 .attr( {
9437 method: config.method,
9438 action: config.action,
9439 enctype: config.enctype
9440 } );
9441 if ( Array.isArray( config.items ) ) {
9442 this.addItems( config.items );
9443 }
9444 };
9445
9446 /* Setup */
9447
9448 OO.inheritClass( OO.ui.FormLayout, OO.ui.Layout );
9449 OO.mixinClass( OO.ui.FormLayout, OO.ui.mixin.GroupElement );
9450
9451 /* Events */
9452
9453 /**
9454 * A 'submit' event is emitted when the form is submitted.
9455 *
9456 * @event submit
9457 */
9458
9459 /* Static Properties */
9460
9461 OO.ui.FormLayout.static.tagName = 'form';
9462
9463 /* Methods */
9464
9465 /**
9466 * Handle form submit events.
9467 *
9468 * @private
9469 * @param {jQuery.Event} e Submit event
9470 * @fires submit
9471 */
9472 OO.ui.FormLayout.prototype.onFormSubmit = function () {
9473 if ( this.emit( 'submit' ) ) {
9474 return false;
9475 }
9476 };
9477
9478 /**
9479 * 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)
9480 * and its size is customized with the #menuSize config. The content area will fill all remaining space.
9481 *
9482 * @example
9483 * var menuLayout = new OO.ui.MenuLayout( {
9484 * position: 'top'
9485 * } ),
9486 * menuPanel = new OO.ui.PanelLayout( { padded: true, expanded: true, scrollable: true } ),
9487 * contentPanel = new OO.ui.PanelLayout( { padded: true, expanded: true, scrollable: true } ),
9488 * select = new OO.ui.SelectWidget( {
9489 * items: [
9490 * new OO.ui.OptionWidget( {
9491 * data: 'before',
9492 * label: 'Before',
9493 * } ),
9494 * new OO.ui.OptionWidget( {
9495 * data: 'after',
9496 * label: 'After',
9497 * } ),
9498 * new OO.ui.OptionWidget( {
9499 * data: 'top',
9500 * label: 'Top',
9501 * } ),
9502 * new OO.ui.OptionWidget( {
9503 * data: 'bottom',
9504 * label: 'Bottom',
9505 * } )
9506 * ]
9507 * } ).on( 'select', function ( item ) {
9508 * menuLayout.setMenuPosition( item.getData() );
9509 * } );
9510 *
9511 * menuLayout.$menu.append(
9512 * menuPanel.$element.append( '<b>Menu panel</b>', select.$element )
9513 * );
9514 * menuLayout.$content.append(
9515 * contentPanel.$element.append( '<b>Content panel</b>', '<p>Note that the menu is positioned relative to the content panel: top, bottom, after, before.</p>')
9516 * );
9517 * $( 'body' ).append( menuLayout.$element );
9518 *
9519 * If menu size needs to be overridden, it can be accomplished using CSS similar to the snippet
9520 * below. MenuLayout's CSS will override the appropriate values with 'auto' or '0' to display the
9521 * menu correctly. If `menuPosition` is known beforehand, CSS rules corresponding to other positions
9522 * may be omitted.
9523 *
9524 * .oo-ui-menuLayout-menu {
9525 * height: 200px;
9526 * width: 200px;
9527 * }
9528 * .oo-ui-menuLayout-content {
9529 * top: 200px;
9530 * left: 200px;
9531 * right: 200px;
9532 * bottom: 200px;
9533 * }
9534 *
9535 * @class
9536 * @extends OO.ui.Layout
9537 *
9538 * @constructor
9539 * @param {Object} [config] Configuration options
9540 * @cfg {boolean} [showMenu=true] Show menu
9541 * @cfg {string} [menuPosition='before'] Position of menu: `top`, `after`, `bottom` or `before`
9542 */
9543 OO.ui.MenuLayout = function OoUiMenuLayout( config ) {
9544 // Configuration initialization
9545 config = $.extend( {
9546 showMenu: true,
9547 menuPosition: 'before'
9548 }, config );
9549
9550 // Parent constructor
9551 OO.ui.MenuLayout.parent.call( this, config );
9552
9553 /**
9554 * Menu DOM node
9555 *
9556 * @property {jQuery}
9557 */
9558 this.$menu = $( '<div>' );
9559 /**
9560 * Content DOM node
9561 *
9562 * @property {jQuery}
9563 */
9564 this.$content = $( '<div>' );
9565
9566 // Initialization
9567 this.$menu
9568 .addClass( 'oo-ui-menuLayout-menu' );
9569 this.$content.addClass( 'oo-ui-menuLayout-content' );
9570 this.$element
9571 .addClass( 'oo-ui-menuLayout' )
9572 .append( this.$content, this.$menu );
9573 this.setMenuPosition( config.menuPosition );
9574 this.toggleMenu( config.showMenu );
9575 };
9576
9577 /* Setup */
9578
9579 OO.inheritClass( OO.ui.MenuLayout, OO.ui.Layout );
9580
9581 /* Methods */
9582
9583 /**
9584 * Toggle menu.
9585 *
9586 * @param {boolean} showMenu Show menu, omit to toggle
9587 * @chainable
9588 */
9589 OO.ui.MenuLayout.prototype.toggleMenu = function ( showMenu ) {
9590 showMenu = showMenu === undefined ? !this.showMenu : !!showMenu;
9591
9592 if ( this.showMenu !== showMenu ) {
9593 this.showMenu = showMenu;
9594 this.$element
9595 .toggleClass( 'oo-ui-menuLayout-showMenu', this.showMenu )
9596 .toggleClass( 'oo-ui-menuLayout-hideMenu', !this.showMenu );
9597 }
9598
9599 return this;
9600 };
9601
9602 /**
9603 * Check if menu is visible
9604 *
9605 * @return {boolean} Menu is visible
9606 */
9607 OO.ui.MenuLayout.prototype.isMenuVisible = function () {
9608 return this.showMenu;
9609 };
9610
9611 /**
9612 * Set menu position.
9613 *
9614 * @param {string} position Position of menu, either `top`, `after`, `bottom` or `before`
9615 * @throws {Error} If position value is not supported
9616 * @chainable
9617 */
9618 OO.ui.MenuLayout.prototype.setMenuPosition = function ( position ) {
9619 this.$element.removeClass( 'oo-ui-menuLayout-' + this.menuPosition );
9620 this.menuPosition = position;
9621 this.$element.addClass( 'oo-ui-menuLayout-' + position );
9622
9623 return this;
9624 };
9625
9626 /**
9627 * Get menu position.
9628 *
9629 * @return {string} Menu position
9630 */
9631 OO.ui.MenuLayout.prototype.getMenuPosition = function () {
9632 return this.menuPosition;
9633 };
9634
9635 /**
9636 * BookletLayouts contain {@link OO.ui.PageLayout page layouts} as well as
9637 * an {@link OO.ui.OutlineSelectWidget outline} that allows users to easily navigate
9638 * through the pages and select which one to display. By default, only one page is
9639 * displayed at a time and the outline is hidden. When a user navigates to a new page,
9640 * the booklet layout automatically focuses on the first focusable element, unless the
9641 * default setting is changed. Optionally, booklets can be configured to show
9642 * {@link OO.ui.OutlineControlsWidget controls} for adding, moving, and removing items.
9643 *
9644 * @example
9645 * // Example of a BookletLayout that contains two PageLayouts.
9646 *
9647 * function PageOneLayout( name, config ) {
9648 * PageOneLayout.parent.call( this, name, config );
9649 * this.$element.append( '<p>First page</p><p>(This booklet has an outline, displayed on the left)</p>' );
9650 * }
9651 * OO.inheritClass( PageOneLayout, OO.ui.PageLayout );
9652 * PageOneLayout.prototype.setupOutlineItem = function () {
9653 * this.outlineItem.setLabel( 'Page One' );
9654 * };
9655 *
9656 * function PageTwoLayout( name, config ) {
9657 * PageTwoLayout.parent.call( this, name, config );
9658 * this.$element.append( '<p>Second page</p>' );
9659 * }
9660 * OO.inheritClass( PageTwoLayout, OO.ui.PageLayout );
9661 * PageTwoLayout.prototype.setupOutlineItem = function () {
9662 * this.outlineItem.setLabel( 'Page Two' );
9663 * };
9664 *
9665 * var page1 = new PageOneLayout( 'one' ),
9666 * page2 = new PageTwoLayout( 'two' );
9667 *
9668 * var booklet = new OO.ui.BookletLayout( {
9669 * outlined: true
9670 * } );
9671 *
9672 * booklet.addPages ( [ page1, page2 ] );
9673 * $( 'body' ).append( booklet.$element );
9674 *
9675 * @class
9676 * @extends OO.ui.MenuLayout
9677 *
9678 * @constructor
9679 * @param {Object} [config] Configuration options
9680 * @cfg {boolean} [continuous=false] Show all pages, one after another
9681 * @cfg {boolean} [autoFocus=true] Focus on the first focusable element when a new page is displayed.
9682 * @cfg {boolean} [outlined=false] Show the outline. The outline is used to navigate through the pages of the booklet.
9683 * @cfg {boolean} [editable=false] Show controls for adding, removing and reordering pages
9684 */
9685 OO.ui.BookletLayout = function OoUiBookletLayout( config ) {
9686 // Configuration initialization
9687 config = config || {};
9688
9689 // Parent constructor
9690 OO.ui.BookletLayout.parent.call( this, config );
9691
9692 // Properties
9693 this.currentPageName = null;
9694 this.pages = {};
9695 this.ignoreFocus = false;
9696 this.stackLayout = new OO.ui.StackLayout( { continuous: !!config.continuous } );
9697 this.$content.append( this.stackLayout.$element );
9698 this.autoFocus = config.autoFocus === undefined || !!config.autoFocus;
9699 this.outlineVisible = false;
9700 this.outlined = !!config.outlined;
9701 if ( this.outlined ) {
9702 this.editable = !!config.editable;
9703 this.outlineControlsWidget = null;
9704 this.outlineSelectWidget = new OO.ui.OutlineSelectWidget();
9705 this.outlinePanel = new OO.ui.PanelLayout( { scrollable: true } );
9706 this.$menu.append( this.outlinePanel.$element );
9707 this.outlineVisible = true;
9708 if ( this.editable ) {
9709 this.outlineControlsWidget = new OO.ui.OutlineControlsWidget(
9710 this.outlineSelectWidget
9711 );
9712 }
9713 }
9714 this.toggleMenu( this.outlined );
9715
9716 // Events
9717 this.stackLayout.connect( this, { set: 'onStackLayoutSet' } );
9718 if ( this.outlined ) {
9719 this.outlineSelectWidget.connect( this, { select: 'onOutlineSelectWidgetSelect' } );
9720 }
9721 if ( this.autoFocus ) {
9722 // Event 'focus' does not bubble, but 'focusin' does
9723 this.stackLayout.$element.on( 'focusin', this.onStackLayoutFocus.bind( this ) );
9724 }
9725
9726 // Initialization
9727 this.$element.addClass( 'oo-ui-bookletLayout' );
9728 this.stackLayout.$element.addClass( 'oo-ui-bookletLayout-stackLayout' );
9729 if ( this.outlined ) {
9730 this.outlinePanel.$element
9731 .addClass( 'oo-ui-bookletLayout-outlinePanel' )
9732 .append( this.outlineSelectWidget.$element );
9733 if ( this.editable ) {
9734 this.outlinePanel.$element
9735 .addClass( 'oo-ui-bookletLayout-outlinePanel-editable' )
9736 .append( this.outlineControlsWidget.$element );
9737 }
9738 }
9739 };
9740
9741 /* Setup */
9742
9743 OO.inheritClass( OO.ui.BookletLayout, OO.ui.MenuLayout );
9744
9745 /* Events */
9746
9747 /**
9748 * A 'set' event is emitted when a page is {@link #setPage set} to be displayed by the booklet layout.
9749 * @event set
9750 * @param {OO.ui.PageLayout} page Current page
9751 */
9752
9753 /**
9754 * An 'add' event is emitted when pages are {@link #addPages added} to the booklet layout.
9755 *
9756 * @event add
9757 * @param {OO.ui.PageLayout[]} page Added pages
9758 * @param {number} index Index pages were added at
9759 */
9760
9761 /**
9762 * A 'remove' event is emitted when pages are {@link #clearPages cleared} or
9763 * {@link #removePages removed} from the booklet.
9764 *
9765 * @event remove
9766 * @param {OO.ui.PageLayout[]} pages Removed pages
9767 */
9768
9769 /* Methods */
9770
9771 /**
9772 * Handle stack layout focus.
9773 *
9774 * @private
9775 * @param {jQuery.Event} e Focusin event
9776 */
9777 OO.ui.BookletLayout.prototype.onStackLayoutFocus = function ( e ) {
9778 var name, $target;
9779
9780 // Find the page that an element was focused within
9781 $target = $( e.target ).closest( '.oo-ui-pageLayout' );
9782 for ( name in this.pages ) {
9783 // Check for page match, exclude current page to find only page changes
9784 if ( this.pages[ name ].$element[ 0 ] === $target[ 0 ] && name !== this.currentPageName ) {
9785 this.setPage( name );
9786 break;
9787 }
9788 }
9789 };
9790
9791 /**
9792 * Handle stack layout set events.
9793 *
9794 * @private
9795 * @param {OO.ui.PanelLayout|null} page The page panel that is now the current panel
9796 */
9797 OO.ui.BookletLayout.prototype.onStackLayoutSet = function ( page ) {
9798 var layout = this;
9799 if ( page ) {
9800 page.scrollElementIntoView( { complete: function () {
9801 if ( layout.autoFocus ) {
9802 layout.focus();
9803 }
9804 } } );
9805 }
9806 };
9807
9808 /**
9809 * Focus the first input in the current page.
9810 *
9811 * If no page is selected, the first selectable page will be selected.
9812 * If the focus is already in an element on the current page, nothing will happen.
9813 * @param {number} [itemIndex] A specific item to focus on
9814 */
9815 OO.ui.BookletLayout.prototype.focus = function ( itemIndex ) {
9816 var page,
9817 items = this.stackLayout.getItems();
9818
9819 if ( itemIndex !== undefined && items[ itemIndex ] ) {
9820 page = items[ itemIndex ];
9821 } else {
9822 page = this.stackLayout.getCurrentItem();
9823 }
9824
9825 if ( !page && this.outlined ) {
9826 this.selectFirstSelectablePage();
9827 page = this.stackLayout.getCurrentItem();
9828 }
9829 if ( !page ) {
9830 return;
9831 }
9832 // Only change the focus if is not already in the current page
9833 if ( !page.$element.find( ':focus' ).length ) {
9834 OO.ui.findFocusable( page.$element ).focus();
9835 }
9836 };
9837
9838 /**
9839 * Find the first focusable input in the booklet layout and focus
9840 * on it.
9841 */
9842 OO.ui.BookletLayout.prototype.focusFirstFocusable = function () {
9843 OO.ui.findFocusable( this.stackLayout.$element ).focus();
9844 };
9845
9846 /**
9847 * Handle outline widget select events.
9848 *
9849 * @private
9850 * @param {OO.ui.OptionWidget|null} item Selected item
9851 */
9852 OO.ui.BookletLayout.prototype.onOutlineSelectWidgetSelect = function ( item ) {
9853 if ( item ) {
9854 this.setPage( item.getData() );
9855 }
9856 };
9857
9858 /**
9859 * Check if booklet has an outline.
9860 *
9861 * @return {boolean} Booklet has an outline
9862 */
9863 OO.ui.BookletLayout.prototype.isOutlined = function () {
9864 return this.outlined;
9865 };
9866
9867 /**
9868 * Check if booklet has editing controls.
9869 *
9870 * @return {boolean} Booklet is editable
9871 */
9872 OO.ui.BookletLayout.prototype.isEditable = function () {
9873 return this.editable;
9874 };
9875
9876 /**
9877 * Check if booklet has a visible outline.
9878 *
9879 * @return {boolean} Outline is visible
9880 */
9881 OO.ui.BookletLayout.prototype.isOutlineVisible = function () {
9882 return this.outlined && this.outlineVisible;
9883 };
9884
9885 /**
9886 * Hide or show the outline.
9887 *
9888 * @param {boolean} [show] Show outline, omit to invert current state
9889 * @chainable
9890 */
9891 OO.ui.BookletLayout.prototype.toggleOutline = function ( show ) {
9892 if ( this.outlined ) {
9893 show = show === undefined ? !this.outlineVisible : !!show;
9894 this.outlineVisible = show;
9895 this.toggleMenu( show );
9896 }
9897
9898 return this;
9899 };
9900
9901 /**
9902 * Get the page closest to the specified page.
9903 *
9904 * @param {OO.ui.PageLayout} page Page to use as a reference point
9905 * @return {OO.ui.PageLayout|null} Page closest to the specified page
9906 */
9907 OO.ui.BookletLayout.prototype.getClosestPage = function ( page ) {
9908 var next, prev, level,
9909 pages = this.stackLayout.getItems(),
9910 index = pages.indexOf( page );
9911
9912 if ( index !== -1 ) {
9913 next = pages[ index + 1 ];
9914 prev = pages[ index - 1 ];
9915 // Prefer adjacent pages at the same level
9916 if ( this.outlined ) {
9917 level = this.outlineSelectWidget.getItemFromData( page.getName() ).getLevel();
9918 if (
9919 prev &&
9920 level === this.outlineSelectWidget.getItemFromData( prev.getName() ).getLevel()
9921 ) {
9922 return prev;
9923 }
9924 if (
9925 next &&
9926 level === this.outlineSelectWidget.getItemFromData( next.getName() ).getLevel()
9927 ) {
9928 return next;
9929 }
9930 }
9931 }
9932 return prev || next || null;
9933 };
9934
9935 /**
9936 * Get the outline widget.
9937 *
9938 * If the booklet is not outlined, the method will return `null`.
9939 *
9940 * @return {OO.ui.OutlineSelectWidget|null} Outline widget, or null if the booklet is not outlined
9941 */
9942 OO.ui.BookletLayout.prototype.getOutline = function () {
9943 return this.outlineSelectWidget;
9944 };
9945
9946 /**
9947 * Get the outline controls widget.
9948 *
9949 * If the outline is not editable, the method will return `null`.
9950 *
9951 * @return {OO.ui.OutlineControlsWidget|null} The outline controls widget.
9952 */
9953 OO.ui.BookletLayout.prototype.getOutlineControls = function () {
9954 return this.outlineControlsWidget;
9955 };
9956
9957 /**
9958 * Get a page by its symbolic name.
9959 *
9960 * @param {string} name Symbolic name of page
9961 * @return {OO.ui.PageLayout|undefined} Page, if found
9962 */
9963 OO.ui.BookletLayout.prototype.getPage = function ( name ) {
9964 return this.pages[ name ];
9965 };
9966
9967 /**
9968 * Get the current page.
9969 *
9970 * @return {OO.ui.PageLayout|undefined} Current page, if found
9971 */
9972 OO.ui.BookletLayout.prototype.getCurrentPage = function () {
9973 var name = this.getCurrentPageName();
9974 return name ? this.getPage( name ) : undefined;
9975 };
9976
9977 /**
9978 * Get the symbolic name of the current page.
9979 *
9980 * @return {string|null} Symbolic name of the current page
9981 */
9982 OO.ui.BookletLayout.prototype.getCurrentPageName = function () {
9983 return this.currentPageName;
9984 };
9985
9986 /**
9987 * Add pages to the booklet layout
9988 *
9989 * When pages are added with the same names as existing pages, the existing pages will be
9990 * automatically removed before the new pages are added.
9991 *
9992 * @param {OO.ui.PageLayout[]} pages Pages to add
9993 * @param {number} index Index of the insertion point
9994 * @fires add
9995 * @chainable
9996 */
9997 OO.ui.BookletLayout.prototype.addPages = function ( pages, index ) {
9998 var i, len, name, page, item, currentIndex,
9999 stackLayoutPages = this.stackLayout.getItems(),
10000 remove = [],
10001 items = [];
10002
10003 // Remove pages with same names
10004 for ( i = 0, len = pages.length; i < len; i++ ) {
10005 page = pages[ i ];
10006 name = page.getName();
10007
10008 if ( Object.prototype.hasOwnProperty.call( this.pages, name ) ) {
10009 // Correct the insertion index
10010 currentIndex = stackLayoutPages.indexOf( this.pages[ name ] );
10011 if ( currentIndex !== -1 && currentIndex + 1 < index ) {
10012 index--;
10013 }
10014 remove.push( this.pages[ name ] );
10015 }
10016 }
10017 if ( remove.length ) {
10018 this.removePages( remove );
10019 }
10020
10021 // Add new pages
10022 for ( i = 0, len = pages.length; i < len; i++ ) {
10023 page = pages[ i ];
10024 name = page.getName();
10025 this.pages[ page.getName() ] = page;
10026 if ( this.outlined ) {
10027 item = new OO.ui.OutlineOptionWidget( { data: name } );
10028 page.setOutlineItem( item );
10029 items.push( item );
10030 }
10031 }
10032
10033 if ( this.outlined && items.length ) {
10034 this.outlineSelectWidget.addItems( items, index );
10035 this.selectFirstSelectablePage();
10036 }
10037 this.stackLayout.addItems( pages, index );
10038 this.emit( 'add', pages, index );
10039
10040 return this;
10041 };
10042
10043 /**
10044 * Remove the specified pages from the booklet layout.
10045 *
10046 * To remove all pages from the booklet, you may wish to use the #clearPages method instead.
10047 *
10048 * @param {OO.ui.PageLayout[]} pages An array of pages to remove
10049 * @fires remove
10050 * @chainable
10051 */
10052 OO.ui.BookletLayout.prototype.removePages = function ( pages ) {
10053 var i, len, name, page,
10054 items = [];
10055
10056 for ( i = 0, len = pages.length; i < len; i++ ) {
10057 page = pages[ i ];
10058 name = page.getName();
10059 delete this.pages[ name ];
10060 if ( this.outlined ) {
10061 items.push( this.outlineSelectWidget.getItemFromData( name ) );
10062 page.setOutlineItem( null );
10063 }
10064 }
10065 if ( this.outlined && items.length ) {
10066 this.outlineSelectWidget.removeItems( items );
10067 this.selectFirstSelectablePage();
10068 }
10069 this.stackLayout.removeItems( pages );
10070 this.emit( 'remove', pages );
10071
10072 return this;
10073 };
10074
10075 /**
10076 * Clear all pages from the booklet layout.
10077 *
10078 * To remove only a subset of pages from the booklet, use the #removePages method.
10079 *
10080 * @fires remove
10081 * @chainable
10082 */
10083 OO.ui.BookletLayout.prototype.clearPages = function () {
10084 var i, len,
10085 pages = this.stackLayout.getItems();
10086
10087 this.pages = {};
10088 this.currentPageName = null;
10089 if ( this.outlined ) {
10090 this.outlineSelectWidget.clearItems();
10091 for ( i = 0, len = pages.length; i < len; i++ ) {
10092 pages[ i ].setOutlineItem( null );
10093 }
10094 }
10095 this.stackLayout.clearItems();
10096
10097 this.emit( 'remove', pages );
10098
10099 return this;
10100 };
10101
10102 /**
10103 * Set the current page by symbolic name.
10104 *
10105 * @fires set
10106 * @param {string} name Symbolic name of page
10107 */
10108 OO.ui.BookletLayout.prototype.setPage = function ( name ) {
10109 var selectedItem,
10110 $focused,
10111 page = this.pages[ name ],
10112 previousPage = this.currentPageName && this.pages[ this.currentPageName ];
10113
10114 if ( name !== this.currentPageName ) {
10115 if ( this.outlined ) {
10116 selectedItem = this.outlineSelectWidget.getSelectedItem();
10117 if ( selectedItem && selectedItem.getData() !== name ) {
10118 this.outlineSelectWidget.selectItemByData( name );
10119 }
10120 }
10121 if ( page ) {
10122 if ( previousPage ) {
10123 previousPage.setActive( false );
10124 // Blur anything focused if the next page doesn't have anything focusable.
10125 // This is not needed if the next page has something focusable (because once it is focused
10126 // this blur happens automatically). If the layout is non-continuous, this check is
10127 // meaningless because the next page is not visible yet and thus can't hold focus.
10128 if (
10129 this.autoFocus &&
10130 this.stackLayout.continuous &&
10131 OO.ui.findFocusable( page.$element ).length !== 0
10132 ) {
10133 $focused = previousPage.$element.find( ':focus' );
10134 if ( $focused.length ) {
10135 $focused[ 0 ].blur();
10136 }
10137 }
10138 }
10139 this.currentPageName = name;
10140 page.setActive( true );
10141 this.stackLayout.setItem( page );
10142 if ( !this.stackLayout.continuous && previousPage ) {
10143 // This should not be necessary, since any inputs on the previous page should have been
10144 // blurred when it was hidden, but browsers are not very consistent about this.
10145 $focused = previousPage.$element.find( ':focus' );
10146 if ( $focused.length ) {
10147 $focused[ 0 ].blur();
10148 }
10149 }
10150 this.emit( 'set', page );
10151 }
10152 }
10153 };
10154
10155 /**
10156 * Select the first selectable page.
10157 *
10158 * @chainable
10159 */
10160 OO.ui.BookletLayout.prototype.selectFirstSelectablePage = function () {
10161 if ( !this.outlineSelectWidget.getSelectedItem() ) {
10162 this.outlineSelectWidget.selectItem( this.outlineSelectWidget.getFirstSelectableItem() );
10163 }
10164
10165 return this;
10166 };
10167
10168 /**
10169 * IndexLayouts contain {@link OO.ui.CardLayout card layouts} as well as
10170 * {@link OO.ui.TabSelectWidget tabs} that allow users to easily navigate through the cards and
10171 * select which one to display. By default, only one card is displayed at a time. When a user
10172 * navigates to a new card, the index layout automatically focuses on the first focusable element,
10173 * unless the default setting is changed.
10174 *
10175 * TODO: This class is similar to BookletLayout, we may want to refactor to reduce duplication
10176 *
10177 * @example
10178 * // Example of a IndexLayout that contains two CardLayouts.
10179 *
10180 * function CardOneLayout( name, config ) {
10181 * CardOneLayout.parent.call( this, name, config );
10182 * this.$element.append( '<p>First card</p>' );
10183 * }
10184 * OO.inheritClass( CardOneLayout, OO.ui.CardLayout );
10185 * CardOneLayout.prototype.setupTabItem = function () {
10186 * this.tabItem.setLabel( 'Card one' );
10187 * };
10188 *
10189 * var card1 = new CardOneLayout( 'one' ),
10190 * card2 = new CardLayout( 'two', { label: 'Card two' } );
10191 *
10192 * card2.$element.append( '<p>Second card</p>' );
10193 *
10194 * var index = new OO.ui.IndexLayout();
10195 *
10196 * index.addCards ( [ card1, card2 ] );
10197 * $( 'body' ).append( index.$element );
10198 *
10199 * @class
10200 * @extends OO.ui.MenuLayout
10201 *
10202 * @constructor
10203 * @param {Object} [config] Configuration options
10204 * @cfg {boolean} [continuous=false] Show all cards, one after another
10205 * @cfg {boolean} [expanded=true] Expand the content panel to fill the entire parent element.
10206 * @cfg {boolean} [autoFocus=true] Focus on the first focusable element when a new card is displayed.
10207 */
10208 OO.ui.IndexLayout = function OoUiIndexLayout( config ) {
10209 // Configuration initialization
10210 config = $.extend( {}, config, { menuPosition: 'top' } );
10211
10212 // Parent constructor
10213 OO.ui.IndexLayout.parent.call( this, config );
10214
10215 // Properties
10216 this.currentCardName = null;
10217 this.cards = {};
10218 this.ignoreFocus = false;
10219 this.stackLayout = new OO.ui.StackLayout( {
10220 continuous: !!config.continuous,
10221 expanded: config.expanded
10222 } );
10223 this.$content.append( this.stackLayout.$element );
10224 this.autoFocus = config.autoFocus === undefined || !!config.autoFocus;
10225
10226 this.tabSelectWidget = new OO.ui.TabSelectWidget();
10227 this.tabPanel = new OO.ui.PanelLayout();
10228 this.$menu.append( this.tabPanel.$element );
10229
10230 this.toggleMenu( true );
10231
10232 // Events
10233 this.stackLayout.connect( this, { set: 'onStackLayoutSet' } );
10234 this.tabSelectWidget.connect( this, { select: 'onTabSelectWidgetSelect' } );
10235 if ( this.autoFocus ) {
10236 // Event 'focus' does not bubble, but 'focusin' does
10237 this.stackLayout.$element.on( 'focusin', this.onStackLayoutFocus.bind( this ) );
10238 }
10239
10240 // Initialization
10241 this.$element.addClass( 'oo-ui-indexLayout' );
10242 this.stackLayout.$element.addClass( 'oo-ui-indexLayout-stackLayout' );
10243 this.tabPanel.$element
10244 .addClass( 'oo-ui-indexLayout-tabPanel' )
10245 .append( this.tabSelectWidget.$element );
10246 };
10247
10248 /* Setup */
10249
10250 OO.inheritClass( OO.ui.IndexLayout, OO.ui.MenuLayout );
10251
10252 /* Events */
10253
10254 /**
10255 * A 'set' event is emitted when a card is {@link #setCard set} to be displayed by the index layout.
10256 * @event set
10257 * @param {OO.ui.CardLayout} card Current card
10258 */
10259
10260 /**
10261 * An 'add' event is emitted when cards are {@link #addCards added} to the index layout.
10262 *
10263 * @event add
10264 * @param {OO.ui.CardLayout[]} card Added cards
10265 * @param {number} index Index cards were added at
10266 */
10267
10268 /**
10269 * A 'remove' event is emitted when cards are {@link #clearCards cleared} or
10270 * {@link #removeCards removed} from the index.
10271 *
10272 * @event remove
10273 * @param {OO.ui.CardLayout[]} cards Removed cards
10274 */
10275
10276 /* Methods */
10277
10278 /**
10279 * Handle stack layout focus.
10280 *
10281 * @private
10282 * @param {jQuery.Event} e Focusin event
10283 */
10284 OO.ui.IndexLayout.prototype.onStackLayoutFocus = function ( e ) {
10285 var name, $target;
10286
10287 // Find the card that an element was focused within
10288 $target = $( e.target ).closest( '.oo-ui-cardLayout' );
10289 for ( name in this.cards ) {
10290 // Check for card match, exclude current card to find only card changes
10291 if ( this.cards[ name ].$element[ 0 ] === $target[ 0 ] && name !== this.currentCardName ) {
10292 this.setCard( name );
10293 break;
10294 }
10295 }
10296 };
10297
10298 /**
10299 * Handle stack layout set events.
10300 *
10301 * @private
10302 * @param {OO.ui.PanelLayout|null} card The card panel that is now the current panel
10303 */
10304 OO.ui.IndexLayout.prototype.onStackLayoutSet = function ( card ) {
10305 var layout = this;
10306 if ( card ) {
10307 card.scrollElementIntoView( { complete: function () {
10308 if ( layout.autoFocus ) {
10309 layout.focus();
10310 }
10311 } } );
10312 }
10313 };
10314
10315 /**
10316 * Focus the first input in the current card.
10317 *
10318 * If no card is selected, the first selectable card will be selected.
10319 * If the focus is already in an element on the current card, nothing will happen.
10320 * @param {number} [itemIndex] A specific item to focus on
10321 */
10322 OO.ui.IndexLayout.prototype.focus = function ( itemIndex ) {
10323 var card,
10324 items = this.stackLayout.getItems();
10325
10326 if ( itemIndex !== undefined && items[ itemIndex ] ) {
10327 card = items[ itemIndex ];
10328 } else {
10329 card = this.stackLayout.getCurrentItem();
10330 }
10331
10332 if ( !card ) {
10333 this.selectFirstSelectableCard();
10334 card = this.stackLayout.getCurrentItem();
10335 }
10336 if ( !card ) {
10337 return;
10338 }
10339 // Only change the focus if is not already in the current card
10340 if ( !card.$element.find( ':focus' ).length ) {
10341 OO.ui.findFocusable( card.$element ).focus();
10342 }
10343 };
10344
10345 /**
10346 * Find the first focusable input in the index layout and focus
10347 * on it.
10348 */
10349 OO.ui.IndexLayout.prototype.focusFirstFocusable = function () {
10350 OO.ui.findFocusable( this.stackLayout.$element ).focus();
10351 };
10352
10353 /**
10354 * Handle tab widget select events.
10355 *
10356 * @private
10357 * @param {OO.ui.OptionWidget|null} item Selected item
10358 */
10359 OO.ui.IndexLayout.prototype.onTabSelectWidgetSelect = function ( item ) {
10360 if ( item ) {
10361 this.setCard( item.getData() );
10362 }
10363 };
10364
10365 /**
10366 * Get the card closest to the specified card.
10367 *
10368 * @param {OO.ui.CardLayout} card Card to use as a reference point
10369 * @return {OO.ui.CardLayout|null} Card closest to the specified card
10370 */
10371 OO.ui.IndexLayout.prototype.getClosestCard = function ( card ) {
10372 var next, prev, level,
10373 cards = this.stackLayout.getItems(),
10374 index = cards.indexOf( card );
10375
10376 if ( index !== -1 ) {
10377 next = cards[ index + 1 ];
10378 prev = cards[ index - 1 ];
10379 // Prefer adjacent cards at the same level
10380 level = this.tabSelectWidget.getItemFromData( card.getName() ).getLevel();
10381 if (
10382 prev &&
10383 level === this.tabSelectWidget.getItemFromData( prev.getName() ).getLevel()
10384 ) {
10385 return prev;
10386 }
10387 if (
10388 next &&
10389 level === this.tabSelectWidget.getItemFromData( next.getName() ).getLevel()
10390 ) {
10391 return next;
10392 }
10393 }
10394 return prev || next || null;
10395 };
10396
10397 /**
10398 * Get the tabs widget.
10399 *
10400 * @return {OO.ui.TabSelectWidget} Tabs widget
10401 */
10402 OO.ui.IndexLayout.prototype.getTabs = function () {
10403 return this.tabSelectWidget;
10404 };
10405
10406 /**
10407 * Get a card by its symbolic name.
10408 *
10409 * @param {string} name Symbolic name of card
10410 * @return {OO.ui.CardLayout|undefined} Card, if found
10411 */
10412 OO.ui.IndexLayout.prototype.getCard = function ( name ) {
10413 return this.cards[ name ];
10414 };
10415
10416 /**
10417 * Get the current card.
10418 *
10419 * @return {OO.ui.CardLayout|undefined} Current card, if found
10420 */
10421 OO.ui.IndexLayout.prototype.getCurrentCard = function () {
10422 var name = this.getCurrentCardName();
10423 return name ? this.getCard( name ) : undefined;
10424 };
10425
10426 /**
10427 * Get the symbolic name of the current card.
10428 *
10429 * @return {string|null} Symbolic name of the current card
10430 */
10431 OO.ui.IndexLayout.prototype.getCurrentCardName = function () {
10432 return this.currentCardName;
10433 };
10434
10435 /**
10436 * Add cards to the index layout
10437 *
10438 * When cards are added with the same names as existing cards, the existing cards will be
10439 * automatically removed before the new cards are added.
10440 *
10441 * @param {OO.ui.CardLayout[]} cards Cards to add
10442 * @param {number} index Index of the insertion point
10443 * @fires add
10444 * @chainable
10445 */
10446 OO.ui.IndexLayout.prototype.addCards = function ( cards, index ) {
10447 var i, len, name, card, item, currentIndex,
10448 stackLayoutCards = this.stackLayout.getItems(),
10449 remove = [],
10450 items = [];
10451
10452 // Remove cards with same names
10453 for ( i = 0, len = cards.length; i < len; i++ ) {
10454 card = cards[ i ];
10455 name = card.getName();
10456
10457 if ( Object.prototype.hasOwnProperty.call( this.cards, name ) ) {
10458 // Correct the insertion index
10459 currentIndex = stackLayoutCards.indexOf( this.cards[ name ] );
10460 if ( currentIndex !== -1 && currentIndex + 1 < index ) {
10461 index--;
10462 }
10463 remove.push( this.cards[ name ] );
10464 }
10465 }
10466 if ( remove.length ) {
10467 this.removeCards( remove );
10468 }
10469
10470 // Add new cards
10471 for ( i = 0, len = cards.length; i < len; i++ ) {
10472 card = cards[ i ];
10473 name = card.getName();
10474 this.cards[ card.getName() ] = card;
10475 item = new OO.ui.TabOptionWidget( { data: name } );
10476 card.setTabItem( item );
10477 items.push( item );
10478 }
10479
10480 if ( items.length ) {
10481 this.tabSelectWidget.addItems( items, index );
10482 this.selectFirstSelectableCard();
10483 }
10484 this.stackLayout.addItems( cards, index );
10485 this.emit( 'add', cards, index );
10486
10487 return this;
10488 };
10489
10490 /**
10491 * Remove the specified cards from the index layout.
10492 *
10493 * To remove all cards from the index, you may wish to use the #clearCards method instead.
10494 *
10495 * @param {OO.ui.CardLayout[]} cards An array of cards to remove
10496 * @fires remove
10497 * @chainable
10498 */
10499 OO.ui.IndexLayout.prototype.removeCards = function ( cards ) {
10500 var i, len, name, card,
10501 items = [];
10502
10503 for ( i = 0, len = cards.length; i < len; i++ ) {
10504 card = cards[ i ];
10505 name = card.getName();
10506 delete this.cards[ name ];
10507 items.push( this.tabSelectWidget.getItemFromData( name ) );
10508 card.setTabItem( null );
10509 }
10510 if ( items.length ) {
10511 this.tabSelectWidget.removeItems( items );
10512 this.selectFirstSelectableCard();
10513 }
10514 this.stackLayout.removeItems( cards );
10515 this.emit( 'remove', cards );
10516
10517 return this;
10518 };
10519
10520 /**
10521 * Clear all cards from the index layout.
10522 *
10523 * To remove only a subset of cards from the index, use the #removeCards method.
10524 *
10525 * @fires remove
10526 * @chainable
10527 */
10528 OO.ui.IndexLayout.prototype.clearCards = function () {
10529 var i, len,
10530 cards = this.stackLayout.getItems();
10531
10532 this.cards = {};
10533 this.currentCardName = null;
10534 this.tabSelectWidget.clearItems();
10535 for ( i = 0, len = cards.length; i < len; i++ ) {
10536 cards[ i ].setTabItem( null );
10537 }
10538 this.stackLayout.clearItems();
10539
10540 this.emit( 'remove', cards );
10541
10542 return this;
10543 };
10544
10545 /**
10546 * Set the current card by symbolic name.
10547 *
10548 * @fires set
10549 * @param {string} name Symbolic name of card
10550 */
10551 OO.ui.IndexLayout.prototype.setCard = function ( name ) {
10552 var selectedItem,
10553 $focused,
10554 card = this.cards[ name ],
10555 previousCard = this.currentCardName && this.cards[ this.currentCardName ];
10556
10557 if ( name !== this.currentCardName ) {
10558 selectedItem = this.tabSelectWidget.getSelectedItem();
10559 if ( selectedItem && selectedItem.getData() !== name ) {
10560 this.tabSelectWidget.selectItemByData( name );
10561 }
10562 if ( card ) {
10563 if ( previousCard ) {
10564 previousCard.setActive( false );
10565 // Blur anything focused if the next card doesn't have anything focusable.
10566 // This is not needed if the next card has something focusable (because once it is focused
10567 // this blur happens automatically). If the layout is non-continuous, this check is
10568 // meaningless because the next card is not visible yet and thus can't hold focus.
10569 if (
10570 this.autoFocus &&
10571 this.stackLayout.continuous &&
10572 OO.ui.findFocusable( card.$element ).length !== 0
10573 ) {
10574 $focused = previousCard.$element.find( ':focus' );
10575 if ( $focused.length ) {
10576 $focused[ 0 ].blur();
10577 }
10578 }
10579 }
10580 this.currentCardName = name;
10581 card.setActive( true );
10582 this.stackLayout.setItem( card );
10583 if ( !this.stackLayout.continuous && previousCard ) {
10584 // This should not be necessary, since any inputs on the previous card should have been
10585 // blurred when it was hidden, but browsers are not very consistent about this.
10586 $focused = previousCard.$element.find( ':focus' );
10587 if ( $focused.length ) {
10588 $focused[ 0 ].blur();
10589 }
10590 }
10591 this.emit( 'set', card );
10592 }
10593 }
10594 };
10595
10596 /**
10597 * Select the first selectable card.
10598 *
10599 * @chainable
10600 */
10601 OO.ui.IndexLayout.prototype.selectFirstSelectableCard = function () {
10602 if ( !this.tabSelectWidget.getSelectedItem() ) {
10603 this.tabSelectWidget.selectItem( this.tabSelectWidget.getFirstSelectableItem() );
10604 }
10605
10606 return this;
10607 };
10608
10609 /**
10610 * PanelLayouts expand to cover the entire area of their parent. They can be configured with scrolling, padding,
10611 * and a frame, and are often used together with {@link OO.ui.StackLayout StackLayouts}.
10612 *
10613 * @example
10614 * // Example of a panel layout
10615 * var panel = new OO.ui.PanelLayout( {
10616 * expanded: false,
10617 * framed: true,
10618 * padded: true,
10619 * $content: $( '<p>A panel layout with padding and a frame.</p>' )
10620 * } );
10621 * $( 'body' ).append( panel.$element );
10622 *
10623 * @class
10624 * @extends OO.ui.Layout
10625 *
10626 * @constructor
10627 * @param {Object} [config] Configuration options
10628 * @cfg {boolean} [scrollable=false] Allow vertical scrolling
10629 * @cfg {boolean} [padded=false] Add padding between the content and the edges of the panel.
10630 * @cfg {boolean} [expanded=true] Expand the panel to fill the entire parent element.
10631 * @cfg {boolean} [framed=false] Render the panel with a frame to visually separate it from outside content.
10632 */
10633 OO.ui.PanelLayout = function OoUiPanelLayout( config ) {
10634 // Configuration initialization
10635 config = $.extend( {
10636 scrollable: false,
10637 padded: false,
10638 expanded: true,
10639 framed: false
10640 }, config );
10641
10642 // Parent constructor
10643 OO.ui.PanelLayout.parent.call( this, config );
10644
10645 // Initialization
10646 this.$element.addClass( 'oo-ui-panelLayout' );
10647 if ( config.scrollable ) {
10648 this.$element.addClass( 'oo-ui-panelLayout-scrollable' );
10649 }
10650 if ( config.padded ) {
10651 this.$element.addClass( 'oo-ui-panelLayout-padded' );
10652 }
10653 if ( config.expanded ) {
10654 this.$element.addClass( 'oo-ui-panelLayout-expanded' );
10655 }
10656 if ( config.framed ) {
10657 this.$element.addClass( 'oo-ui-panelLayout-framed' );
10658 }
10659 };
10660
10661 /* Setup */
10662
10663 OO.inheritClass( OO.ui.PanelLayout, OO.ui.Layout );
10664
10665 /**
10666 * CardLayouts are used within {@link OO.ui.IndexLayout index layouts} to create cards that users can select and display
10667 * from the index's optional {@link OO.ui.TabSelectWidget tab} navigation. Cards are usually not instantiated directly,
10668 * rather extended to include the required content and functionality.
10669 *
10670 * Each card must have a unique symbolic name, which is passed to the constructor. In addition, the card's tab
10671 * item is customized (with a label) using the #setupTabItem method. See
10672 * {@link OO.ui.IndexLayout IndexLayout} for an example.
10673 *
10674 * @class
10675 * @extends OO.ui.PanelLayout
10676 *
10677 * @constructor
10678 * @param {string} name Unique symbolic name of card
10679 * @param {Object} [config] Configuration options
10680 * @cfg {jQuery|string|Function|OO.ui.HtmlSnippet} [label] Label for card's tab
10681 */
10682 OO.ui.CardLayout = function OoUiCardLayout( name, config ) {
10683 // Allow passing positional parameters inside the config object
10684 if ( OO.isPlainObject( name ) && config === undefined ) {
10685 config = name;
10686 name = config.name;
10687 }
10688
10689 // Configuration initialization
10690 config = $.extend( { scrollable: true }, config );
10691
10692 // Parent constructor
10693 OO.ui.CardLayout.parent.call( this, config );
10694
10695 // Properties
10696 this.name = name;
10697 this.label = config.label;
10698 this.tabItem = null;
10699 this.active = false;
10700
10701 // Initialization
10702 this.$element.addClass( 'oo-ui-cardLayout' );
10703 };
10704
10705 /* Setup */
10706
10707 OO.inheritClass( OO.ui.CardLayout, OO.ui.PanelLayout );
10708
10709 /* Events */
10710
10711 /**
10712 * An 'active' event is emitted when the card becomes active. Cards become active when they are
10713 * shown in a index layout that is configured to display only one card at a time.
10714 *
10715 * @event active
10716 * @param {boolean} active Card is active
10717 */
10718
10719 /* Methods */
10720
10721 /**
10722 * Get the symbolic name of the card.
10723 *
10724 * @return {string} Symbolic name of card
10725 */
10726 OO.ui.CardLayout.prototype.getName = function () {
10727 return this.name;
10728 };
10729
10730 /**
10731 * Check if card is active.
10732 *
10733 * Cards become active when they are shown in a {@link OO.ui.IndexLayout index layout} that is configured to display
10734 * only one card at a time. Additional CSS is applied to the card's tab item to reflect the active state.
10735 *
10736 * @return {boolean} Card is active
10737 */
10738 OO.ui.CardLayout.prototype.isActive = function () {
10739 return this.active;
10740 };
10741
10742 /**
10743 * Get tab item.
10744 *
10745 * The tab item allows users to access the card from the index's tab
10746 * navigation. The tab item itself can be customized (with a label, level, etc.) using the #setupTabItem method.
10747 *
10748 * @return {OO.ui.TabOptionWidget|null} Tab option widget
10749 */
10750 OO.ui.CardLayout.prototype.getTabItem = function () {
10751 return this.tabItem;
10752 };
10753
10754 /**
10755 * Set or unset the tab item.
10756 *
10757 * Specify a {@link OO.ui.TabOptionWidget tab option} to set it,
10758 * or `null` to clear the tab item. To customize the tab item itself (e.g., to set a label or tab
10759 * level), use #setupTabItem instead of this method.
10760 *
10761 * @param {OO.ui.TabOptionWidget|null} tabItem Tab option widget, null to clear
10762 * @chainable
10763 */
10764 OO.ui.CardLayout.prototype.setTabItem = function ( tabItem ) {
10765 this.tabItem = tabItem || null;
10766 if ( tabItem ) {
10767 this.setupTabItem();
10768 }
10769 return this;
10770 };
10771
10772 /**
10773 * Set up the tab item.
10774 *
10775 * Use this method to customize the tab item (e.g., to add a label or tab level). To set or unset
10776 * the tab item itself (with a {@link OO.ui.TabOptionWidget tab option} or `null`), use
10777 * the #setTabItem method instead.
10778 *
10779 * @param {OO.ui.TabOptionWidget} tabItem Tab option widget to set up
10780 * @chainable
10781 */
10782 OO.ui.CardLayout.prototype.setupTabItem = function () {
10783 if ( this.label ) {
10784 this.tabItem.setLabel( this.label );
10785 }
10786 return this;
10787 };
10788
10789 /**
10790 * Set the card to its 'active' state.
10791 *
10792 * Cards become active when they are shown in a index layout that is configured to display only one card at a time. Additional
10793 * CSS is applied to the tab item to reflect the card's active state. Outside of the index
10794 * context, setting the active state on a card does nothing.
10795 *
10796 * @param {boolean} value Card is active
10797 * @fires active
10798 */
10799 OO.ui.CardLayout.prototype.setActive = function ( active ) {
10800 active = !!active;
10801
10802 if ( active !== this.active ) {
10803 this.active = active;
10804 this.$element.toggleClass( 'oo-ui-cardLayout-active', this.active );
10805 this.emit( 'active', this.active );
10806 }
10807 };
10808
10809 /**
10810 * PageLayouts are used within {@link OO.ui.BookletLayout booklet layouts} to create pages that users can select and display
10811 * from the booklet's optional {@link OO.ui.OutlineSelectWidget outline} navigation. Pages are usually not instantiated directly,
10812 * rather extended to include the required content and functionality.
10813 *
10814 * Each page must have a unique symbolic name, which is passed to the constructor. In addition, the page's outline
10815 * item is customized (with a label, outline level, etc.) using the #setupOutlineItem method. See
10816 * {@link OO.ui.BookletLayout BookletLayout} for an example.
10817 *
10818 * @class
10819 * @extends OO.ui.PanelLayout
10820 *
10821 * @constructor
10822 * @param {string} name Unique symbolic name of page
10823 * @param {Object} [config] Configuration options
10824 */
10825 OO.ui.PageLayout = function OoUiPageLayout( name, config ) {
10826 // Allow passing positional parameters inside the config object
10827 if ( OO.isPlainObject( name ) && config === undefined ) {
10828 config = name;
10829 name = config.name;
10830 }
10831
10832 // Configuration initialization
10833 config = $.extend( { scrollable: true }, config );
10834
10835 // Parent constructor
10836 OO.ui.PageLayout.parent.call( this, config );
10837
10838 // Properties
10839 this.name = name;
10840 this.outlineItem = null;
10841 this.active = false;
10842
10843 // Initialization
10844 this.$element.addClass( 'oo-ui-pageLayout' );
10845 };
10846
10847 /* Setup */
10848
10849 OO.inheritClass( OO.ui.PageLayout, OO.ui.PanelLayout );
10850
10851 /* Events */
10852
10853 /**
10854 * An 'active' event is emitted when the page becomes active. Pages become active when they are
10855 * shown in a booklet layout that is configured to display only one page at a time.
10856 *
10857 * @event active
10858 * @param {boolean} active Page is active
10859 */
10860
10861 /* Methods */
10862
10863 /**
10864 * Get the symbolic name of the page.
10865 *
10866 * @return {string} Symbolic name of page
10867 */
10868 OO.ui.PageLayout.prototype.getName = function () {
10869 return this.name;
10870 };
10871
10872 /**
10873 * Check if page is active.
10874 *
10875 * Pages become active when they are shown in a {@link OO.ui.BookletLayout booklet layout} that is configured to display
10876 * only one page at a time. Additional CSS is applied to the page's outline item to reflect the active state.
10877 *
10878 * @return {boolean} Page is active
10879 */
10880 OO.ui.PageLayout.prototype.isActive = function () {
10881 return this.active;
10882 };
10883
10884 /**
10885 * Get outline item.
10886 *
10887 * The outline item allows users to access the page from the booklet's outline
10888 * navigation. The outline item itself can be customized (with a label, level, etc.) using the #setupOutlineItem method.
10889 *
10890 * @return {OO.ui.OutlineOptionWidget|null} Outline option widget
10891 */
10892 OO.ui.PageLayout.prototype.getOutlineItem = function () {
10893 return this.outlineItem;
10894 };
10895
10896 /**
10897 * Set or unset the outline item.
10898 *
10899 * Specify an {@link OO.ui.OutlineOptionWidget outline option} to set it,
10900 * or `null` to clear the outline item. To customize the outline item itself (e.g., to set a label or outline
10901 * level), use #setupOutlineItem instead of this method.
10902 *
10903 * @param {OO.ui.OutlineOptionWidget|null} outlineItem Outline option widget, null to clear
10904 * @chainable
10905 */
10906 OO.ui.PageLayout.prototype.setOutlineItem = function ( outlineItem ) {
10907 this.outlineItem = outlineItem || null;
10908 if ( outlineItem ) {
10909 this.setupOutlineItem();
10910 }
10911 return this;
10912 };
10913
10914 /**
10915 * Set up the outline item.
10916 *
10917 * Use this method to customize the outline item (e.g., to add a label or outline level). To set or unset
10918 * the outline item itself (with an {@link OO.ui.OutlineOptionWidget outline option} or `null`), use
10919 * the #setOutlineItem method instead.
10920 *
10921 * @param {OO.ui.OutlineOptionWidget} outlineItem Outline option widget to set up
10922 * @chainable
10923 */
10924 OO.ui.PageLayout.prototype.setupOutlineItem = function () {
10925 return this;
10926 };
10927
10928 /**
10929 * Set the page to its 'active' state.
10930 *
10931 * Pages become active when they are shown in a booklet layout that is configured to display only one page at a time. Additional
10932 * CSS is applied to the outline item to reflect the page's active state. Outside of the booklet
10933 * context, setting the active state on a page does nothing.
10934 *
10935 * @param {boolean} value Page is active
10936 * @fires active
10937 */
10938 OO.ui.PageLayout.prototype.setActive = function ( active ) {
10939 active = !!active;
10940
10941 if ( active !== this.active ) {
10942 this.active = active;
10943 this.$element.toggleClass( 'oo-ui-pageLayout-active', active );
10944 this.emit( 'active', this.active );
10945 }
10946 };
10947
10948 /**
10949 * StackLayouts contain a series of {@link OO.ui.PanelLayout panel layouts}. By default, only one panel is displayed
10950 * at a time, though the stack layout can also be configured to show all contained panels, one after another,
10951 * by setting the #continuous option to 'true'.
10952 *
10953 * @example
10954 * // A stack layout with two panels, configured to be displayed continously
10955 * var myStack = new OO.ui.StackLayout( {
10956 * items: [
10957 * new OO.ui.PanelLayout( {
10958 * $content: $( '<p>Panel One</p>' ),
10959 * padded: true,
10960 * framed: true
10961 * } ),
10962 * new OO.ui.PanelLayout( {
10963 * $content: $( '<p>Panel Two</p>' ),
10964 * padded: true,
10965 * framed: true
10966 * } )
10967 * ],
10968 * continuous: true
10969 * } );
10970 * $( 'body' ).append( myStack.$element );
10971 *
10972 * @class
10973 * @extends OO.ui.PanelLayout
10974 * @mixins OO.ui.mixin.GroupElement
10975 *
10976 * @constructor
10977 * @param {Object} [config] Configuration options
10978 * @cfg {boolean} [continuous=false] Show all panels, one after another. By default, only one panel is displayed at a time.
10979 * @cfg {OO.ui.Layout[]} [items] Panel layouts to add to the stack layout.
10980 */
10981 OO.ui.StackLayout = function OoUiStackLayout( config ) {
10982 // Configuration initialization
10983 config = $.extend( { scrollable: true }, config );
10984
10985 // Parent constructor
10986 OO.ui.StackLayout.parent.call( this, config );
10987
10988 // Mixin constructors
10989 OO.ui.mixin.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) );
10990
10991 // Properties
10992 this.currentItem = null;
10993 this.continuous = !!config.continuous;
10994
10995 // Initialization
10996 this.$element.addClass( 'oo-ui-stackLayout' );
10997 if ( this.continuous ) {
10998 this.$element.addClass( 'oo-ui-stackLayout-continuous' );
10999 }
11000 if ( Array.isArray( config.items ) ) {
11001 this.addItems( config.items );
11002 }
11003 };
11004
11005 /* Setup */
11006
11007 OO.inheritClass( OO.ui.StackLayout, OO.ui.PanelLayout );
11008 OO.mixinClass( OO.ui.StackLayout, OO.ui.mixin.GroupElement );
11009
11010 /* Events */
11011
11012 /**
11013 * A 'set' event is emitted when panels are {@link #addItems added}, {@link #removeItems removed},
11014 * {@link #clearItems cleared} or {@link #setItem displayed}.
11015 *
11016 * @event set
11017 * @param {OO.ui.Layout|null} item Current panel or `null` if no panel is shown
11018 */
11019
11020 /* Methods */
11021
11022 /**
11023 * Get the current panel.
11024 *
11025 * @return {OO.ui.Layout|null}
11026 */
11027 OO.ui.StackLayout.prototype.getCurrentItem = function () {
11028 return this.currentItem;
11029 };
11030
11031 /**
11032 * Unset the current item.
11033 *
11034 * @private
11035 * @param {OO.ui.StackLayout} layout
11036 * @fires set
11037 */
11038 OO.ui.StackLayout.prototype.unsetCurrentItem = function () {
11039 var prevItem = this.currentItem;
11040 if ( prevItem === null ) {
11041 return;
11042 }
11043
11044 this.currentItem = null;
11045 this.emit( 'set', null );
11046 };
11047
11048 /**
11049 * Add panel layouts to the stack layout.
11050 *
11051 * Panels will be added to the end of the stack layout array unless the optional index parameter specifies a different
11052 * insertion point. Adding a panel that is already in the stack will move it to the end of the array or the point specified
11053 * by the index.
11054 *
11055 * @param {OO.ui.Layout[]} items Panels to add
11056 * @param {number} [index] Index of the insertion point
11057 * @chainable
11058 */
11059 OO.ui.StackLayout.prototype.addItems = function ( items, index ) {
11060 // Update the visibility
11061 this.updateHiddenState( items, this.currentItem );
11062
11063 // Mixin method
11064 OO.ui.mixin.GroupElement.prototype.addItems.call( this, items, index );
11065
11066 if ( !this.currentItem && items.length ) {
11067 this.setItem( items[ 0 ] );
11068 }
11069
11070 return this;
11071 };
11072
11073 /**
11074 * Remove the specified panels from the stack layout.
11075 *
11076 * Removed panels are detached from the DOM, not removed, so that they may be reused. To remove all panels,
11077 * you may wish to use the #clearItems method instead.
11078 *
11079 * @param {OO.ui.Layout[]} items Panels to remove
11080 * @chainable
11081 * @fires set
11082 */
11083 OO.ui.StackLayout.prototype.removeItems = function ( items ) {
11084 // Mixin method
11085 OO.ui.mixin.GroupElement.prototype.removeItems.call( this, items );
11086
11087 if ( items.indexOf( this.currentItem ) !== -1 ) {
11088 if ( this.items.length ) {
11089 this.setItem( this.items[ 0 ] );
11090 } else {
11091 this.unsetCurrentItem();
11092 }
11093 }
11094
11095 return this;
11096 };
11097
11098 /**
11099 * Clear all panels from the stack layout.
11100 *
11101 * Cleared panels are detached from the DOM, not removed, so that they may be reused. To remove only
11102 * a subset of panels, use the #removeItems method.
11103 *
11104 * @chainable
11105 * @fires set
11106 */
11107 OO.ui.StackLayout.prototype.clearItems = function () {
11108 this.unsetCurrentItem();
11109 OO.ui.mixin.GroupElement.prototype.clearItems.call( this );
11110
11111 return this;
11112 };
11113
11114 /**
11115 * Show the specified panel.
11116 *
11117 * If another panel is currently displayed, it will be hidden.
11118 *
11119 * @param {OO.ui.Layout} item Panel to show
11120 * @chainable
11121 * @fires set
11122 */
11123 OO.ui.StackLayout.prototype.setItem = function ( item ) {
11124 if ( item !== this.currentItem ) {
11125 this.updateHiddenState( this.items, item );
11126
11127 if ( this.items.indexOf( item ) !== -1 ) {
11128 this.currentItem = item;
11129 this.emit( 'set', item );
11130 } else {
11131 this.unsetCurrentItem();
11132 }
11133 }
11134
11135 return this;
11136 };
11137
11138 /**
11139 * Update the visibility of all items in case of non-continuous view.
11140 *
11141 * Ensure all items are hidden except for the selected one.
11142 * This method does nothing when the stack is continuous.
11143 *
11144 * @private
11145 * @param {OO.ui.Layout[]} items Item list iterate over
11146 * @param {OO.ui.Layout} [selectedItem] Selected item to show
11147 */
11148 OO.ui.StackLayout.prototype.updateHiddenState = function ( items, selectedItem ) {
11149 var i, len;
11150
11151 if ( !this.continuous ) {
11152 for ( i = 0, len = items.length; i < len; i++ ) {
11153 if ( !selectedItem || selectedItem !== items[ i ] ) {
11154 items[ i ].$element.addClass( 'oo-ui-element-hidden' );
11155 }
11156 }
11157 if ( selectedItem ) {
11158 selectedItem.$element.removeClass( 'oo-ui-element-hidden' );
11159 }
11160 }
11161 };
11162
11163 /**
11164 * HorizontalLayout arranges its contents in a single line (using `display: inline-block` for its
11165 * items), with small margins between them. Convenient when you need to put a number of block-level
11166 * widgets on a single line next to each other.
11167 *
11168 * Note that inline elements, such as OO.ui.ButtonWidgets, do not need this wrapper.
11169 *
11170 * @example
11171 * // HorizontalLayout with a text input and a label
11172 * var layout = new OO.ui.HorizontalLayout( {
11173 * items: [
11174 * new OO.ui.LabelWidget( { label: 'Label' } ),
11175 * new OO.ui.TextInputWidget( { value: 'Text' } )
11176 * ]
11177 * } );
11178 * $( 'body' ).append( layout.$element );
11179 *
11180 * @class
11181 * @extends OO.ui.Layout
11182 * @mixins OO.ui.mixin.GroupElement
11183 *
11184 * @constructor
11185 * @param {Object} [config] Configuration options
11186 * @cfg {OO.ui.Widget[]|OO.ui.Layout[]} [items] Widgets or other layouts to add to the layout.
11187 */
11188 OO.ui.HorizontalLayout = function OoUiHorizontalLayout( config ) {
11189 // Configuration initialization
11190 config = config || {};
11191
11192 // Parent constructor
11193 OO.ui.HorizontalLayout.parent.call( this, config );
11194
11195 // Mixin constructors
11196 OO.ui.mixin.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) );
11197
11198 // Initialization
11199 this.$element.addClass( 'oo-ui-horizontalLayout' );
11200 if ( Array.isArray( config.items ) ) {
11201 this.addItems( config.items );
11202 }
11203 };
11204
11205 /* Setup */
11206
11207 OO.inheritClass( OO.ui.HorizontalLayout, OO.ui.Layout );
11208 OO.mixinClass( OO.ui.HorizontalLayout, OO.ui.mixin.GroupElement );
11209
11210 /**
11211 * BarToolGroups are one of three types of {@link OO.ui.ToolGroup toolgroups} that are used to
11212 * create {@link OO.ui.Toolbar toolbars} (the other types of groups are {@link OO.ui.MenuToolGroup MenuToolGroup}
11213 * and {@link OO.ui.ListToolGroup ListToolGroup}). The {@link OO.ui.Tool tools} in a BarToolGroup are
11214 * displayed by icon in a single row. The title of the tool is displayed when users move the mouse over
11215 * the tool.
11216 *
11217 * BarToolGroups are created by a {@link OO.ui.ToolGroupFactory tool group factory} when the toolbar is
11218 * set up.
11219 *
11220 * @example
11221 * // Example of a BarToolGroup with two tools
11222 * var toolFactory = new OO.ui.ToolFactory();
11223 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
11224 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
11225 *
11226 * // We will be placing status text in this element when tools are used
11227 * var $area = $( '<p>' ).text( 'Example of a BarToolGroup with two tools.' );
11228 *
11229 * // Define the tools that we're going to place in our toolbar
11230 *
11231 * // Create a class inheriting from OO.ui.Tool
11232 * function PictureTool() {
11233 * PictureTool.parent.apply( this, arguments );
11234 * }
11235 * OO.inheritClass( PictureTool, OO.ui.Tool );
11236 * // Each tool must have a 'name' (used as an internal identifier, see later) and at least one
11237 * // of 'icon' and 'title' (displayed icon and text).
11238 * PictureTool.static.name = 'picture';
11239 * PictureTool.static.icon = 'picture';
11240 * PictureTool.static.title = 'Insert picture';
11241 * // Defines the action that will happen when this tool is selected (clicked).
11242 * PictureTool.prototype.onSelect = function () {
11243 * $area.text( 'Picture tool clicked!' );
11244 * // Never display this tool as "active" (selected).
11245 * this.setActive( false );
11246 * };
11247 * // Make this tool available in our toolFactory and thus our toolbar
11248 * toolFactory.register( PictureTool );
11249 *
11250 * // This is a PopupTool. Rather than having a custom 'onSelect' action, it will display a
11251 * // little popup window (a PopupWidget).
11252 * function HelpTool( toolGroup, config ) {
11253 * OO.ui.PopupTool.call( this, toolGroup, $.extend( { popup: {
11254 * padded: true,
11255 * label: 'Help',
11256 * head: true
11257 * } }, config ) );
11258 * this.popup.$body.append( '<p>I am helpful!</p>' );
11259 * }
11260 * OO.inheritClass( HelpTool, OO.ui.PopupTool );
11261 * HelpTool.static.name = 'help';
11262 * HelpTool.static.icon = 'help';
11263 * HelpTool.static.title = 'Help';
11264 * toolFactory.register( HelpTool );
11265 *
11266 * // Finally define which tools and in what order appear in the toolbar. Each tool may only be
11267 * // used once (but not all defined tools must be used).
11268 * toolbar.setup( [
11269 * {
11270 * // 'bar' tool groups display tools by icon only
11271 * type: 'bar',
11272 * include: [ 'picture', 'help' ]
11273 * }
11274 * ] );
11275 *
11276 * // Create some UI around the toolbar and place it in the document
11277 * var frame = new OO.ui.PanelLayout( {
11278 * expanded: false,
11279 * framed: true
11280 * } );
11281 * var contentFrame = new OO.ui.PanelLayout( {
11282 * expanded: false,
11283 * padded: true
11284 * } );
11285 * frame.$element.append(
11286 * toolbar.$element,
11287 * contentFrame.$element.append( $area )
11288 * );
11289 * $( 'body' ).append( frame.$element );
11290 *
11291 * // Here is where the toolbar is actually built. This must be done after inserting it into the
11292 * // document.
11293 * toolbar.initialize();
11294 *
11295 * For more information about how to add tools to a bar tool group, please see {@link OO.ui.ToolGroup toolgroup}.
11296 * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki][1].
11297 *
11298 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
11299 *
11300 * @class
11301 * @extends OO.ui.ToolGroup
11302 *
11303 * @constructor
11304 * @param {OO.ui.Toolbar} toolbar
11305 * @param {Object} [config] Configuration options
11306 */
11307 OO.ui.BarToolGroup = function OoUiBarToolGroup( toolbar, config ) {
11308 // Allow passing positional parameters inside the config object
11309 if ( OO.isPlainObject( toolbar ) && config === undefined ) {
11310 config = toolbar;
11311 toolbar = config.toolbar;
11312 }
11313
11314 // Parent constructor
11315 OO.ui.BarToolGroup.parent.call( this, toolbar, config );
11316
11317 // Initialization
11318 this.$element.addClass( 'oo-ui-barToolGroup' );
11319 };
11320
11321 /* Setup */
11322
11323 OO.inheritClass( OO.ui.BarToolGroup, OO.ui.ToolGroup );
11324
11325 /* Static Properties */
11326
11327 OO.ui.BarToolGroup.static.titleTooltips = true;
11328
11329 OO.ui.BarToolGroup.static.accelTooltips = true;
11330
11331 OO.ui.BarToolGroup.static.name = 'bar';
11332
11333 /**
11334 * PopupToolGroup is an abstract base class used by both {@link OO.ui.MenuToolGroup MenuToolGroup}
11335 * and {@link OO.ui.ListToolGroup ListToolGroup} to provide a popup--an overlaid menu or list of tools with an
11336 * optional icon and label. This class can be used for other base classes that also use this functionality.
11337 *
11338 * @abstract
11339 * @class
11340 * @extends OO.ui.ToolGroup
11341 * @mixins OO.ui.mixin.IconElement
11342 * @mixins OO.ui.mixin.IndicatorElement
11343 * @mixins OO.ui.mixin.LabelElement
11344 * @mixins OO.ui.mixin.TitledElement
11345 * @mixins OO.ui.mixin.ClippableElement
11346 * @mixins OO.ui.mixin.TabIndexedElement
11347 *
11348 * @constructor
11349 * @param {OO.ui.Toolbar} toolbar
11350 * @param {Object} [config] Configuration options
11351 * @cfg {string} [header] Text to display at the top of the popup
11352 */
11353 OO.ui.PopupToolGroup = function OoUiPopupToolGroup( toolbar, config ) {
11354 // Allow passing positional parameters inside the config object
11355 if ( OO.isPlainObject( toolbar ) && config === undefined ) {
11356 config = toolbar;
11357 toolbar = config.toolbar;
11358 }
11359
11360 // Configuration initialization
11361 config = config || {};
11362
11363 // Parent constructor
11364 OO.ui.PopupToolGroup.parent.call( this, toolbar, config );
11365
11366 // Properties
11367 this.active = false;
11368 this.dragging = false;
11369 this.onBlurHandler = this.onBlur.bind( this );
11370 this.$handle = $( '<span>' );
11371
11372 // Mixin constructors
11373 OO.ui.mixin.IconElement.call( this, config );
11374 OO.ui.mixin.IndicatorElement.call( this, config );
11375 OO.ui.mixin.LabelElement.call( this, config );
11376 OO.ui.mixin.TitledElement.call( this, config );
11377 OO.ui.mixin.ClippableElement.call( this, $.extend( {}, config, { $clippable: this.$group } ) );
11378 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$handle } ) );
11379
11380 // Events
11381 this.$handle.on( {
11382 keydown: this.onHandleMouseKeyDown.bind( this ),
11383 keyup: this.onHandleMouseKeyUp.bind( this ),
11384 mousedown: this.onHandleMouseKeyDown.bind( this ),
11385 mouseup: this.onHandleMouseKeyUp.bind( this )
11386 } );
11387
11388 // Initialization
11389 this.$handle
11390 .addClass( 'oo-ui-popupToolGroup-handle' )
11391 .append( this.$icon, this.$label, this.$indicator );
11392 // If the pop-up should have a header, add it to the top of the toolGroup.
11393 // Note: If this feature is useful for other widgets, we could abstract it into an
11394 // OO.ui.HeaderedElement mixin constructor.
11395 if ( config.header !== undefined ) {
11396 this.$group
11397 .prepend( $( '<span>' )
11398 .addClass( 'oo-ui-popupToolGroup-header' )
11399 .text( config.header )
11400 );
11401 }
11402 this.$element
11403 .addClass( 'oo-ui-popupToolGroup' )
11404 .prepend( this.$handle );
11405 };
11406
11407 /* Setup */
11408
11409 OO.inheritClass( OO.ui.PopupToolGroup, OO.ui.ToolGroup );
11410 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.mixin.IconElement );
11411 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.mixin.IndicatorElement );
11412 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.mixin.LabelElement );
11413 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.mixin.TitledElement );
11414 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.mixin.ClippableElement );
11415 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.mixin.TabIndexedElement );
11416
11417 /* Methods */
11418
11419 /**
11420 * @inheritdoc
11421 */
11422 OO.ui.PopupToolGroup.prototype.setDisabled = function () {
11423 // Parent method
11424 OO.ui.PopupToolGroup.parent.prototype.setDisabled.apply( this, arguments );
11425
11426 if ( this.isDisabled() && this.isElementAttached() ) {
11427 this.setActive( false );
11428 }
11429 };
11430
11431 /**
11432 * Handle focus being lost.
11433 *
11434 * The event is actually generated from a mouseup/keyup, so it is not a normal blur event object.
11435 *
11436 * @protected
11437 * @param {jQuery.Event} e Mouse up or key up event
11438 */
11439 OO.ui.PopupToolGroup.prototype.onBlur = function ( e ) {
11440 // Only deactivate when clicking outside the dropdown element
11441 if ( $( e.target ).closest( '.oo-ui-popupToolGroup' )[ 0 ] !== this.$element[ 0 ] ) {
11442 this.setActive( false );
11443 }
11444 };
11445
11446 /**
11447 * @inheritdoc
11448 */
11449 OO.ui.PopupToolGroup.prototype.onMouseKeyUp = function ( e ) {
11450 // Only close toolgroup when a tool was actually selected
11451 if (
11452 !this.isDisabled() && this.pressed && this.pressed === this.getTargetTool( e ) &&
11453 ( e.which === 1 || e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
11454 ) {
11455 this.setActive( false );
11456 }
11457 return OO.ui.PopupToolGroup.parent.prototype.onMouseKeyUp.call( this, e );
11458 };
11459
11460 /**
11461 * Handle mouse up and key up events.
11462 *
11463 * @protected
11464 * @param {jQuery.Event} e Mouse up or key up event
11465 */
11466 OO.ui.PopupToolGroup.prototype.onHandleMouseKeyUp = function ( e ) {
11467 if (
11468 !this.isDisabled() &&
11469 ( e.which === 1 || e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
11470 ) {
11471 return false;
11472 }
11473 };
11474
11475 /**
11476 * Handle mouse down and key down events.
11477 *
11478 * @protected
11479 * @param {jQuery.Event} e Mouse down or key down event
11480 */
11481 OO.ui.PopupToolGroup.prototype.onHandleMouseKeyDown = function ( e ) {
11482 if (
11483 !this.isDisabled() &&
11484 ( e.which === 1 || e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
11485 ) {
11486 this.setActive( !this.active );
11487 return false;
11488 }
11489 };
11490
11491 /**
11492 * Switch into 'active' mode.
11493 *
11494 * When active, the popup is visible. A mouseup event anywhere in the document will trigger
11495 * deactivation.
11496 */
11497 OO.ui.PopupToolGroup.prototype.setActive = function ( value ) {
11498 var containerWidth, containerLeft;
11499 value = !!value;
11500 if ( this.active !== value ) {
11501 this.active = value;
11502 if ( value ) {
11503 OO.ui.addCaptureEventListener( this.getElementDocument(), 'mouseup', this.onBlurHandler );
11504 OO.ui.addCaptureEventListener( this.getElementDocument(), 'keyup', this.onBlurHandler );
11505
11506 this.$clippable.css( 'left', '' );
11507 // Try anchoring the popup to the left first
11508 this.$element.addClass( 'oo-ui-popupToolGroup-active oo-ui-popupToolGroup-left' );
11509 this.toggleClipping( true );
11510 if ( this.isClippedHorizontally() ) {
11511 // Anchoring to the left caused the popup to clip, so anchor it to the right instead
11512 this.toggleClipping( false );
11513 this.$element
11514 .removeClass( 'oo-ui-popupToolGroup-left' )
11515 .addClass( 'oo-ui-popupToolGroup-right' );
11516 this.toggleClipping( true );
11517 }
11518 if ( this.isClippedHorizontally() ) {
11519 // Anchoring to the right also caused the popup to clip, so just make it fill the container
11520 containerWidth = this.$clippableScrollableContainer.width();
11521 containerLeft = this.$clippableScrollableContainer.offset().left;
11522
11523 this.toggleClipping( false );
11524 this.$element.removeClass( 'oo-ui-popupToolGroup-right' );
11525
11526 this.$clippable.css( {
11527 left: -( this.$element.offset().left - containerLeft ),
11528 width: containerWidth
11529 } );
11530 }
11531 } else {
11532 OO.ui.removeCaptureEventListener( this.getElementDocument(), 'mouseup', this.onBlurHandler );
11533 OO.ui.removeCaptureEventListener( this.getElementDocument(), 'keyup', this.onBlurHandler );
11534 this.$element.removeClass(
11535 'oo-ui-popupToolGroup-active oo-ui-popupToolGroup-left oo-ui-popupToolGroup-right'
11536 );
11537 this.toggleClipping( false );
11538 }
11539 }
11540 };
11541
11542 /**
11543 * ListToolGroups are one of three types of {@link OO.ui.ToolGroup toolgroups} that are used to
11544 * create {@link OO.ui.Toolbar toolbars} (the other types of groups are {@link OO.ui.MenuToolGroup MenuToolGroup}
11545 * and {@link OO.ui.BarToolGroup BarToolGroup}). The {@link OO.ui.Tool tools} in a ListToolGroup are displayed
11546 * by label in a dropdown menu. The title of the tool is used as the label text. The menu itself can be configured
11547 * with a label, icon, indicator, header, and title.
11548 *
11549 * ListToolGroups can be configured to be expanded and collapsed. Collapsed lists will have a ‘More’ option that
11550 * users can select to see the full list of tools. If a collapsed toolgroup is expanded, a ‘Fewer’ option permits
11551 * users to collapse the list again.
11552 *
11553 * ListToolGroups are created by a {@link OO.ui.ToolGroupFactory toolgroup factory} when the toolbar is set up. The factory
11554 * requires the ListToolGroup's symbolic name, 'list', which is specified along with the other configurations. For more
11555 * information about how to add tools to a ListToolGroup, please see {@link OO.ui.ToolGroup toolgroup}.
11556 *
11557 * @example
11558 * // Example of a ListToolGroup
11559 * var toolFactory = new OO.ui.ToolFactory();
11560 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
11561 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
11562 *
11563 * // Configure and register two tools
11564 * function SettingsTool() {
11565 * SettingsTool.parent.apply( this, arguments );
11566 * }
11567 * OO.inheritClass( SettingsTool, OO.ui.Tool );
11568 * SettingsTool.static.name = 'settings';
11569 * SettingsTool.static.icon = 'settings';
11570 * SettingsTool.static.title = 'Change settings';
11571 * SettingsTool.prototype.onSelect = function () {
11572 * this.setActive( false );
11573 * };
11574 * toolFactory.register( SettingsTool );
11575 * // Register two more tools, nothing interesting here
11576 * function StuffTool() {
11577 * StuffTool.parent.apply( this, arguments );
11578 * }
11579 * OO.inheritClass( StuffTool, OO.ui.Tool );
11580 * StuffTool.static.name = 'stuff';
11581 * StuffTool.static.icon = 'ellipsis';
11582 * StuffTool.static.title = 'Change the world';
11583 * StuffTool.prototype.onSelect = function () {
11584 * this.setActive( false );
11585 * };
11586 * toolFactory.register( StuffTool );
11587 * toolbar.setup( [
11588 * {
11589 * // Configurations for list toolgroup.
11590 * type: 'list',
11591 * label: 'ListToolGroup',
11592 * indicator: 'down',
11593 * icon: 'picture',
11594 * title: 'This is the title, displayed when user moves the mouse over the list toolgroup',
11595 * header: 'This is the header',
11596 * include: [ 'settings', 'stuff' ],
11597 * allowCollapse: ['stuff']
11598 * }
11599 * ] );
11600 *
11601 * // Create some UI around the toolbar and place it in the document
11602 * var frame = new OO.ui.PanelLayout( {
11603 * expanded: false,
11604 * framed: true
11605 * } );
11606 * frame.$element.append(
11607 * toolbar.$element
11608 * );
11609 * $( 'body' ).append( frame.$element );
11610 * // Build the toolbar. This must be done after the toolbar has been appended to the document.
11611 * toolbar.initialize();
11612 *
11613 * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki][1].
11614 *
11615 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
11616 *
11617 * @class
11618 * @extends OO.ui.PopupToolGroup
11619 *
11620 * @constructor
11621 * @param {OO.ui.Toolbar} toolbar
11622 * @param {Object} [config] Configuration options
11623 * @cfg {Array} [allowCollapse] Allow the specified tools to be collapsed. By default, collapsible tools
11624 * will only be displayed if users click the ‘More’ option displayed at the bottom of the list. If
11625 * the list is expanded, a ‘Fewer’ option permits users to collapse the list again. Any tools that
11626 * are included in the toolgroup, but are not designated as collapsible, will always be displayed.
11627 * To open a collapsible list in its expanded state, set #expanded to 'true'.
11628 * @cfg {Array} [forceExpand] Expand the specified tools. All other tools will be designated as collapsible.
11629 * Unless #expanded is set to true, the collapsible tools will be collapsed when the list is first opened.
11630 * @cfg {boolean} [expanded=false] Expand collapsible tools. This config is only relevant if tools have
11631 * been designated as collapsible. When expanded is set to true, all tools in the group will be displayed
11632 * when the list is first opened. Users can collapse the list with a ‘Fewer’ option at the bottom.
11633 */
11634 OO.ui.ListToolGroup = function OoUiListToolGroup( toolbar, config ) {
11635 // Allow passing positional parameters inside the config object
11636 if ( OO.isPlainObject( toolbar ) && config === undefined ) {
11637 config = toolbar;
11638 toolbar = config.toolbar;
11639 }
11640
11641 // Configuration initialization
11642 config = config || {};
11643
11644 // Properties (must be set before parent constructor, which calls #populate)
11645 this.allowCollapse = config.allowCollapse;
11646 this.forceExpand = config.forceExpand;
11647 this.expanded = config.expanded !== undefined ? config.expanded : false;
11648 this.collapsibleTools = [];
11649
11650 // Parent constructor
11651 OO.ui.ListToolGroup.parent.call( this, toolbar, config );
11652
11653 // Initialization
11654 this.$element.addClass( 'oo-ui-listToolGroup' );
11655 };
11656
11657 /* Setup */
11658
11659 OO.inheritClass( OO.ui.ListToolGroup, OO.ui.PopupToolGroup );
11660
11661 /* Static Properties */
11662
11663 OO.ui.ListToolGroup.static.name = 'list';
11664
11665 /* Methods */
11666
11667 /**
11668 * @inheritdoc
11669 */
11670 OO.ui.ListToolGroup.prototype.populate = function () {
11671 var i, len, allowCollapse = [];
11672
11673 OO.ui.ListToolGroup.parent.prototype.populate.call( this );
11674
11675 // Update the list of collapsible tools
11676 if ( this.allowCollapse !== undefined ) {
11677 allowCollapse = this.allowCollapse;
11678 } else if ( this.forceExpand !== undefined ) {
11679 allowCollapse = OO.simpleArrayDifference( Object.keys( this.tools ), this.forceExpand );
11680 }
11681
11682 this.collapsibleTools = [];
11683 for ( i = 0, len = allowCollapse.length; i < len; i++ ) {
11684 if ( this.tools[ allowCollapse[ i ] ] !== undefined ) {
11685 this.collapsibleTools.push( this.tools[ allowCollapse[ i ] ] );
11686 }
11687 }
11688
11689 // Keep at the end, even when tools are added
11690 this.$group.append( this.getExpandCollapseTool().$element );
11691
11692 this.getExpandCollapseTool().toggle( this.collapsibleTools.length !== 0 );
11693 this.updateCollapsibleState();
11694 };
11695
11696 OO.ui.ListToolGroup.prototype.getExpandCollapseTool = function () {
11697 var ExpandCollapseTool;
11698 if ( this.expandCollapseTool === undefined ) {
11699 ExpandCollapseTool = function () {
11700 ExpandCollapseTool.parent.apply( this, arguments );
11701 };
11702
11703 OO.inheritClass( ExpandCollapseTool, OO.ui.Tool );
11704
11705 ExpandCollapseTool.prototype.onSelect = function () {
11706 this.toolGroup.expanded = !this.toolGroup.expanded;
11707 this.toolGroup.updateCollapsibleState();
11708 this.setActive( false );
11709 };
11710 ExpandCollapseTool.prototype.onUpdateState = function () {
11711 // Do nothing. Tool interface requires an implementation of this function.
11712 };
11713
11714 ExpandCollapseTool.static.name = 'more-fewer';
11715
11716 this.expandCollapseTool = new ExpandCollapseTool( this );
11717 }
11718 return this.expandCollapseTool;
11719 };
11720
11721 /**
11722 * @inheritdoc
11723 */
11724 OO.ui.ListToolGroup.prototype.onMouseKeyUp = function ( e ) {
11725 // Do not close the popup when the user wants to show more/fewer tools
11726 if (
11727 $( e.target ).closest( '.oo-ui-tool-name-more-fewer' ).length &&
11728 ( e.which === 1 || e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
11729 ) {
11730 // HACK: Prevent the popup list from being hidden. Skip the PopupToolGroup implementation (which
11731 // hides the popup list when a tool is selected) and call ToolGroup's implementation directly.
11732 return OO.ui.ListToolGroup.parent.parent.prototype.onMouseKeyUp.call( this, e );
11733 } else {
11734 return OO.ui.ListToolGroup.parent.prototype.onMouseKeyUp.call( this, e );
11735 }
11736 };
11737
11738 OO.ui.ListToolGroup.prototype.updateCollapsibleState = function () {
11739 var i, len;
11740
11741 this.getExpandCollapseTool()
11742 .setIcon( this.expanded ? 'collapse' : 'expand' )
11743 .setTitle( OO.ui.msg( this.expanded ? 'ooui-toolgroup-collapse' : 'ooui-toolgroup-expand' ) );
11744
11745 for ( i = 0, len = this.collapsibleTools.length; i < len; i++ ) {
11746 this.collapsibleTools[ i ].toggle( this.expanded );
11747 }
11748 };
11749
11750 /**
11751 * MenuToolGroups are one of three types of {@link OO.ui.ToolGroup toolgroups} that are used to
11752 * create {@link OO.ui.Toolbar toolbars} (the other types of groups are {@link OO.ui.BarToolGroup BarToolGroup}
11753 * and {@link OO.ui.ListToolGroup ListToolGroup}). MenuToolGroups contain selectable {@link OO.ui.Tool tools},
11754 * which are displayed by label in a dropdown menu. The tool's title is used as the label text, and the
11755 * menu label is updated to reflect which tool or tools are currently selected. If no tools are selected,
11756 * the menu label is empty. The menu can be configured with an indicator, icon, title, and/or header.
11757 *
11758 * MenuToolGroups are created by a {@link OO.ui.ToolGroupFactory tool group factory} when the toolbar
11759 * is set up. Note that all tools must define an {@link OO.ui.Tool#onUpdateState onUpdateState} method if
11760 * a MenuToolGroup is used.
11761 *
11762 * @example
11763 * // Example of a MenuToolGroup
11764 * var toolFactory = new OO.ui.ToolFactory();
11765 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
11766 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
11767 *
11768 * // We will be placing status text in this element when tools are used
11769 * var $area = $( '<p>' ).text( 'An example of a MenuToolGroup. Select a tool from the dropdown menu.' );
11770 *
11771 * // Define the tools that we're going to place in our toolbar
11772 *
11773 * function SettingsTool() {
11774 * SettingsTool.parent.apply( this, arguments );
11775 * this.reallyActive = false;
11776 * }
11777 * OO.inheritClass( SettingsTool, OO.ui.Tool );
11778 * SettingsTool.static.name = 'settings';
11779 * SettingsTool.static.icon = 'settings';
11780 * SettingsTool.static.title = 'Change settings';
11781 * SettingsTool.prototype.onSelect = function () {
11782 * $area.text( 'Settings tool clicked!' );
11783 * // Toggle the active state on each click
11784 * this.reallyActive = !this.reallyActive;
11785 * this.setActive( this.reallyActive );
11786 * // To update the menu label
11787 * this.toolbar.emit( 'updateState' );
11788 * };
11789 * SettingsTool.prototype.onUpdateState = function () {
11790 * };
11791 * toolFactory.register( SettingsTool );
11792 *
11793 * function StuffTool() {
11794 * StuffTool.parent.apply( this, arguments );
11795 * this.reallyActive = false;
11796 * }
11797 * OO.inheritClass( StuffTool, OO.ui.Tool );
11798 * StuffTool.static.name = 'stuff';
11799 * StuffTool.static.icon = 'ellipsis';
11800 * StuffTool.static.title = 'More stuff';
11801 * StuffTool.prototype.onSelect = function () {
11802 * $area.text( 'More stuff tool clicked!' );
11803 * // Toggle the active state on each click
11804 * this.reallyActive = !this.reallyActive;
11805 * this.setActive( this.reallyActive );
11806 * // To update the menu label
11807 * this.toolbar.emit( 'updateState' );
11808 * };
11809 * StuffTool.prototype.onUpdateState = function () {
11810 * };
11811 * toolFactory.register( StuffTool );
11812 *
11813 * // Finally define which tools and in what order appear in the toolbar. Each tool may only be
11814 * // used once (but not all defined tools must be used).
11815 * toolbar.setup( [
11816 * {
11817 * type: 'menu',
11818 * header: 'This is the (optional) header',
11819 * title: 'This is the (optional) title',
11820 * indicator: 'down',
11821 * include: [ 'settings', 'stuff' ]
11822 * }
11823 * ] );
11824 *
11825 * // Create some UI around the toolbar and place it in the document
11826 * var frame = new OO.ui.PanelLayout( {
11827 * expanded: false,
11828 * framed: true
11829 * } );
11830 * var contentFrame = new OO.ui.PanelLayout( {
11831 * expanded: false,
11832 * padded: true
11833 * } );
11834 * frame.$element.append(
11835 * toolbar.$element,
11836 * contentFrame.$element.append( $area )
11837 * );
11838 * $( 'body' ).append( frame.$element );
11839 *
11840 * // Here is where the toolbar is actually built. This must be done after inserting it into the
11841 * // document.
11842 * toolbar.initialize();
11843 * toolbar.emit( 'updateState' );
11844 *
11845 * For more information about how to add tools to a MenuToolGroup, please see {@link OO.ui.ToolGroup toolgroup}.
11846 * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki] [1].
11847 *
11848 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
11849 *
11850 * @class
11851 * @extends OO.ui.PopupToolGroup
11852 *
11853 * @constructor
11854 * @param {OO.ui.Toolbar} toolbar
11855 * @param {Object} [config] Configuration options
11856 */
11857 OO.ui.MenuToolGroup = function OoUiMenuToolGroup( toolbar, config ) {
11858 // Allow passing positional parameters inside the config object
11859 if ( OO.isPlainObject( toolbar ) && config === undefined ) {
11860 config = toolbar;
11861 toolbar = config.toolbar;
11862 }
11863
11864 // Configuration initialization
11865 config = config || {};
11866
11867 // Parent constructor
11868 OO.ui.MenuToolGroup.parent.call( this, toolbar, config );
11869
11870 // Events
11871 this.toolbar.connect( this, { updateState: 'onUpdateState' } );
11872
11873 // Initialization
11874 this.$element.addClass( 'oo-ui-menuToolGroup' );
11875 };
11876
11877 /* Setup */
11878
11879 OO.inheritClass( OO.ui.MenuToolGroup, OO.ui.PopupToolGroup );
11880
11881 /* Static Properties */
11882
11883 OO.ui.MenuToolGroup.static.name = 'menu';
11884
11885 /* Methods */
11886
11887 /**
11888 * Handle the toolbar state being updated.
11889 *
11890 * When the state changes, the title of each active item in the menu will be joined together and
11891 * used as a label for the group. The label will be empty if none of the items are active.
11892 *
11893 * @private
11894 */
11895 OO.ui.MenuToolGroup.prototype.onUpdateState = function () {
11896 var name,
11897 labelTexts = [];
11898
11899 for ( name in this.tools ) {
11900 if ( this.tools[ name ].isActive() ) {
11901 labelTexts.push( this.tools[ name ].getTitle() );
11902 }
11903 }
11904
11905 this.setLabel( labelTexts.join( ', ' ) || ' ' );
11906 };
11907
11908 /**
11909 * Popup tools open a popup window when they are selected from the {@link OO.ui.Toolbar toolbar}. Each popup tool is configured
11910 * 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
11911 * an #onSelect or #onUpdateState method, as these methods have been implemented already.
11912 *
11913 * // Example of a popup tool. When selected, a popup tool displays
11914 * // a popup window.
11915 * function HelpTool( toolGroup, config ) {
11916 * OO.ui.PopupTool.call( this, toolGroup, $.extend( { popup: {
11917 * padded: true,
11918 * label: 'Help',
11919 * head: true
11920 * } }, config ) );
11921 * this.popup.$body.append( '<p>I am helpful!</p>' );
11922 * };
11923 * OO.inheritClass( HelpTool, OO.ui.PopupTool );
11924 * HelpTool.static.name = 'help';
11925 * HelpTool.static.icon = 'help';
11926 * HelpTool.static.title = 'Help';
11927 * toolFactory.register( HelpTool );
11928 *
11929 * For an example of a toolbar that contains a popup tool, see {@link OO.ui.Toolbar toolbars}. For more information about
11930 * toolbars in genreral, please see the [OOjs UI documentation on MediaWiki][1].
11931 *
11932 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
11933 *
11934 * @abstract
11935 * @class
11936 * @extends OO.ui.Tool
11937 * @mixins OO.ui.mixin.PopupElement
11938 *
11939 * @constructor
11940 * @param {OO.ui.ToolGroup} toolGroup
11941 * @param {Object} [config] Configuration options
11942 */
11943 OO.ui.PopupTool = function OoUiPopupTool( toolGroup, config ) {
11944 // Allow passing positional parameters inside the config object
11945 if ( OO.isPlainObject( toolGroup ) && config === undefined ) {
11946 config = toolGroup;
11947 toolGroup = config.toolGroup;
11948 }
11949
11950 // Parent constructor
11951 OO.ui.PopupTool.parent.call( this, toolGroup, config );
11952
11953 // Mixin constructors
11954 OO.ui.mixin.PopupElement.call( this, config );
11955
11956 // Initialization
11957 this.$element
11958 .addClass( 'oo-ui-popupTool' )
11959 .append( this.popup.$element );
11960 };
11961
11962 /* Setup */
11963
11964 OO.inheritClass( OO.ui.PopupTool, OO.ui.Tool );
11965 OO.mixinClass( OO.ui.PopupTool, OO.ui.mixin.PopupElement );
11966
11967 /* Methods */
11968
11969 /**
11970 * Handle the tool being selected.
11971 *
11972 * @inheritdoc
11973 */
11974 OO.ui.PopupTool.prototype.onSelect = function () {
11975 if ( !this.isDisabled() ) {
11976 this.popup.toggle();
11977 }
11978 this.setActive( false );
11979 return false;
11980 };
11981
11982 /**
11983 * Handle the toolbar state being updated.
11984 *
11985 * @inheritdoc
11986 */
11987 OO.ui.PopupTool.prototype.onUpdateState = function () {
11988 this.setActive( false );
11989 };
11990
11991 /**
11992 * A ToolGroupTool is a special sort of tool that can contain other {@link OO.ui.Tool tools}
11993 * and {@link OO.ui.ToolGroup toolgroups}. The ToolGroupTool was specifically designed to be used
11994 * inside a {@link OO.ui.BarToolGroup bar} toolgroup to provide access to additional tools from
11995 * the bar item. Included tools will be displayed in a dropdown {@link OO.ui.ListToolGroup list}
11996 * when the ToolGroupTool is selected.
11997 *
11998 * // Example: ToolGroupTool with two nested tools, 'setting1' and 'setting2', defined elsewhere.
11999 *
12000 * function SettingsTool() {
12001 * SettingsTool.parent.apply( this, arguments );
12002 * };
12003 * OO.inheritClass( SettingsTool, OO.ui.ToolGroupTool );
12004 * SettingsTool.static.name = 'settings';
12005 * SettingsTool.static.title = 'Change settings';
12006 * SettingsTool.static.groupConfig = {
12007 * icon: 'settings',
12008 * label: 'ToolGroupTool',
12009 * include: [ 'setting1', 'setting2' ]
12010 * };
12011 * toolFactory.register( SettingsTool );
12012 *
12013 * For more information, please see the [OOjs UI documentation on MediaWiki][1].
12014 *
12015 * Please note that this implementation is subject to change per [T74159] [2].
12016 *
12017 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars#ToolGroupTool
12018 * [2]: https://phabricator.wikimedia.org/T74159
12019 *
12020 * @abstract
12021 * @class
12022 * @extends OO.ui.Tool
12023 *
12024 * @constructor
12025 * @param {OO.ui.ToolGroup} toolGroup
12026 * @param {Object} [config] Configuration options
12027 */
12028 OO.ui.ToolGroupTool = function OoUiToolGroupTool( toolGroup, config ) {
12029 // Allow passing positional parameters inside the config object
12030 if ( OO.isPlainObject( toolGroup ) && config === undefined ) {
12031 config = toolGroup;
12032 toolGroup = config.toolGroup;
12033 }
12034
12035 // Parent constructor
12036 OO.ui.ToolGroupTool.parent.call( this, toolGroup, config );
12037
12038 // Properties
12039 this.innerToolGroup = this.createGroup( this.constructor.static.groupConfig );
12040
12041 // Events
12042 this.innerToolGroup.connect( this, { disable: 'onToolGroupDisable' } );
12043
12044 // Initialization
12045 this.$link.remove();
12046 this.$element
12047 .addClass( 'oo-ui-toolGroupTool' )
12048 .append( this.innerToolGroup.$element );
12049 };
12050
12051 /* Setup */
12052
12053 OO.inheritClass( OO.ui.ToolGroupTool, OO.ui.Tool );
12054
12055 /* Static Properties */
12056
12057 /**
12058 * Toolgroup configuration.
12059 *
12060 * The toolgroup configuration consists of the tools to include, as well as an icon and label
12061 * to use for the bar item. Tools can be included by symbolic name, group, or with the
12062 * wildcard selector. Please see {@link OO.ui.ToolGroup toolgroup} for more information.
12063 *
12064 * @property {Object.<string,Array>}
12065 */
12066 OO.ui.ToolGroupTool.static.groupConfig = {};
12067
12068 /* Methods */
12069
12070 /**
12071 * Handle the tool being selected.
12072 *
12073 * @inheritdoc
12074 */
12075 OO.ui.ToolGroupTool.prototype.onSelect = function () {
12076 this.innerToolGroup.setActive( !this.innerToolGroup.active );
12077 return false;
12078 };
12079
12080 /**
12081 * Synchronize disabledness state of the tool with the inner toolgroup.
12082 *
12083 * @private
12084 * @param {boolean} disabled Element is disabled
12085 */
12086 OO.ui.ToolGroupTool.prototype.onToolGroupDisable = function ( disabled ) {
12087 this.setDisabled( disabled );
12088 };
12089
12090 /**
12091 * Handle the toolbar state being updated.
12092 *
12093 * @inheritdoc
12094 */
12095 OO.ui.ToolGroupTool.prototype.onUpdateState = function () {
12096 this.setActive( false );
12097 };
12098
12099 /**
12100 * Build a {@link OO.ui.ToolGroup toolgroup} from the specified configuration.
12101 *
12102 * @param {Object.<string,Array>} group Toolgroup configuration. Please see {@link OO.ui.ToolGroup toolgroup} for
12103 * more information.
12104 * @return {OO.ui.ListToolGroup}
12105 */
12106 OO.ui.ToolGroupTool.prototype.createGroup = function ( group ) {
12107 if ( group.include === '*' ) {
12108 // Apply defaults to catch-all groups
12109 if ( group.label === undefined ) {
12110 group.label = OO.ui.msg( 'ooui-toolbar-more' );
12111 }
12112 }
12113
12114 return this.toolbar.getToolGroupFactory().create( 'list', this.toolbar, group );
12115 };
12116
12117 /**
12118 * Mixin for OO.ui.Widget subclasses to provide OO.ui.mixin.GroupElement.
12119 *
12120 * Use together with OO.ui.mixin.ItemWidget to make disabled state inheritable.
12121 *
12122 * @private
12123 * @abstract
12124 * @class
12125 * @extends OO.ui.mixin.GroupElement
12126 *
12127 * @constructor
12128 * @param {Object} [config] Configuration options
12129 */
12130 OO.ui.mixin.GroupWidget = function OoUiMixinGroupWidget( config ) {
12131 // Parent constructor
12132 OO.ui.mixin.GroupWidget.parent.call( this, config );
12133 };
12134
12135 /* Setup */
12136
12137 OO.inheritClass( OO.ui.mixin.GroupWidget, OO.ui.mixin.GroupElement );
12138
12139 /* Methods */
12140
12141 /**
12142 * Set the disabled state of the widget.
12143 *
12144 * This will also update the disabled state of child widgets.
12145 *
12146 * @param {boolean} disabled Disable widget
12147 * @chainable
12148 */
12149 OO.ui.mixin.GroupWidget.prototype.setDisabled = function ( disabled ) {
12150 var i, len;
12151
12152 // Parent method
12153 // Note: Calling #setDisabled this way assumes this is mixed into an OO.ui.Widget
12154 OO.ui.Widget.prototype.setDisabled.call( this, disabled );
12155
12156 // During construction, #setDisabled is called before the OO.ui.mixin.GroupElement constructor
12157 if ( this.items ) {
12158 for ( i = 0, len = this.items.length; i < len; i++ ) {
12159 this.items[ i ].updateDisabled();
12160 }
12161 }
12162
12163 return this;
12164 };
12165
12166 /**
12167 * Mixin for widgets used as items in widgets that mix in OO.ui.mixin.GroupWidget.
12168 *
12169 * Item widgets have a reference to a OO.ui.mixin.GroupWidget while they are attached to the group. This
12170 * allows bidirectional communication.
12171 *
12172 * Use together with OO.ui.mixin.GroupWidget to make disabled state inheritable.
12173 *
12174 * @private
12175 * @abstract
12176 * @class
12177 *
12178 * @constructor
12179 */
12180 OO.ui.mixin.ItemWidget = function OoUiMixinItemWidget() {
12181 //
12182 };
12183
12184 /* Methods */
12185
12186 /**
12187 * Check if widget is disabled.
12188 *
12189 * Checks parent if present, making disabled state inheritable.
12190 *
12191 * @return {boolean} Widget is disabled
12192 */
12193 OO.ui.mixin.ItemWidget.prototype.isDisabled = function () {
12194 return this.disabled ||
12195 ( this.elementGroup instanceof OO.ui.Widget && this.elementGroup.isDisabled() );
12196 };
12197
12198 /**
12199 * Set group element is in.
12200 *
12201 * @param {OO.ui.mixin.GroupElement|null} group Group element, null if none
12202 * @chainable
12203 */
12204 OO.ui.mixin.ItemWidget.prototype.setElementGroup = function ( group ) {
12205 // Parent method
12206 // Note: Calling #setElementGroup this way assumes this is mixed into an OO.ui.Element
12207 OO.ui.Element.prototype.setElementGroup.call( this, group );
12208
12209 // Initialize item disabled states
12210 this.updateDisabled();
12211
12212 return this;
12213 };
12214
12215 /**
12216 * OutlineControlsWidget is a set of controls for an {@link OO.ui.OutlineSelectWidget outline select widget}.
12217 * Controls include moving items up and down, removing items, and adding different kinds of items.
12218 *
12219 * **Currently, this class is only used by {@link OO.ui.BookletLayout booklet layouts}.**
12220 *
12221 * @class
12222 * @extends OO.ui.Widget
12223 * @mixins OO.ui.mixin.GroupElement
12224 * @mixins OO.ui.mixin.IconElement
12225 *
12226 * @constructor
12227 * @param {OO.ui.OutlineSelectWidget} outline Outline to control
12228 * @param {Object} [config] Configuration options
12229 * @cfg {Object} [abilities] List of abilties
12230 * @cfg {boolean} [abilities.move=true] Allow moving movable items
12231 * @cfg {boolean} [abilities.remove=true] Allow removing removable items
12232 */
12233 OO.ui.OutlineControlsWidget = function OoUiOutlineControlsWidget( outline, config ) {
12234 // Allow passing positional parameters inside the config object
12235 if ( OO.isPlainObject( outline ) && config === undefined ) {
12236 config = outline;
12237 outline = config.outline;
12238 }
12239
12240 // Configuration initialization
12241 config = $.extend( { icon: 'add' }, config );
12242
12243 // Parent constructor
12244 OO.ui.OutlineControlsWidget.parent.call( this, config );
12245
12246 // Mixin constructors
12247 OO.ui.mixin.GroupElement.call( this, config );
12248 OO.ui.mixin.IconElement.call( this, config );
12249
12250 // Properties
12251 this.outline = outline;
12252 this.$movers = $( '<div>' );
12253 this.upButton = new OO.ui.ButtonWidget( {
12254 framed: false,
12255 icon: 'collapse',
12256 title: OO.ui.msg( 'ooui-outline-control-move-up' )
12257 } );
12258 this.downButton = new OO.ui.ButtonWidget( {
12259 framed: false,
12260 icon: 'expand',
12261 title: OO.ui.msg( 'ooui-outline-control-move-down' )
12262 } );
12263 this.removeButton = new OO.ui.ButtonWidget( {
12264 framed: false,
12265 icon: 'remove',
12266 title: OO.ui.msg( 'ooui-outline-control-remove' )
12267 } );
12268 this.abilities = { move: true, remove: true };
12269
12270 // Events
12271 outline.connect( this, {
12272 select: 'onOutlineChange',
12273 add: 'onOutlineChange',
12274 remove: 'onOutlineChange'
12275 } );
12276 this.upButton.connect( this, { click: [ 'emit', 'move', -1 ] } );
12277 this.downButton.connect( this, { click: [ 'emit', 'move', 1 ] } );
12278 this.removeButton.connect( this, { click: [ 'emit', 'remove' ] } );
12279
12280 // Initialization
12281 this.$element.addClass( 'oo-ui-outlineControlsWidget' );
12282 this.$group.addClass( 'oo-ui-outlineControlsWidget-items' );
12283 this.$movers
12284 .addClass( 'oo-ui-outlineControlsWidget-movers' )
12285 .append( this.removeButton.$element, this.upButton.$element, this.downButton.$element );
12286 this.$element.append( this.$icon, this.$group, this.$movers );
12287 this.setAbilities( config.abilities || {} );
12288 };
12289
12290 /* Setup */
12291
12292 OO.inheritClass( OO.ui.OutlineControlsWidget, OO.ui.Widget );
12293 OO.mixinClass( OO.ui.OutlineControlsWidget, OO.ui.mixin.GroupElement );
12294 OO.mixinClass( OO.ui.OutlineControlsWidget, OO.ui.mixin.IconElement );
12295
12296 /* Events */
12297
12298 /**
12299 * @event move
12300 * @param {number} places Number of places to move
12301 */
12302
12303 /**
12304 * @event remove
12305 */
12306
12307 /* Methods */
12308
12309 /**
12310 * Set abilities.
12311 *
12312 * @param {Object} abilities List of abilties
12313 * @param {boolean} [abilities.move] Allow moving movable items
12314 * @param {boolean} [abilities.remove] Allow removing removable items
12315 */
12316 OO.ui.OutlineControlsWidget.prototype.setAbilities = function ( abilities ) {
12317 var ability;
12318
12319 for ( ability in this.abilities ) {
12320 if ( abilities[ ability ] !== undefined ) {
12321 this.abilities[ ability ] = !!abilities[ ability ];
12322 }
12323 }
12324
12325 this.onOutlineChange();
12326 };
12327
12328 /**
12329 * @private
12330 * Handle outline change events.
12331 */
12332 OO.ui.OutlineControlsWidget.prototype.onOutlineChange = function () {
12333 var i, len, firstMovable, lastMovable,
12334 items = this.outline.getItems(),
12335 selectedItem = this.outline.getSelectedItem(),
12336 movable = this.abilities.move && selectedItem && selectedItem.isMovable(),
12337 removable = this.abilities.remove && selectedItem && selectedItem.isRemovable();
12338
12339 if ( movable ) {
12340 i = -1;
12341 len = items.length;
12342 while ( ++i < len ) {
12343 if ( items[ i ].isMovable() ) {
12344 firstMovable = items[ i ];
12345 break;
12346 }
12347 }
12348 i = len;
12349 while ( i-- ) {
12350 if ( items[ i ].isMovable() ) {
12351 lastMovable = items[ i ];
12352 break;
12353 }
12354 }
12355 }
12356 this.upButton.setDisabled( !movable || selectedItem === firstMovable );
12357 this.downButton.setDisabled( !movable || selectedItem === lastMovable );
12358 this.removeButton.setDisabled( !removable );
12359 };
12360
12361 /**
12362 * ToggleWidget implements basic behavior of widgets with an on/off state.
12363 * Please see OO.ui.ToggleButtonWidget and OO.ui.ToggleSwitchWidget for examples.
12364 *
12365 * @abstract
12366 * @class
12367 * @extends OO.ui.Widget
12368 *
12369 * @constructor
12370 * @param {Object} [config] Configuration options
12371 * @cfg {boolean} [value=false] The toggle’s initial on/off state.
12372 * By default, the toggle is in the 'off' state.
12373 */
12374 OO.ui.ToggleWidget = function OoUiToggleWidget( config ) {
12375 // Configuration initialization
12376 config = config || {};
12377
12378 // Parent constructor
12379 OO.ui.ToggleWidget.parent.call( this, config );
12380
12381 // Properties
12382 this.value = null;
12383
12384 // Initialization
12385 this.$element.addClass( 'oo-ui-toggleWidget' );
12386 this.setValue( !!config.value );
12387 };
12388
12389 /* Setup */
12390
12391 OO.inheritClass( OO.ui.ToggleWidget, OO.ui.Widget );
12392
12393 /* Events */
12394
12395 /**
12396 * @event change
12397 *
12398 * A change event is emitted when the on/off state of the toggle changes.
12399 *
12400 * @param {boolean} value Value representing the new state of the toggle
12401 */
12402
12403 /* Methods */
12404
12405 /**
12406 * Get the value representing the toggle’s state.
12407 *
12408 * @return {boolean} The on/off state of the toggle
12409 */
12410 OO.ui.ToggleWidget.prototype.getValue = function () {
12411 return this.value;
12412 };
12413
12414 /**
12415 * Set the state of the toggle: `true` for 'on', `false' for 'off'.
12416 *
12417 * @param {boolean} value The state of the toggle
12418 * @fires change
12419 * @chainable
12420 */
12421 OO.ui.ToggleWidget.prototype.setValue = function ( value ) {
12422 value = !!value;
12423 if ( this.value !== value ) {
12424 this.value = value;
12425 this.emit( 'change', value );
12426 this.$element.toggleClass( 'oo-ui-toggleWidget-on', value );
12427 this.$element.toggleClass( 'oo-ui-toggleWidget-off', !value );
12428 this.$element.attr( 'aria-checked', value.toString() );
12429 }
12430 return this;
12431 };
12432
12433 /**
12434 * A ButtonGroupWidget groups related buttons and is used together with OO.ui.ButtonWidget and
12435 * its subclasses. Each button in a group is addressed by a unique reference. Buttons can be added,
12436 * removed, and cleared from the group.
12437 *
12438 * @example
12439 * // Example: A ButtonGroupWidget with two buttons
12440 * var button1 = new OO.ui.PopupButtonWidget( {
12441 * label: 'Select a category',
12442 * icon: 'menu',
12443 * popup: {
12444 * $content: $( '<p>List of categories...</p>' ),
12445 * padded: true,
12446 * align: 'left'
12447 * }
12448 * } );
12449 * var button2 = new OO.ui.ButtonWidget( {
12450 * label: 'Add item'
12451 * });
12452 * var buttonGroup = new OO.ui.ButtonGroupWidget( {
12453 * items: [button1, button2]
12454 * } );
12455 * $( 'body' ).append( buttonGroup.$element );
12456 *
12457 * @class
12458 * @extends OO.ui.Widget
12459 * @mixins OO.ui.mixin.GroupElement
12460 *
12461 * @constructor
12462 * @param {Object} [config] Configuration options
12463 * @cfg {OO.ui.ButtonWidget[]} [items] Buttons to add
12464 */
12465 OO.ui.ButtonGroupWidget = function OoUiButtonGroupWidget( config ) {
12466 // Configuration initialization
12467 config = config || {};
12468
12469 // Parent constructor
12470 OO.ui.ButtonGroupWidget.parent.call( this, config );
12471
12472 // Mixin constructors
12473 OO.ui.mixin.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) );
12474
12475 // Initialization
12476 this.$element.addClass( 'oo-ui-buttonGroupWidget' );
12477 if ( Array.isArray( config.items ) ) {
12478 this.addItems( config.items );
12479 }
12480 };
12481
12482 /* Setup */
12483
12484 OO.inheritClass( OO.ui.ButtonGroupWidget, OO.ui.Widget );
12485 OO.mixinClass( OO.ui.ButtonGroupWidget, OO.ui.mixin.GroupElement );
12486
12487 /**
12488 * ButtonWidget is a generic widget for buttons. A wide variety of looks,
12489 * feels, and functionality can be customized via the class’s configuration options
12490 * and methods. Please see the [OOjs UI documentation on MediaWiki] [1] for more information
12491 * and examples.
12492 *
12493 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches
12494 *
12495 * @example
12496 * // A button widget
12497 * var button = new OO.ui.ButtonWidget( {
12498 * label: 'Button with Icon',
12499 * icon: 'remove',
12500 * iconTitle: 'Remove'
12501 * } );
12502 * $( 'body' ).append( button.$element );
12503 *
12504 * NOTE: HTML form buttons should use the OO.ui.ButtonInputWidget class.
12505 *
12506 * @class
12507 * @extends OO.ui.Widget
12508 * @mixins OO.ui.mixin.ButtonElement
12509 * @mixins OO.ui.mixin.IconElement
12510 * @mixins OO.ui.mixin.IndicatorElement
12511 * @mixins OO.ui.mixin.LabelElement
12512 * @mixins OO.ui.mixin.TitledElement
12513 * @mixins OO.ui.mixin.FlaggedElement
12514 * @mixins OO.ui.mixin.TabIndexedElement
12515 * @mixins OO.ui.mixin.AccessKeyedElement
12516 *
12517 * @constructor
12518 * @param {Object} [config] Configuration options
12519 * @cfg {string} [href] Hyperlink to visit when the button is clicked.
12520 * @cfg {string} [target] The frame or window in which to open the hyperlink.
12521 * @cfg {boolean} [noFollow] Search engine traversal hint (default: true)
12522 */
12523 OO.ui.ButtonWidget = function OoUiButtonWidget( config ) {
12524 // Configuration initialization
12525 config = config || {};
12526
12527 // Parent constructor
12528 OO.ui.ButtonWidget.parent.call( this, config );
12529
12530 // Mixin constructors
12531 OO.ui.mixin.ButtonElement.call( this, config );
12532 OO.ui.mixin.IconElement.call( this, config );
12533 OO.ui.mixin.IndicatorElement.call( this, config );
12534 OO.ui.mixin.LabelElement.call( this, config );
12535 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$button } ) );
12536 OO.ui.mixin.FlaggedElement.call( this, config );
12537 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$button } ) );
12538 OO.ui.mixin.AccessKeyedElement.call( this, $.extend( {}, config, { $accessKeyed: this.$button } ) );
12539
12540 // Properties
12541 this.href = null;
12542 this.target = null;
12543 this.noFollow = false;
12544
12545 // Events
12546 this.connect( this, { disable: 'onDisable' } );
12547
12548 // Initialization
12549 this.$button.append( this.$icon, this.$label, this.$indicator );
12550 this.$element
12551 .addClass( 'oo-ui-buttonWidget' )
12552 .append( this.$button );
12553 this.setHref( config.href );
12554 this.setTarget( config.target );
12555 this.setNoFollow( config.noFollow );
12556 };
12557
12558 /* Setup */
12559
12560 OO.inheritClass( OO.ui.ButtonWidget, OO.ui.Widget );
12561 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.ButtonElement );
12562 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.IconElement );
12563 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.IndicatorElement );
12564 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.LabelElement );
12565 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.TitledElement );
12566 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.FlaggedElement );
12567 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.TabIndexedElement );
12568 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.AccessKeyedElement );
12569
12570 /* Methods */
12571
12572 /**
12573 * @inheritdoc
12574 */
12575 OO.ui.ButtonWidget.prototype.onMouseDown = function ( e ) {
12576 if ( !this.isDisabled() ) {
12577 // Remove the tab-index while the button is down to prevent the button from stealing focus
12578 this.$button.removeAttr( 'tabindex' );
12579 }
12580
12581 return OO.ui.mixin.ButtonElement.prototype.onMouseDown.call( this, e );
12582 };
12583
12584 /**
12585 * @inheritdoc
12586 */
12587 OO.ui.ButtonWidget.prototype.onMouseUp = function ( e ) {
12588 if ( !this.isDisabled() ) {
12589 // Restore the tab-index after the button is up to restore the button's accessibility
12590 this.$button.attr( 'tabindex', this.tabIndex );
12591 }
12592
12593 return OO.ui.mixin.ButtonElement.prototype.onMouseUp.call( this, e );
12594 };
12595
12596 /**
12597 * Get hyperlink location.
12598 *
12599 * @return {string} Hyperlink location
12600 */
12601 OO.ui.ButtonWidget.prototype.getHref = function () {
12602 return this.href;
12603 };
12604
12605 /**
12606 * Get hyperlink target.
12607 *
12608 * @return {string} Hyperlink target
12609 */
12610 OO.ui.ButtonWidget.prototype.getTarget = function () {
12611 return this.target;
12612 };
12613
12614 /**
12615 * Get search engine traversal hint.
12616 *
12617 * @return {boolean} Whether search engines should avoid traversing this hyperlink
12618 */
12619 OO.ui.ButtonWidget.prototype.getNoFollow = function () {
12620 return this.noFollow;
12621 };
12622
12623 /**
12624 * Set hyperlink location.
12625 *
12626 * @param {string|null} href Hyperlink location, null to remove
12627 */
12628 OO.ui.ButtonWidget.prototype.setHref = function ( href ) {
12629 href = typeof href === 'string' ? href : null;
12630 if ( href !== null ) {
12631 if ( !OO.ui.isSafeUrl( href ) ) {
12632 throw new Error( 'Potentially unsafe href provided: ' + href );
12633 }
12634
12635 }
12636
12637 if ( href !== this.href ) {
12638 this.href = href;
12639 this.updateHref();
12640 }
12641
12642 return this;
12643 };
12644
12645 /**
12646 * Update the `href` attribute, in case of changes to href or
12647 * disabled state.
12648 *
12649 * @private
12650 * @chainable
12651 */
12652 OO.ui.ButtonWidget.prototype.updateHref = function () {
12653 if ( this.href !== null && !this.isDisabled() ) {
12654 this.$button.attr( 'href', this.href );
12655 } else {
12656 this.$button.removeAttr( 'href' );
12657 }
12658
12659 return this;
12660 };
12661
12662 /**
12663 * Handle disable events.
12664 *
12665 * @private
12666 * @param {boolean} disabled Element is disabled
12667 */
12668 OO.ui.ButtonWidget.prototype.onDisable = function () {
12669 this.updateHref();
12670 };
12671
12672 /**
12673 * Set hyperlink target.
12674 *
12675 * @param {string|null} target Hyperlink target, null to remove
12676 */
12677 OO.ui.ButtonWidget.prototype.setTarget = function ( target ) {
12678 target = typeof target === 'string' ? target : null;
12679
12680 if ( target !== this.target ) {
12681 this.target = target;
12682 if ( target !== null ) {
12683 this.$button.attr( 'target', target );
12684 } else {
12685 this.$button.removeAttr( 'target' );
12686 }
12687 }
12688
12689 return this;
12690 };
12691
12692 /**
12693 * Set search engine traversal hint.
12694 *
12695 * @param {boolean} noFollow True if search engines should avoid traversing this hyperlink
12696 */
12697 OO.ui.ButtonWidget.prototype.setNoFollow = function ( noFollow ) {
12698 noFollow = typeof noFollow === 'boolean' ? noFollow : true;
12699
12700 if ( noFollow !== this.noFollow ) {
12701 this.noFollow = noFollow;
12702 if ( noFollow ) {
12703 this.$button.attr( 'rel', 'nofollow' );
12704 } else {
12705 this.$button.removeAttr( 'rel' );
12706 }
12707 }
12708
12709 return this;
12710 };
12711
12712 /**
12713 * An ActionWidget is a {@link OO.ui.ButtonWidget button widget} that executes an action.
12714 * Action widgets are used with OO.ui.ActionSet, which manages the behavior and availability
12715 * of the actions.
12716 *
12717 * Both actions and action sets are primarily used with {@link OO.ui.Dialog Dialogs}.
12718 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information
12719 * and examples.
12720 *
12721 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Action_sets
12722 *
12723 * @class
12724 * @extends OO.ui.ButtonWidget
12725 * @mixins OO.ui.mixin.PendingElement
12726 *
12727 * @constructor
12728 * @param {Object} [config] Configuration options
12729 * @cfg {string} [action] Symbolic name of the action (e.g., ‘continue’ or ‘cancel’).
12730 * @cfg {string[]} [modes] Symbolic names of the modes (e.g., ‘edit’ or ‘read’) in which the action
12731 * should be made available. See the action set's {@link OO.ui.ActionSet#setMode setMode} method
12732 * for more information about setting modes.
12733 * @cfg {boolean} [framed=false] Render the action button with a frame
12734 */
12735 OO.ui.ActionWidget = function OoUiActionWidget( config ) {
12736 // Configuration initialization
12737 config = $.extend( { framed: false }, config );
12738
12739 // Parent constructor
12740 OO.ui.ActionWidget.parent.call( this, config );
12741
12742 // Mixin constructors
12743 OO.ui.mixin.PendingElement.call( this, config );
12744
12745 // Properties
12746 this.action = config.action || '';
12747 this.modes = config.modes || [];
12748 this.width = 0;
12749 this.height = 0;
12750
12751 // Initialization
12752 this.$element.addClass( 'oo-ui-actionWidget' );
12753 };
12754
12755 /* Setup */
12756
12757 OO.inheritClass( OO.ui.ActionWidget, OO.ui.ButtonWidget );
12758 OO.mixinClass( OO.ui.ActionWidget, OO.ui.mixin.PendingElement );
12759
12760 /* Events */
12761
12762 /**
12763 * A resize event is emitted when the size of the widget changes.
12764 *
12765 * @event resize
12766 */
12767
12768 /* Methods */
12769
12770 /**
12771 * Check if the action is configured to be available in the specified `mode`.
12772 *
12773 * @param {string} mode Name of mode
12774 * @return {boolean} The action is configured with the mode
12775 */
12776 OO.ui.ActionWidget.prototype.hasMode = function ( mode ) {
12777 return this.modes.indexOf( mode ) !== -1;
12778 };
12779
12780 /**
12781 * Get the symbolic name of the action (e.g., ‘continue’ or ‘cancel’).
12782 *
12783 * @return {string}
12784 */
12785 OO.ui.ActionWidget.prototype.getAction = function () {
12786 return this.action;
12787 };
12788
12789 /**
12790 * Get the symbolic name of the mode or modes for which the action is configured to be available.
12791 *
12792 * The current mode is set with the action set's {@link OO.ui.ActionSet#setMode setMode} method.
12793 * Only actions that are configured to be avaiable in the current mode will be visible. All other actions
12794 * are hidden.
12795 *
12796 * @return {string[]}
12797 */
12798 OO.ui.ActionWidget.prototype.getModes = function () {
12799 return this.modes.slice();
12800 };
12801
12802 /**
12803 * Emit a resize event if the size has changed.
12804 *
12805 * @private
12806 * @chainable
12807 */
12808 OO.ui.ActionWidget.prototype.propagateResize = function () {
12809 var width, height;
12810
12811 if ( this.isElementAttached() ) {
12812 width = this.$element.width();
12813 height = this.$element.height();
12814
12815 if ( width !== this.width || height !== this.height ) {
12816 this.width = width;
12817 this.height = height;
12818 this.emit( 'resize' );
12819 }
12820 }
12821
12822 return this;
12823 };
12824
12825 /**
12826 * @inheritdoc
12827 */
12828 OO.ui.ActionWidget.prototype.setIcon = function () {
12829 // Mixin method
12830 OO.ui.mixin.IconElement.prototype.setIcon.apply( this, arguments );
12831 this.propagateResize();
12832
12833 return this;
12834 };
12835
12836 /**
12837 * @inheritdoc
12838 */
12839 OO.ui.ActionWidget.prototype.setLabel = function () {
12840 // Mixin method
12841 OO.ui.mixin.LabelElement.prototype.setLabel.apply( this, arguments );
12842 this.propagateResize();
12843
12844 return this;
12845 };
12846
12847 /**
12848 * @inheritdoc
12849 */
12850 OO.ui.ActionWidget.prototype.setFlags = function () {
12851 // Mixin method
12852 OO.ui.mixin.FlaggedElement.prototype.setFlags.apply( this, arguments );
12853 this.propagateResize();
12854
12855 return this;
12856 };
12857
12858 /**
12859 * @inheritdoc
12860 */
12861 OO.ui.ActionWidget.prototype.clearFlags = function () {
12862 // Mixin method
12863 OO.ui.mixin.FlaggedElement.prototype.clearFlags.apply( this, arguments );
12864 this.propagateResize();
12865
12866 return this;
12867 };
12868
12869 /**
12870 * Toggle the visibility of the action button.
12871 *
12872 * @param {boolean} [show] Show button, omit to toggle visibility
12873 * @chainable
12874 */
12875 OO.ui.ActionWidget.prototype.toggle = function () {
12876 // Parent method
12877 OO.ui.ActionWidget.parent.prototype.toggle.apply( this, arguments );
12878 this.propagateResize();
12879
12880 return this;
12881 };
12882
12883 /**
12884 * PopupButtonWidgets toggle the visibility of a contained {@link OO.ui.PopupWidget PopupWidget},
12885 * which is used to display additional information or options.
12886 *
12887 * @example
12888 * // Example of a popup button.
12889 * var popupButton = new OO.ui.PopupButtonWidget( {
12890 * label: 'Popup button with options',
12891 * icon: 'menu',
12892 * popup: {
12893 * $content: $( '<p>Additional options here.</p>' ),
12894 * padded: true,
12895 * align: 'force-left'
12896 * }
12897 * } );
12898 * // Append the button to the DOM.
12899 * $( 'body' ).append( popupButton.$element );
12900 *
12901 * @class
12902 * @extends OO.ui.ButtonWidget
12903 * @mixins OO.ui.mixin.PopupElement
12904 *
12905 * @constructor
12906 * @param {Object} [config] Configuration options
12907 */
12908 OO.ui.PopupButtonWidget = function OoUiPopupButtonWidget( config ) {
12909 // Parent constructor
12910 OO.ui.PopupButtonWidget.parent.call( this, config );
12911
12912 // Mixin constructors
12913 OO.ui.mixin.PopupElement.call( this, config );
12914
12915 // Events
12916 this.connect( this, { click: 'onAction' } );
12917
12918 // Initialization
12919 this.$element
12920 .addClass( 'oo-ui-popupButtonWidget' )
12921 .attr( 'aria-haspopup', 'true' )
12922 .append( this.popup.$element );
12923 };
12924
12925 /* Setup */
12926
12927 OO.inheritClass( OO.ui.PopupButtonWidget, OO.ui.ButtonWidget );
12928 OO.mixinClass( OO.ui.PopupButtonWidget, OO.ui.mixin.PopupElement );
12929
12930 /* Methods */
12931
12932 /**
12933 * Handle the button action being triggered.
12934 *
12935 * @private
12936 */
12937 OO.ui.PopupButtonWidget.prototype.onAction = function () {
12938 this.popup.toggle();
12939 };
12940
12941 /**
12942 * ToggleButtons are buttons that have a state (‘on’ or ‘off’) that is represented by a
12943 * Boolean value. Like other {@link OO.ui.ButtonWidget buttons}, toggle buttons can be
12944 * configured with {@link OO.ui.mixin.IconElement icons}, {@link OO.ui.mixin.IndicatorElement indicators},
12945 * {@link OO.ui.mixin.TitledElement titles}, {@link OO.ui.mixin.FlaggedElement styling flags},
12946 * and {@link OO.ui.mixin.LabelElement labels}. Please see
12947 * the [OOjs UI documentation][1] on MediaWiki for more information.
12948 *
12949 * @example
12950 * // Toggle buttons in the 'off' and 'on' state.
12951 * var toggleButton1 = new OO.ui.ToggleButtonWidget( {
12952 * label: 'Toggle Button off'
12953 * } );
12954 * var toggleButton2 = new OO.ui.ToggleButtonWidget( {
12955 * label: 'Toggle Button on',
12956 * value: true
12957 * } );
12958 * // Append the buttons to the DOM.
12959 * $( 'body' ).append( toggleButton1.$element, toggleButton2.$element );
12960 *
12961 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#Toggle_buttons
12962 *
12963 * @class
12964 * @extends OO.ui.ToggleWidget
12965 * @mixins OO.ui.mixin.ButtonElement
12966 * @mixins OO.ui.mixin.IconElement
12967 * @mixins OO.ui.mixin.IndicatorElement
12968 * @mixins OO.ui.mixin.LabelElement
12969 * @mixins OO.ui.mixin.TitledElement
12970 * @mixins OO.ui.mixin.FlaggedElement
12971 * @mixins OO.ui.mixin.TabIndexedElement
12972 *
12973 * @constructor
12974 * @param {Object} [config] Configuration options
12975 * @cfg {boolean} [value=false] The toggle button’s initial on/off
12976 * state. By default, the button is in the 'off' state.
12977 */
12978 OO.ui.ToggleButtonWidget = function OoUiToggleButtonWidget( config ) {
12979 // Configuration initialization
12980 config = config || {};
12981
12982 // Parent constructor
12983 OO.ui.ToggleButtonWidget.parent.call( this, config );
12984
12985 // Mixin constructors
12986 OO.ui.mixin.ButtonElement.call( this, config );
12987 OO.ui.mixin.IconElement.call( this, config );
12988 OO.ui.mixin.IndicatorElement.call( this, config );
12989 OO.ui.mixin.LabelElement.call( this, config );
12990 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$button } ) );
12991 OO.ui.mixin.FlaggedElement.call( this, config );
12992 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$button } ) );
12993
12994 // Events
12995 this.connect( this, { click: 'onAction' } );
12996
12997 // Initialization
12998 this.$button.append( this.$icon, this.$label, this.$indicator );
12999 this.$element
13000 .addClass( 'oo-ui-toggleButtonWidget' )
13001 .append( this.$button );
13002 };
13003
13004 /* Setup */
13005
13006 OO.inheritClass( OO.ui.ToggleButtonWidget, OO.ui.ToggleWidget );
13007 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.ButtonElement );
13008 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.IconElement );
13009 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.IndicatorElement );
13010 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.LabelElement );
13011 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.TitledElement );
13012 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.FlaggedElement );
13013 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.TabIndexedElement );
13014
13015 /* Methods */
13016
13017 /**
13018 * Handle the button action being triggered.
13019 *
13020 * @private
13021 */
13022 OO.ui.ToggleButtonWidget.prototype.onAction = function () {
13023 this.setValue( !this.value );
13024 };
13025
13026 /**
13027 * @inheritdoc
13028 */
13029 OO.ui.ToggleButtonWidget.prototype.setValue = function ( value ) {
13030 value = !!value;
13031 if ( value !== this.value ) {
13032 // Might be called from parent constructor before ButtonElement constructor
13033 if ( this.$button ) {
13034 this.$button.attr( 'aria-pressed', value.toString() );
13035 }
13036 this.setActive( value );
13037 }
13038
13039 // Parent method
13040 OO.ui.ToggleButtonWidget.parent.prototype.setValue.call( this, value );
13041
13042 return this;
13043 };
13044
13045 /**
13046 * @inheritdoc
13047 */
13048 OO.ui.ToggleButtonWidget.prototype.setButtonElement = function ( $button ) {
13049 if ( this.$button ) {
13050 this.$button.removeAttr( 'aria-pressed' );
13051 }
13052 OO.ui.mixin.ButtonElement.prototype.setButtonElement.call( this, $button );
13053 this.$button.attr( 'aria-pressed', this.value.toString() );
13054 };
13055
13056 /**
13057 * CapsuleMultiSelectWidgets are something like a {@link OO.ui.ComboBoxWidget combo box widget}
13058 * that allows for selecting multiple values.
13059 *
13060 * For more information about menus and options, please see the [OOjs UI documentation on MediaWiki][1].
13061 *
13062 * @example
13063 * // Example: A CapsuleMultiSelectWidget.
13064 * var capsule = new OO.ui.CapsuleMultiSelectWidget( {
13065 * label: 'CapsuleMultiSelectWidget',
13066 * selected: [ 'Option 1', 'Option 3' ],
13067 * menu: {
13068 * items: [
13069 * new OO.ui.MenuOptionWidget( {
13070 * data: 'Option 1',
13071 * label: 'Option One'
13072 * } ),
13073 * new OO.ui.MenuOptionWidget( {
13074 * data: 'Option 2',
13075 * label: 'Option Two'
13076 * } ),
13077 * new OO.ui.MenuOptionWidget( {
13078 * data: 'Option 3',
13079 * label: 'Option Three'
13080 * } ),
13081 * new OO.ui.MenuOptionWidget( {
13082 * data: 'Option 4',
13083 * label: 'Option Four'
13084 * } ),
13085 * new OO.ui.MenuOptionWidget( {
13086 * data: 'Option 5',
13087 * label: 'Option Five'
13088 * } )
13089 * ]
13090 * }
13091 * } );
13092 * $( 'body' ).append( capsule.$element );
13093 *
13094 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
13095 *
13096 * @class
13097 * @extends OO.ui.Widget
13098 * @mixins OO.ui.mixin.TabIndexedElement
13099 * @mixins OO.ui.mixin.GroupElement
13100 *
13101 * @constructor
13102 * @param {Object} [config] Configuration options
13103 * @cfg {boolean} [allowArbitrary=false] Allow data items to be added even if not present in the menu.
13104 * @cfg {Object} [menu] Configuration options to pass to the {@link OO.ui.MenuSelectWidget menu select widget}.
13105 * @cfg {Object} [popup] Configuration options to pass to the {@link OO.ui.PopupWidget popup widget}.
13106 * If specified, this popup will be shown instead of the menu (but the menu
13107 * will still be used for item labels and allowArbitrary=false). The widgets
13108 * in the popup should use this.addItemsFromData() or this.addItems() as necessary.
13109 * @cfg {jQuery} [$overlay] Render the menu or popup into a separate layer.
13110 * This configuration is useful in cases where the expanded menu is larger than
13111 * its containing `<div>`. The specified overlay layer is usually on top of
13112 * the containing `<div>` and has a larger area. By default, the menu uses
13113 * relative positioning.
13114 */
13115 OO.ui.CapsuleMultiSelectWidget = function OoUiCapsuleMultiSelectWidget( config ) {
13116 var $tabFocus;
13117
13118 // Configuration initialization
13119 config = config || {};
13120
13121 // Parent constructor
13122 OO.ui.CapsuleMultiSelectWidget.parent.call( this, config );
13123
13124 // Properties (must be set before mixin constructor calls)
13125 this.$input = config.popup ? null : $( '<input>' );
13126 this.$handle = $( '<div>' );
13127
13128 // Mixin constructors
13129 OO.ui.mixin.GroupElement.call( this, config );
13130 if ( config.popup ) {
13131 config.popup = $.extend( {}, config.popup, {
13132 align: 'forwards',
13133 anchor: false
13134 } );
13135 OO.ui.mixin.PopupElement.call( this, config );
13136 $tabFocus = $( '<span>' );
13137 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: $tabFocus } ) );
13138 } else {
13139 this.popup = null;
13140 $tabFocus = null;
13141 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$input } ) );
13142 }
13143 OO.ui.mixin.IndicatorElement.call( this, config );
13144 OO.ui.mixin.IconElement.call( this, config );
13145
13146 // Properties
13147 this.allowArbitrary = !!config.allowArbitrary;
13148 this.$overlay = config.$overlay || this.$element;
13149 this.menu = new OO.ui.FloatingMenuSelectWidget( $.extend(
13150 {
13151 widget: this,
13152 $input: this.$input,
13153 $container: this.$element,
13154 filterFromInput: true,
13155 disabled: this.isDisabled()
13156 },
13157 config.menu
13158 ) );
13159
13160 // Events
13161 if ( this.popup ) {
13162 $tabFocus.on( {
13163 focus: this.onFocusForPopup.bind( this )
13164 } );
13165 this.popup.$element.on( 'focusout', this.onPopupFocusOut.bind( this ) );
13166 if ( this.popup.$autoCloseIgnore ) {
13167 this.popup.$autoCloseIgnore.on( 'focusout', this.onPopupFocusOut.bind( this ) );
13168 }
13169 this.popup.connect( this, {
13170 toggle: function ( visible ) {
13171 $tabFocus.toggle( !visible );
13172 }
13173 } );
13174 } else {
13175 this.$input.on( {
13176 focus: this.onInputFocus.bind( this ),
13177 blur: this.onInputBlur.bind( this ),
13178 'propertychange change click mouseup keydown keyup input cut paste select': this.onInputChange.bind( this ),
13179 keydown: this.onKeyDown.bind( this ),
13180 keypress: this.onKeyPress.bind( this )
13181 } );
13182 }
13183 this.menu.connect( this, {
13184 choose: 'onMenuChoose',
13185 add: 'onMenuItemsChange',
13186 remove: 'onMenuItemsChange'
13187 } );
13188 this.$handle.on( {
13189 click: this.onClick.bind( this )
13190 } );
13191
13192 // Initialization
13193 if ( this.$input ) {
13194 this.$input.prop( 'disabled', this.isDisabled() );
13195 this.$input.attr( {
13196 role: 'combobox',
13197 'aria-autocomplete': 'list'
13198 } );
13199 this.$input.width( '1em' );
13200 }
13201 if ( config.data ) {
13202 this.setItemsFromData( config.data );
13203 }
13204 this.$group.addClass( 'oo-ui-capsuleMultiSelectWidget-group' );
13205 this.$handle.addClass( 'oo-ui-capsuleMultiSelectWidget-handle' )
13206 .append( this.$indicator, this.$icon, this.$group );
13207 this.$element.addClass( 'oo-ui-capsuleMultiSelectWidget' )
13208 .append( this.$handle );
13209 if ( this.popup ) {
13210 this.$handle.append( $tabFocus );
13211 this.$overlay.append( this.popup.$element );
13212 } else {
13213 this.$handle.append( this.$input );
13214 this.$overlay.append( this.menu.$element );
13215 }
13216 this.onMenuItemsChange();
13217 };
13218
13219 /* Setup */
13220
13221 OO.inheritClass( OO.ui.CapsuleMultiSelectWidget, OO.ui.Widget );
13222 OO.mixinClass( OO.ui.CapsuleMultiSelectWidget, OO.ui.mixin.GroupElement );
13223 OO.mixinClass( OO.ui.CapsuleMultiSelectWidget, OO.ui.mixin.PopupElement );
13224 OO.mixinClass( OO.ui.CapsuleMultiSelectWidget, OO.ui.mixin.TabIndexedElement );
13225 OO.mixinClass( OO.ui.CapsuleMultiSelectWidget, OO.ui.mixin.IndicatorElement );
13226 OO.mixinClass( OO.ui.CapsuleMultiSelectWidget, OO.ui.mixin.IconElement );
13227
13228 /* Events */
13229
13230 /**
13231 * @event change
13232 *
13233 * A change event is emitted when the set of selected items changes.
13234 *
13235 * @param {Mixed[]} datas Data of the now-selected items
13236 */
13237
13238 /* Methods */
13239
13240 /**
13241 * Construct a OO.ui.CapsuleItemWidget (or a subclass thereof) from given label and data.
13242 *
13243 * @protected
13244 * @param {Mixed} data Custom data of any type.
13245 * @param {string} label The label text.
13246 * @return {OO.ui.CapsuleItemWidget}
13247 */
13248 OO.ui.CapsuleMultiSelectWidget.prototype.createItemWidget = function ( data, label ) {
13249 return new OO.ui.CapsuleItemWidget( { data: data, label: label } );
13250 };
13251
13252 /**
13253 * Get the data of the items in the capsule
13254 * @return {Mixed[]}
13255 */
13256 OO.ui.CapsuleMultiSelectWidget.prototype.getItemsData = function () {
13257 return $.map( this.getItems(), function ( e ) { return e.data; } );
13258 };
13259
13260 /**
13261 * Set the items in the capsule by providing data
13262 * @chainable
13263 * @param {Mixed[]} datas
13264 * @return {OO.ui.CapsuleMultiSelectWidget}
13265 */
13266 OO.ui.CapsuleMultiSelectWidget.prototype.setItemsFromData = function ( datas ) {
13267 var widget = this,
13268 menu = this.menu,
13269 items = this.getItems();
13270
13271 $.each( datas, function ( i, data ) {
13272 var j, label,
13273 item = menu.getItemFromData( data );
13274
13275 if ( item ) {
13276 label = item.label;
13277 } else if ( widget.allowArbitrary ) {
13278 label = String( data );
13279 } else {
13280 return;
13281 }
13282
13283 item = null;
13284 for ( j = 0; j < items.length; j++ ) {
13285 if ( items[ j ].data === data && items[ j ].label === label ) {
13286 item = items[ j ];
13287 items.splice( j, 1 );
13288 break;
13289 }
13290 }
13291 if ( !item ) {
13292 item = widget.createItemWidget( data, label );
13293 }
13294 widget.addItems( [ item ], i );
13295 } );
13296
13297 if ( items.length ) {
13298 widget.removeItems( items );
13299 }
13300
13301 return this;
13302 };
13303
13304 /**
13305 * Add items to the capsule by providing their data
13306 * @chainable
13307 * @param {Mixed[]} datas
13308 * @return {OO.ui.CapsuleMultiSelectWidget}
13309 */
13310 OO.ui.CapsuleMultiSelectWidget.prototype.addItemsFromData = function ( datas ) {
13311 var widget = this,
13312 menu = this.menu,
13313 items = [];
13314
13315 $.each( datas, function ( i, data ) {
13316 var item;
13317
13318 if ( !widget.getItemFromData( data ) ) {
13319 item = menu.getItemFromData( data );
13320 if ( item ) {
13321 items.push( widget.createItemWidget( data, item.label ) );
13322 } else if ( widget.allowArbitrary ) {
13323 items.push( widget.createItemWidget( data, String( data ) ) );
13324 }
13325 }
13326 } );
13327
13328 if ( items.length ) {
13329 this.addItems( items );
13330 }
13331
13332 return this;
13333 };
13334
13335 /**
13336 * Remove items by data
13337 * @chainable
13338 * @param {Mixed[]} datas
13339 * @return {OO.ui.CapsuleMultiSelectWidget}
13340 */
13341 OO.ui.CapsuleMultiSelectWidget.prototype.removeItemsFromData = function ( datas ) {
13342 var widget = this,
13343 items = [];
13344
13345 $.each( datas, function ( i, data ) {
13346 var item = widget.getItemFromData( data );
13347 if ( item ) {
13348 items.push( item );
13349 }
13350 } );
13351
13352 if ( items.length ) {
13353 this.removeItems( items );
13354 }
13355
13356 return this;
13357 };
13358
13359 /**
13360 * @inheritdoc
13361 */
13362 OO.ui.CapsuleMultiSelectWidget.prototype.addItems = function ( items ) {
13363 var same, i, l,
13364 oldItems = this.items.slice();
13365
13366 OO.ui.mixin.GroupElement.prototype.addItems.call( this, items );
13367
13368 if ( this.items.length !== oldItems.length ) {
13369 same = false;
13370 } else {
13371 same = true;
13372 for ( i = 0, l = oldItems.length; same && i < l; i++ ) {
13373 same = same && this.items[ i ] === oldItems[ i ];
13374 }
13375 }
13376 if ( !same ) {
13377 this.emit( 'change', this.getItemsData() );
13378 }
13379
13380 return this;
13381 };
13382
13383 /**
13384 * @inheritdoc
13385 */
13386 OO.ui.CapsuleMultiSelectWidget.prototype.removeItems = function ( items ) {
13387 var same, i, l,
13388 oldItems = this.items.slice();
13389
13390 OO.ui.mixin.GroupElement.prototype.removeItems.call( this, items );
13391
13392 if ( this.items.length !== oldItems.length ) {
13393 same = false;
13394 } else {
13395 same = true;
13396 for ( i = 0, l = oldItems.length; same && i < l; i++ ) {
13397 same = same && this.items[ i ] === oldItems[ i ];
13398 }
13399 }
13400 if ( !same ) {
13401 this.emit( 'change', this.getItemsData() );
13402 }
13403
13404 return this;
13405 };
13406
13407 /**
13408 * @inheritdoc
13409 */
13410 OO.ui.CapsuleMultiSelectWidget.prototype.clearItems = function () {
13411 if ( this.items.length ) {
13412 OO.ui.mixin.GroupElement.prototype.clearItems.call( this );
13413 this.emit( 'change', this.getItemsData() );
13414 }
13415 return this;
13416 };
13417
13418 /**
13419 * Get the capsule widget's menu.
13420 * @return {OO.ui.MenuSelectWidget} Menu widget
13421 */
13422 OO.ui.CapsuleMultiSelectWidget.prototype.getMenu = function () {
13423 return this.menu;
13424 };
13425
13426 /**
13427 * Handle focus events
13428 *
13429 * @private
13430 * @param {jQuery.Event} event
13431 */
13432 OO.ui.CapsuleMultiSelectWidget.prototype.onInputFocus = function () {
13433 if ( !this.isDisabled() ) {
13434 this.menu.toggle( true );
13435 }
13436 };
13437
13438 /**
13439 * Handle blur events
13440 *
13441 * @private
13442 * @param {jQuery.Event} event
13443 */
13444 OO.ui.CapsuleMultiSelectWidget.prototype.onInputBlur = function () {
13445 this.clearInput();
13446 };
13447
13448 /**
13449 * Handle focus events
13450 *
13451 * @private
13452 * @param {jQuery.Event} event
13453 */
13454 OO.ui.CapsuleMultiSelectWidget.prototype.onFocusForPopup = function () {
13455 if ( !this.isDisabled() ) {
13456 this.popup.setSize( this.$handle.width() );
13457 this.popup.toggle( true );
13458 this.popup.$element.find( '*' )
13459 .filter( function () { return OO.ui.isFocusableElement( $( this ), true ); } )
13460 .first()
13461 .focus();
13462 }
13463 };
13464
13465 /**
13466 * Handles popup focus out events.
13467 *
13468 * @private
13469 * @param {Event} e Focus out event
13470 */
13471 OO.ui.CapsuleMultiSelectWidget.prototype.onPopupFocusOut = function () {
13472 var widget = this.popup;
13473
13474 setTimeout( function () {
13475 if (
13476 widget.isVisible() &&
13477 !OO.ui.contains( widget.$element[ 0 ], document.activeElement, true ) &&
13478 ( !widget.$autoCloseIgnore || !widget.$autoCloseIgnore.has( document.activeElement ).length )
13479 ) {
13480 widget.toggle( false );
13481 }
13482 } );
13483 };
13484
13485 /**
13486 * Handle mouse click events.
13487 *
13488 * @private
13489 * @param {jQuery.Event} e Mouse click event
13490 */
13491 OO.ui.CapsuleMultiSelectWidget.prototype.onClick = function ( e ) {
13492 if ( e.which === 1 ) {
13493 this.focus();
13494 return false;
13495 }
13496 };
13497
13498 /**
13499 * Handle key press events.
13500 *
13501 * @private
13502 * @param {jQuery.Event} e Key press event
13503 */
13504 OO.ui.CapsuleMultiSelectWidget.prototype.onKeyPress = function ( e ) {
13505 var item;
13506
13507 if ( !this.isDisabled() ) {
13508 if ( e.which === OO.ui.Keys.ESCAPE ) {
13509 this.clearInput();
13510 return false;
13511 }
13512
13513 if ( !this.popup ) {
13514 this.menu.toggle( true );
13515 if ( e.which === OO.ui.Keys.ENTER ) {
13516 item = this.menu.getItemFromLabel( this.$input.val(), true );
13517 if ( item ) {
13518 this.addItemsFromData( [ item.data ] );
13519 this.clearInput();
13520 } else if ( this.allowArbitrary && this.$input.val().trim() !== '' ) {
13521 this.addItemsFromData( [ this.$input.val() ] );
13522 this.clearInput();
13523 }
13524 return false;
13525 }
13526
13527 // Make sure the input gets resized.
13528 setTimeout( this.onInputChange.bind( this ), 0 );
13529 }
13530 }
13531 };
13532
13533 /**
13534 * Handle key down events.
13535 *
13536 * @private
13537 * @param {jQuery.Event} e Key down event
13538 */
13539 OO.ui.CapsuleMultiSelectWidget.prototype.onKeyDown = function ( e ) {
13540 if ( !this.isDisabled() ) {
13541 // 'keypress' event is not triggered for Backspace
13542 if ( e.keyCode === OO.ui.Keys.BACKSPACE && this.$input.val() === '' ) {
13543 if ( this.items.length ) {
13544 this.removeItems( this.items.slice( -1 ) );
13545 }
13546 return false;
13547 }
13548 }
13549 };
13550
13551 /**
13552 * Handle input change events.
13553 *
13554 * @private
13555 * @param {jQuery.Event} e Event of some sort
13556 */
13557 OO.ui.CapsuleMultiSelectWidget.prototype.onInputChange = function () {
13558 if ( !this.isDisabled() ) {
13559 this.$input.width( this.$input.val().length + 'em' );
13560 }
13561 };
13562
13563 /**
13564 * Handle menu choose events.
13565 *
13566 * @private
13567 * @param {OO.ui.OptionWidget} item Chosen item
13568 */
13569 OO.ui.CapsuleMultiSelectWidget.prototype.onMenuChoose = function ( item ) {
13570 if ( item && item.isVisible() ) {
13571 this.addItemsFromData( [ item.getData() ] );
13572 this.clearInput();
13573 }
13574 };
13575
13576 /**
13577 * Handle menu item change events.
13578 *
13579 * @private
13580 */
13581 OO.ui.CapsuleMultiSelectWidget.prototype.onMenuItemsChange = function () {
13582 this.setItemsFromData( this.getItemsData() );
13583 this.$element.toggleClass( 'oo-ui-capsuleMultiSelectWidget-empty', this.menu.isEmpty() );
13584 };
13585
13586 /**
13587 * Clear the input field
13588 * @private
13589 */
13590 OO.ui.CapsuleMultiSelectWidget.prototype.clearInput = function () {
13591 if ( this.$input ) {
13592 this.$input.val( '' );
13593 this.$input.width( '1em' );
13594 }
13595 if ( this.popup ) {
13596 this.popup.toggle( false );
13597 }
13598 this.menu.toggle( false );
13599 this.menu.selectItem();
13600 this.menu.highlightItem();
13601 };
13602
13603 /**
13604 * @inheritdoc
13605 */
13606 OO.ui.CapsuleMultiSelectWidget.prototype.setDisabled = function ( disabled ) {
13607 var i, len;
13608
13609 // Parent method
13610 OO.ui.CapsuleMultiSelectWidget.parent.prototype.setDisabled.call( this, disabled );
13611
13612 if ( this.$input ) {
13613 this.$input.prop( 'disabled', this.isDisabled() );
13614 }
13615 if ( this.menu ) {
13616 this.menu.setDisabled( this.isDisabled() );
13617 }
13618 if ( this.popup ) {
13619 this.popup.setDisabled( this.isDisabled() );
13620 }
13621
13622 if ( this.items ) {
13623 for ( i = 0, len = this.items.length; i < len; i++ ) {
13624 this.items[ i ].updateDisabled();
13625 }
13626 }
13627
13628 return this;
13629 };
13630
13631 /**
13632 * Focus the widget
13633 * @chainable
13634 * @return {OO.ui.CapsuleMultiSelectWidget}
13635 */
13636 OO.ui.CapsuleMultiSelectWidget.prototype.focus = function () {
13637 if ( !this.isDisabled() ) {
13638 if ( this.popup ) {
13639 this.popup.setSize( this.$handle.width() );
13640 this.popup.toggle( true );
13641 this.popup.$element.find( '*' )
13642 .filter( function () { return OO.ui.isFocusableElement( $( this ), true ); } )
13643 .first()
13644 .focus();
13645 } else {
13646 this.menu.toggle( true );
13647 this.$input.focus();
13648 }
13649 }
13650 return this;
13651 };
13652
13653 /**
13654 * CapsuleItemWidgets are used within a {@link OO.ui.CapsuleMultiSelectWidget
13655 * CapsuleMultiSelectWidget} to display the selected items.
13656 *
13657 * @class
13658 * @extends OO.ui.Widget
13659 * @mixins OO.ui.mixin.ItemWidget
13660 * @mixins OO.ui.mixin.IndicatorElement
13661 * @mixins OO.ui.mixin.LabelElement
13662 * @mixins OO.ui.mixin.FlaggedElement
13663 * @mixins OO.ui.mixin.TabIndexedElement
13664 *
13665 * @constructor
13666 * @param {Object} [config] Configuration options
13667 */
13668 OO.ui.CapsuleItemWidget = function OoUiCapsuleItemWidget( config ) {
13669 // Configuration initialization
13670 config = config || {};
13671
13672 // Parent constructor
13673 OO.ui.CapsuleItemWidget.parent.call( this, config );
13674
13675 // Properties (must be set before mixin constructor calls)
13676 this.$indicator = $( '<span>' );
13677
13678 // Mixin constructors
13679 OO.ui.mixin.ItemWidget.call( this );
13680 OO.ui.mixin.IndicatorElement.call( this, $.extend( {}, config, { $indicator: this.$indicator, indicator: 'clear' } ) );
13681 OO.ui.mixin.LabelElement.call( this, config );
13682 OO.ui.mixin.FlaggedElement.call( this, config );
13683 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$indicator } ) );
13684
13685 // Events
13686 this.$indicator.on( {
13687 keydown: this.onCloseKeyDown.bind( this ),
13688 click: this.onCloseClick.bind( this )
13689 } );
13690 this.$element.on( 'click', false );
13691
13692 // Initialization
13693 this.$element
13694 .addClass( 'oo-ui-capsuleItemWidget' )
13695 .append( this.$indicator, this.$label );
13696 };
13697
13698 /* Setup */
13699
13700 OO.inheritClass( OO.ui.CapsuleItemWidget, OO.ui.Widget );
13701 OO.mixinClass( OO.ui.CapsuleItemWidget, OO.ui.mixin.ItemWidget );
13702 OO.mixinClass( OO.ui.CapsuleItemWidget, OO.ui.mixin.IndicatorElement );
13703 OO.mixinClass( OO.ui.CapsuleItemWidget, OO.ui.mixin.LabelElement );
13704 OO.mixinClass( OO.ui.CapsuleItemWidget, OO.ui.mixin.FlaggedElement );
13705 OO.mixinClass( OO.ui.CapsuleItemWidget, OO.ui.mixin.TabIndexedElement );
13706
13707 /* Methods */
13708
13709 /**
13710 * Handle close icon clicks
13711 * @param {jQuery.Event} event
13712 */
13713 OO.ui.CapsuleItemWidget.prototype.onCloseClick = function () {
13714 var element = this.getElementGroup();
13715
13716 if ( !this.isDisabled() && element && $.isFunction( element.removeItems ) ) {
13717 element.removeItems( [ this ] );
13718 element.focus();
13719 }
13720 };
13721
13722 /**
13723 * Handle close keyboard events
13724 * @param {jQuery.Event} event Key down event
13725 */
13726 OO.ui.CapsuleItemWidget.prototype.onCloseKeyDown = function ( e ) {
13727 if ( !this.isDisabled() && $.isFunction( this.getElementGroup().removeItems ) ) {
13728 switch ( e.which ) {
13729 case OO.ui.Keys.ENTER:
13730 case OO.ui.Keys.BACKSPACE:
13731 case OO.ui.Keys.SPACE:
13732 this.getElementGroup().removeItems( [ this ] );
13733 return false;
13734 }
13735 }
13736 };
13737
13738 /**
13739 * DropdownWidgets are not menus themselves, rather they contain a menu of options created with
13740 * OO.ui.MenuOptionWidget. The DropdownWidget takes care of opening and displaying the menu so that
13741 * users can interact with it.
13742 *
13743 * If you want to use this within a HTML form, such as a OO.ui.FormLayout, use
13744 * OO.ui.DropdownInputWidget instead.
13745 *
13746 * @example
13747 * // Example: A DropdownWidget with a menu that contains three options
13748 * var dropDown = new OO.ui.DropdownWidget( {
13749 * label: 'Dropdown menu: Select a menu option',
13750 * menu: {
13751 * items: [
13752 * new OO.ui.MenuOptionWidget( {
13753 * data: 'a',
13754 * label: 'First'
13755 * } ),
13756 * new OO.ui.MenuOptionWidget( {
13757 * data: 'b',
13758 * label: 'Second'
13759 * } ),
13760 * new OO.ui.MenuOptionWidget( {
13761 * data: 'c',
13762 * label: 'Third'
13763 * } )
13764 * ]
13765 * }
13766 * } );
13767 *
13768 * $( 'body' ).append( dropDown.$element );
13769 *
13770 * dropDown.getMenu().selectItemByData( 'b' );
13771 *
13772 * dropDown.getMenu().getSelectedItem().getData(); // returns 'b'
13773 *
13774 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
13775 *
13776 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
13777 *
13778 * @class
13779 * @extends OO.ui.Widget
13780 * @mixins OO.ui.mixin.IconElement
13781 * @mixins OO.ui.mixin.IndicatorElement
13782 * @mixins OO.ui.mixin.LabelElement
13783 * @mixins OO.ui.mixin.TitledElement
13784 * @mixins OO.ui.mixin.TabIndexedElement
13785 *
13786 * @constructor
13787 * @param {Object} [config] Configuration options
13788 * @cfg {Object} [menu] Configuration options to pass to {@link OO.ui.FloatingMenuSelectWidget menu select widget}
13789 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
13790 * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
13791 * containing `<div>` and has a larger area. By default, the menu uses relative positioning.
13792 */
13793 OO.ui.DropdownWidget = function OoUiDropdownWidget( config ) {
13794 // Configuration initialization
13795 config = $.extend( { indicator: 'down' }, config );
13796
13797 // Parent constructor
13798 OO.ui.DropdownWidget.parent.call( this, config );
13799
13800 // Properties (must be set before TabIndexedElement constructor call)
13801 this.$handle = this.$( '<span>' );
13802 this.$overlay = config.$overlay || this.$element;
13803
13804 // Mixin constructors
13805 OO.ui.mixin.IconElement.call( this, config );
13806 OO.ui.mixin.IndicatorElement.call( this, config );
13807 OO.ui.mixin.LabelElement.call( this, config );
13808 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$label } ) );
13809 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$handle } ) );
13810
13811 // Properties
13812 this.menu = new OO.ui.FloatingMenuSelectWidget( $.extend( {
13813 widget: this,
13814 $container: this.$element
13815 }, config.menu ) );
13816
13817 // Events
13818 this.$handle.on( {
13819 click: this.onClick.bind( this ),
13820 keypress: this.onKeyPress.bind( this )
13821 } );
13822 this.menu.connect( this, { select: 'onMenuSelect' } );
13823
13824 // Initialization
13825 this.$handle
13826 .addClass( 'oo-ui-dropdownWidget-handle' )
13827 .append( this.$icon, this.$label, this.$indicator );
13828 this.$element
13829 .addClass( 'oo-ui-dropdownWidget' )
13830 .append( this.$handle );
13831 this.$overlay.append( this.menu.$element );
13832 };
13833
13834 /* Setup */
13835
13836 OO.inheritClass( OO.ui.DropdownWidget, OO.ui.Widget );
13837 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.IconElement );
13838 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.IndicatorElement );
13839 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.LabelElement );
13840 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.TitledElement );
13841 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.TabIndexedElement );
13842
13843 /* Methods */
13844
13845 /**
13846 * Get the menu.
13847 *
13848 * @return {OO.ui.MenuSelectWidget} Menu of widget
13849 */
13850 OO.ui.DropdownWidget.prototype.getMenu = function () {
13851 return this.menu;
13852 };
13853
13854 /**
13855 * Handles menu select events.
13856 *
13857 * @private
13858 * @param {OO.ui.MenuOptionWidget} item Selected menu item
13859 */
13860 OO.ui.DropdownWidget.prototype.onMenuSelect = function ( item ) {
13861 var selectedLabel;
13862
13863 if ( !item ) {
13864 this.setLabel( null );
13865 return;
13866 }
13867
13868 selectedLabel = item.getLabel();
13869
13870 // If the label is a DOM element, clone it, because setLabel will append() it
13871 if ( selectedLabel instanceof jQuery ) {
13872 selectedLabel = selectedLabel.clone();
13873 }
13874
13875 this.setLabel( selectedLabel );
13876 };
13877
13878 /**
13879 * Handle mouse click events.
13880 *
13881 * @private
13882 * @param {jQuery.Event} e Mouse click event
13883 */
13884 OO.ui.DropdownWidget.prototype.onClick = function ( e ) {
13885 if ( !this.isDisabled() && e.which === 1 ) {
13886 this.menu.toggle();
13887 }
13888 return false;
13889 };
13890
13891 /**
13892 * Handle key press events.
13893 *
13894 * @private
13895 * @param {jQuery.Event} e Key press event
13896 */
13897 OO.ui.DropdownWidget.prototype.onKeyPress = function ( e ) {
13898 if ( !this.isDisabled() &&
13899 ( ( e.which === OO.ui.Keys.SPACE && !this.menu.isVisible() ) || e.which === OO.ui.Keys.ENTER )
13900 ) {
13901 this.menu.toggle();
13902 return false;
13903 }
13904 };
13905
13906 /**
13907 * SelectFileWidgets allow for selecting files, using the HTML5 File API. These
13908 * widgets can be configured with {@link OO.ui.mixin.IconElement icons} and {@link
13909 * OO.ui.mixin.IndicatorElement indicators}.
13910 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
13911 *
13912 * @example
13913 * // Example of a file select widget
13914 * var selectFile = new OO.ui.SelectFileWidget();
13915 * $( 'body' ).append( selectFile.$element );
13916 *
13917 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets
13918 *
13919 * @class
13920 * @extends OO.ui.Widget
13921 * @mixins OO.ui.mixin.IconElement
13922 * @mixins OO.ui.mixin.IndicatorElement
13923 * @mixins OO.ui.mixin.PendingElement
13924 * @mixins OO.ui.mixin.LabelElement
13925 *
13926 * @constructor
13927 * @param {Object} [config] Configuration options
13928 * @cfg {string[]|null} [accept=null] MIME types to accept. null accepts all types.
13929 * @cfg {string} [placeholder] Text to display when no file is selected.
13930 * @cfg {string} [notsupported] Text to display when file support is missing in the browser.
13931 * @cfg {boolean} [droppable=true] Whether to accept files by drag and drop.
13932 * @cfg {boolean} [showDropTarget=false] Whether to show a drop target. Requires droppable to be true.
13933 * @cfg {boolean} [dragDropUI=false] Deprecated alias for showDropTarget
13934 */
13935 OO.ui.SelectFileWidget = function OoUiSelectFileWidget( config ) {
13936 var dragHandler;
13937
13938 // TODO: Remove in next release
13939 if ( config && config.dragDropUI ) {
13940 config.showDropTarget = true;
13941 }
13942
13943 // Configuration initialization
13944 config = $.extend( {
13945 accept: null,
13946 placeholder: OO.ui.msg( 'ooui-selectfile-placeholder' ),
13947 notsupported: OO.ui.msg( 'ooui-selectfile-not-supported' ),
13948 droppable: true,
13949 showDropTarget: false
13950 }, config );
13951
13952 // Parent constructor
13953 OO.ui.SelectFileWidget.parent.call( this, config );
13954
13955 // Mixin constructors
13956 OO.ui.mixin.IconElement.call( this, config );
13957 OO.ui.mixin.IndicatorElement.call( this, config );
13958 OO.ui.mixin.PendingElement.call( this, $.extend( {}, config, { $pending: this.$info } ) );
13959 OO.ui.mixin.LabelElement.call( this, $.extend( {}, config, { autoFitLabel: true } ) );
13960
13961 // Properties
13962 this.$info = $( '<span>' );
13963
13964 // Properties
13965 this.showDropTarget = config.showDropTarget;
13966 this.isSupported = this.constructor.static.isSupported();
13967 this.currentFile = null;
13968 if ( Array.isArray( config.accept ) ) {
13969 this.accept = config.accept;
13970 } else {
13971 this.accept = null;
13972 }
13973 this.placeholder = config.placeholder;
13974 this.notsupported = config.notsupported;
13975 this.onFileSelectedHandler = this.onFileSelected.bind( this );
13976
13977 this.selectButton = new OO.ui.ButtonWidget( {
13978 classes: [ 'oo-ui-selectFileWidget-selectButton' ],
13979 label: 'Select a file',
13980 disabled: this.disabled || !this.isSupported
13981 } );
13982
13983 this.clearButton = new OO.ui.ButtonWidget( {
13984 classes: [ 'oo-ui-selectFileWidget-clearButton' ],
13985 framed: false,
13986 icon: 'remove',
13987 disabled: this.disabled
13988 } );
13989
13990 // Events
13991 this.selectButton.$button.on( {
13992 keypress: this.onKeyPress.bind( this )
13993 } );
13994 this.clearButton.connect( this, {
13995 click: 'onClearClick'
13996 } );
13997 if ( config.droppable ) {
13998 dragHandler = this.onDragEnterOrOver.bind( this );
13999 this.$element.on( {
14000 dragenter: dragHandler,
14001 dragover: dragHandler,
14002 dragleave: this.onDragLeave.bind( this ),
14003 drop: this.onDrop.bind( this )
14004 } );
14005 }
14006
14007 // Initialization
14008 this.addInput();
14009 this.updateUI();
14010 this.$label.addClass( 'oo-ui-selectFileWidget-label' );
14011 this.$info
14012 .addClass( 'oo-ui-selectFileWidget-info' )
14013 .append( this.$icon, this.$label, this.clearButton.$element, this.$indicator );
14014 this.$element
14015 .addClass( 'oo-ui-selectFileWidget' )
14016 .append( this.$info, this.selectButton.$element );
14017 if ( config.droppable && config.showDropTarget ) {
14018 this.$dropTarget = $( '<div>' )
14019 .addClass( 'oo-ui-selectFileWidget-dropTarget' )
14020 .text( OO.ui.msg( 'ooui-selectfile-dragdrop-placeholder' ) )
14021 .on( {
14022 click: this.onDropTargetClick.bind( this )
14023 } );
14024 this.$element.prepend( this.$dropTarget );
14025 }
14026 };
14027
14028 /* Setup */
14029
14030 OO.inheritClass( OO.ui.SelectFileWidget, OO.ui.Widget );
14031 OO.mixinClass( OO.ui.SelectFileWidget, OO.ui.mixin.IconElement );
14032 OO.mixinClass( OO.ui.SelectFileWidget, OO.ui.mixin.IndicatorElement );
14033 OO.mixinClass( OO.ui.SelectFileWidget, OO.ui.mixin.PendingElement );
14034 OO.mixinClass( OO.ui.SelectFileWidget, OO.ui.mixin.LabelElement );
14035
14036 /* Static Properties */
14037
14038 /**
14039 * Check if this widget is supported
14040 *
14041 * @static
14042 * @return {boolean}
14043 */
14044 OO.ui.SelectFileWidget.static.isSupported = function () {
14045 var $input;
14046 if ( OO.ui.SelectFileWidget.static.isSupportedCache === null ) {
14047 $input = $( '<input type="file">' );
14048 OO.ui.SelectFileWidget.static.isSupportedCache = $input[ 0 ].files !== undefined;
14049 }
14050 return OO.ui.SelectFileWidget.static.isSupportedCache;
14051 };
14052
14053 OO.ui.SelectFileWidget.static.isSupportedCache = null;
14054
14055 /* Events */
14056
14057 /**
14058 * @event change
14059 *
14060 * A change event is emitted when the on/off state of the toggle changes.
14061 *
14062 * @param {File|null} value New value
14063 */
14064
14065 /* Methods */
14066
14067 /**
14068 * Get the current value of the field
14069 *
14070 * @return {File|null}
14071 */
14072 OO.ui.SelectFileWidget.prototype.getValue = function () {
14073 return this.currentFile;
14074 };
14075
14076 /**
14077 * Set the current value of the field
14078 *
14079 * @param {File|null} file File to select
14080 */
14081 OO.ui.SelectFileWidget.prototype.setValue = function ( file ) {
14082 if ( this.currentFile !== file ) {
14083 this.currentFile = file;
14084 this.updateUI();
14085 this.emit( 'change', this.currentFile );
14086 }
14087 };
14088
14089 /**
14090 * Update the user interface when a file is selected or unselected
14091 *
14092 * @protected
14093 */
14094 OO.ui.SelectFileWidget.prototype.updateUI = function () {
14095 var $label;
14096 if ( !this.isSupported ) {
14097 this.$element.addClass( 'oo-ui-selectFileWidget-notsupported' );
14098 this.$element.removeClass( 'oo-ui-selectFileWidget-empty' );
14099 this.setLabel( this.notsupported );
14100 } else {
14101 this.$element.addClass( 'oo-ui-selectFileWidget-supported' );
14102 if ( this.currentFile ) {
14103 this.$element.removeClass( 'oo-ui-selectFileWidget-empty' );
14104 $label = $( [] );
14105 if ( this.currentFile.type !== '' ) {
14106 $label = $label.add( $( '<span>' ).addClass( 'oo-ui-selectFileWidget-fileType' ).text( this.currentFile.type ) );
14107 }
14108 $label = $label.add( $( '<span>' ).text( this.currentFile.name ) );
14109 this.setLabel( $label );
14110 } else {
14111 this.$element.addClass( 'oo-ui-selectFileWidget-empty' );
14112 this.setLabel( this.placeholder );
14113 }
14114 }
14115
14116 if ( this.$input ) {
14117 this.$input.attr( 'title', this.getLabel() );
14118 }
14119 };
14120
14121 /**
14122 * Add the input to the widget
14123 *
14124 * @private
14125 */
14126 OO.ui.SelectFileWidget.prototype.addInput = function () {
14127 if ( this.$input ) {
14128 this.$input.remove();
14129 }
14130
14131 if ( !this.isSupported ) {
14132 this.$input = null;
14133 return;
14134 }
14135
14136 this.$input = $( '<input type="file">' );
14137 this.$input.on( 'change', this.onFileSelectedHandler );
14138 this.$input.attr( {
14139 tabindex: -1,
14140 title: this.getLabel()
14141 } );
14142 if ( this.accept ) {
14143 this.$input.attr( 'accept', this.accept.join( ', ' ) );
14144 }
14145 this.selectButton.$button.append( this.$input );
14146 };
14147
14148 /**
14149 * Determine if we should accept this file
14150 *
14151 * @private
14152 * @param {string} File MIME type
14153 * @return {boolean}
14154 */
14155 OO.ui.SelectFileWidget.prototype.isAllowedType = function ( mimeType ) {
14156 var i, mimeTest;
14157
14158 if ( !this.accept || !mimeType ) {
14159 return true;
14160 }
14161
14162 for ( i = 0; i < this.accept.length; i++ ) {
14163 mimeTest = this.accept[ i ];
14164 if ( mimeTest === mimeType ) {
14165 return true;
14166 } else if ( mimeTest.substr( -2 ) === '/*' ) {
14167 mimeTest = mimeTest.substr( 0, mimeTest.length - 1 );
14168 if ( mimeType.substr( 0, mimeTest.length ) === mimeTest ) {
14169 return true;
14170 }
14171 }
14172 }
14173
14174 return false;
14175 };
14176
14177 /**
14178 * Handle file selection from the input
14179 *
14180 * @private
14181 * @param {jQuery.Event} e
14182 */
14183 OO.ui.SelectFileWidget.prototype.onFileSelected = function ( e ) {
14184 var file = OO.getProp( e.target, 'files', 0 ) || null;
14185
14186 if ( file && !this.isAllowedType( file.type ) ) {
14187 file = null;
14188 }
14189
14190 this.setValue( file );
14191 this.addInput();
14192 };
14193
14194 /**
14195 * Handle clear button click events.
14196 *
14197 * @private
14198 */
14199 OO.ui.SelectFileWidget.prototype.onClearClick = function () {
14200 this.setValue( null );
14201 return false;
14202 };
14203
14204 /**
14205 * Handle key press events.
14206 *
14207 * @private
14208 * @param {jQuery.Event} e Key press event
14209 */
14210 OO.ui.SelectFileWidget.prototype.onKeyPress = function ( e ) {
14211 if ( this.isSupported && !this.isDisabled() && this.$input &&
14212 ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
14213 ) {
14214 this.$input.click();
14215 return false;
14216 }
14217 };
14218
14219 /**
14220 * Handle drop target click events.
14221 *
14222 * @private
14223 * @param {jQuery.Event} e Key press event
14224 */
14225 OO.ui.SelectFileWidget.prototype.onDropTargetClick = function () {
14226 if ( this.isSupported && !this.isDisabled() && this.$input ) {
14227 this.$input.click();
14228 return false;
14229 }
14230 };
14231
14232 /**
14233 * Handle drag enter and over events
14234 *
14235 * @private
14236 * @param {jQuery.Event} e Drag event
14237 */
14238 OO.ui.SelectFileWidget.prototype.onDragEnterOrOver = function ( e ) {
14239 var itemOrFile,
14240 droppableFile = false,
14241 dt = e.originalEvent.dataTransfer;
14242
14243 e.preventDefault();
14244 e.stopPropagation();
14245
14246 if ( this.isDisabled() || !this.isSupported ) {
14247 this.$element.removeClass( 'oo-ui-selectFileWidget-canDrop' );
14248 dt.dropEffect = 'none';
14249 return false;
14250 }
14251
14252 // DataTransferItem and File both have a type property, but in Chrome files
14253 // have no information at this point.
14254 itemOrFile = OO.getProp( dt, 'items', 0 ) || OO.getProp( dt, 'files', 0 );
14255 if ( itemOrFile ) {
14256 if ( this.isAllowedType( itemOrFile.type ) ) {
14257 droppableFile = true;
14258 }
14259 // dt.types is Array-like, but not an Array
14260 } else if ( Array.prototype.indexOf.call( OO.getProp( dt, 'types' ) || [], 'Files' ) !== -1 ) {
14261 // File information is not available at this point for security so just assume
14262 // it is acceptable for now.
14263 // https://bugzilla.mozilla.org/show_bug.cgi?id=640534
14264 droppableFile = true;
14265 }
14266
14267 this.$element.toggleClass( 'oo-ui-selectFileWidget-canDrop', droppableFile );
14268 if ( !droppableFile ) {
14269 dt.dropEffect = 'none';
14270 }
14271
14272 return false;
14273 };
14274
14275 /**
14276 * Handle drag leave events
14277 *
14278 * @private
14279 * @param {jQuery.Event} e Drag event
14280 */
14281 OO.ui.SelectFileWidget.prototype.onDragLeave = function () {
14282 this.$element.removeClass( 'oo-ui-selectFileWidget-canDrop' );
14283 };
14284
14285 /**
14286 * Handle drop events
14287 *
14288 * @private
14289 * @param {jQuery.Event} e Drop event
14290 */
14291 OO.ui.SelectFileWidget.prototype.onDrop = function ( e ) {
14292 var file = null,
14293 dt = e.originalEvent.dataTransfer;
14294
14295 e.preventDefault();
14296 e.stopPropagation();
14297 this.$element.removeClass( 'oo-ui-selectFileWidget-canDrop' );
14298
14299 if ( this.isDisabled() || !this.isSupported ) {
14300 return false;
14301 }
14302
14303 file = OO.getProp( dt, 'files', 0 );
14304 if ( file && !this.isAllowedType( file.type ) ) {
14305 file = null;
14306 }
14307 if ( file ) {
14308 this.setValue( file );
14309 }
14310
14311 return false;
14312 };
14313
14314 /**
14315 * @inheritdoc
14316 */
14317 OO.ui.SelectFileWidget.prototype.setDisabled = function ( disabled ) {
14318 OO.ui.SelectFileWidget.parent.prototype.setDisabled.call( this, disabled );
14319 if ( this.selectButton ) {
14320 this.selectButton.setDisabled( disabled );
14321 }
14322 if ( this.clearButton ) {
14323 this.clearButton.setDisabled( disabled );
14324 }
14325 return this;
14326 };
14327
14328 /**
14329 * IconWidget is a generic widget for {@link OO.ui.mixin.IconElement icons}. In general, IconWidgets should be used with OO.ui.LabelWidget,
14330 * which creates a label that identifies the icon’s function. See the [OOjs UI documentation on MediaWiki] [1]
14331 * for a list of icons included in the library.
14332 *
14333 * @example
14334 * // An icon widget with a label
14335 * var myIcon = new OO.ui.IconWidget( {
14336 * icon: 'help',
14337 * iconTitle: 'Help'
14338 * } );
14339 * // Create a label.
14340 * var iconLabel = new OO.ui.LabelWidget( {
14341 * label: 'Help'
14342 * } );
14343 * $( 'body' ).append( myIcon.$element, iconLabel.$element );
14344 *
14345 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
14346 *
14347 * @class
14348 * @extends OO.ui.Widget
14349 * @mixins OO.ui.mixin.IconElement
14350 * @mixins OO.ui.mixin.TitledElement
14351 * @mixins OO.ui.mixin.FlaggedElement
14352 *
14353 * @constructor
14354 * @param {Object} [config] Configuration options
14355 */
14356 OO.ui.IconWidget = function OoUiIconWidget( config ) {
14357 // Configuration initialization
14358 config = config || {};
14359
14360 // Parent constructor
14361 OO.ui.IconWidget.parent.call( this, config );
14362
14363 // Mixin constructors
14364 OO.ui.mixin.IconElement.call( this, $.extend( {}, config, { $icon: this.$element } ) );
14365 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$element } ) );
14366 OO.ui.mixin.FlaggedElement.call( this, $.extend( {}, config, { $flagged: this.$element } ) );
14367
14368 // Initialization
14369 this.$element.addClass( 'oo-ui-iconWidget' );
14370 };
14371
14372 /* Setup */
14373
14374 OO.inheritClass( OO.ui.IconWidget, OO.ui.Widget );
14375 OO.mixinClass( OO.ui.IconWidget, OO.ui.mixin.IconElement );
14376 OO.mixinClass( OO.ui.IconWidget, OO.ui.mixin.TitledElement );
14377 OO.mixinClass( OO.ui.IconWidget, OO.ui.mixin.FlaggedElement );
14378
14379 /* Static Properties */
14380
14381 OO.ui.IconWidget.static.tagName = 'span';
14382
14383 /**
14384 * IndicatorWidgets create indicators, which are small graphics that are generally used to draw
14385 * attention to the status of an item or to clarify the function of a control. For a list of
14386 * indicators included in the library, please see the [OOjs UI documentation on MediaWiki][1].
14387 *
14388 * @example
14389 * // Example of an indicator widget
14390 * var indicator1 = new OO.ui.IndicatorWidget( {
14391 * indicator: 'alert'
14392 * } );
14393 *
14394 * // Create a fieldset layout to add a label
14395 * var fieldset = new OO.ui.FieldsetLayout();
14396 * fieldset.addItems( [
14397 * new OO.ui.FieldLayout( indicator1, { label: 'An alert indicator:' } )
14398 * ] );
14399 * $( 'body' ).append( fieldset.$element );
14400 *
14401 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
14402 *
14403 * @class
14404 * @extends OO.ui.Widget
14405 * @mixins OO.ui.mixin.IndicatorElement
14406 * @mixins OO.ui.mixin.TitledElement
14407 *
14408 * @constructor
14409 * @param {Object} [config] Configuration options
14410 */
14411 OO.ui.IndicatorWidget = function OoUiIndicatorWidget( config ) {
14412 // Configuration initialization
14413 config = config || {};
14414
14415 // Parent constructor
14416 OO.ui.IndicatorWidget.parent.call( this, config );
14417
14418 // Mixin constructors
14419 OO.ui.mixin.IndicatorElement.call( this, $.extend( {}, config, { $indicator: this.$element } ) );
14420 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$element } ) );
14421
14422 // Initialization
14423 this.$element.addClass( 'oo-ui-indicatorWidget' );
14424 };
14425
14426 /* Setup */
14427
14428 OO.inheritClass( OO.ui.IndicatorWidget, OO.ui.Widget );
14429 OO.mixinClass( OO.ui.IndicatorWidget, OO.ui.mixin.IndicatorElement );
14430 OO.mixinClass( OO.ui.IndicatorWidget, OO.ui.mixin.TitledElement );
14431
14432 /* Static Properties */
14433
14434 OO.ui.IndicatorWidget.static.tagName = 'span';
14435
14436 /**
14437 * InputWidget is the base class for all input widgets, which
14438 * include {@link OO.ui.TextInputWidget text inputs}, {@link OO.ui.CheckboxInputWidget checkbox inputs},
14439 * {@link OO.ui.RadioInputWidget radio inputs}, and {@link OO.ui.ButtonInputWidget button inputs}.
14440 * See the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
14441 *
14442 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
14443 *
14444 * @abstract
14445 * @class
14446 * @extends OO.ui.Widget
14447 * @mixins OO.ui.mixin.FlaggedElement
14448 * @mixins OO.ui.mixin.TabIndexedElement
14449 * @mixins OO.ui.mixin.TitledElement
14450 * @mixins OO.ui.mixin.AccessKeyedElement
14451 *
14452 * @constructor
14453 * @param {Object} [config] Configuration options
14454 * @cfg {string} [name=''] The value of the input’s HTML `name` attribute.
14455 * @cfg {string} [value=''] The value of the input.
14456 * @cfg {string} [accessKey=''] The access key of the input.
14457 * @cfg {Function} [inputFilter] The name of an input filter function. Input filters modify the value of an input
14458 * before it is accepted.
14459 */
14460 OO.ui.InputWidget = function OoUiInputWidget( config ) {
14461 // Configuration initialization
14462 config = config || {};
14463
14464 // Parent constructor
14465 OO.ui.InputWidget.parent.call( this, config );
14466
14467 // Properties
14468 this.$input = this.getInputElement( config );
14469 this.value = '';
14470 this.inputFilter = config.inputFilter;
14471
14472 // Mixin constructors
14473 OO.ui.mixin.FlaggedElement.call( this, config );
14474 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$input } ) );
14475 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$input } ) );
14476 OO.ui.mixin.AccessKeyedElement.call( this, $.extend( {}, config, { $accessKeyed: this.$input } ) );
14477
14478 // Events
14479 this.$input.on( 'keydown mouseup cut paste change input select', this.onEdit.bind( this ) );
14480
14481 // Initialization
14482 this.$input
14483 .addClass( 'oo-ui-inputWidget-input' )
14484 .attr( 'name', config.name )
14485 .prop( 'disabled', this.isDisabled() );
14486 this.$element
14487 .addClass( 'oo-ui-inputWidget' )
14488 .append( this.$input );
14489 this.setValue( config.value );
14490 this.setAccessKey( config.accessKey );
14491 };
14492
14493 /* Setup */
14494
14495 OO.inheritClass( OO.ui.InputWidget, OO.ui.Widget );
14496 OO.mixinClass( OO.ui.InputWidget, OO.ui.mixin.FlaggedElement );
14497 OO.mixinClass( OO.ui.InputWidget, OO.ui.mixin.TabIndexedElement );
14498 OO.mixinClass( OO.ui.InputWidget, OO.ui.mixin.TitledElement );
14499 OO.mixinClass( OO.ui.InputWidget, OO.ui.mixin.AccessKeyedElement );
14500
14501 /* Static Properties */
14502
14503 OO.ui.InputWidget.static.supportsSimpleLabel = true;
14504
14505 /* Events */
14506
14507 /**
14508 * @event change
14509 *
14510 * A change event is emitted when the value of the input changes.
14511 *
14512 * @param {string} value
14513 */
14514
14515 /* Methods */
14516
14517 /**
14518 * Get input element.
14519 *
14520 * Subclasses of OO.ui.InputWidget use the `config` parameter to produce different elements in
14521 * different circumstances. The element must have a `value` property (like form elements).
14522 *
14523 * @protected
14524 * @param {Object} config Configuration options
14525 * @return {jQuery} Input element
14526 */
14527 OO.ui.InputWidget.prototype.getInputElement = function () {
14528 return $( '<input>' );
14529 };
14530
14531 /**
14532 * Handle potentially value-changing events.
14533 *
14534 * @private
14535 * @param {jQuery.Event} e Key down, mouse up, cut, paste, change, input, or select event
14536 */
14537 OO.ui.InputWidget.prototype.onEdit = function () {
14538 var widget = this;
14539 if ( !this.isDisabled() ) {
14540 // Allow the stack to clear so the value will be updated
14541 setTimeout( function () {
14542 widget.setValue( widget.$input.val() );
14543 } );
14544 }
14545 };
14546
14547 /**
14548 * Get the value of the input.
14549 *
14550 * @return {string} Input value
14551 */
14552 OO.ui.InputWidget.prototype.getValue = function () {
14553 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
14554 // it, and we won't know unless they're kind enough to trigger a 'change' event.
14555 var value = this.$input.val();
14556 if ( this.value !== value ) {
14557 this.setValue( value );
14558 }
14559 return this.value;
14560 };
14561
14562 /**
14563 * Set the direction of the input, either RTL (right-to-left) or LTR (left-to-right).
14564 *
14565 * @param {boolean} isRTL
14566 * Direction is right-to-left
14567 */
14568 OO.ui.InputWidget.prototype.setRTL = function ( isRTL ) {
14569 this.$input.prop( 'dir', isRTL ? 'rtl' : 'ltr' );
14570 };
14571
14572 /**
14573 * Set the value of the input.
14574 *
14575 * @param {string} value New value
14576 * @fires change
14577 * @chainable
14578 */
14579 OO.ui.InputWidget.prototype.setValue = function ( value ) {
14580 value = this.cleanUpValue( value );
14581 // Update the DOM if it has changed. Note that with cleanUpValue, it
14582 // is possible for the DOM value to change without this.value changing.
14583 if ( this.$input.val() !== value ) {
14584 this.$input.val( value );
14585 }
14586 if ( this.value !== value ) {
14587 this.value = value;
14588 this.emit( 'change', this.value );
14589 }
14590 return this;
14591 };
14592
14593 /**
14594 * Set the input's access key.
14595 * FIXME: This is the same code as in OO.ui.mixin.ButtonElement, maybe find a better place for it?
14596 *
14597 * @param {string} accessKey Input's access key, use empty string to remove
14598 * @chainable
14599 */
14600 OO.ui.InputWidget.prototype.setAccessKey = function ( accessKey ) {
14601 accessKey = typeof accessKey === 'string' && accessKey.length ? accessKey : null;
14602
14603 if ( this.accessKey !== accessKey ) {
14604 if ( this.$input ) {
14605 if ( accessKey !== null ) {
14606 this.$input.attr( 'accesskey', accessKey );
14607 } else {
14608 this.$input.removeAttr( 'accesskey' );
14609 }
14610 }
14611 this.accessKey = accessKey;
14612 }
14613
14614 return this;
14615 };
14616
14617 /**
14618 * Clean up incoming value.
14619 *
14620 * Ensures value is a string, and converts undefined and null to empty string.
14621 *
14622 * @private
14623 * @param {string} value Original value
14624 * @return {string} Cleaned up value
14625 */
14626 OO.ui.InputWidget.prototype.cleanUpValue = function ( value ) {
14627 if ( value === undefined || value === null ) {
14628 return '';
14629 } else if ( this.inputFilter ) {
14630 return this.inputFilter( String( value ) );
14631 } else {
14632 return String( value );
14633 }
14634 };
14635
14636 /**
14637 * Simulate the behavior of clicking on a label bound to this input. This method is only called by
14638 * {@link OO.ui.LabelWidget LabelWidget} and {@link OO.ui.FieldLayout FieldLayout}. It should not be
14639 * called directly.
14640 */
14641 OO.ui.InputWidget.prototype.simulateLabelClick = function () {
14642 if ( !this.isDisabled() ) {
14643 if ( this.$input.is( ':checkbox, :radio' ) ) {
14644 this.$input.click();
14645 }
14646 if ( this.$input.is( ':input' ) ) {
14647 this.$input[ 0 ].focus();
14648 }
14649 }
14650 };
14651
14652 /**
14653 * @inheritdoc
14654 */
14655 OO.ui.InputWidget.prototype.setDisabled = function ( state ) {
14656 OO.ui.InputWidget.parent.prototype.setDisabled.call( this, state );
14657 if ( this.$input ) {
14658 this.$input.prop( 'disabled', this.isDisabled() );
14659 }
14660 return this;
14661 };
14662
14663 /**
14664 * Focus the input.
14665 *
14666 * @chainable
14667 */
14668 OO.ui.InputWidget.prototype.focus = function () {
14669 this.$input[ 0 ].focus();
14670 return this;
14671 };
14672
14673 /**
14674 * Blur the input.
14675 *
14676 * @chainable
14677 */
14678 OO.ui.InputWidget.prototype.blur = function () {
14679 this.$input[ 0 ].blur();
14680 return this;
14681 };
14682
14683 /**
14684 * @inheritdoc
14685 */
14686 OO.ui.InputWidget.prototype.gatherPreInfuseState = function ( node ) {
14687 var
14688 state = OO.ui.InputWidget.parent.prototype.gatherPreInfuseState.call( this, node ),
14689 $input = state.$input || $( node ).find( '.oo-ui-inputWidget-input' );
14690 state.value = $input.val();
14691 // Might be better in TabIndexedElement, but it's awkward to do there because mixins are awkward
14692 state.focus = $input.is( ':focus' );
14693 return state;
14694 };
14695
14696 /**
14697 * @inheritdoc
14698 */
14699 OO.ui.InputWidget.prototype.restorePreInfuseState = function ( state ) {
14700 OO.ui.InputWidget.parent.prototype.restorePreInfuseState.call( this, state );
14701 if ( state.value !== undefined && state.value !== this.getValue() ) {
14702 this.setValue( state.value );
14703 }
14704 if ( state.focus ) {
14705 this.focus();
14706 }
14707 };
14708
14709 /**
14710 * ButtonInputWidget is used to submit HTML forms and is intended to be used within
14711 * a OO.ui.FormLayout. If you do not need the button to work with HTML forms, you probably
14712 * want to use OO.ui.ButtonWidget instead. Button input widgets can be rendered as either an
14713 * HTML `<button/>` (the default) or an HTML `<input/>` tags. See the
14714 * [OOjs UI documentation on MediaWiki] [1] for more information.
14715 *
14716 * @example
14717 * // A ButtonInputWidget rendered as an HTML button, the default.
14718 * var button = new OO.ui.ButtonInputWidget( {
14719 * label: 'Input button',
14720 * icon: 'check',
14721 * value: 'check'
14722 * } );
14723 * $( 'body' ).append( button.$element );
14724 *
14725 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs#Button_inputs
14726 *
14727 * @class
14728 * @extends OO.ui.InputWidget
14729 * @mixins OO.ui.mixin.ButtonElement
14730 * @mixins OO.ui.mixin.IconElement
14731 * @mixins OO.ui.mixin.IndicatorElement
14732 * @mixins OO.ui.mixin.LabelElement
14733 * @mixins OO.ui.mixin.TitledElement
14734 *
14735 * @constructor
14736 * @param {Object} [config] Configuration options
14737 * @cfg {string} [type='button'] The value of the HTML `'type'` attribute: 'button', 'submit' or 'reset'.
14738 * @cfg {boolean} [useInputTag=false] Use an `<input/>` tag instead of a `<button/>` tag, the default.
14739 * Widgets configured to be an `<input/>` do not support {@link #icon icons} and {@link #indicator indicators},
14740 * non-plaintext {@link #label labels}, or {@link #value values}. In general, useInputTag should only
14741 * be set to `true` when there’s need to support IE6 in a form with multiple buttons.
14742 */
14743 OO.ui.ButtonInputWidget = function OoUiButtonInputWidget( config ) {
14744 // Configuration initialization
14745 config = $.extend( { type: 'button', useInputTag: false }, config );
14746
14747 // Properties (must be set before parent constructor, which calls #setValue)
14748 this.useInputTag = config.useInputTag;
14749
14750 // Parent constructor
14751 OO.ui.ButtonInputWidget.parent.call( this, config );
14752
14753 // Mixin constructors
14754 OO.ui.mixin.ButtonElement.call( this, $.extend( {}, config, { $button: this.$input } ) );
14755 OO.ui.mixin.IconElement.call( this, config );
14756 OO.ui.mixin.IndicatorElement.call( this, config );
14757 OO.ui.mixin.LabelElement.call( this, config );
14758 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$input } ) );
14759
14760 // Initialization
14761 if ( !config.useInputTag ) {
14762 this.$input.append( this.$icon, this.$label, this.$indicator );
14763 }
14764 this.$element.addClass( 'oo-ui-buttonInputWidget' );
14765 };
14766
14767 /* Setup */
14768
14769 OO.inheritClass( OO.ui.ButtonInputWidget, OO.ui.InputWidget );
14770 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.ButtonElement );
14771 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.IconElement );
14772 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.IndicatorElement );
14773 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.LabelElement );
14774 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.TitledElement );
14775
14776 /* Static Properties */
14777
14778 /**
14779 * Disable generating `<label>` elements for buttons. One would very rarely need additional label
14780 * for a button, and it's already a big clickable target, and it causes unexpected rendering.
14781 */
14782 OO.ui.ButtonInputWidget.static.supportsSimpleLabel = false;
14783
14784 /* Methods */
14785
14786 /**
14787 * @inheritdoc
14788 * @protected
14789 */
14790 OO.ui.ButtonInputWidget.prototype.getInputElement = function ( config ) {
14791 var type = [ 'button', 'submit', 'reset' ].indexOf( config.type ) !== -1 ?
14792 config.type :
14793 'button';
14794 return $( '<' + ( config.useInputTag ? 'input' : 'button' ) + ' type="' + type + '">' );
14795 };
14796
14797 /**
14798 * Set label value.
14799 *
14800 * If #useInputTag is `true`, the label is set as the `value` of the `<input/>` tag.
14801 *
14802 * @param {jQuery|string|Function|null} label Label nodes, text, a function that returns nodes or
14803 * text, or `null` for no label
14804 * @chainable
14805 */
14806 OO.ui.ButtonInputWidget.prototype.setLabel = function ( label ) {
14807 OO.ui.mixin.LabelElement.prototype.setLabel.call( this, label );
14808
14809 if ( this.useInputTag ) {
14810 if ( typeof label === 'function' ) {
14811 label = OO.ui.resolveMsg( label );
14812 }
14813 if ( label instanceof jQuery ) {
14814 label = label.text();
14815 }
14816 if ( !label ) {
14817 label = '';
14818 }
14819 this.$input.val( label );
14820 }
14821
14822 return this;
14823 };
14824
14825 /**
14826 * Set the value of the input.
14827 *
14828 * This method is disabled for button inputs configured as {@link #useInputTag <input/> tags}, as
14829 * they do not support {@link #value values}.
14830 *
14831 * @param {string} value New value
14832 * @chainable
14833 */
14834 OO.ui.ButtonInputWidget.prototype.setValue = function ( value ) {
14835 if ( !this.useInputTag ) {
14836 OO.ui.ButtonInputWidget.parent.prototype.setValue.call( this, value );
14837 }
14838 return this;
14839 };
14840
14841 /**
14842 * CheckboxInputWidgets, like HTML checkboxes, can be selected and/or configured with a value.
14843 * Note that these {@link OO.ui.InputWidget input widgets} are best laid out
14844 * in {@link OO.ui.FieldLayout field layouts} that use the {@link OO.ui.FieldLayout#align inline}
14845 * alignment. For more information, please see the [OOjs UI documentation on MediaWiki][1].
14846 *
14847 * This widget can be used inside a HTML form, such as a OO.ui.FormLayout.
14848 *
14849 * @example
14850 * // An example of selected, unselected, and disabled checkbox inputs
14851 * var checkbox1=new OO.ui.CheckboxInputWidget( {
14852 * value: 'a',
14853 * selected: true
14854 * } );
14855 * var checkbox2=new OO.ui.CheckboxInputWidget( {
14856 * value: 'b'
14857 * } );
14858 * var checkbox3=new OO.ui.CheckboxInputWidget( {
14859 * value:'c',
14860 * disabled: true
14861 * } );
14862 * // Create a fieldset layout with fields for each checkbox.
14863 * var fieldset = new OO.ui.FieldsetLayout( {
14864 * label: 'Checkboxes'
14865 * } );
14866 * fieldset.addItems( [
14867 * new OO.ui.FieldLayout( checkbox1, { label: 'Selected checkbox', align: 'inline' } ),
14868 * new OO.ui.FieldLayout( checkbox2, { label: 'Unselected checkbox', align: 'inline' } ),
14869 * new OO.ui.FieldLayout( checkbox3, { label: 'Disabled checkbox', align: 'inline' } ),
14870 * ] );
14871 * $( 'body' ).append( fieldset.$element );
14872 *
14873 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
14874 *
14875 * @class
14876 * @extends OO.ui.InputWidget
14877 *
14878 * @constructor
14879 * @param {Object} [config] Configuration options
14880 * @cfg {boolean} [selected=false] Select the checkbox initially. By default, the checkbox is not selected.
14881 */
14882 OO.ui.CheckboxInputWidget = function OoUiCheckboxInputWidget( config ) {
14883 // Configuration initialization
14884 config = config || {};
14885
14886 // Parent constructor
14887 OO.ui.CheckboxInputWidget.parent.call( this, config );
14888
14889 // Initialization
14890 this.$element
14891 .addClass( 'oo-ui-checkboxInputWidget' )
14892 // Required for pretty styling in MediaWiki theme
14893 .append( $( '<span>' ) );
14894 this.setSelected( config.selected !== undefined ? config.selected : false );
14895 };
14896
14897 /* Setup */
14898
14899 OO.inheritClass( OO.ui.CheckboxInputWidget, OO.ui.InputWidget );
14900
14901 /* Methods */
14902
14903 /**
14904 * @inheritdoc
14905 * @protected
14906 */
14907 OO.ui.CheckboxInputWidget.prototype.getInputElement = function () {
14908 return $( '<input type="checkbox" />' );
14909 };
14910
14911 /**
14912 * @inheritdoc
14913 */
14914 OO.ui.CheckboxInputWidget.prototype.onEdit = function () {
14915 var widget = this;
14916 if ( !this.isDisabled() ) {
14917 // Allow the stack to clear so the value will be updated
14918 setTimeout( function () {
14919 widget.setSelected( widget.$input.prop( 'checked' ) );
14920 } );
14921 }
14922 };
14923
14924 /**
14925 * Set selection state of this checkbox.
14926 *
14927 * @param {boolean} state `true` for selected
14928 * @chainable
14929 */
14930 OO.ui.CheckboxInputWidget.prototype.setSelected = function ( state ) {
14931 state = !!state;
14932 if ( this.selected !== state ) {
14933 this.selected = state;
14934 this.$input.prop( 'checked', this.selected );
14935 this.emit( 'change', this.selected );
14936 }
14937 return this;
14938 };
14939
14940 /**
14941 * Check if this checkbox is selected.
14942 *
14943 * @return {boolean} Checkbox is selected
14944 */
14945 OO.ui.CheckboxInputWidget.prototype.isSelected = function () {
14946 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
14947 // it, and we won't know unless they're kind enough to trigger a 'change' event.
14948 var selected = this.$input.prop( 'checked' );
14949 if ( this.selected !== selected ) {
14950 this.setSelected( selected );
14951 }
14952 return this.selected;
14953 };
14954
14955 /**
14956 * @inheritdoc
14957 */
14958 OO.ui.CheckboxInputWidget.prototype.gatherPreInfuseState = function ( node ) {
14959 var
14960 state = OO.ui.CheckboxInputWidget.parent.prototype.gatherPreInfuseState.call( this, node ),
14961 $input = $( node ).find( '.oo-ui-inputWidget-input' );
14962 state.$input = $input; // shortcut for performance, used in InputWidget
14963 state.checked = $input.prop( 'checked' );
14964 return state;
14965 };
14966
14967 /**
14968 * @inheritdoc
14969 */
14970 OO.ui.CheckboxInputWidget.prototype.restorePreInfuseState = function ( state ) {
14971 OO.ui.CheckboxInputWidget.parent.prototype.restorePreInfuseState.call( this, state );
14972 if ( state.checked !== undefined && state.checked !== this.isSelected() ) {
14973 this.setSelected( state.checked );
14974 }
14975 };
14976
14977 /**
14978 * DropdownInputWidget is a {@link OO.ui.DropdownWidget DropdownWidget} intended to be used
14979 * within a HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with the value
14980 * of a hidden HTML `input` tag. Please see the [OOjs UI documentation on MediaWiki][1] for
14981 * more information about input widgets.
14982 *
14983 * A DropdownInputWidget always has a value (one of the options is always selected), unless there
14984 * are no options. If no `value` configuration option is provided, the first option is selected.
14985 * If you need a state representing no value (no option being selected), use a DropdownWidget.
14986 *
14987 * This and OO.ui.RadioSelectInputWidget support the same configuration options.
14988 *
14989 * @example
14990 * // Example: A DropdownInputWidget with three options
14991 * var dropdownInput = new OO.ui.DropdownInputWidget( {
14992 * options: [
14993 * { data: 'a', label: 'First' },
14994 * { data: 'b', label: 'Second'},
14995 * { data: 'c', label: 'Third' }
14996 * ]
14997 * } );
14998 * $( 'body' ).append( dropdownInput.$element );
14999 *
15000 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
15001 *
15002 * @class
15003 * @extends OO.ui.InputWidget
15004 * @mixins OO.ui.mixin.TitledElement
15005 *
15006 * @constructor
15007 * @param {Object} [config] Configuration options
15008 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
15009 * @cfg {Object} [dropdown] Configuration options for {@link OO.ui.DropdownWidget DropdownWidget}
15010 */
15011 OO.ui.DropdownInputWidget = function OoUiDropdownInputWidget( config ) {
15012 // Configuration initialization
15013 config = config || {};
15014
15015 // Properties (must be done before parent constructor which calls #setDisabled)
15016 this.dropdownWidget = new OO.ui.DropdownWidget( config.dropdown );
15017
15018 // Parent constructor
15019 OO.ui.DropdownInputWidget.parent.call( this, config );
15020
15021 // Mixin constructors
15022 OO.ui.mixin.TitledElement.call( this, config );
15023
15024 // Events
15025 this.dropdownWidget.getMenu().connect( this, { select: 'onMenuSelect' } );
15026
15027 // Initialization
15028 this.setOptions( config.options || [] );
15029 this.$element
15030 .addClass( 'oo-ui-dropdownInputWidget' )
15031 .append( this.dropdownWidget.$element );
15032 };
15033
15034 /* Setup */
15035
15036 OO.inheritClass( OO.ui.DropdownInputWidget, OO.ui.InputWidget );
15037 OO.mixinClass( OO.ui.DropdownInputWidget, OO.ui.mixin.TitledElement );
15038
15039 /* Methods */
15040
15041 /**
15042 * @inheritdoc
15043 * @protected
15044 */
15045 OO.ui.DropdownInputWidget.prototype.getInputElement = function () {
15046 return $( '<input type="hidden">' );
15047 };
15048
15049 /**
15050 * Handles menu select events.
15051 *
15052 * @private
15053 * @param {OO.ui.MenuOptionWidget} item Selected menu item
15054 */
15055 OO.ui.DropdownInputWidget.prototype.onMenuSelect = function ( item ) {
15056 this.setValue( item.getData() );
15057 };
15058
15059 /**
15060 * @inheritdoc
15061 */
15062 OO.ui.DropdownInputWidget.prototype.setValue = function ( value ) {
15063 value = this.cleanUpValue( value );
15064 this.dropdownWidget.getMenu().selectItemByData( value );
15065 OO.ui.DropdownInputWidget.parent.prototype.setValue.call( this, value );
15066 return this;
15067 };
15068
15069 /**
15070 * @inheritdoc
15071 */
15072 OO.ui.DropdownInputWidget.prototype.setDisabled = function ( state ) {
15073 this.dropdownWidget.setDisabled( state );
15074 OO.ui.DropdownInputWidget.parent.prototype.setDisabled.call( this, state );
15075 return this;
15076 };
15077
15078 /**
15079 * Set the options available for this input.
15080 *
15081 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
15082 * @chainable
15083 */
15084 OO.ui.DropdownInputWidget.prototype.setOptions = function ( options ) {
15085 var
15086 value = this.getValue(),
15087 widget = this;
15088
15089 // Rebuild the dropdown menu
15090 this.dropdownWidget.getMenu()
15091 .clearItems()
15092 .addItems( options.map( function ( opt ) {
15093 var optValue = widget.cleanUpValue( opt.data );
15094 return new OO.ui.MenuOptionWidget( {
15095 data: optValue,
15096 label: opt.label !== undefined ? opt.label : optValue
15097 } );
15098 } ) );
15099
15100 // Restore the previous value, or reset to something sensible
15101 if ( this.dropdownWidget.getMenu().getItemFromData( value ) ) {
15102 // Previous value is still available, ensure consistency with the dropdown
15103 this.setValue( value );
15104 } else {
15105 // No longer valid, reset
15106 if ( options.length ) {
15107 this.setValue( options[ 0 ].data );
15108 }
15109 }
15110
15111 return this;
15112 };
15113
15114 /**
15115 * @inheritdoc
15116 */
15117 OO.ui.DropdownInputWidget.prototype.focus = function () {
15118 this.dropdownWidget.getMenu().toggle( true );
15119 return this;
15120 };
15121
15122 /**
15123 * @inheritdoc
15124 */
15125 OO.ui.DropdownInputWidget.prototype.blur = function () {
15126 this.dropdownWidget.getMenu().toggle( false );
15127 return this;
15128 };
15129
15130 /**
15131 * RadioInputWidget creates a single radio button. Because radio buttons are usually used as a set,
15132 * in most cases you will want to use a {@link OO.ui.RadioSelectWidget radio select}
15133 * with {@link OO.ui.RadioOptionWidget radio options} instead of this class. For more information,
15134 * please see the [OOjs UI documentation on MediaWiki][1].
15135 *
15136 * This widget can be used inside a HTML form, such as a OO.ui.FormLayout.
15137 *
15138 * @example
15139 * // An example of selected, unselected, and disabled radio inputs
15140 * var radio1 = new OO.ui.RadioInputWidget( {
15141 * value: 'a',
15142 * selected: true
15143 * } );
15144 * var radio2 = new OO.ui.RadioInputWidget( {
15145 * value: 'b'
15146 * } );
15147 * var radio3 = new OO.ui.RadioInputWidget( {
15148 * value: 'c',
15149 * disabled: true
15150 * } );
15151 * // Create a fieldset layout with fields for each radio button.
15152 * var fieldset = new OO.ui.FieldsetLayout( {
15153 * label: 'Radio inputs'
15154 * } );
15155 * fieldset.addItems( [
15156 * new OO.ui.FieldLayout( radio1, { label: 'Selected', align: 'inline' } ),
15157 * new OO.ui.FieldLayout( radio2, { label: 'Unselected', align: 'inline' } ),
15158 * new OO.ui.FieldLayout( radio3, { label: 'Disabled', align: 'inline' } ),
15159 * ] );
15160 * $( 'body' ).append( fieldset.$element );
15161 *
15162 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
15163 *
15164 * @class
15165 * @extends OO.ui.InputWidget
15166 *
15167 * @constructor
15168 * @param {Object} [config] Configuration options
15169 * @cfg {boolean} [selected=false] Select the radio button initially. By default, the radio button is not selected.
15170 */
15171 OO.ui.RadioInputWidget = function OoUiRadioInputWidget( config ) {
15172 // Configuration initialization
15173 config = config || {};
15174
15175 // Parent constructor
15176 OO.ui.RadioInputWidget.parent.call( this, config );
15177
15178 // Initialization
15179 this.$element
15180 .addClass( 'oo-ui-radioInputWidget' )
15181 // Required for pretty styling in MediaWiki theme
15182 .append( $( '<span>' ) );
15183 this.setSelected( config.selected !== undefined ? config.selected : false );
15184 };
15185
15186 /* Setup */
15187
15188 OO.inheritClass( OO.ui.RadioInputWidget, OO.ui.InputWidget );
15189
15190 /* Methods */
15191
15192 /**
15193 * @inheritdoc
15194 * @protected
15195 */
15196 OO.ui.RadioInputWidget.prototype.getInputElement = function () {
15197 return $( '<input type="radio" />' );
15198 };
15199
15200 /**
15201 * @inheritdoc
15202 */
15203 OO.ui.RadioInputWidget.prototype.onEdit = function () {
15204 // RadioInputWidget doesn't track its state.
15205 };
15206
15207 /**
15208 * Set selection state of this radio button.
15209 *
15210 * @param {boolean} state `true` for selected
15211 * @chainable
15212 */
15213 OO.ui.RadioInputWidget.prototype.setSelected = function ( state ) {
15214 // RadioInputWidget doesn't track its state.
15215 this.$input.prop( 'checked', state );
15216 return this;
15217 };
15218
15219 /**
15220 * Check if this radio button is selected.
15221 *
15222 * @return {boolean} Radio is selected
15223 */
15224 OO.ui.RadioInputWidget.prototype.isSelected = function () {
15225 return this.$input.prop( 'checked' );
15226 };
15227
15228 /**
15229 * @inheritdoc
15230 */
15231 OO.ui.RadioInputWidget.prototype.gatherPreInfuseState = function ( node ) {
15232 var
15233 state = OO.ui.RadioInputWidget.parent.prototype.gatherPreInfuseState.call( this, node ),
15234 $input = $( node ).find( '.oo-ui-inputWidget-input' );
15235 state.$input = $input; // shortcut for performance, used in InputWidget
15236 state.checked = $input.prop( 'checked' );
15237 return state;
15238 };
15239
15240 /**
15241 * @inheritdoc
15242 */
15243 OO.ui.RadioInputWidget.prototype.restorePreInfuseState = function ( state ) {
15244 OO.ui.RadioInputWidget.parent.prototype.restorePreInfuseState.call( this, state );
15245 if ( state.checked !== undefined && state.checked !== this.isSelected() ) {
15246 this.setSelected( state.checked );
15247 }
15248 };
15249
15250 /**
15251 * RadioSelectInputWidget is a {@link OO.ui.RadioSelectWidget RadioSelectWidget} intended to be used
15252 * within a HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with the value
15253 * of a hidden HTML `input` tag. Please see the [OOjs UI documentation on MediaWiki][1] for
15254 * more information about input widgets.
15255 *
15256 * This and OO.ui.DropdownInputWidget support the same configuration options.
15257 *
15258 * @example
15259 * // Example: A RadioSelectInputWidget with three options
15260 * var radioSelectInput = new OO.ui.RadioSelectInputWidget( {
15261 * options: [
15262 * { data: 'a', label: 'First' },
15263 * { data: 'b', label: 'Second'},
15264 * { data: 'c', label: 'Third' }
15265 * ]
15266 * } );
15267 * $( 'body' ).append( radioSelectInput.$element );
15268 *
15269 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
15270 *
15271 * @class
15272 * @extends OO.ui.InputWidget
15273 *
15274 * @constructor
15275 * @param {Object} [config] Configuration options
15276 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
15277 */
15278 OO.ui.RadioSelectInputWidget = function OoUiRadioSelectInputWidget( config ) {
15279 // Configuration initialization
15280 config = config || {};
15281
15282 // Properties (must be done before parent constructor which calls #setDisabled)
15283 this.radioSelectWidget = new OO.ui.RadioSelectWidget();
15284
15285 // Parent constructor
15286 OO.ui.RadioSelectInputWidget.parent.call( this, config );
15287
15288 // Events
15289 this.radioSelectWidget.connect( this, { select: 'onMenuSelect' } );
15290
15291 // Initialization
15292 this.setOptions( config.options || [] );
15293 this.$element
15294 .addClass( 'oo-ui-radioSelectInputWidget' )
15295 .append( this.radioSelectWidget.$element );
15296 };
15297
15298 /* Setup */
15299
15300 OO.inheritClass( OO.ui.RadioSelectInputWidget, OO.ui.InputWidget );
15301
15302 /* Static Properties */
15303
15304 OO.ui.RadioSelectInputWidget.static.supportsSimpleLabel = false;
15305
15306 /* Methods */
15307
15308 /**
15309 * @inheritdoc
15310 * @protected
15311 */
15312 OO.ui.RadioSelectInputWidget.prototype.getInputElement = function () {
15313 return $( '<input type="hidden">' );
15314 };
15315
15316 /**
15317 * Handles menu select events.
15318 *
15319 * @private
15320 * @param {OO.ui.RadioOptionWidget} item Selected menu item
15321 */
15322 OO.ui.RadioSelectInputWidget.prototype.onMenuSelect = function ( item ) {
15323 this.setValue( item.getData() );
15324 };
15325
15326 /**
15327 * @inheritdoc
15328 */
15329 OO.ui.RadioSelectInputWidget.prototype.setValue = function ( value ) {
15330 value = this.cleanUpValue( value );
15331 this.radioSelectWidget.selectItemByData( value );
15332 OO.ui.RadioSelectInputWidget.parent.prototype.setValue.call( this, value );
15333 return this;
15334 };
15335
15336 /**
15337 * @inheritdoc
15338 */
15339 OO.ui.RadioSelectInputWidget.prototype.setDisabled = function ( state ) {
15340 this.radioSelectWidget.setDisabled( state );
15341 OO.ui.RadioSelectInputWidget.parent.prototype.setDisabled.call( this, state );
15342 return this;
15343 };
15344
15345 /**
15346 * Set the options available for this input.
15347 *
15348 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
15349 * @chainable
15350 */
15351 OO.ui.RadioSelectInputWidget.prototype.setOptions = function ( options ) {
15352 var
15353 value = this.getValue(),
15354 widget = this;
15355
15356 // Rebuild the radioSelect menu
15357 this.radioSelectWidget
15358 .clearItems()
15359 .addItems( options.map( function ( opt ) {
15360 var optValue = widget.cleanUpValue( opt.data );
15361 return new OO.ui.RadioOptionWidget( {
15362 data: optValue,
15363 label: opt.label !== undefined ? opt.label : optValue
15364 } );
15365 } ) );
15366
15367 // Restore the previous value, or reset to something sensible
15368 if ( this.radioSelectWidget.getItemFromData( value ) ) {
15369 // Previous value is still available, ensure consistency with the radioSelect
15370 this.setValue( value );
15371 } else {
15372 // No longer valid, reset
15373 if ( options.length ) {
15374 this.setValue( options[ 0 ].data );
15375 }
15376 }
15377
15378 return this;
15379 };
15380
15381 /**
15382 * @inheritdoc
15383 */
15384 OO.ui.RadioSelectInputWidget.prototype.gatherPreInfuseState = function ( node ) {
15385 var state = OO.ui.RadioSelectInputWidget.parent.prototype.gatherPreInfuseState.call( this, node );
15386 state.value = $( node ).find( '.oo-ui-radioInputWidget .oo-ui-inputWidget-input:checked' ).val();
15387 return state;
15388 };
15389
15390 /**
15391 * TextInputWidgets, like HTML text inputs, can be configured with options that customize the
15392 * size of the field as well as its presentation. In addition, these widgets can be configured
15393 * with {@link OO.ui.mixin.IconElement icons}, {@link OO.ui.mixin.IndicatorElement indicators}, an optional
15394 * validation-pattern (used to determine if an input value is valid or not) and an input filter,
15395 * which modifies incoming values rather than validating them.
15396 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
15397 *
15398 * This widget can be used inside a HTML form, such as a OO.ui.FormLayout.
15399 *
15400 * @example
15401 * // Example of a text input widget
15402 * var textInput = new OO.ui.TextInputWidget( {
15403 * value: 'Text input'
15404 * } )
15405 * $( 'body' ).append( textInput.$element );
15406 *
15407 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
15408 *
15409 * @class
15410 * @extends OO.ui.InputWidget
15411 * @mixins OO.ui.mixin.IconElement
15412 * @mixins OO.ui.mixin.IndicatorElement
15413 * @mixins OO.ui.mixin.PendingElement
15414 * @mixins OO.ui.mixin.LabelElement
15415 *
15416 * @constructor
15417 * @param {Object} [config] Configuration options
15418 * @cfg {string} [type='text'] The value of the HTML `type` attribute: 'text', 'password', 'search',
15419 * 'email' or 'url'. Ignored if `multiline` is true.
15420 *
15421 * Some values of `type` result in additional behaviors:
15422 *
15423 * - `search`: implies `icon: 'search'` and `indicator: 'clear'`; when clicked, the indicator
15424 * empties the text field
15425 * @cfg {string} [placeholder] Placeholder text
15426 * @cfg {boolean} [autofocus=false] Use an HTML `autofocus` attribute to
15427 * instruct the browser to focus this widget.
15428 * @cfg {boolean} [readOnly=false] Prevent changes to the value of the text input.
15429 * @cfg {number} [maxLength] Maximum number of characters allowed in the input.
15430 * @cfg {boolean} [multiline=false] Allow multiple lines of text
15431 * @cfg {number} [rows] If multiline, number of visible lines in textarea. If used with `autosize`,
15432 * specifies minimum number of rows to display.
15433 * @cfg {boolean} [autosize=false] Automatically resize the text input to fit its content.
15434 * Use the #maxRows config to specify a maximum number of displayed rows.
15435 * @cfg {boolean} [maxRows] Maximum number of rows to display when #autosize is set to true.
15436 * Defaults to the maximum of `10` and `2 * rows`, or `10` if `rows` isn't provided.
15437 * @cfg {string} [labelPosition='after'] The position of the inline label relative to that of
15438 * the value or placeholder text: `'before'` or `'after'`
15439 * @cfg {boolean} [required=false] Mark the field as required. Implies `indicator: 'required'`.
15440 * @cfg {boolean} [autocomplete=true] Should the browser support autocomplete for this field
15441 * @cfg {RegExp|Function|string} [validate] Validation pattern: when string, a symbolic name of a
15442 * pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer'
15443 * (the value must contain only numbers); when RegExp, a regular expression that must match the
15444 * value for it to be considered valid; when Function, a function receiving the value as parameter
15445 * that must return true, or promise resolving to true, for it to be considered valid.
15446 */
15447 OO.ui.TextInputWidget = function OoUiTextInputWidget( config ) {
15448 // Configuration initialization
15449 config = $.extend( {
15450 type: 'text',
15451 labelPosition: 'after'
15452 }, config );
15453 if ( config.type === 'search' ) {
15454 if ( config.icon === undefined ) {
15455 config.icon = 'search';
15456 }
15457 // indicator: 'clear' is set dynamically later, depending on value
15458 }
15459 if ( config.required ) {
15460 if ( config.indicator === undefined ) {
15461 config.indicator = 'required';
15462 }
15463 }
15464
15465 // Parent constructor
15466 OO.ui.TextInputWidget.parent.call( this, config );
15467
15468 // Mixin constructors
15469 OO.ui.mixin.IconElement.call( this, config );
15470 OO.ui.mixin.IndicatorElement.call( this, config );
15471 OO.ui.mixin.PendingElement.call( this, $.extend( {}, config, { $pending: this.$input } ) );
15472 OO.ui.mixin.LabelElement.call( this, config );
15473
15474 // Properties
15475 this.type = this.getSaneType( config );
15476 this.readOnly = false;
15477 this.multiline = !!config.multiline;
15478 this.autosize = !!config.autosize;
15479 this.minRows = config.rows !== undefined ? config.rows : '';
15480 this.maxRows = config.maxRows || Math.max( 2 * ( this.minRows || 0 ), 10 );
15481 this.validate = null;
15482
15483 // Clone for resizing
15484 if ( this.autosize ) {
15485 this.$clone = this.$input
15486 .clone()
15487 .insertAfter( this.$input )
15488 .attr( 'aria-hidden', 'true' )
15489 .addClass( 'oo-ui-element-hidden' );
15490 }
15491
15492 this.setValidation( config.validate );
15493 this.setLabelPosition( config.labelPosition );
15494
15495 // Events
15496 this.$input.on( {
15497 keypress: this.onKeyPress.bind( this ),
15498 blur: this.onBlur.bind( this )
15499 } );
15500 this.$input.one( {
15501 focus: this.onElementAttach.bind( this )
15502 } );
15503 this.$icon.on( 'mousedown', this.onIconMouseDown.bind( this ) );
15504 this.$indicator.on( 'mousedown', this.onIndicatorMouseDown.bind( this ) );
15505 this.on( 'labelChange', this.updatePosition.bind( this ) );
15506 this.connect( this, {
15507 change: 'onChange',
15508 disable: 'onDisable'
15509 } );
15510
15511 // Initialization
15512 this.$element
15513 .addClass( 'oo-ui-textInputWidget oo-ui-textInputWidget-type-' + this.type )
15514 .append( this.$icon, this.$indicator );
15515 this.setReadOnly( !!config.readOnly );
15516 this.updateSearchIndicator();
15517 if ( config.placeholder ) {
15518 this.$input.attr( 'placeholder', config.placeholder );
15519 }
15520 if ( config.maxLength !== undefined ) {
15521 this.$input.attr( 'maxlength', config.maxLength );
15522 }
15523 if ( config.autofocus ) {
15524 this.$input.attr( 'autofocus', 'autofocus' );
15525 }
15526 if ( config.required ) {
15527 this.$input.attr( 'required', 'required' );
15528 this.$input.attr( 'aria-required', 'true' );
15529 }
15530 if ( config.autocomplete === false ) {
15531 this.$input.attr( 'autocomplete', 'off' );
15532 }
15533 if ( this.multiline && config.rows ) {
15534 this.$input.attr( 'rows', config.rows );
15535 }
15536 if ( this.label || config.autosize ) {
15537 this.installParentChangeDetector();
15538 }
15539 };
15540
15541 /* Setup */
15542
15543 OO.inheritClass( OO.ui.TextInputWidget, OO.ui.InputWidget );
15544 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.mixin.IconElement );
15545 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.mixin.IndicatorElement );
15546 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.mixin.PendingElement );
15547 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.mixin.LabelElement );
15548
15549 /* Static Properties */
15550
15551 OO.ui.TextInputWidget.static.validationPatterns = {
15552 'non-empty': /.+/,
15553 integer: /^\d+$/
15554 };
15555
15556 /* Events */
15557
15558 /**
15559 * An `enter` event is emitted when the user presses 'enter' inside the text box.
15560 *
15561 * Not emitted if the input is multiline.
15562 *
15563 * @event enter
15564 */
15565
15566 /* Methods */
15567
15568 /**
15569 * Handle icon mouse down events.
15570 *
15571 * @private
15572 * @param {jQuery.Event} e Mouse down event
15573 * @fires icon
15574 */
15575 OO.ui.TextInputWidget.prototype.onIconMouseDown = function ( e ) {
15576 if ( e.which === 1 ) {
15577 this.$input[ 0 ].focus();
15578 return false;
15579 }
15580 };
15581
15582 /**
15583 * Handle indicator mouse down events.
15584 *
15585 * @private
15586 * @param {jQuery.Event} e Mouse down event
15587 * @fires indicator
15588 */
15589 OO.ui.TextInputWidget.prototype.onIndicatorMouseDown = function ( e ) {
15590 if ( e.which === 1 ) {
15591 if ( this.type === 'search' ) {
15592 // Clear the text field
15593 this.setValue( '' );
15594 }
15595 this.$input[ 0 ].focus();
15596 return false;
15597 }
15598 };
15599
15600 /**
15601 * Handle key press events.
15602 *
15603 * @private
15604 * @param {jQuery.Event} e Key press event
15605 * @fires enter If enter key is pressed and input is not multiline
15606 */
15607 OO.ui.TextInputWidget.prototype.onKeyPress = function ( e ) {
15608 if ( e.which === OO.ui.Keys.ENTER && !this.multiline ) {
15609 this.emit( 'enter', e );
15610 }
15611 };
15612
15613 /**
15614 * Handle blur events.
15615 *
15616 * @private
15617 * @param {jQuery.Event} e Blur event
15618 */
15619 OO.ui.TextInputWidget.prototype.onBlur = function () {
15620 this.setValidityFlag();
15621 };
15622
15623 /**
15624 * Handle element attach events.
15625 *
15626 * @private
15627 * @param {jQuery.Event} e Element attach event
15628 */
15629 OO.ui.TextInputWidget.prototype.onElementAttach = function () {
15630 // Any previously calculated size is now probably invalid if we reattached elsewhere
15631 this.valCache = null;
15632 this.adjustSize();
15633 this.positionLabel();
15634 };
15635
15636 /**
15637 * Handle change events.
15638 *
15639 * @param {string} value
15640 * @private
15641 */
15642 OO.ui.TextInputWidget.prototype.onChange = function () {
15643 this.updateSearchIndicator();
15644 this.setValidityFlag();
15645 this.adjustSize();
15646 };
15647
15648 /**
15649 * Handle disable events.
15650 *
15651 * @param {boolean} disabled Element is disabled
15652 * @private
15653 */
15654 OO.ui.TextInputWidget.prototype.onDisable = function () {
15655 this.updateSearchIndicator();
15656 };
15657
15658 /**
15659 * Check if the input is {@link #readOnly read-only}.
15660 *
15661 * @return {boolean}
15662 */
15663 OO.ui.TextInputWidget.prototype.isReadOnly = function () {
15664 return this.readOnly;
15665 };
15666
15667 /**
15668 * Set the {@link #readOnly read-only} state of the input.
15669 *
15670 * @param {boolean} state Make input read-only
15671 * @chainable
15672 */
15673 OO.ui.TextInputWidget.prototype.setReadOnly = function ( state ) {
15674 this.readOnly = !!state;
15675 this.$input.prop( 'readOnly', this.readOnly );
15676 this.updateSearchIndicator();
15677 return this;
15678 };
15679
15680 /**
15681 * Support function for making #onElementAttach work across browsers.
15682 *
15683 * This whole function could be replaced with one line of code using the DOMNodeInsertedIntoDocument
15684 * event, but it's not supported by Firefox and allegedly deprecated, so we only use it as fallback.
15685 *
15686 * Due to MutationObserver performance woes, #onElementAttach is only somewhat reliably called the
15687 * first time that the element gets attached to the documented.
15688 */
15689 OO.ui.TextInputWidget.prototype.installParentChangeDetector = function () {
15690 var mutationObserver, onRemove, topmostNode, fakeParentNode,
15691 MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver,
15692 widget = this;
15693
15694 if ( MutationObserver ) {
15695 // The new way. If only it wasn't so ugly.
15696
15697 if ( this.$element.closest( 'html' ).length ) {
15698 // Widget is attached already, do nothing. This breaks the functionality of this function when
15699 // the widget is detached and reattached. Alas, doing this correctly with MutationObserver
15700 // would require observation of the whole document, which would hurt performance of other,
15701 // more important code.
15702 return;
15703 }
15704
15705 // Find topmost node in the tree
15706 topmostNode = this.$element[ 0 ];
15707 while ( topmostNode.parentNode ) {
15708 topmostNode = topmostNode.parentNode;
15709 }
15710
15711 // We have no way to detect the $element being attached somewhere without observing the entire
15712 // DOM with subtree modifications, which would hurt performance. So we cheat: we hook to the
15713 // parent node of $element, and instead detect when $element is removed from it (and thus
15714 // probably attached somewhere else). If there is no parent, we create a "fake" one. If it
15715 // doesn't get attached, we end up back here and create the parent.
15716
15717 mutationObserver = new MutationObserver( function ( mutations ) {
15718 var i, j, removedNodes;
15719 for ( i = 0; i < mutations.length; i++ ) {
15720 removedNodes = mutations[ i ].removedNodes;
15721 for ( j = 0; j < removedNodes.length; j++ ) {
15722 if ( removedNodes[ j ] === topmostNode ) {
15723 setTimeout( onRemove, 0 );
15724 return;
15725 }
15726 }
15727 }
15728 } );
15729
15730 onRemove = function () {
15731 // If the node was attached somewhere else, report it
15732 if ( widget.$element.closest( 'html' ).length ) {
15733 widget.onElementAttach();
15734 }
15735 mutationObserver.disconnect();
15736 widget.installParentChangeDetector();
15737 };
15738
15739 // Create a fake parent and observe it
15740 fakeParentNode = $( '<div>' ).append( topmostNode )[ 0 ];
15741 mutationObserver.observe( fakeParentNode, { childList: true } );
15742 } else {
15743 // Using the DOMNodeInsertedIntoDocument event is much nicer and less magical, and works for
15744 // detachment and reattachment, but it's not supported by Firefox and allegedly deprecated.
15745 this.$element.on( 'DOMNodeInsertedIntoDocument', this.onElementAttach.bind( this ) );
15746 }
15747 };
15748
15749 /**
15750 * Automatically adjust the size of the text input.
15751 *
15752 * This only affects #multiline inputs that are {@link #autosize autosized}.
15753 *
15754 * @chainable
15755 */
15756 OO.ui.TextInputWidget.prototype.adjustSize = function () {
15757 var scrollHeight, innerHeight, outerHeight, maxInnerHeight, measurementError, idealHeight;
15758
15759 if ( this.multiline && this.autosize && this.$input.val() !== this.valCache ) {
15760 this.$clone
15761 .val( this.$input.val() )
15762 .attr( 'rows', this.minRows )
15763 // Set inline height property to 0 to measure scroll height
15764 .css( 'height', 0 );
15765
15766 this.$clone.removeClass( 'oo-ui-element-hidden' );
15767
15768 this.valCache = this.$input.val();
15769
15770 scrollHeight = this.$clone[ 0 ].scrollHeight;
15771
15772 // Remove inline height property to measure natural heights
15773 this.$clone.css( 'height', '' );
15774 innerHeight = this.$clone.innerHeight();
15775 outerHeight = this.$clone.outerHeight();
15776
15777 // Measure max rows height
15778 this.$clone
15779 .attr( 'rows', this.maxRows )
15780 .css( 'height', 'auto' )
15781 .val( '' );
15782 maxInnerHeight = this.$clone.innerHeight();
15783
15784 // Difference between reported innerHeight and scrollHeight with no scrollbars present
15785 // Equals 1 on Blink-based browsers and 0 everywhere else
15786 measurementError = maxInnerHeight - this.$clone[ 0 ].scrollHeight;
15787 idealHeight = Math.min( maxInnerHeight, scrollHeight + measurementError );
15788
15789 this.$clone.addClass( 'oo-ui-element-hidden' );
15790
15791 // Only apply inline height when expansion beyond natural height is needed
15792 if ( idealHeight > innerHeight ) {
15793 // Use the difference between the inner and outer height as a buffer
15794 this.$input.css( 'height', idealHeight + ( outerHeight - innerHeight ) );
15795 } else {
15796 this.$input.css( 'height', '' );
15797 }
15798 }
15799 return this;
15800 };
15801
15802 /**
15803 * @inheritdoc
15804 * @protected
15805 */
15806 OO.ui.TextInputWidget.prototype.getInputElement = function ( config ) {
15807 return config.multiline ?
15808 $( '<textarea>' ) :
15809 $( '<input type="' + this.getSaneType( config ) + '" />' );
15810 };
15811
15812 /**
15813 * Get sanitized value for 'type' for given config.
15814 *
15815 * @param {Object} config Configuration options
15816 * @return {string|null}
15817 * @private
15818 */
15819 OO.ui.TextInputWidget.prototype.getSaneType = function ( config ) {
15820 var type = [ 'text', 'password', 'search', 'email', 'url' ].indexOf( config.type ) !== -1 ?
15821 config.type :
15822 'text';
15823 return config.multiline ? 'multiline' : type;
15824 };
15825
15826 /**
15827 * Check if the input supports multiple lines.
15828 *
15829 * @return {boolean}
15830 */
15831 OO.ui.TextInputWidget.prototype.isMultiline = function () {
15832 return !!this.multiline;
15833 };
15834
15835 /**
15836 * Check if the input automatically adjusts its size.
15837 *
15838 * @return {boolean}
15839 */
15840 OO.ui.TextInputWidget.prototype.isAutosizing = function () {
15841 return !!this.autosize;
15842 };
15843
15844 /**
15845 * Select the entire text of the input.
15846 *
15847 * @chainable
15848 */
15849 OO.ui.TextInputWidget.prototype.select = function () {
15850 this.$input.select();
15851 return this;
15852 };
15853
15854 /**
15855 * Focus the input and move the cursor to the end.
15856 */
15857 OO.ui.TextInputWidget.prototype.moveCursorToEnd = function () {
15858 var textRange,
15859 element = this.$input[ 0 ];
15860 this.focus();
15861 if ( element.selectionStart !== undefined ) {
15862 element.selectionStart = element.selectionEnd = element.value.length;
15863 } else if ( element.createTextRange ) {
15864 // IE 8 and below
15865 textRange = element.createTextRange();
15866 textRange.collapse( false );
15867 textRange.select();
15868 }
15869 };
15870
15871 /**
15872 * Set the validation pattern.
15873 *
15874 * The validation pattern is either a regular expression, a function, or the symbolic name of a
15875 * pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer' (the
15876 * value must contain only numbers).
15877 *
15878 * @param {RegExp|Function|string|null} validate Regular expression, function, or the symbolic name
15879 * of a pattern (either ‘integer’ or ‘non-empty’) defined by the class.
15880 */
15881 OO.ui.TextInputWidget.prototype.setValidation = function ( validate ) {
15882 if ( validate instanceof RegExp || validate instanceof Function ) {
15883 this.validate = validate;
15884 } else {
15885 this.validate = this.constructor.static.validationPatterns[ validate ] || /.*/;
15886 }
15887 };
15888
15889 /**
15890 * Sets the 'invalid' flag appropriately.
15891 *
15892 * @param {boolean} [isValid] Optionally override validation result
15893 */
15894 OO.ui.TextInputWidget.prototype.setValidityFlag = function ( isValid ) {
15895 var widget = this,
15896 setFlag = function ( valid ) {
15897 if ( !valid ) {
15898 widget.$input.attr( 'aria-invalid', 'true' );
15899 } else {
15900 widget.$input.removeAttr( 'aria-invalid' );
15901 }
15902 widget.setFlags( { invalid: !valid } );
15903 };
15904
15905 if ( isValid !== undefined ) {
15906 setFlag( isValid );
15907 } else {
15908 this.getValidity().then( function () {
15909 setFlag( true );
15910 }, function () {
15911 setFlag( false );
15912 } );
15913 }
15914 };
15915
15916 /**
15917 * Check if a value is valid.
15918 *
15919 * This method returns a promise that resolves with a boolean `true` if the current value is
15920 * considered valid according to the supplied {@link #validate validation pattern}.
15921 *
15922 * @deprecated
15923 * @return {jQuery.Promise} A promise that resolves to a boolean `true` if the value is valid.
15924 */
15925 OO.ui.TextInputWidget.prototype.isValid = function () {
15926 var result;
15927
15928 if ( this.validate instanceof Function ) {
15929 result = this.validate( this.getValue() );
15930 if ( $.isFunction( result.promise ) ) {
15931 return result.promise();
15932 } else {
15933 return $.Deferred().resolve( !!result ).promise();
15934 }
15935 } else {
15936 return $.Deferred().resolve( !!this.getValue().match( this.validate ) ).promise();
15937 }
15938 };
15939
15940 /**
15941 * Get the validity of current value.
15942 *
15943 * This method returns a promise that resolves if the value is valid and rejects if
15944 * it isn't. Uses the {@link #validate validation pattern} to check for validity.
15945 *
15946 * @return {jQuery.Promise} A promise that resolves if the value is valid, rejects if not.
15947 */
15948 OO.ui.TextInputWidget.prototype.getValidity = function () {
15949 var result, promise;
15950
15951 function rejectOrResolve( valid ) {
15952 if ( valid ) {
15953 return $.Deferred().resolve().promise();
15954 } else {
15955 return $.Deferred().reject().promise();
15956 }
15957 }
15958
15959 if ( this.validate instanceof Function ) {
15960 result = this.validate( this.getValue() );
15961
15962 if ( $.isFunction( result.promise ) ) {
15963 promise = $.Deferred();
15964
15965 result.then( function ( valid ) {
15966 if ( valid ) {
15967 promise.resolve();
15968 } else {
15969 promise.reject();
15970 }
15971 }, function () {
15972 promise.reject();
15973 } );
15974
15975 return promise.promise();
15976 } else {
15977 return rejectOrResolve( result );
15978 }
15979 } else {
15980 return rejectOrResolve( this.getValue().match( this.validate ) );
15981 }
15982 };
15983
15984 /**
15985 * Set the position of the inline label relative to that of the value: `‘before’` or `‘after’`.
15986 *
15987 * @param {string} labelPosition Label position, 'before' or 'after'
15988 * @chainable
15989 */
15990 OO.ui.TextInputWidget.prototype.setLabelPosition = function ( labelPosition ) {
15991 this.labelPosition = labelPosition;
15992 this.updatePosition();
15993 return this;
15994 };
15995
15996 /**
15997 * Deprecated alias of #setLabelPosition
15998 *
15999 * @deprecated Use setLabelPosition instead.
16000 */
16001 OO.ui.TextInputWidget.prototype.setPosition =
16002 OO.ui.TextInputWidget.prototype.setLabelPosition;
16003
16004 /**
16005 * Update the position of the inline label.
16006 *
16007 * This method is called by #setLabelPosition, and can also be called on its own if
16008 * something causes the label to be mispositioned.
16009 *
16010 * @chainable
16011 */
16012 OO.ui.TextInputWidget.prototype.updatePosition = function () {
16013 var after = this.labelPosition === 'after';
16014
16015 this.$element
16016 .toggleClass( 'oo-ui-textInputWidget-labelPosition-after', !!this.label && after )
16017 .toggleClass( 'oo-ui-textInputWidget-labelPosition-before', !!this.label && !after );
16018
16019 this.positionLabel();
16020
16021 return this;
16022 };
16023
16024 /**
16025 * Update the 'clear' indicator displayed on type: 'search' text fields, hiding it when the field is
16026 * already empty or when it's not editable.
16027 */
16028 OO.ui.TextInputWidget.prototype.updateSearchIndicator = function () {
16029 if ( this.type === 'search' ) {
16030 if ( this.getValue() === '' || this.isDisabled() || this.isReadOnly() ) {
16031 this.setIndicator( null );
16032 } else {
16033 this.setIndicator( 'clear' );
16034 }
16035 }
16036 };
16037
16038 /**
16039 * Position the label by setting the correct padding on the input.
16040 *
16041 * @private
16042 * @chainable
16043 */
16044 OO.ui.TextInputWidget.prototype.positionLabel = function () {
16045 var after, rtl, property;
16046 // Clear old values
16047 this.$input
16048 // Clear old values if present
16049 .css( {
16050 'padding-right': '',
16051 'padding-left': ''
16052 } );
16053
16054 if ( this.label ) {
16055 this.$element.append( this.$label );
16056 } else {
16057 this.$label.detach();
16058 return;
16059 }
16060
16061 after = this.labelPosition === 'after';
16062 rtl = this.$element.css( 'direction' ) === 'rtl';
16063 property = after === rtl ? 'padding-left' : 'padding-right';
16064
16065 this.$input.css( property, this.$label.outerWidth( true ) );
16066
16067 return this;
16068 };
16069
16070 /**
16071 * @inheritdoc
16072 */
16073 OO.ui.TextInputWidget.prototype.gatherPreInfuseState = function ( node ) {
16074 var
16075 state = OO.ui.TextInputWidget.parent.prototype.gatherPreInfuseState.call( this, node ),
16076 $input = $( node ).find( '.oo-ui-inputWidget-input' );
16077 state.$input = $input; // shortcut for performance, used in InputWidget
16078 if ( this.multiline ) {
16079 state.scrollTop = $input.scrollTop();
16080 }
16081 return state;
16082 };
16083
16084 /**
16085 * @inheritdoc
16086 */
16087 OO.ui.TextInputWidget.prototype.restorePreInfuseState = function ( state ) {
16088 OO.ui.TextInputWidget.parent.prototype.restorePreInfuseState.call( this, state );
16089 if ( state.scrollTop !== undefined ) {
16090 this.$input.scrollTop( state.scrollTop );
16091 }
16092 };
16093
16094 /**
16095 * ComboBoxWidgets combine a {@link OO.ui.TextInputWidget text input} (where a value
16096 * can be entered manually) and a {@link OO.ui.MenuSelectWidget menu of options} (from which
16097 * a value can be chosen instead). Users can choose options from the combo box in one of two ways:
16098 *
16099 * - by typing a value in the text input field. If the value exactly matches the value of a menu
16100 * option, that option will appear to be selected.
16101 * - by choosing a value from the menu. The value of the chosen option will then appear in the text
16102 * input field.
16103 *
16104 * For more information about menus and options, please see the [OOjs UI documentation on MediaWiki][1].
16105 *
16106 * @example
16107 * // Example: A ComboBoxWidget.
16108 * var comboBox = new OO.ui.ComboBoxWidget( {
16109 * label: 'ComboBoxWidget',
16110 * input: { value: 'Option One' },
16111 * menu: {
16112 * items: [
16113 * new OO.ui.MenuOptionWidget( {
16114 * data: 'Option 1',
16115 * label: 'Option One'
16116 * } ),
16117 * new OO.ui.MenuOptionWidget( {
16118 * data: 'Option 2',
16119 * label: 'Option Two'
16120 * } ),
16121 * new OO.ui.MenuOptionWidget( {
16122 * data: 'Option 3',
16123 * label: 'Option Three'
16124 * } ),
16125 * new OO.ui.MenuOptionWidget( {
16126 * data: 'Option 4',
16127 * label: 'Option Four'
16128 * } ),
16129 * new OO.ui.MenuOptionWidget( {
16130 * data: 'Option 5',
16131 * label: 'Option Five'
16132 * } )
16133 * ]
16134 * }
16135 * } );
16136 * $( 'body' ).append( comboBox.$element );
16137 *
16138 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
16139 *
16140 * @class
16141 * @extends OO.ui.Widget
16142 * @mixins OO.ui.mixin.TabIndexedElement
16143 *
16144 * @constructor
16145 * @param {Object} [config] Configuration options
16146 * @cfg {Object} [menu] Configuration options to pass to the {@link OO.ui.FloatingMenuSelectWidget menu select widget}.
16147 * @cfg {Object} [input] Configuration options to pass to the {@link OO.ui.TextInputWidget text input widget}.
16148 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
16149 * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
16150 * containing `<div>` and has a larger area. By default, the menu uses relative positioning.
16151 */
16152 OO.ui.ComboBoxWidget = function OoUiComboBoxWidget( config ) {
16153 // Configuration initialization
16154 config = config || {};
16155
16156 // Parent constructor
16157 OO.ui.ComboBoxWidget.parent.call( this, config );
16158
16159 // Properties (must be set before TabIndexedElement constructor call)
16160 this.$indicator = this.$( '<span>' );
16161
16162 // Mixin constructors
16163 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$indicator } ) );
16164
16165 // Properties
16166 this.$overlay = config.$overlay || this.$element;
16167 this.input = new OO.ui.TextInputWidget( $.extend(
16168 {
16169 indicator: 'down',
16170 $indicator: this.$indicator,
16171 disabled: this.isDisabled()
16172 },
16173 config.input
16174 ) );
16175 this.input.$input.eq( 0 ).attr( {
16176 role: 'combobox',
16177 'aria-autocomplete': 'list'
16178 } );
16179 this.menu = new OO.ui.FloatingMenuSelectWidget( $.extend(
16180 {
16181 widget: this,
16182 input: this.input,
16183 $container: this.input.$element,
16184 disabled: this.isDisabled()
16185 },
16186 config.menu
16187 ) );
16188
16189 // Events
16190 this.$indicator.on( {
16191 click: this.onClick.bind( this ),
16192 keypress: this.onKeyPress.bind( this )
16193 } );
16194 this.input.connect( this, {
16195 change: 'onInputChange',
16196 enter: 'onInputEnter'
16197 } );
16198 this.menu.connect( this, {
16199 choose: 'onMenuChoose',
16200 add: 'onMenuItemsChange',
16201 remove: 'onMenuItemsChange'
16202 } );
16203
16204 // Initialization
16205 this.$element.addClass( 'oo-ui-comboBoxWidget' ).append( this.input.$element );
16206 this.$overlay.append( this.menu.$element );
16207 this.onMenuItemsChange();
16208 };
16209
16210 /* Setup */
16211
16212 OO.inheritClass( OO.ui.ComboBoxWidget, OO.ui.Widget );
16213 OO.mixinClass( OO.ui.ComboBoxWidget, OO.ui.mixin.TabIndexedElement );
16214
16215 /* Methods */
16216
16217 /**
16218 * Get the combobox's menu.
16219 * @return {OO.ui.FloatingMenuSelectWidget} Menu widget
16220 */
16221 OO.ui.ComboBoxWidget.prototype.getMenu = function () {
16222 return this.menu;
16223 };
16224
16225 /**
16226 * Get the combobox's text input widget.
16227 * @return {OO.ui.TextInputWidget} Text input widget
16228 */
16229 OO.ui.ComboBoxWidget.prototype.getInput = function () {
16230 return this.input;
16231 };
16232
16233 /**
16234 * Handle input change events.
16235 *
16236 * @private
16237 * @param {string} value New value
16238 */
16239 OO.ui.ComboBoxWidget.prototype.onInputChange = function ( value ) {
16240 var match = this.menu.getItemFromData( value );
16241
16242 this.menu.selectItem( match );
16243 if ( this.menu.getHighlightedItem() ) {
16244 this.menu.highlightItem( match );
16245 }
16246
16247 if ( !this.isDisabled() ) {
16248 this.menu.toggle( true );
16249 }
16250 };
16251
16252 /**
16253 * Handle mouse click events.
16254 *
16255 * @private
16256 * @param {jQuery.Event} e Mouse click event
16257 */
16258 OO.ui.ComboBoxWidget.prototype.onClick = function ( e ) {
16259 if ( !this.isDisabled() && e.which === 1 ) {
16260 this.menu.toggle();
16261 this.input.$input[ 0 ].focus();
16262 }
16263 return false;
16264 };
16265
16266 /**
16267 * Handle key press events.
16268 *
16269 * @private
16270 * @param {jQuery.Event} e Key press event
16271 */
16272 OO.ui.ComboBoxWidget.prototype.onKeyPress = function ( e ) {
16273 if ( !this.isDisabled() && ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER ) ) {
16274 this.menu.toggle();
16275 this.input.$input[ 0 ].focus();
16276 return false;
16277 }
16278 };
16279
16280 /**
16281 * Handle input enter events.
16282 *
16283 * @private
16284 */
16285 OO.ui.ComboBoxWidget.prototype.onInputEnter = function () {
16286 if ( !this.isDisabled() ) {
16287 this.menu.toggle( false );
16288 }
16289 };
16290
16291 /**
16292 * Handle menu choose events.
16293 *
16294 * @private
16295 * @param {OO.ui.OptionWidget} item Chosen item
16296 */
16297 OO.ui.ComboBoxWidget.prototype.onMenuChoose = function ( item ) {
16298 this.input.setValue( item.getData() );
16299 };
16300
16301 /**
16302 * Handle menu item change events.
16303 *
16304 * @private
16305 */
16306 OO.ui.ComboBoxWidget.prototype.onMenuItemsChange = function () {
16307 var match = this.menu.getItemFromData( this.input.getValue() );
16308 this.menu.selectItem( match );
16309 if ( this.menu.getHighlightedItem() ) {
16310 this.menu.highlightItem( match );
16311 }
16312 this.$element.toggleClass( 'oo-ui-comboBoxWidget-empty', this.menu.isEmpty() );
16313 };
16314
16315 /**
16316 * @inheritdoc
16317 */
16318 OO.ui.ComboBoxWidget.prototype.setDisabled = function ( disabled ) {
16319 // Parent method
16320 OO.ui.ComboBoxWidget.parent.prototype.setDisabled.call( this, disabled );
16321
16322 if ( this.input ) {
16323 this.input.setDisabled( this.isDisabled() );
16324 }
16325 if ( this.menu ) {
16326 this.menu.setDisabled( this.isDisabled() );
16327 }
16328
16329 return this;
16330 };
16331
16332 /**
16333 * LabelWidgets help identify the function of interface elements. Each LabelWidget can
16334 * be configured with a `label` option that is set to a string, a label node, or a function:
16335 *
16336 * - String: a plaintext string
16337 * - jQuery selection: a jQuery selection, used for anything other than a plaintext label, e.g., a
16338 * label that includes a link or special styling, such as a gray color or additional graphical elements.
16339 * - Function: a function that will produce a string in the future. Functions are used
16340 * in cases where the value of the label is not currently defined.
16341 *
16342 * In addition, the LabelWidget can be associated with an {@link OO.ui.InputWidget input widget}, which
16343 * will come into focus when the label is clicked.
16344 *
16345 * @example
16346 * // Examples of LabelWidgets
16347 * var label1 = new OO.ui.LabelWidget( {
16348 * label: 'plaintext label'
16349 * } );
16350 * var label2 = new OO.ui.LabelWidget( {
16351 * label: $( '<a href="default.html">jQuery label</a>' )
16352 * } );
16353 * // Create a fieldset layout with fields for each example
16354 * var fieldset = new OO.ui.FieldsetLayout();
16355 * fieldset.addItems( [
16356 * new OO.ui.FieldLayout( label1 ),
16357 * new OO.ui.FieldLayout( label2 )
16358 * ] );
16359 * $( 'body' ).append( fieldset.$element );
16360 *
16361 * @class
16362 * @extends OO.ui.Widget
16363 * @mixins OO.ui.mixin.LabelElement
16364 *
16365 * @constructor
16366 * @param {Object} [config] Configuration options
16367 * @cfg {OO.ui.InputWidget} [input] {@link OO.ui.InputWidget Input widget} that uses the label.
16368 * Clicking the label will focus the specified input field.
16369 */
16370 OO.ui.LabelWidget = function OoUiLabelWidget( config ) {
16371 // Configuration initialization
16372 config = config || {};
16373
16374 // Parent constructor
16375 OO.ui.LabelWidget.parent.call( this, config );
16376
16377 // Mixin constructors
16378 OO.ui.mixin.LabelElement.call( this, $.extend( {}, config, { $label: this.$element } ) );
16379 OO.ui.mixin.TitledElement.call( this, config );
16380
16381 // Properties
16382 this.input = config.input;
16383
16384 // Events
16385 if ( this.input instanceof OO.ui.InputWidget ) {
16386 this.$element.on( 'click', this.onClick.bind( this ) );
16387 }
16388
16389 // Initialization
16390 this.$element.addClass( 'oo-ui-labelWidget' );
16391 };
16392
16393 /* Setup */
16394
16395 OO.inheritClass( OO.ui.LabelWidget, OO.ui.Widget );
16396 OO.mixinClass( OO.ui.LabelWidget, OO.ui.mixin.LabelElement );
16397 OO.mixinClass( OO.ui.LabelWidget, OO.ui.mixin.TitledElement );
16398
16399 /* Static Properties */
16400
16401 OO.ui.LabelWidget.static.tagName = 'span';
16402
16403 /* Methods */
16404
16405 /**
16406 * Handles label mouse click events.
16407 *
16408 * @private
16409 * @param {jQuery.Event} e Mouse click event
16410 */
16411 OO.ui.LabelWidget.prototype.onClick = function () {
16412 this.input.simulateLabelClick();
16413 return false;
16414 };
16415
16416 /**
16417 * OptionWidgets are special elements that can be selected and configured with data. The
16418 * data is often unique for each option, but it does not have to be. OptionWidgets are used
16419 * with OO.ui.SelectWidget to create a selection of mutually exclusive options. For more information
16420 * and examples, please see the [OOjs UI documentation on MediaWiki][1].
16421 *
16422 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
16423 *
16424 * @class
16425 * @extends OO.ui.Widget
16426 * @mixins OO.ui.mixin.LabelElement
16427 * @mixins OO.ui.mixin.FlaggedElement
16428 *
16429 * @constructor
16430 * @param {Object} [config] Configuration options
16431 */
16432 OO.ui.OptionWidget = function OoUiOptionWidget( config ) {
16433 // Configuration initialization
16434 config = config || {};
16435
16436 // Parent constructor
16437 OO.ui.OptionWidget.parent.call( this, config );
16438
16439 // Mixin constructors
16440 OO.ui.mixin.ItemWidget.call( this );
16441 OO.ui.mixin.LabelElement.call( this, config );
16442 OO.ui.mixin.FlaggedElement.call( this, config );
16443
16444 // Properties
16445 this.selected = false;
16446 this.highlighted = false;
16447 this.pressed = false;
16448
16449 // Initialization
16450 this.$element
16451 .data( 'oo-ui-optionWidget', this )
16452 .attr( 'role', 'option' )
16453 .attr( 'aria-selected', 'false' )
16454 .addClass( 'oo-ui-optionWidget' )
16455 .append( this.$label );
16456 };
16457
16458 /* Setup */
16459
16460 OO.inheritClass( OO.ui.OptionWidget, OO.ui.Widget );
16461 OO.mixinClass( OO.ui.OptionWidget, OO.ui.mixin.ItemWidget );
16462 OO.mixinClass( OO.ui.OptionWidget, OO.ui.mixin.LabelElement );
16463 OO.mixinClass( OO.ui.OptionWidget, OO.ui.mixin.FlaggedElement );
16464
16465 /* Static Properties */
16466
16467 OO.ui.OptionWidget.static.selectable = true;
16468
16469 OO.ui.OptionWidget.static.highlightable = true;
16470
16471 OO.ui.OptionWidget.static.pressable = true;
16472
16473 OO.ui.OptionWidget.static.scrollIntoViewOnSelect = false;
16474
16475 /* Methods */
16476
16477 /**
16478 * Check if the option can be selected.
16479 *
16480 * @return {boolean} Item is selectable
16481 */
16482 OO.ui.OptionWidget.prototype.isSelectable = function () {
16483 return this.constructor.static.selectable && !this.isDisabled() && this.isVisible();
16484 };
16485
16486 /**
16487 * Check if the option can be highlighted. A highlight indicates that the option
16488 * may be selected when a user presses enter or clicks. Disabled items cannot
16489 * be highlighted.
16490 *
16491 * @return {boolean} Item is highlightable
16492 */
16493 OO.ui.OptionWidget.prototype.isHighlightable = function () {
16494 return this.constructor.static.highlightable && !this.isDisabled() && this.isVisible();
16495 };
16496
16497 /**
16498 * Check if the option can be pressed. The pressed state occurs when a user mouses
16499 * down on an item, but has not yet let go of the mouse.
16500 *
16501 * @return {boolean} Item is pressable
16502 */
16503 OO.ui.OptionWidget.prototype.isPressable = function () {
16504 return this.constructor.static.pressable && !this.isDisabled() && this.isVisible();
16505 };
16506
16507 /**
16508 * Check if the option is selected.
16509 *
16510 * @return {boolean} Item is selected
16511 */
16512 OO.ui.OptionWidget.prototype.isSelected = function () {
16513 return this.selected;
16514 };
16515
16516 /**
16517 * Check if the option is highlighted. A highlight indicates that the
16518 * item may be selected when a user presses enter or clicks.
16519 *
16520 * @return {boolean} Item is highlighted
16521 */
16522 OO.ui.OptionWidget.prototype.isHighlighted = function () {
16523 return this.highlighted;
16524 };
16525
16526 /**
16527 * Check if the option is pressed. The pressed state occurs when a user mouses
16528 * down on an item, but has not yet let go of the mouse. The item may appear
16529 * selected, but it will not be selected until the user releases the mouse.
16530 *
16531 * @return {boolean} Item is pressed
16532 */
16533 OO.ui.OptionWidget.prototype.isPressed = function () {
16534 return this.pressed;
16535 };
16536
16537 /**
16538 * Set the option’s selected state. In general, all modifications to the selection
16539 * should be handled by the SelectWidget’s {@link OO.ui.SelectWidget#selectItem selectItem( [item] )}
16540 * method instead of this method.
16541 *
16542 * @param {boolean} [state=false] Select option
16543 * @chainable
16544 */
16545 OO.ui.OptionWidget.prototype.setSelected = function ( state ) {
16546 if ( this.constructor.static.selectable ) {
16547 this.selected = !!state;
16548 this.$element
16549 .toggleClass( 'oo-ui-optionWidget-selected', state )
16550 .attr( 'aria-selected', state.toString() );
16551 if ( state && this.constructor.static.scrollIntoViewOnSelect ) {
16552 this.scrollElementIntoView();
16553 }
16554 this.updateThemeClasses();
16555 }
16556 return this;
16557 };
16558
16559 /**
16560 * Set the option’s highlighted state. In general, all programmatic
16561 * modifications to the highlight should be handled by the
16562 * SelectWidget’s {@link OO.ui.SelectWidget#highlightItem highlightItem( [item] )}
16563 * method instead of this method.
16564 *
16565 * @param {boolean} [state=false] Highlight option
16566 * @chainable
16567 */
16568 OO.ui.OptionWidget.prototype.setHighlighted = function ( state ) {
16569 if ( this.constructor.static.highlightable ) {
16570 this.highlighted = !!state;
16571 this.$element.toggleClass( 'oo-ui-optionWidget-highlighted', state );
16572 this.updateThemeClasses();
16573 }
16574 return this;
16575 };
16576
16577 /**
16578 * Set the option’s pressed state. In general, all
16579 * programmatic modifications to the pressed state should be handled by the
16580 * SelectWidget’s {@link OO.ui.SelectWidget#pressItem pressItem( [item] )}
16581 * method instead of this method.
16582 *
16583 * @param {boolean} [state=false] Press option
16584 * @chainable
16585 */
16586 OO.ui.OptionWidget.prototype.setPressed = function ( state ) {
16587 if ( this.constructor.static.pressable ) {
16588 this.pressed = !!state;
16589 this.$element.toggleClass( 'oo-ui-optionWidget-pressed', state );
16590 this.updateThemeClasses();
16591 }
16592 return this;
16593 };
16594
16595 /**
16596 * DecoratedOptionWidgets are {@link OO.ui.OptionWidget options} that can be configured
16597 * with an {@link OO.ui.mixin.IconElement icon} and/or {@link OO.ui.mixin.IndicatorElement indicator}.
16598 * This class is used with OO.ui.SelectWidget to create a selection of mutually exclusive
16599 * options. For more information about options and selects, please see the
16600 * [OOjs UI documentation on MediaWiki][1].
16601 *
16602 * @example
16603 * // Decorated options in a select widget
16604 * var select = new OO.ui.SelectWidget( {
16605 * items: [
16606 * new OO.ui.DecoratedOptionWidget( {
16607 * data: 'a',
16608 * label: 'Option with icon',
16609 * icon: 'help'
16610 * } ),
16611 * new OO.ui.DecoratedOptionWidget( {
16612 * data: 'b',
16613 * label: 'Option with indicator',
16614 * indicator: 'next'
16615 * } )
16616 * ]
16617 * } );
16618 * $( 'body' ).append( select.$element );
16619 *
16620 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
16621 *
16622 * @class
16623 * @extends OO.ui.OptionWidget
16624 * @mixins OO.ui.mixin.IconElement
16625 * @mixins OO.ui.mixin.IndicatorElement
16626 *
16627 * @constructor
16628 * @param {Object} [config] Configuration options
16629 */
16630 OO.ui.DecoratedOptionWidget = function OoUiDecoratedOptionWidget( config ) {
16631 // Parent constructor
16632 OO.ui.DecoratedOptionWidget.parent.call( this, config );
16633
16634 // Mixin constructors
16635 OO.ui.mixin.IconElement.call( this, config );
16636 OO.ui.mixin.IndicatorElement.call( this, config );
16637
16638 // Initialization
16639 this.$element
16640 .addClass( 'oo-ui-decoratedOptionWidget' )
16641 .prepend( this.$icon )
16642 .append( this.$indicator );
16643 };
16644
16645 /* Setup */
16646
16647 OO.inheritClass( OO.ui.DecoratedOptionWidget, OO.ui.OptionWidget );
16648 OO.mixinClass( OO.ui.DecoratedOptionWidget, OO.ui.mixin.IconElement );
16649 OO.mixinClass( OO.ui.DecoratedOptionWidget, OO.ui.mixin.IndicatorElement );
16650
16651 /**
16652 * ButtonOptionWidget is a special type of {@link OO.ui.mixin.ButtonElement button element} that
16653 * can be selected and configured with data. The class is
16654 * used with OO.ui.ButtonSelectWidget to create a selection of button options. Please see the
16655 * [OOjs UI documentation on MediaWiki] [1] for more information.
16656 *
16657 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Button_selects_and_options
16658 *
16659 * @class
16660 * @extends OO.ui.DecoratedOptionWidget
16661 * @mixins OO.ui.mixin.ButtonElement
16662 * @mixins OO.ui.mixin.TabIndexedElement
16663 * @mixins OO.ui.mixin.TitledElement
16664 *
16665 * @constructor
16666 * @param {Object} [config] Configuration options
16667 */
16668 OO.ui.ButtonOptionWidget = function OoUiButtonOptionWidget( config ) {
16669 // Configuration initialization
16670 config = config || {};
16671
16672 // Parent constructor
16673 OO.ui.ButtonOptionWidget.parent.call( this, config );
16674
16675 // Mixin constructors
16676 OO.ui.mixin.ButtonElement.call( this, config );
16677 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$button } ) );
16678 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, {
16679 $tabIndexed: this.$button,
16680 tabIndex: -1
16681 } ) );
16682
16683 // Initialization
16684 this.$element.addClass( 'oo-ui-buttonOptionWidget' );
16685 this.$button.append( this.$element.contents() );
16686 this.$element.append( this.$button );
16687 };
16688
16689 /* Setup */
16690
16691 OO.inheritClass( OO.ui.ButtonOptionWidget, OO.ui.DecoratedOptionWidget );
16692 OO.mixinClass( OO.ui.ButtonOptionWidget, OO.ui.mixin.ButtonElement );
16693 OO.mixinClass( OO.ui.ButtonOptionWidget, OO.ui.mixin.TitledElement );
16694 OO.mixinClass( OO.ui.ButtonOptionWidget, OO.ui.mixin.TabIndexedElement );
16695
16696 /* Static Properties */
16697
16698 // Allow button mouse down events to pass through so they can be handled by the parent select widget
16699 OO.ui.ButtonOptionWidget.static.cancelButtonMouseDownEvents = false;
16700
16701 OO.ui.ButtonOptionWidget.static.highlightable = false;
16702
16703 /* Methods */
16704
16705 /**
16706 * @inheritdoc
16707 */
16708 OO.ui.ButtonOptionWidget.prototype.setSelected = function ( state ) {
16709 OO.ui.ButtonOptionWidget.parent.prototype.setSelected.call( this, state );
16710
16711 if ( this.constructor.static.selectable ) {
16712 this.setActive( state );
16713 }
16714
16715 return this;
16716 };
16717
16718 /**
16719 * RadioOptionWidget is an option widget that looks like a radio button.
16720 * The class is used with OO.ui.RadioSelectWidget to create a selection of radio options.
16721 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information.
16722 *
16723 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Button_selects_and_option
16724 *
16725 * @class
16726 * @extends OO.ui.OptionWidget
16727 *
16728 * @constructor
16729 * @param {Object} [config] Configuration options
16730 */
16731 OO.ui.RadioOptionWidget = function OoUiRadioOptionWidget( config ) {
16732 // Configuration initialization
16733 config = config || {};
16734
16735 // Properties (must be done before parent constructor which calls #setDisabled)
16736 this.radio = new OO.ui.RadioInputWidget( { value: config.data, tabIndex: -1 } );
16737
16738 // Parent constructor
16739 OO.ui.RadioOptionWidget.parent.call( this, config );
16740
16741 // Events
16742 this.radio.$input.on( 'focus', this.onInputFocus.bind( this ) );
16743
16744 // Initialization
16745 // Remove implicit role, we're handling it ourselves
16746 this.radio.$input.attr( 'role', 'presentation' );
16747 this.$element
16748 .addClass( 'oo-ui-radioOptionWidget' )
16749 .attr( 'role', 'radio' )
16750 .attr( 'aria-checked', 'false' )
16751 .removeAttr( 'aria-selected' )
16752 .prepend( this.radio.$element );
16753 };
16754
16755 /* Setup */
16756
16757 OO.inheritClass( OO.ui.RadioOptionWidget, OO.ui.OptionWidget );
16758
16759 /* Static Properties */
16760
16761 OO.ui.RadioOptionWidget.static.highlightable = false;
16762
16763 OO.ui.RadioOptionWidget.static.scrollIntoViewOnSelect = true;
16764
16765 OO.ui.RadioOptionWidget.static.pressable = false;
16766
16767 OO.ui.RadioOptionWidget.static.tagName = 'label';
16768
16769 /* Methods */
16770
16771 /**
16772 * @param {jQuery.Event} e Focus event
16773 * @private
16774 */
16775 OO.ui.RadioOptionWidget.prototype.onInputFocus = function () {
16776 this.radio.$input.blur();
16777 this.$element.parent().focus();
16778 };
16779
16780 /**
16781 * @inheritdoc
16782 */
16783 OO.ui.RadioOptionWidget.prototype.setSelected = function ( state ) {
16784 OO.ui.RadioOptionWidget.parent.prototype.setSelected.call( this, state );
16785
16786 this.radio.setSelected( state );
16787 this.$element
16788 .attr( 'aria-checked', state.toString() )
16789 .removeAttr( 'aria-selected' );
16790
16791 return this;
16792 };
16793
16794 /**
16795 * @inheritdoc
16796 */
16797 OO.ui.RadioOptionWidget.prototype.setDisabled = function ( disabled ) {
16798 OO.ui.RadioOptionWidget.parent.prototype.setDisabled.call( this, disabled );
16799
16800 this.radio.setDisabled( this.isDisabled() );
16801
16802 return this;
16803 };
16804
16805 /**
16806 * MenuOptionWidget is an option widget that looks like a menu item. The class is used with
16807 * OO.ui.MenuSelectWidget to create a menu of mutually exclusive options. Please see
16808 * the [OOjs UI documentation on MediaWiki] [1] for more information.
16809 *
16810 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
16811 *
16812 * @class
16813 * @extends OO.ui.DecoratedOptionWidget
16814 *
16815 * @constructor
16816 * @param {Object} [config] Configuration options
16817 */
16818 OO.ui.MenuOptionWidget = function OoUiMenuOptionWidget( config ) {
16819 // Configuration initialization
16820 config = $.extend( { icon: 'check' }, config );
16821
16822 // Parent constructor
16823 OO.ui.MenuOptionWidget.parent.call( this, config );
16824
16825 // Initialization
16826 this.$element
16827 .attr( 'role', 'menuitem' )
16828 .addClass( 'oo-ui-menuOptionWidget' );
16829 };
16830
16831 /* Setup */
16832
16833 OO.inheritClass( OO.ui.MenuOptionWidget, OO.ui.DecoratedOptionWidget );
16834
16835 /* Static Properties */
16836
16837 OO.ui.MenuOptionWidget.static.scrollIntoViewOnSelect = true;
16838
16839 /**
16840 * MenuSectionOptionWidgets are used inside {@link OO.ui.MenuSelectWidget menu select widgets} to group one or more related
16841 * {@link OO.ui.MenuOptionWidget menu options}. MenuSectionOptionWidgets cannot be highlighted or selected.
16842 *
16843 * @example
16844 * var myDropdown = new OO.ui.DropdownWidget( {
16845 * menu: {
16846 * items: [
16847 * new OO.ui.MenuSectionOptionWidget( {
16848 * label: 'Dogs'
16849 * } ),
16850 * new OO.ui.MenuOptionWidget( {
16851 * data: 'corgi',
16852 * label: 'Welsh Corgi'
16853 * } ),
16854 * new OO.ui.MenuOptionWidget( {
16855 * data: 'poodle',
16856 * label: 'Standard Poodle'
16857 * } ),
16858 * new OO.ui.MenuSectionOptionWidget( {
16859 * label: 'Cats'
16860 * } ),
16861 * new OO.ui.MenuOptionWidget( {
16862 * data: 'lion',
16863 * label: 'Lion'
16864 * } )
16865 * ]
16866 * }
16867 * } );
16868 * $( 'body' ).append( myDropdown.$element );
16869 *
16870 * @class
16871 * @extends OO.ui.DecoratedOptionWidget
16872 *
16873 * @constructor
16874 * @param {Object} [config] Configuration options
16875 */
16876 OO.ui.MenuSectionOptionWidget = function OoUiMenuSectionOptionWidget( config ) {
16877 // Parent constructor
16878 OO.ui.MenuSectionOptionWidget.parent.call( this, config );
16879
16880 // Initialization
16881 this.$element.addClass( 'oo-ui-menuSectionOptionWidget' );
16882 };
16883
16884 /* Setup */
16885
16886 OO.inheritClass( OO.ui.MenuSectionOptionWidget, OO.ui.DecoratedOptionWidget );
16887
16888 /* Static Properties */
16889
16890 OO.ui.MenuSectionOptionWidget.static.selectable = false;
16891
16892 OO.ui.MenuSectionOptionWidget.static.highlightable = false;
16893
16894 /**
16895 * OutlineOptionWidget is an item in an {@link OO.ui.OutlineSelectWidget OutlineSelectWidget}.
16896 *
16897 * Currently, this class is only used by {@link OO.ui.BookletLayout booklet layouts}, which contain
16898 * {@link OO.ui.PageLayout page layouts}. See {@link OO.ui.BookletLayout BookletLayout}
16899 * for an example.
16900 *
16901 * @class
16902 * @extends OO.ui.DecoratedOptionWidget
16903 *
16904 * @constructor
16905 * @param {Object} [config] Configuration options
16906 * @cfg {number} [level] Indentation level
16907 * @cfg {boolean} [movable] Allow modification from {@link OO.ui.OutlineControlsWidget outline controls}.
16908 */
16909 OO.ui.OutlineOptionWidget = function OoUiOutlineOptionWidget( config ) {
16910 // Configuration initialization
16911 config = config || {};
16912
16913 // Parent constructor
16914 OO.ui.OutlineOptionWidget.parent.call( this, config );
16915
16916 // Properties
16917 this.level = 0;
16918 this.movable = !!config.movable;
16919 this.removable = !!config.removable;
16920
16921 // Initialization
16922 this.$element.addClass( 'oo-ui-outlineOptionWidget' );
16923 this.setLevel( config.level );
16924 };
16925
16926 /* Setup */
16927
16928 OO.inheritClass( OO.ui.OutlineOptionWidget, OO.ui.DecoratedOptionWidget );
16929
16930 /* Static Properties */
16931
16932 OO.ui.OutlineOptionWidget.static.highlightable = false;
16933
16934 OO.ui.OutlineOptionWidget.static.scrollIntoViewOnSelect = true;
16935
16936 OO.ui.OutlineOptionWidget.static.levelClass = 'oo-ui-outlineOptionWidget-level-';
16937
16938 OO.ui.OutlineOptionWidget.static.levels = 3;
16939
16940 /* Methods */
16941
16942 /**
16943 * Check if item is movable.
16944 *
16945 * Movability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
16946 *
16947 * @return {boolean} Item is movable
16948 */
16949 OO.ui.OutlineOptionWidget.prototype.isMovable = function () {
16950 return this.movable;
16951 };
16952
16953 /**
16954 * Check if item is removable.
16955 *
16956 * Removability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
16957 *
16958 * @return {boolean} Item is removable
16959 */
16960 OO.ui.OutlineOptionWidget.prototype.isRemovable = function () {
16961 return this.removable;
16962 };
16963
16964 /**
16965 * Get indentation level.
16966 *
16967 * @return {number} Indentation level
16968 */
16969 OO.ui.OutlineOptionWidget.prototype.getLevel = function () {
16970 return this.level;
16971 };
16972
16973 /**
16974 * Set movability.
16975 *
16976 * Movability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
16977 *
16978 * @param {boolean} movable Item is movable
16979 * @chainable
16980 */
16981 OO.ui.OutlineOptionWidget.prototype.setMovable = function ( movable ) {
16982 this.movable = !!movable;
16983 this.updateThemeClasses();
16984 return this;
16985 };
16986
16987 /**
16988 * Set removability.
16989 *
16990 * Removability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
16991 *
16992 * @param {boolean} movable Item is removable
16993 * @chainable
16994 */
16995 OO.ui.OutlineOptionWidget.prototype.setRemovable = function ( removable ) {
16996 this.removable = !!removable;
16997 this.updateThemeClasses();
16998 return this;
16999 };
17000
17001 /**
17002 * Set indentation level.
17003 *
17004 * @param {number} [level=0] Indentation level, in the range of [0,#maxLevel]
17005 * @chainable
17006 */
17007 OO.ui.OutlineOptionWidget.prototype.setLevel = function ( level ) {
17008 var levels = this.constructor.static.levels,
17009 levelClass = this.constructor.static.levelClass,
17010 i = levels;
17011
17012 this.level = level ? Math.max( 0, Math.min( levels - 1, level ) ) : 0;
17013 while ( i-- ) {
17014 if ( this.level === i ) {
17015 this.$element.addClass( levelClass + i );
17016 } else {
17017 this.$element.removeClass( levelClass + i );
17018 }
17019 }
17020 this.updateThemeClasses();
17021
17022 return this;
17023 };
17024
17025 /**
17026 * TabOptionWidget is an item in a {@link OO.ui.TabSelectWidget TabSelectWidget}.
17027 *
17028 * Currently, this class is only used by {@link OO.ui.IndexLayout index layouts}, which contain
17029 * {@link OO.ui.CardLayout card layouts}. See {@link OO.ui.IndexLayout IndexLayout}
17030 * for an example.
17031 *
17032 * @class
17033 * @extends OO.ui.OptionWidget
17034 *
17035 * @constructor
17036 * @param {Object} [config] Configuration options
17037 */
17038 OO.ui.TabOptionWidget = function OoUiTabOptionWidget( config ) {
17039 // Configuration initialization
17040 config = config || {};
17041
17042 // Parent constructor
17043 OO.ui.TabOptionWidget.parent.call( this, config );
17044
17045 // Initialization
17046 this.$element.addClass( 'oo-ui-tabOptionWidget' );
17047 };
17048
17049 /* Setup */
17050
17051 OO.inheritClass( OO.ui.TabOptionWidget, OO.ui.OptionWidget );
17052
17053 /* Static Properties */
17054
17055 OO.ui.TabOptionWidget.static.highlightable = false;
17056
17057 /**
17058 * PopupWidget is a container for content. The popup is overlaid and positioned absolutely.
17059 * By default, each popup has an anchor that points toward its origin.
17060 * Please see the [OOjs UI documentation on Mediawiki] [1] for more information and examples.
17061 *
17062 * @example
17063 * // A popup widget.
17064 * var popup = new OO.ui.PopupWidget( {
17065 * $content: $( '<p>Hi there!</p>' ),
17066 * padded: true,
17067 * width: 300
17068 * } );
17069 *
17070 * $( 'body' ).append( popup.$element );
17071 * // To display the popup, toggle the visibility to 'true'.
17072 * popup.toggle( true );
17073 *
17074 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups
17075 *
17076 * @class
17077 * @extends OO.ui.Widget
17078 * @mixins OO.ui.mixin.LabelElement
17079 * @mixins OO.ui.mixin.ClippableElement
17080 *
17081 * @constructor
17082 * @param {Object} [config] Configuration options
17083 * @cfg {number} [width=320] Width of popup in pixels
17084 * @cfg {number} [height] Height of popup in pixels. Omit to use the automatic height.
17085 * @cfg {boolean} [anchor=true] Show anchor pointing to origin of popup
17086 * @cfg {string} [align='center'] Alignment of the popup: `center`, `force-left`, `force-right`, `backwards` or `forwards`.
17087 * If the popup is forced-left the popup body is leaning towards the left. For force-right alignment, the body of the
17088 * popup is leaning towards the right of the screen.
17089 * Using 'backwards' is a logical direction which will result in the popup leaning towards the beginning of the sentence
17090 * in the given language, which means it will flip to the correct positioning in right-to-left languages.
17091 * Using 'forward' will also result in a logical alignment where the body of the popup leans towards the end of the
17092 * sentence in the given language.
17093 * @cfg {jQuery} [$container] Constrain the popup to the boundaries of the specified container.
17094 * See the [OOjs UI docs on MediaWiki][3] for an example.
17095 * [3]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups#containerExample
17096 * @cfg {number} [containerPadding=10] Padding between the popup and its container, specified as a number of pixels.
17097 * @cfg {jQuery} [$content] Content to append to the popup's body
17098 * @cfg {jQuery} [$footer] Content to append to the popup's footer
17099 * @cfg {boolean} [autoClose=false] Automatically close the popup when it loses focus.
17100 * @cfg {jQuery} [$autoCloseIgnore] Elements that will not close the popup when clicked.
17101 * This config option is only relevant if #autoClose is set to `true`. See the [OOjs UI docs on MediaWiki][2]
17102 * for an example.
17103 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups#autocloseExample
17104 * @cfg {boolean} [head] Show a popup header that contains a #label (if specified) and close
17105 * button.
17106 * @cfg {boolean} [padded] Add padding to the popup's body
17107 */
17108 OO.ui.PopupWidget = function OoUiPopupWidget( config ) {
17109 // Configuration initialization
17110 config = config || {};
17111
17112 // Parent constructor
17113 OO.ui.PopupWidget.parent.call( this, config );
17114
17115 // Properties (must be set before ClippableElement constructor call)
17116 this.$body = $( '<div>' );
17117 this.$popup = $( '<div>' );
17118
17119 // Mixin constructors
17120 OO.ui.mixin.LabelElement.call( this, config );
17121 OO.ui.mixin.ClippableElement.call( this, $.extend( {}, config, {
17122 $clippable: this.$body,
17123 $clippableContainer: this.$popup
17124 } ) );
17125
17126 // Properties
17127 this.$head = $( '<div>' );
17128 this.$footer = $( '<div>' );
17129 this.$anchor = $( '<div>' );
17130 // If undefined, will be computed lazily in updateDimensions()
17131 this.$container = config.$container;
17132 this.containerPadding = config.containerPadding !== undefined ? config.containerPadding : 10;
17133 this.autoClose = !!config.autoClose;
17134 this.$autoCloseIgnore = config.$autoCloseIgnore;
17135 this.transitionTimeout = null;
17136 this.anchor = null;
17137 this.width = config.width !== undefined ? config.width : 320;
17138 this.height = config.height !== undefined ? config.height : null;
17139 this.setAlignment( config.align );
17140 this.closeButton = new OO.ui.ButtonWidget( { framed: false, icon: 'close' } );
17141 this.onMouseDownHandler = this.onMouseDown.bind( this );
17142 this.onDocumentKeyDownHandler = this.onDocumentKeyDown.bind( this );
17143
17144 // Events
17145 this.closeButton.connect( this, { click: 'onCloseButtonClick' } );
17146
17147 // Initialization
17148 this.toggleAnchor( config.anchor === undefined || config.anchor );
17149 this.$body.addClass( 'oo-ui-popupWidget-body' );
17150 this.$anchor.addClass( 'oo-ui-popupWidget-anchor' );
17151 this.$head
17152 .addClass( 'oo-ui-popupWidget-head' )
17153 .append( this.$label, this.closeButton.$element );
17154 this.$footer.addClass( 'oo-ui-popupWidget-footer' );
17155 if ( !config.head ) {
17156 this.$head.addClass( 'oo-ui-element-hidden' );
17157 }
17158 if ( !config.$footer ) {
17159 this.$footer.addClass( 'oo-ui-element-hidden' );
17160 }
17161 this.$popup
17162 .addClass( 'oo-ui-popupWidget-popup' )
17163 .append( this.$head, this.$body, this.$footer );
17164 this.$element
17165 .addClass( 'oo-ui-popupWidget' )
17166 .append( this.$popup, this.$anchor );
17167 // Move content, which was added to #$element by OO.ui.Widget, to the body
17168 if ( config.$content instanceof jQuery ) {
17169 this.$body.append( config.$content );
17170 }
17171 if ( config.$footer instanceof jQuery ) {
17172 this.$footer.append( config.$footer );
17173 }
17174 if ( config.padded ) {
17175 this.$body.addClass( 'oo-ui-popupWidget-body-padded' );
17176 }
17177
17178 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
17179 // that reference properties not initialized at that time of parent class construction
17180 // TODO: Find a better way to handle post-constructor setup
17181 this.visible = false;
17182 this.$element.addClass( 'oo-ui-element-hidden' );
17183 };
17184
17185 /* Setup */
17186
17187 OO.inheritClass( OO.ui.PopupWidget, OO.ui.Widget );
17188 OO.mixinClass( OO.ui.PopupWidget, OO.ui.mixin.LabelElement );
17189 OO.mixinClass( OO.ui.PopupWidget, OO.ui.mixin.ClippableElement );
17190
17191 /* Methods */
17192
17193 /**
17194 * Handles mouse down events.
17195 *
17196 * @private
17197 * @param {MouseEvent} e Mouse down event
17198 */
17199 OO.ui.PopupWidget.prototype.onMouseDown = function ( e ) {
17200 if (
17201 this.isVisible() &&
17202 !$.contains( this.$element[ 0 ], e.target ) &&
17203 ( !this.$autoCloseIgnore || !this.$autoCloseIgnore.has( e.target ).length )
17204 ) {
17205 this.toggle( false );
17206 }
17207 };
17208
17209 /**
17210 * Bind mouse down listener.
17211 *
17212 * @private
17213 */
17214 OO.ui.PopupWidget.prototype.bindMouseDownListener = function () {
17215 // Capture clicks outside popup
17216 OO.ui.addCaptureEventListener( this.getElementWindow(), 'mousedown', this.onMouseDownHandler );
17217 };
17218
17219 /**
17220 * Handles close button click events.
17221 *
17222 * @private
17223 */
17224 OO.ui.PopupWidget.prototype.onCloseButtonClick = function () {
17225 if ( this.isVisible() ) {
17226 this.toggle( false );
17227 }
17228 };
17229
17230 /**
17231 * Unbind mouse down listener.
17232 *
17233 * @private
17234 */
17235 OO.ui.PopupWidget.prototype.unbindMouseDownListener = function () {
17236 OO.ui.removeCaptureEventListener( this.getElementWindow(), 'mousedown', this.onMouseDownHandler );
17237 };
17238
17239 /**
17240 * Handles key down events.
17241 *
17242 * @private
17243 * @param {KeyboardEvent} e Key down event
17244 */
17245 OO.ui.PopupWidget.prototype.onDocumentKeyDown = function ( e ) {
17246 if (
17247 e.which === OO.ui.Keys.ESCAPE &&
17248 this.isVisible()
17249 ) {
17250 this.toggle( false );
17251 e.preventDefault();
17252 e.stopPropagation();
17253 }
17254 };
17255
17256 /**
17257 * Bind key down listener.
17258 *
17259 * @private
17260 */
17261 OO.ui.PopupWidget.prototype.bindKeyDownListener = function () {
17262 OO.ui.addCaptureEventListener( this.getElementWindow(), 'keydown', this.onDocumentKeyDownHandler );
17263 };
17264
17265 /**
17266 * Unbind key down listener.
17267 *
17268 * @private
17269 */
17270 OO.ui.PopupWidget.prototype.unbindKeyDownListener = function () {
17271 OO.ui.removeCaptureEventListener( this.getElementWindow(), 'keydown', this.onDocumentKeyDownHandler );
17272 };
17273
17274 /**
17275 * Show, hide, or toggle the visibility of the anchor.
17276 *
17277 * @param {boolean} [show] Show anchor, omit to toggle
17278 */
17279 OO.ui.PopupWidget.prototype.toggleAnchor = function ( show ) {
17280 show = show === undefined ? !this.anchored : !!show;
17281
17282 if ( this.anchored !== show ) {
17283 if ( show ) {
17284 this.$element.addClass( 'oo-ui-popupWidget-anchored' );
17285 } else {
17286 this.$element.removeClass( 'oo-ui-popupWidget-anchored' );
17287 }
17288 this.anchored = show;
17289 }
17290 };
17291
17292 /**
17293 * Check if the anchor is visible.
17294 *
17295 * @return {boolean} Anchor is visible
17296 */
17297 OO.ui.PopupWidget.prototype.hasAnchor = function () {
17298 return this.anchor;
17299 };
17300
17301 /**
17302 * @inheritdoc
17303 */
17304 OO.ui.PopupWidget.prototype.toggle = function ( show ) {
17305 var change;
17306 show = show === undefined ? !this.isVisible() : !!show;
17307
17308 change = show !== this.isVisible();
17309
17310 // Parent method
17311 OO.ui.PopupWidget.parent.prototype.toggle.call( this, show );
17312
17313 if ( change ) {
17314 if ( show ) {
17315 if ( this.autoClose ) {
17316 this.bindMouseDownListener();
17317 this.bindKeyDownListener();
17318 }
17319 this.updateDimensions();
17320 this.toggleClipping( true );
17321 } else {
17322 this.toggleClipping( false );
17323 if ( this.autoClose ) {
17324 this.unbindMouseDownListener();
17325 this.unbindKeyDownListener();
17326 }
17327 }
17328 }
17329
17330 return this;
17331 };
17332
17333 /**
17334 * Set the size of the popup.
17335 *
17336 * Changing the size may also change the popup's position depending on the alignment.
17337 *
17338 * @param {number} width Width in pixels
17339 * @param {number} height Height in pixels
17340 * @param {boolean} [transition=false] Use a smooth transition
17341 * @chainable
17342 */
17343 OO.ui.PopupWidget.prototype.setSize = function ( width, height, transition ) {
17344 this.width = width;
17345 this.height = height !== undefined ? height : null;
17346 if ( this.isVisible() ) {
17347 this.updateDimensions( transition );
17348 }
17349 };
17350
17351 /**
17352 * Update the size and position.
17353 *
17354 * Only use this to keep the popup properly anchored. Use #setSize to change the size, and this will
17355 * be called automatically.
17356 *
17357 * @param {boolean} [transition=false] Use a smooth transition
17358 * @chainable
17359 */
17360 OO.ui.PopupWidget.prototype.updateDimensions = function ( transition ) {
17361 var popupOffset, originOffset, containerLeft, containerWidth, containerRight,
17362 popupLeft, popupRight, overlapLeft, overlapRight, anchorWidth,
17363 align = this.align,
17364 widget = this;
17365
17366 if ( !this.$container ) {
17367 // Lazy-initialize $container if not specified in constructor
17368 this.$container = $( this.getClosestScrollableElementContainer() );
17369 }
17370
17371 // Set height and width before measuring things, since it might cause our measurements
17372 // to change (e.g. due to scrollbars appearing or disappearing)
17373 this.$popup.css( {
17374 width: this.width,
17375 height: this.height !== null ? this.height : 'auto'
17376 } );
17377
17378 // If we are in RTL, we need to flip the alignment, unless it is center
17379 if ( align === 'forwards' || align === 'backwards' ) {
17380 if ( this.$container.css( 'direction' ) === 'rtl' ) {
17381 align = ( { forwards: 'force-left', backwards: 'force-right' } )[ this.align ];
17382 } else {
17383 align = ( { forwards: 'force-right', backwards: 'force-left' } )[ this.align ];
17384 }
17385
17386 }
17387
17388 // Compute initial popupOffset based on alignment
17389 popupOffset = this.width * ( { 'force-left': -1, center: -0.5, 'force-right': 0 } )[ align ];
17390
17391 // Figure out if this will cause the popup to go beyond the edge of the container
17392 originOffset = this.$element.offset().left;
17393 containerLeft = this.$container.offset().left;
17394 containerWidth = this.$container.innerWidth();
17395 containerRight = containerLeft + containerWidth;
17396 popupLeft = popupOffset - this.containerPadding;
17397 popupRight = popupOffset + this.containerPadding + this.width + this.containerPadding;
17398 overlapLeft = ( originOffset + popupLeft ) - containerLeft;
17399 overlapRight = containerRight - ( originOffset + popupRight );
17400
17401 // Adjust offset to make the popup not go beyond the edge, if needed
17402 if ( overlapRight < 0 ) {
17403 popupOffset += overlapRight;
17404 } else if ( overlapLeft < 0 ) {
17405 popupOffset -= overlapLeft;
17406 }
17407
17408 // Adjust offset to avoid anchor being rendered too close to the edge
17409 // $anchor.width() doesn't work with the pure CSS anchor (returns 0)
17410 // TODO: Find a measurement that works for CSS anchors and image anchors
17411 anchorWidth = this.$anchor[ 0 ].scrollWidth * 2;
17412 if ( popupOffset + this.width < anchorWidth ) {
17413 popupOffset = anchorWidth - this.width;
17414 } else if ( -popupOffset < anchorWidth ) {
17415 popupOffset = -anchorWidth;
17416 }
17417
17418 // Prevent transition from being interrupted
17419 clearTimeout( this.transitionTimeout );
17420 if ( transition ) {
17421 // Enable transition
17422 this.$element.addClass( 'oo-ui-popupWidget-transitioning' );
17423 }
17424
17425 // Position body relative to anchor
17426 this.$popup.css( 'margin-left', popupOffset );
17427
17428 if ( transition ) {
17429 // Prevent transitioning after transition is complete
17430 this.transitionTimeout = setTimeout( function () {
17431 widget.$element.removeClass( 'oo-ui-popupWidget-transitioning' );
17432 }, 200 );
17433 } else {
17434 // Prevent transitioning immediately
17435 this.$element.removeClass( 'oo-ui-popupWidget-transitioning' );
17436 }
17437
17438 // Reevaluate clipping state since we've relocated and resized the popup
17439 this.clip();
17440
17441 return this;
17442 };
17443
17444 /**
17445 * Set popup alignment
17446 * @param {string} align Alignment of the popup, `center`, `force-left`, `force-right`,
17447 * `backwards` or `forwards`.
17448 */
17449 OO.ui.PopupWidget.prototype.setAlignment = function ( align ) {
17450 // Validate alignment and transform deprecated values
17451 if ( [ 'left', 'right', 'force-left', 'force-right', 'backwards', 'forwards', 'center' ].indexOf( align ) > -1 ) {
17452 this.align = { left: 'force-right', right: 'force-left' }[ align ] || align;
17453 } else {
17454 this.align = 'center';
17455 }
17456 };
17457
17458 /**
17459 * Get popup alignment
17460 * @return {string} align Alignment of the popup, `center`, `force-left`, `force-right`,
17461 * `backwards` or `forwards`.
17462 */
17463 OO.ui.PopupWidget.prototype.getAlignment = function () {
17464 return this.align;
17465 };
17466
17467 /**
17468 * Progress bars visually display the status of an operation, such as a download,
17469 * and can be either determinate or indeterminate:
17470 *
17471 * - **determinate** process bars show the percent of an operation that is complete.
17472 *
17473 * - **indeterminate** process bars use a visual display of motion to indicate that an operation
17474 * is taking place. Because the extent of an indeterminate operation is unknown, the bar does
17475 * not use percentages.
17476 *
17477 * The value of the `progress` configuration determines whether the bar is determinate or indeterminate.
17478 *
17479 * @example
17480 * // Examples of determinate and indeterminate progress bars.
17481 * var progressBar1 = new OO.ui.ProgressBarWidget( {
17482 * progress: 33
17483 * } );
17484 * var progressBar2 = new OO.ui.ProgressBarWidget();
17485 *
17486 * // Create a FieldsetLayout to layout progress bars
17487 * var fieldset = new OO.ui.FieldsetLayout;
17488 * fieldset.addItems( [
17489 * new OO.ui.FieldLayout( progressBar1, {label: 'Determinate', align: 'top'}),
17490 * new OO.ui.FieldLayout( progressBar2, {label: 'Indeterminate', align: 'top'})
17491 * ] );
17492 * $( 'body' ).append( fieldset.$element );
17493 *
17494 * @class
17495 * @extends OO.ui.Widget
17496 *
17497 * @constructor
17498 * @param {Object} [config] Configuration options
17499 * @cfg {number|boolean} [progress=false] The type of progress bar (determinate or indeterminate).
17500 * To create a determinate progress bar, specify a number that reflects the initial percent complete.
17501 * By default, the progress bar is indeterminate.
17502 */
17503 OO.ui.ProgressBarWidget = function OoUiProgressBarWidget( config ) {
17504 // Configuration initialization
17505 config = config || {};
17506
17507 // Parent constructor
17508 OO.ui.ProgressBarWidget.parent.call( this, config );
17509
17510 // Properties
17511 this.$bar = $( '<div>' );
17512 this.progress = null;
17513
17514 // Initialization
17515 this.setProgress( config.progress !== undefined ? config.progress : false );
17516 this.$bar.addClass( 'oo-ui-progressBarWidget-bar' );
17517 this.$element
17518 .attr( {
17519 role: 'progressbar',
17520 'aria-valuemin': 0,
17521 'aria-valuemax': 100
17522 } )
17523 .addClass( 'oo-ui-progressBarWidget' )
17524 .append( this.$bar );
17525 };
17526
17527 /* Setup */
17528
17529 OO.inheritClass( OO.ui.ProgressBarWidget, OO.ui.Widget );
17530
17531 /* Static Properties */
17532
17533 OO.ui.ProgressBarWidget.static.tagName = 'div';
17534
17535 /* Methods */
17536
17537 /**
17538 * Get the percent of the progress that has been completed. Indeterminate progresses will return `false`.
17539 *
17540 * @return {number|boolean} Progress percent
17541 */
17542 OO.ui.ProgressBarWidget.prototype.getProgress = function () {
17543 return this.progress;
17544 };
17545
17546 /**
17547 * Set the percent of the process completed or `false` for an indeterminate process.
17548 *
17549 * @param {number|boolean} progress Progress percent or `false` for indeterminate
17550 */
17551 OO.ui.ProgressBarWidget.prototype.setProgress = function ( progress ) {
17552 this.progress = progress;
17553
17554 if ( progress !== false ) {
17555 this.$bar.css( 'width', this.progress + '%' );
17556 this.$element.attr( 'aria-valuenow', this.progress );
17557 } else {
17558 this.$bar.css( 'width', '' );
17559 this.$element.removeAttr( 'aria-valuenow' );
17560 }
17561 this.$element.toggleClass( 'oo-ui-progressBarWidget-indeterminate', !progress );
17562 };
17563
17564 /**
17565 * SearchWidgets combine a {@link OO.ui.TextInputWidget text input field}, where users can type a search query,
17566 * and a menu of search results, which is displayed beneath the query
17567 * field. Unlike {@link OO.ui.mixin.LookupElement lookup menus}, search result menus are always visible to the user.
17568 * Users can choose an item from the menu or type a query into the text field to search for a matching result item.
17569 * In general, search widgets are used inside a separate {@link OO.ui.Dialog dialog} window.
17570 *
17571 * Each time the query is changed, the search result menu is cleared and repopulated. Please see
17572 * the [OOjs UI demos][1] for an example.
17573 *
17574 * [1]: https://tools.wmflabs.org/oojs-ui/oojs-ui/demos/#dialogs-mediawiki-vector-ltr
17575 *
17576 * @class
17577 * @extends OO.ui.Widget
17578 *
17579 * @constructor
17580 * @param {Object} [config] Configuration options
17581 * @cfg {string|jQuery} [placeholder] Placeholder text for query input
17582 * @cfg {string} [value] Initial query value
17583 */
17584 OO.ui.SearchWidget = function OoUiSearchWidget( config ) {
17585 // Configuration initialization
17586 config = config || {};
17587
17588 // Parent constructor
17589 OO.ui.SearchWidget.parent.call( this, config );
17590
17591 // Properties
17592 this.query = new OO.ui.TextInputWidget( {
17593 icon: 'search',
17594 placeholder: config.placeholder,
17595 value: config.value
17596 } );
17597 this.results = new OO.ui.SelectWidget();
17598 this.$query = $( '<div>' );
17599 this.$results = $( '<div>' );
17600
17601 // Events
17602 this.query.connect( this, {
17603 change: 'onQueryChange',
17604 enter: 'onQueryEnter'
17605 } );
17606 this.query.$input.on( 'keydown', this.onQueryKeydown.bind( this ) );
17607
17608 // Initialization
17609 this.$query
17610 .addClass( 'oo-ui-searchWidget-query' )
17611 .append( this.query.$element );
17612 this.$results
17613 .addClass( 'oo-ui-searchWidget-results' )
17614 .append( this.results.$element );
17615 this.$element
17616 .addClass( 'oo-ui-searchWidget' )
17617 .append( this.$results, this.$query );
17618 };
17619
17620 /* Setup */
17621
17622 OO.inheritClass( OO.ui.SearchWidget, OO.ui.Widget );
17623
17624 /* Methods */
17625
17626 /**
17627 * Handle query key down events.
17628 *
17629 * @private
17630 * @param {jQuery.Event} e Key down event
17631 */
17632 OO.ui.SearchWidget.prototype.onQueryKeydown = function ( e ) {
17633 var highlightedItem, nextItem,
17634 dir = e.which === OO.ui.Keys.DOWN ? 1 : ( e.which === OO.ui.Keys.UP ? -1 : 0 );
17635
17636 if ( dir ) {
17637 highlightedItem = this.results.getHighlightedItem();
17638 if ( !highlightedItem ) {
17639 highlightedItem = this.results.getSelectedItem();
17640 }
17641 nextItem = this.results.getRelativeSelectableItem( highlightedItem, dir );
17642 this.results.highlightItem( nextItem );
17643 nextItem.scrollElementIntoView();
17644 }
17645 };
17646
17647 /**
17648 * Handle select widget select events.
17649 *
17650 * Clears existing results. Subclasses should repopulate items according to new query.
17651 *
17652 * @private
17653 * @param {string} value New value
17654 */
17655 OO.ui.SearchWidget.prototype.onQueryChange = function () {
17656 // Reset
17657 this.results.clearItems();
17658 };
17659
17660 /**
17661 * Handle select widget enter key events.
17662 *
17663 * Chooses highlighted item.
17664 *
17665 * @private
17666 * @param {string} value New value
17667 */
17668 OO.ui.SearchWidget.prototype.onQueryEnter = function () {
17669 // Reset
17670 this.results.chooseItem( this.results.getHighlightedItem() );
17671 };
17672
17673 /**
17674 * Get the query input.
17675 *
17676 * @return {OO.ui.TextInputWidget} Query input
17677 */
17678 OO.ui.SearchWidget.prototype.getQuery = function () {
17679 return this.query;
17680 };
17681
17682 /**
17683 * Get the search results menu.
17684 *
17685 * @return {OO.ui.SelectWidget} Menu of search results
17686 */
17687 OO.ui.SearchWidget.prototype.getResults = function () {
17688 return this.results;
17689 };
17690
17691 /**
17692 * A SelectWidget is of a generic selection of options. The OOjs UI library contains several types of
17693 * select widgets, including {@link OO.ui.ButtonSelectWidget button selects},
17694 * {@link OO.ui.RadioSelectWidget radio selects}, and {@link OO.ui.MenuSelectWidget
17695 * menu selects}.
17696 *
17697 * This class should be used together with OO.ui.OptionWidget or OO.ui.DecoratedOptionWidget. For more
17698 * information, please see the [OOjs UI documentation on MediaWiki][1].
17699 *
17700 * @example
17701 * // Example of a select widget with three options
17702 * var select = new OO.ui.SelectWidget( {
17703 * items: [
17704 * new OO.ui.OptionWidget( {
17705 * data: 'a',
17706 * label: 'Option One',
17707 * } ),
17708 * new OO.ui.OptionWidget( {
17709 * data: 'b',
17710 * label: 'Option Two',
17711 * } ),
17712 * new OO.ui.OptionWidget( {
17713 * data: 'c',
17714 * label: 'Option Three',
17715 * } )
17716 * ]
17717 * } );
17718 * $( 'body' ).append( select.$element );
17719 *
17720 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
17721 *
17722 * @abstract
17723 * @class
17724 * @extends OO.ui.Widget
17725 * @mixins OO.ui.mixin.GroupWidget
17726 *
17727 * @constructor
17728 * @param {Object} [config] Configuration options
17729 * @cfg {OO.ui.OptionWidget[]} [items] An array of options to add to the select.
17730 * Options are created with {@link OO.ui.OptionWidget OptionWidget} classes. See
17731 * the [OOjs UI documentation on MediaWiki] [2] for examples.
17732 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
17733 */
17734 OO.ui.SelectWidget = function OoUiSelectWidget( config ) {
17735 // Configuration initialization
17736 config = config || {};
17737
17738 // Parent constructor
17739 OO.ui.SelectWidget.parent.call( this, config );
17740
17741 // Mixin constructors
17742 OO.ui.mixin.GroupWidget.call( this, $.extend( {}, config, { $group: this.$element } ) );
17743
17744 // Properties
17745 this.pressed = false;
17746 this.selecting = null;
17747 this.onMouseUpHandler = this.onMouseUp.bind( this );
17748 this.onMouseMoveHandler = this.onMouseMove.bind( this );
17749 this.onKeyDownHandler = this.onKeyDown.bind( this );
17750 this.onKeyPressHandler = this.onKeyPress.bind( this );
17751 this.keyPressBuffer = '';
17752 this.keyPressBufferTimer = null;
17753
17754 // Events
17755 this.connect( this, {
17756 toggle: 'onToggle'
17757 } );
17758 this.$element.on( {
17759 mousedown: this.onMouseDown.bind( this ),
17760 mouseover: this.onMouseOver.bind( this ),
17761 mouseleave: this.onMouseLeave.bind( this )
17762 } );
17763
17764 // Initialization
17765 this.$element
17766 .addClass( 'oo-ui-selectWidget oo-ui-selectWidget-depressed' )
17767 .attr( 'role', 'listbox' );
17768 if ( Array.isArray( config.items ) ) {
17769 this.addItems( config.items );
17770 }
17771 };
17772
17773 /* Setup */
17774
17775 OO.inheritClass( OO.ui.SelectWidget, OO.ui.Widget );
17776
17777 // Need to mixin base class as well
17778 OO.mixinClass( OO.ui.SelectWidget, OO.ui.mixin.GroupElement );
17779 OO.mixinClass( OO.ui.SelectWidget, OO.ui.mixin.GroupWidget );
17780
17781 /* Static */
17782 OO.ui.SelectWidget.static.passAllFilter = function () {
17783 return true;
17784 };
17785
17786 /* Events */
17787
17788 /**
17789 * @event highlight
17790 *
17791 * A `highlight` event is emitted when the highlight is changed with the #highlightItem method.
17792 *
17793 * @param {OO.ui.OptionWidget|null} item Highlighted item
17794 */
17795
17796 /**
17797 * @event press
17798 *
17799 * A `press` event is emitted when the #pressItem method is used to programmatically modify the
17800 * pressed state of an option.
17801 *
17802 * @param {OO.ui.OptionWidget|null} item Pressed item
17803 */
17804
17805 /**
17806 * @event select
17807 *
17808 * A `select` event is emitted when the selection is modified programmatically with the #selectItem method.
17809 *
17810 * @param {OO.ui.OptionWidget|null} item Selected item
17811 */
17812
17813 /**
17814 * @event choose
17815 * A `choose` event is emitted when an item is chosen with the #chooseItem method.
17816 * @param {OO.ui.OptionWidget} item Chosen item
17817 */
17818
17819 /**
17820 * @event add
17821 *
17822 * An `add` event is emitted when options are added to the select with the #addItems method.
17823 *
17824 * @param {OO.ui.OptionWidget[]} items Added items
17825 * @param {number} index Index of insertion point
17826 */
17827
17828 /**
17829 * @event remove
17830 *
17831 * A `remove` event is emitted when options are removed from the select with the #clearItems
17832 * or #removeItems methods.
17833 *
17834 * @param {OO.ui.OptionWidget[]} items Removed items
17835 */
17836
17837 /* Methods */
17838
17839 /**
17840 * Handle mouse down events.
17841 *
17842 * @private
17843 * @param {jQuery.Event} e Mouse down event
17844 */
17845 OO.ui.SelectWidget.prototype.onMouseDown = function ( e ) {
17846 var item;
17847
17848 if ( !this.isDisabled() && e.which === 1 ) {
17849 this.togglePressed( true );
17850 item = this.getTargetItem( e );
17851 if ( item && item.isSelectable() ) {
17852 this.pressItem( item );
17853 this.selecting = item;
17854 OO.ui.addCaptureEventListener(
17855 this.getElementDocument(),
17856 'mouseup',
17857 this.onMouseUpHandler
17858 );
17859 OO.ui.addCaptureEventListener(
17860 this.getElementDocument(),
17861 'mousemove',
17862 this.onMouseMoveHandler
17863 );
17864 }
17865 }
17866 return false;
17867 };
17868
17869 /**
17870 * Handle mouse up events.
17871 *
17872 * @private
17873 * @param {jQuery.Event} e Mouse up event
17874 */
17875 OO.ui.SelectWidget.prototype.onMouseUp = function ( e ) {
17876 var item;
17877
17878 this.togglePressed( false );
17879 if ( !this.selecting ) {
17880 item = this.getTargetItem( e );
17881 if ( item && item.isSelectable() ) {
17882 this.selecting = item;
17883 }
17884 }
17885 if ( !this.isDisabled() && e.which === 1 && this.selecting ) {
17886 this.pressItem( null );
17887 this.chooseItem( this.selecting );
17888 this.selecting = null;
17889 }
17890
17891 OO.ui.removeCaptureEventListener( this.getElementDocument(), 'mouseup',
17892 this.onMouseUpHandler );
17893 OO.ui.removeCaptureEventListener( this.getElementDocument(), 'mousemove',
17894 this.onMouseMoveHandler );
17895
17896 return false;
17897 };
17898
17899 /**
17900 * Handle mouse move events.
17901 *
17902 * @private
17903 * @param {jQuery.Event} e Mouse move event
17904 */
17905 OO.ui.SelectWidget.prototype.onMouseMove = function ( e ) {
17906 var item;
17907
17908 if ( !this.isDisabled() && this.pressed ) {
17909 item = this.getTargetItem( e );
17910 if ( item && item !== this.selecting && item.isSelectable() ) {
17911 this.pressItem( item );
17912 this.selecting = item;
17913 }
17914 }
17915 return false;
17916 };
17917
17918 /**
17919 * Handle mouse over events.
17920 *
17921 * @private
17922 * @param {jQuery.Event} e Mouse over event
17923 */
17924 OO.ui.SelectWidget.prototype.onMouseOver = function ( e ) {
17925 var item;
17926
17927 if ( !this.isDisabled() ) {
17928 item = this.getTargetItem( e );
17929 this.highlightItem( item && item.isHighlightable() ? item : null );
17930 }
17931 return false;
17932 };
17933
17934 /**
17935 * Handle mouse leave events.
17936 *
17937 * @private
17938 * @param {jQuery.Event} e Mouse over event
17939 */
17940 OO.ui.SelectWidget.prototype.onMouseLeave = function () {
17941 if ( !this.isDisabled() ) {
17942 this.highlightItem( null );
17943 }
17944 return false;
17945 };
17946
17947 /**
17948 * Handle key down events.
17949 *
17950 * @protected
17951 * @param {jQuery.Event} e Key down event
17952 */
17953 OO.ui.SelectWidget.prototype.onKeyDown = function ( e ) {
17954 var nextItem,
17955 handled = false,
17956 currentItem = this.getHighlightedItem() || this.getSelectedItem();
17957
17958 if ( !this.isDisabled() && this.isVisible() ) {
17959 switch ( e.keyCode ) {
17960 case OO.ui.Keys.ENTER:
17961 if ( currentItem && currentItem.constructor.static.highlightable ) {
17962 // Was only highlighted, now let's select it. No-op if already selected.
17963 this.chooseItem( currentItem );
17964 handled = true;
17965 }
17966 break;
17967 case OO.ui.Keys.UP:
17968 case OO.ui.Keys.LEFT:
17969 this.clearKeyPressBuffer();
17970 nextItem = this.getRelativeSelectableItem( currentItem, -1 );
17971 handled = true;
17972 break;
17973 case OO.ui.Keys.DOWN:
17974 case OO.ui.Keys.RIGHT:
17975 this.clearKeyPressBuffer();
17976 nextItem = this.getRelativeSelectableItem( currentItem, 1 );
17977 handled = true;
17978 break;
17979 case OO.ui.Keys.ESCAPE:
17980 case OO.ui.Keys.TAB:
17981 if ( currentItem && currentItem.constructor.static.highlightable ) {
17982 currentItem.setHighlighted( false );
17983 }
17984 this.unbindKeyDownListener();
17985 this.unbindKeyPressListener();
17986 // Don't prevent tabbing away / defocusing
17987 handled = false;
17988 break;
17989 }
17990
17991 if ( nextItem ) {
17992 if ( nextItem.constructor.static.highlightable ) {
17993 this.highlightItem( nextItem );
17994 } else {
17995 this.chooseItem( nextItem );
17996 }
17997 nextItem.scrollElementIntoView();
17998 }
17999
18000 if ( handled ) {
18001 // Can't just return false, because e is not always a jQuery event
18002 e.preventDefault();
18003 e.stopPropagation();
18004 }
18005 }
18006 };
18007
18008 /**
18009 * Bind key down listener.
18010 *
18011 * @protected
18012 */
18013 OO.ui.SelectWidget.prototype.bindKeyDownListener = function () {
18014 OO.ui.addCaptureEventListener( this.getElementWindow(), 'keydown', this.onKeyDownHandler );
18015 };
18016
18017 /**
18018 * Unbind key down listener.
18019 *
18020 * @protected
18021 */
18022 OO.ui.SelectWidget.prototype.unbindKeyDownListener = function () {
18023 OO.ui.removeCaptureEventListener( this.getElementWindow(), 'keydown', this.onKeyDownHandler );
18024 };
18025
18026 /**
18027 * Clear the key-press buffer
18028 *
18029 * @protected
18030 */
18031 OO.ui.SelectWidget.prototype.clearKeyPressBuffer = function () {
18032 if ( this.keyPressBufferTimer ) {
18033 clearTimeout( this.keyPressBufferTimer );
18034 this.keyPressBufferTimer = null;
18035 }
18036 this.keyPressBuffer = '';
18037 };
18038
18039 /**
18040 * Handle key press events.
18041 *
18042 * @protected
18043 * @param {jQuery.Event} e Key press event
18044 */
18045 OO.ui.SelectWidget.prototype.onKeyPress = function ( e ) {
18046 var c, filter, item;
18047
18048 if ( !e.charCode ) {
18049 if ( e.keyCode === OO.ui.Keys.BACKSPACE && this.keyPressBuffer !== '' ) {
18050 this.keyPressBuffer = this.keyPressBuffer.substr( 0, this.keyPressBuffer.length - 1 );
18051 return false;
18052 }
18053 return;
18054 }
18055 if ( String.fromCodePoint ) {
18056 c = String.fromCodePoint( e.charCode );
18057 } else {
18058 c = String.fromCharCode( e.charCode );
18059 }
18060
18061 if ( this.keyPressBufferTimer ) {
18062 clearTimeout( this.keyPressBufferTimer );
18063 }
18064 this.keyPressBufferTimer = setTimeout( this.clearKeyPressBuffer.bind( this ), 1500 );
18065
18066 item = this.getHighlightedItem() || this.getSelectedItem();
18067
18068 if ( this.keyPressBuffer === c ) {
18069 // Common (if weird) special case: typing "xxxx" will cycle through all
18070 // the items beginning with "x".
18071 if ( item ) {
18072 item = this.getRelativeSelectableItem( item, 1 );
18073 }
18074 } else {
18075 this.keyPressBuffer += c;
18076 }
18077
18078 filter = this.getItemMatcher( this.keyPressBuffer, false );
18079 if ( !item || !filter( item ) ) {
18080 item = this.getRelativeSelectableItem( item, 1, filter );
18081 }
18082 if ( item ) {
18083 if ( item.constructor.static.highlightable ) {
18084 this.highlightItem( item );
18085 } else {
18086 this.chooseItem( item );
18087 }
18088 item.scrollElementIntoView();
18089 }
18090
18091 return false;
18092 };
18093
18094 /**
18095 * Get a matcher for the specific string
18096 *
18097 * @protected
18098 * @param {string} s String to match against items
18099 * @param {boolean} [exact=false] Only accept exact matches
18100 * @return {Function} function ( OO.ui.OptionItem ) => boolean
18101 */
18102 OO.ui.SelectWidget.prototype.getItemMatcher = function ( s, exact ) {
18103 var re;
18104
18105 if ( s.normalize ) {
18106 s = s.normalize();
18107 }
18108 s = exact ? s.trim() : s.replace( /^\s+/, '' );
18109 re = '^\\s*' + s.replace( /([\\{}()|.?*+\-\^$\[\]])/g, '\\$1' ).replace( /\s+/g, '\\s+' );
18110 if ( exact ) {
18111 re += '\\s*$';
18112 }
18113 re = new RegExp( re, 'i' );
18114 return function ( item ) {
18115 var l = item.getLabel();
18116 if ( typeof l !== 'string' ) {
18117 l = item.$label.text();
18118 }
18119 if ( l.normalize ) {
18120 l = l.normalize();
18121 }
18122 return re.test( l );
18123 };
18124 };
18125
18126 /**
18127 * Bind key press listener.
18128 *
18129 * @protected
18130 */
18131 OO.ui.SelectWidget.prototype.bindKeyPressListener = function () {
18132 OO.ui.addCaptureEventListener( this.getElementWindow(), 'keypress', this.onKeyPressHandler );
18133 };
18134
18135 /**
18136 * Unbind key down listener.
18137 *
18138 * If you override this, be sure to call this.clearKeyPressBuffer() from your
18139 * implementation.
18140 *
18141 * @protected
18142 */
18143 OO.ui.SelectWidget.prototype.unbindKeyPressListener = function () {
18144 OO.ui.removeCaptureEventListener( this.getElementWindow(), 'keypress', this.onKeyPressHandler );
18145 this.clearKeyPressBuffer();
18146 };
18147
18148 /**
18149 * Visibility change handler
18150 *
18151 * @protected
18152 * @param {boolean} visible
18153 */
18154 OO.ui.SelectWidget.prototype.onToggle = function ( visible ) {
18155 if ( !visible ) {
18156 this.clearKeyPressBuffer();
18157 }
18158 };
18159
18160 /**
18161 * Get the closest item to a jQuery.Event.
18162 *
18163 * @private
18164 * @param {jQuery.Event} e
18165 * @return {OO.ui.OptionWidget|null} Outline item widget, `null` if none was found
18166 */
18167 OO.ui.SelectWidget.prototype.getTargetItem = function ( e ) {
18168 return $( e.target ).closest( '.oo-ui-optionWidget' ).data( 'oo-ui-optionWidget' ) || null;
18169 };
18170
18171 /**
18172 * Get selected item.
18173 *
18174 * @return {OO.ui.OptionWidget|null} Selected item, `null` if no item is selected
18175 */
18176 OO.ui.SelectWidget.prototype.getSelectedItem = function () {
18177 var i, len;
18178
18179 for ( i = 0, len = this.items.length; i < len; i++ ) {
18180 if ( this.items[ i ].isSelected() ) {
18181 return this.items[ i ];
18182 }
18183 }
18184 return null;
18185 };
18186
18187 /**
18188 * Get highlighted item.
18189 *
18190 * @return {OO.ui.OptionWidget|null} Highlighted item, `null` if no item is highlighted
18191 */
18192 OO.ui.SelectWidget.prototype.getHighlightedItem = function () {
18193 var i, len;
18194
18195 for ( i = 0, len = this.items.length; i < len; i++ ) {
18196 if ( this.items[ i ].isHighlighted() ) {
18197 return this.items[ i ];
18198 }
18199 }
18200 return null;
18201 };
18202
18203 /**
18204 * Toggle pressed state.
18205 *
18206 * Press is a state that occurs when a user mouses down on an item, but
18207 * has not yet let go of the mouse. The item may appear selected, but it will not be selected
18208 * until the user releases the mouse.
18209 *
18210 * @param {boolean} pressed An option is being pressed
18211 */
18212 OO.ui.SelectWidget.prototype.togglePressed = function ( pressed ) {
18213 if ( pressed === undefined ) {
18214 pressed = !this.pressed;
18215 }
18216 if ( pressed !== this.pressed ) {
18217 this.$element
18218 .toggleClass( 'oo-ui-selectWidget-pressed', pressed )
18219 .toggleClass( 'oo-ui-selectWidget-depressed', !pressed );
18220 this.pressed = pressed;
18221 }
18222 };
18223
18224 /**
18225 * Highlight an option. If the `item` param is omitted, no options will be highlighted
18226 * and any existing highlight will be removed. The highlight is mutually exclusive.
18227 *
18228 * @param {OO.ui.OptionWidget} [item] Item to highlight, omit for no highlight
18229 * @fires highlight
18230 * @chainable
18231 */
18232 OO.ui.SelectWidget.prototype.highlightItem = function ( item ) {
18233 var i, len, highlighted,
18234 changed = false;
18235
18236 for ( i = 0, len = this.items.length; i < len; i++ ) {
18237 highlighted = this.items[ i ] === item;
18238 if ( this.items[ i ].isHighlighted() !== highlighted ) {
18239 this.items[ i ].setHighlighted( highlighted );
18240 changed = true;
18241 }
18242 }
18243 if ( changed ) {
18244 this.emit( 'highlight', item );
18245 }
18246
18247 return this;
18248 };
18249
18250 /**
18251 * Fetch an item by its label.
18252 *
18253 * @param {string} label Label of the item to select.
18254 * @param {boolean} [prefix=false] Allow a prefix match, if only a single item matches
18255 * @return {OO.ui.Element|null} Item with equivalent label, `null` if none exists
18256 */
18257 OO.ui.SelectWidget.prototype.getItemFromLabel = function ( label, prefix ) {
18258 var i, item, found,
18259 len = this.items.length,
18260 filter = this.getItemMatcher( label, true );
18261
18262 for ( i = 0; i < len; i++ ) {
18263 item = this.items[ i ];
18264 if ( item instanceof OO.ui.OptionWidget && item.isSelectable() && filter( item ) ) {
18265 return item;
18266 }
18267 }
18268
18269 if ( prefix ) {
18270 found = null;
18271 filter = this.getItemMatcher( label, false );
18272 for ( i = 0; i < len; i++ ) {
18273 item = this.items[ i ];
18274 if ( item instanceof OO.ui.OptionWidget && item.isSelectable() && filter( item ) ) {
18275 if ( found ) {
18276 return null;
18277 }
18278 found = item;
18279 }
18280 }
18281 if ( found ) {
18282 return found;
18283 }
18284 }
18285
18286 return null;
18287 };
18288
18289 /**
18290 * Programmatically select an option by its label. If the item does not exist,
18291 * all options will be deselected.
18292 *
18293 * @param {string} [label] Label of the item to select.
18294 * @param {boolean} [prefix=false] Allow a prefix match, if only a single item matches
18295 * @fires select
18296 * @chainable
18297 */
18298 OO.ui.SelectWidget.prototype.selectItemByLabel = function ( label, prefix ) {
18299 var itemFromLabel = this.getItemFromLabel( label, !!prefix );
18300 if ( label === undefined || !itemFromLabel ) {
18301 return this.selectItem();
18302 }
18303 return this.selectItem( itemFromLabel );
18304 };
18305
18306 /**
18307 * Programmatically select an option by its data. If the `data` parameter is omitted,
18308 * or if the item does not exist, all options will be deselected.
18309 *
18310 * @param {Object|string} [data] Value of the item to select, omit to deselect all
18311 * @fires select
18312 * @chainable
18313 */
18314 OO.ui.SelectWidget.prototype.selectItemByData = function ( data ) {
18315 var itemFromData = this.getItemFromData( data );
18316 if ( data === undefined || !itemFromData ) {
18317 return this.selectItem();
18318 }
18319 return this.selectItem( itemFromData );
18320 };
18321
18322 /**
18323 * Programmatically select an option by its reference. If the `item` parameter is omitted,
18324 * all options will be deselected.
18325 *
18326 * @param {OO.ui.OptionWidget} [item] Item to select, omit to deselect all
18327 * @fires select
18328 * @chainable
18329 */
18330 OO.ui.SelectWidget.prototype.selectItem = function ( item ) {
18331 var i, len, selected,
18332 changed = false;
18333
18334 for ( i = 0, len = this.items.length; i < len; i++ ) {
18335 selected = this.items[ i ] === item;
18336 if ( this.items[ i ].isSelected() !== selected ) {
18337 this.items[ i ].setSelected( selected );
18338 changed = true;
18339 }
18340 }
18341 if ( changed ) {
18342 this.emit( 'select', item );
18343 }
18344
18345 return this;
18346 };
18347
18348 /**
18349 * Press an item.
18350 *
18351 * Press is a state that occurs when a user mouses down on an item, but has not
18352 * yet let go of the mouse. The item may appear selected, but it will not be selected until the user
18353 * releases the mouse.
18354 *
18355 * @param {OO.ui.OptionWidget} [item] Item to press, omit to depress all
18356 * @fires press
18357 * @chainable
18358 */
18359 OO.ui.SelectWidget.prototype.pressItem = function ( item ) {
18360 var i, len, pressed,
18361 changed = false;
18362
18363 for ( i = 0, len = this.items.length; i < len; i++ ) {
18364 pressed = this.items[ i ] === item;
18365 if ( this.items[ i ].isPressed() !== pressed ) {
18366 this.items[ i ].setPressed( pressed );
18367 changed = true;
18368 }
18369 }
18370 if ( changed ) {
18371 this.emit( 'press', item );
18372 }
18373
18374 return this;
18375 };
18376
18377 /**
18378 * Choose an item.
18379 *
18380 * Note that ‘choose’ should never be modified programmatically. A user can choose
18381 * an option with the keyboard or mouse and it becomes selected. To select an item programmatically,
18382 * use the #selectItem method.
18383 *
18384 * This method is identical to #selectItem, but may vary in subclasses that take additional action
18385 * when users choose an item with the keyboard or mouse.
18386 *
18387 * @param {OO.ui.OptionWidget} item Item to choose
18388 * @fires choose
18389 * @chainable
18390 */
18391 OO.ui.SelectWidget.prototype.chooseItem = function ( item ) {
18392 this.selectItem( item );
18393 this.emit( 'choose', item );
18394
18395 return this;
18396 };
18397
18398 /**
18399 * Get an option by its position relative to the specified item (or to the start of the option array,
18400 * if item is `null`). The direction in which to search through the option array is specified with a
18401 * number: -1 for reverse (the default) or 1 for forward. The method will return an option, or
18402 * `null` if there are no options in the array.
18403 *
18404 * @param {OO.ui.OptionWidget|null} item Item to describe the start position, or `null` to start at the beginning of the array.
18405 * @param {number} direction Direction to move in: -1 to move backward, 1 to move forward
18406 * @param {Function} filter Only consider items for which this function returns
18407 * true. Function takes an OO.ui.OptionWidget and returns a boolean.
18408 * @return {OO.ui.OptionWidget|null} Item at position, `null` if there are no items in the select
18409 */
18410 OO.ui.SelectWidget.prototype.getRelativeSelectableItem = function ( item, direction, filter ) {
18411 var currentIndex, nextIndex, i,
18412 increase = direction > 0 ? 1 : -1,
18413 len = this.items.length;
18414
18415 if ( !$.isFunction( filter ) ) {
18416 filter = OO.ui.SelectWidget.static.passAllFilter;
18417 }
18418
18419 if ( item instanceof OO.ui.OptionWidget ) {
18420 currentIndex = this.items.indexOf( item );
18421 nextIndex = ( currentIndex + increase + len ) % len;
18422 } else {
18423 // If no item is selected and moving forward, start at the beginning.
18424 // If moving backward, start at the end.
18425 nextIndex = direction > 0 ? 0 : len - 1;
18426 }
18427
18428 for ( i = 0; i < len; i++ ) {
18429 item = this.items[ nextIndex ];
18430 if ( item instanceof OO.ui.OptionWidget && item.isSelectable() && filter( item ) ) {
18431 return item;
18432 }
18433 nextIndex = ( nextIndex + increase + len ) % len;
18434 }
18435 return null;
18436 };
18437
18438 /**
18439 * Get the next selectable item or `null` if there are no selectable items.
18440 * Disabled options and menu-section markers and breaks are not selectable.
18441 *
18442 * @return {OO.ui.OptionWidget|null} Item, `null` if there aren't any selectable items
18443 */
18444 OO.ui.SelectWidget.prototype.getFirstSelectableItem = function () {
18445 var i, len, item;
18446
18447 for ( i = 0, len = this.items.length; i < len; i++ ) {
18448 item = this.items[ i ];
18449 if ( item instanceof OO.ui.OptionWidget && item.isSelectable() ) {
18450 return item;
18451 }
18452 }
18453
18454 return null;
18455 };
18456
18457 /**
18458 * Add an array of options to the select. Optionally, an index number can be used to
18459 * specify an insertion point.
18460 *
18461 * @param {OO.ui.OptionWidget[]} items Items to add
18462 * @param {number} [index] Index to insert items after
18463 * @fires add
18464 * @chainable
18465 */
18466 OO.ui.SelectWidget.prototype.addItems = function ( items, index ) {
18467 // Mixin method
18468 OO.ui.mixin.GroupWidget.prototype.addItems.call( this, items, index );
18469
18470 // Always provide an index, even if it was omitted
18471 this.emit( 'add', items, index === undefined ? this.items.length - items.length - 1 : index );
18472
18473 return this;
18474 };
18475
18476 /**
18477 * Remove the specified array of options from the select. Options will be detached
18478 * from the DOM, not removed, so they can be reused later. To remove all options from
18479 * the select, you may wish to use the #clearItems method instead.
18480 *
18481 * @param {OO.ui.OptionWidget[]} items Items to remove
18482 * @fires remove
18483 * @chainable
18484 */
18485 OO.ui.SelectWidget.prototype.removeItems = function ( items ) {
18486 var i, len, item;
18487
18488 // Deselect items being removed
18489 for ( i = 0, len = items.length; i < len; i++ ) {
18490 item = items[ i ];
18491 if ( item.isSelected() ) {
18492 this.selectItem( null );
18493 }
18494 }
18495
18496 // Mixin method
18497 OO.ui.mixin.GroupWidget.prototype.removeItems.call( this, items );
18498
18499 this.emit( 'remove', items );
18500
18501 return this;
18502 };
18503
18504 /**
18505 * Clear all options from the select. Options will be detached from the DOM, not removed,
18506 * so that they can be reused later. To remove a subset of options from the select, use
18507 * the #removeItems method.
18508 *
18509 * @fires remove
18510 * @chainable
18511 */
18512 OO.ui.SelectWidget.prototype.clearItems = function () {
18513 var items = this.items.slice();
18514
18515 // Mixin method
18516 OO.ui.mixin.GroupWidget.prototype.clearItems.call( this );
18517
18518 // Clear selection
18519 this.selectItem( null );
18520
18521 this.emit( 'remove', items );
18522
18523 return this;
18524 };
18525
18526 /**
18527 * ButtonSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains
18528 * button options and is used together with
18529 * OO.ui.ButtonOptionWidget. The ButtonSelectWidget provides an interface for
18530 * highlighting, choosing, and selecting mutually exclusive options. Please see
18531 * the [OOjs UI documentation on MediaWiki] [1] for more information.
18532 *
18533 * @example
18534 * // Example: A ButtonSelectWidget that contains three ButtonOptionWidgets
18535 * var option1 = new OO.ui.ButtonOptionWidget( {
18536 * data: 1,
18537 * label: 'Option 1',
18538 * title: 'Button option 1'
18539 * } );
18540 *
18541 * var option2 = new OO.ui.ButtonOptionWidget( {
18542 * data: 2,
18543 * label: 'Option 2',
18544 * title: 'Button option 2'
18545 * } );
18546 *
18547 * var option3 = new OO.ui.ButtonOptionWidget( {
18548 * data: 3,
18549 * label: 'Option 3',
18550 * title: 'Button option 3'
18551 * } );
18552 *
18553 * var buttonSelect=new OO.ui.ButtonSelectWidget( {
18554 * items: [ option1, option2, option3 ]
18555 * } );
18556 * $( 'body' ).append( buttonSelect.$element );
18557 *
18558 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
18559 *
18560 * @class
18561 * @extends OO.ui.SelectWidget
18562 * @mixins OO.ui.mixin.TabIndexedElement
18563 *
18564 * @constructor
18565 * @param {Object} [config] Configuration options
18566 */
18567 OO.ui.ButtonSelectWidget = function OoUiButtonSelectWidget( config ) {
18568 // Parent constructor
18569 OO.ui.ButtonSelectWidget.parent.call( this, config );
18570
18571 // Mixin constructors
18572 OO.ui.mixin.TabIndexedElement.call( this, config );
18573
18574 // Events
18575 this.$element.on( {
18576 focus: this.bindKeyDownListener.bind( this ),
18577 blur: this.unbindKeyDownListener.bind( this )
18578 } );
18579
18580 // Initialization
18581 this.$element.addClass( 'oo-ui-buttonSelectWidget' );
18582 };
18583
18584 /* Setup */
18585
18586 OO.inheritClass( OO.ui.ButtonSelectWidget, OO.ui.SelectWidget );
18587 OO.mixinClass( OO.ui.ButtonSelectWidget, OO.ui.mixin.TabIndexedElement );
18588
18589 /**
18590 * RadioSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains radio
18591 * options and is used together with OO.ui.RadioOptionWidget. The RadioSelectWidget provides
18592 * an interface for adding, removing and selecting options.
18593 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
18594 *
18595 * If you want to use this within a HTML form, such as a OO.ui.FormLayout, use
18596 * OO.ui.RadioSelectInputWidget instead.
18597 *
18598 * @example
18599 * // A RadioSelectWidget with RadioOptions.
18600 * var option1 = new OO.ui.RadioOptionWidget( {
18601 * data: 'a',
18602 * label: 'Selected radio option'
18603 * } );
18604 *
18605 * var option2 = new OO.ui.RadioOptionWidget( {
18606 * data: 'b',
18607 * label: 'Unselected radio option'
18608 * } );
18609 *
18610 * var radioSelect=new OO.ui.RadioSelectWidget( {
18611 * items: [ option1, option2 ]
18612 * } );
18613 *
18614 * // Select 'option 1' using the RadioSelectWidget's selectItem() method.
18615 * radioSelect.selectItem( option1 );
18616 *
18617 * $( 'body' ).append( radioSelect.$element );
18618 *
18619 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
18620
18621 *
18622 * @class
18623 * @extends OO.ui.SelectWidget
18624 * @mixins OO.ui.mixin.TabIndexedElement
18625 *
18626 * @constructor
18627 * @param {Object} [config] Configuration options
18628 */
18629 OO.ui.RadioSelectWidget = function OoUiRadioSelectWidget( config ) {
18630 // Parent constructor
18631 OO.ui.RadioSelectWidget.parent.call( this, config );
18632
18633 // Mixin constructors
18634 OO.ui.mixin.TabIndexedElement.call( this, config );
18635
18636 // Events
18637 this.$element.on( {
18638 focus: this.bindKeyDownListener.bind( this ),
18639 blur: this.unbindKeyDownListener.bind( this )
18640 } );
18641
18642 // Initialization
18643 this.$element
18644 .addClass( 'oo-ui-radioSelectWidget' )
18645 .attr( 'role', 'radiogroup' );
18646 };
18647
18648 /* Setup */
18649
18650 OO.inheritClass( OO.ui.RadioSelectWidget, OO.ui.SelectWidget );
18651 OO.mixinClass( OO.ui.RadioSelectWidget, OO.ui.mixin.TabIndexedElement );
18652
18653 /**
18654 * MenuSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains options and
18655 * is used together with OO.ui.MenuOptionWidget. It is designed be used as part of another widget.
18656 * See {@link OO.ui.DropdownWidget DropdownWidget}, {@link OO.ui.ComboBoxWidget ComboBoxWidget},
18657 * and {@link OO.ui.mixin.LookupElement LookupElement} for examples of widgets that contain menus.
18658 * MenuSelectWidgets themselves are not instantiated directly, rather subclassed
18659 * and customized to be opened, closed, and displayed as needed.
18660 *
18661 * By default, menus are clipped to the visible viewport and are not visible when a user presses the
18662 * mouse outside the menu.
18663 *
18664 * Menus also have support for keyboard interaction:
18665 *
18666 * - Enter/Return key: choose and select a menu option
18667 * - Up-arrow key: highlight the previous menu option
18668 * - Down-arrow key: highlight the next menu option
18669 * - Esc key: hide the menu
18670 *
18671 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
18672 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
18673 *
18674 * @class
18675 * @extends OO.ui.SelectWidget
18676 * @mixins OO.ui.mixin.ClippableElement
18677 *
18678 * @constructor
18679 * @param {Object} [config] Configuration options
18680 * @cfg {OO.ui.TextInputWidget} [input] Text input used to implement option highlighting for menu items that match
18681 * the text the user types. This config is used by {@link OO.ui.ComboBoxWidget ComboBoxWidget}
18682 * and {@link OO.ui.mixin.LookupElement LookupElement}
18683 * @cfg {jQuery} [$input] Text input used to implement option highlighting for menu items that match
18684 * the text the user types. This config is used by {@link OO.ui.CapsuleMultiSelectWidget CapsuleMultiSelectWidget}
18685 * @cfg {OO.ui.Widget} [widget] Widget associated with the menu's active state. If the user clicks the mouse
18686 * anywhere on the page outside of this widget, the menu is hidden. For example, if there is a button
18687 * that toggles the menu's visibility on click, the menu will be hidden then re-shown when the user clicks
18688 * that button, unless the button (or its parent widget) is passed in here.
18689 * @cfg {boolean} [autoHide=true] Hide the menu when the mouse is pressed outside the menu.
18690 * @cfg {boolean} [filterFromInput=false] Filter the displayed options from the input
18691 */
18692 OO.ui.MenuSelectWidget = function OoUiMenuSelectWidget( config ) {
18693 // Configuration initialization
18694 config = config || {};
18695
18696 // Parent constructor
18697 OO.ui.MenuSelectWidget.parent.call( this, config );
18698
18699 // Mixin constructors
18700 OO.ui.mixin.ClippableElement.call( this, $.extend( {}, config, { $clippable: this.$group } ) );
18701
18702 // Properties
18703 this.newItems = null;
18704 this.autoHide = config.autoHide === undefined || !!config.autoHide;
18705 this.filterFromInput = !!config.filterFromInput;
18706 this.$input = config.$input ? config.$input : config.input ? config.input.$input : null;
18707 this.$widget = config.widget ? config.widget.$element : null;
18708 this.onDocumentMouseDownHandler = this.onDocumentMouseDown.bind( this );
18709 this.onInputEditHandler = OO.ui.debounce( this.updateItemVisibility.bind( this ), 100 );
18710
18711 // Initialization
18712 this.$element
18713 .addClass( 'oo-ui-menuSelectWidget' )
18714 .attr( 'role', 'menu' );
18715
18716 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
18717 // that reference properties not initialized at that time of parent class construction
18718 // TODO: Find a better way to handle post-constructor setup
18719 this.visible = false;
18720 this.$element.addClass( 'oo-ui-element-hidden' );
18721 };
18722
18723 /* Setup */
18724
18725 OO.inheritClass( OO.ui.MenuSelectWidget, OO.ui.SelectWidget );
18726 OO.mixinClass( OO.ui.MenuSelectWidget, OO.ui.mixin.ClippableElement );
18727
18728 /* Methods */
18729
18730 /**
18731 * Handles document mouse down events.
18732 *
18733 * @protected
18734 * @param {jQuery.Event} e Key down event
18735 */
18736 OO.ui.MenuSelectWidget.prototype.onDocumentMouseDown = function ( e ) {
18737 if (
18738 !OO.ui.contains( this.$element[ 0 ], e.target, true ) &&
18739 ( !this.$widget || !OO.ui.contains( this.$widget[ 0 ], e.target, true ) )
18740 ) {
18741 this.toggle( false );
18742 }
18743 };
18744
18745 /**
18746 * @inheritdoc
18747 */
18748 OO.ui.MenuSelectWidget.prototype.onKeyDown = function ( e ) {
18749 var currentItem = this.getHighlightedItem() || this.getSelectedItem();
18750
18751 if ( !this.isDisabled() && this.isVisible() ) {
18752 switch ( e.keyCode ) {
18753 case OO.ui.Keys.LEFT:
18754 case OO.ui.Keys.RIGHT:
18755 // Do nothing if a text field is associated, arrow keys will be handled natively
18756 if ( !this.$input ) {
18757 OO.ui.MenuSelectWidget.parent.prototype.onKeyDown.call( this, e );
18758 }
18759 break;
18760 case OO.ui.Keys.ESCAPE:
18761 case OO.ui.Keys.TAB:
18762 if ( currentItem ) {
18763 currentItem.setHighlighted( false );
18764 }
18765 this.toggle( false );
18766 // Don't prevent tabbing away, prevent defocusing
18767 if ( e.keyCode === OO.ui.Keys.ESCAPE ) {
18768 e.preventDefault();
18769 e.stopPropagation();
18770 }
18771 break;
18772 default:
18773 OO.ui.MenuSelectWidget.parent.prototype.onKeyDown.call( this, e );
18774 return;
18775 }
18776 }
18777 };
18778
18779 /**
18780 * Update menu item visibility after input changes.
18781 * @protected
18782 */
18783 OO.ui.MenuSelectWidget.prototype.updateItemVisibility = function () {
18784 var i, item,
18785 len = this.items.length,
18786 showAll = !this.isVisible(),
18787 filter = showAll ? null : this.getItemMatcher( this.$input.val() );
18788
18789 for ( i = 0; i < len; i++ ) {
18790 item = this.items[ i ];
18791 if ( item instanceof OO.ui.OptionWidget ) {
18792 item.toggle( showAll || filter( item ) );
18793 }
18794 }
18795
18796 // Reevaluate clipping
18797 this.clip();
18798 };
18799
18800 /**
18801 * @inheritdoc
18802 */
18803 OO.ui.MenuSelectWidget.prototype.bindKeyDownListener = function () {
18804 if ( this.$input ) {
18805 this.$input.on( 'keydown', this.onKeyDownHandler );
18806 } else {
18807 OO.ui.MenuSelectWidget.parent.prototype.bindKeyDownListener.call( this );
18808 }
18809 };
18810
18811 /**
18812 * @inheritdoc
18813 */
18814 OO.ui.MenuSelectWidget.prototype.unbindKeyDownListener = function () {
18815 if ( this.$input ) {
18816 this.$input.off( 'keydown', this.onKeyDownHandler );
18817 } else {
18818 OO.ui.MenuSelectWidget.parent.prototype.unbindKeyDownListener.call( this );
18819 }
18820 };
18821
18822 /**
18823 * @inheritdoc
18824 */
18825 OO.ui.MenuSelectWidget.prototype.bindKeyPressListener = function () {
18826 if ( this.$input ) {
18827 if ( this.filterFromInput ) {
18828 this.$input.on( 'keydown mouseup cut paste change input select', this.onInputEditHandler );
18829 }
18830 } else {
18831 OO.ui.MenuSelectWidget.parent.prototype.bindKeyPressListener.call( this );
18832 }
18833 };
18834
18835 /**
18836 * @inheritdoc
18837 */
18838 OO.ui.MenuSelectWidget.prototype.unbindKeyPressListener = function () {
18839 if ( this.$input ) {
18840 if ( this.filterFromInput ) {
18841 this.$input.off( 'keydown mouseup cut paste change input select', this.onInputEditHandler );
18842 this.updateItemVisibility();
18843 }
18844 } else {
18845 OO.ui.MenuSelectWidget.parent.prototype.unbindKeyPressListener.call( this );
18846 }
18847 };
18848
18849 /**
18850 * Choose an item.
18851 *
18852 * When a user chooses an item, the menu is closed.
18853 *
18854 * Note that ‘choose’ should never be modified programmatically. A user can choose an option with the keyboard
18855 * or mouse and it becomes selected. To select an item programmatically, use the #selectItem method.
18856 * @param {OO.ui.OptionWidget} item Item to choose
18857 * @chainable
18858 */
18859 OO.ui.MenuSelectWidget.prototype.chooseItem = function ( item ) {
18860 OO.ui.MenuSelectWidget.parent.prototype.chooseItem.call( this, item );
18861 this.toggle( false );
18862 return this;
18863 };
18864
18865 /**
18866 * @inheritdoc
18867 */
18868 OO.ui.MenuSelectWidget.prototype.addItems = function ( items, index ) {
18869 var i, len, item;
18870
18871 // Parent method
18872 OO.ui.MenuSelectWidget.parent.prototype.addItems.call( this, items, index );
18873
18874 // Auto-initialize
18875 if ( !this.newItems ) {
18876 this.newItems = [];
18877 }
18878
18879 for ( i = 0, len = items.length; i < len; i++ ) {
18880 item = items[ i ];
18881 if ( this.isVisible() ) {
18882 // Defer fitting label until item has been attached
18883 item.fitLabel();
18884 } else {
18885 this.newItems.push( item );
18886 }
18887 }
18888
18889 // Reevaluate clipping
18890 this.clip();
18891
18892 return this;
18893 };
18894
18895 /**
18896 * @inheritdoc
18897 */
18898 OO.ui.MenuSelectWidget.prototype.removeItems = function ( items ) {
18899 // Parent method
18900 OO.ui.MenuSelectWidget.parent.prototype.removeItems.call( this, items );
18901
18902 // Reevaluate clipping
18903 this.clip();
18904
18905 return this;
18906 };
18907
18908 /**
18909 * @inheritdoc
18910 */
18911 OO.ui.MenuSelectWidget.prototype.clearItems = function () {
18912 // Parent method
18913 OO.ui.MenuSelectWidget.parent.prototype.clearItems.call( this );
18914
18915 // Reevaluate clipping
18916 this.clip();
18917
18918 return this;
18919 };
18920
18921 /**
18922 * @inheritdoc
18923 */
18924 OO.ui.MenuSelectWidget.prototype.toggle = function ( visible ) {
18925 var i, len, change;
18926
18927 visible = ( visible === undefined ? !this.visible : !!visible ) && !!this.items.length;
18928 change = visible !== this.isVisible();
18929
18930 // Parent method
18931 OO.ui.MenuSelectWidget.parent.prototype.toggle.call( this, visible );
18932
18933 if ( change ) {
18934 if ( visible ) {
18935 this.bindKeyDownListener();
18936 this.bindKeyPressListener();
18937
18938 if ( this.newItems && this.newItems.length ) {
18939 for ( i = 0, len = this.newItems.length; i < len; i++ ) {
18940 this.newItems[ i ].fitLabel();
18941 }
18942 this.newItems = null;
18943 }
18944 this.toggleClipping( true );
18945
18946 // Auto-hide
18947 if ( this.autoHide ) {
18948 OO.ui.addCaptureEventListener( this.getElementDocument(), 'mousedown', this.onDocumentMouseDownHandler );
18949 }
18950 } else {
18951 this.unbindKeyDownListener();
18952 this.unbindKeyPressListener();
18953 OO.ui.removeCaptureEventListener( this.getElementDocument(), 'mousedown', this.onDocumentMouseDownHandler );
18954 this.toggleClipping( false );
18955 }
18956 }
18957
18958 return this;
18959 };
18960
18961 /**
18962 * FloatingMenuSelectWidget is a menu that will stick under a specified
18963 * container, even when it is inserted elsewhere in the document (for example,
18964 * in a OO.ui.Window's $overlay). This is sometimes necessary to prevent the
18965 * menu from being clipped too aggresively.
18966 *
18967 * The menu's position is automatically calculated and maintained when the menu
18968 * is toggled or the window is resized.
18969 *
18970 * See OO.ui.ComboBoxWidget for an example of a widget that uses this class.
18971 *
18972 * @class
18973 * @extends OO.ui.MenuSelectWidget
18974 * @mixins OO.ui.mixin.FloatableElement
18975 *
18976 * @constructor
18977 * @param {OO.ui.Widget} [inputWidget] Widget to provide the menu for.
18978 * Deprecated, omit this parameter and specify `$container` instead.
18979 * @param {Object} [config] Configuration options
18980 * @cfg {jQuery} [$container=inputWidget.$element] Element to render menu under
18981 */
18982 OO.ui.FloatingMenuSelectWidget = function OoUiFloatingMenuSelectWidget( inputWidget, config ) {
18983 // Allow 'inputWidget' parameter and config for backwards compatibility
18984 if ( OO.isPlainObject( inputWidget ) && config === undefined ) {
18985 config = inputWidget;
18986 inputWidget = config.inputWidget;
18987 }
18988
18989 // Configuration initialization
18990 config = config || {};
18991
18992 // Parent constructor
18993 OO.ui.FloatingMenuSelectWidget.parent.call( this, config );
18994
18995 // Properties (must be set before mixin constructors)
18996 this.inputWidget = inputWidget; // For backwards compatibility
18997 this.$container = config.$container || this.inputWidget.$element;
18998
18999 // Mixins constructors
19000 OO.ui.mixin.FloatableElement.call( this, $.extend( {}, config, { $floatableContainer: this.$container } ) );
19001
19002 // Initialization
19003 this.$element.addClass( 'oo-ui-floatingMenuSelectWidget' );
19004 // For backwards compatibility
19005 this.$element.addClass( 'oo-ui-textInputMenuSelectWidget' );
19006 };
19007
19008 /* Setup */
19009
19010 OO.inheritClass( OO.ui.FloatingMenuSelectWidget, OO.ui.MenuSelectWidget );
19011 OO.mixinClass( OO.ui.FloatingMenuSelectWidget, OO.ui.mixin.FloatableElement );
19012
19013 // For backwards compatibility
19014 OO.ui.TextInputMenuSelectWidget = OO.ui.FloatingMenuSelectWidget;
19015
19016 /* Methods */
19017
19018 /**
19019 * @inheritdoc
19020 */
19021 OO.ui.FloatingMenuSelectWidget.prototype.toggle = function ( visible ) {
19022 var change;
19023 visible = visible === undefined ? !this.isVisible() : !!visible;
19024 change = visible !== this.isVisible();
19025
19026 if ( change && visible ) {
19027 // Make sure the width is set before the parent method runs.
19028 this.setIdealSize( this.$container.width() );
19029 }
19030
19031 // Parent method
19032 // This will call this.clip(), which is nonsensical since we're not positioned yet...
19033 OO.ui.FloatingMenuSelectWidget.parent.prototype.toggle.call( this, visible );
19034
19035 if ( change ) {
19036 this.togglePositioning( this.isVisible() );
19037 }
19038
19039 return this;
19040 };
19041
19042 /**
19043 * OutlineSelectWidget is a structured list that contains {@link OO.ui.OutlineOptionWidget outline options}
19044 * A set of controls can be provided with an {@link OO.ui.OutlineControlsWidget outline controls} widget.
19045 *
19046 * **Currently, this class is only used by {@link OO.ui.BookletLayout booklet layouts}.**
19047 *
19048 * @class
19049 * @extends OO.ui.SelectWidget
19050 * @mixins OO.ui.mixin.TabIndexedElement
19051 *
19052 * @constructor
19053 * @param {Object} [config] Configuration options
19054 */
19055 OO.ui.OutlineSelectWidget = function OoUiOutlineSelectWidget( config ) {
19056 // Parent constructor
19057 OO.ui.OutlineSelectWidget.parent.call( this, config );
19058
19059 // Mixin constructors
19060 OO.ui.mixin.TabIndexedElement.call( this, config );
19061
19062 // Events
19063 this.$element.on( {
19064 focus: this.bindKeyDownListener.bind( this ),
19065 blur: this.unbindKeyDownListener.bind( this )
19066 } );
19067
19068 // Initialization
19069 this.$element.addClass( 'oo-ui-outlineSelectWidget' );
19070 };
19071
19072 /* Setup */
19073
19074 OO.inheritClass( OO.ui.OutlineSelectWidget, OO.ui.SelectWidget );
19075 OO.mixinClass( OO.ui.OutlineSelectWidget, OO.ui.mixin.TabIndexedElement );
19076
19077 /**
19078 * TabSelectWidget is a list that contains {@link OO.ui.TabOptionWidget tab options}
19079 *
19080 * **Currently, this class is only used by {@link OO.ui.IndexLayout index layouts}.**
19081 *
19082 * @class
19083 * @extends OO.ui.SelectWidget
19084 * @mixins OO.ui.mixin.TabIndexedElement
19085 *
19086 * @constructor
19087 * @param {Object} [config] Configuration options
19088 */
19089 OO.ui.TabSelectWidget = function OoUiTabSelectWidget( config ) {
19090 // Parent constructor
19091 OO.ui.TabSelectWidget.parent.call( this, config );
19092
19093 // Mixin constructors
19094 OO.ui.mixin.TabIndexedElement.call( this, config );
19095
19096 // Events
19097 this.$element.on( {
19098 focus: this.bindKeyDownListener.bind( this ),
19099 blur: this.unbindKeyDownListener.bind( this )
19100 } );
19101
19102 // Initialization
19103 this.$element.addClass( 'oo-ui-tabSelectWidget' );
19104 };
19105
19106 /* Setup */
19107
19108 OO.inheritClass( OO.ui.TabSelectWidget, OO.ui.SelectWidget );
19109 OO.mixinClass( OO.ui.TabSelectWidget, OO.ui.mixin.TabIndexedElement );
19110
19111 /**
19112 * NumberInputWidgets combine a {@link OO.ui.TextInputWidget text input} (where a value
19113 * can be entered manually) and two {@link OO.ui.ButtonWidget button widgets}
19114 * (to adjust the value in increments) to allow the user to enter a number.
19115 *
19116 * @example
19117 * // Example: A NumberInputWidget.
19118 * var numberInput = new OO.ui.NumberInputWidget( {
19119 * label: 'NumberInputWidget',
19120 * input: { value: 5, min: 1, max: 10 }
19121 * } );
19122 * $( 'body' ).append( numberInput.$element );
19123 *
19124 * @class
19125 * @extends OO.ui.Widget
19126 *
19127 * @constructor
19128 * @param {Object} [config] Configuration options
19129 * @cfg {Object} [input] Configuration options to pass to the {@link OO.ui.TextInputWidget text input widget}.
19130 * @cfg {Object} [minusButton] Configuration options to pass to the {@link OO.ui.ButtonWidget decrementing button widget}.
19131 * @cfg {Object} [plusButton] Configuration options to pass to the {@link OO.ui.ButtonWidget incrementing button widget}.
19132 * @cfg {boolean} [isInteger=false] Whether the field accepts only integer values.
19133 * @cfg {number} [min=-Infinity] Minimum allowed value
19134 * @cfg {number} [max=Infinity] Maximum allowed value
19135 * @cfg {number} [step=1] Delta when using the buttons or up/down arrow keys
19136 * @cfg {number|null} [pageStep] Delta when using the page-up/page-down keys. Defaults to 10 times #step.
19137 */
19138 OO.ui.NumberInputWidget = function OoUiNumberInputWidget( config ) {
19139 // Configuration initialization
19140 config = $.extend( {
19141 isInteger: false,
19142 min: -Infinity,
19143 max: Infinity,
19144 step: 1,
19145 pageStep: null
19146 }, config );
19147
19148 // Parent constructor
19149 OO.ui.NumberInputWidget.parent.call( this, config );
19150
19151 // Properties
19152 this.input = new OO.ui.TextInputWidget( $.extend(
19153 {
19154 disabled: this.isDisabled()
19155 },
19156 config.input
19157 ) );
19158 this.minusButton = new OO.ui.ButtonWidget( $.extend(
19159 {
19160 disabled: this.isDisabled(),
19161 tabIndex: -1
19162 },
19163 config.minusButton,
19164 {
19165 classes: [ 'oo-ui-numberInputWidget-minusButton' ],
19166 label: '−'
19167 }
19168 ) );
19169 this.plusButton = new OO.ui.ButtonWidget( $.extend(
19170 {
19171 disabled: this.isDisabled(),
19172 tabIndex: -1
19173 },
19174 config.plusButton,
19175 {
19176 classes: [ 'oo-ui-numberInputWidget-plusButton' ],
19177 label: '+'
19178 }
19179 ) );
19180
19181 // Events
19182 this.input.connect( this, {
19183 change: this.emit.bind( this, 'change' ),
19184 enter: this.emit.bind( this, 'enter' )
19185 } );
19186 this.input.$input.on( {
19187 keydown: this.onKeyDown.bind( this ),
19188 'wheel mousewheel DOMMouseScroll': this.onWheel.bind( this )
19189 } );
19190 this.plusButton.connect( this, {
19191 click: [ 'onButtonClick', +1 ]
19192 } );
19193 this.minusButton.connect( this, {
19194 click: [ 'onButtonClick', -1 ]
19195 } );
19196
19197 // Initialization
19198 this.setIsInteger( !!config.isInteger );
19199 this.setRange( config.min, config.max );
19200 this.setStep( config.step, config.pageStep );
19201
19202 this.$field = $( '<div>' ).addClass( 'oo-ui-numberInputWidget-field' )
19203 .append(
19204 this.minusButton.$element,
19205 this.input.$element,
19206 this.plusButton.$element
19207 );
19208 this.$element.addClass( 'oo-ui-numberInputWidget' ).append( this.$field );
19209 this.input.setValidation( this.validateNumber.bind( this ) );
19210 };
19211
19212 /* Setup */
19213
19214 OO.inheritClass( OO.ui.NumberInputWidget, OO.ui.Widget );
19215
19216 /* Events */
19217
19218 /**
19219 * A `change` event is emitted when the value of the input changes.
19220 *
19221 * @event change
19222 */
19223
19224 /**
19225 * An `enter` event is emitted when the user presses 'enter' inside the text box.
19226 *
19227 * @event enter
19228 */
19229
19230 /* Methods */
19231
19232 /**
19233 * Set whether only integers are allowed
19234 * @param {boolean} flag
19235 */
19236 OO.ui.NumberInputWidget.prototype.setIsInteger = function ( flag ) {
19237 this.isInteger = !!flag;
19238 this.input.setValidityFlag();
19239 };
19240
19241 /**
19242 * Get whether only integers are allowed
19243 * @return {boolean} Flag value
19244 */
19245 OO.ui.NumberInputWidget.prototype.getIsInteger = function () {
19246 return this.isInteger;
19247 };
19248
19249 /**
19250 * Set the range of allowed values
19251 * @param {number} min Minimum allowed value
19252 * @param {number} max Maximum allowed value
19253 */
19254 OO.ui.NumberInputWidget.prototype.setRange = function ( min, max ) {
19255 if ( min > max ) {
19256 throw new Error( 'Minimum (' + min + ') must not be greater than maximum (' + max + ')' );
19257 }
19258 this.min = min;
19259 this.max = max;
19260 this.input.setValidityFlag();
19261 };
19262
19263 /**
19264 * Get the current range
19265 * @return {number[]} Minimum and maximum values
19266 */
19267 OO.ui.NumberInputWidget.prototype.getRange = function () {
19268 return [ this.min, this.max ];
19269 };
19270
19271 /**
19272 * Set the stepping deltas
19273 * @param {number} step Normal step
19274 * @param {number|null} pageStep Page step. If null, 10 * step will be used.
19275 */
19276 OO.ui.NumberInputWidget.prototype.setStep = function ( step, pageStep ) {
19277 if ( step <= 0 ) {
19278 throw new Error( 'Step value must be positive' );
19279 }
19280 if ( pageStep === null ) {
19281 pageStep = step * 10;
19282 } else if ( pageStep <= 0 ) {
19283 throw new Error( 'Page step value must be positive' );
19284 }
19285 this.step = step;
19286 this.pageStep = pageStep;
19287 };
19288
19289 /**
19290 * Get the current stepping values
19291 * @return {number[]} Step and page step
19292 */
19293 OO.ui.NumberInputWidget.prototype.getStep = function () {
19294 return [ this.step, this.pageStep ];
19295 };
19296
19297 /**
19298 * Get the current value of the widget
19299 * @return {string}
19300 */
19301 OO.ui.NumberInputWidget.prototype.getValue = function () {
19302 return this.input.getValue();
19303 };
19304
19305 /**
19306 * Get the current value of the widget as a number
19307 * @return {number} May be NaN, or an invalid number
19308 */
19309 OO.ui.NumberInputWidget.prototype.getNumericValue = function () {
19310 return +this.input.getValue();
19311 };
19312
19313 /**
19314 * Set the value of the widget
19315 * @param {string} value Invalid values are allowed
19316 */
19317 OO.ui.NumberInputWidget.prototype.setValue = function ( value ) {
19318 this.input.setValue( value );
19319 };
19320
19321 /**
19322 * Adjust the value of the widget
19323 * @param {number} delta Adjustment amount
19324 */
19325 OO.ui.NumberInputWidget.prototype.adjustValue = function ( delta ) {
19326 var n, v = this.getNumericValue();
19327
19328 delta = +delta;
19329 if ( isNaN( delta ) || !isFinite( delta ) ) {
19330 throw new Error( 'Delta must be a finite number' );
19331 }
19332
19333 if ( isNaN( v ) ) {
19334 n = 0;
19335 } else {
19336 n = v + delta;
19337 n = Math.max( Math.min( n, this.max ), this.min );
19338 if ( this.isInteger ) {
19339 n = Math.round( n );
19340 }
19341 }
19342
19343 if ( n !== v ) {
19344 this.setValue( n );
19345 }
19346 };
19347
19348 /**
19349 * Validate input
19350 * @private
19351 * @param {string} value Field value
19352 * @return {boolean}
19353 */
19354 OO.ui.NumberInputWidget.prototype.validateNumber = function ( value ) {
19355 var n = +value;
19356 if ( isNaN( n ) || !isFinite( n ) ) {
19357 return false;
19358 }
19359
19360 /*jshint bitwise: false */
19361 if ( this.isInteger && ( n | 0 ) !== n ) {
19362 return false;
19363 }
19364 /*jshint bitwise: true */
19365
19366 if ( n < this.min || n > this.max ) {
19367 return false;
19368 }
19369
19370 return true;
19371 };
19372
19373 /**
19374 * Handle mouse click events.
19375 *
19376 * @private
19377 * @param {number} dir +1 or -1
19378 */
19379 OO.ui.NumberInputWidget.prototype.onButtonClick = function ( dir ) {
19380 this.adjustValue( dir * this.step );
19381 };
19382
19383 /**
19384 * Handle mouse wheel events.
19385 *
19386 * @private
19387 * @param {jQuery.Event} event
19388 */
19389 OO.ui.NumberInputWidget.prototype.onWheel = function ( event ) {
19390 var delta = 0;
19391
19392 // Standard 'wheel' event
19393 if ( event.originalEvent.deltaMode !== undefined ) {
19394 this.sawWheelEvent = true;
19395 }
19396 if ( event.originalEvent.deltaY ) {
19397 delta = -event.originalEvent.deltaY;
19398 } else if ( event.originalEvent.deltaX ) {
19399 delta = event.originalEvent.deltaX;
19400 }
19401
19402 // Non-standard events
19403 if ( !this.sawWheelEvent ) {
19404 if ( event.originalEvent.wheelDeltaX ) {
19405 delta = -event.originalEvent.wheelDeltaX;
19406 } else if ( event.originalEvent.wheelDeltaY ) {
19407 delta = event.originalEvent.wheelDeltaY;
19408 } else if ( event.originalEvent.wheelDelta ) {
19409 delta = event.originalEvent.wheelDelta;
19410 } else if ( event.originalEvent.detail ) {
19411 delta = -event.originalEvent.detail;
19412 }
19413 }
19414
19415 if ( delta ) {
19416 delta = delta < 0 ? -1 : 1;
19417 this.adjustValue( delta * this.step );
19418 }
19419
19420 return false;
19421 };
19422
19423 /**
19424 * Handle key down events.
19425 *
19426 * @private
19427 * @param {jQuery.Event} e Key down event
19428 */
19429 OO.ui.NumberInputWidget.prototype.onKeyDown = function ( e ) {
19430 if ( !this.isDisabled() ) {
19431 switch ( e.which ) {
19432 case OO.ui.Keys.UP:
19433 this.adjustValue( this.step );
19434 return false;
19435 case OO.ui.Keys.DOWN:
19436 this.adjustValue( -this.step );
19437 return false;
19438 case OO.ui.Keys.PAGEUP:
19439 this.adjustValue( this.pageStep );
19440 return false;
19441 case OO.ui.Keys.PAGEDOWN:
19442 this.adjustValue( -this.pageStep );
19443 return false;
19444 }
19445 }
19446 };
19447
19448 /**
19449 * @inheritdoc
19450 */
19451 OO.ui.NumberInputWidget.prototype.setDisabled = function ( disabled ) {
19452 // Parent method
19453 OO.ui.NumberInputWidget.parent.prototype.setDisabled.call( this, disabled );
19454
19455 if ( this.input ) {
19456 this.input.setDisabled( this.isDisabled() );
19457 }
19458 if ( this.minusButton ) {
19459 this.minusButton.setDisabled( this.isDisabled() );
19460 }
19461 if ( this.plusButton ) {
19462 this.plusButton.setDisabled( this.isDisabled() );
19463 }
19464
19465 return this;
19466 };
19467
19468 /**
19469 * ToggleSwitches are switches that slide on and off. Their state is represented by a Boolean
19470 * value (`true` for ‘on’, and `false` otherwise, the default). The ‘off’ state is represented
19471 * visually by a slider in the leftmost position.
19472 *
19473 * @example
19474 * // Toggle switches in the 'off' and 'on' position.
19475 * var toggleSwitch1 = new OO.ui.ToggleSwitchWidget();
19476 * var toggleSwitch2 = new OO.ui.ToggleSwitchWidget( {
19477 * value: true
19478 * } );
19479 *
19480 * // Create a FieldsetLayout to layout and label switches
19481 * var fieldset = new OO.ui.FieldsetLayout( {
19482 * label: 'Toggle switches'
19483 * } );
19484 * fieldset.addItems( [
19485 * new OO.ui.FieldLayout( toggleSwitch1, { label: 'Off', align: 'top' } ),
19486 * new OO.ui.FieldLayout( toggleSwitch2, { label: 'On', align: 'top' } )
19487 * ] );
19488 * $( 'body' ).append( fieldset.$element );
19489 *
19490 * @class
19491 * @extends OO.ui.ToggleWidget
19492 * @mixins OO.ui.mixin.TabIndexedElement
19493 *
19494 * @constructor
19495 * @param {Object} [config] Configuration options
19496 * @cfg {boolean} [value=false] The toggle switch’s initial on/off state.
19497 * By default, the toggle switch is in the 'off' position.
19498 */
19499 OO.ui.ToggleSwitchWidget = function OoUiToggleSwitchWidget( config ) {
19500 // Parent constructor
19501 OO.ui.ToggleSwitchWidget.parent.call( this, config );
19502
19503 // Mixin constructors
19504 OO.ui.mixin.TabIndexedElement.call( this, config );
19505
19506 // Properties
19507 this.dragging = false;
19508 this.dragStart = null;
19509 this.sliding = false;
19510 this.$glow = $( '<span>' );
19511 this.$grip = $( '<span>' );
19512
19513 // Events
19514 this.$element.on( {
19515 click: this.onClick.bind( this ),
19516 keypress: this.onKeyPress.bind( this )
19517 } );
19518
19519 // Initialization
19520 this.$glow.addClass( 'oo-ui-toggleSwitchWidget-glow' );
19521 this.$grip.addClass( 'oo-ui-toggleSwitchWidget-grip' );
19522 this.$element
19523 .addClass( 'oo-ui-toggleSwitchWidget' )
19524 .attr( 'role', 'checkbox' )
19525 .append( this.$glow, this.$grip );
19526 };
19527
19528 /* Setup */
19529
19530 OO.inheritClass( OO.ui.ToggleSwitchWidget, OO.ui.ToggleWidget );
19531 OO.mixinClass( OO.ui.ToggleSwitchWidget, OO.ui.mixin.TabIndexedElement );
19532
19533 /* Methods */
19534
19535 /**
19536 * Handle mouse click events.
19537 *
19538 * @private
19539 * @param {jQuery.Event} e Mouse click event
19540 */
19541 OO.ui.ToggleSwitchWidget.prototype.onClick = function ( e ) {
19542 if ( !this.isDisabled() && e.which === 1 ) {
19543 this.setValue( !this.value );
19544 }
19545 return false;
19546 };
19547
19548 /**
19549 * Handle key press events.
19550 *
19551 * @private
19552 * @param {jQuery.Event} e Key press event
19553 */
19554 OO.ui.ToggleSwitchWidget.prototype.onKeyPress = function ( e ) {
19555 if ( !this.isDisabled() && ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER ) ) {
19556 this.setValue( !this.value );
19557 return false;
19558 }
19559 };
19560
19561 /*!
19562 * Deprecated aliases for classes in the `OO.ui.mixin` namespace.
19563 */
19564
19565 /**
19566 * @inheritdoc OO.ui.mixin.ButtonElement
19567 * @deprecated Use {@link OO.ui.mixin.ButtonElement} instead.
19568 */
19569 OO.ui.ButtonElement = OO.ui.mixin.ButtonElement;
19570
19571 /**
19572 * @inheritdoc OO.ui.mixin.ClippableElement
19573 * @deprecated Use {@link OO.ui.mixin.ClippableElement} instead.
19574 */
19575 OO.ui.ClippableElement = OO.ui.mixin.ClippableElement;
19576
19577 /**
19578 * @inheritdoc OO.ui.mixin.DraggableElement
19579 * @deprecated Use {@link OO.ui.mixin.DraggableElement} instead.
19580 */
19581 OO.ui.DraggableElement = OO.ui.mixin.DraggableElement;
19582
19583 /**
19584 * @inheritdoc OO.ui.mixin.DraggableGroupElement
19585 * @deprecated Use {@link OO.ui.mixin.DraggableGroupElement} instead.
19586 */
19587 OO.ui.DraggableGroupElement = OO.ui.mixin.DraggableGroupElement;
19588
19589 /**
19590 * @inheritdoc OO.ui.mixin.FlaggedElement
19591 * @deprecated Use {@link OO.ui.mixin.FlaggedElement} instead.
19592 */
19593 OO.ui.FlaggedElement = OO.ui.mixin.FlaggedElement;
19594
19595 /**
19596 * @inheritdoc OO.ui.mixin.GroupElement
19597 * @deprecated Use {@link OO.ui.mixin.GroupElement} instead.
19598 */
19599 OO.ui.GroupElement = OO.ui.mixin.GroupElement;
19600
19601 /**
19602 * @inheritdoc OO.ui.mixin.GroupWidget
19603 * @deprecated Use {@link OO.ui.mixin.GroupWidget} instead.
19604 */
19605 OO.ui.GroupWidget = OO.ui.mixin.GroupWidget;
19606
19607 /**
19608 * @inheritdoc OO.ui.mixin.IconElement
19609 * @deprecated Use {@link OO.ui.mixin.IconElement} instead.
19610 */
19611 OO.ui.IconElement = OO.ui.mixin.IconElement;
19612
19613 /**
19614 * @inheritdoc OO.ui.mixin.IndicatorElement
19615 * @deprecated Use {@link OO.ui.mixin.IndicatorElement} instead.
19616 */
19617 OO.ui.IndicatorElement = OO.ui.mixin.IndicatorElement;
19618
19619 /**
19620 * @inheritdoc OO.ui.mixin.ItemWidget
19621 * @deprecated Use {@link OO.ui.mixin.ItemWidget} instead.
19622 */
19623 OO.ui.ItemWidget = OO.ui.mixin.ItemWidget;
19624
19625 /**
19626 * @inheritdoc OO.ui.mixin.LabelElement
19627 * @deprecated Use {@link OO.ui.mixin.LabelElement} instead.
19628 */
19629 OO.ui.LabelElement = OO.ui.mixin.LabelElement;
19630
19631 /**
19632 * @inheritdoc OO.ui.mixin.LookupElement
19633 * @deprecated Use {@link OO.ui.mixin.LookupElement} instead.
19634 */
19635 OO.ui.LookupElement = OO.ui.mixin.LookupElement;
19636
19637 /**
19638 * @inheritdoc OO.ui.mixin.PendingElement
19639 * @deprecated Use {@link OO.ui.mixin.PendingElement} instead.
19640 */
19641 OO.ui.PendingElement = OO.ui.mixin.PendingElement;
19642
19643 /**
19644 * @inheritdoc OO.ui.mixin.PopupElement
19645 * @deprecated Use {@link OO.ui.mixin.PopupElement} instead.
19646 */
19647 OO.ui.PopupElement = OO.ui.mixin.PopupElement;
19648
19649 /**
19650 * @inheritdoc OO.ui.mixin.TabIndexedElement
19651 * @deprecated Use {@link OO.ui.mixin.TabIndexedElement} instead.
19652 */
19653 OO.ui.TabIndexedElement = OO.ui.mixin.TabIndexedElement;
19654
19655 /**
19656 * @inheritdoc OO.ui.mixin.TitledElement
19657 * @deprecated Use {@link OO.ui.mixin.TitledElement} instead.
19658 */
19659 OO.ui.TitledElement = OO.ui.mixin.TitledElement;
19660
19661 }( OO ) );