Merge "API: Use message-per-value for apihelp-query+usercontribs-param-prop"
[lhc/web/wiklou.git] / resources / lib / oojs-ui / oojs-ui.js
1 /*!
2 * OOjs UI v0.12.4
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-08-13T21:01:04Z
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} [description]
68 */
69 OO.ui.isFocusableElement = function ( $element ) {
70 var node = $element[0],
71 nodeName = node.nodeName.toLowerCase(),
72 // Check if the element have tabindex set
73 isInElementGroup = /^(input|select|textarea|button|object)$/.test( nodeName ),
74 // Check if the element is a link with href or if it has tabindex
75 isOtherElement = (
76 ( nodeName === 'a' && node.href ) ||
77 !isNaN( $element.attr( 'tabindex' ) )
78 ),
79 // Check if the element is visible
80 isVisible = (
81 // This is quicker than calling $element.is( ':visible' )
82 $.expr.filters.visible( node ) &&
83 // Check that all parents are visible
84 !$element.parents().addBack().filter( function () {
85 return $.css( this, 'visibility' ) === 'hidden';
86 } ).length
87 ),
88 isTabOk = isNaN( $element.attr( 'tabindex' ) ) || +$element.attr( 'tabindex' ) >= 0;
89
90 return (
91 ( isInElementGroup ? !node.disabled : isOtherElement ) &&
92 isVisible && isTabOk
93 );
94 };
95
96 /**
97 * Get the user's language and any fallback languages.
98 *
99 * These language codes are used to localize user interface elements in the user's language.
100 *
101 * In environments that provide a localization system, this function should be overridden to
102 * return the user's language(s). The default implementation returns English (en) only.
103 *
104 * @return {string[]} Language codes, in descending order of priority
105 */
106 OO.ui.getUserLanguages = function () {
107 return [ 'en' ];
108 };
109
110 /**
111 * Get a value in an object keyed by language code.
112 *
113 * @param {Object.<string,Mixed>} obj Object keyed by language code
114 * @param {string|null} [lang] Language code, if omitted or null defaults to any user language
115 * @param {string} [fallback] Fallback code, used if no matching language can be found
116 * @return {Mixed} Local value
117 */
118 OO.ui.getLocalValue = function ( obj, lang, fallback ) {
119 var i, len, langs;
120
121 // Requested language
122 if ( obj[ lang ] ) {
123 return obj[ lang ];
124 }
125 // Known user language
126 langs = OO.ui.getUserLanguages();
127 for ( i = 0, len = langs.length; i < len; i++ ) {
128 lang = langs[ i ];
129 if ( obj[ lang ] ) {
130 return obj[ lang ];
131 }
132 }
133 // Fallback language
134 if ( obj[ fallback ] ) {
135 return obj[ fallback ];
136 }
137 // First existing language
138 for ( lang in obj ) {
139 return obj[ lang ];
140 }
141
142 return undefined;
143 };
144
145 /**
146 * Check if a node is contained within another node
147 *
148 * Similar to jQuery#contains except a list of containers can be supplied
149 * and a boolean argument allows you to include the container in the match list
150 *
151 * @param {HTMLElement|HTMLElement[]} containers Container node(s) to search in
152 * @param {HTMLElement} contained Node to find
153 * @param {boolean} [matchContainers] Include the container(s) in the list of nodes to match, otherwise only match descendants
154 * @return {boolean} The node is in the list of target nodes
155 */
156 OO.ui.contains = function ( containers, contained, matchContainers ) {
157 var i;
158 if ( !Array.isArray( containers ) ) {
159 containers = [ containers ];
160 }
161 for ( i = containers.length - 1; i >= 0; i-- ) {
162 if ( ( matchContainers && contained === containers[ i ] ) || $.contains( containers[ i ], contained ) ) {
163 return true;
164 }
165 }
166 return false;
167 };
168
169 /**
170 * Return a function, that, as long as it continues to be invoked, will not
171 * be triggered. The function will be called after it stops being called for
172 * N milliseconds. If `immediate` is passed, trigger the function on the
173 * leading edge, instead of the trailing.
174 *
175 * Ported from: http://underscorejs.org/underscore.js
176 *
177 * @param {Function} func
178 * @param {number} wait
179 * @param {boolean} immediate
180 * @return {Function}
181 */
182 OO.ui.debounce = function ( func, wait, immediate ) {
183 var timeout;
184 return function () {
185 var context = this,
186 args = arguments,
187 later = function () {
188 timeout = null;
189 if ( !immediate ) {
190 func.apply( context, args );
191 }
192 };
193 if ( immediate && !timeout ) {
194 func.apply( context, args );
195 }
196 clearTimeout( timeout );
197 timeout = setTimeout( later, wait );
198 };
199 };
200
201 /**
202 * Reconstitute a JavaScript object corresponding to a widget created by
203 * the PHP implementation.
204 *
205 * This is an alias for `OO.ui.Element.static.infuse()`.
206 *
207 * @param {string|HTMLElement|jQuery} idOrNode
208 * A DOM id (if a string) or node for the widget to infuse.
209 * @return {OO.ui.Element}
210 * The `OO.ui.Element` corresponding to this (infusable) document node.
211 */
212 OO.ui.infuse = function ( idOrNode ) {
213 return OO.ui.Element.static.infuse( idOrNode );
214 };
215
216 ( function () {
217 /**
218 * Message store for the default implementation of OO.ui.msg
219 *
220 * Environments that provide a localization system should not use this, but should override
221 * OO.ui.msg altogether.
222 *
223 * @private
224 */
225 var messages = {
226 // Tool tip for a button that moves items in a list down one place
227 'ooui-outline-control-move-down': 'Move item down',
228 // Tool tip for a button that moves items in a list up one place
229 'ooui-outline-control-move-up': 'Move item up',
230 // Tool tip for a button that removes items from a list
231 'ooui-outline-control-remove': 'Remove item',
232 // Label for the toolbar group that contains a list of all other available tools
233 'ooui-toolbar-more': 'More',
234 // Label for the fake tool that expands the full list of tools in a toolbar group
235 'ooui-toolgroup-expand': 'More',
236 // Label for the fake tool that collapses the full list of tools in a toolbar group
237 'ooui-toolgroup-collapse': 'Fewer',
238 // Default label for the accept button of a confirmation dialog
239 'ooui-dialog-message-accept': 'OK',
240 // Default label for the reject button of a confirmation dialog
241 'ooui-dialog-message-reject': 'Cancel',
242 // Title for process dialog error description
243 'ooui-dialog-process-error': 'Something went wrong',
244 // Label for process dialog dismiss error button, visible when describing errors
245 'ooui-dialog-process-dismiss': 'Dismiss',
246 // Label for process dialog retry action button, visible when describing only recoverable errors
247 'ooui-dialog-process-retry': 'Try again',
248 // Label for process dialog retry action button, visible when describing only warnings
249 'ooui-dialog-process-continue': 'Continue',
250 // Default placeholder for file selection widgets
251 'ooui-selectfile-not-supported': 'File selection is not supported',
252 // Default placeholder for file selection widgets
253 'ooui-selectfile-placeholder': 'No file is selected',
254 // Semicolon separator
255 'ooui-semicolon-separator': '; '
256 };
257
258 /**
259 * Get a localized message.
260 *
261 * In environments that provide a localization system, this function should be overridden to
262 * return the message translated in the user's language. The default implementation always returns
263 * English messages.
264 *
265 * After the message key, message parameters may optionally be passed. In the default implementation,
266 * any occurrences of $1 are replaced with the first parameter, $2 with the second parameter, etc.
267 * Alternative implementations of OO.ui.msg may use any substitution system they like, as long as
268 * they support unnamed, ordered message parameters.
269 *
270 * @abstract
271 * @param {string} key Message key
272 * @param {Mixed...} [params] Message parameters
273 * @return {string} Translated message with parameters substituted
274 */
275 OO.ui.msg = function ( key ) {
276 var message = messages[ key ],
277 params = Array.prototype.slice.call( arguments, 1 );
278 if ( typeof message === 'string' ) {
279 // Perform $1 substitution
280 message = message.replace( /\$(\d+)/g, function ( unused, n ) {
281 var i = parseInt( n, 10 );
282 return params[ i - 1 ] !== undefined ? params[ i - 1 ] : '$' + n;
283 } );
284 } else {
285 // Return placeholder if message not found
286 message = '[' + key + ']';
287 }
288 return message;
289 };
290
291 /**
292 * Package a message and arguments for deferred resolution.
293 *
294 * Use this when you are statically specifying a message and the message may not yet be present.
295 *
296 * @param {string} key Message key
297 * @param {Mixed...} [params] Message parameters
298 * @return {Function} Function that returns the resolved message when executed
299 */
300 OO.ui.deferMsg = function () {
301 var args = arguments;
302 return function () {
303 return OO.ui.msg.apply( OO.ui, args );
304 };
305 };
306
307 /**
308 * Resolve a message.
309 *
310 * If the message is a function it will be executed, otherwise it will pass through directly.
311 *
312 * @param {Function|string} msg Deferred message, or message text
313 * @return {string} Resolved message
314 */
315 OO.ui.resolveMsg = function ( msg ) {
316 if ( $.isFunction( msg ) ) {
317 return msg();
318 }
319 return msg;
320 };
321
322 /**
323 * @param {string} url
324 * @return {boolean}
325 */
326 OO.ui.isSafeUrl = function ( url ) {
327 var protocol,
328 // Keep in sync with php/Tag.php
329 whitelist = [
330 'bitcoin:', 'ftp:', 'ftps:', 'geo:', 'git:', 'gopher:', 'http:', 'https:', 'irc:', 'ircs:',
331 'magnet:', 'mailto:', 'mms:', 'news:', 'nntp:', 'redis:', 'sftp:', 'sip:', 'sips:', 'sms:', 'ssh:',
332 'svn:', 'tel:', 'telnet:', 'urn:', 'worldwind:', 'xmpp:'
333 ];
334
335 if ( url.indexOf( ':' ) === -1 ) {
336 // No protocol, safe
337 return true;
338 }
339
340 protocol = url.split( ':', 1 )[0] + ':';
341 if ( !protocol.match( /^([A-za-z0-9\+\.\-])+:/ ) ) {
342 // Not a valid protocol, safe
343 return true;
344 }
345
346 // Safe if in the whitelist
347 return $.inArray( protocol, whitelist ) !== -1;
348 };
349
350 } )();
351
352 /*!
353 * Mixin namespace.
354 */
355
356 /**
357 * Namespace for OOjs UI mixins.
358 *
359 * Mixins are named according to the type of object they are intended to
360 * be mixed in to. For example, OO.ui.mixin.GroupElement is intended to be
361 * mixed in to an instance of OO.ui.Element, and OO.ui.mixin.GroupWidget
362 * is intended to be mixed in to an instance of OO.ui.Widget.
363 *
364 * @class
365 * @singleton
366 */
367 OO.ui.mixin = {};
368
369 /**
370 * PendingElement is a mixin that is used to create elements that notify users that something is happening
371 * and that they should wait before proceeding. The pending state is visually represented with a pending
372 * texture that appears in the head of a pending {@link OO.ui.ProcessDialog process dialog} or in the input
373 * field of a {@link OO.ui.TextInputWidget text input widget}.
374 *
375 * Currently, {@link OO.ui.ActionWidget Action widgets}, which mix in this class, can also be marked as pending, but only when
376 * used in {@link OO.ui.MessageDialog message dialogs}. The behavior is not currently supported for action widgets used
377 * in process dialogs.
378 *
379 * @example
380 * function MessageDialog( config ) {
381 * MessageDialog.parent.call( this, config );
382 * }
383 * OO.inheritClass( MessageDialog, OO.ui.MessageDialog );
384 *
385 * MessageDialog.static.actions = [
386 * { action: 'save', label: 'Done', flags: 'primary' },
387 * { label: 'Cancel', flags: 'safe' }
388 * ];
389 *
390 * MessageDialog.prototype.initialize = function () {
391 * MessageDialog.parent.prototype.initialize.apply( this, arguments );
392 * this.content = new OO.ui.PanelLayout( { $: this.$, padded: true } );
393 * 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>' );
394 * this.$body.append( this.content.$element );
395 * };
396 * MessageDialog.prototype.getBodyHeight = function () {
397 * return 100;
398 * }
399 * MessageDialog.prototype.getActionProcess = function ( action ) {
400 * var dialog = this;
401 * if ( action === 'save' ) {
402 * dialog.getActions().get({actions: 'save'})[0].pushPending();
403 * return new OO.ui.Process()
404 * .next( 1000 )
405 * .next( function () {
406 * dialog.getActions().get({actions: 'save'})[0].popPending();
407 * } );
408 * }
409 * return MessageDialog.parent.prototype.getActionProcess.call( this, action );
410 * };
411 *
412 * var windowManager = new OO.ui.WindowManager();
413 * $( 'body' ).append( windowManager.$element );
414 *
415 * var dialog = new MessageDialog();
416 * windowManager.addWindows( [ dialog ] );
417 * windowManager.openWindow( dialog );
418 *
419 * @abstract
420 * @class
421 *
422 * @constructor
423 * @param {Object} [config] Configuration options
424 * @cfg {jQuery} [$pending] Element to mark as pending, defaults to this.$element
425 */
426 OO.ui.mixin.PendingElement = function OoUiMixinPendingElement( config ) {
427 // Configuration initialization
428 config = config || {};
429
430 // Properties
431 this.pending = 0;
432 this.$pending = null;
433
434 // Initialisation
435 this.setPendingElement( config.$pending || this.$element );
436 };
437
438 /* Setup */
439
440 OO.initClass( OO.ui.mixin.PendingElement );
441
442 /* Methods */
443
444 /**
445 * Set the pending element (and clean up any existing one).
446 *
447 * @param {jQuery} $pending The element to set to pending.
448 */
449 OO.ui.mixin.PendingElement.prototype.setPendingElement = function ( $pending ) {
450 if ( this.$pending ) {
451 this.$pending.removeClass( 'oo-ui-pendingElement-pending' );
452 }
453
454 this.$pending = $pending;
455 if ( this.pending > 0 ) {
456 this.$pending.addClass( 'oo-ui-pendingElement-pending' );
457 }
458 };
459
460 /**
461 * Check if an element is pending.
462 *
463 * @return {boolean} Element is pending
464 */
465 OO.ui.mixin.PendingElement.prototype.isPending = function () {
466 return !!this.pending;
467 };
468
469 /**
470 * Increase the pending counter. The pending state will remain active until the counter is zero
471 * (i.e., the number of calls to #pushPending and #popPending is the same).
472 *
473 * @chainable
474 */
475 OO.ui.mixin.PendingElement.prototype.pushPending = function () {
476 if ( this.pending === 0 ) {
477 this.$pending.addClass( 'oo-ui-pendingElement-pending' );
478 this.updateThemeClasses();
479 }
480 this.pending++;
481
482 return this;
483 };
484
485 /**
486 * Decrease the pending counter. The pending state will remain active until the counter is zero
487 * (i.e., the number of calls to #pushPending and #popPending is the same).
488 *
489 * @chainable
490 */
491 OO.ui.mixin.PendingElement.prototype.popPending = function () {
492 if ( this.pending === 1 ) {
493 this.$pending.removeClass( 'oo-ui-pendingElement-pending' );
494 this.updateThemeClasses();
495 }
496 this.pending = Math.max( 0, this.pending - 1 );
497
498 return this;
499 };
500
501 /**
502 * ActionSets manage the behavior of the {@link OO.ui.ActionWidget action widgets} that comprise them.
503 * Actions can be made available for specific contexts (modes) and circumstances
504 * (abilities). Action sets are primarily used with {@link OO.ui.Dialog Dialogs}.
505 *
506 * ActionSets contain two types of actions:
507 *
508 * - 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.
509 * - Other: Other actions include all non-special visible actions.
510 *
511 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
512 *
513 * @example
514 * // Example: An action set used in a process dialog
515 * function MyProcessDialog( config ) {
516 * MyProcessDialog.parent.call( this, config );
517 * }
518 * OO.inheritClass( MyProcessDialog, OO.ui.ProcessDialog );
519 * MyProcessDialog.static.title = 'An action set in a process dialog';
520 * // An action set that uses modes ('edit' and 'help' mode, in this example).
521 * MyProcessDialog.static.actions = [
522 * { action: 'continue', modes: 'edit', label: 'Continue', flags: [ 'primary', 'constructive' ] },
523 * { action: 'help', modes: 'edit', label: 'Help' },
524 * { modes: 'edit', label: 'Cancel', flags: 'safe' },
525 * { action: 'back', modes: 'help', label: 'Back', flags: 'safe' }
526 * ];
527 *
528 * MyProcessDialog.prototype.initialize = function () {
529 * MyProcessDialog.parent.prototype.initialize.apply( this, arguments );
530 * this.panel1 = new OO.ui.PanelLayout( { padded: true, expanded: false } );
531 * 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>' );
532 * this.panel2 = new OO.ui.PanelLayout( { padded: true, expanded: false } );
533 * 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>' );
534 * this.stackLayout = new OO.ui.StackLayout( {
535 * items: [ this.panel1, this.panel2 ]
536 * } );
537 * this.$body.append( this.stackLayout.$element );
538 * };
539 * MyProcessDialog.prototype.getSetupProcess = function ( data ) {
540 * return MyProcessDialog.parent.prototype.getSetupProcess.call( this, data )
541 * .next( function () {
542 * this.actions.setMode( 'edit' );
543 * }, this );
544 * };
545 * MyProcessDialog.prototype.getActionProcess = function ( action ) {
546 * if ( action === 'help' ) {
547 * this.actions.setMode( 'help' );
548 * this.stackLayout.setItem( this.panel2 );
549 * } else if ( action === 'back' ) {
550 * this.actions.setMode( 'edit' );
551 * this.stackLayout.setItem( this.panel1 );
552 * } else if ( action === 'continue' ) {
553 * var dialog = this;
554 * return new OO.ui.Process( function () {
555 * dialog.close();
556 * } );
557 * }
558 * return MyProcessDialog.parent.prototype.getActionProcess.call( this, action );
559 * };
560 * MyProcessDialog.prototype.getBodyHeight = function () {
561 * return this.panel1.$element.outerHeight( true );
562 * };
563 * var windowManager = new OO.ui.WindowManager();
564 * $( 'body' ).append( windowManager.$element );
565 * var dialog = new MyProcessDialog( {
566 * size: 'medium'
567 * } );
568 * windowManager.addWindows( [ dialog ] );
569 * windowManager.openWindow( dialog );
570 *
571 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Action_sets
572 *
573 * @abstract
574 * @class
575 * @mixins OO.EventEmitter
576 *
577 * @constructor
578 * @param {Object} [config] Configuration options
579 */
580 OO.ui.ActionSet = function OoUiActionSet( config ) {
581 // Configuration initialization
582 config = config || {};
583
584 // Mixin constructors
585 OO.EventEmitter.call( this );
586
587 // Properties
588 this.list = [];
589 this.categories = {
590 actions: 'getAction',
591 flags: 'getFlags',
592 modes: 'getModes'
593 };
594 this.categorized = {};
595 this.special = {};
596 this.others = [];
597 this.organized = false;
598 this.changing = false;
599 this.changed = false;
600 };
601
602 /* Setup */
603
604 OO.mixinClass( OO.ui.ActionSet, OO.EventEmitter );
605
606 /* Static Properties */
607
608 /**
609 * Symbolic name of the flags used to identify special actions. Special actions are displayed in the
610 * header of a {@link OO.ui.ProcessDialog process dialog}.
611 * See the [OOjs UI documentation on MediaWiki][2] for more information and examples.
612 *
613 * [2]:https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs
614 *
615 * @abstract
616 * @static
617 * @inheritable
618 * @property {string}
619 */
620 OO.ui.ActionSet.static.specialFlags = [ 'safe', 'primary' ];
621
622 /* Events */
623
624 /**
625 * @event click
626 *
627 * A 'click' event is emitted when an action is clicked.
628 *
629 * @param {OO.ui.ActionWidget} action Action that was clicked
630 */
631
632 /**
633 * @event resize
634 *
635 * A 'resize' event is emitted when an action widget is resized.
636 *
637 * @param {OO.ui.ActionWidget} action Action that was resized
638 */
639
640 /**
641 * @event add
642 *
643 * An 'add' event is emitted when actions are {@link #method-add added} to the action set.
644 *
645 * @param {OO.ui.ActionWidget[]} added Actions added
646 */
647
648 /**
649 * @event remove
650 *
651 * A 'remove' event is emitted when actions are {@link #method-remove removed}
652 * or {@link #clear cleared}.
653 *
654 * @param {OO.ui.ActionWidget[]} added Actions removed
655 */
656
657 /**
658 * @event change
659 *
660 * A 'change' event is emitted when actions are {@link #method-add added}, {@link #clear cleared},
661 * or {@link #method-remove removed} from the action set or when the {@link #setMode mode} is changed.
662 *
663 */
664
665 /* Methods */
666
667 /**
668 * Handle action change events.
669 *
670 * @private
671 * @fires change
672 */
673 OO.ui.ActionSet.prototype.onActionChange = function () {
674 this.organized = false;
675 if ( this.changing ) {
676 this.changed = true;
677 } else {
678 this.emit( 'change' );
679 }
680 };
681
682 /**
683 * Check if an action is one of the special actions.
684 *
685 * @param {OO.ui.ActionWidget} action Action to check
686 * @return {boolean} Action is special
687 */
688 OO.ui.ActionSet.prototype.isSpecial = function ( action ) {
689 var flag;
690
691 for ( flag in this.special ) {
692 if ( action === this.special[ flag ] ) {
693 return true;
694 }
695 }
696
697 return false;
698 };
699
700 /**
701 * Get action widgets based on the specified filter: ‘actions’, ‘flags’, ‘modes’, ‘visible’,
702 * or ‘disabled’.
703 *
704 * @param {Object} [filters] Filters to use, omit to get all actions
705 * @param {string|string[]} [filters.actions] Actions that action widgets must have
706 * @param {string|string[]} [filters.flags] Flags that action widgets must have (e.g., 'safe')
707 * @param {string|string[]} [filters.modes] Modes that action widgets must have
708 * @param {boolean} [filters.visible] Action widgets must be visible
709 * @param {boolean} [filters.disabled] Action widgets must be disabled
710 * @return {OO.ui.ActionWidget[]} Action widgets matching all criteria
711 */
712 OO.ui.ActionSet.prototype.get = function ( filters ) {
713 var i, len, list, category, actions, index, match, matches;
714
715 if ( filters ) {
716 this.organize();
717
718 // Collect category candidates
719 matches = [];
720 for ( category in this.categorized ) {
721 list = filters[ category ];
722 if ( list ) {
723 if ( !Array.isArray( list ) ) {
724 list = [ list ];
725 }
726 for ( i = 0, len = list.length; i < len; i++ ) {
727 actions = this.categorized[ category ][ list[ i ] ];
728 if ( Array.isArray( actions ) ) {
729 matches.push.apply( matches, actions );
730 }
731 }
732 }
733 }
734 // Remove by boolean filters
735 for ( i = 0, len = matches.length; i < len; i++ ) {
736 match = matches[ i ];
737 if (
738 ( filters.visible !== undefined && match.isVisible() !== filters.visible ) ||
739 ( filters.disabled !== undefined && match.isDisabled() !== filters.disabled )
740 ) {
741 matches.splice( i, 1 );
742 len--;
743 i--;
744 }
745 }
746 // Remove duplicates
747 for ( i = 0, len = matches.length; i < len; i++ ) {
748 match = matches[ i ];
749 index = matches.lastIndexOf( match );
750 while ( index !== i ) {
751 matches.splice( index, 1 );
752 len--;
753 index = matches.lastIndexOf( match );
754 }
755 }
756 return matches;
757 }
758 return this.list.slice();
759 };
760
761 /**
762 * Get 'special' actions.
763 *
764 * Special actions are the first visible action widgets with special flags, such as 'safe' and 'primary'.
765 * Special flags can be configured in subclasses by changing the static #specialFlags property.
766 *
767 * @return {OO.ui.ActionWidget[]|null} 'Special' action widgets.
768 */
769 OO.ui.ActionSet.prototype.getSpecial = function () {
770 this.organize();
771 return $.extend( {}, this.special );
772 };
773
774 /**
775 * Get 'other' actions.
776 *
777 * Other actions include all non-special visible action widgets.
778 *
779 * @return {OO.ui.ActionWidget[]} 'Other' action widgets
780 */
781 OO.ui.ActionSet.prototype.getOthers = function () {
782 this.organize();
783 return this.others.slice();
784 };
785
786 /**
787 * Set the mode (e.g., ‘edit’ or ‘view’). Only {@link OO.ui.ActionWidget#modes actions} configured
788 * to be available in the specified mode will be made visible. All other actions will be hidden.
789 *
790 * @param {string} mode The mode. Only actions configured to be available in the specified
791 * mode will be made visible.
792 * @chainable
793 * @fires toggle
794 * @fires change
795 */
796 OO.ui.ActionSet.prototype.setMode = function ( mode ) {
797 var i, len, action;
798
799 this.changing = true;
800 for ( i = 0, len = this.list.length; i < len; i++ ) {
801 action = this.list[ i ];
802 action.toggle( action.hasMode( mode ) );
803 }
804
805 this.organized = false;
806 this.changing = false;
807 this.emit( 'change' );
808
809 return this;
810 };
811
812 /**
813 * Set the abilities of the specified actions.
814 *
815 * Action widgets that are configured with the specified actions will be enabled
816 * or disabled based on the boolean values specified in the `actions`
817 * parameter.
818 *
819 * @param {Object.<string,boolean>} actions A list keyed by action name with boolean
820 * values that indicate whether or not the action should be enabled.
821 * @chainable
822 */
823 OO.ui.ActionSet.prototype.setAbilities = function ( actions ) {
824 var i, len, action, item;
825
826 for ( i = 0, len = this.list.length; i < len; i++ ) {
827 item = this.list[ i ];
828 action = item.getAction();
829 if ( actions[ action ] !== undefined ) {
830 item.setDisabled( !actions[ action ] );
831 }
832 }
833
834 return this;
835 };
836
837 /**
838 * Executes a function once per action.
839 *
840 * When making changes to multiple actions, use this method instead of iterating over the actions
841 * manually to defer emitting a #change event until after all actions have been changed.
842 *
843 * @param {Object|null} actions Filters to use to determine which actions to iterate over; see #get
844 * @param {Function} callback Callback to run for each action; callback is invoked with three
845 * arguments: the action, the action's index, the list of actions being iterated over
846 * @chainable
847 */
848 OO.ui.ActionSet.prototype.forEach = function ( filter, callback ) {
849 this.changed = false;
850 this.changing = true;
851 this.get( filter ).forEach( callback );
852 this.changing = false;
853 if ( this.changed ) {
854 this.emit( 'change' );
855 }
856
857 return this;
858 };
859
860 /**
861 * Add action widgets to the action set.
862 *
863 * @param {OO.ui.ActionWidget[]} actions Action widgets to add
864 * @chainable
865 * @fires add
866 * @fires change
867 */
868 OO.ui.ActionSet.prototype.add = function ( actions ) {
869 var i, len, action;
870
871 this.changing = true;
872 for ( i = 0, len = actions.length; i < len; i++ ) {
873 action = actions[ i ];
874 action.connect( this, {
875 click: [ 'emit', 'click', action ],
876 resize: [ 'emit', 'resize', action ],
877 toggle: [ 'onActionChange' ]
878 } );
879 this.list.push( action );
880 }
881 this.organized = false;
882 this.emit( 'add', actions );
883 this.changing = false;
884 this.emit( 'change' );
885
886 return this;
887 };
888
889 /**
890 * Remove action widgets from the set.
891 *
892 * To remove all actions, you may wish to use the #clear method instead.
893 *
894 * @param {OO.ui.ActionWidget[]} actions Action widgets to remove
895 * @chainable
896 * @fires remove
897 * @fires change
898 */
899 OO.ui.ActionSet.prototype.remove = function ( actions ) {
900 var i, len, index, action;
901
902 this.changing = true;
903 for ( i = 0, len = actions.length; i < len; i++ ) {
904 action = actions[ i ];
905 index = this.list.indexOf( action );
906 if ( index !== -1 ) {
907 action.disconnect( this );
908 this.list.splice( index, 1 );
909 }
910 }
911 this.organized = false;
912 this.emit( 'remove', actions );
913 this.changing = false;
914 this.emit( 'change' );
915
916 return this;
917 };
918
919 /**
920 * Remove all action widets from the set.
921 *
922 * To remove only specified actions, use the {@link #method-remove remove} method instead.
923 *
924 * @chainable
925 * @fires remove
926 * @fires change
927 */
928 OO.ui.ActionSet.prototype.clear = function () {
929 var i, len, action,
930 removed = this.list.slice();
931
932 this.changing = true;
933 for ( i = 0, len = this.list.length; i < len; i++ ) {
934 action = this.list[ i ];
935 action.disconnect( this );
936 }
937
938 this.list = [];
939
940 this.organized = false;
941 this.emit( 'remove', removed );
942 this.changing = false;
943 this.emit( 'change' );
944
945 return this;
946 };
947
948 /**
949 * Organize actions.
950 *
951 * This is called whenever organized information is requested. It will only reorganize the actions
952 * if something has changed since the last time it ran.
953 *
954 * @private
955 * @chainable
956 */
957 OO.ui.ActionSet.prototype.organize = function () {
958 var i, iLen, j, jLen, flag, action, category, list, item, special,
959 specialFlags = this.constructor.static.specialFlags;
960
961 if ( !this.organized ) {
962 this.categorized = {};
963 this.special = {};
964 this.others = [];
965 for ( i = 0, iLen = this.list.length; i < iLen; i++ ) {
966 action = this.list[ i ];
967 if ( action.isVisible() ) {
968 // Populate categories
969 for ( category in this.categories ) {
970 if ( !this.categorized[ category ] ) {
971 this.categorized[ category ] = {};
972 }
973 list = action[ this.categories[ category ] ]();
974 if ( !Array.isArray( list ) ) {
975 list = [ list ];
976 }
977 for ( j = 0, jLen = list.length; j < jLen; j++ ) {
978 item = list[ j ];
979 if ( !this.categorized[ category ][ item ] ) {
980 this.categorized[ category ][ item ] = [];
981 }
982 this.categorized[ category ][ item ].push( action );
983 }
984 }
985 // Populate special/others
986 special = false;
987 for ( j = 0, jLen = specialFlags.length; j < jLen; j++ ) {
988 flag = specialFlags[ j ];
989 if ( !this.special[ flag ] && action.hasFlag( flag ) ) {
990 this.special[ flag ] = action;
991 special = true;
992 break;
993 }
994 }
995 if ( !special ) {
996 this.others.push( action );
997 }
998 }
999 }
1000 this.organized = true;
1001 }
1002
1003 return this;
1004 };
1005
1006 /**
1007 * Each Element represents a rendering in the DOM—a button or an icon, for example, or anything
1008 * that is visible to a user. Unlike {@link OO.ui.Widget widgets}, plain elements usually do not have events
1009 * connected to them and can't be interacted with.
1010 *
1011 * @abstract
1012 * @class
1013 *
1014 * @constructor
1015 * @param {Object} [config] Configuration options
1016 * @cfg {string[]} [classes] The names of the CSS classes to apply to the element. CSS styles are added
1017 * to the top level (e.g., the outermost div) of the element. See the [OOjs UI documentation on MediaWiki][2]
1018 * for an example.
1019 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#cssExample
1020 * @cfg {string} [id] The HTML id attribute used in the rendered tag.
1021 * @cfg {string} [text] Text to insert
1022 * @cfg {Array} [content] An array of content elements to append (after #text).
1023 * Strings will be html-escaped; use an OO.ui.HtmlSnippet to append raw HTML.
1024 * Instances of OO.ui.Element will have their $element appended.
1025 * @cfg {jQuery} [$content] Content elements to append (after #text)
1026 * @cfg {Mixed} [data] Custom data of any type or combination of types (e.g., string, number, array, object).
1027 * Data can also be specified with the #setData method.
1028 */
1029 OO.ui.Element = function OoUiElement( config ) {
1030 // Configuration initialization
1031 config = config || {};
1032
1033 // Properties
1034 this.$ = $;
1035 this.visible = true;
1036 this.data = config.data;
1037 this.$element = config.$element ||
1038 $( document.createElement( this.getTagName() ) );
1039 this.elementGroup = null;
1040 this.debouncedUpdateThemeClassesHandler = this.debouncedUpdateThemeClasses.bind( this );
1041 this.updateThemeClassesPending = false;
1042
1043 // Initialization
1044 if ( Array.isArray( config.classes ) ) {
1045 this.$element.addClass( config.classes.join( ' ' ) );
1046 }
1047 if ( config.id ) {
1048 this.$element.attr( 'id', config.id );
1049 }
1050 if ( config.text ) {
1051 this.$element.text( config.text );
1052 }
1053 if ( config.content ) {
1054 // The `content` property treats plain strings as text; use an
1055 // HtmlSnippet to append HTML content. `OO.ui.Element`s get their
1056 // appropriate $element appended.
1057 this.$element.append( config.content.map( function ( v ) {
1058 if ( typeof v === 'string' ) {
1059 // Escape string so it is properly represented in HTML.
1060 return document.createTextNode( v );
1061 } else if ( v instanceof OO.ui.HtmlSnippet ) {
1062 // Bypass escaping.
1063 return v.toString();
1064 } else if ( v instanceof OO.ui.Element ) {
1065 return v.$element;
1066 }
1067 return v;
1068 } ) );
1069 }
1070 if ( config.$content ) {
1071 // The `$content` property treats plain strings as HTML.
1072 this.$element.append( config.$content );
1073 }
1074 };
1075
1076 /* Setup */
1077
1078 OO.initClass( OO.ui.Element );
1079
1080 /* Static Properties */
1081
1082 /**
1083 * The name of the HTML tag used by the element.
1084 *
1085 * The static value may be ignored if the #getTagName method is overridden.
1086 *
1087 * @static
1088 * @inheritable
1089 * @property {string}
1090 */
1091 OO.ui.Element.static.tagName = 'div';
1092
1093 /* Static Methods */
1094
1095 /**
1096 * Reconstitute a JavaScript object corresponding to a widget created
1097 * by the PHP implementation.
1098 *
1099 * @param {string|HTMLElement|jQuery} idOrNode
1100 * A DOM id (if a string) or node for the widget to infuse.
1101 * @return {OO.ui.Element}
1102 * The `OO.ui.Element` corresponding to this (infusable) document node.
1103 * For `Tag` objects emitted on the HTML side (used occasionally for content)
1104 * the value returned is a newly-created Element wrapping around the existing
1105 * DOM node.
1106 */
1107 OO.ui.Element.static.infuse = function ( idOrNode ) {
1108 var obj = OO.ui.Element.static.unsafeInfuse( idOrNode, false );
1109 // Verify that the type matches up.
1110 // FIXME: uncomment after T89721 is fixed (see T90929)
1111 /*
1112 if ( !( obj instanceof this['class'] ) ) {
1113 throw new Error( 'Infusion type mismatch!' );
1114 }
1115 */
1116 return obj;
1117 };
1118
1119 /**
1120 * Implementation helper for `infuse`; skips the type check and has an
1121 * extra property so that only the top-level invocation touches the DOM.
1122 * @private
1123 * @param {string|HTMLElement|jQuery} idOrNode
1124 * @param {jQuery.Promise|boolean} domPromise A promise that will be resolved
1125 * when the top-level widget of this infusion is inserted into DOM,
1126 * replacing the original node; or false for top-level invocation.
1127 * @return {OO.ui.Element}
1128 */
1129 OO.ui.Element.static.unsafeInfuse = function ( idOrNode, domPromise ) {
1130 // look for a cached result of a previous infusion.
1131 var id, $elem, data, cls, parts, parent, obj, top, state;
1132 if ( typeof idOrNode === 'string' ) {
1133 id = idOrNode;
1134 $elem = $( document.getElementById( id ) );
1135 } else {
1136 $elem = $( idOrNode );
1137 id = $elem.attr( 'id' );
1138 }
1139 if ( !$elem.length ) {
1140 throw new Error( 'Widget not found: ' + id );
1141 }
1142 data = $elem.data( 'ooui-infused' ) || $elem[0].oouiInfused;
1143 if ( data ) {
1144 // cached!
1145 if ( data === true ) {
1146 throw new Error( 'Circular dependency! ' + id );
1147 }
1148 return data;
1149 }
1150 data = $elem.attr( 'data-ooui' );
1151 if ( !data ) {
1152 throw new Error( 'No infusion data found: ' + id );
1153 }
1154 try {
1155 data = $.parseJSON( data );
1156 } catch ( _ ) {
1157 data = null;
1158 }
1159 if ( !( data && data._ ) ) {
1160 throw new Error( 'No valid infusion data found: ' + id );
1161 }
1162 if ( data._ === 'Tag' ) {
1163 // Special case: this is a raw Tag; wrap existing node, don't rebuild.
1164 return new OO.ui.Element( { $element: $elem } );
1165 }
1166 parts = data._.split( '.' );
1167 cls = OO.getProp.apply( OO, [ window ].concat( parts ) );
1168 if ( cls === undefined ) {
1169 // The PHP output might be old and not including the "OO.ui" prefix
1170 // TODO: Remove this back-compat after next major release
1171 cls = OO.getProp.apply( OO, [ OO.ui ].concat( parts ) );
1172 if ( cls === undefined ) {
1173 throw new Error( 'Unknown widget type: id: ' + id + ', class: ' + data._ );
1174 }
1175 }
1176
1177 // Verify that we're creating an OO.ui.Element instance
1178 parent = cls.parent;
1179
1180 while ( parent !== undefined ) {
1181 if ( parent === OO.ui.Element ) {
1182 // Safe
1183 break;
1184 }
1185
1186 parent = parent.parent;
1187 }
1188
1189 if ( parent !== OO.ui.Element ) {
1190 throw new Error( 'Unknown widget type: id: ' + id + ', class: ' + data._ );
1191 }
1192
1193 if ( domPromise === false ) {
1194 top = $.Deferred();
1195 domPromise = top.promise();
1196 }
1197 $elem.data( 'ooui-infused', true ); // prevent loops
1198 data.id = id; // implicit
1199 data = OO.copy( data, null, function deserialize( value ) {
1200 if ( OO.isPlainObject( value ) ) {
1201 if ( value.tag ) {
1202 return OO.ui.Element.static.unsafeInfuse( value.tag, domPromise );
1203 }
1204 if ( value.html ) {
1205 return new OO.ui.HtmlSnippet( value.html );
1206 }
1207 }
1208 } );
1209 // jscs:disable requireCapitalizedConstructors
1210 obj = new cls( data ); // rebuild widget
1211 // pick up dynamic state, like focus, value of form inputs, scroll position, etc.
1212 state = obj.gatherPreInfuseState( $elem );
1213 // now replace old DOM with this new DOM.
1214 if ( top ) {
1215 $elem.replaceWith( obj.$element );
1216 // This element is now gone from the DOM, but if anyone is holding a reference to it,
1217 // let's allow them to OO.ui.infuse() it and do what they expect (T105828).
1218 // Do not use jQuery.data(), as using it on detached nodes leaks memory in 1.x line by design.
1219 $elem[0].oouiInfused = obj;
1220 top.resolve();
1221 }
1222 obj.$element.data( 'ooui-infused', obj );
1223 // set the 'data-ooui' attribute so we can identify infused widgets
1224 obj.$element.attr( 'data-ooui', '' );
1225 // restore dynamic state after the new element is inserted into DOM
1226 domPromise.done( obj.restorePreInfuseState.bind( obj, state ) );
1227 return obj;
1228 };
1229
1230 /**
1231 * Get a jQuery function within a specific document.
1232 *
1233 * @static
1234 * @param {jQuery|HTMLElement|HTMLDocument|Window} context Context to bind the function to
1235 * @param {jQuery} [$iframe] HTML iframe element that contains the document, omit if document is
1236 * not in an iframe
1237 * @return {Function} Bound jQuery function
1238 */
1239 OO.ui.Element.static.getJQuery = function ( context, $iframe ) {
1240 function wrapper( selector ) {
1241 return $( selector, wrapper.context );
1242 }
1243
1244 wrapper.context = this.getDocument( context );
1245
1246 if ( $iframe ) {
1247 wrapper.$iframe = $iframe;
1248 }
1249
1250 return wrapper;
1251 };
1252
1253 /**
1254 * Get the document of an element.
1255 *
1256 * @static
1257 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Object to get the document for
1258 * @return {HTMLDocument|null} Document object
1259 */
1260 OO.ui.Element.static.getDocument = function ( obj ) {
1261 // jQuery - selections created "offscreen" won't have a context, so .context isn't reliable
1262 return ( obj[ 0 ] && obj[ 0 ].ownerDocument ) ||
1263 // Empty jQuery selections might have a context
1264 obj.context ||
1265 // HTMLElement
1266 obj.ownerDocument ||
1267 // Window
1268 obj.document ||
1269 // HTMLDocument
1270 ( obj.nodeType === 9 && obj ) ||
1271 null;
1272 };
1273
1274 /**
1275 * Get the window of an element or document.
1276 *
1277 * @static
1278 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the window for
1279 * @return {Window} Window object
1280 */
1281 OO.ui.Element.static.getWindow = function ( obj ) {
1282 var doc = this.getDocument( obj );
1283 return doc.parentWindow || doc.defaultView;
1284 };
1285
1286 /**
1287 * Get the direction of an element or document.
1288 *
1289 * @static
1290 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the direction for
1291 * @return {string} Text direction, either 'ltr' or 'rtl'
1292 */
1293 OO.ui.Element.static.getDir = function ( obj ) {
1294 var isDoc, isWin;
1295
1296 if ( obj instanceof jQuery ) {
1297 obj = obj[ 0 ];
1298 }
1299 isDoc = obj.nodeType === 9;
1300 isWin = obj.document !== undefined;
1301 if ( isDoc || isWin ) {
1302 if ( isWin ) {
1303 obj = obj.document;
1304 }
1305 obj = obj.body;
1306 }
1307 return $( obj ).css( 'direction' );
1308 };
1309
1310 /**
1311 * Get the offset between two frames.
1312 *
1313 * TODO: Make this function not use recursion.
1314 *
1315 * @static
1316 * @param {Window} from Window of the child frame
1317 * @param {Window} [to=window] Window of the parent frame
1318 * @param {Object} [offset] Offset to start with, used internally
1319 * @return {Object} Offset object, containing left and top properties
1320 */
1321 OO.ui.Element.static.getFrameOffset = function ( from, to, offset ) {
1322 var i, len, frames, frame, rect;
1323
1324 if ( !to ) {
1325 to = window;
1326 }
1327 if ( !offset ) {
1328 offset = { top: 0, left: 0 };
1329 }
1330 if ( from.parent === from ) {
1331 return offset;
1332 }
1333
1334 // Get iframe element
1335 frames = from.parent.document.getElementsByTagName( 'iframe' );
1336 for ( i = 0, len = frames.length; i < len; i++ ) {
1337 if ( frames[ i ].contentWindow === from ) {
1338 frame = frames[ i ];
1339 break;
1340 }
1341 }
1342
1343 // Recursively accumulate offset values
1344 if ( frame ) {
1345 rect = frame.getBoundingClientRect();
1346 offset.left += rect.left;
1347 offset.top += rect.top;
1348 if ( from !== to ) {
1349 this.getFrameOffset( from.parent, offset );
1350 }
1351 }
1352 return offset;
1353 };
1354
1355 /**
1356 * Get the offset between two elements.
1357 *
1358 * The two elements may be in a different frame, but in that case the frame $element is in must
1359 * be contained in the frame $anchor is in.
1360 *
1361 * @static
1362 * @param {jQuery} $element Element whose position to get
1363 * @param {jQuery} $anchor Element to get $element's position relative to
1364 * @return {Object} Translated position coordinates, containing top and left properties
1365 */
1366 OO.ui.Element.static.getRelativePosition = function ( $element, $anchor ) {
1367 var iframe, iframePos,
1368 pos = $element.offset(),
1369 anchorPos = $anchor.offset(),
1370 elementDocument = this.getDocument( $element ),
1371 anchorDocument = this.getDocument( $anchor );
1372
1373 // If $element isn't in the same document as $anchor, traverse up
1374 while ( elementDocument !== anchorDocument ) {
1375 iframe = elementDocument.defaultView.frameElement;
1376 if ( !iframe ) {
1377 throw new Error( '$element frame is not contained in $anchor frame' );
1378 }
1379 iframePos = $( iframe ).offset();
1380 pos.left += iframePos.left;
1381 pos.top += iframePos.top;
1382 elementDocument = iframe.ownerDocument;
1383 }
1384 pos.left -= anchorPos.left;
1385 pos.top -= anchorPos.top;
1386 return pos;
1387 };
1388
1389 /**
1390 * Get element border sizes.
1391 *
1392 * @static
1393 * @param {HTMLElement} el Element to measure
1394 * @return {Object} Dimensions object with `top`, `left`, `bottom` and `right` properties
1395 */
1396 OO.ui.Element.static.getBorders = function ( el ) {
1397 var doc = el.ownerDocument,
1398 win = doc.parentWindow || doc.defaultView,
1399 style = win && win.getComputedStyle ?
1400 win.getComputedStyle( el, null ) :
1401 el.currentStyle,
1402 $el = $( el ),
1403 top = parseFloat( style ? style.borderTopWidth : $el.css( 'borderTopWidth' ) ) || 0,
1404 left = parseFloat( style ? style.borderLeftWidth : $el.css( 'borderLeftWidth' ) ) || 0,
1405 bottom = parseFloat( style ? style.borderBottomWidth : $el.css( 'borderBottomWidth' ) ) || 0,
1406 right = parseFloat( style ? style.borderRightWidth : $el.css( 'borderRightWidth' ) ) || 0;
1407
1408 return {
1409 top: top,
1410 left: left,
1411 bottom: bottom,
1412 right: right
1413 };
1414 };
1415
1416 /**
1417 * Get dimensions of an element or window.
1418 *
1419 * @static
1420 * @param {HTMLElement|Window} el Element to measure
1421 * @return {Object} Dimensions object with `borders`, `scroll`, `scrollbar` and `rect` properties
1422 */
1423 OO.ui.Element.static.getDimensions = function ( el ) {
1424 var $el, $win,
1425 doc = el.ownerDocument || el.document,
1426 win = doc.parentWindow || doc.defaultView;
1427
1428 if ( win === el || el === doc.documentElement ) {
1429 $win = $( win );
1430 return {
1431 borders: { top: 0, left: 0, bottom: 0, right: 0 },
1432 scroll: {
1433 top: $win.scrollTop(),
1434 left: $win.scrollLeft()
1435 },
1436 scrollbar: { right: 0, bottom: 0 },
1437 rect: {
1438 top: 0,
1439 left: 0,
1440 bottom: $win.innerHeight(),
1441 right: $win.innerWidth()
1442 }
1443 };
1444 } else {
1445 $el = $( el );
1446 return {
1447 borders: this.getBorders( el ),
1448 scroll: {
1449 top: $el.scrollTop(),
1450 left: $el.scrollLeft()
1451 },
1452 scrollbar: {
1453 right: $el.innerWidth() - el.clientWidth,
1454 bottom: $el.innerHeight() - el.clientHeight
1455 },
1456 rect: el.getBoundingClientRect()
1457 };
1458 }
1459 };
1460
1461 /**
1462 * Get scrollable object parent
1463 *
1464 * documentElement can't be used to get or set the scrollTop
1465 * property on Blink. Changing and testing its value lets us
1466 * use 'body' or 'documentElement' based on what is working.
1467 *
1468 * https://code.google.com/p/chromium/issues/detail?id=303131
1469 *
1470 * @static
1471 * @param {HTMLElement} el Element to find scrollable parent for
1472 * @return {HTMLElement} Scrollable parent
1473 */
1474 OO.ui.Element.static.getRootScrollableElement = function ( el ) {
1475 var scrollTop, body;
1476
1477 if ( OO.ui.scrollableElement === undefined ) {
1478 body = el.ownerDocument.body;
1479 scrollTop = body.scrollTop;
1480 body.scrollTop = 1;
1481
1482 if ( body.scrollTop === 1 ) {
1483 body.scrollTop = scrollTop;
1484 OO.ui.scrollableElement = 'body';
1485 } else {
1486 OO.ui.scrollableElement = 'documentElement';
1487 }
1488 }
1489
1490 return el.ownerDocument[ OO.ui.scrollableElement ];
1491 };
1492
1493 /**
1494 * Get closest scrollable container.
1495 *
1496 * Traverses up until either a scrollable element or the root is reached, in which case the window
1497 * will be returned.
1498 *
1499 * @static
1500 * @param {HTMLElement} el Element to find scrollable container for
1501 * @param {string} [dimension] Dimension of scrolling to look for; `x`, `y` or omit for either
1502 * @return {HTMLElement} Closest scrollable container
1503 */
1504 OO.ui.Element.static.getClosestScrollableContainer = function ( el, dimension ) {
1505 var i, val,
1506 // props = [ 'overflow' ] doesn't work due to https://bugzilla.mozilla.org/show_bug.cgi?id=889091
1507 props = [ 'overflow-x', 'overflow-y' ],
1508 $parent = $( el ).parent();
1509
1510 if ( dimension === 'x' || dimension === 'y' ) {
1511 props = [ 'overflow-' + dimension ];
1512 }
1513
1514 while ( $parent.length ) {
1515 if ( $parent[ 0 ] === this.getRootScrollableElement( el ) ) {
1516 return $parent[ 0 ];
1517 }
1518 i = props.length;
1519 while ( i-- ) {
1520 val = $parent.css( props[ i ] );
1521 if ( val === 'auto' || val === 'scroll' ) {
1522 return $parent[ 0 ];
1523 }
1524 }
1525 $parent = $parent.parent();
1526 }
1527 return this.getDocument( el ).body;
1528 };
1529
1530 /**
1531 * Scroll element into view.
1532 *
1533 * @static
1534 * @param {HTMLElement} el Element to scroll into view
1535 * @param {Object} [config] Configuration options
1536 * @param {string} [config.duration] jQuery animation duration value
1537 * @param {string} [config.direction] Scroll in only one direction, e.g. 'x' or 'y', omit
1538 * to scroll in both directions
1539 * @param {Function} [config.complete] Function to call when scrolling completes
1540 */
1541 OO.ui.Element.static.scrollIntoView = function ( el, config ) {
1542 // Configuration initialization
1543 config = config || {};
1544
1545 var rel, anim = {},
1546 callback = typeof config.complete === 'function' && config.complete,
1547 sc = this.getClosestScrollableContainer( el, config.direction ),
1548 $sc = $( sc ),
1549 eld = this.getDimensions( el ),
1550 scd = this.getDimensions( sc ),
1551 $win = $( this.getWindow( el ) );
1552
1553 // Compute the distances between the edges of el and the edges of the scroll viewport
1554 if ( $sc.is( 'html, body' ) ) {
1555 // If the scrollable container is the root, this is easy
1556 rel = {
1557 top: eld.rect.top,
1558 bottom: $win.innerHeight() - eld.rect.bottom,
1559 left: eld.rect.left,
1560 right: $win.innerWidth() - eld.rect.right
1561 };
1562 } else {
1563 // Otherwise, we have to subtract el's coordinates from sc's coordinates
1564 rel = {
1565 top: eld.rect.top - ( scd.rect.top + scd.borders.top ),
1566 bottom: scd.rect.bottom - scd.borders.bottom - scd.scrollbar.bottom - eld.rect.bottom,
1567 left: eld.rect.left - ( scd.rect.left + scd.borders.left ),
1568 right: scd.rect.right - scd.borders.right - scd.scrollbar.right - eld.rect.right
1569 };
1570 }
1571
1572 if ( !config.direction || config.direction === 'y' ) {
1573 if ( rel.top < 0 ) {
1574 anim.scrollTop = scd.scroll.top + rel.top;
1575 } else if ( rel.top > 0 && rel.bottom < 0 ) {
1576 anim.scrollTop = scd.scroll.top + Math.min( rel.top, -rel.bottom );
1577 }
1578 }
1579 if ( !config.direction || config.direction === 'x' ) {
1580 if ( rel.left < 0 ) {
1581 anim.scrollLeft = scd.scroll.left + rel.left;
1582 } else if ( rel.left > 0 && rel.right < 0 ) {
1583 anim.scrollLeft = scd.scroll.left + Math.min( rel.left, -rel.right );
1584 }
1585 }
1586 if ( !$.isEmptyObject( anim ) ) {
1587 $sc.stop( true ).animate( anim, config.duration || 'fast' );
1588 if ( callback ) {
1589 $sc.queue( function ( next ) {
1590 callback();
1591 next();
1592 } );
1593 }
1594 } else {
1595 if ( callback ) {
1596 callback();
1597 }
1598 }
1599 };
1600
1601 /**
1602 * Force the browser to reconsider whether it really needs to render scrollbars inside the element
1603 * and reserve space for them, because it probably doesn't.
1604 *
1605 * Workaround primarily for <https://code.google.com/p/chromium/issues/detail?id=387290>, but also
1606 * similar bugs in other browsers. "Just" forcing a reflow is not sufficient in all cases, we need
1607 * to first actually detach (or hide, but detaching is simpler) all children, *then* force a reflow,
1608 * and then reattach (or show) them back.
1609 *
1610 * @static
1611 * @param {HTMLElement} el Element to reconsider the scrollbars on
1612 */
1613 OO.ui.Element.static.reconsiderScrollbars = function ( el ) {
1614 var i, len, scrollLeft, scrollTop, nodes = [];
1615 // Save scroll position
1616 scrollLeft = el.scrollLeft;
1617 scrollTop = el.scrollTop;
1618 // Detach all children
1619 while ( el.firstChild ) {
1620 nodes.push( el.firstChild );
1621 el.removeChild( el.firstChild );
1622 }
1623 // Force reflow
1624 void el.offsetHeight;
1625 // Reattach all children
1626 for ( i = 0, len = nodes.length; i < len; i++ ) {
1627 el.appendChild( nodes[ i ] );
1628 }
1629 // Restore scroll position (no-op if scrollbars disappeared)
1630 el.scrollLeft = scrollLeft;
1631 el.scrollTop = scrollTop;
1632 };
1633
1634 /* Methods */
1635
1636 /**
1637 * Toggle visibility of an element.
1638 *
1639 * @param {boolean} [show] Make element visible, omit to toggle visibility
1640 * @fires visible
1641 * @chainable
1642 */
1643 OO.ui.Element.prototype.toggle = function ( show ) {
1644 show = show === undefined ? !this.visible : !!show;
1645
1646 if ( show !== this.isVisible() ) {
1647 this.visible = show;
1648 this.$element.toggleClass( 'oo-ui-element-hidden', !this.visible );
1649 this.emit( 'toggle', show );
1650 }
1651
1652 return this;
1653 };
1654
1655 /**
1656 * Check if element is visible.
1657 *
1658 * @return {boolean} element is visible
1659 */
1660 OO.ui.Element.prototype.isVisible = function () {
1661 return this.visible;
1662 };
1663
1664 /**
1665 * Get element data.
1666 *
1667 * @return {Mixed} Element data
1668 */
1669 OO.ui.Element.prototype.getData = function () {
1670 return this.data;
1671 };
1672
1673 /**
1674 * Set element data.
1675 *
1676 * @param {Mixed} Element data
1677 * @chainable
1678 */
1679 OO.ui.Element.prototype.setData = function ( data ) {
1680 this.data = data;
1681 return this;
1682 };
1683
1684 /**
1685 * Check if element supports one or more methods.
1686 *
1687 * @param {string|string[]} methods Method or list of methods to check
1688 * @return {boolean} All methods are supported
1689 */
1690 OO.ui.Element.prototype.supports = function ( methods ) {
1691 var i, len,
1692 support = 0;
1693
1694 methods = Array.isArray( methods ) ? methods : [ methods ];
1695 for ( i = 0, len = methods.length; i < len; i++ ) {
1696 if ( $.isFunction( this[ methods[ i ] ] ) ) {
1697 support++;
1698 }
1699 }
1700
1701 return methods.length === support;
1702 };
1703
1704 /**
1705 * Update the theme-provided classes.
1706 *
1707 * @localdoc This is called in element mixins and widget classes any time state changes.
1708 * Updating is debounced, minimizing overhead of changing multiple attributes and
1709 * guaranteeing that theme updates do not occur within an element's constructor
1710 */
1711 OO.ui.Element.prototype.updateThemeClasses = function () {
1712 if ( !this.updateThemeClassesPending ) {
1713 this.updateThemeClassesPending = true;
1714 setTimeout( this.debouncedUpdateThemeClassesHandler );
1715 }
1716 };
1717
1718 /**
1719 * @private
1720 */
1721 OO.ui.Element.prototype.debouncedUpdateThemeClasses = function () {
1722 OO.ui.theme.updateElementClasses( this );
1723 this.updateThemeClassesPending = false;
1724 };
1725
1726 /**
1727 * Get the HTML tag name.
1728 *
1729 * Override this method to base the result on instance information.
1730 *
1731 * @return {string} HTML tag name
1732 */
1733 OO.ui.Element.prototype.getTagName = function () {
1734 return this.constructor.static.tagName;
1735 };
1736
1737 /**
1738 * Check if the element is attached to the DOM
1739 * @return {boolean} The element is attached to the DOM
1740 */
1741 OO.ui.Element.prototype.isElementAttached = function () {
1742 return $.contains( this.getElementDocument(), this.$element[ 0 ] );
1743 };
1744
1745 /**
1746 * Get the DOM document.
1747 *
1748 * @return {HTMLDocument} Document object
1749 */
1750 OO.ui.Element.prototype.getElementDocument = function () {
1751 // Don't cache this in other ways either because subclasses could can change this.$element
1752 return OO.ui.Element.static.getDocument( this.$element );
1753 };
1754
1755 /**
1756 * Get the DOM window.
1757 *
1758 * @return {Window} Window object
1759 */
1760 OO.ui.Element.prototype.getElementWindow = function () {
1761 return OO.ui.Element.static.getWindow( this.$element );
1762 };
1763
1764 /**
1765 * Get closest scrollable container.
1766 */
1767 OO.ui.Element.prototype.getClosestScrollableElementContainer = function () {
1768 return OO.ui.Element.static.getClosestScrollableContainer( this.$element[ 0 ] );
1769 };
1770
1771 /**
1772 * Get group element is in.
1773 *
1774 * @return {OO.ui.mixin.GroupElement|null} Group element, null if none
1775 */
1776 OO.ui.Element.prototype.getElementGroup = function () {
1777 return this.elementGroup;
1778 };
1779
1780 /**
1781 * Set group element is in.
1782 *
1783 * @param {OO.ui.mixin.GroupElement|null} group Group element, null if none
1784 * @chainable
1785 */
1786 OO.ui.Element.prototype.setElementGroup = function ( group ) {
1787 this.elementGroup = group;
1788 return this;
1789 };
1790
1791 /**
1792 * Scroll element into view.
1793 *
1794 * @param {Object} [config] Configuration options
1795 */
1796 OO.ui.Element.prototype.scrollElementIntoView = function ( config ) {
1797 return OO.ui.Element.static.scrollIntoView( this.$element[ 0 ], config );
1798 };
1799
1800 /**
1801 * Gather the dynamic state (focus, value of form inputs, scroll position, etc.) of a HTML DOM node
1802 * (and its children) that represent an Element of the same type and configuration as the current
1803 * one, generated by the PHP implementation.
1804 *
1805 * This method is called just before `node` is detached from the DOM. The return value of this
1806 * function will be passed to #restorePreInfuseState after this widget's #$element is inserted into
1807 * DOM to replace `node`.
1808 *
1809 * @protected
1810 * @param {HTMLElement} node
1811 * @return {Object}
1812 */
1813 OO.ui.Element.prototype.gatherPreInfuseState = function () {
1814 return {};
1815 };
1816
1817 /**
1818 * Restore the pre-infusion dynamic state for this widget.
1819 *
1820 * This method is called after #$element has been inserted into DOM. The parameter is the return
1821 * value of #gatherPreInfuseState.
1822 *
1823 * @protected
1824 * @param {Object} state
1825 */
1826 OO.ui.Element.prototype.restorePreInfuseState = function () {
1827 };
1828
1829 /**
1830 * Layouts are containers for elements and are used to arrange other widgets of arbitrary type in a way
1831 * that is centrally controlled and can be updated dynamically. Layouts can be, and usually are, combined.
1832 * See {@link OO.ui.FieldsetLayout FieldsetLayout}, {@link OO.ui.FieldLayout FieldLayout}, {@link OO.ui.FormLayout FormLayout},
1833 * {@link OO.ui.PanelLayout PanelLayout}, {@link OO.ui.StackLayout StackLayout}, {@link OO.ui.PageLayout PageLayout},
1834 * {@link OO.ui.HorizontalLayout HorizontalLayout}, and {@link OO.ui.BookletLayout BookletLayout} for more information and examples.
1835 *
1836 * @abstract
1837 * @class
1838 * @extends OO.ui.Element
1839 * @mixins OO.EventEmitter
1840 *
1841 * @constructor
1842 * @param {Object} [config] Configuration options
1843 */
1844 OO.ui.Layout = function OoUiLayout( config ) {
1845 // Configuration initialization
1846 config = config || {};
1847
1848 // Parent constructor
1849 OO.ui.Layout.parent.call( this, config );
1850
1851 // Mixin constructors
1852 OO.EventEmitter.call( this );
1853
1854 // Initialization
1855 this.$element.addClass( 'oo-ui-layout' );
1856 };
1857
1858 /* Setup */
1859
1860 OO.inheritClass( OO.ui.Layout, OO.ui.Element );
1861 OO.mixinClass( OO.ui.Layout, OO.EventEmitter );
1862
1863 /**
1864 * Widgets are compositions of one or more OOjs UI elements that users can both view
1865 * and interact with. All widgets can be configured and modified via a standard API,
1866 * and their state can change dynamically according to a model.
1867 *
1868 * @abstract
1869 * @class
1870 * @extends OO.ui.Element
1871 * @mixins OO.EventEmitter
1872 *
1873 * @constructor
1874 * @param {Object} [config] Configuration options
1875 * @cfg {boolean} [disabled=false] Disable the widget. Disabled widgets cannot be used and their
1876 * appearance reflects this state.
1877 */
1878 OO.ui.Widget = function OoUiWidget( config ) {
1879 // Initialize config
1880 config = $.extend( { disabled: false }, config );
1881
1882 // Parent constructor
1883 OO.ui.Widget.parent.call( this, config );
1884
1885 // Mixin constructors
1886 OO.EventEmitter.call( this );
1887
1888 // Properties
1889 this.disabled = null;
1890 this.wasDisabled = null;
1891
1892 // Initialization
1893 this.$element.addClass( 'oo-ui-widget' );
1894 this.setDisabled( !!config.disabled );
1895 };
1896
1897 /* Setup */
1898
1899 OO.inheritClass( OO.ui.Widget, OO.ui.Element );
1900 OO.mixinClass( OO.ui.Widget, OO.EventEmitter );
1901
1902 /* Static Properties */
1903
1904 /**
1905 * Whether this widget will behave reasonably when wrapped in a HTML `<label>`. If this is true,
1906 * wrappers such as OO.ui.FieldLayout may use a `<label>` instead of implementing own label click
1907 * handling.
1908 *
1909 * @static
1910 * @inheritable
1911 * @property {boolean}
1912 */
1913 OO.ui.Widget.static.supportsSimpleLabel = false;
1914
1915 /* Events */
1916
1917 /**
1918 * @event disable
1919 *
1920 * A 'disable' event is emitted when a widget is disabled.
1921 *
1922 * @param {boolean} disabled Widget is disabled
1923 */
1924
1925 /**
1926 * @event toggle
1927 *
1928 * A 'toggle' event is emitted when the visibility of the widget changes.
1929 *
1930 * @param {boolean} visible Widget is visible
1931 */
1932
1933 /* Methods */
1934
1935 /**
1936 * Check if the widget is disabled.
1937 *
1938 * @return {boolean} Widget is disabled
1939 */
1940 OO.ui.Widget.prototype.isDisabled = function () {
1941 return this.disabled;
1942 };
1943
1944 /**
1945 * Set the 'disabled' state of the widget.
1946 *
1947 * When a widget is disabled, it cannot be used and its appearance is updated to reflect this state.
1948 *
1949 * @param {boolean} disabled Disable widget
1950 * @chainable
1951 */
1952 OO.ui.Widget.prototype.setDisabled = function ( disabled ) {
1953 var isDisabled;
1954
1955 this.disabled = !!disabled;
1956 isDisabled = this.isDisabled();
1957 if ( isDisabled !== this.wasDisabled ) {
1958 this.$element.toggleClass( 'oo-ui-widget-disabled', isDisabled );
1959 this.$element.toggleClass( 'oo-ui-widget-enabled', !isDisabled );
1960 this.$element.attr( 'aria-disabled', isDisabled.toString() );
1961 this.emit( 'disable', isDisabled );
1962 this.updateThemeClasses();
1963 }
1964 this.wasDisabled = isDisabled;
1965
1966 return this;
1967 };
1968
1969 /**
1970 * Update the disabled state, in case of changes in parent widget.
1971 *
1972 * @chainable
1973 */
1974 OO.ui.Widget.prototype.updateDisabled = function () {
1975 this.setDisabled( this.disabled );
1976 return this;
1977 };
1978
1979 /**
1980 * A window is a container for elements that are in a child frame. They are used with
1981 * a window manager (OO.ui.WindowManager), which is used to open and close the window and control
1982 * its presentation. The size of a window is specified using a symbolic name (e.g., ‘small’, ‘medium’,
1983 * ‘large’), which is interpreted by the window manager. If the requested size is not recognized,
1984 * the window manager will choose a sensible fallback.
1985 *
1986 * The lifecycle of a window has three primary stages (opening, opened, and closing) in which
1987 * different processes are executed:
1988 *
1989 * **opening**: The opening stage begins when the window manager's {@link OO.ui.WindowManager#openWindow
1990 * openWindow} or the window's {@link #open open} methods are used, and the window manager begins to open
1991 * the window.
1992 *
1993 * - {@link #getSetupProcess} method is called and its result executed
1994 * - {@link #getReadyProcess} method is called and its result executed
1995 *
1996 * **opened**: The window is now open
1997 *
1998 * **closing**: The closing stage begins when the window manager's
1999 * {@link OO.ui.WindowManager#closeWindow closeWindow}
2000 * or the window's {@link #close} methods are used, and the window manager begins to close the window.
2001 *
2002 * - {@link #getHoldProcess} method is called and its result executed
2003 * - {@link #getTeardownProcess} method is called and its result executed. The window is now closed
2004 *
2005 * Each of the window's processes (setup, ready, hold, and teardown) can be extended in subclasses
2006 * by overriding the window's #getSetupProcess, #getReadyProcess, #getHoldProcess and #getTeardownProcess
2007 * methods. Note that each {@link OO.ui.Process process} is executed in series, so asynchronous
2008 * processing can complete. Always assume window processes are executed asynchronously.
2009 *
2010 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
2011 *
2012 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows
2013 *
2014 * @abstract
2015 * @class
2016 * @extends OO.ui.Element
2017 * @mixins OO.EventEmitter
2018 *
2019 * @constructor
2020 * @param {Object} [config] Configuration options
2021 * @cfg {string} [size] Symbolic name of the dialog size: `small`, `medium`, `large`, `larger` or
2022 * `full`. If omitted, the value of the {@link #static-size static size} property will be used.
2023 */
2024 OO.ui.Window = function OoUiWindow( config ) {
2025 // Configuration initialization
2026 config = config || {};
2027
2028 // Parent constructor
2029 OO.ui.Window.parent.call( this, config );
2030
2031 // Mixin constructors
2032 OO.EventEmitter.call( this );
2033
2034 // Properties
2035 this.manager = null;
2036 this.size = config.size || this.constructor.static.size;
2037 this.$frame = $( '<div>' );
2038 this.$overlay = $( '<div>' );
2039 this.$content = $( '<div>' );
2040
2041 // Initialization
2042 this.$overlay.addClass( 'oo-ui-window-overlay' );
2043 this.$content
2044 .addClass( 'oo-ui-window-content' )
2045 .attr( 'tabindex', 0 );
2046 this.$frame
2047 .addClass( 'oo-ui-window-frame' )
2048 .append( this.$content );
2049
2050 this.$element
2051 .addClass( 'oo-ui-window' )
2052 .append( this.$frame, this.$overlay );
2053
2054 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
2055 // that reference properties not initialized at that time of parent class construction
2056 // TODO: Find a better way to handle post-constructor setup
2057 this.visible = false;
2058 this.$element.addClass( 'oo-ui-element-hidden' );
2059 };
2060
2061 /* Setup */
2062
2063 OO.inheritClass( OO.ui.Window, OO.ui.Element );
2064 OO.mixinClass( OO.ui.Window, OO.EventEmitter );
2065
2066 /* Static Properties */
2067
2068 /**
2069 * Symbolic name of the window size: `small`, `medium`, `large`, `larger` or `full`.
2070 *
2071 * The static size is used if no #size is configured during construction.
2072 *
2073 * @static
2074 * @inheritable
2075 * @property {string}
2076 */
2077 OO.ui.Window.static.size = 'medium';
2078
2079 /* Methods */
2080
2081 /**
2082 * Handle mouse down events.
2083 *
2084 * @private
2085 * @param {jQuery.Event} e Mouse down event
2086 */
2087 OO.ui.Window.prototype.onMouseDown = function ( e ) {
2088 // Prevent clicking on the click-block from stealing focus
2089 if ( e.target === this.$element[ 0 ] ) {
2090 return false;
2091 }
2092 };
2093
2094 /**
2095 * Check if the window has been initialized.
2096 *
2097 * Initialization occurs when a window is added to a manager.
2098 *
2099 * @return {boolean} Window has been initialized
2100 */
2101 OO.ui.Window.prototype.isInitialized = function () {
2102 return !!this.manager;
2103 };
2104
2105 /**
2106 * Check if the window is visible.
2107 *
2108 * @return {boolean} Window is visible
2109 */
2110 OO.ui.Window.prototype.isVisible = function () {
2111 return this.visible;
2112 };
2113
2114 /**
2115 * Check if the window is opening.
2116 *
2117 * This method is a wrapper around the window manager's {@link OO.ui.WindowManager#isOpening isOpening}
2118 * method.
2119 *
2120 * @return {boolean} Window is opening
2121 */
2122 OO.ui.Window.prototype.isOpening = function () {
2123 return this.manager.isOpening( this );
2124 };
2125
2126 /**
2127 * Check if the window is closing.
2128 *
2129 * This method is a wrapper around the window manager's {@link OO.ui.WindowManager#isClosing isClosing} method.
2130 *
2131 * @return {boolean} Window is closing
2132 */
2133 OO.ui.Window.prototype.isClosing = function () {
2134 return this.manager.isClosing( this );
2135 };
2136
2137 /**
2138 * Check if the window is opened.
2139 *
2140 * This method is a wrapper around the window manager's {@link OO.ui.WindowManager#isOpened isOpened} method.
2141 *
2142 * @return {boolean} Window is opened
2143 */
2144 OO.ui.Window.prototype.isOpened = function () {
2145 return this.manager.isOpened( this );
2146 };
2147
2148 /**
2149 * Get the window manager.
2150 *
2151 * All windows must be attached to a window manager, which is used to open
2152 * and close the window and control its presentation.
2153 *
2154 * @return {OO.ui.WindowManager} Manager of window
2155 */
2156 OO.ui.Window.prototype.getManager = function () {
2157 return this.manager;
2158 };
2159
2160 /**
2161 * Get the symbolic name of the window size (e.g., `small` or `medium`).
2162 *
2163 * @return {string} Symbolic name of the size: `small`, `medium`, `large`, `larger`, `full`
2164 */
2165 OO.ui.Window.prototype.getSize = function () {
2166 var viewport = OO.ui.Element.static.getDimensions( this.getElementWindow() ),
2167 sizes = this.manager.constructor.static.sizes,
2168 size = this.size;
2169
2170 if ( !sizes[ size ] ) {
2171 size = this.manager.constructor.static.defaultSize;
2172 }
2173 if ( size !== 'full' && viewport.rect.right - viewport.rect.left < sizes[ size ].width ) {
2174 size = 'full';
2175 }
2176
2177 return size;
2178 };
2179
2180 /**
2181 * Get the size properties associated with the current window size
2182 *
2183 * @return {Object} Size properties
2184 */
2185 OO.ui.Window.prototype.getSizeProperties = function () {
2186 return this.manager.constructor.static.sizes[ this.getSize() ];
2187 };
2188
2189 /**
2190 * Disable transitions on window's frame for the duration of the callback function, then enable them
2191 * back.
2192 *
2193 * @private
2194 * @param {Function} callback Function to call while transitions are disabled
2195 */
2196 OO.ui.Window.prototype.withoutSizeTransitions = function ( callback ) {
2197 // Temporarily resize the frame so getBodyHeight() can use scrollHeight measurements.
2198 // Disable transitions first, otherwise we'll get values from when the window was animating.
2199 var oldTransition,
2200 styleObj = this.$frame[ 0 ].style;
2201 oldTransition = styleObj.transition || styleObj.OTransition || styleObj.MsTransition ||
2202 styleObj.MozTransition || styleObj.WebkitTransition;
2203 styleObj.transition = styleObj.OTransition = styleObj.MsTransition =
2204 styleObj.MozTransition = styleObj.WebkitTransition = 'none';
2205 callback();
2206 // Force reflow to make sure the style changes done inside callback really are not transitioned
2207 this.$frame.height();
2208 styleObj.transition = styleObj.OTransition = styleObj.MsTransition =
2209 styleObj.MozTransition = styleObj.WebkitTransition = oldTransition;
2210 };
2211
2212 /**
2213 * Get the height of the full window contents (i.e., the window head, body and foot together).
2214 *
2215 * What consistitutes the head, body, and foot varies depending on the window type.
2216 * A {@link OO.ui.MessageDialog message dialog} displays a title and message in its body,
2217 * and any actions in the foot. A {@link OO.ui.ProcessDialog process dialog} displays a title
2218 * and special actions in the head, and dialog content in the body.
2219 *
2220 * To get just the height of the dialog body, use the #getBodyHeight method.
2221 *
2222 * @return {number} The height of the window contents (the dialog head, body and foot) in pixels
2223 */
2224 OO.ui.Window.prototype.getContentHeight = function () {
2225 var bodyHeight,
2226 win = this,
2227 bodyStyleObj = this.$body[ 0 ].style,
2228 frameStyleObj = this.$frame[ 0 ].style;
2229
2230 // Temporarily resize the frame so getBodyHeight() can use scrollHeight measurements.
2231 // Disable transitions first, otherwise we'll get values from when the window was animating.
2232 this.withoutSizeTransitions( function () {
2233 var oldHeight = frameStyleObj.height,
2234 oldPosition = bodyStyleObj.position;
2235 frameStyleObj.height = '1px';
2236 // Force body to resize to new width
2237 bodyStyleObj.position = 'relative';
2238 bodyHeight = win.getBodyHeight();
2239 frameStyleObj.height = oldHeight;
2240 bodyStyleObj.position = oldPosition;
2241 } );
2242
2243 return (
2244 // Add buffer for border
2245 ( this.$frame.outerHeight() - this.$frame.innerHeight() ) +
2246 // Use combined heights of children
2247 ( this.$head.outerHeight( true ) + bodyHeight + this.$foot.outerHeight( true ) )
2248 );
2249 };
2250
2251 /**
2252 * Get the height of the window body.
2253 *
2254 * To get the height of the full window contents (the window body, head, and foot together),
2255 * use #getContentHeight.
2256 *
2257 * When this function is called, the window will temporarily have been resized
2258 * to height=1px, so .scrollHeight measurements can be taken accurately.
2259 *
2260 * @return {number} Height of the window body in pixels
2261 */
2262 OO.ui.Window.prototype.getBodyHeight = function () {
2263 return this.$body[ 0 ].scrollHeight;
2264 };
2265
2266 /**
2267 * Get the directionality of the frame (right-to-left or left-to-right).
2268 *
2269 * @return {string} Directionality: `'ltr'` or `'rtl'`
2270 */
2271 OO.ui.Window.prototype.getDir = function () {
2272 return OO.ui.Element.static.getDir( this.$content ) || 'ltr';
2273 };
2274
2275 /**
2276 * Get the 'setup' process.
2277 *
2278 * The setup process is used to set up a window for use in a particular context,
2279 * based on the `data` argument. This method is called during the opening phase of the window’s
2280 * lifecycle.
2281 *
2282 * Override this method to add additional steps to the ‘setup’ process the parent method provides
2283 * using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next} methods
2284 * of OO.ui.Process.
2285 *
2286 * To add window content that persists between openings, you may wish to use the #initialize method
2287 * instead.
2288 *
2289 * @abstract
2290 * @param {Object} [data] Window opening data
2291 * @return {OO.ui.Process} Setup process
2292 */
2293 OO.ui.Window.prototype.getSetupProcess = function () {
2294 return new OO.ui.Process();
2295 };
2296
2297 /**
2298 * Get the ‘ready’ process.
2299 *
2300 * The ready process is used to ready a window for use in a particular
2301 * context, based on the `data` argument. This method is called during the opening phase of
2302 * the window’s lifecycle, after the window has been {@link #getSetupProcess setup}.
2303 *
2304 * Override this method to add additional steps to the ‘ready’ process the parent method
2305 * provides using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next}
2306 * methods of OO.ui.Process.
2307 *
2308 * @abstract
2309 * @param {Object} [data] Window opening data
2310 * @return {OO.ui.Process} Ready process
2311 */
2312 OO.ui.Window.prototype.getReadyProcess = function () {
2313 return new OO.ui.Process();
2314 };
2315
2316 /**
2317 * Get the 'hold' process.
2318 *
2319 * The hold proccess is used to keep a window from being used in a particular context,
2320 * based on the `data` argument. This method is called during the closing phase of the window’s
2321 * lifecycle.
2322 *
2323 * Override this method to add additional steps to the 'hold' process the parent method provides
2324 * using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next} methods
2325 * of OO.ui.Process.
2326 *
2327 * @abstract
2328 * @param {Object} [data] Window closing data
2329 * @return {OO.ui.Process} Hold process
2330 */
2331 OO.ui.Window.prototype.getHoldProcess = function () {
2332 return new OO.ui.Process();
2333 };
2334
2335 /**
2336 * Get the ‘teardown’ process.
2337 *
2338 * The teardown process is used to teardown a window after use. During teardown,
2339 * user interactions within the window are conveyed and the window is closed, based on the `data`
2340 * argument. This method is called during the closing phase of the window’s lifecycle.
2341 *
2342 * Override this method to add additional steps to the ‘teardown’ process the parent method provides
2343 * using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next} methods
2344 * of OO.ui.Process.
2345 *
2346 * @abstract
2347 * @param {Object} [data] Window closing data
2348 * @return {OO.ui.Process} Teardown process
2349 */
2350 OO.ui.Window.prototype.getTeardownProcess = function () {
2351 return new OO.ui.Process();
2352 };
2353
2354 /**
2355 * Set the window manager.
2356 *
2357 * This will cause the window to initialize. Calling it more than once will cause an error.
2358 *
2359 * @param {OO.ui.WindowManager} manager Manager for this window
2360 * @throws {Error} An error is thrown if the method is called more than once
2361 * @chainable
2362 */
2363 OO.ui.Window.prototype.setManager = function ( manager ) {
2364 if ( this.manager ) {
2365 throw new Error( 'Cannot set window manager, window already has a manager' );
2366 }
2367
2368 this.manager = manager;
2369 this.initialize();
2370
2371 return this;
2372 };
2373
2374 /**
2375 * Set the window size by symbolic name (e.g., 'small' or 'medium')
2376 *
2377 * @param {string} size Symbolic name of size: `small`, `medium`, `large`, `larger` or
2378 * `full`
2379 * @chainable
2380 */
2381 OO.ui.Window.prototype.setSize = function ( size ) {
2382 this.size = size;
2383 this.updateSize();
2384 return this;
2385 };
2386
2387 /**
2388 * Update the window size.
2389 *
2390 * @throws {Error} An error is thrown if the window is not attached to a window manager
2391 * @chainable
2392 */
2393 OO.ui.Window.prototype.updateSize = function () {
2394 if ( !this.manager ) {
2395 throw new Error( 'Cannot update window size, must be attached to a manager' );
2396 }
2397
2398 this.manager.updateWindowSize( this );
2399
2400 return this;
2401 };
2402
2403 /**
2404 * Set window dimensions. This method is called by the {@link OO.ui.WindowManager window manager}
2405 * when the window is opening. In general, setDimensions should not be called directly.
2406 *
2407 * To set the size of the window, use the #setSize method.
2408 *
2409 * @param {Object} dim CSS dimension properties
2410 * @param {string|number} [dim.width] Width
2411 * @param {string|number} [dim.minWidth] Minimum width
2412 * @param {string|number} [dim.maxWidth] Maximum width
2413 * @param {string|number} [dim.width] Height, omit to set based on height of contents
2414 * @param {string|number} [dim.minWidth] Minimum height
2415 * @param {string|number} [dim.maxWidth] Maximum height
2416 * @chainable
2417 */
2418 OO.ui.Window.prototype.setDimensions = function ( dim ) {
2419 var height,
2420 win = this,
2421 styleObj = this.$frame[ 0 ].style;
2422
2423 // Calculate the height we need to set using the correct width
2424 if ( dim.height === undefined ) {
2425 this.withoutSizeTransitions( function () {
2426 var oldWidth = styleObj.width;
2427 win.$frame.css( 'width', dim.width || '' );
2428 height = win.getContentHeight();
2429 styleObj.width = oldWidth;
2430 } );
2431 } else {
2432 height = dim.height;
2433 }
2434
2435 this.$frame.css( {
2436 width: dim.width || '',
2437 minWidth: dim.minWidth || '',
2438 maxWidth: dim.maxWidth || '',
2439 height: height || '',
2440 minHeight: dim.minHeight || '',
2441 maxHeight: dim.maxHeight || ''
2442 } );
2443
2444 return this;
2445 };
2446
2447 /**
2448 * Initialize window contents.
2449 *
2450 * Before the window is opened for the first time, #initialize is called so that content that
2451 * persists between openings can be added to the window.
2452 *
2453 * To set up a window with new content each time the window opens, use #getSetupProcess.
2454 *
2455 * @throws {Error} An error is thrown if the window is not attached to a window manager
2456 * @chainable
2457 */
2458 OO.ui.Window.prototype.initialize = function () {
2459 if ( !this.manager ) {
2460 throw new Error( 'Cannot initialize window, must be attached to a manager' );
2461 }
2462
2463 // Properties
2464 this.$head = $( '<div>' );
2465 this.$body = $( '<div>' );
2466 this.$foot = $( '<div>' );
2467 this.$document = $( this.getElementDocument() );
2468
2469 // Events
2470 this.$element.on( 'mousedown', this.onMouseDown.bind( this ) );
2471
2472 // Initialization
2473 this.$head.addClass( 'oo-ui-window-head' );
2474 this.$body.addClass( 'oo-ui-window-body' );
2475 this.$foot.addClass( 'oo-ui-window-foot' );
2476 this.$content.append( this.$head, this.$body, this.$foot );
2477
2478 return this;
2479 };
2480
2481 /**
2482 * Open the window.
2483 *
2484 * This method is a wrapper around a call to the window manager’s {@link OO.ui.WindowManager#openWindow openWindow}
2485 * method, which returns a promise resolved when the window is done opening.
2486 *
2487 * To customize the window each time it opens, use #getSetupProcess or #getReadyProcess.
2488 *
2489 * @param {Object} [data] Window opening data
2490 * @return {jQuery.Promise} Promise resolved with a value when the window is opened, or rejected
2491 * if the window fails to open. When the promise is resolved successfully, the first argument of the
2492 * value is a new promise, which is resolved when the window begins closing.
2493 * @throws {Error} An error is thrown if the window is not attached to a window manager
2494 */
2495 OO.ui.Window.prototype.open = function ( data ) {
2496 if ( !this.manager ) {
2497 throw new Error( 'Cannot open window, must be attached to a manager' );
2498 }
2499
2500 return this.manager.openWindow( this, data );
2501 };
2502
2503 /**
2504 * Close the window.
2505 *
2506 * This method is a wrapper around a call to the window
2507 * manager’s {@link OO.ui.WindowManager#closeWindow closeWindow} method,
2508 * which returns a closing promise resolved when the window is done closing.
2509 *
2510 * The window's #getHoldProcess and #getTeardownProcess methods are called during the closing
2511 * phase of the window’s lifecycle and can be used to specify closing behavior each time
2512 * the window closes.
2513 *
2514 * @param {Object} [data] Window closing data
2515 * @return {jQuery.Promise} Promise resolved when window is closed
2516 * @throws {Error} An error is thrown if the window is not attached to a window manager
2517 */
2518 OO.ui.Window.prototype.close = function ( data ) {
2519 if ( !this.manager ) {
2520 throw new Error( 'Cannot close window, must be attached to a manager' );
2521 }
2522
2523 return this.manager.closeWindow( this, data );
2524 };
2525
2526 /**
2527 * Setup window.
2528 *
2529 * This is called by OO.ui.WindowManager during window opening, and should not be called directly
2530 * by other systems.
2531 *
2532 * @param {Object} [data] Window opening data
2533 * @return {jQuery.Promise} Promise resolved when window is setup
2534 */
2535 OO.ui.Window.prototype.setup = function ( data ) {
2536 var win = this,
2537 deferred = $.Deferred();
2538
2539 this.toggle( true );
2540
2541 this.getSetupProcess( data ).execute().done( function () {
2542 // Force redraw by asking the browser to measure the elements' widths
2543 win.$element.addClass( 'oo-ui-window-active oo-ui-window-setup' ).width();
2544 win.$content.addClass( 'oo-ui-window-content-setup' ).width();
2545 deferred.resolve();
2546 } );
2547
2548 return deferred.promise();
2549 };
2550
2551 /**
2552 * Ready window.
2553 *
2554 * This is called by OO.ui.WindowManager during window opening, and should not be called directly
2555 * by other systems.
2556 *
2557 * @param {Object} [data] Window opening data
2558 * @return {jQuery.Promise} Promise resolved when window is ready
2559 */
2560 OO.ui.Window.prototype.ready = function ( data ) {
2561 var win = this,
2562 deferred = $.Deferred();
2563
2564 this.$content.focus();
2565 this.getReadyProcess( data ).execute().done( function () {
2566 // Force redraw by asking the browser to measure the elements' widths
2567 win.$element.addClass( 'oo-ui-window-ready' ).width();
2568 win.$content.addClass( 'oo-ui-window-content-ready' ).width();
2569 deferred.resolve();
2570 } );
2571
2572 return deferred.promise();
2573 };
2574
2575 /**
2576 * Hold window.
2577 *
2578 * This is called by OO.ui.WindowManager during window closing, and should not be called directly
2579 * by other systems.
2580 *
2581 * @param {Object} [data] Window closing data
2582 * @return {jQuery.Promise} Promise resolved when window is held
2583 */
2584 OO.ui.Window.prototype.hold = function ( data ) {
2585 var win = this,
2586 deferred = $.Deferred();
2587
2588 this.getHoldProcess( data ).execute().done( function () {
2589 // Get the focused element within the window's content
2590 var $focus = win.$content.find( OO.ui.Element.static.getDocument( win.$content ).activeElement );
2591
2592 // Blur the focused element
2593 if ( $focus.length ) {
2594 $focus[ 0 ].blur();
2595 }
2596
2597 // Force redraw by asking the browser to measure the elements' widths
2598 win.$element.removeClass( 'oo-ui-window-ready' ).width();
2599 win.$content.removeClass( 'oo-ui-window-content-ready' ).width();
2600 deferred.resolve();
2601 } );
2602
2603 return deferred.promise();
2604 };
2605
2606 /**
2607 * Teardown window.
2608 *
2609 * This is called by OO.ui.WindowManager during window closing, and should not be called directly
2610 * by other systems.
2611 *
2612 * @param {Object} [data] Window closing data
2613 * @return {jQuery.Promise} Promise resolved when window is torn down
2614 */
2615 OO.ui.Window.prototype.teardown = function ( data ) {
2616 var win = this;
2617
2618 return this.getTeardownProcess( data ).execute()
2619 .done( function () {
2620 // Force redraw by asking the browser to measure the elements' widths
2621 win.$element.removeClass( 'oo-ui-window-active oo-ui-window-setup' ).width();
2622 win.$content.removeClass( 'oo-ui-window-content-setup' ).width();
2623 win.toggle( false );
2624 } );
2625 };
2626
2627 /**
2628 * The Dialog class serves as the base class for the other types of dialogs.
2629 * Unless extended to include controls, the rendered dialog box is a simple window
2630 * that users can close by hitting the ‘Esc’ key. Dialog windows are used with OO.ui.WindowManager,
2631 * which opens, closes, and controls the presentation of the window. See the
2632 * [OOjs UI documentation on MediaWiki] [1] for more information.
2633 *
2634 * @example
2635 * // A simple dialog window.
2636 * function MyDialog( config ) {
2637 * MyDialog.parent.call( this, config );
2638 * }
2639 * OO.inheritClass( MyDialog, OO.ui.Dialog );
2640 * MyDialog.prototype.initialize = function () {
2641 * MyDialog.parent.prototype.initialize.call( this );
2642 * this.content = new OO.ui.PanelLayout( { padded: true, expanded: false } );
2643 * this.content.$element.append( '<p>A simple dialog window. Press \'Esc\' to close.</p>' );
2644 * this.$body.append( this.content.$element );
2645 * };
2646 * MyDialog.prototype.getBodyHeight = function () {
2647 * return this.content.$element.outerHeight( true );
2648 * };
2649 * var myDialog = new MyDialog( {
2650 * size: 'medium'
2651 * } );
2652 * // Create and append a window manager, which opens and closes the window.
2653 * var windowManager = new OO.ui.WindowManager();
2654 * $( 'body' ).append( windowManager.$element );
2655 * windowManager.addWindows( [ myDialog ] );
2656 * // Open the window!
2657 * windowManager.openWindow( myDialog );
2658 *
2659 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Dialogs
2660 *
2661 * @abstract
2662 * @class
2663 * @extends OO.ui.Window
2664 * @mixins OO.ui.mixin.PendingElement
2665 *
2666 * @constructor
2667 * @param {Object} [config] Configuration options
2668 */
2669 OO.ui.Dialog = function OoUiDialog( config ) {
2670 // Parent constructor
2671 OO.ui.Dialog.parent.call( this, config );
2672
2673 // Mixin constructors
2674 OO.ui.mixin.PendingElement.call( this );
2675
2676 // Properties
2677 this.actions = new OO.ui.ActionSet();
2678 this.attachedActions = [];
2679 this.currentAction = null;
2680 this.onDocumentKeyDownHandler = this.onDocumentKeyDown.bind( this );
2681
2682 // Events
2683 this.actions.connect( this, {
2684 click: 'onActionClick',
2685 resize: 'onActionResize',
2686 change: 'onActionsChange'
2687 } );
2688
2689 // Initialization
2690 this.$element
2691 .addClass( 'oo-ui-dialog' )
2692 .attr( 'role', 'dialog' );
2693 };
2694
2695 /* Setup */
2696
2697 OO.inheritClass( OO.ui.Dialog, OO.ui.Window );
2698 OO.mixinClass( OO.ui.Dialog, OO.ui.mixin.PendingElement );
2699
2700 /* Static Properties */
2701
2702 /**
2703 * Symbolic name of dialog.
2704 *
2705 * The dialog class must have a symbolic name in order to be registered with OO.Factory.
2706 * Please see the [OOjs UI documentation on MediaWiki] [3] for more information.
2707 *
2708 * [3]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
2709 *
2710 * @abstract
2711 * @static
2712 * @inheritable
2713 * @property {string}
2714 */
2715 OO.ui.Dialog.static.name = '';
2716
2717 /**
2718 * The dialog title.
2719 *
2720 * The title can be specified as a plaintext string, a {@link OO.ui.mixin.LabelElement Label} node, or a function
2721 * that will produce a Label node or string. The title can also be specified with data passed to the
2722 * constructor (see #getSetupProcess). In this case, the static value will be overriden.
2723 *
2724 * @abstract
2725 * @static
2726 * @inheritable
2727 * @property {jQuery|string|Function}
2728 */
2729 OO.ui.Dialog.static.title = '';
2730
2731 /**
2732 * An array of configured {@link OO.ui.ActionWidget action widgets}.
2733 *
2734 * Actions can also be specified with data passed to the constructor (see #getSetupProcess). In this case, the static
2735 * value will be overriden.
2736 *
2737 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Action_sets
2738 *
2739 * @static
2740 * @inheritable
2741 * @property {Object[]}
2742 */
2743 OO.ui.Dialog.static.actions = [];
2744
2745 /**
2746 * Close the dialog when the 'Esc' key is pressed.
2747 *
2748 * @static
2749 * @abstract
2750 * @inheritable
2751 * @property {boolean}
2752 */
2753 OO.ui.Dialog.static.escapable = true;
2754
2755 /* Methods */
2756
2757 /**
2758 * Handle frame document key down events.
2759 *
2760 * @private
2761 * @param {jQuery.Event} e Key down event
2762 */
2763 OO.ui.Dialog.prototype.onDocumentKeyDown = function ( e ) {
2764 if ( e.which === OO.ui.Keys.ESCAPE ) {
2765 this.close();
2766 e.preventDefault();
2767 e.stopPropagation();
2768 }
2769 };
2770
2771 /**
2772 * Handle action resized events.
2773 *
2774 * @private
2775 * @param {OO.ui.ActionWidget} action Action that was resized
2776 */
2777 OO.ui.Dialog.prototype.onActionResize = function () {
2778 // Override in subclass
2779 };
2780
2781 /**
2782 * Handle action click events.
2783 *
2784 * @private
2785 * @param {OO.ui.ActionWidget} action Action that was clicked
2786 */
2787 OO.ui.Dialog.prototype.onActionClick = function ( action ) {
2788 if ( !this.isPending() ) {
2789 this.executeAction( action.getAction() );
2790 }
2791 };
2792
2793 /**
2794 * Handle actions change event.
2795 *
2796 * @private
2797 */
2798 OO.ui.Dialog.prototype.onActionsChange = function () {
2799 this.detachActions();
2800 if ( !this.isClosing() ) {
2801 this.attachActions();
2802 }
2803 };
2804
2805 /**
2806 * Get the set of actions used by the dialog.
2807 *
2808 * @return {OO.ui.ActionSet}
2809 */
2810 OO.ui.Dialog.prototype.getActions = function () {
2811 return this.actions;
2812 };
2813
2814 /**
2815 * Get a process for taking action.
2816 *
2817 * When you override this method, you can create a new OO.ui.Process and return it, or add additional
2818 * accept steps to the process the parent method provides using the {@link OO.ui.Process#first 'first'}
2819 * and {@link OO.ui.Process#next 'next'} methods of OO.ui.Process.
2820 *
2821 * @abstract
2822 * @param {string} [action] Symbolic name of action
2823 * @return {OO.ui.Process} Action process
2824 */
2825 OO.ui.Dialog.prototype.getActionProcess = function ( action ) {
2826 return new OO.ui.Process()
2827 .next( function () {
2828 if ( !action ) {
2829 // An empty action always closes the dialog without data, which should always be
2830 // safe and make no changes
2831 this.close();
2832 }
2833 }, this );
2834 };
2835
2836 /**
2837 * @inheritdoc
2838 *
2839 * @param {Object} [data] Dialog opening data
2840 * @param {jQuery|string|Function|null} [data.title] Dialog title, omit to use
2841 * the {@link #static-title static title}
2842 * @param {Object[]} [data.actions] List of configuration options for each
2843 * {@link OO.ui.ActionWidget action widget}, omit to use {@link #static-actions static actions}.
2844 */
2845 OO.ui.Dialog.prototype.getSetupProcess = function ( data ) {
2846 data = data || {};
2847
2848 // Parent method
2849 return OO.ui.Dialog.parent.prototype.getSetupProcess.call( this, data )
2850 .next( function () {
2851 var config = this.constructor.static,
2852 actions = data.actions !== undefined ? data.actions : config.actions;
2853
2854 this.title.setLabel(
2855 data.title !== undefined ? data.title : this.constructor.static.title
2856 );
2857 this.actions.add( this.getActionWidgets( actions ) );
2858
2859 if ( this.constructor.static.escapable ) {
2860 this.$document.on( 'keydown', this.onDocumentKeyDownHandler );
2861 }
2862 }, this );
2863 };
2864
2865 /**
2866 * @inheritdoc
2867 */
2868 OO.ui.Dialog.prototype.getTeardownProcess = function ( data ) {
2869 // Parent method
2870 return OO.ui.Dialog.parent.prototype.getTeardownProcess.call( this, data )
2871 .first( function () {
2872 if ( this.constructor.static.escapable ) {
2873 this.$document.off( 'keydown', this.onDocumentKeyDownHandler );
2874 }
2875
2876 this.actions.clear();
2877 this.currentAction = null;
2878 }, this );
2879 };
2880
2881 /**
2882 * @inheritdoc
2883 */
2884 OO.ui.Dialog.prototype.initialize = function () {
2885 // Parent method
2886 OO.ui.Dialog.parent.prototype.initialize.call( this );
2887
2888 var titleId = OO.ui.generateElementId();
2889
2890 // Properties
2891 this.title = new OO.ui.LabelWidget( {
2892 id: titleId
2893 } );
2894
2895 // Initialization
2896 this.$content.addClass( 'oo-ui-dialog-content' );
2897 this.$element.attr( 'aria-labelledby', titleId );
2898 this.setPendingElement( this.$head );
2899 };
2900
2901 /**
2902 * Get action widgets from a list of configs
2903 *
2904 * @param {Object[]} actions Action widget configs
2905 * @return {OO.ui.ActionWidget[]} Action widgets
2906 */
2907 OO.ui.Dialog.prototype.getActionWidgets = function ( actions ) {
2908 var i, len, widgets = [];
2909 for ( i = 0, len = actions.length; i < len; i++ ) {
2910 widgets.push(
2911 new OO.ui.ActionWidget( actions[ i ] )
2912 );
2913 }
2914 return widgets;
2915 };
2916
2917 /**
2918 * Attach action actions.
2919 *
2920 * @protected
2921 */
2922 OO.ui.Dialog.prototype.attachActions = function () {
2923 // Remember the list of potentially attached actions
2924 this.attachedActions = this.actions.get();
2925 };
2926
2927 /**
2928 * Detach action actions.
2929 *
2930 * @protected
2931 * @chainable
2932 */
2933 OO.ui.Dialog.prototype.detachActions = function () {
2934 var i, len;
2935
2936 // Detach all actions that may have been previously attached
2937 for ( i = 0, len = this.attachedActions.length; i < len; i++ ) {
2938 this.attachedActions[ i ].$element.detach();
2939 }
2940 this.attachedActions = [];
2941 };
2942
2943 /**
2944 * Execute an action.
2945 *
2946 * @param {string} action Symbolic name of action to execute
2947 * @return {jQuery.Promise} Promise resolved when action completes, rejected if it fails
2948 */
2949 OO.ui.Dialog.prototype.executeAction = function ( action ) {
2950 this.pushPending();
2951 this.currentAction = action;
2952 return this.getActionProcess( action ).execute()
2953 .always( this.popPending.bind( this ) );
2954 };
2955
2956 /**
2957 * Window managers are used to open and close {@link OO.ui.Window windows} and control their presentation.
2958 * Managed windows are mutually exclusive. If a new window is opened while a current window is opening
2959 * or is opened, the current window will be closed and any ongoing {@link OO.ui.Process process} will be cancelled. Windows
2960 * themselves are persistent and—rather than being torn down when closed—can be repopulated with the
2961 * pertinent data and reused.
2962 *
2963 * Over the lifecycle of a window, the window manager makes available three promises: `opening`,
2964 * `opened`, and `closing`, which represent the primary stages of the cycle:
2965 *
2966 * **Opening**: the opening stage begins when the window manager’s #openWindow or a window’s
2967 * {@link OO.ui.Window#open open} method is used, and the window manager begins to open the window.
2968 *
2969 * - an `opening` event is emitted with an `opening` promise
2970 * - the #getSetupDelay method is called and the returned value is used to time a pause in execution before
2971 * the window’s {@link OO.ui.Window#getSetupProcess getSetupProcess} method is called on the
2972 * window and its result executed
2973 * - a `setup` progress notification is emitted from the `opening` promise
2974 * - the #getReadyDelay method is called the returned value is used to time a pause in execution before
2975 * the window’s {@link OO.ui.Window#getReadyProcess getReadyProcess} method is called on the
2976 * window and its result executed
2977 * - a `ready` progress notification is emitted from the `opening` promise
2978 * - the `opening` promise is resolved with an `opened` promise
2979 *
2980 * **Opened**: the window is now open.
2981 *
2982 * **Closing**: the closing stage begins when the window manager's #closeWindow or the
2983 * window's {@link OO.ui.Window#close close} methods is used, and the window manager begins
2984 * to close the window.
2985 *
2986 * - the `opened` promise is resolved with `closing` promise and a `closing` event is emitted
2987 * - the #getHoldDelay method is called and the returned value is used to time a pause in execution before
2988 * the window's {@link OO.ui.Window#getHoldProcess getHoldProces} method is called on the
2989 * window and its result executed
2990 * - a `hold` progress notification is emitted from the `closing` promise
2991 * - the #getTeardownDelay() method is called and the returned value is used to time a pause in execution before
2992 * the window's {@link OO.ui.Window#getTeardownProcess getTeardownProcess} method is called on the
2993 * window and its result executed
2994 * - a `teardown` progress notification is emitted from the `closing` promise
2995 * - the `closing` promise is resolved. The window is now closed
2996 *
2997 * See the [OOjs UI documentation on MediaWiki][1] for more information.
2998 *
2999 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
3000 *
3001 * @class
3002 * @extends OO.ui.Element
3003 * @mixins OO.EventEmitter
3004 *
3005 * @constructor
3006 * @param {Object} [config] Configuration options
3007 * @cfg {OO.Factory} [factory] Window factory to use for automatic instantiation
3008 * Note that window classes that are instantiated with a factory must have
3009 * a {@link OO.ui.Dialog#static-name static name} property that specifies a symbolic name.
3010 * @cfg {boolean} [modal=true] Prevent interaction outside the dialog
3011 */
3012 OO.ui.WindowManager = function OoUiWindowManager( config ) {
3013 // Configuration initialization
3014 config = config || {};
3015
3016 // Parent constructor
3017 OO.ui.WindowManager.parent.call( this, config );
3018
3019 // Mixin constructors
3020 OO.EventEmitter.call( this );
3021
3022 // Properties
3023 this.factory = config.factory;
3024 this.modal = config.modal === undefined || !!config.modal;
3025 this.windows = {};
3026 this.opening = null;
3027 this.opened = null;
3028 this.closing = null;
3029 this.preparingToOpen = null;
3030 this.preparingToClose = null;
3031 this.currentWindow = null;
3032 this.globalEvents = false;
3033 this.$ariaHidden = null;
3034 this.onWindowResizeTimeout = null;
3035 this.onWindowResizeHandler = this.onWindowResize.bind( this );
3036 this.afterWindowResizeHandler = this.afterWindowResize.bind( this );
3037
3038 // Initialization
3039 this.$element
3040 .addClass( 'oo-ui-windowManager' )
3041 .toggleClass( 'oo-ui-windowManager-modal', this.modal );
3042 };
3043
3044 /* Setup */
3045
3046 OO.inheritClass( OO.ui.WindowManager, OO.ui.Element );
3047 OO.mixinClass( OO.ui.WindowManager, OO.EventEmitter );
3048
3049 /* Events */
3050
3051 /**
3052 * An 'opening' event is emitted when the window begins to be opened.
3053 *
3054 * @event opening
3055 * @param {OO.ui.Window} win Window that's being opened
3056 * @param {jQuery.Promise} opening An `opening` promise resolved with a value when the window is opened successfully.
3057 * When the `opening` promise is resolved, the first argument of the value is an 'opened' promise, the second argument
3058 * is the opening data. The `opening` promise emits `setup` and `ready` notifications when those processes are complete.
3059 * @param {Object} data Window opening data
3060 */
3061
3062 /**
3063 * A 'closing' event is emitted when the window begins to be closed.
3064 *
3065 * @event closing
3066 * @param {OO.ui.Window} win Window that's being closed
3067 * @param {jQuery.Promise} closing A `closing` promise is resolved with a value when the window
3068 * is closed successfully. The promise emits `hold` and `teardown` notifications when those
3069 * processes are complete. When the `closing` promise is resolved, the first argument of its value
3070 * is the closing data.
3071 * @param {Object} data Window closing data
3072 */
3073
3074 /**
3075 * A 'resize' event is emitted when a window is resized.
3076 *
3077 * @event resize
3078 * @param {OO.ui.Window} win Window that was resized
3079 */
3080
3081 /* Static Properties */
3082
3083 /**
3084 * Map of the symbolic name of each window size and its CSS properties.
3085 *
3086 * @static
3087 * @inheritable
3088 * @property {Object}
3089 */
3090 OO.ui.WindowManager.static.sizes = {
3091 small: {
3092 width: 300
3093 },
3094 medium: {
3095 width: 500
3096 },
3097 large: {
3098 width: 700
3099 },
3100 larger: {
3101 width: 900
3102 },
3103 full: {
3104 // These can be non-numeric because they are never used in calculations
3105 width: '100%',
3106 height: '100%'
3107 }
3108 };
3109
3110 /**
3111 * Symbolic name of the default window size.
3112 *
3113 * The default size is used if the window's requested size is not recognized.
3114 *
3115 * @static
3116 * @inheritable
3117 * @property {string}
3118 */
3119 OO.ui.WindowManager.static.defaultSize = 'medium';
3120
3121 /* Methods */
3122
3123 /**
3124 * Handle window resize events.
3125 *
3126 * @private
3127 * @param {jQuery.Event} e Window resize event
3128 */
3129 OO.ui.WindowManager.prototype.onWindowResize = function () {
3130 clearTimeout( this.onWindowResizeTimeout );
3131 this.onWindowResizeTimeout = setTimeout( this.afterWindowResizeHandler, 200 );
3132 };
3133
3134 /**
3135 * Handle window resize events.
3136 *
3137 * @private
3138 * @param {jQuery.Event} e Window resize event
3139 */
3140 OO.ui.WindowManager.prototype.afterWindowResize = function () {
3141 if ( this.currentWindow ) {
3142 this.updateWindowSize( this.currentWindow );
3143 }
3144 };
3145
3146 /**
3147 * Check if window is opening.
3148 *
3149 * @return {boolean} Window is opening
3150 */
3151 OO.ui.WindowManager.prototype.isOpening = function ( win ) {
3152 return win === this.currentWindow && !!this.opening && this.opening.state() === 'pending';
3153 };
3154
3155 /**
3156 * Check if window is closing.
3157 *
3158 * @return {boolean} Window is closing
3159 */
3160 OO.ui.WindowManager.prototype.isClosing = function ( win ) {
3161 return win === this.currentWindow && !!this.closing && this.closing.state() === 'pending';
3162 };
3163
3164 /**
3165 * Check if window is opened.
3166 *
3167 * @return {boolean} Window is opened
3168 */
3169 OO.ui.WindowManager.prototype.isOpened = function ( win ) {
3170 return win === this.currentWindow && !!this.opened && this.opened.state() === 'pending';
3171 };
3172
3173 /**
3174 * Check if a window is being managed.
3175 *
3176 * @param {OO.ui.Window} win Window to check
3177 * @return {boolean} Window is being managed
3178 */
3179 OO.ui.WindowManager.prototype.hasWindow = function ( win ) {
3180 var name;
3181
3182 for ( name in this.windows ) {
3183 if ( this.windows[ name ] === win ) {
3184 return true;
3185 }
3186 }
3187
3188 return false;
3189 };
3190
3191 /**
3192 * Get the number of milliseconds to wait after opening begins before executing the ‘setup’ process.
3193 *
3194 * @param {OO.ui.Window} win Window being opened
3195 * @param {Object} [data] Window opening data
3196 * @return {number} Milliseconds to wait
3197 */
3198 OO.ui.WindowManager.prototype.getSetupDelay = function () {
3199 return 0;
3200 };
3201
3202 /**
3203 * Get the number of milliseconds to wait after setup has finished before executing the ‘ready’ process.
3204 *
3205 * @param {OO.ui.Window} win Window being opened
3206 * @param {Object} [data] Window opening data
3207 * @return {number} Milliseconds to wait
3208 */
3209 OO.ui.WindowManager.prototype.getReadyDelay = function () {
3210 return 0;
3211 };
3212
3213 /**
3214 * Get the number of milliseconds to wait after closing has begun before executing the 'hold' process.
3215 *
3216 * @param {OO.ui.Window} win Window being closed
3217 * @param {Object} [data] Window closing data
3218 * @return {number} Milliseconds to wait
3219 */
3220 OO.ui.WindowManager.prototype.getHoldDelay = function () {
3221 return 0;
3222 };
3223
3224 /**
3225 * Get the number of milliseconds to wait after the ‘hold’ process has finished before
3226 * executing the ‘teardown’ process.
3227 *
3228 * @param {OO.ui.Window} win Window being closed
3229 * @param {Object} [data] Window closing data
3230 * @return {number} Milliseconds to wait
3231 */
3232 OO.ui.WindowManager.prototype.getTeardownDelay = function () {
3233 return this.modal ? 250 : 0;
3234 };
3235
3236 /**
3237 * Get a window by its symbolic name.
3238 *
3239 * If the window is not yet instantiated and its symbolic name is recognized by a factory, it will be
3240 * instantiated and added to the window manager automatically. Please see the [OOjs UI documentation on MediaWiki][3]
3241 * for more information about using factories.
3242 * [3]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
3243 *
3244 * @param {string} name Symbolic name of the window
3245 * @return {jQuery.Promise} Promise resolved with matching window, or rejected with an OO.ui.Error
3246 * @throws {Error} An error is thrown if the symbolic name is not recognized by the factory.
3247 * @throws {Error} An error is thrown if the named window is not recognized as a managed window.
3248 */
3249 OO.ui.WindowManager.prototype.getWindow = function ( name ) {
3250 var deferred = $.Deferred(),
3251 win = this.windows[ name ];
3252
3253 if ( !( win instanceof OO.ui.Window ) ) {
3254 if ( this.factory ) {
3255 if ( !this.factory.lookup( name ) ) {
3256 deferred.reject( new OO.ui.Error(
3257 'Cannot auto-instantiate window: symbolic name is unrecognized by the factory'
3258 ) );
3259 } else {
3260 win = this.factory.create( name );
3261 this.addWindows( [ win ] );
3262 deferred.resolve( win );
3263 }
3264 } else {
3265 deferred.reject( new OO.ui.Error(
3266 'Cannot get unmanaged window: symbolic name unrecognized as a managed window'
3267 ) );
3268 }
3269 } else {
3270 deferred.resolve( win );
3271 }
3272
3273 return deferred.promise();
3274 };
3275
3276 /**
3277 * Get current window.
3278 *
3279 * @return {OO.ui.Window|null} Currently opening/opened/closing window
3280 */
3281 OO.ui.WindowManager.prototype.getCurrentWindow = function () {
3282 return this.currentWindow;
3283 };
3284
3285 /**
3286 * Open a window.
3287 *
3288 * @param {OO.ui.Window|string} win Window object or symbolic name of window to open
3289 * @param {Object} [data] Window opening data
3290 * @return {jQuery.Promise} An `opening` promise resolved when the window is done opening.
3291 * See {@link #event-opening 'opening' event} for more information about `opening` promises.
3292 * @fires opening
3293 */
3294 OO.ui.WindowManager.prototype.openWindow = function ( win, data ) {
3295 var manager = this,
3296 opening = $.Deferred();
3297
3298 // Argument handling
3299 if ( typeof win === 'string' ) {
3300 return this.getWindow( win ).then( function ( win ) {
3301 return manager.openWindow( win, data );
3302 } );
3303 }
3304
3305 // Error handling
3306 if ( !this.hasWindow( win ) ) {
3307 opening.reject( new OO.ui.Error(
3308 'Cannot open window: window is not attached to manager'
3309 ) );
3310 } else if ( this.preparingToOpen || this.opening || this.opened ) {
3311 opening.reject( new OO.ui.Error(
3312 'Cannot open window: another window is opening or open'
3313 ) );
3314 }
3315
3316 // Window opening
3317 if ( opening.state() !== 'rejected' ) {
3318 // If a window is currently closing, wait for it to complete
3319 this.preparingToOpen = $.when( this.closing );
3320 // Ensure handlers get called after preparingToOpen is set
3321 this.preparingToOpen.done( function () {
3322 if ( manager.modal ) {
3323 manager.toggleGlobalEvents( true );
3324 manager.toggleAriaIsolation( true );
3325 }
3326 manager.currentWindow = win;
3327 manager.opening = opening;
3328 manager.preparingToOpen = null;
3329 manager.emit( 'opening', win, opening, data );
3330 setTimeout( function () {
3331 win.setup( data ).then( function () {
3332 manager.updateWindowSize( win );
3333 manager.opening.notify( { state: 'setup' } );
3334 setTimeout( function () {
3335 win.ready( data ).then( function () {
3336 manager.opening.notify( { state: 'ready' } );
3337 manager.opening = null;
3338 manager.opened = $.Deferred();
3339 opening.resolve( manager.opened.promise(), data );
3340 } );
3341 }, manager.getReadyDelay() );
3342 } );
3343 }, manager.getSetupDelay() );
3344 } );
3345 }
3346
3347 return opening.promise();
3348 };
3349
3350 /**
3351 * Close a window.
3352 *
3353 * @param {OO.ui.Window|string} win Window object or symbolic name of window to close
3354 * @param {Object} [data] Window closing data
3355 * @return {jQuery.Promise} A `closing` promise resolved when the window is done closing.
3356 * See {@link #event-closing 'closing' event} for more information about closing promises.
3357 * @throws {Error} An error is thrown if the window is not managed by the window manager.
3358 * @fires closing
3359 */
3360 OO.ui.WindowManager.prototype.closeWindow = function ( win, data ) {
3361 var manager = this,
3362 closing = $.Deferred(),
3363 opened;
3364
3365 // Argument handling
3366 if ( typeof win === 'string' ) {
3367 win = this.windows[ win ];
3368 } else if ( !this.hasWindow( win ) ) {
3369 win = null;
3370 }
3371
3372 // Error handling
3373 if ( !win ) {
3374 closing.reject( new OO.ui.Error(
3375 'Cannot close window: window is not attached to manager'
3376 ) );
3377 } else if ( win !== this.currentWindow ) {
3378 closing.reject( new OO.ui.Error(
3379 'Cannot close window: window already closed with different data'
3380 ) );
3381 } else if ( this.preparingToClose || this.closing ) {
3382 closing.reject( new OO.ui.Error(
3383 'Cannot close window: window already closing with different data'
3384 ) );
3385 }
3386
3387 // Window closing
3388 if ( closing.state() !== 'rejected' ) {
3389 // If the window is currently opening, close it when it's done
3390 this.preparingToClose = $.when( this.opening );
3391 // Ensure handlers get called after preparingToClose is set
3392 this.preparingToClose.done( function () {
3393 manager.closing = closing;
3394 manager.preparingToClose = null;
3395 manager.emit( 'closing', win, closing, data );
3396 opened = manager.opened;
3397 manager.opened = null;
3398 opened.resolve( closing.promise(), data );
3399 setTimeout( function () {
3400 win.hold( data ).then( function () {
3401 closing.notify( { state: 'hold' } );
3402 setTimeout( function () {
3403 win.teardown( data ).then( function () {
3404 closing.notify( { state: 'teardown' } );
3405 if ( manager.modal ) {
3406 manager.toggleGlobalEvents( false );
3407 manager.toggleAriaIsolation( false );
3408 }
3409 manager.closing = null;
3410 manager.currentWindow = null;
3411 closing.resolve( data );
3412 } );
3413 }, manager.getTeardownDelay() );
3414 } );
3415 }, manager.getHoldDelay() );
3416 } );
3417 }
3418
3419 return closing.promise();
3420 };
3421
3422 /**
3423 * Add windows to the window manager.
3424 *
3425 * Windows can be added by reference, symbolic name, or explicitly defined symbolic names.
3426 * See the [OOjs ui documentation on MediaWiki] [2] for examples.
3427 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
3428 *
3429 * @param {Object.<string,OO.ui.Window>|OO.ui.Window[]} windows An array of window objects specified
3430 * by reference, symbolic name, or explicitly defined symbolic names.
3431 * @throws {Error} An error is thrown if a window is added by symbolic name, but has neither an
3432 * explicit nor a statically configured symbolic name.
3433 */
3434 OO.ui.WindowManager.prototype.addWindows = function ( windows ) {
3435 var i, len, win, name, list;
3436
3437 if ( Array.isArray( windows ) ) {
3438 // Convert to map of windows by looking up symbolic names from static configuration
3439 list = {};
3440 for ( i = 0, len = windows.length; i < len; i++ ) {
3441 name = windows[ i ].constructor.static.name;
3442 if ( typeof name !== 'string' ) {
3443 throw new Error( 'Cannot add window' );
3444 }
3445 list[ name ] = windows[ i ];
3446 }
3447 } else if ( OO.isPlainObject( windows ) ) {
3448 list = windows;
3449 }
3450
3451 // Add windows
3452 for ( name in list ) {
3453 win = list[ name ];
3454 this.windows[ name ] = win.toggle( false );
3455 this.$element.append( win.$element );
3456 win.setManager( this );
3457 }
3458 };
3459
3460 /**
3461 * Remove the specified windows from the windows manager.
3462 *
3463 * Windows will be closed before they are removed. If you wish to remove all windows, you may wish to use
3464 * the #clearWindows method instead. If you no longer need the window manager and want to ensure that it no
3465 * longer listens to events, use the #destroy method.
3466 *
3467 * @param {string[]} names Symbolic names of windows to remove
3468 * @return {jQuery.Promise} Promise resolved when window is closed and removed
3469 * @throws {Error} An error is thrown if the named windows are not managed by the window manager.
3470 */
3471 OO.ui.WindowManager.prototype.removeWindows = function ( names ) {
3472 var i, len, win, name, cleanupWindow,
3473 manager = this,
3474 promises = [],
3475 cleanup = function ( name, win ) {
3476 delete manager.windows[ name ];
3477 win.$element.detach();
3478 };
3479
3480 for ( i = 0, len = names.length; i < len; i++ ) {
3481 name = names[ i ];
3482 win = this.windows[ name ];
3483 if ( !win ) {
3484 throw new Error( 'Cannot remove window' );
3485 }
3486 cleanupWindow = cleanup.bind( null, name, win );
3487 promises.push( this.closeWindow( name ).then( cleanupWindow, cleanupWindow ) );
3488 }
3489
3490 return $.when.apply( $, promises );
3491 };
3492
3493 /**
3494 * Remove all windows from the window manager.
3495 *
3496 * Windows will be closed before they are removed. Note that the window manager, though not in use, will still
3497 * listen to events. If the window manager will not be used again, you may wish to use the #destroy method instead.
3498 * To remove just a subset of windows, use the #removeWindows method.
3499 *
3500 * @return {jQuery.Promise} Promise resolved when all windows are closed and removed
3501 */
3502 OO.ui.WindowManager.prototype.clearWindows = function () {
3503 return this.removeWindows( Object.keys( this.windows ) );
3504 };
3505
3506 /**
3507 * Set dialog size. In general, this method should not be called directly.
3508 *
3509 * Fullscreen mode will be used if the dialog is too wide to fit in the screen.
3510 *
3511 * @chainable
3512 */
3513 OO.ui.WindowManager.prototype.updateWindowSize = function ( win ) {
3514 // Bypass for non-current, and thus invisible, windows
3515 if ( win !== this.currentWindow ) {
3516 return;
3517 }
3518
3519 var isFullscreen = win.getSize() === 'full';
3520
3521 this.$element.toggleClass( 'oo-ui-windowManager-fullscreen', isFullscreen );
3522 this.$element.toggleClass( 'oo-ui-windowManager-floating', !isFullscreen );
3523 win.setDimensions( win.getSizeProperties() );
3524
3525 this.emit( 'resize', win );
3526
3527 return this;
3528 };
3529
3530 /**
3531 * Bind or unbind global events for scrolling.
3532 *
3533 * @private
3534 * @param {boolean} [on] Bind global events
3535 * @chainable
3536 */
3537 OO.ui.WindowManager.prototype.toggleGlobalEvents = function ( on ) {
3538 on = on === undefined ? !!this.globalEvents : !!on;
3539
3540 var scrollWidth, bodyMargin,
3541 $body = $( this.getElementDocument().body ),
3542 // We could have multiple window managers open so only modify
3543 // the body css at the bottom of the stack
3544 stackDepth = $body.data( 'windowManagerGlobalEvents' ) || 0 ;
3545
3546 if ( on ) {
3547 if ( !this.globalEvents ) {
3548 $( this.getElementWindow() ).on( {
3549 // Start listening for top-level window dimension changes
3550 'orientationchange resize': this.onWindowResizeHandler
3551 } );
3552 if ( stackDepth === 0 ) {
3553 scrollWidth = window.innerWidth - document.documentElement.clientWidth;
3554 bodyMargin = parseFloat( $body.css( 'margin-right' ) ) || 0;
3555 $body.css( {
3556 overflow: 'hidden',
3557 'margin-right': bodyMargin + scrollWidth
3558 } );
3559 }
3560 stackDepth++;
3561 this.globalEvents = true;
3562 }
3563 } else if ( this.globalEvents ) {
3564 $( this.getElementWindow() ).off( {
3565 // Stop listening for top-level window dimension changes
3566 'orientationchange resize': this.onWindowResizeHandler
3567 } );
3568 stackDepth--;
3569 if ( stackDepth === 0 ) {
3570 $body.css( {
3571 overflow: '',
3572 'margin-right': ''
3573 } );
3574 }
3575 this.globalEvents = false;
3576 }
3577 $body.data( 'windowManagerGlobalEvents', stackDepth );
3578
3579 return this;
3580 };
3581
3582 /**
3583 * Toggle screen reader visibility of content other than the window manager.
3584 *
3585 * @private
3586 * @param {boolean} [isolate] Make only the window manager visible to screen readers
3587 * @chainable
3588 */
3589 OO.ui.WindowManager.prototype.toggleAriaIsolation = function ( isolate ) {
3590 isolate = isolate === undefined ? !this.$ariaHidden : !!isolate;
3591
3592 if ( isolate ) {
3593 if ( !this.$ariaHidden ) {
3594 // Hide everything other than the window manager from screen readers
3595 this.$ariaHidden = $( 'body' )
3596 .children()
3597 .not( this.$element.parentsUntil( 'body' ).last() )
3598 .attr( 'aria-hidden', '' );
3599 }
3600 } else if ( this.$ariaHidden ) {
3601 // Restore screen reader visibility
3602 this.$ariaHidden.removeAttr( 'aria-hidden' );
3603 this.$ariaHidden = null;
3604 }
3605
3606 return this;
3607 };
3608
3609 /**
3610 * Destroy the window manager.
3611 *
3612 * Destroying the window manager ensures that it will no longer listen to events. If you would like to
3613 * continue using the window manager, but wish to remove all windows from it, use the #clearWindows method
3614 * instead.
3615 */
3616 OO.ui.WindowManager.prototype.destroy = function () {
3617 this.toggleGlobalEvents( false );
3618 this.toggleAriaIsolation( false );
3619 this.clearWindows();
3620 this.$element.remove();
3621 };
3622
3623 /**
3624 * Errors contain a required message (either a string or jQuery selection) that is used to describe what went wrong
3625 * in a {@link OO.ui.Process process}. The error's #recoverable and #warning configurations are used to customize the
3626 * appearance and functionality of the error interface.
3627 *
3628 * The basic error interface contains a formatted error message as well as two buttons: 'Dismiss' and 'Try again' (i.e., the error
3629 * is 'recoverable' by default). If the error is not recoverable, the 'Try again' button will not be rendered and the widget
3630 * that initiated the failed process will be disabled.
3631 *
3632 * If the error is a warning, the error interface will include a 'Dismiss' and a 'Continue' button, which will try the
3633 * process again.
3634 *
3635 * For an example of error interfaces, please see the [OOjs UI documentation on MediaWiki][1].
3636 *
3637 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Processes_and_errors
3638 *
3639 * @class
3640 *
3641 * @constructor
3642 * @param {string|jQuery} message Description of error
3643 * @param {Object} [config] Configuration options
3644 * @cfg {boolean} [recoverable=true] Error is recoverable.
3645 * By default, errors are recoverable, and users can try the process again.
3646 * @cfg {boolean} [warning=false] Error is a warning.
3647 * If the error is a warning, the error interface will include a
3648 * 'Dismiss' and a 'Continue' button. It is the responsibility of the developer to ensure that the warning
3649 * is not triggered a second time if the user chooses to continue.
3650 */
3651 OO.ui.Error = function OoUiError( message, config ) {
3652 // Allow passing positional parameters inside the config object
3653 if ( OO.isPlainObject( message ) && config === undefined ) {
3654 config = message;
3655 message = config.message;
3656 }
3657
3658 // Configuration initialization
3659 config = config || {};
3660
3661 // Properties
3662 this.message = message instanceof jQuery ? message : String( message );
3663 this.recoverable = config.recoverable === undefined || !!config.recoverable;
3664 this.warning = !!config.warning;
3665 };
3666
3667 /* Setup */
3668
3669 OO.initClass( OO.ui.Error );
3670
3671 /* Methods */
3672
3673 /**
3674 * Check if the error is recoverable.
3675 *
3676 * If the error is recoverable, users are able to try the process again.
3677 *
3678 * @return {boolean} Error is recoverable
3679 */
3680 OO.ui.Error.prototype.isRecoverable = function () {
3681 return this.recoverable;
3682 };
3683
3684 /**
3685 * Check if the error is a warning.
3686 *
3687 * If the error is a warning, the error interface will include a 'Dismiss' and a 'Continue' button.
3688 *
3689 * @return {boolean} Error is warning
3690 */
3691 OO.ui.Error.prototype.isWarning = function () {
3692 return this.warning;
3693 };
3694
3695 /**
3696 * Get error message as DOM nodes.
3697 *
3698 * @return {jQuery} Error message in DOM nodes
3699 */
3700 OO.ui.Error.prototype.getMessage = function () {
3701 return this.message instanceof jQuery ?
3702 this.message.clone() :
3703 $( '<div>' ).text( this.message ).contents();
3704 };
3705
3706 /**
3707 * Get the error message text.
3708 *
3709 * @return {string} Error message
3710 */
3711 OO.ui.Error.prototype.getMessageText = function () {
3712 return this.message instanceof jQuery ? this.message.text() : this.message;
3713 };
3714
3715 /**
3716 * Wraps an HTML snippet for use with configuration values which default
3717 * to strings. This bypasses the default html-escaping done to string
3718 * values.
3719 *
3720 * @class
3721 *
3722 * @constructor
3723 * @param {string} [content] HTML content
3724 */
3725 OO.ui.HtmlSnippet = function OoUiHtmlSnippet( content ) {
3726 // Properties
3727 this.content = content;
3728 };
3729
3730 /* Setup */
3731
3732 OO.initClass( OO.ui.HtmlSnippet );
3733
3734 /* Methods */
3735
3736 /**
3737 * Render into HTML.
3738 *
3739 * @return {string} Unchanged HTML snippet.
3740 */
3741 OO.ui.HtmlSnippet.prototype.toString = function () {
3742 return this.content;
3743 };
3744
3745 /**
3746 * A Process is a list of steps that are called in sequence. The step can be a number, a jQuery promise,
3747 * or a function:
3748 *
3749 * - **number**: the process will wait for the specified number of milliseconds before proceeding.
3750 * - **promise**: the process will continue to the next step when the promise is successfully resolved
3751 * or stop if the promise is rejected.
3752 * - **function**: the process will execute the function. The process will stop if the function returns
3753 * either a boolean `false` or a promise that is rejected; if the function returns a number, the process
3754 * will wait for that number of milliseconds before proceeding.
3755 *
3756 * If the process fails, an {@link OO.ui.Error error} is generated. Depending on how the error is
3757 * configured, users can dismiss the error and try the process again, or not. If a process is stopped,
3758 * its remaining steps will not be performed.
3759 *
3760 * @class
3761 *
3762 * @constructor
3763 * @param {number|jQuery.Promise|Function} step Number of miliseconds to wait before proceeding, promise
3764 * that must be resolved before proceeding, or a function to execute. See #createStep for more information. see #createStep for more information
3765 * @param {Object} [context=null] Execution context of the function. The context is ignored if the step is
3766 * a number or promise.
3767 * @return {Object} Step object, with `callback` and `context` properties
3768 */
3769 OO.ui.Process = function ( step, context ) {
3770 // Properties
3771 this.steps = [];
3772
3773 // Initialization
3774 if ( step !== undefined ) {
3775 this.next( step, context );
3776 }
3777 };
3778
3779 /* Setup */
3780
3781 OO.initClass( OO.ui.Process );
3782
3783 /* Methods */
3784
3785 /**
3786 * Start the process.
3787 *
3788 * @return {jQuery.Promise} Promise that is resolved when all steps have successfully completed.
3789 * If any of the steps return a promise that is rejected or a boolean false, this promise is rejected
3790 * and any remaining steps are not performed.
3791 */
3792 OO.ui.Process.prototype.execute = function () {
3793 var i, len, promise;
3794
3795 /**
3796 * Continue execution.
3797 *
3798 * @ignore
3799 * @param {Array} step A function and the context it should be called in
3800 * @return {Function} Function that continues the process
3801 */
3802 function proceed( step ) {
3803 return function () {
3804 // Execute step in the correct context
3805 var deferred,
3806 result = step.callback.call( step.context );
3807
3808 if ( result === false ) {
3809 // Use rejected promise for boolean false results
3810 return $.Deferred().reject( [] ).promise();
3811 }
3812 if ( typeof result === 'number' ) {
3813 if ( result < 0 ) {
3814 throw new Error( 'Cannot go back in time: flux capacitor is out of service' );
3815 }
3816 // Use a delayed promise for numbers, expecting them to be in milliseconds
3817 deferred = $.Deferred();
3818 setTimeout( deferred.resolve, result );
3819 return deferred.promise();
3820 }
3821 if ( result instanceof OO.ui.Error ) {
3822 // Use rejected promise for error
3823 return $.Deferred().reject( [ result ] ).promise();
3824 }
3825 if ( Array.isArray( result ) && result.length && result[ 0 ] instanceof OO.ui.Error ) {
3826 // Use rejected promise for list of errors
3827 return $.Deferred().reject( result ).promise();
3828 }
3829 // Duck-type the object to see if it can produce a promise
3830 if ( result && $.isFunction( result.promise ) ) {
3831 // Use a promise generated from the result
3832 return result.promise();
3833 }
3834 // Use resolved promise for other results
3835 return $.Deferred().resolve().promise();
3836 };
3837 }
3838
3839 if ( this.steps.length ) {
3840 // Generate a chain reaction of promises
3841 promise = proceed( this.steps[ 0 ] )();
3842 for ( i = 1, len = this.steps.length; i < len; i++ ) {
3843 promise = promise.then( proceed( this.steps[ i ] ) );
3844 }
3845 } else {
3846 promise = $.Deferred().resolve().promise();
3847 }
3848
3849 return promise;
3850 };
3851
3852 /**
3853 * Create a process step.
3854 *
3855 * @private
3856 * @param {number|jQuery.Promise|Function} step
3857 *
3858 * - Number of milliseconds to wait before proceeding
3859 * - Promise that must be resolved before proceeding
3860 * - Function to execute
3861 * - If the function returns a boolean false the process will stop
3862 * - If the function returns a promise, the process will continue to the next
3863 * step when the promise is resolved or stop if the promise is rejected
3864 * - If the function returns a number, the process will wait for that number of
3865 * milliseconds before proceeding
3866 * @param {Object} [context=null] Execution context of the function. The context is
3867 * ignored if the step is a number or promise.
3868 * @return {Object} Step object, with `callback` and `context` properties
3869 */
3870 OO.ui.Process.prototype.createStep = function ( step, context ) {
3871 if ( typeof step === 'number' || $.isFunction( step.promise ) ) {
3872 return {
3873 callback: function () {
3874 return step;
3875 },
3876 context: null
3877 };
3878 }
3879 if ( $.isFunction( step ) ) {
3880 return {
3881 callback: step,
3882 context: context
3883 };
3884 }
3885 throw new Error( 'Cannot create process step: number, promise or function expected' );
3886 };
3887
3888 /**
3889 * Add step to the beginning of the process.
3890 *
3891 * @inheritdoc #createStep
3892 * @return {OO.ui.Process} this
3893 * @chainable
3894 */
3895 OO.ui.Process.prototype.first = function ( step, context ) {
3896 this.steps.unshift( this.createStep( step, context ) );
3897 return this;
3898 };
3899
3900 /**
3901 * Add step to the end of the process.
3902 *
3903 * @inheritdoc #createStep
3904 * @return {OO.ui.Process} this
3905 * @chainable
3906 */
3907 OO.ui.Process.prototype.next = function ( step, context ) {
3908 this.steps.push( this.createStep( step, context ) );
3909 return this;
3910 };
3911
3912 /**
3913 * A ToolFactory creates tools on demand. All tools ({@link OO.ui.Tool Tools}, {@link OO.ui.PopupTool PopupTools},
3914 * and {@link OO.ui.ToolGroupTool ToolGroupTools}) must be registered with a tool factory. Tools are
3915 * registered by their symbolic name. See {@link OO.ui.Toolbar toolbars} for an example.
3916 *
3917 * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki][1].
3918 *
3919 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
3920 *
3921 * @class
3922 * @extends OO.Factory
3923 * @constructor
3924 */
3925 OO.ui.ToolFactory = function OoUiToolFactory() {
3926 // Parent constructor
3927 OO.ui.ToolFactory.parent.call( this );
3928 };
3929
3930 /* Setup */
3931
3932 OO.inheritClass( OO.ui.ToolFactory, OO.Factory );
3933
3934 /* Methods */
3935
3936 /**
3937 * Get tools from the factory
3938 *
3939 * @param {Array} include Included tools
3940 * @param {Array} exclude Excluded tools
3941 * @param {Array} promote Promoted tools
3942 * @param {Array} demote Demoted tools
3943 * @return {string[]} List of tools
3944 */
3945 OO.ui.ToolFactory.prototype.getTools = function ( include, exclude, promote, demote ) {
3946 var i, len, included, promoted, demoted,
3947 auto = [],
3948 used = {};
3949
3950 // Collect included and not excluded tools
3951 included = OO.simpleArrayDifference( this.extract( include ), this.extract( exclude ) );
3952
3953 // Promotion
3954 promoted = this.extract( promote, used );
3955 demoted = this.extract( demote, used );
3956
3957 // Auto
3958 for ( i = 0, len = included.length; i < len; i++ ) {
3959 if ( !used[ included[ i ] ] ) {
3960 auto.push( included[ i ] );
3961 }
3962 }
3963
3964 return promoted.concat( auto ).concat( demoted );
3965 };
3966
3967 /**
3968 * Get a flat list of names from a list of names or groups.
3969 *
3970 * Tools can be specified in the following ways:
3971 *
3972 * - A specific tool: `{ name: 'tool-name' }` or `'tool-name'`
3973 * - All tools in a group: `{ group: 'group-name' }`
3974 * - All tools: `'*'`
3975 *
3976 * @private
3977 * @param {Array|string} collection List of tools
3978 * @param {Object} [used] Object with names that should be skipped as properties; extracted
3979 * names will be added as properties
3980 * @return {string[]} List of extracted names
3981 */
3982 OO.ui.ToolFactory.prototype.extract = function ( collection, used ) {
3983 var i, len, item, name, tool,
3984 names = [];
3985
3986 if ( collection === '*' ) {
3987 for ( name in this.registry ) {
3988 tool = this.registry[ name ];
3989 if (
3990 // Only add tools by group name when auto-add is enabled
3991 tool.static.autoAddToCatchall &&
3992 // Exclude already used tools
3993 ( !used || !used[ name ] )
3994 ) {
3995 names.push( name );
3996 if ( used ) {
3997 used[ name ] = true;
3998 }
3999 }
4000 }
4001 } else if ( Array.isArray( collection ) ) {
4002 for ( i = 0, len = collection.length; i < len; i++ ) {
4003 item = collection[ i ];
4004 // Allow plain strings as shorthand for named tools
4005 if ( typeof item === 'string' ) {
4006 item = { name: item };
4007 }
4008 if ( OO.isPlainObject( item ) ) {
4009 if ( item.group ) {
4010 for ( name in this.registry ) {
4011 tool = this.registry[ name ];
4012 if (
4013 // Include tools with matching group
4014 tool.static.group === item.group &&
4015 // Only add tools by group name when auto-add is enabled
4016 tool.static.autoAddToGroup &&
4017 // Exclude already used tools
4018 ( !used || !used[ name ] )
4019 ) {
4020 names.push( name );
4021 if ( used ) {
4022 used[ name ] = true;
4023 }
4024 }
4025 }
4026 // Include tools with matching name and exclude already used tools
4027 } else if ( item.name && ( !used || !used[ item.name ] ) ) {
4028 names.push( item.name );
4029 if ( used ) {
4030 used[ item.name ] = true;
4031 }
4032 }
4033 }
4034 }
4035 }
4036 return names;
4037 };
4038
4039 /**
4040 * ToolGroupFactories create {@link OO.ui.ToolGroup toolgroups} on demand. The toolgroup classes must
4041 * specify a symbolic name and be registered with the factory. The following classes are registered by
4042 * default:
4043 *
4044 * - {@link OO.ui.BarToolGroup BarToolGroups} (‘bar’)
4045 * - {@link OO.ui.MenuToolGroup MenuToolGroups} (‘menu’)
4046 * - {@link OO.ui.ListToolGroup ListToolGroups} (‘list’)
4047 *
4048 * See {@link OO.ui.Toolbar toolbars} for an example.
4049 *
4050 * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki][1].
4051 *
4052 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
4053 * @class
4054 * @extends OO.Factory
4055 * @constructor
4056 */
4057 OO.ui.ToolGroupFactory = function OoUiToolGroupFactory() {
4058 // Parent constructor
4059 OO.Factory.call( this );
4060
4061 var i, l,
4062 defaultClasses = this.constructor.static.getDefaultClasses();
4063
4064 // Register default toolgroups
4065 for ( i = 0, l = defaultClasses.length; i < l; i++ ) {
4066 this.register( defaultClasses[ i ] );
4067 }
4068 };
4069
4070 /* Setup */
4071
4072 OO.inheritClass( OO.ui.ToolGroupFactory, OO.Factory );
4073
4074 /* Static Methods */
4075
4076 /**
4077 * Get a default set of classes to be registered on construction.
4078 *
4079 * @return {Function[]} Default classes
4080 */
4081 OO.ui.ToolGroupFactory.static.getDefaultClasses = function () {
4082 return [
4083 OO.ui.BarToolGroup,
4084 OO.ui.ListToolGroup,
4085 OO.ui.MenuToolGroup
4086 ];
4087 };
4088
4089 /**
4090 * Theme logic.
4091 *
4092 * @abstract
4093 * @class
4094 *
4095 * @constructor
4096 * @param {Object} [config] Configuration options
4097 */
4098 OO.ui.Theme = function OoUiTheme( config ) {
4099 // Configuration initialization
4100 config = config || {};
4101 };
4102
4103 /* Setup */
4104
4105 OO.initClass( OO.ui.Theme );
4106
4107 /* Methods */
4108
4109 /**
4110 * Get a list of classes to be applied to a widget.
4111 *
4112 * The 'on' and 'off' lists combined MUST contain keys for all classes the theme adds or removes,
4113 * otherwise state transitions will not work properly.
4114 *
4115 * @param {OO.ui.Element} element Element for which to get classes
4116 * @return {Object.<string,string[]>} Categorized class names with `on` and `off` lists
4117 */
4118 OO.ui.Theme.prototype.getElementClasses = function ( /* element */ ) {
4119 return { on: [], off: [] };
4120 };
4121
4122 /**
4123 * Update CSS classes provided by the theme.
4124 *
4125 * For elements with theme logic hooks, this should be called any time there's a state change.
4126 *
4127 * @param {OO.ui.Element} element Element for which to update classes
4128 * @return {Object.<string,string[]>} Categorized class names with `on` and `off` lists
4129 */
4130 OO.ui.Theme.prototype.updateElementClasses = function ( element ) {
4131 var classes = this.getElementClasses( element );
4132
4133 element.$element
4134 .removeClass( classes.off.join( ' ' ) )
4135 .addClass( classes.on.join( ' ' ) );
4136 };
4137
4138 /**
4139 * The TabIndexedElement class is an attribute mixin used to add additional functionality to an
4140 * element created by another class. The mixin provides a ‘tabIndex’ property, which specifies the
4141 * order in which users will navigate through the focusable elements via the "tab" key.
4142 *
4143 * @example
4144 * // TabIndexedElement is mixed into the ButtonWidget class
4145 * // to provide a tabIndex property.
4146 * var button1 = new OO.ui.ButtonWidget( {
4147 * label: 'fourth',
4148 * tabIndex: 4
4149 * } );
4150 * var button2 = new OO.ui.ButtonWidget( {
4151 * label: 'second',
4152 * tabIndex: 2
4153 * } );
4154 * var button3 = new OO.ui.ButtonWidget( {
4155 * label: 'third',
4156 * tabIndex: 3
4157 * } );
4158 * var button4 = new OO.ui.ButtonWidget( {
4159 * label: 'first',
4160 * tabIndex: 1
4161 * } );
4162 * $( 'body' ).append( button1.$element, button2.$element, button3.$element, button4.$element );
4163 *
4164 * @abstract
4165 * @class
4166 *
4167 * @constructor
4168 * @param {Object} [config] Configuration options
4169 * @cfg {jQuery} [$tabIndexed] The element that should use the tabindex functionality. By default,
4170 * the functionality is applied to the element created by the class ($element). If a different element is specified, the tabindex
4171 * functionality will be applied to it instead.
4172 * @cfg {number|null} [tabIndex=0] Number that specifies the element’s position in the tab-navigation
4173 * order (e.g., 1 for the first focusable element). Use 0 to use the default navigation order; use -1
4174 * to remove the element from the tab-navigation flow.
4175 */
4176 OO.ui.mixin.TabIndexedElement = function OoUiMixinTabIndexedElement( config ) {
4177 // Configuration initialization
4178 config = $.extend( { tabIndex: 0 }, config );
4179
4180 // Properties
4181 this.$tabIndexed = null;
4182 this.tabIndex = null;
4183
4184 // Events
4185 this.connect( this, { disable: 'onTabIndexedElementDisable' } );
4186
4187 // Initialization
4188 this.setTabIndex( config.tabIndex );
4189 this.setTabIndexedElement( config.$tabIndexed || this.$element );
4190 };
4191
4192 /* Setup */
4193
4194 OO.initClass( OO.ui.mixin.TabIndexedElement );
4195
4196 /* Methods */
4197
4198 /**
4199 * Set the element that should use the tabindex functionality.
4200 *
4201 * This method is used to retarget a tabindex mixin so that its functionality applies
4202 * to the specified element. If an element is currently using the functionality, the mixin’s
4203 * effect on that element is removed before the new element is set up.
4204 *
4205 * @param {jQuery} $tabIndexed Element that should use the tabindex functionality
4206 * @chainable
4207 */
4208 OO.ui.mixin.TabIndexedElement.prototype.setTabIndexedElement = function ( $tabIndexed ) {
4209 var tabIndex = this.tabIndex;
4210 // Remove attributes from old $tabIndexed
4211 this.setTabIndex( null );
4212 // Force update of new $tabIndexed
4213 this.$tabIndexed = $tabIndexed;
4214 this.tabIndex = tabIndex;
4215 return this.updateTabIndex();
4216 };
4217
4218 /**
4219 * Set the value of the tabindex.
4220 *
4221 * @param {number|null} tabIndex Tabindex value, or `null` for no tabindex
4222 * @chainable
4223 */
4224 OO.ui.mixin.TabIndexedElement.prototype.setTabIndex = function ( tabIndex ) {
4225 tabIndex = typeof tabIndex === 'number' ? tabIndex : null;
4226
4227 if ( this.tabIndex !== tabIndex ) {
4228 this.tabIndex = tabIndex;
4229 this.updateTabIndex();
4230 }
4231
4232 return this;
4233 };
4234
4235 /**
4236 * Update the `tabindex` attribute, in case of changes to tab index or
4237 * disabled state.
4238 *
4239 * @private
4240 * @chainable
4241 */
4242 OO.ui.mixin.TabIndexedElement.prototype.updateTabIndex = function () {
4243 if ( this.$tabIndexed ) {
4244 if ( this.tabIndex !== null ) {
4245 // Do not index over disabled elements
4246 this.$tabIndexed.attr( {
4247 tabindex: this.isDisabled() ? -1 : this.tabIndex,
4248 // ChromeVox and NVDA do not seem to inherit this from parent elements
4249 'aria-disabled': this.isDisabled().toString()
4250 } );
4251 } else {
4252 this.$tabIndexed.removeAttr( 'tabindex aria-disabled' );
4253 }
4254 }
4255 return this;
4256 };
4257
4258 /**
4259 * Handle disable events.
4260 *
4261 * @private
4262 * @param {boolean} disabled Element is disabled
4263 */
4264 OO.ui.mixin.TabIndexedElement.prototype.onTabIndexedElementDisable = function () {
4265 this.updateTabIndex();
4266 };
4267
4268 /**
4269 * Get the value of the tabindex.
4270 *
4271 * @return {number|null} Tabindex value
4272 */
4273 OO.ui.mixin.TabIndexedElement.prototype.getTabIndex = function () {
4274 return this.tabIndex;
4275 };
4276
4277 /**
4278 * ButtonElement is often mixed into other classes to generate a button, which is a clickable
4279 * interface element that can be configured with access keys for accessibility.
4280 * See the [OOjs UI documentation on MediaWiki] [1] for examples.
4281 *
4282 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#Buttons
4283 * @abstract
4284 * @class
4285 *
4286 * @constructor
4287 * @param {Object} [config] Configuration options
4288 * @cfg {jQuery} [$button] The button element created by the class.
4289 * If this configuration is omitted, the button element will use a generated `<a>`.
4290 * @cfg {boolean} [framed=true] Render the button with a frame
4291 * @cfg {string} [accessKey] Button's access key
4292 */
4293 OO.ui.mixin.ButtonElement = function OoUiMixinButtonElement( config ) {
4294 // Configuration initialization
4295 config = config || {};
4296
4297 // Properties
4298 this.$button = null;
4299 this.framed = null;
4300 this.accessKey = null;
4301 this.active = false;
4302 this.onMouseUpHandler = this.onMouseUp.bind( this );
4303 this.onMouseDownHandler = this.onMouseDown.bind( this );
4304 this.onKeyDownHandler = this.onKeyDown.bind( this );
4305 this.onKeyUpHandler = this.onKeyUp.bind( this );
4306 this.onClickHandler = this.onClick.bind( this );
4307 this.onKeyPressHandler = this.onKeyPress.bind( this );
4308
4309 // Initialization
4310 this.$element.addClass( 'oo-ui-buttonElement' );
4311 this.toggleFramed( config.framed === undefined || config.framed );
4312 this.setAccessKey( config.accessKey );
4313 this.setButtonElement( config.$button || $( '<a>' ) );
4314 };
4315
4316 /* Setup */
4317
4318 OO.initClass( OO.ui.mixin.ButtonElement );
4319
4320 /* Static Properties */
4321
4322 /**
4323 * Cancel mouse down events.
4324 *
4325 * This property is usually set to `true` to prevent the focus from changing when the button is clicked.
4326 * Classes such as {@link OO.ui.mixin.DraggableElement DraggableElement} and {@link OO.ui.ButtonOptionWidget ButtonOptionWidget}
4327 * use a value of `false` so that dragging behavior is possible and mousedown events can be handled by a
4328 * parent widget.
4329 *
4330 * @static
4331 * @inheritable
4332 * @property {boolean}
4333 */
4334 OO.ui.mixin.ButtonElement.static.cancelButtonMouseDownEvents = true;
4335
4336 /* Events */
4337
4338 /**
4339 * A 'click' event is emitted when the button element is clicked.
4340 *
4341 * @event click
4342 */
4343
4344 /* Methods */
4345
4346 /**
4347 * Set the button element.
4348 *
4349 * This method is used to retarget a button mixin so that its functionality applies to
4350 * the specified button element instead of the one created by the class. If a button element
4351 * is already set, the method will remove the mixin’s effect on that element.
4352 *
4353 * @param {jQuery} $button Element to use as button
4354 */
4355 OO.ui.mixin.ButtonElement.prototype.setButtonElement = function ( $button ) {
4356 if ( this.$button ) {
4357 this.$button
4358 .removeClass( 'oo-ui-buttonElement-button' )
4359 .removeAttr( 'role accesskey' )
4360 .off( {
4361 mousedown: this.onMouseDownHandler,
4362 keydown: this.onKeyDownHandler,
4363 click: this.onClickHandler,
4364 keypress: this.onKeyPressHandler
4365 } );
4366 }
4367
4368 this.$button = $button
4369 .addClass( 'oo-ui-buttonElement-button' )
4370 .attr( { role: 'button', accesskey: this.accessKey } )
4371 .on( {
4372 mousedown: this.onMouseDownHandler,
4373 keydown: this.onKeyDownHandler,
4374 click: this.onClickHandler,
4375 keypress: this.onKeyPressHandler
4376 } );
4377 };
4378
4379 /**
4380 * Handles mouse down events.
4381 *
4382 * @protected
4383 * @param {jQuery.Event} e Mouse down event
4384 */
4385 OO.ui.mixin.ButtonElement.prototype.onMouseDown = function ( e ) {
4386 if ( this.isDisabled() || e.which !== 1 ) {
4387 return;
4388 }
4389 this.$element.addClass( 'oo-ui-buttonElement-pressed' );
4390 // Run the mouseup handler no matter where the mouse is when the button is let go, so we can
4391 // reliably remove the pressed class
4392 this.getElementDocument().addEventListener( 'mouseup', this.onMouseUpHandler, true );
4393 // Prevent change of focus unless specifically configured otherwise
4394 if ( this.constructor.static.cancelButtonMouseDownEvents ) {
4395 return false;
4396 }
4397 };
4398
4399 /**
4400 * Handles mouse up events.
4401 *
4402 * @protected
4403 * @param {jQuery.Event} e Mouse up event
4404 */
4405 OO.ui.mixin.ButtonElement.prototype.onMouseUp = function ( e ) {
4406 if ( this.isDisabled() || e.which !== 1 ) {
4407 return;
4408 }
4409 this.$element.removeClass( 'oo-ui-buttonElement-pressed' );
4410 // Stop listening for mouseup, since we only needed this once
4411 this.getElementDocument().removeEventListener( 'mouseup', this.onMouseUpHandler, true );
4412 };
4413
4414 /**
4415 * Handles mouse click events.
4416 *
4417 * @protected
4418 * @param {jQuery.Event} e Mouse click event
4419 * @fires click
4420 */
4421 OO.ui.mixin.ButtonElement.prototype.onClick = function ( e ) {
4422 if ( !this.isDisabled() && e.which === 1 ) {
4423 if ( this.emit( 'click' ) ) {
4424 return false;
4425 }
4426 }
4427 };
4428
4429 /**
4430 * Handles key down events.
4431 *
4432 * @protected
4433 * @param {jQuery.Event} e Key down event
4434 */
4435 OO.ui.mixin.ButtonElement.prototype.onKeyDown = function ( e ) {
4436 if ( this.isDisabled() || ( e.which !== OO.ui.Keys.SPACE && e.which !== OO.ui.Keys.ENTER ) ) {
4437 return;
4438 }
4439 this.$element.addClass( 'oo-ui-buttonElement-pressed' );
4440 // Run the keyup handler no matter where the key is when the button is let go, so we can
4441 // reliably remove the pressed class
4442 this.getElementDocument().addEventListener( 'keyup', this.onKeyUpHandler, true );
4443 };
4444
4445 /**
4446 * Handles key up events.
4447 *
4448 * @protected
4449 * @param {jQuery.Event} e Key up event
4450 */
4451 OO.ui.mixin.ButtonElement.prototype.onKeyUp = function ( e ) {
4452 if ( this.isDisabled() || ( e.which !== OO.ui.Keys.SPACE && e.which !== OO.ui.Keys.ENTER ) ) {
4453 return;
4454 }
4455 this.$element.removeClass( 'oo-ui-buttonElement-pressed' );
4456 // Stop listening for keyup, since we only needed this once
4457 this.getElementDocument().removeEventListener( 'keyup', this.onKeyUpHandler, true );
4458 };
4459
4460 /**
4461 * Handles key press events.
4462 *
4463 * @protected
4464 * @param {jQuery.Event} e Key press event
4465 * @fires click
4466 */
4467 OO.ui.mixin.ButtonElement.prototype.onKeyPress = function ( e ) {
4468 if ( !this.isDisabled() && ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER ) ) {
4469 if ( this.emit( 'click' ) ) {
4470 return false;
4471 }
4472 }
4473 };
4474
4475 /**
4476 * Check if button has a frame.
4477 *
4478 * @return {boolean} Button is framed
4479 */
4480 OO.ui.mixin.ButtonElement.prototype.isFramed = function () {
4481 return this.framed;
4482 };
4483
4484 /**
4485 * Render the button with or without a frame. Omit the `framed` parameter to toggle the button frame on and off.
4486 *
4487 * @param {boolean} [framed] Make button framed, omit to toggle
4488 * @chainable
4489 */
4490 OO.ui.mixin.ButtonElement.prototype.toggleFramed = function ( framed ) {
4491 framed = framed === undefined ? !this.framed : !!framed;
4492 if ( framed !== this.framed ) {
4493 this.framed = framed;
4494 this.$element
4495 .toggleClass( 'oo-ui-buttonElement-frameless', !framed )
4496 .toggleClass( 'oo-ui-buttonElement-framed', framed );
4497 this.updateThemeClasses();
4498 }
4499
4500 return this;
4501 };
4502
4503 /**
4504 * Set the button's access key.
4505 *
4506 * @param {string} accessKey Button's access key, use empty string to remove
4507 * @chainable
4508 */
4509 OO.ui.mixin.ButtonElement.prototype.setAccessKey = function ( accessKey ) {
4510 accessKey = typeof accessKey === 'string' && accessKey.length ? accessKey : null;
4511
4512 if ( this.accessKey !== accessKey ) {
4513 if ( this.$button ) {
4514 if ( accessKey !== null ) {
4515 this.$button.attr( 'accesskey', accessKey );
4516 } else {
4517 this.$button.removeAttr( 'accesskey' );
4518 }
4519 }
4520 this.accessKey = accessKey;
4521 }
4522
4523 return this;
4524 };
4525
4526 /**
4527 * Set the button to its 'active' state.
4528 *
4529 * The active state occurs when a {@link OO.ui.ButtonOptionWidget ButtonOptionWidget} or
4530 * a {@link OO.ui.ToggleButtonWidget ToggleButtonWidget} is pressed. This method does nothing
4531 * for other button types.
4532 *
4533 * @param {boolean} [value] Make button active
4534 * @chainable
4535 */
4536 OO.ui.mixin.ButtonElement.prototype.setActive = function ( value ) {
4537 this.$element.toggleClass( 'oo-ui-buttonElement-active', !!value );
4538 return this;
4539 };
4540
4541 /**
4542 * Any OOjs UI widget that contains other widgets (such as {@link OO.ui.ButtonWidget buttons} or
4543 * {@link OO.ui.OptionWidget options}) mixes in GroupElement. Adding, removing, and clearing
4544 * items from the group is done through the interface the class provides.
4545 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
4546 *
4547 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Groups
4548 *
4549 * @abstract
4550 * @class
4551 *
4552 * @constructor
4553 * @param {Object} [config] Configuration options
4554 * @cfg {jQuery} [$group] The container element created by the class. If this configuration
4555 * is omitted, the group element will use a generated `<div>`.
4556 */
4557 OO.ui.mixin.GroupElement = function OoUiMixinGroupElement( config ) {
4558 // Configuration initialization
4559 config = config || {};
4560
4561 // Properties
4562 this.$group = null;
4563 this.items = [];
4564 this.aggregateItemEvents = {};
4565
4566 // Initialization
4567 this.setGroupElement( config.$group || $( '<div>' ) );
4568 };
4569
4570 /* Methods */
4571
4572 /**
4573 * Set the group element.
4574 *
4575 * If an element is already set, items will be moved to the new element.
4576 *
4577 * @param {jQuery} $group Element to use as group
4578 */
4579 OO.ui.mixin.GroupElement.prototype.setGroupElement = function ( $group ) {
4580 var i, len;
4581
4582 this.$group = $group;
4583 for ( i = 0, len = this.items.length; i < len; i++ ) {
4584 this.$group.append( this.items[ i ].$element );
4585 }
4586 };
4587
4588 /**
4589 * Check if a group contains no items.
4590 *
4591 * @return {boolean} Group is empty
4592 */
4593 OO.ui.mixin.GroupElement.prototype.isEmpty = function () {
4594 return !this.items.length;
4595 };
4596
4597 /**
4598 * Get all items in the group.
4599 *
4600 * The method returns an array of item references (e.g., [button1, button2, button3]) and is useful
4601 * when synchronizing groups of items, or whenever the references are required (e.g., when removing items
4602 * from a group).
4603 *
4604 * @return {OO.ui.Element[]} An array of items.
4605 */
4606 OO.ui.mixin.GroupElement.prototype.getItems = function () {
4607 return this.items.slice( 0 );
4608 };
4609
4610 /**
4611 * Get an item by its data.
4612 *
4613 * Only the first item with matching data will be returned. To return all matching items,
4614 * use the #getItemsFromData method.
4615 *
4616 * @param {Object} data Item data to search for
4617 * @return {OO.ui.Element|null} Item with equivalent data, `null` if none exists
4618 */
4619 OO.ui.mixin.GroupElement.prototype.getItemFromData = function ( data ) {
4620 var i, len, item,
4621 hash = OO.getHash( data );
4622
4623 for ( i = 0, len = this.items.length; i < len; i++ ) {
4624 item = this.items[ i ];
4625 if ( hash === OO.getHash( item.getData() ) ) {
4626 return item;
4627 }
4628 }
4629
4630 return null;
4631 };
4632
4633 /**
4634 * Get items by their data.
4635 *
4636 * All items with matching data will be returned. To return only the first match, use the #getItemFromData method instead.
4637 *
4638 * @param {Object} data Item data to search for
4639 * @return {OO.ui.Element[]} Items with equivalent data
4640 */
4641 OO.ui.mixin.GroupElement.prototype.getItemsFromData = function ( data ) {
4642 var i, len, item,
4643 hash = OO.getHash( data ),
4644 items = [];
4645
4646 for ( i = 0, len = this.items.length; i < len; i++ ) {
4647 item = this.items[ i ];
4648 if ( hash === OO.getHash( item.getData() ) ) {
4649 items.push( item );
4650 }
4651 }
4652
4653 return items;
4654 };
4655
4656 /**
4657 * Aggregate the events emitted by the group.
4658 *
4659 * When events are aggregated, the group will listen to all contained items for the event,
4660 * and then emit the event under a new name. The new event will contain an additional leading
4661 * parameter containing the item that emitted the original event. Other arguments emitted from
4662 * the original event are passed through.
4663 *
4664 * @param {Object.<string,string|null>} events An object keyed by the name of the event that should be
4665 * aggregated (e.g., ‘click’) and the value of the new name to use (e.g., ‘groupClick’).
4666 * A `null` value will remove aggregated events.
4667
4668 * @throws {Error} An error is thrown if aggregation already exists.
4669 */
4670 OO.ui.mixin.GroupElement.prototype.aggregate = function ( events ) {
4671 var i, len, item, add, remove, itemEvent, groupEvent;
4672
4673 for ( itemEvent in events ) {
4674 groupEvent = events[ itemEvent ];
4675
4676 // Remove existing aggregated event
4677 if ( Object.prototype.hasOwnProperty.call( this.aggregateItemEvents, itemEvent ) ) {
4678 // Don't allow duplicate aggregations
4679 if ( groupEvent ) {
4680 throw new Error( 'Duplicate item event aggregation for ' + itemEvent );
4681 }
4682 // Remove event aggregation from existing items
4683 for ( i = 0, len = this.items.length; i < len; i++ ) {
4684 item = this.items[ i ];
4685 if ( item.connect && item.disconnect ) {
4686 remove = {};
4687 remove[ itemEvent ] = [ 'emit', this.aggregateItemEvents[itemEvent], item ];
4688 item.disconnect( this, remove );
4689 }
4690 }
4691 // Prevent future items from aggregating event
4692 delete this.aggregateItemEvents[ itemEvent ];
4693 }
4694
4695 // Add new aggregate event
4696 if ( groupEvent ) {
4697 // Make future items aggregate event
4698 this.aggregateItemEvents[ itemEvent ] = groupEvent;
4699 // Add event aggregation to existing items
4700 for ( i = 0, len = this.items.length; i < len; i++ ) {
4701 item = this.items[ i ];
4702 if ( item.connect && item.disconnect ) {
4703 add = {};
4704 add[ itemEvent ] = [ 'emit', groupEvent, item ];
4705 item.connect( this, add );
4706 }
4707 }
4708 }
4709 }
4710 };
4711
4712 /**
4713 * Add items to the group.
4714 *
4715 * Items will be added to the end of the group array unless the optional `index` parameter specifies
4716 * a different insertion point. Adding an existing item will move it to the end of the array or the point specified by the `index`.
4717 *
4718 * @param {OO.ui.Element[]} items An array of items to add to the group
4719 * @param {number} [index] Index of the insertion point
4720 * @chainable
4721 */
4722 OO.ui.mixin.GroupElement.prototype.addItems = function ( items, index ) {
4723 var i, len, item, event, events, currentIndex,
4724 itemElements = [];
4725
4726 for ( i = 0, len = items.length; i < len; i++ ) {
4727 item = items[ i ];
4728
4729 // Check if item exists then remove it first, effectively "moving" it
4730 currentIndex = $.inArray( item, this.items );
4731 if ( currentIndex >= 0 ) {
4732 this.removeItems( [ item ] );
4733 // Adjust index to compensate for removal
4734 if ( currentIndex < index ) {
4735 index--;
4736 }
4737 }
4738 // Add the item
4739 if ( item.connect && item.disconnect && !$.isEmptyObject( this.aggregateItemEvents ) ) {
4740 events = {};
4741 for ( event in this.aggregateItemEvents ) {
4742 events[ event ] = [ 'emit', this.aggregateItemEvents[ event ], item ];
4743 }
4744 item.connect( this, events );
4745 }
4746 item.setElementGroup( this );
4747 itemElements.push( item.$element.get( 0 ) );
4748 }
4749
4750 if ( index === undefined || index < 0 || index >= this.items.length ) {
4751 this.$group.append( itemElements );
4752 this.items.push.apply( this.items, items );
4753 } else if ( index === 0 ) {
4754 this.$group.prepend( itemElements );
4755 this.items.unshift.apply( this.items, items );
4756 } else {
4757 this.items[ index ].$element.before( itemElements );
4758 this.items.splice.apply( this.items, [ index, 0 ].concat( items ) );
4759 }
4760
4761 return this;
4762 };
4763
4764 /**
4765 * Remove the specified items from a group.
4766 *
4767 * Removed items are detached (not removed) from the DOM so that they may be reused.
4768 * To remove all items from a group, you may wish to use the #clearItems method instead.
4769 *
4770 * @param {OO.ui.Element[]} items An array of items to remove
4771 * @chainable
4772 */
4773 OO.ui.mixin.GroupElement.prototype.removeItems = function ( items ) {
4774 var i, len, item, index, remove, itemEvent;
4775
4776 // Remove specific items
4777 for ( i = 0, len = items.length; i < len; i++ ) {
4778 item = items[ i ];
4779 index = $.inArray( item, this.items );
4780 if ( index !== -1 ) {
4781 if (
4782 item.connect && item.disconnect &&
4783 !$.isEmptyObject( this.aggregateItemEvents )
4784 ) {
4785 remove = {};
4786 if ( Object.prototype.hasOwnProperty.call( this.aggregateItemEvents, itemEvent ) ) {
4787 remove[ itemEvent ] = [ 'emit', this.aggregateItemEvents[ itemEvent ], item ];
4788 }
4789 item.disconnect( this, remove );
4790 }
4791 item.setElementGroup( null );
4792 this.items.splice( index, 1 );
4793 item.$element.detach();
4794 }
4795 }
4796
4797 return this;
4798 };
4799
4800 /**
4801 * Clear all items from the group.
4802 *
4803 * Cleared items are detached from the DOM, not removed, so that they may be reused.
4804 * To remove only a subset of items from a group, use the #removeItems method.
4805 *
4806 * @chainable
4807 */
4808 OO.ui.mixin.GroupElement.prototype.clearItems = function () {
4809 var i, len, item, remove, itemEvent;
4810
4811 // Remove all items
4812 for ( i = 0, len = this.items.length; i < len; i++ ) {
4813 item = this.items[ i ];
4814 if (
4815 item.connect && item.disconnect &&
4816 !$.isEmptyObject( this.aggregateItemEvents )
4817 ) {
4818 remove = {};
4819 if ( Object.prototype.hasOwnProperty.call( this.aggregateItemEvents, itemEvent ) ) {
4820 remove[ itemEvent ] = [ 'emit', this.aggregateItemEvents[ itemEvent ], item ];
4821 }
4822 item.disconnect( this, remove );
4823 }
4824 item.setElementGroup( null );
4825 item.$element.detach();
4826 }
4827
4828 this.items = [];
4829 return this;
4830 };
4831
4832 /**
4833 * DraggableElement is a mixin class used to create elements that can be clicked
4834 * and dragged by a mouse to a new position within a group. This class must be used
4835 * in conjunction with OO.ui.mixin.DraggableGroupElement, which provides a container for
4836 * the draggable elements.
4837 *
4838 * @abstract
4839 * @class
4840 *
4841 * @constructor
4842 */
4843 OO.ui.mixin.DraggableElement = function OoUiMixinDraggableElement() {
4844 // Properties
4845 this.index = null;
4846
4847 // Initialize and events
4848 this.$element
4849 .attr( 'draggable', true )
4850 .addClass( 'oo-ui-draggableElement' )
4851 .on( {
4852 dragstart: this.onDragStart.bind( this ),
4853 dragover: this.onDragOver.bind( this ),
4854 dragend: this.onDragEnd.bind( this ),
4855 drop: this.onDrop.bind( this )
4856 } );
4857 };
4858
4859 OO.initClass( OO.ui.mixin.DraggableElement );
4860
4861 /* Events */
4862
4863 /**
4864 * @event dragstart
4865 *
4866 * A dragstart event is emitted when the user clicks and begins dragging an item.
4867 * @param {OO.ui.mixin.DraggableElement} item The item the user has clicked and is dragging with the mouse.
4868 */
4869
4870 /**
4871 * @event dragend
4872 * A dragend event is emitted when the user drags an item and releases the mouse,
4873 * thus terminating the drag operation.
4874 */
4875
4876 /**
4877 * @event drop
4878 * A drop event is emitted when the user drags an item and then releases the mouse button
4879 * over a valid target.
4880 */
4881
4882 /* Static Properties */
4883
4884 /**
4885 * @inheritdoc OO.ui.mixin.ButtonElement
4886 */
4887 OO.ui.mixin.DraggableElement.static.cancelButtonMouseDownEvents = false;
4888
4889 /* Methods */
4890
4891 /**
4892 * Respond to dragstart event.
4893 *
4894 * @private
4895 * @param {jQuery.Event} event jQuery event
4896 * @fires dragstart
4897 */
4898 OO.ui.mixin.DraggableElement.prototype.onDragStart = function ( e ) {
4899 var dataTransfer = e.originalEvent.dataTransfer;
4900 // Define drop effect
4901 dataTransfer.dropEffect = 'none';
4902 dataTransfer.effectAllowed = 'move';
4903 // We must set up a dataTransfer data property or Firefox seems to
4904 // ignore the fact the element is draggable.
4905 try {
4906 dataTransfer.setData( 'application-x/OOjs-UI-draggable', this.getIndex() );
4907 } catch ( err ) {
4908 // The above is only for firefox. No need to set a catch clause
4909 // if it fails, move on.
4910 }
4911 // Add dragging class
4912 this.$element.addClass( 'oo-ui-draggableElement-dragging' );
4913 // Emit event
4914 this.emit( 'dragstart', this );
4915 return true;
4916 };
4917
4918 /**
4919 * Respond to dragend event.
4920 *
4921 * @private
4922 * @fires dragend
4923 */
4924 OO.ui.mixin.DraggableElement.prototype.onDragEnd = function () {
4925 this.$element.removeClass( 'oo-ui-draggableElement-dragging' );
4926 this.emit( 'dragend' );
4927 };
4928
4929 /**
4930 * Handle drop event.
4931 *
4932 * @private
4933 * @param {jQuery.Event} event jQuery event
4934 * @fires drop
4935 */
4936 OO.ui.mixin.DraggableElement.prototype.onDrop = function ( e ) {
4937 e.preventDefault();
4938 this.emit( 'drop', e );
4939 };
4940
4941 /**
4942 * In order for drag/drop to work, the dragover event must
4943 * return false and stop propogation.
4944 *
4945 * @private
4946 */
4947 OO.ui.mixin.DraggableElement.prototype.onDragOver = function ( e ) {
4948 e.preventDefault();
4949 };
4950
4951 /**
4952 * Set item index.
4953 * Store it in the DOM so we can access from the widget drag event
4954 *
4955 * @private
4956 * @param {number} Item index
4957 */
4958 OO.ui.mixin.DraggableElement.prototype.setIndex = function ( index ) {
4959 if ( this.index !== index ) {
4960 this.index = index;
4961 this.$element.data( 'index', index );
4962 }
4963 };
4964
4965 /**
4966 * Get item index
4967 *
4968 * @private
4969 * @return {number} Item index
4970 */
4971 OO.ui.mixin.DraggableElement.prototype.getIndex = function () {
4972 return this.index;
4973 };
4974
4975 /**
4976 * DraggableGroupElement is a mixin class used to create a group element to
4977 * contain draggable elements, which are items that can be clicked and dragged by a mouse.
4978 * The class is used with OO.ui.mixin.DraggableElement.
4979 *
4980 * @abstract
4981 * @class
4982 * @mixins OO.ui.mixin.GroupElement
4983 *
4984 * @constructor
4985 * @param {Object} [config] Configuration options
4986 * @cfg {string} [orientation] Item orientation: 'horizontal' or 'vertical'. The orientation
4987 * should match the layout of the items. Items displayed in a single row
4988 * or in several rows should use horizontal orientation. The vertical orientation should only be
4989 * used when the items are displayed in a single column. Defaults to 'vertical'
4990 */
4991 OO.ui.mixin.DraggableGroupElement = function OoUiMixinDraggableGroupElement( config ) {
4992 // Configuration initialization
4993 config = config || {};
4994
4995 // Parent constructor
4996 OO.ui.mixin.GroupElement.call( this, config );
4997
4998 // Properties
4999 this.orientation = config.orientation || 'vertical';
5000 this.dragItem = null;
5001 this.itemDragOver = null;
5002 this.itemKeys = {};
5003 this.sideInsertion = '';
5004
5005 // Events
5006 this.aggregate( {
5007 dragstart: 'itemDragStart',
5008 dragend: 'itemDragEnd',
5009 drop: 'itemDrop'
5010 } );
5011 this.connect( this, {
5012 itemDragStart: 'onItemDragStart',
5013 itemDrop: 'onItemDrop',
5014 itemDragEnd: 'onItemDragEnd'
5015 } );
5016 this.$element.on( {
5017 dragover: $.proxy( this.onDragOver, this ),
5018 dragleave: $.proxy( this.onDragLeave, this )
5019 } );
5020
5021 // Initialize
5022 if ( Array.isArray( config.items ) ) {
5023 this.addItems( config.items );
5024 }
5025 this.$placeholder = $( '<div>' )
5026 .addClass( 'oo-ui-draggableGroupElement-placeholder' );
5027 this.$element
5028 .addClass( 'oo-ui-draggableGroupElement' )
5029 .append( this.$status )
5030 .toggleClass( 'oo-ui-draggableGroupElement-horizontal', this.orientation === 'horizontal' )
5031 .prepend( this.$placeholder );
5032 };
5033
5034 /* Setup */
5035 OO.mixinClass( OO.ui.mixin.DraggableGroupElement, OO.ui.mixin.GroupElement );
5036
5037 /* Events */
5038
5039 /**
5040 * A 'reorder' event is emitted when the order of items in the group changes.
5041 *
5042 * @event reorder
5043 * @param {OO.ui.mixin.DraggableElement} item Reordered item
5044 * @param {number} [newIndex] New index for the item
5045 */
5046
5047 /* Methods */
5048
5049 /**
5050 * Respond to item drag start event
5051 *
5052 * @private
5053 * @param {OO.ui.mixin.DraggableElement} item Dragged item
5054 */
5055 OO.ui.mixin.DraggableGroupElement.prototype.onItemDragStart = function ( item ) {
5056 var i, len;
5057
5058 // Map the index of each object
5059 for ( i = 0, len = this.items.length; i < len; i++ ) {
5060 this.items[ i ].setIndex( i );
5061 }
5062
5063 if ( this.orientation === 'horizontal' ) {
5064 // Set the height of the indicator
5065 this.$placeholder.css( {
5066 height: item.$element.outerHeight(),
5067 width: 2
5068 } );
5069 } else {
5070 // Set the width of the indicator
5071 this.$placeholder.css( {
5072 height: 2,
5073 width: item.$element.outerWidth()
5074 } );
5075 }
5076 this.setDragItem( item );
5077 };
5078
5079 /**
5080 * Respond to item drag end event
5081 *
5082 * @private
5083 */
5084 OO.ui.mixin.DraggableGroupElement.prototype.onItemDragEnd = function () {
5085 this.unsetDragItem();
5086 return false;
5087 };
5088
5089 /**
5090 * Handle drop event and switch the order of the items accordingly
5091 *
5092 * @private
5093 * @param {OO.ui.mixin.DraggableElement} item Dropped item
5094 * @fires reorder
5095 */
5096 OO.ui.mixin.DraggableGroupElement.prototype.onItemDrop = function ( item ) {
5097 var toIndex = item.getIndex();
5098 // Check if the dropped item is from the current group
5099 // TODO: Figure out a way to configure a list of legally droppable
5100 // elements even if they are not yet in the list
5101 if ( this.getDragItem() ) {
5102 // If the insertion point is 'after', the insertion index
5103 // is shifted to the right (or to the left in RTL, hence 'after')
5104 if ( this.sideInsertion === 'after' ) {
5105 toIndex++;
5106 }
5107 // Emit change event
5108 this.emit( 'reorder', this.getDragItem(), toIndex );
5109 }
5110 this.unsetDragItem();
5111 // Return false to prevent propogation
5112 return false;
5113 };
5114
5115 /**
5116 * Handle dragleave event.
5117 *
5118 * @private
5119 */
5120 OO.ui.mixin.DraggableGroupElement.prototype.onDragLeave = function () {
5121 // This means the item was dragged outside the widget
5122 this.$placeholder
5123 .css( 'left', 0 )
5124 .addClass( 'oo-ui-element-hidden' );
5125 };
5126
5127 /**
5128 * Respond to dragover event
5129 *
5130 * @private
5131 * @param {jQuery.Event} event Event details
5132 */
5133 OO.ui.mixin.DraggableGroupElement.prototype.onDragOver = function ( e ) {
5134 var dragOverObj, $optionWidget, itemOffset, itemMidpoint, itemBoundingRect,
5135 itemSize, cssOutput, dragPosition, itemIndex, itemPosition,
5136 clientX = e.originalEvent.clientX,
5137 clientY = e.originalEvent.clientY;
5138
5139 // Get the OptionWidget item we are dragging over
5140 dragOverObj = this.getElementDocument().elementFromPoint( clientX, clientY );
5141 $optionWidget = $( dragOverObj ).closest( '.oo-ui-draggableElement' );
5142 if ( $optionWidget[ 0 ] ) {
5143 itemOffset = $optionWidget.offset();
5144 itemBoundingRect = $optionWidget[ 0 ].getBoundingClientRect();
5145 itemPosition = $optionWidget.position();
5146 itemIndex = $optionWidget.data( 'index' );
5147 }
5148
5149 if (
5150 itemOffset &&
5151 this.isDragging() &&
5152 itemIndex !== this.getDragItem().getIndex()
5153 ) {
5154 if ( this.orientation === 'horizontal' ) {
5155 // Calculate where the mouse is relative to the item width
5156 itemSize = itemBoundingRect.width;
5157 itemMidpoint = itemBoundingRect.left + itemSize / 2;
5158 dragPosition = clientX;
5159 // Which side of the item we hover over will dictate
5160 // where the placeholder will appear, on the left or
5161 // on the right
5162 cssOutput = {
5163 left: dragPosition < itemMidpoint ? itemPosition.left : itemPosition.left + itemSize,
5164 top: itemPosition.top
5165 };
5166 } else {
5167 // Calculate where the mouse is relative to the item height
5168 itemSize = itemBoundingRect.height;
5169 itemMidpoint = itemBoundingRect.top + itemSize / 2;
5170 dragPosition = clientY;
5171 // Which side of the item we hover over will dictate
5172 // where the placeholder will appear, on the top or
5173 // on the bottom
5174 cssOutput = {
5175 top: dragPosition < itemMidpoint ? itemPosition.top : itemPosition.top + itemSize,
5176 left: itemPosition.left
5177 };
5178 }
5179 // Store whether we are before or after an item to rearrange
5180 // For horizontal layout, we need to account for RTL, as this is flipped
5181 if ( this.orientation === 'horizontal' && this.$element.css( 'direction' ) === 'rtl' ) {
5182 this.sideInsertion = dragPosition < itemMidpoint ? 'after' : 'before';
5183 } else {
5184 this.sideInsertion = dragPosition < itemMidpoint ? 'before' : 'after';
5185 }
5186 // Add drop indicator between objects
5187 this.$placeholder
5188 .css( cssOutput )
5189 .removeClass( 'oo-ui-element-hidden' );
5190 } else {
5191 // This means the item was dragged outside the widget
5192 this.$placeholder
5193 .css( 'left', 0 )
5194 .addClass( 'oo-ui-element-hidden' );
5195 }
5196 // Prevent default
5197 e.preventDefault();
5198 };
5199
5200 /**
5201 * Set a dragged item
5202 *
5203 * @param {OO.ui.mixin.DraggableElement} item Dragged item
5204 */
5205 OO.ui.mixin.DraggableGroupElement.prototype.setDragItem = function ( item ) {
5206 this.dragItem = item;
5207 };
5208
5209 /**
5210 * Unset the current dragged item
5211 */
5212 OO.ui.mixin.DraggableGroupElement.prototype.unsetDragItem = function () {
5213 this.dragItem = null;
5214 this.itemDragOver = null;
5215 this.$placeholder.addClass( 'oo-ui-element-hidden' );
5216 this.sideInsertion = '';
5217 };
5218
5219 /**
5220 * Get the item that is currently being dragged.
5221 *
5222 * @return {OO.ui.mixin.DraggableElement|null} The currently dragged item, or `null` if no item is being dragged
5223 */
5224 OO.ui.mixin.DraggableGroupElement.prototype.getDragItem = function () {
5225 return this.dragItem;
5226 };
5227
5228 /**
5229 * Check if an item in the group is currently being dragged.
5230 *
5231 * @return {Boolean} Item is being dragged
5232 */
5233 OO.ui.mixin.DraggableGroupElement.prototype.isDragging = function () {
5234 return this.getDragItem() !== null;
5235 };
5236
5237 /**
5238 * IconElement is often mixed into other classes to generate an icon.
5239 * Icons are graphics, about the size of normal text. They are used to aid the user
5240 * in locating a control or to convey information in a space-efficient way. See the
5241 * [OOjs UI documentation on MediaWiki] [1] for a list of icons
5242 * included in the library.
5243 *
5244 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
5245 *
5246 * @abstract
5247 * @class
5248 *
5249 * @constructor
5250 * @param {Object} [config] Configuration options
5251 * @cfg {jQuery} [$icon] The icon element created by the class. If this configuration is omitted,
5252 * the icon element will use a generated `<span>`. To use a different HTML tag, or to specify that
5253 * the icon element be set to an existing icon instead of the one generated by this class, set a
5254 * value using a jQuery selection. For example:
5255 *
5256 * // Use a <div> tag instead of a <span>
5257 * $icon: $("<div>")
5258 * // Use an existing icon element instead of the one generated by the class
5259 * $icon: this.$element
5260 * // Use an icon element from a child widget
5261 * $icon: this.childwidget.$element
5262 * @cfg {Object|string} [icon=''] The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of
5263 * symbolic names. A map is used for i18n purposes and contains a `default` icon
5264 * name and additional names keyed by language code. The `default` name is used when no icon is keyed
5265 * by the user's language.
5266 *
5267 * Example of an i18n map:
5268 *
5269 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
5270 * See the [OOjs UI documentation on MediaWiki] [2] for a list of icons included in the library.
5271 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
5272 * @cfg {string|Function} [iconTitle] A text string used as the icon title, or a function that returns title
5273 * text. The icon title is displayed when users move the mouse over the icon.
5274 */
5275 OO.ui.mixin.IconElement = function OoUiMixinIconElement( config ) {
5276 // Configuration initialization
5277 config = config || {};
5278
5279 // Properties
5280 this.$icon = null;
5281 this.icon = null;
5282 this.iconTitle = null;
5283
5284 // Initialization
5285 this.setIcon( config.icon || this.constructor.static.icon );
5286 this.setIconTitle( config.iconTitle || this.constructor.static.iconTitle );
5287 this.setIconElement( config.$icon || $( '<span>' ) );
5288 };
5289
5290 /* Setup */
5291
5292 OO.initClass( OO.ui.mixin.IconElement );
5293
5294 /* Static Properties */
5295
5296 /**
5297 * The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of symbolic names. A map is used
5298 * for i18n purposes and contains a `default` icon name and additional names keyed by
5299 * language code. The `default` name is used when no icon is keyed by the user's language.
5300 *
5301 * Example of an i18n map:
5302 *
5303 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
5304 *
5305 * Note: the static property will be overridden if the #icon configuration is used.
5306 *
5307 * @static
5308 * @inheritable
5309 * @property {Object|string}
5310 */
5311 OO.ui.mixin.IconElement.static.icon = null;
5312
5313 /**
5314 * The icon title, displayed when users move the mouse over the icon. The value can be text, a
5315 * function that returns title text, or `null` for no title.
5316 *
5317 * The static property will be overridden if the #iconTitle configuration is used.
5318 *
5319 * @static
5320 * @inheritable
5321 * @property {string|Function|null}
5322 */
5323 OO.ui.mixin.IconElement.static.iconTitle = null;
5324
5325 /* Methods */
5326
5327 /**
5328 * Set the icon element. This method is used to retarget an icon mixin so that its functionality
5329 * applies to the specified icon element instead of the one created by the class. If an icon
5330 * element is already set, the mixin’s effect on that element is removed. Generated CSS classes
5331 * and mixin methods will no longer affect the element.
5332 *
5333 * @param {jQuery} $icon Element to use as icon
5334 */
5335 OO.ui.mixin.IconElement.prototype.setIconElement = function ( $icon ) {
5336 if ( this.$icon ) {
5337 this.$icon
5338 .removeClass( 'oo-ui-iconElement-icon oo-ui-icon-' + this.icon )
5339 .removeAttr( 'title' );
5340 }
5341
5342 this.$icon = $icon
5343 .addClass( 'oo-ui-iconElement-icon' )
5344 .toggleClass( 'oo-ui-icon-' + this.icon, !!this.icon );
5345 if ( this.iconTitle !== null ) {
5346 this.$icon.attr( 'title', this.iconTitle );
5347 }
5348 };
5349
5350 /**
5351 * Set icon by symbolic name (e.g., ‘remove’ or ‘menu’). Use `null` to remove an icon.
5352 * The icon parameter can also be set to a map of icon names. See the #icon config setting
5353 * for an example.
5354 *
5355 * @param {Object|string|null} icon A symbolic icon name, a {@link #icon map of icon names} keyed
5356 * by language code, or `null` to remove the icon.
5357 * @chainable
5358 */
5359 OO.ui.mixin.IconElement.prototype.setIcon = function ( icon ) {
5360 icon = OO.isPlainObject( icon ) ? OO.ui.getLocalValue( icon, null, 'default' ) : icon;
5361 icon = typeof icon === 'string' && icon.trim().length ? icon.trim() : null;
5362
5363 if ( this.icon !== icon ) {
5364 if ( this.$icon ) {
5365 if ( this.icon !== null ) {
5366 this.$icon.removeClass( 'oo-ui-icon-' + this.icon );
5367 }
5368 if ( icon !== null ) {
5369 this.$icon.addClass( 'oo-ui-icon-' + icon );
5370 }
5371 }
5372 this.icon = icon;
5373 }
5374
5375 this.$element.toggleClass( 'oo-ui-iconElement', !!this.icon );
5376 this.updateThemeClasses();
5377
5378 return this;
5379 };
5380
5381 /**
5382 * Set the icon title. Use `null` to remove the title.
5383 *
5384 * @param {string|Function|null} iconTitle A text string used as the icon title,
5385 * a function that returns title text, or `null` for no title.
5386 * @chainable
5387 */
5388 OO.ui.mixin.IconElement.prototype.setIconTitle = function ( iconTitle ) {
5389 iconTitle = typeof iconTitle === 'function' ||
5390 ( typeof iconTitle === 'string' && iconTitle.length ) ?
5391 OO.ui.resolveMsg( iconTitle ) : null;
5392
5393 if ( this.iconTitle !== iconTitle ) {
5394 this.iconTitle = iconTitle;
5395 if ( this.$icon ) {
5396 if ( this.iconTitle !== null ) {
5397 this.$icon.attr( 'title', iconTitle );
5398 } else {
5399 this.$icon.removeAttr( 'title' );
5400 }
5401 }
5402 }
5403
5404 return this;
5405 };
5406
5407 /**
5408 * Get the symbolic name of the icon.
5409 *
5410 * @return {string} Icon name
5411 */
5412 OO.ui.mixin.IconElement.prototype.getIcon = function () {
5413 return this.icon;
5414 };
5415
5416 /**
5417 * Get the icon title. The title text is displayed when a user moves the mouse over the icon.
5418 *
5419 * @return {string} Icon title text
5420 */
5421 OO.ui.mixin.IconElement.prototype.getIconTitle = function () {
5422 return this.iconTitle;
5423 };
5424
5425 /**
5426 * IndicatorElement is often mixed into other classes to generate an indicator.
5427 * Indicators are small graphics that are generally used in two ways:
5428 *
5429 * - To draw attention to the status of an item. For example, an indicator might be
5430 * used to show that an item in a list has errors that need to be resolved.
5431 * - To clarify the function of a control that acts in an exceptional way (a button
5432 * that opens a menu instead of performing an action directly, for example).
5433 *
5434 * For a list of indicators included in the library, please see the
5435 * [OOjs UI documentation on MediaWiki] [1].
5436 *
5437 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
5438 *
5439 * @abstract
5440 * @class
5441 *
5442 * @constructor
5443 * @param {Object} [config] Configuration options
5444 * @cfg {jQuery} [$indicator] The indicator element created by the class. If this
5445 * configuration is omitted, the indicator element will use a generated `<span>`.
5446 * @cfg {string} [indicator] Symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
5447 * See the [OOjs UI documentation on MediaWiki][2] for a list of indicators included
5448 * in the library.
5449 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
5450 * @cfg {string|Function} [indicatorTitle] A text string used as the indicator title,
5451 * or a function that returns title text. The indicator title is displayed when users move
5452 * the mouse over the indicator.
5453 */
5454 OO.ui.mixin.IndicatorElement = function OoUiMixinIndicatorElement( config ) {
5455 // Configuration initialization
5456 config = config || {};
5457
5458 // Properties
5459 this.$indicator = null;
5460 this.indicator = null;
5461 this.indicatorTitle = null;
5462
5463 // Initialization
5464 this.setIndicator( config.indicator || this.constructor.static.indicator );
5465 this.setIndicatorTitle( config.indicatorTitle || this.constructor.static.indicatorTitle );
5466 this.setIndicatorElement( config.$indicator || $( '<span>' ) );
5467 };
5468
5469 /* Setup */
5470
5471 OO.initClass( OO.ui.mixin.IndicatorElement );
5472
5473 /* Static Properties */
5474
5475 /**
5476 * Symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
5477 * The static property will be overridden if the #indicator configuration is used.
5478 *
5479 * @static
5480 * @inheritable
5481 * @property {string|null}
5482 */
5483 OO.ui.mixin.IndicatorElement.static.indicator = null;
5484
5485 /**
5486 * A text string used as the indicator title, a function that returns title text, or `null`
5487 * for no title. The static property will be overridden if the #indicatorTitle configuration is used.
5488 *
5489 * @static
5490 * @inheritable
5491 * @property {string|Function|null}
5492 */
5493 OO.ui.mixin.IndicatorElement.static.indicatorTitle = null;
5494
5495 /* Methods */
5496
5497 /**
5498 * Set the indicator element.
5499 *
5500 * If an element is already set, it will be cleaned up before setting up the new element.
5501 *
5502 * @param {jQuery} $indicator Element to use as indicator
5503 */
5504 OO.ui.mixin.IndicatorElement.prototype.setIndicatorElement = function ( $indicator ) {
5505 if ( this.$indicator ) {
5506 this.$indicator
5507 .removeClass( 'oo-ui-indicatorElement-indicator oo-ui-indicator-' + this.indicator )
5508 .removeAttr( 'title' );
5509 }
5510
5511 this.$indicator = $indicator
5512 .addClass( 'oo-ui-indicatorElement-indicator' )
5513 .toggleClass( 'oo-ui-indicator-' + this.indicator, !!this.indicator );
5514 if ( this.indicatorTitle !== null ) {
5515 this.$indicator.attr( 'title', this.indicatorTitle );
5516 }
5517 };
5518
5519 /**
5520 * Set the indicator by its symbolic name: ‘alert’, ‘down’, ‘next’, ‘previous’, ‘required’, ‘up’. Use `null` to remove the indicator.
5521 *
5522 * @param {string|null} indicator Symbolic name of indicator, or `null` for no indicator
5523 * @chainable
5524 */
5525 OO.ui.mixin.IndicatorElement.prototype.setIndicator = function ( indicator ) {
5526 indicator = typeof indicator === 'string' && indicator.length ? indicator.trim() : null;
5527
5528 if ( this.indicator !== indicator ) {
5529 if ( this.$indicator ) {
5530 if ( this.indicator !== null ) {
5531 this.$indicator.removeClass( 'oo-ui-indicator-' + this.indicator );
5532 }
5533 if ( indicator !== null ) {
5534 this.$indicator.addClass( 'oo-ui-indicator-' + indicator );
5535 }
5536 }
5537 this.indicator = indicator;
5538 }
5539
5540 this.$element.toggleClass( 'oo-ui-indicatorElement', !!this.indicator );
5541 this.updateThemeClasses();
5542
5543 return this;
5544 };
5545
5546 /**
5547 * Set the indicator title.
5548 *
5549 * The title is displayed when a user moves the mouse over the indicator.
5550 *
5551 * @param {string|Function|null} indicator Indicator title text, a function that returns text, or
5552 * `null` for no indicator title
5553 * @chainable
5554 */
5555 OO.ui.mixin.IndicatorElement.prototype.setIndicatorTitle = function ( indicatorTitle ) {
5556 indicatorTitle = typeof indicatorTitle === 'function' ||
5557 ( typeof indicatorTitle === 'string' && indicatorTitle.length ) ?
5558 OO.ui.resolveMsg( indicatorTitle ) : null;
5559
5560 if ( this.indicatorTitle !== indicatorTitle ) {
5561 this.indicatorTitle = indicatorTitle;
5562 if ( this.$indicator ) {
5563 if ( this.indicatorTitle !== null ) {
5564 this.$indicator.attr( 'title', indicatorTitle );
5565 } else {
5566 this.$indicator.removeAttr( 'title' );
5567 }
5568 }
5569 }
5570
5571 return this;
5572 };
5573
5574 /**
5575 * Get the symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
5576 *
5577 * @return {string} Symbolic name of indicator
5578 */
5579 OO.ui.mixin.IndicatorElement.prototype.getIndicator = function () {
5580 return this.indicator;
5581 };
5582
5583 /**
5584 * Get the indicator title.
5585 *
5586 * The title is displayed when a user moves the mouse over the indicator.
5587 *
5588 * @return {string} Indicator title text
5589 */
5590 OO.ui.mixin.IndicatorElement.prototype.getIndicatorTitle = function () {
5591 return this.indicatorTitle;
5592 };
5593
5594 /**
5595 * LabelElement is often mixed into other classes to generate a label, which
5596 * helps identify the function of an interface element.
5597 * See the [OOjs UI documentation on MediaWiki] [1] for more information.
5598 *
5599 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Labels
5600 *
5601 * @abstract
5602 * @class
5603 *
5604 * @constructor
5605 * @param {Object} [config] Configuration options
5606 * @cfg {jQuery} [$label] The label element created by the class. If this
5607 * configuration is omitted, the label element will use a generated `<span>`.
5608 * @cfg {jQuery|string|Function|OO.ui.HtmlSnippet} [label] The label text. The label can be specified
5609 * as a plaintext string, a jQuery selection of elements, or a function that will produce a string
5610 * in the future. See the [OOjs UI documentation on MediaWiki] [2] for examples.
5611 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Labels
5612 * @cfg {boolean} [autoFitLabel=true] Fit the label to the width of the parent element.
5613 * The label will be truncated to fit if necessary.
5614 */
5615 OO.ui.mixin.LabelElement = function OoUiMixinLabelElement( config ) {
5616 // Configuration initialization
5617 config = config || {};
5618
5619 // Properties
5620 this.$label = null;
5621 this.label = null;
5622 this.autoFitLabel = config.autoFitLabel === undefined || !!config.autoFitLabel;
5623
5624 // Initialization
5625 this.setLabel( config.label || this.constructor.static.label );
5626 this.setLabelElement( config.$label || $( '<span>' ) );
5627 };
5628
5629 /* Setup */
5630
5631 OO.initClass( OO.ui.mixin.LabelElement );
5632
5633 /* Events */
5634
5635 /**
5636 * @event labelChange
5637 * @param {string} value
5638 */
5639
5640 /* Static Properties */
5641
5642 /**
5643 * The label text. The label can be specified as a plaintext string, a function that will
5644 * produce a string in the future, or `null` for no label. The static value will
5645 * be overridden if a label is specified with the #label config option.
5646 *
5647 * @static
5648 * @inheritable
5649 * @property {string|Function|null}
5650 */
5651 OO.ui.mixin.LabelElement.static.label = null;
5652
5653 /* Methods */
5654
5655 /**
5656 * Set the label element.
5657 *
5658 * If an element is already set, it will be cleaned up before setting up the new element.
5659 *
5660 * @param {jQuery} $label Element to use as label
5661 */
5662 OO.ui.mixin.LabelElement.prototype.setLabelElement = function ( $label ) {
5663 if ( this.$label ) {
5664 this.$label.removeClass( 'oo-ui-labelElement-label' ).empty();
5665 }
5666
5667 this.$label = $label.addClass( 'oo-ui-labelElement-label' );
5668 this.setLabelContent( this.label );
5669 };
5670
5671 /**
5672 * Set the label.
5673 *
5674 * An empty string will result in the label being hidden. A string containing only whitespace will
5675 * be converted to a single `&nbsp;`.
5676 *
5677 * @param {jQuery|string|OO.ui.HtmlSnippet|Function|null} label Label nodes; text; a function that returns nodes or
5678 * text; or null for no label
5679 * @chainable
5680 */
5681 OO.ui.mixin.LabelElement.prototype.setLabel = function ( label ) {
5682 label = typeof label === 'function' ? OO.ui.resolveMsg( label ) : label;
5683 label = ( ( typeof label === 'string' && label.length ) || label instanceof jQuery || label instanceof OO.ui.HtmlSnippet ) ? label : null;
5684
5685 this.$element.toggleClass( 'oo-ui-labelElement', !!label );
5686
5687 if ( this.label !== label ) {
5688 if ( this.$label ) {
5689 this.setLabelContent( label );
5690 }
5691 this.label = label;
5692 this.emit( 'labelChange' );
5693 }
5694
5695 return this;
5696 };
5697
5698 /**
5699 * Get the label.
5700 *
5701 * @return {jQuery|string|Function|null} Label nodes; text; a function that returns nodes or
5702 * text; or null for no label
5703 */
5704 OO.ui.mixin.LabelElement.prototype.getLabel = function () {
5705 return this.label;
5706 };
5707
5708 /**
5709 * Fit the label.
5710 *
5711 * @chainable
5712 */
5713 OO.ui.mixin.LabelElement.prototype.fitLabel = function () {
5714 if ( this.$label && this.$label.autoEllipsis && this.autoFitLabel ) {
5715 this.$label.autoEllipsis( { hasSpan: false, tooltip: true } );
5716 }
5717
5718 return this;
5719 };
5720
5721 /**
5722 * Set the content of the label.
5723 *
5724 * Do not call this method until after the label element has been set by #setLabelElement.
5725 *
5726 * @private
5727 * @param {jQuery|string|Function|null} label Label nodes; text; a function that returns nodes or
5728 * text; or null for no label
5729 */
5730 OO.ui.mixin.LabelElement.prototype.setLabelContent = function ( label ) {
5731 if ( typeof label === 'string' ) {
5732 if ( label.match( /^\s*$/ ) ) {
5733 // Convert whitespace only string to a single non-breaking space
5734 this.$label.html( '&nbsp;' );
5735 } else {
5736 this.$label.text( label );
5737 }
5738 } else if ( label instanceof OO.ui.HtmlSnippet ) {
5739 this.$label.html( label.toString() );
5740 } else if ( label instanceof jQuery ) {
5741 this.$label.empty().append( label );
5742 } else {
5743 this.$label.empty();
5744 }
5745 };
5746
5747 /**
5748 * LookupElement is a mixin that creates a {@link OO.ui.TextInputMenuSelectWidget menu} of suggested values for
5749 * a {@link OO.ui.TextInputWidget text input widget}. Suggested values are based on the characters the user types
5750 * into the text input field and, in general, the menu is only displayed when the user types. If a suggested value is chosen
5751 * from the lookup menu, that value becomes the value of the input field.
5752 *
5753 * Note that a new menu of suggested items is displayed when a value is chosen from the lookup menu. If this is
5754 * not the desired behavior, disable lookup menus with the #setLookupsDisabled method, then set the value, then
5755 * re-enable lookups.
5756 *
5757 * See the [OOjs UI demos][1] for an example.
5758 *
5759 * [1]: https://tools.wmflabs.org/oojs-ui/oojs-ui/demos/index.html#widgets-apex-vector-ltr
5760 *
5761 * @class
5762 * @abstract
5763 *
5764 * @constructor
5765 * @param {Object} [config] Configuration options
5766 * @cfg {jQuery} [$overlay] Overlay for the lookup menu; defaults to relative positioning
5767 * @cfg {jQuery} [$container=this.$element] The container element. The lookup menu is rendered beneath the specified element.
5768 * @cfg {boolean} [allowSuggestionsWhenEmpty=false] Request and display a lookup menu when the text input is empty.
5769 * By default, the lookup menu is not generated and displayed until the user begins to type.
5770 */
5771 OO.ui.mixin.LookupElement = function OoUiMixinLookupElement( config ) {
5772 // Configuration initialization
5773 config = config || {};
5774
5775 // Properties
5776 this.$overlay = config.$overlay || this.$element;
5777 this.lookupMenu = new OO.ui.TextInputMenuSelectWidget( this, {
5778 widget: this,
5779 input: this,
5780 $container: config.$container
5781 } );
5782
5783 this.allowSuggestionsWhenEmpty = config.allowSuggestionsWhenEmpty || false;
5784
5785 this.lookupCache = {};
5786 this.lookupQuery = null;
5787 this.lookupRequest = null;
5788 this.lookupsDisabled = false;
5789 this.lookupInputFocused = false;
5790
5791 // Events
5792 this.$input.on( {
5793 focus: this.onLookupInputFocus.bind( this ),
5794 blur: this.onLookupInputBlur.bind( this ),
5795 mousedown: this.onLookupInputMouseDown.bind( this )
5796 } );
5797 this.connect( this, { change: 'onLookupInputChange' } );
5798 this.lookupMenu.connect( this, {
5799 toggle: 'onLookupMenuToggle',
5800 choose: 'onLookupMenuItemChoose'
5801 } );
5802
5803 // Initialization
5804 this.$element.addClass( 'oo-ui-lookupElement' );
5805 this.lookupMenu.$element.addClass( 'oo-ui-lookupElement-menu' );
5806 this.$overlay.append( this.lookupMenu.$element );
5807 };
5808
5809 /* Methods */
5810
5811 /**
5812 * Handle input focus event.
5813 *
5814 * @protected
5815 * @param {jQuery.Event} e Input focus event
5816 */
5817 OO.ui.mixin.LookupElement.prototype.onLookupInputFocus = function () {
5818 this.lookupInputFocused = true;
5819 this.populateLookupMenu();
5820 };
5821
5822 /**
5823 * Handle input blur event.
5824 *
5825 * @protected
5826 * @param {jQuery.Event} e Input blur event
5827 */
5828 OO.ui.mixin.LookupElement.prototype.onLookupInputBlur = function () {
5829 this.closeLookupMenu();
5830 this.lookupInputFocused = false;
5831 };
5832
5833 /**
5834 * Handle input mouse down event.
5835 *
5836 * @protected
5837 * @param {jQuery.Event} e Input mouse down event
5838 */
5839 OO.ui.mixin.LookupElement.prototype.onLookupInputMouseDown = function () {
5840 // Only open the menu if the input was already focused.
5841 // This way we allow the user to open the menu again after closing it with Esc
5842 // by clicking in the input. Opening (and populating) the menu when initially
5843 // clicking into the input is handled by the focus handler.
5844 if ( this.lookupInputFocused && !this.lookupMenu.isVisible() ) {
5845 this.populateLookupMenu();
5846 }
5847 };
5848
5849 /**
5850 * Handle input change event.
5851 *
5852 * @protected
5853 * @param {string} value New input value
5854 */
5855 OO.ui.mixin.LookupElement.prototype.onLookupInputChange = function () {
5856 if ( this.lookupInputFocused ) {
5857 this.populateLookupMenu();
5858 }
5859 };
5860
5861 /**
5862 * Handle the lookup menu being shown/hidden.
5863 *
5864 * @protected
5865 * @param {boolean} visible Whether the lookup menu is now visible.
5866 */
5867 OO.ui.mixin.LookupElement.prototype.onLookupMenuToggle = function ( visible ) {
5868 if ( !visible ) {
5869 // When the menu is hidden, abort any active request and clear the menu.
5870 // This has to be done here in addition to closeLookupMenu(), because
5871 // MenuSelectWidget will close itself when the user presses Esc.
5872 this.abortLookupRequest();
5873 this.lookupMenu.clearItems();
5874 }
5875 };
5876
5877 /**
5878 * Handle menu item 'choose' event, updating the text input value to the value of the clicked item.
5879 *
5880 * @protected
5881 * @param {OO.ui.MenuOptionWidget} item Selected item
5882 */
5883 OO.ui.mixin.LookupElement.prototype.onLookupMenuItemChoose = function ( item ) {
5884 this.setValue( item.getData() );
5885 };
5886
5887 /**
5888 * Get lookup menu.
5889 *
5890 * @private
5891 * @return {OO.ui.TextInputMenuSelectWidget}
5892 */
5893 OO.ui.mixin.LookupElement.prototype.getLookupMenu = function () {
5894 return this.lookupMenu;
5895 };
5896
5897 /**
5898 * Disable or re-enable lookups.
5899 *
5900 * When lookups are disabled, calls to #populateLookupMenu will be ignored.
5901 *
5902 * @param {boolean} disabled Disable lookups
5903 */
5904 OO.ui.mixin.LookupElement.prototype.setLookupsDisabled = function ( disabled ) {
5905 this.lookupsDisabled = !!disabled;
5906 };
5907
5908 /**
5909 * Open the menu. If there are no entries in the menu, this does nothing.
5910 *
5911 * @private
5912 * @chainable
5913 */
5914 OO.ui.mixin.LookupElement.prototype.openLookupMenu = function () {
5915 if ( !this.lookupMenu.isEmpty() ) {
5916 this.lookupMenu.toggle( true );
5917 }
5918 return this;
5919 };
5920
5921 /**
5922 * Close the menu, empty it, and abort any pending request.
5923 *
5924 * @private
5925 * @chainable
5926 */
5927 OO.ui.mixin.LookupElement.prototype.closeLookupMenu = function () {
5928 this.lookupMenu.toggle( false );
5929 this.abortLookupRequest();
5930 this.lookupMenu.clearItems();
5931 return this;
5932 };
5933
5934 /**
5935 * Request menu items based on the input's current value, and when they arrive,
5936 * populate the menu with these items and show the menu.
5937 *
5938 * If lookups have been disabled with #setLookupsDisabled, this function does nothing.
5939 *
5940 * @private
5941 * @chainable
5942 */
5943 OO.ui.mixin.LookupElement.prototype.populateLookupMenu = function () {
5944 var widget = this,
5945 value = this.getValue();
5946
5947 if ( this.lookupsDisabled ) {
5948 return;
5949 }
5950
5951 // If the input is empty, clear the menu, unless suggestions when empty are allowed.
5952 if ( !this.allowSuggestionsWhenEmpty && value === '' ) {
5953 this.closeLookupMenu();
5954 // Skip population if there is already a request pending for the current value
5955 } else if ( value !== this.lookupQuery ) {
5956 this.getLookupMenuItems()
5957 .done( function ( items ) {
5958 widget.lookupMenu.clearItems();
5959 if ( items.length ) {
5960 widget.lookupMenu
5961 .addItems( items )
5962 .toggle( true );
5963 widget.initializeLookupMenuSelection();
5964 } else {
5965 widget.lookupMenu.toggle( false );
5966 }
5967 } )
5968 .fail( function () {
5969 widget.lookupMenu.clearItems();
5970 } );
5971 }
5972
5973 return this;
5974 };
5975
5976 /**
5977 * Highlight the first selectable item in the menu.
5978 *
5979 * @private
5980 * @chainable
5981 */
5982 OO.ui.mixin.LookupElement.prototype.initializeLookupMenuSelection = function () {
5983 if ( !this.lookupMenu.getSelectedItem() ) {
5984 this.lookupMenu.highlightItem( this.lookupMenu.getFirstSelectableItem() );
5985 }
5986 };
5987
5988 /**
5989 * Get lookup menu items for the current query.
5990 *
5991 * @private
5992 * @return {jQuery.Promise} Promise object which will be passed menu items as the first argument of
5993 * the done event. If the request was aborted to make way for a subsequent request, this promise
5994 * will not be rejected: it will remain pending forever.
5995 */
5996 OO.ui.mixin.LookupElement.prototype.getLookupMenuItems = function () {
5997 var widget = this,
5998 value = this.getValue(),
5999 deferred = $.Deferred(),
6000 ourRequest;
6001
6002 this.abortLookupRequest();
6003 if ( Object.prototype.hasOwnProperty.call( this.lookupCache, value ) ) {
6004 deferred.resolve( this.getLookupMenuOptionsFromData( this.lookupCache[ value ] ) );
6005 } else {
6006 this.pushPending();
6007 this.lookupQuery = value;
6008 ourRequest = this.lookupRequest = this.getLookupRequest();
6009 ourRequest
6010 .always( function () {
6011 // We need to pop pending even if this is an old request, otherwise
6012 // the widget will remain pending forever.
6013 // TODO: this assumes that an aborted request will fail or succeed soon after
6014 // being aborted, or at least eventually. It would be nice if we could popPending()
6015 // at abort time, but only if we knew that we hadn't already called popPending()
6016 // for that request.
6017 widget.popPending();
6018 } )
6019 .done( function ( response ) {
6020 // If this is an old request (and aborting it somehow caused it to still succeed),
6021 // ignore its success completely
6022 if ( ourRequest === widget.lookupRequest ) {
6023 widget.lookupQuery = null;
6024 widget.lookupRequest = null;
6025 widget.lookupCache[ value ] = widget.getLookupCacheDataFromResponse( response );
6026 deferred.resolve( widget.getLookupMenuOptionsFromData( widget.lookupCache[ value ] ) );
6027 }
6028 } )
6029 .fail( function () {
6030 // If this is an old request (or a request failing because it's being aborted),
6031 // ignore its failure completely
6032 if ( ourRequest === widget.lookupRequest ) {
6033 widget.lookupQuery = null;
6034 widget.lookupRequest = null;
6035 deferred.reject();
6036 }
6037 } );
6038 }
6039 return deferred.promise();
6040 };
6041
6042 /**
6043 * Abort the currently pending lookup request, if any.
6044 *
6045 * @private
6046 */
6047 OO.ui.mixin.LookupElement.prototype.abortLookupRequest = function () {
6048 var oldRequest = this.lookupRequest;
6049 if ( oldRequest ) {
6050 // First unset this.lookupRequest to the fail handler will notice
6051 // that the request is no longer current
6052 this.lookupRequest = null;
6053 this.lookupQuery = null;
6054 oldRequest.abort();
6055 }
6056 };
6057
6058 /**
6059 * Get a new request object of the current lookup query value.
6060 *
6061 * @protected
6062 * @abstract
6063 * @return {jQuery.Promise} jQuery AJAX object, or promise object with an .abort() method
6064 */
6065 OO.ui.mixin.LookupElement.prototype.getLookupRequest = function () {
6066 // Stub, implemented in subclass
6067 return null;
6068 };
6069
6070 /**
6071 * Pre-process data returned by the request from #getLookupRequest.
6072 *
6073 * The return value of this function will be cached, and any further queries for the given value
6074 * will use the cache rather than doing API requests.
6075 *
6076 * @protected
6077 * @abstract
6078 * @param {Mixed} response Response from server
6079 * @return {Mixed} Cached result data
6080 */
6081 OO.ui.mixin.LookupElement.prototype.getLookupCacheDataFromResponse = function () {
6082 // Stub, implemented in subclass
6083 return [];
6084 };
6085
6086 /**
6087 * Get a list of menu option widgets from the (possibly cached) data returned by
6088 * #getLookupCacheDataFromResponse.
6089 *
6090 * @protected
6091 * @abstract
6092 * @param {Mixed} data Cached result data, usually an array
6093 * @return {OO.ui.MenuOptionWidget[]} Menu items
6094 */
6095 OO.ui.mixin.LookupElement.prototype.getLookupMenuOptionsFromData = function () {
6096 // Stub, implemented in subclass
6097 return [];
6098 };
6099
6100 /**
6101 * Set the read-only state of the widget.
6102 *
6103 * This will also disable/enable the lookups functionality.
6104 *
6105 * @param {boolean} readOnly Make input read-only
6106 * @chainable
6107 */
6108 OO.ui.mixin.LookupElement.prototype.setReadOnly = function ( readOnly ) {
6109 // Parent method
6110 // Note: Calling #setReadOnly this way assumes this is mixed into an OO.ui.TextInputWidget
6111 OO.ui.TextInputWidget.prototype.setReadOnly.call( this, readOnly );
6112
6113 this.setLookupsDisabled( readOnly );
6114 // During construction, #setReadOnly is called before the OO.ui.mixin.LookupElement constructor
6115 if ( readOnly && this.lookupMenu ) {
6116 this.closeLookupMenu();
6117 }
6118
6119 return this;
6120 };
6121
6122 /**
6123 * PopupElement is mixed into other classes to generate a {@link OO.ui.PopupWidget popup widget}.
6124 * A popup is a container for content. It is overlaid and positioned absolutely. By default, each
6125 * popup has an anchor, which is an arrow-like protrusion that points toward the popup’s origin.
6126 * See {@link OO.ui.PopupWidget PopupWidget} for an example.
6127 *
6128 * @abstract
6129 * @class
6130 *
6131 * @constructor
6132 * @param {Object} [config] Configuration options
6133 * @cfg {Object} [popup] Configuration to pass to popup
6134 * @cfg {boolean} [popup.autoClose=true] Popup auto-closes when it loses focus
6135 */
6136 OO.ui.mixin.PopupElement = function OoUiMixinPopupElement( config ) {
6137 // Configuration initialization
6138 config = config || {};
6139
6140 // Properties
6141 this.popup = new OO.ui.PopupWidget( $.extend(
6142 { autoClose: true },
6143 config.popup,
6144 { $autoCloseIgnore: this.$element }
6145 ) );
6146 };
6147
6148 /* Methods */
6149
6150 /**
6151 * Get popup.
6152 *
6153 * @return {OO.ui.PopupWidget} Popup widget
6154 */
6155 OO.ui.mixin.PopupElement.prototype.getPopup = function () {
6156 return this.popup;
6157 };
6158
6159 /**
6160 * The FlaggedElement class is an attribute mixin, meaning that it is used to add
6161 * additional functionality to an element created by another class. The class provides
6162 * a ‘flags’ property assigned the name (or an array of names) of styling flags,
6163 * which are used to customize the look and feel of a widget to better describe its
6164 * importance and functionality.
6165 *
6166 * The library currently contains the following styling flags for general use:
6167 *
6168 * - **progressive**: Progressive styling is applied to convey that the widget will move the user forward in a process.
6169 * - **destructive**: Destructive styling is applied to convey that the widget will remove something.
6170 * - **constructive**: Constructive styling is applied to convey that the widget will create something.
6171 *
6172 * The flags affect the appearance of the buttons:
6173 *
6174 * @example
6175 * // FlaggedElement is mixed into ButtonWidget to provide styling flags
6176 * var button1 = new OO.ui.ButtonWidget( {
6177 * label: 'Constructive',
6178 * flags: 'constructive'
6179 * } );
6180 * var button2 = new OO.ui.ButtonWidget( {
6181 * label: 'Destructive',
6182 * flags: 'destructive'
6183 * } );
6184 * var button3 = new OO.ui.ButtonWidget( {
6185 * label: 'Progressive',
6186 * flags: 'progressive'
6187 * } );
6188 * $( 'body' ).append( button1.$element, button2.$element, button3.$element );
6189 *
6190 * {@link OO.ui.ActionWidget ActionWidgets}, which are a special kind of button that execute an action, use these flags: **primary** and **safe**.
6191 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information.
6192 *
6193 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Flagged
6194 *
6195 * @abstract
6196 * @class
6197 *
6198 * @constructor
6199 * @param {Object} [config] Configuration options
6200 * @cfg {string|string[]} [flags] The name or names of the flags (e.g., 'constructive' or 'primary') to apply.
6201 * Please see the [OOjs UI documentation on MediaWiki] [2] for more information about available flags.
6202 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Flagged
6203 * @cfg {jQuery} [$flagged] The flagged element. By default,
6204 * the flagged functionality is applied to the element created by the class ($element).
6205 * If a different element is specified, the flagged functionality will be applied to it instead.
6206 */
6207 OO.ui.mixin.FlaggedElement = function OoUiMixinFlaggedElement( config ) {
6208 // Configuration initialization
6209 config = config || {};
6210
6211 // Properties
6212 this.flags = {};
6213 this.$flagged = null;
6214
6215 // Initialization
6216 this.setFlags( config.flags );
6217 this.setFlaggedElement( config.$flagged || this.$element );
6218 };
6219
6220 /* Events */
6221
6222 /**
6223 * @event flag
6224 * A flag event is emitted when the #clearFlags or #setFlags methods are used. The `changes`
6225 * parameter contains the name of each modified flag and indicates whether it was
6226 * added or removed.
6227 *
6228 * @param {Object.<string,boolean>} changes Object keyed by flag name. A Boolean `true` indicates
6229 * that the flag was added, `false` that the flag was removed.
6230 */
6231
6232 /* Methods */
6233
6234 /**
6235 * Set the flagged element.
6236 *
6237 * This method is used to retarget a flagged mixin so that its functionality applies to the specified element.
6238 * If an element is already set, the method will remove the mixin’s effect on that element.
6239 *
6240 * @param {jQuery} $flagged Element that should be flagged
6241 */
6242 OO.ui.mixin.FlaggedElement.prototype.setFlaggedElement = function ( $flagged ) {
6243 var classNames = Object.keys( this.flags ).map( function ( flag ) {
6244 return 'oo-ui-flaggedElement-' + flag;
6245 } ).join( ' ' );
6246
6247 if ( this.$flagged ) {
6248 this.$flagged.removeClass( classNames );
6249 }
6250
6251 this.$flagged = $flagged.addClass( classNames );
6252 };
6253
6254 /**
6255 * Check if the specified flag is set.
6256 *
6257 * @param {string} flag Name of flag
6258 * @return {boolean} The flag is set
6259 */
6260 OO.ui.mixin.FlaggedElement.prototype.hasFlag = function ( flag ) {
6261 // This may be called before the constructor, thus before this.flags is set
6262 return this.flags && ( flag in this.flags );
6263 };
6264
6265 /**
6266 * Get the names of all flags set.
6267 *
6268 * @return {string[]} Flag names
6269 */
6270 OO.ui.mixin.FlaggedElement.prototype.getFlags = function () {
6271 // This may be called before the constructor, thus before this.flags is set
6272 return Object.keys( this.flags || {} );
6273 };
6274
6275 /**
6276 * Clear all flags.
6277 *
6278 * @chainable
6279 * @fires flag
6280 */
6281 OO.ui.mixin.FlaggedElement.prototype.clearFlags = function () {
6282 var flag, className,
6283 changes = {},
6284 remove = [],
6285 classPrefix = 'oo-ui-flaggedElement-';
6286
6287 for ( flag in this.flags ) {
6288 className = classPrefix + flag;
6289 changes[ flag ] = false;
6290 delete this.flags[ flag ];
6291 remove.push( className );
6292 }
6293
6294 if ( this.$flagged ) {
6295 this.$flagged.removeClass( remove.join( ' ' ) );
6296 }
6297
6298 this.updateThemeClasses();
6299 this.emit( 'flag', changes );
6300
6301 return this;
6302 };
6303
6304 /**
6305 * Add one or more flags.
6306 *
6307 * @param {string|string[]|Object.<string, boolean>} flags A flag name, an array of flag names,
6308 * or an object keyed by flag name with a boolean value that indicates whether the flag should
6309 * be added (`true`) or removed (`false`).
6310 * @chainable
6311 * @fires flag
6312 */
6313 OO.ui.mixin.FlaggedElement.prototype.setFlags = function ( flags ) {
6314 var i, len, flag, className,
6315 changes = {},
6316 add = [],
6317 remove = [],
6318 classPrefix = 'oo-ui-flaggedElement-';
6319
6320 if ( typeof flags === 'string' ) {
6321 className = classPrefix + flags;
6322 // Set
6323 if ( !this.flags[ flags ] ) {
6324 this.flags[ flags ] = true;
6325 add.push( className );
6326 }
6327 } else if ( Array.isArray( flags ) ) {
6328 for ( i = 0, len = flags.length; i < len; i++ ) {
6329 flag = flags[ i ];
6330 className = classPrefix + flag;
6331 // Set
6332 if ( !this.flags[ flag ] ) {
6333 changes[ flag ] = true;
6334 this.flags[ flag ] = true;
6335 add.push( className );
6336 }
6337 }
6338 } else if ( OO.isPlainObject( flags ) ) {
6339 for ( flag in flags ) {
6340 className = classPrefix + flag;
6341 if ( flags[ flag ] ) {
6342 // Set
6343 if ( !this.flags[ flag ] ) {
6344 changes[ flag ] = true;
6345 this.flags[ flag ] = true;
6346 add.push( className );
6347 }
6348 } else {
6349 // Remove
6350 if ( this.flags[ flag ] ) {
6351 changes[ flag ] = false;
6352 delete this.flags[ flag ];
6353 remove.push( className );
6354 }
6355 }
6356 }
6357 }
6358
6359 if ( this.$flagged ) {
6360 this.$flagged
6361 .addClass( add.join( ' ' ) )
6362 .removeClass( remove.join( ' ' ) );
6363 }
6364
6365 this.updateThemeClasses();
6366 this.emit( 'flag', changes );
6367
6368 return this;
6369 };
6370
6371 /**
6372 * TitledElement is mixed into other classes to provide a `title` attribute.
6373 * Titles are rendered by the browser and are made visible when the user moves
6374 * the mouse over the element. Titles are not visible on touch devices.
6375 *
6376 * @example
6377 * // TitledElement provides a 'title' attribute to the
6378 * // ButtonWidget class
6379 * var button = new OO.ui.ButtonWidget( {
6380 * label: 'Button with Title',
6381 * title: 'I am a button'
6382 * } );
6383 * $( 'body' ).append( button.$element );
6384 *
6385 * @abstract
6386 * @class
6387 *
6388 * @constructor
6389 * @param {Object} [config] Configuration options
6390 * @cfg {jQuery} [$titled] The element to which the `title` attribute is applied.
6391 * If this config is omitted, the title functionality is applied to $element, the
6392 * element created by the class.
6393 * @cfg {string|Function} [title] The title text or a function that returns text. If
6394 * this config is omitted, the value of the {@link #static-title static title} property is used.
6395 */
6396 OO.ui.mixin.TitledElement = function OoUiMixinTitledElement( config ) {
6397 // Configuration initialization
6398 config = config || {};
6399
6400 // Properties
6401 this.$titled = null;
6402 this.title = null;
6403
6404 // Initialization
6405 this.setTitle( config.title || this.constructor.static.title );
6406 this.setTitledElement( config.$titled || this.$element );
6407 };
6408
6409 /* Setup */
6410
6411 OO.initClass( OO.ui.mixin.TitledElement );
6412
6413 /* Static Properties */
6414
6415 /**
6416 * The title text, a function that returns text, or `null` for no title. The value of the static property
6417 * is overridden if the #title config option is used.
6418 *
6419 * @static
6420 * @inheritable
6421 * @property {string|Function|null}
6422 */
6423 OO.ui.mixin.TitledElement.static.title = null;
6424
6425 /* Methods */
6426
6427 /**
6428 * Set the titled element.
6429 *
6430 * This method is used to retarget a titledElement mixin so that its functionality applies to the specified element.
6431 * If an element is already set, the mixin’s effect on that element is removed before the new element is set up.
6432 *
6433 * @param {jQuery} $titled Element that should use the 'titled' functionality
6434 */
6435 OO.ui.mixin.TitledElement.prototype.setTitledElement = function ( $titled ) {
6436 if ( this.$titled ) {
6437 this.$titled.removeAttr( 'title' );
6438 }
6439
6440 this.$titled = $titled;
6441 if ( this.title ) {
6442 this.$titled.attr( 'title', this.title );
6443 }
6444 };
6445
6446 /**
6447 * Set title.
6448 *
6449 * @param {string|Function|null} title Title text, a function that returns text, or `null` for no title
6450 * @chainable
6451 */
6452 OO.ui.mixin.TitledElement.prototype.setTitle = function ( title ) {
6453 title = typeof title === 'string' ? OO.ui.resolveMsg( title ) : null;
6454
6455 if ( this.title !== title ) {
6456 if ( this.$titled ) {
6457 if ( title !== null ) {
6458 this.$titled.attr( 'title', title );
6459 } else {
6460 this.$titled.removeAttr( 'title' );
6461 }
6462 }
6463 this.title = title;
6464 }
6465
6466 return this;
6467 };
6468
6469 /**
6470 * Get title.
6471 *
6472 * @return {string} Title string
6473 */
6474 OO.ui.mixin.TitledElement.prototype.getTitle = function () {
6475 return this.title;
6476 };
6477
6478 /**
6479 * Element that can be automatically clipped to visible boundaries.
6480 *
6481 * Whenever the element's natural height changes, you have to call
6482 * {@link OO.ui.mixin.ClippableElement#clip} to make sure it's still
6483 * clipping correctly.
6484 *
6485 * @abstract
6486 * @class
6487 *
6488 * @constructor
6489 * @param {Object} [config] Configuration options
6490 * @cfg {jQuery} [$clippable] Nodes to clip, assigned to #$clippable, omit to use #$element
6491 */
6492 OO.ui.mixin.ClippableElement = function OoUiMixinClippableElement( config ) {
6493 // Configuration initialization
6494 config = config || {};
6495
6496 // Properties
6497 this.$clippable = null;
6498 this.clipping = false;
6499 this.clippedHorizontally = false;
6500 this.clippedVertically = false;
6501 this.$clippableContainer = null;
6502 this.$clippableScroller = null;
6503 this.$clippableWindow = null;
6504 this.idealWidth = null;
6505 this.idealHeight = null;
6506 this.onClippableContainerScrollHandler = this.clip.bind( this );
6507 this.onClippableWindowResizeHandler = this.clip.bind( this );
6508
6509 // Initialization
6510 this.setClippableElement( config.$clippable || this.$element );
6511 };
6512
6513 /* Methods */
6514
6515 /**
6516 * Set clippable element.
6517 *
6518 * If an element is already set, it will be cleaned up before setting up the new element.
6519 *
6520 * @param {jQuery} $clippable Element to make clippable
6521 */
6522 OO.ui.mixin.ClippableElement.prototype.setClippableElement = function ( $clippable ) {
6523 if ( this.$clippable ) {
6524 this.$clippable.removeClass( 'oo-ui-clippableElement-clippable' );
6525 this.$clippable.css( { width: '', height: '', overflowX: '', overflowY: '' } );
6526 OO.ui.Element.static.reconsiderScrollbars( this.$clippable[ 0 ] );
6527 }
6528
6529 this.$clippable = $clippable.addClass( 'oo-ui-clippableElement-clippable' );
6530 this.clip();
6531 };
6532
6533 /**
6534 * Toggle clipping.
6535 *
6536 * Do not turn clipping on until after the element is attached to the DOM and visible.
6537 *
6538 * @param {boolean} [clipping] Enable clipping, omit to toggle
6539 * @chainable
6540 */
6541 OO.ui.mixin.ClippableElement.prototype.toggleClipping = function ( clipping ) {
6542 clipping = clipping === undefined ? !this.clipping : !!clipping;
6543
6544 if ( this.clipping !== clipping ) {
6545 this.clipping = clipping;
6546 if ( clipping ) {
6547 this.$clippableContainer = $( this.getClosestScrollableElementContainer() );
6548 // If the clippable container is the root, we have to listen to scroll events and check
6549 // jQuery.scrollTop on the window because of browser inconsistencies
6550 this.$clippableScroller = this.$clippableContainer.is( 'html, body' ) ?
6551 $( OO.ui.Element.static.getWindow( this.$clippableContainer ) ) :
6552 this.$clippableContainer;
6553 this.$clippableScroller.on( 'scroll', this.onClippableContainerScrollHandler );
6554 this.$clippableWindow = $( this.getElementWindow() )
6555 .on( 'resize', this.onClippableWindowResizeHandler );
6556 // Initial clip after visible
6557 this.clip();
6558 } else {
6559 this.$clippable.css( { width: '', height: '', overflowX: '', overflowY: '' } );
6560 OO.ui.Element.static.reconsiderScrollbars( this.$clippable[ 0 ] );
6561
6562 this.$clippableContainer = null;
6563 this.$clippableScroller.off( 'scroll', this.onClippableContainerScrollHandler );
6564 this.$clippableScroller = null;
6565 this.$clippableWindow.off( 'resize', this.onClippableWindowResizeHandler );
6566 this.$clippableWindow = null;
6567 }
6568 }
6569
6570 return this;
6571 };
6572
6573 /**
6574 * Check if the element will be clipped to fit the visible area of the nearest scrollable container.
6575 *
6576 * @return {boolean} Element will be clipped to the visible area
6577 */
6578 OO.ui.mixin.ClippableElement.prototype.isClipping = function () {
6579 return this.clipping;
6580 };
6581
6582 /**
6583 * Check if the bottom or right of the element is being clipped by the nearest scrollable container.
6584 *
6585 * @return {boolean} Part of the element is being clipped
6586 */
6587 OO.ui.mixin.ClippableElement.prototype.isClipped = function () {
6588 return this.clippedHorizontally || this.clippedVertically;
6589 };
6590
6591 /**
6592 * Check if the right of the element is being clipped by the nearest scrollable container.
6593 *
6594 * @return {boolean} Part of the element is being clipped
6595 */
6596 OO.ui.mixin.ClippableElement.prototype.isClippedHorizontally = function () {
6597 return this.clippedHorizontally;
6598 };
6599
6600 /**
6601 * Check if the bottom of the element is being clipped by the nearest scrollable container.
6602 *
6603 * @return {boolean} Part of the element is being clipped
6604 */
6605 OO.ui.mixin.ClippableElement.prototype.isClippedVertically = function () {
6606 return this.clippedVertically;
6607 };
6608
6609 /**
6610 * Set the ideal size. These are the dimensions the element will have when it's not being clipped.
6611 *
6612 * @param {number|string} [width] Width as a number of pixels or CSS string with unit suffix
6613 * @param {number|string} [height] Height as a number of pixels or CSS string with unit suffix
6614 */
6615 OO.ui.mixin.ClippableElement.prototype.setIdealSize = function ( width, height ) {
6616 this.idealWidth = width;
6617 this.idealHeight = height;
6618
6619 if ( !this.clipping ) {
6620 // Update dimensions
6621 this.$clippable.css( { width: width, height: height } );
6622 }
6623 // While clipping, idealWidth and idealHeight are not considered
6624 };
6625
6626 /**
6627 * Clip element to visible boundaries and allow scrolling when needed. Call this method when
6628 * the element's natural height changes.
6629 *
6630 * Element will be clipped the bottom or right of the element is within 10px of the edge of, or
6631 * overlapped by, the visible area of the nearest scrollable container.
6632 *
6633 * @chainable
6634 */
6635 OO.ui.mixin.ClippableElement.prototype.clip = function () {
6636 if ( !this.clipping ) {
6637 // this.$clippableContainer and this.$clippableWindow are null, so the below will fail
6638 return this;
6639 }
6640
6641 var buffer = 7, // Chosen by fair dice roll
6642 cOffset = this.$clippable.offset(),
6643 $container = this.$clippableContainer.is( 'html, body' ) ?
6644 this.$clippableWindow : this.$clippableContainer,
6645 ccOffset = $container.offset() || { top: 0, left: 0 },
6646 ccHeight = $container.innerHeight() - buffer,
6647 ccWidth = $container.innerWidth() - buffer,
6648 cWidth = this.$clippable.outerWidth() + buffer,
6649 scrollerIsWindow = this.$clippableScroller[0] === this.$clippableWindow[0],
6650 scrollTop = scrollerIsWindow ? this.$clippableScroller.scrollTop() : 0,
6651 scrollLeft = scrollerIsWindow ? this.$clippableScroller.scrollLeft() : 0,
6652 desiredWidth = cOffset.left < 0 ?
6653 cWidth + cOffset.left :
6654 ( ccOffset.left + scrollLeft + ccWidth ) - cOffset.left,
6655 desiredHeight = ( ccOffset.top + scrollTop + ccHeight ) - cOffset.top,
6656 naturalWidth = this.$clippable.prop( 'scrollWidth' ),
6657 naturalHeight = this.$clippable.prop( 'scrollHeight' ),
6658 clipWidth = desiredWidth < naturalWidth,
6659 clipHeight = desiredHeight < naturalHeight;
6660
6661 if ( clipWidth ) {
6662 this.$clippable.css( { overflowX: 'scroll', width: desiredWidth } );
6663 } else {
6664 this.$clippable.css( { width: this.idealWidth || '', overflowX: '' } );
6665 }
6666 if ( clipHeight ) {
6667 this.$clippable.css( { overflowY: 'scroll', height: desiredHeight } );
6668 } else {
6669 this.$clippable.css( { height: this.idealHeight || '', overflowY: '' } );
6670 }
6671
6672 // If we stopped clipping in at least one of the dimensions
6673 if ( ( this.clippedHorizontally && !clipWidth ) || ( this.clippedVertically && !clipHeight ) ) {
6674 OO.ui.Element.static.reconsiderScrollbars( this.$clippable[ 0 ] );
6675 }
6676
6677 this.clippedHorizontally = clipWidth;
6678 this.clippedVertically = clipHeight;
6679
6680 return this;
6681 };
6682
6683 /**
6684 * Tools, together with {@link OO.ui.ToolGroup toolgroups}, constitute {@link OO.ui.Toolbar toolbars}.
6685 * Each tool is configured with a static name, title, and icon and is customized with the command to carry
6686 * out when the tool is selected. Tools must also be registered with a {@link OO.ui.ToolFactory tool factory},
6687 * which creates the tools on demand.
6688 *
6689 * Tools are added to toolgroups ({@link OO.ui.ListToolGroup ListToolGroup},
6690 * {@link OO.ui.BarToolGroup BarToolGroup}, or {@link OO.ui.MenuToolGroup MenuToolGroup}), which determine how
6691 * the tool is displayed in the toolbar. See {@link OO.ui.Toolbar toolbars} for an example.
6692 *
6693 * For more information, please see the [OOjs UI documentation on MediaWiki][1].
6694 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
6695 *
6696 * @abstract
6697 * @class
6698 * @extends OO.ui.Widget
6699 * @mixins OO.ui.mixin.IconElement
6700 * @mixins OO.ui.mixin.FlaggedElement
6701 * @mixins OO.ui.mixin.TabIndexedElement
6702 *
6703 * @constructor
6704 * @param {OO.ui.ToolGroup} toolGroup
6705 * @param {Object} [config] Configuration options
6706 * @cfg {string|Function} [title] Title text or a function that returns text. If this config is omitted, the value of
6707 * the {@link #static-title static title} property is used.
6708 *
6709 * The title is used in different ways depending on the type of toolgroup that contains the tool. The
6710 * 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
6711 * part of a {@link OO.ui.ListToolGroup list} or {@link OO.ui.MenuToolGroup menu} toolgroup.
6712 *
6713 * For bar toolgroups, a description of the accelerator key is appended to the title if an accelerator key
6714 * is associated with an action by the same name as the tool and accelerator functionality has been added to the application.
6715 * To add accelerator key functionality, you must subclass OO.ui.Toolbar and override the {@link OO.ui.Toolbar#getToolAccelerator getToolAccelerator} method.
6716 */
6717 OO.ui.Tool = function OoUiTool( toolGroup, config ) {
6718 // Allow passing positional parameters inside the config object
6719 if ( OO.isPlainObject( toolGroup ) && config === undefined ) {
6720 config = toolGroup;
6721 toolGroup = config.toolGroup;
6722 }
6723
6724 // Configuration initialization
6725 config = config || {};
6726
6727 // Parent constructor
6728 OO.ui.Tool.parent.call( this, config );
6729
6730 // Properties
6731 this.toolGroup = toolGroup;
6732 this.toolbar = this.toolGroup.getToolbar();
6733 this.active = false;
6734 this.$title = $( '<span>' );
6735 this.$accel = $( '<span>' );
6736 this.$link = $( '<a>' );
6737 this.title = null;
6738
6739 // Mixin constructors
6740 OO.ui.mixin.IconElement.call( this, config );
6741 OO.ui.mixin.FlaggedElement.call( this, config );
6742 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$link } ) );
6743
6744 // Events
6745 this.toolbar.connect( this, { updateState: 'onUpdateState' } );
6746
6747 // Initialization
6748 this.$title.addClass( 'oo-ui-tool-title' );
6749 this.$accel
6750 .addClass( 'oo-ui-tool-accel' )
6751 .prop( {
6752 // This may need to be changed if the key names are ever localized,
6753 // but for now they are essentially written in English
6754 dir: 'ltr',
6755 lang: 'en'
6756 } );
6757 this.$link
6758 .addClass( 'oo-ui-tool-link' )
6759 .append( this.$icon, this.$title, this.$accel )
6760 .attr( 'role', 'button' );
6761 this.$element
6762 .data( 'oo-ui-tool', this )
6763 .addClass(
6764 'oo-ui-tool ' + 'oo-ui-tool-name-' +
6765 this.constructor.static.name.replace( /^([^\/]+)\/([^\/]+).*$/, '$1-$2' )
6766 )
6767 .toggleClass( 'oo-ui-tool-with-label', this.constructor.static.displayBothIconAndLabel )
6768 .append( this.$link );
6769 this.setTitle( config.title || this.constructor.static.title );
6770 };
6771
6772 /* Setup */
6773
6774 OO.inheritClass( OO.ui.Tool, OO.ui.Widget );
6775 OO.mixinClass( OO.ui.Tool, OO.ui.mixin.IconElement );
6776 OO.mixinClass( OO.ui.Tool, OO.ui.mixin.FlaggedElement );
6777 OO.mixinClass( OO.ui.Tool, OO.ui.mixin.TabIndexedElement );
6778
6779 /* Static Properties */
6780
6781 /**
6782 * @static
6783 * @inheritdoc
6784 */
6785 OO.ui.Tool.static.tagName = 'span';
6786
6787 /**
6788 * Symbolic name of tool.
6789 *
6790 * The symbolic name is used internally to register the tool with a {@link OO.ui.ToolFactory ToolFactory}. It can
6791 * also be used when adding tools to toolgroups.
6792 *
6793 * @abstract
6794 * @static
6795 * @inheritable
6796 * @property {string}
6797 */
6798 OO.ui.Tool.static.name = '';
6799
6800 /**
6801 * Symbolic name of the group.
6802 *
6803 * The group name is used to associate tools with each other so that they can be selected later by
6804 * a {@link OO.ui.ToolGroup toolgroup}.
6805 *
6806 * @abstract
6807 * @static
6808 * @inheritable
6809 * @property {string}
6810 */
6811 OO.ui.Tool.static.group = '';
6812
6813 /**
6814 * 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.
6815 *
6816 * @abstract
6817 * @static
6818 * @inheritable
6819 * @property {string|Function}
6820 */
6821 OO.ui.Tool.static.title = '';
6822
6823 /**
6824 * Display both icon and label when the tool is used in a {@link OO.ui.BarToolGroup bar} toolgroup.
6825 * Normally only the icon is displayed, or only the label if no icon is given.
6826 *
6827 * @static
6828 * @inheritable
6829 * @property {boolean}
6830 */
6831 OO.ui.Tool.static.displayBothIconAndLabel = false;
6832
6833 /**
6834 * Add tool to catch-all groups automatically.
6835 *
6836 * A catch-all group, which contains all tools that do not currently belong to a toolgroup,
6837 * can be included in a toolgroup using the wildcard selector, an asterisk (*).
6838 *
6839 * @static
6840 * @inheritable
6841 * @property {boolean}
6842 */
6843 OO.ui.Tool.static.autoAddToCatchall = true;
6844
6845 /**
6846 * Add tool to named groups automatically.
6847 *
6848 * By default, tools that are configured with a static ‘group’ property are added
6849 * to that group and will be selected when the symbolic name of the group is specified (e.g., when
6850 * toolgroups include tools by group name).
6851 *
6852 * @static
6853 * @property {boolean}
6854 * @inheritable
6855 */
6856 OO.ui.Tool.static.autoAddToGroup = true;
6857
6858 /**
6859 * Check if this tool is compatible with given data.
6860 *
6861 * This is a stub that can be overriden to provide support for filtering tools based on an
6862 * arbitrary piece of information (e.g., where the cursor is in a document). The implementation
6863 * must also call this method so that the compatibility check can be performed.
6864 *
6865 * @static
6866 * @inheritable
6867 * @param {Mixed} data Data to check
6868 * @return {boolean} Tool can be used with data
6869 */
6870 OO.ui.Tool.static.isCompatibleWith = function () {
6871 return false;
6872 };
6873
6874 /* Methods */
6875
6876 /**
6877 * Handle the toolbar state being updated.
6878 *
6879 * This is an abstract method that must be overridden in a concrete subclass.
6880 *
6881 * @protected
6882 * @abstract
6883 */
6884 OO.ui.Tool.prototype.onUpdateState = function () {
6885 throw new Error(
6886 'OO.ui.Tool.onUpdateState not implemented in this subclass:' + this.constructor
6887 );
6888 };
6889
6890 /**
6891 * Handle the tool being selected.
6892 *
6893 * This is an abstract method that must be overridden in a concrete subclass.
6894 *
6895 * @protected
6896 * @abstract
6897 */
6898 OO.ui.Tool.prototype.onSelect = function () {
6899 throw new Error(
6900 'OO.ui.Tool.onSelect not implemented in this subclass:' + this.constructor
6901 );
6902 };
6903
6904 /**
6905 * Check if the tool is active.
6906 *
6907 * Tools become active when their #onSelect or #onUpdateState handlers change them to appear pressed
6908 * with the #setActive method. Additional CSS is applied to the tool to reflect the active state.
6909 *
6910 * @return {boolean} Tool is active
6911 */
6912 OO.ui.Tool.prototype.isActive = function () {
6913 return this.active;
6914 };
6915
6916 /**
6917 * Make the tool appear active or inactive.
6918 *
6919 * This method should be called within #onSelect or #onUpdateState event handlers to make the tool
6920 * appear pressed or not.
6921 *
6922 * @param {boolean} state Make tool appear active
6923 */
6924 OO.ui.Tool.prototype.setActive = function ( state ) {
6925 this.active = !!state;
6926 if ( this.active ) {
6927 this.$element.addClass( 'oo-ui-tool-active' );
6928 } else {
6929 this.$element.removeClass( 'oo-ui-tool-active' );
6930 }
6931 };
6932
6933 /**
6934 * Set the tool #title.
6935 *
6936 * @param {string|Function} title Title text or a function that returns text
6937 * @chainable
6938 */
6939 OO.ui.Tool.prototype.setTitle = function ( title ) {
6940 this.title = OO.ui.resolveMsg( title );
6941 this.updateTitle();
6942 return this;
6943 };
6944
6945 /**
6946 * Get the tool #title.
6947 *
6948 * @return {string} Title text
6949 */
6950 OO.ui.Tool.prototype.getTitle = function () {
6951 return this.title;
6952 };
6953
6954 /**
6955 * Get the tool's symbolic name.
6956 *
6957 * @return {string} Symbolic name of tool
6958 */
6959 OO.ui.Tool.prototype.getName = function () {
6960 return this.constructor.static.name;
6961 };
6962
6963 /**
6964 * Update the title.
6965 */
6966 OO.ui.Tool.prototype.updateTitle = function () {
6967 var titleTooltips = this.toolGroup.constructor.static.titleTooltips,
6968 accelTooltips = this.toolGroup.constructor.static.accelTooltips,
6969 accel = this.toolbar.getToolAccelerator( this.constructor.static.name ),
6970 tooltipParts = [];
6971
6972 this.$title.text( this.title );
6973 this.$accel.text( accel );
6974
6975 if ( titleTooltips && typeof this.title === 'string' && this.title.length ) {
6976 tooltipParts.push( this.title );
6977 }
6978 if ( accelTooltips && typeof accel === 'string' && accel.length ) {
6979 tooltipParts.push( accel );
6980 }
6981 if ( tooltipParts.length ) {
6982 this.$link.attr( 'title', tooltipParts.join( ' ' ) );
6983 } else {
6984 this.$link.removeAttr( 'title' );
6985 }
6986 };
6987
6988 /**
6989 * Destroy tool.
6990 *
6991 * Destroying the tool removes all event handlers and the tool’s DOM elements.
6992 * Call this method whenever you are done using a tool.
6993 */
6994 OO.ui.Tool.prototype.destroy = function () {
6995 this.toolbar.disconnect( this );
6996 this.$element.remove();
6997 };
6998
6999 /**
7000 * Toolbars are complex interface components that permit users to easily access a variety
7001 * of {@link OO.ui.Tool tools} (e.g., formatting commands) and actions, which are additional commands that are
7002 * part of the toolbar, but not configured as tools.
7003 *
7004 * Individual tools are customized and then registered with a {@link OO.ui.ToolFactory tool factory}, which creates
7005 * the tools on demand. Each tool has a symbolic name (used when registering the tool), a title (e.g., ‘Insert
7006 * picture’), and an icon.
7007 *
7008 * Individual tools are organized in {@link OO.ui.ToolGroup toolgroups}, which can be {@link OO.ui.MenuToolGroup menus}
7009 * of tools, {@link OO.ui.ListToolGroup lists} of tools, or a single {@link OO.ui.BarToolGroup bar} of tools.
7010 * The arrangement and order of the toolgroups is customized when the toolbar is set up. Tools can be presented in
7011 * any order, but each can only appear once in the toolbar.
7012 *
7013 * The following is an example of a basic toolbar.
7014 *
7015 * @example
7016 * // Example of a toolbar
7017 * // Create the toolbar
7018 * var toolFactory = new OO.ui.ToolFactory();
7019 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
7020 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
7021 *
7022 * // We will be placing status text in this element when tools are used
7023 * var $area = $( '<p>' ).text( 'Toolbar example' );
7024 *
7025 * // Define the tools that we're going to place in our toolbar
7026 *
7027 * // Create a class inheriting from OO.ui.Tool
7028 * function PictureTool() {
7029 * PictureTool.parent.apply( this, arguments );
7030 * }
7031 * OO.inheritClass( PictureTool, OO.ui.Tool );
7032 * // Each tool must have a 'name' (used as an internal identifier, see later) and at least one
7033 * // of 'icon' and 'title' (displayed icon and text).
7034 * PictureTool.static.name = 'picture';
7035 * PictureTool.static.icon = 'picture';
7036 * PictureTool.static.title = 'Insert picture';
7037 * // Defines the action that will happen when this tool is selected (clicked).
7038 * PictureTool.prototype.onSelect = function () {
7039 * $area.text( 'Picture tool clicked!' );
7040 * // Never display this tool as "active" (selected).
7041 * this.setActive( false );
7042 * };
7043 * // Make this tool available in our toolFactory and thus our toolbar
7044 * toolFactory.register( PictureTool );
7045 *
7046 * // Register two more tools, nothing interesting here
7047 * function SettingsTool() {
7048 * SettingsTool.parent.apply( this, arguments );
7049 * }
7050 * OO.inheritClass( SettingsTool, OO.ui.Tool );
7051 * SettingsTool.static.name = 'settings';
7052 * SettingsTool.static.icon = 'settings';
7053 * SettingsTool.static.title = 'Change settings';
7054 * SettingsTool.prototype.onSelect = function () {
7055 * $area.text( 'Settings tool clicked!' );
7056 * this.setActive( false );
7057 * };
7058 * toolFactory.register( SettingsTool );
7059 *
7060 * // Register two more tools, nothing interesting here
7061 * function StuffTool() {
7062 * StuffTool.parent.apply( this, arguments );
7063 * }
7064 * OO.inheritClass( StuffTool, OO.ui.Tool );
7065 * StuffTool.static.name = 'stuff';
7066 * StuffTool.static.icon = 'ellipsis';
7067 * StuffTool.static.title = 'More stuff';
7068 * StuffTool.prototype.onSelect = function () {
7069 * $area.text( 'More stuff tool clicked!' );
7070 * this.setActive( false );
7071 * };
7072 * toolFactory.register( StuffTool );
7073 *
7074 * // This is a PopupTool. Rather than having a custom 'onSelect' action, it will display a
7075 * // little popup window (a PopupWidget).
7076 * function HelpTool( toolGroup, config ) {
7077 * OO.ui.PopupTool.call( this, toolGroup, $.extend( { popup: {
7078 * padded: true,
7079 * label: 'Help',
7080 * head: true
7081 * } }, config ) );
7082 * this.popup.$body.append( '<p>I am helpful!</p>' );
7083 * }
7084 * OO.inheritClass( HelpTool, OO.ui.PopupTool );
7085 * HelpTool.static.name = 'help';
7086 * HelpTool.static.icon = 'help';
7087 * HelpTool.static.title = 'Help';
7088 * toolFactory.register( HelpTool );
7089 *
7090 * // Finally define which tools and in what order appear in the toolbar. Each tool may only be
7091 * // used once (but not all defined tools must be used).
7092 * toolbar.setup( [
7093 * {
7094 * // 'bar' tool groups display tools' icons only, side-by-side.
7095 * type: 'bar',
7096 * include: [ 'picture', 'help' ]
7097 * },
7098 * {
7099 * // 'list' tool groups display both the titles and icons, in a dropdown list.
7100 * type: 'list',
7101 * indicator: 'down',
7102 * label: 'More',
7103 * include: [ 'settings', 'stuff' ]
7104 * }
7105 * // Note how the tools themselves are toolgroup-agnostic - the same tool can be displayed
7106 * // either in a 'list' or a 'bar'. There is a 'menu' tool group too, not showcased here,
7107 * // since it's more complicated to use. (See the next example snippet on this page.)
7108 * ] );
7109 *
7110 * // Create some UI around the toolbar and place it in the document
7111 * var frame = new OO.ui.PanelLayout( {
7112 * expanded: false,
7113 * framed: true
7114 * } );
7115 * var contentFrame = new OO.ui.PanelLayout( {
7116 * expanded: false,
7117 * padded: true
7118 * } );
7119 * frame.$element.append(
7120 * toolbar.$element,
7121 * contentFrame.$element.append( $area )
7122 * );
7123 * $( 'body' ).append( frame.$element );
7124 *
7125 * // Here is where the toolbar is actually built. This must be done after inserting it into the
7126 * // document.
7127 * toolbar.initialize();
7128 *
7129 * The following example extends the previous one to illustrate 'menu' toolgroups and the usage of
7130 * 'updateState' event.
7131 *
7132 * @example
7133 * // Create the toolbar
7134 * var toolFactory = new OO.ui.ToolFactory();
7135 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
7136 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
7137 *
7138 * // We will be placing status text in this element when tools are used
7139 * var $area = $( '<p>' ).text( 'Toolbar example' );
7140 *
7141 * // Define the tools that we're going to place in our toolbar
7142 *
7143 * // Create a class inheriting from OO.ui.Tool
7144 * function PictureTool() {
7145 * PictureTool.parent.apply( this, arguments );
7146 * }
7147 * OO.inheritClass( PictureTool, OO.ui.Tool );
7148 * // Each tool must have a 'name' (used as an internal identifier, see later) and at least one
7149 * // of 'icon' and 'title' (displayed icon and text).
7150 * PictureTool.static.name = 'picture';
7151 * PictureTool.static.icon = 'picture';
7152 * PictureTool.static.title = 'Insert picture';
7153 * // Defines the action that will happen when this tool is selected (clicked).
7154 * PictureTool.prototype.onSelect = function () {
7155 * $area.text( 'Picture tool clicked!' );
7156 * // Never display this tool as "active" (selected).
7157 * this.setActive( false );
7158 * };
7159 * // The toolbar can be synchronized with the state of some external stuff, like a text
7160 * // editor's editing area, highlighting the tools (e.g. a 'bold' tool would be shown as active
7161 * // when the text cursor was inside bolded text). Here we simply disable this feature.
7162 * PictureTool.prototype.onUpdateState = function () {
7163 * };
7164 * // Make this tool available in our toolFactory and thus our toolbar
7165 * toolFactory.register( PictureTool );
7166 *
7167 * // Register two more tools, nothing interesting here
7168 * function SettingsTool() {
7169 * SettingsTool.parent.apply( this, arguments );
7170 * this.reallyActive = false;
7171 * }
7172 * OO.inheritClass( SettingsTool, OO.ui.Tool );
7173 * SettingsTool.static.name = 'settings';
7174 * SettingsTool.static.icon = 'settings';
7175 * SettingsTool.static.title = 'Change settings';
7176 * SettingsTool.prototype.onSelect = function () {
7177 * $area.text( 'Settings tool clicked!' );
7178 * // Toggle the active state on each click
7179 * this.reallyActive = !this.reallyActive;
7180 * this.setActive( this.reallyActive );
7181 * // To update the menu label
7182 * this.toolbar.emit( 'updateState' );
7183 * };
7184 * SettingsTool.prototype.onUpdateState = function () {
7185 * };
7186 * toolFactory.register( SettingsTool );
7187 *
7188 * // Register two more tools, nothing interesting here
7189 * function StuffTool() {
7190 * StuffTool.parent.apply( this, arguments );
7191 * this.reallyActive = false;
7192 * }
7193 * OO.inheritClass( StuffTool, OO.ui.Tool );
7194 * StuffTool.static.name = 'stuff';
7195 * StuffTool.static.icon = 'ellipsis';
7196 * StuffTool.static.title = 'More stuff';
7197 * StuffTool.prototype.onSelect = function () {
7198 * $area.text( 'More stuff tool clicked!' );
7199 * // Toggle the active state on each click
7200 * this.reallyActive = !this.reallyActive;
7201 * this.setActive( this.reallyActive );
7202 * // To update the menu label
7203 * this.toolbar.emit( 'updateState' );
7204 * };
7205 * StuffTool.prototype.onUpdateState = function () {
7206 * };
7207 * toolFactory.register( StuffTool );
7208 *
7209 * // This is a PopupTool. Rather than having a custom 'onSelect' action, it will display a
7210 * // little popup window (a PopupWidget). 'onUpdateState' is also already implemented.
7211 * function HelpTool( toolGroup, config ) {
7212 * OO.ui.PopupTool.call( this, toolGroup, $.extend( { popup: {
7213 * padded: true,
7214 * label: 'Help',
7215 * head: true
7216 * } }, config ) );
7217 * this.popup.$body.append( '<p>I am helpful!</p>' );
7218 * }
7219 * OO.inheritClass( HelpTool, OO.ui.PopupTool );
7220 * HelpTool.static.name = 'help';
7221 * HelpTool.static.icon = 'help';
7222 * HelpTool.static.title = 'Help';
7223 * toolFactory.register( HelpTool );
7224 *
7225 * // Finally define which tools and in what order appear in the toolbar. Each tool may only be
7226 * // used once (but not all defined tools must be used).
7227 * toolbar.setup( [
7228 * {
7229 * // 'bar' tool groups display tools' icons only, side-by-side.
7230 * type: 'bar',
7231 * include: [ 'picture', 'help' ]
7232 * },
7233 * {
7234 * // 'menu' tool groups display both the titles and icons, in a dropdown menu.
7235 * // Menu label indicates which items are selected.
7236 * type: 'menu',
7237 * indicator: 'down',
7238 * include: [ 'settings', 'stuff' ]
7239 * }
7240 * ] );
7241 *
7242 * // Create some UI around the toolbar and place it in the document
7243 * var frame = new OO.ui.PanelLayout( {
7244 * expanded: false,
7245 * framed: true
7246 * } );
7247 * var contentFrame = new OO.ui.PanelLayout( {
7248 * expanded: false,
7249 * padded: true
7250 * } );
7251 * frame.$element.append(
7252 * toolbar.$element,
7253 * contentFrame.$element.append( $area )
7254 * );
7255 * $( 'body' ).append( frame.$element );
7256 *
7257 * // Here is where the toolbar is actually built. This must be done after inserting it into the
7258 * // document.
7259 * toolbar.initialize();
7260 * toolbar.emit( 'updateState' );
7261 *
7262 * @class
7263 * @extends OO.ui.Element
7264 * @mixins OO.EventEmitter
7265 * @mixins OO.ui.mixin.GroupElement
7266 *
7267 * @constructor
7268 * @param {OO.ui.ToolFactory} toolFactory Factory for creating tools
7269 * @param {OO.ui.ToolGroupFactory} toolGroupFactory Factory for creating toolgroups
7270 * @param {Object} [config] Configuration options
7271 * @cfg {boolean} [actions] Add an actions section to the toolbar. Actions are commands that are included
7272 * in the toolbar, but are not configured as tools. By default, actions are displayed on the right side of
7273 * the toolbar.
7274 * @cfg {boolean} [shadow] Add a shadow below the toolbar.
7275 */
7276 OO.ui.Toolbar = function OoUiToolbar( toolFactory, toolGroupFactory, config ) {
7277 // Allow passing positional parameters inside the config object
7278 if ( OO.isPlainObject( toolFactory ) && config === undefined ) {
7279 config = toolFactory;
7280 toolFactory = config.toolFactory;
7281 toolGroupFactory = config.toolGroupFactory;
7282 }
7283
7284 // Configuration initialization
7285 config = config || {};
7286
7287 // Parent constructor
7288 OO.ui.Toolbar.parent.call( this, config );
7289
7290 // Mixin constructors
7291 OO.EventEmitter.call( this );
7292 OO.ui.mixin.GroupElement.call( this, config );
7293
7294 // Properties
7295 this.toolFactory = toolFactory;
7296 this.toolGroupFactory = toolGroupFactory;
7297 this.groups = [];
7298 this.tools = {};
7299 this.$bar = $( '<div>' );
7300 this.$actions = $( '<div>' );
7301 this.initialized = false;
7302 this.onWindowResizeHandler = this.onWindowResize.bind( this );
7303
7304 // Events
7305 this.$element
7306 .add( this.$bar ).add( this.$group ).add( this.$actions )
7307 .on( 'mousedown keydown', this.onPointerDown.bind( this ) );
7308
7309 // Initialization
7310 this.$group.addClass( 'oo-ui-toolbar-tools' );
7311 if ( config.actions ) {
7312 this.$bar.append( this.$actions.addClass( 'oo-ui-toolbar-actions' ) );
7313 }
7314 this.$bar
7315 .addClass( 'oo-ui-toolbar-bar' )
7316 .append( this.$group, '<div style="clear:both"></div>' );
7317 if ( config.shadow ) {
7318 this.$bar.append( '<div class="oo-ui-toolbar-shadow"></div>' );
7319 }
7320 this.$element.addClass( 'oo-ui-toolbar' ).append( this.$bar );
7321 };
7322
7323 /* Setup */
7324
7325 OO.inheritClass( OO.ui.Toolbar, OO.ui.Element );
7326 OO.mixinClass( OO.ui.Toolbar, OO.EventEmitter );
7327 OO.mixinClass( OO.ui.Toolbar, OO.ui.mixin.GroupElement );
7328
7329 /* Methods */
7330
7331 /**
7332 * Get the tool factory.
7333 *
7334 * @return {OO.ui.ToolFactory} Tool factory
7335 */
7336 OO.ui.Toolbar.prototype.getToolFactory = function () {
7337 return this.toolFactory;
7338 };
7339
7340 /**
7341 * Get the toolgroup factory.
7342 *
7343 * @return {OO.Factory} Toolgroup factory
7344 */
7345 OO.ui.Toolbar.prototype.getToolGroupFactory = function () {
7346 return this.toolGroupFactory;
7347 };
7348
7349 /**
7350 * Handles mouse down events.
7351 *
7352 * @private
7353 * @param {jQuery.Event} e Mouse down event
7354 */
7355 OO.ui.Toolbar.prototype.onPointerDown = function ( e ) {
7356 var $closestWidgetToEvent = $( e.target ).closest( '.oo-ui-widget' ),
7357 $closestWidgetToToolbar = this.$element.closest( '.oo-ui-widget' );
7358 if ( !$closestWidgetToEvent.length || $closestWidgetToEvent[ 0 ] === $closestWidgetToToolbar[ 0 ] ) {
7359 return false;
7360 }
7361 };
7362
7363 /**
7364 * Handle window resize event.
7365 *
7366 * @private
7367 * @param {jQuery.Event} e Window resize event
7368 */
7369 OO.ui.Toolbar.prototype.onWindowResize = function () {
7370 this.$element.toggleClass(
7371 'oo-ui-toolbar-narrow',
7372 this.$bar.width() <= this.narrowThreshold
7373 );
7374 };
7375
7376 /**
7377 * Sets up handles and preloads required information for the toolbar to work.
7378 * This must be called after it is attached to a visible document and before doing anything else.
7379 */
7380 OO.ui.Toolbar.prototype.initialize = function () {
7381 this.initialized = true;
7382 this.narrowThreshold = this.$group.width() + this.$actions.width();
7383 $( this.getElementWindow() ).on( 'resize', this.onWindowResizeHandler );
7384 this.onWindowResize();
7385 };
7386
7387 /**
7388 * Set up the toolbar.
7389 *
7390 * The toolbar is set up with a list of toolgroup configurations that specify the type of
7391 * toolgroup ({@link OO.ui.BarToolGroup bar}, {@link OO.ui.MenuToolGroup menu}, or {@link OO.ui.ListToolGroup list})
7392 * to add and which tools to include, exclude, promote, or demote within that toolgroup. Please
7393 * see {@link OO.ui.ToolGroup toolgroups} for more information about including tools in toolgroups.
7394 *
7395 * @param {Object.<string,Array>} groups List of toolgroup configurations
7396 * @param {Array|string} [groups.include] Tools to include in the toolgroup
7397 * @param {Array|string} [groups.exclude] Tools to exclude from the toolgroup
7398 * @param {Array|string} [groups.promote] Tools to promote to the beginning of the toolgroup
7399 * @param {Array|string} [groups.demote] Tools to demote to the end of the toolgroup
7400 */
7401 OO.ui.Toolbar.prototype.setup = function ( groups ) {
7402 var i, len, type, group,
7403 items = [],
7404 defaultType = 'bar';
7405
7406 // Cleanup previous groups
7407 this.reset();
7408
7409 // Build out new groups
7410 for ( i = 0, len = groups.length; i < len; i++ ) {
7411 group = groups[ i ];
7412 if ( group.include === '*' ) {
7413 // Apply defaults to catch-all groups
7414 if ( group.type === undefined ) {
7415 group.type = 'list';
7416 }
7417 if ( group.label === undefined ) {
7418 group.label = OO.ui.msg( 'ooui-toolbar-more' );
7419 }
7420 }
7421 // Check type has been registered
7422 type = this.getToolGroupFactory().lookup( group.type ) ? group.type : defaultType;
7423 items.push(
7424 this.getToolGroupFactory().create( type, this, group )
7425 );
7426 }
7427 this.addItems( items );
7428 };
7429
7430 /**
7431 * Remove all tools and toolgroups from the toolbar.
7432 */
7433 OO.ui.Toolbar.prototype.reset = function () {
7434 var i, len;
7435
7436 this.groups = [];
7437 this.tools = {};
7438 for ( i = 0, len = this.items.length; i < len; i++ ) {
7439 this.items[ i ].destroy();
7440 }
7441 this.clearItems();
7442 };
7443
7444 /**
7445 * Destroy the toolbar.
7446 *
7447 * Destroying the toolbar removes all event handlers and DOM elements that constitute the toolbar. Call
7448 * this method whenever you are done using a toolbar.
7449 */
7450 OO.ui.Toolbar.prototype.destroy = function () {
7451 $( this.getElementWindow() ).off( 'resize', this.onWindowResizeHandler );
7452 this.reset();
7453 this.$element.remove();
7454 };
7455
7456 /**
7457 * Check if the tool is available.
7458 *
7459 * Available tools are ones that have not yet been added to the toolbar.
7460 *
7461 * @param {string} name Symbolic name of tool
7462 * @return {boolean} Tool is available
7463 */
7464 OO.ui.Toolbar.prototype.isToolAvailable = function ( name ) {
7465 return !this.tools[ name ];
7466 };
7467
7468 /**
7469 * Prevent tool from being used again.
7470 *
7471 * @param {OO.ui.Tool} tool Tool to reserve
7472 */
7473 OO.ui.Toolbar.prototype.reserveTool = function ( tool ) {
7474 this.tools[ tool.getName() ] = tool;
7475 };
7476
7477 /**
7478 * Allow tool to be used again.
7479 *
7480 * @param {OO.ui.Tool} tool Tool to release
7481 */
7482 OO.ui.Toolbar.prototype.releaseTool = function ( tool ) {
7483 delete this.tools[ tool.getName() ];
7484 };
7485
7486 /**
7487 * Get accelerator label for tool.
7488 *
7489 * The OOjs UI library does not contain an accelerator system, but this is the hook for one. To
7490 * use an accelerator system, subclass the toolbar and override this method, which is meant to return a label
7491 * that describes the accelerator keys for the tool passed (by symbolic name) to the method.
7492 *
7493 * @param {string} name Symbolic name of tool
7494 * @return {string|undefined} Tool accelerator label if available
7495 */
7496 OO.ui.Toolbar.prototype.getToolAccelerator = function () {
7497 return undefined;
7498 };
7499
7500 /**
7501 * ToolGroups are collections of {@link OO.ui.Tool tools} that are used in a {@link OO.ui.Toolbar toolbar}.
7502 * The type of toolgroup ({@link OO.ui.ListToolGroup list}, {@link OO.ui.BarToolGroup bar}, or {@link OO.ui.MenuToolGroup menu})
7503 * to which a tool belongs determines how the tool is arranged and displayed in the toolbar. Toolgroups
7504 * themselves are created on demand with a {@link OO.ui.ToolGroupFactory toolgroup factory}.
7505 *
7506 * Toolgroups can contain individual tools, groups of tools, or all available tools:
7507 *
7508 * To include an individual tool (or array of individual tools), specify tools by symbolic name:
7509 *
7510 * include: [ 'tool-name' ] or [ { name: 'tool-name' }]
7511 *
7512 * 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.)
7513 *
7514 * include: [ { group: 'group-name' } ]
7515 *
7516 * To include all tools that are not yet assigned to a toolgroup, use the catch-all selector, an asterisk (*):
7517 *
7518 * include: '*'
7519 *
7520 * See {@link OO.ui.Toolbar toolbars} for a full example. For more information about toolbars in general,
7521 * please see the [OOjs UI documentation on MediaWiki][1].
7522 *
7523 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
7524 *
7525 * @abstract
7526 * @class
7527 * @extends OO.ui.Widget
7528 * @mixins OO.ui.mixin.GroupElement
7529 *
7530 * @constructor
7531 * @param {OO.ui.Toolbar} toolbar
7532 * @param {Object} [config] Configuration options
7533 * @cfg {Array|string} [include=[]] List of tools to include in the toolgroup.
7534 * @cfg {Array|string} [exclude=[]] List of tools to exclude from the toolgroup.
7535 * @cfg {Array|string} [promote=[]] List of tools to promote to the beginning of the toolgroup.
7536 * @cfg {Array|string} [demote=[]] List of tools to demote to the end of the toolgroup.
7537 * This setting is particularly useful when tools have been added to the toolgroup
7538 * en masse (e.g., via the catch-all selector).
7539 */
7540 OO.ui.ToolGroup = function OoUiToolGroup( toolbar, config ) {
7541 // Allow passing positional parameters inside the config object
7542 if ( OO.isPlainObject( toolbar ) && config === undefined ) {
7543 config = toolbar;
7544 toolbar = config.toolbar;
7545 }
7546
7547 // Configuration initialization
7548 config = config || {};
7549
7550 // Parent constructor
7551 OO.ui.ToolGroup.parent.call( this, config );
7552
7553 // Mixin constructors
7554 OO.ui.mixin.GroupElement.call( this, config );
7555
7556 // Properties
7557 this.toolbar = toolbar;
7558 this.tools = {};
7559 this.pressed = null;
7560 this.autoDisabled = false;
7561 this.include = config.include || [];
7562 this.exclude = config.exclude || [];
7563 this.promote = config.promote || [];
7564 this.demote = config.demote || [];
7565 this.onCapturedMouseKeyUpHandler = this.onCapturedMouseKeyUp.bind( this );
7566
7567 // Events
7568 this.$element.on( {
7569 mousedown: this.onMouseKeyDown.bind( this ),
7570 mouseup: this.onMouseKeyUp.bind( this ),
7571 keydown: this.onMouseKeyDown.bind( this ),
7572 keyup: this.onMouseKeyUp.bind( this ),
7573 focus: this.onMouseOverFocus.bind( this ),
7574 blur: this.onMouseOutBlur.bind( this ),
7575 mouseover: this.onMouseOverFocus.bind( this ),
7576 mouseout: this.onMouseOutBlur.bind( this )
7577 } );
7578 this.toolbar.getToolFactory().connect( this, { register: 'onToolFactoryRegister' } );
7579 this.aggregate( { disable: 'itemDisable' } );
7580 this.connect( this, { itemDisable: 'updateDisabled' } );
7581
7582 // Initialization
7583 this.$group.addClass( 'oo-ui-toolGroup-tools' );
7584 this.$element
7585 .addClass( 'oo-ui-toolGroup' )
7586 .append( this.$group );
7587 this.populate();
7588 };
7589
7590 /* Setup */
7591
7592 OO.inheritClass( OO.ui.ToolGroup, OO.ui.Widget );
7593 OO.mixinClass( OO.ui.ToolGroup, OO.ui.mixin.GroupElement );
7594
7595 /* Events */
7596
7597 /**
7598 * @event update
7599 */
7600
7601 /* Static Properties */
7602
7603 /**
7604 * Show labels in tooltips.
7605 *
7606 * @static
7607 * @inheritable
7608 * @property {boolean}
7609 */
7610 OO.ui.ToolGroup.static.titleTooltips = false;
7611
7612 /**
7613 * Show acceleration labels in tooltips.
7614 *
7615 * Note: The OOjs UI library does not include an accelerator system, but does contain
7616 * a hook for one. To use an accelerator system, subclass the {@link OO.ui.Toolbar toolbar} and
7617 * override the {@link OO.ui.Toolbar#getToolAccelerator getToolAccelerator} method, which is
7618 * meant to return a label that describes the accelerator keys for a given tool (e.g., 'Ctrl + M').
7619 *
7620 * @static
7621 * @inheritable
7622 * @property {boolean}
7623 */
7624 OO.ui.ToolGroup.static.accelTooltips = false;
7625
7626 /**
7627 * Automatically disable the toolgroup when all tools are disabled
7628 *
7629 * @static
7630 * @inheritable
7631 * @property {boolean}
7632 */
7633 OO.ui.ToolGroup.static.autoDisable = true;
7634
7635 /* Methods */
7636
7637 /**
7638 * @inheritdoc
7639 */
7640 OO.ui.ToolGroup.prototype.isDisabled = function () {
7641 return this.autoDisabled || OO.ui.ToolGroup.parent.prototype.isDisabled.apply( this, arguments );
7642 };
7643
7644 /**
7645 * @inheritdoc
7646 */
7647 OO.ui.ToolGroup.prototype.updateDisabled = function () {
7648 var i, item, allDisabled = true;
7649
7650 if ( this.constructor.static.autoDisable ) {
7651 for ( i = this.items.length - 1; i >= 0; i-- ) {
7652 item = this.items[ i ];
7653 if ( !item.isDisabled() ) {
7654 allDisabled = false;
7655 break;
7656 }
7657 }
7658 this.autoDisabled = allDisabled;
7659 }
7660 OO.ui.ToolGroup.parent.prototype.updateDisabled.apply( this, arguments );
7661 };
7662
7663 /**
7664 * Handle mouse down and key down events.
7665 *
7666 * @protected
7667 * @param {jQuery.Event} e Mouse down or key down event
7668 */
7669 OO.ui.ToolGroup.prototype.onMouseKeyDown = function ( e ) {
7670 if (
7671 !this.isDisabled() &&
7672 ( e.which === 1 || e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
7673 ) {
7674 this.pressed = this.getTargetTool( e );
7675 if ( this.pressed ) {
7676 this.pressed.setActive( true );
7677 this.getElementDocument().addEventListener( 'mouseup', this.onCapturedMouseKeyUpHandler, true );
7678 this.getElementDocument().addEventListener( 'keyup', this.onCapturedMouseKeyUpHandler, true );
7679 }
7680 return false;
7681 }
7682 };
7683
7684 /**
7685 * Handle captured mouse up and key up events.
7686 *
7687 * @protected
7688 * @param {Event} e Mouse up or key up event
7689 */
7690 OO.ui.ToolGroup.prototype.onCapturedMouseKeyUp = function ( e ) {
7691 this.getElementDocument().removeEventListener( 'mouseup', this.onCapturedMouseKeyUpHandler, true );
7692 this.getElementDocument().removeEventListener( 'keyup', this.onCapturedMouseKeyUpHandler, true );
7693 // onMouseKeyUp may be called a second time, depending on where the mouse is when the button is
7694 // released, but since `this.pressed` will no longer be true, the second call will be ignored.
7695 this.onMouseKeyUp( e );
7696 };
7697
7698 /**
7699 * Handle mouse up and key up events.
7700 *
7701 * @protected
7702 * @param {jQuery.Event} e Mouse up or key up event
7703 */
7704 OO.ui.ToolGroup.prototype.onMouseKeyUp = function ( e ) {
7705 var tool = this.getTargetTool( e );
7706
7707 if (
7708 !this.isDisabled() && this.pressed && this.pressed === tool &&
7709 ( e.which === 1 || e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
7710 ) {
7711 this.pressed.onSelect();
7712 this.pressed = null;
7713 return false;
7714 }
7715
7716 this.pressed = null;
7717 };
7718
7719 /**
7720 * Handle mouse over and focus events.
7721 *
7722 * @protected
7723 * @param {jQuery.Event} e Mouse over or focus event
7724 */
7725 OO.ui.ToolGroup.prototype.onMouseOverFocus = function ( e ) {
7726 var tool = this.getTargetTool( e );
7727
7728 if ( this.pressed && this.pressed === tool ) {
7729 this.pressed.setActive( true );
7730 }
7731 };
7732
7733 /**
7734 * Handle mouse out and blur events.
7735 *
7736 * @protected
7737 * @param {jQuery.Event} e Mouse out or blur event
7738 */
7739 OO.ui.ToolGroup.prototype.onMouseOutBlur = function ( e ) {
7740 var tool = this.getTargetTool( e );
7741
7742 if ( this.pressed && this.pressed === tool ) {
7743 this.pressed.setActive( false );
7744 }
7745 };
7746
7747 /**
7748 * Get the closest tool to a jQuery.Event.
7749 *
7750 * Only tool links are considered, which prevents other elements in the tool such as popups from
7751 * triggering tool group interactions.
7752 *
7753 * @private
7754 * @param {jQuery.Event} e
7755 * @return {OO.ui.Tool|null} Tool, `null` if none was found
7756 */
7757 OO.ui.ToolGroup.prototype.getTargetTool = function ( e ) {
7758 var tool,
7759 $item = $( e.target ).closest( '.oo-ui-tool-link' );
7760
7761 if ( $item.length ) {
7762 tool = $item.parent().data( 'oo-ui-tool' );
7763 }
7764
7765 return tool && !tool.isDisabled() ? tool : null;
7766 };
7767
7768 /**
7769 * Handle tool registry register events.
7770 *
7771 * If a tool is registered after the group is created, we must repopulate the list to account for:
7772 *
7773 * - a tool being added that may be included
7774 * - a tool already included being overridden
7775 *
7776 * @protected
7777 * @param {string} name Symbolic name of tool
7778 */
7779 OO.ui.ToolGroup.prototype.onToolFactoryRegister = function () {
7780 this.populate();
7781 };
7782
7783 /**
7784 * Get the toolbar that contains the toolgroup.
7785 *
7786 * @return {OO.ui.Toolbar} Toolbar that contains the toolgroup
7787 */
7788 OO.ui.ToolGroup.prototype.getToolbar = function () {
7789 return this.toolbar;
7790 };
7791
7792 /**
7793 * Add and remove tools based on configuration.
7794 */
7795 OO.ui.ToolGroup.prototype.populate = function () {
7796 var i, len, name, tool,
7797 toolFactory = this.toolbar.getToolFactory(),
7798 names = {},
7799 add = [],
7800 remove = [],
7801 list = this.toolbar.getToolFactory().getTools(
7802 this.include, this.exclude, this.promote, this.demote
7803 );
7804
7805 // Build a list of needed tools
7806 for ( i = 0, len = list.length; i < len; i++ ) {
7807 name = list[ i ];
7808 if (
7809 // Tool exists
7810 toolFactory.lookup( name ) &&
7811 // Tool is available or is already in this group
7812 ( this.toolbar.isToolAvailable( name ) || this.tools[ name ] )
7813 ) {
7814 // Hack to prevent infinite recursion via ToolGroupTool. We need to reserve the tool before
7815 // creating it, but we can't call reserveTool() yet because we haven't created the tool.
7816 this.toolbar.tools[ name ] = true;
7817 tool = this.tools[ name ];
7818 if ( !tool ) {
7819 // Auto-initialize tools on first use
7820 this.tools[ name ] = tool = toolFactory.create( name, this );
7821 tool.updateTitle();
7822 }
7823 this.toolbar.reserveTool( tool );
7824 add.push( tool );
7825 names[ name ] = true;
7826 }
7827 }
7828 // Remove tools that are no longer needed
7829 for ( name in this.tools ) {
7830 if ( !names[ name ] ) {
7831 this.tools[ name ].destroy();
7832 this.toolbar.releaseTool( this.tools[ name ] );
7833 remove.push( this.tools[ name ] );
7834 delete this.tools[ name ];
7835 }
7836 }
7837 if ( remove.length ) {
7838 this.removeItems( remove );
7839 }
7840 // Update emptiness state
7841 if ( add.length ) {
7842 this.$element.removeClass( 'oo-ui-toolGroup-empty' );
7843 } else {
7844 this.$element.addClass( 'oo-ui-toolGroup-empty' );
7845 }
7846 // Re-add tools (moving existing ones to new locations)
7847 this.addItems( add );
7848 // Disabled state may depend on items
7849 this.updateDisabled();
7850 };
7851
7852 /**
7853 * Destroy toolgroup.
7854 */
7855 OO.ui.ToolGroup.prototype.destroy = function () {
7856 var name;
7857
7858 this.clearItems();
7859 this.toolbar.getToolFactory().disconnect( this );
7860 for ( name in this.tools ) {
7861 this.toolbar.releaseTool( this.tools[ name ] );
7862 this.tools[ name ].disconnect( this ).destroy();
7863 delete this.tools[ name ];
7864 }
7865 this.$element.remove();
7866 };
7867
7868 /**
7869 * MessageDialogs display a confirmation or alert message. By default, the rendered dialog box
7870 * consists of a header that contains the dialog title, a body with the message, and a footer that
7871 * contains any {@link OO.ui.ActionWidget action widgets}. The MessageDialog class is the only type
7872 * of {@link OO.ui.Dialog dialog} that is usually instantiated directly.
7873 *
7874 * There are two basic types of message dialogs, confirmation and alert:
7875 *
7876 * - **confirmation**: the dialog title describes what a progressive action will do and the message provides
7877 * more details about the consequences.
7878 * - **alert**: the dialog title describes which event occurred and the message provides more information
7879 * about why the event occurred.
7880 *
7881 * The MessageDialog class specifies two actions: ‘accept’, the primary
7882 * action (e.g., ‘ok’) and ‘reject,’ the safe action (e.g., ‘cancel’). Both will close the window,
7883 * passing along the selected action.
7884 *
7885 * For more information and examples, please see the [OOjs UI documentation on MediaWiki][1].
7886 *
7887 * @example
7888 * // Example: Creating and opening a message dialog window.
7889 * var messageDialog = new OO.ui.MessageDialog();
7890 *
7891 * // Create and append a window manager.
7892 * var windowManager = new OO.ui.WindowManager();
7893 * $( 'body' ).append( windowManager.$element );
7894 * windowManager.addWindows( [ messageDialog ] );
7895 * // Open the window.
7896 * windowManager.openWindow( messageDialog, {
7897 * title: 'Basic message dialog',
7898 * message: 'This is the message'
7899 * } );
7900 *
7901 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Message_Dialogs
7902 *
7903 * @class
7904 * @extends OO.ui.Dialog
7905 *
7906 * @constructor
7907 * @param {Object} [config] Configuration options
7908 */
7909 OO.ui.MessageDialog = function OoUiMessageDialog( config ) {
7910 // Parent constructor
7911 OO.ui.MessageDialog.parent.call( this, config );
7912
7913 // Properties
7914 this.verticalActionLayout = null;
7915
7916 // Initialization
7917 this.$element.addClass( 'oo-ui-messageDialog' );
7918 };
7919
7920 /* Setup */
7921
7922 OO.inheritClass( OO.ui.MessageDialog, OO.ui.Dialog );
7923
7924 /* Static Properties */
7925
7926 OO.ui.MessageDialog.static.name = 'message';
7927
7928 OO.ui.MessageDialog.static.size = 'small';
7929
7930 OO.ui.MessageDialog.static.verbose = false;
7931
7932 /**
7933 * Dialog title.
7934 *
7935 * The title of a confirmation dialog describes what a progressive action will do. The
7936 * title of an alert dialog describes which event occurred.
7937 *
7938 * @static
7939 * @inheritable
7940 * @property {jQuery|string|Function|null}
7941 */
7942 OO.ui.MessageDialog.static.title = null;
7943
7944 /**
7945 * The message displayed in the dialog body.
7946 *
7947 * A confirmation message describes the consequences of a progressive action. An alert
7948 * message describes why an event occurred.
7949 *
7950 * @static
7951 * @inheritable
7952 * @property {jQuery|string|Function|null}
7953 */
7954 OO.ui.MessageDialog.static.message = null;
7955
7956 OO.ui.MessageDialog.static.actions = [
7957 { action: 'accept', label: OO.ui.deferMsg( 'ooui-dialog-message-accept' ), flags: 'primary' },
7958 { action: 'reject', label: OO.ui.deferMsg( 'ooui-dialog-message-reject' ), flags: 'safe' }
7959 ];
7960
7961 /* Methods */
7962
7963 /**
7964 * @inheritdoc
7965 */
7966 OO.ui.MessageDialog.prototype.setManager = function ( manager ) {
7967 OO.ui.MessageDialog.parent.prototype.setManager.call( this, manager );
7968
7969 // Events
7970 this.manager.connect( this, {
7971 resize: 'onResize'
7972 } );
7973
7974 return this;
7975 };
7976
7977 /**
7978 * @inheritdoc
7979 */
7980 OO.ui.MessageDialog.prototype.onActionResize = function ( action ) {
7981 this.fitActions();
7982 return OO.ui.MessageDialog.parent.prototype.onActionResize.call( this, action );
7983 };
7984
7985 /**
7986 * Handle window resized events.
7987 *
7988 * @private
7989 */
7990 OO.ui.MessageDialog.prototype.onResize = function () {
7991 var dialog = this;
7992 dialog.fitActions();
7993 // Wait for CSS transition to finish and do it again :(
7994 setTimeout( function () {
7995 dialog.fitActions();
7996 }, 300 );
7997 };
7998
7999 /**
8000 * Toggle action layout between vertical and horizontal.
8001 *
8002 *
8003 * @private
8004 * @param {boolean} [value] Layout actions vertically, omit to toggle
8005 * @chainable
8006 */
8007 OO.ui.MessageDialog.prototype.toggleVerticalActionLayout = function ( value ) {
8008 value = value === undefined ? !this.verticalActionLayout : !!value;
8009
8010 if ( value !== this.verticalActionLayout ) {
8011 this.verticalActionLayout = value;
8012 this.$actions
8013 .toggleClass( 'oo-ui-messageDialog-actions-vertical', value )
8014 .toggleClass( 'oo-ui-messageDialog-actions-horizontal', !value );
8015 }
8016
8017 return this;
8018 };
8019
8020 /**
8021 * @inheritdoc
8022 */
8023 OO.ui.MessageDialog.prototype.getActionProcess = function ( action ) {
8024 if ( action ) {
8025 return new OO.ui.Process( function () {
8026 this.close( { action: action } );
8027 }, this );
8028 }
8029 return OO.ui.MessageDialog.parent.prototype.getActionProcess.call( this, action );
8030 };
8031
8032 /**
8033 * @inheritdoc
8034 *
8035 * @param {Object} [data] Dialog opening data
8036 * @param {jQuery|string|Function|null} [data.title] Description of the action being confirmed
8037 * @param {jQuery|string|Function|null} [data.message] Description of the action's consequence
8038 * @param {boolean} [data.verbose] Message is verbose and should be styled as a long message
8039 * @param {Object[]} [data.actions] List of OO.ui.ActionOptionWidget configuration options for each
8040 * action item
8041 */
8042 OO.ui.MessageDialog.prototype.getSetupProcess = function ( data ) {
8043 data = data || {};
8044
8045 // Parent method
8046 return OO.ui.MessageDialog.parent.prototype.getSetupProcess.call( this, data )
8047 .next( function () {
8048 this.title.setLabel(
8049 data.title !== undefined ? data.title : this.constructor.static.title
8050 );
8051 this.message.setLabel(
8052 data.message !== undefined ? data.message : this.constructor.static.message
8053 );
8054 this.message.$element.toggleClass(
8055 'oo-ui-messageDialog-message-verbose',
8056 data.verbose !== undefined ? data.verbose : this.constructor.static.verbose
8057 );
8058 }, this );
8059 };
8060
8061 /**
8062 * @inheritdoc
8063 */
8064 OO.ui.MessageDialog.prototype.getBodyHeight = function () {
8065 var bodyHeight, oldOverflow,
8066 $scrollable = this.container.$element;
8067
8068 oldOverflow = $scrollable[ 0 ].style.overflow;
8069 $scrollable[ 0 ].style.overflow = 'hidden';
8070
8071 OO.ui.Element.static.reconsiderScrollbars( $scrollable[ 0 ] );
8072
8073 bodyHeight = this.text.$element.outerHeight( true );
8074 $scrollable[ 0 ].style.overflow = oldOverflow;
8075
8076 return bodyHeight;
8077 };
8078
8079 /**
8080 * @inheritdoc
8081 */
8082 OO.ui.MessageDialog.prototype.setDimensions = function ( dim ) {
8083 var $scrollable = this.container.$element;
8084 OO.ui.MessageDialog.parent.prototype.setDimensions.call( this, dim );
8085
8086 // Twiddle the overflow property, otherwise an unnecessary scrollbar will be produced.
8087 // Need to do it after transition completes (250ms), add 50ms just in case.
8088 setTimeout( function () {
8089 var oldOverflow = $scrollable[ 0 ].style.overflow;
8090 $scrollable[ 0 ].style.overflow = 'hidden';
8091
8092 OO.ui.Element.static.reconsiderScrollbars( $scrollable[ 0 ] );
8093
8094 $scrollable[ 0 ].style.overflow = oldOverflow;
8095 }, 300 );
8096
8097 return this;
8098 };
8099
8100 /**
8101 * @inheritdoc
8102 */
8103 OO.ui.MessageDialog.prototype.initialize = function () {
8104 // Parent method
8105 OO.ui.MessageDialog.parent.prototype.initialize.call( this );
8106
8107 // Properties
8108 this.$actions = $( '<div>' );
8109 this.container = new OO.ui.PanelLayout( {
8110 scrollable: true, classes: [ 'oo-ui-messageDialog-container' ]
8111 } );
8112 this.text = new OO.ui.PanelLayout( {
8113 padded: true, expanded: false, classes: [ 'oo-ui-messageDialog-text' ]
8114 } );
8115 this.message = new OO.ui.LabelWidget( {
8116 classes: [ 'oo-ui-messageDialog-message' ]
8117 } );
8118
8119 // Initialization
8120 this.title.$element.addClass( 'oo-ui-messageDialog-title' );
8121 this.$content.addClass( 'oo-ui-messageDialog-content' );
8122 this.container.$element.append( this.text.$element );
8123 this.text.$element.append( this.title.$element, this.message.$element );
8124 this.$body.append( this.container.$element );
8125 this.$actions.addClass( 'oo-ui-messageDialog-actions' );
8126 this.$foot.append( this.$actions );
8127 };
8128
8129 /**
8130 * @inheritdoc
8131 */
8132 OO.ui.MessageDialog.prototype.attachActions = function () {
8133 var i, len, other, special, others;
8134
8135 // Parent method
8136 OO.ui.MessageDialog.parent.prototype.attachActions.call( this );
8137
8138 special = this.actions.getSpecial();
8139 others = this.actions.getOthers();
8140 if ( special.safe ) {
8141 this.$actions.append( special.safe.$element );
8142 special.safe.toggleFramed( false );
8143 }
8144 if ( others.length ) {
8145 for ( i = 0, len = others.length; i < len; i++ ) {
8146 other = others[ i ];
8147 this.$actions.append( other.$element );
8148 other.toggleFramed( false );
8149 }
8150 }
8151 if ( special.primary ) {
8152 this.$actions.append( special.primary.$element );
8153 special.primary.toggleFramed( false );
8154 }
8155
8156 if ( !this.isOpening() ) {
8157 // If the dialog is currently opening, this will be called automatically soon.
8158 // This also calls #fitActions.
8159 this.updateSize();
8160 }
8161 };
8162
8163 /**
8164 * Fit action actions into columns or rows.
8165 *
8166 * Columns will be used if all labels can fit without overflow, otherwise rows will be used.
8167 *
8168 * @private
8169 */
8170 OO.ui.MessageDialog.prototype.fitActions = function () {
8171 var i, len, action,
8172 previous = this.verticalActionLayout,
8173 actions = this.actions.get();
8174
8175 // Detect clipping
8176 this.toggleVerticalActionLayout( false );
8177 for ( i = 0, len = actions.length; i < len; i++ ) {
8178 action = actions[ i ];
8179 if ( action.$element.innerWidth() < action.$label.outerWidth( true ) ) {
8180 this.toggleVerticalActionLayout( true );
8181 break;
8182 }
8183 }
8184
8185 // Move the body out of the way of the foot
8186 this.$body.css( 'bottom', this.$foot.outerHeight( true ) );
8187
8188 if ( this.verticalActionLayout !== previous ) {
8189 // We changed the layout, window height might need to be updated.
8190 this.updateSize();
8191 }
8192 };
8193
8194 /**
8195 * ProcessDialog windows encapsulate a {@link OO.ui.Process process} and all of the code necessary
8196 * to complete it. If the process terminates with an error, a customizable {@link OO.ui.Error error
8197 * interface} alerts users to the trouble, permitting the user to dismiss the error and try again when
8198 * relevant. The ProcessDialog class is always extended and customized with the actions and content
8199 * required for each process.
8200 *
8201 * The process dialog box consists of a header that visually represents the ‘working’ state of long
8202 * processes with an animation. The header contains the dialog title as well as
8203 * two {@link OO.ui.ActionWidget action widgets}: a ‘safe’ action on the left (e.g., ‘Cancel’) and
8204 * a ‘primary’ action on the right (e.g., ‘Done’).
8205 *
8206 * Like other windows, the process dialog is managed by a {@link OO.ui.WindowManager window manager}.
8207 * Please see the [OOjs UI documentation on MediaWiki][1] for more information and examples.
8208 *
8209 * @example
8210 * // Example: Creating and opening a process dialog window.
8211 * function MyProcessDialog( config ) {
8212 * MyProcessDialog.parent.call( this, config );
8213 * }
8214 * OO.inheritClass( MyProcessDialog, OO.ui.ProcessDialog );
8215 *
8216 * MyProcessDialog.static.title = 'Process dialog';
8217 * MyProcessDialog.static.actions = [
8218 * { action: 'save', label: 'Done', flags: 'primary' },
8219 * { label: 'Cancel', flags: 'safe' }
8220 * ];
8221 *
8222 * MyProcessDialog.prototype.initialize = function () {
8223 * MyProcessDialog.parent.prototype.initialize.apply( this, arguments );
8224 * this.content = new OO.ui.PanelLayout( { padded: true, expanded: false } );
8225 * 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>' );
8226 * this.$body.append( this.content.$element );
8227 * };
8228 * MyProcessDialog.prototype.getActionProcess = function ( action ) {
8229 * var dialog = this;
8230 * if ( action ) {
8231 * return new OO.ui.Process( function () {
8232 * dialog.close( { action: action } );
8233 * } );
8234 * }
8235 * return MyProcessDialog.parent.prototype.getActionProcess.call( this, action );
8236 * };
8237 *
8238 * var windowManager = new OO.ui.WindowManager();
8239 * $( 'body' ).append( windowManager.$element );
8240 *
8241 * var dialog = new MyProcessDialog();
8242 * windowManager.addWindows( [ dialog ] );
8243 * windowManager.openWindow( dialog );
8244 *
8245 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs
8246 *
8247 * @abstract
8248 * @class
8249 * @extends OO.ui.Dialog
8250 *
8251 * @constructor
8252 * @param {Object} [config] Configuration options
8253 */
8254 OO.ui.ProcessDialog = function OoUiProcessDialog( config ) {
8255 // Parent constructor
8256 OO.ui.ProcessDialog.parent.call( this, config );
8257
8258 // Properties
8259 this.fitOnOpen = false;
8260
8261 // Initialization
8262 this.$element.addClass( 'oo-ui-processDialog' );
8263 };
8264
8265 /* Setup */
8266
8267 OO.inheritClass( OO.ui.ProcessDialog, OO.ui.Dialog );
8268
8269 /* Methods */
8270
8271 /**
8272 * Handle dismiss button click events.
8273 *
8274 * Hides errors.
8275 *
8276 * @private
8277 */
8278 OO.ui.ProcessDialog.prototype.onDismissErrorButtonClick = function () {
8279 this.hideErrors();
8280 };
8281
8282 /**
8283 * Handle retry button click events.
8284 *
8285 * Hides errors and then tries again.
8286 *
8287 * @private
8288 */
8289 OO.ui.ProcessDialog.prototype.onRetryButtonClick = function () {
8290 this.hideErrors();
8291 this.executeAction( this.currentAction );
8292 };
8293
8294 /**
8295 * @inheritdoc
8296 */
8297 OO.ui.ProcessDialog.prototype.onActionResize = function ( action ) {
8298 if ( this.actions.isSpecial( action ) ) {
8299 this.fitLabel();
8300 }
8301 return OO.ui.ProcessDialog.parent.prototype.onActionResize.call( this, action );
8302 };
8303
8304 /**
8305 * @inheritdoc
8306 */
8307 OO.ui.ProcessDialog.prototype.initialize = function () {
8308 // Parent method
8309 OO.ui.ProcessDialog.parent.prototype.initialize.call( this );
8310
8311 // Properties
8312 this.$navigation = $( '<div>' );
8313 this.$location = $( '<div>' );
8314 this.$safeActions = $( '<div>' );
8315 this.$primaryActions = $( '<div>' );
8316 this.$otherActions = $( '<div>' );
8317 this.dismissButton = new OO.ui.ButtonWidget( {
8318 label: OO.ui.msg( 'ooui-dialog-process-dismiss' )
8319 } );
8320 this.retryButton = new OO.ui.ButtonWidget();
8321 this.$errors = $( '<div>' );
8322 this.$errorsTitle = $( '<div>' );
8323
8324 // Events
8325 this.dismissButton.connect( this, { click: 'onDismissErrorButtonClick' } );
8326 this.retryButton.connect( this, { click: 'onRetryButtonClick' } );
8327
8328 // Initialization
8329 this.title.$element.addClass( 'oo-ui-processDialog-title' );
8330 this.$location
8331 .append( this.title.$element )
8332 .addClass( 'oo-ui-processDialog-location' );
8333 this.$safeActions.addClass( 'oo-ui-processDialog-actions-safe' );
8334 this.$primaryActions.addClass( 'oo-ui-processDialog-actions-primary' );
8335 this.$otherActions.addClass( 'oo-ui-processDialog-actions-other' );
8336 this.$errorsTitle
8337 .addClass( 'oo-ui-processDialog-errors-title' )
8338 .text( OO.ui.msg( 'ooui-dialog-process-error' ) );
8339 this.$errors
8340 .addClass( 'oo-ui-processDialog-errors oo-ui-element-hidden' )
8341 .append( this.$errorsTitle, this.dismissButton.$element, this.retryButton.$element );
8342 this.$content
8343 .addClass( 'oo-ui-processDialog-content' )
8344 .append( this.$errors );
8345 this.$navigation
8346 .addClass( 'oo-ui-processDialog-navigation' )
8347 .append( this.$safeActions, this.$location, this.$primaryActions );
8348 this.$head.append( this.$navigation );
8349 this.$foot.append( this.$otherActions );
8350 };
8351
8352 /**
8353 * @inheritdoc
8354 */
8355 OO.ui.ProcessDialog.prototype.getActionWidgets = function ( actions ) {
8356 var i, len, widgets = [];
8357 for ( i = 0, len = actions.length; i < len; i++ ) {
8358 widgets.push(
8359 new OO.ui.ActionWidget( $.extend( { framed: true }, actions[ i ] ) )
8360 );
8361 }
8362 return widgets;
8363 };
8364
8365 /**
8366 * @inheritdoc
8367 */
8368 OO.ui.ProcessDialog.prototype.attachActions = function () {
8369 var i, len, other, special, others;
8370
8371 // Parent method
8372 OO.ui.ProcessDialog.parent.prototype.attachActions.call( this );
8373
8374 special = this.actions.getSpecial();
8375 others = this.actions.getOthers();
8376 if ( special.primary ) {
8377 this.$primaryActions.append( special.primary.$element );
8378 }
8379 for ( i = 0, len = others.length; i < len; i++ ) {
8380 other = others[ i ];
8381 this.$otherActions.append( other.$element );
8382 }
8383 if ( special.safe ) {
8384 this.$safeActions.append( special.safe.$element );
8385 }
8386
8387 this.fitLabel();
8388 this.$body.css( 'bottom', this.$foot.outerHeight( true ) );
8389 };
8390
8391 /**
8392 * @inheritdoc
8393 */
8394 OO.ui.ProcessDialog.prototype.executeAction = function ( action ) {
8395 var process = this;
8396 return OO.ui.ProcessDialog.parent.prototype.executeAction.call( this, action )
8397 .fail( function ( errors ) {
8398 process.showErrors( errors || [] );
8399 } );
8400 };
8401
8402 /**
8403 * @inheritdoc
8404 */
8405 OO.ui.ProcessDialog.prototype.setDimensions = function () {
8406 // Parent method
8407 OO.ui.ProcessDialog.parent.prototype.setDimensions.apply( this, arguments );
8408
8409 this.fitLabel();
8410 };
8411
8412 /**
8413 * Fit label between actions.
8414 *
8415 * @private
8416 * @chainable
8417 */
8418 OO.ui.ProcessDialog.prototype.fitLabel = function () {
8419 var safeWidth, primaryWidth, biggerWidth, labelWidth, navigationWidth, leftWidth, rightWidth,
8420 size = this.getSizeProperties();
8421
8422 if ( typeof size.width !== 'number' ) {
8423 if ( this.isOpened() ) {
8424 navigationWidth = this.$head.width() - 20;
8425 } else if ( this.isOpening() ) {
8426 if ( !this.fitOnOpen ) {
8427 // Size is relative and the dialog isn't open yet, so wait.
8428 this.manager.opening.done( this.fitLabel.bind( this ) );
8429 this.fitOnOpen = true;
8430 }
8431 return;
8432 } else {
8433 return;
8434 }
8435 } else {
8436 navigationWidth = size.width - 20;
8437 }
8438
8439 safeWidth = this.$safeActions.is( ':visible' ) ? this.$safeActions.width() : 0;
8440 primaryWidth = this.$primaryActions.is( ':visible' ) ? this.$primaryActions.width() : 0;
8441 biggerWidth = Math.max( safeWidth, primaryWidth );
8442
8443 labelWidth = this.title.$element.width();
8444
8445 if ( 2 * biggerWidth + labelWidth < navigationWidth ) {
8446 // We have enough space to center the label
8447 leftWidth = rightWidth = biggerWidth;
8448 } else {
8449 // Let's hope we at least have enough space not to overlap, because we can't wrap the label…
8450 if ( this.getDir() === 'ltr' ) {
8451 leftWidth = safeWidth;
8452 rightWidth = primaryWidth;
8453 } else {
8454 leftWidth = primaryWidth;
8455 rightWidth = safeWidth;
8456 }
8457 }
8458
8459 this.$location.css( { paddingLeft: leftWidth, paddingRight: rightWidth } );
8460
8461 return this;
8462 };
8463
8464 /**
8465 * Handle errors that occurred during accept or reject processes.
8466 *
8467 * @private
8468 * @param {OO.ui.Error[]|OO.ui.Error} errors Errors to be handled
8469 */
8470 OO.ui.ProcessDialog.prototype.showErrors = function ( errors ) {
8471 var i, len, $item, actions,
8472 items = [],
8473 abilities = {},
8474 recoverable = true,
8475 warning = false;
8476
8477 if ( errors instanceof OO.ui.Error ) {
8478 errors = [ errors ];
8479 }
8480
8481 for ( i = 0, len = errors.length; i < len; i++ ) {
8482 if ( !errors[ i ].isRecoverable() ) {
8483 recoverable = false;
8484 }
8485 if ( errors[ i ].isWarning() ) {
8486 warning = true;
8487 }
8488 $item = $( '<div>' )
8489 .addClass( 'oo-ui-processDialog-error' )
8490 .append( errors[ i ].getMessage() );
8491 items.push( $item[ 0 ] );
8492 }
8493 this.$errorItems = $( items );
8494 if ( recoverable ) {
8495 abilities[this.currentAction] = true;
8496 // Copy the flags from the first matching action
8497 actions = this.actions.get( { actions: this.currentAction } );
8498 if ( actions.length ) {
8499 this.retryButton.clearFlags().setFlags( actions[0].getFlags() );
8500 }
8501 } else {
8502 abilities[this.currentAction] = false;
8503 this.actions.setAbilities( abilities );
8504 }
8505 if ( warning ) {
8506 this.retryButton.setLabel( OO.ui.msg( 'ooui-dialog-process-continue' ) );
8507 } else {
8508 this.retryButton.setLabel( OO.ui.msg( 'ooui-dialog-process-retry' ) );
8509 }
8510 this.retryButton.toggle( recoverable );
8511 this.$errorsTitle.after( this.$errorItems );
8512 this.$errors.removeClass( 'oo-ui-element-hidden' ).scrollTop( 0 );
8513 };
8514
8515 /**
8516 * Hide errors.
8517 *
8518 * @private
8519 */
8520 OO.ui.ProcessDialog.prototype.hideErrors = function () {
8521 this.$errors.addClass( 'oo-ui-element-hidden' );
8522 if ( this.$errorItems ) {
8523 this.$errorItems.remove();
8524 this.$errorItems = null;
8525 }
8526 };
8527
8528 /**
8529 * @inheritdoc
8530 */
8531 OO.ui.ProcessDialog.prototype.getTeardownProcess = function ( data ) {
8532 // Parent method
8533 return OO.ui.ProcessDialog.parent.prototype.getTeardownProcess.call( this, data )
8534 .first( function () {
8535 // Make sure to hide errors
8536 this.hideErrors();
8537 this.fitOnOpen = false;
8538 }, this );
8539 };
8540
8541 /**
8542 * FieldLayouts are used with OO.ui.FieldsetLayout. Each FieldLayout requires a field-widget,
8543 * which is a widget that is specified by reference before any optional configuration settings.
8544 *
8545 * Field layouts can be configured with help text and/or labels. Labels are aligned in one of four ways:
8546 *
8547 * - **left**: The label is placed before the field-widget and aligned with the left margin.
8548 * A left-alignment is used for forms with many fields.
8549 * - **right**: The label is placed before the field-widget and aligned to the right margin.
8550 * A right-alignment is used for long but familiar forms which users tab through,
8551 * verifying the current field with a quick glance at the label.
8552 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
8553 * that users fill out from top to bottom.
8554 * - **inline**: The label is placed after the field-widget and aligned to the left.
8555 * An inline-alignment is best used with checkboxes or radio buttons.
8556 *
8557 * Help text is accessed via a help icon that appears in the upper right corner of the rendered field layout.
8558 * Please see the [OOjs UI documentation on MediaWiki] [1] for examples and more information.
8559 *
8560 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Fields_and_Fieldsets
8561 * @class
8562 * @extends OO.ui.Layout
8563 * @mixins OO.ui.mixin.LabelElement
8564 * @mixins OO.ui.mixin.TitledElement
8565 *
8566 * @constructor
8567 * @param {OO.ui.Widget} fieldWidget Field widget
8568 * @param {Object} [config] Configuration options
8569 * @cfg {string} [align='left'] Alignment of the label: 'left', 'right', 'top' or 'inline'
8570 * @cfg {Array} [errors] Error messages about the widget, which will be displayed below the widget.
8571 * The array may contain strings or OO.ui.HtmlSnippet instances.
8572 * @cfg {Array} [notices] Notices about the widget, which will be displayed below the widget.
8573 * The array may contain strings or OO.ui.HtmlSnippet instances.
8574 * @cfg {string|OO.ui.HtmlSnippet} [help] Help text. When help text is specified, a "help" icon will appear
8575 * in the upper-right corner of the rendered field; clicking it will display the text in a popup.
8576 * For important messages, you are advised to use `notices`, as they are always shown.
8577 */
8578 OO.ui.FieldLayout = function OoUiFieldLayout( fieldWidget, config ) {
8579 // Allow passing positional parameters inside the config object
8580 if ( OO.isPlainObject( fieldWidget ) && config === undefined ) {
8581 config = fieldWidget;
8582 fieldWidget = config.fieldWidget;
8583 }
8584
8585 var hasInputWidget = fieldWidget.constructor.static.supportsSimpleLabel,
8586 div, i;
8587
8588 // Configuration initialization
8589 config = $.extend( { align: 'left' }, config );
8590
8591 // Parent constructor
8592 OO.ui.FieldLayout.parent.call( this, config );
8593
8594 // Mixin constructors
8595 OO.ui.mixin.LabelElement.call( this, config );
8596 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$label } ) );
8597
8598 // Properties
8599 this.fieldWidget = fieldWidget;
8600 this.errors = config.errors || [];
8601 this.notices = config.notices || [];
8602 this.$field = $( '<div>' );
8603 this.$messages = $( '<ul>' );
8604 this.$body = $( '<' + ( hasInputWidget ? 'label' : 'div' ) + '>' );
8605 this.align = null;
8606 if ( config.help ) {
8607 this.popupButtonWidget = new OO.ui.PopupButtonWidget( {
8608 classes: [ 'oo-ui-fieldLayout-help' ],
8609 framed: false,
8610 icon: 'info'
8611 } );
8612
8613 div = $( '<div>' );
8614 if ( config.help instanceof OO.ui.HtmlSnippet ) {
8615 div.html( config.help.toString() );
8616 } else {
8617 div.text( config.help );
8618 }
8619 this.popupButtonWidget.getPopup().$body.append(
8620 div.addClass( 'oo-ui-fieldLayout-help-content' )
8621 );
8622 this.$help = this.popupButtonWidget.$element;
8623 } else {
8624 this.$help = $( [] );
8625 }
8626
8627 // Events
8628 if ( hasInputWidget ) {
8629 this.$label.on( 'click', this.onLabelClick.bind( this ) );
8630 }
8631 this.fieldWidget.connect( this, { disable: 'onFieldDisable' } );
8632
8633 // Initialization
8634 this.$element
8635 .addClass( 'oo-ui-fieldLayout' )
8636 .append( this.$help, this.$body );
8637 if ( this.errors.length || this.notices.length ) {
8638 this.$element.append( this.$messages );
8639 }
8640 this.$body.addClass( 'oo-ui-fieldLayout-body' );
8641 this.$messages.addClass( 'oo-ui-fieldLayout-messages' );
8642 this.$field
8643 .addClass( 'oo-ui-fieldLayout-field' )
8644 .toggleClass( 'oo-ui-fieldLayout-disable', this.fieldWidget.isDisabled() )
8645 .append( this.fieldWidget.$element );
8646
8647 for ( i = 0; i < this.notices.length; i++ ) {
8648 this.$messages.append( this.makeMessage( 'notice', this.notices[i] ) );
8649 }
8650 for ( i = 0; i < this.errors.length; i++ ) {
8651 this.$messages.append( this.makeMessage( 'error', this.errors[i] ) );
8652 }
8653
8654 this.setAlignment( config.align );
8655 };
8656
8657 /* Setup */
8658
8659 OO.inheritClass( OO.ui.FieldLayout, OO.ui.Layout );
8660 OO.mixinClass( OO.ui.FieldLayout, OO.ui.mixin.LabelElement );
8661 OO.mixinClass( OO.ui.FieldLayout, OO.ui.mixin.TitledElement );
8662
8663 /* Methods */
8664
8665 /**
8666 * Handle field disable events.
8667 *
8668 * @private
8669 * @param {boolean} value Field is disabled
8670 */
8671 OO.ui.FieldLayout.prototype.onFieldDisable = function ( value ) {
8672 this.$element.toggleClass( 'oo-ui-fieldLayout-disabled', value );
8673 };
8674
8675 /**
8676 * Handle label mouse click events.
8677 *
8678 * @private
8679 * @param {jQuery.Event} e Mouse click event
8680 */
8681 OO.ui.FieldLayout.prototype.onLabelClick = function () {
8682 this.fieldWidget.simulateLabelClick();
8683 return false;
8684 };
8685
8686 /**
8687 * Get the widget contained by the field.
8688 *
8689 * @return {OO.ui.Widget} Field widget
8690 */
8691 OO.ui.FieldLayout.prototype.getField = function () {
8692 return this.fieldWidget;
8693 };
8694
8695 /**
8696 * @param {string} kind 'error' or 'notice'
8697 * @param {string|OO.ui.HtmlSnippet} text
8698 * @return {jQuery}
8699 */
8700 OO.ui.FieldLayout.prototype.makeMessage = function ( kind, text ) {
8701 var $listItem, $icon, message;
8702 $listItem = $( '<li>' );
8703 if ( kind === 'error' ) {
8704 $icon = new OO.ui.IconWidget( { icon: 'alert', flags: [ 'warning' ] } ).$element;
8705 } else if ( kind === 'notice' ) {
8706 $icon = new OO.ui.IconWidget( { icon: 'info' } ).$element;
8707 } else {
8708 $icon = '';
8709 }
8710 message = new OO.ui.LabelWidget( { label: text } );
8711 $listItem
8712 .append( $icon, message.$element )
8713 .addClass( 'oo-ui-fieldLayout-messages-' + kind );
8714 return $listItem;
8715 };
8716
8717 /**
8718 * Set the field alignment mode.
8719 *
8720 * @private
8721 * @param {string} value Alignment mode, either 'left', 'right', 'top' or 'inline'
8722 * @chainable
8723 */
8724 OO.ui.FieldLayout.prototype.setAlignment = function ( value ) {
8725 if ( value !== this.align ) {
8726 // Default to 'left'
8727 if ( [ 'left', 'right', 'top', 'inline' ].indexOf( value ) === -1 ) {
8728 value = 'left';
8729 }
8730 // Reorder elements
8731 if ( value === 'inline' ) {
8732 this.$body.append( this.$field, this.$label );
8733 } else {
8734 this.$body.append( this.$label, this.$field );
8735 }
8736 // Set classes. The following classes can be used here:
8737 // * oo-ui-fieldLayout-align-left
8738 // * oo-ui-fieldLayout-align-right
8739 // * oo-ui-fieldLayout-align-top
8740 // * oo-ui-fieldLayout-align-inline
8741 if ( this.align ) {
8742 this.$element.removeClass( 'oo-ui-fieldLayout-align-' + this.align );
8743 }
8744 this.$element.addClass( 'oo-ui-fieldLayout-align-' + value );
8745 this.align = value;
8746 }
8747
8748 return this;
8749 };
8750
8751 /**
8752 * ActionFieldLayouts are used with OO.ui.FieldsetLayout. The layout consists of a field-widget, a button,
8753 * and an optional label and/or help text. The field-widget (e.g., a {@link OO.ui.TextInputWidget TextInputWidget}),
8754 * is required and is specified before any optional configuration settings.
8755 *
8756 * Labels can be aligned in one of four ways:
8757 *
8758 * - **left**: The label is placed before the field-widget and aligned with the left margin.
8759 * A left-alignment is used for forms with many fields.
8760 * - **right**: The label is placed before the field-widget and aligned to the right margin.
8761 * A right-alignment is used for long but familiar forms which users tab through,
8762 * verifying the current field with a quick glance at the label.
8763 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
8764 * that users fill out from top to bottom.
8765 * - **inline**: The label is placed after the field-widget and aligned to the left.
8766 * An inline-alignment is best used with checkboxes or radio buttons.
8767 *
8768 * Help text is accessed via a help icon that appears in the upper right corner of the rendered field layout when help
8769 * text is specified.
8770 *
8771 * @example
8772 * // Example of an ActionFieldLayout
8773 * var actionFieldLayout = new OO.ui.ActionFieldLayout(
8774 * new OO.ui.TextInputWidget( {
8775 * placeholder: 'Field widget'
8776 * } ),
8777 * new OO.ui.ButtonWidget( {
8778 * label: 'Button'
8779 * } ),
8780 * {
8781 * label: 'An ActionFieldLayout. This label is aligned top',
8782 * align: 'top',
8783 * help: 'This is help text'
8784 * }
8785 * );
8786 *
8787 * $( 'body' ).append( actionFieldLayout.$element );
8788 *
8789 *
8790 * @class
8791 * @extends OO.ui.FieldLayout
8792 *
8793 * @constructor
8794 * @param {OO.ui.Widget} fieldWidget Field widget
8795 * @param {OO.ui.ButtonWidget} buttonWidget Button widget
8796 */
8797 OO.ui.ActionFieldLayout = function OoUiActionFieldLayout( fieldWidget, buttonWidget, config ) {
8798 // Allow passing positional parameters inside the config object
8799 if ( OO.isPlainObject( fieldWidget ) && config === undefined ) {
8800 config = fieldWidget;
8801 fieldWidget = config.fieldWidget;
8802 buttonWidget = config.buttonWidget;
8803 }
8804
8805 // Parent constructor
8806 OO.ui.ActionFieldLayout.parent.call( this, fieldWidget, config );
8807
8808 // Properties
8809 this.buttonWidget = buttonWidget;
8810 this.$button = $( '<div>' );
8811 this.$input = $( '<div>' );
8812
8813 // Initialization
8814 this.$element
8815 .addClass( 'oo-ui-actionFieldLayout' );
8816 this.$button
8817 .addClass( 'oo-ui-actionFieldLayout-button' )
8818 .append( this.buttonWidget.$element );
8819 this.$input
8820 .addClass( 'oo-ui-actionFieldLayout-input' )
8821 .append( this.fieldWidget.$element );
8822 this.$field
8823 .append( this.$input, this.$button );
8824 };
8825
8826 /* Setup */
8827
8828 OO.inheritClass( OO.ui.ActionFieldLayout, OO.ui.FieldLayout );
8829
8830 /**
8831 * FieldsetLayouts are composed of one or more {@link OO.ui.FieldLayout FieldLayouts},
8832 * which each contain an individual widget and, optionally, a label. Each Fieldset can be
8833 * configured with a label as well. For more information and examples,
8834 * please see the [OOjs UI documentation on MediaWiki][1].
8835 *
8836 * @example
8837 * // Example of a fieldset layout
8838 * var input1 = new OO.ui.TextInputWidget( {
8839 * placeholder: 'A text input field'
8840 * } );
8841 *
8842 * var input2 = new OO.ui.TextInputWidget( {
8843 * placeholder: 'A text input field'
8844 * } );
8845 *
8846 * var fieldset = new OO.ui.FieldsetLayout( {
8847 * label: 'Example of a fieldset layout'
8848 * } );
8849 *
8850 * fieldset.addItems( [
8851 * new OO.ui.FieldLayout( input1, {
8852 * label: 'Field One'
8853 * } ),
8854 * new OO.ui.FieldLayout( input2, {
8855 * label: 'Field Two'
8856 * } )
8857 * ] );
8858 * $( 'body' ).append( fieldset.$element );
8859 *
8860 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Fields_and_Fieldsets
8861 *
8862 * @class
8863 * @extends OO.ui.Layout
8864 * @mixins OO.ui.mixin.IconElement
8865 * @mixins OO.ui.mixin.LabelElement
8866 * @mixins OO.ui.mixin.GroupElement
8867 *
8868 * @constructor
8869 * @param {Object} [config] Configuration options
8870 * @cfg {OO.ui.FieldLayout[]} [items] An array of fields to add to the fieldset. See OO.ui.FieldLayout for more information about fields.
8871 */
8872 OO.ui.FieldsetLayout = function OoUiFieldsetLayout( config ) {
8873 // Configuration initialization
8874 config = config || {};
8875
8876 // Parent constructor
8877 OO.ui.FieldsetLayout.parent.call( this, config );
8878
8879 // Mixin constructors
8880 OO.ui.mixin.IconElement.call( this, config );
8881 OO.ui.mixin.LabelElement.call( this, config );
8882 OO.ui.mixin.GroupElement.call( this, config );
8883
8884 if ( config.help ) {
8885 this.popupButtonWidget = new OO.ui.PopupButtonWidget( {
8886 classes: [ 'oo-ui-fieldsetLayout-help' ],
8887 framed: false,
8888 icon: 'info'
8889 } );
8890
8891 this.popupButtonWidget.getPopup().$body.append(
8892 $( '<div>' )
8893 .text( config.help )
8894 .addClass( 'oo-ui-fieldsetLayout-help-content' )
8895 );
8896 this.$help = this.popupButtonWidget.$element;
8897 } else {
8898 this.$help = $( [] );
8899 }
8900
8901 // Initialization
8902 this.$element
8903 .addClass( 'oo-ui-fieldsetLayout' )
8904 .prepend( this.$help, this.$icon, this.$label, this.$group );
8905 if ( Array.isArray( config.items ) ) {
8906 this.addItems( config.items );
8907 }
8908 };
8909
8910 /* Setup */
8911
8912 OO.inheritClass( OO.ui.FieldsetLayout, OO.ui.Layout );
8913 OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.mixin.IconElement );
8914 OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.mixin.LabelElement );
8915 OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.mixin.GroupElement );
8916
8917 /**
8918 * FormLayouts are used to wrap {@link OO.ui.FieldsetLayout FieldsetLayouts} when you intend to use browser-based
8919 * form submission for the fields instead of handling them in JavaScript. Form layouts can be configured with an
8920 * HTML form action, an encoding type, and a method using the #action, #enctype, and #method configs, respectively.
8921 * See the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
8922 *
8923 * Only widgets from the {@link OO.ui.InputWidget InputWidget} family support form submission. It
8924 * includes standard form elements like {@link OO.ui.CheckboxInputWidget checkboxes}, {@link
8925 * OO.ui.RadioInputWidget radio buttons} and {@link OO.ui.TextInputWidget text fields}, as well as
8926 * some fancier controls. Some controls have both regular and InputWidget variants, for example
8927 * OO.ui.DropdownWidget and OO.ui.DropdownInputWidget – only the latter support form submission and
8928 * often have simplified APIs to match the capabilities of HTML forms.
8929 * See the [OOjs UI Inputs documentation on MediaWiki] [2] for more information about InputWidgets.
8930 *
8931 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Forms
8932 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
8933 *
8934 * @example
8935 * // Example of a form layout that wraps a fieldset layout
8936 * var input1 = new OO.ui.TextInputWidget( {
8937 * placeholder: 'Username'
8938 * } );
8939 * var input2 = new OO.ui.TextInputWidget( {
8940 * placeholder: 'Password',
8941 * type: 'password'
8942 * } );
8943 * var submit = new OO.ui.ButtonInputWidget( {
8944 * label: 'Submit'
8945 * } );
8946 *
8947 * var fieldset = new OO.ui.FieldsetLayout( {
8948 * label: 'A form layout'
8949 * } );
8950 * fieldset.addItems( [
8951 * new OO.ui.FieldLayout( input1, {
8952 * label: 'Username',
8953 * align: 'top'
8954 * } ),
8955 * new OO.ui.FieldLayout( input2, {
8956 * label: 'Password',
8957 * align: 'top'
8958 * } ),
8959 * new OO.ui.FieldLayout( submit )
8960 * ] );
8961 * var form = new OO.ui.FormLayout( {
8962 * items: [ fieldset ],
8963 * action: '/api/formhandler',
8964 * method: 'get'
8965 * } )
8966 * $( 'body' ).append( form.$element );
8967 *
8968 * @class
8969 * @extends OO.ui.Layout
8970 * @mixins OO.ui.mixin.GroupElement
8971 *
8972 * @constructor
8973 * @param {Object} [config] Configuration options
8974 * @cfg {string} [method] HTML form `method` attribute
8975 * @cfg {string} [action] HTML form `action` attribute
8976 * @cfg {string} [enctype] HTML form `enctype` attribute
8977 * @cfg {OO.ui.FieldsetLayout[]} [items] Fieldset layouts to add to the form layout.
8978 */
8979 OO.ui.FormLayout = function OoUiFormLayout( config ) {
8980 // Configuration initialization
8981 config = config || {};
8982
8983 // Parent constructor
8984 OO.ui.FormLayout.parent.call( this, config );
8985
8986 // Mixin constructors
8987 OO.ui.mixin.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) );
8988
8989 // Events
8990 this.$element.on( 'submit', this.onFormSubmit.bind( this ) );
8991
8992 // Make sure the action is safe
8993 if ( config.action !== undefined && !OO.ui.isSafeUrl( config.action ) ) {
8994 throw new Error( 'Potentially unsafe action provided: ' + config.action );
8995 }
8996
8997 // Initialization
8998 this.$element
8999 .addClass( 'oo-ui-formLayout' )
9000 .attr( {
9001 method: config.method,
9002 action: config.action,
9003 enctype: config.enctype
9004 } );
9005 if ( Array.isArray( config.items ) ) {
9006 this.addItems( config.items );
9007 }
9008 };
9009
9010 /* Setup */
9011
9012 OO.inheritClass( OO.ui.FormLayout, OO.ui.Layout );
9013 OO.mixinClass( OO.ui.FormLayout, OO.ui.mixin.GroupElement );
9014
9015 /* Events */
9016
9017 /**
9018 * A 'submit' event is emitted when the form is submitted.
9019 *
9020 * @event submit
9021 */
9022
9023 /* Static Properties */
9024
9025 OO.ui.FormLayout.static.tagName = 'form';
9026
9027 /* Methods */
9028
9029 /**
9030 * Handle form submit events.
9031 *
9032 * @private
9033 * @param {jQuery.Event} e Submit event
9034 * @fires submit
9035 */
9036 OO.ui.FormLayout.prototype.onFormSubmit = function () {
9037 if ( this.emit( 'submit' ) ) {
9038 return false;
9039 }
9040 };
9041
9042 /**
9043 * 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)
9044 * and its size is customized with the #menuSize config. The content area will fill all remaining space.
9045 *
9046 * @example
9047 * var menuLayout = new OO.ui.MenuLayout( {
9048 * position: 'top'
9049 * } ),
9050 * menuPanel = new OO.ui.PanelLayout( { padded: true, expanded: true, scrollable: true } ),
9051 * contentPanel = new OO.ui.PanelLayout( { padded: true, expanded: true, scrollable: true } ),
9052 * select = new OO.ui.SelectWidget( {
9053 * items: [
9054 * new OO.ui.OptionWidget( {
9055 * data: 'before',
9056 * label: 'Before',
9057 * } ),
9058 * new OO.ui.OptionWidget( {
9059 * data: 'after',
9060 * label: 'After',
9061 * } ),
9062 * new OO.ui.OptionWidget( {
9063 * data: 'top',
9064 * label: 'Top',
9065 * } ),
9066 * new OO.ui.OptionWidget( {
9067 * data: 'bottom',
9068 * label: 'Bottom',
9069 * } )
9070 * ]
9071 * } ).on( 'select', function ( item ) {
9072 * menuLayout.setMenuPosition( item.getData() );
9073 * } );
9074 *
9075 * menuLayout.$menu.append(
9076 * menuPanel.$element.append( '<b>Menu panel</b>', select.$element )
9077 * );
9078 * menuLayout.$content.append(
9079 * contentPanel.$element.append( '<b>Content panel</b>', '<p>Note that the menu is positioned relative to the content panel: top, bottom, after, before.</p>')
9080 * );
9081 * $( 'body' ).append( menuLayout.$element );
9082 *
9083 * If menu size needs to be overridden, it can be accomplished using CSS similar to the snippet
9084 * below. MenuLayout's CSS will override the appropriate values with 'auto' or '0' to display the
9085 * menu correctly. If `menuPosition` is known beforehand, CSS rules corresponding to other positions
9086 * may be omitted.
9087 *
9088 * .oo-ui-menuLayout-menu {
9089 * height: 200px;
9090 * width: 200px;
9091 * }
9092 * .oo-ui-menuLayout-content {
9093 * top: 200px;
9094 * left: 200px;
9095 * right: 200px;
9096 * bottom: 200px;
9097 * }
9098 *
9099 * @class
9100 * @extends OO.ui.Layout
9101 *
9102 * @constructor
9103 * @param {Object} [config] Configuration options
9104 * @cfg {boolean} [showMenu=true] Show menu
9105 * @cfg {string} [menuPosition='before'] Position of menu: `top`, `after`, `bottom` or `before`
9106 */
9107 OO.ui.MenuLayout = function OoUiMenuLayout( config ) {
9108 // Configuration initialization
9109 config = $.extend( {
9110 showMenu: true,
9111 menuPosition: 'before'
9112 }, config );
9113
9114 // Parent constructor
9115 OO.ui.MenuLayout.parent.call( this, config );
9116
9117 /**
9118 * Menu DOM node
9119 *
9120 * @property {jQuery}
9121 */
9122 this.$menu = $( '<div>' );
9123 /**
9124 * Content DOM node
9125 *
9126 * @property {jQuery}
9127 */
9128 this.$content = $( '<div>' );
9129
9130 // Initialization
9131 this.$menu
9132 .addClass( 'oo-ui-menuLayout-menu' );
9133 this.$content.addClass( 'oo-ui-menuLayout-content' );
9134 this.$element
9135 .addClass( 'oo-ui-menuLayout' )
9136 .append( this.$content, this.$menu );
9137 this.setMenuPosition( config.menuPosition );
9138 this.toggleMenu( config.showMenu );
9139 };
9140
9141 /* Setup */
9142
9143 OO.inheritClass( OO.ui.MenuLayout, OO.ui.Layout );
9144
9145 /* Methods */
9146
9147 /**
9148 * Toggle menu.
9149 *
9150 * @param {boolean} showMenu Show menu, omit to toggle
9151 * @chainable
9152 */
9153 OO.ui.MenuLayout.prototype.toggleMenu = function ( showMenu ) {
9154 showMenu = showMenu === undefined ? !this.showMenu : !!showMenu;
9155
9156 if ( this.showMenu !== showMenu ) {
9157 this.showMenu = showMenu;
9158 this.$element
9159 .toggleClass( 'oo-ui-menuLayout-showMenu', this.showMenu )
9160 .toggleClass( 'oo-ui-menuLayout-hideMenu', !this.showMenu );
9161 }
9162
9163 return this;
9164 };
9165
9166 /**
9167 * Check if menu is visible
9168 *
9169 * @return {boolean} Menu is visible
9170 */
9171 OO.ui.MenuLayout.prototype.isMenuVisible = function () {
9172 return this.showMenu;
9173 };
9174
9175 /**
9176 * Set menu position.
9177 *
9178 * @param {string} position Position of menu, either `top`, `after`, `bottom` or `before`
9179 * @throws {Error} If position value is not supported
9180 * @chainable
9181 */
9182 OO.ui.MenuLayout.prototype.setMenuPosition = function ( position ) {
9183 this.$element.removeClass( 'oo-ui-menuLayout-' + this.menuPosition );
9184 this.menuPosition = position;
9185 this.$element.addClass( 'oo-ui-menuLayout-' + position );
9186
9187 return this;
9188 };
9189
9190 /**
9191 * Get menu position.
9192 *
9193 * @return {string} Menu position
9194 */
9195 OO.ui.MenuLayout.prototype.getMenuPosition = function () {
9196 return this.menuPosition;
9197 };
9198
9199 /**
9200 * BookletLayouts contain {@link OO.ui.PageLayout page layouts} as well as
9201 * an {@link OO.ui.OutlineSelectWidget outline} that allows users to easily navigate
9202 * through the pages and select which one to display. By default, only one page is
9203 * displayed at a time and the outline is hidden. When a user navigates to a new page,
9204 * the booklet layout automatically focuses on the first focusable element, unless the
9205 * default setting is changed. Optionally, booklets can be configured to show
9206 * {@link OO.ui.OutlineControlsWidget controls} for adding, moving, and removing items.
9207 *
9208 * @example
9209 * // Example of a BookletLayout that contains two PageLayouts.
9210 *
9211 * function PageOneLayout( name, config ) {
9212 * PageOneLayout.parent.call( this, name, config );
9213 * this.$element.append( '<p>First page</p><p>(This booklet has an outline, displayed on the left)</p>' );
9214 * }
9215 * OO.inheritClass( PageOneLayout, OO.ui.PageLayout );
9216 * PageOneLayout.prototype.setupOutlineItem = function () {
9217 * this.outlineItem.setLabel( 'Page One' );
9218 * };
9219 *
9220 * function PageTwoLayout( name, config ) {
9221 * PageTwoLayout.parent.call( this, name, config );
9222 * this.$element.append( '<p>Second page</p>' );
9223 * }
9224 * OO.inheritClass( PageTwoLayout, OO.ui.PageLayout );
9225 * PageTwoLayout.prototype.setupOutlineItem = function () {
9226 * this.outlineItem.setLabel( 'Page Two' );
9227 * };
9228 *
9229 * var page1 = new PageOneLayout( 'one' ),
9230 * page2 = new PageTwoLayout( 'two' );
9231 *
9232 * var booklet = new OO.ui.BookletLayout( {
9233 * outlined: true
9234 * } );
9235 *
9236 * booklet.addPages ( [ page1, page2 ] );
9237 * $( 'body' ).append( booklet.$element );
9238 *
9239 * @class
9240 * @extends OO.ui.MenuLayout
9241 *
9242 * @constructor
9243 * @param {Object} [config] Configuration options
9244 * @cfg {boolean} [continuous=false] Show all pages, one after another
9245 * @cfg {boolean} [autoFocus=true] Focus on the first focusable element when a new page is displayed.
9246 * @cfg {boolean} [outlined=false] Show the outline. The outline is used to navigate through the pages of the booklet.
9247 * @cfg {boolean} [editable=false] Show controls for adding, removing and reordering pages
9248 */
9249 OO.ui.BookletLayout = function OoUiBookletLayout( config ) {
9250 // Configuration initialization
9251 config = config || {};
9252
9253 // Parent constructor
9254 OO.ui.BookletLayout.parent.call( this, config );
9255
9256 // Properties
9257 this.currentPageName = null;
9258 this.pages = {};
9259 this.ignoreFocus = false;
9260 this.stackLayout = new OO.ui.StackLayout( { continuous: !!config.continuous } );
9261 this.$content.append( this.stackLayout.$element );
9262 this.autoFocus = config.autoFocus === undefined || !!config.autoFocus;
9263 this.outlineVisible = false;
9264 this.outlined = !!config.outlined;
9265 if ( this.outlined ) {
9266 this.editable = !!config.editable;
9267 this.outlineControlsWidget = null;
9268 this.outlineSelectWidget = new OO.ui.OutlineSelectWidget();
9269 this.outlinePanel = new OO.ui.PanelLayout( { scrollable: true } );
9270 this.$menu.append( this.outlinePanel.$element );
9271 this.outlineVisible = true;
9272 if ( this.editable ) {
9273 this.outlineControlsWidget = new OO.ui.OutlineControlsWidget(
9274 this.outlineSelectWidget
9275 );
9276 }
9277 }
9278 this.toggleMenu( this.outlined );
9279
9280 // Events
9281 this.stackLayout.connect( this, { set: 'onStackLayoutSet' } );
9282 if ( this.outlined ) {
9283 this.outlineSelectWidget.connect( this, { select: 'onOutlineSelectWidgetSelect' } );
9284 }
9285 if ( this.autoFocus ) {
9286 // Event 'focus' does not bubble, but 'focusin' does
9287 this.stackLayout.$element.on( 'focusin', this.onStackLayoutFocus.bind( this ) );
9288 }
9289
9290 // Initialization
9291 this.$element.addClass( 'oo-ui-bookletLayout' );
9292 this.stackLayout.$element.addClass( 'oo-ui-bookletLayout-stackLayout' );
9293 if ( this.outlined ) {
9294 this.outlinePanel.$element
9295 .addClass( 'oo-ui-bookletLayout-outlinePanel' )
9296 .append( this.outlineSelectWidget.$element );
9297 if ( this.editable ) {
9298 this.outlinePanel.$element
9299 .addClass( 'oo-ui-bookletLayout-outlinePanel-editable' )
9300 .append( this.outlineControlsWidget.$element );
9301 }
9302 }
9303 };
9304
9305 /* Setup */
9306
9307 OO.inheritClass( OO.ui.BookletLayout, OO.ui.MenuLayout );
9308
9309 /* Events */
9310
9311 /**
9312 * A 'set' event is emitted when a page is {@link #setPage set} to be displayed by the booklet layout.
9313 * @event set
9314 * @param {OO.ui.PageLayout} page Current page
9315 */
9316
9317 /**
9318 * An 'add' event is emitted when pages are {@link #addPages added} to the booklet layout.
9319 *
9320 * @event add
9321 * @param {OO.ui.PageLayout[]} page Added pages
9322 * @param {number} index Index pages were added at
9323 */
9324
9325 /**
9326 * A 'remove' event is emitted when pages are {@link #clearPages cleared} or
9327 * {@link #removePages removed} from the booklet.
9328 *
9329 * @event remove
9330 * @param {OO.ui.PageLayout[]} pages Removed pages
9331 */
9332
9333 /* Methods */
9334
9335 /**
9336 * Handle stack layout focus.
9337 *
9338 * @private
9339 * @param {jQuery.Event} e Focusin event
9340 */
9341 OO.ui.BookletLayout.prototype.onStackLayoutFocus = function ( e ) {
9342 var name, $target;
9343
9344 // Find the page that an element was focused within
9345 $target = $( e.target ).closest( '.oo-ui-pageLayout' );
9346 for ( name in this.pages ) {
9347 // Check for page match, exclude current page to find only page changes
9348 if ( this.pages[ name ].$element[ 0 ] === $target[ 0 ] && name !== this.currentPageName ) {
9349 this.setPage( name );
9350 break;
9351 }
9352 }
9353 };
9354
9355 /**
9356 * Handle stack layout set events.
9357 *
9358 * @private
9359 * @param {OO.ui.PanelLayout|null} page The page panel that is now the current panel
9360 */
9361 OO.ui.BookletLayout.prototype.onStackLayoutSet = function ( page ) {
9362 var layout = this;
9363 if ( page ) {
9364 page.scrollElementIntoView( { complete: function () {
9365 if ( layout.autoFocus ) {
9366 layout.focus();
9367 }
9368 } } );
9369 }
9370 };
9371
9372 /**
9373 * Focus the first input in the current page.
9374 *
9375 * If no page is selected, the first selectable page will be selected.
9376 * If the focus is already in an element on the current page, nothing will happen.
9377 * @param {number} [itemIndex] A specific item to focus on
9378 */
9379 OO.ui.BookletLayout.prototype.focus = function ( itemIndex ) {
9380 var $input, page,
9381 items = this.stackLayout.getItems();
9382
9383 if ( itemIndex !== undefined && items[ itemIndex ] ) {
9384 page = items[ itemIndex ];
9385 } else {
9386 page = this.stackLayout.getCurrentItem();
9387 }
9388
9389 if ( !page && this.outlined ) {
9390 this.selectFirstSelectablePage();
9391 page = this.stackLayout.getCurrentItem();
9392 }
9393 if ( !page ) {
9394 return;
9395 }
9396 // Only change the focus if is not already in the current page
9397 if ( !page.$element.find( ':focus' ).length ) {
9398 $input = page.$element.find( ':input:first' );
9399 if ( $input.length ) {
9400 $input[ 0 ].focus();
9401 }
9402 }
9403 };
9404
9405 /**
9406 * Find the first focusable input in the booklet layout and focus
9407 * on it.
9408 */
9409 OO.ui.BookletLayout.prototype.focusFirstFocusable = function () {
9410 var i, len,
9411 found = false,
9412 items = this.stackLayout.getItems(),
9413 checkAndFocus = function () {
9414 if ( OO.ui.isFocusableElement( $( this ) ) ) {
9415 $( this ).focus();
9416 found = true;
9417 return false;
9418 }
9419 };
9420
9421 for ( i = 0, len = items.length; i < len; i++ ) {
9422 if ( found ) {
9423 break;
9424 }
9425 // Find all potentially focusable elements in the item
9426 // and check if they are focusable
9427 items[i].$element
9428 .find( 'input, select, textarea, button, object' )
9429 /* jshint loopfunc:true */
9430 .each( checkAndFocus );
9431 }
9432 };
9433
9434 /**
9435 * Handle outline widget select events.
9436 *
9437 * @private
9438 * @param {OO.ui.OptionWidget|null} item Selected item
9439 */
9440 OO.ui.BookletLayout.prototype.onOutlineSelectWidgetSelect = function ( item ) {
9441 if ( item ) {
9442 this.setPage( item.getData() );
9443 }
9444 };
9445
9446 /**
9447 * Check if booklet has an outline.
9448 *
9449 * @return {boolean} Booklet has an outline
9450 */
9451 OO.ui.BookletLayout.prototype.isOutlined = function () {
9452 return this.outlined;
9453 };
9454
9455 /**
9456 * Check if booklet has editing controls.
9457 *
9458 * @return {boolean} Booklet is editable
9459 */
9460 OO.ui.BookletLayout.prototype.isEditable = function () {
9461 return this.editable;
9462 };
9463
9464 /**
9465 * Check if booklet has a visible outline.
9466 *
9467 * @return {boolean} Outline is visible
9468 */
9469 OO.ui.BookletLayout.prototype.isOutlineVisible = function () {
9470 return this.outlined && this.outlineVisible;
9471 };
9472
9473 /**
9474 * Hide or show the outline.
9475 *
9476 * @param {boolean} [show] Show outline, omit to invert current state
9477 * @chainable
9478 */
9479 OO.ui.BookletLayout.prototype.toggleOutline = function ( show ) {
9480 if ( this.outlined ) {
9481 show = show === undefined ? !this.outlineVisible : !!show;
9482 this.outlineVisible = show;
9483 this.toggleMenu( show );
9484 }
9485
9486 return this;
9487 };
9488
9489 /**
9490 * Get the page closest to the specified page.
9491 *
9492 * @param {OO.ui.PageLayout} page Page to use as a reference point
9493 * @return {OO.ui.PageLayout|null} Page closest to the specified page
9494 */
9495 OO.ui.BookletLayout.prototype.getClosestPage = function ( page ) {
9496 var next, prev, level,
9497 pages = this.stackLayout.getItems(),
9498 index = $.inArray( page, pages );
9499
9500 if ( index !== -1 ) {
9501 next = pages[ index + 1 ];
9502 prev = pages[ index - 1 ];
9503 // Prefer adjacent pages at the same level
9504 if ( this.outlined ) {
9505 level = this.outlineSelectWidget.getItemFromData( page.getName() ).getLevel();
9506 if (
9507 prev &&
9508 level === this.outlineSelectWidget.getItemFromData( prev.getName() ).getLevel()
9509 ) {
9510 return prev;
9511 }
9512 if (
9513 next &&
9514 level === this.outlineSelectWidget.getItemFromData( next.getName() ).getLevel()
9515 ) {
9516 return next;
9517 }
9518 }
9519 }
9520 return prev || next || null;
9521 };
9522
9523 /**
9524 * Get the outline widget.
9525 *
9526 * If the booklet is not outlined, the method will return `null`.
9527 *
9528 * @return {OO.ui.OutlineSelectWidget|null} Outline widget, or null if the booklet is not outlined
9529 */
9530 OO.ui.BookletLayout.prototype.getOutline = function () {
9531 return this.outlineSelectWidget;
9532 };
9533
9534 /**
9535 * Get the outline controls widget.
9536 *
9537 * If the outline is not editable, the method will return `null`.
9538 *
9539 * @return {OO.ui.OutlineControlsWidget|null} The outline controls widget.
9540 */
9541 OO.ui.BookletLayout.prototype.getOutlineControls = function () {
9542 return this.outlineControlsWidget;
9543 };
9544
9545 /**
9546 * Get a page by its symbolic name.
9547 *
9548 * @param {string} name Symbolic name of page
9549 * @return {OO.ui.PageLayout|undefined} Page, if found
9550 */
9551 OO.ui.BookletLayout.prototype.getPage = function ( name ) {
9552 return this.pages[ name ];
9553 };
9554
9555 /**
9556 * Get the current page.
9557 *
9558 * @return {OO.ui.PageLayout|undefined} Current page, if found
9559 */
9560 OO.ui.BookletLayout.prototype.getCurrentPage = function () {
9561 var name = this.getCurrentPageName();
9562 return name ? this.getPage( name ) : undefined;
9563 };
9564
9565 /**
9566 * Get the symbolic name of the current page.
9567 *
9568 * @return {string|null} Symbolic name of the current page
9569 */
9570 OO.ui.BookletLayout.prototype.getCurrentPageName = function () {
9571 return this.currentPageName;
9572 };
9573
9574 /**
9575 * Add pages to the booklet layout
9576 *
9577 * When pages are added with the same names as existing pages, the existing pages will be
9578 * automatically removed before the new pages are added.
9579 *
9580 * @param {OO.ui.PageLayout[]} pages Pages to add
9581 * @param {number} index Index of the insertion point
9582 * @fires add
9583 * @chainable
9584 */
9585 OO.ui.BookletLayout.prototype.addPages = function ( pages, index ) {
9586 var i, len, name, page, item, currentIndex,
9587 stackLayoutPages = this.stackLayout.getItems(),
9588 remove = [],
9589 items = [];
9590
9591 // Remove pages with same names
9592 for ( i = 0, len = pages.length; i < len; i++ ) {
9593 page = pages[ i ];
9594 name = page.getName();
9595
9596 if ( Object.prototype.hasOwnProperty.call( this.pages, name ) ) {
9597 // Correct the insertion index
9598 currentIndex = $.inArray( this.pages[ name ], stackLayoutPages );
9599 if ( currentIndex !== -1 && currentIndex + 1 < index ) {
9600 index--;
9601 }
9602 remove.push( this.pages[ name ] );
9603 }
9604 }
9605 if ( remove.length ) {
9606 this.removePages( remove );
9607 }
9608
9609 // Add new pages
9610 for ( i = 0, len = pages.length; i < len; i++ ) {
9611 page = pages[ i ];
9612 name = page.getName();
9613 this.pages[ page.getName() ] = page;
9614 if ( this.outlined ) {
9615 item = new OO.ui.OutlineOptionWidget( { data: name } );
9616 page.setOutlineItem( item );
9617 items.push( item );
9618 }
9619 }
9620
9621 if ( this.outlined && items.length ) {
9622 this.outlineSelectWidget.addItems( items, index );
9623 this.selectFirstSelectablePage();
9624 }
9625 this.stackLayout.addItems( pages, index );
9626 this.emit( 'add', pages, index );
9627
9628 return this;
9629 };
9630
9631 /**
9632 * Remove the specified pages from the booklet layout.
9633 *
9634 * To remove all pages from the booklet, you may wish to use the #clearPages method instead.
9635 *
9636 * @param {OO.ui.PageLayout[]} pages An array of pages to remove
9637 * @fires remove
9638 * @chainable
9639 */
9640 OO.ui.BookletLayout.prototype.removePages = function ( pages ) {
9641 var i, len, name, page,
9642 items = [];
9643
9644 for ( i = 0, len = pages.length; i < len; i++ ) {
9645 page = pages[ i ];
9646 name = page.getName();
9647 delete this.pages[ name ];
9648 if ( this.outlined ) {
9649 items.push( this.outlineSelectWidget.getItemFromData( name ) );
9650 page.setOutlineItem( null );
9651 }
9652 }
9653 if ( this.outlined && items.length ) {
9654 this.outlineSelectWidget.removeItems( items );
9655 this.selectFirstSelectablePage();
9656 }
9657 this.stackLayout.removeItems( pages );
9658 this.emit( 'remove', pages );
9659
9660 return this;
9661 };
9662
9663 /**
9664 * Clear all pages from the booklet layout.
9665 *
9666 * To remove only a subset of pages from the booklet, use the #removePages method.
9667 *
9668 * @fires remove
9669 * @chainable
9670 */
9671 OO.ui.BookletLayout.prototype.clearPages = function () {
9672 var i, len,
9673 pages = this.stackLayout.getItems();
9674
9675 this.pages = {};
9676 this.currentPageName = null;
9677 if ( this.outlined ) {
9678 this.outlineSelectWidget.clearItems();
9679 for ( i = 0, len = pages.length; i < len; i++ ) {
9680 pages[ i ].setOutlineItem( null );
9681 }
9682 }
9683 this.stackLayout.clearItems();
9684
9685 this.emit( 'remove', pages );
9686
9687 return this;
9688 };
9689
9690 /**
9691 * Set the current page by symbolic name.
9692 *
9693 * @fires set
9694 * @param {string} name Symbolic name of page
9695 */
9696 OO.ui.BookletLayout.prototype.setPage = function ( name ) {
9697 var selectedItem,
9698 $focused,
9699 page = this.pages[ name ];
9700
9701 if ( name !== this.currentPageName ) {
9702 if ( this.outlined ) {
9703 selectedItem = this.outlineSelectWidget.getSelectedItem();
9704 if ( selectedItem && selectedItem.getData() !== name ) {
9705 this.outlineSelectWidget.selectItemByData( name );
9706 }
9707 }
9708 if ( page ) {
9709 if ( this.currentPageName && this.pages[ this.currentPageName ] ) {
9710 this.pages[ this.currentPageName ].setActive( false );
9711 // Blur anything focused if the next page doesn't have anything focusable - this
9712 // is not needed if the next page has something focusable because once it is focused
9713 // this blur happens automatically
9714 if ( this.autoFocus && !page.$element.find( ':input' ).length ) {
9715 $focused = this.pages[ this.currentPageName ].$element.find( ':focus' );
9716 if ( $focused.length ) {
9717 $focused[ 0 ].blur();
9718 }
9719 }
9720 }
9721 this.currentPageName = name;
9722 this.stackLayout.setItem( page );
9723 page.setActive( true );
9724 this.emit( 'set', page );
9725 }
9726 }
9727 };
9728
9729 /**
9730 * Select the first selectable page.
9731 *
9732 * @chainable
9733 */
9734 OO.ui.BookletLayout.prototype.selectFirstSelectablePage = function () {
9735 if ( !this.outlineSelectWidget.getSelectedItem() ) {
9736 this.outlineSelectWidget.selectItem( this.outlineSelectWidget.getFirstSelectableItem() );
9737 }
9738
9739 return this;
9740 };
9741
9742 /**
9743 * IndexLayouts contain {@link OO.ui.CardLayout card layouts} as well as
9744 * {@link OO.ui.TabSelectWidget tabs} that allow users to easily navigate through the cards and
9745 * select which one to display. By default, only one card is displayed at a time. When a user
9746 * navigates to a new card, the index layout automatically focuses on the first focusable element,
9747 * unless the default setting is changed.
9748 *
9749 * TODO: This class is similar to BookletLayout, we may want to refactor to reduce duplication
9750 *
9751 * @example
9752 * // Example of a IndexLayout that contains two CardLayouts.
9753 *
9754 * function CardOneLayout( name, config ) {
9755 * CardOneLayout.parent.call( this, name, config );
9756 * this.$element.append( '<p>First card</p>' );
9757 * }
9758 * OO.inheritClass( CardOneLayout, OO.ui.CardLayout );
9759 * CardOneLayout.prototype.setupTabItem = function () {
9760 * this.tabItem.setLabel( 'Card One' );
9761 * };
9762 *
9763 * function CardTwoLayout( name, config ) {
9764 * CardTwoLayout.parent.call( this, name, config );
9765 * this.$element.append( '<p>Second card</p>' );
9766 * }
9767 * OO.inheritClass( CardTwoLayout, OO.ui.CardLayout );
9768 * CardTwoLayout.prototype.setupTabItem = function () {
9769 * this.tabItem.setLabel( 'Card Two' );
9770 * };
9771 *
9772 * var card1 = new CardOneLayout( 'one' ),
9773 * card2 = new CardTwoLayout( 'two' );
9774 *
9775 * var index = new OO.ui.IndexLayout();
9776 *
9777 * index.addCards ( [ card1, card2 ] );
9778 * $( 'body' ).append( index.$element );
9779 *
9780 * @class
9781 * @extends OO.ui.MenuLayout
9782 *
9783 * @constructor
9784 * @param {Object} [config] Configuration options
9785 * @cfg {boolean} [continuous=false] Show all cards, one after another
9786 * @cfg {boolean} [autoFocus=true] Focus on the first focusable element when a new card is displayed.
9787 */
9788 OO.ui.IndexLayout = function OoUiIndexLayout( config ) {
9789 // Configuration initialization
9790 config = $.extend( {}, config, { menuPosition: 'top' } );
9791
9792 // Parent constructor
9793 OO.ui.IndexLayout.parent.call( this, config );
9794
9795 // Properties
9796 this.currentCardName = null;
9797 this.cards = {};
9798 this.ignoreFocus = false;
9799 this.stackLayout = new OO.ui.StackLayout( { continuous: !!config.continuous } );
9800 this.$content.append( this.stackLayout.$element );
9801 this.autoFocus = config.autoFocus === undefined || !!config.autoFocus;
9802
9803 this.tabSelectWidget = new OO.ui.TabSelectWidget();
9804 this.tabPanel = new OO.ui.PanelLayout();
9805 this.$menu.append( this.tabPanel.$element );
9806
9807 this.toggleMenu( true );
9808
9809 // Events
9810 this.stackLayout.connect( this, { set: 'onStackLayoutSet' } );
9811 this.tabSelectWidget.connect( this, { select: 'onTabSelectWidgetSelect' } );
9812 if ( this.autoFocus ) {
9813 // Event 'focus' does not bubble, but 'focusin' does
9814 this.stackLayout.$element.on( 'focusin', this.onStackLayoutFocus.bind( this ) );
9815 }
9816
9817 // Initialization
9818 this.$element.addClass( 'oo-ui-indexLayout' );
9819 this.stackLayout.$element.addClass( 'oo-ui-indexLayout-stackLayout' );
9820 this.tabPanel.$element
9821 .addClass( 'oo-ui-indexLayout-tabPanel' )
9822 .append( this.tabSelectWidget.$element );
9823 };
9824
9825 /* Setup */
9826
9827 OO.inheritClass( OO.ui.IndexLayout, OO.ui.MenuLayout );
9828
9829 /* Events */
9830
9831 /**
9832 * A 'set' event is emitted when a card is {@link #setCard set} to be displayed by the index layout.
9833 * @event set
9834 * @param {OO.ui.CardLayout} card Current card
9835 */
9836
9837 /**
9838 * An 'add' event is emitted when cards are {@link #addCards added} to the index layout.
9839 *
9840 * @event add
9841 * @param {OO.ui.CardLayout[]} card Added cards
9842 * @param {number} index Index cards were added at
9843 */
9844
9845 /**
9846 * A 'remove' event is emitted when cards are {@link #clearCards cleared} or
9847 * {@link #removeCards removed} from the index.
9848 *
9849 * @event remove
9850 * @param {OO.ui.CardLayout[]} cards Removed cards
9851 */
9852
9853 /* Methods */
9854
9855 /**
9856 * Handle stack layout focus.
9857 *
9858 * @private
9859 * @param {jQuery.Event} e Focusin event
9860 */
9861 OO.ui.IndexLayout.prototype.onStackLayoutFocus = function ( e ) {
9862 var name, $target;
9863
9864 // Find the card that an element was focused within
9865 $target = $( e.target ).closest( '.oo-ui-cardLayout' );
9866 for ( name in this.cards ) {
9867 // Check for card match, exclude current card to find only card changes
9868 if ( this.cards[ name ].$element[ 0 ] === $target[ 0 ] && name !== this.currentCardName ) {
9869 this.setCard( name );
9870 break;
9871 }
9872 }
9873 };
9874
9875 /**
9876 * Handle stack layout set events.
9877 *
9878 * @private
9879 * @param {OO.ui.PanelLayout|null} card The card panel that is now the current panel
9880 */
9881 OO.ui.IndexLayout.prototype.onStackLayoutSet = function ( card ) {
9882 var layout = this;
9883 if ( card ) {
9884 card.scrollElementIntoView( { complete: function () {
9885 if ( layout.autoFocus ) {
9886 layout.focus();
9887 }
9888 } } );
9889 }
9890 };
9891
9892 /**
9893 * Focus the first input in the current card.
9894 *
9895 * If no card is selected, the first selectable card will be selected.
9896 * If the focus is already in an element on the current card, nothing will happen.
9897 * @param {number} [itemIndex] A specific item to focus on
9898 */
9899 OO.ui.IndexLayout.prototype.focus = function ( itemIndex ) {
9900 var $input, card,
9901 items = this.stackLayout.getItems();
9902
9903 if ( itemIndex !== undefined && items[ itemIndex ] ) {
9904 card = items[ itemIndex ];
9905 } else {
9906 card = this.stackLayout.getCurrentItem();
9907 }
9908
9909 if ( !card ) {
9910 this.selectFirstSelectableCard();
9911 card = this.stackLayout.getCurrentItem();
9912 }
9913 if ( !card ) {
9914 return;
9915 }
9916 // Only change the focus if is not already in the current card
9917 if ( !card.$element.find( ':focus' ).length ) {
9918 $input = card.$element.find( ':input:first' );
9919 if ( $input.length ) {
9920 $input[ 0 ].focus();
9921 }
9922 }
9923 };
9924
9925 /**
9926 * Find the first focusable input in the index layout and focus
9927 * on it.
9928 */
9929 OO.ui.IndexLayout.prototype.focusFirstFocusable = function () {
9930 var i, len,
9931 found = false,
9932 items = this.stackLayout.getItems(),
9933 checkAndFocus = function () {
9934 if ( OO.ui.isFocusableElement( $( this ) ) ) {
9935 $( this ).focus();
9936 found = true;
9937 return false;
9938 }
9939 };
9940
9941 for ( i = 0, len = items.length; i < len; i++ ) {
9942 if ( found ) {
9943 break;
9944 }
9945 // Find all potentially focusable elements in the item
9946 // and check if they are focusable
9947 items[i].$element
9948 .find( 'input, select, textarea, button, object' )
9949 .each( checkAndFocus );
9950 }
9951 };
9952
9953 /**
9954 * Handle tab widget select events.
9955 *
9956 * @private
9957 * @param {OO.ui.OptionWidget|null} item Selected item
9958 */
9959 OO.ui.IndexLayout.prototype.onTabSelectWidgetSelect = function ( item ) {
9960 if ( item ) {
9961 this.setCard( item.getData() );
9962 }
9963 };
9964
9965 /**
9966 * Get the card closest to the specified card.
9967 *
9968 * @param {OO.ui.CardLayout} card Card to use as a reference point
9969 * @return {OO.ui.CardLayout|null} Card closest to the specified card
9970 */
9971 OO.ui.IndexLayout.prototype.getClosestCard = function ( card ) {
9972 var next, prev, level,
9973 cards = this.stackLayout.getItems(),
9974 index = $.inArray( card, cards );
9975
9976 if ( index !== -1 ) {
9977 next = cards[ index + 1 ];
9978 prev = cards[ index - 1 ];
9979 // Prefer adjacent cards at the same level
9980 level = this.tabSelectWidget.getItemFromData( card.getName() ).getLevel();
9981 if (
9982 prev &&
9983 level === this.tabSelectWidget.getItemFromData( prev.getName() ).getLevel()
9984 ) {
9985 return prev;
9986 }
9987 if (
9988 next &&
9989 level === this.tabSelectWidget.getItemFromData( next.getName() ).getLevel()
9990 ) {
9991 return next;
9992 }
9993 }
9994 return prev || next || null;
9995 };
9996
9997 /**
9998 * Get the tabs widget.
9999 *
10000 * @return {OO.ui.TabSelectWidget} Tabs widget
10001 */
10002 OO.ui.IndexLayout.prototype.getTabs = function () {
10003 return this.tabSelectWidget;
10004 };
10005
10006 /**
10007 * Get a card by its symbolic name.
10008 *
10009 * @param {string} name Symbolic name of card
10010 * @return {OO.ui.CardLayout|undefined} Card, if found
10011 */
10012 OO.ui.IndexLayout.prototype.getCard = function ( name ) {
10013 return this.cards[ name ];
10014 };
10015
10016 /**
10017 * Get the current card.
10018 *
10019 * @return {OO.ui.CardLayout|undefined} Current card, if found
10020 */
10021 OO.ui.IndexLayout.prototype.getCurrentCard = function () {
10022 var name = this.getCurrentCardName();
10023 return name ? this.getCard( name ) : undefined;
10024 };
10025
10026 /**
10027 * Get the symbolic name of the current card.
10028 *
10029 * @return {string|null} Symbolic name of the current card
10030 */
10031 OO.ui.IndexLayout.prototype.getCurrentCardName = function () {
10032 return this.currentCardName;
10033 };
10034
10035 /**
10036 * Add cards to the index layout
10037 *
10038 * When cards are added with the same names as existing cards, the existing cards will be
10039 * automatically removed before the new cards are added.
10040 *
10041 * @param {OO.ui.CardLayout[]} cards Cards to add
10042 * @param {number} index Index of the insertion point
10043 * @fires add
10044 * @chainable
10045 */
10046 OO.ui.IndexLayout.prototype.addCards = function ( cards, index ) {
10047 var i, len, name, card, item, currentIndex,
10048 stackLayoutCards = this.stackLayout.getItems(),
10049 remove = [],
10050 items = [];
10051
10052 // Remove cards with same names
10053 for ( i = 0, len = cards.length; i < len; i++ ) {
10054 card = cards[ i ];
10055 name = card.getName();
10056
10057 if ( Object.prototype.hasOwnProperty.call( this.cards, name ) ) {
10058 // Correct the insertion index
10059 currentIndex = $.inArray( this.cards[ name ], stackLayoutCards );
10060 if ( currentIndex !== -1 && currentIndex + 1 < index ) {
10061 index--;
10062 }
10063 remove.push( this.cards[ name ] );
10064 }
10065 }
10066 if ( remove.length ) {
10067 this.removeCards( remove );
10068 }
10069
10070 // Add new cards
10071 for ( i = 0, len = cards.length; i < len; i++ ) {
10072 card = cards[ i ];
10073 name = card.getName();
10074 this.cards[ card.getName() ] = card;
10075 item = new OO.ui.TabOptionWidget( { data: name } );
10076 card.setTabItem( item );
10077 items.push( item );
10078 }
10079
10080 if ( items.length ) {
10081 this.tabSelectWidget.addItems( items, index );
10082 this.selectFirstSelectableCard();
10083 }
10084 this.stackLayout.addItems( cards, index );
10085 this.emit( 'add', cards, index );
10086
10087 return this;
10088 };
10089
10090 /**
10091 * Remove the specified cards from the index layout.
10092 *
10093 * To remove all cards from the index, you may wish to use the #clearCards method instead.
10094 *
10095 * @param {OO.ui.CardLayout[]} cards An array of cards to remove
10096 * @fires remove
10097 * @chainable
10098 */
10099 OO.ui.IndexLayout.prototype.removeCards = function ( cards ) {
10100 var i, len, name, card,
10101 items = [];
10102
10103 for ( i = 0, len = cards.length; i < len; i++ ) {
10104 card = cards[ i ];
10105 name = card.getName();
10106 delete this.cards[ name ];
10107 items.push( this.tabSelectWidget.getItemFromData( name ) );
10108 card.setTabItem( null );
10109 }
10110 if ( items.length ) {
10111 this.tabSelectWidget.removeItems( items );
10112 this.selectFirstSelectableCard();
10113 }
10114 this.stackLayout.removeItems( cards );
10115 this.emit( 'remove', cards );
10116
10117 return this;
10118 };
10119
10120 /**
10121 * Clear all cards from the index layout.
10122 *
10123 * To remove only a subset of cards from the index, use the #removeCards method.
10124 *
10125 * @fires remove
10126 * @chainable
10127 */
10128 OO.ui.IndexLayout.prototype.clearCards = function () {
10129 var i, len,
10130 cards = this.stackLayout.getItems();
10131
10132 this.cards = {};
10133 this.currentCardName = null;
10134 this.tabSelectWidget.clearItems();
10135 for ( i = 0, len = cards.length; i < len; i++ ) {
10136 cards[ i ].setTabItem( null );
10137 }
10138 this.stackLayout.clearItems();
10139
10140 this.emit( 'remove', cards );
10141
10142 return this;
10143 };
10144
10145 /**
10146 * Set the current card by symbolic name.
10147 *
10148 * @fires set
10149 * @param {string} name Symbolic name of card
10150 */
10151 OO.ui.IndexLayout.prototype.setCard = function ( name ) {
10152 var selectedItem,
10153 $focused,
10154 card = this.cards[ name ];
10155
10156 if ( name !== this.currentCardName ) {
10157 selectedItem = this.tabSelectWidget.getSelectedItem();
10158 if ( selectedItem && selectedItem.getData() !== name ) {
10159 this.tabSelectWidget.selectItemByData( name );
10160 }
10161 if ( card ) {
10162 if ( this.currentCardName && this.cards[ this.currentCardName ] ) {
10163 this.cards[ this.currentCardName ].setActive( false );
10164 // Blur anything focused if the next card doesn't have anything focusable - this
10165 // is not needed if the next card has something focusable because once it is focused
10166 // this blur happens automatically
10167 if ( this.autoFocus && !card.$element.find( ':input' ).length ) {
10168 $focused = this.cards[ this.currentCardName ].$element.find( ':focus' );
10169 if ( $focused.length ) {
10170 $focused[ 0 ].blur();
10171 }
10172 }
10173 }
10174 this.currentCardName = name;
10175 this.stackLayout.setItem( card );
10176 card.setActive( true );
10177 this.emit( 'set', card );
10178 }
10179 }
10180 };
10181
10182 /**
10183 * Select the first selectable card.
10184 *
10185 * @chainable
10186 */
10187 OO.ui.IndexLayout.prototype.selectFirstSelectableCard = function () {
10188 if ( !this.tabSelectWidget.getSelectedItem() ) {
10189 this.tabSelectWidget.selectItem( this.tabSelectWidget.getFirstSelectableItem() );
10190 }
10191
10192 return this;
10193 };
10194
10195 /**
10196 * PanelLayouts expand to cover the entire area of their parent. They can be configured with scrolling, padding,
10197 * and a frame, and are often used together with {@link OO.ui.StackLayout StackLayouts}.
10198 *
10199 * @example
10200 * // Example of a panel layout
10201 * var panel = new OO.ui.PanelLayout( {
10202 * expanded: false,
10203 * framed: true,
10204 * padded: true,
10205 * $content: $( '<p>A panel layout with padding and a frame.</p>' )
10206 * } );
10207 * $( 'body' ).append( panel.$element );
10208 *
10209 * @class
10210 * @extends OO.ui.Layout
10211 *
10212 * @constructor
10213 * @param {Object} [config] Configuration options
10214 * @cfg {boolean} [scrollable=false] Allow vertical scrolling
10215 * @cfg {boolean} [padded=false] Add padding between the content and the edges of the panel.
10216 * @cfg {boolean} [expanded=true] Expand the panel to fill the entire parent element.
10217 * @cfg {boolean} [framed=false] Render the panel with a frame to visually separate it from outside content.
10218 */
10219 OO.ui.PanelLayout = function OoUiPanelLayout( config ) {
10220 // Configuration initialization
10221 config = $.extend( {
10222 scrollable: false,
10223 padded: false,
10224 expanded: true,
10225 framed: false
10226 }, config );
10227
10228 // Parent constructor
10229 OO.ui.PanelLayout.parent.call( this, config );
10230
10231 // Initialization
10232 this.$element.addClass( 'oo-ui-panelLayout' );
10233 if ( config.scrollable ) {
10234 this.$element.addClass( 'oo-ui-panelLayout-scrollable' );
10235 }
10236 if ( config.padded ) {
10237 this.$element.addClass( 'oo-ui-panelLayout-padded' );
10238 }
10239 if ( config.expanded ) {
10240 this.$element.addClass( 'oo-ui-panelLayout-expanded' );
10241 }
10242 if ( config.framed ) {
10243 this.$element.addClass( 'oo-ui-panelLayout-framed' );
10244 }
10245 };
10246
10247 /* Setup */
10248
10249 OO.inheritClass( OO.ui.PanelLayout, OO.ui.Layout );
10250
10251 /**
10252 * CardLayouts are used within {@link OO.ui.IndexLayout index layouts} to create cards that users can select and display
10253 * from the index's optional {@link OO.ui.TabSelectWidget tab} navigation. Cards are usually not instantiated directly,
10254 * rather extended to include the required content and functionality.
10255 *
10256 * Each card must have a unique symbolic name, which is passed to the constructor. In addition, the card's tab
10257 * item is customized (with a label) using the #setupTabItem method. See
10258 * {@link OO.ui.IndexLayout IndexLayout} for an example.
10259 *
10260 * @class
10261 * @extends OO.ui.PanelLayout
10262 *
10263 * @constructor
10264 * @param {string} name Unique symbolic name of card
10265 * @param {Object} [config] Configuration options
10266 */
10267 OO.ui.CardLayout = function OoUiCardLayout( name, config ) {
10268 // Allow passing positional parameters inside the config object
10269 if ( OO.isPlainObject( name ) && config === undefined ) {
10270 config = name;
10271 name = config.name;
10272 }
10273
10274 // Configuration initialization
10275 config = $.extend( { scrollable: true }, config );
10276
10277 // Parent constructor
10278 OO.ui.CardLayout.parent.call( this, config );
10279
10280 // Properties
10281 this.name = name;
10282 this.tabItem = null;
10283 this.active = false;
10284
10285 // Initialization
10286 this.$element.addClass( 'oo-ui-cardLayout' );
10287 };
10288
10289 /* Setup */
10290
10291 OO.inheritClass( OO.ui.CardLayout, OO.ui.PanelLayout );
10292
10293 /* Events */
10294
10295 /**
10296 * An 'active' event is emitted when the card becomes active. Cards become active when they are
10297 * shown in a index layout that is configured to display only one card at a time.
10298 *
10299 * @event active
10300 * @param {boolean} active Card is active
10301 */
10302
10303 /* Methods */
10304
10305 /**
10306 * Get the symbolic name of the card.
10307 *
10308 * @return {string} Symbolic name of card
10309 */
10310 OO.ui.CardLayout.prototype.getName = function () {
10311 return this.name;
10312 };
10313
10314 /**
10315 * Check if card is active.
10316 *
10317 * Cards become active when they are shown in a {@link OO.ui.IndexLayout index layout} that is configured to display
10318 * only one card at a time. Additional CSS is applied to the card's tab item to reflect the active state.
10319 *
10320 * @return {boolean} Card is active
10321 */
10322 OO.ui.CardLayout.prototype.isActive = function () {
10323 return this.active;
10324 };
10325
10326 /**
10327 * Get tab item.
10328 *
10329 * The tab item allows users to access the card from the index's tab
10330 * navigation. The tab item itself can be customized (with a label, level, etc.) using the #setupTabItem method.
10331 *
10332 * @return {OO.ui.TabOptionWidget|null} Tab option widget
10333 */
10334 OO.ui.CardLayout.prototype.getTabItem = function () {
10335 return this.tabItem;
10336 };
10337
10338 /**
10339 * Set or unset the tab item.
10340 *
10341 * Specify a {@link OO.ui.TabOptionWidget tab option} to set it,
10342 * or `null` to clear the tab item. To customize the tab item itself (e.g., to set a label or tab
10343 * level), use #setupTabItem instead of this method.
10344 *
10345 * @param {OO.ui.TabOptionWidget|null} tabItem Tab option widget, null to clear
10346 * @chainable
10347 */
10348 OO.ui.CardLayout.prototype.setTabItem = function ( tabItem ) {
10349 this.tabItem = tabItem || null;
10350 if ( tabItem ) {
10351 this.setupTabItem();
10352 }
10353 return this;
10354 };
10355
10356 /**
10357 * Set up the tab item.
10358 *
10359 * Use this method to customize the tab item (e.g., to add a label or tab level). To set or unset
10360 * the tab item itself (with a {@link OO.ui.TabOptionWidget tab option} or `null`), use
10361 * the #setTabItem method instead.
10362 *
10363 * @param {OO.ui.TabOptionWidget} tabItem Tab option widget to set up
10364 * @chainable
10365 */
10366 OO.ui.CardLayout.prototype.setupTabItem = function () {
10367 return this;
10368 };
10369
10370 /**
10371 * Set the card to its 'active' state.
10372 *
10373 * Cards become active when they are shown in a index layout that is configured to display only one card at a time. Additional
10374 * CSS is applied to the tab item to reflect the card's active state. Outside of the index
10375 * context, setting the active state on a card does nothing.
10376 *
10377 * @param {boolean} value Card is active
10378 * @fires active
10379 */
10380 OO.ui.CardLayout.prototype.setActive = function ( active ) {
10381 active = !!active;
10382
10383 if ( active !== this.active ) {
10384 this.active = active;
10385 this.$element.toggleClass( 'oo-ui-cardLayout-active', this.active );
10386 this.emit( 'active', this.active );
10387 }
10388 };
10389
10390 /**
10391 * PageLayouts are used within {@link OO.ui.BookletLayout booklet layouts} to create pages that users can select and display
10392 * from the booklet's optional {@link OO.ui.OutlineSelectWidget outline} navigation. Pages are usually not instantiated directly,
10393 * rather extended to include the required content and functionality.
10394 *
10395 * Each page must have a unique symbolic name, which is passed to the constructor. In addition, the page's outline
10396 * item is customized (with a label, outline level, etc.) using the #setupOutlineItem method. See
10397 * {@link OO.ui.BookletLayout BookletLayout} for an example.
10398 *
10399 * @class
10400 * @extends OO.ui.PanelLayout
10401 *
10402 * @constructor
10403 * @param {string} name Unique symbolic name of page
10404 * @param {Object} [config] Configuration options
10405 */
10406 OO.ui.PageLayout = function OoUiPageLayout( name, config ) {
10407 // Allow passing positional parameters inside the config object
10408 if ( OO.isPlainObject( name ) && config === undefined ) {
10409 config = name;
10410 name = config.name;
10411 }
10412
10413 // Configuration initialization
10414 config = $.extend( { scrollable: true }, config );
10415
10416 // Parent constructor
10417 OO.ui.PageLayout.parent.call( this, config );
10418
10419 // Properties
10420 this.name = name;
10421 this.outlineItem = null;
10422 this.active = false;
10423
10424 // Initialization
10425 this.$element.addClass( 'oo-ui-pageLayout' );
10426 };
10427
10428 /* Setup */
10429
10430 OO.inheritClass( OO.ui.PageLayout, OO.ui.PanelLayout );
10431
10432 /* Events */
10433
10434 /**
10435 * An 'active' event is emitted when the page becomes active. Pages become active when they are
10436 * shown in a booklet layout that is configured to display only one page at a time.
10437 *
10438 * @event active
10439 * @param {boolean} active Page is active
10440 */
10441
10442 /* Methods */
10443
10444 /**
10445 * Get the symbolic name of the page.
10446 *
10447 * @return {string} Symbolic name of page
10448 */
10449 OO.ui.PageLayout.prototype.getName = function () {
10450 return this.name;
10451 };
10452
10453 /**
10454 * Check if page is active.
10455 *
10456 * Pages become active when they are shown in a {@link OO.ui.BookletLayout booklet layout} that is configured to display
10457 * only one page at a time. Additional CSS is applied to the page's outline item to reflect the active state.
10458 *
10459 * @return {boolean} Page is active
10460 */
10461 OO.ui.PageLayout.prototype.isActive = function () {
10462 return this.active;
10463 };
10464
10465 /**
10466 * Get outline item.
10467 *
10468 * The outline item allows users to access the page from the booklet's outline
10469 * navigation. The outline item itself can be customized (with a label, level, etc.) using the #setupOutlineItem method.
10470 *
10471 * @return {OO.ui.OutlineOptionWidget|null} Outline option widget
10472 */
10473 OO.ui.PageLayout.prototype.getOutlineItem = function () {
10474 return this.outlineItem;
10475 };
10476
10477 /**
10478 * Set or unset the outline item.
10479 *
10480 * Specify an {@link OO.ui.OutlineOptionWidget outline option} to set it,
10481 * or `null` to clear the outline item. To customize the outline item itself (e.g., to set a label or outline
10482 * level), use #setupOutlineItem instead of this method.
10483 *
10484 * @param {OO.ui.OutlineOptionWidget|null} outlineItem Outline option widget, null to clear
10485 * @chainable
10486 */
10487 OO.ui.PageLayout.prototype.setOutlineItem = function ( outlineItem ) {
10488 this.outlineItem = outlineItem || null;
10489 if ( outlineItem ) {
10490 this.setupOutlineItem();
10491 }
10492 return this;
10493 };
10494
10495 /**
10496 * Set up the outline item.
10497 *
10498 * Use this method to customize the outline item (e.g., to add a label or outline level). To set or unset
10499 * the outline item itself (with an {@link OO.ui.OutlineOptionWidget outline option} or `null`), use
10500 * the #setOutlineItem method instead.
10501 *
10502 * @param {OO.ui.OutlineOptionWidget} outlineItem Outline option widget to set up
10503 * @chainable
10504 */
10505 OO.ui.PageLayout.prototype.setupOutlineItem = function () {
10506 return this;
10507 };
10508
10509 /**
10510 * Set the page to its 'active' state.
10511 *
10512 * Pages become active when they are shown in a booklet layout that is configured to display only one page at a time. Additional
10513 * CSS is applied to the outline item to reflect the page's active state. Outside of the booklet
10514 * context, setting the active state on a page does nothing.
10515 *
10516 * @param {boolean} value Page is active
10517 * @fires active
10518 */
10519 OO.ui.PageLayout.prototype.setActive = function ( active ) {
10520 active = !!active;
10521
10522 if ( active !== this.active ) {
10523 this.active = active;
10524 this.$element.toggleClass( 'oo-ui-pageLayout-active', active );
10525 this.emit( 'active', this.active );
10526 }
10527 };
10528
10529 /**
10530 * StackLayouts contain a series of {@link OO.ui.PanelLayout panel layouts}. By default, only one panel is displayed
10531 * at a time, though the stack layout can also be configured to show all contained panels, one after another,
10532 * by setting the #continuous option to 'true'.
10533 *
10534 * @example
10535 * // A stack layout with two panels, configured to be displayed continously
10536 * var myStack = new OO.ui.StackLayout( {
10537 * items: [
10538 * new OO.ui.PanelLayout( {
10539 * $content: $( '<p>Panel One</p>' ),
10540 * padded: true,
10541 * framed: true
10542 * } ),
10543 * new OO.ui.PanelLayout( {
10544 * $content: $( '<p>Panel Two</p>' ),
10545 * padded: true,
10546 * framed: true
10547 * } )
10548 * ],
10549 * continuous: true
10550 * } );
10551 * $( 'body' ).append( myStack.$element );
10552 *
10553 * @class
10554 * @extends OO.ui.PanelLayout
10555 * @mixins OO.ui.mixin.GroupElement
10556 *
10557 * @constructor
10558 * @param {Object} [config] Configuration options
10559 * @cfg {boolean} [continuous=false] Show all panels, one after another. By default, only one panel is displayed at a time.
10560 * @cfg {OO.ui.Layout[]} [items] Panel layouts to add to the stack layout.
10561 */
10562 OO.ui.StackLayout = function OoUiStackLayout( config ) {
10563 // Configuration initialization
10564 config = $.extend( { scrollable: true }, config );
10565
10566 // Parent constructor
10567 OO.ui.StackLayout.parent.call( this, config );
10568
10569 // Mixin constructors
10570 OO.ui.mixin.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) );
10571
10572 // Properties
10573 this.currentItem = null;
10574 this.continuous = !!config.continuous;
10575
10576 // Initialization
10577 this.$element.addClass( 'oo-ui-stackLayout' );
10578 if ( this.continuous ) {
10579 this.$element.addClass( 'oo-ui-stackLayout-continuous' );
10580 }
10581 if ( Array.isArray( config.items ) ) {
10582 this.addItems( config.items );
10583 }
10584 };
10585
10586 /* Setup */
10587
10588 OO.inheritClass( OO.ui.StackLayout, OO.ui.PanelLayout );
10589 OO.mixinClass( OO.ui.StackLayout, OO.ui.mixin.GroupElement );
10590
10591 /* Events */
10592
10593 /**
10594 * A 'set' event is emitted when panels are {@link #addItems added}, {@link #removeItems removed},
10595 * {@link #clearItems cleared} or {@link #setItem displayed}.
10596 *
10597 * @event set
10598 * @param {OO.ui.Layout|null} item Current panel or `null` if no panel is shown
10599 */
10600
10601 /* Methods */
10602
10603 /**
10604 * Get the current panel.
10605 *
10606 * @return {OO.ui.Layout|null}
10607 */
10608 OO.ui.StackLayout.prototype.getCurrentItem = function () {
10609 return this.currentItem;
10610 };
10611
10612 /**
10613 * Unset the current item.
10614 *
10615 * @private
10616 * @param {OO.ui.StackLayout} layout
10617 * @fires set
10618 */
10619 OO.ui.StackLayout.prototype.unsetCurrentItem = function () {
10620 var prevItem = this.currentItem;
10621 if ( prevItem === null ) {
10622 return;
10623 }
10624
10625 this.currentItem = null;
10626 this.emit( 'set', null );
10627 };
10628
10629 /**
10630 * Add panel layouts to the stack layout.
10631 *
10632 * Panels will be added to the end of the stack layout array unless the optional index parameter specifies a different
10633 * insertion point. Adding a panel that is already in the stack will move it to the end of the array or the point specified
10634 * by the index.
10635 *
10636 * @param {OO.ui.Layout[]} items Panels to add
10637 * @param {number} [index] Index of the insertion point
10638 * @chainable
10639 */
10640 OO.ui.StackLayout.prototype.addItems = function ( items, index ) {
10641 // Update the visibility
10642 this.updateHiddenState( items, this.currentItem );
10643
10644 // Mixin method
10645 OO.ui.mixin.GroupElement.prototype.addItems.call( this, items, index );
10646
10647 if ( !this.currentItem && items.length ) {
10648 this.setItem( items[ 0 ] );
10649 }
10650
10651 return this;
10652 };
10653
10654 /**
10655 * Remove the specified panels from the stack layout.
10656 *
10657 * Removed panels are detached from the DOM, not removed, so that they may be reused. To remove all panels,
10658 * you may wish to use the #clearItems method instead.
10659 *
10660 * @param {OO.ui.Layout[]} items Panels to remove
10661 * @chainable
10662 * @fires set
10663 */
10664 OO.ui.StackLayout.prototype.removeItems = function ( items ) {
10665 // Mixin method
10666 OO.ui.mixin.GroupElement.prototype.removeItems.call( this, items );
10667
10668 if ( $.inArray( this.currentItem, items ) !== -1 ) {
10669 if ( this.items.length ) {
10670 this.setItem( this.items[ 0 ] );
10671 } else {
10672 this.unsetCurrentItem();
10673 }
10674 }
10675
10676 return this;
10677 };
10678
10679 /**
10680 * Clear all panels from the stack layout.
10681 *
10682 * Cleared panels are detached from the DOM, not removed, so that they may be reused. To remove only
10683 * a subset of panels, use the #removeItems method.
10684 *
10685 * @chainable
10686 * @fires set
10687 */
10688 OO.ui.StackLayout.prototype.clearItems = function () {
10689 this.unsetCurrentItem();
10690 OO.ui.mixin.GroupElement.prototype.clearItems.call( this );
10691
10692 return this;
10693 };
10694
10695 /**
10696 * Show the specified panel.
10697 *
10698 * If another panel is currently displayed, it will be hidden.
10699 *
10700 * @param {OO.ui.Layout} item Panel to show
10701 * @chainable
10702 * @fires set
10703 */
10704 OO.ui.StackLayout.prototype.setItem = function ( item ) {
10705 if ( item !== this.currentItem ) {
10706 this.updateHiddenState( this.items, item );
10707
10708 if ( $.inArray( item, this.items ) !== -1 ) {
10709 this.currentItem = item;
10710 this.emit( 'set', item );
10711 } else {
10712 this.unsetCurrentItem();
10713 }
10714 }
10715
10716 return this;
10717 };
10718
10719 /**
10720 * Update the visibility of all items in case of non-continuous view.
10721 *
10722 * Ensure all items are hidden except for the selected one.
10723 * This method does nothing when the stack is continuous.
10724 *
10725 * @private
10726 * @param {OO.ui.Layout[]} items Item list iterate over
10727 * @param {OO.ui.Layout} [selectedItem] Selected item to show
10728 */
10729 OO.ui.StackLayout.prototype.updateHiddenState = function ( items, selectedItem ) {
10730 var i, len;
10731
10732 if ( !this.continuous ) {
10733 for ( i = 0, len = items.length; i < len; i++ ) {
10734 if ( !selectedItem || selectedItem !== items[ i ] ) {
10735 items[ i ].$element.addClass( 'oo-ui-element-hidden' );
10736 }
10737 }
10738 if ( selectedItem ) {
10739 selectedItem.$element.removeClass( 'oo-ui-element-hidden' );
10740 }
10741 }
10742 };
10743
10744 /**
10745 * HorizontalLayout arranges its contents in a single line (using `display: inline-block` for its
10746 * items), with small margins between them. Convenient when you need to put a number of block-level
10747 * widgets on a single line next to each other.
10748 *
10749 * Note that inline elements, such as OO.ui.ButtonWidgets, do not need this wrapper.
10750 *
10751 * @example
10752 * // HorizontalLayout with a text input and a label
10753 * var layout = new OO.ui.HorizontalLayout( {
10754 * items: [
10755 * new OO.ui.LabelWidget( { label: 'Label' } ),
10756 * new OO.ui.TextInputWidget( { value: 'Text' } )
10757 * ]
10758 * } );
10759 * $( 'body' ).append( layout.$element );
10760 *
10761 * @class
10762 * @extends OO.ui.Layout
10763 * @mixins OO.ui.mixin.GroupElement
10764 *
10765 * @constructor
10766 * @param {Object} [config] Configuration options
10767 * @cfg {OO.ui.Widget[]|OO.ui.Layout[]} [items] Widgets or other layouts to add to the layout.
10768 */
10769 OO.ui.HorizontalLayout = function OoUiHorizontalLayout( config ) {
10770 // Configuration initialization
10771 config = config || {};
10772
10773 // Parent constructor
10774 OO.ui.HorizontalLayout.parent.call( this, config );
10775
10776 // Mixin constructors
10777 OO.ui.mixin.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) );
10778
10779 // Initialization
10780 this.$element.addClass( 'oo-ui-horizontalLayout' );
10781 if ( Array.isArray( config.items ) ) {
10782 this.addItems( config.items );
10783 }
10784 };
10785
10786 /* Setup */
10787
10788 OO.inheritClass( OO.ui.HorizontalLayout, OO.ui.Layout );
10789 OO.mixinClass( OO.ui.HorizontalLayout, OO.ui.mixin.GroupElement );
10790
10791 /**
10792 * BarToolGroups are one of three types of {@link OO.ui.ToolGroup toolgroups} that are used to
10793 * create {@link OO.ui.Toolbar toolbars} (the other types of groups are {@link OO.ui.MenuToolGroup MenuToolGroup}
10794 * and {@link OO.ui.ListToolGroup ListToolGroup}). The {@link OO.ui.Tool tools} in a BarToolGroup are
10795 * displayed by icon in a single row. The title of the tool is displayed when users move the mouse over
10796 * the tool.
10797 *
10798 * BarToolGroups are created by a {@link OO.ui.ToolGroupFactory tool group factory} when the toolbar is
10799 * set up.
10800 *
10801 * @example
10802 * // Example of a BarToolGroup with two tools
10803 * var toolFactory = new OO.ui.ToolFactory();
10804 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
10805 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
10806 *
10807 * // We will be placing status text in this element when tools are used
10808 * var $area = $( '<p>' ).text( 'Example of a BarToolGroup with two tools.' );
10809 *
10810 * // Define the tools that we're going to place in our toolbar
10811 *
10812 * // Create a class inheriting from OO.ui.Tool
10813 * function PictureTool() {
10814 * PictureTool.parent.apply( this, arguments );
10815 * }
10816 * OO.inheritClass( PictureTool, OO.ui.Tool );
10817 * // Each tool must have a 'name' (used as an internal identifier, see later) and at least one
10818 * // of 'icon' and 'title' (displayed icon and text).
10819 * PictureTool.static.name = 'picture';
10820 * PictureTool.static.icon = 'picture';
10821 * PictureTool.static.title = 'Insert picture';
10822 * // Defines the action that will happen when this tool is selected (clicked).
10823 * PictureTool.prototype.onSelect = function () {
10824 * $area.text( 'Picture tool clicked!' );
10825 * // Never display this tool as "active" (selected).
10826 * this.setActive( false );
10827 * };
10828 * // Make this tool available in our toolFactory and thus our toolbar
10829 * toolFactory.register( PictureTool );
10830 *
10831 * // This is a PopupTool. Rather than having a custom 'onSelect' action, it will display a
10832 * // little popup window (a PopupWidget).
10833 * function HelpTool( toolGroup, config ) {
10834 * OO.ui.PopupTool.call( this, toolGroup, $.extend( { popup: {
10835 * padded: true,
10836 * label: 'Help',
10837 * head: true
10838 * } }, config ) );
10839 * this.popup.$body.append( '<p>I am helpful!</p>' );
10840 * }
10841 * OO.inheritClass( HelpTool, OO.ui.PopupTool );
10842 * HelpTool.static.name = 'help';
10843 * HelpTool.static.icon = 'help';
10844 * HelpTool.static.title = 'Help';
10845 * toolFactory.register( HelpTool );
10846 *
10847 * // Finally define which tools and in what order appear in the toolbar. Each tool may only be
10848 * // used once (but not all defined tools must be used).
10849 * toolbar.setup( [
10850 * {
10851 * // 'bar' tool groups display tools by icon only
10852 * type: 'bar',
10853 * include: [ 'picture', 'help' ]
10854 * }
10855 * ] );
10856 *
10857 * // Create some UI around the toolbar and place it in the document
10858 * var frame = new OO.ui.PanelLayout( {
10859 * expanded: false,
10860 * framed: true
10861 * } );
10862 * var contentFrame = new OO.ui.PanelLayout( {
10863 * expanded: false,
10864 * padded: true
10865 * } );
10866 * frame.$element.append(
10867 * toolbar.$element,
10868 * contentFrame.$element.append( $area )
10869 * );
10870 * $( 'body' ).append( frame.$element );
10871 *
10872 * // Here is where the toolbar is actually built. This must be done after inserting it into the
10873 * // document.
10874 * toolbar.initialize();
10875 *
10876 * For more information about how to add tools to a bar tool group, please see {@link OO.ui.ToolGroup toolgroup}.
10877 * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki][1].
10878 *
10879 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
10880 *
10881 * @class
10882 * @extends OO.ui.ToolGroup
10883 *
10884 * @constructor
10885 * @param {OO.ui.Toolbar} toolbar
10886 * @param {Object} [config] Configuration options
10887 */
10888 OO.ui.BarToolGroup = function OoUiBarToolGroup( toolbar, config ) {
10889 // Allow passing positional parameters inside the config object
10890 if ( OO.isPlainObject( toolbar ) && config === undefined ) {
10891 config = toolbar;
10892 toolbar = config.toolbar;
10893 }
10894
10895 // Parent constructor
10896 OO.ui.BarToolGroup.parent.call( this, toolbar, config );
10897
10898 // Initialization
10899 this.$element.addClass( 'oo-ui-barToolGroup' );
10900 };
10901
10902 /* Setup */
10903
10904 OO.inheritClass( OO.ui.BarToolGroup, OO.ui.ToolGroup );
10905
10906 /* Static Properties */
10907
10908 OO.ui.BarToolGroup.static.titleTooltips = true;
10909
10910 OO.ui.BarToolGroup.static.accelTooltips = true;
10911
10912 OO.ui.BarToolGroup.static.name = 'bar';
10913
10914 /**
10915 * PopupToolGroup is an abstract base class used by both {@link OO.ui.MenuToolGroup MenuToolGroup}
10916 * and {@link OO.ui.ListToolGroup ListToolGroup} to provide a popup--an overlaid menu or list of tools with an
10917 * optional icon and label. This class can be used for other base classes that also use this functionality.
10918 *
10919 * @abstract
10920 * @class
10921 * @extends OO.ui.ToolGroup
10922 * @mixins OO.ui.mixin.IconElement
10923 * @mixins OO.ui.mixin.IndicatorElement
10924 * @mixins OO.ui.mixin.LabelElement
10925 * @mixins OO.ui.mixin.TitledElement
10926 * @mixins OO.ui.mixin.ClippableElement
10927 * @mixins OO.ui.mixin.TabIndexedElement
10928 *
10929 * @constructor
10930 * @param {OO.ui.Toolbar} toolbar
10931 * @param {Object} [config] Configuration options
10932 * @cfg {string} [header] Text to display at the top of the popup
10933 */
10934 OO.ui.PopupToolGroup = function OoUiPopupToolGroup( toolbar, config ) {
10935 // Allow passing positional parameters inside the config object
10936 if ( OO.isPlainObject( toolbar ) && config === undefined ) {
10937 config = toolbar;
10938 toolbar = config.toolbar;
10939 }
10940
10941 // Configuration initialization
10942 config = config || {};
10943
10944 // Parent constructor
10945 OO.ui.PopupToolGroup.parent.call( this, toolbar, config );
10946
10947 // Properties
10948 this.active = false;
10949 this.dragging = false;
10950 this.onBlurHandler = this.onBlur.bind( this );
10951 this.$handle = $( '<span>' );
10952
10953 // Mixin constructors
10954 OO.ui.mixin.IconElement.call( this, config );
10955 OO.ui.mixin.IndicatorElement.call( this, config );
10956 OO.ui.mixin.LabelElement.call( this, config );
10957 OO.ui.mixin.TitledElement.call( this, config );
10958 OO.ui.mixin.ClippableElement.call( this, $.extend( {}, config, { $clippable: this.$group } ) );
10959 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$handle } ) );
10960
10961 // Events
10962 this.$handle.on( {
10963 keydown: this.onHandleMouseKeyDown.bind( this ),
10964 keyup: this.onHandleMouseKeyUp.bind( this ),
10965 mousedown: this.onHandleMouseKeyDown.bind( this ),
10966 mouseup: this.onHandleMouseKeyUp.bind( this )
10967 } );
10968
10969 // Initialization
10970 this.$handle
10971 .addClass( 'oo-ui-popupToolGroup-handle' )
10972 .append( this.$icon, this.$label, this.$indicator );
10973 // If the pop-up should have a header, add it to the top of the toolGroup.
10974 // Note: If this feature is useful for other widgets, we could abstract it into an
10975 // OO.ui.HeaderedElement mixin constructor.
10976 if ( config.header !== undefined ) {
10977 this.$group
10978 .prepend( $( '<span>' )
10979 .addClass( 'oo-ui-popupToolGroup-header' )
10980 .text( config.header )
10981 );
10982 }
10983 this.$element
10984 .addClass( 'oo-ui-popupToolGroup' )
10985 .prepend( this.$handle );
10986 };
10987
10988 /* Setup */
10989
10990 OO.inheritClass( OO.ui.PopupToolGroup, OO.ui.ToolGroup );
10991 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.mixin.IconElement );
10992 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.mixin.IndicatorElement );
10993 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.mixin.LabelElement );
10994 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.mixin.TitledElement );
10995 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.mixin.ClippableElement );
10996 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.mixin.TabIndexedElement );
10997
10998 /* Methods */
10999
11000 /**
11001 * @inheritdoc
11002 */
11003 OO.ui.PopupToolGroup.prototype.setDisabled = function () {
11004 // Parent method
11005 OO.ui.PopupToolGroup.parent.prototype.setDisabled.apply( this, arguments );
11006
11007 if ( this.isDisabled() && this.isElementAttached() ) {
11008 this.setActive( false );
11009 }
11010 };
11011
11012 /**
11013 * Handle focus being lost.
11014 *
11015 * The event is actually generated from a mouseup/keyup, so it is not a normal blur event object.
11016 *
11017 * @protected
11018 * @param {jQuery.Event} e Mouse up or key up event
11019 */
11020 OO.ui.PopupToolGroup.prototype.onBlur = function ( e ) {
11021 // Only deactivate when clicking outside the dropdown element
11022 if ( $( e.target ).closest( '.oo-ui-popupToolGroup' )[ 0 ] !== this.$element[ 0 ] ) {
11023 this.setActive( false );
11024 }
11025 };
11026
11027 /**
11028 * @inheritdoc
11029 */
11030 OO.ui.PopupToolGroup.prototype.onMouseKeyUp = function ( e ) {
11031 // Only close toolgroup when a tool was actually selected
11032 if (
11033 !this.isDisabled() && this.pressed && this.pressed === this.getTargetTool( e ) &&
11034 ( e.which === 1 || e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
11035 ) {
11036 this.setActive( false );
11037 }
11038 return OO.ui.PopupToolGroup.parent.prototype.onMouseKeyUp.call( this, e );
11039 };
11040
11041 /**
11042 * Handle mouse up and key up events.
11043 *
11044 * @protected
11045 * @param {jQuery.Event} e Mouse up or key up event
11046 */
11047 OO.ui.PopupToolGroup.prototype.onHandleMouseKeyUp = function ( e ) {
11048 if (
11049 !this.isDisabled() &&
11050 ( e.which === 1 || e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
11051 ) {
11052 return false;
11053 }
11054 };
11055
11056 /**
11057 * Handle mouse down and key down events.
11058 *
11059 * @protected
11060 * @param {jQuery.Event} e Mouse down or key down event
11061 */
11062 OO.ui.PopupToolGroup.prototype.onHandleMouseKeyDown = function ( e ) {
11063 if (
11064 !this.isDisabled() &&
11065 ( e.which === 1 || e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
11066 ) {
11067 this.setActive( !this.active );
11068 return false;
11069 }
11070 };
11071
11072 /**
11073 * Switch into 'active' mode.
11074 *
11075 * When active, the popup is visible. A mouseup event anywhere in the document will trigger
11076 * deactivation.
11077 */
11078 OO.ui.PopupToolGroup.prototype.setActive = function ( value ) {
11079 var containerWidth, containerLeft;
11080 value = !!value;
11081 if ( this.active !== value ) {
11082 this.active = value;
11083 if ( value ) {
11084 this.getElementDocument().addEventListener( 'mouseup', this.onBlurHandler, true );
11085 this.getElementDocument().addEventListener( 'keyup', this.onBlurHandler, true );
11086
11087 this.$clippable.css( 'left', '' );
11088 // Try anchoring the popup to the left first
11089 this.$element.addClass( 'oo-ui-popupToolGroup-active oo-ui-popupToolGroup-left' );
11090 this.toggleClipping( true );
11091 if ( this.isClippedHorizontally() ) {
11092 // Anchoring to the left caused the popup to clip, so anchor it to the right instead
11093 this.toggleClipping( false );
11094 this.$element
11095 .removeClass( 'oo-ui-popupToolGroup-left' )
11096 .addClass( 'oo-ui-popupToolGroup-right' );
11097 this.toggleClipping( true );
11098 }
11099 if ( this.isClippedHorizontally() ) {
11100 // Anchoring to the right also caused the popup to clip, so just make it fill the container
11101 containerWidth = this.$clippableContainer.width();
11102 containerLeft = this.$clippableContainer.offset().left;
11103
11104 this.toggleClipping( false );
11105 this.$element.removeClass( 'oo-ui-popupToolGroup-right' );
11106
11107 this.$clippable.css( {
11108 left: -( this.$element.offset().left - containerLeft ),
11109 width: containerWidth
11110 } );
11111 }
11112 } else {
11113 this.getElementDocument().removeEventListener( 'mouseup', this.onBlurHandler, true );
11114 this.getElementDocument().removeEventListener( 'keyup', this.onBlurHandler, true );
11115 this.$element.removeClass(
11116 'oo-ui-popupToolGroup-active oo-ui-popupToolGroup-left oo-ui-popupToolGroup-right'
11117 );
11118 this.toggleClipping( false );
11119 }
11120 }
11121 };
11122
11123 /**
11124 * ListToolGroups are one of three types of {@link OO.ui.ToolGroup toolgroups} that are used to
11125 * create {@link OO.ui.Toolbar toolbars} (the other types of groups are {@link OO.ui.MenuToolGroup MenuToolGroup}
11126 * and {@link OO.ui.BarToolGroup BarToolGroup}). The {@link OO.ui.Tool tools} in a ListToolGroup are displayed
11127 * by label in a dropdown menu. The title of the tool is used as the label text. The menu itself can be configured
11128 * with a label, icon, indicator, header, and title.
11129 *
11130 * ListToolGroups can be configured to be expanded and collapsed. Collapsed lists will have a ‘More’ option that
11131 * users can select to see the full list of tools. If a collapsed toolgroup is expanded, a ‘Fewer’ option permits
11132 * users to collapse the list again.
11133 *
11134 * ListToolGroups are created by a {@link OO.ui.ToolGroupFactory toolgroup factory} when the toolbar is set up. The factory
11135 * requires the ListToolGroup's symbolic name, 'list', which is specified along with the other configurations. For more
11136 * information about how to add tools to a ListToolGroup, please see {@link OO.ui.ToolGroup toolgroup}.
11137 *
11138 * @example
11139 * // Example of a ListToolGroup
11140 * var toolFactory = new OO.ui.ToolFactory();
11141 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
11142 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
11143 *
11144 * // Configure and register two tools
11145 * function SettingsTool() {
11146 * SettingsTool.parent.apply( this, arguments );
11147 * }
11148 * OO.inheritClass( SettingsTool, OO.ui.Tool );
11149 * SettingsTool.static.name = 'settings';
11150 * SettingsTool.static.icon = 'settings';
11151 * SettingsTool.static.title = 'Change settings';
11152 * SettingsTool.prototype.onSelect = function () {
11153 * this.setActive( false );
11154 * };
11155 * toolFactory.register( SettingsTool );
11156 * // Register two more tools, nothing interesting here
11157 * function StuffTool() {
11158 * StuffTool.parent.apply( this, arguments );
11159 * }
11160 * OO.inheritClass( StuffTool, OO.ui.Tool );
11161 * StuffTool.static.name = 'stuff';
11162 * StuffTool.static.icon = 'ellipsis';
11163 * StuffTool.static.title = 'Change the world';
11164 * StuffTool.prototype.onSelect = function () {
11165 * this.setActive( false );
11166 * };
11167 * toolFactory.register( StuffTool );
11168 * toolbar.setup( [
11169 * {
11170 * // Configurations for list toolgroup.
11171 * type: 'list',
11172 * label: 'ListToolGroup',
11173 * indicator: 'down',
11174 * icon: 'picture',
11175 * title: 'This is the title, displayed when user moves the mouse over the list toolgroup',
11176 * header: 'This is the header',
11177 * include: [ 'settings', 'stuff' ],
11178 * allowCollapse: ['stuff']
11179 * }
11180 * ] );
11181 *
11182 * // Create some UI around the toolbar and place it in the document
11183 * var frame = new OO.ui.PanelLayout( {
11184 * expanded: false,
11185 * framed: true
11186 * } );
11187 * frame.$element.append(
11188 * toolbar.$element
11189 * );
11190 * $( 'body' ).append( frame.$element );
11191 * // Build the toolbar. This must be done after the toolbar has been appended to the document.
11192 * toolbar.initialize();
11193 *
11194 * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki][1].
11195 *
11196 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
11197 *
11198 * @class
11199 * @extends OO.ui.PopupToolGroup
11200 *
11201 * @constructor
11202 * @param {OO.ui.Toolbar} toolbar
11203 * @param {Object} [config] Configuration options
11204 * @cfg {Array} [allowCollapse] Allow the specified tools to be collapsed. By default, collapsible tools
11205 * will only be displayed if users click the ‘More’ option displayed at the bottom of the list. If
11206 * the list is expanded, a ‘Fewer’ option permits users to collapse the list again. Any tools that
11207 * are included in the toolgroup, but are not designated as collapsible, will always be displayed.
11208 * To open a collapsible list in its expanded state, set #expanded to 'true'.
11209 * @cfg {Array} [forceExpand] Expand the specified tools. All other tools will be designated as collapsible.
11210 * Unless #expanded is set to true, the collapsible tools will be collapsed when the list is first opened.
11211 * @cfg {boolean} [expanded=false] Expand collapsible tools. This config is only relevant if tools have
11212 * been designated as collapsible. When expanded is set to true, all tools in the group will be displayed
11213 * when the list is first opened. Users can collapse the list with a ‘Fewer’ option at the bottom.
11214 */
11215 OO.ui.ListToolGroup = function OoUiListToolGroup( toolbar, config ) {
11216 // Allow passing positional parameters inside the config object
11217 if ( OO.isPlainObject( toolbar ) && config === undefined ) {
11218 config = toolbar;
11219 toolbar = config.toolbar;
11220 }
11221
11222 // Configuration initialization
11223 config = config || {};
11224
11225 // Properties (must be set before parent constructor, which calls #populate)
11226 this.allowCollapse = config.allowCollapse;
11227 this.forceExpand = config.forceExpand;
11228 this.expanded = config.expanded !== undefined ? config.expanded : false;
11229 this.collapsibleTools = [];
11230
11231 // Parent constructor
11232 OO.ui.ListToolGroup.parent.call( this, toolbar, config );
11233
11234 // Initialization
11235 this.$element.addClass( 'oo-ui-listToolGroup' );
11236 };
11237
11238 /* Setup */
11239
11240 OO.inheritClass( OO.ui.ListToolGroup, OO.ui.PopupToolGroup );
11241
11242 /* Static Properties */
11243
11244 OO.ui.ListToolGroup.static.name = 'list';
11245
11246 /* Methods */
11247
11248 /**
11249 * @inheritdoc
11250 */
11251 OO.ui.ListToolGroup.prototype.populate = function () {
11252 var i, len, allowCollapse = [];
11253
11254 OO.ui.ListToolGroup.parent.prototype.populate.call( this );
11255
11256 // Update the list of collapsible tools
11257 if ( this.allowCollapse !== undefined ) {
11258 allowCollapse = this.allowCollapse;
11259 } else if ( this.forceExpand !== undefined ) {
11260 allowCollapse = OO.simpleArrayDifference( Object.keys( this.tools ), this.forceExpand );
11261 }
11262
11263 this.collapsibleTools = [];
11264 for ( i = 0, len = allowCollapse.length; i < len; i++ ) {
11265 if ( this.tools[ allowCollapse[ i ] ] !== undefined ) {
11266 this.collapsibleTools.push( this.tools[ allowCollapse[ i ] ] );
11267 }
11268 }
11269
11270 // Keep at the end, even when tools are added
11271 this.$group.append( this.getExpandCollapseTool().$element );
11272
11273 this.getExpandCollapseTool().toggle( this.collapsibleTools.length !== 0 );
11274 this.updateCollapsibleState();
11275 };
11276
11277 OO.ui.ListToolGroup.prototype.getExpandCollapseTool = function () {
11278 if ( this.expandCollapseTool === undefined ) {
11279 var ExpandCollapseTool = function () {
11280 ExpandCollapseTool.parent.apply( this, arguments );
11281 };
11282
11283 OO.inheritClass( ExpandCollapseTool, OO.ui.Tool );
11284
11285 ExpandCollapseTool.prototype.onSelect = function () {
11286 this.toolGroup.expanded = !this.toolGroup.expanded;
11287 this.toolGroup.updateCollapsibleState();
11288 this.setActive( false );
11289 };
11290 ExpandCollapseTool.prototype.onUpdateState = function () {
11291 // Do nothing. Tool interface requires an implementation of this function.
11292 };
11293
11294 ExpandCollapseTool.static.name = 'more-fewer';
11295
11296 this.expandCollapseTool = new ExpandCollapseTool( this );
11297 }
11298 return this.expandCollapseTool;
11299 };
11300
11301 /**
11302 * @inheritdoc
11303 */
11304 OO.ui.ListToolGroup.prototype.onMouseKeyUp = function ( e ) {
11305 // Do not close the popup when the user wants to show more/fewer tools
11306 if (
11307 $( e.target ).closest( '.oo-ui-tool-name-more-fewer' ).length &&
11308 ( e.which === 1 || e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
11309 ) {
11310 // HACK: Prevent the popup list from being hidden. Skip the PopupToolGroup implementation (which
11311 // hides the popup list when a tool is selected) and call ToolGroup's implementation directly.
11312 return OO.ui.ListToolGroup.parent.parent.prototype.onMouseKeyUp.call( this, e );
11313 } else {
11314 return OO.ui.ListToolGroup.parent.prototype.onMouseKeyUp.call( this, e );
11315 }
11316 };
11317
11318 OO.ui.ListToolGroup.prototype.updateCollapsibleState = function () {
11319 var i, len;
11320
11321 this.getExpandCollapseTool()
11322 .setIcon( this.expanded ? 'collapse' : 'expand' )
11323 .setTitle( OO.ui.msg( this.expanded ? 'ooui-toolgroup-collapse' : 'ooui-toolgroup-expand' ) );
11324
11325 for ( i = 0, len = this.collapsibleTools.length; i < len; i++ ) {
11326 this.collapsibleTools[ i ].toggle( this.expanded );
11327 }
11328 };
11329
11330 /**
11331 * MenuToolGroups are one of three types of {@link OO.ui.ToolGroup toolgroups} that are used to
11332 * create {@link OO.ui.Toolbar toolbars} (the other types of groups are {@link OO.ui.BarToolGroup BarToolGroup}
11333 * and {@link OO.ui.ListToolGroup ListToolGroup}). MenuToolGroups contain selectable {@link OO.ui.Tool tools},
11334 * which are displayed by label in a dropdown menu. The tool's title is used as the label text, and the
11335 * menu label is updated to reflect which tool or tools are currently selected. If no tools are selected,
11336 * the menu label is empty. The menu can be configured with an indicator, icon, title, and/or header.
11337 *
11338 * MenuToolGroups are created by a {@link OO.ui.ToolGroupFactory tool group factory} when the toolbar
11339 * is set up. Note that all tools must define an {@link OO.ui.Tool#onUpdateState onUpdateState} method if
11340 * a MenuToolGroup is used.
11341 *
11342 * @example
11343 * // Example of a MenuToolGroup
11344 * var toolFactory = new OO.ui.ToolFactory();
11345 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
11346 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
11347 *
11348 * // We will be placing status text in this element when tools are used
11349 * var $area = $( '<p>' ).text( 'An example of a MenuToolGroup. Select a tool from the dropdown menu.' );
11350 *
11351 * // Define the tools that we're going to place in our toolbar
11352 *
11353 * function SettingsTool() {
11354 * SettingsTool.parent.apply( this, arguments );
11355 * this.reallyActive = false;
11356 * }
11357 * OO.inheritClass( SettingsTool, OO.ui.Tool );
11358 * SettingsTool.static.name = 'settings';
11359 * SettingsTool.static.icon = 'settings';
11360 * SettingsTool.static.title = 'Change settings';
11361 * SettingsTool.prototype.onSelect = function () {
11362 * $area.text( 'Settings tool clicked!' );
11363 * // Toggle the active state on each click
11364 * this.reallyActive = !this.reallyActive;
11365 * this.setActive( this.reallyActive );
11366 * // To update the menu label
11367 * this.toolbar.emit( 'updateState' );
11368 * };
11369 * SettingsTool.prototype.onUpdateState = function () {
11370 * };
11371 * toolFactory.register( SettingsTool );
11372 *
11373 * function StuffTool() {
11374 * StuffTool.parent.apply( this, arguments );
11375 * this.reallyActive = false;
11376 * }
11377 * OO.inheritClass( StuffTool, OO.ui.Tool );
11378 * StuffTool.static.name = 'stuff';
11379 * StuffTool.static.icon = 'ellipsis';
11380 * StuffTool.static.title = 'More stuff';
11381 * StuffTool.prototype.onSelect = function () {
11382 * $area.text( 'More stuff tool clicked!' );
11383 * // Toggle the active state on each click
11384 * this.reallyActive = !this.reallyActive;
11385 * this.setActive( this.reallyActive );
11386 * // To update the menu label
11387 * this.toolbar.emit( 'updateState' );
11388 * };
11389 * StuffTool.prototype.onUpdateState = function () {
11390 * };
11391 * toolFactory.register( StuffTool );
11392 *
11393 * // Finally define which tools and in what order appear in the toolbar. Each tool may only be
11394 * // used once (but not all defined tools must be used).
11395 * toolbar.setup( [
11396 * {
11397 * type: 'menu',
11398 * header: 'This is the (optional) header',
11399 * title: 'This is the (optional) title',
11400 * indicator: 'down',
11401 * include: [ 'settings', 'stuff' ]
11402 * }
11403 * ] );
11404 *
11405 * // Create some UI around the toolbar and place it in the document
11406 * var frame = new OO.ui.PanelLayout( {
11407 * expanded: false,
11408 * framed: true
11409 * } );
11410 * var contentFrame = new OO.ui.PanelLayout( {
11411 * expanded: false,
11412 * padded: true
11413 * } );
11414 * frame.$element.append(
11415 * toolbar.$element,
11416 * contentFrame.$element.append( $area )
11417 * );
11418 * $( 'body' ).append( frame.$element );
11419 *
11420 * // Here is where the toolbar is actually built. This must be done after inserting it into the
11421 * // document.
11422 * toolbar.initialize();
11423 * toolbar.emit( 'updateState' );
11424 *
11425 * For more information about how to add tools to a MenuToolGroup, please see {@link OO.ui.ToolGroup toolgroup}.
11426 * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki] [1].
11427 *
11428 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
11429 *
11430 * @class
11431 * @extends OO.ui.PopupToolGroup
11432 *
11433 * @constructor
11434 * @param {OO.ui.Toolbar} toolbar
11435 * @param {Object} [config] Configuration options
11436 */
11437 OO.ui.MenuToolGroup = function OoUiMenuToolGroup( toolbar, config ) {
11438 // Allow passing positional parameters inside the config object
11439 if ( OO.isPlainObject( toolbar ) && config === undefined ) {
11440 config = toolbar;
11441 toolbar = config.toolbar;
11442 }
11443
11444 // Configuration initialization
11445 config = config || {};
11446
11447 // Parent constructor
11448 OO.ui.MenuToolGroup.parent.call( this, toolbar, config );
11449
11450 // Events
11451 this.toolbar.connect( this, { updateState: 'onUpdateState' } );
11452
11453 // Initialization
11454 this.$element.addClass( 'oo-ui-menuToolGroup' );
11455 };
11456
11457 /* Setup */
11458
11459 OO.inheritClass( OO.ui.MenuToolGroup, OO.ui.PopupToolGroup );
11460
11461 /* Static Properties */
11462
11463 OO.ui.MenuToolGroup.static.name = 'menu';
11464
11465 /* Methods */
11466
11467 /**
11468 * Handle the toolbar state being updated.
11469 *
11470 * When the state changes, the title of each active item in the menu will be joined together and
11471 * used as a label for the group. The label will be empty if none of the items are active.
11472 *
11473 * @private
11474 */
11475 OO.ui.MenuToolGroup.prototype.onUpdateState = function () {
11476 var name,
11477 labelTexts = [];
11478
11479 for ( name in this.tools ) {
11480 if ( this.tools[ name ].isActive() ) {
11481 labelTexts.push( this.tools[ name ].getTitle() );
11482 }
11483 }
11484
11485 this.setLabel( labelTexts.join( ', ' ) || ' ' );
11486 };
11487
11488 /**
11489 * Popup tools open a popup window when they are selected from the {@link OO.ui.Toolbar toolbar}. Each popup tool is configured
11490 * 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
11491 * an #onSelect or #onUpdateState method, as these methods have been implemented already.
11492 *
11493 * // Example of a popup tool. When selected, a popup tool displays
11494 * // a popup window.
11495 * function HelpTool( toolGroup, config ) {
11496 * OO.ui.PopupTool.call( this, toolGroup, $.extend( { popup: {
11497 * padded: true,
11498 * label: 'Help',
11499 * head: true
11500 * } }, config ) );
11501 * this.popup.$body.append( '<p>I am helpful!</p>' );
11502 * };
11503 * OO.inheritClass( HelpTool, OO.ui.PopupTool );
11504 * HelpTool.static.name = 'help';
11505 * HelpTool.static.icon = 'help';
11506 * HelpTool.static.title = 'Help';
11507 * toolFactory.register( HelpTool );
11508 *
11509 * For an example of a toolbar that contains a popup tool, see {@link OO.ui.Toolbar toolbars}. For more information about
11510 * toolbars in genreral, please see the [OOjs UI documentation on MediaWiki][1].
11511 *
11512 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
11513 *
11514 * @abstract
11515 * @class
11516 * @extends OO.ui.Tool
11517 * @mixins OO.ui.mixin.PopupElement
11518 *
11519 * @constructor
11520 * @param {OO.ui.ToolGroup} toolGroup
11521 * @param {Object} [config] Configuration options
11522 */
11523 OO.ui.PopupTool = function OoUiPopupTool( toolGroup, config ) {
11524 // Allow passing positional parameters inside the config object
11525 if ( OO.isPlainObject( toolGroup ) && config === undefined ) {
11526 config = toolGroup;
11527 toolGroup = config.toolGroup;
11528 }
11529
11530 // Parent constructor
11531 OO.ui.PopupTool.parent.call( this, toolGroup, config );
11532
11533 // Mixin constructors
11534 OO.ui.mixin.PopupElement.call( this, config );
11535
11536 // Initialization
11537 this.$element
11538 .addClass( 'oo-ui-popupTool' )
11539 .append( this.popup.$element );
11540 };
11541
11542 /* Setup */
11543
11544 OO.inheritClass( OO.ui.PopupTool, OO.ui.Tool );
11545 OO.mixinClass( OO.ui.PopupTool, OO.ui.mixin.PopupElement );
11546
11547 /* Methods */
11548
11549 /**
11550 * Handle the tool being selected.
11551 *
11552 * @inheritdoc
11553 */
11554 OO.ui.PopupTool.prototype.onSelect = function () {
11555 if ( !this.isDisabled() ) {
11556 this.popup.toggle();
11557 }
11558 this.setActive( false );
11559 return false;
11560 };
11561
11562 /**
11563 * Handle the toolbar state being updated.
11564 *
11565 * @inheritdoc
11566 */
11567 OO.ui.PopupTool.prototype.onUpdateState = function () {
11568 this.setActive( false );
11569 };
11570
11571 /**
11572 * A ToolGroupTool is a special sort of tool that can contain other {@link OO.ui.Tool tools}
11573 * and {@link OO.ui.ToolGroup toolgroups}. The ToolGroupTool was specifically designed to be used
11574 * inside a {@link OO.ui.BarToolGroup bar} toolgroup to provide access to additional tools from
11575 * the bar item. Included tools will be displayed in a dropdown {@link OO.ui.ListToolGroup list}
11576 * when the ToolGroupTool is selected.
11577 *
11578 * // Example: ToolGroupTool with two nested tools, 'setting1' and 'setting2', defined elsewhere.
11579 *
11580 * function SettingsTool() {
11581 * SettingsTool.parent.apply( this, arguments );
11582 * };
11583 * OO.inheritClass( SettingsTool, OO.ui.ToolGroupTool );
11584 * SettingsTool.static.name = 'settings';
11585 * SettingsTool.static.title = 'Change settings';
11586 * SettingsTool.static.groupConfig = {
11587 * icon: 'settings',
11588 * label: 'ToolGroupTool',
11589 * include: [ 'setting1', 'setting2' ]
11590 * };
11591 * toolFactory.register( SettingsTool );
11592 *
11593 * For more information, please see the [OOjs UI documentation on MediaWiki][1].
11594 *
11595 * Please note that this implementation is subject to change per [T74159] [2].
11596 *
11597 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars#ToolGroupTool
11598 * [2]: https://phabricator.wikimedia.org/T74159
11599 *
11600 * @abstract
11601 * @class
11602 * @extends OO.ui.Tool
11603 *
11604 * @constructor
11605 * @param {OO.ui.ToolGroup} toolGroup
11606 * @param {Object} [config] Configuration options
11607 */
11608 OO.ui.ToolGroupTool = function OoUiToolGroupTool( toolGroup, config ) {
11609 // Allow passing positional parameters inside the config object
11610 if ( OO.isPlainObject( toolGroup ) && config === undefined ) {
11611 config = toolGroup;
11612 toolGroup = config.toolGroup;
11613 }
11614
11615 // Parent constructor
11616 OO.ui.ToolGroupTool.parent.call( this, toolGroup, config );
11617
11618 // Properties
11619 this.innerToolGroup = this.createGroup( this.constructor.static.groupConfig );
11620
11621 // Events
11622 this.innerToolGroup.connect( this, { disable: 'onToolGroupDisable' } );
11623
11624 // Initialization
11625 this.$link.remove();
11626 this.$element
11627 .addClass( 'oo-ui-toolGroupTool' )
11628 .append( this.innerToolGroup.$element );
11629 };
11630
11631 /* Setup */
11632
11633 OO.inheritClass( OO.ui.ToolGroupTool, OO.ui.Tool );
11634
11635 /* Static Properties */
11636
11637 /**
11638 * Toolgroup configuration.
11639 *
11640 * The toolgroup configuration consists of the tools to include, as well as an icon and label
11641 * to use for the bar item. Tools can be included by symbolic name, group, or with the
11642 * wildcard selector. Please see {@link OO.ui.ToolGroup toolgroup} for more information.
11643 *
11644 * @property {Object.<string,Array>}
11645 */
11646 OO.ui.ToolGroupTool.static.groupConfig = {};
11647
11648 /* Methods */
11649
11650 /**
11651 * Handle the tool being selected.
11652 *
11653 * @inheritdoc
11654 */
11655 OO.ui.ToolGroupTool.prototype.onSelect = function () {
11656 this.innerToolGroup.setActive( !this.innerToolGroup.active );
11657 return false;
11658 };
11659
11660 /**
11661 * Synchronize disabledness state of the tool with the inner toolgroup.
11662 *
11663 * @private
11664 * @param {boolean} disabled Element is disabled
11665 */
11666 OO.ui.ToolGroupTool.prototype.onToolGroupDisable = function ( disabled ) {
11667 this.setDisabled( disabled );
11668 };
11669
11670 /**
11671 * Handle the toolbar state being updated.
11672 *
11673 * @inheritdoc
11674 */
11675 OO.ui.ToolGroupTool.prototype.onUpdateState = function () {
11676 this.setActive( false );
11677 };
11678
11679 /**
11680 * Build a {@link OO.ui.ToolGroup toolgroup} from the specified configuration.
11681 *
11682 * @param {Object.<string,Array>} group Toolgroup configuration. Please see {@link OO.ui.ToolGroup toolgroup} for
11683 * more information.
11684 * @return {OO.ui.ListToolGroup}
11685 */
11686 OO.ui.ToolGroupTool.prototype.createGroup = function ( group ) {
11687 if ( group.include === '*' ) {
11688 // Apply defaults to catch-all groups
11689 if ( group.label === undefined ) {
11690 group.label = OO.ui.msg( 'ooui-toolbar-more' );
11691 }
11692 }
11693
11694 return this.toolbar.getToolGroupFactory().create( 'list', this.toolbar, group );
11695 };
11696
11697 /**
11698 * Mixin for OO.ui.Widget subclasses to provide OO.ui.mixin.GroupElement.
11699 *
11700 * Use together with OO.ui.mixin.ItemWidget to make disabled state inheritable.
11701 *
11702 * @private
11703 * @abstract
11704 * @class
11705 * @extends OO.ui.mixin.GroupElement
11706 *
11707 * @constructor
11708 * @param {Object} [config] Configuration options
11709 */
11710 OO.ui.mixin.GroupWidget = function OoUiMixinGroupWidget( config ) {
11711 // Parent constructor
11712 OO.ui.mixin.GroupWidget.parent.call( this, config );
11713 };
11714
11715 /* Setup */
11716
11717 OO.inheritClass( OO.ui.mixin.GroupWidget, OO.ui.mixin.GroupElement );
11718
11719 /* Methods */
11720
11721 /**
11722 * Set the disabled state of the widget.
11723 *
11724 * This will also update the disabled state of child widgets.
11725 *
11726 * @param {boolean} disabled Disable widget
11727 * @chainable
11728 */
11729 OO.ui.mixin.GroupWidget.prototype.setDisabled = function ( disabled ) {
11730 var i, len;
11731
11732 // Parent method
11733 // Note: Calling #setDisabled this way assumes this is mixed into an OO.ui.Widget
11734 OO.ui.Widget.prototype.setDisabled.call( this, disabled );
11735
11736 // During construction, #setDisabled is called before the OO.ui.mixin.GroupElement constructor
11737 if ( this.items ) {
11738 for ( i = 0, len = this.items.length; i < len; i++ ) {
11739 this.items[ i ].updateDisabled();
11740 }
11741 }
11742
11743 return this;
11744 };
11745
11746 /**
11747 * Mixin for widgets used as items in widgets that mix in OO.ui.mixin.GroupWidget.
11748 *
11749 * Item widgets have a reference to a OO.ui.mixin.GroupWidget while they are attached to the group. This
11750 * allows bidirectional communication.
11751 *
11752 * Use together with OO.ui.mixin.GroupWidget to make disabled state inheritable.
11753 *
11754 * @private
11755 * @abstract
11756 * @class
11757 *
11758 * @constructor
11759 */
11760 OO.ui.mixin.ItemWidget = function OoUiMixinItemWidget() {
11761 //
11762 };
11763
11764 /* Methods */
11765
11766 /**
11767 * Check if widget is disabled.
11768 *
11769 * Checks parent if present, making disabled state inheritable.
11770 *
11771 * @return {boolean} Widget is disabled
11772 */
11773 OO.ui.mixin.ItemWidget.prototype.isDisabled = function () {
11774 return this.disabled ||
11775 ( this.elementGroup instanceof OO.ui.Widget && this.elementGroup.isDisabled() );
11776 };
11777
11778 /**
11779 * Set group element is in.
11780 *
11781 * @param {OO.ui.mixin.GroupElement|null} group Group element, null if none
11782 * @chainable
11783 */
11784 OO.ui.mixin.ItemWidget.prototype.setElementGroup = function ( group ) {
11785 // Parent method
11786 // Note: Calling #setElementGroup this way assumes this is mixed into an OO.ui.Element
11787 OO.ui.Element.prototype.setElementGroup.call( this, group );
11788
11789 // Initialize item disabled states
11790 this.updateDisabled();
11791
11792 return this;
11793 };
11794
11795 /**
11796 * OutlineControlsWidget is a set of controls for an {@link OO.ui.OutlineSelectWidget outline select widget}.
11797 * Controls include moving items up and down, removing items, and adding different kinds of items.
11798 *
11799 * **Currently, this class is only used by {@link OO.ui.BookletLayout booklet layouts}.**
11800 *
11801 * @class
11802 * @extends OO.ui.Widget
11803 * @mixins OO.ui.mixin.GroupElement
11804 * @mixins OO.ui.mixin.IconElement
11805 *
11806 * @constructor
11807 * @param {OO.ui.OutlineSelectWidget} outline Outline to control
11808 * @param {Object} [config] Configuration options
11809 * @cfg {Object} [abilities] List of abilties
11810 * @cfg {boolean} [abilities.move=true] Allow moving movable items
11811 * @cfg {boolean} [abilities.remove=true] Allow removing removable items
11812 */
11813 OO.ui.OutlineControlsWidget = function OoUiOutlineControlsWidget( outline, config ) {
11814 // Allow passing positional parameters inside the config object
11815 if ( OO.isPlainObject( outline ) && config === undefined ) {
11816 config = outline;
11817 outline = config.outline;
11818 }
11819
11820 // Configuration initialization
11821 config = $.extend( { icon: 'add' }, config );
11822
11823 // Parent constructor
11824 OO.ui.OutlineControlsWidget.parent.call( this, config );
11825
11826 // Mixin constructors
11827 OO.ui.mixin.GroupElement.call( this, config );
11828 OO.ui.mixin.IconElement.call( this, config );
11829
11830 // Properties
11831 this.outline = outline;
11832 this.$movers = $( '<div>' );
11833 this.upButton = new OO.ui.ButtonWidget( {
11834 framed: false,
11835 icon: 'collapse',
11836 title: OO.ui.msg( 'ooui-outline-control-move-up' )
11837 } );
11838 this.downButton = new OO.ui.ButtonWidget( {
11839 framed: false,
11840 icon: 'expand',
11841 title: OO.ui.msg( 'ooui-outline-control-move-down' )
11842 } );
11843 this.removeButton = new OO.ui.ButtonWidget( {
11844 framed: false,
11845 icon: 'remove',
11846 title: OO.ui.msg( 'ooui-outline-control-remove' )
11847 } );
11848 this.abilities = { move: true, remove: true };
11849
11850 // Events
11851 outline.connect( this, {
11852 select: 'onOutlineChange',
11853 add: 'onOutlineChange',
11854 remove: 'onOutlineChange'
11855 } );
11856 this.upButton.connect( this, { click: [ 'emit', 'move', -1 ] } );
11857 this.downButton.connect( this, { click: [ 'emit', 'move', 1 ] } );
11858 this.removeButton.connect( this, { click: [ 'emit', 'remove' ] } );
11859
11860 // Initialization
11861 this.$element.addClass( 'oo-ui-outlineControlsWidget' );
11862 this.$group.addClass( 'oo-ui-outlineControlsWidget-items' );
11863 this.$movers
11864 .addClass( 'oo-ui-outlineControlsWidget-movers' )
11865 .append( this.removeButton.$element, this.upButton.$element, this.downButton.$element );
11866 this.$element.append( this.$icon, this.$group, this.$movers );
11867 this.setAbilities( config.abilities || {} );
11868 };
11869
11870 /* Setup */
11871
11872 OO.inheritClass( OO.ui.OutlineControlsWidget, OO.ui.Widget );
11873 OO.mixinClass( OO.ui.OutlineControlsWidget, OO.ui.mixin.GroupElement );
11874 OO.mixinClass( OO.ui.OutlineControlsWidget, OO.ui.mixin.IconElement );
11875
11876 /* Events */
11877
11878 /**
11879 * @event move
11880 * @param {number} places Number of places to move
11881 */
11882
11883 /**
11884 * @event remove
11885 */
11886
11887 /* Methods */
11888
11889 /**
11890 * Set abilities.
11891 *
11892 * @param {Object} abilities List of abilties
11893 * @param {boolean} [abilities.move] Allow moving movable items
11894 * @param {boolean} [abilities.remove] Allow removing removable items
11895 */
11896 OO.ui.OutlineControlsWidget.prototype.setAbilities = function ( abilities ) {
11897 var ability;
11898
11899 for ( ability in this.abilities ) {
11900 if ( abilities[ability] !== undefined ) {
11901 this.abilities[ability] = !!abilities[ability];
11902 }
11903 }
11904
11905 this.onOutlineChange();
11906 };
11907
11908 /**
11909 *
11910 * @private
11911 * Handle outline change events.
11912 */
11913 OO.ui.OutlineControlsWidget.prototype.onOutlineChange = function () {
11914 var i, len, firstMovable, lastMovable,
11915 items = this.outline.getItems(),
11916 selectedItem = this.outline.getSelectedItem(),
11917 movable = this.abilities.move && selectedItem && selectedItem.isMovable(),
11918 removable = this.abilities.remove && selectedItem && selectedItem.isRemovable();
11919
11920 if ( movable ) {
11921 i = -1;
11922 len = items.length;
11923 while ( ++i < len ) {
11924 if ( items[ i ].isMovable() ) {
11925 firstMovable = items[ i ];
11926 break;
11927 }
11928 }
11929 i = len;
11930 while ( i-- ) {
11931 if ( items[ i ].isMovable() ) {
11932 lastMovable = items[ i ];
11933 break;
11934 }
11935 }
11936 }
11937 this.upButton.setDisabled( !movable || selectedItem === firstMovable );
11938 this.downButton.setDisabled( !movable || selectedItem === lastMovable );
11939 this.removeButton.setDisabled( !removable );
11940 };
11941
11942 /**
11943 * ToggleWidget implements basic behavior of widgets with an on/off state.
11944 * Please see OO.ui.ToggleButtonWidget and OO.ui.ToggleSwitchWidget for examples.
11945 *
11946 * @abstract
11947 * @class
11948 * @extends OO.ui.Widget
11949 *
11950 * @constructor
11951 * @param {Object} [config] Configuration options
11952 * @cfg {boolean} [value=false] The toggle’s initial on/off state.
11953 * By default, the toggle is in the 'off' state.
11954 */
11955 OO.ui.ToggleWidget = function OoUiToggleWidget( config ) {
11956 // Configuration initialization
11957 config = config || {};
11958
11959 // Parent constructor
11960 OO.ui.ToggleWidget.parent.call( this, config );
11961
11962 // Properties
11963 this.value = null;
11964
11965 // Initialization
11966 this.$element.addClass( 'oo-ui-toggleWidget' );
11967 this.setValue( !!config.value );
11968 };
11969
11970 /* Setup */
11971
11972 OO.inheritClass( OO.ui.ToggleWidget, OO.ui.Widget );
11973
11974 /* Events */
11975
11976 /**
11977 * @event change
11978 *
11979 * A change event is emitted when the on/off state of the toggle changes.
11980 *
11981 * @param {boolean} value Value representing the new state of the toggle
11982 */
11983
11984 /* Methods */
11985
11986 /**
11987 * Get the value representing the toggle’s state.
11988 *
11989 * @return {boolean} The on/off state of the toggle
11990 */
11991 OO.ui.ToggleWidget.prototype.getValue = function () {
11992 return this.value;
11993 };
11994
11995 /**
11996 * Set the state of the toggle: `true` for 'on', `false' for 'off'.
11997 *
11998 * @param {boolean} value The state of the toggle
11999 * @fires change
12000 * @chainable
12001 */
12002 OO.ui.ToggleWidget.prototype.setValue = function ( value ) {
12003 value = !!value;
12004 if ( this.value !== value ) {
12005 this.value = value;
12006 this.emit( 'change', value );
12007 this.$element.toggleClass( 'oo-ui-toggleWidget-on', value );
12008 this.$element.toggleClass( 'oo-ui-toggleWidget-off', !value );
12009 this.$element.attr( 'aria-checked', value.toString() );
12010 }
12011 return this;
12012 };
12013
12014 /**
12015 * A ButtonGroupWidget groups related buttons and is used together with OO.ui.ButtonWidget and
12016 * its subclasses. Each button in a group is addressed by a unique reference. Buttons can be added,
12017 * removed, and cleared from the group.
12018 *
12019 * @example
12020 * // Example: A ButtonGroupWidget with two buttons
12021 * var button1 = new OO.ui.PopupButtonWidget( {
12022 * label: 'Select a category',
12023 * icon: 'menu',
12024 * popup: {
12025 * $content: $( '<p>List of categories...</p>' ),
12026 * padded: true,
12027 * align: 'left'
12028 * }
12029 * } );
12030 * var button2 = new OO.ui.ButtonWidget( {
12031 * label: 'Add item'
12032 * });
12033 * var buttonGroup = new OO.ui.ButtonGroupWidget( {
12034 * items: [button1, button2]
12035 * } );
12036 * $( 'body' ).append( buttonGroup.$element );
12037 *
12038 * @class
12039 * @extends OO.ui.Widget
12040 * @mixins OO.ui.mixin.GroupElement
12041 *
12042 * @constructor
12043 * @param {Object} [config] Configuration options
12044 * @cfg {OO.ui.ButtonWidget[]} [items] Buttons to add
12045 */
12046 OO.ui.ButtonGroupWidget = function OoUiButtonGroupWidget( config ) {
12047 // Configuration initialization
12048 config = config || {};
12049
12050 // Parent constructor
12051 OO.ui.ButtonGroupWidget.parent.call( this, config );
12052
12053 // Mixin constructors
12054 OO.ui.mixin.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) );
12055
12056 // Initialization
12057 this.$element.addClass( 'oo-ui-buttonGroupWidget' );
12058 if ( Array.isArray( config.items ) ) {
12059 this.addItems( config.items );
12060 }
12061 };
12062
12063 /* Setup */
12064
12065 OO.inheritClass( OO.ui.ButtonGroupWidget, OO.ui.Widget );
12066 OO.mixinClass( OO.ui.ButtonGroupWidget, OO.ui.mixin.GroupElement );
12067
12068 /**
12069 * ButtonWidget is a generic widget for buttons. A wide variety of looks,
12070 * feels, and functionality can be customized via the class’s configuration options
12071 * and methods. Please see the [OOjs UI documentation on MediaWiki] [1] for more information
12072 * and examples.
12073 *
12074 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches
12075 *
12076 * @example
12077 * // A button widget
12078 * var button = new OO.ui.ButtonWidget( {
12079 * label: 'Button with Icon',
12080 * icon: 'remove',
12081 * iconTitle: 'Remove'
12082 * } );
12083 * $( 'body' ).append( button.$element );
12084 *
12085 * NOTE: HTML form buttons should use the OO.ui.ButtonInputWidget class.
12086 *
12087 * @class
12088 * @extends OO.ui.Widget
12089 * @mixins OO.ui.mixin.ButtonElement
12090 * @mixins OO.ui.mixin.IconElement
12091 * @mixins OO.ui.mixin.IndicatorElement
12092 * @mixins OO.ui.mixin.LabelElement
12093 * @mixins OO.ui.mixin.TitledElement
12094 * @mixins OO.ui.mixin.FlaggedElement
12095 * @mixins OO.ui.mixin.TabIndexedElement
12096 *
12097 * @constructor
12098 * @param {Object} [config] Configuration options
12099 * @cfg {string} [href] Hyperlink to visit when the button is clicked.
12100 * @cfg {string} [target] The frame or window in which to open the hyperlink.
12101 * @cfg {boolean} [noFollow] Search engine traversal hint (default: true)
12102 */
12103 OO.ui.ButtonWidget = function OoUiButtonWidget( config ) {
12104 // Configuration initialization
12105 config = config || {};
12106
12107 // Parent constructor
12108 OO.ui.ButtonWidget.parent.call( this, config );
12109
12110 // Mixin constructors
12111 OO.ui.mixin.ButtonElement.call( this, config );
12112 OO.ui.mixin.IconElement.call( this, config );
12113 OO.ui.mixin.IndicatorElement.call( this, config );
12114 OO.ui.mixin.LabelElement.call( this, config );
12115 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$button } ) );
12116 OO.ui.mixin.FlaggedElement.call( this, config );
12117 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$button } ) );
12118
12119 // Properties
12120 this.href = null;
12121 this.target = null;
12122 this.noFollow = false;
12123
12124 // Events
12125 this.connect( this, { disable: 'onDisable' } );
12126
12127 // Initialization
12128 this.$button.append( this.$icon, this.$label, this.$indicator );
12129 this.$element
12130 .addClass( 'oo-ui-buttonWidget' )
12131 .append( this.$button );
12132 this.setHref( config.href );
12133 this.setTarget( config.target );
12134 this.setNoFollow( config.noFollow );
12135 };
12136
12137 /* Setup */
12138
12139 OO.inheritClass( OO.ui.ButtonWidget, OO.ui.Widget );
12140 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.ButtonElement );
12141 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.IconElement );
12142 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.IndicatorElement );
12143 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.LabelElement );
12144 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.TitledElement );
12145 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.FlaggedElement );
12146 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.TabIndexedElement );
12147
12148 /* Methods */
12149
12150 /**
12151 * @inheritdoc
12152 */
12153 OO.ui.ButtonWidget.prototype.onMouseDown = function ( e ) {
12154 if ( !this.isDisabled() ) {
12155 // Remove the tab-index while the button is down to prevent the button from stealing focus
12156 this.$button.removeAttr( 'tabindex' );
12157 }
12158
12159 return OO.ui.mixin.ButtonElement.prototype.onMouseDown.call( this, e );
12160 };
12161
12162 /**
12163 * @inheritdoc
12164 */
12165 OO.ui.ButtonWidget.prototype.onMouseUp = function ( e ) {
12166 if ( !this.isDisabled() ) {
12167 // Restore the tab-index after the button is up to restore the button's accessibility
12168 this.$button.attr( 'tabindex', this.tabIndex );
12169 }
12170
12171 return OO.ui.mixin.ButtonElement.prototype.onMouseUp.call( this, e );
12172 };
12173
12174 /**
12175 * Get hyperlink location.
12176 *
12177 * @return {string} Hyperlink location
12178 */
12179 OO.ui.ButtonWidget.prototype.getHref = function () {
12180 return this.href;
12181 };
12182
12183 /**
12184 * Get hyperlink target.
12185 *
12186 * @return {string} Hyperlink target
12187 */
12188 OO.ui.ButtonWidget.prototype.getTarget = function () {
12189 return this.target;
12190 };
12191
12192 /**
12193 * Get search engine traversal hint.
12194 *
12195 * @return {boolean} Whether search engines should avoid traversing this hyperlink
12196 */
12197 OO.ui.ButtonWidget.prototype.getNoFollow = function () {
12198 return this.noFollow;
12199 };
12200
12201 /**
12202 * Set hyperlink location.
12203 *
12204 * @param {string|null} href Hyperlink location, null to remove
12205 */
12206 OO.ui.ButtonWidget.prototype.setHref = function ( href ) {
12207 href = typeof href === 'string' ? href : null;
12208 if ( href !== null ) {
12209 if ( !OO.ui.isSafeUrl( href ) ) {
12210 throw new Error( 'Potentially unsafe href provided: ' + href );
12211 }
12212
12213 }
12214
12215 if ( href !== this.href ) {
12216 this.href = href;
12217 this.updateHref();
12218 }
12219
12220 return this;
12221 };
12222
12223 /**
12224 * Update the `href` attribute, in case of changes to href or
12225 * disabled state.
12226 *
12227 * @private
12228 * @chainable
12229 */
12230 OO.ui.ButtonWidget.prototype.updateHref = function () {
12231 if ( this.href !== null && !this.isDisabled() ) {
12232 this.$button.attr( 'href', this.href );
12233 } else {
12234 this.$button.removeAttr( 'href' );
12235 }
12236
12237 return this;
12238 };
12239
12240 /**
12241 * Handle disable events.
12242 *
12243 * @private
12244 * @param {boolean} disabled Element is disabled
12245 */
12246 OO.ui.ButtonWidget.prototype.onDisable = function () {
12247 this.updateHref();
12248 };
12249
12250 /**
12251 * Set hyperlink target.
12252 *
12253 * @param {string|null} target Hyperlink target, null to remove
12254 */
12255 OO.ui.ButtonWidget.prototype.setTarget = function ( target ) {
12256 target = typeof target === 'string' ? target : null;
12257
12258 if ( target !== this.target ) {
12259 this.target = target;
12260 if ( target !== null ) {
12261 this.$button.attr( 'target', target );
12262 } else {
12263 this.$button.removeAttr( 'target' );
12264 }
12265 }
12266
12267 return this;
12268 };
12269
12270 /**
12271 * Set search engine traversal hint.
12272 *
12273 * @param {boolean} noFollow True if search engines should avoid traversing this hyperlink
12274 */
12275 OO.ui.ButtonWidget.prototype.setNoFollow = function ( noFollow ) {
12276 noFollow = typeof noFollow === 'boolean' ? noFollow : true;
12277
12278 if ( noFollow !== this.noFollow ) {
12279 this.noFollow = noFollow;
12280 if ( noFollow ) {
12281 this.$button.attr( 'rel', 'nofollow' );
12282 } else {
12283 this.$button.removeAttr( 'rel' );
12284 }
12285 }
12286
12287 return this;
12288 };
12289
12290 /**
12291 * An ActionWidget is a {@link OO.ui.ButtonWidget button widget} that executes an action.
12292 * Action widgets are used with OO.ui.ActionSet, which manages the behavior and availability
12293 * of the actions.
12294 *
12295 * Both actions and action sets are primarily used with {@link OO.ui.Dialog Dialogs}.
12296 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information
12297 * and examples.
12298 *
12299 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Action_sets
12300 *
12301 * @class
12302 * @extends OO.ui.ButtonWidget
12303 * @mixins OO.ui.mixin.PendingElement
12304 *
12305 * @constructor
12306 * @param {Object} [config] Configuration options
12307 * @cfg {string} [action] Symbolic name of the action (e.g., ‘continue’ or ‘cancel’).
12308 * @cfg {string[]} [modes] Symbolic names of the modes (e.g., ‘edit’ or ‘read’) in which the action
12309 * should be made available. See the action set's {@link OO.ui.ActionSet#setMode setMode} method
12310 * for more information about setting modes.
12311 * @cfg {boolean} [framed=false] Render the action button with a frame
12312 */
12313 OO.ui.ActionWidget = function OoUiActionWidget( config ) {
12314 // Configuration initialization
12315 config = $.extend( { framed: false }, config );
12316
12317 // Parent constructor
12318 OO.ui.ActionWidget.parent.call( this, config );
12319
12320 // Mixin constructors
12321 OO.ui.mixin.PendingElement.call( this, config );
12322
12323 // Properties
12324 this.action = config.action || '';
12325 this.modes = config.modes || [];
12326 this.width = 0;
12327 this.height = 0;
12328
12329 // Initialization
12330 this.$element.addClass( 'oo-ui-actionWidget' );
12331 };
12332
12333 /* Setup */
12334
12335 OO.inheritClass( OO.ui.ActionWidget, OO.ui.ButtonWidget );
12336 OO.mixinClass( OO.ui.ActionWidget, OO.ui.mixin.PendingElement );
12337
12338 /* Events */
12339
12340 /**
12341 * A resize event is emitted when the size of the widget changes.
12342 *
12343 * @event resize
12344 */
12345
12346 /* Methods */
12347
12348 /**
12349 * Check if the action is configured to be available in the specified `mode`.
12350 *
12351 * @param {string} mode Name of mode
12352 * @return {boolean} The action is configured with the mode
12353 */
12354 OO.ui.ActionWidget.prototype.hasMode = function ( mode ) {
12355 return this.modes.indexOf( mode ) !== -1;
12356 };
12357
12358 /**
12359 * Get the symbolic name of the action (e.g., ‘continue’ or ‘cancel’).
12360 *
12361 * @return {string}
12362 */
12363 OO.ui.ActionWidget.prototype.getAction = function () {
12364 return this.action;
12365 };
12366
12367 /**
12368 * Get the symbolic name of the mode or modes for which the action is configured to be available.
12369 *
12370 * The current mode is set with the action set's {@link OO.ui.ActionSet#setMode setMode} method.
12371 * Only actions that are configured to be avaiable in the current mode will be visible. All other actions
12372 * are hidden.
12373 *
12374 * @return {string[]}
12375 */
12376 OO.ui.ActionWidget.prototype.getModes = function () {
12377 return this.modes.slice();
12378 };
12379
12380 /**
12381 * Emit a resize event if the size has changed.
12382 *
12383 * @private
12384 * @chainable
12385 */
12386 OO.ui.ActionWidget.prototype.propagateResize = function () {
12387 var width, height;
12388
12389 if ( this.isElementAttached() ) {
12390 width = this.$element.width();
12391 height = this.$element.height();
12392
12393 if ( width !== this.width || height !== this.height ) {
12394 this.width = width;
12395 this.height = height;
12396 this.emit( 'resize' );
12397 }
12398 }
12399
12400 return this;
12401 };
12402
12403 /**
12404 * @inheritdoc
12405 */
12406 OO.ui.ActionWidget.prototype.setIcon = function () {
12407 // Mixin method
12408 OO.ui.mixin.IconElement.prototype.setIcon.apply( this, arguments );
12409 this.propagateResize();
12410
12411 return this;
12412 };
12413
12414 /**
12415 * @inheritdoc
12416 */
12417 OO.ui.ActionWidget.prototype.setLabel = function () {
12418 // Mixin method
12419 OO.ui.mixin.LabelElement.prototype.setLabel.apply( this, arguments );
12420 this.propagateResize();
12421
12422 return this;
12423 };
12424
12425 /**
12426 * @inheritdoc
12427 */
12428 OO.ui.ActionWidget.prototype.setFlags = function () {
12429 // Mixin method
12430 OO.ui.mixin.FlaggedElement.prototype.setFlags.apply( this, arguments );
12431 this.propagateResize();
12432
12433 return this;
12434 };
12435
12436 /**
12437 * @inheritdoc
12438 */
12439 OO.ui.ActionWidget.prototype.clearFlags = function () {
12440 // Mixin method
12441 OO.ui.mixin.FlaggedElement.prototype.clearFlags.apply( this, arguments );
12442 this.propagateResize();
12443
12444 return this;
12445 };
12446
12447 /**
12448 * Toggle the visibility of the action button.
12449 *
12450 * @param {boolean} [show] Show button, omit to toggle visibility
12451 * @chainable
12452 */
12453 OO.ui.ActionWidget.prototype.toggle = function () {
12454 // Parent method
12455 OO.ui.ActionWidget.parent.prototype.toggle.apply( this, arguments );
12456 this.propagateResize();
12457
12458 return this;
12459 };
12460
12461 /**
12462 * PopupButtonWidgets toggle the visibility of a contained {@link OO.ui.PopupWidget PopupWidget},
12463 * which is used to display additional information or options.
12464 *
12465 * @example
12466 * // Example of a popup button.
12467 * var popupButton = new OO.ui.PopupButtonWidget( {
12468 * label: 'Popup button with options',
12469 * icon: 'menu',
12470 * popup: {
12471 * $content: $( '<p>Additional options here.</p>' ),
12472 * padded: true,
12473 * align: 'force-left'
12474 * }
12475 * } );
12476 * // Append the button to the DOM.
12477 * $( 'body' ).append( popupButton.$element );
12478 *
12479 * @class
12480 * @extends OO.ui.ButtonWidget
12481 * @mixins OO.ui.mixin.PopupElement
12482 *
12483 * @constructor
12484 * @param {Object} [config] Configuration options
12485 */
12486 OO.ui.PopupButtonWidget = function OoUiPopupButtonWidget( config ) {
12487 // Parent constructor
12488 OO.ui.PopupButtonWidget.parent.call( this, config );
12489
12490 // Mixin constructors
12491 OO.ui.mixin.PopupElement.call( this, config );
12492
12493 // Events
12494 this.connect( this, { click: 'onAction' } );
12495
12496 // Initialization
12497 this.$element
12498 .addClass( 'oo-ui-popupButtonWidget' )
12499 .attr( 'aria-haspopup', 'true' )
12500 .append( this.popup.$element );
12501 };
12502
12503 /* Setup */
12504
12505 OO.inheritClass( OO.ui.PopupButtonWidget, OO.ui.ButtonWidget );
12506 OO.mixinClass( OO.ui.PopupButtonWidget, OO.ui.mixin.PopupElement );
12507
12508 /* Methods */
12509
12510 /**
12511 * Handle the button action being triggered.
12512 *
12513 * @private
12514 */
12515 OO.ui.PopupButtonWidget.prototype.onAction = function () {
12516 this.popup.toggle();
12517 };
12518
12519 /**
12520 * ToggleButtons are buttons that have a state (‘on’ or ‘off’) that is represented by a
12521 * Boolean value. Like other {@link OO.ui.ButtonWidget buttons}, toggle buttons can be
12522 * configured with {@link OO.ui.mixin.IconElement icons}, {@link OO.ui.mixin.IndicatorElement indicators},
12523 * {@link OO.ui.mixin.TitledElement titles}, {@link OO.ui.mixin.FlaggedElement styling flags},
12524 * and {@link OO.ui.mixin.LabelElement labels}. Please see
12525 * the [OOjs UI documentation][1] on MediaWiki for more information.
12526 *
12527 * @example
12528 * // Toggle buttons in the 'off' and 'on' state.
12529 * var toggleButton1 = new OO.ui.ToggleButtonWidget( {
12530 * label: 'Toggle Button off'
12531 * } );
12532 * var toggleButton2 = new OO.ui.ToggleButtonWidget( {
12533 * label: 'Toggle Button on',
12534 * value: true
12535 * } );
12536 * // Append the buttons to the DOM.
12537 * $( 'body' ).append( toggleButton1.$element, toggleButton2.$element );
12538 *
12539 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#Toggle_buttons
12540 *
12541 * @class
12542 * @extends OO.ui.ToggleWidget
12543 * @mixins OO.ui.mixin.ButtonElement
12544 * @mixins OO.ui.mixin.IconElement
12545 * @mixins OO.ui.mixin.IndicatorElement
12546 * @mixins OO.ui.mixin.LabelElement
12547 * @mixins OO.ui.mixin.TitledElement
12548 * @mixins OO.ui.mixin.FlaggedElement
12549 * @mixins OO.ui.mixin.TabIndexedElement
12550 *
12551 * @constructor
12552 * @param {Object} [config] Configuration options
12553 * @cfg {boolean} [value=false] The toggle button’s initial on/off
12554 * state. By default, the button is in the 'off' state.
12555 */
12556 OO.ui.ToggleButtonWidget = function OoUiToggleButtonWidget( config ) {
12557 // Configuration initialization
12558 config = config || {};
12559
12560 // Parent constructor
12561 OO.ui.ToggleButtonWidget.parent.call( this, config );
12562
12563 // Mixin constructors
12564 OO.ui.mixin.ButtonElement.call( this, config );
12565 OO.ui.mixin.IconElement.call( this, config );
12566 OO.ui.mixin.IndicatorElement.call( this, config );
12567 OO.ui.mixin.LabelElement.call( this, config );
12568 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$button } ) );
12569 OO.ui.mixin.FlaggedElement.call( this, config );
12570 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$button } ) );
12571
12572 // Events
12573 this.connect( this, { click: 'onAction' } );
12574
12575 // Initialization
12576 this.$button.append( this.$icon, this.$label, this.$indicator );
12577 this.$element
12578 .addClass( 'oo-ui-toggleButtonWidget' )
12579 .append( this.$button );
12580 };
12581
12582 /* Setup */
12583
12584 OO.inheritClass( OO.ui.ToggleButtonWidget, OO.ui.ToggleWidget );
12585 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.ButtonElement );
12586 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.IconElement );
12587 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.IndicatorElement );
12588 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.LabelElement );
12589 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.TitledElement );
12590 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.FlaggedElement );
12591 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.TabIndexedElement );
12592
12593 /* Methods */
12594
12595 /**
12596 * Handle the button action being triggered.
12597 *
12598 * @private
12599 */
12600 OO.ui.ToggleButtonWidget.prototype.onAction = function () {
12601 this.setValue( !this.value );
12602 };
12603
12604 /**
12605 * @inheritdoc
12606 */
12607 OO.ui.ToggleButtonWidget.prototype.setValue = function ( value ) {
12608 value = !!value;
12609 if ( value !== this.value ) {
12610 // Might be called from parent constructor before ButtonElement constructor
12611 if ( this.$button ) {
12612 this.$button.attr( 'aria-pressed', value.toString() );
12613 }
12614 this.setActive( value );
12615 }
12616
12617 // Parent method
12618 OO.ui.ToggleButtonWidget.parent.prototype.setValue.call( this, value );
12619
12620 return this;
12621 };
12622
12623 /**
12624 * @inheritdoc
12625 */
12626 OO.ui.ToggleButtonWidget.prototype.setButtonElement = function ( $button ) {
12627 if ( this.$button ) {
12628 this.$button.removeAttr( 'aria-pressed' );
12629 }
12630 OO.ui.mixin.ButtonElement.prototype.setButtonElement.call( this, $button );
12631 this.$button.attr( 'aria-pressed', this.value.toString() );
12632 };
12633
12634 /**
12635 * CapsuleMultiSelectWidgets are something like a {@link OO.ui.ComboBoxWidget combo box widget}
12636 * that allows for selecting multiple values.
12637 *
12638 * For more information about menus and options, please see the [OOjs UI documentation on MediaWiki][1].
12639 *
12640 * @example
12641 * // Example: A CapsuleMultiSelectWidget.
12642 * var capsule = new OO.ui.CapsuleMultiSelectWidget( {
12643 * label: 'CapsuleMultiSelectWidget',
12644 * selected: [ 'Option 1', 'Option 3' ],
12645 * menu: {
12646 * items: [
12647 * new OO.ui.MenuOptionWidget( {
12648 * data: 'Option 1',
12649 * label: 'Option One'
12650 * } ),
12651 * new OO.ui.MenuOptionWidget( {
12652 * data: 'Option 2',
12653 * label: 'Option Two'
12654 * } ),
12655 * new OO.ui.MenuOptionWidget( {
12656 * data: 'Option 3',
12657 * label: 'Option Three'
12658 * } ),
12659 * new OO.ui.MenuOptionWidget( {
12660 * data: 'Option 4',
12661 * label: 'Option Four'
12662 * } ),
12663 * new OO.ui.MenuOptionWidget( {
12664 * data: 'Option 5',
12665 * label: 'Option Five'
12666 * } )
12667 * ]
12668 * }
12669 * } );
12670 * $( 'body' ).append( capsule.$element );
12671 *
12672 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
12673 *
12674 * @class
12675 * @extends OO.ui.Widget
12676 * @mixins OO.ui.mixin.TabIndexedElement
12677 * @mixins OO.ui.mixin.GroupElement
12678 *
12679 * @constructor
12680 * @param {Object} [config] Configuration options
12681 * @cfg {boolean} [allowArbitrary=false] Allow data items to be added even if not present in the menu.
12682 * @cfg {Object} [menu] Configuration options to pass to the {@link OO.ui.MenuSelectWidget menu select widget}.
12683 * @cfg {Object} [popup] Configuration options to pass to the {@link OO.ui.PopupWidget popup widget}.
12684 * If specified, this popup will be shown instead of the menu (but the menu
12685 * will still be used for item labels and allowArbitrary=false). The widgets
12686 * in the popup should use this.addItemsFromData() or this.addItems() as necessary.
12687 * @cfg {jQuery} [$overlay] Render the menu or popup into a separate layer.
12688 * This configuration is useful in cases where the expanded menu is larger than
12689 * its containing `<div>`. The specified overlay layer is usually on top of
12690 * the containing `<div>` and has a larger area. By default, the menu uses
12691 * relative positioning.
12692 */
12693 OO.ui.CapsuleMultiSelectWidget = function OoUiCapsuleMultiSelectWidget( config ) {
12694 var $tabFocus;
12695
12696 // Configuration initialization
12697 config = config || {};
12698
12699 // Parent constructor
12700 OO.ui.CapsuleMultiSelectWidget.parent.call( this, config );
12701
12702 // Properties (must be set before mixin constructor calls)
12703 this.$input = config.popup ? null : $( '<input>' );
12704 this.$handle = $( '<div>' );
12705
12706 // Mixin constructors
12707 OO.ui.mixin.GroupElement.call( this, config );
12708 if ( config.popup ) {
12709 config.popup = $.extend( {}, config.popup, {
12710 align: 'forwards',
12711 anchor: false
12712 } );
12713 OO.ui.mixin.PopupElement.call( this, config );
12714 $tabFocus = $( '<span>' );
12715 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: $tabFocus } ) );
12716 } else {
12717 this.popup = null;
12718 $tabFocus = null;
12719 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$input } ) );
12720 }
12721 OO.ui.mixin.IndicatorElement.call( this, config );
12722 OO.ui.mixin.IconElement.call( this, config );
12723
12724 // Properties
12725 this.allowArbitrary = !!config.allowArbitrary;
12726 this.$overlay = config.$overlay || this.$element;
12727 this.menu = new OO.ui.MenuSelectWidget( $.extend(
12728 {
12729 widget: this,
12730 $input: this.$input,
12731 filterFromInput: true,
12732 disabled: this.isDisabled()
12733 },
12734 config.menu
12735 ) );
12736
12737 // Events
12738 if ( this.popup ) {
12739 $tabFocus.on( {
12740 focus: this.onFocusForPopup.bind( this )
12741 } );
12742 this.popup.$element.on( 'focusout', this.onPopupFocusOut.bind( this ) );
12743 if ( this.popup.$autoCloseIgnore ) {
12744 this.popup.$autoCloseIgnore.on( 'focusout', this.onPopupFocusOut.bind( this ) );
12745 }
12746 this.popup.connect( this, {
12747 toggle: function ( visible ) {
12748 $tabFocus.toggle( !visible );
12749 }
12750 } );
12751 } else {
12752 this.$input.on( {
12753 focus: this.onInputFocus.bind( this ),
12754 blur: this.onInputBlur.bind( this ),
12755 'propertychange change click mouseup keydown keyup input cut paste select': this.onInputChange.bind( this ),
12756 keydown: this.onKeyDown.bind( this ),
12757 keypress: this.onKeyPress.bind( this )
12758 } );
12759 }
12760 this.menu.connect( this, {
12761 choose: 'onMenuChoose',
12762 add: 'onMenuItemsChange',
12763 remove: 'onMenuItemsChange'
12764 } );
12765 this.$handle.on( {
12766 click: this.onClick.bind( this )
12767 } );
12768
12769 // Initialization
12770 if ( this.$input ) {
12771 this.$input.prop( 'disabled', this.isDisabled() );
12772 this.$input.attr( {
12773 role: 'combobox',
12774 'aria-autocomplete': 'list'
12775 } );
12776 this.$input.width( '1em' );
12777 }
12778 if ( config.data ) {
12779 this.setItemsFromData( config.data );
12780 }
12781 this.$group.addClass( 'oo-ui-capsuleMultiSelectWidget-group' );
12782 this.$handle.addClass( 'oo-ui-capsuleMultiSelectWidget-handle' )
12783 .append( this.$indicator, this.$icon, this.$group );
12784 this.$element.addClass( 'oo-ui-capsuleMultiSelectWidget' )
12785 .append( this.$handle );
12786 if ( this.popup ) {
12787 this.$handle.append( $tabFocus );
12788 this.$overlay.append( this.popup.$element );
12789 } else {
12790 this.$handle.append( this.$input );
12791 this.$overlay.append( this.menu.$element );
12792 }
12793 this.onMenuItemsChange();
12794 };
12795
12796 /* Setup */
12797
12798 OO.inheritClass( OO.ui.CapsuleMultiSelectWidget, OO.ui.Widget );
12799 OO.mixinClass( OO.ui.CapsuleMultiSelectWidget, OO.ui.mixin.GroupElement );
12800 OO.mixinClass( OO.ui.CapsuleMultiSelectWidget, OO.ui.mixin.PopupElement );
12801 OO.mixinClass( OO.ui.CapsuleMultiSelectWidget, OO.ui.mixin.TabIndexedElement );
12802 OO.mixinClass( OO.ui.CapsuleMultiSelectWidget, OO.ui.mixin.IndicatorElement );
12803 OO.mixinClass( OO.ui.CapsuleMultiSelectWidget, OO.ui.mixin.IconElement );
12804
12805 /* Events */
12806
12807 /**
12808 * @event change
12809 *
12810 * A change event is emitted when the set of selected items changes.
12811 *
12812 * @param {Mixed[]} datas Data of the now-selected items
12813 */
12814
12815 /* Methods */
12816
12817 /**
12818 * Get the data of the items in the capsule
12819 * @return {Mixed[]}
12820 */
12821 OO.ui.CapsuleMultiSelectWidget.prototype.getItemsData = function () {
12822 return $.map( this.getItems(), function ( e ) { return e.data; } );
12823 };
12824
12825 /**
12826 * Set the items in the capsule by providing data
12827 * @chainable
12828 * @param {Mixed[]} datas
12829 * @return {OO.ui.CapsuleMultiSelectWidget}
12830 */
12831 OO.ui.CapsuleMultiSelectWidget.prototype.setItemsFromData = function ( datas ) {
12832 var widget = this,
12833 menu = this.menu,
12834 items = this.getItems();
12835
12836 $.each( datas, function ( i, data ) {
12837 var j, label,
12838 item = menu.getItemFromData( data );
12839
12840 if ( item ) {
12841 label = item.label;
12842 } else if ( widget.allowArbitrary ) {
12843 label = String( data );
12844 } else {
12845 return;
12846 }
12847
12848 item = null;
12849 for ( j = 0; j < items.length; j++ ) {
12850 if ( items[j].data === data && items[j].label === label ) {
12851 item = items[j];
12852 items.splice( j, 1 );
12853 break;
12854 }
12855 }
12856 if ( !item ) {
12857 item = new OO.ui.CapsuleItemWidget( { data: data, label: label } );
12858 }
12859 widget.addItems( [ item ], i );
12860 } );
12861
12862 if ( items.length ) {
12863 widget.removeItems( items );
12864 }
12865
12866 return this;
12867 };
12868
12869 /**
12870 * Add items to the capsule by providing their data
12871 * @chainable
12872 * @param {Mixed[]} datas
12873 * @return {OO.ui.CapsuleMultiSelectWidget}
12874 */
12875 OO.ui.CapsuleMultiSelectWidget.prototype.addItemsFromData = function ( datas ) {
12876 var widget = this,
12877 menu = this.menu,
12878 items = [];
12879
12880 $.each( datas, function ( i, data ) {
12881 var item;
12882
12883 if ( !widget.getItemFromData( data ) ) {
12884 item = menu.getItemFromData( data );
12885 if ( item ) {
12886 items.push( new OO.ui.CapsuleItemWidget( { data: data, label: item.label } ) );
12887 } else if ( widget.allowArbitrary ) {
12888 items.push( new OO.ui.CapsuleItemWidget( { data: data, label: String( data ) } ) );
12889 }
12890 }
12891 } );
12892
12893 if ( items.length ) {
12894 this.addItems( items );
12895 }
12896
12897 return this;
12898 };
12899
12900 /**
12901 * Remove items by data
12902 * @chainable
12903 * @param {Mixed[]} datas
12904 * @return {OO.ui.CapsuleMultiSelectWidget}
12905 */
12906 OO.ui.CapsuleMultiSelectWidget.prototype.removeItemsFromData = function ( datas ) {
12907 var widget = this,
12908 items = [];
12909
12910 $.each( datas, function ( i, data ) {
12911 var item = widget.getItemFromData( data );
12912 if ( item ) {
12913 items.push( item );
12914 }
12915 } );
12916
12917 if ( items.length ) {
12918 this.removeItems( items );
12919 }
12920
12921 return this;
12922 };
12923
12924 /**
12925 * @inheritdoc
12926 */
12927 OO.ui.CapsuleMultiSelectWidget.prototype.addItems = function ( items ) {
12928 var same, i, l,
12929 oldItems = this.items.slice();
12930
12931 OO.ui.mixin.GroupElement.prototype.addItems.call( this, items );
12932
12933 if ( this.items.length !== oldItems.length ) {
12934 same = false;
12935 } else {
12936 same = true;
12937 for ( i = 0, l = oldItems.length; same && i < l; i++ ) {
12938 same = same && this.items[i] === oldItems[i];
12939 }
12940 }
12941 if ( !same ) {
12942 this.emit( 'change', this.getItemsData() );
12943 }
12944
12945 return this;
12946 };
12947
12948 /**
12949 * @inheritdoc
12950 */
12951 OO.ui.CapsuleMultiSelectWidget.prototype.removeItems = function ( items ) {
12952 var same, i, l,
12953 oldItems = this.items.slice();
12954
12955 OO.ui.mixin.GroupElement.prototype.removeItems.call( this, items );
12956
12957 if ( this.items.length !== oldItems.length ) {
12958 same = false;
12959 } else {
12960 same = true;
12961 for ( i = 0, l = oldItems.length; same && i < l; i++ ) {
12962 same = same && this.items[i] === oldItems[i];
12963 }
12964 }
12965 if ( !same ) {
12966 this.emit( 'change', this.getItemsData() );
12967 }
12968
12969 return this;
12970 };
12971
12972 /**
12973 * @inheritdoc
12974 */
12975 OO.ui.CapsuleMultiSelectWidget.prototype.clearItems = function () {
12976 if ( this.items.length ) {
12977 OO.ui.mixin.GroupElement.prototype.clearItems.call( this );
12978 this.emit( 'change', this.getItemsData() );
12979 }
12980 return this;
12981 };
12982
12983 /**
12984 * Get the capsule widget's menu.
12985 * @return {OO.ui.MenuSelectWidget} Menu widget
12986 */
12987 OO.ui.CapsuleMultiSelectWidget.prototype.getMenu = function () {
12988 return this.menu;
12989 };
12990
12991 /**
12992 * Handle focus events
12993 *
12994 * @private
12995 * @param {jQuery.Event} event
12996 */
12997 OO.ui.CapsuleMultiSelectWidget.prototype.onInputFocus = function () {
12998 if ( !this.isDisabled() ) {
12999 this.menu.toggle( true );
13000 }
13001 };
13002
13003 /**
13004 * Handle blur events
13005 *
13006 * @private
13007 * @param {jQuery.Event} event
13008 */
13009 OO.ui.CapsuleMultiSelectWidget.prototype.onInputBlur = function () {
13010 this.clearInput();
13011 };
13012
13013 /**
13014 * Handle focus events
13015 *
13016 * @private
13017 * @param {jQuery.Event} event
13018 */
13019 OO.ui.CapsuleMultiSelectWidget.prototype.onFocusForPopup = function () {
13020 if ( !this.isDisabled() ) {
13021 this.popup.setSize( this.$handle.width() );
13022 this.popup.toggle( true );
13023 this.popup.$element.find( '*' )
13024 .filter( function () { return OO.ui.isFocusableElement( $( this ), true ); } )
13025 .first()
13026 .focus();
13027 }
13028 };
13029
13030 /**
13031 * Handles popup focus out events.
13032 *
13033 * @private
13034 * @param {Event} e Focus out event
13035 */
13036 OO.ui.CapsuleMultiSelectWidget.prototype.onPopupFocusOut = function () {
13037 var widget = this.popup;
13038
13039 setTimeout( function () {
13040 if (
13041 widget.isVisible() &&
13042 !OO.ui.contains( widget.$element[0], document.activeElement, true ) &&
13043 ( !widget.$autoCloseIgnore || !widget.$autoCloseIgnore.has( document.activeElement ).length )
13044 ) {
13045 widget.toggle( false );
13046 }
13047 } );
13048 };
13049
13050 /**
13051 * Handle mouse click events.
13052 *
13053 * @private
13054 * @param {jQuery.Event} e Mouse click event
13055 */
13056 OO.ui.CapsuleMultiSelectWidget.prototype.onClick = function ( e ) {
13057 if ( e.which === 1 ) {
13058 this.focus();
13059 return false;
13060 }
13061 };
13062
13063 /**
13064 * Handle key press events.
13065 *
13066 * @private
13067 * @param {jQuery.Event} e Key press event
13068 */
13069 OO.ui.CapsuleMultiSelectWidget.prototype.onKeyPress = function ( e ) {
13070 var item;
13071
13072 if ( !this.isDisabled() ) {
13073 if ( e.which === OO.ui.Keys.ESCAPE ) {
13074 this.clearInput();
13075 return false;
13076 }
13077
13078 if ( !this.popup ) {
13079 this.menu.toggle( true );
13080 if ( e.which === OO.ui.Keys.ENTER ) {
13081 item = this.menu.getItemFromLabel( this.$input.val(), true );
13082 if ( item ) {
13083 this.addItemsFromData( [ item.data ] );
13084 this.clearInput();
13085 } else if ( this.allowArbitrary && this.$input.val().trim() !== '' ) {
13086 this.addItemsFromData( [ this.$input.val() ] );
13087 this.clearInput();
13088 }
13089 return false;
13090 }
13091
13092 // Make sure the input gets resized.
13093 setTimeout( this.onInputChange.bind( this ), 0 );
13094 }
13095 }
13096 };
13097
13098 /**
13099 * Handle key down events.
13100 *
13101 * @private
13102 * @param {jQuery.Event} e Key down event
13103 */
13104 OO.ui.CapsuleMultiSelectWidget.prototype.onKeyDown = function ( e ) {
13105 if ( !this.isDisabled() ) {
13106 // 'keypress' event is not triggered for Backspace
13107 if ( e.keyCode === OO.ui.Keys.BACKSPACE && this.$input.val() === '' ) {
13108 if ( this.items.length ) {
13109 this.removeItems( this.items.slice( -1 ) );
13110 }
13111 return false;
13112 }
13113 }
13114 };
13115
13116 /**
13117 * Handle input change events.
13118 *
13119 * @private
13120 * @param {jQuery.Event} e Event of some sort
13121 */
13122 OO.ui.CapsuleMultiSelectWidget.prototype.onInputChange = function () {
13123 if ( !this.isDisabled() ) {
13124 this.$input.width( this.$input.val().length + 'em' );
13125 }
13126 };
13127
13128 /**
13129 * Handle menu choose events.
13130 *
13131 * @private
13132 * @param {OO.ui.OptionWidget} item Chosen item
13133 */
13134 OO.ui.CapsuleMultiSelectWidget.prototype.onMenuChoose = function ( item ) {
13135 if ( item && item.isVisible() ) {
13136 this.addItemsFromData( [ item.getData() ] );
13137 this.clearInput();
13138 }
13139 };
13140
13141 /**
13142 * Handle menu item change events.
13143 *
13144 * @private
13145 */
13146 OO.ui.CapsuleMultiSelectWidget.prototype.onMenuItemsChange = function () {
13147 this.setItemsFromData( this.getItemsData() );
13148 this.$element.toggleClass( 'oo-ui-capsuleMultiSelectWidget-empty', this.menu.isEmpty() );
13149 };
13150
13151 /**
13152 * Clear the input field
13153 * @private
13154 */
13155 OO.ui.CapsuleMultiSelectWidget.prototype.clearInput = function () {
13156 if ( this.$input ) {
13157 this.$input.val( '' );
13158 this.$input.width( '1em' );
13159 }
13160 if ( this.popup ) {
13161 this.popup.toggle( false );
13162 }
13163 this.menu.toggle( false );
13164 this.menu.selectItem();
13165 this.menu.highlightItem();
13166 };
13167
13168 /**
13169 * @inheritdoc
13170 */
13171 OO.ui.CapsuleMultiSelectWidget.prototype.setDisabled = function ( disabled ) {
13172 var i, len;
13173
13174 // Parent method
13175 OO.ui.CapsuleMultiSelectWidget.parent.prototype.setDisabled.call( this, disabled );
13176
13177 if ( this.$input ) {
13178 this.$input.prop( 'disabled', this.isDisabled() );
13179 }
13180 if ( this.menu ) {
13181 this.menu.setDisabled( this.isDisabled() );
13182 }
13183 if ( this.popup ) {
13184 this.popup.setDisabled( this.isDisabled() );
13185 }
13186
13187 if ( this.items ) {
13188 for ( i = 0, len = this.items.length; i < len; i++ ) {
13189 this.items[i].updateDisabled();
13190 }
13191 }
13192
13193 return this;
13194 };
13195
13196 /**
13197 * Focus the widget
13198 * @chainable
13199 * @return {OO.ui.CapsuleMultiSelectWidget}
13200 */
13201 OO.ui.CapsuleMultiSelectWidget.prototype.focus = function () {
13202 if ( !this.isDisabled() ) {
13203 if ( this.popup ) {
13204 this.popup.setSize( this.$handle.width() );
13205 this.popup.toggle( true );
13206 this.popup.$element.find( '*' )
13207 .filter( function () { return OO.ui.isFocusableElement( $( this ), true ); } )
13208 .first()
13209 .focus();
13210 } else {
13211 this.menu.toggle( true );
13212 this.$input.focus();
13213 }
13214 }
13215 return this;
13216 };
13217
13218 /**
13219 * CapsuleItemWidgets are used within a {@link OO.ui.CapsuleMultiSelectWidget
13220 * CapsuleMultiSelectWidget} to display the selected items.
13221 *
13222 * @class
13223 * @extends OO.ui.Widget
13224 * @mixins OO.ui.mixin.ItemWidget
13225 * @mixins OO.ui.mixin.IndicatorElement
13226 * @mixins OO.ui.mixin.LabelElement
13227 * @mixins OO.ui.mixin.FlaggedElement
13228 * @mixins OO.ui.mixin.TabIndexedElement
13229 *
13230 * @constructor
13231 * @param {Object} [config] Configuration options
13232 */
13233 OO.ui.CapsuleItemWidget = function OoUiCapsuleItemWidget( config ) {
13234 // Configuration initialization
13235 config = config || {};
13236
13237 // Parent constructor
13238 OO.ui.CapsuleItemWidget.parent.call( this, config );
13239
13240 // Properties (must be set before mixin constructor calls)
13241 this.$indicator = $( '<span>' );
13242
13243 // Mixin constructors
13244 OO.ui.mixin.ItemWidget.call( this );
13245 OO.ui.mixin.IndicatorElement.call( this, $.extend( {}, config, { $indicator: this.$indicator, indicator: 'clear' } ) );
13246 OO.ui.mixin.LabelElement.call( this, config );
13247 OO.ui.mixin.FlaggedElement.call( this, config );
13248 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$indicator } ) );
13249
13250 // Events
13251 this.$indicator.on( {
13252 keydown: this.onCloseKeyDown.bind( this ),
13253 click: this.onCloseClick.bind( this )
13254 } );
13255 this.$element.on( 'click', false );
13256
13257 // Initialization
13258 this.$element
13259 .addClass( 'oo-ui-capsuleItemWidget' )
13260 .append( this.$indicator, this.$label );
13261 };
13262
13263 /* Setup */
13264
13265 OO.inheritClass( OO.ui.CapsuleItemWidget, OO.ui.Widget );
13266 OO.mixinClass( OO.ui.CapsuleItemWidget, OO.ui.mixin.ItemWidget );
13267 OO.mixinClass( OO.ui.CapsuleItemWidget, OO.ui.mixin.IndicatorElement );
13268 OO.mixinClass( OO.ui.CapsuleItemWidget, OO.ui.mixin.LabelElement );
13269 OO.mixinClass( OO.ui.CapsuleItemWidget, OO.ui.mixin.FlaggedElement );
13270 OO.mixinClass( OO.ui.CapsuleItemWidget, OO.ui.mixin.TabIndexedElement );
13271
13272 /* Methods */
13273
13274 /**
13275 * Handle close icon clicks
13276 * @param {jQuery.Event} event
13277 */
13278 OO.ui.CapsuleItemWidget.prototype.onCloseClick = function () {
13279 var element = this.getElementGroup();
13280
13281 if ( !this.isDisabled() && element && $.isFunction( element.removeItems ) ) {
13282 element.removeItems( [ this ] );
13283 element.focus();
13284 }
13285 };
13286
13287 /**
13288 * Handle close keyboard events
13289 * @param {jQuery.Event} event Key down event
13290 */
13291 OO.ui.CapsuleItemWidget.prototype.onCloseKeyDown = function ( e ) {
13292 if ( !this.isDisabled() && $.isFunction( this.getElementGroup().removeItems ) ) {
13293 switch ( e.which ) {
13294 case OO.ui.Keys.ENTER:
13295 case OO.ui.Keys.BACKSPACE:
13296 case OO.ui.Keys.SPACE:
13297 this.getElementGroup().removeItems( [ this ] );
13298 return false;
13299 }
13300 }
13301 };
13302
13303 /**
13304 * DropdownWidgets are not menus themselves, rather they contain a menu of options created with
13305 * OO.ui.MenuOptionWidget. The DropdownWidget takes care of opening and displaying the menu so that
13306 * users can interact with it.
13307 *
13308 * If you want to use this within a HTML form, such as a OO.ui.FormLayout, use
13309 * OO.ui.DropdownInputWidget instead.
13310 *
13311 * @example
13312 * // Example: A DropdownWidget with a menu that contains three options
13313 * var dropDown = new OO.ui.DropdownWidget( {
13314 * label: 'Dropdown menu: Select a menu option',
13315 * menu: {
13316 * items: [
13317 * new OO.ui.MenuOptionWidget( {
13318 * data: 'a',
13319 * label: 'First'
13320 * } ),
13321 * new OO.ui.MenuOptionWidget( {
13322 * data: 'b',
13323 * label: 'Second'
13324 * } ),
13325 * new OO.ui.MenuOptionWidget( {
13326 * data: 'c',
13327 * label: 'Third'
13328 * } )
13329 * ]
13330 * }
13331 * } );
13332 *
13333 * $( 'body' ).append( dropDown.$element );
13334 *
13335 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
13336 *
13337 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
13338 *
13339 * @class
13340 * @extends OO.ui.Widget
13341 * @mixins OO.ui.mixin.IconElement
13342 * @mixins OO.ui.mixin.IndicatorElement
13343 * @mixins OO.ui.mixin.LabelElement
13344 * @mixins OO.ui.mixin.TitledElement
13345 * @mixins OO.ui.mixin.TabIndexedElement
13346 *
13347 * @constructor
13348 * @param {Object} [config] Configuration options
13349 * @cfg {Object} [menu] Configuration options to pass to menu widget
13350 */
13351 OO.ui.DropdownWidget = function OoUiDropdownWidget( config ) {
13352 // Configuration initialization
13353 config = $.extend( { indicator: 'down' }, config );
13354
13355 // Parent constructor
13356 OO.ui.DropdownWidget.parent.call( this, config );
13357
13358 // Properties (must be set before TabIndexedElement constructor call)
13359 this.$handle = this.$( '<span>' );
13360
13361 // Mixin constructors
13362 OO.ui.mixin.IconElement.call( this, config );
13363 OO.ui.mixin.IndicatorElement.call( this, config );
13364 OO.ui.mixin.LabelElement.call( this, config );
13365 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$label } ) );
13366 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$handle } ) );
13367
13368 // Properties
13369 this.menu = new OO.ui.MenuSelectWidget( $.extend( { widget: this }, config.menu ) );
13370
13371 // Events
13372 this.$handle.on( {
13373 click: this.onClick.bind( this ),
13374 keypress: this.onKeyPress.bind( this )
13375 } );
13376 this.menu.connect( this, { select: 'onMenuSelect' } );
13377
13378 // Initialization
13379 this.$handle
13380 .addClass( 'oo-ui-dropdownWidget-handle' )
13381 .append( this.$icon, this.$label, this.$indicator );
13382 this.$element
13383 .addClass( 'oo-ui-dropdownWidget' )
13384 .append( this.$handle, this.menu.$element );
13385 };
13386
13387 /* Setup */
13388
13389 OO.inheritClass( OO.ui.DropdownWidget, OO.ui.Widget );
13390 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.IconElement );
13391 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.IndicatorElement );
13392 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.LabelElement );
13393 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.TitledElement );
13394 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.TabIndexedElement );
13395
13396 /* Methods */
13397
13398 /**
13399 * Get the menu.
13400 *
13401 * @return {OO.ui.MenuSelectWidget} Menu of widget
13402 */
13403 OO.ui.DropdownWidget.prototype.getMenu = function () {
13404 return this.menu;
13405 };
13406
13407 /**
13408 * Handles menu select events.
13409 *
13410 * @private
13411 * @param {OO.ui.MenuOptionWidget} item Selected menu item
13412 */
13413 OO.ui.DropdownWidget.prototype.onMenuSelect = function ( item ) {
13414 var selectedLabel;
13415
13416 if ( !item ) {
13417 this.setLabel( null );
13418 return;
13419 }
13420
13421 selectedLabel = item.getLabel();
13422
13423 // If the label is a DOM element, clone it, because setLabel will append() it
13424 if ( selectedLabel instanceof jQuery ) {
13425 selectedLabel = selectedLabel.clone();
13426 }
13427
13428 this.setLabel( selectedLabel );
13429 };
13430
13431 /**
13432 * Handle mouse click events.
13433 *
13434 * @private
13435 * @param {jQuery.Event} e Mouse click event
13436 */
13437 OO.ui.DropdownWidget.prototype.onClick = function ( e ) {
13438 if ( !this.isDisabled() && e.which === 1 ) {
13439 this.menu.toggle();
13440 }
13441 return false;
13442 };
13443
13444 /**
13445 * Handle key press events.
13446 *
13447 * @private
13448 * @param {jQuery.Event} e Key press event
13449 */
13450 OO.ui.DropdownWidget.prototype.onKeyPress = function ( e ) {
13451 if ( !this.isDisabled() &&
13452 ( ( e.which === OO.ui.Keys.SPACE && !this.menu.isVisible() ) || e.which === OO.ui.Keys.ENTER )
13453 ) {
13454 this.menu.toggle();
13455 return false;
13456 }
13457 };
13458
13459 /**
13460 * SelectFileWidgets allow for selecting files, using the HTML5 File API. These
13461 * widgets can be configured with {@link OO.ui.mixin.IconElement icons} and {@link
13462 * OO.ui.mixin.IndicatorElement indicators}.
13463 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
13464 *
13465 * @example
13466 * // Example of a file select widget
13467 * var selectFile = new OO.ui.SelectFileWidget();
13468 * $( 'body' ).append( selectFile.$element );
13469 *
13470 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets
13471 *
13472 * @class
13473 * @extends OO.ui.Widget
13474 * @mixins OO.ui.mixin.IconElement
13475 * @mixins OO.ui.mixin.IndicatorElement
13476 * @mixins OO.ui.mixin.PendingElement
13477 * @mixins OO.ui.mixin.LabelElement
13478 * @mixins OO.ui.mixin.TabIndexedElement
13479 *
13480 * @constructor
13481 * @param {Object} [config] Configuration options
13482 * @cfg {string[]|null} [accept=null] MIME types to accept. null accepts all types.
13483 * @cfg {string} [placeholder] Text to display when no file is selected.
13484 * @cfg {string} [notsupported] Text to display when file support is missing in the browser.
13485 * @cfg {boolean} [droppable=true] Whether to accept files by drag and drop.
13486 */
13487 OO.ui.SelectFileWidget = function OoUiSelectFileWidget( config ) {
13488 var dragHandler;
13489
13490 // Configuration initialization
13491 config = $.extend( {
13492 accept: null,
13493 placeholder: OO.ui.msg( 'ooui-selectfile-placeholder' ),
13494 notsupported: OO.ui.msg( 'ooui-selectfile-not-supported' ),
13495 droppable: true
13496 }, config );
13497
13498 // Parent constructor
13499 OO.ui.SelectFileWidget.parent.call( this, config );
13500
13501 // Properties (must be set before TabIndexedElement constructor call)
13502 this.$handle = $( '<span>' );
13503
13504 // Mixin constructors
13505 OO.ui.mixin.IconElement.call( this, config );
13506 OO.ui.mixin.IndicatorElement.call( this, config );
13507 OO.ui.mixin.PendingElement.call( this, $.extend( {}, config, { $pending: this.$handle } ) );
13508 OO.ui.mixin.LabelElement.call( this, $.extend( {}, config, { autoFitLabel: true } ) );
13509 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$handle } ) );
13510
13511 // Properties
13512 this.isSupported = this.constructor.static.isSupported();
13513 this.currentFile = null;
13514 if ( Array.isArray( config.accept ) ) {
13515 this.accept = config.accept;
13516 } else {
13517 this.accept = null;
13518 }
13519 this.placeholder = config.placeholder;
13520 this.notsupported = config.notsupported;
13521 this.onFileSelectedHandler = this.onFileSelected.bind( this );
13522
13523 this.clearButton = new OO.ui.ButtonWidget( {
13524 classes: [ 'oo-ui-selectFileWidget-clearButton' ],
13525 framed: false,
13526 icon: 'remove',
13527 disabled: this.disabled
13528 } );
13529
13530 // Events
13531 this.$handle.on( {
13532 keypress: this.onKeyPress.bind( this )
13533 } );
13534 this.clearButton.connect( this, {
13535 click: 'onClearClick'
13536 } );
13537 if ( config.droppable ) {
13538 dragHandler = this.onDragEnterOrOver.bind( this );
13539 this.$handle.on( {
13540 dragenter: dragHandler,
13541 dragover: dragHandler,
13542 dragleave: this.onDragLeave.bind( this ),
13543 drop: this.onDrop.bind( this )
13544 } );
13545 }
13546
13547 // Initialization
13548 this.addInput();
13549 this.updateUI();
13550 this.$label.addClass( 'oo-ui-selectFileWidget-label' );
13551 this.$handle
13552 .addClass( 'oo-ui-selectFileWidget-handle' )
13553 .append( this.$icon, this.$label, this.clearButton.$element, this.$indicator );
13554 this.$element
13555 .addClass( 'oo-ui-selectFileWidget' )
13556 .append( this.$handle );
13557 if ( config.droppable ) {
13558 this.$element.addClass( 'oo-ui-selectFileWidget-droppable' );
13559 }
13560 };
13561
13562 /* Setup */
13563
13564 OO.inheritClass( OO.ui.SelectFileWidget, OO.ui.Widget );
13565 OO.mixinClass( OO.ui.SelectFileWidget, OO.ui.mixin.IconElement );
13566 OO.mixinClass( OO.ui.SelectFileWidget, OO.ui.mixin.IndicatorElement );
13567 OO.mixinClass( OO.ui.SelectFileWidget, OO.ui.mixin.PendingElement );
13568 OO.mixinClass( OO.ui.SelectFileWidget, OO.ui.mixin.LabelElement );
13569 OO.mixinClass( OO.ui.SelectFileWidget, OO.ui.mixin.TabIndexedElement );
13570
13571 /* Static Properties */
13572
13573 /**
13574 * Check if this widget is supported
13575 *
13576 * @static
13577 * @return {boolean}
13578 */
13579 OO.ui.SelectFileWidget.static.isSupported = function () {
13580 var $input;
13581 if ( OO.ui.SelectFileWidget.static.isSupportedCache === null ) {
13582 $input = $( '<input type="file">' );
13583 OO.ui.SelectFileWidget.static.isSupportedCache = $input[0].files !== undefined;
13584 }
13585 return OO.ui.SelectFileWidget.static.isSupportedCache;
13586 };
13587
13588 OO.ui.SelectFileWidget.static.isSupportedCache = null;
13589
13590 /* Events */
13591
13592 /**
13593 * @event change
13594 *
13595 * A change event is emitted when the on/off state of the toggle changes.
13596 *
13597 * @param {File|null} value New value
13598 */
13599
13600 /* Methods */
13601
13602 /**
13603 * Get the current value of the field
13604 *
13605 * @return {File|null}
13606 */
13607 OO.ui.SelectFileWidget.prototype.getValue = function () {
13608 return this.currentFile;
13609 };
13610
13611 /**
13612 * Set the current value of the field
13613 *
13614 * @param {File|null} file File to select
13615 */
13616 OO.ui.SelectFileWidget.prototype.setValue = function ( file ) {
13617 if ( this.currentFile !== file ) {
13618 this.currentFile = file;
13619 this.updateUI();
13620 this.emit( 'change', this.currentFile );
13621 }
13622 };
13623
13624 /**
13625 * Update the user interface when a file is selected or unselected
13626 *
13627 * @protected
13628 */
13629 OO.ui.SelectFileWidget.prototype.updateUI = function () {
13630 if ( !this.isSupported ) {
13631 this.$element.addClass( 'oo-ui-selectFileWidget-notsupported' );
13632 this.$element.removeClass( 'oo-ui-selectFileWidget-empty' );
13633 this.setLabel( this.notsupported );
13634 } else if ( this.currentFile ) {
13635 this.$element.removeClass( 'oo-ui-selectFileWidget-empty' );
13636 this.setLabel( this.currentFile.name +
13637 ( this.currentFile.type !== '' ? OO.ui.msg( 'ooui-semicolon-separator' ) + this.currentFile.type : '' )
13638 );
13639 } else {
13640 this.$element.addClass( 'oo-ui-selectFileWidget-empty' );
13641 this.setLabel( this.placeholder );
13642 }
13643
13644 if ( this.$input ) {
13645 this.$input.attr( 'title', this.getLabel() );
13646 }
13647 };
13648
13649 /**
13650 * Add the input to the handle
13651 *
13652 * @private
13653 */
13654 OO.ui.SelectFileWidget.prototype.addInput = function () {
13655 if ( this.$input ) {
13656 this.$input.remove();
13657 }
13658
13659 if ( !this.isSupported ) {
13660 this.$input = null;
13661 return;
13662 }
13663
13664 this.$input = $( '<input type="file">' );
13665 this.$input.on( 'change', this.onFileSelectedHandler );
13666 this.$input.attr( {
13667 tabindex: -1,
13668 title: this.getLabel()
13669 } );
13670 if ( this.accept ) {
13671 this.$input.attr( 'accept', this.accept.join( ', ' ) );
13672 }
13673 this.$handle.append( this.$input );
13674 };
13675
13676 /**
13677 * Determine if we should accept this file
13678 *
13679 * @private
13680 * @param {File} file
13681 * @return {boolean}
13682 */
13683 OO.ui.SelectFileWidget.prototype.isFileAcceptable = function ( file ) {
13684 var i, mime, mimeTest;
13685
13686 if ( !this.accept || file.type === '' ) {
13687 return true;
13688 }
13689
13690 mime = file.type;
13691 for ( i = 0; i < this.accept.length; i++ ) {
13692 mimeTest = this.accept[i];
13693 if ( mimeTest === mime ) {
13694 return true;
13695 } else if ( mimeTest.substr( -2 ) === '/*' ) {
13696 mimeTest = mimeTest.substr( 0, mimeTest.length - 1 );
13697 if ( mime.substr( 0, mimeTest.length ) === mimeTest ) {
13698 return true;
13699 }
13700 }
13701 }
13702
13703 return false;
13704 };
13705
13706 /**
13707 * Handle file selection from the input
13708 *
13709 * @private
13710 * @param {jQuery.Event} e
13711 */
13712 OO.ui.SelectFileWidget.prototype.onFileSelected = function ( e ) {
13713 var file = null;
13714
13715 if ( e.target.files && e.target.files[0] ) {
13716 file = e.target.files[0];
13717 if ( !this.isFileAcceptable( file ) ) {
13718 file = null;
13719 }
13720 }
13721
13722 this.setValue( file );
13723 this.addInput();
13724 };
13725
13726 /**
13727 * Handle clear button click events.
13728 *
13729 * @private
13730 */
13731 OO.ui.SelectFileWidget.prototype.onClearClick = function () {
13732 this.setValue( null );
13733 return false;
13734 };
13735
13736 /**
13737 * Handle key press events.
13738 *
13739 * @private
13740 * @param {jQuery.Event} e Key press event
13741 */
13742 OO.ui.SelectFileWidget.prototype.onKeyPress = function ( e ) {
13743 if ( this.isSupported && !this.isDisabled() && this.$input &&
13744 ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
13745 ) {
13746 this.$input.click();
13747 return false;
13748 }
13749 };
13750
13751 /**
13752 * Handle drag enter and over events
13753 *
13754 * @private
13755 * @param {jQuery.Event} e Drag event
13756 */
13757 OO.ui.SelectFileWidget.prototype.onDragEnterOrOver = function ( e ) {
13758 var file = null,
13759 dt = e.originalEvent.dataTransfer;
13760
13761 e.preventDefault();
13762 e.stopPropagation();
13763
13764 if ( this.isDisabled() || !this.isSupported ) {
13765 this.$element.removeClass( 'oo-ui-selectFileWidget-canDrop' );
13766 dt.dropEffect = 'none';
13767 return false;
13768 }
13769
13770 if ( dt && dt.files && dt.files[0] ) {
13771 file = dt.files[0];
13772 if ( !this.isFileAcceptable( file ) ) {
13773 file = null;
13774 }
13775 } else if ( dt && dt.types && $.inArray( 'Files', dt.types ) ) {
13776 // We know we have files so set 'file' to something truthy, we just
13777 // can't know any details about them.
13778 // * https://bugzilla.mozilla.org/show_bug.cgi?id=640534
13779 file = 'Files exist, but details are unknown';
13780 }
13781 if ( file ) {
13782 this.$element.addClass( 'oo-ui-selectFileWidget-canDrop' );
13783 } else {
13784 this.$element.removeClass( 'oo-ui-selectFileWidget-canDrop' );
13785 dt.dropEffect = 'none';
13786 }
13787
13788 return false;
13789 };
13790
13791 /**
13792 * Handle drag leave events
13793 *
13794 * @private
13795 * @param {jQuery.Event} e Drag event
13796 */
13797 OO.ui.SelectFileWidget.prototype.onDragLeave = function () {
13798 this.$element.removeClass( 'oo-ui-selectFileWidget-canDrop' );
13799 };
13800
13801 /**
13802 * Handle drop events
13803 *
13804 * @private
13805 * @param {jQuery.Event} e Drop event
13806 */
13807 OO.ui.SelectFileWidget.prototype.onDrop = function ( e ) {
13808 var file = null,
13809 dt = e.originalEvent.dataTransfer;
13810
13811 e.preventDefault();
13812 e.stopPropagation();
13813 this.$element.removeClass( 'oo-ui-selectFileWidget-canDrop' );
13814
13815 if ( this.isDisabled() || !this.isSupported ) {
13816 return false;
13817 }
13818
13819 if ( dt && dt.files && dt.files[0] ) {
13820 file = dt.files[0];
13821 if ( !this.isFileAcceptable( file ) ) {
13822 file = null;
13823 }
13824 }
13825 if ( file ) {
13826 this.setValue( file );
13827 }
13828
13829 return false;
13830 };
13831
13832 /**
13833 * @inheritdoc
13834 */
13835 OO.ui.SelectFileWidget.prototype.setDisabled = function ( state ) {
13836 OO.ui.SelectFileWidget.parent.prototype.setDisabled.call( this, state );
13837 if ( this.clearButton ) {
13838 this.clearButton.setDisabled( state );
13839 }
13840 return this;
13841 };
13842
13843 /**
13844 * IconWidget is a generic widget for {@link OO.ui.mixin.IconElement icons}. In general, IconWidgets should be used with OO.ui.LabelWidget,
13845 * which creates a label that identifies the icon’s function. See the [OOjs UI documentation on MediaWiki] [1]
13846 * for a list of icons included in the library.
13847 *
13848 * @example
13849 * // An icon widget with a label
13850 * var myIcon = new OO.ui.IconWidget( {
13851 * icon: 'help',
13852 * iconTitle: 'Help'
13853 * } );
13854 * // Create a label.
13855 * var iconLabel = new OO.ui.LabelWidget( {
13856 * label: 'Help'
13857 * } );
13858 * $( 'body' ).append( myIcon.$element, iconLabel.$element );
13859 *
13860 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
13861 *
13862 * @class
13863 * @extends OO.ui.Widget
13864 * @mixins OO.ui.mixin.IconElement
13865 * @mixins OO.ui.mixin.TitledElement
13866 * @mixins OO.ui.mixin.FlaggedElement
13867 *
13868 * @constructor
13869 * @param {Object} [config] Configuration options
13870 */
13871 OO.ui.IconWidget = function OoUiIconWidget( config ) {
13872 // Configuration initialization
13873 config = config || {};
13874
13875 // Parent constructor
13876 OO.ui.IconWidget.parent.call( this, config );
13877
13878 // Mixin constructors
13879 OO.ui.mixin.IconElement.call( this, $.extend( {}, config, { $icon: this.$element } ) );
13880 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$element } ) );
13881 OO.ui.mixin.FlaggedElement.call( this, $.extend( {}, config, { $flagged: this.$element } ) );
13882
13883 // Initialization
13884 this.$element.addClass( 'oo-ui-iconWidget' );
13885 };
13886
13887 /* Setup */
13888
13889 OO.inheritClass( OO.ui.IconWidget, OO.ui.Widget );
13890 OO.mixinClass( OO.ui.IconWidget, OO.ui.mixin.IconElement );
13891 OO.mixinClass( OO.ui.IconWidget, OO.ui.mixin.TitledElement );
13892 OO.mixinClass( OO.ui.IconWidget, OO.ui.mixin.FlaggedElement );
13893
13894 /* Static Properties */
13895
13896 OO.ui.IconWidget.static.tagName = 'span';
13897
13898 /**
13899 * IndicatorWidgets create indicators, which are small graphics that are generally used to draw
13900 * attention to the status of an item or to clarify the function of a control. For a list of
13901 * indicators included in the library, please see the [OOjs UI documentation on MediaWiki][1].
13902 *
13903 * @example
13904 * // Example of an indicator widget
13905 * var indicator1 = new OO.ui.IndicatorWidget( {
13906 * indicator: 'alert'
13907 * } );
13908 *
13909 * // Create a fieldset layout to add a label
13910 * var fieldset = new OO.ui.FieldsetLayout();
13911 * fieldset.addItems( [
13912 * new OO.ui.FieldLayout( indicator1, { label: 'An alert indicator:' } )
13913 * ] );
13914 * $( 'body' ).append( fieldset.$element );
13915 *
13916 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
13917 *
13918 * @class
13919 * @extends OO.ui.Widget
13920 * @mixins OO.ui.mixin.IndicatorElement
13921 * @mixins OO.ui.mixin.TitledElement
13922 *
13923 * @constructor
13924 * @param {Object} [config] Configuration options
13925 */
13926 OO.ui.IndicatorWidget = function OoUiIndicatorWidget( config ) {
13927 // Configuration initialization
13928 config = config || {};
13929
13930 // Parent constructor
13931 OO.ui.IndicatorWidget.parent.call( this, config );
13932
13933 // Mixin constructors
13934 OO.ui.mixin.IndicatorElement.call( this, $.extend( {}, config, { $indicator: this.$element } ) );
13935 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$element } ) );
13936
13937 // Initialization
13938 this.$element.addClass( 'oo-ui-indicatorWidget' );
13939 };
13940
13941 /* Setup */
13942
13943 OO.inheritClass( OO.ui.IndicatorWidget, OO.ui.Widget );
13944 OO.mixinClass( OO.ui.IndicatorWidget, OO.ui.mixin.IndicatorElement );
13945 OO.mixinClass( OO.ui.IndicatorWidget, OO.ui.mixin.TitledElement );
13946
13947 /* Static Properties */
13948
13949 OO.ui.IndicatorWidget.static.tagName = 'span';
13950
13951 /**
13952 * InputWidget is the base class for all input widgets, which
13953 * include {@link OO.ui.TextInputWidget text inputs}, {@link OO.ui.CheckboxInputWidget checkbox inputs},
13954 * {@link OO.ui.RadioInputWidget radio inputs}, and {@link OO.ui.ButtonInputWidget button inputs}.
13955 * See the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
13956 *
13957 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
13958 *
13959 * @abstract
13960 * @class
13961 * @extends OO.ui.Widget
13962 * @mixins OO.ui.mixin.FlaggedElement
13963 * @mixins OO.ui.mixin.TabIndexedElement
13964 *
13965 * @constructor
13966 * @param {Object} [config] Configuration options
13967 * @cfg {string} [name=''] The value of the input’s HTML `name` attribute.
13968 * @cfg {string} [value=''] The value of the input.
13969 * @cfg {Function} [inputFilter] The name of an input filter function. Input filters modify the value of an input
13970 * before it is accepted.
13971 */
13972 OO.ui.InputWidget = function OoUiInputWidget( config ) {
13973 // Configuration initialization
13974 config = config || {};
13975
13976 // Parent constructor
13977 OO.ui.InputWidget.parent.call( this, config );
13978
13979 // Properties
13980 this.$input = this.getInputElement( config );
13981 this.value = '';
13982 this.inputFilter = config.inputFilter;
13983
13984 // Mixin constructors
13985 OO.ui.mixin.FlaggedElement.call( this, config );
13986 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$input } ) );
13987
13988 // Events
13989 this.$input.on( 'keydown mouseup cut paste change input select', this.onEdit.bind( this ) );
13990
13991 // Initialization
13992 this.$input
13993 .addClass( 'oo-ui-inputWidget-input' )
13994 .attr( 'name', config.name )
13995 .prop( 'disabled', this.isDisabled() );
13996 this.$element
13997 .addClass( 'oo-ui-inputWidget' )
13998 .append( this.$input );
13999 this.setValue( config.value );
14000 };
14001
14002 /* Setup */
14003
14004 OO.inheritClass( OO.ui.InputWidget, OO.ui.Widget );
14005 OO.mixinClass( OO.ui.InputWidget, OO.ui.mixin.FlaggedElement );
14006 OO.mixinClass( OO.ui.InputWidget, OO.ui.mixin.TabIndexedElement );
14007
14008 /* Static Properties */
14009
14010 OO.ui.InputWidget.static.supportsSimpleLabel = true;
14011
14012 /* Events */
14013
14014 /**
14015 * @event change
14016 *
14017 * A change event is emitted when the value of the input changes.
14018 *
14019 * @param {string} value
14020 */
14021
14022 /* Methods */
14023
14024 /**
14025 * Get input element.
14026 *
14027 * Subclasses of OO.ui.InputWidget use the `config` parameter to produce different elements in
14028 * different circumstances. The element must have a `value` property (like form elements).
14029 *
14030 * @protected
14031 * @param {Object} config Configuration options
14032 * @return {jQuery} Input element
14033 */
14034 OO.ui.InputWidget.prototype.getInputElement = function () {
14035 return $( '<input>' );
14036 };
14037
14038 /**
14039 * Handle potentially value-changing events.
14040 *
14041 * @private
14042 * @param {jQuery.Event} e Key down, mouse up, cut, paste, change, input, or select event
14043 */
14044 OO.ui.InputWidget.prototype.onEdit = function () {
14045 var widget = this;
14046 if ( !this.isDisabled() ) {
14047 // Allow the stack to clear so the value will be updated
14048 setTimeout( function () {
14049 widget.setValue( widget.$input.val() );
14050 } );
14051 }
14052 };
14053
14054 /**
14055 * Get the value of the input.
14056 *
14057 * @return {string} Input value
14058 */
14059 OO.ui.InputWidget.prototype.getValue = function () {
14060 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
14061 // it, and we won't know unless they're kind enough to trigger a 'change' event.
14062 var value = this.$input.val();
14063 if ( this.value !== value ) {
14064 this.setValue( value );
14065 }
14066 return this.value;
14067 };
14068
14069 /**
14070 * Set the direction of the input, either RTL (right-to-left) or LTR (left-to-right).
14071 *
14072 * @param {boolean} isRTL
14073 * Direction is right-to-left
14074 */
14075 OO.ui.InputWidget.prototype.setRTL = function ( isRTL ) {
14076 this.$input.prop( 'dir', isRTL ? 'rtl' : 'ltr' );
14077 };
14078
14079 /**
14080 * Set the value of the input.
14081 *
14082 * @param {string} value New value
14083 * @fires change
14084 * @chainable
14085 */
14086 OO.ui.InputWidget.prototype.setValue = function ( value ) {
14087 value = this.cleanUpValue( value );
14088 // Update the DOM if it has changed. Note that with cleanUpValue, it
14089 // is possible for the DOM value to change without this.value changing.
14090 if ( this.$input.val() !== value ) {
14091 this.$input.val( value );
14092 }
14093 if ( this.value !== value ) {
14094 this.value = value;
14095 this.emit( 'change', this.value );
14096 }
14097 return this;
14098 };
14099
14100 /**
14101 * Clean up incoming value.
14102 *
14103 * Ensures value is a string, and converts undefined and null to empty string.
14104 *
14105 * @private
14106 * @param {string} value Original value
14107 * @return {string} Cleaned up value
14108 */
14109 OO.ui.InputWidget.prototype.cleanUpValue = function ( value ) {
14110 if ( value === undefined || value === null ) {
14111 return '';
14112 } else if ( this.inputFilter ) {
14113 return this.inputFilter( String( value ) );
14114 } else {
14115 return String( value );
14116 }
14117 };
14118
14119 /**
14120 * Simulate the behavior of clicking on a label bound to this input. This method is only called by
14121 * {@link OO.ui.LabelWidget LabelWidget} and {@link OO.ui.FieldLayout FieldLayout}. It should not be
14122 * called directly.
14123 */
14124 OO.ui.InputWidget.prototype.simulateLabelClick = function () {
14125 if ( !this.isDisabled() ) {
14126 if ( this.$input.is( ':checkbox, :radio' ) ) {
14127 this.$input.click();
14128 }
14129 if ( this.$input.is( ':input' ) ) {
14130 this.$input[ 0 ].focus();
14131 }
14132 }
14133 };
14134
14135 /**
14136 * @inheritdoc
14137 */
14138 OO.ui.InputWidget.prototype.setDisabled = function ( state ) {
14139 OO.ui.InputWidget.parent.prototype.setDisabled.call( this, state );
14140 if ( this.$input ) {
14141 this.$input.prop( 'disabled', this.isDisabled() );
14142 }
14143 return this;
14144 };
14145
14146 /**
14147 * Focus the input.
14148 *
14149 * @chainable
14150 */
14151 OO.ui.InputWidget.prototype.focus = function () {
14152 this.$input[ 0 ].focus();
14153 return this;
14154 };
14155
14156 /**
14157 * Blur the input.
14158 *
14159 * @chainable
14160 */
14161 OO.ui.InputWidget.prototype.blur = function () {
14162 this.$input[ 0 ].blur();
14163 return this;
14164 };
14165
14166 /**
14167 * @inheritdoc
14168 */
14169 OO.ui.InputWidget.prototype.gatherPreInfuseState = function ( node ) {
14170 var
14171 state = OO.ui.InputWidget.parent.prototype.gatherPreInfuseState.call( this, node ),
14172 $input = state.$input || $( node ).find( '.oo-ui-inputWidget-input' );
14173 state.value = $input.val();
14174 // Might be better in TabIndexedElement, but it's awkward to do there because mixins are awkward
14175 state.focus = $input.is( ':focus' );
14176 return state;
14177 };
14178
14179 /**
14180 * @inheritdoc
14181 */
14182 OO.ui.InputWidget.prototype.restorePreInfuseState = function ( state ) {
14183 OO.ui.InputWidget.parent.prototype.restorePreInfuseState.call( this, state );
14184 if ( state.value !== undefined && state.value !== this.getValue() ) {
14185 this.setValue( state.value );
14186 }
14187 if ( state.focus ) {
14188 this.focus();
14189 }
14190 };
14191
14192 /**
14193 * ButtonInputWidget is used to submit HTML forms and is intended to be used within
14194 * a OO.ui.FormLayout. If you do not need the button to work with HTML forms, you probably
14195 * want to use OO.ui.ButtonWidget instead. Button input widgets can be rendered as either an
14196 * HTML `<button/>` (the default) or an HTML `<input/>` tags. See the
14197 * [OOjs UI documentation on MediaWiki] [1] for more information.
14198 *
14199 * @example
14200 * // A ButtonInputWidget rendered as an HTML button, the default.
14201 * var button = new OO.ui.ButtonInputWidget( {
14202 * label: 'Input button',
14203 * icon: 'check',
14204 * value: 'check'
14205 * } );
14206 * $( 'body' ).append( button.$element );
14207 *
14208 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs#Button_inputs
14209 *
14210 * @class
14211 * @extends OO.ui.InputWidget
14212 * @mixins OO.ui.mixin.ButtonElement
14213 * @mixins OO.ui.mixin.IconElement
14214 * @mixins OO.ui.mixin.IndicatorElement
14215 * @mixins OO.ui.mixin.LabelElement
14216 * @mixins OO.ui.mixin.TitledElement
14217 *
14218 * @constructor
14219 * @param {Object} [config] Configuration options
14220 * @cfg {string} [type='button'] The value of the HTML `'type'` attribute: 'button', 'submit' or 'reset'.
14221 * @cfg {boolean} [useInputTag=false] Use an `<input/>` tag instead of a `<button/>` tag, the default.
14222 * Widgets configured to be an `<input/>` do not support {@link #icon icons} and {@link #indicator indicators},
14223 * non-plaintext {@link #label labels}, or {@link #value values}. In general, useInputTag should only
14224 * be set to `true` when there’s need to support IE6 in a form with multiple buttons.
14225 */
14226 OO.ui.ButtonInputWidget = function OoUiButtonInputWidget( config ) {
14227 // Configuration initialization
14228 config = $.extend( { type: 'button', useInputTag: false }, config );
14229
14230 // Properties (must be set before parent constructor, which calls #setValue)
14231 this.useInputTag = config.useInputTag;
14232
14233 // Parent constructor
14234 OO.ui.ButtonInputWidget.parent.call( this, config );
14235
14236 // Mixin constructors
14237 OO.ui.mixin.ButtonElement.call( this, $.extend( {}, config, { $button: this.$input } ) );
14238 OO.ui.mixin.IconElement.call( this, config );
14239 OO.ui.mixin.IndicatorElement.call( this, config );
14240 OO.ui.mixin.LabelElement.call( this, config );
14241 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$input } ) );
14242
14243 // Initialization
14244 if ( !config.useInputTag ) {
14245 this.$input.append( this.$icon, this.$label, this.$indicator );
14246 }
14247 this.$element.addClass( 'oo-ui-buttonInputWidget' );
14248 };
14249
14250 /* Setup */
14251
14252 OO.inheritClass( OO.ui.ButtonInputWidget, OO.ui.InputWidget );
14253 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.ButtonElement );
14254 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.IconElement );
14255 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.IndicatorElement );
14256 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.LabelElement );
14257 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.TitledElement );
14258
14259 /* Static Properties */
14260
14261 /**
14262 * Disable generating `<label>` elements for buttons. One would very rarely need additional label
14263 * for a button, and it's already a big clickable target, and it causes unexpected rendering.
14264 */
14265 OO.ui.ButtonInputWidget.static.supportsSimpleLabel = false;
14266
14267 /* Methods */
14268
14269 /**
14270 * @inheritdoc
14271 * @protected
14272 */
14273 OO.ui.ButtonInputWidget.prototype.getInputElement = function ( config ) {
14274 var type = [ 'button', 'submit', 'reset' ].indexOf( config.type ) !== -1 ?
14275 config.type :
14276 'button';
14277 return $( '<' + ( config.useInputTag ? 'input' : 'button' ) + ' type="' + type + '">' );
14278 };
14279
14280 /**
14281 * Set label value.
14282 *
14283 * If #useInputTag is `true`, the label is set as the `value` of the `<input/>` tag.
14284 *
14285 * @param {jQuery|string|Function|null} label Label nodes, text, a function that returns nodes or
14286 * text, or `null` for no label
14287 * @chainable
14288 */
14289 OO.ui.ButtonInputWidget.prototype.setLabel = function ( label ) {
14290 OO.ui.mixin.LabelElement.prototype.setLabel.call( this, label );
14291
14292 if ( this.useInputTag ) {
14293 if ( typeof label === 'function' ) {
14294 label = OO.ui.resolveMsg( label );
14295 }
14296 if ( label instanceof jQuery ) {
14297 label = label.text();
14298 }
14299 if ( !label ) {
14300 label = '';
14301 }
14302 this.$input.val( label );
14303 }
14304
14305 return this;
14306 };
14307
14308 /**
14309 * Set the value of the input.
14310 *
14311 * This method is disabled for button inputs configured as {@link #useInputTag <input/> tags}, as
14312 * they do not support {@link #value values}.
14313 *
14314 * @param {string} value New value
14315 * @chainable
14316 */
14317 OO.ui.ButtonInputWidget.prototype.setValue = function ( value ) {
14318 if ( !this.useInputTag ) {
14319 OO.ui.ButtonInputWidget.parent.prototype.setValue.call( this, value );
14320 }
14321 return this;
14322 };
14323
14324 /**
14325 * CheckboxInputWidgets, like HTML checkboxes, can be selected and/or configured with a value.
14326 * Note that these {@link OO.ui.InputWidget input widgets} are best laid out
14327 * in {@link OO.ui.FieldLayout field layouts} that use the {@link OO.ui.FieldLayout#align inline}
14328 * alignment. For more information, please see the [OOjs UI documentation on MediaWiki][1].
14329 *
14330 * This widget can be used inside a HTML form, such as a OO.ui.FormLayout.
14331 *
14332 * @example
14333 * // An example of selected, unselected, and disabled checkbox inputs
14334 * var checkbox1=new OO.ui.CheckboxInputWidget( {
14335 * value: 'a',
14336 * selected: true
14337 * } );
14338 * var checkbox2=new OO.ui.CheckboxInputWidget( {
14339 * value: 'b'
14340 * } );
14341 * var checkbox3=new OO.ui.CheckboxInputWidget( {
14342 * value:'c',
14343 * disabled: true
14344 * } );
14345 * // Create a fieldset layout with fields for each checkbox.
14346 * var fieldset = new OO.ui.FieldsetLayout( {
14347 * label: 'Checkboxes'
14348 * } );
14349 * fieldset.addItems( [
14350 * new OO.ui.FieldLayout( checkbox1, { label: 'Selected checkbox', align: 'inline' } ),
14351 * new OO.ui.FieldLayout( checkbox2, { label: 'Unselected checkbox', align: 'inline' } ),
14352 * new OO.ui.FieldLayout( checkbox3, { label: 'Disabled checkbox', align: 'inline' } ),
14353 * ] );
14354 * $( 'body' ).append( fieldset.$element );
14355 *
14356 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
14357 *
14358 * @class
14359 * @extends OO.ui.InputWidget
14360 *
14361 * @constructor
14362 * @param {Object} [config] Configuration options
14363 * @cfg {boolean} [selected=false] Select the checkbox initially. By default, the checkbox is not selected.
14364 */
14365 OO.ui.CheckboxInputWidget = function OoUiCheckboxInputWidget( config ) {
14366 // Configuration initialization
14367 config = config || {};
14368
14369 // Parent constructor
14370 OO.ui.CheckboxInputWidget.parent.call( this, config );
14371
14372 // Initialization
14373 this.$element
14374 .addClass( 'oo-ui-checkboxInputWidget' )
14375 // Required for pretty styling in MediaWiki theme
14376 .append( $( '<span>' ) );
14377 this.setSelected( config.selected !== undefined ? config.selected : false );
14378 };
14379
14380 /* Setup */
14381
14382 OO.inheritClass( OO.ui.CheckboxInputWidget, OO.ui.InputWidget );
14383
14384 /* Methods */
14385
14386 /**
14387 * @inheritdoc
14388 * @protected
14389 */
14390 OO.ui.CheckboxInputWidget.prototype.getInputElement = function () {
14391 return $( '<input type="checkbox" />' );
14392 };
14393
14394 /**
14395 * @inheritdoc
14396 */
14397 OO.ui.CheckboxInputWidget.prototype.onEdit = function () {
14398 var widget = this;
14399 if ( !this.isDisabled() ) {
14400 // Allow the stack to clear so the value will be updated
14401 setTimeout( function () {
14402 widget.setSelected( widget.$input.prop( 'checked' ) );
14403 } );
14404 }
14405 };
14406
14407 /**
14408 * Set selection state of this checkbox.
14409 *
14410 * @param {boolean} state `true` for selected
14411 * @chainable
14412 */
14413 OO.ui.CheckboxInputWidget.prototype.setSelected = function ( state ) {
14414 state = !!state;
14415 if ( this.selected !== state ) {
14416 this.selected = state;
14417 this.$input.prop( 'checked', this.selected );
14418 this.emit( 'change', this.selected );
14419 }
14420 return this;
14421 };
14422
14423 /**
14424 * Check if this checkbox is selected.
14425 *
14426 * @return {boolean} Checkbox is selected
14427 */
14428 OO.ui.CheckboxInputWidget.prototype.isSelected = function () {
14429 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
14430 // it, and we won't know unless they're kind enough to trigger a 'change' event.
14431 var selected = this.$input.prop( 'checked' );
14432 if ( this.selected !== selected ) {
14433 this.setSelected( selected );
14434 }
14435 return this.selected;
14436 };
14437
14438 /**
14439 * @inheritdoc
14440 */
14441 OO.ui.CheckboxInputWidget.prototype.gatherPreInfuseState = function ( node ) {
14442 var
14443 state = OO.ui.CheckboxInputWidget.parent.prototype.gatherPreInfuseState.call( this, node ),
14444 $input = $( node ).find( '.oo-ui-inputWidget-input' );
14445 state.$input = $input; // shortcut for performance, used in InputWidget
14446 state.checked = $input.prop( 'checked' );
14447 return state;
14448 };
14449
14450 /**
14451 * @inheritdoc
14452 */
14453 OO.ui.CheckboxInputWidget.prototype.restorePreInfuseState = function ( state ) {
14454 OO.ui.CheckboxInputWidget.parent.prototype.restorePreInfuseState.call( this, state );
14455 if ( state.checked !== undefined && state.checked !== this.isSelected() ) {
14456 this.setSelected( state.checked );
14457 }
14458 };
14459
14460 /**
14461 * DropdownInputWidget is a {@link OO.ui.DropdownWidget DropdownWidget} intended to be used
14462 * within a HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with the value
14463 * of a hidden HTML `input` tag. Please see the [OOjs UI documentation on MediaWiki][1] for
14464 * more information about input widgets.
14465 *
14466 * A DropdownInputWidget always has a value (one of the options is always selected), unless there
14467 * are no options. If no `value` configuration option is provided, the first option is selected.
14468 * If you need a state representing no value (no option being selected), use a DropdownWidget.
14469 *
14470 * This and OO.ui.RadioSelectInputWidget support the same configuration options.
14471 *
14472 * @example
14473 * // Example: A DropdownInputWidget with three options
14474 * var dropdownInput = new OO.ui.DropdownInputWidget( {
14475 * options: [
14476 * { data: 'a', label: 'First' },
14477 * { data: 'b', label: 'Second'},
14478 * { data: 'c', label: 'Third' }
14479 * ]
14480 * } );
14481 * $( 'body' ).append( dropdownInput.$element );
14482 *
14483 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
14484 *
14485 * @class
14486 * @extends OO.ui.InputWidget
14487 * @mixins OO.ui.mixin.TitledElement
14488 *
14489 * @constructor
14490 * @param {Object} [config] Configuration options
14491 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
14492 */
14493 OO.ui.DropdownInputWidget = function OoUiDropdownInputWidget( config ) {
14494 // Configuration initialization
14495 config = config || {};
14496
14497 // Properties (must be done before parent constructor which calls #setDisabled)
14498 this.dropdownWidget = new OO.ui.DropdownWidget();
14499
14500 // Parent constructor
14501 OO.ui.DropdownInputWidget.parent.call( this, config );
14502
14503 // Mixin constructors
14504 OO.ui.mixin.TitledElement.call( this, config );
14505
14506 // Events
14507 this.dropdownWidget.getMenu().connect( this, { select: 'onMenuSelect' } );
14508
14509 // Initialization
14510 this.setOptions( config.options || [] );
14511 this.$element
14512 .addClass( 'oo-ui-dropdownInputWidget' )
14513 .append( this.dropdownWidget.$element );
14514 };
14515
14516 /* Setup */
14517
14518 OO.inheritClass( OO.ui.DropdownInputWidget, OO.ui.InputWidget );
14519 OO.mixinClass( OO.ui.DropdownInputWidget, OO.ui.mixin.TitledElement );
14520
14521 /* Methods */
14522
14523 /**
14524 * @inheritdoc
14525 * @protected
14526 */
14527 OO.ui.DropdownInputWidget.prototype.getInputElement = function () {
14528 return $( '<input type="hidden">' );
14529 };
14530
14531 /**
14532 * Handles menu select events.
14533 *
14534 * @private
14535 * @param {OO.ui.MenuOptionWidget} item Selected menu item
14536 */
14537 OO.ui.DropdownInputWidget.prototype.onMenuSelect = function ( item ) {
14538 this.setValue( item.getData() );
14539 };
14540
14541 /**
14542 * @inheritdoc
14543 */
14544 OO.ui.DropdownInputWidget.prototype.setValue = function ( value ) {
14545 value = this.cleanUpValue( value );
14546 this.dropdownWidget.getMenu().selectItemByData( value );
14547 OO.ui.DropdownInputWidget.parent.prototype.setValue.call( this, value );
14548 return this;
14549 };
14550
14551 /**
14552 * @inheritdoc
14553 */
14554 OO.ui.DropdownInputWidget.prototype.setDisabled = function ( state ) {
14555 this.dropdownWidget.setDisabled( state );
14556 OO.ui.DropdownInputWidget.parent.prototype.setDisabled.call( this, state );
14557 return this;
14558 };
14559
14560 /**
14561 * Set the options available for this input.
14562 *
14563 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
14564 * @chainable
14565 */
14566 OO.ui.DropdownInputWidget.prototype.setOptions = function ( options ) {
14567 var
14568 value = this.getValue(),
14569 widget = this;
14570
14571 // Rebuild the dropdown menu
14572 this.dropdownWidget.getMenu()
14573 .clearItems()
14574 .addItems( options.map( function ( opt ) {
14575 var optValue = widget.cleanUpValue( opt.data );
14576 return new OO.ui.MenuOptionWidget( {
14577 data: optValue,
14578 label: opt.label !== undefined ? opt.label : optValue
14579 } );
14580 } ) );
14581
14582 // Restore the previous value, or reset to something sensible
14583 if ( this.dropdownWidget.getMenu().getItemFromData( value ) ) {
14584 // Previous value is still available, ensure consistency with the dropdown
14585 this.setValue( value );
14586 } else {
14587 // No longer valid, reset
14588 if ( options.length ) {
14589 this.setValue( options[ 0 ].data );
14590 }
14591 }
14592
14593 return this;
14594 };
14595
14596 /**
14597 * @inheritdoc
14598 */
14599 OO.ui.DropdownInputWidget.prototype.focus = function () {
14600 this.dropdownWidget.getMenu().toggle( true );
14601 return this;
14602 };
14603
14604 /**
14605 * @inheritdoc
14606 */
14607 OO.ui.DropdownInputWidget.prototype.blur = function () {
14608 this.dropdownWidget.getMenu().toggle( false );
14609 return this;
14610 };
14611
14612 /**
14613 * RadioInputWidget creates a single radio button. Because radio buttons are usually used as a set,
14614 * in most cases you will want to use a {@link OO.ui.RadioSelectWidget radio select}
14615 * with {@link OO.ui.RadioOptionWidget radio options} instead of this class. For more information,
14616 * please see the [OOjs UI documentation on MediaWiki][1].
14617 *
14618 * This widget can be used inside a HTML form, such as a OO.ui.FormLayout.
14619 *
14620 * @example
14621 * // An example of selected, unselected, and disabled radio inputs
14622 * var radio1 = new OO.ui.RadioInputWidget( {
14623 * value: 'a',
14624 * selected: true
14625 * } );
14626 * var radio2 = new OO.ui.RadioInputWidget( {
14627 * value: 'b'
14628 * } );
14629 * var radio3 = new OO.ui.RadioInputWidget( {
14630 * value: 'c',
14631 * disabled: true
14632 * } );
14633 * // Create a fieldset layout with fields for each radio button.
14634 * var fieldset = new OO.ui.FieldsetLayout( {
14635 * label: 'Radio inputs'
14636 * } );
14637 * fieldset.addItems( [
14638 * new OO.ui.FieldLayout( radio1, { label: 'Selected', align: 'inline' } ),
14639 * new OO.ui.FieldLayout( radio2, { label: 'Unselected', align: 'inline' } ),
14640 * new OO.ui.FieldLayout( radio3, { label: 'Disabled', align: 'inline' } ),
14641 * ] );
14642 * $( 'body' ).append( fieldset.$element );
14643 *
14644 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
14645 *
14646 * @class
14647 * @extends OO.ui.InputWidget
14648 *
14649 * @constructor
14650 * @param {Object} [config] Configuration options
14651 * @cfg {boolean} [selected=false] Select the radio button initially. By default, the radio button is not selected.
14652 */
14653 OO.ui.RadioInputWidget = function OoUiRadioInputWidget( config ) {
14654 // Configuration initialization
14655 config = config || {};
14656
14657 // Parent constructor
14658 OO.ui.RadioInputWidget.parent.call( this, config );
14659
14660 // Initialization
14661 this.$element
14662 .addClass( 'oo-ui-radioInputWidget' )
14663 // Required for pretty styling in MediaWiki theme
14664 .append( $( '<span>' ) );
14665 this.setSelected( config.selected !== undefined ? config.selected : false );
14666 };
14667
14668 /* Setup */
14669
14670 OO.inheritClass( OO.ui.RadioInputWidget, OO.ui.InputWidget );
14671
14672 /* Methods */
14673
14674 /**
14675 * @inheritdoc
14676 * @protected
14677 */
14678 OO.ui.RadioInputWidget.prototype.getInputElement = function () {
14679 return $( '<input type="radio" />' );
14680 };
14681
14682 /**
14683 * @inheritdoc
14684 */
14685 OO.ui.RadioInputWidget.prototype.onEdit = function () {
14686 // RadioInputWidget doesn't track its state.
14687 };
14688
14689 /**
14690 * Set selection state of this radio button.
14691 *
14692 * @param {boolean} state `true` for selected
14693 * @chainable
14694 */
14695 OO.ui.RadioInputWidget.prototype.setSelected = function ( state ) {
14696 // RadioInputWidget doesn't track its state.
14697 this.$input.prop( 'checked', state );
14698 return this;
14699 };
14700
14701 /**
14702 * Check if this radio button is selected.
14703 *
14704 * @return {boolean} Radio is selected
14705 */
14706 OO.ui.RadioInputWidget.prototype.isSelected = function () {
14707 return this.$input.prop( 'checked' );
14708 };
14709
14710 /**
14711 * @inheritdoc
14712 */
14713 OO.ui.RadioInputWidget.prototype.gatherPreInfuseState = function ( node ) {
14714 var
14715 state = OO.ui.RadioInputWidget.parent.prototype.gatherPreInfuseState.call( this, node ),
14716 $input = $( node ).find( '.oo-ui-inputWidget-input' );
14717 state.$input = $input; // shortcut for performance, used in InputWidget
14718 state.checked = $input.prop( 'checked' );
14719 return state;
14720 };
14721
14722 /**
14723 * @inheritdoc
14724 */
14725 OO.ui.RadioInputWidget.prototype.restorePreInfuseState = function ( state ) {
14726 OO.ui.RadioInputWidget.parent.prototype.restorePreInfuseState.call( this, state );
14727 if ( state.checked !== undefined && state.checked !== this.isSelected() ) {
14728 this.setSelected( state.checked );
14729 }
14730 };
14731
14732 /**
14733 * RadioSelectInputWidget is a {@link OO.ui.RadioSelectWidget RadioSelectWidget} intended to be used
14734 * within a HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with the value
14735 * of a hidden HTML `input` tag. Please see the [OOjs UI documentation on MediaWiki][1] for
14736 * more information about input widgets.
14737 *
14738 * This and OO.ui.DropdownInputWidget support the same configuration options.
14739 *
14740 * @example
14741 * // Example: A RadioSelectInputWidget with three options
14742 * var radioSelectInput = new OO.ui.RadioSelectInputWidget( {
14743 * options: [
14744 * { data: 'a', label: 'First' },
14745 * { data: 'b', label: 'Second'},
14746 * { data: 'c', label: 'Third' }
14747 * ]
14748 * } );
14749 * $( 'body' ).append( radioSelectInput.$element );
14750 *
14751 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
14752 *
14753 * @class
14754 * @extends OO.ui.InputWidget
14755 *
14756 * @constructor
14757 * @param {Object} [config] Configuration options
14758 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
14759 */
14760 OO.ui.RadioSelectInputWidget = function OoUiRadioSelectInputWidget( config ) {
14761 // Configuration initialization
14762 config = config || {};
14763
14764 // Properties (must be done before parent constructor which calls #setDisabled)
14765 this.radioSelectWidget = new OO.ui.RadioSelectWidget();
14766
14767 // Parent constructor
14768 OO.ui.RadioSelectInputWidget.parent.call( this, config );
14769
14770 // Events
14771 this.radioSelectWidget.connect( this, { select: 'onMenuSelect' } );
14772
14773 // Initialization
14774 this.setOptions( config.options || [] );
14775 this.$element
14776 .addClass( 'oo-ui-radioSelectInputWidget' )
14777 .append( this.radioSelectWidget.$element );
14778 };
14779
14780 /* Setup */
14781
14782 OO.inheritClass( OO.ui.RadioSelectInputWidget, OO.ui.InputWidget );
14783
14784 /* Static Properties */
14785
14786 OO.ui.RadioSelectInputWidget.static.supportsSimpleLabel = false;
14787
14788 /* Methods */
14789
14790 /**
14791 * @inheritdoc
14792 * @protected
14793 */
14794 OO.ui.RadioSelectInputWidget.prototype.getInputElement = function () {
14795 return $( '<input type="hidden">' );
14796 };
14797
14798 /**
14799 * Handles menu select events.
14800 *
14801 * @private
14802 * @param {OO.ui.RadioOptionWidget} item Selected menu item
14803 */
14804 OO.ui.RadioSelectInputWidget.prototype.onMenuSelect = function ( item ) {
14805 this.setValue( item.getData() );
14806 };
14807
14808 /**
14809 * @inheritdoc
14810 */
14811 OO.ui.RadioSelectInputWidget.prototype.setValue = function ( value ) {
14812 value = this.cleanUpValue( value );
14813 this.radioSelectWidget.selectItemByData( value );
14814 OO.ui.RadioSelectInputWidget.parent.prototype.setValue.call( this, value );
14815 return this;
14816 };
14817
14818 /**
14819 * @inheritdoc
14820 */
14821 OO.ui.RadioSelectInputWidget.prototype.setDisabled = function ( state ) {
14822 this.radioSelectWidget.setDisabled( state );
14823 OO.ui.RadioSelectInputWidget.parent.prototype.setDisabled.call( this, state );
14824 return this;
14825 };
14826
14827 /**
14828 * Set the options available for this input.
14829 *
14830 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
14831 * @chainable
14832 */
14833 OO.ui.RadioSelectInputWidget.prototype.setOptions = function ( options ) {
14834 var
14835 value = this.getValue(),
14836 widget = this;
14837
14838 // Rebuild the radioSelect menu
14839 this.radioSelectWidget
14840 .clearItems()
14841 .addItems( options.map( function ( opt ) {
14842 var optValue = widget.cleanUpValue( opt.data );
14843 return new OO.ui.RadioOptionWidget( {
14844 data: optValue,
14845 label: opt.label !== undefined ? opt.label : optValue
14846 } );
14847 } ) );
14848
14849 // Restore the previous value, or reset to something sensible
14850 if ( this.radioSelectWidget.getItemFromData( value ) ) {
14851 // Previous value is still available, ensure consistency with the radioSelect
14852 this.setValue( value );
14853 } else {
14854 // No longer valid, reset
14855 if ( options.length ) {
14856 this.setValue( options[ 0 ].data );
14857 }
14858 }
14859
14860 return this;
14861 };
14862
14863 /**
14864 * @inheritdoc
14865 */
14866 OO.ui.RadioSelectInputWidget.prototype.gatherPreInfuseState = function ( node ) {
14867 var state = OO.ui.RadioSelectInputWidget.parent.prototype.gatherPreInfuseState.call( this, node );
14868 state.value = $( node ).find( '.oo-ui-radioInputWidget .oo-ui-inputWidget-input:checked' ).val();
14869 return state;
14870 };
14871
14872 /**
14873 * TextInputWidgets, like HTML text inputs, can be configured with options that customize the
14874 * size of the field as well as its presentation. In addition, these widgets can be configured
14875 * with {@link OO.ui.mixin.IconElement icons}, {@link OO.ui.mixin.IndicatorElement indicators}, an optional
14876 * validation-pattern (used to determine if an input value is valid or not) and an input filter,
14877 * which modifies incoming values rather than validating them.
14878 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
14879 *
14880 * This widget can be used inside a HTML form, such as a OO.ui.FormLayout.
14881 *
14882 * @example
14883 * // Example of a text input widget
14884 * var textInput = new OO.ui.TextInputWidget( {
14885 * value: 'Text input'
14886 * } )
14887 * $( 'body' ).append( textInput.$element );
14888 *
14889 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
14890 *
14891 * @class
14892 * @extends OO.ui.InputWidget
14893 * @mixins OO.ui.mixin.IconElement
14894 * @mixins OO.ui.mixin.IndicatorElement
14895 * @mixins OO.ui.mixin.PendingElement
14896 * @mixins OO.ui.mixin.LabelElement
14897 *
14898 * @constructor
14899 * @param {Object} [config] Configuration options
14900 * @cfg {string} [type='text'] The value of the HTML `type` attribute: 'text', 'password', 'search',
14901 * 'email' or 'url'. Ignored if `multiline` is true.
14902 *
14903 * Some values of `type` result in additional behaviors:
14904 *
14905 * - `search`: implies `icon: 'search'` and `indicator: 'clear'`; when clicked, the indicator
14906 * empties the text field
14907 * @cfg {string} [placeholder] Placeholder text
14908 * @cfg {boolean} [autofocus=false] Use an HTML `autofocus` attribute to
14909 * instruct the browser to focus this widget.
14910 * @cfg {boolean} [readOnly=false] Prevent changes to the value of the text input.
14911 * @cfg {number} [maxLength] Maximum number of characters allowed in the input.
14912 * @cfg {boolean} [multiline=false] Allow multiple lines of text
14913 * @cfg {number} [rows] If multiline, number of visible lines in textarea. If used with `autosize`,
14914 * specifies minimum number of rows to display.
14915 * @cfg {boolean} [autosize=false] Automatically resize the text input to fit its content.
14916 * Use the #maxRows config to specify a maximum number of displayed rows.
14917 * @cfg {boolean} [maxRows] Maximum number of rows to display when #autosize is set to true.
14918 * Defaults to the maximum of `10` and `2 * rows`, or `10` if `rows` isn't provided.
14919 * @cfg {string} [labelPosition='after'] The position of the inline label relative to that of
14920 * the value or placeholder text: `'before'` or `'after'`
14921 * @cfg {boolean} [required=false] Mark the field as required. Implies `indicator: 'required'`.
14922 * @cfg {boolean} [autocomplete=true] Should the browser support autocomplete for this field
14923 * @cfg {RegExp|Function|string} [validate] Validation pattern: when string, a symbolic name of a
14924 * pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer'
14925 * (the value must contain only numbers); when RegExp, a regular expression that must match the
14926 * value for it to be considered valid; when Function, a function receiving the value as parameter
14927 * that must return true, or promise that resolves, for it to be considered valid.
14928 */
14929 OO.ui.TextInputWidget = function OoUiTextInputWidget( config ) {
14930 // Configuration initialization
14931 config = $.extend( {
14932 type: 'text',
14933 labelPosition: 'after'
14934 }, config );
14935 if ( config.type === 'search' ) {
14936 if ( config.icon === undefined ) {
14937 config.icon = 'search';
14938 }
14939 // indicator: 'clear' is set dynamically later, depending on value
14940 }
14941 if ( config.required ) {
14942 if ( config.indicator === undefined ) {
14943 config.indicator = 'required';
14944 }
14945 }
14946
14947 // Parent constructor
14948 OO.ui.TextInputWidget.parent.call( this, config );
14949
14950 // Mixin constructors
14951 OO.ui.mixin.IconElement.call( this, config );
14952 OO.ui.mixin.IndicatorElement.call( this, config );
14953 OO.ui.mixin.PendingElement.call( this, $.extend( {}, config, { $pending: this.$input } ) );
14954 OO.ui.mixin.LabelElement.call( this, config );
14955
14956 // Properties
14957 this.type = this.getSaneType( config );
14958 this.readOnly = false;
14959 this.multiline = !!config.multiline;
14960 this.autosize = !!config.autosize;
14961 this.minRows = config.rows !== undefined ? config.rows : '';
14962 this.maxRows = config.maxRows || Math.max( 2 * ( this.minRows || 0 ), 10 );
14963 this.validate = null;
14964
14965 // Clone for resizing
14966 if ( this.autosize ) {
14967 this.$clone = this.$input
14968 .clone()
14969 .insertAfter( this.$input )
14970 .attr( 'aria-hidden', 'true' )
14971 .addClass( 'oo-ui-element-hidden' );
14972 }
14973
14974 this.setValidation( config.validate );
14975 this.setLabelPosition( config.labelPosition );
14976
14977 // Events
14978 this.$input.on( {
14979 keypress: this.onKeyPress.bind( this ),
14980 blur: this.onBlur.bind( this )
14981 } );
14982 this.$input.one( {
14983 focus: this.onElementAttach.bind( this )
14984 } );
14985 this.$icon.on( 'mousedown', this.onIconMouseDown.bind( this ) );
14986 this.$indicator.on( 'mousedown', this.onIndicatorMouseDown.bind( this ) );
14987 this.on( 'labelChange', this.updatePosition.bind( this ) );
14988 this.connect( this, {
14989 change: 'onChange',
14990 disable: 'onDisable'
14991 } );
14992
14993 // Initialization
14994 this.$element
14995 .addClass( 'oo-ui-textInputWidget oo-ui-textInputWidget-type-' + this.type )
14996 .append( this.$icon, this.$indicator );
14997 this.setReadOnly( !!config.readOnly );
14998 this.updateSearchIndicator();
14999 if ( config.placeholder ) {
15000 this.$input.attr( 'placeholder', config.placeholder );
15001 }
15002 if ( config.maxLength !== undefined ) {
15003 this.$input.attr( 'maxlength', config.maxLength );
15004 }
15005 if ( config.autofocus ) {
15006 this.$input.attr( 'autofocus', 'autofocus' );
15007 }
15008 if ( config.required ) {
15009 this.$input.attr( 'required', 'required' );
15010 this.$input.attr( 'aria-required', 'true' );
15011 }
15012 if ( config.autocomplete === false ) {
15013 this.$input.attr( 'autocomplete', 'off' );
15014 }
15015 if ( this.multiline && config.rows ) {
15016 this.$input.attr( 'rows', config.rows );
15017 }
15018 if ( this.label || config.autosize ) {
15019 this.installParentChangeDetector();
15020 }
15021 };
15022
15023 /* Setup */
15024
15025 OO.inheritClass( OO.ui.TextInputWidget, OO.ui.InputWidget );
15026 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.mixin.IconElement );
15027 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.mixin.IndicatorElement );
15028 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.mixin.PendingElement );
15029 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.mixin.LabelElement );
15030
15031 /* Static Properties */
15032
15033 OO.ui.TextInputWidget.static.validationPatterns = {
15034 'non-empty': /.+/,
15035 integer: /^\d+$/
15036 };
15037
15038 /* Events */
15039
15040 /**
15041 * An `enter` event is emitted when the user presses 'enter' inside the text box.
15042 *
15043 * Not emitted if the input is multiline.
15044 *
15045 * @event enter
15046 */
15047
15048 /* Methods */
15049
15050 /**
15051 * Handle icon mouse down events.
15052 *
15053 * @private
15054 * @param {jQuery.Event} e Mouse down event
15055 * @fires icon
15056 */
15057 OO.ui.TextInputWidget.prototype.onIconMouseDown = function ( e ) {
15058 if ( e.which === 1 ) {
15059 this.$input[ 0 ].focus();
15060 return false;
15061 }
15062 };
15063
15064 /**
15065 * Handle indicator mouse down events.
15066 *
15067 * @private
15068 * @param {jQuery.Event} e Mouse down event
15069 * @fires indicator
15070 */
15071 OO.ui.TextInputWidget.prototype.onIndicatorMouseDown = function ( e ) {
15072 if ( e.which === 1 ) {
15073 if ( this.type === 'search' ) {
15074 // Clear the text field
15075 this.setValue( '' );
15076 }
15077 this.$input[ 0 ].focus();
15078 return false;
15079 }
15080 };
15081
15082 /**
15083 * Handle key press events.
15084 *
15085 * @private
15086 * @param {jQuery.Event} e Key press event
15087 * @fires enter If enter key is pressed and input is not multiline
15088 */
15089 OO.ui.TextInputWidget.prototype.onKeyPress = function ( e ) {
15090 if ( e.which === OO.ui.Keys.ENTER && !this.multiline ) {
15091 this.emit( 'enter', e );
15092 }
15093 };
15094
15095 /**
15096 * Handle blur events.
15097 *
15098 * @private
15099 * @param {jQuery.Event} e Blur event
15100 */
15101 OO.ui.TextInputWidget.prototype.onBlur = function () {
15102 this.setValidityFlag();
15103 };
15104
15105 /**
15106 * Handle element attach events.
15107 *
15108 * @private
15109 * @param {jQuery.Event} e Element attach event
15110 */
15111 OO.ui.TextInputWidget.prototype.onElementAttach = function () {
15112 // Any previously calculated size is now probably invalid if we reattached elsewhere
15113 this.valCache = null;
15114 this.adjustSize();
15115 this.positionLabel();
15116 };
15117
15118 /**
15119 * Handle change events.
15120 *
15121 * @param {string} value
15122 * @private
15123 */
15124 OO.ui.TextInputWidget.prototype.onChange = function () {
15125 this.updateSearchIndicator();
15126 this.setValidityFlag();
15127 this.adjustSize();
15128 };
15129
15130 /**
15131 * Handle disable events.
15132 *
15133 * @param {boolean} disabled Element is disabled
15134 * @private
15135 */
15136 OO.ui.TextInputWidget.prototype.onDisable = function () {
15137 this.updateSearchIndicator();
15138 };
15139
15140 /**
15141 * Check if the input is {@link #readOnly read-only}.
15142 *
15143 * @return {boolean}
15144 */
15145 OO.ui.TextInputWidget.prototype.isReadOnly = function () {
15146 return this.readOnly;
15147 };
15148
15149 /**
15150 * Set the {@link #readOnly read-only} state of the input.
15151 *
15152 * @param {boolean} state Make input read-only
15153 * @chainable
15154 */
15155 OO.ui.TextInputWidget.prototype.setReadOnly = function ( state ) {
15156 this.readOnly = !!state;
15157 this.$input.prop( 'readOnly', this.readOnly );
15158 this.updateSearchIndicator();
15159 return this;
15160 };
15161
15162 /**
15163 * Support function for making #onElementAttach work across browsers.
15164 *
15165 * This whole function could be replaced with one line of code using the DOMNodeInsertedIntoDocument
15166 * event, but it's not supported by Firefox and allegedly deprecated, so we only use it as fallback.
15167 *
15168 * Due to MutationObserver performance woes, #onElementAttach is only somewhat reliably called the
15169 * first time that the element gets attached to the documented.
15170 */
15171 OO.ui.TextInputWidget.prototype.installParentChangeDetector = function () {
15172 var mutationObserver, onRemove, topmostNode, fakeParentNode,
15173 MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver,
15174 widget = this;
15175
15176 if ( MutationObserver ) {
15177 // The new way. If only it wasn't so ugly.
15178
15179 if ( this.$element.closest( 'html' ).length ) {
15180 // Widget is attached already, do nothing. This breaks the functionality of this function when
15181 // the widget is detached and reattached. Alas, doing this correctly with MutationObserver
15182 // would require observation of the whole document, which would hurt performance of other,
15183 // more important code.
15184 return;
15185 }
15186
15187 // Find topmost node in the tree
15188 topmostNode = this.$element[0];
15189 while ( topmostNode.parentNode ) {
15190 topmostNode = topmostNode.parentNode;
15191 }
15192
15193 // We have no way to detect the $element being attached somewhere without observing the entire
15194 // DOM with subtree modifications, which would hurt performance. So we cheat: we hook to the
15195 // parent node of $element, and instead detect when $element is removed from it (and thus
15196 // probably attached somewhere else). If there is no parent, we create a "fake" one. If it
15197 // doesn't get attached, we end up back here and create the parent.
15198
15199 mutationObserver = new MutationObserver( function ( mutations ) {
15200 var i, j, removedNodes;
15201 for ( i = 0; i < mutations.length; i++ ) {
15202 removedNodes = mutations[ i ].removedNodes;
15203 for ( j = 0; j < removedNodes.length; j++ ) {
15204 if ( removedNodes[ j ] === topmostNode ) {
15205 setTimeout( onRemove, 0 );
15206 return;
15207 }
15208 }
15209 }
15210 } );
15211
15212 onRemove = function () {
15213 // If the node was attached somewhere else, report it
15214 if ( widget.$element.closest( 'html' ).length ) {
15215 widget.onElementAttach();
15216 }
15217 mutationObserver.disconnect();
15218 widget.installParentChangeDetector();
15219 };
15220
15221 // Create a fake parent and observe it
15222 fakeParentNode = $( '<div>' ).append( topmostNode )[0];
15223 mutationObserver.observe( fakeParentNode, { childList: true } );
15224 } else {
15225 // Using the DOMNodeInsertedIntoDocument event is much nicer and less magical, and works for
15226 // detachment and reattachment, but it's not supported by Firefox and allegedly deprecated.
15227 this.$element.on( 'DOMNodeInsertedIntoDocument', this.onElementAttach.bind( this ) );
15228 }
15229 };
15230
15231 /**
15232 * Automatically adjust the size of the text input.
15233 *
15234 * This only affects #multiline inputs that are {@link #autosize autosized}.
15235 *
15236 * @chainable
15237 */
15238 OO.ui.TextInputWidget.prototype.adjustSize = function () {
15239 var scrollHeight, innerHeight, outerHeight, maxInnerHeight, measurementError, idealHeight;
15240
15241 if ( this.multiline && this.autosize && this.$input.val() !== this.valCache ) {
15242 this.$clone
15243 .val( this.$input.val() )
15244 .attr( 'rows', this.minRows )
15245 // Set inline height property to 0 to measure scroll height
15246 .css( 'height', 0 );
15247
15248 this.$clone.removeClass( 'oo-ui-element-hidden' );
15249
15250 this.valCache = this.$input.val();
15251
15252 scrollHeight = this.$clone[ 0 ].scrollHeight;
15253
15254 // Remove inline height property to measure natural heights
15255 this.$clone.css( 'height', '' );
15256 innerHeight = this.$clone.innerHeight();
15257 outerHeight = this.$clone.outerHeight();
15258
15259 // Measure max rows height
15260 this.$clone
15261 .attr( 'rows', this.maxRows )
15262 .css( 'height', 'auto' )
15263 .val( '' );
15264 maxInnerHeight = this.$clone.innerHeight();
15265
15266 // Difference between reported innerHeight and scrollHeight with no scrollbars present
15267 // Equals 1 on Blink-based browsers and 0 everywhere else
15268 measurementError = maxInnerHeight - this.$clone[ 0 ].scrollHeight;
15269 idealHeight = Math.min( maxInnerHeight, scrollHeight + measurementError );
15270
15271 this.$clone.addClass( 'oo-ui-element-hidden' );
15272
15273 // Only apply inline height when expansion beyond natural height is needed
15274 if ( idealHeight > innerHeight ) {
15275 // Use the difference between the inner and outer height as a buffer
15276 this.$input.css( 'height', idealHeight + ( outerHeight - innerHeight ) );
15277 } else {
15278 this.$input.css( 'height', '' );
15279 }
15280 }
15281 return this;
15282 };
15283
15284 /**
15285 * @inheritdoc
15286 * @protected
15287 */
15288 OO.ui.TextInputWidget.prototype.getInputElement = function ( config ) {
15289 return config.multiline ?
15290 $( '<textarea>' ) :
15291 $( '<input type="' + this.getSaneType( config ) + '" />' );
15292 };
15293
15294 /**
15295 * Get sanitized value for 'type' for given config.
15296 *
15297 * @param {Object} config Configuration options
15298 * @return {string|null}
15299 * @private
15300 */
15301 OO.ui.TextInputWidget.prototype.getSaneType = function ( config ) {
15302 var type = [ 'text', 'password', 'search', 'email', 'url' ].indexOf( config.type ) !== -1 ?
15303 config.type :
15304 'text';
15305 return config.multiline ? 'multiline' : type;
15306 };
15307
15308 /**
15309 * Check if the input supports multiple lines.
15310 *
15311 * @return {boolean}
15312 */
15313 OO.ui.TextInputWidget.prototype.isMultiline = function () {
15314 return !!this.multiline;
15315 };
15316
15317 /**
15318 * Check if the input automatically adjusts its size.
15319 *
15320 * @return {boolean}
15321 */
15322 OO.ui.TextInputWidget.prototype.isAutosizing = function () {
15323 return !!this.autosize;
15324 };
15325
15326 /**
15327 * Select the entire text of the input.
15328 *
15329 * @chainable
15330 */
15331 OO.ui.TextInputWidget.prototype.select = function () {
15332 this.$input.select();
15333 return this;
15334 };
15335
15336 /**
15337 * Set the validation pattern.
15338 *
15339 * The validation pattern is either a regular expression, a function, or the symbolic name of a
15340 * pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer' (the
15341 * value must contain only numbers).
15342 *
15343 * @param {RegExp|Function|string|null} validate Regular expression, function, or the symbolic name
15344 * of a pattern (either ‘integer’ or ‘non-empty’) defined by the class.
15345 */
15346 OO.ui.TextInputWidget.prototype.setValidation = function ( validate ) {
15347 if ( validate instanceof RegExp || validate instanceof Function ) {
15348 this.validate = validate;
15349 } else {
15350 this.validate = this.constructor.static.validationPatterns[ validate ] || /.*/;
15351 }
15352 };
15353
15354 /**
15355 * Sets the 'invalid' flag appropriately.
15356 *
15357 * @param {boolean} [isValid] Optionally override validation result
15358 */
15359 OO.ui.TextInputWidget.prototype.setValidityFlag = function ( isValid ) {
15360 var widget = this,
15361 setFlag = function ( valid ) {
15362 if ( !valid ) {
15363 widget.$input.attr( 'aria-invalid', 'true' );
15364 } else {
15365 widget.$input.removeAttr( 'aria-invalid' );
15366 }
15367 widget.setFlags( { invalid: !valid } );
15368 };
15369
15370 if ( isValid !== undefined ) {
15371 setFlag( isValid );
15372 } else {
15373 this.getValidity().then( function () {
15374 setFlag( true );
15375 }, function () {
15376 setFlag( false );
15377 } );
15378 }
15379 };
15380
15381 /**
15382 * Check if a value is valid.
15383 *
15384 * This method returns a promise that resolves with a boolean `true` if the current value is
15385 * considered valid according to the supplied {@link #validate validation pattern}.
15386 *
15387 * @deprecated
15388 * @return {jQuery.Promise} A promise that resolves to a boolean `true` if the value is valid.
15389 */
15390 OO.ui.TextInputWidget.prototype.isValid = function () {
15391 if ( this.validate instanceof Function ) {
15392 var result = this.validate( this.getValue() );
15393 if ( $.isFunction( result.promise ) ) {
15394 return result.promise();
15395 } else {
15396 return $.Deferred().resolve( !!result ).promise();
15397 }
15398 } else {
15399 return $.Deferred().resolve( !!this.getValue().match( this.validate ) ).promise();
15400 }
15401 };
15402
15403 /**
15404 * Get the validity of current value.
15405 *
15406 * This method returns a promise that resolves if the value is valid and rejects if
15407 * it isn't. Uses the {@link #validate validation pattern} to check for validity.
15408 *
15409 * @return {jQuery.Promise} A promise that resolves if the value is valid, rejects if not.
15410 */
15411 OO.ui.TextInputWidget.prototype.getValidity = function () {
15412 var result, promise;
15413
15414 function rejectOrResolve( valid ) {
15415 if ( valid ) {
15416 return $.Deferred().resolve().promise();
15417 } else {
15418 return $.Deferred().reject().promise();
15419 }
15420 }
15421
15422 if ( this.validate instanceof Function ) {
15423 result = this.validate( this.getValue() );
15424
15425 if ( $.isFunction( result.promise ) ) {
15426 promise = $.Deferred();
15427
15428 result.then( function ( valid ) {
15429 if ( valid ) {
15430 promise.resolve();
15431 } else {
15432 promise.reject();
15433 }
15434 }, function () {
15435 promise.reject();
15436 } );
15437
15438 return promise.promise();
15439 } else {
15440 return rejectOrResolve( result );
15441 }
15442 } else {
15443 return rejectOrResolve( this.getValue().match( this.validate ) );
15444 }
15445 };
15446
15447 /**
15448 * Set the position of the inline label relative to that of the value: `‘before’` or `‘after’`.
15449 *
15450 * @param {string} labelPosition Label position, 'before' or 'after'
15451 * @chainable
15452 */
15453 OO.ui.TextInputWidget.prototype.setLabelPosition = function ( labelPosition ) {
15454 this.labelPosition = labelPosition;
15455 this.updatePosition();
15456 return this;
15457 };
15458
15459 /**
15460 * Deprecated alias of #setLabelPosition
15461 *
15462 * @deprecated Use setLabelPosition instead.
15463 */
15464 OO.ui.TextInputWidget.prototype.setPosition =
15465 OO.ui.TextInputWidget.prototype.setLabelPosition;
15466
15467 /**
15468 * Update the position of the inline label.
15469 *
15470 * This method is called by #setLabelPosition, and can also be called on its own if
15471 * something causes the label to be mispositioned.
15472 *
15473 * @chainable
15474 */
15475 OO.ui.TextInputWidget.prototype.updatePosition = function () {
15476 var after = this.labelPosition === 'after';
15477
15478 this.$element
15479 .toggleClass( 'oo-ui-textInputWidget-labelPosition-after', !!this.label && after )
15480 .toggleClass( 'oo-ui-textInputWidget-labelPosition-before', !!this.label && !after );
15481
15482 this.positionLabel();
15483
15484 return this;
15485 };
15486
15487 /**
15488 * Update the 'clear' indicator displayed on type: 'search' text fields, hiding it when the field is
15489 * already empty or when it's not editable.
15490 */
15491 OO.ui.TextInputWidget.prototype.updateSearchIndicator = function () {
15492 if ( this.type === 'search' ) {
15493 if ( this.getValue() === '' || this.isDisabled() || this.isReadOnly() ) {
15494 this.setIndicator( null );
15495 } else {
15496 this.setIndicator( 'clear' );
15497 }
15498 }
15499 };
15500
15501 /**
15502 * Position the label by setting the correct padding on the input.
15503 *
15504 * @private
15505 * @chainable
15506 */
15507 OO.ui.TextInputWidget.prototype.positionLabel = function () {
15508 // Clear old values
15509 this.$input
15510 // Clear old values if present
15511 .css( {
15512 'padding-right': '',
15513 'padding-left': ''
15514 } );
15515
15516 if ( this.label ) {
15517 this.$element.append( this.$label );
15518 } else {
15519 this.$label.detach();
15520 return;
15521 }
15522
15523 var after = this.labelPosition === 'after',
15524 rtl = this.$element.css( 'direction' ) === 'rtl',
15525 property = after === rtl ? 'padding-left' : 'padding-right';
15526
15527 this.$input.css( property, this.$label.outerWidth( true ) );
15528
15529 return this;
15530 };
15531
15532 /**
15533 * @inheritdoc
15534 */
15535 OO.ui.TextInputWidget.prototype.gatherPreInfuseState = function ( node ) {
15536 var
15537 state = OO.ui.TextInputWidget.parent.prototype.gatherPreInfuseState.call( this, node ),
15538 $input = $( node ).find( '.oo-ui-inputWidget-input' );
15539 state.$input = $input; // shortcut for performance, used in InputWidget
15540 if ( this.multiline ) {
15541 state.scrollTop = $input.scrollTop();
15542 }
15543 return state;
15544 };
15545
15546 /**
15547 * @inheritdoc
15548 */
15549 OO.ui.TextInputWidget.prototype.restorePreInfuseState = function ( state ) {
15550 OO.ui.TextInputWidget.parent.prototype.restorePreInfuseState.call( this, state );
15551 if ( state.scrollTop !== undefined ) {
15552 this.$input.scrollTop( state.scrollTop );
15553 }
15554 };
15555
15556 /**
15557 * ComboBoxWidgets combine a {@link OO.ui.TextInputWidget text input} (where a value
15558 * can be entered manually) and a {@link OO.ui.MenuSelectWidget menu of options} (from which
15559 * a value can be chosen instead). Users can choose options from the combo box in one of two ways:
15560 *
15561 * - by typing a value in the text input field. If the value exactly matches the value of a menu
15562 * option, that option will appear to be selected.
15563 * - by choosing a value from the menu. The value of the chosen option will then appear in the text
15564 * input field.
15565 *
15566 * For more information about menus and options, please see the [OOjs UI documentation on MediaWiki][1].
15567 *
15568 * @example
15569 * // Example: A ComboBoxWidget.
15570 * var comboBox = new OO.ui.ComboBoxWidget( {
15571 * label: 'ComboBoxWidget',
15572 * input: { value: 'Option One' },
15573 * menu: {
15574 * items: [
15575 * new OO.ui.MenuOptionWidget( {
15576 * data: 'Option 1',
15577 * label: 'Option One'
15578 * } ),
15579 * new OO.ui.MenuOptionWidget( {
15580 * data: 'Option 2',
15581 * label: 'Option Two'
15582 * } ),
15583 * new OO.ui.MenuOptionWidget( {
15584 * data: 'Option 3',
15585 * label: 'Option Three'
15586 * } ),
15587 * new OO.ui.MenuOptionWidget( {
15588 * data: 'Option 4',
15589 * label: 'Option Four'
15590 * } ),
15591 * new OO.ui.MenuOptionWidget( {
15592 * data: 'Option 5',
15593 * label: 'Option Five'
15594 * } )
15595 * ]
15596 * }
15597 * } );
15598 * $( 'body' ).append( comboBox.$element );
15599 *
15600 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
15601 *
15602 * @class
15603 * @extends OO.ui.Widget
15604 * @mixins OO.ui.mixin.TabIndexedElement
15605 *
15606 * @constructor
15607 * @param {Object} [config] Configuration options
15608 * @cfg {Object} [menu] Configuration options to pass to the {@link OO.ui.MenuSelectWidget menu select widget}.
15609 * @cfg {Object} [input] Configuration options to pass to the {@link OO.ui.TextInputWidget text input widget}.
15610 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
15611 * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
15612 * containing `<div>` and has a larger area. By default, the menu uses relative positioning.
15613 */
15614 OO.ui.ComboBoxWidget = function OoUiComboBoxWidget( config ) {
15615 // Configuration initialization
15616 config = config || {};
15617
15618 // Parent constructor
15619 OO.ui.ComboBoxWidget.parent.call( this, config );
15620
15621 // Properties (must be set before TabIndexedElement constructor call)
15622 this.$indicator = this.$( '<span>' );
15623
15624 // Mixin constructors
15625 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$indicator } ) );
15626
15627 // Properties
15628 this.$overlay = config.$overlay || this.$element;
15629 this.input = new OO.ui.TextInputWidget( $.extend(
15630 {
15631 indicator: 'down',
15632 $indicator: this.$indicator,
15633 disabled: this.isDisabled()
15634 },
15635 config.input
15636 ) );
15637 this.input.$input.eq( 0 ).attr( {
15638 role: 'combobox',
15639 'aria-autocomplete': 'list'
15640 } );
15641 this.menu = new OO.ui.TextInputMenuSelectWidget( this.input, $.extend(
15642 {
15643 widget: this,
15644 input: this.input,
15645 disabled: this.isDisabled()
15646 },
15647 config.menu
15648 ) );
15649
15650 // Events
15651 this.$indicator.on( {
15652 click: this.onClick.bind( this ),
15653 keypress: this.onKeyPress.bind( this )
15654 } );
15655 this.input.connect( this, {
15656 change: 'onInputChange',
15657 enter: 'onInputEnter'
15658 } );
15659 this.menu.connect( this, {
15660 choose: 'onMenuChoose',
15661 add: 'onMenuItemsChange',
15662 remove: 'onMenuItemsChange'
15663 } );
15664
15665 // Initialization
15666 this.$element.addClass( 'oo-ui-comboBoxWidget' ).append( this.input.$element );
15667 this.$overlay.append( this.menu.$element );
15668 this.onMenuItemsChange();
15669 };
15670
15671 /* Setup */
15672
15673 OO.inheritClass( OO.ui.ComboBoxWidget, OO.ui.Widget );
15674 OO.mixinClass( OO.ui.ComboBoxWidget, OO.ui.mixin.TabIndexedElement );
15675
15676 /* Methods */
15677
15678 /**
15679 * Get the combobox's menu.
15680 * @return {OO.ui.TextInputMenuSelectWidget} Menu widget
15681 */
15682 OO.ui.ComboBoxWidget.prototype.getMenu = function () {
15683 return this.menu;
15684 };
15685
15686 /**
15687 * Get the combobox's text input widget.
15688 * @return {OO.ui.TextInputWidget} Text input widget
15689 */
15690 OO.ui.ComboBoxWidget.prototype.getInput = function () {
15691 return this.input;
15692 };
15693
15694 /**
15695 * Handle input change events.
15696 *
15697 * @private
15698 * @param {string} value New value
15699 */
15700 OO.ui.ComboBoxWidget.prototype.onInputChange = function ( value ) {
15701 var match = this.menu.getItemFromData( value );
15702
15703 this.menu.selectItem( match );
15704 if ( this.menu.getHighlightedItem() ) {
15705 this.menu.highlightItem( match );
15706 }
15707
15708 if ( !this.isDisabled() ) {
15709 this.menu.toggle( true );
15710 }
15711 };
15712
15713 /**
15714 * Handle mouse click events.
15715 *
15716 *
15717 * @private
15718 * @param {jQuery.Event} e Mouse click event
15719 */
15720 OO.ui.ComboBoxWidget.prototype.onClick = function ( e ) {
15721 if ( !this.isDisabled() && e.which === 1 ) {
15722 this.menu.toggle();
15723 this.input.$input[ 0 ].focus();
15724 }
15725 return false;
15726 };
15727
15728 /**
15729 * Handle key press events.
15730 *
15731 *
15732 * @private
15733 * @param {jQuery.Event} e Key press event
15734 */
15735 OO.ui.ComboBoxWidget.prototype.onKeyPress = function ( e ) {
15736 if ( !this.isDisabled() && ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER ) ) {
15737 this.menu.toggle();
15738 this.input.$input[ 0 ].focus();
15739 return false;
15740 }
15741 };
15742
15743 /**
15744 * Handle input enter events.
15745 *
15746 * @private
15747 */
15748 OO.ui.ComboBoxWidget.prototype.onInputEnter = function () {
15749 if ( !this.isDisabled() ) {
15750 this.menu.toggle( false );
15751 }
15752 };
15753
15754 /**
15755 * Handle menu choose events.
15756 *
15757 * @private
15758 * @param {OO.ui.OptionWidget} item Chosen item
15759 */
15760 OO.ui.ComboBoxWidget.prototype.onMenuChoose = function ( item ) {
15761 this.input.setValue( item.getData() );
15762 };
15763
15764 /**
15765 * Handle menu item change events.
15766 *
15767 * @private
15768 */
15769 OO.ui.ComboBoxWidget.prototype.onMenuItemsChange = function () {
15770 var match = this.menu.getItemFromData( this.input.getValue() );
15771 this.menu.selectItem( match );
15772 if ( this.menu.getHighlightedItem() ) {
15773 this.menu.highlightItem( match );
15774 }
15775 this.$element.toggleClass( 'oo-ui-comboBoxWidget-empty', this.menu.isEmpty() );
15776 };
15777
15778 /**
15779 * @inheritdoc
15780 */
15781 OO.ui.ComboBoxWidget.prototype.setDisabled = function ( disabled ) {
15782 // Parent method
15783 OO.ui.ComboBoxWidget.parent.prototype.setDisabled.call( this, disabled );
15784
15785 if ( this.input ) {
15786 this.input.setDisabled( this.isDisabled() );
15787 }
15788 if ( this.menu ) {
15789 this.menu.setDisabled( this.isDisabled() );
15790 }
15791
15792 return this;
15793 };
15794
15795 /**
15796 * LabelWidgets help identify the function of interface elements. Each LabelWidget can
15797 * be configured with a `label` option that is set to a string, a label node, or a function:
15798 *
15799 * - String: a plaintext string
15800 * - jQuery selection: a jQuery selection, used for anything other than a plaintext label, e.g., a
15801 * label that includes a link or special styling, such as a gray color or additional graphical elements.
15802 * - Function: a function that will produce a string in the future. Functions are used
15803 * in cases where the value of the label is not currently defined.
15804 *
15805 * In addition, the LabelWidget can be associated with an {@link OO.ui.InputWidget input widget}, which
15806 * will come into focus when the label is clicked.
15807 *
15808 * @example
15809 * // Examples of LabelWidgets
15810 * var label1 = new OO.ui.LabelWidget( {
15811 * label: 'plaintext label'
15812 * } );
15813 * var label2 = new OO.ui.LabelWidget( {
15814 * label: $( '<a href="default.html">jQuery label</a>' )
15815 * } );
15816 * // Create a fieldset layout with fields for each example
15817 * var fieldset = new OO.ui.FieldsetLayout();
15818 * fieldset.addItems( [
15819 * new OO.ui.FieldLayout( label1 ),
15820 * new OO.ui.FieldLayout( label2 )
15821 * ] );
15822 * $( 'body' ).append( fieldset.$element );
15823 *
15824 *
15825 * @class
15826 * @extends OO.ui.Widget
15827 * @mixins OO.ui.mixin.LabelElement
15828 *
15829 * @constructor
15830 * @param {Object} [config] Configuration options
15831 * @cfg {OO.ui.InputWidget} [input] {@link OO.ui.InputWidget Input widget} that uses the label.
15832 * Clicking the label will focus the specified input field.
15833 */
15834 OO.ui.LabelWidget = function OoUiLabelWidget( config ) {
15835 // Configuration initialization
15836 config = config || {};
15837
15838 // Parent constructor
15839 OO.ui.LabelWidget.parent.call( this, config );
15840
15841 // Mixin constructors
15842 OO.ui.mixin.LabelElement.call( this, $.extend( {}, config, { $label: this.$element } ) );
15843 OO.ui.mixin.TitledElement.call( this, config );
15844
15845 // Properties
15846 this.input = config.input;
15847
15848 // Events
15849 if ( this.input instanceof OO.ui.InputWidget ) {
15850 this.$element.on( 'click', this.onClick.bind( this ) );
15851 }
15852
15853 // Initialization
15854 this.$element.addClass( 'oo-ui-labelWidget' );
15855 };
15856
15857 /* Setup */
15858
15859 OO.inheritClass( OO.ui.LabelWidget, OO.ui.Widget );
15860 OO.mixinClass( OO.ui.LabelWidget, OO.ui.mixin.LabelElement );
15861 OO.mixinClass( OO.ui.LabelWidget, OO.ui.mixin.TitledElement );
15862
15863 /* Static Properties */
15864
15865 OO.ui.LabelWidget.static.tagName = 'span';
15866
15867 /* Methods */
15868
15869 /**
15870 * Handles label mouse click events.
15871 *
15872 * @private
15873 * @param {jQuery.Event} e Mouse click event
15874 */
15875 OO.ui.LabelWidget.prototype.onClick = function () {
15876 this.input.simulateLabelClick();
15877 return false;
15878 };
15879
15880 /**
15881 * OptionWidgets are special elements that can be selected and configured with data. The
15882 * data is often unique for each option, but it does not have to be. OptionWidgets are used
15883 * with OO.ui.SelectWidget to create a selection of mutually exclusive options. For more information
15884 * and examples, please see the [OOjs UI documentation on MediaWiki][1].
15885 *
15886 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
15887 *
15888 * @class
15889 * @extends OO.ui.Widget
15890 * @mixins OO.ui.mixin.LabelElement
15891 * @mixins OO.ui.mixin.FlaggedElement
15892 *
15893 * @constructor
15894 * @param {Object} [config] Configuration options
15895 */
15896 OO.ui.OptionWidget = function OoUiOptionWidget( config ) {
15897 // Configuration initialization
15898 config = config || {};
15899
15900 // Parent constructor
15901 OO.ui.OptionWidget.parent.call( this, config );
15902
15903 // Mixin constructors
15904 OO.ui.mixin.ItemWidget.call( this );
15905 OO.ui.mixin.LabelElement.call( this, config );
15906 OO.ui.mixin.FlaggedElement.call( this, config );
15907
15908 // Properties
15909 this.selected = false;
15910 this.highlighted = false;
15911 this.pressed = false;
15912
15913 // Initialization
15914 this.$element
15915 .data( 'oo-ui-optionWidget', this )
15916 .attr( 'role', 'option' )
15917 .attr( 'aria-selected', 'false' )
15918 .addClass( 'oo-ui-optionWidget' )
15919 .append( this.$label );
15920 };
15921
15922 /* Setup */
15923
15924 OO.inheritClass( OO.ui.OptionWidget, OO.ui.Widget );
15925 OO.mixinClass( OO.ui.OptionWidget, OO.ui.mixin.ItemWidget );
15926 OO.mixinClass( OO.ui.OptionWidget, OO.ui.mixin.LabelElement );
15927 OO.mixinClass( OO.ui.OptionWidget, OO.ui.mixin.FlaggedElement );
15928
15929 /* Static Properties */
15930
15931 OO.ui.OptionWidget.static.selectable = true;
15932
15933 OO.ui.OptionWidget.static.highlightable = true;
15934
15935 OO.ui.OptionWidget.static.pressable = true;
15936
15937 OO.ui.OptionWidget.static.scrollIntoViewOnSelect = false;
15938
15939 /* Methods */
15940
15941 /**
15942 * Check if the option can be selected.
15943 *
15944 * @return {boolean} Item is selectable
15945 */
15946 OO.ui.OptionWidget.prototype.isSelectable = function () {
15947 return this.constructor.static.selectable && !this.isDisabled() && this.isVisible();
15948 };
15949
15950 /**
15951 * Check if the option can be highlighted. A highlight indicates that the option
15952 * may be selected when a user presses enter or clicks. Disabled items cannot
15953 * be highlighted.
15954 *
15955 * @return {boolean} Item is highlightable
15956 */
15957 OO.ui.OptionWidget.prototype.isHighlightable = function () {
15958 return this.constructor.static.highlightable && !this.isDisabled() && this.isVisible();
15959 };
15960
15961 /**
15962 * Check if the option can be pressed. The pressed state occurs when a user mouses
15963 * down on an item, but has not yet let go of the mouse.
15964 *
15965 * @return {boolean} Item is pressable
15966 */
15967 OO.ui.OptionWidget.prototype.isPressable = function () {
15968 return this.constructor.static.pressable && !this.isDisabled() && this.isVisible();
15969 };
15970
15971 /**
15972 * Check if the option is selected.
15973 *
15974 * @return {boolean} Item is selected
15975 */
15976 OO.ui.OptionWidget.prototype.isSelected = function () {
15977 return this.selected;
15978 };
15979
15980 /**
15981 * Check if the option is highlighted. A highlight indicates that the
15982 * item may be selected when a user presses enter or clicks.
15983 *
15984 * @return {boolean} Item is highlighted
15985 */
15986 OO.ui.OptionWidget.prototype.isHighlighted = function () {
15987 return this.highlighted;
15988 };
15989
15990 /**
15991 * Check if the option is pressed. The pressed state occurs when a user mouses
15992 * down on an item, but has not yet let go of the mouse. The item may appear
15993 * selected, but it will not be selected until the user releases the mouse.
15994 *
15995 * @return {boolean} Item is pressed
15996 */
15997 OO.ui.OptionWidget.prototype.isPressed = function () {
15998 return this.pressed;
15999 };
16000
16001 /**
16002 * Set the option’s selected state. In general, all modifications to the selection
16003 * should be handled by the SelectWidget’s {@link OO.ui.SelectWidget#selectItem selectItem( [item] )}
16004 * method instead of this method.
16005 *
16006 * @param {boolean} [state=false] Select option
16007 * @chainable
16008 */
16009 OO.ui.OptionWidget.prototype.setSelected = function ( state ) {
16010 if ( this.constructor.static.selectable ) {
16011 this.selected = !!state;
16012 this.$element
16013 .toggleClass( 'oo-ui-optionWidget-selected', state )
16014 .attr( 'aria-selected', state.toString() );
16015 if ( state && this.constructor.static.scrollIntoViewOnSelect ) {
16016 this.scrollElementIntoView();
16017 }
16018 this.updateThemeClasses();
16019 }
16020 return this;
16021 };
16022
16023 /**
16024 * Set the option’s highlighted state. In general, all programmatic
16025 * modifications to the highlight should be handled by the
16026 * SelectWidget’s {@link OO.ui.SelectWidget#highlightItem highlightItem( [item] )}
16027 * method instead of this method.
16028 *
16029 * @param {boolean} [state=false] Highlight option
16030 * @chainable
16031 */
16032 OO.ui.OptionWidget.prototype.setHighlighted = function ( state ) {
16033 if ( this.constructor.static.highlightable ) {
16034 this.highlighted = !!state;
16035 this.$element.toggleClass( 'oo-ui-optionWidget-highlighted', state );
16036 this.updateThemeClasses();
16037 }
16038 return this;
16039 };
16040
16041 /**
16042 * Set the option’s pressed state. In general, all
16043 * programmatic modifications to the pressed state should be handled by the
16044 * SelectWidget’s {@link OO.ui.SelectWidget#pressItem pressItem( [item] )}
16045 * method instead of this method.
16046 *
16047 * @param {boolean} [state=false] Press option
16048 * @chainable
16049 */
16050 OO.ui.OptionWidget.prototype.setPressed = function ( state ) {
16051 if ( this.constructor.static.pressable ) {
16052 this.pressed = !!state;
16053 this.$element.toggleClass( 'oo-ui-optionWidget-pressed', state );
16054 this.updateThemeClasses();
16055 }
16056 return this;
16057 };
16058
16059 /**
16060 * DecoratedOptionWidgets are {@link OO.ui.OptionWidget options} that can be configured
16061 * with an {@link OO.ui.mixin.IconElement icon} and/or {@link OO.ui.mixin.IndicatorElement indicator}.
16062 * This class is used with OO.ui.SelectWidget to create a selection of mutually exclusive
16063 * options. For more information about options and selects, please see the
16064 * [OOjs UI documentation on MediaWiki][1].
16065 *
16066 * @example
16067 * // Decorated options in a select widget
16068 * var select = new OO.ui.SelectWidget( {
16069 * items: [
16070 * new OO.ui.DecoratedOptionWidget( {
16071 * data: 'a',
16072 * label: 'Option with icon',
16073 * icon: 'help'
16074 * } ),
16075 * new OO.ui.DecoratedOptionWidget( {
16076 * data: 'b',
16077 * label: 'Option with indicator',
16078 * indicator: 'next'
16079 * } )
16080 * ]
16081 * } );
16082 * $( 'body' ).append( select.$element );
16083 *
16084 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
16085 *
16086 * @class
16087 * @extends OO.ui.OptionWidget
16088 * @mixins OO.ui.mixin.IconElement
16089 * @mixins OO.ui.mixin.IndicatorElement
16090 *
16091 * @constructor
16092 * @param {Object} [config] Configuration options
16093 */
16094 OO.ui.DecoratedOptionWidget = function OoUiDecoratedOptionWidget( config ) {
16095 // Parent constructor
16096 OO.ui.DecoratedOptionWidget.parent.call( this, config );
16097
16098 // Mixin constructors
16099 OO.ui.mixin.IconElement.call( this, config );
16100 OO.ui.mixin.IndicatorElement.call( this, config );
16101
16102 // Initialization
16103 this.$element
16104 .addClass( 'oo-ui-decoratedOptionWidget' )
16105 .prepend( this.$icon )
16106 .append( this.$indicator );
16107 };
16108
16109 /* Setup */
16110
16111 OO.inheritClass( OO.ui.DecoratedOptionWidget, OO.ui.OptionWidget );
16112 OO.mixinClass( OO.ui.DecoratedOptionWidget, OO.ui.mixin.IconElement );
16113 OO.mixinClass( OO.ui.DecoratedOptionWidget, OO.ui.mixin.IndicatorElement );
16114
16115 /**
16116 * ButtonOptionWidget is a special type of {@link OO.ui.mixin.ButtonElement button element} that
16117 * can be selected and configured with data. The class is
16118 * used with OO.ui.ButtonSelectWidget to create a selection of button options. Please see the
16119 * [OOjs UI documentation on MediaWiki] [1] for more information.
16120 *
16121 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Button_selects_and_options
16122 *
16123 * @class
16124 * @extends OO.ui.DecoratedOptionWidget
16125 * @mixins OO.ui.mixin.ButtonElement
16126 * @mixins OO.ui.mixin.TabIndexedElement
16127 *
16128 * @constructor
16129 * @param {Object} [config] Configuration options
16130 */
16131 OO.ui.ButtonOptionWidget = function OoUiButtonOptionWidget( config ) {
16132 // Configuration initialization
16133 config = config || {};
16134
16135 // Parent constructor
16136 OO.ui.ButtonOptionWidget.parent.call( this, config );
16137
16138 // Mixin constructors
16139 OO.ui.mixin.ButtonElement.call( this, config );
16140 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, {
16141 $tabIndexed: this.$button,
16142 tabIndex: -1
16143 } ) );
16144
16145 // Initialization
16146 this.$element.addClass( 'oo-ui-buttonOptionWidget' );
16147 this.$button.append( this.$element.contents() );
16148 this.$element.append( this.$button );
16149 };
16150
16151 /* Setup */
16152
16153 OO.inheritClass( OO.ui.ButtonOptionWidget, OO.ui.DecoratedOptionWidget );
16154 OO.mixinClass( OO.ui.ButtonOptionWidget, OO.ui.mixin.ButtonElement );
16155 OO.mixinClass( OO.ui.ButtonOptionWidget, OO.ui.mixin.TabIndexedElement );
16156
16157 /* Static Properties */
16158
16159 // Allow button mouse down events to pass through so they can be handled by the parent select widget
16160 OO.ui.ButtonOptionWidget.static.cancelButtonMouseDownEvents = false;
16161
16162 OO.ui.ButtonOptionWidget.static.highlightable = false;
16163
16164 /* Methods */
16165
16166 /**
16167 * @inheritdoc
16168 */
16169 OO.ui.ButtonOptionWidget.prototype.setSelected = function ( state ) {
16170 OO.ui.ButtonOptionWidget.parent.prototype.setSelected.call( this, state );
16171
16172 if ( this.constructor.static.selectable ) {
16173 this.setActive( state );
16174 }
16175
16176 return this;
16177 };
16178
16179 /**
16180 * RadioOptionWidget is an option widget that looks like a radio button.
16181 * The class is used with OO.ui.RadioSelectWidget to create a selection of radio options.
16182 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information.
16183 *
16184 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Button_selects_and_option
16185 *
16186 * @class
16187 * @extends OO.ui.OptionWidget
16188 *
16189 * @constructor
16190 * @param {Object} [config] Configuration options
16191 */
16192 OO.ui.RadioOptionWidget = function OoUiRadioOptionWidget( config ) {
16193 // Configuration initialization
16194 config = config || {};
16195
16196 // Properties (must be done before parent constructor which calls #setDisabled)
16197 this.radio = new OO.ui.RadioInputWidget( { value: config.data, tabIndex: -1 } );
16198
16199 // Parent constructor
16200 OO.ui.RadioOptionWidget.parent.call( this, config );
16201
16202 // Events
16203 this.radio.$input.on( 'focus', this.onInputFocus.bind( this ) );
16204
16205 // Initialization
16206 // Remove implicit role, we're handling it ourselves
16207 this.radio.$input.attr( 'role', 'presentation' );
16208 this.$element
16209 .addClass( 'oo-ui-radioOptionWidget' )
16210 .attr( 'role', 'radio' )
16211 .attr( 'aria-checked', 'false' )
16212 .removeAttr( 'aria-selected' )
16213 .prepend( this.radio.$element );
16214 };
16215
16216 /* Setup */
16217
16218 OO.inheritClass( OO.ui.RadioOptionWidget, OO.ui.OptionWidget );
16219
16220 /* Static Properties */
16221
16222 OO.ui.RadioOptionWidget.static.highlightable = false;
16223
16224 OO.ui.RadioOptionWidget.static.scrollIntoViewOnSelect = true;
16225
16226 OO.ui.RadioOptionWidget.static.pressable = false;
16227
16228 OO.ui.RadioOptionWidget.static.tagName = 'label';
16229
16230 /* Methods */
16231
16232 /**
16233 * @param {jQuery.Event} e Focus event
16234 * @private
16235 */
16236 OO.ui.RadioOptionWidget.prototype.onInputFocus = function () {
16237 this.radio.$input.blur();
16238 this.$element.parent().focus();
16239 };
16240
16241 /**
16242 * @inheritdoc
16243 */
16244 OO.ui.RadioOptionWidget.prototype.setSelected = function ( state ) {
16245 OO.ui.RadioOptionWidget.parent.prototype.setSelected.call( this, state );
16246
16247 this.radio.setSelected( state );
16248 this.$element
16249 .attr( 'aria-checked', state.toString() )
16250 .removeAttr( 'aria-selected' );
16251
16252 return this;
16253 };
16254
16255 /**
16256 * @inheritdoc
16257 */
16258 OO.ui.RadioOptionWidget.prototype.setDisabled = function ( disabled ) {
16259 OO.ui.RadioOptionWidget.parent.prototype.setDisabled.call( this, disabled );
16260
16261 this.radio.setDisabled( this.isDisabled() );
16262
16263 return this;
16264 };
16265
16266 /**
16267 * MenuOptionWidget is an option widget that looks like a menu item. The class is used with
16268 * OO.ui.MenuSelectWidget to create a menu of mutually exclusive options. Please see
16269 * the [OOjs UI documentation on MediaWiki] [1] for more information.
16270 *
16271 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
16272 *
16273 * @class
16274 * @extends OO.ui.DecoratedOptionWidget
16275 *
16276 * @constructor
16277 * @param {Object} [config] Configuration options
16278 */
16279 OO.ui.MenuOptionWidget = function OoUiMenuOptionWidget( config ) {
16280 // Configuration initialization
16281 config = $.extend( { icon: 'check' }, config );
16282
16283 // Parent constructor
16284 OO.ui.MenuOptionWidget.parent.call( this, config );
16285
16286 // Initialization
16287 this.$element
16288 .attr( 'role', 'menuitem' )
16289 .addClass( 'oo-ui-menuOptionWidget' );
16290 };
16291
16292 /* Setup */
16293
16294 OO.inheritClass( OO.ui.MenuOptionWidget, OO.ui.DecoratedOptionWidget );
16295
16296 /* Static Properties */
16297
16298 OO.ui.MenuOptionWidget.static.scrollIntoViewOnSelect = true;
16299
16300 /**
16301 * MenuSectionOptionWidgets are used inside {@link OO.ui.MenuSelectWidget menu select widgets} to group one or more related
16302 * {@link OO.ui.MenuOptionWidget menu options}. MenuSectionOptionWidgets cannot be highlighted or selected.
16303 *
16304 * @example
16305 * var myDropdown = new OO.ui.DropdownWidget( {
16306 * menu: {
16307 * items: [
16308 * new OO.ui.MenuSectionOptionWidget( {
16309 * label: 'Dogs'
16310 * } ),
16311 * new OO.ui.MenuOptionWidget( {
16312 * data: 'corgi',
16313 * label: 'Welsh Corgi'
16314 * } ),
16315 * new OO.ui.MenuOptionWidget( {
16316 * data: 'poodle',
16317 * label: 'Standard Poodle'
16318 * } ),
16319 * new OO.ui.MenuSectionOptionWidget( {
16320 * label: 'Cats'
16321 * } ),
16322 * new OO.ui.MenuOptionWidget( {
16323 * data: 'lion',
16324 * label: 'Lion'
16325 * } )
16326 * ]
16327 * }
16328 * } );
16329 * $( 'body' ).append( myDropdown.$element );
16330 *
16331 *
16332 * @class
16333 * @extends OO.ui.DecoratedOptionWidget
16334 *
16335 * @constructor
16336 * @param {Object} [config] Configuration options
16337 */
16338 OO.ui.MenuSectionOptionWidget = function OoUiMenuSectionOptionWidget( config ) {
16339 // Parent constructor
16340 OO.ui.MenuSectionOptionWidget.parent.call( this, config );
16341
16342 // Initialization
16343 this.$element.addClass( 'oo-ui-menuSectionOptionWidget' );
16344 };
16345
16346 /* Setup */
16347
16348 OO.inheritClass( OO.ui.MenuSectionOptionWidget, OO.ui.DecoratedOptionWidget );
16349
16350 /* Static Properties */
16351
16352 OO.ui.MenuSectionOptionWidget.static.selectable = false;
16353
16354 OO.ui.MenuSectionOptionWidget.static.highlightable = false;
16355
16356 /**
16357 * OutlineOptionWidget is an item in an {@link OO.ui.OutlineSelectWidget OutlineSelectWidget}.
16358 *
16359 * Currently, this class is only used by {@link OO.ui.BookletLayout booklet layouts}, which contain
16360 * {@link OO.ui.PageLayout page layouts}. See {@link OO.ui.BookletLayout BookletLayout}
16361 * for an example.
16362 *
16363 * @class
16364 * @extends OO.ui.DecoratedOptionWidget
16365 *
16366 * @constructor
16367 * @param {Object} [config] Configuration options
16368 * @cfg {number} [level] Indentation level
16369 * @cfg {boolean} [movable] Allow modification from {@link OO.ui.OutlineControlsWidget outline controls}.
16370 */
16371 OO.ui.OutlineOptionWidget = function OoUiOutlineOptionWidget( config ) {
16372 // Configuration initialization
16373 config = config || {};
16374
16375 // Parent constructor
16376 OO.ui.OutlineOptionWidget.parent.call( this, config );
16377
16378 // Properties
16379 this.level = 0;
16380 this.movable = !!config.movable;
16381 this.removable = !!config.removable;
16382
16383 // Initialization
16384 this.$element.addClass( 'oo-ui-outlineOptionWidget' );
16385 this.setLevel( config.level );
16386 };
16387
16388 /* Setup */
16389
16390 OO.inheritClass( OO.ui.OutlineOptionWidget, OO.ui.DecoratedOptionWidget );
16391
16392 /* Static Properties */
16393
16394 OO.ui.OutlineOptionWidget.static.highlightable = false;
16395
16396 OO.ui.OutlineOptionWidget.static.scrollIntoViewOnSelect = true;
16397
16398 OO.ui.OutlineOptionWidget.static.levelClass = 'oo-ui-outlineOptionWidget-level-';
16399
16400 OO.ui.OutlineOptionWidget.static.levels = 3;
16401
16402 /* Methods */
16403
16404 /**
16405 * Check if item is movable.
16406 *
16407 * Movability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
16408 *
16409 * @return {boolean} Item is movable
16410 */
16411 OO.ui.OutlineOptionWidget.prototype.isMovable = function () {
16412 return this.movable;
16413 };
16414
16415 /**
16416 * Check if item is removable.
16417 *
16418 * Removability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
16419 *
16420 * @return {boolean} Item is removable
16421 */
16422 OO.ui.OutlineOptionWidget.prototype.isRemovable = function () {
16423 return this.removable;
16424 };
16425
16426 /**
16427 * Get indentation level.
16428 *
16429 * @return {number} Indentation level
16430 */
16431 OO.ui.OutlineOptionWidget.prototype.getLevel = function () {
16432 return this.level;
16433 };
16434
16435 /**
16436 * Set movability.
16437 *
16438 * Movability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
16439 *
16440 * @param {boolean} movable Item is movable
16441 * @chainable
16442 */
16443 OO.ui.OutlineOptionWidget.prototype.setMovable = function ( movable ) {
16444 this.movable = !!movable;
16445 this.updateThemeClasses();
16446 return this;
16447 };
16448
16449 /**
16450 * Set removability.
16451 *
16452 * Removability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
16453 *
16454 * @param {boolean} movable Item is removable
16455 * @chainable
16456 */
16457 OO.ui.OutlineOptionWidget.prototype.setRemovable = function ( removable ) {
16458 this.removable = !!removable;
16459 this.updateThemeClasses();
16460 return this;
16461 };
16462
16463 /**
16464 * Set indentation level.
16465 *
16466 * @param {number} [level=0] Indentation level, in the range of [0,#maxLevel]
16467 * @chainable
16468 */
16469 OO.ui.OutlineOptionWidget.prototype.setLevel = function ( level ) {
16470 var levels = this.constructor.static.levels,
16471 levelClass = this.constructor.static.levelClass,
16472 i = levels;
16473
16474 this.level = level ? Math.max( 0, Math.min( levels - 1, level ) ) : 0;
16475 while ( i-- ) {
16476 if ( this.level === i ) {
16477 this.$element.addClass( levelClass + i );
16478 } else {
16479 this.$element.removeClass( levelClass + i );
16480 }
16481 }
16482 this.updateThemeClasses();
16483
16484 return this;
16485 };
16486
16487 /**
16488 * TabOptionWidget is an item in a {@link OO.ui.TabSelectWidget TabSelectWidget}.
16489 *
16490 * Currently, this class is only used by {@link OO.ui.IndexLayout index layouts}, which contain
16491 * {@link OO.ui.CardLayout card layouts}. See {@link OO.ui.IndexLayout IndexLayout}
16492 * for an example.
16493 *
16494 * @class
16495 * @extends OO.ui.OptionWidget
16496 *
16497 * @constructor
16498 * @param {Object} [config] Configuration options
16499 */
16500 OO.ui.TabOptionWidget = function OoUiTabOptionWidget( config ) {
16501 // Configuration initialization
16502 config = config || {};
16503
16504 // Parent constructor
16505 OO.ui.TabOptionWidget.parent.call( this, config );
16506
16507 // Initialization
16508 this.$element.addClass( 'oo-ui-tabOptionWidget' );
16509 };
16510
16511 /* Setup */
16512
16513 OO.inheritClass( OO.ui.TabOptionWidget, OO.ui.OptionWidget );
16514
16515 /* Static Properties */
16516
16517 OO.ui.TabOptionWidget.static.highlightable = false;
16518
16519 /**
16520 * PopupWidget is a container for content. The popup is overlaid and positioned absolutely.
16521 * By default, each popup has an anchor that points toward its origin.
16522 * Please see the [OOjs UI documentation on Mediawiki] [1] for more information and examples.
16523 *
16524 * @example
16525 * // A popup widget.
16526 * var popup = new OO.ui.PopupWidget( {
16527 * $content: $( '<p>Hi there!</p>' ),
16528 * padded: true,
16529 * width: 300
16530 * } );
16531 *
16532 * $( 'body' ).append( popup.$element );
16533 * // To display the popup, toggle the visibility to 'true'.
16534 * popup.toggle( true );
16535 *
16536 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups
16537 *
16538 * @class
16539 * @extends OO.ui.Widget
16540 * @mixins OO.ui.mixin.LabelElement
16541 *
16542 * @constructor
16543 * @param {Object} [config] Configuration options
16544 * @cfg {number} [width=320] Width of popup in pixels
16545 * @cfg {number} [height] Height of popup in pixels. Omit to use the automatic height.
16546 * @cfg {boolean} [anchor=true] Show anchor pointing to origin of popup
16547 * @cfg {string} [align='center'] Alignment of the popup: `center`, `force-left`, `force-right`, `backwards` or `forwards`.
16548 * If the popup is forced-left the popup body is leaning towards the left. For force-right alignment, the body of the
16549 * popup is leaning towards the right of the screen.
16550 * Using 'backwards' is a logical direction which will result in the popup leaning towards the beginning of the sentence
16551 * in the given language, which means it will flip to the correct positioning in right-to-left languages.
16552 * Using 'forward' will also result in a logical alignment where the body of the popup leans towards the end of the
16553 * sentence in the given language.
16554 * @cfg {jQuery} [$container] Constrain the popup to the boundaries of the specified container.
16555 * See the [OOjs UI docs on MediaWiki][3] for an example.
16556 * [3]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups#containerExample
16557 * @cfg {number} [containerPadding=10] Padding between the popup and its container, specified as a number of pixels.
16558 * @cfg {jQuery} [$content] Content to append to the popup's body
16559 * @cfg {boolean} [autoClose=false] Automatically close the popup when it loses focus.
16560 * @cfg {jQuery} [$autoCloseIgnore] Elements that will not close the popup when clicked.
16561 * This config option is only relevant if #autoClose is set to `true`. See the [OOjs UI docs on MediaWiki][2]
16562 * for an example.
16563 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups#autocloseExample
16564 * @cfg {boolean} [head] Show a popup header that contains a #label (if specified) and close
16565 * button.
16566 * @cfg {boolean} [padded] Add padding to the popup's body
16567 */
16568 OO.ui.PopupWidget = function OoUiPopupWidget( config ) {
16569 // Configuration initialization
16570 config = config || {};
16571
16572 // Parent constructor
16573 OO.ui.PopupWidget.parent.call( this, config );
16574
16575 // Properties (must be set before ClippableElement constructor call)
16576 this.$body = $( '<div>' );
16577
16578 // Mixin constructors
16579 OO.ui.mixin.LabelElement.call( this, config );
16580 OO.ui.mixin.ClippableElement.call( this, $.extend( {}, config, { $clippable: this.$body } ) );
16581
16582 // Properties
16583 this.$popup = $( '<div>' );
16584 this.$head = $( '<div>' );
16585 this.$anchor = $( '<div>' );
16586 // If undefined, will be computed lazily in updateDimensions()
16587 this.$container = config.$container;
16588 this.containerPadding = config.containerPadding !== undefined ? config.containerPadding : 10;
16589 this.autoClose = !!config.autoClose;
16590 this.$autoCloseIgnore = config.$autoCloseIgnore;
16591 this.transitionTimeout = null;
16592 this.anchor = null;
16593 this.width = config.width !== undefined ? config.width : 320;
16594 this.height = config.height !== undefined ? config.height : null;
16595 this.setAlignment( config.align );
16596 this.closeButton = new OO.ui.ButtonWidget( { framed: false, icon: 'close' } );
16597 this.onMouseDownHandler = this.onMouseDown.bind( this );
16598 this.onDocumentKeyDownHandler = this.onDocumentKeyDown.bind( this );
16599
16600 // Events
16601 this.closeButton.connect( this, { click: 'onCloseButtonClick' } );
16602
16603 // Initialization
16604 this.toggleAnchor( config.anchor === undefined || config.anchor );
16605 this.$body.addClass( 'oo-ui-popupWidget-body' );
16606 this.$anchor.addClass( 'oo-ui-popupWidget-anchor' );
16607 this.$head
16608 .addClass( 'oo-ui-popupWidget-head' )
16609 .append( this.$label, this.closeButton.$element );
16610 if ( !config.head ) {
16611 this.$head.addClass( 'oo-ui-element-hidden' );
16612 }
16613 this.$popup
16614 .addClass( 'oo-ui-popupWidget-popup' )
16615 .append( this.$head, this.$body );
16616 this.$element
16617 .addClass( 'oo-ui-popupWidget' )
16618 .append( this.$popup, this.$anchor );
16619 // Move content, which was added to #$element by OO.ui.Widget, to the body
16620 if ( config.$content instanceof jQuery ) {
16621 this.$body.append( config.$content );
16622 }
16623 if ( config.padded ) {
16624 this.$body.addClass( 'oo-ui-popupWidget-body-padded' );
16625 }
16626
16627 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
16628 // that reference properties not initialized at that time of parent class construction
16629 // TODO: Find a better way to handle post-constructor setup
16630 this.visible = false;
16631 this.$element.addClass( 'oo-ui-element-hidden' );
16632 };
16633
16634 /* Setup */
16635
16636 OO.inheritClass( OO.ui.PopupWidget, OO.ui.Widget );
16637 OO.mixinClass( OO.ui.PopupWidget, OO.ui.mixin.LabelElement );
16638 OO.mixinClass( OO.ui.PopupWidget, OO.ui.mixin.ClippableElement );
16639
16640 /* Methods */
16641
16642 /**
16643 * Handles mouse down events.
16644 *
16645 * @private
16646 * @param {MouseEvent} e Mouse down event
16647 */
16648 OO.ui.PopupWidget.prototype.onMouseDown = function ( e ) {
16649 if (
16650 this.isVisible() &&
16651 !$.contains( this.$element[ 0 ], e.target ) &&
16652 ( !this.$autoCloseIgnore || !this.$autoCloseIgnore.has( e.target ).length )
16653 ) {
16654 this.toggle( false );
16655 }
16656 };
16657
16658 /**
16659 * Bind mouse down listener.
16660 *
16661 * @private
16662 */
16663 OO.ui.PopupWidget.prototype.bindMouseDownListener = function () {
16664 // Capture clicks outside popup
16665 this.getElementWindow().addEventListener( 'mousedown', this.onMouseDownHandler, true );
16666 };
16667
16668 /**
16669 * Handles close button click events.
16670 *
16671 * @private
16672 */
16673 OO.ui.PopupWidget.prototype.onCloseButtonClick = function () {
16674 if ( this.isVisible() ) {
16675 this.toggle( false );
16676 }
16677 };
16678
16679 /**
16680 * Unbind mouse down listener.
16681 *
16682 * @private
16683 */
16684 OO.ui.PopupWidget.prototype.unbindMouseDownListener = function () {
16685 this.getElementWindow().removeEventListener( 'mousedown', this.onMouseDownHandler, true );
16686 };
16687
16688 /**
16689 * Handles key down events.
16690 *
16691 * @private
16692 * @param {KeyboardEvent} e Key down event
16693 */
16694 OO.ui.PopupWidget.prototype.onDocumentKeyDown = function ( e ) {
16695 if (
16696 e.which === OO.ui.Keys.ESCAPE &&
16697 this.isVisible()
16698 ) {
16699 this.toggle( false );
16700 e.preventDefault();
16701 e.stopPropagation();
16702 }
16703 };
16704
16705 /**
16706 * Bind key down listener.
16707 *
16708 * @private
16709 */
16710 OO.ui.PopupWidget.prototype.bindKeyDownListener = function () {
16711 this.getElementWindow().addEventListener( 'keydown', this.onDocumentKeyDownHandler, true );
16712 };
16713
16714 /**
16715 * Unbind key down listener.
16716 *
16717 * @private
16718 */
16719 OO.ui.PopupWidget.prototype.unbindKeyDownListener = function () {
16720 this.getElementWindow().removeEventListener( 'keydown', this.onDocumentKeyDownHandler, true );
16721 };
16722
16723 /**
16724 * Show, hide, or toggle the visibility of the anchor.
16725 *
16726 * @param {boolean} [show] Show anchor, omit to toggle
16727 */
16728 OO.ui.PopupWidget.prototype.toggleAnchor = function ( show ) {
16729 show = show === undefined ? !this.anchored : !!show;
16730
16731 if ( this.anchored !== show ) {
16732 if ( show ) {
16733 this.$element.addClass( 'oo-ui-popupWidget-anchored' );
16734 } else {
16735 this.$element.removeClass( 'oo-ui-popupWidget-anchored' );
16736 }
16737 this.anchored = show;
16738 }
16739 };
16740
16741 /**
16742 * Check if the anchor is visible.
16743 *
16744 * @return {boolean} Anchor is visible
16745 */
16746 OO.ui.PopupWidget.prototype.hasAnchor = function () {
16747 return this.anchor;
16748 };
16749
16750 /**
16751 * @inheritdoc
16752 */
16753 OO.ui.PopupWidget.prototype.toggle = function ( show ) {
16754 show = show === undefined ? !this.isVisible() : !!show;
16755
16756 var change = show !== this.isVisible();
16757
16758 // Parent method
16759 OO.ui.PopupWidget.parent.prototype.toggle.call( this, show );
16760
16761 if ( change ) {
16762 if ( show ) {
16763 if ( this.autoClose ) {
16764 this.bindMouseDownListener();
16765 this.bindKeyDownListener();
16766 }
16767 this.updateDimensions();
16768 this.toggleClipping( true );
16769 } else {
16770 this.toggleClipping( false );
16771 if ( this.autoClose ) {
16772 this.unbindMouseDownListener();
16773 this.unbindKeyDownListener();
16774 }
16775 }
16776 }
16777
16778 return this;
16779 };
16780
16781 /**
16782 * Set the size of the popup.
16783 *
16784 * Changing the size may also change the popup's position depending on the alignment.
16785 *
16786 * @param {number} width Width in pixels
16787 * @param {number} height Height in pixels
16788 * @param {boolean} [transition=false] Use a smooth transition
16789 * @chainable
16790 */
16791 OO.ui.PopupWidget.prototype.setSize = function ( width, height, transition ) {
16792 this.width = width;
16793 this.height = height !== undefined ? height : null;
16794 if ( this.isVisible() ) {
16795 this.updateDimensions( transition );
16796 }
16797 };
16798
16799 /**
16800 * Update the size and position.
16801 *
16802 * Only use this to keep the popup properly anchored. Use #setSize to change the size, and this will
16803 * be called automatically.
16804 *
16805 * @param {boolean} [transition=false] Use a smooth transition
16806 * @chainable
16807 */
16808 OO.ui.PopupWidget.prototype.updateDimensions = function ( transition ) {
16809 var popupOffset, originOffset, containerLeft, containerWidth, containerRight,
16810 popupLeft, popupRight, overlapLeft, overlapRight, anchorWidth,
16811 align = this.align,
16812 widget = this;
16813
16814 if ( !this.$container ) {
16815 // Lazy-initialize $container if not specified in constructor
16816 this.$container = $( this.getClosestScrollableElementContainer() );
16817 }
16818
16819 // Set height and width before measuring things, since it might cause our measurements
16820 // to change (e.g. due to scrollbars appearing or disappearing)
16821 this.$popup.css( {
16822 width: this.width,
16823 height: this.height !== null ? this.height : 'auto'
16824 } );
16825
16826 // If we are in RTL, we need to flip the alignment, unless it is center
16827 if ( align === 'forwards' || align === 'backwards' ) {
16828 if ( this.$container.css( 'direction' ) === 'rtl' ) {
16829 align = ( { forwards: 'force-left', backwards: 'force-right' } )[ this.align ];
16830 } else {
16831 align = ( { forwards: 'force-right', backwards: 'force-left' } )[ this.align ];
16832 }
16833
16834 }
16835
16836 // Compute initial popupOffset based on alignment
16837 popupOffset = this.width * ( { 'force-left': -1, center: -0.5, 'force-right': 0 } )[ align ];
16838
16839 // Figure out if this will cause the popup to go beyond the edge of the container
16840 originOffset = this.$element.offset().left;
16841 containerLeft = this.$container.offset().left;
16842 containerWidth = this.$container.innerWidth();
16843 containerRight = containerLeft + containerWidth;
16844 popupLeft = popupOffset - this.containerPadding;
16845 popupRight = popupOffset + this.containerPadding + this.width + this.containerPadding;
16846 overlapLeft = ( originOffset + popupLeft ) - containerLeft;
16847 overlapRight = containerRight - ( originOffset + popupRight );
16848
16849 // Adjust offset to make the popup not go beyond the edge, if needed
16850 if ( overlapRight < 0 ) {
16851 popupOffset += overlapRight;
16852 } else if ( overlapLeft < 0 ) {
16853 popupOffset -= overlapLeft;
16854 }
16855
16856 // Adjust offset to avoid anchor being rendered too close to the edge
16857 // $anchor.width() doesn't work with the pure CSS anchor (returns 0)
16858 // TODO: Find a measurement that works for CSS anchors and image anchors
16859 anchorWidth = this.$anchor[ 0 ].scrollWidth * 2;
16860 if ( popupOffset + this.width < anchorWidth ) {
16861 popupOffset = anchorWidth - this.width;
16862 } else if ( -popupOffset < anchorWidth ) {
16863 popupOffset = -anchorWidth;
16864 }
16865
16866 // Prevent transition from being interrupted
16867 clearTimeout( this.transitionTimeout );
16868 if ( transition ) {
16869 // Enable transition
16870 this.$element.addClass( 'oo-ui-popupWidget-transitioning' );
16871 }
16872
16873 // Position body relative to anchor
16874 this.$popup.css( 'margin-left', popupOffset );
16875
16876 if ( transition ) {
16877 // Prevent transitioning after transition is complete
16878 this.transitionTimeout = setTimeout( function () {
16879 widget.$element.removeClass( 'oo-ui-popupWidget-transitioning' );
16880 }, 200 );
16881 } else {
16882 // Prevent transitioning immediately
16883 this.$element.removeClass( 'oo-ui-popupWidget-transitioning' );
16884 }
16885
16886 // Reevaluate clipping state since we've relocated and resized the popup
16887 this.clip();
16888
16889 return this;
16890 };
16891
16892 /**
16893 * Set popup alignment
16894 * @param {string} align Alignment of the popup, `center`, `force-left`, `force-right`,
16895 * `backwards` or `forwards`.
16896 */
16897 OO.ui.PopupWidget.prototype.setAlignment = function ( align ) {
16898 // Validate alignment and transform deprecated values
16899 if ( [ 'left', 'right', 'force-left', 'force-right', 'backwards', 'forwards', 'center' ].indexOf( align ) > -1 ) {
16900 this.align = { left: 'force-right', right: 'force-left' }[ align ] || align;
16901 } else {
16902 this.align = 'center';
16903 }
16904 };
16905
16906 /**
16907 * Get popup alignment
16908 * @return {string} align Alignment of the popup, `center`, `force-left`, `force-right`,
16909 * `backwards` or `forwards`.
16910 */
16911 OO.ui.PopupWidget.prototype.getAlignment = function () {
16912 return this.align;
16913 };
16914
16915 /**
16916 * Progress bars visually display the status of an operation, such as a download,
16917 * and can be either determinate or indeterminate:
16918 *
16919 * - **determinate** process bars show the percent of an operation that is complete.
16920 *
16921 * - **indeterminate** process bars use a visual display of motion to indicate that an operation
16922 * is taking place. Because the extent of an indeterminate operation is unknown, the bar does
16923 * not use percentages.
16924 *
16925 * The value of the `progress` configuration determines whether the bar is determinate or indeterminate.
16926 *
16927 * @example
16928 * // Examples of determinate and indeterminate progress bars.
16929 * var progressBar1 = new OO.ui.ProgressBarWidget( {
16930 * progress: 33
16931 * } );
16932 * var progressBar2 = new OO.ui.ProgressBarWidget();
16933 *
16934 * // Create a FieldsetLayout to layout progress bars
16935 * var fieldset = new OO.ui.FieldsetLayout;
16936 * fieldset.addItems( [
16937 * new OO.ui.FieldLayout( progressBar1, {label: 'Determinate', align: 'top'}),
16938 * new OO.ui.FieldLayout( progressBar2, {label: 'Indeterminate', align: 'top'})
16939 * ] );
16940 * $( 'body' ).append( fieldset.$element );
16941 *
16942 * @class
16943 * @extends OO.ui.Widget
16944 *
16945 * @constructor
16946 * @param {Object} [config] Configuration options
16947 * @cfg {number|boolean} [progress=false] The type of progress bar (determinate or indeterminate).
16948 * To create a determinate progress bar, specify a number that reflects the initial percent complete.
16949 * By default, the progress bar is indeterminate.
16950 */
16951 OO.ui.ProgressBarWidget = function OoUiProgressBarWidget( config ) {
16952 // Configuration initialization
16953 config = config || {};
16954
16955 // Parent constructor
16956 OO.ui.ProgressBarWidget.parent.call( this, config );
16957
16958 // Properties
16959 this.$bar = $( '<div>' );
16960 this.progress = null;
16961
16962 // Initialization
16963 this.setProgress( config.progress !== undefined ? config.progress : false );
16964 this.$bar.addClass( 'oo-ui-progressBarWidget-bar' );
16965 this.$element
16966 .attr( {
16967 role: 'progressbar',
16968 'aria-valuemin': 0,
16969 'aria-valuemax': 100
16970 } )
16971 .addClass( 'oo-ui-progressBarWidget' )
16972 .append( this.$bar );
16973 };
16974
16975 /* Setup */
16976
16977 OO.inheritClass( OO.ui.ProgressBarWidget, OO.ui.Widget );
16978
16979 /* Static Properties */
16980
16981 OO.ui.ProgressBarWidget.static.tagName = 'div';
16982
16983 /* Methods */
16984
16985 /**
16986 * Get the percent of the progress that has been completed. Indeterminate progresses will return `false`.
16987 *
16988 * @return {number|boolean} Progress percent
16989 */
16990 OO.ui.ProgressBarWidget.prototype.getProgress = function () {
16991 return this.progress;
16992 };
16993
16994 /**
16995 * Set the percent of the process completed or `false` for an indeterminate process.
16996 *
16997 * @param {number|boolean} progress Progress percent or `false` for indeterminate
16998 */
16999 OO.ui.ProgressBarWidget.prototype.setProgress = function ( progress ) {
17000 this.progress = progress;
17001
17002 if ( progress !== false ) {
17003 this.$bar.css( 'width', this.progress + '%' );
17004 this.$element.attr( 'aria-valuenow', this.progress );
17005 } else {
17006 this.$bar.css( 'width', '' );
17007 this.$element.removeAttr( 'aria-valuenow' );
17008 }
17009 this.$element.toggleClass( 'oo-ui-progressBarWidget-indeterminate', !progress );
17010 };
17011
17012 /**
17013 * SearchWidgets combine a {@link OO.ui.TextInputWidget text input field}, where users can type a search query,
17014 * and a {@link OO.ui.TextInputMenuSelectWidget menu} of search results, which is displayed beneath the query
17015 * field. Unlike {@link OO.ui.mixin.LookupElement lookup menus}, search result menus are always visible to the user.
17016 * Users can choose an item from the menu or type a query into the text field to search for a matching result item.
17017 * In general, search widgets are used inside a separate {@link OO.ui.Dialog dialog} window.
17018 *
17019 * Each time the query is changed, the search result menu is cleared and repopulated. Please see
17020 * the [OOjs UI demos][1] for an example.
17021 *
17022 * [1]: https://tools.wmflabs.org/oojs-ui/oojs-ui/demos/#dialogs-mediawiki-vector-ltr
17023 *
17024 * @class
17025 * @extends OO.ui.Widget
17026 *
17027 * @constructor
17028 * @param {Object} [config] Configuration options
17029 * @cfg {string|jQuery} [placeholder] Placeholder text for query input
17030 * @cfg {string} [value] Initial query value
17031 */
17032 OO.ui.SearchWidget = function OoUiSearchWidget( config ) {
17033 // Configuration initialization
17034 config = config || {};
17035
17036 // Parent constructor
17037 OO.ui.SearchWidget.parent.call( this, config );
17038
17039 // Properties
17040 this.query = new OO.ui.TextInputWidget( {
17041 icon: 'search',
17042 placeholder: config.placeholder,
17043 value: config.value
17044 } );
17045 this.results = new OO.ui.SelectWidget();
17046 this.$query = $( '<div>' );
17047 this.$results = $( '<div>' );
17048
17049 // Events
17050 this.query.connect( this, {
17051 change: 'onQueryChange',
17052 enter: 'onQueryEnter'
17053 } );
17054 this.query.$input.on( 'keydown', this.onQueryKeydown.bind( this ) );
17055
17056 // Initialization
17057 this.$query
17058 .addClass( 'oo-ui-searchWidget-query' )
17059 .append( this.query.$element );
17060 this.$results
17061 .addClass( 'oo-ui-searchWidget-results' )
17062 .append( this.results.$element );
17063 this.$element
17064 .addClass( 'oo-ui-searchWidget' )
17065 .append( this.$results, this.$query );
17066 };
17067
17068 /* Setup */
17069
17070 OO.inheritClass( OO.ui.SearchWidget, OO.ui.Widget );
17071
17072 /* Methods */
17073
17074 /**
17075 * Handle query key down events.
17076 *
17077 * @private
17078 * @param {jQuery.Event} e Key down event
17079 */
17080 OO.ui.SearchWidget.prototype.onQueryKeydown = function ( e ) {
17081 var highlightedItem, nextItem,
17082 dir = e.which === OO.ui.Keys.DOWN ? 1 : ( e.which === OO.ui.Keys.UP ? -1 : 0 );
17083
17084 if ( dir ) {
17085 highlightedItem = this.results.getHighlightedItem();
17086 if ( !highlightedItem ) {
17087 highlightedItem = this.results.getSelectedItem();
17088 }
17089 nextItem = this.results.getRelativeSelectableItem( highlightedItem, dir );
17090 this.results.highlightItem( nextItem );
17091 nextItem.scrollElementIntoView();
17092 }
17093 };
17094
17095 /**
17096 * Handle select widget select events.
17097 *
17098 * Clears existing results. Subclasses should repopulate items according to new query.
17099 *
17100 * @private
17101 * @param {string} value New value
17102 */
17103 OO.ui.SearchWidget.prototype.onQueryChange = function () {
17104 // Reset
17105 this.results.clearItems();
17106 };
17107
17108 /**
17109 * Handle select widget enter key events.
17110 *
17111 * Chooses highlighted item.
17112 *
17113 * @private
17114 * @param {string} value New value
17115 */
17116 OO.ui.SearchWidget.prototype.onQueryEnter = function () {
17117 // Reset
17118 this.results.chooseItem( this.results.getHighlightedItem() );
17119 };
17120
17121 /**
17122 * Get the query input.
17123 *
17124 * @return {OO.ui.TextInputWidget} Query input
17125 */
17126 OO.ui.SearchWidget.prototype.getQuery = function () {
17127 return this.query;
17128 };
17129
17130 /**
17131 * Get the search results menu.
17132 *
17133 * @return {OO.ui.SelectWidget} Menu of search results
17134 */
17135 OO.ui.SearchWidget.prototype.getResults = function () {
17136 return this.results;
17137 };
17138
17139 /**
17140 * A SelectWidget is of a generic selection of options. The OOjs UI library contains several types of
17141 * select widgets, including {@link OO.ui.ButtonSelectWidget button selects},
17142 * {@link OO.ui.RadioSelectWidget radio selects}, and {@link OO.ui.MenuSelectWidget
17143 * menu selects}.
17144 *
17145 * This class should be used together with OO.ui.OptionWidget or OO.ui.DecoratedOptionWidget. For more
17146 * information, please see the [OOjs UI documentation on MediaWiki][1].
17147 *
17148 * @example
17149 * // Example of a select widget with three options
17150 * var select = new OO.ui.SelectWidget( {
17151 * items: [
17152 * new OO.ui.OptionWidget( {
17153 * data: 'a',
17154 * label: 'Option One',
17155 * } ),
17156 * new OO.ui.OptionWidget( {
17157 * data: 'b',
17158 * label: 'Option Two',
17159 * } ),
17160 * new OO.ui.OptionWidget( {
17161 * data: 'c',
17162 * label: 'Option Three',
17163 * } )
17164 * ]
17165 * } );
17166 * $( 'body' ).append( select.$element );
17167 *
17168 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
17169 *
17170 * @abstract
17171 * @class
17172 * @extends OO.ui.Widget
17173 * @mixins OO.ui.mixin.GroupWidget
17174 *
17175 * @constructor
17176 * @param {Object} [config] Configuration options
17177 * @cfg {OO.ui.OptionWidget[]} [items] An array of options to add to the select.
17178 * Options are created with {@link OO.ui.OptionWidget OptionWidget} classes. See
17179 * the [OOjs UI documentation on MediaWiki] [2] for examples.
17180 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
17181 */
17182 OO.ui.SelectWidget = function OoUiSelectWidget( config ) {
17183 // Configuration initialization
17184 config = config || {};
17185
17186 // Parent constructor
17187 OO.ui.SelectWidget.parent.call( this, config );
17188
17189 // Mixin constructors
17190 OO.ui.mixin.GroupWidget.call( this, $.extend( {}, config, { $group: this.$element } ) );
17191
17192 // Properties
17193 this.pressed = false;
17194 this.selecting = null;
17195 this.onMouseUpHandler = this.onMouseUp.bind( this );
17196 this.onMouseMoveHandler = this.onMouseMove.bind( this );
17197 this.onKeyDownHandler = this.onKeyDown.bind( this );
17198 this.onKeyPressHandler = this.onKeyPress.bind( this );
17199 this.keyPressBuffer = '';
17200 this.keyPressBufferTimer = null;
17201
17202 // Events
17203 this.connect( this, {
17204 toggle: 'onToggle'
17205 } );
17206 this.$element.on( {
17207 mousedown: this.onMouseDown.bind( this ),
17208 mouseover: this.onMouseOver.bind( this ),
17209 mouseleave: this.onMouseLeave.bind( this )
17210 } );
17211
17212 // Initialization
17213 this.$element
17214 .addClass( 'oo-ui-selectWidget oo-ui-selectWidget-depressed' )
17215 .attr( 'role', 'listbox' );
17216 if ( Array.isArray( config.items ) ) {
17217 this.addItems( config.items );
17218 }
17219 };
17220
17221 /* Setup */
17222
17223 OO.inheritClass( OO.ui.SelectWidget, OO.ui.Widget );
17224
17225 // Need to mixin base class as well
17226 OO.mixinClass( OO.ui.SelectWidget, OO.ui.mixin.GroupElement );
17227 OO.mixinClass( OO.ui.SelectWidget, OO.ui.mixin.GroupWidget );
17228
17229 /* Static */
17230 OO.ui.SelectWidget.static.passAllFilter = function () {
17231 return true;
17232 };
17233
17234 /* Events */
17235
17236 /**
17237 * @event highlight
17238 *
17239 * A `highlight` event is emitted when the highlight is changed with the #highlightItem method.
17240 *
17241 * @param {OO.ui.OptionWidget|null} item Highlighted item
17242 */
17243
17244 /**
17245 * @event press
17246 *
17247 * A `press` event is emitted when the #pressItem method is used to programmatically modify the
17248 * pressed state of an option.
17249 *
17250 * @param {OO.ui.OptionWidget|null} item Pressed item
17251 */
17252
17253 /**
17254 * @event select
17255 *
17256 * A `select` event is emitted when the selection is modified programmatically with the #selectItem method.
17257 *
17258 * @param {OO.ui.OptionWidget|null} item Selected item
17259 */
17260
17261 /**
17262 * @event choose
17263 * A `choose` event is emitted when an item is chosen with the #chooseItem method.
17264 * @param {OO.ui.OptionWidget} item Chosen item
17265 */
17266
17267 /**
17268 * @event add
17269 *
17270 * An `add` event is emitted when options are added to the select with the #addItems method.
17271 *
17272 * @param {OO.ui.OptionWidget[]} items Added items
17273 * @param {number} index Index of insertion point
17274 */
17275
17276 /**
17277 * @event remove
17278 *
17279 * A `remove` event is emitted when options are removed from the select with the #clearItems
17280 * or #removeItems methods.
17281 *
17282 * @param {OO.ui.OptionWidget[]} items Removed items
17283 */
17284
17285 /* Methods */
17286
17287 /**
17288 * Handle mouse down events.
17289 *
17290 * @private
17291 * @param {jQuery.Event} e Mouse down event
17292 */
17293 OO.ui.SelectWidget.prototype.onMouseDown = function ( e ) {
17294 var item;
17295
17296 if ( !this.isDisabled() && e.which === 1 ) {
17297 this.togglePressed( true );
17298 item = this.getTargetItem( e );
17299 if ( item && item.isSelectable() ) {
17300 this.pressItem( item );
17301 this.selecting = item;
17302 this.getElementDocument().addEventListener(
17303 'mouseup',
17304 this.onMouseUpHandler,
17305 true
17306 );
17307 this.getElementDocument().addEventListener(
17308 'mousemove',
17309 this.onMouseMoveHandler,
17310 true
17311 );
17312 }
17313 }
17314 return false;
17315 };
17316
17317 /**
17318 * Handle mouse up events.
17319 *
17320 * @private
17321 * @param {jQuery.Event} e Mouse up event
17322 */
17323 OO.ui.SelectWidget.prototype.onMouseUp = function ( e ) {
17324 var item;
17325
17326 this.togglePressed( false );
17327 if ( !this.selecting ) {
17328 item = this.getTargetItem( e );
17329 if ( item && item.isSelectable() ) {
17330 this.selecting = item;
17331 }
17332 }
17333 if ( !this.isDisabled() && e.which === 1 && this.selecting ) {
17334 this.pressItem( null );
17335 this.chooseItem( this.selecting );
17336 this.selecting = null;
17337 }
17338
17339 this.getElementDocument().removeEventListener(
17340 'mouseup',
17341 this.onMouseUpHandler,
17342 true
17343 );
17344 this.getElementDocument().removeEventListener(
17345 'mousemove',
17346 this.onMouseMoveHandler,
17347 true
17348 );
17349
17350 return false;
17351 };
17352
17353 /**
17354 * Handle mouse move events.
17355 *
17356 * @private
17357 * @param {jQuery.Event} e Mouse move event
17358 */
17359 OO.ui.SelectWidget.prototype.onMouseMove = function ( e ) {
17360 var item;
17361
17362 if ( !this.isDisabled() && this.pressed ) {
17363 item = this.getTargetItem( e );
17364 if ( item && item !== this.selecting && item.isSelectable() ) {
17365 this.pressItem( item );
17366 this.selecting = item;
17367 }
17368 }
17369 return false;
17370 };
17371
17372 /**
17373 * Handle mouse over events.
17374 *
17375 * @private
17376 * @param {jQuery.Event} e Mouse over event
17377 */
17378 OO.ui.SelectWidget.prototype.onMouseOver = function ( e ) {
17379 var item;
17380
17381 if ( !this.isDisabled() ) {
17382 item = this.getTargetItem( e );
17383 this.highlightItem( item && item.isHighlightable() ? item : null );
17384 }
17385 return false;
17386 };
17387
17388 /**
17389 * Handle mouse leave events.
17390 *
17391 * @private
17392 * @param {jQuery.Event} e Mouse over event
17393 */
17394 OO.ui.SelectWidget.prototype.onMouseLeave = function () {
17395 if ( !this.isDisabled() ) {
17396 this.highlightItem( null );
17397 }
17398 return false;
17399 };
17400
17401 /**
17402 * Handle key down events.
17403 *
17404 * @protected
17405 * @param {jQuery.Event} e Key down event
17406 */
17407 OO.ui.SelectWidget.prototype.onKeyDown = function ( e ) {
17408 var nextItem,
17409 handled = false,
17410 currentItem = this.getHighlightedItem() || this.getSelectedItem();
17411
17412 if ( !this.isDisabled() && this.isVisible() ) {
17413 switch ( e.keyCode ) {
17414 case OO.ui.Keys.ENTER:
17415 if ( currentItem && currentItem.constructor.static.highlightable ) {
17416 // Was only highlighted, now let's select it. No-op if already selected.
17417 this.chooseItem( currentItem );
17418 handled = true;
17419 }
17420 break;
17421 case OO.ui.Keys.UP:
17422 case OO.ui.Keys.LEFT:
17423 this.clearKeyPressBuffer();
17424 nextItem = this.getRelativeSelectableItem( currentItem, -1 );
17425 handled = true;
17426 break;
17427 case OO.ui.Keys.DOWN:
17428 case OO.ui.Keys.RIGHT:
17429 this.clearKeyPressBuffer();
17430 nextItem = this.getRelativeSelectableItem( currentItem, 1 );
17431 handled = true;
17432 break;
17433 case OO.ui.Keys.ESCAPE:
17434 case OO.ui.Keys.TAB:
17435 if ( currentItem && currentItem.constructor.static.highlightable ) {
17436 currentItem.setHighlighted( false );
17437 }
17438 this.unbindKeyDownListener();
17439 this.unbindKeyPressListener();
17440 // Don't prevent tabbing away / defocusing
17441 handled = false;
17442 break;
17443 }
17444
17445 if ( nextItem ) {
17446 if ( nextItem.constructor.static.highlightable ) {
17447 this.highlightItem( nextItem );
17448 } else {
17449 this.chooseItem( nextItem );
17450 }
17451 nextItem.scrollElementIntoView();
17452 }
17453
17454 if ( handled ) {
17455 // Can't just return false, because e is not always a jQuery event
17456 e.preventDefault();
17457 e.stopPropagation();
17458 }
17459 }
17460 };
17461
17462 /**
17463 * Bind key down listener.
17464 *
17465 * @protected
17466 */
17467 OO.ui.SelectWidget.prototype.bindKeyDownListener = function () {
17468 this.getElementWindow().addEventListener( 'keydown', this.onKeyDownHandler, true );
17469 };
17470
17471 /**
17472 * Unbind key down listener.
17473 *
17474 * @protected
17475 */
17476 OO.ui.SelectWidget.prototype.unbindKeyDownListener = function () {
17477 this.getElementWindow().removeEventListener( 'keydown', this.onKeyDownHandler, true );
17478 };
17479
17480 /**
17481 * Clear the key-press buffer
17482 *
17483 * @protected
17484 */
17485 OO.ui.SelectWidget.prototype.clearKeyPressBuffer = function () {
17486 if ( this.keyPressBufferTimer ) {
17487 clearTimeout( this.keyPressBufferTimer );
17488 this.keyPressBufferTimer = null;
17489 }
17490 this.keyPressBuffer = '';
17491 };
17492
17493 /**
17494 * Handle key press events.
17495 *
17496 * @protected
17497 * @param {jQuery.Event} e Key press event
17498 */
17499 OO.ui.SelectWidget.prototype.onKeyPress = function ( e ) {
17500 var c, filter, item;
17501
17502 if ( !e.charCode ) {
17503 if ( e.keyCode === OO.ui.Keys.BACKSPACE && this.keyPressBuffer !== '' ) {
17504 this.keyPressBuffer = this.keyPressBuffer.substr( 0, this.keyPressBuffer.length - 1 );
17505 return false;
17506 }
17507 return;
17508 }
17509 if ( String.fromCodePoint ) {
17510 c = String.fromCodePoint( e.charCode );
17511 } else {
17512 c = String.fromCharCode( e.charCode );
17513 }
17514
17515 if ( this.keyPressBufferTimer ) {
17516 clearTimeout( this.keyPressBufferTimer );
17517 }
17518 this.keyPressBufferTimer = setTimeout( this.clearKeyPressBuffer.bind( this ), 1500 );
17519
17520 item = this.getHighlightedItem() || this.getSelectedItem();
17521
17522 if ( this.keyPressBuffer === c ) {
17523 // Common (if weird) special case: typing "xxxx" will cycle through all
17524 // the items beginning with "x".
17525 if ( item ) {
17526 item = this.getRelativeSelectableItem( item, 1 );
17527 }
17528 } else {
17529 this.keyPressBuffer += c;
17530 }
17531
17532 filter = this.getItemMatcher( this.keyPressBuffer, false );
17533 if ( !item || !filter( item ) ) {
17534 item = this.getRelativeSelectableItem( item, 1, filter );
17535 }
17536 if ( item ) {
17537 if ( item.constructor.static.highlightable ) {
17538 this.highlightItem( item );
17539 } else {
17540 this.chooseItem( item );
17541 }
17542 item.scrollElementIntoView();
17543 }
17544
17545 return false;
17546 };
17547
17548 /**
17549 * Get a matcher for the specific string
17550 *
17551 * @protected
17552 * @param {string} s String to match against items
17553 * @param {boolean} [exact=false] Only accept exact matches
17554 * @return {Function} function ( OO.ui.OptionItem ) => boolean
17555 */
17556 OO.ui.SelectWidget.prototype.getItemMatcher = function ( s, exact ) {
17557 var re;
17558
17559 if ( s.normalize ) {
17560 s = s.normalize();
17561 }
17562 s = exact ? s.trim() : s.replace( /^\s+/, '' );
17563 re = '^\\s*' + s.replace( /([\\{}()|.?*+\-\^$\[\]])/g, '\\$1' ).replace( /\s+/g, '\\s+' );
17564 if ( exact ) {
17565 re += '\\s*$';
17566 }
17567 re = new RegExp( re, 'i' );
17568 return function ( item ) {
17569 var l = item.getLabel();
17570 if ( typeof l !== 'string' ) {
17571 l = item.$label.text();
17572 }
17573 if ( l.normalize ) {
17574 l = l.normalize();
17575 }
17576 return re.test( l );
17577 };
17578 };
17579
17580 /**
17581 * Bind key press listener.
17582 *
17583 * @protected
17584 */
17585 OO.ui.SelectWidget.prototype.bindKeyPressListener = function () {
17586 this.getElementWindow().addEventListener( 'keypress', this.onKeyPressHandler, true );
17587 };
17588
17589 /**
17590 * Unbind key down listener.
17591 *
17592 * If you override this, be sure to call this.clearKeyPressBuffer() from your
17593 * implementation.
17594 *
17595 * @protected
17596 */
17597 OO.ui.SelectWidget.prototype.unbindKeyPressListener = function () {
17598 this.getElementWindow().removeEventListener( 'keypress', this.onKeyPressHandler, true );
17599 this.clearKeyPressBuffer();
17600 };
17601
17602 /**
17603 * Visibility change handler
17604 *
17605 * @protected
17606 * @param {boolean} visible
17607 */
17608 OO.ui.SelectWidget.prototype.onToggle = function ( visible ) {
17609 if ( !visible ) {
17610 this.clearKeyPressBuffer();
17611 }
17612 };
17613
17614 /**
17615 * Get the closest item to a jQuery.Event.
17616 *
17617 * @private
17618 * @param {jQuery.Event} e
17619 * @return {OO.ui.OptionWidget|null} Outline item widget, `null` if none was found
17620 */
17621 OO.ui.SelectWidget.prototype.getTargetItem = function ( e ) {
17622 return $( e.target ).closest( '.oo-ui-optionWidget' ).data( 'oo-ui-optionWidget' ) || null;
17623 };
17624
17625 /**
17626 * Get selected item.
17627 *
17628 * @return {OO.ui.OptionWidget|null} Selected item, `null` if no item is selected
17629 */
17630 OO.ui.SelectWidget.prototype.getSelectedItem = function () {
17631 var i, len;
17632
17633 for ( i = 0, len = this.items.length; i < len; i++ ) {
17634 if ( this.items[ i ].isSelected() ) {
17635 return this.items[ i ];
17636 }
17637 }
17638 return null;
17639 };
17640
17641 /**
17642 * Get highlighted item.
17643 *
17644 * @return {OO.ui.OptionWidget|null} Highlighted item, `null` if no item is highlighted
17645 */
17646 OO.ui.SelectWidget.prototype.getHighlightedItem = function () {
17647 var i, len;
17648
17649 for ( i = 0, len = this.items.length; i < len; i++ ) {
17650 if ( this.items[ i ].isHighlighted() ) {
17651 return this.items[ i ];
17652 }
17653 }
17654 return null;
17655 };
17656
17657 /**
17658 * Toggle pressed state.
17659 *
17660 * Press is a state that occurs when a user mouses down on an item, but
17661 * has not yet let go of the mouse. The item may appear selected, but it will not be selected
17662 * until the user releases the mouse.
17663 *
17664 * @param {boolean} pressed An option is being pressed
17665 */
17666 OO.ui.SelectWidget.prototype.togglePressed = function ( pressed ) {
17667 if ( pressed === undefined ) {
17668 pressed = !this.pressed;
17669 }
17670 if ( pressed !== this.pressed ) {
17671 this.$element
17672 .toggleClass( 'oo-ui-selectWidget-pressed', pressed )
17673 .toggleClass( 'oo-ui-selectWidget-depressed', !pressed );
17674 this.pressed = pressed;
17675 }
17676 };
17677
17678 /**
17679 * Highlight an option. If the `item` param is omitted, no options will be highlighted
17680 * and any existing highlight will be removed. The highlight is mutually exclusive.
17681 *
17682 * @param {OO.ui.OptionWidget} [item] Item to highlight, omit for no highlight
17683 * @fires highlight
17684 * @chainable
17685 */
17686 OO.ui.SelectWidget.prototype.highlightItem = function ( item ) {
17687 var i, len, highlighted,
17688 changed = false;
17689
17690 for ( i = 0, len = this.items.length; i < len; i++ ) {
17691 highlighted = this.items[ i ] === item;
17692 if ( this.items[ i ].isHighlighted() !== highlighted ) {
17693 this.items[ i ].setHighlighted( highlighted );
17694 changed = true;
17695 }
17696 }
17697 if ( changed ) {
17698 this.emit( 'highlight', item );
17699 }
17700
17701 return this;
17702 };
17703
17704 /**
17705 * Fetch an item by its label.
17706 *
17707 * @param {string} label Label of the item to select.
17708 * @param {boolean} [prefix=false] Allow a prefix match, if only a single item matches
17709 * @return {OO.ui.Element|null} Item with equivalent label, `null` if none exists
17710 */
17711 OO.ui.SelectWidget.prototype.getItemFromLabel = function ( label, prefix ) {
17712 var i, item, found,
17713 len = this.items.length,
17714 filter = this.getItemMatcher( label, true );
17715
17716 for ( i = 0; i < len; i++ ) {
17717 item = this.items[i];
17718 if ( item instanceof OO.ui.OptionWidget && item.isSelectable() && filter( item ) ) {
17719 return item;
17720 }
17721 }
17722
17723 if ( prefix ) {
17724 found = null;
17725 filter = this.getItemMatcher( label, false );
17726 for ( i = 0; i < len; i++ ) {
17727 item = this.items[i];
17728 if ( item instanceof OO.ui.OptionWidget && item.isSelectable() && filter( item ) ) {
17729 if ( found ) {
17730 return null;
17731 }
17732 found = item;
17733 }
17734 }
17735 if ( found ) {
17736 return found;
17737 }
17738 }
17739
17740 return null;
17741 };
17742
17743 /**
17744 * Programmatically select an option by its label. If the item does not exist,
17745 * all options will be deselected.
17746 *
17747 * @param {string} [label] Label of the item to select.
17748 * @param {boolean} [prefix=false] Allow a prefix match, if only a single item matches
17749 * @fires select
17750 * @chainable
17751 */
17752 OO.ui.SelectWidget.prototype.selectItemByLabel = function ( label, prefix ) {
17753 var itemFromLabel = this.getItemFromLabel( label, !!prefix );
17754 if ( label === undefined || !itemFromLabel ) {
17755 return this.selectItem();
17756 }
17757 return this.selectItem( itemFromLabel );
17758 };
17759
17760 /**
17761 * Programmatically select an option by its data. If the `data` parameter is omitted,
17762 * or if the item does not exist, all options will be deselected.
17763 *
17764 * @param {Object|string} [data] Value of the item to select, omit to deselect all
17765 * @fires select
17766 * @chainable
17767 */
17768 OO.ui.SelectWidget.prototype.selectItemByData = function ( data ) {
17769 var itemFromData = this.getItemFromData( data );
17770 if ( data === undefined || !itemFromData ) {
17771 return this.selectItem();
17772 }
17773 return this.selectItem( itemFromData );
17774 };
17775
17776 /**
17777 * Programmatically select an option by its reference. If the `item` parameter is omitted,
17778 * all options will be deselected.
17779 *
17780 * @param {OO.ui.OptionWidget} [item] Item to select, omit to deselect all
17781 * @fires select
17782 * @chainable
17783 */
17784 OO.ui.SelectWidget.prototype.selectItem = function ( item ) {
17785 var i, len, selected,
17786 changed = false;
17787
17788 for ( i = 0, len = this.items.length; i < len; i++ ) {
17789 selected = this.items[ i ] === item;
17790 if ( this.items[ i ].isSelected() !== selected ) {
17791 this.items[ i ].setSelected( selected );
17792 changed = true;
17793 }
17794 }
17795 if ( changed ) {
17796 this.emit( 'select', item );
17797 }
17798
17799 return this;
17800 };
17801
17802 /**
17803 * Press an item.
17804 *
17805 * Press is a state that occurs when a user mouses down on an item, but has not
17806 * yet let go of the mouse. The item may appear selected, but it will not be selected until the user
17807 * releases the mouse.
17808 *
17809 * @param {OO.ui.OptionWidget} [item] Item to press, omit to depress all
17810 * @fires press
17811 * @chainable
17812 */
17813 OO.ui.SelectWidget.prototype.pressItem = function ( item ) {
17814 var i, len, pressed,
17815 changed = false;
17816
17817 for ( i = 0, len = this.items.length; i < len; i++ ) {
17818 pressed = this.items[ i ] === item;
17819 if ( this.items[ i ].isPressed() !== pressed ) {
17820 this.items[ i ].setPressed( pressed );
17821 changed = true;
17822 }
17823 }
17824 if ( changed ) {
17825 this.emit( 'press', item );
17826 }
17827
17828 return this;
17829 };
17830
17831 /**
17832 * Choose an item.
17833 *
17834 * Note that ‘choose’ should never be modified programmatically. A user can choose
17835 * an option with the keyboard or mouse and it becomes selected. To select an item programmatically,
17836 * use the #selectItem method.
17837 *
17838 * This method is identical to #selectItem, but may vary in subclasses that take additional action
17839 * when users choose an item with the keyboard or mouse.
17840 *
17841 * @param {OO.ui.OptionWidget} item Item to choose
17842 * @fires choose
17843 * @chainable
17844 */
17845 OO.ui.SelectWidget.prototype.chooseItem = function ( item ) {
17846 this.selectItem( item );
17847 this.emit( 'choose', item );
17848
17849 return this;
17850 };
17851
17852 /**
17853 * Get an option by its position relative to the specified item (or to the start of the option array,
17854 * if item is `null`). The direction in which to search through the option array is specified with a
17855 * number: -1 for reverse (the default) or 1 for forward. The method will return an option, or
17856 * `null` if there are no options in the array.
17857 *
17858 * @param {OO.ui.OptionWidget|null} item Item to describe the start position, or `null` to start at the beginning of the array.
17859 * @param {number} direction Direction to move in: -1 to move backward, 1 to move forward
17860 * @param {Function} filter Only consider items for which this function returns
17861 * true. Function takes an OO.ui.OptionWidget and returns a boolean.
17862 * @return {OO.ui.OptionWidget|null} Item at position, `null` if there are no items in the select
17863 */
17864 OO.ui.SelectWidget.prototype.getRelativeSelectableItem = function ( item, direction, filter ) {
17865 var currentIndex, nextIndex, i,
17866 increase = direction > 0 ? 1 : -1,
17867 len = this.items.length;
17868
17869 if ( !$.isFunction( filter ) ) {
17870 filter = OO.ui.SelectWidget.static.passAllFilter;
17871 }
17872
17873 if ( item instanceof OO.ui.OptionWidget ) {
17874 currentIndex = $.inArray( item, this.items );
17875 nextIndex = ( currentIndex + increase + len ) % len;
17876 } else {
17877 // If no item is selected and moving forward, start at the beginning.
17878 // If moving backward, start at the end.
17879 nextIndex = direction > 0 ? 0 : len - 1;
17880 }
17881
17882 for ( i = 0; i < len; i++ ) {
17883 item = this.items[ nextIndex ];
17884 if ( item instanceof OO.ui.OptionWidget && item.isSelectable() && filter( item ) ) {
17885 return item;
17886 }
17887 nextIndex = ( nextIndex + increase + len ) % len;
17888 }
17889 return null;
17890 };
17891
17892 /**
17893 * Get the next selectable item or `null` if there are no selectable items.
17894 * Disabled options and menu-section markers and breaks are not selectable.
17895 *
17896 * @return {OO.ui.OptionWidget|null} Item, `null` if there aren't any selectable items
17897 */
17898 OO.ui.SelectWidget.prototype.getFirstSelectableItem = function () {
17899 var i, len, item;
17900
17901 for ( i = 0, len = this.items.length; i < len; i++ ) {
17902 item = this.items[ i ];
17903 if ( item instanceof OO.ui.OptionWidget && item.isSelectable() ) {
17904 return item;
17905 }
17906 }
17907
17908 return null;
17909 };
17910
17911 /**
17912 * Add an array of options to the select. Optionally, an index number can be used to
17913 * specify an insertion point.
17914 *
17915 * @param {OO.ui.OptionWidget[]} items Items to add
17916 * @param {number} [index] Index to insert items after
17917 * @fires add
17918 * @chainable
17919 */
17920 OO.ui.SelectWidget.prototype.addItems = function ( items, index ) {
17921 // Mixin method
17922 OO.ui.mixin.GroupWidget.prototype.addItems.call( this, items, index );
17923
17924 // Always provide an index, even if it was omitted
17925 this.emit( 'add', items, index === undefined ? this.items.length - items.length - 1 : index );
17926
17927 return this;
17928 };
17929
17930 /**
17931 * Remove the specified array of options from the select. Options will be detached
17932 * from the DOM, not removed, so they can be reused later. To remove all options from
17933 * the select, you may wish to use the #clearItems method instead.
17934 *
17935 * @param {OO.ui.OptionWidget[]} items Items to remove
17936 * @fires remove
17937 * @chainable
17938 */
17939 OO.ui.SelectWidget.prototype.removeItems = function ( items ) {
17940 var i, len, item;
17941
17942 // Deselect items being removed
17943 for ( i = 0, len = items.length; i < len; i++ ) {
17944 item = items[ i ];
17945 if ( item.isSelected() ) {
17946 this.selectItem( null );
17947 }
17948 }
17949
17950 // Mixin method
17951 OO.ui.mixin.GroupWidget.prototype.removeItems.call( this, items );
17952
17953 this.emit( 'remove', items );
17954
17955 return this;
17956 };
17957
17958 /**
17959 * Clear all options from the select. Options will be detached from the DOM, not removed,
17960 * so that they can be reused later. To remove a subset of options from the select, use
17961 * the #removeItems method.
17962 *
17963 * @fires remove
17964 * @chainable
17965 */
17966 OO.ui.SelectWidget.prototype.clearItems = function () {
17967 var items = this.items.slice();
17968
17969 // Mixin method
17970 OO.ui.mixin.GroupWidget.prototype.clearItems.call( this );
17971
17972 // Clear selection
17973 this.selectItem( null );
17974
17975 this.emit( 'remove', items );
17976
17977 return this;
17978 };
17979
17980 /**
17981 * ButtonSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains
17982 * button options and is used together with
17983 * OO.ui.ButtonOptionWidget. The ButtonSelectWidget provides an interface for
17984 * highlighting, choosing, and selecting mutually exclusive options. Please see
17985 * the [OOjs UI documentation on MediaWiki] [1] for more information.
17986 *
17987 * @example
17988 * // Example: A ButtonSelectWidget that contains three ButtonOptionWidgets
17989 * var option1 = new OO.ui.ButtonOptionWidget( {
17990 * data: 1,
17991 * label: 'Option 1',
17992 * title: 'Button option 1'
17993 * } );
17994 *
17995 * var option2 = new OO.ui.ButtonOptionWidget( {
17996 * data: 2,
17997 * label: 'Option 2',
17998 * title: 'Button option 2'
17999 * } );
18000 *
18001 * var option3 = new OO.ui.ButtonOptionWidget( {
18002 * data: 3,
18003 * label: 'Option 3',
18004 * title: 'Button option 3'
18005 * } );
18006 *
18007 * var buttonSelect=new OO.ui.ButtonSelectWidget( {
18008 * items: [ option1, option2, option3 ]
18009 * } );
18010 * $( 'body' ).append( buttonSelect.$element );
18011 *
18012 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
18013 *
18014 * @class
18015 * @extends OO.ui.SelectWidget
18016 * @mixins OO.ui.mixin.TabIndexedElement
18017 *
18018 * @constructor
18019 * @param {Object} [config] Configuration options
18020 */
18021 OO.ui.ButtonSelectWidget = function OoUiButtonSelectWidget( config ) {
18022 // Parent constructor
18023 OO.ui.ButtonSelectWidget.parent.call( this, config );
18024
18025 // Mixin constructors
18026 OO.ui.mixin.TabIndexedElement.call( this, config );
18027
18028 // Events
18029 this.$element.on( {
18030 focus: this.bindKeyDownListener.bind( this ),
18031 blur: this.unbindKeyDownListener.bind( this )
18032 } );
18033
18034 // Initialization
18035 this.$element.addClass( 'oo-ui-buttonSelectWidget' );
18036 };
18037
18038 /* Setup */
18039
18040 OO.inheritClass( OO.ui.ButtonSelectWidget, OO.ui.SelectWidget );
18041 OO.mixinClass( OO.ui.ButtonSelectWidget, OO.ui.mixin.TabIndexedElement );
18042
18043 /**
18044 * RadioSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains radio
18045 * options and is used together with OO.ui.RadioOptionWidget. The RadioSelectWidget provides
18046 * an interface for adding, removing and selecting options.
18047 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
18048 *
18049 * If you want to use this within a HTML form, such as a OO.ui.FormLayout, use
18050 * OO.ui.RadioSelectInputWidget instead.
18051 *
18052 * @example
18053 * // A RadioSelectWidget with RadioOptions.
18054 * var option1 = new OO.ui.RadioOptionWidget( {
18055 * data: 'a',
18056 * label: 'Selected radio option'
18057 * } );
18058 *
18059 * var option2 = new OO.ui.RadioOptionWidget( {
18060 * data: 'b',
18061 * label: 'Unselected radio option'
18062 * } );
18063 *
18064 * var radioSelect=new OO.ui.RadioSelectWidget( {
18065 * items: [ option1, option2 ]
18066 * } );
18067 *
18068 * // Select 'option 1' using the RadioSelectWidget's selectItem() method.
18069 * radioSelect.selectItem( option1 );
18070 *
18071 * $( 'body' ).append( radioSelect.$element );
18072 *
18073 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
18074
18075 *
18076 * @class
18077 * @extends OO.ui.SelectWidget
18078 * @mixins OO.ui.mixin.TabIndexedElement
18079 *
18080 * @constructor
18081 * @param {Object} [config] Configuration options
18082 */
18083 OO.ui.RadioSelectWidget = function OoUiRadioSelectWidget( config ) {
18084 // Parent constructor
18085 OO.ui.RadioSelectWidget.parent.call( this, config );
18086
18087 // Mixin constructors
18088 OO.ui.mixin.TabIndexedElement.call( this, config );
18089
18090 // Events
18091 this.$element.on( {
18092 focus: this.bindKeyDownListener.bind( this ),
18093 blur: this.unbindKeyDownListener.bind( this )
18094 } );
18095
18096 // Initialization
18097 this.$element
18098 .addClass( 'oo-ui-radioSelectWidget' )
18099 .attr( 'role', 'radiogroup' );
18100 };
18101
18102 /* Setup */
18103
18104 OO.inheritClass( OO.ui.RadioSelectWidget, OO.ui.SelectWidget );
18105 OO.mixinClass( OO.ui.RadioSelectWidget, OO.ui.mixin.TabIndexedElement );
18106
18107 /**
18108 * MenuSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains options and
18109 * is used together with OO.ui.MenuOptionWidget. It is designed be used as part of another widget.
18110 * See {@link OO.ui.DropdownWidget DropdownWidget}, {@link OO.ui.ComboBoxWidget ComboBoxWidget},
18111 * and {@link OO.ui.mixin.LookupElement LookupElement} for examples of widgets that contain menus.
18112 * MenuSelectWidgets themselves are not instantiated directly, rather subclassed
18113 * and customized to be opened, closed, and displayed as needed.
18114 *
18115 * By default, menus are clipped to the visible viewport and are not visible when a user presses the
18116 * mouse outside the menu.
18117 *
18118 * Menus also have support for keyboard interaction:
18119 *
18120 * - Enter/Return key: choose and select a menu option
18121 * - Up-arrow key: highlight the previous menu option
18122 * - Down-arrow key: highlight the next menu option
18123 * - Esc key: hide the menu
18124 *
18125 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
18126 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
18127 *
18128 * @class
18129 * @extends OO.ui.SelectWidget
18130 * @mixins OO.ui.mixin.ClippableElement
18131 *
18132 * @constructor
18133 * @param {Object} [config] Configuration options
18134 * @cfg {OO.ui.TextInputWidget} [input] Text input used to implement option highlighting for menu items that match
18135 * the text the user types. This config is used by {@link OO.ui.ComboBoxWidget ComboBoxWidget}
18136 * and {@link OO.ui.mixin.LookupElement LookupElement}
18137 * @cfg {jQuery} [$input] Text input used to implement option highlighting for menu items that match
18138 * the text the user types. This config is used by {@link OO.ui.CapsuleMultiSelectWidget CapsuleMultiSelectWidget}
18139 * @cfg {OO.ui.Widget} [widget] Widget associated with the menu's active state. If the user clicks the mouse
18140 * anywhere on the page outside of this widget, the menu is hidden. For example, if there is a button
18141 * that toggles the menu's visibility on click, the menu will be hidden then re-shown when the user clicks
18142 * that button, unless the button (or its parent widget) is passed in here.
18143 * @cfg {boolean} [autoHide=true] Hide the menu when the mouse is pressed outside the menu.
18144 * @cfg {boolean} [filterFromInput=false] Filter the displayed options from the input
18145 */
18146 OO.ui.MenuSelectWidget = function OoUiMenuSelectWidget( config ) {
18147 // Configuration initialization
18148 config = config || {};
18149
18150 // Parent constructor
18151 OO.ui.MenuSelectWidget.parent.call( this, config );
18152
18153 // Mixin constructors
18154 OO.ui.mixin.ClippableElement.call( this, $.extend( {}, config, { $clippable: this.$group } ) );
18155
18156 // Properties
18157 this.newItems = null;
18158 this.autoHide = config.autoHide === undefined || !!config.autoHide;
18159 this.filterFromInput = !!config.filterFromInput;
18160 this.$input = config.$input ? config.$input : config.input ? config.input.$input : null;
18161 this.$widget = config.widget ? config.widget.$element : null;
18162 this.onDocumentMouseDownHandler = this.onDocumentMouseDown.bind( this );
18163 this.onInputEditHandler = OO.ui.debounce( this.updateItemVisibility.bind( this ), 100 );
18164
18165 // Initialization
18166 this.$element
18167 .addClass( 'oo-ui-menuSelectWidget' )
18168 .attr( 'role', 'menu' );
18169
18170 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
18171 // that reference properties not initialized at that time of parent class construction
18172 // TODO: Find a better way to handle post-constructor setup
18173 this.visible = false;
18174 this.$element.addClass( 'oo-ui-element-hidden' );
18175 };
18176
18177 /* Setup */
18178
18179 OO.inheritClass( OO.ui.MenuSelectWidget, OO.ui.SelectWidget );
18180 OO.mixinClass( OO.ui.MenuSelectWidget, OO.ui.mixin.ClippableElement );
18181
18182 /* Methods */
18183
18184 /**
18185 * Handles document mouse down events.
18186 *
18187 * @protected
18188 * @param {jQuery.Event} e Key down event
18189 */
18190 OO.ui.MenuSelectWidget.prototype.onDocumentMouseDown = function ( e ) {
18191 if (
18192 !OO.ui.contains( this.$element[ 0 ], e.target, true ) &&
18193 ( !this.$widget || !OO.ui.contains( this.$widget[ 0 ], e.target, true ) )
18194 ) {
18195 this.toggle( false );
18196 }
18197 };
18198
18199 /**
18200 * @inheritdoc
18201 */
18202 OO.ui.MenuSelectWidget.prototype.onKeyDown = function ( e ) {
18203 var currentItem = this.getHighlightedItem() || this.getSelectedItem();
18204
18205 if ( !this.isDisabled() && this.isVisible() ) {
18206 switch ( e.keyCode ) {
18207 case OO.ui.Keys.LEFT:
18208 case OO.ui.Keys.RIGHT:
18209 // Do nothing if a text field is associated, arrow keys will be handled natively
18210 if ( !this.$input ) {
18211 OO.ui.MenuSelectWidget.parent.prototype.onKeyDown.call( this, e );
18212 }
18213 break;
18214 case OO.ui.Keys.ESCAPE:
18215 case OO.ui.Keys.TAB:
18216 if ( currentItem ) {
18217 currentItem.setHighlighted( false );
18218 }
18219 this.toggle( false );
18220 // Don't prevent tabbing away, prevent defocusing
18221 if ( e.keyCode === OO.ui.Keys.ESCAPE ) {
18222 e.preventDefault();
18223 e.stopPropagation();
18224 }
18225 break;
18226 default:
18227 OO.ui.MenuSelectWidget.parent.prototype.onKeyDown.call( this, e );
18228 return;
18229 }
18230 }
18231 };
18232
18233 /**
18234 * Update menu item visibility after input changes.
18235 * @protected
18236 */
18237 OO.ui.MenuSelectWidget.prototype.updateItemVisibility = function () {
18238 var i, item,
18239 len = this.items.length,
18240 showAll = !this.isVisible(),
18241 filter = showAll ? null : this.getItemMatcher( this.$input.val() );
18242
18243 for ( i = 0; i < len; i++ ) {
18244 item = this.items[i];
18245 if ( item instanceof OO.ui.OptionWidget ) {
18246 item.toggle( showAll || filter( item ) );
18247 }
18248 }
18249
18250 // Reevaluate clipping
18251 this.clip();
18252 };
18253
18254 /**
18255 * @inheritdoc
18256 */
18257 OO.ui.MenuSelectWidget.prototype.bindKeyDownListener = function () {
18258 if ( this.$input ) {
18259 this.$input.on( 'keydown', this.onKeyDownHandler );
18260 } else {
18261 OO.ui.MenuSelectWidget.parent.prototype.bindKeyDownListener.call( this );
18262 }
18263 };
18264
18265 /**
18266 * @inheritdoc
18267 */
18268 OO.ui.MenuSelectWidget.prototype.unbindKeyDownListener = function () {
18269 if ( this.$input ) {
18270 this.$input.off( 'keydown', this.onKeyDownHandler );
18271 } else {
18272 OO.ui.MenuSelectWidget.parent.prototype.unbindKeyDownListener.call( this );
18273 }
18274 };
18275
18276 /**
18277 * @inheritdoc
18278 */
18279 OO.ui.MenuSelectWidget.prototype.bindKeyPressListener = function () {
18280 if ( this.$input ) {
18281 if ( this.filterFromInput ) {
18282 this.$input.on( 'keydown mouseup cut paste change input select', this.onInputEditHandler );
18283 }
18284 } else {
18285 OO.ui.MenuSelectWidget.parent.prototype.bindKeyPressListener.call( this );
18286 }
18287 };
18288
18289 /**
18290 * @inheritdoc
18291 */
18292 OO.ui.MenuSelectWidget.prototype.unbindKeyPressListener = function () {
18293 if ( this.$input ) {
18294 if ( this.filterFromInput ) {
18295 this.$input.off( 'keydown mouseup cut paste change input select', this.onInputEditHandler );
18296 this.updateItemVisibility();
18297 }
18298 } else {
18299 OO.ui.MenuSelectWidget.parent.prototype.unbindKeyPressListener.call( this );
18300 }
18301 };
18302
18303 /**
18304 * Choose an item.
18305 *
18306 * When a user chooses an item, the menu is closed.
18307 *
18308 * Note that ‘choose’ should never be modified programmatically. A user can choose an option with the keyboard
18309 * or mouse and it becomes selected. To select an item programmatically, use the #selectItem method.
18310 * @param {OO.ui.OptionWidget} item Item to choose
18311 * @chainable
18312 */
18313 OO.ui.MenuSelectWidget.prototype.chooseItem = function ( item ) {
18314 OO.ui.MenuSelectWidget.parent.prototype.chooseItem.call( this, item );
18315 this.toggle( false );
18316 return this;
18317 };
18318
18319 /**
18320 * @inheritdoc
18321 */
18322 OO.ui.MenuSelectWidget.prototype.addItems = function ( items, index ) {
18323 var i, len, item;
18324
18325 // Parent method
18326 OO.ui.MenuSelectWidget.parent.prototype.addItems.call( this, items, index );
18327
18328 // Auto-initialize
18329 if ( !this.newItems ) {
18330 this.newItems = [];
18331 }
18332
18333 for ( i = 0, len = items.length; i < len; i++ ) {
18334 item = items[ i ];
18335 if ( this.isVisible() ) {
18336 // Defer fitting label until item has been attached
18337 item.fitLabel();
18338 } else {
18339 this.newItems.push( item );
18340 }
18341 }
18342
18343 // Reevaluate clipping
18344 this.clip();
18345
18346 return this;
18347 };
18348
18349 /**
18350 * @inheritdoc
18351 */
18352 OO.ui.MenuSelectWidget.prototype.removeItems = function ( items ) {
18353 // Parent method
18354 OO.ui.MenuSelectWidget.parent.prototype.removeItems.call( this, items );
18355
18356 // Reevaluate clipping
18357 this.clip();
18358
18359 return this;
18360 };
18361
18362 /**
18363 * @inheritdoc
18364 */
18365 OO.ui.MenuSelectWidget.prototype.clearItems = function () {
18366 // Parent method
18367 OO.ui.MenuSelectWidget.parent.prototype.clearItems.call( this );
18368
18369 // Reevaluate clipping
18370 this.clip();
18371
18372 return this;
18373 };
18374
18375 /**
18376 * @inheritdoc
18377 */
18378 OO.ui.MenuSelectWidget.prototype.toggle = function ( visible ) {
18379 visible = ( visible === undefined ? !this.visible : !!visible ) && !!this.items.length;
18380
18381 var i, len,
18382 change = visible !== this.isVisible();
18383
18384 // Parent method
18385 OO.ui.MenuSelectWidget.parent.prototype.toggle.call( this, visible );
18386
18387 if ( change ) {
18388 if ( visible ) {
18389 this.bindKeyDownListener();
18390 this.bindKeyPressListener();
18391
18392 if ( this.newItems && this.newItems.length ) {
18393 for ( i = 0, len = this.newItems.length; i < len; i++ ) {
18394 this.newItems[ i ].fitLabel();
18395 }
18396 this.newItems = null;
18397 }
18398 this.toggleClipping( true );
18399
18400 // Auto-hide
18401 if ( this.autoHide ) {
18402 this.getElementDocument().addEventListener(
18403 'mousedown', this.onDocumentMouseDownHandler, true
18404 );
18405 }
18406 } else {
18407 this.unbindKeyDownListener();
18408 this.unbindKeyPressListener();
18409 this.getElementDocument().removeEventListener(
18410 'mousedown', this.onDocumentMouseDownHandler, true
18411 );
18412 this.toggleClipping( false );
18413 }
18414 }
18415
18416 return this;
18417 };
18418
18419 /**
18420 * TextInputMenuSelectWidget is a menu that is specially designed to be positioned beneath
18421 * a {@link OO.ui.TextInputWidget text input} field. The menu's position is automatically
18422 * calculated and maintained when the menu is toggled or the window is resized.
18423 * See OO.ui.ComboBoxWidget for an example of a widget that uses this class.
18424 *
18425 * @class
18426 * @extends OO.ui.MenuSelectWidget
18427 *
18428 * @constructor
18429 * @param {OO.ui.TextInputWidget} inputWidget Text input widget to provide menu for
18430 * @param {Object} [config] Configuration options
18431 * @cfg {jQuery} [$container=input.$element] Element to render menu under
18432 */
18433 OO.ui.TextInputMenuSelectWidget = function OoUiTextInputMenuSelectWidget( inputWidget, config ) {
18434 // Allow passing positional parameters inside the config object
18435 if ( OO.isPlainObject( inputWidget ) && config === undefined ) {
18436 config = inputWidget;
18437 inputWidget = config.inputWidget;
18438 }
18439
18440 // Configuration initialization
18441 config = config || {};
18442
18443 // Parent constructor
18444 OO.ui.TextInputMenuSelectWidget.parent.call( this, config );
18445
18446 // Properties
18447 this.inputWidget = inputWidget;
18448 this.$container = config.$container || this.inputWidget.$element;
18449 this.onWindowResizeHandler = this.onWindowResize.bind( this );
18450
18451 // Initialization
18452 this.$element.addClass( 'oo-ui-textInputMenuSelectWidget' );
18453 };
18454
18455 /* Setup */
18456
18457 OO.inheritClass( OO.ui.TextInputMenuSelectWidget, OO.ui.MenuSelectWidget );
18458
18459 /* Methods */
18460
18461 /**
18462 * Handle window resize event.
18463 *
18464 * @private
18465 * @param {jQuery.Event} e Window resize event
18466 */
18467 OO.ui.TextInputMenuSelectWidget.prototype.onWindowResize = function () {
18468 this.position();
18469 };
18470
18471 /**
18472 * @inheritdoc
18473 */
18474 OO.ui.TextInputMenuSelectWidget.prototype.toggle = function ( visible ) {
18475 visible = visible === undefined ? !this.isVisible() : !!visible;
18476
18477 var change = visible !== this.isVisible();
18478
18479 if ( change && visible ) {
18480 // Make sure the width is set before the parent method runs.
18481 // After this we have to call this.position(); again to actually
18482 // position ourselves correctly.
18483 this.position();
18484 }
18485
18486 // Parent method
18487 OO.ui.TextInputMenuSelectWidget.parent.prototype.toggle.call( this, visible );
18488
18489 if ( change ) {
18490 if ( this.isVisible() ) {
18491 this.position();
18492 $( this.getElementWindow() ).on( 'resize', this.onWindowResizeHandler );
18493 } else {
18494 $( this.getElementWindow() ).off( 'resize', this.onWindowResizeHandler );
18495 }
18496 }
18497
18498 return this;
18499 };
18500
18501 /**
18502 * Position the menu.
18503 *
18504 * @private
18505 * @chainable
18506 */
18507 OO.ui.TextInputMenuSelectWidget.prototype.position = function () {
18508 var $container = this.$container,
18509 pos = OO.ui.Element.static.getRelativePosition( $container, this.$element.offsetParent() );
18510
18511 // Position under input
18512 pos.top += $container.height();
18513 this.$element.css( pos );
18514
18515 // Set width
18516 this.setIdealSize( $container.width() );
18517 // We updated the position, so re-evaluate the clipping state
18518 this.clip();
18519
18520 return this;
18521 };
18522
18523 /**
18524 * OutlineSelectWidget is a structured list that contains {@link OO.ui.OutlineOptionWidget outline options}
18525 * A set of controls can be provided with an {@link OO.ui.OutlineControlsWidget outline controls} widget.
18526 *
18527 * **Currently, this class is only used by {@link OO.ui.BookletLayout booklet layouts}.**
18528 *
18529 * @class
18530 * @extends OO.ui.SelectWidget
18531 * @mixins OO.ui.mixin.TabIndexedElement
18532 *
18533 * @constructor
18534 * @param {Object} [config] Configuration options
18535 */
18536 OO.ui.OutlineSelectWidget = function OoUiOutlineSelectWidget( config ) {
18537 // Parent constructor
18538 OO.ui.OutlineSelectWidget.parent.call( this, config );
18539
18540 // Mixin constructors
18541 OO.ui.mixin.TabIndexedElement.call( this, config );
18542
18543 // Events
18544 this.$element.on( {
18545 focus: this.bindKeyDownListener.bind( this ),
18546 blur: this.unbindKeyDownListener.bind( this )
18547 } );
18548
18549 // Initialization
18550 this.$element.addClass( 'oo-ui-outlineSelectWidget' );
18551 };
18552
18553 /* Setup */
18554
18555 OO.inheritClass( OO.ui.OutlineSelectWidget, OO.ui.SelectWidget );
18556 OO.mixinClass( OO.ui.OutlineSelectWidget, OO.ui.mixin.TabIndexedElement );
18557
18558 /**
18559 * TabSelectWidget is a list that contains {@link OO.ui.TabOptionWidget tab options}
18560 *
18561 * **Currently, this class is only used by {@link OO.ui.IndexLayout index layouts}.**
18562 *
18563 * @class
18564 * @extends OO.ui.SelectWidget
18565 * @mixins OO.ui.mixin.TabIndexedElement
18566 *
18567 * @constructor
18568 * @param {Object} [config] Configuration options
18569 */
18570 OO.ui.TabSelectWidget = function OoUiTabSelectWidget( config ) {
18571 // Parent constructor
18572 OO.ui.TabSelectWidget.parent.call( this, config );
18573
18574 // Mixin constructors
18575 OO.ui.mixin.TabIndexedElement.call( this, config );
18576
18577 // Events
18578 this.$element.on( {
18579 focus: this.bindKeyDownListener.bind( this ),
18580 blur: this.unbindKeyDownListener.bind( this )
18581 } );
18582
18583 // Initialization
18584 this.$element.addClass( 'oo-ui-tabSelectWidget' );
18585 };
18586
18587 /* Setup */
18588
18589 OO.inheritClass( OO.ui.TabSelectWidget, OO.ui.SelectWidget );
18590 OO.mixinClass( OO.ui.TabSelectWidget, OO.ui.mixin.TabIndexedElement );
18591
18592 /**
18593 * NumberInputWidgets combine a {@link OO.ui.TextInputWidget text input} (where a value
18594 * can be entered manually) and two {@link OO.ui.ButtonWidget button widgets}
18595 * (to adjust the value in increments) to allow the user to enter a number.
18596 *
18597 * @example
18598 * // Example: A NumberInputWidget.
18599 * var numberInput = new OO.ui.NumberInputWidget( {
18600 * label: 'NumberInputWidget',
18601 * input: { value: 5, min: 1, max: 10 }
18602 * } );
18603 * $( 'body' ).append( numberInput.$element );
18604 *
18605 * @class
18606 * @extends OO.ui.Widget
18607 *
18608 * @constructor
18609 * @param {Object} [config] Configuration options
18610 * @cfg {Object} [input] Configuration options to pass to the {@link OO.ui.TextInputWidget text input widget}.
18611 * @cfg {Object} [minusButton] Configuration options to pass to the {@link OO.ui.ButtonWidget decrementing button widget}.
18612 * @cfg {Object} [plusButton] Configuration options to pass to the {@link OO.ui.ButtonWidget incrementing button widget}.
18613 * @cfg {boolean} [isInteger=false] Whether the field accepts only integer values.
18614 * @cfg {number} [min=-Infinity] Minimum allowed value
18615 * @cfg {number} [max=Infinity] Maximum allowed value
18616 * @cfg {number} [step=1] Delta when using the buttons or up/down arrow keys
18617 * @cfg {number|null} [pageStep] Delta when using the page-up/page-down keys. Defaults to 10 times #step.
18618 */
18619 OO.ui.NumberInputWidget = function OoUiNumberInputWidget( config ) {
18620 // Configuration initialization
18621 config = $.extend( {
18622 isInteger: false,
18623 min: -Infinity,
18624 max: Infinity,
18625 step: 1,
18626 pageStep: null
18627 }, config );
18628
18629 // Parent constructor
18630 OO.ui.NumberInputWidget.parent.call( this, config );
18631
18632 // Properties
18633 this.input = new OO.ui.TextInputWidget( $.extend(
18634 {
18635 disabled: this.isDisabled()
18636 },
18637 config.input
18638 ) );
18639 this.minusButton = new OO.ui.ButtonWidget( $.extend(
18640 {
18641 disabled: this.isDisabled(),
18642 tabIndex: -1
18643 },
18644 config.minusButton,
18645 {
18646 classes: [ 'oo-ui-numberInputWidget-minusButton' ],
18647 label: '−'
18648 }
18649 ) );
18650 this.plusButton = new OO.ui.ButtonWidget( $.extend(
18651 {
18652 disabled: this.isDisabled(),
18653 tabIndex: -1
18654 },
18655 config.plusButton,
18656 {
18657 classes: [ 'oo-ui-numberInputWidget-plusButton' ],
18658 label: '+'
18659 }
18660 ) );
18661
18662 // Events
18663 this.input.connect( this, {
18664 change: this.emit.bind( this, 'change' ),
18665 enter: this.emit.bind( this, 'enter' )
18666 } );
18667 this.input.$input.on( {
18668 keydown: this.onKeyDown.bind( this ),
18669 'wheel mousewheel DOMMouseScroll': this.onWheel.bind( this )
18670 } );
18671 this.plusButton.connect( this, {
18672 click: [ 'onButtonClick', +1 ]
18673 } );
18674 this.minusButton.connect( this, {
18675 click: [ 'onButtonClick', -1 ]
18676 } );
18677
18678 // Initialization
18679 this.setIsInteger( !!config.isInteger );
18680 this.setRange( config.min, config.max );
18681 this.setStep( config.step, config.pageStep );
18682
18683 this.$field = $( '<div>' ).addClass( 'oo-ui-numberInputWidget-field' )
18684 .append(
18685 this.minusButton.$element,
18686 this.input.$element,
18687 this.plusButton.$element
18688 );
18689 this.$element.addClass( 'oo-ui-numberInputWidget' ).append( this.$field );
18690 this.input.setValidation( this.validateNumber.bind( this ) );
18691 };
18692
18693 /* Setup */
18694
18695 OO.inheritClass( OO.ui.NumberInputWidget, OO.ui.Widget );
18696
18697 /* Events */
18698
18699 /**
18700 * A `change` event is emitted when the value of the input changes.
18701 *
18702 * @event change
18703 */
18704
18705 /**
18706 * An `enter` event is emitted when the user presses 'enter' inside the text box.
18707 *
18708 * @event enter
18709 */
18710
18711 /* Methods */
18712
18713 /**
18714 * Set whether only integers are allowed
18715 * @param {boolean} flag
18716 */
18717 OO.ui.NumberInputWidget.prototype.setIsInteger = function ( flag ) {
18718 this.isInteger = !!flag;
18719 this.input.setValidityFlag();
18720 };
18721
18722 /**
18723 * Get whether only integers are allowed
18724 * @return {boolean} Flag value
18725 */
18726 OO.ui.NumberInputWidget.prototype.getIsInteger = function () {
18727 return this.isInteger;
18728 };
18729
18730 /**
18731 * Set the range of allowed values
18732 * @param {number} min Minimum allowed value
18733 * @param {number} max Maximum allowed value
18734 */
18735 OO.ui.NumberInputWidget.prototype.setRange = function ( min, max ) {
18736 if ( min > max ) {
18737 throw new Error( 'Minimum (' + min + ') must not be greater than maximum (' + max + ')' );
18738 }
18739 this.min = min;
18740 this.max = max;
18741 this.input.setValidityFlag();
18742 };
18743
18744 /**
18745 * Get the current range
18746 * @return {number[]} Minimum and maximum values
18747 */
18748 OO.ui.NumberInputWidget.prototype.getRange = function () {
18749 return [ this.min, this.max ];
18750 };
18751
18752 /**
18753 * Set the stepping deltas
18754 * @param {number} step Normal step
18755 * @param {number|null} pageStep Page step. If null, 10 * step will be used.
18756 */
18757 OO.ui.NumberInputWidget.prototype.setStep = function ( step, pageStep ) {
18758 if ( step <= 0 ) {
18759 throw new Error( 'Step value must be positive' );
18760 }
18761 if ( pageStep === null ) {
18762 pageStep = step * 10;
18763 } else if ( pageStep <= 0 ) {
18764 throw new Error( 'Page step value must be positive' );
18765 }
18766 this.step = step;
18767 this.pageStep = pageStep;
18768 };
18769
18770 /**
18771 * Get the current stepping values
18772 * @return {number[]} Step and page step
18773 */
18774 OO.ui.NumberInputWidget.prototype.getStep = function () {
18775 return [ this.step, this.pageStep ];
18776 };
18777
18778 /**
18779 * Get the current value of the widget
18780 * @return {string}
18781 */
18782 OO.ui.NumberInputWidget.prototype.getValue = function () {
18783 return this.input.getValue();
18784 };
18785
18786 /**
18787 * Get the current value of the widget as a number
18788 * @return {number} May be NaN, or an invalid number
18789 */
18790 OO.ui.NumberInputWidget.prototype.getNumericValue = function () {
18791 return +this.input.getValue();
18792 };
18793
18794 /**
18795 * Set the value of the widget
18796 * @param {string} value Invalid values are allowed
18797 */
18798 OO.ui.NumberInputWidget.prototype.setValue = function ( value ) {
18799 this.input.setValue( value );
18800 };
18801
18802 /**
18803 * Adjust the value of the widget
18804 * @param {number} delta Adjustment amount
18805 */
18806 OO.ui.NumberInputWidget.prototype.adjustValue = function ( delta ) {
18807 var n, v = this.getNumericValue();
18808
18809 delta = +delta;
18810 if ( isNaN( delta ) || !isFinite( delta ) ) {
18811 throw new Error( 'Delta must be a finite number' );
18812 }
18813
18814 if ( isNaN( v ) ) {
18815 n = 0;
18816 } else {
18817 n = v + delta;
18818 n = Math.max( Math.min( n, this.max ), this.min );
18819 if ( this.isInteger ) {
18820 n = Math.round( n );
18821 }
18822 }
18823
18824 if ( n !== v ) {
18825 this.setValue( n );
18826 }
18827 };
18828
18829 /**
18830 * Validate input
18831 * @private
18832 * @param {string} value Field value
18833 * @return {boolean}
18834 */
18835 OO.ui.NumberInputWidget.prototype.validateNumber = function ( value ) {
18836 var n = +value;
18837 if ( isNaN( n ) || !isFinite( n ) ) {
18838 return false;
18839 }
18840
18841 /*jshint bitwise: false */
18842 if ( this.isInteger && ( n | 0 ) !== n ) {
18843 return false;
18844 }
18845 /*jshint bitwise: true */
18846
18847 if ( n < this.min || n > this.max ) {
18848 return false;
18849 }
18850
18851 return true;
18852 };
18853
18854 /**
18855 * Handle mouse click events.
18856 *
18857 * @private
18858 * @param {number} dir +1 or -1
18859 */
18860 OO.ui.NumberInputWidget.prototype.onButtonClick = function ( dir ) {
18861 this.adjustValue( dir * this.step );
18862 };
18863
18864 /**
18865 * Handle mouse wheel events.
18866 *
18867 * @private
18868 * @param {jQuery.Event} event
18869 */
18870 OO.ui.NumberInputWidget.prototype.onWheel = function ( event ) {
18871 var delta = 0;
18872
18873 // Standard 'wheel' event
18874 if ( event.originalEvent.deltaMode !== undefined ) {
18875 this.sawWheelEvent = true;
18876 }
18877 if ( event.originalEvent.deltaY ) {
18878 delta = -event.originalEvent.deltaY;
18879 } else if ( event.originalEvent.deltaX ) {
18880 delta = event.originalEvent.deltaX;
18881 }
18882
18883 // Non-standard events
18884 if ( !this.sawWheelEvent ) {
18885 if ( event.originalEvent.wheelDeltaX ) {
18886 delta = -event.originalEvent.wheelDeltaX;
18887 } else if ( event.originalEvent.wheelDeltaY ) {
18888 delta = event.originalEvent.wheelDeltaY;
18889 } else if ( event.originalEvent.wheelDelta ) {
18890 delta = event.originalEvent.wheelDelta;
18891 } else if ( event.originalEvent.detail ) {
18892 delta = -event.originalEvent.detail;
18893 }
18894 }
18895
18896 if ( delta ) {
18897 delta = delta < 0 ? -1 : 1;
18898 this.adjustValue( delta * this.step );
18899 }
18900
18901 return false;
18902 };
18903
18904 /**
18905 * Handle key down events.
18906 *
18907 *
18908 * @private
18909 * @param {jQuery.Event} e Key down event
18910 */
18911 OO.ui.NumberInputWidget.prototype.onKeyDown = function ( e ) {
18912 if ( !this.isDisabled() ) {
18913 switch ( e.which ) {
18914 case OO.ui.Keys.UP:
18915 this.adjustValue( this.step );
18916 return false;
18917 case OO.ui.Keys.DOWN:
18918 this.adjustValue( -this.step );
18919 return false;
18920 case OO.ui.Keys.PAGEUP:
18921 this.adjustValue( this.pageStep );
18922 return false;
18923 case OO.ui.Keys.PAGEDOWN:
18924 this.adjustValue( -this.pageStep );
18925 return false;
18926 }
18927 }
18928 };
18929
18930 /**
18931 * @inheritdoc
18932 */
18933 OO.ui.NumberInputWidget.prototype.setDisabled = function ( disabled ) {
18934 // Parent method
18935 OO.ui.NumberInputWidget.parent.prototype.setDisabled.call( this, disabled );
18936
18937 if ( this.input ) {
18938 this.input.setDisabled( this.isDisabled() );
18939 }
18940 if ( this.minusButton ) {
18941 this.minusButton.setDisabled( this.isDisabled() );
18942 }
18943 if ( this.plusButton ) {
18944 this.plusButton.setDisabled( this.isDisabled() );
18945 }
18946
18947 return this;
18948 };
18949
18950 /**
18951 * ToggleSwitches are switches that slide on and off. Their state is represented by a Boolean
18952 * value (`true` for ‘on’, and `false` otherwise, the default). The ‘off’ state is represented
18953 * visually by a slider in the leftmost position.
18954 *
18955 * @example
18956 * // Toggle switches in the 'off' and 'on' position.
18957 * var toggleSwitch1 = new OO.ui.ToggleSwitchWidget();
18958 * var toggleSwitch2 = new OO.ui.ToggleSwitchWidget( {
18959 * value: true
18960 * } );
18961 *
18962 * // Create a FieldsetLayout to layout and label switches
18963 * var fieldset = new OO.ui.FieldsetLayout( {
18964 * label: 'Toggle switches'
18965 * } );
18966 * fieldset.addItems( [
18967 * new OO.ui.FieldLayout( toggleSwitch1, { label: 'Off', align: 'top' } ),
18968 * new OO.ui.FieldLayout( toggleSwitch2, { label: 'On', align: 'top' } )
18969 * ] );
18970 * $( 'body' ).append( fieldset.$element );
18971 *
18972 * @class
18973 * @extends OO.ui.ToggleWidget
18974 * @mixins OO.ui.mixin.TabIndexedElement
18975 *
18976 * @constructor
18977 * @param {Object} [config] Configuration options
18978 * @cfg {boolean} [value=false] The toggle switch’s initial on/off state.
18979 * By default, the toggle switch is in the 'off' position.
18980 */
18981 OO.ui.ToggleSwitchWidget = function OoUiToggleSwitchWidget( config ) {
18982 // Parent constructor
18983 OO.ui.ToggleSwitchWidget.parent.call( this, config );
18984
18985 // Mixin constructors
18986 OO.ui.mixin.TabIndexedElement.call( this, config );
18987
18988 // Properties
18989 this.dragging = false;
18990 this.dragStart = null;
18991 this.sliding = false;
18992 this.$glow = $( '<span>' );
18993 this.$grip = $( '<span>' );
18994
18995 // Events
18996 this.$element.on( {
18997 click: this.onClick.bind( this ),
18998 keypress: this.onKeyPress.bind( this )
18999 } );
19000
19001 // Initialization
19002 this.$glow.addClass( 'oo-ui-toggleSwitchWidget-glow' );
19003 this.$grip.addClass( 'oo-ui-toggleSwitchWidget-grip' );
19004 this.$element
19005 .addClass( 'oo-ui-toggleSwitchWidget' )
19006 .attr( 'role', 'checkbox' )
19007 .append( this.$glow, this.$grip );
19008 };
19009
19010 /* Setup */
19011
19012 OO.inheritClass( OO.ui.ToggleSwitchWidget, OO.ui.ToggleWidget );
19013 OO.mixinClass( OO.ui.ToggleSwitchWidget, OO.ui.mixin.TabIndexedElement );
19014
19015 /* Methods */
19016
19017 /**
19018 * Handle mouse click events.
19019 *
19020 * @private
19021 * @param {jQuery.Event} e Mouse click event
19022 */
19023 OO.ui.ToggleSwitchWidget.prototype.onClick = function ( e ) {
19024 if ( !this.isDisabled() && e.which === 1 ) {
19025 this.setValue( !this.value );
19026 }
19027 return false;
19028 };
19029
19030 /**
19031 * Handle key press events.
19032 *
19033 * @private
19034 * @param {jQuery.Event} e Key press event
19035 */
19036 OO.ui.ToggleSwitchWidget.prototype.onKeyPress = function ( e ) {
19037 if ( !this.isDisabled() && ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER ) ) {
19038 this.setValue( !this.value );
19039 return false;
19040 }
19041 };
19042
19043 /*!
19044 * Deprecated aliases for classes in the `OO.ui.mixin` namespace.
19045 */
19046
19047 /**
19048 * @inheritdoc OO.ui.mixin.ButtonElement
19049 * @deprecated Use {@link OO.ui.mixin.ButtonElement} instead.
19050 */
19051 OO.ui.ButtonElement = OO.ui.mixin.ButtonElement;
19052
19053 /**
19054 * @inheritdoc OO.ui.mixin.ClippableElement
19055 * @deprecated Use {@link OO.ui.mixin.ClippableElement} instead.
19056 */
19057 OO.ui.ClippableElement = OO.ui.mixin.ClippableElement;
19058
19059 /**
19060 * @inheritdoc OO.ui.mixin.DraggableElement
19061 * @deprecated Use {@link OO.ui.mixin.DraggableElement} instead.
19062 */
19063 OO.ui.DraggableElement = OO.ui.mixin.DraggableElement;
19064
19065 /**
19066 * @inheritdoc OO.ui.mixin.DraggableGroupElement
19067 * @deprecated Use {@link OO.ui.mixin.DraggableGroupElement} instead.
19068 */
19069 OO.ui.DraggableGroupElement = OO.ui.mixin.DraggableGroupElement;
19070
19071 /**
19072 * @inheritdoc OO.ui.mixin.FlaggedElement
19073 * @deprecated Use {@link OO.ui.mixin.FlaggedElement} instead.
19074 */
19075 OO.ui.FlaggedElement = OO.ui.mixin.FlaggedElement;
19076
19077 /**
19078 * @inheritdoc OO.ui.mixin.GroupElement
19079 * @deprecated Use {@link OO.ui.mixin.GroupElement} instead.
19080 */
19081 OO.ui.GroupElement = OO.ui.mixin.GroupElement;
19082
19083 /**
19084 * @inheritdoc OO.ui.mixin.GroupWidget
19085 * @deprecated Use {@link OO.ui.mixin.GroupWidget} instead.
19086 */
19087 OO.ui.GroupWidget = OO.ui.mixin.GroupWidget;
19088
19089 /**
19090 * @inheritdoc OO.ui.mixin.IconElement
19091 * @deprecated Use {@link OO.ui.mixin.IconElement} instead.
19092 */
19093 OO.ui.IconElement = OO.ui.mixin.IconElement;
19094
19095 /**
19096 * @inheritdoc OO.ui.mixin.IndicatorElement
19097 * @deprecated Use {@link OO.ui.mixin.IndicatorElement} instead.
19098 */
19099 OO.ui.IndicatorElement = OO.ui.mixin.IndicatorElement;
19100
19101 /**
19102 * @inheritdoc OO.ui.mixin.ItemWidget
19103 * @deprecated Use {@link OO.ui.mixin.ItemWidget} instead.
19104 */
19105 OO.ui.ItemWidget = OO.ui.mixin.ItemWidget;
19106
19107 /**
19108 * @inheritdoc OO.ui.mixin.LabelElement
19109 * @deprecated Use {@link OO.ui.mixin.LabelElement} instead.
19110 */
19111 OO.ui.LabelElement = OO.ui.mixin.LabelElement;
19112
19113 /**
19114 * @inheritdoc OO.ui.mixin.LookupElement
19115 * @deprecated Use {@link OO.ui.mixin.LookupElement} instead.
19116 */
19117 OO.ui.LookupElement = OO.ui.mixin.LookupElement;
19118
19119 /**
19120 * @inheritdoc OO.ui.mixin.PendingElement
19121 * @deprecated Use {@link OO.ui.mixin.PendingElement} instead.
19122 */
19123 OO.ui.PendingElement = OO.ui.mixin.PendingElement;
19124
19125 /**
19126 * @inheritdoc OO.ui.mixin.PopupElement
19127 * @deprecated Use {@link OO.ui.mixin.PopupElement} instead.
19128 */
19129 OO.ui.PopupElement = OO.ui.mixin.PopupElement;
19130
19131 /**
19132 * @inheritdoc OO.ui.mixin.TabIndexedElement
19133 * @deprecated Use {@link OO.ui.mixin.TabIndexedElement} instead.
19134 */
19135 OO.ui.TabIndexedElement = OO.ui.mixin.TabIndexedElement;
19136
19137 /**
19138 * @inheritdoc OO.ui.mixin.TitledElement
19139 * @deprecated Use {@link OO.ui.mixin.TitledElement} instead.
19140 */
19141 OO.ui.TitledElement = OO.ui.mixin.TitledElement;
19142
19143 }( OO ) );