Merge "Fixed BufferingStatsdDataFactory::timing() callers to use ms"
[lhc/web/wiklou.git] / resources / lib / oojs-ui / oojs-ui.js
1 /*!
2 * OOjs UI v0.12.5
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-19T02:10:17Z
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 * Proxy for `node.addEventListener( eventName, handler, true )`, if the browser supports it.
203 * Otherwise falls back to non-capturing event listeners.
204 *
205 * @param {HTMLElement} node
206 * @param {string} eventName
207 * @param {Function} handler
208 */
209 OO.ui.addCaptureEventListener = function ( node, eventName, handler ) {
210 if ( node.addEventListener ) {
211 node.addEventListener( eventName, handler, true );
212 } else {
213 node.attachEvent( 'on' + eventName, handler );
214 }
215 };
216
217 /**
218 * Proxy for `node.removeEventListener( eventName, handler, true )`, if the browser supports it.
219 * Otherwise falls back to non-capturing event listeners.
220 *
221 * @param {HTMLElement} node
222 * @param {string} eventName
223 * @param {Function} handler
224 */
225 OO.ui.removeCaptureEventListener = function ( node, eventName, handler ) {
226 if ( node.addEventListener ) {
227 node.removeEventListener( eventName, handler, true );
228 } else {
229 node.detachEvent( 'on' + eventName, handler );
230 }
231 };
232
233 /**
234 * Reconstitute a JavaScript object corresponding to a widget created by
235 * the PHP implementation.
236 *
237 * This is an alias for `OO.ui.Element.static.infuse()`.
238 *
239 * @param {string|HTMLElement|jQuery} idOrNode
240 * A DOM id (if a string) or node for the widget to infuse.
241 * @return {OO.ui.Element}
242 * The `OO.ui.Element` corresponding to this (infusable) document node.
243 */
244 OO.ui.infuse = function ( idOrNode ) {
245 return OO.ui.Element.static.infuse( idOrNode );
246 };
247
248 ( function () {
249 /**
250 * Message store for the default implementation of OO.ui.msg
251 *
252 * Environments that provide a localization system should not use this, but should override
253 * OO.ui.msg altogether.
254 *
255 * @private
256 */
257 var messages = {
258 // Tool tip for a button that moves items in a list down one place
259 'ooui-outline-control-move-down': 'Move item down',
260 // Tool tip for a button that moves items in a list up one place
261 'ooui-outline-control-move-up': 'Move item up',
262 // Tool tip for a button that removes items from a list
263 'ooui-outline-control-remove': 'Remove item',
264 // Label for the toolbar group that contains a list of all other available tools
265 'ooui-toolbar-more': 'More',
266 // Label for the fake tool that expands the full list of tools in a toolbar group
267 'ooui-toolgroup-expand': 'More',
268 // Label for the fake tool that collapses the full list of tools in a toolbar group
269 'ooui-toolgroup-collapse': 'Fewer',
270 // Default label for the accept button of a confirmation dialog
271 'ooui-dialog-message-accept': 'OK',
272 // Default label for the reject button of a confirmation dialog
273 'ooui-dialog-message-reject': 'Cancel',
274 // Title for process dialog error description
275 'ooui-dialog-process-error': 'Something went wrong',
276 // Label for process dialog dismiss error button, visible when describing errors
277 'ooui-dialog-process-dismiss': 'Dismiss',
278 // Label for process dialog retry action button, visible when describing only recoverable errors
279 'ooui-dialog-process-retry': 'Try again',
280 // Label for process dialog retry action button, visible when describing only warnings
281 'ooui-dialog-process-continue': 'Continue',
282 // Default placeholder for file selection widgets
283 'ooui-selectfile-not-supported': 'File selection is not supported',
284 // Default placeholder for file selection widgets
285 'ooui-selectfile-placeholder': 'No file is selected',
286 // Semicolon separator
287 'ooui-semicolon-separator': '; '
288 };
289
290 /**
291 * Get a localized message.
292 *
293 * In environments that provide a localization system, this function should be overridden to
294 * return the message translated in the user's language. The default implementation always returns
295 * English messages.
296 *
297 * After the message key, message parameters may optionally be passed. In the default implementation,
298 * any occurrences of $1 are replaced with the first parameter, $2 with the second parameter, etc.
299 * Alternative implementations of OO.ui.msg may use any substitution system they like, as long as
300 * they support unnamed, ordered message parameters.
301 *
302 * @abstract
303 * @param {string} key Message key
304 * @param {Mixed...} [params] Message parameters
305 * @return {string} Translated message with parameters substituted
306 */
307 OO.ui.msg = function ( key ) {
308 var message = messages[ key ],
309 params = Array.prototype.slice.call( arguments, 1 );
310 if ( typeof message === 'string' ) {
311 // Perform $1 substitution
312 message = message.replace( /\$(\d+)/g, function ( unused, n ) {
313 var i = parseInt( n, 10 );
314 return params[ i - 1 ] !== undefined ? params[ i - 1 ] : '$' + n;
315 } );
316 } else {
317 // Return placeholder if message not found
318 message = '[' + key + ']';
319 }
320 return message;
321 };
322
323 /**
324 * Package a message and arguments for deferred resolution.
325 *
326 * Use this when you are statically specifying a message and the message may not yet be present.
327 *
328 * @param {string} key Message key
329 * @param {Mixed...} [params] Message parameters
330 * @return {Function} Function that returns the resolved message when executed
331 */
332 OO.ui.deferMsg = function () {
333 var args = arguments;
334 return function () {
335 return OO.ui.msg.apply( OO.ui, args );
336 };
337 };
338
339 /**
340 * Resolve a message.
341 *
342 * If the message is a function it will be executed, otherwise it will pass through directly.
343 *
344 * @param {Function|string} msg Deferred message, or message text
345 * @return {string} Resolved message
346 */
347 OO.ui.resolveMsg = function ( msg ) {
348 if ( $.isFunction( msg ) ) {
349 return msg();
350 }
351 return msg;
352 };
353
354 /**
355 * @param {string} url
356 * @return {boolean}
357 */
358 OO.ui.isSafeUrl = function ( url ) {
359 var protocol,
360 // Keep in sync with php/Tag.php
361 whitelist = [
362 'bitcoin:', 'ftp:', 'ftps:', 'geo:', 'git:', 'gopher:', 'http:', 'https:', 'irc:', 'ircs:',
363 'magnet:', 'mailto:', 'mms:', 'news:', 'nntp:', 'redis:', 'sftp:', 'sip:', 'sips:', 'sms:', 'ssh:',
364 'svn:', 'tel:', 'telnet:', 'urn:', 'worldwind:', 'xmpp:'
365 ];
366
367 if ( url.indexOf( ':' ) === -1 ) {
368 // No protocol, safe
369 return true;
370 }
371
372 protocol = url.split( ':', 1 )[0] + ':';
373 if ( !protocol.match( /^([A-za-z0-9\+\.\-])+:/ ) ) {
374 // Not a valid protocol, safe
375 return true;
376 }
377
378 // Safe if in the whitelist
379 return $.inArray( protocol, whitelist ) !== -1;
380 };
381
382 } )();
383
384 /*!
385 * Mixin namespace.
386 */
387
388 /**
389 * Namespace for OOjs UI mixins.
390 *
391 * Mixins are named according to the type of object they are intended to
392 * be mixed in to. For example, OO.ui.mixin.GroupElement is intended to be
393 * mixed in to an instance of OO.ui.Element, and OO.ui.mixin.GroupWidget
394 * is intended to be mixed in to an instance of OO.ui.Widget.
395 *
396 * @class
397 * @singleton
398 */
399 OO.ui.mixin = {};
400
401 /**
402 * PendingElement is a mixin that is used to create elements that notify users that something is happening
403 * and that they should wait before proceeding. The pending state is visually represented with a pending
404 * texture that appears in the head of a pending {@link OO.ui.ProcessDialog process dialog} or in the input
405 * field of a {@link OO.ui.TextInputWidget text input widget}.
406 *
407 * Currently, {@link OO.ui.ActionWidget Action widgets}, which mix in this class, can also be marked as pending, but only when
408 * used in {@link OO.ui.MessageDialog message dialogs}. The behavior is not currently supported for action widgets used
409 * in process dialogs.
410 *
411 * @example
412 * function MessageDialog( config ) {
413 * MessageDialog.parent.call( this, config );
414 * }
415 * OO.inheritClass( MessageDialog, OO.ui.MessageDialog );
416 *
417 * MessageDialog.static.actions = [
418 * { action: 'save', label: 'Done', flags: 'primary' },
419 * { label: 'Cancel', flags: 'safe' }
420 * ];
421 *
422 * MessageDialog.prototype.initialize = function () {
423 * MessageDialog.parent.prototype.initialize.apply( this, arguments );
424 * this.content = new OO.ui.PanelLayout( { $: this.$, padded: true } );
425 * 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>' );
426 * this.$body.append( this.content.$element );
427 * };
428 * MessageDialog.prototype.getBodyHeight = function () {
429 * return 100;
430 * }
431 * MessageDialog.prototype.getActionProcess = function ( action ) {
432 * var dialog = this;
433 * if ( action === 'save' ) {
434 * dialog.getActions().get({actions: 'save'})[0].pushPending();
435 * return new OO.ui.Process()
436 * .next( 1000 )
437 * .next( function () {
438 * dialog.getActions().get({actions: 'save'})[0].popPending();
439 * } );
440 * }
441 * return MessageDialog.parent.prototype.getActionProcess.call( this, action );
442 * };
443 *
444 * var windowManager = new OO.ui.WindowManager();
445 * $( 'body' ).append( windowManager.$element );
446 *
447 * var dialog = new MessageDialog();
448 * windowManager.addWindows( [ dialog ] );
449 * windowManager.openWindow( dialog );
450 *
451 * @abstract
452 * @class
453 *
454 * @constructor
455 * @param {Object} [config] Configuration options
456 * @cfg {jQuery} [$pending] Element to mark as pending, defaults to this.$element
457 */
458 OO.ui.mixin.PendingElement = function OoUiMixinPendingElement( config ) {
459 // Configuration initialization
460 config = config || {};
461
462 // Properties
463 this.pending = 0;
464 this.$pending = null;
465
466 // Initialisation
467 this.setPendingElement( config.$pending || this.$element );
468 };
469
470 /* Setup */
471
472 OO.initClass( OO.ui.mixin.PendingElement );
473
474 /* Methods */
475
476 /**
477 * Set the pending element (and clean up any existing one).
478 *
479 * @param {jQuery} $pending The element to set to pending.
480 */
481 OO.ui.mixin.PendingElement.prototype.setPendingElement = function ( $pending ) {
482 if ( this.$pending ) {
483 this.$pending.removeClass( 'oo-ui-pendingElement-pending' );
484 }
485
486 this.$pending = $pending;
487 if ( this.pending > 0 ) {
488 this.$pending.addClass( 'oo-ui-pendingElement-pending' );
489 }
490 };
491
492 /**
493 * Check if an element is pending.
494 *
495 * @return {boolean} Element is pending
496 */
497 OO.ui.mixin.PendingElement.prototype.isPending = function () {
498 return !!this.pending;
499 };
500
501 /**
502 * Increase the pending counter. The pending state will remain active until the counter is zero
503 * (i.e., the number of calls to #pushPending and #popPending is the same).
504 *
505 * @chainable
506 */
507 OO.ui.mixin.PendingElement.prototype.pushPending = function () {
508 if ( this.pending === 0 ) {
509 this.$pending.addClass( 'oo-ui-pendingElement-pending' );
510 this.updateThemeClasses();
511 }
512 this.pending++;
513
514 return this;
515 };
516
517 /**
518 * Decrease the pending counter. The pending state will remain active until the counter is zero
519 * (i.e., the number of calls to #pushPending and #popPending is the same).
520 *
521 * @chainable
522 */
523 OO.ui.mixin.PendingElement.prototype.popPending = function () {
524 if ( this.pending === 1 ) {
525 this.$pending.removeClass( 'oo-ui-pendingElement-pending' );
526 this.updateThemeClasses();
527 }
528 this.pending = Math.max( 0, this.pending - 1 );
529
530 return this;
531 };
532
533 /**
534 * ActionSets manage the behavior of the {@link OO.ui.ActionWidget action widgets} that comprise them.
535 * Actions can be made available for specific contexts (modes) and circumstances
536 * (abilities). Action sets are primarily used with {@link OO.ui.Dialog Dialogs}.
537 *
538 * ActionSets contain two types of actions:
539 *
540 * - 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.
541 * - Other: Other actions include all non-special visible actions.
542 *
543 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
544 *
545 * @example
546 * // Example: An action set used in a process dialog
547 * function MyProcessDialog( config ) {
548 * MyProcessDialog.parent.call( this, config );
549 * }
550 * OO.inheritClass( MyProcessDialog, OO.ui.ProcessDialog );
551 * MyProcessDialog.static.title = 'An action set in a process dialog';
552 * // An action set that uses modes ('edit' and 'help' mode, in this example).
553 * MyProcessDialog.static.actions = [
554 * { action: 'continue', modes: 'edit', label: 'Continue', flags: [ 'primary', 'constructive' ] },
555 * { action: 'help', modes: 'edit', label: 'Help' },
556 * { modes: 'edit', label: 'Cancel', flags: 'safe' },
557 * { action: 'back', modes: 'help', label: 'Back', flags: 'safe' }
558 * ];
559 *
560 * MyProcessDialog.prototype.initialize = function () {
561 * MyProcessDialog.parent.prototype.initialize.apply( this, arguments );
562 * this.panel1 = new OO.ui.PanelLayout( { padded: true, expanded: false } );
563 * 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>' );
564 * this.panel2 = new OO.ui.PanelLayout( { padded: true, expanded: false } );
565 * 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>' );
566 * this.stackLayout = new OO.ui.StackLayout( {
567 * items: [ this.panel1, this.panel2 ]
568 * } );
569 * this.$body.append( this.stackLayout.$element );
570 * };
571 * MyProcessDialog.prototype.getSetupProcess = function ( data ) {
572 * return MyProcessDialog.parent.prototype.getSetupProcess.call( this, data )
573 * .next( function () {
574 * this.actions.setMode( 'edit' );
575 * }, this );
576 * };
577 * MyProcessDialog.prototype.getActionProcess = function ( action ) {
578 * if ( action === 'help' ) {
579 * this.actions.setMode( 'help' );
580 * this.stackLayout.setItem( this.panel2 );
581 * } else if ( action === 'back' ) {
582 * this.actions.setMode( 'edit' );
583 * this.stackLayout.setItem( this.panel1 );
584 * } else if ( action === 'continue' ) {
585 * var dialog = this;
586 * return new OO.ui.Process( function () {
587 * dialog.close();
588 * } );
589 * }
590 * return MyProcessDialog.parent.prototype.getActionProcess.call( this, action );
591 * };
592 * MyProcessDialog.prototype.getBodyHeight = function () {
593 * return this.panel1.$element.outerHeight( true );
594 * };
595 * var windowManager = new OO.ui.WindowManager();
596 * $( 'body' ).append( windowManager.$element );
597 * var dialog = new MyProcessDialog( {
598 * size: 'medium'
599 * } );
600 * windowManager.addWindows( [ dialog ] );
601 * windowManager.openWindow( dialog );
602 *
603 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Action_sets
604 *
605 * @abstract
606 * @class
607 * @mixins OO.EventEmitter
608 *
609 * @constructor
610 * @param {Object} [config] Configuration options
611 */
612 OO.ui.ActionSet = function OoUiActionSet( config ) {
613 // Configuration initialization
614 config = config || {};
615
616 // Mixin constructors
617 OO.EventEmitter.call( this );
618
619 // Properties
620 this.list = [];
621 this.categories = {
622 actions: 'getAction',
623 flags: 'getFlags',
624 modes: 'getModes'
625 };
626 this.categorized = {};
627 this.special = {};
628 this.others = [];
629 this.organized = false;
630 this.changing = false;
631 this.changed = false;
632 };
633
634 /* Setup */
635
636 OO.mixinClass( OO.ui.ActionSet, OO.EventEmitter );
637
638 /* Static Properties */
639
640 /**
641 * Symbolic name of the flags used to identify special actions. Special actions are displayed in the
642 * header of a {@link OO.ui.ProcessDialog process dialog}.
643 * See the [OOjs UI documentation on MediaWiki][2] for more information and examples.
644 *
645 * [2]:https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs
646 *
647 * @abstract
648 * @static
649 * @inheritable
650 * @property {string}
651 */
652 OO.ui.ActionSet.static.specialFlags = [ 'safe', 'primary' ];
653
654 /* Events */
655
656 /**
657 * @event click
658 *
659 * A 'click' event is emitted when an action is clicked.
660 *
661 * @param {OO.ui.ActionWidget} action Action that was clicked
662 */
663
664 /**
665 * @event resize
666 *
667 * A 'resize' event is emitted when an action widget is resized.
668 *
669 * @param {OO.ui.ActionWidget} action Action that was resized
670 */
671
672 /**
673 * @event add
674 *
675 * An 'add' event is emitted when actions are {@link #method-add added} to the action set.
676 *
677 * @param {OO.ui.ActionWidget[]} added Actions added
678 */
679
680 /**
681 * @event remove
682 *
683 * A 'remove' event is emitted when actions are {@link #method-remove removed}
684 * or {@link #clear cleared}.
685 *
686 * @param {OO.ui.ActionWidget[]} added Actions removed
687 */
688
689 /**
690 * @event change
691 *
692 * A 'change' event is emitted when actions are {@link #method-add added}, {@link #clear cleared},
693 * or {@link #method-remove removed} from the action set or when the {@link #setMode mode} is changed.
694 *
695 */
696
697 /* Methods */
698
699 /**
700 * Handle action change events.
701 *
702 * @private
703 * @fires change
704 */
705 OO.ui.ActionSet.prototype.onActionChange = function () {
706 this.organized = false;
707 if ( this.changing ) {
708 this.changed = true;
709 } else {
710 this.emit( 'change' );
711 }
712 };
713
714 /**
715 * Check if an action is one of the special actions.
716 *
717 * @param {OO.ui.ActionWidget} action Action to check
718 * @return {boolean} Action is special
719 */
720 OO.ui.ActionSet.prototype.isSpecial = function ( action ) {
721 var flag;
722
723 for ( flag in this.special ) {
724 if ( action === this.special[ flag ] ) {
725 return true;
726 }
727 }
728
729 return false;
730 };
731
732 /**
733 * Get action widgets based on the specified filter: ‘actions’, ‘flags’, ‘modes’, ‘visible’,
734 * or ‘disabled’.
735 *
736 * @param {Object} [filters] Filters to use, omit to get all actions
737 * @param {string|string[]} [filters.actions] Actions that action widgets must have
738 * @param {string|string[]} [filters.flags] Flags that action widgets must have (e.g., 'safe')
739 * @param {string|string[]} [filters.modes] Modes that action widgets must have
740 * @param {boolean} [filters.visible] Action widgets must be visible
741 * @param {boolean} [filters.disabled] Action widgets must be disabled
742 * @return {OO.ui.ActionWidget[]} Action widgets matching all criteria
743 */
744 OO.ui.ActionSet.prototype.get = function ( filters ) {
745 var i, len, list, category, actions, index, match, matches;
746
747 if ( filters ) {
748 this.organize();
749
750 // Collect category candidates
751 matches = [];
752 for ( category in this.categorized ) {
753 list = filters[ category ];
754 if ( list ) {
755 if ( !Array.isArray( list ) ) {
756 list = [ list ];
757 }
758 for ( i = 0, len = list.length; i < len; i++ ) {
759 actions = this.categorized[ category ][ list[ i ] ];
760 if ( Array.isArray( actions ) ) {
761 matches.push.apply( matches, actions );
762 }
763 }
764 }
765 }
766 // Remove by boolean filters
767 for ( i = 0, len = matches.length; i < len; i++ ) {
768 match = matches[ i ];
769 if (
770 ( filters.visible !== undefined && match.isVisible() !== filters.visible ) ||
771 ( filters.disabled !== undefined && match.isDisabled() !== filters.disabled )
772 ) {
773 matches.splice( i, 1 );
774 len--;
775 i--;
776 }
777 }
778 // Remove duplicates
779 for ( i = 0, len = matches.length; i < len; i++ ) {
780 match = matches[ i ];
781 index = matches.lastIndexOf( match );
782 while ( index !== i ) {
783 matches.splice( index, 1 );
784 len--;
785 index = matches.lastIndexOf( match );
786 }
787 }
788 return matches;
789 }
790 return this.list.slice();
791 };
792
793 /**
794 * Get 'special' actions.
795 *
796 * Special actions are the first visible action widgets with special flags, such as 'safe' and 'primary'.
797 * Special flags can be configured in subclasses by changing the static #specialFlags property.
798 *
799 * @return {OO.ui.ActionWidget[]|null} 'Special' action widgets.
800 */
801 OO.ui.ActionSet.prototype.getSpecial = function () {
802 this.organize();
803 return $.extend( {}, this.special );
804 };
805
806 /**
807 * Get 'other' actions.
808 *
809 * Other actions include all non-special visible action widgets.
810 *
811 * @return {OO.ui.ActionWidget[]} 'Other' action widgets
812 */
813 OO.ui.ActionSet.prototype.getOthers = function () {
814 this.organize();
815 return this.others.slice();
816 };
817
818 /**
819 * Set the mode (e.g., ‘edit’ or ‘view’). Only {@link OO.ui.ActionWidget#modes actions} configured
820 * to be available in the specified mode will be made visible. All other actions will be hidden.
821 *
822 * @param {string} mode The mode. Only actions configured to be available in the specified
823 * mode will be made visible.
824 * @chainable
825 * @fires toggle
826 * @fires change
827 */
828 OO.ui.ActionSet.prototype.setMode = function ( mode ) {
829 var i, len, action;
830
831 this.changing = true;
832 for ( i = 0, len = this.list.length; i < len; i++ ) {
833 action = this.list[ i ];
834 action.toggle( action.hasMode( mode ) );
835 }
836
837 this.organized = false;
838 this.changing = false;
839 this.emit( 'change' );
840
841 return this;
842 };
843
844 /**
845 * Set the abilities of the specified actions.
846 *
847 * Action widgets that are configured with the specified actions will be enabled
848 * or disabled based on the boolean values specified in the `actions`
849 * parameter.
850 *
851 * @param {Object.<string,boolean>} actions A list keyed by action name with boolean
852 * values that indicate whether or not the action should be enabled.
853 * @chainable
854 */
855 OO.ui.ActionSet.prototype.setAbilities = function ( actions ) {
856 var i, len, action, item;
857
858 for ( i = 0, len = this.list.length; i < len; i++ ) {
859 item = this.list[ i ];
860 action = item.getAction();
861 if ( actions[ action ] !== undefined ) {
862 item.setDisabled( !actions[ action ] );
863 }
864 }
865
866 return this;
867 };
868
869 /**
870 * Executes a function once per action.
871 *
872 * When making changes to multiple actions, use this method instead of iterating over the actions
873 * manually to defer emitting a #change event until after all actions have been changed.
874 *
875 * @param {Object|null} actions Filters to use to determine which actions to iterate over; see #get
876 * @param {Function} callback Callback to run for each action; callback is invoked with three
877 * arguments: the action, the action's index, the list of actions being iterated over
878 * @chainable
879 */
880 OO.ui.ActionSet.prototype.forEach = function ( filter, callback ) {
881 this.changed = false;
882 this.changing = true;
883 this.get( filter ).forEach( callback );
884 this.changing = false;
885 if ( this.changed ) {
886 this.emit( 'change' );
887 }
888
889 return this;
890 };
891
892 /**
893 * Add action widgets to the action set.
894 *
895 * @param {OO.ui.ActionWidget[]} actions Action widgets to add
896 * @chainable
897 * @fires add
898 * @fires change
899 */
900 OO.ui.ActionSet.prototype.add = function ( actions ) {
901 var i, len, action;
902
903 this.changing = true;
904 for ( i = 0, len = actions.length; i < len; i++ ) {
905 action = actions[ i ];
906 action.connect( this, {
907 click: [ 'emit', 'click', action ],
908 resize: [ 'emit', 'resize', action ],
909 toggle: [ 'onActionChange' ]
910 } );
911 this.list.push( action );
912 }
913 this.organized = false;
914 this.emit( 'add', actions );
915 this.changing = false;
916 this.emit( 'change' );
917
918 return this;
919 };
920
921 /**
922 * Remove action widgets from the set.
923 *
924 * To remove all actions, you may wish to use the #clear method instead.
925 *
926 * @param {OO.ui.ActionWidget[]} actions Action widgets to remove
927 * @chainable
928 * @fires remove
929 * @fires change
930 */
931 OO.ui.ActionSet.prototype.remove = function ( actions ) {
932 var i, len, index, action;
933
934 this.changing = true;
935 for ( i = 0, len = actions.length; i < len; i++ ) {
936 action = actions[ i ];
937 index = this.list.indexOf( action );
938 if ( index !== -1 ) {
939 action.disconnect( this );
940 this.list.splice( index, 1 );
941 }
942 }
943 this.organized = false;
944 this.emit( 'remove', actions );
945 this.changing = false;
946 this.emit( 'change' );
947
948 return this;
949 };
950
951 /**
952 * Remove all action widets from the set.
953 *
954 * To remove only specified actions, use the {@link #method-remove remove} method instead.
955 *
956 * @chainable
957 * @fires remove
958 * @fires change
959 */
960 OO.ui.ActionSet.prototype.clear = function () {
961 var i, len, action,
962 removed = this.list.slice();
963
964 this.changing = true;
965 for ( i = 0, len = this.list.length; i < len; i++ ) {
966 action = this.list[ i ];
967 action.disconnect( this );
968 }
969
970 this.list = [];
971
972 this.organized = false;
973 this.emit( 'remove', removed );
974 this.changing = false;
975 this.emit( 'change' );
976
977 return this;
978 };
979
980 /**
981 * Organize actions.
982 *
983 * This is called whenever organized information is requested. It will only reorganize the actions
984 * if something has changed since the last time it ran.
985 *
986 * @private
987 * @chainable
988 */
989 OO.ui.ActionSet.prototype.organize = function () {
990 var i, iLen, j, jLen, flag, action, category, list, item, special,
991 specialFlags = this.constructor.static.specialFlags;
992
993 if ( !this.organized ) {
994 this.categorized = {};
995 this.special = {};
996 this.others = [];
997 for ( i = 0, iLen = this.list.length; i < iLen; i++ ) {
998 action = this.list[ i ];
999 if ( action.isVisible() ) {
1000 // Populate categories
1001 for ( category in this.categories ) {
1002 if ( !this.categorized[ category ] ) {
1003 this.categorized[ category ] = {};
1004 }
1005 list = action[ this.categories[ category ] ]();
1006 if ( !Array.isArray( list ) ) {
1007 list = [ list ];
1008 }
1009 for ( j = 0, jLen = list.length; j < jLen; j++ ) {
1010 item = list[ j ];
1011 if ( !this.categorized[ category ][ item ] ) {
1012 this.categorized[ category ][ item ] = [];
1013 }
1014 this.categorized[ category ][ item ].push( action );
1015 }
1016 }
1017 // Populate special/others
1018 special = false;
1019 for ( j = 0, jLen = specialFlags.length; j < jLen; j++ ) {
1020 flag = specialFlags[ j ];
1021 if ( !this.special[ flag ] && action.hasFlag( flag ) ) {
1022 this.special[ flag ] = action;
1023 special = true;
1024 break;
1025 }
1026 }
1027 if ( !special ) {
1028 this.others.push( action );
1029 }
1030 }
1031 }
1032 this.organized = true;
1033 }
1034
1035 return this;
1036 };
1037
1038 /**
1039 * Each Element represents a rendering in the DOM—a button or an icon, for example, or anything
1040 * that is visible to a user. Unlike {@link OO.ui.Widget widgets}, plain elements usually do not have events
1041 * connected to them and can't be interacted with.
1042 *
1043 * @abstract
1044 * @class
1045 *
1046 * @constructor
1047 * @param {Object} [config] Configuration options
1048 * @cfg {string[]} [classes] The names of the CSS classes to apply to the element. CSS styles are added
1049 * to the top level (e.g., the outermost div) of the element. See the [OOjs UI documentation on MediaWiki][2]
1050 * for an example.
1051 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#cssExample
1052 * @cfg {string} [id] The HTML id attribute used in the rendered tag.
1053 * @cfg {string} [text] Text to insert
1054 * @cfg {Array} [content] An array of content elements to append (after #text).
1055 * Strings will be html-escaped; use an OO.ui.HtmlSnippet to append raw HTML.
1056 * Instances of OO.ui.Element will have their $element appended.
1057 * @cfg {jQuery} [$content] Content elements to append (after #text)
1058 * @cfg {Mixed} [data] Custom data of any type or combination of types (e.g., string, number, array, object).
1059 * Data can also be specified with the #setData method.
1060 */
1061 OO.ui.Element = function OoUiElement( config ) {
1062 // Configuration initialization
1063 config = config || {};
1064
1065 // Properties
1066 this.$ = $;
1067 this.visible = true;
1068 this.data = config.data;
1069 this.$element = config.$element ||
1070 $( document.createElement( this.getTagName() ) );
1071 this.elementGroup = null;
1072 this.debouncedUpdateThemeClassesHandler = this.debouncedUpdateThemeClasses.bind( this );
1073 this.updateThemeClassesPending = false;
1074
1075 // Initialization
1076 if ( Array.isArray( config.classes ) ) {
1077 this.$element.addClass( config.classes.join( ' ' ) );
1078 }
1079 if ( config.id ) {
1080 this.$element.attr( 'id', config.id );
1081 }
1082 if ( config.text ) {
1083 this.$element.text( config.text );
1084 }
1085 if ( config.content ) {
1086 // The `content` property treats plain strings as text; use an
1087 // HtmlSnippet to append HTML content. `OO.ui.Element`s get their
1088 // appropriate $element appended.
1089 this.$element.append( config.content.map( function ( v ) {
1090 if ( typeof v === 'string' ) {
1091 // Escape string so it is properly represented in HTML.
1092 return document.createTextNode( v );
1093 } else if ( v instanceof OO.ui.HtmlSnippet ) {
1094 // Bypass escaping.
1095 return v.toString();
1096 } else if ( v instanceof OO.ui.Element ) {
1097 return v.$element;
1098 }
1099 return v;
1100 } ) );
1101 }
1102 if ( config.$content ) {
1103 // The `$content` property treats plain strings as HTML.
1104 this.$element.append( config.$content );
1105 }
1106 };
1107
1108 /* Setup */
1109
1110 OO.initClass( OO.ui.Element );
1111
1112 /* Static Properties */
1113
1114 /**
1115 * The name of the HTML tag used by the element.
1116 *
1117 * The static value may be ignored if the #getTagName method is overridden.
1118 *
1119 * @static
1120 * @inheritable
1121 * @property {string}
1122 */
1123 OO.ui.Element.static.tagName = 'div';
1124
1125 /* Static Methods */
1126
1127 /**
1128 * Reconstitute a JavaScript object corresponding to a widget created
1129 * by the PHP implementation.
1130 *
1131 * @param {string|HTMLElement|jQuery} idOrNode
1132 * A DOM id (if a string) or node for the widget to infuse.
1133 * @return {OO.ui.Element}
1134 * The `OO.ui.Element` corresponding to this (infusable) document node.
1135 * For `Tag` objects emitted on the HTML side (used occasionally for content)
1136 * the value returned is a newly-created Element wrapping around the existing
1137 * DOM node.
1138 */
1139 OO.ui.Element.static.infuse = function ( idOrNode ) {
1140 var obj = OO.ui.Element.static.unsafeInfuse( idOrNode, false );
1141 // Verify that the type matches up.
1142 // FIXME: uncomment after T89721 is fixed (see T90929)
1143 /*
1144 if ( !( obj instanceof this['class'] ) ) {
1145 throw new Error( 'Infusion type mismatch!' );
1146 }
1147 */
1148 return obj;
1149 };
1150
1151 /**
1152 * Implementation helper for `infuse`; skips the type check and has an
1153 * extra property so that only the top-level invocation touches the DOM.
1154 * @private
1155 * @param {string|HTMLElement|jQuery} idOrNode
1156 * @param {jQuery.Promise|boolean} domPromise A promise that will be resolved
1157 * when the top-level widget of this infusion is inserted into DOM,
1158 * replacing the original node; or false for top-level invocation.
1159 * @return {OO.ui.Element}
1160 */
1161 OO.ui.Element.static.unsafeInfuse = function ( idOrNode, domPromise ) {
1162 // look for a cached result of a previous infusion.
1163 var id, $elem, data, cls, parts, parent, obj, top, state;
1164 if ( typeof idOrNode === 'string' ) {
1165 id = idOrNode;
1166 $elem = $( document.getElementById( id ) );
1167 } else {
1168 $elem = $( idOrNode );
1169 id = $elem.attr( 'id' );
1170 }
1171 if ( !$elem.length ) {
1172 throw new Error( 'Widget not found: ' + id );
1173 }
1174 data = $elem.data( 'ooui-infused' ) || $elem[0].oouiInfused;
1175 if ( data ) {
1176 // cached!
1177 if ( data === true ) {
1178 throw new Error( 'Circular dependency! ' + id );
1179 }
1180 return data;
1181 }
1182 data = $elem.attr( 'data-ooui' );
1183 if ( !data ) {
1184 throw new Error( 'No infusion data found: ' + id );
1185 }
1186 try {
1187 data = $.parseJSON( data );
1188 } catch ( _ ) {
1189 data = null;
1190 }
1191 if ( !( data && data._ ) ) {
1192 throw new Error( 'No valid infusion data found: ' + id );
1193 }
1194 if ( data._ === 'Tag' ) {
1195 // Special case: this is a raw Tag; wrap existing node, don't rebuild.
1196 return new OO.ui.Element( { $element: $elem } );
1197 }
1198 parts = data._.split( '.' );
1199 cls = OO.getProp.apply( OO, [ window ].concat( parts ) );
1200 if ( cls === undefined ) {
1201 // The PHP output might be old and not including the "OO.ui" prefix
1202 // TODO: Remove this back-compat after next major release
1203 cls = OO.getProp.apply( OO, [ OO.ui ].concat( parts ) );
1204 if ( cls === undefined ) {
1205 throw new Error( 'Unknown widget type: id: ' + id + ', class: ' + data._ );
1206 }
1207 }
1208
1209 // Verify that we're creating an OO.ui.Element instance
1210 parent = cls.parent;
1211
1212 while ( parent !== undefined ) {
1213 if ( parent === OO.ui.Element ) {
1214 // Safe
1215 break;
1216 }
1217
1218 parent = parent.parent;
1219 }
1220
1221 if ( parent !== OO.ui.Element ) {
1222 throw new Error( 'Unknown widget type: id: ' + id + ', class: ' + data._ );
1223 }
1224
1225 if ( domPromise === false ) {
1226 top = $.Deferred();
1227 domPromise = top.promise();
1228 }
1229 $elem.data( 'ooui-infused', true ); // prevent loops
1230 data.id = id; // implicit
1231 data = OO.copy( data, null, function deserialize( value ) {
1232 if ( OO.isPlainObject( value ) ) {
1233 if ( value.tag ) {
1234 return OO.ui.Element.static.unsafeInfuse( value.tag, domPromise );
1235 }
1236 if ( value.html ) {
1237 return new OO.ui.HtmlSnippet( value.html );
1238 }
1239 }
1240 } );
1241 // jscs:disable requireCapitalizedConstructors
1242 obj = new cls( data ); // rebuild widget
1243 // pick up dynamic state, like focus, value of form inputs, scroll position, etc.
1244 state = obj.gatherPreInfuseState( $elem );
1245 // now replace old DOM with this new DOM.
1246 if ( top ) {
1247 $elem.replaceWith( obj.$element );
1248 // This element is now gone from the DOM, but if anyone is holding a reference to it,
1249 // let's allow them to OO.ui.infuse() it and do what they expect (T105828).
1250 // Do not use jQuery.data(), as using it on detached nodes leaks memory in 1.x line by design.
1251 $elem[0].oouiInfused = obj;
1252 top.resolve();
1253 }
1254 obj.$element.data( 'ooui-infused', obj );
1255 // set the 'data-ooui' attribute so we can identify infused widgets
1256 obj.$element.attr( 'data-ooui', '' );
1257 // restore dynamic state after the new element is inserted into DOM
1258 domPromise.done( obj.restorePreInfuseState.bind( obj, state ) );
1259 return obj;
1260 };
1261
1262 /**
1263 * Get a jQuery function within a specific document.
1264 *
1265 * @static
1266 * @param {jQuery|HTMLElement|HTMLDocument|Window} context Context to bind the function to
1267 * @param {jQuery} [$iframe] HTML iframe element that contains the document, omit if document is
1268 * not in an iframe
1269 * @return {Function} Bound jQuery function
1270 */
1271 OO.ui.Element.static.getJQuery = function ( context, $iframe ) {
1272 function wrapper( selector ) {
1273 return $( selector, wrapper.context );
1274 }
1275
1276 wrapper.context = this.getDocument( context );
1277
1278 if ( $iframe ) {
1279 wrapper.$iframe = $iframe;
1280 }
1281
1282 return wrapper;
1283 };
1284
1285 /**
1286 * Get the document of an element.
1287 *
1288 * @static
1289 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Object to get the document for
1290 * @return {HTMLDocument|null} Document object
1291 */
1292 OO.ui.Element.static.getDocument = function ( obj ) {
1293 // jQuery - selections created "offscreen" won't have a context, so .context isn't reliable
1294 return ( obj[ 0 ] && obj[ 0 ].ownerDocument ) ||
1295 // Empty jQuery selections might have a context
1296 obj.context ||
1297 // HTMLElement
1298 obj.ownerDocument ||
1299 // Window
1300 obj.document ||
1301 // HTMLDocument
1302 ( obj.nodeType === 9 && obj ) ||
1303 null;
1304 };
1305
1306 /**
1307 * Get the window of an element or document.
1308 *
1309 * @static
1310 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the window for
1311 * @return {Window} Window object
1312 */
1313 OO.ui.Element.static.getWindow = function ( obj ) {
1314 var doc = this.getDocument( obj );
1315 return doc.parentWindow || doc.defaultView;
1316 };
1317
1318 /**
1319 * Get the direction of an element or document.
1320 *
1321 * @static
1322 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the direction for
1323 * @return {string} Text direction, either 'ltr' or 'rtl'
1324 */
1325 OO.ui.Element.static.getDir = function ( obj ) {
1326 var isDoc, isWin;
1327
1328 if ( obj instanceof jQuery ) {
1329 obj = obj[ 0 ];
1330 }
1331 isDoc = obj.nodeType === 9;
1332 isWin = obj.document !== undefined;
1333 if ( isDoc || isWin ) {
1334 if ( isWin ) {
1335 obj = obj.document;
1336 }
1337 obj = obj.body;
1338 }
1339 return $( obj ).css( 'direction' );
1340 };
1341
1342 /**
1343 * Get the offset between two frames.
1344 *
1345 * TODO: Make this function not use recursion.
1346 *
1347 * @static
1348 * @param {Window} from Window of the child frame
1349 * @param {Window} [to=window] Window of the parent frame
1350 * @param {Object} [offset] Offset to start with, used internally
1351 * @return {Object} Offset object, containing left and top properties
1352 */
1353 OO.ui.Element.static.getFrameOffset = function ( from, to, offset ) {
1354 var i, len, frames, frame, rect;
1355
1356 if ( !to ) {
1357 to = window;
1358 }
1359 if ( !offset ) {
1360 offset = { top: 0, left: 0 };
1361 }
1362 if ( from.parent === from ) {
1363 return offset;
1364 }
1365
1366 // Get iframe element
1367 frames = from.parent.document.getElementsByTagName( 'iframe' );
1368 for ( i = 0, len = frames.length; i < len; i++ ) {
1369 if ( frames[ i ].contentWindow === from ) {
1370 frame = frames[ i ];
1371 break;
1372 }
1373 }
1374
1375 // Recursively accumulate offset values
1376 if ( frame ) {
1377 rect = frame.getBoundingClientRect();
1378 offset.left += rect.left;
1379 offset.top += rect.top;
1380 if ( from !== to ) {
1381 this.getFrameOffset( from.parent, offset );
1382 }
1383 }
1384 return offset;
1385 };
1386
1387 /**
1388 * Get the offset between two elements.
1389 *
1390 * The two elements may be in a different frame, but in that case the frame $element is in must
1391 * be contained in the frame $anchor is in.
1392 *
1393 * @static
1394 * @param {jQuery} $element Element whose position to get
1395 * @param {jQuery} $anchor Element to get $element's position relative to
1396 * @return {Object} Translated position coordinates, containing top and left properties
1397 */
1398 OO.ui.Element.static.getRelativePosition = function ( $element, $anchor ) {
1399 var iframe, iframePos,
1400 pos = $element.offset(),
1401 anchorPos = $anchor.offset(),
1402 elementDocument = this.getDocument( $element ),
1403 anchorDocument = this.getDocument( $anchor );
1404
1405 // If $element isn't in the same document as $anchor, traverse up
1406 while ( elementDocument !== anchorDocument ) {
1407 iframe = elementDocument.defaultView.frameElement;
1408 if ( !iframe ) {
1409 throw new Error( '$element frame is not contained in $anchor frame' );
1410 }
1411 iframePos = $( iframe ).offset();
1412 pos.left += iframePos.left;
1413 pos.top += iframePos.top;
1414 elementDocument = iframe.ownerDocument;
1415 }
1416 pos.left -= anchorPos.left;
1417 pos.top -= anchorPos.top;
1418 return pos;
1419 };
1420
1421 /**
1422 * Get element border sizes.
1423 *
1424 * @static
1425 * @param {HTMLElement} el Element to measure
1426 * @return {Object} Dimensions object with `top`, `left`, `bottom` and `right` properties
1427 */
1428 OO.ui.Element.static.getBorders = function ( el ) {
1429 var doc = el.ownerDocument,
1430 win = doc.parentWindow || doc.defaultView,
1431 style = win && win.getComputedStyle ?
1432 win.getComputedStyle( el, null ) :
1433 el.currentStyle,
1434 $el = $( el ),
1435 top = parseFloat( style ? style.borderTopWidth : $el.css( 'borderTopWidth' ) ) || 0,
1436 left = parseFloat( style ? style.borderLeftWidth : $el.css( 'borderLeftWidth' ) ) || 0,
1437 bottom = parseFloat( style ? style.borderBottomWidth : $el.css( 'borderBottomWidth' ) ) || 0,
1438 right = parseFloat( style ? style.borderRightWidth : $el.css( 'borderRightWidth' ) ) || 0;
1439
1440 return {
1441 top: top,
1442 left: left,
1443 bottom: bottom,
1444 right: right
1445 };
1446 };
1447
1448 /**
1449 * Get dimensions of an element or window.
1450 *
1451 * @static
1452 * @param {HTMLElement|Window} el Element to measure
1453 * @return {Object} Dimensions object with `borders`, `scroll`, `scrollbar` and `rect` properties
1454 */
1455 OO.ui.Element.static.getDimensions = function ( el ) {
1456 var $el, $win,
1457 doc = el.ownerDocument || el.document,
1458 win = doc.parentWindow || doc.defaultView;
1459
1460 if ( win === el || el === doc.documentElement ) {
1461 $win = $( win );
1462 return {
1463 borders: { top: 0, left: 0, bottom: 0, right: 0 },
1464 scroll: {
1465 top: $win.scrollTop(),
1466 left: $win.scrollLeft()
1467 },
1468 scrollbar: { right: 0, bottom: 0 },
1469 rect: {
1470 top: 0,
1471 left: 0,
1472 bottom: $win.innerHeight(),
1473 right: $win.innerWidth()
1474 }
1475 };
1476 } else {
1477 $el = $( el );
1478 return {
1479 borders: this.getBorders( el ),
1480 scroll: {
1481 top: $el.scrollTop(),
1482 left: $el.scrollLeft()
1483 },
1484 scrollbar: {
1485 right: $el.innerWidth() - el.clientWidth,
1486 bottom: $el.innerHeight() - el.clientHeight
1487 },
1488 rect: el.getBoundingClientRect()
1489 };
1490 }
1491 };
1492
1493 /**
1494 * Get scrollable object parent
1495 *
1496 * documentElement can't be used to get or set the scrollTop
1497 * property on Blink. Changing and testing its value lets us
1498 * use 'body' or 'documentElement' based on what is working.
1499 *
1500 * https://code.google.com/p/chromium/issues/detail?id=303131
1501 *
1502 * @static
1503 * @param {HTMLElement} el Element to find scrollable parent for
1504 * @return {HTMLElement} Scrollable parent
1505 */
1506 OO.ui.Element.static.getRootScrollableElement = function ( el ) {
1507 var scrollTop, body;
1508
1509 if ( OO.ui.scrollableElement === undefined ) {
1510 body = el.ownerDocument.body;
1511 scrollTop = body.scrollTop;
1512 body.scrollTop = 1;
1513
1514 if ( body.scrollTop === 1 ) {
1515 body.scrollTop = scrollTop;
1516 OO.ui.scrollableElement = 'body';
1517 } else {
1518 OO.ui.scrollableElement = 'documentElement';
1519 }
1520 }
1521
1522 return el.ownerDocument[ OO.ui.scrollableElement ];
1523 };
1524
1525 /**
1526 * Get closest scrollable container.
1527 *
1528 * Traverses up until either a scrollable element or the root is reached, in which case the window
1529 * will be returned.
1530 *
1531 * @static
1532 * @param {HTMLElement} el Element to find scrollable container for
1533 * @param {string} [dimension] Dimension of scrolling to look for; `x`, `y` or omit for either
1534 * @return {HTMLElement} Closest scrollable container
1535 */
1536 OO.ui.Element.static.getClosestScrollableContainer = function ( el, dimension ) {
1537 var i, val,
1538 // props = [ 'overflow' ] doesn't work due to https://bugzilla.mozilla.org/show_bug.cgi?id=889091
1539 props = [ 'overflow-x', 'overflow-y' ],
1540 $parent = $( el ).parent();
1541
1542 if ( dimension === 'x' || dimension === 'y' ) {
1543 props = [ 'overflow-' + dimension ];
1544 }
1545
1546 while ( $parent.length ) {
1547 if ( $parent[ 0 ] === this.getRootScrollableElement( el ) ) {
1548 return $parent[ 0 ];
1549 }
1550 i = props.length;
1551 while ( i-- ) {
1552 val = $parent.css( props[ i ] );
1553 if ( val === 'auto' || val === 'scroll' ) {
1554 return $parent[ 0 ];
1555 }
1556 }
1557 $parent = $parent.parent();
1558 }
1559 return this.getDocument( el ).body;
1560 };
1561
1562 /**
1563 * Scroll element into view.
1564 *
1565 * @static
1566 * @param {HTMLElement} el Element to scroll into view
1567 * @param {Object} [config] Configuration options
1568 * @param {string} [config.duration] jQuery animation duration value
1569 * @param {string} [config.direction] Scroll in only one direction, e.g. 'x' or 'y', omit
1570 * to scroll in both directions
1571 * @param {Function} [config.complete] Function to call when scrolling completes
1572 */
1573 OO.ui.Element.static.scrollIntoView = function ( el, config ) {
1574 // Configuration initialization
1575 config = config || {};
1576
1577 var rel, anim = {},
1578 callback = typeof config.complete === 'function' && config.complete,
1579 sc = this.getClosestScrollableContainer( el, config.direction ),
1580 $sc = $( sc ),
1581 eld = this.getDimensions( el ),
1582 scd = this.getDimensions( sc ),
1583 $win = $( this.getWindow( el ) );
1584
1585 // Compute the distances between the edges of el and the edges of the scroll viewport
1586 if ( $sc.is( 'html, body' ) ) {
1587 // If the scrollable container is the root, this is easy
1588 rel = {
1589 top: eld.rect.top,
1590 bottom: $win.innerHeight() - eld.rect.bottom,
1591 left: eld.rect.left,
1592 right: $win.innerWidth() - eld.rect.right
1593 };
1594 } else {
1595 // Otherwise, we have to subtract el's coordinates from sc's coordinates
1596 rel = {
1597 top: eld.rect.top - ( scd.rect.top + scd.borders.top ),
1598 bottom: scd.rect.bottom - scd.borders.bottom - scd.scrollbar.bottom - eld.rect.bottom,
1599 left: eld.rect.left - ( scd.rect.left + scd.borders.left ),
1600 right: scd.rect.right - scd.borders.right - scd.scrollbar.right - eld.rect.right
1601 };
1602 }
1603
1604 if ( !config.direction || config.direction === 'y' ) {
1605 if ( rel.top < 0 ) {
1606 anim.scrollTop = scd.scroll.top + rel.top;
1607 } else if ( rel.top > 0 && rel.bottom < 0 ) {
1608 anim.scrollTop = scd.scroll.top + Math.min( rel.top, -rel.bottom );
1609 }
1610 }
1611 if ( !config.direction || config.direction === 'x' ) {
1612 if ( rel.left < 0 ) {
1613 anim.scrollLeft = scd.scroll.left + rel.left;
1614 } else if ( rel.left > 0 && rel.right < 0 ) {
1615 anim.scrollLeft = scd.scroll.left + Math.min( rel.left, -rel.right );
1616 }
1617 }
1618 if ( !$.isEmptyObject( anim ) ) {
1619 $sc.stop( true ).animate( anim, config.duration || 'fast' );
1620 if ( callback ) {
1621 $sc.queue( function ( next ) {
1622 callback();
1623 next();
1624 } );
1625 }
1626 } else {
1627 if ( callback ) {
1628 callback();
1629 }
1630 }
1631 };
1632
1633 /**
1634 * Force the browser to reconsider whether it really needs to render scrollbars inside the element
1635 * and reserve space for them, because it probably doesn't.
1636 *
1637 * Workaround primarily for <https://code.google.com/p/chromium/issues/detail?id=387290>, but also
1638 * similar bugs in other browsers. "Just" forcing a reflow is not sufficient in all cases, we need
1639 * to first actually detach (or hide, but detaching is simpler) all children, *then* force a reflow,
1640 * and then reattach (or show) them back.
1641 *
1642 * @static
1643 * @param {HTMLElement} el Element to reconsider the scrollbars on
1644 */
1645 OO.ui.Element.static.reconsiderScrollbars = function ( el ) {
1646 var i, len, scrollLeft, scrollTop, nodes = [];
1647 // Save scroll position
1648 scrollLeft = el.scrollLeft;
1649 scrollTop = el.scrollTop;
1650 // Detach all children
1651 while ( el.firstChild ) {
1652 nodes.push( el.firstChild );
1653 el.removeChild( el.firstChild );
1654 }
1655 // Force reflow
1656 void el.offsetHeight;
1657 // Reattach all children
1658 for ( i = 0, len = nodes.length; i < len; i++ ) {
1659 el.appendChild( nodes[ i ] );
1660 }
1661 // Restore scroll position (no-op if scrollbars disappeared)
1662 el.scrollLeft = scrollLeft;
1663 el.scrollTop = scrollTop;
1664 };
1665
1666 /* Methods */
1667
1668 /**
1669 * Toggle visibility of an element.
1670 *
1671 * @param {boolean} [show] Make element visible, omit to toggle visibility
1672 * @fires visible
1673 * @chainable
1674 */
1675 OO.ui.Element.prototype.toggle = function ( show ) {
1676 show = show === undefined ? !this.visible : !!show;
1677
1678 if ( show !== this.isVisible() ) {
1679 this.visible = show;
1680 this.$element.toggleClass( 'oo-ui-element-hidden', !this.visible );
1681 this.emit( 'toggle', show );
1682 }
1683
1684 return this;
1685 };
1686
1687 /**
1688 * Check if element is visible.
1689 *
1690 * @return {boolean} element is visible
1691 */
1692 OO.ui.Element.prototype.isVisible = function () {
1693 return this.visible;
1694 };
1695
1696 /**
1697 * Get element data.
1698 *
1699 * @return {Mixed} Element data
1700 */
1701 OO.ui.Element.prototype.getData = function () {
1702 return this.data;
1703 };
1704
1705 /**
1706 * Set element data.
1707 *
1708 * @param {Mixed} Element data
1709 * @chainable
1710 */
1711 OO.ui.Element.prototype.setData = function ( data ) {
1712 this.data = data;
1713 return this;
1714 };
1715
1716 /**
1717 * Check if element supports one or more methods.
1718 *
1719 * @param {string|string[]} methods Method or list of methods to check
1720 * @return {boolean} All methods are supported
1721 */
1722 OO.ui.Element.prototype.supports = function ( methods ) {
1723 var i, len,
1724 support = 0;
1725
1726 methods = Array.isArray( methods ) ? methods : [ methods ];
1727 for ( i = 0, len = methods.length; i < len; i++ ) {
1728 if ( $.isFunction( this[ methods[ i ] ] ) ) {
1729 support++;
1730 }
1731 }
1732
1733 return methods.length === support;
1734 };
1735
1736 /**
1737 * Update the theme-provided classes.
1738 *
1739 * @localdoc This is called in element mixins and widget classes any time state changes.
1740 * Updating is debounced, minimizing overhead of changing multiple attributes and
1741 * guaranteeing that theme updates do not occur within an element's constructor
1742 */
1743 OO.ui.Element.prototype.updateThemeClasses = function () {
1744 if ( !this.updateThemeClassesPending ) {
1745 this.updateThemeClassesPending = true;
1746 setTimeout( this.debouncedUpdateThemeClassesHandler );
1747 }
1748 };
1749
1750 /**
1751 * @private
1752 */
1753 OO.ui.Element.prototype.debouncedUpdateThemeClasses = function () {
1754 OO.ui.theme.updateElementClasses( this );
1755 this.updateThemeClassesPending = false;
1756 };
1757
1758 /**
1759 * Get the HTML tag name.
1760 *
1761 * Override this method to base the result on instance information.
1762 *
1763 * @return {string} HTML tag name
1764 */
1765 OO.ui.Element.prototype.getTagName = function () {
1766 return this.constructor.static.tagName;
1767 };
1768
1769 /**
1770 * Check if the element is attached to the DOM
1771 * @return {boolean} The element is attached to the DOM
1772 */
1773 OO.ui.Element.prototype.isElementAttached = function () {
1774 return $.contains( this.getElementDocument(), this.$element[ 0 ] );
1775 };
1776
1777 /**
1778 * Get the DOM document.
1779 *
1780 * @return {HTMLDocument} Document object
1781 */
1782 OO.ui.Element.prototype.getElementDocument = function () {
1783 // Don't cache this in other ways either because subclasses could can change this.$element
1784 return OO.ui.Element.static.getDocument( this.$element );
1785 };
1786
1787 /**
1788 * Get the DOM window.
1789 *
1790 * @return {Window} Window object
1791 */
1792 OO.ui.Element.prototype.getElementWindow = function () {
1793 return OO.ui.Element.static.getWindow( this.$element );
1794 };
1795
1796 /**
1797 * Get closest scrollable container.
1798 */
1799 OO.ui.Element.prototype.getClosestScrollableElementContainer = function () {
1800 return OO.ui.Element.static.getClosestScrollableContainer( this.$element[ 0 ] );
1801 };
1802
1803 /**
1804 * Get group element is in.
1805 *
1806 * @return {OO.ui.mixin.GroupElement|null} Group element, null if none
1807 */
1808 OO.ui.Element.prototype.getElementGroup = function () {
1809 return this.elementGroup;
1810 };
1811
1812 /**
1813 * Set group element is in.
1814 *
1815 * @param {OO.ui.mixin.GroupElement|null} group Group element, null if none
1816 * @chainable
1817 */
1818 OO.ui.Element.prototype.setElementGroup = function ( group ) {
1819 this.elementGroup = group;
1820 return this;
1821 };
1822
1823 /**
1824 * Scroll element into view.
1825 *
1826 * @param {Object} [config] Configuration options
1827 */
1828 OO.ui.Element.prototype.scrollElementIntoView = function ( config ) {
1829 return OO.ui.Element.static.scrollIntoView( this.$element[ 0 ], config );
1830 };
1831
1832 /**
1833 * Gather the dynamic state (focus, value of form inputs, scroll position, etc.) of a HTML DOM node
1834 * (and its children) that represent an Element of the same type and configuration as the current
1835 * one, generated by the PHP implementation.
1836 *
1837 * This method is called just before `node` is detached from the DOM. The return value of this
1838 * function will be passed to #restorePreInfuseState after this widget's #$element is inserted into
1839 * DOM to replace `node`.
1840 *
1841 * @protected
1842 * @param {HTMLElement} node
1843 * @return {Object}
1844 */
1845 OO.ui.Element.prototype.gatherPreInfuseState = function () {
1846 return {};
1847 };
1848
1849 /**
1850 * Restore the pre-infusion dynamic state for this widget.
1851 *
1852 * This method is called after #$element has been inserted into DOM. The parameter is the return
1853 * value of #gatherPreInfuseState.
1854 *
1855 * @protected
1856 * @param {Object} state
1857 */
1858 OO.ui.Element.prototype.restorePreInfuseState = function () {
1859 };
1860
1861 /**
1862 * Layouts are containers for elements and are used to arrange other widgets of arbitrary type in a way
1863 * that is centrally controlled and can be updated dynamically. Layouts can be, and usually are, combined.
1864 * See {@link OO.ui.FieldsetLayout FieldsetLayout}, {@link OO.ui.FieldLayout FieldLayout}, {@link OO.ui.FormLayout FormLayout},
1865 * {@link OO.ui.PanelLayout PanelLayout}, {@link OO.ui.StackLayout StackLayout}, {@link OO.ui.PageLayout PageLayout},
1866 * {@link OO.ui.HorizontalLayout HorizontalLayout}, and {@link OO.ui.BookletLayout BookletLayout} for more information and examples.
1867 *
1868 * @abstract
1869 * @class
1870 * @extends OO.ui.Element
1871 * @mixins OO.EventEmitter
1872 *
1873 * @constructor
1874 * @param {Object} [config] Configuration options
1875 */
1876 OO.ui.Layout = function OoUiLayout( config ) {
1877 // Configuration initialization
1878 config = config || {};
1879
1880 // Parent constructor
1881 OO.ui.Layout.parent.call( this, config );
1882
1883 // Mixin constructors
1884 OO.EventEmitter.call( this );
1885
1886 // Initialization
1887 this.$element.addClass( 'oo-ui-layout' );
1888 };
1889
1890 /* Setup */
1891
1892 OO.inheritClass( OO.ui.Layout, OO.ui.Element );
1893 OO.mixinClass( OO.ui.Layout, OO.EventEmitter );
1894
1895 /**
1896 * Widgets are compositions of one or more OOjs UI elements that users can both view
1897 * and interact with. All widgets can be configured and modified via a standard API,
1898 * and their state can change dynamically according to a model.
1899 *
1900 * @abstract
1901 * @class
1902 * @extends OO.ui.Element
1903 * @mixins OO.EventEmitter
1904 *
1905 * @constructor
1906 * @param {Object} [config] Configuration options
1907 * @cfg {boolean} [disabled=false] Disable the widget. Disabled widgets cannot be used and their
1908 * appearance reflects this state.
1909 */
1910 OO.ui.Widget = function OoUiWidget( config ) {
1911 // Initialize config
1912 config = $.extend( { disabled: false }, config );
1913
1914 // Parent constructor
1915 OO.ui.Widget.parent.call( this, config );
1916
1917 // Mixin constructors
1918 OO.EventEmitter.call( this );
1919
1920 // Properties
1921 this.disabled = null;
1922 this.wasDisabled = null;
1923
1924 // Initialization
1925 this.$element.addClass( 'oo-ui-widget' );
1926 this.setDisabled( !!config.disabled );
1927 };
1928
1929 /* Setup */
1930
1931 OO.inheritClass( OO.ui.Widget, OO.ui.Element );
1932 OO.mixinClass( OO.ui.Widget, OO.EventEmitter );
1933
1934 /* Static Properties */
1935
1936 /**
1937 * Whether this widget will behave reasonably when wrapped in a HTML `<label>`. If this is true,
1938 * wrappers such as OO.ui.FieldLayout may use a `<label>` instead of implementing own label click
1939 * handling.
1940 *
1941 * @static
1942 * @inheritable
1943 * @property {boolean}
1944 */
1945 OO.ui.Widget.static.supportsSimpleLabel = false;
1946
1947 /* Events */
1948
1949 /**
1950 * @event disable
1951 *
1952 * A 'disable' event is emitted when a widget is disabled.
1953 *
1954 * @param {boolean} disabled Widget is disabled
1955 */
1956
1957 /**
1958 * @event toggle
1959 *
1960 * A 'toggle' event is emitted when the visibility of the widget changes.
1961 *
1962 * @param {boolean} visible Widget is visible
1963 */
1964
1965 /* Methods */
1966
1967 /**
1968 * Check if the widget is disabled.
1969 *
1970 * @return {boolean} Widget is disabled
1971 */
1972 OO.ui.Widget.prototype.isDisabled = function () {
1973 return this.disabled;
1974 };
1975
1976 /**
1977 * Set the 'disabled' state of the widget.
1978 *
1979 * When a widget is disabled, it cannot be used and its appearance is updated to reflect this state.
1980 *
1981 * @param {boolean} disabled Disable widget
1982 * @chainable
1983 */
1984 OO.ui.Widget.prototype.setDisabled = function ( disabled ) {
1985 var isDisabled;
1986
1987 this.disabled = !!disabled;
1988 isDisabled = this.isDisabled();
1989 if ( isDisabled !== this.wasDisabled ) {
1990 this.$element.toggleClass( 'oo-ui-widget-disabled', isDisabled );
1991 this.$element.toggleClass( 'oo-ui-widget-enabled', !isDisabled );
1992 this.$element.attr( 'aria-disabled', isDisabled.toString() );
1993 this.emit( 'disable', isDisabled );
1994 this.updateThemeClasses();
1995 }
1996 this.wasDisabled = isDisabled;
1997
1998 return this;
1999 };
2000
2001 /**
2002 * Update the disabled state, in case of changes in parent widget.
2003 *
2004 * @chainable
2005 */
2006 OO.ui.Widget.prototype.updateDisabled = function () {
2007 this.setDisabled( this.disabled );
2008 return this;
2009 };
2010
2011 /**
2012 * A window is a container for elements that are in a child frame. They are used with
2013 * a window manager (OO.ui.WindowManager), which is used to open and close the window and control
2014 * its presentation. The size of a window is specified using a symbolic name (e.g., ‘small’, ‘medium’,
2015 * ‘large’), which is interpreted by the window manager. If the requested size is not recognized,
2016 * the window manager will choose a sensible fallback.
2017 *
2018 * The lifecycle of a window has three primary stages (opening, opened, and closing) in which
2019 * different processes are executed:
2020 *
2021 * **opening**: The opening stage begins when the window manager's {@link OO.ui.WindowManager#openWindow
2022 * openWindow} or the window's {@link #open open} methods are used, and the window manager begins to open
2023 * the window.
2024 *
2025 * - {@link #getSetupProcess} method is called and its result executed
2026 * - {@link #getReadyProcess} method is called and its result executed
2027 *
2028 * **opened**: The window is now open
2029 *
2030 * **closing**: The closing stage begins when the window manager's
2031 * {@link OO.ui.WindowManager#closeWindow closeWindow}
2032 * or the window's {@link #close} methods are used, and the window manager begins to close the window.
2033 *
2034 * - {@link #getHoldProcess} method is called and its result executed
2035 * - {@link #getTeardownProcess} method is called and its result executed. The window is now closed
2036 *
2037 * Each of the window's processes (setup, ready, hold, and teardown) can be extended in subclasses
2038 * by overriding the window's #getSetupProcess, #getReadyProcess, #getHoldProcess and #getTeardownProcess
2039 * methods. Note that each {@link OO.ui.Process process} is executed in series, so asynchronous
2040 * processing can complete. Always assume window processes are executed asynchronously.
2041 *
2042 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
2043 *
2044 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows
2045 *
2046 * @abstract
2047 * @class
2048 * @extends OO.ui.Element
2049 * @mixins OO.EventEmitter
2050 *
2051 * @constructor
2052 * @param {Object} [config] Configuration options
2053 * @cfg {string} [size] Symbolic name of the dialog size: `small`, `medium`, `large`, `larger` or
2054 * `full`. If omitted, the value of the {@link #static-size static size} property will be used.
2055 */
2056 OO.ui.Window = function OoUiWindow( config ) {
2057 // Configuration initialization
2058 config = config || {};
2059
2060 // Parent constructor
2061 OO.ui.Window.parent.call( this, config );
2062
2063 // Mixin constructors
2064 OO.EventEmitter.call( this );
2065
2066 // Properties
2067 this.manager = null;
2068 this.size = config.size || this.constructor.static.size;
2069 this.$frame = $( '<div>' );
2070 this.$overlay = $( '<div>' );
2071 this.$content = $( '<div>' );
2072
2073 // Initialization
2074 this.$overlay.addClass( 'oo-ui-window-overlay' );
2075 this.$content
2076 .addClass( 'oo-ui-window-content' )
2077 .attr( 'tabindex', 0 );
2078 this.$frame
2079 .addClass( 'oo-ui-window-frame' )
2080 .append( this.$content );
2081
2082 this.$element
2083 .addClass( 'oo-ui-window' )
2084 .append( this.$frame, this.$overlay );
2085
2086 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
2087 // that reference properties not initialized at that time of parent class construction
2088 // TODO: Find a better way to handle post-constructor setup
2089 this.visible = false;
2090 this.$element.addClass( 'oo-ui-element-hidden' );
2091 };
2092
2093 /* Setup */
2094
2095 OO.inheritClass( OO.ui.Window, OO.ui.Element );
2096 OO.mixinClass( OO.ui.Window, OO.EventEmitter );
2097
2098 /* Static Properties */
2099
2100 /**
2101 * Symbolic name of the window size: `small`, `medium`, `large`, `larger` or `full`.
2102 *
2103 * The static size is used if no #size is configured during construction.
2104 *
2105 * @static
2106 * @inheritable
2107 * @property {string}
2108 */
2109 OO.ui.Window.static.size = 'medium';
2110
2111 /* Methods */
2112
2113 /**
2114 * Handle mouse down events.
2115 *
2116 * @private
2117 * @param {jQuery.Event} e Mouse down event
2118 */
2119 OO.ui.Window.prototype.onMouseDown = function ( e ) {
2120 // Prevent clicking on the click-block from stealing focus
2121 if ( e.target === this.$element[ 0 ] ) {
2122 return false;
2123 }
2124 };
2125
2126 /**
2127 * Check if the window has been initialized.
2128 *
2129 * Initialization occurs when a window is added to a manager.
2130 *
2131 * @return {boolean} Window has been initialized
2132 */
2133 OO.ui.Window.prototype.isInitialized = function () {
2134 return !!this.manager;
2135 };
2136
2137 /**
2138 * Check if the window is visible.
2139 *
2140 * @return {boolean} Window is visible
2141 */
2142 OO.ui.Window.prototype.isVisible = function () {
2143 return this.visible;
2144 };
2145
2146 /**
2147 * Check if the window is opening.
2148 *
2149 * This method is a wrapper around the window manager's {@link OO.ui.WindowManager#isOpening isOpening}
2150 * method.
2151 *
2152 * @return {boolean} Window is opening
2153 */
2154 OO.ui.Window.prototype.isOpening = function () {
2155 return this.manager.isOpening( this );
2156 };
2157
2158 /**
2159 * Check if the window is closing.
2160 *
2161 * This method is a wrapper around the window manager's {@link OO.ui.WindowManager#isClosing isClosing} method.
2162 *
2163 * @return {boolean} Window is closing
2164 */
2165 OO.ui.Window.prototype.isClosing = function () {
2166 return this.manager.isClosing( this );
2167 };
2168
2169 /**
2170 * Check if the window is opened.
2171 *
2172 * This method is a wrapper around the window manager's {@link OO.ui.WindowManager#isOpened isOpened} method.
2173 *
2174 * @return {boolean} Window is opened
2175 */
2176 OO.ui.Window.prototype.isOpened = function () {
2177 return this.manager.isOpened( this );
2178 };
2179
2180 /**
2181 * Get the window manager.
2182 *
2183 * All windows must be attached to a window manager, which is used to open
2184 * and close the window and control its presentation.
2185 *
2186 * @return {OO.ui.WindowManager} Manager of window
2187 */
2188 OO.ui.Window.prototype.getManager = function () {
2189 return this.manager;
2190 };
2191
2192 /**
2193 * Get the symbolic name of the window size (e.g., `small` or `medium`).
2194 *
2195 * @return {string} Symbolic name of the size: `small`, `medium`, `large`, `larger`, `full`
2196 */
2197 OO.ui.Window.prototype.getSize = function () {
2198 var viewport = OO.ui.Element.static.getDimensions( this.getElementWindow() ),
2199 sizes = this.manager.constructor.static.sizes,
2200 size = this.size;
2201
2202 if ( !sizes[ size ] ) {
2203 size = this.manager.constructor.static.defaultSize;
2204 }
2205 if ( size !== 'full' && viewport.rect.right - viewport.rect.left < sizes[ size ].width ) {
2206 size = 'full';
2207 }
2208
2209 return size;
2210 };
2211
2212 /**
2213 * Get the size properties associated with the current window size
2214 *
2215 * @return {Object} Size properties
2216 */
2217 OO.ui.Window.prototype.getSizeProperties = function () {
2218 return this.manager.constructor.static.sizes[ this.getSize() ];
2219 };
2220
2221 /**
2222 * Disable transitions on window's frame for the duration of the callback function, then enable them
2223 * back.
2224 *
2225 * @private
2226 * @param {Function} callback Function to call while transitions are disabled
2227 */
2228 OO.ui.Window.prototype.withoutSizeTransitions = function ( callback ) {
2229 // Temporarily resize the frame so getBodyHeight() can use scrollHeight measurements.
2230 // Disable transitions first, otherwise we'll get values from when the window was animating.
2231 var oldTransition,
2232 styleObj = this.$frame[ 0 ].style;
2233 oldTransition = styleObj.transition || styleObj.OTransition || styleObj.MsTransition ||
2234 styleObj.MozTransition || styleObj.WebkitTransition;
2235 styleObj.transition = styleObj.OTransition = styleObj.MsTransition =
2236 styleObj.MozTransition = styleObj.WebkitTransition = 'none';
2237 callback();
2238 // Force reflow to make sure the style changes done inside callback really are not transitioned
2239 this.$frame.height();
2240 styleObj.transition = styleObj.OTransition = styleObj.MsTransition =
2241 styleObj.MozTransition = styleObj.WebkitTransition = oldTransition;
2242 };
2243
2244 /**
2245 * Get the height of the full window contents (i.e., the window head, body and foot together).
2246 *
2247 * What consistitutes the head, body, and foot varies depending on the window type.
2248 * A {@link OO.ui.MessageDialog message dialog} displays a title and message in its body,
2249 * and any actions in the foot. A {@link OO.ui.ProcessDialog process dialog} displays a title
2250 * and special actions in the head, and dialog content in the body.
2251 *
2252 * To get just the height of the dialog body, use the #getBodyHeight method.
2253 *
2254 * @return {number} The height of the window contents (the dialog head, body and foot) in pixels
2255 */
2256 OO.ui.Window.prototype.getContentHeight = function () {
2257 var bodyHeight,
2258 win = this,
2259 bodyStyleObj = this.$body[ 0 ].style,
2260 frameStyleObj = this.$frame[ 0 ].style;
2261
2262 // Temporarily resize the frame so getBodyHeight() can use scrollHeight measurements.
2263 // Disable transitions first, otherwise we'll get values from when the window was animating.
2264 this.withoutSizeTransitions( function () {
2265 var oldHeight = frameStyleObj.height,
2266 oldPosition = bodyStyleObj.position;
2267 frameStyleObj.height = '1px';
2268 // Force body to resize to new width
2269 bodyStyleObj.position = 'relative';
2270 bodyHeight = win.getBodyHeight();
2271 frameStyleObj.height = oldHeight;
2272 bodyStyleObj.position = oldPosition;
2273 } );
2274
2275 return (
2276 // Add buffer for border
2277 ( this.$frame.outerHeight() - this.$frame.innerHeight() ) +
2278 // Use combined heights of children
2279 ( this.$head.outerHeight( true ) + bodyHeight + this.$foot.outerHeight( true ) )
2280 );
2281 };
2282
2283 /**
2284 * Get the height of the window body.
2285 *
2286 * To get the height of the full window contents (the window body, head, and foot together),
2287 * use #getContentHeight.
2288 *
2289 * When this function is called, the window will temporarily have been resized
2290 * to height=1px, so .scrollHeight measurements can be taken accurately.
2291 *
2292 * @return {number} Height of the window body in pixels
2293 */
2294 OO.ui.Window.prototype.getBodyHeight = function () {
2295 return this.$body[ 0 ].scrollHeight;
2296 };
2297
2298 /**
2299 * Get the directionality of the frame (right-to-left or left-to-right).
2300 *
2301 * @return {string} Directionality: `'ltr'` or `'rtl'`
2302 */
2303 OO.ui.Window.prototype.getDir = function () {
2304 return OO.ui.Element.static.getDir( this.$content ) || 'ltr';
2305 };
2306
2307 /**
2308 * Get the 'setup' process.
2309 *
2310 * The setup process is used to set up a window for use in a particular context,
2311 * based on the `data` argument. This method is called during the opening phase of the window’s
2312 * lifecycle.
2313 *
2314 * Override this method to add additional steps to the ‘setup’ process the parent method provides
2315 * using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next} methods
2316 * of OO.ui.Process.
2317 *
2318 * To add window content that persists between openings, you may wish to use the #initialize method
2319 * instead.
2320 *
2321 * @abstract
2322 * @param {Object} [data] Window opening data
2323 * @return {OO.ui.Process} Setup process
2324 */
2325 OO.ui.Window.prototype.getSetupProcess = function () {
2326 return new OO.ui.Process();
2327 };
2328
2329 /**
2330 * Get the ‘ready’ process.
2331 *
2332 * The ready process is used to ready a window for use in a particular
2333 * context, based on the `data` argument. This method is called during the opening phase of
2334 * the window’s lifecycle, after the window has been {@link #getSetupProcess setup}.
2335 *
2336 * Override this method to add additional steps to the ‘ready’ process the parent method
2337 * provides using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next}
2338 * methods of OO.ui.Process.
2339 *
2340 * @abstract
2341 * @param {Object} [data] Window opening data
2342 * @return {OO.ui.Process} Ready process
2343 */
2344 OO.ui.Window.prototype.getReadyProcess = function () {
2345 return new OO.ui.Process();
2346 };
2347
2348 /**
2349 * Get the 'hold' process.
2350 *
2351 * The hold proccess is used to keep a window from being used in a particular context,
2352 * based on the `data` argument. This method is called during the closing phase of the window’s
2353 * lifecycle.
2354 *
2355 * Override this method to add additional steps to the 'hold' process the parent method provides
2356 * using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next} methods
2357 * of OO.ui.Process.
2358 *
2359 * @abstract
2360 * @param {Object} [data] Window closing data
2361 * @return {OO.ui.Process} Hold process
2362 */
2363 OO.ui.Window.prototype.getHoldProcess = function () {
2364 return new OO.ui.Process();
2365 };
2366
2367 /**
2368 * Get the ‘teardown’ process.
2369 *
2370 * The teardown process is used to teardown a window after use. During teardown,
2371 * user interactions within the window are conveyed and the window is closed, based on the `data`
2372 * argument. This method is called during the closing phase of the window’s lifecycle.
2373 *
2374 * Override this method to add additional steps to the ‘teardown’ process the parent method provides
2375 * using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next} methods
2376 * of OO.ui.Process.
2377 *
2378 * @abstract
2379 * @param {Object} [data] Window closing data
2380 * @return {OO.ui.Process} Teardown process
2381 */
2382 OO.ui.Window.prototype.getTeardownProcess = function () {
2383 return new OO.ui.Process();
2384 };
2385
2386 /**
2387 * Set the window manager.
2388 *
2389 * This will cause the window to initialize. Calling it more than once will cause an error.
2390 *
2391 * @param {OO.ui.WindowManager} manager Manager for this window
2392 * @throws {Error} An error is thrown if the method is called more than once
2393 * @chainable
2394 */
2395 OO.ui.Window.prototype.setManager = function ( manager ) {
2396 if ( this.manager ) {
2397 throw new Error( 'Cannot set window manager, window already has a manager' );
2398 }
2399
2400 this.manager = manager;
2401 this.initialize();
2402
2403 return this;
2404 };
2405
2406 /**
2407 * Set the window size by symbolic name (e.g., 'small' or 'medium')
2408 *
2409 * @param {string} size Symbolic name of size: `small`, `medium`, `large`, `larger` or
2410 * `full`
2411 * @chainable
2412 */
2413 OO.ui.Window.prototype.setSize = function ( size ) {
2414 this.size = size;
2415 this.updateSize();
2416 return this;
2417 };
2418
2419 /**
2420 * Update the window size.
2421 *
2422 * @throws {Error} An error is thrown if the window is not attached to a window manager
2423 * @chainable
2424 */
2425 OO.ui.Window.prototype.updateSize = function () {
2426 if ( !this.manager ) {
2427 throw new Error( 'Cannot update window size, must be attached to a manager' );
2428 }
2429
2430 this.manager.updateWindowSize( this );
2431
2432 return this;
2433 };
2434
2435 /**
2436 * Set window dimensions. This method is called by the {@link OO.ui.WindowManager window manager}
2437 * when the window is opening. In general, setDimensions should not be called directly.
2438 *
2439 * To set the size of the window, use the #setSize method.
2440 *
2441 * @param {Object} dim CSS dimension properties
2442 * @param {string|number} [dim.width] Width
2443 * @param {string|number} [dim.minWidth] Minimum width
2444 * @param {string|number} [dim.maxWidth] Maximum width
2445 * @param {string|number} [dim.width] Height, omit to set based on height of contents
2446 * @param {string|number} [dim.minWidth] Minimum height
2447 * @param {string|number} [dim.maxWidth] Maximum height
2448 * @chainable
2449 */
2450 OO.ui.Window.prototype.setDimensions = function ( dim ) {
2451 var height,
2452 win = this,
2453 styleObj = this.$frame[ 0 ].style;
2454
2455 // Calculate the height we need to set using the correct width
2456 if ( dim.height === undefined ) {
2457 this.withoutSizeTransitions( function () {
2458 var oldWidth = styleObj.width;
2459 win.$frame.css( 'width', dim.width || '' );
2460 height = win.getContentHeight();
2461 styleObj.width = oldWidth;
2462 } );
2463 } else {
2464 height = dim.height;
2465 }
2466
2467 this.$frame.css( {
2468 width: dim.width || '',
2469 minWidth: dim.minWidth || '',
2470 maxWidth: dim.maxWidth || '',
2471 height: height || '',
2472 minHeight: dim.minHeight || '',
2473 maxHeight: dim.maxHeight || ''
2474 } );
2475
2476 return this;
2477 };
2478
2479 /**
2480 * Initialize window contents.
2481 *
2482 * Before the window is opened for the first time, #initialize is called so that content that
2483 * persists between openings can be added to the window.
2484 *
2485 * To set up a window with new content each time the window opens, use #getSetupProcess.
2486 *
2487 * @throws {Error} An error is thrown if the window is not attached to a window manager
2488 * @chainable
2489 */
2490 OO.ui.Window.prototype.initialize = function () {
2491 if ( !this.manager ) {
2492 throw new Error( 'Cannot initialize window, must be attached to a manager' );
2493 }
2494
2495 // Properties
2496 this.$head = $( '<div>' );
2497 this.$body = $( '<div>' );
2498 this.$foot = $( '<div>' );
2499 this.$document = $( this.getElementDocument() );
2500
2501 // Events
2502 this.$element.on( 'mousedown', this.onMouseDown.bind( this ) );
2503
2504 // Initialization
2505 this.$head.addClass( 'oo-ui-window-head' );
2506 this.$body.addClass( 'oo-ui-window-body' );
2507 this.$foot.addClass( 'oo-ui-window-foot' );
2508 this.$content.append( this.$head, this.$body, this.$foot );
2509
2510 return this;
2511 };
2512
2513 /**
2514 * Open the window.
2515 *
2516 * This method is a wrapper around a call to the window manager’s {@link OO.ui.WindowManager#openWindow openWindow}
2517 * method, which returns a promise resolved when the window is done opening.
2518 *
2519 * To customize the window each time it opens, use #getSetupProcess or #getReadyProcess.
2520 *
2521 * @param {Object} [data] Window opening data
2522 * @return {jQuery.Promise} Promise resolved with a value when the window is opened, or rejected
2523 * if the window fails to open. When the promise is resolved successfully, the first argument of the
2524 * value is a new promise, which is resolved when the window begins closing.
2525 * @throws {Error} An error is thrown if the window is not attached to a window manager
2526 */
2527 OO.ui.Window.prototype.open = function ( data ) {
2528 if ( !this.manager ) {
2529 throw new Error( 'Cannot open window, must be attached to a manager' );
2530 }
2531
2532 return this.manager.openWindow( this, data );
2533 };
2534
2535 /**
2536 * Close the window.
2537 *
2538 * This method is a wrapper around a call to the window
2539 * manager’s {@link OO.ui.WindowManager#closeWindow closeWindow} method,
2540 * which returns a closing promise resolved when the window is done closing.
2541 *
2542 * The window's #getHoldProcess and #getTeardownProcess methods are called during the closing
2543 * phase of the window’s lifecycle and can be used to specify closing behavior each time
2544 * the window closes.
2545 *
2546 * @param {Object} [data] Window closing data
2547 * @return {jQuery.Promise} Promise resolved when window is closed
2548 * @throws {Error} An error is thrown if the window is not attached to a window manager
2549 */
2550 OO.ui.Window.prototype.close = function ( data ) {
2551 if ( !this.manager ) {
2552 throw new Error( 'Cannot close window, must be attached to a manager' );
2553 }
2554
2555 return this.manager.closeWindow( this, data );
2556 };
2557
2558 /**
2559 * Setup window.
2560 *
2561 * This is called by OO.ui.WindowManager during window opening, and should not be called directly
2562 * by other systems.
2563 *
2564 * @param {Object} [data] Window opening data
2565 * @return {jQuery.Promise} Promise resolved when window is setup
2566 */
2567 OO.ui.Window.prototype.setup = function ( data ) {
2568 var win = this,
2569 deferred = $.Deferred();
2570
2571 this.toggle( true );
2572
2573 this.getSetupProcess( data ).execute().done( function () {
2574 // Force redraw by asking the browser to measure the elements' widths
2575 win.$element.addClass( 'oo-ui-window-active oo-ui-window-setup' ).width();
2576 win.$content.addClass( 'oo-ui-window-content-setup' ).width();
2577 deferred.resolve();
2578 } );
2579
2580 return deferred.promise();
2581 };
2582
2583 /**
2584 * Ready window.
2585 *
2586 * This is called by OO.ui.WindowManager during window opening, and should not be called directly
2587 * by other systems.
2588 *
2589 * @param {Object} [data] Window opening data
2590 * @return {jQuery.Promise} Promise resolved when window is ready
2591 */
2592 OO.ui.Window.prototype.ready = function ( data ) {
2593 var win = this,
2594 deferred = $.Deferred();
2595
2596 this.$content.focus();
2597 this.getReadyProcess( data ).execute().done( function () {
2598 // Force redraw by asking the browser to measure the elements' widths
2599 win.$element.addClass( 'oo-ui-window-ready' ).width();
2600 win.$content.addClass( 'oo-ui-window-content-ready' ).width();
2601 deferred.resolve();
2602 } );
2603
2604 return deferred.promise();
2605 };
2606
2607 /**
2608 * Hold window.
2609 *
2610 * This is called by OO.ui.WindowManager during window closing, and should not be called directly
2611 * by other systems.
2612 *
2613 * @param {Object} [data] Window closing data
2614 * @return {jQuery.Promise} Promise resolved when window is held
2615 */
2616 OO.ui.Window.prototype.hold = function ( data ) {
2617 var win = this,
2618 deferred = $.Deferred();
2619
2620 this.getHoldProcess( data ).execute().done( function () {
2621 // Get the focused element within the window's content
2622 var $focus = win.$content.find( OO.ui.Element.static.getDocument( win.$content ).activeElement );
2623
2624 // Blur the focused element
2625 if ( $focus.length ) {
2626 $focus[ 0 ].blur();
2627 }
2628
2629 // Force redraw by asking the browser to measure the elements' widths
2630 win.$element.removeClass( 'oo-ui-window-ready' ).width();
2631 win.$content.removeClass( 'oo-ui-window-content-ready' ).width();
2632 deferred.resolve();
2633 } );
2634
2635 return deferred.promise();
2636 };
2637
2638 /**
2639 * Teardown window.
2640 *
2641 * This is called by OO.ui.WindowManager during window closing, and should not be called directly
2642 * by other systems.
2643 *
2644 * @param {Object} [data] Window closing data
2645 * @return {jQuery.Promise} Promise resolved when window is torn down
2646 */
2647 OO.ui.Window.prototype.teardown = function ( data ) {
2648 var win = this;
2649
2650 return this.getTeardownProcess( data ).execute()
2651 .done( function () {
2652 // Force redraw by asking the browser to measure the elements' widths
2653 win.$element.removeClass( 'oo-ui-window-active oo-ui-window-setup' ).width();
2654 win.$content.removeClass( 'oo-ui-window-content-setup' ).width();
2655 win.toggle( false );
2656 } );
2657 };
2658
2659 /**
2660 * The Dialog class serves as the base class for the other types of dialogs.
2661 * Unless extended to include controls, the rendered dialog box is a simple window
2662 * that users can close by hitting the ‘Esc’ key. Dialog windows are used with OO.ui.WindowManager,
2663 * which opens, closes, and controls the presentation of the window. See the
2664 * [OOjs UI documentation on MediaWiki] [1] for more information.
2665 *
2666 * @example
2667 * // A simple dialog window.
2668 * function MyDialog( config ) {
2669 * MyDialog.parent.call( this, config );
2670 * }
2671 * OO.inheritClass( MyDialog, OO.ui.Dialog );
2672 * MyDialog.prototype.initialize = function () {
2673 * MyDialog.parent.prototype.initialize.call( this );
2674 * this.content = new OO.ui.PanelLayout( { padded: true, expanded: false } );
2675 * this.content.$element.append( '<p>A simple dialog window. Press \'Esc\' to close.</p>' );
2676 * this.$body.append( this.content.$element );
2677 * };
2678 * MyDialog.prototype.getBodyHeight = function () {
2679 * return this.content.$element.outerHeight( true );
2680 * };
2681 * var myDialog = new MyDialog( {
2682 * size: 'medium'
2683 * } );
2684 * // Create and append a window manager, which opens and closes the window.
2685 * var windowManager = new OO.ui.WindowManager();
2686 * $( 'body' ).append( windowManager.$element );
2687 * windowManager.addWindows( [ myDialog ] );
2688 * // Open the window!
2689 * windowManager.openWindow( myDialog );
2690 *
2691 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Dialogs
2692 *
2693 * @abstract
2694 * @class
2695 * @extends OO.ui.Window
2696 * @mixins OO.ui.mixin.PendingElement
2697 *
2698 * @constructor
2699 * @param {Object} [config] Configuration options
2700 */
2701 OO.ui.Dialog = function OoUiDialog( config ) {
2702 // Parent constructor
2703 OO.ui.Dialog.parent.call( this, config );
2704
2705 // Mixin constructors
2706 OO.ui.mixin.PendingElement.call( this );
2707
2708 // Properties
2709 this.actions = new OO.ui.ActionSet();
2710 this.attachedActions = [];
2711 this.currentAction = null;
2712 this.onDocumentKeyDownHandler = this.onDocumentKeyDown.bind( this );
2713
2714 // Events
2715 this.actions.connect( this, {
2716 click: 'onActionClick',
2717 resize: 'onActionResize',
2718 change: 'onActionsChange'
2719 } );
2720
2721 // Initialization
2722 this.$element
2723 .addClass( 'oo-ui-dialog' )
2724 .attr( 'role', 'dialog' );
2725 };
2726
2727 /* Setup */
2728
2729 OO.inheritClass( OO.ui.Dialog, OO.ui.Window );
2730 OO.mixinClass( OO.ui.Dialog, OO.ui.mixin.PendingElement );
2731
2732 /* Static Properties */
2733
2734 /**
2735 * Symbolic name of dialog.
2736 *
2737 * The dialog class must have a symbolic name in order to be registered with OO.Factory.
2738 * Please see the [OOjs UI documentation on MediaWiki] [3] for more information.
2739 *
2740 * [3]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
2741 *
2742 * @abstract
2743 * @static
2744 * @inheritable
2745 * @property {string}
2746 */
2747 OO.ui.Dialog.static.name = '';
2748
2749 /**
2750 * The dialog title.
2751 *
2752 * The title can be specified as a plaintext string, a {@link OO.ui.mixin.LabelElement Label} node, or a function
2753 * that will produce a Label node or string. The title can also be specified with data passed to the
2754 * constructor (see #getSetupProcess). In this case, the static value will be overriden.
2755 *
2756 * @abstract
2757 * @static
2758 * @inheritable
2759 * @property {jQuery|string|Function}
2760 */
2761 OO.ui.Dialog.static.title = '';
2762
2763 /**
2764 * An array of configured {@link OO.ui.ActionWidget action widgets}.
2765 *
2766 * Actions can also be specified with data passed to the constructor (see #getSetupProcess). In this case, the static
2767 * value will be overriden.
2768 *
2769 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Action_sets
2770 *
2771 * @static
2772 * @inheritable
2773 * @property {Object[]}
2774 */
2775 OO.ui.Dialog.static.actions = [];
2776
2777 /**
2778 * Close the dialog when the 'Esc' key is pressed.
2779 *
2780 * @static
2781 * @abstract
2782 * @inheritable
2783 * @property {boolean}
2784 */
2785 OO.ui.Dialog.static.escapable = true;
2786
2787 /* Methods */
2788
2789 /**
2790 * Handle frame document key down events.
2791 *
2792 * @private
2793 * @param {jQuery.Event} e Key down event
2794 */
2795 OO.ui.Dialog.prototype.onDocumentKeyDown = function ( e ) {
2796 if ( e.which === OO.ui.Keys.ESCAPE ) {
2797 this.close();
2798 e.preventDefault();
2799 e.stopPropagation();
2800 }
2801 };
2802
2803 /**
2804 * Handle action resized events.
2805 *
2806 * @private
2807 * @param {OO.ui.ActionWidget} action Action that was resized
2808 */
2809 OO.ui.Dialog.prototype.onActionResize = function () {
2810 // Override in subclass
2811 };
2812
2813 /**
2814 * Handle action click events.
2815 *
2816 * @private
2817 * @param {OO.ui.ActionWidget} action Action that was clicked
2818 */
2819 OO.ui.Dialog.prototype.onActionClick = function ( action ) {
2820 if ( !this.isPending() ) {
2821 this.executeAction( action.getAction() );
2822 }
2823 };
2824
2825 /**
2826 * Handle actions change event.
2827 *
2828 * @private
2829 */
2830 OO.ui.Dialog.prototype.onActionsChange = function () {
2831 this.detachActions();
2832 if ( !this.isClosing() ) {
2833 this.attachActions();
2834 }
2835 };
2836
2837 /**
2838 * Get the set of actions used by the dialog.
2839 *
2840 * @return {OO.ui.ActionSet}
2841 */
2842 OO.ui.Dialog.prototype.getActions = function () {
2843 return this.actions;
2844 };
2845
2846 /**
2847 * Get a process for taking action.
2848 *
2849 * When you override this method, you can create a new OO.ui.Process and return it, or add additional
2850 * accept steps to the process the parent method provides using the {@link OO.ui.Process#first 'first'}
2851 * and {@link OO.ui.Process#next 'next'} methods of OO.ui.Process.
2852 *
2853 * @abstract
2854 * @param {string} [action] Symbolic name of action
2855 * @return {OO.ui.Process} Action process
2856 */
2857 OO.ui.Dialog.prototype.getActionProcess = function ( action ) {
2858 return new OO.ui.Process()
2859 .next( function () {
2860 if ( !action ) {
2861 // An empty action always closes the dialog without data, which should always be
2862 // safe and make no changes
2863 this.close();
2864 }
2865 }, this );
2866 };
2867
2868 /**
2869 * @inheritdoc
2870 *
2871 * @param {Object} [data] Dialog opening data
2872 * @param {jQuery|string|Function|null} [data.title] Dialog title, omit to use
2873 * the {@link #static-title static title}
2874 * @param {Object[]} [data.actions] List of configuration options for each
2875 * {@link OO.ui.ActionWidget action widget}, omit to use {@link #static-actions static actions}.
2876 */
2877 OO.ui.Dialog.prototype.getSetupProcess = function ( data ) {
2878 data = data || {};
2879
2880 // Parent method
2881 return OO.ui.Dialog.parent.prototype.getSetupProcess.call( this, data )
2882 .next( function () {
2883 var config = this.constructor.static,
2884 actions = data.actions !== undefined ? data.actions : config.actions;
2885
2886 this.title.setLabel(
2887 data.title !== undefined ? data.title : this.constructor.static.title
2888 );
2889 this.actions.add( this.getActionWidgets( actions ) );
2890
2891 if ( this.constructor.static.escapable ) {
2892 this.$document.on( 'keydown', this.onDocumentKeyDownHandler );
2893 }
2894 }, this );
2895 };
2896
2897 /**
2898 * @inheritdoc
2899 */
2900 OO.ui.Dialog.prototype.getTeardownProcess = function ( data ) {
2901 // Parent method
2902 return OO.ui.Dialog.parent.prototype.getTeardownProcess.call( this, data )
2903 .first( function () {
2904 if ( this.constructor.static.escapable ) {
2905 this.$document.off( 'keydown', this.onDocumentKeyDownHandler );
2906 }
2907
2908 this.actions.clear();
2909 this.currentAction = null;
2910 }, this );
2911 };
2912
2913 /**
2914 * @inheritdoc
2915 */
2916 OO.ui.Dialog.prototype.initialize = function () {
2917 // Parent method
2918 OO.ui.Dialog.parent.prototype.initialize.call( this );
2919
2920 var titleId = OO.ui.generateElementId();
2921
2922 // Properties
2923 this.title = new OO.ui.LabelWidget( {
2924 id: titleId
2925 } );
2926
2927 // Initialization
2928 this.$content.addClass( 'oo-ui-dialog-content' );
2929 this.$element.attr( 'aria-labelledby', titleId );
2930 this.setPendingElement( this.$head );
2931 };
2932
2933 /**
2934 * Get action widgets from a list of configs
2935 *
2936 * @param {Object[]} actions Action widget configs
2937 * @return {OO.ui.ActionWidget[]} Action widgets
2938 */
2939 OO.ui.Dialog.prototype.getActionWidgets = function ( actions ) {
2940 var i, len, widgets = [];
2941 for ( i = 0, len = actions.length; i < len; i++ ) {
2942 widgets.push(
2943 new OO.ui.ActionWidget( actions[ i ] )
2944 );
2945 }
2946 return widgets;
2947 };
2948
2949 /**
2950 * Attach action actions.
2951 *
2952 * @protected
2953 */
2954 OO.ui.Dialog.prototype.attachActions = function () {
2955 // Remember the list of potentially attached actions
2956 this.attachedActions = this.actions.get();
2957 };
2958
2959 /**
2960 * Detach action actions.
2961 *
2962 * @protected
2963 * @chainable
2964 */
2965 OO.ui.Dialog.prototype.detachActions = function () {
2966 var i, len;
2967
2968 // Detach all actions that may have been previously attached
2969 for ( i = 0, len = this.attachedActions.length; i < len; i++ ) {
2970 this.attachedActions[ i ].$element.detach();
2971 }
2972 this.attachedActions = [];
2973 };
2974
2975 /**
2976 * Execute an action.
2977 *
2978 * @param {string} action Symbolic name of action to execute
2979 * @return {jQuery.Promise} Promise resolved when action completes, rejected if it fails
2980 */
2981 OO.ui.Dialog.prototype.executeAction = function ( action ) {
2982 this.pushPending();
2983 this.currentAction = action;
2984 return this.getActionProcess( action ).execute()
2985 .always( this.popPending.bind( this ) );
2986 };
2987
2988 /**
2989 * Window managers are used to open and close {@link OO.ui.Window windows} and control their presentation.
2990 * Managed windows are mutually exclusive. If a new window is opened while a current window is opening
2991 * or is opened, the current window will be closed and any ongoing {@link OO.ui.Process process} will be cancelled. Windows
2992 * themselves are persistent and—rather than being torn down when closed—can be repopulated with the
2993 * pertinent data and reused.
2994 *
2995 * Over the lifecycle of a window, the window manager makes available three promises: `opening`,
2996 * `opened`, and `closing`, which represent the primary stages of the cycle:
2997 *
2998 * **Opening**: the opening stage begins when the window manager’s #openWindow or a window’s
2999 * {@link OO.ui.Window#open open} method is used, and the window manager begins to open the window.
3000 *
3001 * - an `opening` event is emitted with an `opening` promise
3002 * - the #getSetupDelay method is called and the returned value is used to time a pause in execution before
3003 * the window’s {@link OO.ui.Window#getSetupProcess getSetupProcess} method is called on the
3004 * window and its result executed
3005 * - a `setup` progress notification is emitted from the `opening` promise
3006 * - the #getReadyDelay method is called the returned value is used to time a pause in execution before
3007 * the window’s {@link OO.ui.Window#getReadyProcess getReadyProcess} method is called on the
3008 * window and its result executed
3009 * - a `ready` progress notification is emitted from the `opening` promise
3010 * - the `opening` promise is resolved with an `opened` promise
3011 *
3012 * **Opened**: the window is now open.
3013 *
3014 * **Closing**: the closing stage begins when the window manager's #closeWindow or the
3015 * window's {@link OO.ui.Window#close close} methods is used, and the window manager begins
3016 * to close the window.
3017 *
3018 * - the `opened` promise is resolved with `closing` promise and a `closing` event is emitted
3019 * - the #getHoldDelay method is called and the returned value is used to time a pause in execution before
3020 * the window's {@link OO.ui.Window#getHoldProcess getHoldProces} method is called on the
3021 * window and its result executed
3022 * - a `hold` progress notification is emitted from the `closing` promise
3023 * - the #getTeardownDelay() method is called and the returned value is used to time a pause in execution before
3024 * the window's {@link OO.ui.Window#getTeardownProcess getTeardownProcess} method is called on the
3025 * window and its result executed
3026 * - a `teardown` progress notification is emitted from the `closing` promise
3027 * - the `closing` promise is resolved. The window is now closed
3028 *
3029 * See the [OOjs UI documentation on MediaWiki][1] for more information.
3030 *
3031 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
3032 *
3033 * @class
3034 * @extends OO.ui.Element
3035 * @mixins OO.EventEmitter
3036 *
3037 * @constructor
3038 * @param {Object} [config] Configuration options
3039 * @cfg {OO.Factory} [factory] Window factory to use for automatic instantiation
3040 * Note that window classes that are instantiated with a factory must have
3041 * a {@link OO.ui.Dialog#static-name static name} property that specifies a symbolic name.
3042 * @cfg {boolean} [modal=true] Prevent interaction outside the dialog
3043 */
3044 OO.ui.WindowManager = function OoUiWindowManager( config ) {
3045 // Configuration initialization
3046 config = config || {};
3047
3048 // Parent constructor
3049 OO.ui.WindowManager.parent.call( this, config );
3050
3051 // Mixin constructors
3052 OO.EventEmitter.call( this );
3053
3054 // Properties
3055 this.factory = config.factory;
3056 this.modal = config.modal === undefined || !!config.modal;
3057 this.windows = {};
3058 this.opening = null;
3059 this.opened = null;
3060 this.closing = null;
3061 this.preparingToOpen = null;
3062 this.preparingToClose = null;
3063 this.currentWindow = null;
3064 this.globalEvents = false;
3065 this.$ariaHidden = null;
3066 this.onWindowResizeTimeout = null;
3067 this.onWindowResizeHandler = this.onWindowResize.bind( this );
3068 this.afterWindowResizeHandler = this.afterWindowResize.bind( this );
3069
3070 // Initialization
3071 this.$element
3072 .addClass( 'oo-ui-windowManager' )
3073 .toggleClass( 'oo-ui-windowManager-modal', this.modal );
3074 };
3075
3076 /* Setup */
3077
3078 OO.inheritClass( OO.ui.WindowManager, OO.ui.Element );
3079 OO.mixinClass( OO.ui.WindowManager, OO.EventEmitter );
3080
3081 /* Events */
3082
3083 /**
3084 * An 'opening' event is emitted when the window begins to be opened.
3085 *
3086 * @event opening
3087 * @param {OO.ui.Window} win Window that's being opened
3088 * @param {jQuery.Promise} opening An `opening` promise resolved with a value when the window is opened successfully.
3089 * When the `opening` promise is resolved, the first argument of the value is an 'opened' promise, the second argument
3090 * is the opening data. The `opening` promise emits `setup` and `ready` notifications when those processes are complete.
3091 * @param {Object} data Window opening data
3092 */
3093
3094 /**
3095 * A 'closing' event is emitted when the window begins to be closed.
3096 *
3097 * @event closing
3098 * @param {OO.ui.Window} win Window that's being closed
3099 * @param {jQuery.Promise} closing A `closing` promise is resolved with a value when the window
3100 * is closed successfully. The promise emits `hold` and `teardown` notifications when those
3101 * processes are complete. When the `closing` promise is resolved, the first argument of its value
3102 * is the closing data.
3103 * @param {Object} data Window closing data
3104 */
3105
3106 /**
3107 * A 'resize' event is emitted when a window is resized.
3108 *
3109 * @event resize
3110 * @param {OO.ui.Window} win Window that was resized
3111 */
3112
3113 /* Static Properties */
3114
3115 /**
3116 * Map of the symbolic name of each window size and its CSS properties.
3117 *
3118 * @static
3119 * @inheritable
3120 * @property {Object}
3121 */
3122 OO.ui.WindowManager.static.sizes = {
3123 small: {
3124 width: 300
3125 },
3126 medium: {
3127 width: 500
3128 },
3129 large: {
3130 width: 700
3131 },
3132 larger: {
3133 width: 900
3134 },
3135 full: {
3136 // These can be non-numeric because they are never used in calculations
3137 width: '100%',
3138 height: '100%'
3139 }
3140 };
3141
3142 /**
3143 * Symbolic name of the default window size.
3144 *
3145 * The default size is used if the window's requested size is not recognized.
3146 *
3147 * @static
3148 * @inheritable
3149 * @property {string}
3150 */
3151 OO.ui.WindowManager.static.defaultSize = 'medium';
3152
3153 /* Methods */
3154
3155 /**
3156 * Handle window resize events.
3157 *
3158 * @private
3159 * @param {jQuery.Event} e Window resize event
3160 */
3161 OO.ui.WindowManager.prototype.onWindowResize = function () {
3162 clearTimeout( this.onWindowResizeTimeout );
3163 this.onWindowResizeTimeout = setTimeout( this.afterWindowResizeHandler, 200 );
3164 };
3165
3166 /**
3167 * Handle window resize events.
3168 *
3169 * @private
3170 * @param {jQuery.Event} e Window resize event
3171 */
3172 OO.ui.WindowManager.prototype.afterWindowResize = function () {
3173 if ( this.currentWindow ) {
3174 this.updateWindowSize( this.currentWindow );
3175 }
3176 };
3177
3178 /**
3179 * Check if window is opening.
3180 *
3181 * @return {boolean} Window is opening
3182 */
3183 OO.ui.WindowManager.prototype.isOpening = function ( win ) {
3184 return win === this.currentWindow && !!this.opening && this.opening.state() === 'pending';
3185 };
3186
3187 /**
3188 * Check if window is closing.
3189 *
3190 * @return {boolean} Window is closing
3191 */
3192 OO.ui.WindowManager.prototype.isClosing = function ( win ) {
3193 return win === this.currentWindow && !!this.closing && this.closing.state() === 'pending';
3194 };
3195
3196 /**
3197 * Check if window is opened.
3198 *
3199 * @return {boolean} Window is opened
3200 */
3201 OO.ui.WindowManager.prototype.isOpened = function ( win ) {
3202 return win === this.currentWindow && !!this.opened && this.opened.state() === 'pending';
3203 };
3204
3205 /**
3206 * Check if a window is being managed.
3207 *
3208 * @param {OO.ui.Window} win Window to check
3209 * @return {boolean} Window is being managed
3210 */
3211 OO.ui.WindowManager.prototype.hasWindow = function ( win ) {
3212 var name;
3213
3214 for ( name in this.windows ) {
3215 if ( this.windows[ name ] === win ) {
3216 return true;
3217 }
3218 }
3219
3220 return false;
3221 };
3222
3223 /**
3224 * Get the number of milliseconds to wait after opening begins before executing the ‘setup’ process.
3225 *
3226 * @param {OO.ui.Window} win Window being opened
3227 * @param {Object} [data] Window opening data
3228 * @return {number} Milliseconds to wait
3229 */
3230 OO.ui.WindowManager.prototype.getSetupDelay = function () {
3231 return 0;
3232 };
3233
3234 /**
3235 * Get the number of milliseconds to wait after setup has finished before executing the ‘ready’ process.
3236 *
3237 * @param {OO.ui.Window} win Window being opened
3238 * @param {Object} [data] Window opening data
3239 * @return {number} Milliseconds to wait
3240 */
3241 OO.ui.WindowManager.prototype.getReadyDelay = function () {
3242 return 0;
3243 };
3244
3245 /**
3246 * Get the number of milliseconds to wait after closing has begun before executing the 'hold' process.
3247 *
3248 * @param {OO.ui.Window} win Window being closed
3249 * @param {Object} [data] Window closing data
3250 * @return {number} Milliseconds to wait
3251 */
3252 OO.ui.WindowManager.prototype.getHoldDelay = function () {
3253 return 0;
3254 };
3255
3256 /**
3257 * Get the number of milliseconds to wait after the ‘hold’ process has finished before
3258 * executing the ‘teardown’ process.
3259 *
3260 * @param {OO.ui.Window} win Window being closed
3261 * @param {Object} [data] Window closing data
3262 * @return {number} Milliseconds to wait
3263 */
3264 OO.ui.WindowManager.prototype.getTeardownDelay = function () {
3265 return this.modal ? 250 : 0;
3266 };
3267
3268 /**
3269 * Get a window by its symbolic name.
3270 *
3271 * If the window is not yet instantiated and its symbolic name is recognized by a factory, it will be
3272 * instantiated and added to the window manager automatically. Please see the [OOjs UI documentation on MediaWiki][3]
3273 * for more information about using factories.
3274 * [3]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
3275 *
3276 * @param {string} name Symbolic name of the window
3277 * @return {jQuery.Promise} Promise resolved with matching window, or rejected with an OO.ui.Error
3278 * @throws {Error} An error is thrown if the symbolic name is not recognized by the factory.
3279 * @throws {Error} An error is thrown if the named window is not recognized as a managed window.
3280 */
3281 OO.ui.WindowManager.prototype.getWindow = function ( name ) {
3282 var deferred = $.Deferred(),
3283 win = this.windows[ name ];
3284
3285 if ( !( win instanceof OO.ui.Window ) ) {
3286 if ( this.factory ) {
3287 if ( !this.factory.lookup( name ) ) {
3288 deferred.reject( new OO.ui.Error(
3289 'Cannot auto-instantiate window: symbolic name is unrecognized by the factory'
3290 ) );
3291 } else {
3292 win = this.factory.create( name );
3293 this.addWindows( [ win ] );
3294 deferred.resolve( win );
3295 }
3296 } else {
3297 deferred.reject( new OO.ui.Error(
3298 'Cannot get unmanaged window: symbolic name unrecognized as a managed window'
3299 ) );
3300 }
3301 } else {
3302 deferred.resolve( win );
3303 }
3304
3305 return deferred.promise();
3306 };
3307
3308 /**
3309 * Get current window.
3310 *
3311 * @return {OO.ui.Window|null} Currently opening/opened/closing window
3312 */
3313 OO.ui.WindowManager.prototype.getCurrentWindow = function () {
3314 return this.currentWindow;
3315 };
3316
3317 /**
3318 * Open a window.
3319 *
3320 * @param {OO.ui.Window|string} win Window object or symbolic name of window to open
3321 * @param {Object} [data] Window opening data
3322 * @return {jQuery.Promise} An `opening` promise resolved when the window is done opening.
3323 * See {@link #event-opening 'opening' event} for more information about `opening` promises.
3324 * @fires opening
3325 */
3326 OO.ui.WindowManager.prototype.openWindow = function ( win, data ) {
3327 var manager = this,
3328 opening = $.Deferred();
3329
3330 // Argument handling
3331 if ( typeof win === 'string' ) {
3332 return this.getWindow( win ).then( function ( win ) {
3333 return manager.openWindow( win, data );
3334 } );
3335 }
3336
3337 // Error handling
3338 if ( !this.hasWindow( win ) ) {
3339 opening.reject( new OO.ui.Error(
3340 'Cannot open window: window is not attached to manager'
3341 ) );
3342 } else if ( this.preparingToOpen || this.opening || this.opened ) {
3343 opening.reject( new OO.ui.Error(
3344 'Cannot open window: another window is opening or open'
3345 ) );
3346 }
3347
3348 // Window opening
3349 if ( opening.state() !== 'rejected' ) {
3350 // If a window is currently closing, wait for it to complete
3351 this.preparingToOpen = $.when( this.closing );
3352 // Ensure handlers get called after preparingToOpen is set
3353 this.preparingToOpen.done( function () {
3354 if ( manager.modal ) {
3355 manager.toggleGlobalEvents( true );
3356 manager.toggleAriaIsolation( true );
3357 }
3358 manager.currentWindow = win;
3359 manager.opening = opening;
3360 manager.preparingToOpen = null;
3361 manager.emit( 'opening', win, opening, data );
3362 setTimeout( function () {
3363 win.setup( data ).then( function () {
3364 manager.updateWindowSize( win );
3365 manager.opening.notify( { state: 'setup' } );
3366 setTimeout( function () {
3367 win.ready( data ).then( function () {
3368 manager.opening.notify( { state: 'ready' } );
3369 manager.opening = null;
3370 manager.opened = $.Deferred();
3371 opening.resolve( manager.opened.promise(), data );
3372 } );
3373 }, manager.getReadyDelay() );
3374 } );
3375 }, manager.getSetupDelay() );
3376 } );
3377 }
3378
3379 return opening.promise();
3380 };
3381
3382 /**
3383 * Close a window.
3384 *
3385 * @param {OO.ui.Window|string} win Window object or symbolic name of window to close
3386 * @param {Object} [data] Window closing data
3387 * @return {jQuery.Promise} A `closing` promise resolved when the window is done closing.
3388 * See {@link #event-closing 'closing' event} for more information about closing promises.
3389 * @throws {Error} An error is thrown if the window is not managed by the window manager.
3390 * @fires closing
3391 */
3392 OO.ui.WindowManager.prototype.closeWindow = function ( win, data ) {
3393 var manager = this,
3394 closing = $.Deferred(),
3395 opened;
3396
3397 // Argument handling
3398 if ( typeof win === 'string' ) {
3399 win = this.windows[ win ];
3400 } else if ( !this.hasWindow( win ) ) {
3401 win = null;
3402 }
3403
3404 // Error handling
3405 if ( !win ) {
3406 closing.reject( new OO.ui.Error(
3407 'Cannot close window: window is not attached to manager'
3408 ) );
3409 } else if ( win !== this.currentWindow ) {
3410 closing.reject( new OO.ui.Error(
3411 'Cannot close window: window already closed with different data'
3412 ) );
3413 } else if ( this.preparingToClose || this.closing ) {
3414 closing.reject( new OO.ui.Error(
3415 'Cannot close window: window already closing with different data'
3416 ) );
3417 }
3418
3419 // Window closing
3420 if ( closing.state() !== 'rejected' ) {
3421 // If the window is currently opening, close it when it's done
3422 this.preparingToClose = $.when( this.opening );
3423 // Ensure handlers get called after preparingToClose is set
3424 this.preparingToClose.done( function () {
3425 manager.closing = closing;
3426 manager.preparingToClose = null;
3427 manager.emit( 'closing', win, closing, data );
3428 opened = manager.opened;
3429 manager.opened = null;
3430 opened.resolve( closing.promise(), data );
3431 setTimeout( function () {
3432 win.hold( data ).then( function () {
3433 closing.notify( { state: 'hold' } );
3434 setTimeout( function () {
3435 win.teardown( data ).then( function () {
3436 closing.notify( { state: 'teardown' } );
3437 if ( manager.modal ) {
3438 manager.toggleGlobalEvents( false );
3439 manager.toggleAriaIsolation( false );
3440 }
3441 manager.closing = null;
3442 manager.currentWindow = null;
3443 closing.resolve( data );
3444 } );
3445 }, manager.getTeardownDelay() );
3446 } );
3447 }, manager.getHoldDelay() );
3448 } );
3449 }
3450
3451 return closing.promise();
3452 };
3453
3454 /**
3455 * Add windows to the window manager.
3456 *
3457 * Windows can be added by reference, symbolic name, or explicitly defined symbolic names.
3458 * See the [OOjs ui documentation on MediaWiki] [2] for examples.
3459 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
3460 *
3461 * @param {Object.<string,OO.ui.Window>|OO.ui.Window[]} windows An array of window objects specified
3462 * by reference, symbolic name, or explicitly defined symbolic names.
3463 * @throws {Error} An error is thrown if a window is added by symbolic name, but has neither an
3464 * explicit nor a statically configured symbolic name.
3465 */
3466 OO.ui.WindowManager.prototype.addWindows = function ( windows ) {
3467 var i, len, win, name, list;
3468
3469 if ( Array.isArray( windows ) ) {
3470 // Convert to map of windows by looking up symbolic names from static configuration
3471 list = {};
3472 for ( i = 0, len = windows.length; i < len; i++ ) {
3473 name = windows[ i ].constructor.static.name;
3474 if ( typeof name !== 'string' ) {
3475 throw new Error( 'Cannot add window' );
3476 }
3477 list[ name ] = windows[ i ];
3478 }
3479 } else if ( OO.isPlainObject( windows ) ) {
3480 list = windows;
3481 }
3482
3483 // Add windows
3484 for ( name in list ) {
3485 win = list[ name ];
3486 this.windows[ name ] = win.toggle( false );
3487 this.$element.append( win.$element );
3488 win.setManager( this );
3489 }
3490 };
3491
3492 /**
3493 * Remove the specified windows from the windows manager.
3494 *
3495 * Windows will be closed before they are removed. If you wish to remove all windows, you may wish to use
3496 * the #clearWindows method instead. If you no longer need the window manager and want to ensure that it no
3497 * longer listens to events, use the #destroy method.
3498 *
3499 * @param {string[]} names Symbolic names of windows to remove
3500 * @return {jQuery.Promise} Promise resolved when window is closed and removed
3501 * @throws {Error} An error is thrown if the named windows are not managed by the window manager.
3502 */
3503 OO.ui.WindowManager.prototype.removeWindows = function ( names ) {
3504 var i, len, win, name, cleanupWindow,
3505 manager = this,
3506 promises = [],
3507 cleanup = function ( name, win ) {
3508 delete manager.windows[ name ];
3509 win.$element.detach();
3510 };
3511
3512 for ( i = 0, len = names.length; i < len; i++ ) {
3513 name = names[ i ];
3514 win = this.windows[ name ];
3515 if ( !win ) {
3516 throw new Error( 'Cannot remove window' );
3517 }
3518 cleanupWindow = cleanup.bind( null, name, win );
3519 promises.push( this.closeWindow( name ).then( cleanupWindow, cleanupWindow ) );
3520 }
3521
3522 return $.when.apply( $, promises );
3523 };
3524
3525 /**
3526 * Remove all windows from the window manager.
3527 *
3528 * Windows will be closed before they are removed. Note that the window manager, though not in use, will still
3529 * listen to events. If the window manager will not be used again, you may wish to use the #destroy method instead.
3530 * To remove just a subset of windows, use the #removeWindows method.
3531 *
3532 * @return {jQuery.Promise} Promise resolved when all windows are closed and removed
3533 */
3534 OO.ui.WindowManager.prototype.clearWindows = function () {
3535 return this.removeWindows( Object.keys( this.windows ) );
3536 };
3537
3538 /**
3539 * Set dialog size. In general, this method should not be called directly.
3540 *
3541 * Fullscreen mode will be used if the dialog is too wide to fit in the screen.
3542 *
3543 * @chainable
3544 */
3545 OO.ui.WindowManager.prototype.updateWindowSize = function ( win ) {
3546 // Bypass for non-current, and thus invisible, windows
3547 if ( win !== this.currentWindow ) {
3548 return;
3549 }
3550
3551 var isFullscreen = win.getSize() === 'full';
3552
3553 this.$element.toggleClass( 'oo-ui-windowManager-fullscreen', isFullscreen );
3554 this.$element.toggleClass( 'oo-ui-windowManager-floating', !isFullscreen );
3555 win.setDimensions( win.getSizeProperties() );
3556
3557 this.emit( 'resize', win );
3558
3559 return this;
3560 };
3561
3562 /**
3563 * Bind or unbind global events for scrolling.
3564 *
3565 * @private
3566 * @param {boolean} [on] Bind global events
3567 * @chainable
3568 */
3569 OO.ui.WindowManager.prototype.toggleGlobalEvents = function ( on ) {
3570 on = on === undefined ? !!this.globalEvents : !!on;
3571
3572 var scrollWidth, bodyMargin,
3573 $body = $( this.getElementDocument().body ),
3574 // We could have multiple window managers open so only modify
3575 // the body css at the bottom of the stack
3576 stackDepth = $body.data( 'windowManagerGlobalEvents' ) || 0 ;
3577
3578 if ( on ) {
3579 if ( !this.globalEvents ) {
3580 $( this.getElementWindow() ).on( {
3581 // Start listening for top-level window dimension changes
3582 'orientationchange resize': this.onWindowResizeHandler
3583 } );
3584 if ( stackDepth === 0 ) {
3585 scrollWidth = window.innerWidth - document.documentElement.clientWidth;
3586 bodyMargin = parseFloat( $body.css( 'margin-right' ) ) || 0;
3587 $body.css( {
3588 overflow: 'hidden',
3589 'margin-right': bodyMargin + scrollWidth
3590 } );
3591 }
3592 stackDepth++;
3593 this.globalEvents = true;
3594 }
3595 } else if ( this.globalEvents ) {
3596 $( this.getElementWindow() ).off( {
3597 // Stop listening for top-level window dimension changes
3598 'orientationchange resize': this.onWindowResizeHandler
3599 } );
3600 stackDepth--;
3601 if ( stackDepth === 0 ) {
3602 $body.css( {
3603 overflow: '',
3604 'margin-right': ''
3605 } );
3606 }
3607 this.globalEvents = false;
3608 }
3609 $body.data( 'windowManagerGlobalEvents', stackDepth );
3610
3611 return this;
3612 };
3613
3614 /**
3615 * Toggle screen reader visibility of content other than the window manager.
3616 *
3617 * @private
3618 * @param {boolean} [isolate] Make only the window manager visible to screen readers
3619 * @chainable
3620 */
3621 OO.ui.WindowManager.prototype.toggleAriaIsolation = function ( isolate ) {
3622 isolate = isolate === undefined ? !this.$ariaHidden : !!isolate;
3623
3624 if ( isolate ) {
3625 if ( !this.$ariaHidden ) {
3626 // Hide everything other than the window manager from screen readers
3627 this.$ariaHidden = $( 'body' )
3628 .children()
3629 .not( this.$element.parentsUntil( 'body' ).last() )
3630 .attr( 'aria-hidden', '' );
3631 }
3632 } else if ( this.$ariaHidden ) {
3633 // Restore screen reader visibility
3634 this.$ariaHidden.removeAttr( 'aria-hidden' );
3635 this.$ariaHidden = null;
3636 }
3637
3638 return this;
3639 };
3640
3641 /**
3642 * Destroy the window manager.
3643 *
3644 * Destroying the window manager ensures that it will no longer listen to events. If you would like to
3645 * continue using the window manager, but wish to remove all windows from it, use the #clearWindows method
3646 * instead.
3647 */
3648 OO.ui.WindowManager.prototype.destroy = function () {
3649 this.toggleGlobalEvents( false );
3650 this.toggleAriaIsolation( false );
3651 this.clearWindows();
3652 this.$element.remove();
3653 };
3654
3655 /**
3656 * Errors contain a required message (either a string or jQuery selection) that is used to describe what went wrong
3657 * in a {@link OO.ui.Process process}. The error's #recoverable and #warning configurations are used to customize the
3658 * appearance and functionality of the error interface.
3659 *
3660 * The basic error interface contains a formatted error message as well as two buttons: 'Dismiss' and 'Try again' (i.e., the error
3661 * is 'recoverable' by default). If the error is not recoverable, the 'Try again' button will not be rendered and the widget
3662 * that initiated the failed process will be disabled.
3663 *
3664 * If the error is a warning, the error interface will include a 'Dismiss' and a 'Continue' button, which will try the
3665 * process again.
3666 *
3667 * For an example of error interfaces, please see the [OOjs UI documentation on MediaWiki][1].
3668 *
3669 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Processes_and_errors
3670 *
3671 * @class
3672 *
3673 * @constructor
3674 * @param {string|jQuery} message Description of error
3675 * @param {Object} [config] Configuration options
3676 * @cfg {boolean} [recoverable=true] Error is recoverable.
3677 * By default, errors are recoverable, and users can try the process again.
3678 * @cfg {boolean} [warning=false] Error is a warning.
3679 * If the error is a warning, the error interface will include a
3680 * 'Dismiss' and a 'Continue' button. It is the responsibility of the developer to ensure that the warning
3681 * is not triggered a second time if the user chooses to continue.
3682 */
3683 OO.ui.Error = function OoUiError( message, config ) {
3684 // Allow passing positional parameters inside the config object
3685 if ( OO.isPlainObject( message ) && config === undefined ) {
3686 config = message;
3687 message = config.message;
3688 }
3689
3690 // Configuration initialization
3691 config = config || {};
3692
3693 // Properties
3694 this.message = message instanceof jQuery ? message : String( message );
3695 this.recoverable = config.recoverable === undefined || !!config.recoverable;
3696 this.warning = !!config.warning;
3697 };
3698
3699 /* Setup */
3700
3701 OO.initClass( OO.ui.Error );
3702
3703 /* Methods */
3704
3705 /**
3706 * Check if the error is recoverable.
3707 *
3708 * If the error is recoverable, users are able to try the process again.
3709 *
3710 * @return {boolean} Error is recoverable
3711 */
3712 OO.ui.Error.prototype.isRecoverable = function () {
3713 return this.recoverable;
3714 };
3715
3716 /**
3717 * Check if the error is a warning.
3718 *
3719 * If the error is a warning, the error interface will include a 'Dismiss' and a 'Continue' button.
3720 *
3721 * @return {boolean} Error is warning
3722 */
3723 OO.ui.Error.prototype.isWarning = function () {
3724 return this.warning;
3725 };
3726
3727 /**
3728 * Get error message as DOM nodes.
3729 *
3730 * @return {jQuery} Error message in DOM nodes
3731 */
3732 OO.ui.Error.prototype.getMessage = function () {
3733 return this.message instanceof jQuery ?
3734 this.message.clone() :
3735 $( '<div>' ).text( this.message ).contents();
3736 };
3737
3738 /**
3739 * Get the error message text.
3740 *
3741 * @return {string} Error message
3742 */
3743 OO.ui.Error.prototype.getMessageText = function () {
3744 return this.message instanceof jQuery ? this.message.text() : this.message;
3745 };
3746
3747 /**
3748 * Wraps an HTML snippet for use with configuration values which default
3749 * to strings. This bypasses the default html-escaping done to string
3750 * values.
3751 *
3752 * @class
3753 *
3754 * @constructor
3755 * @param {string} [content] HTML content
3756 */
3757 OO.ui.HtmlSnippet = function OoUiHtmlSnippet( content ) {
3758 // Properties
3759 this.content = content;
3760 };
3761
3762 /* Setup */
3763
3764 OO.initClass( OO.ui.HtmlSnippet );
3765
3766 /* Methods */
3767
3768 /**
3769 * Render into HTML.
3770 *
3771 * @return {string} Unchanged HTML snippet.
3772 */
3773 OO.ui.HtmlSnippet.prototype.toString = function () {
3774 return this.content;
3775 };
3776
3777 /**
3778 * A Process is a list of steps that are called in sequence. The step can be a number, a jQuery promise,
3779 * or a function:
3780 *
3781 * - **number**: the process will wait for the specified number of milliseconds before proceeding.
3782 * - **promise**: the process will continue to the next step when the promise is successfully resolved
3783 * or stop if the promise is rejected.
3784 * - **function**: the process will execute the function. The process will stop if the function returns
3785 * either a boolean `false` or a promise that is rejected; if the function returns a number, the process
3786 * will wait for that number of milliseconds before proceeding.
3787 *
3788 * If the process fails, an {@link OO.ui.Error error} is generated. Depending on how the error is
3789 * configured, users can dismiss the error and try the process again, or not. If a process is stopped,
3790 * its remaining steps will not be performed.
3791 *
3792 * @class
3793 *
3794 * @constructor
3795 * @param {number|jQuery.Promise|Function} step Number of miliseconds to wait before proceeding, promise
3796 * that must be resolved before proceeding, or a function to execute. See #createStep for more information. see #createStep for more information
3797 * @param {Object} [context=null] Execution context of the function. The context is ignored if the step is
3798 * a number or promise.
3799 * @return {Object} Step object, with `callback` and `context` properties
3800 */
3801 OO.ui.Process = function ( step, context ) {
3802 // Properties
3803 this.steps = [];
3804
3805 // Initialization
3806 if ( step !== undefined ) {
3807 this.next( step, context );
3808 }
3809 };
3810
3811 /* Setup */
3812
3813 OO.initClass( OO.ui.Process );
3814
3815 /* Methods */
3816
3817 /**
3818 * Start the process.
3819 *
3820 * @return {jQuery.Promise} Promise that is resolved when all steps have successfully completed.
3821 * If any of the steps return a promise that is rejected or a boolean false, this promise is rejected
3822 * and any remaining steps are not performed.
3823 */
3824 OO.ui.Process.prototype.execute = function () {
3825 var i, len, promise;
3826
3827 /**
3828 * Continue execution.
3829 *
3830 * @ignore
3831 * @param {Array} step A function and the context it should be called in
3832 * @return {Function} Function that continues the process
3833 */
3834 function proceed( step ) {
3835 return function () {
3836 // Execute step in the correct context
3837 var deferred,
3838 result = step.callback.call( step.context );
3839
3840 if ( result === false ) {
3841 // Use rejected promise for boolean false results
3842 return $.Deferred().reject( [] ).promise();
3843 }
3844 if ( typeof result === 'number' ) {
3845 if ( result < 0 ) {
3846 throw new Error( 'Cannot go back in time: flux capacitor is out of service' );
3847 }
3848 // Use a delayed promise for numbers, expecting them to be in milliseconds
3849 deferred = $.Deferred();
3850 setTimeout( deferred.resolve, result );
3851 return deferred.promise();
3852 }
3853 if ( result instanceof OO.ui.Error ) {
3854 // Use rejected promise for error
3855 return $.Deferred().reject( [ result ] ).promise();
3856 }
3857 if ( Array.isArray( result ) && result.length && result[ 0 ] instanceof OO.ui.Error ) {
3858 // Use rejected promise for list of errors
3859 return $.Deferred().reject( result ).promise();
3860 }
3861 // Duck-type the object to see if it can produce a promise
3862 if ( result && $.isFunction( result.promise ) ) {
3863 // Use a promise generated from the result
3864 return result.promise();
3865 }
3866 // Use resolved promise for other results
3867 return $.Deferred().resolve().promise();
3868 };
3869 }
3870
3871 if ( this.steps.length ) {
3872 // Generate a chain reaction of promises
3873 promise = proceed( this.steps[ 0 ] )();
3874 for ( i = 1, len = this.steps.length; i < len; i++ ) {
3875 promise = promise.then( proceed( this.steps[ i ] ) );
3876 }
3877 } else {
3878 promise = $.Deferred().resolve().promise();
3879 }
3880
3881 return promise;
3882 };
3883
3884 /**
3885 * Create a process step.
3886 *
3887 * @private
3888 * @param {number|jQuery.Promise|Function} step
3889 *
3890 * - Number of milliseconds to wait before proceeding
3891 * - Promise that must be resolved before proceeding
3892 * - Function to execute
3893 * - If the function returns a boolean false the process will stop
3894 * - If the function returns a promise, the process will continue to the next
3895 * step when the promise is resolved or stop if the promise is rejected
3896 * - If the function returns a number, the process will wait for that number of
3897 * milliseconds before proceeding
3898 * @param {Object} [context=null] Execution context of the function. The context is
3899 * ignored if the step is a number or promise.
3900 * @return {Object} Step object, with `callback` and `context` properties
3901 */
3902 OO.ui.Process.prototype.createStep = function ( step, context ) {
3903 if ( typeof step === 'number' || $.isFunction( step.promise ) ) {
3904 return {
3905 callback: function () {
3906 return step;
3907 },
3908 context: null
3909 };
3910 }
3911 if ( $.isFunction( step ) ) {
3912 return {
3913 callback: step,
3914 context: context
3915 };
3916 }
3917 throw new Error( 'Cannot create process step: number, promise or function expected' );
3918 };
3919
3920 /**
3921 * Add step to the beginning of the process.
3922 *
3923 * @inheritdoc #createStep
3924 * @return {OO.ui.Process} this
3925 * @chainable
3926 */
3927 OO.ui.Process.prototype.first = function ( step, context ) {
3928 this.steps.unshift( this.createStep( step, context ) );
3929 return this;
3930 };
3931
3932 /**
3933 * Add step to the end of the process.
3934 *
3935 * @inheritdoc #createStep
3936 * @return {OO.ui.Process} this
3937 * @chainable
3938 */
3939 OO.ui.Process.prototype.next = function ( step, context ) {
3940 this.steps.push( this.createStep( step, context ) );
3941 return this;
3942 };
3943
3944 /**
3945 * A ToolFactory creates tools on demand. All tools ({@link OO.ui.Tool Tools}, {@link OO.ui.PopupTool PopupTools},
3946 * and {@link OO.ui.ToolGroupTool ToolGroupTools}) must be registered with a tool factory. Tools are
3947 * registered by their symbolic name. See {@link OO.ui.Toolbar toolbars} for an example.
3948 *
3949 * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki][1].
3950 *
3951 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
3952 *
3953 * @class
3954 * @extends OO.Factory
3955 * @constructor
3956 */
3957 OO.ui.ToolFactory = function OoUiToolFactory() {
3958 // Parent constructor
3959 OO.ui.ToolFactory.parent.call( this );
3960 };
3961
3962 /* Setup */
3963
3964 OO.inheritClass( OO.ui.ToolFactory, OO.Factory );
3965
3966 /* Methods */
3967
3968 /**
3969 * Get tools from the factory
3970 *
3971 * @param {Array} include Included tools
3972 * @param {Array} exclude Excluded tools
3973 * @param {Array} promote Promoted tools
3974 * @param {Array} demote Demoted tools
3975 * @return {string[]} List of tools
3976 */
3977 OO.ui.ToolFactory.prototype.getTools = function ( include, exclude, promote, demote ) {
3978 var i, len, included, promoted, demoted,
3979 auto = [],
3980 used = {};
3981
3982 // Collect included and not excluded tools
3983 included = OO.simpleArrayDifference( this.extract( include ), this.extract( exclude ) );
3984
3985 // Promotion
3986 promoted = this.extract( promote, used );
3987 demoted = this.extract( demote, used );
3988
3989 // Auto
3990 for ( i = 0, len = included.length; i < len; i++ ) {
3991 if ( !used[ included[ i ] ] ) {
3992 auto.push( included[ i ] );
3993 }
3994 }
3995
3996 return promoted.concat( auto ).concat( demoted );
3997 };
3998
3999 /**
4000 * Get a flat list of names from a list of names or groups.
4001 *
4002 * Tools can be specified in the following ways:
4003 *
4004 * - A specific tool: `{ name: 'tool-name' }` or `'tool-name'`
4005 * - All tools in a group: `{ group: 'group-name' }`
4006 * - All tools: `'*'`
4007 *
4008 * @private
4009 * @param {Array|string} collection List of tools
4010 * @param {Object} [used] Object with names that should be skipped as properties; extracted
4011 * names will be added as properties
4012 * @return {string[]} List of extracted names
4013 */
4014 OO.ui.ToolFactory.prototype.extract = function ( collection, used ) {
4015 var i, len, item, name, tool,
4016 names = [];
4017
4018 if ( collection === '*' ) {
4019 for ( name in this.registry ) {
4020 tool = this.registry[ name ];
4021 if (
4022 // Only add tools by group name when auto-add is enabled
4023 tool.static.autoAddToCatchall &&
4024 // Exclude already used tools
4025 ( !used || !used[ name ] )
4026 ) {
4027 names.push( name );
4028 if ( used ) {
4029 used[ name ] = true;
4030 }
4031 }
4032 }
4033 } else if ( Array.isArray( collection ) ) {
4034 for ( i = 0, len = collection.length; i < len; i++ ) {
4035 item = collection[ i ];
4036 // Allow plain strings as shorthand for named tools
4037 if ( typeof item === 'string' ) {
4038 item = { name: item };
4039 }
4040 if ( OO.isPlainObject( item ) ) {
4041 if ( item.group ) {
4042 for ( name in this.registry ) {
4043 tool = this.registry[ name ];
4044 if (
4045 // Include tools with matching group
4046 tool.static.group === item.group &&
4047 // Only add tools by group name when auto-add is enabled
4048 tool.static.autoAddToGroup &&
4049 // Exclude already used tools
4050 ( !used || !used[ name ] )
4051 ) {
4052 names.push( name );
4053 if ( used ) {
4054 used[ name ] = true;
4055 }
4056 }
4057 }
4058 // Include tools with matching name and exclude already used tools
4059 } else if ( item.name && ( !used || !used[ item.name ] ) ) {
4060 names.push( item.name );
4061 if ( used ) {
4062 used[ item.name ] = true;
4063 }
4064 }
4065 }
4066 }
4067 }
4068 return names;
4069 };
4070
4071 /**
4072 * ToolGroupFactories create {@link OO.ui.ToolGroup toolgroups} on demand. The toolgroup classes must
4073 * specify a symbolic name and be registered with the factory. The following classes are registered by
4074 * default:
4075 *
4076 * - {@link OO.ui.BarToolGroup BarToolGroups} (‘bar’)
4077 * - {@link OO.ui.MenuToolGroup MenuToolGroups} (‘menu’)
4078 * - {@link OO.ui.ListToolGroup ListToolGroups} (‘list’)
4079 *
4080 * See {@link OO.ui.Toolbar toolbars} for an example.
4081 *
4082 * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki][1].
4083 *
4084 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
4085 * @class
4086 * @extends OO.Factory
4087 * @constructor
4088 */
4089 OO.ui.ToolGroupFactory = function OoUiToolGroupFactory() {
4090 // Parent constructor
4091 OO.Factory.call( this );
4092
4093 var i, l,
4094 defaultClasses = this.constructor.static.getDefaultClasses();
4095
4096 // Register default toolgroups
4097 for ( i = 0, l = defaultClasses.length; i < l; i++ ) {
4098 this.register( defaultClasses[ i ] );
4099 }
4100 };
4101
4102 /* Setup */
4103
4104 OO.inheritClass( OO.ui.ToolGroupFactory, OO.Factory );
4105
4106 /* Static Methods */
4107
4108 /**
4109 * Get a default set of classes to be registered on construction.
4110 *
4111 * @return {Function[]} Default classes
4112 */
4113 OO.ui.ToolGroupFactory.static.getDefaultClasses = function () {
4114 return [
4115 OO.ui.BarToolGroup,
4116 OO.ui.ListToolGroup,
4117 OO.ui.MenuToolGroup
4118 ];
4119 };
4120
4121 /**
4122 * Theme logic.
4123 *
4124 * @abstract
4125 * @class
4126 *
4127 * @constructor
4128 * @param {Object} [config] Configuration options
4129 */
4130 OO.ui.Theme = function OoUiTheme( config ) {
4131 // Configuration initialization
4132 config = config || {};
4133 };
4134
4135 /* Setup */
4136
4137 OO.initClass( OO.ui.Theme );
4138
4139 /* Methods */
4140
4141 /**
4142 * Get a list of classes to be applied to a widget.
4143 *
4144 * The 'on' and 'off' lists combined MUST contain keys for all classes the theme adds or removes,
4145 * otherwise state transitions will not work properly.
4146 *
4147 * @param {OO.ui.Element} element Element for which to get classes
4148 * @return {Object.<string,string[]>} Categorized class names with `on` and `off` lists
4149 */
4150 OO.ui.Theme.prototype.getElementClasses = function ( /* element */ ) {
4151 return { on: [], off: [] };
4152 };
4153
4154 /**
4155 * Update CSS classes provided by the theme.
4156 *
4157 * For elements with theme logic hooks, this should be called any time there's a state change.
4158 *
4159 * @param {OO.ui.Element} element Element for which to update classes
4160 * @return {Object.<string,string[]>} Categorized class names with `on` and `off` lists
4161 */
4162 OO.ui.Theme.prototype.updateElementClasses = function ( element ) {
4163 var classes = this.getElementClasses( element );
4164
4165 element.$element
4166 .removeClass( classes.off.join( ' ' ) )
4167 .addClass( classes.on.join( ' ' ) );
4168 };
4169
4170 /**
4171 * The TabIndexedElement class is an attribute mixin used to add additional functionality to an
4172 * element created by another class. The mixin provides a ‘tabIndex’ property, which specifies the
4173 * order in which users will navigate through the focusable elements via the "tab" key.
4174 *
4175 * @example
4176 * // TabIndexedElement is mixed into the ButtonWidget class
4177 * // to provide a tabIndex property.
4178 * var button1 = new OO.ui.ButtonWidget( {
4179 * label: 'fourth',
4180 * tabIndex: 4
4181 * } );
4182 * var button2 = new OO.ui.ButtonWidget( {
4183 * label: 'second',
4184 * tabIndex: 2
4185 * } );
4186 * var button3 = new OO.ui.ButtonWidget( {
4187 * label: 'third',
4188 * tabIndex: 3
4189 * } );
4190 * var button4 = new OO.ui.ButtonWidget( {
4191 * label: 'first',
4192 * tabIndex: 1
4193 * } );
4194 * $( 'body' ).append( button1.$element, button2.$element, button3.$element, button4.$element );
4195 *
4196 * @abstract
4197 * @class
4198 *
4199 * @constructor
4200 * @param {Object} [config] Configuration options
4201 * @cfg {jQuery} [$tabIndexed] The element that should use the tabindex functionality. By default,
4202 * the functionality is applied to the element created by the class ($element). If a different element is specified, the tabindex
4203 * functionality will be applied to it instead.
4204 * @cfg {number|null} [tabIndex=0] Number that specifies the element’s position in the tab-navigation
4205 * order (e.g., 1 for the first focusable element). Use 0 to use the default navigation order; use -1
4206 * to remove the element from the tab-navigation flow.
4207 */
4208 OO.ui.mixin.TabIndexedElement = function OoUiMixinTabIndexedElement( config ) {
4209 // Configuration initialization
4210 config = $.extend( { tabIndex: 0 }, config );
4211
4212 // Properties
4213 this.$tabIndexed = null;
4214 this.tabIndex = null;
4215
4216 // Events
4217 this.connect( this, { disable: 'onTabIndexedElementDisable' } );
4218
4219 // Initialization
4220 this.setTabIndex( config.tabIndex );
4221 this.setTabIndexedElement( config.$tabIndexed || this.$element );
4222 };
4223
4224 /* Setup */
4225
4226 OO.initClass( OO.ui.mixin.TabIndexedElement );
4227
4228 /* Methods */
4229
4230 /**
4231 * Set the element that should use the tabindex functionality.
4232 *
4233 * This method is used to retarget a tabindex mixin so that its functionality applies
4234 * to the specified element. If an element is currently using the functionality, the mixin’s
4235 * effect on that element is removed before the new element is set up.
4236 *
4237 * @param {jQuery} $tabIndexed Element that should use the tabindex functionality
4238 * @chainable
4239 */
4240 OO.ui.mixin.TabIndexedElement.prototype.setTabIndexedElement = function ( $tabIndexed ) {
4241 var tabIndex = this.tabIndex;
4242 // Remove attributes from old $tabIndexed
4243 this.setTabIndex( null );
4244 // Force update of new $tabIndexed
4245 this.$tabIndexed = $tabIndexed;
4246 this.tabIndex = tabIndex;
4247 return this.updateTabIndex();
4248 };
4249
4250 /**
4251 * Set the value of the tabindex.
4252 *
4253 * @param {number|null} tabIndex Tabindex value, or `null` for no tabindex
4254 * @chainable
4255 */
4256 OO.ui.mixin.TabIndexedElement.prototype.setTabIndex = function ( tabIndex ) {
4257 tabIndex = typeof tabIndex === 'number' ? tabIndex : null;
4258
4259 if ( this.tabIndex !== tabIndex ) {
4260 this.tabIndex = tabIndex;
4261 this.updateTabIndex();
4262 }
4263
4264 return this;
4265 };
4266
4267 /**
4268 * Update the `tabindex` attribute, in case of changes to tab index or
4269 * disabled state.
4270 *
4271 * @private
4272 * @chainable
4273 */
4274 OO.ui.mixin.TabIndexedElement.prototype.updateTabIndex = function () {
4275 if ( this.$tabIndexed ) {
4276 if ( this.tabIndex !== null ) {
4277 // Do not index over disabled elements
4278 this.$tabIndexed.attr( {
4279 tabindex: this.isDisabled() ? -1 : this.tabIndex,
4280 // ChromeVox and NVDA do not seem to inherit this from parent elements
4281 'aria-disabled': this.isDisabled().toString()
4282 } );
4283 } else {
4284 this.$tabIndexed.removeAttr( 'tabindex aria-disabled' );
4285 }
4286 }
4287 return this;
4288 };
4289
4290 /**
4291 * Handle disable events.
4292 *
4293 * @private
4294 * @param {boolean} disabled Element is disabled
4295 */
4296 OO.ui.mixin.TabIndexedElement.prototype.onTabIndexedElementDisable = function () {
4297 this.updateTabIndex();
4298 };
4299
4300 /**
4301 * Get the value of the tabindex.
4302 *
4303 * @return {number|null} Tabindex value
4304 */
4305 OO.ui.mixin.TabIndexedElement.prototype.getTabIndex = function () {
4306 return this.tabIndex;
4307 };
4308
4309 /**
4310 * ButtonElement is often mixed into other classes to generate a button, which is a clickable
4311 * interface element that can be configured with access keys for accessibility.
4312 * See the [OOjs UI documentation on MediaWiki] [1] for examples.
4313 *
4314 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#Buttons
4315 * @abstract
4316 * @class
4317 *
4318 * @constructor
4319 * @param {Object} [config] Configuration options
4320 * @cfg {jQuery} [$button] The button element created by the class.
4321 * If this configuration is omitted, the button element will use a generated `<a>`.
4322 * @cfg {boolean} [framed=true] Render the button with a frame
4323 * @cfg {string} [accessKey] Button's access key
4324 */
4325 OO.ui.mixin.ButtonElement = function OoUiMixinButtonElement( config ) {
4326 // Configuration initialization
4327 config = config || {};
4328
4329 // Properties
4330 this.$button = null;
4331 this.framed = null;
4332 this.accessKey = null;
4333 this.active = false;
4334 this.onMouseUpHandler = this.onMouseUp.bind( this );
4335 this.onMouseDownHandler = this.onMouseDown.bind( this );
4336 this.onKeyDownHandler = this.onKeyDown.bind( this );
4337 this.onKeyUpHandler = this.onKeyUp.bind( this );
4338 this.onClickHandler = this.onClick.bind( this );
4339 this.onKeyPressHandler = this.onKeyPress.bind( this );
4340
4341 // Initialization
4342 this.$element.addClass( 'oo-ui-buttonElement' );
4343 this.toggleFramed( config.framed === undefined || config.framed );
4344 this.setAccessKey( config.accessKey );
4345 this.setButtonElement( config.$button || $( '<a>' ) );
4346 };
4347
4348 /* Setup */
4349
4350 OO.initClass( OO.ui.mixin.ButtonElement );
4351
4352 /* Static Properties */
4353
4354 /**
4355 * Cancel mouse down events.
4356 *
4357 * This property is usually set to `true` to prevent the focus from changing when the button is clicked.
4358 * Classes such as {@link OO.ui.mixin.DraggableElement DraggableElement} and {@link OO.ui.ButtonOptionWidget ButtonOptionWidget}
4359 * use a value of `false` so that dragging behavior is possible and mousedown events can be handled by a
4360 * parent widget.
4361 *
4362 * @static
4363 * @inheritable
4364 * @property {boolean}
4365 */
4366 OO.ui.mixin.ButtonElement.static.cancelButtonMouseDownEvents = true;
4367
4368 /* Events */
4369
4370 /**
4371 * A 'click' event is emitted when the button element is clicked.
4372 *
4373 * @event click
4374 */
4375
4376 /* Methods */
4377
4378 /**
4379 * Set the button element.
4380 *
4381 * This method is used to retarget a button mixin so that its functionality applies to
4382 * the specified button element instead of the one created by the class. If a button element
4383 * is already set, the method will remove the mixin’s effect on that element.
4384 *
4385 * @param {jQuery} $button Element to use as button
4386 */
4387 OO.ui.mixin.ButtonElement.prototype.setButtonElement = function ( $button ) {
4388 if ( this.$button ) {
4389 this.$button
4390 .removeClass( 'oo-ui-buttonElement-button' )
4391 .removeAttr( 'role accesskey' )
4392 .off( {
4393 mousedown: this.onMouseDownHandler,
4394 keydown: this.onKeyDownHandler,
4395 click: this.onClickHandler,
4396 keypress: this.onKeyPressHandler
4397 } );
4398 }
4399
4400 this.$button = $button
4401 .addClass( 'oo-ui-buttonElement-button' )
4402 .attr( { role: 'button', accesskey: this.accessKey } )
4403 .on( {
4404 mousedown: this.onMouseDownHandler,
4405 keydown: this.onKeyDownHandler,
4406 click: this.onClickHandler,
4407 keypress: this.onKeyPressHandler
4408 } );
4409 };
4410
4411 /**
4412 * Handles mouse down events.
4413 *
4414 * @protected
4415 * @param {jQuery.Event} e Mouse down event
4416 */
4417 OO.ui.mixin.ButtonElement.prototype.onMouseDown = function ( e ) {
4418 if ( this.isDisabled() || e.which !== 1 ) {
4419 return;
4420 }
4421 this.$element.addClass( 'oo-ui-buttonElement-pressed' );
4422 // Run the mouseup handler no matter where the mouse is when the button is let go, so we can
4423 // reliably remove the pressed class
4424 OO.ui.addCaptureEventListener( this.getElementDocument(), 'mouseup', this.onMouseUpHandler );
4425 // Prevent change of focus unless specifically configured otherwise
4426 if ( this.constructor.static.cancelButtonMouseDownEvents ) {
4427 return false;
4428 }
4429 };
4430
4431 /**
4432 * Handles mouse up events.
4433 *
4434 * @protected
4435 * @param {jQuery.Event} e Mouse up event
4436 */
4437 OO.ui.mixin.ButtonElement.prototype.onMouseUp = function ( e ) {
4438 if ( this.isDisabled() || e.which !== 1 ) {
4439 return;
4440 }
4441 this.$element.removeClass( 'oo-ui-buttonElement-pressed' );
4442 // Stop listening for mouseup, since we only needed this once
4443 OO.ui.removeCaptureEventListener( this.getElementDocument(), 'mouseup', this.onMouseUpHandler );
4444 };
4445
4446 /**
4447 * Handles mouse click events.
4448 *
4449 * @protected
4450 * @param {jQuery.Event} e Mouse click event
4451 * @fires click
4452 */
4453 OO.ui.mixin.ButtonElement.prototype.onClick = function ( e ) {
4454 if ( !this.isDisabled() && e.which === 1 ) {
4455 if ( this.emit( 'click' ) ) {
4456 return false;
4457 }
4458 }
4459 };
4460
4461 /**
4462 * Handles key down events.
4463 *
4464 * @protected
4465 * @param {jQuery.Event} e Key down event
4466 */
4467 OO.ui.mixin.ButtonElement.prototype.onKeyDown = function ( e ) {
4468 if ( this.isDisabled() || ( e.which !== OO.ui.Keys.SPACE && e.which !== OO.ui.Keys.ENTER ) ) {
4469 return;
4470 }
4471 this.$element.addClass( 'oo-ui-buttonElement-pressed' );
4472 // Run the keyup handler no matter where the key is when the button is let go, so we can
4473 // reliably remove the pressed class
4474 OO.ui.addCaptureEventListener( this.getElementDocument(), 'keyup', this.onKeyUpHandler );
4475 };
4476
4477 /**
4478 * Handles key up events.
4479 *
4480 * @protected
4481 * @param {jQuery.Event} e Key up event
4482 */
4483 OO.ui.mixin.ButtonElement.prototype.onKeyUp = function ( e ) {
4484 if ( this.isDisabled() || ( e.which !== OO.ui.Keys.SPACE && e.which !== OO.ui.Keys.ENTER ) ) {
4485 return;
4486 }
4487 this.$element.removeClass( 'oo-ui-buttonElement-pressed' );
4488 // Stop listening for keyup, since we only needed this once
4489 OO.ui.removeCaptureEventListener( this.getElementDocument(), 'keyup', this.onKeyUpHandler );
4490 };
4491
4492 /**
4493 * Handles key press events.
4494 *
4495 * @protected
4496 * @param {jQuery.Event} e Key press event
4497 * @fires click
4498 */
4499 OO.ui.mixin.ButtonElement.prototype.onKeyPress = function ( e ) {
4500 if ( !this.isDisabled() && ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER ) ) {
4501 if ( this.emit( 'click' ) ) {
4502 return false;
4503 }
4504 }
4505 };
4506
4507 /**
4508 * Check if button has a frame.
4509 *
4510 * @return {boolean} Button is framed
4511 */
4512 OO.ui.mixin.ButtonElement.prototype.isFramed = function () {
4513 return this.framed;
4514 };
4515
4516 /**
4517 * Render the button with or without a frame. Omit the `framed` parameter to toggle the button frame on and off.
4518 *
4519 * @param {boolean} [framed] Make button framed, omit to toggle
4520 * @chainable
4521 */
4522 OO.ui.mixin.ButtonElement.prototype.toggleFramed = function ( framed ) {
4523 framed = framed === undefined ? !this.framed : !!framed;
4524 if ( framed !== this.framed ) {
4525 this.framed = framed;
4526 this.$element
4527 .toggleClass( 'oo-ui-buttonElement-frameless', !framed )
4528 .toggleClass( 'oo-ui-buttonElement-framed', framed );
4529 this.updateThemeClasses();
4530 }
4531
4532 return this;
4533 };
4534
4535 /**
4536 * Set the button's access key.
4537 *
4538 * @param {string} accessKey Button's access key, use empty string to remove
4539 * @chainable
4540 */
4541 OO.ui.mixin.ButtonElement.prototype.setAccessKey = function ( accessKey ) {
4542 accessKey = typeof accessKey === 'string' && accessKey.length ? accessKey : null;
4543
4544 if ( this.accessKey !== accessKey ) {
4545 if ( this.$button ) {
4546 if ( accessKey !== null ) {
4547 this.$button.attr( 'accesskey', accessKey );
4548 } else {
4549 this.$button.removeAttr( 'accesskey' );
4550 }
4551 }
4552 this.accessKey = accessKey;
4553 }
4554
4555 return this;
4556 };
4557
4558 /**
4559 * Set the button to its 'active' state.
4560 *
4561 * The active state occurs when a {@link OO.ui.ButtonOptionWidget ButtonOptionWidget} or
4562 * a {@link OO.ui.ToggleButtonWidget ToggleButtonWidget} is pressed. This method does nothing
4563 * for other button types.
4564 *
4565 * @param {boolean} [value] Make button active
4566 * @chainable
4567 */
4568 OO.ui.mixin.ButtonElement.prototype.setActive = function ( value ) {
4569 this.$element.toggleClass( 'oo-ui-buttonElement-active', !!value );
4570 return this;
4571 };
4572
4573 /**
4574 * Any OOjs UI widget that contains other widgets (such as {@link OO.ui.ButtonWidget buttons} or
4575 * {@link OO.ui.OptionWidget options}) mixes in GroupElement. Adding, removing, and clearing
4576 * items from the group is done through the interface the class provides.
4577 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
4578 *
4579 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Groups
4580 *
4581 * @abstract
4582 * @class
4583 *
4584 * @constructor
4585 * @param {Object} [config] Configuration options
4586 * @cfg {jQuery} [$group] The container element created by the class. If this configuration
4587 * is omitted, the group element will use a generated `<div>`.
4588 */
4589 OO.ui.mixin.GroupElement = function OoUiMixinGroupElement( config ) {
4590 // Configuration initialization
4591 config = config || {};
4592
4593 // Properties
4594 this.$group = null;
4595 this.items = [];
4596 this.aggregateItemEvents = {};
4597
4598 // Initialization
4599 this.setGroupElement( config.$group || $( '<div>' ) );
4600 };
4601
4602 /* Methods */
4603
4604 /**
4605 * Set the group element.
4606 *
4607 * If an element is already set, items will be moved to the new element.
4608 *
4609 * @param {jQuery} $group Element to use as group
4610 */
4611 OO.ui.mixin.GroupElement.prototype.setGroupElement = function ( $group ) {
4612 var i, len;
4613
4614 this.$group = $group;
4615 for ( i = 0, len = this.items.length; i < len; i++ ) {
4616 this.$group.append( this.items[ i ].$element );
4617 }
4618 };
4619
4620 /**
4621 * Check if a group contains no items.
4622 *
4623 * @return {boolean} Group is empty
4624 */
4625 OO.ui.mixin.GroupElement.prototype.isEmpty = function () {
4626 return !this.items.length;
4627 };
4628
4629 /**
4630 * Get all items in the group.
4631 *
4632 * The method returns an array of item references (e.g., [button1, button2, button3]) and is useful
4633 * when synchronizing groups of items, or whenever the references are required (e.g., when removing items
4634 * from a group).
4635 *
4636 * @return {OO.ui.Element[]} An array of items.
4637 */
4638 OO.ui.mixin.GroupElement.prototype.getItems = function () {
4639 return this.items.slice( 0 );
4640 };
4641
4642 /**
4643 * Get an item by its data.
4644 *
4645 * Only the first item with matching data will be returned. To return all matching items,
4646 * use the #getItemsFromData method.
4647 *
4648 * @param {Object} data Item data to search for
4649 * @return {OO.ui.Element|null} Item with equivalent data, `null` if none exists
4650 */
4651 OO.ui.mixin.GroupElement.prototype.getItemFromData = function ( data ) {
4652 var i, len, item,
4653 hash = OO.getHash( data );
4654
4655 for ( i = 0, len = this.items.length; i < len; i++ ) {
4656 item = this.items[ i ];
4657 if ( hash === OO.getHash( item.getData() ) ) {
4658 return item;
4659 }
4660 }
4661
4662 return null;
4663 };
4664
4665 /**
4666 * Get items by their data.
4667 *
4668 * All items with matching data will be returned. To return only the first match, use the #getItemFromData method instead.
4669 *
4670 * @param {Object} data Item data to search for
4671 * @return {OO.ui.Element[]} Items with equivalent data
4672 */
4673 OO.ui.mixin.GroupElement.prototype.getItemsFromData = function ( data ) {
4674 var i, len, item,
4675 hash = OO.getHash( data ),
4676 items = [];
4677
4678 for ( i = 0, len = this.items.length; i < len; i++ ) {
4679 item = this.items[ i ];
4680 if ( hash === OO.getHash( item.getData() ) ) {
4681 items.push( item );
4682 }
4683 }
4684
4685 return items;
4686 };
4687
4688 /**
4689 * Aggregate the events emitted by the group.
4690 *
4691 * When events are aggregated, the group will listen to all contained items for the event,
4692 * and then emit the event under a new name. The new event will contain an additional leading
4693 * parameter containing the item that emitted the original event. Other arguments emitted from
4694 * the original event are passed through.
4695 *
4696 * @param {Object.<string,string|null>} events An object keyed by the name of the event that should be
4697 * aggregated (e.g., ‘click’) and the value of the new name to use (e.g., ‘groupClick’).
4698 * A `null` value will remove aggregated events.
4699
4700 * @throws {Error} An error is thrown if aggregation already exists.
4701 */
4702 OO.ui.mixin.GroupElement.prototype.aggregate = function ( events ) {
4703 var i, len, item, add, remove, itemEvent, groupEvent;
4704
4705 for ( itemEvent in events ) {
4706 groupEvent = events[ itemEvent ];
4707
4708 // Remove existing aggregated event
4709 if ( Object.prototype.hasOwnProperty.call( this.aggregateItemEvents, itemEvent ) ) {
4710 // Don't allow duplicate aggregations
4711 if ( groupEvent ) {
4712 throw new Error( 'Duplicate item event aggregation for ' + itemEvent );
4713 }
4714 // Remove event aggregation from existing items
4715 for ( i = 0, len = this.items.length; i < len; i++ ) {
4716 item = this.items[ i ];
4717 if ( item.connect && item.disconnect ) {
4718 remove = {};
4719 remove[ itemEvent ] = [ 'emit', this.aggregateItemEvents[itemEvent], item ];
4720 item.disconnect( this, remove );
4721 }
4722 }
4723 // Prevent future items from aggregating event
4724 delete this.aggregateItemEvents[ itemEvent ];
4725 }
4726
4727 // Add new aggregate event
4728 if ( groupEvent ) {
4729 // Make future items aggregate event
4730 this.aggregateItemEvents[ itemEvent ] = groupEvent;
4731 // Add event aggregation to existing items
4732 for ( i = 0, len = this.items.length; i < len; i++ ) {
4733 item = this.items[ i ];
4734 if ( item.connect && item.disconnect ) {
4735 add = {};
4736 add[ itemEvent ] = [ 'emit', groupEvent, item ];
4737 item.connect( this, add );
4738 }
4739 }
4740 }
4741 }
4742 };
4743
4744 /**
4745 * Add items to the group.
4746 *
4747 * Items will be added to the end of the group array unless the optional `index` parameter specifies
4748 * a different insertion point. Adding an existing item will move it to the end of the array or the point specified by the `index`.
4749 *
4750 * @param {OO.ui.Element[]} items An array of items to add to the group
4751 * @param {number} [index] Index of the insertion point
4752 * @chainable
4753 */
4754 OO.ui.mixin.GroupElement.prototype.addItems = function ( items, index ) {
4755 var i, len, item, event, events, currentIndex,
4756 itemElements = [];
4757
4758 for ( i = 0, len = items.length; i < len; i++ ) {
4759 item = items[ i ];
4760
4761 // Check if item exists then remove it first, effectively "moving" it
4762 currentIndex = $.inArray( item, this.items );
4763 if ( currentIndex >= 0 ) {
4764 this.removeItems( [ item ] );
4765 // Adjust index to compensate for removal
4766 if ( currentIndex < index ) {
4767 index--;
4768 }
4769 }
4770 // Add the item
4771 if ( item.connect && item.disconnect && !$.isEmptyObject( this.aggregateItemEvents ) ) {
4772 events = {};
4773 for ( event in this.aggregateItemEvents ) {
4774 events[ event ] = [ 'emit', this.aggregateItemEvents[ event ], item ];
4775 }
4776 item.connect( this, events );
4777 }
4778 item.setElementGroup( this );
4779 itemElements.push( item.$element.get( 0 ) );
4780 }
4781
4782 if ( index === undefined || index < 0 || index >= this.items.length ) {
4783 this.$group.append( itemElements );
4784 this.items.push.apply( this.items, items );
4785 } else if ( index === 0 ) {
4786 this.$group.prepend( itemElements );
4787 this.items.unshift.apply( this.items, items );
4788 } else {
4789 this.items[ index ].$element.before( itemElements );
4790 this.items.splice.apply( this.items, [ index, 0 ].concat( items ) );
4791 }
4792
4793 return this;
4794 };
4795
4796 /**
4797 * Remove the specified items from a group.
4798 *
4799 * Removed items are detached (not removed) from the DOM so that they may be reused.
4800 * To remove all items from a group, you may wish to use the #clearItems method instead.
4801 *
4802 * @param {OO.ui.Element[]} items An array of items to remove
4803 * @chainable
4804 */
4805 OO.ui.mixin.GroupElement.prototype.removeItems = function ( items ) {
4806 var i, len, item, index, remove, itemEvent;
4807
4808 // Remove specific items
4809 for ( i = 0, len = items.length; i < len; i++ ) {
4810 item = items[ i ];
4811 index = $.inArray( item, this.items );
4812 if ( index !== -1 ) {
4813 if (
4814 item.connect && item.disconnect &&
4815 !$.isEmptyObject( this.aggregateItemEvents )
4816 ) {
4817 remove = {};
4818 if ( Object.prototype.hasOwnProperty.call( this.aggregateItemEvents, itemEvent ) ) {
4819 remove[ itemEvent ] = [ 'emit', this.aggregateItemEvents[ itemEvent ], item ];
4820 }
4821 item.disconnect( this, remove );
4822 }
4823 item.setElementGroup( null );
4824 this.items.splice( index, 1 );
4825 item.$element.detach();
4826 }
4827 }
4828
4829 return this;
4830 };
4831
4832 /**
4833 * Clear all items from the group.
4834 *
4835 * Cleared items are detached from the DOM, not removed, so that they may be reused.
4836 * To remove only a subset of items from a group, use the #removeItems method.
4837 *
4838 * @chainable
4839 */
4840 OO.ui.mixin.GroupElement.prototype.clearItems = function () {
4841 var i, len, item, remove, itemEvent;
4842
4843 // Remove all items
4844 for ( i = 0, len = this.items.length; i < len; i++ ) {
4845 item = this.items[ i ];
4846 if (
4847 item.connect && item.disconnect &&
4848 !$.isEmptyObject( this.aggregateItemEvents )
4849 ) {
4850 remove = {};
4851 if ( Object.prototype.hasOwnProperty.call( this.aggregateItemEvents, itemEvent ) ) {
4852 remove[ itemEvent ] = [ 'emit', this.aggregateItemEvents[ itemEvent ], item ];
4853 }
4854 item.disconnect( this, remove );
4855 }
4856 item.setElementGroup( null );
4857 item.$element.detach();
4858 }
4859
4860 this.items = [];
4861 return this;
4862 };
4863
4864 /**
4865 * DraggableElement is a mixin class used to create elements that can be clicked
4866 * and dragged by a mouse to a new position within a group. This class must be used
4867 * in conjunction with OO.ui.mixin.DraggableGroupElement, which provides a container for
4868 * the draggable elements.
4869 *
4870 * @abstract
4871 * @class
4872 *
4873 * @constructor
4874 */
4875 OO.ui.mixin.DraggableElement = function OoUiMixinDraggableElement() {
4876 // Properties
4877 this.index = null;
4878
4879 // Initialize and events
4880 this.$element
4881 .attr( 'draggable', true )
4882 .addClass( 'oo-ui-draggableElement' )
4883 .on( {
4884 dragstart: this.onDragStart.bind( this ),
4885 dragover: this.onDragOver.bind( this ),
4886 dragend: this.onDragEnd.bind( this ),
4887 drop: this.onDrop.bind( this )
4888 } );
4889 };
4890
4891 OO.initClass( OO.ui.mixin.DraggableElement );
4892
4893 /* Events */
4894
4895 /**
4896 * @event dragstart
4897 *
4898 * A dragstart event is emitted when the user clicks and begins dragging an item.
4899 * @param {OO.ui.mixin.DraggableElement} item The item the user has clicked and is dragging with the mouse.
4900 */
4901
4902 /**
4903 * @event dragend
4904 * A dragend event is emitted when the user drags an item and releases the mouse,
4905 * thus terminating the drag operation.
4906 */
4907
4908 /**
4909 * @event drop
4910 * A drop event is emitted when the user drags an item and then releases the mouse button
4911 * over a valid target.
4912 */
4913
4914 /* Static Properties */
4915
4916 /**
4917 * @inheritdoc OO.ui.mixin.ButtonElement
4918 */
4919 OO.ui.mixin.DraggableElement.static.cancelButtonMouseDownEvents = false;
4920
4921 /* Methods */
4922
4923 /**
4924 * Respond to dragstart event.
4925 *
4926 * @private
4927 * @param {jQuery.Event} event jQuery event
4928 * @fires dragstart
4929 */
4930 OO.ui.mixin.DraggableElement.prototype.onDragStart = function ( e ) {
4931 var dataTransfer = e.originalEvent.dataTransfer;
4932 // Define drop effect
4933 dataTransfer.dropEffect = 'none';
4934 dataTransfer.effectAllowed = 'move';
4935 // We must set up a dataTransfer data property or Firefox seems to
4936 // ignore the fact the element is draggable.
4937 try {
4938 dataTransfer.setData( 'application-x/OOjs-UI-draggable', this.getIndex() );
4939 } catch ( err ) {
4940 // The above is only for firefox. No need to set a catch clause
4941 // if it fails, move on.
4942 }
4943 // Add dragging class
4944 this.$element.addClass( 'oo-ui-draggableElement-dragging' );
4945 // Emit event
4946 this.emit( 'dragstart', this );
4947 return true;
4948 };
4949
4950 /**
4951 * Respond to dragend event.
4952 *
4953 * @private
4954 * @fires dragend
4955 */
4956 OO.ui.mixin.DraggableElement.prototype.onDragEnd = function () {
4957 this.$element.removeClass( 'oo-ui-draggableElement-dragging' );
4958 this.emit( 'dragend' );
4959 };
4960
4961 /**
4962 * Handle drop event.
4963 *
4964 * @private
4965 * @param {jQuery.Event} event jQuery event
4966 * @fires drop
4967 */
4968 OO.ui.mixin.DraggableElement.prototype.onDrop = function ( e ) {
4969 e.preventDefault();
4970 this.emit( 'drop', e );
4971 };
4972
4973 /**
4974 * In order for drag/drop to work, the dragover event must
4975 * return false and stop propogation.
4976 *
4977 * @private
4978 */
4979 OO.ui.mixin.DraggableElement.prototype.onDragOver = function ( e ) {
4980 e.preventDefault();
4981 };
4982
4983 /**
4984 * Set item index.
4985 * Store it in the DOM so we can access from the widget drag event
4986 *
4987 * @private
4988 * @param {number} Item index
4989 */
4990 OO.ui.mixin.DraggableElement.prototype.setIndex = function ( index ) {
4991 if ( this.index !== index ) {
4992 this.index = index;
4993 this.$element.data( 'index', index );
4994 }
4995 };
4996
4997 /**
4998 * Get item index
4999 *
5000 * @private
5001 * @return {number} Item index
5002 */
5003 OO.ui.mixin.DraggableElement.prototype.getIndex = function () {
5004 return this.index;
5005 };
5006
5007 /**
5008 * DraggableGroupElement is a mixin class used to create a group element to
5009 * contain draggable elements, which are items that can be clicked and dragged by a mouse.
5010 * The class is used with OO.ui.mixin.DraggableElement.
5011 *
5012 * @abstract
5013 * @class
5014 * @mixins OO.ui.mixin.GroupElement
5015 *
5016 * @constructor
5017 * @param {Object} [config] Configuration options
5018 * @cfg {string} [orientation] Item orientation: 'horizontal' or 'vertical'. The orientation
5019 * should match the layout of the items. Items displayed in a single row
5020 * or in several rows should use horizontal orientation. The vertical orientation should only be
5021 * used when the items are displayed in a single column. Defaults to 'vertical'
5022 */
5023 OO.ui.mixin.DraggableGroupElement = function OoUiMixinDraggableGroupElement( config ) {
5024 // Configuration initialization
5025 config = config || {};
5026
5027 // Parent constructor
5028 OO.ui.mixin.GroupElement.call( this, config );
5029
5030 // Properties
5031 this.orientation = config.orientation || 'vertical';
5032 this.dragItem = null;
5033 this.itemDragOver = null;
5034 this.itemKeys = {};
5035 this.sideInsertion = '';
5036
5037 // Events
5038 this.aggregate( {
5039 dragstart: 'itemDragStart',
5040 dragend: 'itemDragEnd',
5041 drop: 'itemDrop'
5042 } );
5043 this.connect( this, {
5044 itemDragStart: 'onItemDragStart',
5045 itemDrop: 'onItemDrop',
5046 itemDragEnd: 'onItemDragEnd'
5047 } );
5048 this.$element.on( {
5049 dragover: $.proxy( this.onDragOver, this ),
5050 dragleave: $.proxy( this.onDragLeave, this )
5051 } );
5052
5053 // Initialize
5054 if ( Array.isArray( config.items ) ) {
5055 this.addItems( config.items );
5056 }
5057 this.$placeholder = $( '<div>' )
5058 .addClass( 'oo-ui-draggableGroupElement-placeholder' );
5059 this.$element
5060 .addClass( 'oo-ui-draggableGroupElement' )
5061 .append( this.$status )
5062 .toggleClass( 'oo-ui-draggableGroupElement-horizontal', this.orientation === 'horizontal' )
5063 .prepend( this.$placeholder );
5064 };
5065
5066 /* Setup */
5067 OO.mixinClass( OO.ui.mixin.DraggableGroupElement, OO.ui.mixin.GroupElement );
5068
5069 /* Events */
5070
5071 /**
5072 * A 'reorder' event is emitted when the order of items in the group changes.
5073 *
5074 * @event reorder
5075 * @param {OO.ui.mixin.DraggableElement} item Reordered item
5076 * @param {number} [newIndex] New index for the item
5077 */
5078
5079 /* Methods */
5080
5081 /**
5082 * Respond to item drag start event
5083 *
5084 * @private
5085 * @param {OO.ui.mixin.DraggableElement} item Dragged item
5086 */
5087 OO.ui.mixin.DraggableGroupElement.prototype.onItemDragStart = function ( item ) {
5088 var i, len;
5089
5090 // Map the index of each object
5091 for ( i = 0, len = this.items.length; i < len; i++ ) {
5092 this.items[ i ].setIndex( i );
5093 }
5094
5095 if ( this.orientation === 'horizontal' ) {
5096 // Set the height of the indicator
5097 this.$placeholder.css( {
5098 height: item.$element.outerHeight(),
5099 width: 2
5100 } );
5101 } else {
5102 // Set the width of the indicator
5103 this.$placeholder.css( {
5104 height: 2,
5105 width: item.$element.outerWidth()
5106 } );
5107 }
5108 this.setDragItem( item );
5109 };
5110
5111 /**
5112 * Respond to item drag end event
5113 *
5114 * @private
5115 */
5116 OO.ui.mixin.DraggableGroupElement.prototype.onItemDragEnd = function () {
5117 this.unsetDragItem();
5118 return false;
5119 };
5120
5121 /**
5122 * Handle drop event and switch the order of the items accordingly
5123 *
5124 * @private
5125 * @param {OO.ui.mixin.DraggableElement} item Dropped item
5126 * @fires reorder
5127 */
5128 OO.ui.mixin.DraggableGroupElement.prototype.onItemDrop = function ( item ) {
5129 var toIndex = item.getIndex();
5130 // Check if the dropped item is from the current group
5131 // TODO: Figure out a way to configure a list of legally droppable
5132 // elements even if they are not yet in the list
5133 if ( this.getDragItem() ) {
5134 // If the insertion point is 'after', the insertion index
5135 // is shifted to the right (or to the left in RTL, hence 'after')
5136 if ( this.sideInsertion === 'after' ) {
5137 toIndex++;
5138 }
5139 // Emit change event
5140 this.emit( 'reorder', this.getDragItem(), toIndex );
5141 }
5142 this.unsetDragItem();
5143 // Return false to prevent propogation
5144 return false;
5145 };
5146
5147 /**
5148 * Handle dragleave event.
5149 *
5150 * @private
5151 */
5152 OO.ui.mixin.DraggableGroupElement.prototype.onDragLeave = function () {
5153 // This means the item was dragged outside the widget
5154 this.$placeholder
5155 .css( 'left', 0 )
5156 .addClass( 'oo-ui-element-hidden' );
5157 };
5158
5159 /**
5160 * Respond to dragover event
5161 *
5162 * @private
5163 * @param {jQuery.Event} event Event details
5164 */
5165 OO.ui.mixin.DraggableGroupElement.prototype.onDragOver = function ( e ) {
5166 var dragOverObj, $optionWidget, itemOffset, itemMidpoint, itemBoundingRect,
5167 itemSize, cssOutput, dragPosition, itemIndex, itemPosition,
5168 clientX = e.originalEvent.clientX,
5169 clientY = e.originalEvent.clientY;
5170
5171 // Get the OptionWidget item we are dragging over
5172 dragOverObj = this.getElementDocument().elementFromPoint( clientX, clientY );
5173 $optionWidget = $( dragOverObj ).closest( '.oo-ui-draggableElement' );
5174 if ( $optionWidget[ 0 ] ) {
5175 itemOffset = $optionWidget.offset();
5176 itemBoundingRect = $optionWidget[ 0 ].getBoundingClientRect();
5177 itemPosition = $optionWidget.position();
5178 itemIndex = $optionWidget.data( 'index' );
5179 }
5180
5181 if (
5182 itemOffset &&
5183 this.isDragging() &&
5184 itemIndex !== this.getDragItem().getIndex()
5185 ) {
5186 if ( this.orientation === 'horizontal' ) {
5187 // Calculate where the mouse is relative to the item width
5188 itemSize = itemBoundingRect.width;
5189 itemMidpoint = itemBoundingRect.left + itemSize / 2;
5190 dragPosition = clientX;
5191 // Which side of the item we hover over will dictate
5192 // where the placeholder will appear, on the left or
5193 // on the right
5194 cssOutput = {
5195 left: dragPosition < itemMidpoint ? itemPosition.left : itemPosition.left + itemSize,
5196 top: itemPosition.top
5197 };
5198 } else {
5199 // Calculate where the mouse is relative to the item height
5200 itemSize = itemBoundingRect.height;
5201 itemMidpoint = itemBoundingRect.top + itemSize / 2;
5202 dragPosition = clientY;
5203 // Which side of the item we hover over will dictate
5204 // where the placeholder will appear, on the top or
5205 // on the bottom
5206 cssOutput = {
5207 top: dragPosition < itemMidpoint ? itemPosition.top : itemPosition.top + itemSize,
5208 left: itemPosition.left
5209 };
5210 }
5211 // Store whether we are before or after an item to rearrange
5212 // For horizontal layout, we need to account for RTL, as this is flipped
5213 if ( this.orientation === 'horizontal' && this.$element.css( 'direction' ) === 'rtl' ) {
5214 this.sideInsertion = dragPosition < itemMidpoint ? 'after' : 'before';
5215 } else {
5216 this.sideInsertion = dragPosition < itemMidpoint ? 'before' : 'after';
5217 }
5218 // Add drop indicator between objects
5219 this.$placeholder
5220 .css( cssOutput )
5221 .removeClass( 'oo-ui-element-hidden' );
5222 } else {
5223 // This means the item was dragged outside the widget
5224 this.$placeholder
5225 .css( 'left', 0 )
5226 .addClass( 'oo-ui-element-hidden' );
5227 }
5228 // Prevent default
5229 e.preventDefault();
5230 };
5231
5232 /**
5233 * Set a dragged item
5234 *
5235 * @param {OO.ui.mixin.DraggableElement} item Dragged item
5236 */
5237 OO.ui.mixin.DraggableGroupElement.prototype.setDragItem = function ( item ) {
5238 this.dragItem = item;
5239 };
5240
5241 /**
5242 * Unset the current dragged item
5243 */
5244 OO.ui.mixin.DraggableGroupElement.prototype.unsetDragItem = function () {
5245 this.dragItem = null;
5246 this.itemDragOver = null;
5247 this.$placeholder.addClass( 'oo-ui-element-hidden' );
5248 this.sideInsertion = '';
5249 };
5250
5251 /**
5252 * Get the item that is currently being dragged.
5253 *
5254 * @return {OO.ui.mixin.DraggableElement|null} The currently dragged item, or `null` if no item is being dragged
5255 */
5256 OO.ui.mixin.DraggableGroupElement.prototype.getDragItem = function () {
5257 return this.dragItem;
5258 };
5259
5260 /**
5261 * Check if an item in the group is currently being dragged.
5262 *
5263 * @return {Boolean} Item is being dragged
5264 */
5265 OO.ui.mixin.DraggableGroupElement.prototype.isDragging = function () {
5266 return this.getDragItem() !== null;
5267 };
5268
5269 /**
5270 * IconElement is often mixed into other classes to generate an icon.
5271 * Icons are graphics, about the size of normal text. They are used to aid the user
5272 * in locating a control or to convey information in a space-efficient way. See the
5273 * [OOjs UI documentation on MediaWiki] [1] for a list of icons
5274 * included in the library.
5275 *
5276 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
5277 *
5278 * @abstract
5279 * @class
5280 *
5281 * @constructor
5282 * @param {Object} [config] Configuration options
5283 * @cfg {jQuery} [$icon] The icon element created by the class. If this configuration is omitted,
5284 * the icon element will use a generated `<span>`. To use a different HTML tag, or to specify that
5285 * the icon element be set to an existing icon instead of the one generated by this class, set a
5286 * value using a jQuery selection. For example:
5287 *
5288 * // Use a <div> tag instead of a <span>
5289 * $icon: $("<div>")
5290 * // Use an existing icon element instead of the one generated by the class
5291 * $icon: this.$element
5292 * // Use an icon element from a child widget
5293 * $icon: this.childwidget.$element
5294 * @cfg {Object|string} [icon=''] The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of
5295 * symbolic names. A map is used for i18n purposes and contains a `default` icon
5296 * name and additional names keyed by language code. The `default` name is used when no icon is keyed
5297 * by the user's language.
5298 *
5299 * Example of an i18n map:
5300 *
5301 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
5302 * See the [OOjs UI documentation on MediaWiki] [2] for a list of icons included in the library.
5303 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
5304 * @cfg {string|Function} [iconTitle] A text string used as the icon title, or a function that returns title
5305 * text. The icon title is displayed when users move the mouse over the icon.
5306 */
5307 OO.ui.mixin.IconElement = function OoUiMixinIconElement( config ) {
5308 // Configuration initialization
5309 config = config || {};
5310
5311 // Properties
5312 this.$icon = null;
5313 this.icon = null;
5314 this.iconTitle = null;
5315
5316 // Initialization
5317 this.setIcon( config.icon || this.constructor.static.icon );
5318 this.setIconTitle( config.iconTitle || this.constructor.static.iconTitle );
5319 this.setIconElement( config.$icon || $( '<span>' ) );
5320 };
5321
5322 /* Setup */
5323
5324 OO.initClass( OO.ui.mixin.IconElement );
5325
5326 /* Static Properties */
5327
5328 /**
5329 * The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of symbolic names. A map is used
5330 * for i18n purposes and contains a `default` icon name and additional names keyed by
5331 * language code. The `default` name is used when no icon is keyed by the user's language.
5332 *
5333 * Example of an i18n map:
5334 *
5335 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
5336 *
5337 * Note: the static property will be overridden if the #icon configuration is used.
5338 *
5339 * @static
5340 * @inheritable
5341 * @property {Object|string}
5342 */
5343 OO.ui.mixin.IconElement.static.icon = null;
5344
5345 /**
5346 * The icon title, displayed when users move the mouse over the icon. The value can be text, a
5347 * function that returns title text, or `null` for no title.
5348 *
5349 * The static property will be overridden if the #iconTitle configuration is used.
5350 *
5351 * @static
5352 * @inheritable
5353 * @property {string|Function|null}
5354 */
5355 OO.ui.mixin.IconElement.static.iconTitle = null;
5356
5357 /* Methods */
5358
5359 /**
5360 * Set the icon element. This method is used to retarget an icon mixin so that its functionality
5361 * applies to the specified icon element instead of the one created by the class. If an icon
5362 * element is already set, the mixin’s effect on that element is removed. Generated CSS classes
5363 * and mixin methods will no longer affect the element.
5364 *
5365 * @param {jQuery} $icon Element to use as icon
5366 */
5367 OO.ui.mixin.IconElement.prototype.setIconElement = function ( $icon ) {
5368 if ( this.$icon ) {
5369 this.$icon
5370 .removeClass( 'oo-ui-iconElement-icon oo-ui-icon-' + this.icon )
5371 .removeAttr( 'title' );
5372 }
5373
5374 this.$icon = $icon
5375 .addClass( 'oo-ui-iconElement-icon' )
5376 .toggleClass( 'oo-ui-icon-' + this.icon, !!this.icon );
5377 if ( this.iconTitle !== null ) {
5378 this.$icon.attr( 'title', this.iconTitle );
5379 }
5380 };
5381
5382 /**
5383 * Set icon by symbolic name (e.g., ‘remove’ or ‘menu’). Use `null` to remove an icon.
5384 * The icon parameter can also be set to a map of icon names. See the #icon config setting
5385 * for an example.
5386 *
5387 * @param {Object|string|null} icon A symbolic icon name, a {@link #icon map of icon names} keyed
5388 * by language code, or `null` to remove the icon.
5389 * @chainable
5390 */
5391 OO.ui.mixin.IconElement.prototype.setIcon = function ( icon ) {
5392 icon = OO.isPlainObject( icon ) ? OO.ui.getLocalValue( icon, null, 'default' ) : icon;
5393 icon = typeof icon === 'string' && icon.trim().length ? icon.trim() : null;
5394
5395 if ( this.icon !== icon ) {
5396 if ( this.$icon ) {
5397 if ( this.icon !== null ) {
5398 this.$icon.removeClass( 'oo-ui-icon-' + this.icon );
5399 }
5400 if ( icon !== null ) {
5401 this.$icon.addClass( 'oo-ui-icon-' + icon );
5402 }
5403 }
5404 this.icon = icon;
5405 }
5406
5407 this.$element.toggleClass( 'oo-ui-iconElement', !!this.icon );
5408 this.updateThemeClasses();
5409
5410 return this;
5411 };
5412
5413 /**
5414 * Set the icon title. Use `null` to remove the title.
5415 *
5416 * @param {string|Function|null} iconTitle A text string used as the icon title,
5417 * a function that returns title text, or `null` for no title.
5418 * @chainable
5419 */
5420 OO.ui.mixin.IconElement.prototype.setIconTitle = function ( iconTitle ) {
5421 iconTitle = typeof iconTitle === 'function' ||
5422 ( typeof iconTitle === 'string' && iconTitle.length ) ?
5423 OO.ui.resolveMsg( iconTitle ) : null;
5424
5425 if ( this.iconTitle !== iconTitle ) {
5426 this.iconTitle = iconTitle;
5427 if ( this.$icon ) {
5428 if ( this.iconTitle !== null ) {
5429 this.$icon.attr( 'title', iconTitle );
5430 } else {
5431 this.$icon.removeAttr( 'title' );
5432 }
5433 }
5434 }
5435
5436 return this;
5437 };
5438
5439 /**
5440 * Get the symbolic name of the icon.
5441 *
5442 * @return {string} Icon name
5443 */
5444 OO.ui.mixin.IconElement.prototype.getIcon = function () {
5445 return this.icon;
5446 };
5447
5448 /**
5449 * Get the icon title. The title text is displayed when a user moves the mouse over the icon.
5450 *
5451 * @return {string} Icon title text
5452 */
5453 OO.ui.mixin.IconElement.prototype.getIconTitle = function () {
5454 return this.iconTitle;
5455 };
5456
5457 /**
5458 * IndicatorElement is often mixed into other classes to generate an indicator.
5459 * Indicators are small graphics that are generally used in two ways:
5460 *
5461 * - To draw attention to the status of an item. For example, an indicator might be
5462 * used to show that an item in a list has errors that need to be resolved.
5463 * - To clarify the function of a control that acts in an exceptional way (a button
5464 * that opens a menu instead of performing an action directly, for example).
5465 *
5466 * For a list of indicators included in the library, please see the
5467 * [OOjs UI documentation on MediaWiki] [1].
5468 *
5469 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
5470 *
5471 * @abstract
5472 * @class
5473 *
5474 * @constructor
5475 * @param {Object} [config] Configuration options
5476 * @cfg {jQuery} [$indicator] The indicator element created by the class. If this
5477 * configuration is omitted, the indicator element will use a generated `<span>`.
5478 * @cfg {string} [indicator] Symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
5479 * See the [OOjs UI documentation on MediaWiki][2] for a list of indicators included
5480 * in the library.
5481 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
5482 * @cfg {string|Function} [indicatorTitle] A text string used as the indicator title,
5483 * or a function that returns title text. The indicator title is displayed when users move
5484 * the mouse over the indicator.
5485 */
5486 OO.ui.mixin.IndicatorElement = function OoUiMixinIndicatorElement( config ) {
5487 // Configuration initialization
5488 config = config || {};
5489
5490 // Properties
5491 this.$indicator = null;
5492 this.indicator = null;
5493 this.indicatorTitle = null;
5494
5495 // Initialization
5496 this.setIndicator( config.indicator || this.constructor.static.indicator );
5497 this.setIndicatorTitle( config.indicatorTitle || this.constructor.static.indicatorTitle );
5498 this.setIndicatorElement( config.$indicator || $( '<span>' ) );
5499 };
5500
5501 /* Setup */
5502
5503 OO.initClass( OO.ui.mixin.IndicatorElement );
5504
5505 /* Static Properties */
5506
5507 /**
5508 * Symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
5509 * The static property will be overridden if the #indicator configuration is used.
5510 *
5511 * @static
5512 * @inheritable
5513 * @property {string|null}
5514 */
5515 OO.ui.mixin.IndicatorElement.static.indicator = null;
5516
5517 /**
5518 * A text string used as the indicator title, a function that returns title text, or `null`
5519 * for no title. The static property will be overridden if the #indicatorTitle configuration is used.
5520 *
5521 * @static
5522 * @inheritable
5523 * @property {string|Function|null}
5524 */
5525 OO.ui.mixin.IndicatorElement.static.indicatorTitle = null;
5526
5527 /* Methods */
5528
5529 /**
5530 * Set the indicator element.
5531 *
5532 * If an element is already set, it will be cleaned up before setting up the new element.
5533 *
5534 * @param {jQuery} $indicator Element to use as indicator
5535 */
5536 OO.ui.mixin.IndicatorElement.prototype.setIndicatorElement = function ( $indicator ) {
5537 if ( this.$indicator ) {
5538 this.$indicator
5539 .removeClass( 'oo-ui-indicatorElement-indicator oo-ui-indicator-' + this.indicator )
5540 .removeAttr( 'title' );
5541 }
5542
5543 this.$indicator = $indicator
5544 .addClass( 'oo-ui-indicatorElement-indicator' )
5545 .toggleClass( 'oo-ui-indicator-' + this.indicator, !!this.indicator );
5546 if ( this.indicatorTitle !== null ) {
5547 this.$indicator.attr( 'title', this.indicatorTitle );
5548 }
5549 };
5550
5551 /**
5552 * Set the indicator by its symbolic name: ‘alert’, ‘down’, ‘next’, ‘previous’, ‘required’, ‘up’. Use `null` to remove the indicator.
5553 *
5554 * @param {string|null} indicator Symbolic name of indicator, or `null` for no indicator
5555 * @chainable
5556 */
5557 OO.ui.mixin.IndicatorElement.prototype.setIndicator = function ( indicator ) {
5558 indicator = typeof indicator === 'string' && indicator.length ? indicator.trim() : null;
5559
5560 if ( this.indicator !== indicator ) {
5561 if ( this.$indicator ) {
5562 if ( this.indicator !== null ) {
5563 this.$indicator.removeClass( 'oo-ui-indicator-' + this.indicator );
5564 }
5565 if ( indicator !== null ) {
5566 this.$indicator.addClass( 'oo-ui-indicator-' + indicator );
5567 }
5568 }
5569 this.indicator = indicator;
5570 }
5571
5572 this.$element.toggleClass( 'oo-ui-indicatorElement', !!this.indicator );
5573 this.updateThemeClasses();
5574
5575 return this;
5576 };
5577
5578 /**
5579 * Set the indicator title.
5580 *
5581 * The title is displayed when a user moves the mouse over the indicator.
5582 *
5583 * @param {string|Function|null} indicator Indicator title text, a function that returns text, or
5584 * `null` for no indicator title
5585 * @chainable
5586 */
5587 OO.ui.mixin.IndicatorElement.prototype.setIndicatorTitle = function ( indicatorTitle ) {
5588 indicatorTitle = typeof indicatorTitle === 'function' ||
5589 ( typeof indicatorTitle === 'string' && indicatorTitle.length ) ?
5590 OO.ui.resolveMsg( indicatorTitle ) : null;
5591
5592 if ( this.indicatorTitle !== indicatorTitle ) {
5593 this.indicatorTitle = indicatorTitle;
5594 if ( this.$indicator ) {
5595 if ( this.indicatorTitle !== null ) {
5596 this.$indicator.attr( 'title', indicatorTitle );
5597 } else {
5598 this.$indicator.removeAttr( 'title' );
5599 }
5600 }
5601 }
5602
5603 return this;
5604 };
5605
5606 /**
5607 * Get the symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
5608 *
5609 * @return {string} Symbolic name of indicator
5610 */
5611 OO.ui.mixin.IndicatorElement.prototype.getIndicator = function () {
5612 return this.indicator;
5613 };
5614
5615 /**
5616 * Get the indicator title.
5617 *
5618 * The title is displayed when a user moves the mouse over the indicator.
5619 *
5620 * @return {string} Indicator title text
5621 */
5622 OO.ui.mixin.IndicatorElement.prototype.getIndicatorTitle = function () {
5623 return this.indicatorTitle;
5624 };
5625
5626 /**
5627 * LabelElement is often mixed into other classes to generate a label, which
5628 * helps identify the function of an interface element.
5629 * See the [OOjs UI documentation on MediaWiki] [1] for more information.
5630 *
5631 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Labels
5632 *
5633 * @abstract
5634 * @class
5635 *
5636 * @constructor
5637 * @param {Object} [config] Configuration options
5638 * @cfg {jQuery} [$label] The label element created by the class. If this
5639 * configuration is omitted, the label element will use a generated `<span>`.
5640 * @cfg {jQuery|string|Function|OO.ui.HtmlSnippet} [label] The label text. The label can be specified
5641 * as a plaintext string, a jQuery selection of elements, or a function that will produce a string
5642 * in the future. See the [OOjs UI documentation on MediaWiki] [2] for examples.
5643 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Labels
5644 * @cfg {boolean} [autoFitLabel=true] Fit the label to the width of the parent element.
5645 * The label will be truncated to fit if necessary.
5646 */
5647 OO.ui.mixin.LabelElement = function OoUiMixinLabelElement( config ) {
5648 // Configuration initialization
5649 config = config || {};
5650
5651 // Properties
5652 this.$label = null;
5653 this.label = null;
5654 this.autoFitLabel = config.autoFitLabel === undefined || !!config.autoFitLabel;
5655
5656 // Initialization
5657 this.setLabel( config.label || this.constructor.static.label );
5658 this.setLabelElement( config.$label || $( '<span>' ) );
5659 };
5660
5661 /* Setup */
5662
5663 OO.initClass( OO.ui.mixin.LabelElement );
5664
5665 /* Events */
5666
5667 /**
5668 * @event labelChange
5669 * @param {string} value
5670 */
5671
5672 /* Static Properties */
5673
5674 /**
5675 * The label text. The label can be specified as a plaintext string, a function that will
5676 * produce a string in the future, or `null` for no label. The static value will
5677 * be overridden if a label is specified with the #label config option.
5678 *
5679 * @static
5680 * @inheritable
5681 * @property {string|Function|null}
5682 */
5683 OO.ui.mixin.LabelElement.static.label = null;
5684
5685 /* Methods */
5686
5687 /**
5688 * Set the label element.
5689 *
5690 * If an element is already set, it will be cleaned up before setting up the new element.
5691 *
5692 * @param {jQuery} $label Element to use as label
5693 */
5694 OO.ui.mixin.LabelElement.prototype.setLabelElement = function ( $label ) {
5695 if ( this.$label ) {
5696 this.$label.removeClass( 'oo-ui-labelElement-label' ).empty();
5697 }
5698
5699 this.$label = $label.addClass( 'oo-ui-labelElement-label' );
5700 this.setLabelContent( this.label );
5701 };
5702
5703 /**
5704 * Set the label.
5705 *
5706 * An empty string will result in the label being hidden. A string containing only whitespace will
5707 * be converted to a single `&nbsp;`.
5708 *
5709 * @param {jQuery|string|OO.ui.HtmlSnippet|Function|null} label Label nodes; text; a function that returns nodes or
5710 * text; or null for no label
5711 * @chainable
5712 */
5713 OO.ui.mixin.LabelElement.prototype.setLabel = function ( label ) {
5714 label = typeof label === 'function' ? OO.ui.resolveMsg( label ) : label;
5715 label = ( ( typeof label === 'string' && label.length ) || label instanceof jQuery || label instanceof OO.ui.HtmlSnippet ) ? label : null;
5716
5717 this.$element.toggleClass( 'oo-ui-labelElement', !!label );
5718
5719 if ( this.label !== label ) {
5720 if ( this.$label ) {
5721 this.setLabelContent( label );
5722 }
5723 this.label = label;
5724 this.emit( 'labelChange' );
5725 }
5726
5727 return this;
5728 };
5729
5730 /**
5731 * Get the label.
5732 *
5733 * @return {jQuery|string|Function|null} Label nodes; text; a function that returns nodes or
5734 * text; or null for no label
5735 */
5736 OO.ui.mixin.LabelElement.prototype.getLabel = function () {
5737 return this.label;
5738 };
5739
5740 /**
5741 * Fit the label.
5742 *
5743 * @chainable
5744 */
5745 OO.ui.mixin.LabelElement.prototype.fitLabel = function () {
5746 if ( this.$label && this.$label.autoEllipsis && this.autoFitLabel ) {
5747 this.$label.autoEllipsis( { hasSpan: false, tooltip: true } );
5748 }
5749
5750 return this;
5751 };
5752
5753 /**
5754 * Set the content of the label.
5755 *
5756 * Do not call this method until after the label element has been set by #setLabelElement.
5757 *
5758 * @private
5759 * @param {jQuery|string|Function|null} label Label nodes; text; a function that returns nodes or
5760 * text; or null for no label
5761 */
5762 OO.ui.mixin.LabelElement.prototype.setLabelContent = function ( label ) {
5763 if ( typeof label === 'string' ) {
5764 if ( label.match( /^\s*$/ ) ) {
5765 // Convert whitespace only string to a single non-breaking space
5766 this.$label.html( '&nbsp;' );
5767 } else {
5768 this.$label.text( label );
5769 }
5770 } else if ( label instanceof OO.ui.HtmlSnippet ) {
5771 this.$label.html( label.toString() );
5772 } else if ( label instanceof jQuery ) {
5773 this.$label.empty().append( label );
5774 } else {
5775 this.$label.empty();
5776 }
5777 };
5778
5779 /**
5780 * LookupElement is a mixin that creates a {@link OO.ui.FloatingMenuSelectWidget menu} of suggested values for
5781 * a {@link OO.ui.TextInputWidget text input widget}. Suggested values are based on the characters the user types
5782 * into the text input field and, in general, the menu is only displayed when the user types. If a suggested value is chosen
5783 * from the lookup menu, that value becomes the value of the input field.
5784 *
5785 * Note that a new menu of suggested items is displayed when a value is chosen from the lookup menu. If this is
5786 * not the desired behavior, disable lookup menus with the #setLookupsDisabled method, then set the value, then
5787 * re-enable lookups.
5788 *
5789 * See the [OOjs UI demos][1] for an example.
5790 *
5791 * [1]: https://tools.wmflabs.org/oojs-ui/oojs-ui/demos/index.html#widgets-apex-vector-ltr
5792 *
5793 * @class
5794 * @abstract
5795 *
5796 * @constructor
5797 * @param {Object} [config] Configuration options
5798 * @cfg {jQuery} [$overlay] Overlay for the lookup menu; defaults to relative positioning
5799 * @cfg {jQuery} [$container=this.$element] The container element. The lookup menu is rendered beneath the specified element.
5800 * @cfg {boolean} [allowSuggestionsWhenEmpty=false] Request and display a lookup menu when the text input is empty.
5801 * By default, the lookup menu is not generated and displayed until the user begins to type.
5802 */
5803 OO.ui.mixin.LookupElement = function OoUiMixinLookupElement( config ) {
5804 // Configuration initialization
5805 config = config || {};
5806
5807 // Properties
5808 this.$overlay = config.$overlay || this.$element;
5809 this.lookupMenu = new OO.ui.FloatingMenuSelectWidget( {
5810 widget: this,
5811 input: this,
5812 $container: config.$container || this.$element
5813 } );
5814
5815 this.allowSuggestionsWhenEmpty = config.allowSuggestionsWhenEmpty || false;
5816
5817 this.lookupCache = {};
5818 this.lookupQuery = null;
5819 this.lookupRequest = null;
5820 this.lookupsDisabled = false;
5821 this.lookupInputFocused = false;
5822
5823 // Events
5824 this.$input.on( {
5825 focus: this.onLookupInputFocus.bind( this ),
5826 blur: this.onLookupInputBlur.bind( this ),
5827 mousedown: this.onLookupInputMouseDown.bind( this )
5828 } );
5829 this.connect( this, { change: 'onLookupInputChange' } );
5830 this.lookupMenu.connect( this, {
5831 toggle: 'onLookupMenuToggle',
5832 choose: 'onLookupMenuItemChoose'
5833 } );
5834
5835 // Initialization
5836 this.$element.addClass( 'oo-ui-lookupElement' );
5837 this.lookupMenu.$element.addClass( 'oo-ui-lookupElement-menu' );
5838 this.$overlay.append( this.lookupMenu.$element );
5839 };
5840
5841 /* Methods */
5842
5843 /**
5844 * Handle input focus event.
5845 *
5846 * @protected
5847 * @param {jQuery.Event} e Input focus event
5848 */
5849 OO.ui.mixin.LookupElement.prototype.onLookupInputFocus = function () {
5850 this.lookupInputFocused = true;
5851 this.populateLookupMenu();
5852 };
5853
5854 /**
5855 * Handle input blur event.
5856 *
5857 * @protected
5858 * @param {jQuery.Event} e Input blur event
5859 */
5860 OO.ui.mixin.LookupElement.prototype.onLookupInputBlur = function () {
5861 this.closeLookupMenu();
5862 this.lookupInputFocused = false;
5863 };
5864
5865 /**
5866 * Handle input mouse down event.
5867 *
5868 * @protected
5869 * @param {jQuery.Event} e Input mouse down event
5870 */
5871 OO.ui.mixin.LookupElement.prototype.onLookupInputMouseDown = function () {
5872 // Only open the menu if the input was already focused.
5873 // This way we allow the user to open the menu again after closing it with Esc
5874 // by clicking in the input. Opening (and populating) the menu when initially
5875 // clicking into the input is handled by the focus handler.
5876 if ( this.lookupInputFocused && !this.lookupMenu.isVisible() ) {
5877 this.populateLookupMenu();
5878 }
5879 };
5880
5881 /**
5882 * Handle input change event.
5883 *
5884 * @protected
5885 * @param {string} value New input value
5886 */
5887 OO.ui.mixin.LookupElement.prototype.onLookupInputChange = function () {
5888 if ( this.lookupInputFocused ) {
5889 this.populateLookupMenu();
5890 }
5891 };
5892
5893 /**
5894 * Handle the lookup menu being shown/hidden.
5895 *
5896 * @protected
5897 * @param {boolean} visible Whether the lookup menu is now visible.
5898 */
5899 OO.ui.mixin.LookupElement.prototype.onLookupMenuToggle = function ( visible ) {
5900 if ( !visible ) {
5901 // When the menu is hidden, abort any active request and clear the menu.
5902 // This has to be done here in addition to closeLookupMenu(), because
5903 // MenuSelectWidget will close itself when the user presses Esc.
5904 this.abortLookupRequest();
5905 this.lookupMenu.clearItems();
5906 }
5907 };
5908
5909 /**
5910 * Handle menu item 'choose' event, updating the text input value to the value of the clicked item.
5911 *
5912 * @protected
5913 * @param {OO.ui.MenuOptionWidget} item Selected item
5914 */
5915 OO.ui.mixin.LookupElement.prototype.onLookupMenuItemChoose = function ( item ) {
5916 this.setValue( item.getData() );
5917 };
5918
5919 /**
5920 * Get lookup menu.
5921 *
5922 * @private
5923 * @return {OO.ui.FloatingMenuSelectWidget}
5924 */
5925 OO.ui.mixin.LookupElement.prototype.getLookupMenu = function () {
5926 return this.lookupMenu;
5927 };
5928
5929 /**
5930 * Disable or re-enable lookups.
5931 *
5932 * When lookups are disabled, calls to #populateLookupMenu will be ignored.
5933 *
5934 * @param {boolean} disabled Disable lookups
5935 */
5936 OO.ui.mixin.LookupElement.prototype.setLookupsDisabled = function ( disabled ) {
5937 this.lookupsDisabled = !!disabled;
5938 };
5939
5940 /**
5941 * Open the menu. If there are no entries in the menu, this does nothing.
5942 *
5943 * @private
5944 * @chainable
5945 */
5946 OO.ui.mixin.LookupElement.prototype.openLookupMenu = function () {
5947 if ( !this.lookupMenu.isEmpty() ) {
5948 this.lookupMenu.toggle( true );
5949 }
5950 return this;
5951 };
5952
5953 /**
5954 * Close the menu, empty it, and abort any pending request.
5955 *
5956 * @private
5957 * @chainable
5958 */
5959 OO.ui.mixin.LookupElement.prototype.closeLookupMenu = function () {
5960 this.lookupMenu.toggle( false );
5961 this.abortLookupRequest();
5962 this.lookupMenu.clearItems();
5963 return this;
5964 };
5965
5966 /**
5967 * Request menu items based on the input's current value, and when they arrive,
5968 * populate the menu with these items and show the menu.
5969 *
5970 * If lookups have been disabled with #setLookupsDisabled, this function does nothing.
5971 *
5972 * @private
5973 * @chainable
5974 */
5975 OO.ui.mixin.LookupElement.prototype.populateLookupMenu = function () {
5976 var widget = this,
5977 value = this.getValue();
5978
5979 if ( this.lookupsDisabled ) {
5980 return;
5981 }
5982
5983 // If the input is empty, clear the menu, unless suggestions when empty are allowed.
5984 if ( !this.allowSuggestionsWhenEmpty && value === '' ) {
5985 this.closeLookupMenu();
5986 // Skip population if there is already a request pending for the current value
5987 } else if ( value !== this.lookupQuery ) {
5988 this.getLookupMenuItems()
5989 .done( function ( items ) {
5990 widget.lookupMenu.clearItems();
5991 if ( items.length ) {
5992 widget.lookupMenu
5993 .addItems( items )
5994 .toggle( true );
5995 widget.initializeLookupMenuSelection();
5996 } else {
5997 widget.lookupMenu.toggle( false );
5998 }
5999 } )
6000 .fail( function () {
6001 widget.lookupMenu.clearItems();
6002 } );
6003 }
6004
6005 return this;
6006 };
6007
6008 /**
6009 * Highlight the first selectable item in the menu.
6010 *
6011 * @private
6012 * @chainable
6013 */
6014 OO.ui.mixin.LookupElement.prototype.initializeLookupMenuSelection = function () {
6015 if ( !this.lookupMenu.getSelectedItem() ) {
6016 this.lookupMenu.highlightItem( this.lookupMenu.getFirstSelectableItem() );
6017 }
6018 };
6019
6020 /**
6021 * Get lookup menu items for the current query.
6022 *
6023 * @private
6024 * @return {jQuery.Promise} Promise object which will be passed menu items as the first argument of
6025 * the done event. If the request was aborted to make way for a subsequent request, this promise
6026 * will not be rejected: it will remain pending forever.
6027 */
6028 OO.ui.mixin.LookupElement.prototype.getLookupMenuItems = function () {
6029 var widget = this,
6030 value = this.getValue(),
6031 deferred = $.Deferred(),
6032 ourRequest;
6033
6034 this.abortLookupRequest();
6035 if ( Object.prototype.hasOwnProperty.call( this.lookupCache, value ) ) {
6036 deferred.resolve( this.getLookupMenuOptionsFromData( this.lookupCache[ value ] ) );
6037 } else {
6038 this.pushPending();
6039 this.lookupQuery = value;
6040 ourRequest = this.lookupRequest = this.getLookupRequest();
6041 ourRequest
6042 .always( function () {
6043 // We need to pop pending even if this is an old request, otherwise
6044 // the widget will remain pending forever.
6045 // TODO: this assumes that an aborted request will fail or succeed soon after
6046 // being aborted, or at least eventually. It would be nice if we could popPending()
6047 // at abort time, but only if we knew that we hadn't already called popPending()
6048 // for that request.
6049 widget.popPending();
6050 } )
6051 .done( function ( response ) {
6052 // If this is an old request (and aborting it somehow caused it to still succeed),
6053 // ignore its success completely
6054 if ( ourRequest === widget.lookupRequest ) {
6055 widget.lookupQuery = null;
6056 widget.lookupRequest = null;
6057 widget.lookupCache[ value ] = widget.getLookupCacheDataFromResponse( response );
6058 deferred.resolve( widget.getLookupMenuOptionsFromData( widget.lookupCache[ value ] ) );
6059 }
6060 } )
6061 .fail( function () {
6062 // If this is an old request (or a request failing because it's being aborted),
6063 // ignore its failure completely
6064 if ( ourRequest === widget.lookupRequest ) {
6065 widget.lookupQuery = null;
6066 widget.lookupRequest = null;
6067 deferred.reject();
6068 }
6069 } );
6070 }
6071 return deferred.promise();
6072 };
6073
6074 /**
6075 * Abort the currently pending lookup request, if any.
6076 *
6077 * @private
6078 */
6079 OO.ui.mixin.LookupElement.prototype.abortLookupRequest = function () {
6080 var oldRequest = this.lookupRequest;
6081 if ( oldRequest ) {
6082 // First unset this.lookupRequest to the fail handler will notice
6083 // that the request is no longer current
6084 this.lookupRequest = null;
6085 this.lookupQuery = null;
6086 oldRequest.abort();
6087 }
6088 };
6089
6090 /**
6091 * Get a new request object of the current lookup query value.
6092 *
6093 * @protected
6094 * @abstract
6095 * @return {jQuery.Promise} jQuery AJAX object, or promise object with an .abort() method
6096 */
6097 OO.ui.mixin.LookupElement.prototype.getLookupRequest = function () {
6098 // Stub, implemented in subclass
6099 return null;
6100 };
6101
6102 /**
6103 * Pre-process data returned by the request from #getLookupRequest.
6104 *
6105 * The return value of this function will be cached, and any further queries for the given value
6106 * will use the cache rather than doing API requests.
6107 *
6108 * @protected
6109 * @abstract
6110 * @param {Mixed} response Response from server
6111 * @return {Mixed} Cached result data
6112 */
6113 OO.ui.mixin.LookupElement.prototype.getLookupCacheDataFromResponse = function () {
6114 // Stub, implemented in subclass
6115 return [];
6116 };
6117
6118 /**
6119 * Get a list of menu option widgets from the (possibly cached) data returned by
6120 * #getLookupCacheDataFromResponse.
6121 *
6122 * @protected
6123 * @abstract
6124 * @param {Mixed} data Cached result data, usually an array
6125 * @return {OO.ui.MenuOptionWidget[]} Menu items
6126 */
6127 OO.ui.mixin.LookupElement.prototype.getLookupMenuOptionsFromData = function () {
6128 // Stub, implemented in subclass
6129 return [];
6130 };
6131
6132 /**
6133 * Set the read-only state of the widget.
6134 *
6135 * This will also disable/enable the lookups functionality.
6136 *
6137 * @param {boolean} readOnly Make input read-only
6138 * @chainable
6139 */
6140 OO.ui.mixin.LookupElement.prototype.setReadOnly = function ( readOnly ) {
6141 // Parent method
6142 // Note: Calling #setReadOnly this way assumes this is mixed into an OO.ui.TextInputWidget
6143 OO.ui.TextInputWidget.prototype.setReadOnly.call( this, readOnly );
6144
6145 this.setLookupsDisabled( readOnly );
6146 // During construction, #setReadOnly is called before the OO.ui.mixin.LookupElement constructor
6147 if ( readOnly && this.lookupMenu ) {
6148 this.closeLookupMenu();
6149 }
6150
6151 return this;
6152 };
6153
6154 /**
6155 * PopupElement is mixed into other classes to generate a {@link OO.ui.PopupWidget popup widget}.
6156 * A popup is a container for content. It is overlaid and positioned absolutely. By default, each
6157 * popup has an anchor, which is an arrow-like protrusion that points toward the popup’s origin.
6158 * See {@link OO.ui.PopupWidget PopupWidget} for an example.
6159 *
6160 * @abstract
6161 * @class
6162 *
6163 * @constructor
6164 * @param {Object} [config] Configuration options
6165 * @cfg {Object} [popup] Configuration to pass to popup
6166 * @cfg {boolean} [popup.autoClose=true] Popup auto-closes when it loses focus
6167 */
6168 OO.ui.mixin.PopupElement = function OoUiMixinPopupElement( config ) {
6169 // Configuration initialization
6170 config = config || {};
6171
6172 // Properties
6173 this.popup = new OO.ui.PopupWidget( $.extend(
6174 { autoClose: true },
6175 config.popup,
6176 { $autoCloseIgnore: this.$element }
6177 ) );
6178 };
6179
6180 /* Methods */
6181
6182 /**
6183 * Get popup.
6184 *
6185 * @return {OO.ui.PopupWidget} Popup widget
6186 */
6187 OO.ui.mixin.PopupElement.prototype.getPopup = function () {
6188 return this.popup;
6189 };
6190
6191 /**
6192 * The FlaggedElement class is an attribute mixin, meaning that it is used to add
6193 * additional functionality to an element created by another class. The class provides
6194 * a ‘flags’ property assigned the name (or an array of names) of styling flags,
6195 * which are used to customize the look and feel of a widget to better describe its
6196 * importance and functionality.
6197 *
6198 * The library currently contains the following styling flags for general use:
6199 *
6200 * - **progressive**: Progressive styling is applied to convey that the widget will move the user forward in a process.
6201 * - **destructive**: Destructive styling is applied to convey that the widget will remove something.
6202 * - **constructive**: Constructive styling is applied to convey that the widget will create something.
6203 *
6204 * The flags affect the appearance of the buttons:
6205 *
6206 * @example
6207 * // FlaggedElement is mixed into ButtonWidget to provide styling flags
6208 * var button1 = new OO.ui.ButtonWidget( {
6209 * label: 'Constructive',
6210 * flags: 'constructive'
6211 * } );
6212 * var button2 = new OO.ui.ButtonWidget( {
6213 * label: 'Destructive',
6214 * flags: 'destructive'
6215 * } );
6216 * var button3 = new OO.ui.ButtonWidget( {
6217 * label: 'Progressive',
6218 * flags: 'progressive'
6219 * } );
6220 * $( 'body' ).append( button1.$element, button2.$element, button3.$element );
6221 *
6222 * {@link OO.ui.ActionWidget ActionWidgets}, which are a special kind of button that execute an action, use these flags: **primary** and **safe**.
6223 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information.
6224 *
6225 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Flagged
6226 *
6227 * @abstract
6228 * @class
6229 *
6230 * @constructor
6231 * @param {Object} [config] Configuration options
6232 * @cfg {string|string[]} [flags] The name or names of the flags (e.g., 'constructive' or 'primary') to apply.
6233 * Please see the [OOjs UI documentation on MediaWiki] [2] for more information about available flags.
6234 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Flagged
6235 * @cfg {jQuery} [$flagged] The flagged element. By default,
6236 * the flagged functionality is applied to the element created by the class ($element).
6237 * If a different element is specified, the flagged functionality will be applied to it instead.
6238 */
6239 OO.ui.mixin.FlaggedElement = function OoUiMixinFlaggedElement( config ) {
6240 // Configuration initialization
6241 config = config || {};
6242
6243 // Properties
6244 this.flags = {};
6245 this.$flagged = null;
6246
6247 // Initialization
6248 this.setFlags( config.flags );
6249 this.setFlaggedElement( config.$flagged || this.$element );
6250 };
6251
6252 /* Events */
6253
6254 /**
6255 * @event flag
6256 * A flag event is emitted when the #clearFlags or #setFlags methods are used. The `changes`
6257 * parameter contains the name of each modified flag and indicates whether it was
6258 * added or removed.
6259 *
6260 * @param {Object.<string,boolean>} changes Object keyed by flag name. A Boolean `true` indicates
6261 * that the flag was added, `false` that the flag was removed.
6262 */
6263
6264 /* Methods */
6265
6266 /**
6267 * Set the flagged element.
6268 *
6269 * This method is used to retarget a flagged mixin so that its functionality applies to the specified element.
6270 * If an element is already set, the method will remove the mixin’s effect on that element.
6271 *
6272 * @param {jQuery} $flagged Element that should be flagged
6273 */
6274 OO.ui.mixin.FlaggedElement.prototype.setFlaggedElement = function ( $flagged ) {
6275 var classNames = Object.keys( this.flags ).map( function ( flag ) {
6276 return 'oo-ui-flaggedElement-' + flag;
6277 } ).join( ' ' );
6278
6279 if ( this.$flagged ) {
6280 this.$flagged.removeClass( classNames );
6281 }
6282
6283 this.$flagged = $flagged.addClass( classNames );
6284 };
6285
6286 /**
6287 * Check if the specified flag is set.
6288 *
6289 * @param {string} flag Name of flag
6290 * @return {boolean} The flag is set
6291 */
6292 OO.ui.mixin.FlaggedElement.prototype.hasFlag = function ( flag ) {
6293 // This may be called before the constructor, thus before this.flags is set
6294 return this.flags && ( flag in this.flags );
6295 };
6296
6297 /**
6298 * Get the names of all flags set.
6299 *
6300 * @return {string[]} Flag names
6301 */
6302 OO.ui.mixin.FlaggedElement.prototype.getFlags = function () {
6303 // This may be called before the constructor, thus before this.flags is set
6304 return Object.keys( this.flags || {} );
6305 };
6306
6307 /**
6308 * Clear all flags.
6309 *
6310 * @chainable
6311 * @fires flag
6312 */
6313 OO.ui.mixin.FlaggedElement.prototype.clearFlags = function () {
6314 var flag, className,
6315 changes = {},
6316 remove = [],
6317 classPrefix = 'oo-ui-flaggedElement-';
6318
6319 for ( flag in this.flags ) {
6320 className = classPrefix + flag;
6321 changes[ flag ] = false;
6322 delete this.flags[ flag ];
6323 remove.push( className );
6324 }
6325
6326 if ( this.$flagged ) {
6327 this.$flagged.removeClass( remove.join( ' ' ) );
6328 }
6329
6330 this.updateThemeClasses();
6331 this.emit( 'flag', changes );
6332
6333 return this;
6334 };
6335
6336 /**
6337 * Add one or more flags.
6338 *
6339 * @param {string|string[]|Object.<string, boolean>} flags A flag name, an array of flag names,
6340 * or an object keyed by flag name with a boolean value that indicates whether the flag should
6341 * be added (`true`) or removed (`false`).
6342 * @chainable
6343 * @fires flag
6344 */
6345 OO.ui.mixin.FlaggedElement.prototype.setFlags = function ( flags ) {
6346 var i, len, flag, className,
6347 changes = {},
6348 add = [],
6349 remove = [],
6350 classPrefix = 'oo-ui-flaggedElement-';
6351
6352 if ( typeof flags === 'string' ) {
6353 className = classPrefix + flags;
6354 // Set
6355 if ( !this.flags[ flags ] ) {
6356 this.flags[ flags ] = true;
6357 add.push( className );
6358 }
6359 } else if ( Array.isArray( flags ) ) {
6360 for ( i = 0, len = flags.length; i < len; i++ ) {
6361 flag = flags[ i ];
6362 className = classPrefix + flag;
6363 // Set
6364 if ( !this.flags[ flag ] ) {
6365 changes[ flag ] = true;
6366 this.flags[ flag ] = true;
6367 add.push( className );
6368 }
6369 }
6370 } else if ( OO.isPlainObject( flags ) ) {
6371 for ( flag in flags ) {
6372 className = classPrefix + flag;
6373 if ( flags[ flag ] ) {
6374 // Set
6375 if ( !this.flags[ flag ] ) {
6376 changes[ flag ] = true;
6377 this.flags[ flag ] = true;
6378 add.push( className );
6379 }
6380 } else {
6381 // Remove
6382 if ( this.flags[ flag ] ) {
6383 changes[ flag ] = false;
6384 delete this.flags[ flag ];
6385 remove.push( className );
6386 }
6387 }
6388 }
6389 }
6390
6391 if ( this.$flagged ) {
6392 this.$flagged
6393 .addClass( add.join( ' ' ) )
6394 .removeClass( remove.join( ' ' ) );
6395 }
6396
6397 this.updateThemeClasses();
6398 this.emit( 'flag', changes );
6399
6400 return this;
6401 };
6402
6403 /**
6404 * TitledElement is mixed into other classes to provide a `title` attribute.
6405 * Titles are rendered by the browser and are made visible when the user moves
6406 * the mouse over the element. Titles are not visible on touch devices.
6407 *
6408 * @example
6409 * // TitledElement provides a 'title' attribute to the
6410 * // ButtonWidget class
6411 * var button = new OO.ui.ButtonWidget( {
6412 * label: 'Button with Title',
6413 * title: 'I am a button'
6414 * } );
6415 * $( 'body' ).append( button.$element );
6416 *
6417 * @abstract
6418 * @class
6419 *
6420 * @constructor
6421 * @param {Object} [config] Configuration options
6422 * @cfg {jQuery} [$titled] The element to which the `title` attribute is applied.
6423 * If this config is omitted, the title functionality is applied to $element, the
6424 * element created by the class.
6425 * @cfg {string|Function} [title] The title text or a function that returns text. If
6426 * this config is omitted, the value of the {@link #static-title static title} property is used.
6427 */
6428 OO.ui.mixin.TitledElement = function OoUiMixinTitledElement( config ) {
6429 // Configuration initialization
6430 config = config || {};
6431
6432 // Properties
6433 this.$titled = null;
6434 this.title = null;
6435
6436 // Initialization
6437 this.setTitle( config.title || this.constructor.static.title );
6438 this.setTitledElement( config.$titled || this.$element );
6439 };
6440
6441 /* Setup */
6442
6443 OO.initClass( OO.ui.mixin.TitledElement );
6444
6445 /* Static Properties */
6446
6447 /**
6448 * The title text, a function that returns text, or `null` for no title. The value of the static property
6449 * is overridden if the #title config option is used.
6450 *
6451 * @static
6452 * @inheritable
6453 * @property {string|Function|null}
6454 */
6455 OO.ui.mixin.TitledElement.static.title = null;
6456
6457 /* Methods */
6458
6459 /**
6460 * Set the titled element.
6461 *
6462 * This method is used to retarget a titledElement mixin so that its functionality applies to the specified element.
6463 * If an element is already set, the mixin’s effect on that element is removed before the new element is set up.
6464 *
6465 * @param {jQuery} $titled Element that should use the 'titled' functionality
6466 */
6467 OO.ui.mixin.TitledElement.prototype.setTitledElement = function ( $titled ) {
6468 if ( this.$titled ) {
6469 this.$titled.removeAttr( 'title' );
6470 }
6471
6472 this.$titled = $titled;
6473 if ( this.title ) {
6474 this.$titled.attr( 'title', this.title );
6475 }
6476 };
6477
6478 /**
6479 * Set title.
6480 *
6481 * @param {string|Function|null} title Title text, a function that returns text, or `null` for no title
6482 * @chainable
6483 */
6484 OO.ui.mixin.TitledElement.prototype.setTitle = function ( title ) {
6485 title = typeof title === 'string' ? OO.ui.resolveMsg( title ) : null;
6486
6487 if ( this.title !== title ) {
6488 if ( this.$titled ) {
6489 if ( title !== null ) {
6490 this.$titled.attr( 'title', title );
6491 } else {
6492 this.$titled.removeAttr( 'title' );
6493 }
6494 }
6495 this.title = title;
6496 }
6497
6498 return this;
6499 };
6500
6501 /**
6502 * Get title.
6503 *
6504 * @return {string} Title string
6505 */
6506 OO.ui.mixin.TitledElement.prototype.getTitle = function () {
6507 return this.title;
6508 };
6509
6510 /**
6511 * Element that can be automatically clipped to visible boundaries.
6512 *
6513 * Whenever the element's natural height changes, you have to call
6514 * {@link OO.ui.mixin.ClippableElement#clip} to make sure it's still
6515 * clipping correctly.
6516 *
6517 * @abstract
6518 * @class
6519 *
6520 * @constructor
6521 * @param {Object} [config] Configuration options
6522 * @cfg {jQuery} [$clippable] Nodes to clip, assigned to #$clippable, omit to use #$element
6523 */
6524 OO.ui.mixin.ClippableElement = function OoUiMixinClippableElement( config ) {
6525 // Configuration initialization
6526 config = config || {};
6527
6528 // Properties
6529 this.$clippable = null;
6530 this.clipping = false;
6531 this.clippedHorizontally = false;
6532 this.clippedVertically = false;
6533 this.$clippableContainer = null;
6534 this.$clippableScroller = null;
6535 this.$clippableWindow = null;
6536 this.idealWidth = null;
6537 this.idealHeight = null;
6538 this.onClippableContainerScrollHandler = this.clip.bind( this );
6539 this.onClippableWindowResizeHandler = this.clip.bind( this );
6540
6541 // Initialization
6542 this.setClippableElement( config.$clippable || this.$element );
6543 };
6544
6545 /* Methods */
6546
6547 /**
6548 * Set clippable element.
6549 *
6550 * If an element is already set, it will be cleaned up before setting up the new element.
6551 *
6552 * @param {jQuery} $clippable Element to make clippable
6553 */
6554 OO.ui.mixin.ClippableElement.prototype.setClippableElement = function ( $clippable ) {
6555 if ( this.$clippable ) {
6556 this.$clippable.removeClass( 'oo-ui-clippableElement-clippable' );
6557 this.$clippable.css( { width: '', height: '', overflowX: '', overflowY: '' } );
6558 OO.ui.Element.static.reconsiderScrollbars( this.$clippable[ 0 ] );
6559 }
6560
6561 this.$clippable = $clippable.addClass( 'oo-ui-clippableElement-clippable' );
6562 this.clip();
6563 };
6564
6565 /**
6566 * Toggle clipping.
6567 *
6568 * Do not turn clipping on until after the element is attached to the DOM and visible.
6569 *
6570 * @param {boolean} [clipping] Enable clipping, omit to toggle
6571 * @chainable
6572 */
6573 OO.ui.mixin.ClippableElement.prototype.toggleClipping = function ( clipping ) {
6574 clipping = clipping === undefined ? !this.clipping : !!clipping;
6575
6576 if ( this.clipping !== clipping ) {
6577 this.clipping = clipping;
6578 if ( clipping ) {
6579 this.$clippableContainer = $( this.getClosestScrollableElementContainer() );
6580 // If the clippable container is the root, we have to listen to scroll events and check
6581 // jQuery.scrollTop on the window because of browser inconsistencies
6582 this.$clippableScroller = this.$clippableContainer.is( 'html, body' ) ?
6583 $( OO.ui.Element.static.getWindow( this.$clippableContainer ) ) :
6584 this.$clippableContainer;
6585 this.$clippableScroller.on( 'scroll', this.onClippableContainerScrollHandler );
6586 this.$clippableWindow = $( this.getElementWindow() )
6587 .on( 'resize', this.onClippableWindowResizeHandler );
6588 // Initial clip after visible
6589 this.clip();
6590 } else {
6591 this.$clippable.css( { width: '', height: '', overflowX: '', overflowY: '' } );
6592 OO.ui.Element.static.reconsiderScrollbars( this.$clippable[ 0 ] );
6593
6594 this.$clippableContainer = null;
6595 this.$clippableScroller.off( 'scroll', this.onClippableContainerScrollHandler );
6596 this.$clippableScroller = null;
6597 this.$clippableWindow.off( 'resize', this.onClippableWindowResizeHandler );
6598 this.$clippableWindow = null;
6599 }
6600 }
6601
6602 return this;
6603 };
6604
6605 /**
6606 * Check if the element will be clipped to fit the visible area of the nearest scrollable container.
6607 *
6608 * @return {boolean} Element will be clipped to the visible area
6609 */
6610 OO.ui.mixin.ClippableElement.prototype.isClipping = function () {
6611 return this.clipping;
6612 };
6613
6614 /**
6615 * Check if the bottom or right of the element is being clipped by the nearest scrollable container.
6616 *
6617 * @return {boolean} Part of the element is being clipped
6618 */
6619 OO.ui.mixin.ClippableElement.prototype.isClipped = function () {
6620 return this.clippedHorizontally || this.clippedVertically;
6621 };
6622
6623 /**
6624 * Check if the right of the element is being clipped by the nearest scrollable container.
6625 *
6626 * @return {boolean} Part of the element is being clipped
6627 */
6628 OO.ui.mixin.ClippableElement.prototype.isClippedHorizontally = function () {
6629 return this.clippedHorizontally;
6630 };
6631
6632 /**
6633 * Check if the bottom of the element is being clipped by the nearest scrollable container.
6634 *
6635 * @return {boolean} Part of the element is being clipped
6636 */
6637 OO.ui.mixin.ClippableElement.prototype.isClippedVertically = function () {
6638 return this.clippedVertically;
6639 };
6640
6641 /**
6642 * Set the ideal size. These are the dimensions the element will have when it's not being clipped.
6643 *
6644 * @param {number|string} [width] Width as a number of pixels or CSS string with unit suffix
6645 * @param {number|string} [height] Height as a number of pixels or CSS string with unit suffix
6646 */
6647 OO.ui.mixin.ClippableElement.prototype.setIdealSize = function ( width, height ) {
6648 this.idealWidth = width;
6649 this.idealHeight = height;
6650
6651 if ( !this.clipping ) {
6652 // Update dimensions
6653 this.$clippable.css( { width: width, height: height } );
6654 }
6655 // While clipping, idealWidth and idealHeight are not considered
6656 };
6657
6658 /**
6659 * Clip element to visible boundaries and allow scrolling when needed. Call this method when
6660 * the element's natural height changes.
6661 *
6662 * Element will be clipped the bottom or right of the element is within 10px of the edge of, or
6663 * overlapped by, the visible area of the nearest scrollable container.
6664 *
6665 * @chainable
6666 */
6667 OO.ui.mixin.ClippableElement.prototype.clip = function () {
6668 if ( !this.clipping ) {
6669 // this.$clippableContainer and this.$clippableWindow are null, so the below will fail
6670 return this;
6671 }
6672
6673 var buffer = 7, // Chosen by fair dice roll
6674 cOffset = this.$clippable.offset(),
6675 $container = this.$clippableContainer.is( 'html, body' ) ?
6676 this.$clippableWindow : this.$clippableContainer,
6677 ccOffset = $container.offset() || { top: 0, left: 0 },
6678 ccHeight = $container.innerHeight() - buffer,
6679 ccWidth = $container.innerWidth() - buffer,
6680 cWidth = this.$clippable.outerWidth() + buffer,
6681 scrollerIsWindow = this.$clippableScroller[0] === this.$clippableWindow[0],
6682 scrollTop = scrollerIsWindow ? this.$clippableScroller.scrollTop() : 0,
6683 scrollLeft = scrollerIsWindow ? this.$clippableScroller.scrollLeft() : 0,
6684 desiredWidth = cOffset.left < 0 ?
6685 cWidth + cOffset.left :
6686 ( ccOffset.left + scrollLeft + ccWidth ) - cOffset.left,
6687 desiredHeight = ( ccOffset.top + scrollTop + ccHeight ) - cOffset.top,
6688 naturalWidth = this.$clippable.prop( 'scrollWidth' ),
6689 naturalHeight = this.$clippable.prop( 'scrollHeight' ),
6690 clipWidth = desiredWidth < naturalWidth,
6691 clipHeight = desiredHeight < naturalHeight;
6692
6693 if ( clipWidth ) {
6694 this.$clippable.css( { overflowX: 'scroll', width: desiredWidth } );
6695 } else {
6696 this.$clippable.css( { width: this.idealWidth || '', overflowX: '' } );
6697 }
6698 if ( clipHeight ) {
6699 this.$clippable.css( { overflowY: 'scroll', height: desiredHeight } );
6700 } else {
6701 this.$clippable.css( { height: this.idealHeight || '', overflowY: '' } );
6702 }
6703
6704 // If we stopped clipping in at least one of the dimensions
6705 if ( ( this.clippedHorizontally && !clipWidth ) || ( this.clippedVertically && !clipHeight ) ) {
6706 OO.ui.Element.static.reconsiderScrollbars( this.$clippable[ 0 ] );
6707 }
6708
6709 this.clippedHorizontally = clipWidth;
6710 this.clippedVertically = clipHeight;
6711
6712 return this;
6713 };
6714
6715 /**
6716 * Tools, together with {@link OO.ui.ToolGroup toolgroups}, constitute {@link OO.ui.Toolbar toolbars}.
6717 * Each tool is configured with a static name, title, and icon and is customized with the command to carry
6718 * out when the tool is selected. Tools must also be registered with a {@link OO.ui.ToolFactory tool factory},
6719 * which creates the tools on demand.
6720 *
6721 * Tools are added to toolgroups ({@link OO.ui.ListToolGroup ListToolGroup},
6722 * {@link OO.ui.BarToolGroup BarToolGroup}, or {@link OO.ui.MenuToolGroup MenuToolGroup}), which determine how
6723 * the tool is displayed in the toolbar. See {@link OO.ui.Toolbar toolbars} for an example.
6724 *
6725 * For more information, please see the [OOjs UI documentation on MediaWiki][1].
6726 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
6727 *
6728 * @abstract
6729 * @class
6730 * @extends OO.ui.Widget
6731 * @mixins OO.ui.mixin.IconElement
6732 * @mixins OO.ui.mixin.FlaggedElement
6733 * @mixins OO.ui.mixin.TabIndexedElement
6734 *
6735 * @constructor
6736 * @param {OO.ui.ToolGroup} toolGroup
6737 * @param {Object} [config] Configuration options
6738 * @cfg {string|Function} [title] Title text or a function that returns text. If this config is omitted, the value of
6739 * the {@link #static-title static title} property is used.
6740 *
6741 * The title is used in different ways depending on the type of toolgroup that contains the tool. The
6742 * 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
6743 * part of a {@link OO.ui.ListToolGroup list} or {@link OO.ui.MenuToolGroup menu} toolgroup.
6744 *
6745 * For bar toolgroups, a description of the accelerator key is appended to the title if an accelerator key
6746 * is associated with an action by the same name as the tool and accelerator functionality has been added to the application.
6747 * To add accelerator key functionality, you must subclass OO.ui.Toolbar and override the {@link OO.ui.Toolbar#getToolAccelerator getToolAccelerator} method.
6748 */
6749 OO.ui.Tool = function OoUiTool( toolGroup, config ) {
6750 // Allow passing positional parameters inside the config object
6751 if ( OO.isPlainObject( toolGroup ) && config === undefined ) {
6752 config = toolGroup;
6753 toolGroup = config.toolGroup;
6754 }
6755
6756 // Configuration initialization
6757 config = config || {};
6758
6759 // Parent constructor
6760 OO.ui.Tool.parent.call( this, config );
6761
6762 // Properties
6763 this.toolGroup = toolGroup;
6764 this.toolbar = this.toolGroup.getToolbar();
6765 this.active = false;
6766 this.$title = $( '<span>' );
6767 this.$accel = $( '<span>' );
6768 this.$link = $( '<a>' );
6769 this.title = null;
6770
6771 // Mixin constructors
6772 OO.ui.mixin.IconElement.call( this, config );
6773 OO.ui.mixin.FlaggedElement.call( this, config );
6774 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$link } ) );
6775
6776 // Events
6777 this.toolbar.connect( this, { updateState: 'onUpdateState' } );
6778
6779 // Initialization
6780 this.$title.addClass( 'oo-ui-tool-title' );
6781 this.$accel
6782 .addClass( 'oo-ui-tool-accel' )
6783 .prop( {
6784 // This may need to be changed if the key names are ever localized,
6785 // but for now they are essentially written in English
6786 dir: 'ltr',
6787 lang: 'en'
6788 } );
6789 this.$link
6790 .addClass( 'oo-ui-tool-link' )
6791 .append( this.$icon, this.$title, this.$accel )
6792 .attr( 'role', 'button' );
6793 this.$element
6794 .data( 'oo-ui-tool', this )
6795 .addClass(
6796 'oo-ui-tool ' + 'oo-ui-tool-name-' +
6797 this.constructor.static.name.replace( /^([^\/]+)\/([^\/]+).*$/, '$1-$2' )
6798 )
6799 .toggleClass( 'oo-ui-tool-with-label', this.constructor.static.displayBothIconAndLabel )
6800 .append( this.$link );
6801 this.setTitle( config.title || this.constructor.static.title );
6802 };
6803
6804 /* Setup */
6805
6806 OO.inheritClass( OO.ui.Tool, OO.ui.Widget );
6807 OO.mixinClass( OO.ui.Tool, OO.ui.mixin.IconElement );
6808 OO.mixinClass( OO.ui.Tool, OO.ui.mixin.FlaggedElement );
6809 OO.mixinClass( OO.ui.Tool, OO.ui.mixin.TabIndexedElement );
6810
6811 /* Static Properties */
6812
6813 /**
6814 * @static
6815 * @inheritdoc
6816 */
6817 OO.ui.Tool.static.tagName = 'span';
6818
6819 /**
6820 * Symbolic name of tool.
6821 *
6822 * The symbolic name is used internally to register the tool with a {@link OO.ui.ToolFactory ToolFactory}. It can
6823 * also be used when adding tools to toolgroups.
6824 *
6825 * @abstract
6826 * @static
6827 * @inheritable
6828 * @property {string}
6829 */
6830 OO.ui.Tool.static.name = '';
6831
6832 /**
6833 * Symbolic name of the group.
6834 *
6835 * The group name is used to associate tools with each other so that they can be selected later by
6836 * a {@link OO.ui.ToolGroup toolgroup}.
6837 *
6838 * @abstract
6839 * @static
6840 * @inheritable
6841 * @property {string}
6842 */
6843 OO.ui.Tool.static.group = '';
6844
6845 /**
6846 * 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.
6847 *
6848 * @abstract
6849 * @static
6850 * @inheritable
6851 * @property {string|Function}
6852 */
6853 OO.ui.Tool.static.title = '';
6854
6855 /**
6856 * Display both icon and label when the tool is used in a {@link OO.ui.BarToolGroup bar} toolgroup.
6857 * Normally only the icon is displayed, or only the label if no icon is given.
6858 *
6859 * @static
6860 * @inheritable
6861 * @property {boolean}
6862 */
6863 OO.ui.Tool.static.displayBothIconAndLabel = false;
6864
6865 /**
6866 * Add tool to catch-all groups automatically.
6867 *
6868 * A catch-all group, which contains all tools that do not currently belong to a toolgroup,
6869 * can be included in a toolgroup using the wildcard selector, an asterisk (*).
6870 *
6871 * @static
6872 * @inheritable
6873 * @property {boolean}
6874 */
6875 OO.ui.Tool.static.autoAddToCatchall = true;
6876
6877 /**
6878 * Add tool to named groups automatically.
6879 *
6880 * By default, tools that are configured with a static ‘group’ property are added
6881 * to that group and will be selected when the symbolic name of the group is specified (e.g., when
6882 * toolgroups include tools by group name).
6883 *
6884 * @static
6885 * @property {boolean}
6886 * @inheritable
6887 */
6888 OO.ui.Tool.static.autoAddToGroup = true;
6889
6890 /**
6891 * Check if this tool is compatible with given data.
6892 *
6893 * This is a stub that can be overriden to provide support for filtering tools based on an
6894 * arbitrary piece of information (e.g., where the cursor is in a document). The implementation
6895 * must also call this method so that the compatibility check can be performed.
6896 *
6897 * @static
6898 * @inheritable
6899 * @param {Mixed} data Data to check
6900 * @return {boolean} Tool can be used with data
6901 */
6902 OO.ui.Tool.static.isCompatibleWith = function () {
6903 return false;
6904 };
6905
6906 /* Methods */
6907
6908 /**
6909 * Handle the toolbar state being updated.
6910 *
6911 * This is an abstract method that must be overridden in a concrete subclass.
6912 *
6913 * @protected
6914 * @abstract
6915 */
6916 OO.ui.Tool.prototype.onUpdateState = function () {
6917 throw new Error(
6918 'OO.ui.Tool.onUpdateState not implemented in this subclass:' + this.constructor
6919 );
6920 };
6921
6922 /**
6923 * Handle the tool being selected.
6924 *
6925 * This is an abstract method that must be overridden in a concrete subclass.
6926 *
6927 * @protected
6928 * @abstract
6929 */
6930 OO.ui.Tool.prototype.onSelect = function () {
6931 throw new Error(
6932 'OO.ui.Tool.onSelect not implemented in this subclass:' + this.constructor
6933 );
6934 };
6935
6936 /**
6937 * Check if the tool is active.
6938 *
6939 * Tools become active when their #onSelect or #onUpdateState handlers change them to appear pressed
6940 * with the #setActive method. Additional CSS is applied to the tool to reflect the active state.
6941 *
6942 * @return {boolean} Tool is active
6943 */
6944 OO.ui.Tool.prototype.isActive = function () {
6945 return this.active;
6946 };
6947
6948 /**
6949 * Make the tool appear active or inactive.
6950 *
6951 * This method should be called within #onSelect or #onUpdateState event handlers to make the tool
6952 * appear pressed or not.
6953 *
6954 * @param {boolean} state Make tool appear active
6955 */
6956 OO.ui.Tool.prototype.setActive = function ( state ) {
6957 this.active = !!state;
6958 if ( this.active ) {
6959 this.$element.addClass( 'oo-ui-tool-active' );
6960 } else {
6961 this.$element.removeClass( 'oo-ui-tool-active' );
6962 }
6963 };
6964
6965 /**
6966 * Set the tool #title.
6967 *
6968 * @param {string|Function} title Title text or a function that returns text
6969 * @chainable
6970 */
6971 OO.ui.Tool.prototype.setTitle = function ( title ) {
6972 this.title = OO.ui.resolveMsg( title );
6973 this.updateTitle();
6974 return this;
6975 };
6976
6977 /**
6978 * Get the tool #title.
6979 *
6980 * @return {string} Title text
6981 */
6982 OO.ui.Tool.prototype.getTitle = function () {
6983 return this.title;
6984 };
6985
6986 /**
6987 * Get the tool's symbolic name.
6988 *
6989 * @return {string} Symbolic name of tool
6990 */
6991 OO.ui.Tool.prototype.getName = function () {
6992 return this.constructor.static.name;
6993 };
6994
6995 /**
6996 * Update the title.
6997 */
6998 OO.ui.Tool.prototype.updateTitle = function () {
6999 var titleTooltips = this.toolGroup.constructor.static.titleTooltips,
7000 accelTooltips = this.toolGroup.constructor.static.accelTooltips,
7001 accel = this.toolbar.getToolAccelerator( this.constructor.static.name ),
7002 tooltipParts = [];
7003
7004 this.$title.text( this.title );
7005 this.$accel.text( accel );
7006
7007 if ( titleTooltips && typeof this.title === 'string' && this.title.length ) {
7008 tooltipParts.push( this.title );
7009 }
7010 if ( accelTooltips && typeof accel === 'string' && accel.length ) {
7011 tooltipParts.push( accel );
7012 }
7013 if ( tooltipParts.length ) {
7014 this.$link.attr( 'title', tooltipParts.join( ' ' ) );
7015 } else {
7016 this.$link.removeAttr( 'title' );
7017 }
7018 };
7019
7020 /**
7021 * Destroy tool.
7022 *
7023 * Destroying the tool removes all event handlers and the tool’s DOM elements.
7024 * Call this method whenever you are done using a tool.
7025 */
7026 OO.ui.Tool.prototype.destroy = function () {
7027 this.toolbar.disconnect( this );
7028 this.$element.remove();
7029 };
7030
7031 /**
7032 * Toolbars are complex interface components that permit users to easily access a variety
7033 * of {@link OO.ui.Tool tools} (e.g., formatting commands) and actions, which are additional commands that are
7034 * part of the toolbar, but not configured as tools.
7035 *
7036 * Individual tools are customized and then registered with a {@link OO.ui.ToolFactory tool factory}, which creates
7037 * the tools on demand. Each tool has a symbolic name (used when registering the tool), a title (e.g., ‘Insert
7038 * picture’), and an icon.
7039 *
7040 * Individual tools are organized in {@link OO.ui.ToolGroup toolgroups}, which can be {@link OO.ui.MenuToolGroup menus}
7041 * of tools, {@link OO.ui.ListToolGroup lists} of tools, or a single {@link OO.ui.BarToolGroup bar} of tools.
7042 * The arrangement and order of the toolgroups is customized when the toolbar is set up. Tools can be presented in
7043 * any order, but each can only appear once in the toolbar.
7044 *
7045 * The following is an example of a basic toolbar.
7046 *
7047 * @example
7048 * // Example of a toolbar
7049 * // Create the toolbar
7050 * var toolFactory = new OO.ui.ToolFactory();
7051 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
7052 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
7053 *
7054 * // We will be placing status text in this element when tools are used
7055 * var $area = $( '<p>' ).text( 'Toolbar example' );
7056 *
7057 * // Define the tools that we're going to place in our toolbar
7058 *
7059 * // Create a class inheriting from OO.ui.Tool
7060 * function PictureTool() {
7061 * PictureTool.parent.apply( this, arguments );
7062 * }
7063 * OO.inheritClass( PictureTool, OO.ui.Tool );
7064 * // Each tool must have a 'name' (used as an internal identifier, see later) and at least one
7065 * // of 'icon' and 'title' (displayed icon and text).
7066 * PictureTool.static.name = 'picture';
7067 * PictureTool.static.icon = 'picture';
7068 * PictureTool.static.title = 'Insert picture';
7069 * // Defines the action that will happen when this tool is selected (clicked).
7070 * PictureTool.prototype.onSelect = function () {
7071 * $area.text( 'Picture tool clicked!' );
7072 * // Never display this tool as "active" (selected).
7073 * this.setActive( false );
7074 * };
7075 * // Make this tool available in our toolFactory and thus our toolbar
7076 * toolFactory.register( PictureTool );
7077 *
7078 * // Register two more tools, nothing interesting here
7079 * function SettingsTool() {
7080 * SettingsTool.parent.apply( this, arguments );
7081 * }
7082 * OO.inheritClass( SettingsTool, OO.ui.Tool );
7083 * SettingsTool.static.name = 'settings';
7084 * SettingsTool.static.icon = 'settings';
7085 * SettingsTool.static.title = 'Change settings';
7086 * SettingsTool.prototype.onSelect = function () {
7087 * $area.text( 'Settings tool clicked!' );
7088 * this.setActive( false );
7089 * };
7090 * toolFactory.register( SettingsTool );
7091 *
7092 * // Register two more tools, nothing interesting here
7093 * function StuffTool() {
7094 * StuffTool.parent.apply( this, arguments );
7095 * }
7096 * OO.inheritClass( StuffTool, OO.ui.Tool );
7097 * StuffTool.static.name = 'stuff';
7098 * StuffTool.static.icon = 'ellipsis';
7099 * StuffTool.static.title = 'More stuff';
7100 * StuffTool.prototype.onSelect = function () {
7101 * $area.text( 'More stuff tool clicked!' );
7102 * this.setActive( false );
7103 * };
7104 * toolFactory.register( StuffTool );
7105 *
7106 * // This is a PopupTool. Rather than having a custom 'onSelect' action, it will display a
7107 * // little popup window (a PopupWidget).
7108 * function HelpTool( toolGroup, config ) {
7109 * OO.ui.PopupTool.call( this, toolGroup, $.extend( { popup: {
7110 * padded: true,
7111 * label: 'Help',
7112 * head: true
7113 * } }, config ) );
7114 * this.popup.$body.append( '<p>I am helpful!</p>' );
7115 * }
7116 * OO.inheritClass( HelpTool, OO.ui.PopupTool );
7117 * HelpTool.static.name = 'help';
7118 * HelpTool.static.icon = 'help';
7119 * HelpTool.static.title = 'Help';
7120 * toolFactory.register( HelpTool );
7121 *
7122 * // Finally define which tools and in what order appear in the toolbar. Each tool may only be
7123 * // used once (but not all defined tools must be used).
7124 * toolbar.setup( [
7125 * {
7126 * // 'bar' tool groups display tools' icons only, side-by-side.
7127 * type: 'bar',
7128 * include: [ 'picture', 'help' ]
7129 * },
7130 * {
7131 * // 'list' tool groups display both the titles and icons, in a dropdown list.
7132 * type: 'list',
7133 * indicator: 'down',
7134 * label: 'More',
7135 * include: [ 'settings', 'stuff' ]
7136 * }
7137 * // Note how the tools themselves are toolgroup-agnostic - the same tool can be displayed
7138 * // either in a 'list' or a 'bar'. There is a 'menu' tool group too, not showcased here,
7139 * // since it's more complicated to use. (See the next example snippet on this page.)
7140 * ] );
7141 *
7142 * // Create some UI around the toolbar and place it in the document
7143 * var frame = new OO.ui.PanelLayout( {
7144 * expanded: false,
7145 * framed: true
7146 * } );
7147 * var contentFrame = new OO.ui.PanelLayout( {
7148 * expanded: false,
7149 * padded: true
7150 * } );
7151 * frame.$element.append(
7152 * toolbar.$element,
7153 * contentFrame.$element.append( $area )
7154 * );
7155 * $( 'body' ).append( frame.$element );
7156 *
7157 * // Here is where the toolbar is actually built. This must be done after inserting it into the
7158 * // document.
7159 * toolbar.initialize();
7160 *
7161 * The following example extends the previous one to illustrate 'menu' toolgroups and the usage of
7162 * 'updateState' event.
7163 *
7164 * @example
7165 * // Create the toolbar
7166 * var toolFactory = new OO.ui.ToolFactory();
7167 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
7168 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
7169 *
7170 * // We will be placing status text in this element when tools are used
7171 * var $area = $( '<p>' ).text( 'Toolbar example' );
7172 *
7173 * // Define the tools that we're going to place in our toolbar
7174 *
7175 * // Create a class inheriting from OO.ui.Tool
7176 * function PictureTool() {
7177 * PictureTool.parent.apply( this, arguments );
7178 * }
7179 * OO.inheritClass( PictureTool, OO.ui.Tool );
7180 * // Each tool must have a 'name' (used as an internal identifier, see later) and at least one
7181 * // of 'icon' and 'title' (displayed icon and text).
7182 * PictureTool.static.name = 'picture';
7183 * PictureTool.static.icon = 'picture';
7184 * PictureTool.static.title = 'Insert picture';
7185 * // Defines the action that will happen when this tool is selected (clicked).
7186 * PictureTool.prototype.onSelect = function () {
7187 * $area.text( 'Picture tool clicked!' );
7188 * // Never display this tool as "active" (selected).
7189 * this.setActive( false );
7190 * };
7191 * // The toolbar can be synchronized with the state of some external stuff, like a text
7192 * // editor's editing area, highlighting the tools (e.g. a 'bold' tool would be shown as active
7193 * // when the text cursor was inside bolded text). Here we simply disable this feature.
7194 * PictureTool.prototype.onUpdateState = function () {
7195 * };
7196 * // Make this tool available in our toolFactory and thus our toolbar
7197 * toolFactory.register( PictureTool );
7198 *
7199 * // Register two more tools, nothing interesting here
7200 * function SettingsTool() {
7201 * SettingsTool.parent.apply( this, arguments );
7202 * this.reallyActive = false;
7203 * }
7204 * OO.inheritClass( SettingsTool, OO.ui.Tool );
7205 * SettingsTool.static.name = 'settings';
7206 * SettingsTool.static.icon = 'settings';
7207 * SettingsTool.static.title = 'Change settings';
7208 * SettingsTool.prototype.onSelect = function () {
7209 * $area.text( 'Settings tool clicked!' );
7210 * // Toggle the active state on each click
7211 * this.reallyActive = !this.reallyActive;
7212 * this.setActive( this.reallyActive );
7213 * // To update the menu label
7214 * this.toolbar.emit( 'updateState' );
7215 * };
7216 * SettingsTool.prototype.onUpdateState = function () {
7217 * };
7218 * toolFactory.register( SettingsTool );
7219 *
7220 * // Register two more tools, nothing interesting here
7221 * function StuffTool() {
7222 * StuffTool.parent.apply( this, arguments );
7223 * this.reallyActive = false;
7224 * }
7225 * OO.inheritClass( StuffTool, OO.ui.Tool );
7226 * StuffTool.static.name = 'stuff';
7227 * StuffTool.static.icon = 'ellipsis';
7228 * StuffTool.static.title = 'More stuff';
7229 * StuffTool.prototype.onSelect = function () {
7230 * $area.text( 'More stuff tool clicked!' );
7231 * // Toggle the active state on each click
7232 * this.reallyActive = !this.reallyActive;
7233 * this.setActive( this.reallyActive );
7234 * // To update the menu label
7235 * this.toolbar.emit( 'updateState' );
7236 * };
7237 * StuffTool.prototype.onUpdateState = function () {
7238 * };
7239 * toolFactory.register( StuffTool );
7240 *
7241 * // This is a PopupTool. Rather than having a custom 'onSelect' action, it will display a
7242 * // little popup window (a PopupWidget). 'onUpdateState' is also already implemented.
7243 * function HelpTool( toolGroup, config ) {
7244 * OO.ui.PopupTool.call( this, toolGroup, $.extend( { popup: {
7245 * padded: true,
7246 * label: 'Help',
7247 * head: true
7248 * } }, config ) );
7249 * this.popup.$body.append( '<p>I am helpful!</p>' );
7250 * }
7251 * OO.inheritClass( HelpTool, OO.ui.PopupTool );
7252 * HelpTool.static.name = 'help';
7253 * HelpTool.static.icon = 'help';
7254 * HelpTool.static.title = 'Help';
7255 * toolFactory.register( HelpTool );
7256 *
7257 * // Finally define which tools and in what order appear in the toolbar. Each tool may only be
7258 * // used once (but not all defined tools must be used).
7259 * toolbar.setup( [
7260 * {
7261 * // 'bar' tool groups display tools' icons only, side-by-side.
7262 * type: 'bar',
7263 * include: [ 'picture', 'help' ]
7264 * },
7265 * {
7266 * // 'menu' tool groups display both the titles and icons, in a dropdown menu.
7267 * // Menu label indicates which items are selected.
7268 * type: 'menu',
7269 * indicator: 'down',
7270 * include: [ 'settings', 'stuff' ]
7271 * }
7272 * ] );
7273 *
7274 * // Create some UI around the toolbar and place it in the document
7275 * var frame = new OO.ui.PanelLayout( {
7276 * expanded: false,
7277 * framed: true
7278 * } );
7279 * var contentFrame = new OO.ui.PanelLayout( {
7280 * expanded: false,
7281 * padded: true
7282 * } );
7283 * frame.$element.append(
7284 * toolbar.$element,
7285 * contentFrame.$element.append( $area )
7286 * );
7287 * $( 'body' ).append( frame.$element );
7288 *
7289 * // Here is where the toolbar is actually built. This must be done after inserting it into the
7290 * // document.
7291 * toolbar.initialize();
7292 * toolbar.emit( 'updateState' );
7293 *
7294 * @class
7295 * @extends OO.ui.Element
7296 * @mixins OO.EventEmitter
7297 * @mixins OO.ui.mixin.GroupElement
7298 *
7299 * @constructor
7300 * @param {OO.ui.ToolFactory} toolFactory Factory for creating tools
7301 * @param {OO.ui.ToolGroupFactory} toolGroupFactory Factory for creating toolgroups
7302 * @param {Object} [config] Configuration options
7303 * @cfg {boolean} [actions] Add an actions section to the toolbar. Actions are commands that are included
7304 * in the toolbar, but are not configured as tools. By default, actions are displayed on the right side of
7305 * the toolbar.
7306 * @cfg {boolean} [shadow] Add a shadow below the toolbar.
7307 */
7308 OO.ui.Toolbar = function OoUiToolbar( toolFactory, toolGroupFactory, config ) {
7309 // Allow passing positional parameters inside the config object
7310 if ( OO.isPlainObject( toolFactory ) && config === undefined ) {
7311 config = toolFactory;
7312 toolFactory = config.toolFactory;
7313 toolGroupFactory = config.toolGroupFactory;
7314 }
7315
7316 // Configuration initialization
7317 config = config || {};
7318
7319 // Parent constructor
7320 OO.ui.Toolbar.parent.call( this, config );
7321
7322 // Mixin constructors
7323 OO.EventEmitter.call( this );
7324 OO.ui.mixin.GroupElement.call( this, config );
7325
7326 // Properties
7327 this.toolFactory = toolFactory;
7328 this.toolGroupFactory = toolGroupFactory;
7329 this.groups = [];
7330 this.tools = {};
7331 this.$bar = $( '<div>' );
7332 this.$actions = $( '<div>' );
7333 this.initialized = false;
7334 this.onWindowResizeHandler = this.onWindowResize.bind( this );
7335
7336 // Events
7337 this.$element
7338 .add( this.$bar ).add( this.$group ).add( this.$actions )
7339 .on( 'mousedown keydown', this.onPointerDown.bind( this ) );
7340
7341 // Initialization
7342 this.$group.addClass( 'oo-ui-toolbar-tools' );
7343 if ( config.actions ) {
7344 this.$bar.append( this.$actions.addClass( 'oo-ui-toolbar-actions' ) );
7345 }
7346 this.$bar
7347 .addClass( 'oo-ui-toolbar-bar' )
7348 .append( this.$group, '<div style="clear:both"></div>' );
7349 if ( config.shadow ) {
7350 this.$bar.append( '<div class="oo-ui-toolbar-shadow"></div>' );
7351 }
7352 this.$element.addClass( 'oo-ui-toolbar' ).append( this.$bar );
7353 };
7354
7355 /* Setup */
7356
7357 OO.inheritClass( OO.ui.Toolbar, OO.ui.Element );
7358 OO.mixinClass( OO.ui.Toolbar, OO.EventEmitter );
7359 OO.mixinClass( OO.ui.Toolbar, OO.ui.mixin.GroupElement );
7360
7361 /* Methods */
7362
7363 /**
7364 * Get the tool factory.
7365 *
7366 * @return {OO.ui.ToolFactory} Tool factory
7367 */
7368 OO.ui.Toolbar.prototype.getToolFactory = function () {
7369 return this.toolFactory;
7370 };
7371
7372 /**
7373 * Get the toolgroup factory.
7374 *
7375 * @return {OO.Factory} Toolgroup factory
7376 */
7377 OO.ui.Toolbar.prototype.getToolGroupFactory = function () {
7378 return this.toolGroupFactory;
7379 };
7380
7381 /**
7382 * Handles mouse down events.
7383 *
7384 * @private
7385 * @param {jQuery.Event} e Mouse down event
7386 */
7387 OO.ui.Toolbar.prototype.onPointerDown = function ( e ) {
7388 var $closestWidgetToEvent = $( e.target ).closest( '.oo-ui-widget' ),
7389 $closestWidgetToToolbar = this.$element.closest( '.oo-ui-widget' );
7390 if ( !$closestWidgetToEvent.length || $closestWidgetToEvent[ 0 ] === $closestWidgetToToolbar[ 0 ] ) {
7391 return false;
7392 }
7393 };
7394
7395 /**
7396 * Handle window resize event.
7397 *
7398 * @private
7399 * @param {jQuery.Event} e Window resize event
7400 */
7401 OO.ui.Toolbar.prototype.onWindowResize = function () {
7402 this.$element.toggleClass(
7403 'oo-ui-toolbar-narrow',
7404 this.$bar.width() <= this.narrowThreshold
7405 );
7406 };
7407
7408 /**
7409 * Sets up handles and preloads required information for the toolbar to work.
7410 * This must be called after it is attached to a visible document and before doing anything else.
7411 */
7412 OO.ui.Toolbar.prototype.initialize = function () {
7413 this.initialized = true;
7414 this.narrowThreshold = this.$group.width() + this.$actions.width();
7415 $( this.getElementWindow() ).on( 'resize', this.onWindowResizeHandler );
7416 this.onWindowResize();
7417 };
7418
7419 /**
7420 * Set up the toolbar.
7421 *
7422 * The toolbar is set up with a list of toolgroup configurations that specify the type of
7423 * toolgroup ({@link OO.ui.BarToolGroup bar}, {@link OO.ui.MenuToolGroup menu}, or {@link OO.ui.ListToolGroup list})
7424 * to add and which tools to include, exclude, promote, or demote within that toolgroup. Please
7425 * see {@link OO.ui.ToolGroup toolgroups} for more information about including tools in toolgroups.
7426 *
7427 * @param {Object.<string,Array>} groups List of toolgroup configurations
7428 * @param {Array|string} [groups.include] Tools to include in the toolgroup
7429 * @param {Array|string} [groups.exclude] Tools to exclude from the toolgroup
7430 * @param {Array|string} [groups.promote] Tools to promote to the beginning of the toolgroup
7431 * @param {Array|string} [groups.demote] Tools to demote to the end of the toolgroup
7432 */
7433 OO.ui.Toolbar.prototype.setup = function ( groups ) {
7434 var i, len, type, group,
7435 items = [],
7436 defaultType = 'bar';
7437
7438 // Cleanup previous groups
7439 this.reset();
7440
7441 // Build out new groups
7442 for ( i = 0, len = groups.length; i < len; i++ ) {
7443 group = groups[ i ];
7444 if ( group.include === '*' ) {
7445 // Apply defaults to catch-all groups
7446 if ( group.type === undefined ) {
7447 group.type = 'list';
7448 }
7449 if ( group.label === undefined ) {
7450 group.label = OO.ui.msg( 'ooui-toolbar-more' );
7451 }
7452 }
7453 // Check type has been registered
7454 type = this.getToolGroupFactory().lookup( group.type ) ? group.type : defaultType;
7455 items.push(
7456 this.getToolGroupFactory().create( type, this, group )
7457 );
7458 }
7459 this.addItems( items );
7460 };
7461
7462 /**
7463 * Remove all tools and toolgroups from the toolbar.
7464 */
7465 OO.ui.Toolbar.prototype.reset = function () {
7466 var i, len;
7467
7468 this.groups = [];
7469 this.tools = {};
7470 for ( i = 0, len = this.items.length; i < len; i++ ) {
7471 this.items[ i ].destroy();
7472 }
7473 this.clearItems();
7474 };
7475
7476 /**
7477 * Destroy the toolbar.
7478 *
7479 * Destroying the toolbar removes all event handlers and DOM elements that constitute the toolbar. Call
7480 * this method whenever you are done using a toolbar.
7481 */
7482 OO.ui.Toolbar.prototype.destroy = function () {
7483 $( this.getElementWindow() ).off( 'resize', this.onWindowResizeHandler );
7484 this.reset();
7485 this.$element.remove();
7486 };
7487
7488 /**
7489 * Check if the tool is available.
7490 *
7491 * Available tools are ones that have not yet been added to the toolbar.
7492 *
7493 * @param {string} name Symbolic name of tool
7494 * @return {boolean} Tool is available
7495 */
7496 OO.ui.Toolbar.prototype.isToolAvailable = function ( name ) {
7497 return !this.tools[ name ];
7498 };
7499
7500 /**
7501 * Prevent tool from being used again.
7502 *
7503 * @param {OO.ui.Tool} tool Tool to reserve
7504 */
7505 OO.ui.Toolbar.prototype.reserveTool = function ( tool ) {
7506 this.tools[ tool.getName() ] = tool;
7507 };
7508
7509 /**
7510 * Allow tool to be used again.
7511 *
7512 * @param {OO.ui.Tool} tool Tool to release
7513 */
7514 OO.ui.Toolbar.prototype.releaseTool = function ( tool ) {
7515 delete this.tools[ tool.getName() ];
7516 };
7517
7518 /**
7519 * Get accelerator label for tool.
7520 *
7521 * The OOjs UI library does not contain an accelerator system, but this is the hook for one. To
7522 * use an accelerator system, subclass the toolbar and override this method, which is meant to return a label
7523 * that describes the accelerator keys for the tool passed (by symbolic name) to the method.
7524 *
7525 * @param {string} name Symbolic name of tool
7526 * @return {string|undefined} Tool accelerator label if available
7527 */
7528 OO.ui.Toolbar.prototype.getToolAccelerator = function () {
7529 return undefined;
7530 };
7531
7532 /**
7533 * ToolGroups are collections of {@link OO.ui.Tool tools} that are used in a {@link OO.ui.Toolbar toolbar}.
7534 * The type of toolgroup ({@link OO.ui.ListToolGroup list}, {@link OO.ui.BarToolGroup bar}, or {@link OO.ui.MenuToolGroup menu})
7535 * to which a tool belongs determines how the tool is arranged and displayed in the toolbar. Toolgroups
7536 * themselves are created on demand with a {@link OO.ui.ToolGroupFactory toolgroup factory}.
7537 *
7538 * Toolgroups can contain individual tools, groups of tools, or all available tools:
7539 *
7540 * To include an individual tool (or array of individual tools), specify tools by symbolic name:
7541 *
7542 * include: [ 'tool-name' ] or [ { name: 'tool-name' }]
7543 *
7544 * 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.)
7545 *
7546 * include: [ { group: 'group-name' } ]
7547 *
7548 * To include all tools that are not yet assigned to a toolgroup, use the catch-all selector, an asterisk (*):
7549 *
7550 * include: '*'
7551 *
7552 * See {@link OO.ui.Toolbar toolbars} for a full example. For more information about toolbars in general,
7553 * please see the [OOjs UI documentation on MediaWiki][1].
7554 *
7555 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
7556 *
7557 * @abstract
7558 * @class
7559 * @extends OO.ui.Widget
7560 * @mixins OO.ui.mixin.GroupElement
7561 *
7562 * @constructor
7563 * @param {OO.ui.Toolbar} toolbar
7564 * @param {Object} [config] Configuration options
7565 * @cfg {Array|string} [include=[]] List of tools to include in the toolgroup.
7566 * @cfg {Array|string} [exclude=[]] List of tools to exclude from the toolgroup.
7567 * @cfg {Array|string} [promote=[]] List of tools to promote to the beginning of the toolgroup.
7568 * @cfg {Array|string} [demote=[]] List of tools to demote to the end of the toolgroup.
7569 * This setting is particularly useful when tools have been added to the toolgroup
7570 * en masse (e.g., via the catch-all selector).
7571 */
7572 OO.ui.ToolGroup = function OoUiToolGroup( toolbar, config ) {
7573 // Allow passing positional parameters inside the config object
7574 if ( OO.isPlainObject( toolbar ) && config === undefined ) {
7575 config = toolbar;
7576 toolbar = config.toolbar;
7577 }
7578
7579 // Configuration initialization
7580 config = config || {};
7581
7582 // Parent constructor
7583 OO.ui.ToolGroup.parent.call( this, config );
7584
7585 // Mixin constructors
7586 OO.ui.mixin.GroupElement.call( this, config );
7587
7588 // Properties
7589 this.toolbar = toolbar;
7590 this.tools = {};
7591 this.pressed = null;
7592 this.autoDisabled = false;
7593 this.include = config.include || [];
7594 this.exclude = config.exclude || [];
7595 this.promote = config.promote || [];
7596 this.demote = config.demote || [];
7597 this.onCapturedMouseKeyUpHandler = this.onCapturedMouseKeyUp.bind( this );
7598
7599 // Events
7600 this.$element.on( {
7601 mousedown: this.onMouseKeyDown.bind( this ),
7602 mouseup: this.onMouseKeyUp.bind( this ),
7603 keydown: this.onMouseKeyDown.bind( this ),
7604 keyup: this.onMouseKeyUp.bind( this ),
7605 focus: this.onMouseOverFocus.bind( this ),
7606 blur: this.onMouseOutBlur.bind( this ),
7607 mouseover: this.onMouseOverFocus.bind( this ),
7608 mouseout: this.onMouseOutBlur.bind( this )
7609 } );
7610 this.toolbar.getToolFactory().connect( this, { register: 'onToolFactoryRegister' } );
7611 this.aggregate( { disable: 'itemDisable' } );
7612 this.connect( this, { itemDisable: 'updateDisabled' } );
7613
7614 // Initialization
7615 this.$group.addClass( 'oo-ui-toolGroup-tools' );
7616 this.$element
7617 .addClass( 'oo-ui-toolGroup' )
7618 .append( this.$group );
7619 this.populate();
7620 };
7621
7622 /* Setup */
7623
7624 OO.inheritClass( OO.ui.ToolGroup, OO.ui.Widget );
7625 OO.mixinClass( OO.ui.ToolGroup, OO.ui.mixin.GroupElement );
7626
7627 /* Events */
7628
7629 /**
7630 * @event update
7631 */
7632
7633 /* Static Properties */
7634
7635 /**
7636 * Show labels in tooltips.
7637 *
7638 * @static
7639 * @inheritable
7640 * @property {boolean}
7641 */
7642 OO.ui.ToolGroup.static.titleTooltips = false;
7643
7644 /**
7645 * Show acceleration labels in tooltips.
7646 *
7647 * Note: The OOjs UI library does not include an accelerator system, but does contain
7648 * a hook for one. To use an accelerator system, subclass the {@link OO.ui.Toolbar toolbar} and
7649 * override the {@link OO.ui.Toolbar#getToolAccelerator getToolAccelerator} method, which is
7650 * meant to return a label that describes the accelerator keys for a given tool (e.g., 'Ctrl + M').
7651 *
7652 * @static
7653 * @inheritable
7654 * @property {boolean}
7655 */
7656 OO.ui.ToolGroup.static.accelTooltips = false;
7657
7658 /**
7659 * Automatically disable the toolgroup when all tools are disabled
7660 *
7661 * @static
7662 * @inheritable
7663 * @property {boolean}
7664 */
7665 OO.ui.ToolGroup.static.autoDisable = true;
7666
7667 /* Methods */
7668
7669 /**
7670 * @inheritdoc
7671 */
7672 OO.ui.ToolGroup.prototype.isDisabled = function () {
7673 return this.autoDisabled || OO.ui.ToolGroup.parent.prototype.isDisabled.apply( this, arguments );
7674 };
7675
7676 /**
7677 * @inheritdoc
7678 */
7679 OO.ui.ToolGroup.prototype.updateDisabled = function () {
7680 var i, item, allDisabled = true;
7681
7682 if ( this.constructor.static.autoDisable ) {
7683 for ( i = this.items.length - 1; i >= 0; i-- ) {
7684 item = this.items[ i ];
7685 if ( !item.isDisabled() ) {
7686 allDisabled = false;
7687 break;
7688 }
7689 }
7690 this.autoDisabled = allDisabled;
7691 }
7692 OO.ui.ToolGroup.parent.prototype.updateDisabled.apply( this, arguments );
7693 };
7694
7695 /**
7696 * Handle mouse down and key down events.
7697 *
7698 * @protected
7699 * @param {jQuery.Event} e Mouse down or key down event
7700 */
7701 OO.ui.ToolGroup.prototype.onMouseKeyDown = function ( e ) {
7702 if (
7703 !this.isDisabled() &&
7704 ( e.which === 1 || e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
7705 ) {
7706 this.pressed = this.getTargetTool( e );
7707 if ( this.pressed ) {
7708 this.pressed.setActive( true );
7709 OO.ui.addCaptureEventListener( this.getElementDocument(), 'mouseup', this.onCapturedMouseKeyUpHandler );
7710 OO.ui.addCaptureEventListener( this.getElementDocument(), 'keyup', this.onCapturedMouseKeyUpHandler );
7711 }
7712 return false;
7713 }
7714 };
7715
7716 /**
7717 * Handle captured mouse up and key up events.
7718 *
7719 * @protected
7720 * @param {Event} e Mouse up or key up event
7721 */
7722 OO.ui.ToolGroup.prototype.onCapturedMouseKeyUp = function ( e ) {
7723 OO.ui.removeCaptureEventListener( this.getElementDocument(), 'mouseup', this.onCapturedMouseKeyUpHandler );
7724 OO.ui.removeCaptureEventListener( this.getElementDocument(), 'keyup', this.onCapturedMouseKeyUpHandler );
7725 // onMouseKeyUp may be called a second time, depending on where the mouse is when the button is
7726 // released, but since `this.pressed` will no longer be true, the second call will be ignored.
7727 this.onMouseKeyUp( e );
7728 };
7729
7730 /**
7731 * Handle mouse up and key up events.
7732 *
7733 * @protected
7734 * @param {jQuery.Event} e Mouse up or key up event
7735 */
7736 OO.ui.ToolGroup.prototype.onMouseKeyUp = function ( e ) {
7737 var tool = this.getTargetTool( e );
7738
7739 if (
7740 !this.isDisabled() && this.pressed && this.pressed === tool &&
7741 ( e.which === 1 || e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
7742 ) {
7743 this.pressed.onSelect();
7744 this.pressed = null;
7745 return false;
7746 }
7747
7748 this.pressed = null;
7749 };
7750
7751 /**
7752 * Handle mouse over and focus events.
7753 *
7754 * @protected
7755 * @param {jQuery.Event} e Mouse over or focus event
7756 */
7757 OO.ui.ToolGroup.prototype.onMouseOverFocus = function ( e ) {
7758 var tool = this.getTargetTool( e );
7759
7760 if ( this.pressed && this.pressed === tool ) {
7761 this.pressed.setActive( true );
7762 }
7763 };
7764
7765 /**
7766 * Handle mouse out and blur events.
7767 *
7768 * @protected
7769 * @param {jQuery.Event} e Mouse out or blur event
7770 */
7771 OO.ui.ToolGroup.prototype.onMouseOutBlur = function ( e ) {
7772 var tool = this.getTargetTool( e );
7773
7774 if ( this.pressed && this.pressed === tool ) {
7775 this.pressed.setActive( false );
7776 }
7777 };
7778
7779 /**
7780 * Get the closest tool to a jQuery.Event.
7781 *
7782 * Only tool links are considered, which prevents other elements in the tool such as popups from
7783 * triggering tool group interactions.
7784 *
7785 * @private
7786 * @param {jQuery.Event} e
7787 * @return {OO.ui.Tool|null} Tool, `null` if none was found
7788 */
7789 OO.ui.ToolGroup.prototype.getTargetTool = function ( e ) {
7790 var tool,
7791 $item = $( e.target ).closest( '.oo-ui-tool-link' );
7792
7793 if ( $item.length ) {
7794 tool = $item.parent().data( 'oo-ui-tool' );
7795 }
7796
7797 return tool && !tool.isDisabled() ? tool : null;
7798 };
7799
7800 /**
7801 * Handle tool registry register events.
7802 *
7803 * If a tool is registered after the group is created, we must repopulate the list to account for:
7804 *
7805 * - a tool being added that may be included
7806 * - a tool already included being overridden
7807 *
7808 * @protected
7809 * @param {string} name Symbolic name of tool
7810 */
7811 OO.ui.ToolGroup.prototype.onToolFactoryRegister = function () {
7812 this.populate();
7813 };
7814
7815 /**
7816 * Get the toolbar that contains the toolgroup.
7817 *
7818 * @return {OO.ui.Toolbar} Toolbar that contains the toolgroup
7819 */
7820 OO.ui.ToolGroup.prototype.getToolbar = function () {
7821 return this.toolbar;
7822 };
7823
7824 /**
7825 * Add and remove tools based on configuration.
7826 */
7827 OO.ui.ToolGroup.prototype.populate = function () {
7828 var i, len, name, tool,
7829 toolFactory = this.toolbar.getToolFactory(),
7830 names = {},
7831 add = [],
7832 remove = [],
7833 list = this.toolbar.getToolFactory().getTools(
7834 this.include, this.exclude, this.promote, this.demote
7835 );
7836
7837 // Build a list of needed tools
7838 for ( i = 0, len = list.length; i < len; i++ ) {
7839 name = list[ i ];
7840 if (
7841 // Tool exists
7842 toolFactory.lookup( name ) &&
7843 // Tool is available or is already in this group
7844 ( this.toolbar.isToolAvailable( name ) || this.tools[ name ] )
7845 ) {
7846 // Hack to prevent infinite recursion via ToolGroupTool. We need to reserve the tool before
7847 // creating it, but we can't call reserveTool() yet because we haven't created the tool.
7848 this.toolbar.tools[ name ] = true;
7849 tool = this.tools[ name ];
7850 if ( !tool ) {
7851 // Auto-initialize tools on first use
7852 this.tools[ name ] = tool = toolFactory.create( name, this );
7853 tool.updateTitle();
7854 }
7855 this.toolbar.reserveTool( tool );
7856 add.push( tool );
7857 names[ name ] = true;
7858 }
7859 }
7860 // Remove tools that are no longer needed
7861 for ( name in this.tools ) {
7862 if ( !names[ name ] ) {
7863 this.tools[ name ].destroy();
7864 this.toolbar.releaseTool( this.tools[ name ] );
7865 remove.push( this.tools[ name ] );
7866 delete this.tools[ name ];
7867 }
7868 }
7869 if ( remove.length ) {
7870 this.removeItems( remove );
7871 }
7872 // Update emptiness state
7873 if ( add.length ) {
7874 this.$element.removeClass( 'oo-ui-toolGroup-empty' );
7875 } else {
7876 this.$element.addClass( 'oo-ui-toolGroup-empty' );
7877 }
7878 // Re-add tools (moving existing ones to new locations)
7879 this.addItems( add );
7880 // Disabled state may depend on items
7881 this.updateDisabled();
7882 };
7883
7884 /**
7885 * Destroy toolgroup.
7886 */
7887 OO.ui.ToolGroup.prototype.destroy = function () {
7888 var name;
7889
7890 this.clearItems();
7891 this.toolbar.getToolFactory().disconnect( this );
7892 for ( name in this.tools ) {
7893 this.toolbar.releaseTool( this.tools[ name ] );
7894 this.tools[ name ].disconnect( this ).destroy();
7895 delete this.tools[ name ];
7896 }
7897 this.$element.remove();
7898 };
7899
7900 /**
7901 * MessageDialogs display a confirmation or alert message. By default, the rendered dialog box
7902 * consists of a header that contains the dialog title, a body with the message, and a footer that
7903 * contains any {@link OO.ui.ActionWidget action widgets}. The MessageDialog class is the only type
7904 * of {@link OO.ui.Dialog dialog} that is usually instantiated directly.
7905 *
7906 * There are two basic types of message dialogs, confirmation and alert:
7907 *
7908 * - **confirmation**: the dialog title describes what a progressive action will do and the message provides
7909 * more details about the consequences.
7910 * - **alert**: the dialog title describes which event occurred and the message provides more information
7911 * about why the event occurred.
7912 *
7913 * The MessageDialog class specifies two actions: ‘accept’, the primary
7914 * action (e.g., ‘ok’) and ‘reject,’ the safe action (e.g., ‘cancel’). Both will close the window,
7915 * passing along the selected action.
7916 *
7917 * For more information and examples, please see the [OOjs UI documentation on MediaWiki][1].
7918 *
7919 * @example
7920 * // Example: Creating and opening a message dialog window.
7921 * var messageDialog = new OO.ui.MessageDialog();
7922 *
7923 * // Create and append a window manager.
7924 * var windowManager = new OO.ui.WindowManager();
7925 * $( 'body' ).append( windowManager.$element );
7926 * windowManager.addWindows( [ messageDialog ] );
7927 * // Open the window.
7928 * windowManager.openWindow( messageDialog, {
7929 * title: 'Basic message dialog',
7930 * message: 'This is the message'
7931 * } );
7932 *
7933 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Message_Dialogs
7934 *
7935 * @class
7936 * @extends OO.ui.Dialog
7937 *
7938 * @constructor
7939 * @param {Object} [config] Configuration options
7940 */
7941 OO.ui.MessageDialog = function OoUiMessageDialog( config ) {
7942 // Parent constructor
7943 OO.ui.MessageDialog.parent.call( this, config );
7944
7945 // Properties
7946 this.verticalActionLayout = null;
7947
7948 // Initialization
7949 this.$element.addClass( 'oo-ui-messageDialog' );
7950 };
7951
7952 /* Setup */
7953
7954 OO.inheritClass( OO.ui.MessageDialog, OO.ui.Dialog );
7955
7956 /* Static Properties */
7957
7958 OO.ui.MessageDialog.static.name = 'message';
7959
7960 OO.ui.MessageDialog.static.size = 'small';
7961
7962 OO.ui.MessageDialog.static.verbose = false;
7963
7964 /**
7965 * Dialog title.
7966 *
7967 * The title of a confirmation dialog describes what a progressive action will do. The
7968 * title of an alert dialog describes which event occurred.
7969 *
7970 * @static
7971 * @inheritable
7972 * @property {jQuery|string|Function|null}
7973 */
7974 OO.ui.MessageDialog.static.title = null;
7975
7976 /**
7977 * The message displayed in the dialog body.
7978 *
7979 * A confirmation message describes the consequences of a progressive action. An alert
7980 * message describes why an event occurred.
7981 *
7982 * @static
7983 * @inheritable
7984 * @property {jQuery|string|Function|null}
7985 */
7986 OO.ui.MessageDialog.static.message = null;
7987
7988 OO.ui.MessageDialog.static.actions = [
7989 { action: 'accept', label: OO.ui.deferMsg( 'ooui-dialog-message-accept' ), flags: 'primary' },
7990 { action: 'reject', label: OO.ui.deferMsg( 'ooui-dialog-message-reject' ), flags: 'safe' }
7991 ];
7992
7993 /* Methods */
7994
7995 /**
7996 * @inheritdoc
7997 */
7998 OO.ui.MessageDialog.prototype.setManager = function ( manager ) {
7999 OO.ui.MessageDialog.parent.prototype.setManager.call( this, manager );
8000
8001 // Events
8002 this.manager.connect( this, {
8003 resize: 'onResize'
8004 } );
8005
8006 return this;
8007 };
8008
8009 /**
8010 * @inheritdoc
8011 */
8012 OO.ui.MessageDialog.prototype.onActionResize = function ( action ) {
8013 this.fitActions();
8014 return OO.ui.MessageDialog.parent.prototype.onActionResize.call( this, action );
8015 };
8016
8017 /**
8018 * Handle window resized events.
8019 *
8020 * @private
8021 */
8022 OO.ui.MessageDialog.prototype.onResize = function () {
8023 var dialog = this;
8024 dialog.fitActions();
8025 // Wait for CSS transition to finish and do it again :(
8026 setTimeout( function () {
8027 dialog.fitActions();
8028 }, 300 );
8029 };
8030
8031 /**
8032 * Toggle action layout between vertical and horizontal.
8033 *
8034 *
8035 * @private
8036 * @param {boolean} [value] Layout actions vertically, omit to toggle
8037 * @chainable
8038 */
8039 OO.ui.MessageDialog.prototype.toggleVerticalActionLayout = function ( value ) {
8040 value = value === undefined ? !this.verticalActionLayout : !!value;
8041
8042 if ( value !== this.verticalActionLayout ) {
8043 this.verticalActionLayout = value;
8044 this.$actions
8045 .toggleClass( 'oo-ui-messageDialog-actions-vertical', value )
8046 .toggleClass( 'oo-ui-messageDialog-actions-horizontal', !value );
8047 }
8048
8049 return this;
8050 };
8051
8052 /**
8053 * @inheritdoc
8054 */
8055 OO.ui.MessageDialog.prototype.getActionProcess = function ( action ) {
8056 if ( action ) {
8057 return new OO.ui.Process( function () {
8058 this.close( { action: action } );
8059 }, this );
8060 }
8061 return OO.ui.MessageDialog.parent.prototype.getActionProcess.call( this, action );
8062 };
8063
8064 /**
8065 * @inheritdoc
8066 *
8067 * @param {Object} [data] Dialog opening data
8068 * @param {jQuery|string|Function|null} [data.title] Description of the action being confirmed
8069 * @param {jQuery|string|Function|null} [data.message] Description of the action's consequence
8070 * @param {boolean} [data.verbose] Message is verbose and should be styled as a long message
8071 * @param {Object[]} [data.actions] List of OO.ui.ActionOptionWidget configuration options for each
8072 * action item
8073 */
8074 OO.ui.MessageDialog.prototype.getSetupProcess = function ( data ) {
8075 data = data || {};
8076
8077 // Parent method
8078 return OO.ui.MessageDialog.parent.prototype.getSetupProcess.call( this, data )
8079 .next( function () {
8080 this.title.setLabel(
8081 data.title !== undefined ? data.title : this.constructor.static.title
8082 );
8083 this.message.setLabel(
8084 data.message !== undefined ? data.message : this.constructor.static.message
8085 );
8086 this.message.$element.toggleClass(
8087 'oo-ui-messageDialog-message-verbose',
8088 data.verbose !== undefined ? data.verbose : this.constructor.static.verbose
8089 );
8090 }, this );
8091 };
8092
8093 /**
8094 * @inheritdoc
8095 */
8096 OO.ui.MessageDialog.prototype.getReadyProcess = function ( data ) {
8097 data = data || {};
8098
8099 // Parent method
8100 return OO.ui.MessageDialog.parent.prototype.getReadyProcess.call( this, data )
8101 .next( function () {
8102 // Focus the primary action button
8103 var actions = this.actions.get();
8104 actions = actions.filter( function ( action ) {
8105 return action.getFlags().indexOf( 'primary' ) > -1;
8106 } );
8107 if ( actions.length > 0 ) {
8108 actions[0].$button.focus();
8109 }
8110 }, this );
8111 };
8112
8113 /**
8114 * @inheritdoc
8115 */
8116 OO.ui.MessageDialog.prototype.getBodyHeight = function () {
8117 var bodyHeight, oldOverflow,
8118 $scrollable = this.container.$element;
8119
8120 oldOverflow = $scrollable[ 0 ].style.overflow;
8121 $scrollable[ 0 ].style.overflow = 'hidden';
8122
8123 OO.ui.Element.static.reconsiderScrollbars( $scrollable[ 0 ] );
8124
8125 bodyHeight = this.text.$element.outerHeight( true );
8126 $scrollable[ 0 ].style.overflow = oldOverflow;
8127
8128 return bodyHeight;
8129 };
8130
8131 /**
8132 * @inheritdoc
8133 */
8134 OO.ui.MessageDialog.prototype.setDimensions = function ( dim ) {
8135 var $scrollable = this.container.$element;
8136 OO.ui.MessageDialog.parent.prototype.setDimensions.call( this, dim );
8137
8138 // Twiddle the overflow property, otherwise an unnecessary scrollbar will be produced.
8139 // Need to do it after transition completes (250ms), add 50ms just in case.
8140 setTimeout( function () {
8141 var oldOverflow = $scrollable[ 0 ].style.overflow;
8142 $scrollable[ 0 ].style.overflow = 'hidden';
8143
8144 OO.ui.Element.static.reconsiderScrollbars( $scrollable[ 0 ] );
8145
8146 $scrollable[ 0 ].style.overflow = oldOverflow;
8147 }, 300 );
8148
8149 return this;
8150 };
8151
8152 /**
8153 * @inheritdoc
8154 */
8155 OO.ui.MessageDialog.prototype.initialize = function () {
8156 // Parent method
8157 OO.ui.MessageDialog.parent.prototype.initialize.call( this );
8158
8159 // Properties
8160 this.$actions = $( '<div>' );
8161 this.container = new OO.ui.PanelLayout( {
8162 scrollable: true, classes: [ 'oo-ui-messageDialog-container' ]
8163 } );
8164 this.text = new OO.ui.PanelLayout( {
8165 padded: true, expanded: false, classes: [ 'oo-ui-messageDialog-text' ]
8166 } );
8167 this.message = new OO.ui.LabelWidget( {
8168 classes: [ 'oo-ui-messageDialog-message' ]
8169 } );
8170
8171 // Initialization
8172 this.title.$element.addClass( 'oo-ui-messageDialog-title' );
8173 this.$content.addClass( 'oo-ui-messageDialog-content' );
8174 this.container.$element.append( this.text.$element );
8175 this.text.$element.append( this.title.$element, this.message.$element );
8176 this.$body.append( this.container.$element );
8177 this.$actions.addClass( 'oo-ui-messageDialog-actions' );
8178 this.$foot.append( this.$actions );
8179 };
8180
8181 /**
8182 * @inheritdoc
8183 */
8184 OO.ui.MessageDialog.prototype.attachActions = function () {
8185 var i, len, other, special, others;
8186
8187 // Parent method
8188 OO.ui.MessageDialog.parent.prototype.attachActions.call( this );
8189
8190 special = this.actions.getSpecial();
8191 others = this.actions.getOthers();
8192
8193 if ( special.safe ) {
8194 this.$actions.append( special.safe.$element );
8195 special.safe.toggleFramed( false );
8196 }
8197 if ( others.length ) {
8198 for ( i = 0, len = others.length; i < len; i++ ) {
8199 other = others[ i ];
8200 this.$actions.append( other.$element );
8201 other.toggleFramed( false );
8202 }
8203 }
8204 if ( special.primary ) {
8205 this.$actions.append( special.primary.$element );
8206 special.primary.toggleFramed( false );
8207 }
8208
8209 if ( !this.isOpening() ) {
8210 // If the dialog is currently opening, this will be called automatically soon.
8211 // This also calls #fitActions.
8212 this.updateSize();
8213 }
8214 };
8215
8216 /**
8217 * Fit action actions into columns or rows.
8218 *
8219 * Columns will be used if all labels can fit without overflow, otherwise rows will be used.
8220 *
8221 * @private
8222 */
8223 OO.ui.MessageDialog.prototype.fitActions = function () {
8224 var i, len, action,
8225 previous = this.verticalActionLayout,
8226 actions = this.actions.get();
8227
8228 // Detect clipping
8229 this.toggleVerticalActionLayout( false );
8230 for ( i = 0, len = actions.length; i < len; i++ ) {
8231 action = actions[ i ];
8232 if ( action.$element.innerWidth() < action.$label.outerWidth( true ) ) {
8233 this.toggleVerticalActionLayout( true );
8234 break;
8235 }
8236 }
8237
8238 // Move the body out of the way of the foot
8239 this.$body.css( 'bottom', this.$foot.outerHeight( true ) );
8240
8241 if ( this.verticalActionLayout !== previous ) {
8242 // We changed the layout, window height might need to be updated.
8243 this.updateSize();
8244 }
8245 };
8246
8247 /**
8248 * ProcessDialog windows encapsulate a {@link OO.ui.Process process} and all of the code necessary
8249 * to complete it. If the process terminates with an error, a customizable {@link OO.ui.Error error
8250 * interface} alerts users to the trouble, permitting the user to dismiss the error and try again when
8251 * relevant. The ProcessDialog class is always extended and customized with the actions and content
8252 * required for each process.
8253 *
8254 * The process dialog box consists of a header that visually represents the ‘working’ state of long
8255 * processes with an animation. The header contains the dialog title as well as
8256 * two {@link OO.ui.ActionWidget action widgets}: a ‘safe’ action on the left (e.g., ‘Cancel’) and
8257 * a ‘primary’ action on the right (e.g., ‘Done’).
8258 *
8259 * Like other windows, the process dialog is managed by a {@link OO.ui.WindowManager window manager}.
8260 * Please see the [OOjs UI documentation on MediaWiki][1] for more information and examples.
8261 *
8262 * @example
8263 * // Example: Creating and opening a process dialog window.
8264 * function MyProcessDialog( config ) {
8265 * MyProcessDialog.parent.call( this, config );
8266 * }
8267 * OO.inheritClass( MyProcessDialog, OO.ui.ProcessDialog );
8268 *
8269 * MyProcessDialog.static.title = 'Process dialog';
8270 * MyProcessDialog.static.actions = [
8271 * { action: 'save', label: 'Done', flags: 'primary' },
8272 * { label: 'Cancel', flags: 'safe' }
8273 * ];
8274 *
8275 * MyProcessDialog.prototype.initialize = function () {
8276 * MyProcessDialog.parent.prototype.initialize.apply( this, arguments );
8277 * this.content = new OO.ui.PanelLayout( { padded: true, expanded: false } );
8278 * 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>' );
8279 * this.$body.append( this.content.$element );
8280 * };
8281 * MyProcessDialog.prototype.getActionProcess = function ( action ) {
8282 * var dialog = this;
8283 * if ( action ) {
8284 * return new OO.ui.Process( function () {
8285 * dialog.close( { action: action } );
8286 * } );
8287 * }
8288 * return MyProcessDialog.parent.prototype.getActionProcess.call( this, action );
8289 * };
8290 *
8291 * var windowManager = new OO.ui.WindowManager();
8292 * $( 'body' ).append( windowManager.$element );
8293 *
8294 * var dialog = new MyProcessDialog();
8295 * windowManager.addWindows( [ dialog ] );
8296 * windowManager.openWindow( dialog );
8297 *
8298 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs
8299 *
8300 * @abstract
8301 * @class
8302 * @extends OO.ui.Dialog
8303 *
8304 * @constructor
8305 * @param {Object} [config] Configuration options
8306 */
8307 OO.ui.ProcessDialog = function OoUiProcessDialog( config ) {
8308 // Parent constructor
8309 OO.ui.ProcessDialog.parent.call( this, config );
8310
8311 // Properties
8312 this.fitOnOpen = false;
8313
8314 // Initialization
8315 this.$element.addClass( 'oo-ui-processDialog' );
8316 };
8317
8318 /* Setup */
8319
8320 OO.inheritClass( OO.ui.ProcessDialog, OO.ui.Dialog );
8321
8322 /* Methods */
8323
8324 /**
8325 * Handle dismiss button click events.
8326 *
8327 * Hides errors.
8328 *
8329 * @private
8330 */
8331 OO.ui.ProcessDialog.prototype.onDismissErrorButtonClick = function () {
8332 this.hideErrors();
8333 };
8334
8335 /**
8336 * Handle retry button click events.
8337 *
8338 * Hides errors and then tries again.
8339 *
8340 * @private
8341 */
8342 OO.ui.ProcessDialog.prototype.onRetryButtonClick = function () {
8343 this.hideErrors();
8344 this.executeAction( this.currentAction );
8345 };
8346
8347 /**
8348 * @inheritdoc
8349 */
8350 OO.ui.ProcessDialog.prototype.onActionResize = function ( action ) {
8351 if ( this.actions.isSpecial( action ) ) {
8352 this.fitLabel();
8353 }
8354 return OO.ui.ProcessDialog.parent.prototype.onActionResize.call( this, action );
8355 };
8356
8357 /**
8358 * @inheritdoc
8359 */
8360 OO.ui.ProcessDialog.prototype.initialize = function () {
8361 // Parent method
8362 OO.ui.ProcessDialog.parent.prototype.initialize.call( this );
8363
8364 // Properties
8365 this.$navigation = $( '<div>' );
8366 this.$location = $( '<div>' );
8367 this.$safeActions = $( '<div>' );
8368 this.$primaryActions = $( '<div>' );
8369 this.$otherActions = $( '<div>' );
8370 this.dismissButton = new OO.ui.ButtonWidget( {
8371 label: OO.ui.msg( 'ooui-dialog-process-dismiss' )
8372 } );
8373 this.retryButton = new OO.ui.ButtonWidget();
8374 this.$errors = $( '<div>' );
8375 this.$errorsTitle = $( '<div>' );
8376
8377 // Events
8378 this.dismissButton.connect( this, { click: 'onDismissErrorButtonClick' } );
8379 this.retryButton.connect( this, { click: 'onRetryButtonClick' } );
8380
8381 // Initialization
8382 this.title.$element.addClass( 'oo-ui-processDialog-title' );
8383 this.$location
8384 .append( this.title.$element )
8385 .addClass( 'oo-ui-processDialog-location' );
8386 this.$safeActions.addClass( 'oo-ui-processDialog-actions-safe' );
8387 this.$primaryActions.addClass( 'oo-ui-processDialog-actions-primary' );
8388 this.$otherActions.addClass( 'oo-ui-processDialog-actions-other' );
8389 this.$errorsTitle
8390 .addClass( 'oo-ui-processDialog-errors-title' )
8391 .text( OO.ui.msg( 'ooui-dialog-process-error' ) );
8392 this.$errors
8393 .addClass( 'oo-ui-processDialog-errors oo-ui-element-hidden' )
8394 .append( this.$errorsTitle, this.dismissButton.$element, this.retryButton.$element );
8395 this.$content
8396 .addClass( 'oo-ui-processDialog-content' )
8397 .append( this.$errors );
8398 this.$navigation
8399 .addClass( 'oo-ui-processDialog-navigation' )
8400 .append( this.$safeActions, this.$location, this.$primaryActions );
8401 this.$head.append( this.$navigation );
8402 this.$foot.append( this.$otherActions );
8403 };
8404
8405 /**
8406 * @inheritdoc
8407 */
8408 OO.ui.ProcessDialog.prototype.getActionWidgets = function ( actions ) {
8409 var i, len, widgets = [];
8410 for ( i = 0, len = actions.length; i < len; i++ ) {
8411 widgets.push(
8412 new OO.ui.ActionWidget( $.extend( { framed: true }, actions[ i ] ) )
8413 );
8414 }
8415 return widgets;
8416 };
8417
8418 /**
8419 * @inheritdoc
8420 */
8421 OO.ui.ProcessDialog.prototype.attachActions = function () {
8422 var i, len, other, special, others;
8423
8424 // Parent method
8425 OO.ui.ProcessDialog.parent.prototype.attachActions.call( this );
8426
8427 special = this.actions.getSpecial();
8428 others = this.actions.getOthers();
8429 if ( special.primary ) {
8430 this.$primaryActions.append( special.primary.$element );
8431 }
8432 for ( i = 0, len = others.length; i < len; i++ ) {
8433 other = others[ i ];
8434 this.$otherActions.append( other.$element );
8435 }
8436 if ( special.safe ) {
8437 this.$safeActions.append( special.safe.$element );
8438 }
8439
8440 this.fitLabel();
8441 this.$body.css( 'bottom', this.$foot.outerHeight( true ) );
8442 };
8443
8444 /**
8445 * @inheritdoc
8446 */
8447 OO.ui.ProcessDialog.prototype.executeAction = function ( action ) {
8448 var process = this;
8449 return OO.ui.ProcessDialog.parent.prototype.executeAction.call( this, action )
8450 .fail( function ( errors ) {
8451 process.showErrors( errors || [] );
8452 } );
8453 };
8454
8455 /**
8456 * @inheritdoc
8457 */
8458 OO.ui.ProcessDialog.prototype.setDimensions = function () {
8459 // Parent method
8460 OO.ui.ProcessDialog.parent.prototype.setDimensions.apply( this, arguments );
8461
8462 this.fitLabel();
8463 };
8464
8465 /**
8466 * Fit label between actions.
8467 *
8468 * @private
8469 * @chainable
8470 */
8471 OO.ui.ProcessDialog.prototype.fitLabel = function () {
8472 var safeWidth, primaryWidth, biggerWidth, labelWidth, navigationWidth, leftWidth, rightWidth,
8473 size = this.getSizeProperties();
8474
8475 if ( typeof size.width !== 'number' ) {
8476 if ( this.isOpened() ) {
8477 navigationWidth = this.$head.width() - 20;
8478 } else if ( this.isOpening() ) {
8479 if ( !this.fitOnOpen ) {
8480 // Size is relative and the dialog isn't open yet, so wait.
8481 this.manager.opening.done( this.fitLabel.bind( this ) );
8482 this.fitOnOpen = true;
8483 }
8484 return;
8485 } else {
8486 return;
8487 }
8488 } else {
8489 navigationWidth = size.width - 20;
8490 }
8491
8492 safeWidth = this.$safeActions.is( ':visible' ) ? this.$safeActions.width() : 0;
8493 primaryWidth = this.$primaryActions.is( ':visible' ) ? this.$primaryActions.width() : 0;
8494 biggerWidth = Math.max( safeWidth, primaryWidth );
8495
8496 labelWidth = this.title.$element.width();
8497
8498 if ( 2 * biggerWidth + labelWidth < navigationWidth ) {
8499 // We have enough space to center the label
8500 leftWidth = rightWidth = biggerWidth;
8501 } else {
8502 // Let's hope we at least have enough space not to overlap, because we can't wrap the label…
8503 if ( this.getDir() === 'ltr' ) {
8504 leftWidth = safeWidth;
8505 rightWidth = primaryWidth;
8506 } else {
8507 leftWidth = primaryWidth;
8508 rightWidth = safeWidth;
8509 }
8510 }
8511
8512 this.$location.css( { paddingLeft: leftWidth, paddingRight: rightWidth } );
8513
8514 return this;
8515 };
8516
8517 /**
8518 * Handle errors that occurred during accept or reject processes.
8519 *
8520 * @private
8521 * @param {OO.ui.Error[]|OO.ui.Error} errors Errors to be handled
8522 */
8523 OO.ui.ProcessDialog.prototype.showErrors = function ( errors ) {
8524 var i, len, $item, actions,
8525 items = [],
8526 abilities = {},
8527 recoverable = true,
8528 warning = false;
8529
8530 if ( errors instanceof OO.ui.Error ) {
8531 errors = [ errors ];
8532 }
8533
8534 for ( i = 0, len = errors.length; i < len; i++ ) {
8535 if ( !errors[ i ].isRecoverable() ) {
8536 recoverable = false;
8537 }
8538 if ( errors[ i ].isWarning() ) {
8539 warning = true;
8540 }
8541 $item = $( '<div>' )
8542 .addClass( 'oo-ui-processDialog-error' )
8543 .append( errors[ i ].getMessage() );
8544 items.push( $item[ 0 ] );
8545 }
8546 this.$errorItems = $( items );
8547 if ( recoverable ) {
8548 abilities[this.currentAction] = true;
8549 // Copy the flags from the first matching action
8550 actions = this.actions.get( { actions: this.currentAction } );
8551 if ( actions.length ) {
8552 this.retryButton.clearFlags().setFlags( actions[0].getFlags() );
8553 }
8554 } else {
8555 abilities[this.currentAction] = false;
8556 this.actions.setAbilities( abilities );
8557 }
8558 if ( warning ) {
8559 this.retryButton.setLabel( OO.ui.msg( 'ooui-dialog-process-continue' ) );
8560 } else {
8561 this.retryButton.setLabel( OO.ui.msg( 'ooui-dialog-process-retry' ) );
8562 }
8563 this.retryButton.toggle( recoverable );
8564 this.$errorsTitle.after( this.$errorItems );
8565 this.$errors.removeClass( 'oo-ui-element-hidden' ).scrollTop( 0 );
8566 };
8567
8568 /**
8569 * Hide errors.
8570 *
8571 * @private
8572 */
8573 OO.ui.ProcessDialog.prototype.hideErrors = function () {
8574 this.$errors.addClass( 'oo-ui-element-hidden' );
8575 if ( this.$errorItems ) {
8576 this.$errorItems.remove();
8577 this.$errorItems = null;
8578 }
8579 };
8580
8581 /**
8582 * @inheritdoc
8583 */
8584 OO.ui.ProcessDialog.prototype.getTeardownProcess = function ( data ) {
8585 // Parent method
8586 return OO.ui.ProcessDialog.parent.prototype.getTeardownProcess.call( this, data )
8587 .first( function () {
8588 // Make sure to hide errors
8589 this.hideErrors();
8590 this.fitOnOpen = false;
8591 }, this );
8592 };
8593
8594 /**
8595 * FieldLayouts are used with OO.ui.FieldsetLayout. Each FieldLayout requires a field-widget,
8596 * which is a widget that is specified by reference before any optional configuration settings.
8597 *
8598 * Field layouts can be configured with help text and/or labels. Labels are aligned in one of four ways:
8599 *
8600 * - **left**: The label is placed before the field-widget and aligned with the left margin.
8601 * A left-alignment is used for forms with many fields.
8602 * - **right**: The label is placed before the field-widget and aligned to the right margin.
8603 * A right-alignment is used for long but familiar forms which users tab through,
8604 * verifying the current field with a quick glance at the label.
8605 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
8606 * that users fill out from top to bottom.
8607 * - **inline**: The label is placed after the field-widget and aligned to the left.
8608 * An inline-alignment is best used with checkboxes or radio buttons.
8609 *
8610 * Help text is accessed via a help icon that appears in the upper right corner of the rendered field layout.
8611 * Please see the [OOjs UI documentation on MediaWiki] [1] for examples and more information.
8612 *
8613 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Fields_and_Fieldsets
8614 * @class
8615 * @extends OO.ui.Layout
8616 * @mixins OO.ui.mixin.LabelElement
8617 * @mixins OO.ui.mixin.TitledElement
8618 *
8619 * @constructor
8620 * @param {OO.ui.Widget} fieldWidget Field widget
8621 * @param {Object} [config] Configuration options
8622 * @cfg {string} [align='left'] Alignment of the label: 'left', 'right', 'top' or 'inline'
8623 * @cfg {Array} [errors] Error messages about the widget, which will be displayed below the widget.
8624 * The array may contain strings or OO.ui.HtmlSnippet instances.
8625 * @cfg {Array} [notices] Notices about the widget, which will be displayed below the widget.
8626 * The array may contain strings or OO.ui.HtmlSnippet instances.
8627 * @cfg {string|OO.ui.HtmlSnippet} [help] Help text. When help text is specified, a "help" icon will appear
8628 * in the upper-right corner of the rendered field; clicking it will display the text in a popup.
8629 * For important messages, you are advised to use `notices`, as they are always shown.
8630 *
8631 * @throws {Error} An error is thrown if no widget is specified
8632 */
8633 OO.ui.FieldLayout = function OoUiFieldLayout( fieldWidget, config ) {
8634 // Allow passing positional parameters inside the config object
8635 if ( OO.isPlainObject( fieldWidget ) && config === undefined ) {
8636 config = fieldWidget;
8637 fieldWidget = config.fieldWidget;
8638 }
8639
8640 // Make sure we have required constructor arguments
8641 if ( fieldWidget === undefined ) {
8642 throw new Error( 'Widget not found' );
8643 }
8644
8645 var hasInputWidget = fieldWidget.constructor.static.supportsSimpleLabel,
8646 div, i;
8647
8648 // Configuration initialization
8649 config = $.extend( { align: 'left' }, config );
8650
8651 // Parent constructor
8652 OO.ui.FieldLayout.parent.call( this, config );
8653
8654 // Mixin constructors
8655 OO.ui.mixin.LabelElement.call( this, config );
8656 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$label } ) );
8657
8658 // Properties
8659 this.fieldWidget = fieldWidget;
8660 this.errors = config.errors || [];
8661 this.notices = config.notices || [];
8662 this.$field = $( '<div>' );
8663 this.$messages = $( '<ul>' );
8664 this.$body = $( '<' + ( hasInputWidget ? 'label' : 'div' ) + '>' );
8665 this.align = null;
8666 if ( config.help ) {
8667 this.popupButtonWidget = new OO.ui.PopupButtonWidget( {
8668 classes: [ 'oo-ui-fieldLayout-help' ],
8669 framed: false,
8670 icon: 'info'
8671 } );
8672
8673 div = $( '<div>' );
8674 if ( config.help instanceof OO.ui.HtmlSnippet ) {
8675 div.html( config.help.toString() );
8676 } else {
8677 div.text( config.help );
8678 }
8679 this.popupButtonWidget.getPopup().$body.append(
8680 div.addClass( 'oo-ui-fieldLayout-help-content' )
8681 );
8682 this.$help = this.popupButtonWidget.$element;
8683 } else {
8684 this.$help = $( [] );
8685 }
8686
8687 // Events
8688 if ( hasInputWidget ) {
8689 this.$label.on( 'click', this.onLabelClick.bind( this ) );
8690 }
8691 this.fieldWidget.connect( this, { disable: 'onFieldDisable' } );
8692
8693 // Initialization
8694 this.$element
8695 .addClass( 'oo-ui-fieldLayout' )
8696 .append( this.$help, this.$body );
8697 if ( this.errors.length || this.notices.length ) {
8698 this.$element.append( this.$messages );
8699 }
8700 this.$body.addClass( 'oo-ui-fieldLayout-body' );
8701 this.$messages.addClass( 'oo-ui-fieldLayout-messages' );
8702 this.$field
8703 .addClass( 'oo-ui-fieldLayout-field' )
8704 .toggleClass( 'oo-ui-fieldLayout-disable', this.fieldWidget.isDisabled() )
8705 .append( this.fieldWidget.$element );
8706
8707 for ( i = 0; i < this.notices.length; i++ ) {
8708 this.$messages.append( this.makeMessage( 'notice', this.notices[i] ) );
8709 }
8710 for ( i = 0; i < this.errors.length; i++ ) {
8711 this.$messages.append( this.makeMessage( 'error', this.errors[i] ) );
8712 }
8713
8714 this.setAlignment( config.align );
8715 };
8716
8717 /* Setup */
8718
8719 OO.inheritClass( OO.ui.FieldLayout, OO.ui.Layout );
8720 OO.mixinClass( OO.ui.FieldLayout, OO.ui.mixin.LabelElement );
8721 OO.mixinClass( OO.ui.FieldLayout, OO.ui.mixin.TitledElement );
8722
8723 /* Methods */
8724
8725 /**
8726 * Handle field disable events.
8727 *
8728 * @private
8729 * @param {boolean} value Field is disabled
8730 */
8731 OO.ui.FieldLayout.prototype.onFieldDisable = function ( value ) {
8732 this.$element.toggleClass( 'oo-ui-fieldLayout-disabled', value );
8733 };
8734
8735 /**
8736 * Handle label mouse click events.
8737 *
8738 * @private
8739 * @param {jQuery.Event} e Mouse click event
8740 */
8741 OO.ui.FieldLayout.prototype.onLabelClick = function () {
8742 this.fieldWidget.simulateLabelClick();
8743 return false;
8744 };
8745
8746 /**
8747 * Get the widget contained by the field.
8748 *
8749 * @return {OO.ui.Widget} Field widget
8750 */
8751 OO.ui.FieldLayout.prototype.getField = function () {
8752 return this.fieldWidget;
8753 };
8754
8755 /**
8756 * @param {string} kind 'error' or 'notice'
8757 * @param {string|OO.ui.HtmlSnippet} text
8758 * @return {jQuery}
8759 */
8760 OO.ui.FieldLayout.prototype.makeMessage = function ( kind, text ) {
8761 var $listItem, $icon, message;
8762 $listItem = $( '<li>' );
8763 if ( kind === 'error' ) {
8764 $icon = new OO.ui.IconWidget( { icon: 'alert', flags: [ 'warning' ] } ).$element;
8765 } else if ( kind === 'notice' ) {
8766 $icon = new OO.ui.IconWidget( { icon: 'info' } ).$element;
8767 } else {
8768 $icon = '';
8769 }
8770 message = new OO.ui.LabelWidget( { label: text } );
8771 $listItem
8772 .append( $icon, message.$element )
8773 .addClass( 'oo-ui-fieldLayout-messages-' + kind );
8774 return $listItem;
8775 };
8776
8777 /**
8778 * Set the field alignment mode.
8779 *
8780 * @private
8781 * @param {string} value Alignment mode, either 'left', 'right', 'top' or 'inline'
8782 * @chainable
8783 */
8784 OO.ui.FieldLayout.prototype.setAlignment = function ( value ) {
8785 if ( value !== this.align ) {
8786 // Default to 'left'
8787 if ( [ 'left', 'right', 'top', 'inline' ].indexOf( value ) === -1 ) {
8788 value = 'left';
8789 }
8790 // Reorder elements
8791 if ( value === 'inline' ) {
8792 this.$body.append( this.$field, this.$label );
8793 } else {
8794 this.$body.append( this.$label, this.$field );
8795 }
8796 // Set classes. The following classes can be used here:
8797 // * oo-ui-fieldLayout-align-left
8798 // * oo-ui-fieldLayout-align-right
8799 // * oo-ui-fieldLayout-align-top
8800 // * oo-ui-fieldLayout-align-inline
8801 if ( this.align ) {
8802 this.$element.removeClass( 'oo-ui-fieldLayout-align-' + this.align );
8803 }
8804 this.$element.addClass( 'oo-ui-fieldLayout-align-' + value );
8805 this.align = value;
8806 }
8807
8808 return this;
8809 };
8810
8811 /**
8812 * ActionFieldLayouts are used with OO.ui.FieldsetLayout. The layout consists of a field-widget, a button,
8813 * and an optional label and/or help text. The field-widget (e.g., a {@link OO.ui.TextInputWidget TextInputWidget}),
8814 * is required and is specified before any optional configuration settings.
8815 *
8816 * Labels can be aligned in one of four ways:
8817 *
8818 * - **left**: The label is placed before the field-widget and aligned with the left margin.
8819 * A left-alignment is used for forms with many fields.
8820 * - **right**: The label is placed before the field-widget and aligned to the right margin.
8821 * A right-alignment is used for long but familiar forms which users tab through,
8822 * verifying the current field with a quick glance at the label.
8823 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
8824 * that users fill out from top to bottom.
8825 * - **inline**: The label is placed after the field-widget and aligned to the left.
8826 * An inline-alignment is best used with checkboxes or radio buttons.
8827 *
8828 * Help text is accessed via a help icon that appears in the upper right corner of the rendered field layout when help
8829 * text is specified.
8830 *
8831 * @example
8832 * // Example of an ActionFieldLayout
8833 * var actionFieldLayout = new OO.ui.ActionFieldLayout(
8834 * new OO.ui.TextInputWidget( {
8835 * placeholder: 'Field widget'
8836 * } ),
8837 * new OO.ui.ButtonWidget( {
8838 * label: 'Button'
8839 * } ),
8840 * {
8841 * label: 'An ActionFieldLayout. This label is aligned top',
8842 * align: 'top',
8843 * help: 'This is help text'
8844 * }
8845 * );
8846 *
8847 * $( 'body' ).append( actionFieldLayout.$element );
8848 *
8849 *
8850 * @class
8851 * @extends OO.ui.FieldLayout
8852 *
8853 * @constructor
8854 * @param {OO.ui.Widget} fieldWidget Field widget
8855 * @param {OO.ui.ButtonWidget} buttonWidget Button widget
8856 */
8857 OO.ui.ActionFieldLayout = function OoUiActionFieldLayout( fieldWidget, buttonWidget, config ) {
8858 // Allow passing positional parameters inside the config object
8859 if ( OO.isPlainObject( fieldWidget ) && config === undefined ) {
8860 config = fieldWidget;
8861 fieldWidget = config.fieldWidget;
8862 buttonWidget = config.buttonWidget;
8863 }
8864
8865 // Parent constructor
8866 OO.ui.ActionFieldLayout.parent.call( this, fieldWidget, config );
8867
8868 // Properties
8869 this.buttonWidget = buttonWidget;
8870 this.$button = $( '<div>' );
8871 this.$input = $( '<div>' );
8872
8873 // Initialization
8874 this.$element
8875 .addClass( 'oo-ui-actionFieldLayout' );
8876 this.$button
8877 .addClass( 'oo-ui-actionFieldLayout-button' )
8878 .append( this.buttonWidget.$element );
8879 this.$input
8880 .addClass( 'oo-ui-actionFieldLayout-input' )
8881 .append( this.fieldWidget.$element );
8882 this.$field
8883 .append( this.$input, this.$button );
8884 };
8885
8886 /* Setup */
8887
8888 OO.inheritClass( OO.ui.ActionFieldLayout, OO.ui.FieldLayout );
8889
8890 /**
8891 * FieldsetLayouts are composed of one or more {@link OO.ui.FieldLayout FieldLayouts},
8892 * which each contain an individual widget and, optionally, a label. Each Fieldset can be
8893 * configured with a label as well. For more information and examples,
8894 * please see the [OOjs UI documentation on MediaWiki][1].
8895 *
8896 * @example
8897 * // Example of a fieldset layout
8898 * var input1 = new OO.ui.TextInputWidget( {
8899 * placeholder: 'A text input field'
8900 * } );
8901 *
8902 * var input2 = new OO.ui.TextInputWidget( {
8903 * placeholder: 'A text input field'
8904 * } );
8905 *
8906 * var fieldset = new OO.ui.FieldsetLayout( {
8907 * label: 'Example of a fieldset layout'
8908 * } );
8909 *
8910 * fieldset.addItems( [
8911 * new OO.ui.FieldLayout( input1, {
8912 * label: 'Field One'
8913 * } ),
8914 * new OO.ui.FieldLayout( input2, {
8915 * label: 'Field Two'
8916 * } )
8917 * ] );
8918 * $( 'body' ).append( fieldset.$element );
8919 *
8920 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Fields_and_Fieldsets
8921 *
8922 * @class
8923 * @extends OO.ui.Layout
8924 * @mixins OO.ui.mixin.IconElement
8925 * @mixins OO.ui.mixin.LabelElement
8926 * @mixins OO.ui.mixin.GroupElement
8927 *
8928 * @constructor
8929 * @param {Object} [config] Configuration options
8930 * @cfg {OO.ui.FieldLayout[]} [items] An array of fields to add to the fieldset. See OO.ui.FieldLayout for more information about fields.
8931 */
8932 OO.ui.FieldsetLayout = function OoUiFieldsetLayout( config ) {
8933 // Configuration initialization
8934 config = config || {};
8935
8936 // Parent constructor
8937 OO.ui.FieldsetLayout.parent.call( this, config );
8938
8939 // Mixin constructors
8940 OO.ui.mixin.IconElement.call( this, config );
8941 OO.ui.mixin.LabelElement.call( this, config );
8942 OO.ui.mixin.GroupElement.call( this, config );
8943
8944 if ( config.help ) {
8945 this.popupButtonWidget = new OO.ui.PopupButtonWidget( {
8946 classes: [ 'oo-ui-fieldsetLayout-help' ],
8947 framed: false,
8948 icon: 'info'
8949 } );
8950
8951 this.popupButtonWidget.getPopup().$body.append(
8952 $( '<div>' )
8953 .text( config.help )
8954 .addClass( 'oo-ui-fieldsetLayout-help-content' )
8955 );
8956 this.$help = this.popupButtonWidget.$element;
8957 } else {
8958 this.$help = $( [] );
8959 }
8960
8961 // Initialization
8962 this.$element
8963 .addClass( 'oo-ui-fieldsetLayout' )
8964 .prepend( this.$help, this.$icon, this.$label, this.$group );
8965 if ( Array.isArray( config.items ) ) {
8966 this.addItems( config.items );
8967 }
8968 };
8969
8970 /* Setup */
8971
8972 OO.inheritClass( OO.ui.FieldsetLayout, OO.ui.Layout );
8973 OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.mixin.IconElement );
8974 OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.mixin.LabelElement );
8975 OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.mixin.GroupElement );
8976
8977 /**
8978 * FormLayouts are used to wrap {@link OO.ui.FieldsetLayout FieldsetLayouts} when you intend to use browser-based
8979 * form submission for the fields instead of handling them in JavaScript. Form layouts can be configured with an
8980 * HTML form action, an encoding type, and a method using the #action, #enctype, and #method configs, respectively.
8981 * See the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
8982 *
8983 * Only widgets from the {@link OO.ui.InputWidget InputWidget} family support form submission. It
8984 * includes standard form elements like {@link OO.ui.CheckboxInputWidget checkboxes}, {@link
8985 * OO.ui.RadioInputWidget radio buttons} and {@link OO.ui.TextInputWidget text fields}, as well as
8986 * some fancier controls. Some controls have both regular and InputWidget variants, for example
8987 * OO.ui.DropdownWidget and OO.ui.DropdownInputWidget – only the latter support form submission and
8988 * often have simplified APIs to match the capabilities of HTML forms.
8989 * See the [OOjs UI Inputs documentation on MediaWiki] [2] for more information about InputWidgets.
8990 *
8991 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Forms
8992 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
8993 *
8994 * @example
8995 * // Example of a form layout that wraps a fieldset layout
8996 * var input1 = new OO.ui.TextInputWidget( {
8997 * placeholder: 'Username'
8998 * } );
8999 * var input2 = new OO.ui.TextInputWidget( {
9000 * placeholder: 'Password',
9001 * type: 'password'
9002 * } );
9003 * var submit = new OO.ui.ButtonInputWidget( {
9004 * label: 'Submit'
9005 * } );
9006 *
9007 * var fieldset = new OO.ui.FieldsetLayout( {
9008 * label: 'A form layout'
9009 * } );
9010 * fieldset.addItems( [
9011 * new OO.ui.FieldLayout( input1, {
9012 * label: 'Username',
9013 * align: 'top'
9014 * } ),
9015 * new OO.ui.FieldLayout( input2, {
9016 * label: 'Password',
9017 * align: 'top'
9018 * } ),
9019 * new OO.ui.FieldLayout( submit )
9020 * ] );
9021 * var form = new OO.ui.FormLayout( {
9022 * items: [ fieldset ],
9023 * action: '/api/formhandler',
9024 * method: 'get'
9025 * } )
9026 * $( 'body' ).append( form.$element );
9027 *
9028 * @class
9029 * @extends OO.ui.Layout
9030 * @mixins OO.ui.mixin.GroupElement
9031 *
9032 * @constructor
9033 * @param {Object} [config] Configuration options
9034 * @cfg {string} [method] HTML form `method` attribute
9035 * @cfg {string} [action] HTML form `action` attribute
9036 * @cfg {string} [enctype] HTML form `enctype` attribute
9037 * @cfg {OO.ui.FieldsetLayout[]} [items] Fieldset layouts to add to the form layout.
9038 */
9039 OO.ui.FormLayout = function OoUiFormLayout( config ) {
9040 // Configuration initialization
9041 config = config || {};
9042
9043 // Parent constructor
9044 OO.ui.FormLayout.parent.call( this, config );
9045
9046 // Mixin constructors
9047 OO.ui.mixin.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) );
9048
9049 // Events
9050 this.$element.on( 'submit', this.onFormSubmit.bind( this ) );
9051
9052 // Make sure the action is safe
9053 if ( config.action !== undefined && !OO.ui.isSafeUrl( config.action ) ) {
9054 throw new Error( 'Potentially unsafe action provided: ' + config.action );
9055 }
9056
9057 // Initialization
9058 this.$element
9059 .addClass( 'oo-ui-formLayout' )
9060 .attr( {
9061 method: config.method,
9062 action: config.action,
9063 enctype: config.enctype
9064 } );
9065 if ( Array.isArray( config.items ) ) {
9066 this.addItems( config.items );
9067 }
9068 };
9069
9070 /* Setup */
9071
9072 OO.inheritClass( OO.ui.FormLayout, OO.ui.Layout );
9073 OO.mixinClass( OO.ui.FormLayout, OO.ui.mixin.GroupElement );
9074
9075 /* Events */
9076
9077 /**
9078 * A 'submit' event is emitted when the form is submitted.
9079 *
9080 * @event submit
9081 */
9082
9083 /* Static Properties */
9084
9085 OO.ui.FormLayout.static.tagName = 'form';
9086
9087 /* Methods */
9088
9089 /**
9090 * Handle form submit events.
9091 *
9092 * @private
9093 * @param {jQuery.Event} e Submit event
9094 * @fires submit
9095 */
9096 OO.ui.FormLayout.prototype.onFormSubmit = function () {
9097 if ( this.emit( 'submit' ) ) {
9098 return false;
9099 }
9100 };
9101
9102 /**
9103 * 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)
9104 * and its size is customized with the #menuSize config. The content area will fill all remaining space.
9105 *
9106 * @example
9107 * var menuLayout = new OO.ui.MenuLayout( {
9108 * position: 'top'
9109 * } ),
9110 * menuPanel = new OO.ui.PanelLayout( { padded: true, expanded: true, scrollable: true } ),
9111 * contentPanel = new OO.ui.PanelLayout( { padded: true, expanded: true, scrollable: true } ),
9112 * select = new OO.ui.SelectWidget( {
9113 * items: [
9114 * new OO.ui.OptionWidget( {
9115 * data: 'before',
9116 * label: 'Before',
9117 * } ),
9118 * new OO.ui.OptionWidget( {
9119 * data: 'after',
9120 * label: 'After',
9121 * } ),
9122 * new OO.ui.OptionWidget( {
9123 * data: 'top',
9124 * label: 'Top',
9125 * } ),
9126 * new OO.ui.OptionWidget( {
9127 * data: 'bottom',
9128 * label: 'Bottom',
9129 * } )
9130 * ]
9131 * } ).on( 'select', function ( item ) {
9132 * menuLayout.setMenuPosition( item.getData() );
9133 * } );
9134 *
9135 * menuLayout.$menu.append(
9136 * menuPanel.$element.append( '<b>Menu panel</b>', select.$element )
9137 * );
9138 * menuLayout.$content.append(
9139 * contentPanel.$element.append( '<b>Content panel</b>', '<p>Note that the menu is positioned relative to the content panel: top, bottom, after, before.</p>')
9140 * );
9141 * $( 'body' ).append( menuLayout.$element );
9142 *
9143 * If menu size needs to be overridden, it can be accomplished using CSS similar to the snippet
9144 * below. MenuLayout's CSS will override the appropriate values with 'auto' or '0' to display the
9145 * menu correctly. If `menuPosition` is known beforehand, CSS rules corresponding to other positions
9146 * may be omitted.
9147 *
9148 * .oo-ui-menuLayout-menu {
9149 * height: 200px;
9150 * width: 200px;
9151 * }
9152 * .oo-ui-menuLayout-content {
9153 * top: 200px;
9154 * left: 200px;
9155 * right: 200px;
9156 * bottom: 200px;
9157 * }
9158 *
9159 * @class
9160 * @extends OO.ui.Layout
9161 *
9162 * @constructor
9163 * @param {Object} [config] Configuration options
9164 * @cfg {boolean} [showMenu=true] Show menu
9165 * @cfg {string} [menuPosition='before'] Position of menu: `top`, `after`, `bottom` or `before`
9166 */
9167 OO.ui.MenuLayout = function OoUiMenuLayout( config ) {
9168 // Configuration initialization
9169 config = $.extend( {
9170 showMenu: true,
9171 menuPosition: 'before'
9172 }, config );
9173
9174 // Parent constructor
9175 OO.ui.MenuLayout.parent.call( this, config );
9176
9177 /**
9178 * Menu DOM node
9179 *
9180 * @property {jQuery}
9181 */
9182 this.$menu = $( '<div>' );
9183 /**
9184 * Content DOM node
9185 *
9186 * @property {jQuery}
9187 */
9188 this.$content = $( '<div>' );
9189
9190 // Initialization
9191 this.$menu
9192 .addClass( 'oo-ui-menuLayout-menu' );
9193 this.$content.addClass( 'oo-ui-menuLayout-content' );
9194 this.$element
9195 .addClass( 'oo-ui-menuLayout' )
9196 .append( this.$content, this.$menu );
9197 this.setMenuPosition( config.menuPosition );
9198 this.toggleMenu( config.showMenu );
9199 };
9200
9201 /* Setup */
9202
9203 OO.inheritClass( OO.ui.MenuLayout, OO.ui.Layout );
9204
9205 /* Methods */
9206
9207 /**
9208 * Toggle menu.
9209 *
9210 * @param {boolean} showMenu Show menu, omit to toggle
9211 * @chainable
9212 */
9213 OO.ui.MenuLayout.prototype.toggleMenu = function ( showMenu ) {
9214 showMenu = showMenu === undefined ? !this.showMenu : !!showMenu;
9215
9216 if ( this.showMenu !== showMenu ) {
9217 this.showMenu = showMenu;
9218 this.$element
9219 .toggleClass( 'oo-ui-menuLayout-showMenu', this.showMenu )
9220 .toggleClass( 'oo-ui-menuLayout-hideMenu', !this.showMenu );
9221 }
9222
9223 return this;
9224 };
9225
9226 /**
9227 * Check if menu is visible
9228 *
9229 * @return {boolean} Menu is visible
9230 */
9231 OO.ui.MenuLayout.prototype.isMenuVisible = function () {
9232 return this.showMenu;
9233 };
9234
9235 /**
9236 * Set menu position.
9237 *
9238 * @param {string} position Position of menu, either `top`, `after`, `bottom` or `before`
9239 * @throws {Error} If position value is not supported
9240 * @chainable
9241 */
9242 OO.ui.MenuLayout.prototype.setMenuPosition = function ( position ) {
9243 this.$element.removeClass( 'oo-ui-menuLayout-' + this.menuPosition );
9244 this.menuPosition = position;
9245 this.$element.addClass( 'oo-ui-menuLayout-' + position );
9246
9247 return this;
9248 };
9249
9250 /**
9251 * Get menu position.
9252 *
9253 * @return {string} Menu position
9254 */
9255 OO.ui.MenuLayout.prototype.getMenuPosition = function () {
9256 return this.menuPosition;
9257 };
9258
9259 /**
9260 * BookletLayouts contain {@link OO.ui.PageLayout page layouts} as well as
9261 * an {@link OO.ui.OutlineSelectWidget outline} that allows users to easily navigate
9262 * through the pages and select which one to display. By default, only one page is
9263 * displayed at a time and the outline is hidden. When a user navigates to a new page,
9264 * the booklet layout automatically focuses on the first focusable element, unless the
9265 * default setting is changed. Optionally, booklets can be configured to show
9266 * {@link OO.ui.OutlineControlsWidget controls} for adding, moving, and removing items.
9267 *
9268 * @example
9269 * // Example of a BookletLayout that contains two PageLayouts.
9270 *
9271 * function PageOneLayout( name, config ) {
9272 * PageOneLayout.parent.call( this, name, config );
9273 * this.$element.append( '<p>First page</p><p>(This booklet has an outline, displayed on the left)</p>' );
9274 * }
9275 * OO.inheritClass( PageOneLayout, OO.ui.PageLayout );
9276 * PageOneLayout.prototype.setupOutlineItem = function () {
9277 * this.outlineItem.setLabel( 'Page One' );
9278 * };
9279 *
9280 * function PageTwoLayout( name, config ) {
9281 * PageTwoLayout.parent.call( this, name, config );
9282 * this.$element.append( '<p>Second page</p>' );
9283 * }
9284 * OO.inheritClass( PageTwoLayout, OO.ui.PageLayout );
9285 * PageTwoLayout.prototype.setupOutlineItem = function () {
9286 * this.outlineItem.setLabel( 'Page Two' );
9287 * };
9288 *
9289 * var page1 = new PageOneLayout( 'one' ),
9290 * page2 = new PageTwoLayout( 'two' );
9291 *
9292 * var booklet = new OO.ui.BookletLayout( {
9293 * outlined: true
9294 * } );
9295 *
9296 * booklet.addPages ( [ page1, page2 ] );
9297 * $( 'body' ).append( booklet.$element );
9298 *
9299 * @class
9300 * @extends OO.ui.MenuLayout
9301 *
9302 * @constructor
9303 * @param {Object} [config] Configuration options
9304 * @cfg {boolean} [continuous=false] Show all pages, one after another
9305 * @cfg {boolean} [autoFocus=true] Focus on the first focusable element when a new page is displayed.
9306 * @cfg {boolean} [outlined=false] Show the outline. The outline is used to navigate through the pages of the booklet.
9307 * @cfg {boolean} [editable=false] Show controls for adding, removing and reordering pages
9308 */
9309 OO.ui.BookletLayout = function OoUiBookletLayout( config ) {
9310 // Configuration initialization
9311 config = config || {};
9312
9313 // Parent constructor
9314 OO.ui.BookletLayout.parent.call( this, config );
9315
9316 // Properties
9317 this.currentPageName = null;
9318 this.pages = {};
9319 this.ignoreFocus = false;
9320 this.stackLayout = new OO.ui.StackLayout( { continuous: !!config.continuous } );
9321 this.$content.append( this.stackLayout.$element );
9322 this.autoFocus = config.autoFocus === undefined || !!config.autoFocus;
9323 this.outlineVisible = false;
9324 this.outlined = !!config.outlined;
9325 if ( this.outlined ) {
9326 this.editable = !!config.editable;
9327 this.outlineControlsWidget = null;
9328 this.outlineSelectWidget = new OO.ui.OutlineSelectWidget();
9329 this.outlinePanel = new OO.ui.PanelLayout( { scrollable: true } );
9330 this.$menu.append( this.outlinePanel.$element );
9331 this.outlineVisible = true;
9332 if ( this.editable ) {
9333 this.outlineControlsWidget = new OO.ui.OutlineControlsWidget(
9334 this.outlineSelectWidget
9335 );
9336 }
9337 }
9338 this.toggleMenu( this.outlined );
9339
9340 // Events
9341 this.stackLayout.connect( this, { set: 'onStackLayoutSet' } );
9342 if ( this.outlined ) {
9343 this.outlineSelectWidget.connect( this, { select: 'onOutlineSelectWidgetSelect' } );
9344 }
9345 if ( this.autoFocus ) {
9346 // Event 'focus' does not bubble, but 'focusin' does
9347 this.stackLayout.$element.on( 'focusin', this.onStackLayoutFocus.bind( this ) );
9348 }
9349
9350 // Initialization
9351 this.$element.addClass( 'oo-ui-bookletLayout' );
9352 this.stackLayout.$element.addClass( 'oo-ui-bookletLayout-stackLayout' );
9353 if ( this.outlined ) {
9354 this.outlinePanel.$element
9355 .addClass( 'oo-ui-bookletLayout-outlinePanel' )
9356 .append( this.outlineSelectWidget.$element );
9357 if ( this.editable ) {
9358 this.outlinePanel.$element
9359 .addClass( 'oo-ui-bookletLayout-outlinePanel-editable' )
9360 .append( this.outlineControlsWidget.$element );
9361 }
9362 }
9363 };
9364
9365 /* Setup */
9366
9367 OO.inheritClass( OO.ui.BookletLayout, OO.ui.MenuLayout );
9368
9369 /* Events */
9370
9371 /**
9372 * A 'set' event is emitted when a page is {@link #setPage set} to be displayed by the booklet layout.
9373 * @event set
9374 * @param {OO.ui.PageLayout} page Current page
9375 */
9376
9377 /**
9378 * An 'add' event is emitted when pages are {@link #addPages added} to the booklet layout.
9379 *
9380 * @event add
9381 * @param {OO.ui.PageLayout[]} page Added pages
9382 * @param {number} index Index pages were added at
9383 */
9384
9385 /**
9386 * A 'remove' event is emitted when pages are {@link #clearPages cleared} or
9387 * {@link #removePages removed} from the booklet.
9388 *
9389 * @event remove
9390 * @param {OO.ui.PageLayout[]} pages Removed pages
9391 */
9392
9393 /* Methods */
9394
9395 /**
9396 * Handle stack layout focus.
9397 *
9398 * @private
9399 * @param {jQuery.Event} e Focusin event
9400 */
9401 OO.ui.BookletLayout.prototype.onStackLayoutFocus = function ( e ) {
9402 var name, $target;
9403
9404 // Find the page that an element was focused within
9405 $target = $( e.target ).closest( '.oo-ui-pageLayout' );
9406 for ( name in this.pages ) {
9407 // Check for page match, exclude current page to find only page changes
9408 if ( this.pages[ name ].$element[ 0 ] === $target[ 0 ] && name !== this.currentPageName ) {
9409 this.setPage( name );
9410 break;
9411 }
9412 }
9413 };
9414
9415 /**
9416 * Handle stack layout set events.
9417 *
9418 * @private
9419 * @param {OO.ui.PanelLayout|null} page The page panel that is now the current panel
9420 */
9421 OO.ui.BookletLayout.prototype.onStackLayoutSet = function ( page ) {
9422 var layout = this;
9423 if ( page ) {
9424 page.scrollElementIntoView( { complete: function () {
9425 if ( layout.autoFocus ) {
9426 layout.focus();
9427 }
9428 } } );
9429 }
9430 };
9431
9432 /**
9433 * Focus the first input in the current page.
9434 *
9435 * If no page is selected, the first selectable page will be selected.
9436 * If the focus is already in an element on the current page, nothing will happen.
9437 * @param {number} [itemIndex] A specific item to focus on
9438 */
9439 OO.ui.BookletLayout.prototype.focus = function ( itemIndex ) {
9440 var $input, page,
9441 items = this.stackLayout.getItems();
9442
9443 if ( itemIndex !== undefined && items[ itemIndex ] ) {
9444 page = items[ itemIndex ];
9445 } else {
9446 page = this.stackLayout.getCurrentItem();
9447 }
9448
9449 if ( !page && this.outlined ) {
9450 this.selectFirstSelectablePage();
9451 page = this.stackLayout.getCurrentItem();
9452 }
9453 if ( !page ) {
9454 return;
9455 }
9456 // Only change the focus if is not already in the current page
9457 if ( !page.$element.find( ':focus' ).length ) {
9458 $input = page.$element.find( ':input:first' );
9459 if ( $input.length ) {
9460 $input[ 0 ].focus();
9461 }
9462 }
9463 };
9464
9465 /**
9466 * Find the first focusable input in the booklet layout and focus
9467 * on it.
9468 */
9469 OO.ui.BookletLayout.prototype.focusFirstFocusable = function () {
9470 var i, len,
9471 found = false,
9472 items = this.stackLayout.getItems(),
9473 checkAndFocus = function () {
9474 if ( OO.ui.isFocusableElement( $( this ) ) ) {
9475 $( this ).focus();
9476 found = true;
9477 return false;
9478 }
9479 };
9480
9481 for ( i = 0, len = items.length; i < len; i++ ) {
9482 if ( found ) {
9483 break;
9484 }
9485 // Find all potentially focusable elements in the item
9486 // and check if they are focusable
9487 items[i].$element
9488 .find( 'input, select, textarea, button, object' )
9489 /* jshint loopfunc:true */
9490 .each( checkAndFocus );
9491 }
9492 };
9493
9494 /**
9495 * Handle outline widget select events.
9496 *
9497 * @private
9498 * @param {OO.ui.OptionWidget|null} item Selected item
9499 */
9500 OO.ui.BookletLayout.prototype.onOutlineSelectWidgetSelect = function ( item ) {
9501 if ( item ) {
9502 this.setPage( item.getData() );
9503 }
9504 };
9505
9506 /**
9507 * Check if booklet has an outline.
9508 *
9509 * @return {boolean} Booklet has an outline
9510 */
9511 OO.ui.BookletLayout.prototype.isOutlined = function () {
9512 return this.outlined;
9513 };
9514
9515 /**
9516 * Check if booklet has editing controls.
9517 *
9518 * @return {boolean} Booklet is editable
9519 */
9520 OO.ui.BookletLayout.prototype.isEditable = function () {
9521 return this.editable;
9522 };
9523
9524 /**
9525 * Check if booklet has a visible outline.
9526 *
9527 * @return {boolean} Outline is visible
9528 */
9529 OO.ui.BookletLayout.prototype.isOutlineVisible = function () {
9530 return this.outlined && this.outlineVisible;
9531 };
9532
9533 /**
9534 * Hide or show the outline.
9535 *
9536 * @param {boolean} [show] Show outline, omit to invert current state
9537 * @chainable
9538 */
9539 OO.ui.BookletLayout.prototype.toggleOutline = function ( show ) {
9540 if ( this.outlined ) {
9541 show = show === undefined ? !this.outlineVisible : !!show;
9542 this.outlineVisible = show;
9543 this.toggleMenu( show );
9544 }
9545
9546 return this;
9547 };
9548
9549 /**
9550 * Get the page closest to the specified page.
9551 *
9552 * @param {OO.ui.PageLayout} page Page to use as a reference point
9553 * @return {OO.ui.PageLayout|null} Page closest to the specified page
9554 */
9555 OO.ui.BookletLayout.prototype.getClosestPage = function ( page ) {
9556 var next, prev, level,
9557 pages = this.stackLayout.getItems(),
9558 index = $.inArray( page, pages );
9559
9560 if ( index !== -1 ) {
9561 next = pages[ index + 1 ];
9562 prev = pages[ index - 1 ];
9563 // Prefer adjacent pages at the same level
9564 if ( this.outlined ) {
9565 level = this.outlineSelectWidget.getItemFromData( page.getName() ).getLevel();
9566 if (
9567 prev &&
9568 level === this.outlineSelectWidget.getItemFromData( prev.getName() ).getLevel()
9569 ) {
9570 return prev;
9571 }
9572 if (
9573 next &&
9574 level === this.outlineSelectWidget.getItemFromData( next.getName() ).getLevel()
9575 ) {
9576 return next;
9577 }
9578 }
9579 }
9580 return prev || next || null;
9581 };
9582
9583 /**
9584 * Get the outline widget.
9585 *
9586 * If the booklet is not outlined, the method will return `null`.
9587 *
9588 * @return {OO.ui.OutlineSelectWidget|null} Outline widget, or null if the booklet is not outlined
9589 */
9590 OO.ui.BookletLayout.prototype.getOutline = function () {
9591 return this.outlineSelectWidget;
9592 };
9593
9594 /**
9595 * Get the outline controls widget.
9596 *
9597 * If the outline is not editable, the method will return `null`.
9598 *
9599 * @return {OO.ui.OutlineControlsWidget|null} The outline controls widget.
9600 */
9601 OO.ui.BookletLayout.prototype.getOutlineControls = function () {
9602 return this.outlineControlsWidget;
9603 };
9604
9605 /**
9606 * Get a page by its symbolic name.
9607 *
9608 * @param {string} name Symbolic name of page
9609 * @return {OO.ui.PageLayout|undefined} Page, if found
9610 */
9611 OO.ui.BookletLayout.prototype.getPage = function ( name ) {
9612 return this.pages[ name ];
9613 };
9614
9615 /**
9616 * Get the current page.
9617 *
9618 * @return {OO.ui.PageLayout|undefined} Current page, if found
9619 */
9620 OO.ui.BookletLayout.prototype.getCurrentPage = function () {
9621 var name = this.getCurrentPageName();
9622 return name ? this.getPage( name ) : undefined;
9623 };
9624
9625 /**
9626 * Get the symbolic name of the current page.
9627 *
9628 * @return {string|null} Symbolic name of the current page
9629 */
9630 OO.ui.BookletLayout.prototype.getCurrentPageName = function () {
9631 return this.currentPageName;
9632 };
9633
9634 /**
9635 * Add pages to the booklet layout
9636 *
9637 * When pages are added with the same names as existing pages, the existing pages will be
9638 * automatically removed before the new pages are added.
9639 *
9640 * @param {OO.ui.PageLayout[]} pages Pages to add
9641 * @param {number} index Index of the insertion point
9642 * @fires add
9643 * @chainable
9644 */
9645 OO.ui.BookletLayout.prototype.addPages = function ( pages, index ) {
9646 var i, len, name, page, item, currentIndex,
9647 stackLayoutPages = this.stackLayout.getItems(),
9648 remove = [],
9649 items = [];
9650
9651 // Remove pages with same names
9652 for ( i = 0, len = pages.length; i < len; i++ ) {
9653 page = pages[ i ];
9654 name = page.getName();
9655
9656 if ( Object.prototype.hasOwnProperty.call( this.pages, name ) ) {
9657 // Correct the insertion index
9658 currentIndex = $.inArray( this.pages[ name ], stackLayoutPages );
9659 if ( currentIndex !== -1 && currentIndex + 1 < index ) {
9660 index--;
9661 }
9662 remove.push( this.pages[ name ] );
9663 }
9664 }
9665 if ( remove.length ) {
9666 this.removePages( remove );
9667 }
9668
9669 // Add new pages
9670 for ( i = 0, len = pages.length; i < len; i++ ) {
9671 page = pages[ i ];
9672 name = page.getName();
9673 this.pages[ page.getName() ] = page;
9674 if ( this.outlined ) {
9675 item = new OO.ui.OutlineOptionWidget( { data: name } );
9676 page.setOutlineItem( item );
9677 items.push( item );
9678 }
9679 }
9680
9681 if ( this.outlined && items.length ) {
9682 this.outlineSelectWidget.addItems( items, index );
9683 this.selectFirstSelectablePage();
9684 }
9685 this.stackLayout.addItems( pages, index );
9686 this.emit( 'add', pages, index );
9687
9688 return this;
9689 };
9690
9691 /**
9692 * Remove the specified pages from the booklet layout.
9693 *
9694 * To remove all pages from the booklet, you may wish to use the #clearPages method instead.
9695 *
9696 * @param {OO.ui.PageLayout[]} pages An array of pages to remove
9697 * @fires remove
9698 * @chainable
9699 */
9700 OO.ui.BookletLayout.prototype.removePages = function ( pages ) {
9701 var i, len, name, page,
9702 items = [];
9703
9704 for ( i = 0, len = pages.length; i < len; i++ ) {
9705 page = pages[ i ];
9706 name = page.getName();
9707 delete this.pages[ name ];
9708 if ( this.outlined ) {
9709 items.push( this.outlineSelectWidget.getItemFromData( name ) );
9710 page.setOutlineItem( null );
9711 }
9712 }
9713 if ( this.outlined && items.length ) {
9714 this.outlineSelectWidget.removeItems( items );
9715 this.selectFirstSelectablePage();
9716 }
9717 this.stackLayout.removeItems( pages );
9718 this.emit( 'remove', pages );
9719
9720 return this;
9721 };
9722
9723 /**
9724 * Clear all pages from the booklet layout.
9725 *
9726 * To remove only a subset of pages from the booklet, use the #removePages method.
9727 *
9728 * @fires remove
9729 * @chainable
9730 */
9731 OO.ui.BookletLayout.prototype.clearPages = function () {
9732 var i, len,
9733 pages = this.stackLayout.getItems();
9734
9735 this.pages = {};
9736 this.currentPageName = null;
9737 if ( this.outlined ) {
9738 this.outlineSelectWidget.clearItems();
9739 for ( i = 0, len = pages.length; i < len; i++ ) {
9740 pages[ i ].setOutlineItem( null );
9741 }
9742 }
9743 this.stackLayout.clearItems();
9744
9745 this.emit( 'remove', pages );
9746
9747 return this;
9748 };
9749
9750 /**
9751 * Set the current page by symbolic name.
9752 *
9753 * @fires set
9754 * @param {string} name Symbolic name of page
9755 */
9756 OO.ui.BookletLayout.prototype.setPage = function ( name ) {
9757 var selectedItem,
9758 $focused,
9759 page = this.pages[ name ];
9760
9761 if ( name !== this.currentPageName ) {
9762 if ( this.outlined ) {
9763 selectedItem = this.outlineSelectWidget.getSelectedItem();
9764 if ( selectedItem && selectedItem.getData() !== name ) {
9765 this.outlineSelectWidget.selectItemByData( name );
9766 }
9767 }
9768 if ( page ) {
9769 if ( this.currentPageName && this.pages[ this.currentPageName ] ) {
9770 this.pages[ this.currentPageName ].setActive( false );
9771 // Blur anything focused if the next page doesn't have anything focusable - this
9772 // is not needed if the next page has something focusable because once it is focused
9773 // this blur happens automatically
9774 if ( this.autoFocus && !page.$element.find( ':input' ).length ) {
9775 $focused = this.pages[ this.currentPageName ].$element.find( ':focus' );
9776 if ( $focused.length ) {
9777 $focused[ 0 ].blur();
9778 }
9779 }
9780 }
9781 this.currentPageName = name;
9782 this.stackLayout.setItem( page );
9783 page.setActive( true );
9784 this.emit( 'set', page );
9785 }
9786 }
9787 };
9788
9789 /**
9790 * Select the first selectable page.
9791 *
9792 * @chainable
9793 */
9794 OO.ui.BookletLayout.prototype.selectFirstSelectablePage = function () {
9795 if ( !this.outlineSelectWidget.getSelectedItem() ) {
9796 this.outlineSelectWidget.selectItem( this.outlineSelectWidget.getFirstSelectableItem() );
9797 }
9798
9799 return this;
9800 };
9801
9802 /**
9803 * IndexLayouts contain {@link OO.ui.CardLayout card layouts} as well as
9804 * {@link OO.ui.TabSelectWidget tabs} that allow users to easily navigate through the cards and
9805 * select which one to display. By default, only one card is displayed at a time. When a user
9806 * navigates to a new card, the index layout automatically focuses on the first focusable element,
9807 * unless the default setting is changed.
9808 *
9809 * TODO: This class is similar to BookletLayout, we may want to refactor to reduce duplication
9810 *
9811 * @example
9812 * // Example of a IndexLayout that contains two CardLayouts.
9813 *
9814 * function CardOneLayout( name, config ) {
9815 * CardOneLayout.parent.call( this, name, config );
9816 * this.$element.append( '<p>First card</p>' );
9817 * }
9818 * OO.inheritClass( CardOneLayout, OO.ui.CardLayout );
9819 * CardOneLayout.prototype.setupTabItem = function () {
9820 * this.tabItem.setLabel( 'Card One' );
9821 * };
9822 *
9823 * function CardTwoLayout( name, config ) {
9824 * CardTwoLayout.parent.call( this, name, config );
9825 * this.$element.append( '<p>Second card</p>' );
9826 * }
9827 * OO.inheritClass( CardTwoLayout, OO.ui.CardLayout );
9828 * CardTwoLayout.prototype.setupTabItem = function () {
9829 * this.tabItem.setLabel( 'Card Two' );
9830 * };
9831 *
9832 * var card1 = new CardOneLayout( 'one' ),
9833 * card2 = new CardTwoLayout( 'two' );
9834 *
9835 * var index = new OO.ui.IndexLayout();
9836 *
9837 * index.addCards ( [ card1, card2 ] );
9838 * $( 'body' ).append( index.$element );
9839 *
9840 * @class
9841 * @extends OO.ui.MenuLayout
9842 *
9843 * @constructor
9844 * @param {Object} [config] Configuration options
9845 * @cfg {boolean} [continuous=false] Show all cards, one after another
9846 * @cfg {boolean} [autoFocus=true] Focus on the first focusable element when a new card is displayed.
9847 */
9848 OO.ui.IndexLayout = function OoUiIndexLayout( config ) {
9849 // Configuration initialization
9850 config = $.extend( {}, config, { menuPosition: 'top' } );
9851
9852 // Parent constructor
9853 OO.ui.IndexLayout.parent.call( this, config );
9854
9855 // Properties
9856 this.currentCardName = null;
9857 this.cards = {};
9858 this.ignoreFocus = false;
9859 this.stackLayout = new OO.ui.StackLayout( { continuous: !!config.continuous } );
9860 this.$content.append( this.stackLayout.$element );
9861 this.autoFocus = config.autoFocus === undefined || !!config.autoFocus;
9862
9863 this.tabSelectWidget = new OO.ui.TabSelectWidget();
9864 this.tabPanel = new OO.ui.PanelLayout();
9865 this.$menu.append( this.tabPanel.$element );
9866
9867 this.toggleMenu( true );
9868
9869 // Events
9870 this.stackLayout.connect( this, { set: 'onStackLayoutSet' } );
9871 this.tabSelectWidget.connect( this, { select: 'onTabSelectWidgetSelect' } );
9872 if ( this.autoFocus ) {
9873 // Event 'focus' does not bubble, but 'focusin' does
9874 this.stackLayout.$element.on( 'focusin', this.onStackLayoutFocus.bind( this ) );
9875 }
9876
9877 // Initialization
9878 this.$element.addClass( 'oo-ui-indexLayout' );
9879 this.stackLayout.$element.addClass( 'oo-ui-indexLayout-stackLayout' );
9880 this.tabPanel.$element
9881 .addClass( 'oo-ui-indexLayout-tabPanel' )
9882 .append( this.tabSelectWidget.$element );
9883 };
9884
9885 /* Setup */
9886
9887 OO.inheritClass( OO.ui.IndexLayout, OO.ui.MenuLayout );
9888
9889 /* Events */
9890
9891 /**
9892 * A 'set' event is emitted when a card is {@link #setCard set} to be displayed by the index layout.
9893 * @event set
9894 * @param {OO.ui.CardLayout} card Current card
9895 */
9896
9897 /**
9898 * An 'add' event is emitted when cards are {@link #addCards added} to the index layout.
9899 *
9900 * @event add
9901 * @param {OO.ui.CardLayout[]} card Added cards
9902 * @param {number} index Index cards were added at
9903 */
9904
9905 /**
9906 * A 'remove' event is emitted when cards are {@link #clearCards cleared} or
9907 * {@link #removeCards removed} from the index.
9908 *
9909 * @event remove
9910 * @param {OO.ui.CardLayout[]} cards Removed cards
9911 */
9912
9913 /* Methods */
9914
9915 /**
9916 * Handle stack layout focus.
9917 *
9918 * @private
9919 * @param {jQuery.Event} e Focusin event
9920 */
9921 OO.ui.IndexLayout.prototype.onStackLayoutFocus = function ( e ) {
9922 var name, $target;
9923
9924 // Find the card that an element was focused within
9925 $target = $( e.target ).closest( '.oo-ui-cardLayout' );
9926 for ( name in this.cards ) {
9927 // Check for card match, exclude current card to find only card changes
9928 if ( this.cards[ name ].$element[ 0 ] === $target[ 0 ] && name !== this.currentCardName ) {
9929 this.setCard( name );
9930 break;
9931 }
9932 }
9933 };
9934
9935 /**
9936 * Handle stack layout set events.
9937 *
9938 * @private
9939 * @param {OO.ui.PanelLayout|null} card The card panel that is now the current panel
9940 */
9941 OO.ui.IndexLayout.prototype.onStackLayoutSet = function ( card ) {
9942 var layout = this;
9943 if ( card ) {
9944 card.scrollElementIntoView( { complete: function () {
9945 if ( layout.autoFocus ) {
9946 layout.focus();
9947 }
9948 } } );
9949 }
9950 };
9951
9952 /**
9953 * Focus the first input in the current card.
9954 *
9955 * If no card is selected, the first selectable card will be selected.
9956 * If the focus is already in an element on the current card, nothing will happen.
9957 * @param {number} [itemIndex] A specific item to focus on
9958 */
9959 OO.ui.IndexLayout.prototype.focus = function ( itemIndex ) {
9960 var $input, card,
9961 items = this.stackLayout.getItems();
9962
9963 if ( itemIndex !== undefined && items[ itemIndex ] ) {
9964 card = items[ itemIndex ];
9965 } else {
9966 card = this.stackLayout.getCurrentItem();
9967 }
9968
9969 if ( !card ) {
9970 this.selectFirstSelectableCard();
9971 card = this.stackLayout.getCurrentItem();
9972 }
9973 if ( !card ) {
9974 return;
9975 }
9976 // Only change the focus if is not already in the current card
9977 if ( !card.$element.find( ':focus' ).length ) {
9978 $input = card.$element.find( ':input:first' );
9979 if ( $input.length ) {
9980 $input[ 0 ].focus();
9981 }
9982 }
9983 };
9984
9985 /**
9986 * Find the first focusable input in the index layout and focus
9987 * on it.
9988 */
9989 OO.ui.IndexLayout.prototype.focusFirstFocusable = function () {
9990 var i, len,
9991 found = false,
9992 items = this.stackLayout.getItems(),
9993 checkAndFocus = function () {
9994 if ( OO.ui.isFocusableElement( $( this ) ) ) {
9995 $( this ).focus();
9996 found = true;
9997 return false;
9998 }
9999 };
10000
10001 for ( i = 0, len = items.length; i < len; i++ ) {
10002 if ( found ) {
10003 break;
10004 }
10005 // Find all potentially focusable elements in the item
10006 // and check if they are focusable
10007 items[i].$element
10008 .find( 'input, select, textarea, button, object' )
10009 .each( checkAndFocus );
10010 }
10011 };
10012
10013 /**
10014 * Handle tab widget select events.
10015 *
10016 * @private
10017 * @param {OO.ui.OptionWidget|null} item Selected item
10018 */
10019 OO.ui.IndexLayout.prototype.onTabSelectWidgetSelect = function ( item ) {
10020 if ( item ) {
10021 this.setCard( item.getData() );
10022 }
10023 };
10024
10025 /**
10026 * Get the card closest to the specified card.
10027 *
10028 * @param {OO.ui.CardLayout} card Card to use as a reference point
10029 * @return {OO.ui.CardLayout|null} Card closest to the specified card
10030 */
10031 OO.ui.IndexLayout.prototype.getClosestCard = function ( card ) {
10032 var next, prev, level,
10033 cards = this.stackLayout.getItems(),
10034 index = $.inArray( card, cards );
10035
10036 if ( index !== -1 ) {
10037 next = cards[ index + 1 ];
10038 prev = cards[ index - 1 ];
10039 // Prefer adjacent cards at the same level
10040 level = this.tabSelectWidget.getItemFromData( card.getName() ).getLevel();
10041 if (
10042 prev &&
10043 level === this.tabSelectWidget.getItemFromData( prev.getName() ).getLevel()
10044 ) {
10045 return prev;
10046 }
10047 if (
10048 next &&
10049 level === this.tabSelectWidget.getItemFromData( next.getName() ).getLevel()
10050 ) {
10051 return next;
10052 }
10053 }
10054 return prev || next || null;
10055 };
10056
10057 /**
10058 * Get the tabs widget.
10059 *
10060 * @return {OO.ui.TabSelectWidget} Tabs widget
10061 */
10062 OO.ui.IndexLayout.prototype.getTabs = function () {
10063 return this.tabSelectWidget;
10064 };
10065
10066 /**
10067 * Get a card by its symbolic name.
10068 *
10069 * @param {string} name Symbolic name of card
10070 * @return {OO.ui.CardLayout|undefined} Card, if found
10071 */
10072 OO.ui.IndexLayout.prototype.getCard = function ( name ) {
10073 return this.cards[ name ];
10074 };
10075
10076 /**
10077 * Get the current card.
10078 *
10079 * @return {OO.ui.CardLayout|undefined} Current card, if found
10080 */
10081 OO.ui.IndexLayout.prototype.getCurrentCard = function () {
10082 var name = this.getCurrentCardName();
10083 return name ? this.getCard( name ) : undefined;
10084 };
10085
10086 /**
10087 * Get the symbolic name of the current card.
10088 *
10089 * @return {string|null} Symbolic name of the current card
10090 */
10091 OO.ui.IndexLayout.prototype.getCurrentCardName = function () {
10092 return this.currentCardName;
10093 };
10094
10095 /**
10096 * Add cards to the index layout
10097 *
10098 * When cards are added with the same names as existing cards, the existing cards will be
10099 * automatically removed before the new cards are added.
10100 *
10101 * @param {OO.ui.CardLayout[]} cards Cards to add
10102 * @param {number} index Index of the insertion point
10103 * @fires add
10104 * @chainable
10105 */
10106 OO.ui.IndexLayout.prototype.addCards = function ( cards, index ) {
10107 var i, len, name, card, item, currentIndex,
10108 stackLayoutCards = this.stackLayout.getItems(),
10109 remove = [],
10110 items = [];
10111
10112 // Remove cards with same names
10113 for ( i = 0, len = cards.length; i < len; i++ ) {
10114 card = cards[ i ];
10115 name = card.getName();
10116
10117 if ( Object.prototype.hasOwnProperty.call( this.cards, name ) ) {
10118 // Correct the insertion index
10119 currentIndex = $.inArray( this.cards[ name ], stackLayoutCards );
10120 if ( currentIndex !== -1 && currentIndex + 1 < index ) {
10121 index--;
10122 }
10123 remove.push( this.cards[ name ] );
10124 }
10125 }
10126 if ( remove.length ) {
10127 this.removeCards( remove );
10128 }
10129
10130 // Add new cards
10131 for ( i = 0, len = cards.length; i < len; i++ ) {
10132 card = cards[ i ];
10133 name = card.getName();
10134 this.cards[ card.getName() ] = card;
10135 item = new OO.ui.TabOptionWidget( { data: name } );
10136 card.setTabItem( item );
10137 items.push( item );
10138 }
10139
10140 if ( items.length ) {
10141 this.tabSelectWidget.addItems( items, index );
10142 this.selectFirstSelectableCard();
10143 }
10144 this.stackLayout.addItems( cards, index );
10145 this.emit( 'add', cards, index );
10146
10147 return this;
10148 };
10149
10150 /**
10151 * Remove the specified cards from the index layout.
10152 *
10153 * To remove all cards from the index, you may wish to use the #clearCards method instead.
10154 *
10155 * @param {OO.ui.CardLayout[]} cards An array of cards to remove
10156 * @fires remove
10157 * @chainable
10158 */
10159 OO.ui.IndexLayout.prototype.removeCards = function ( cards ) {
10160 var i, len, name, card,
10161 items = [];
10162
10163 for ( i = 0, len = cards.length; i < len; i++ ) {
10164 card = cards[ i ];
10165 name = card.getName();
10166 delete this.cards[ name ];
10167 items.push( this.tabSelectWidget.getItemFromData( name ) );
10168 card.setTabItem( null );
10169 }
10170 if ( items.length ) {
10171 this.tabSelectWidget.removeItems( items );
10172 this.selectFirstSelectableCard();
10173 }
10174 this.stackLayout.removeItems( cards );
10175 this.emit( 'remove', cards );
10176
10177 return this;
10178 };
10179
10180 /**
10181 * Clear all cards from the index layout.
10182 *
10183 * To remove only a subset of cards from the index, use the #removeCards method.
10184 *
10185 * @fires remove
10186 * @chainable
10187 */
10188 OO.ui.IndexLayout.prototype.clearCards = function () {
10189 var i, len,
10190 cards = this.stackLayout.getItems();
10191
10192 this.cards = {};
10193 this.currentCardName = null;
10194 this.tabSelectWidget.clearItems();
10195 for ( i = 0, len = cards.length; i < len; i++ ) {
10196 cards[ i ].setTabItem( null );
10197 }
10198 this.stackLayout.clearItems();
10199
10200 this.emit( 'remove', cards );
10201
10202 return this;
10203 };
10204
10205 /**
10206 * Set the current card by symbolic name.
10207 *
10208 * @fires set
10209 * @param {string} name Symbolic name of card
10210 */
10211 OO.ui.IndexLayout.prototype.setCard = function ( name ) {
10212 var selectedItem,
10213 $focused,
10214 card = this.cards[ name ];
10215
10216 if ( name !== this.currentCardName ) {
10217 selectedItem = this.tabSelectWidget.getSelectedItem();
10218 if ( selectedItem && selectedItem.getData() !== name ) {
10219 this.tabSelectWidget.selectItemByData( name );
10220 }
10221 if ( card ) {
10222 if ( this.currentCardName && this.cards[ this.currentCardName ] ) {
10223 this.cards[ this.currentCardName ].setActive( false );
10224 // Blur anything focused if the next card doesn't have anything focusable - this
10225 // is not needed if the next card has something focusable because once it is focused
10226 // this blur happens automatically
10227 if ( this.autoFocus && !card.$element.find( ':input' ).length ) {
10228 $focused = this.cards[ this.currentCardName ].$element.find( ':focus' );
10229 if ( $focused.length ) {
10230 $focused[ 0 ].blur();
10231 }
10232 }
10233 }
10234 this.currentCardName = name;
10235 this.stackLayout.setItem( card );
10236 card.setActive( true );
10237 this.emit( 'set', card );
10238 }
10239 }
10240 };
10241
10242 /**
10243 * Select the first selectable card.
10244 *
10245 * @chainable
10246 */
10247 OO.ui.IndexLayout.prototype.selectFirstSelectableCard = function () {
10248 if ( !this.tabSelectWidget.getSelectedItem() ) {
10249 this.tabSelectWidget.selectItem( this.tabSelectWidget.getFirstSelectableItem() );
10250 }
10251
10252 return this;
10253 };
10254
10255 /**
10256 * PanelLayouts expand to cover the entire area of their parent. They can be configured with scrolling, padding,
10257 * and a frame, and are often used together with {@link OO.ui.StackLayout StackLayouts}.
10258 *
10259 * @example
10260 * // Example of a panel layout
10261 * var panel = new OO.ui.PanelLayout( {
10262 * expanded: false,
10263 * framed: true,
10264 * padded: true,
10265 * $content: $( '<p>A panel layout with padding and a frame.</p>' )
10266 * } );
10267 * $( 'body' ).append( panel.$element );
10268 *
10269 * @class
10270 * @extends OO.ui.Layout
10271 *
10272 * @constructor
10273 * @param {Object} [config] Configuration options
10274 * @cfg {boolean} [scrollable=false] Allow vertical scrolling
10275 * @cfg {boolean} [padded=false] Add padding between the content and the edges of the panel.
10276 * @cfg {boolean} [expanded=true] Expand the panel to fill the entire parent element.
10277 * @cfg {boolean} [framed=false] Render the panel with a frame to visually separate it from outside content.
10278 */
10279 OO.ui.PanelLayout = function OoUiPanelLayout( config ) {
10280 // Configuration initialization
10281 config = $.extend( {
10282 scrollable: false,
10283 padded: false,
10284 expanded: true,
10285 framed: false
10286 }, config );
10287
10288 // Parent constructor
10289 OO.ui.PanelLayout.parent.call( this, config );
10290
10291 // Initialization
10292 this.$element.addClass( 'oo-ui-panelLayout' );
10293 if ( config.scrollable ) {
10294 this.$element.addClass( 'oo-ui-panelLayout-scrollable' );
10295 }
10296 if ( config.padded ) {
10297 this.$element.addClass( 'oo-ui-panelLayout-padded' );
10298 }
10299 if ( config.expanded ) {
10300 this.$element.addClass( 'oo-ui-panelLayout-expanded' );
10301 }
10302 if ( config.framed ) {
10303 this.$element.addClass( 'oo-ui-panelLayout-framed' );
10304 }
10305 };
10306
10307 /* Setup */
10308
10309 OO.inheritClass( OO.ui.PanelLayout, OO.ui.Layout );
10310
10311 /**
10312 * CardLayouts are used within {@link OO.ui.IndexLayout index layouts} to create cards that users can select and display
10313 * from the index's optional {@link OO.ui.TabSelectWidget tab} navigation. Cards are usually not instantiated directly,
10314 * rather extended to include the required content and functionality.
10315 *
10316 * Each card must have a unique symbolic name, which is passed to the constructor. In addition, the card's tab
10317 * item is customized (with a label) using the #setupTabItem method. See
10318 * {@link OO.ui.IndexLayout IndexLayout} for an example.
10319 *
10320 * @class
10321 * @extends OO.ui.PanelLayout
10322 *
10323 * @constructor
10324 * @param {string} name Unique symbolic name of card
10325 * @param {Object} [config] Configuration options
10326 */
10327 OO.ui.CardLayout = function OoUiCardLayout( name, config ) {
10328 // Allow passing positional parameters inside the config object
10329 if ( OO.isPlainObject( name ) && config === undefined ) {
10330 config = name;
10331 name = config.name;
10332 }
10333
10334 // Configuration initialization
10335 config = $.extend( { scrollable: true }, config );
10336
10337 // Parent constructor
10338 OO.ui.CardLayout.parent.call( this, config );
10339
10340 // Properties
10341 this.name = name;
10342 this.tabItem = null;
10343 this.active = false;
10344
10345 // Initialization
10346 this.$element.addClass( 'oo-ui-cardLayout' );
10347 };
10348
10349 /* Setup */
10350
10351 OO.inheritClass( OO.ui.CardLayout, OO.ui.PanelLayout );
10352
10353 /* Events */
10354
10355 /**
10356 * An 'active' event is emitted when the card becomes active. Cards become active when they are
10357 * shown in a index layout that is configured to display only one card at a time.
10358 *
10359 * @event active
10360 * @param {boolean} active Card is active
10361 */
10362
10363 /* Methods */
10364
10365 /**
10366 * Get the symbolic name of the card.
10367 *
10368 * @return {string} Symbolic name of card
10369 */
10370 OO.ui.CardLayout.prototype.getName = function () {
10371 return this.name;
10372 };
10373
10374 /**
10375 * Check if card is active.
10376 *
10377 * Cards become active when they are shown in a {@link OO.ui.IndexLayout index layout} that is configured to display
10378 * only one card at a time. Additional CSS is applied to the card's tab item to reflect the active state.
10379 *
10380 * @return {boolean} Card is active
10381 */
10382 OO.ui.CardLayout.prototype.isActive = function () {
10383 return this.active;
10384 };
10385
10386 /**
10387 * Get tab item.
10388 *
10389 * The tab item allows users to access the card from the index's tab
10390 * navigation. The tab item itself can be customized (with a label, level, etc.) using the #setupTabItem method.
10391 *
10392 * @return {OO.ui.TabOptionWidget|null} Tab option widget
10393 */
10394 OO.ui.CardLayout.prototype.getTabItem = function () {
10395 return this.tabItem;
10396 };
10397
10398 /**
10399 * Set or unset the tab item.
10400 *
10401 * Specify a {@link OO.ui.TabOptionWidget tab option} to set it,
10402 * or `null` to clear the tab item. To customize the tab item itself (e.g., to set a label or tab
10403 * level), use #setupTabItem instead of this method.
10404 *
10405 * @param {OO.ui.TabOptionWidget|null} tabItem Tab option widget, null to clear
10406 * @chainable
10407 */
10408 OO.ui.CardLayout.prototype.setTabItem = function ( tabItem ) {
10409 this.tabItem = tabItem || null;
10410 if ( tabItem ) {
10411 this.setupTabItem();
10412 }
10413 return this;
10414 };
10415
10416 /**
10417 * Set up the tab item.
10418 *
10419 * Use this method to customize the tab item (e.g., to add a label or tab level). To set or unset
10420 * the tab item itself (with a {@link OO.ui.TabOptionWidget tab option} or `null`), use
10421 * the #setTabItem method instead.
10422 *
10423 * @param {OO.ui.TabOptionWidget} tabItem Tab option widget to set up
10424 * @chainable
10425 */
10426 OO.ui.CardLayout.prototype.setupTabItem = function () {
10427 return this;
10428 };
10429
10430 /**
10431 * Set the card to its 'active' state.
10432 *
10433 * Cards become active when they are shown in a index layout that is configured to display only one card at a time. Additional
10434 * CSS is applied to the tab item to reflect the card's active state. Outside of the index
10435 * context, setting the active state on a card does nothing.
10436 *
10437 * @param {boolean} value Card is active
10438 * @fires active
10439 */
10440 OO.ui.CardLayout.prototype.setActive = function ( active ) {
10441 active = !!active;
10442
10443 if ( active !== this.active ) {
10444 this.active = active;
10445 this.$element.toggleClass( 'oo-ui-cardLayout-active', this.active );
10446 this.emit( 'active', this.active );
10447 }
10448 };
10449
10450 /**
10451 * PageLayouts are used within {@link OO.ui.BookletLayout booklet layouts} to create pages that users can select and display
10452 * from the booklet's optional {@link OO.ui.OutlineSelectWidget outline} navigation. Pages are usually not instantiated directly,
10453 * rather extended to include the required content and functionality.
10454 *
10455 * Each page must have a unique symbolic name, which is passed to the constructor. In addition, the page's outline
10456 * item is customized (with a label, outline level, etc.) using the #setupOutlineItem method. See
10457 * {@link OO.ui.BookletLayout BookletLayout} for an example.
10458 *
10459 * @class
10460 * @extends OO.ui.PanelLayout
10461 *
10462 * @constructor
10463 * @param {string} name Unique symbolic name of page
10464 * @param {Object} [config] Configuration options
10465 */
10466 OO.ui.PageLayout = function OoUiPageLayout( name, config ) {
10467 // Allow passing positional parameters inside the config object
10468 if ( OO.isPlainObject( name ) && config === undefined ) {
10469 config = name;
10470 name = config.name;
10471 }
10472
10473 // Configuration initialization
10474 config = $.extend( { scrollable: true }, config );
10475
10476 // Parent constructor
10477 OO.ui.PageLayout.parent.call( this, config );
10478
10479 // Properties
10480 this.name = name;
10481 this.outlineItem = null;
10482 this.active = false;
10483
10484 // Initialization
10485 this.$element.addClass( 'oo-ui-pageLayout' );
10486 };
10487
10488 /* Setup */
10489
10490 OO.inheritClass( OO.ui.PageLayout, OO.ui.PanelLayout );
10491
10492 /* Events */
10493
10494 /**
10495 * An 'active' event is emitted when the page becomes active. Pages become active when they are
10496 * shown in a booklet layout that is configured to display only one page at a time.
10497 *
10498 * @event active
10499 * @param {boolean} active Page is active
10500 */
10501
10502 /* Methods */
10503
10504 /**
10505 * Get the symbolic name of the page.
10506 *
10507 * @return {string} Symbolic name of page
10508 */
10509 OO.ui.PageLayout.prototype.getName = function () {
10510 return this.name;
10511 };
10512
10513 /**
10514 * Check if page is active.
10515 *
10516 * Pages become active when they are shown in a {@link OO.ui.BookletLayout booklet layout} that is configured to display
10517 * only one page at a time. Additional CSS is applied to the page's outline item to reflect the active state.
10518 *
10519 * @return {boolean} Page is active
10520 */
10521 OO.ui.PageLayout.prototype.isActive = function () {
10522 return this.active;
10523 };
10524
10525 /**
10526 * Get outline item.
10527 *
10528 * The outline item allows users to access the page from the booklet's outline
10529 * navigation. The outline item itself can be customized (with a label, level, etc.) using the #setupOutlineItem method.
10530 *
10531 * @return {OO.ui.OutlineOptionWidget|null} Outline option widget
10532 */
10533 OO.ui.PageLayout.prototype.getOutlineItem = function () {
10534 return this.outlineItem;
10535 };
10536
10537 /**
10538 * Set or unset the outline item.
10539 *
10540 * Specify an {@link OO.ui.OutlineOptionWidget outline option} to set it,
10541 * or `null` to clear the outline item. To customize the outline item itself (e.g., to set a label or outline
10542 * level), use #setupOutlineItem instead of this method.
10543 *
10544 * @param {OO.ui.OutlineOptionWidget|null} outlineItem Outline option widget, null to clear
10545 * @chainable
10546 */
10547 OO.ui.PageLayout.prototype.setOutlineItem = function ( outlineItem ) {
10548 this.outlineItem = outlineItem || null;
10549 if ( outlineItem ) {
10550 this.setupOutlineItem();
10551 }
10552 return this;
10553 };
10554
10555 /**
10556 * Set up the outline item.
10557 *
10558 * Use this method to customize the outline item (e.g., to add a label or outline level). To set or unset
10559 * the outline item itself (with an {@link OO.ui.OutlineOptionWidget outline option} or `null`), use
10560 * the #setOutlineItem method instead.
10561 *
10562 * @param {OO.ui.OutlineOptionWidget} outlineItem Outline option widget to set up
10563 * @chainable
10564 */
10565 OO.ui.PageLayout.prototype.setupOutlineItem = function () {
10566 return this;
10567 };
10568
10569 /**
10570 * Set the page to its 'active' state.
10571 *
10572 * Pages become active when they are shown in a booklet layout that is configured to display only one page at a time. Additional
10573 * CSS is applied to the outline item to reflect the page's active state. Outside of the booklet
10574 * context, setting the active state on a page does nothing.
10575 *
10576 * @param {boolean} value Page is active
10577 * @fires active
10578 */
10579 OO.ui.PageLayout.prototype.setActive = function ( active ) {
10580 active = !!active;
10581
10582 if ( active !== this.active ) {
10583 this.active = active;
10584 this.$element.toggleClass( 'oo-ui-pageLayout-active', active );
10585 this.emit( 'active', this.active );
10586 }
10587 };
10588
10589 /**
10590 * StackLayouts contain a series of {@link OO.ui.PanelLayout panel layouts}. By default, only one panel is displayed
10591 * at a time, though the stack layout can also be configured to show all contained panels, one after another,
10592 * by setting the #continuous option to 'true'.
10593 *
10594 * @example
10595 * // A stack layout with two panels, configured to be displayed continously
10596 * var myStack = new OO.ui.StackLayout( {
10597 * items: [
10598 * new OO.ui.PanelLayout( {
10599 * $content: $( '<p>Panel One</p>' ),
10600 * padded: true,
10601 * framed: true
10602 * } ),
10603 * new OO.ui.PanelLayout( {
10604 * $content: $( '<p>Panel Two</p>' ),
10605 * padded: true,
10606 * framed: true
10607 * } )
10608 * ],
10609 * continuous: true
10610 * } );
10611 * $( 'body' ).append( myStack.$element );
10612 *
10613 * @class
10614 * @extends OO.ui.PanelLayout
10615 * @mixins OO.ui.mixin.GroupElement
10616 *
10617 * @constructor
10618 * @param {Object} [config] Configuration options
10619 * @cfg {boolean} [continuous=false] Show all panels, one after another. By default, only one panel is displayed at a time.
10620 * @cfg {OO.ui.Layout[]} [items] Panel layouts to add to the stack layout.
10621 */
10622 OO.ui.StackLayout = function OoUiStackLayout( config ) {
10623 // Configuration initialization
10624 config = $.extend( { scrollable: true }, config );
10625
10626 // Parent constructor
10627 OO.ui.StackLayout.parent.call( this, config );
10628
10629 // Mixin constructors
10630 OO.ui.mixin.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) );
10631
10632 // Properties
10633 this.currentItem = null;
10634 this.continuous = !!config.continuous;
10635
10636 // Initialization
10637 this.$element.addClass( 'oo-ui-stackLayout' );
10638 if ( this.continuous ) {
10639 this.$element.addClass( 'oo-ui-stackLayout-continuous' );
10640 }
10641 if ( Array.isArray( config.items ) ) {
10642 this.addItems( config.items );
10643 }
10644 };
10645
10646 /* Setup */
10647
10648 OO.inheritClass( OO.ui.StackLayout, OO.ui.PanelLayout );
10649 OO.mixinClass( OO.ui.StackLayout, OO.ui.mixin.GroupElement );
10650
10651 /* Events */
10652
10653 /**
10654 * A 'set' event is emitted when panels are {@link #addItems added}, {@link #removeItems removed},
10655 * {@link #clearItems cleared} or {@link #setItem displayed}.
10656 *
10657 * @event set
10658 * @param {OO.ui.Layout|null} item Current panel or `null` if no panel is shown
10659 */
10660
10661 /* Methods */
10662
10663 /**
10664 * Get the current panel.
10665 *
10666 * @return {OO.ui.Layout|null}
10667 */
10668 OO.ui.StackLayout.prototype.getCurrentItem = function () {
10669 return this.currentItem;
10670 };
10671
10672 /**
10673 * Unset the current item.
10674 *
10675 * @private
10676 * @param {OO.ui.StackLayout} layout
10677 * @fires set
10678 */
10679 OO.ui.StackLayout.prototype.unsetCurrentItem = function () {
10680 var prevItem = this.currentItem;
10681 if ( prevItem === null ) {
10682 return;
10683 }
10684
10685 this.currentItem = null;
10686 this.emit( 'set', null );
10687 };
10688
10689 /**
10690 * Add panel layouts to the stack layout.
10691 *
10692 * Panels will be added to the end of the stack layout array unless the optional index parameter specifies a different
10693 * insertion point. Adding a panel that is already in the stack will move it to the end of the array or the point specified
10694 * by the index.
10695 *
10696 * @param {OO.ui.Layout[]} items Panels to add
10697 * @param {number} [index] Index of the insertion point
10698 * @chainable
10699 */
10700 OO.ui.StackLayout.prototype.addItems = function ( items, index ) {
10701 // Update the visibility
10702 this.updateHiddenState( items, this.currentItem );
10703
10704 // Mixin method
10705 OO.ui.mixin.GroupElement.prototype.addItems.call( this, items, index );
10706
10707 if ( !this.currentItem && items.length ) {
10708 this.setItem( items[ 0 ] );
10709 }
10710
10711 return this;
10712 };
10713
10714 /**
10715 * Remove the specified panels from the stack layout.
10716 *
10717 * Removed panels are detached from the DOM, not removed, so that they may be reused. To remove all panels,
10718 * you may wish to use the #clearItems method instead.
10719 *
10720 * @param {OO.ui.Layout[]} items Panels to remove
10721 * @chainable
10722 * @fires set
10723 */
10724 OO.ui.StackLayout.prototype.removeItems = function ( items ) {
10725 // Mixin method
10726 OO.ui.mixin.GroupElement.prototype.removeItems.call( this, items );
10727
10728 if ( $.inArray( this.currentItem, items ) !== -1 ) {
10729 if ( this.items.length ) {
10730 this.setItem( this.items[ 0 ] );
10731 } else {
10732 this.unsetCurrentItem();
10733 }
10734 }
10735
10736 return this;
10737 };
10738
10739 /**
10740 * Clear all panels from the stack layout.
10741 *
10742 * Cleared panels are detached from the DOM, not removed, so that they may be reused. To remove only
10743 * a subset of panels, use the #removeItems method.
10744 *
10745 * @chainable
10746 * @fires set
10747 */
10748 OO.ui.StackLayout.prototype.clearItems = function () {
10749 this.unsetCurrentItem();
10750 OO.ui.mixin.GroupElement.prototype.clearItems.call( this );
10751
10752 return this;
10753 };
10754
10755 /**
10756 * Show the specified panel.
10757 *
10758 * If another panel is currently displayed, it will be hidden.
10759 *
10760 * @param {OO.ui.Layout} item Panel to show
10761 * @chainable
10762 * @fires set
10763 */
10764 OO.ui.StackLayout.prototype.setItem = function ( item ) {
10765 if ( item !== this.currentItem ) {
10766 this.updateHiddenState( this.items, item );
10767
10768 if ( $.inArray( item, this.items ) !== -1 ) {
10769 this.currentItem = item;
10770 this.emit( 'set', item );
10771 } else {
10772 this.unsetCurrentItem();
10773 }
10774 }
10775
10776 return this;
10777 };
10778
10779 /**
10780 * Update the visibility of all items in case of non-continuous view.
10781 *
10782 * Ensure all items are hidden except for the selected one.
10783 * This method does nothing when the stack is continuous.
10784 *
10785 * @private
10786 * @param {OO.ui.Layout[]} items Item list iterate over
10787 * @param {OO.ui.Layout} [selectedItem] Selected item to show
10788 */
10789 OO.ui.StackLayout.prototype.updateHiddenState = function ( items, selectedItem ) {
10790 var i, len;
10791
10792 if ( !this.continuous ) {
10793 for ( i = 0, len = items.length; i < len; i++ ) {
10794 if ( !selectedItem || selectedItem !== items[ i ] ) {
10795 items[ i ].$element.addClass( 'oo-ui-element-hidden' );
10796 }
10797 }
10798 if ( selectedItem ) {
10799 selectedItem.$element.removeClass( 'oo-ui-element-hidden' );
10800 }
10801 }
10802 };
10803
10804 /**
10805 * HorizontalLayout arranges its contents in a single line (using `display: inline-block` for its
10806 * items), with small margins between them. Convenient when you need to put a number of block-level
10807 * widgets on a single line next to each other.
10808 *
10809 * Note that inline elements, such as OO.ui.ButtonWidgets, do not need this wrapper.
10810 *
10811 * @example
10812 * // HorizontalLayout with a text input and a label
10813 * var layout = new OO.ui.HorizontalLayout( {
10814 * items: [
10815 * new OO.ui.LabelWidget( { label: 'Label' } ),
10816 * new OO.ui.TextInputWidget( { value: 'Text' } )
10817 * ]
10818 * } );
10819 * $( 'body' ).append( layout.$element );
10820 *
10821 * @class
10822 * @extends OO.ui.Layout
10823 * @mixins OO.ui.mixin.GroupElement
10824 *
10825 * @constructor
10826 * @param {Object} [config] Configuration options
10827 * @cfg {OO.ui.Widget[]|OO.ui.Layout[]} [items] Widgets or other layouts to add to the layout.
10828 */
10829 OO.ui.HorizontalLayout = function OoUiHorizontalLayout( config ) {
10830 // Configuration initialization
10831 config = config || {};
10832
10833 // Parent constructor
10834 OO.ui.HorizontalLayout.parent.call( this, config );
10835
10836 // Mixin constructors
10837 OO.ui.mixin.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) );
10838
10839 // Initialization
10840 this.$element.addClass( 'oo-ui-horizontalLayout' );
10841 if ( Array.isArray( config.items ) ) {
10842 this.addItems( config.items );
10843 }
10844 };
10845
10846 /* Setup */
10847
10848 OO.inheritClass( OO.ui.HorizontalLayout, OO.ui.Layout );
10849 OO.mixinClass( OO.ui.HorizontalLayout, OO.ui.mixin.GroupElement );
10850
10851 /**
10852 * BarToolGroups are one of three types of {@link OO.ui.ToolGroup toolgroups} that are used to
10853 * create {@link OO.ui.Toolbar toolbars} (the other types of groups are {@link OO.ui.MenuToolGroup MenuToolGroup}
10854 * and {@link OO.ui.ListToolGroup ListToolGroup}). The {@link OO.ui.Tool tools} in a BarToolGroup are
10855 * displayed by icon in a single row. The title of the tool is displayed when users move the mouse over
10856 * the tool.
10857 *
10858 * BarToolGroups are created by a {@link OO.ui.ToolGroupFactory tool group factory} when the toolbar is
10859 * set up.
10860 *
10861 * @example
10862 * // Example of a BarToolGroup with two tools
10863 * var toolFactory = new OO.ui.ToolFactory();
10864 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
10865 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
10866 *
10867 * // We will be placing status text in this element when tools are used
10868 * var $area = $( '<p>' ).text( 'Example of a BarToolGroup with two tools.' );
10869 *
10870 * // Define the tools that we're going to place in our toolbar
10871 *
10872 * // Create a class inheriting from OO.ui.Tool
10873 * function PictureTool() {
10874 * PictureTool.parent.apply( this, arguments );
10875 * }
10876 * OO.inheritClass( PictureTool, OO.ui.Tool );
10877 * // Each tool must have a 'name' (used as an internal identifier, see later) and at least one
10878 * // of 'icon' and 'title' (displayed icon and text).
10879 * PictureTool.static.name = 'picture';
10880 * PictureTool.static.icon = 'picture';
10881 * PictureTool.static.title = 'Insert picture';
10882 * // Defines the action that will happen when this tool is selected (clicked).
10883 * PictureTool.prototype.onSelect = function () {
10884 * $area.text( 'Picture tool clicked!' );
10885 * // Never display this tool as "active" (selected).
10886 * this.setActive( false );
10887 * };
10888 * // Make this tool available in our toolFactory and thus our toolbar
10889 * toolFactory.register( PictureTool );
10890 *
10891 * // This is a PopupTool. Rather than having a custom 'onSelect' action, it will display a
10892 * // little popup window (a PopupWidget).
10893 * function HelpTool( toolGroup, config ) {
10894 * OO.ui.PopupTool.call( this, toolGroup, $.extend( { popup: {
10895 * padded: true,
10896 * label: 'Help',
10897 * head: true
10898 * } }, config ) );
10899 * this.popup.$body.append( '<p>I am helpful!</p>' );
10900 * }
10901 * OO.inheritClass( HelpTool, OO.ui.PopupTool );
10902 * HelpTool.static.name = 'help';
10903 * HelpTool.static.icon = 'help';
10904 * HelpTool.static.title = 'Help';
10905 * toolFactory.register( HelpTool );
10906 *
10907 * // Finally define which tools and in what order appear in the toolbar. Each tool may only be
10908 * // used once (but not all defined tools must be used).
10909 * toolbar.setup( [
10910 * {
10911 * // 'bar' tool groups display tools by icon only
10912 * type: 'bar',
10913 * include: [ 'picture', 'help' ]
10914 * }
10915 * ] );
10916 *
10917 * // Create some UI around the toolbar and place it in the document
10918 * var frame = new OO.ui.PanelLayout( {
10919 * expanded: false,
10920 * framed: true
10921 * } );
10922 * var contentFrame = new OO.ui.PanelLayout( {
10923 * expanded: false,
10924 * padded: true
10925 * } );
10926 * frame.$element.append(
10927 * toolbar.$element,
10928 * contentFrame.$element.append( $area )
10929 * );
10930 * $( 'body' ).append( frame.$element );
10931 *
10932 * // Here is where the toolbar is actually built. This must be done after inserting it into the
10933 * // document.
10934 * toolbar.initialize();
10935 *
10936 * For more information about how to add tools to a bar tool group, please see {@link OO.ui.ToolGroup toolgroup}.
10937 * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki][1].
10938 *
10939 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
10940 *
10941 * @class
10942 * @extends OO.ui.ToolGroup
10943 *
10944 * @constructor
10945 * @param {OO.ui.Toolbar} toolbar
10946 * @param {Object} [config] Configuration options
10947 */
10948 OO.ui.BarToolGroup = function OoUiBarToolGroup( toolbar, config ) {
10949 // Allow passing positional parameters inside the config object
10950 if ( OO.isPlainObject( toolbar ) && config === undefined ) {
10951 config = toolbar;
10952 toolbar = config.toolbar;
10953 }
10954
10955 // Parent constructor
10956 OO.ui.BarToolGroup.parent.call( this, toolbar, config );
10957
10958 // Initialization
10959 this.$element.addClass( 'oo-ui-barToolGroup' );
10960 };
10961
10962 /* Setup */
10963
10964 OO.inheritClass( OO.ui.BarToolGroup, OO.ui.ToolGroup );
10965
10966 /* Static Properties */
10967
10968 OO.ui.BarToolGroup.static.titleTooltips = true;
10969
10970 OO.ui.BarToolGroup.static.accelTooltips = true;
10971
10972 OO.ui.BarToolGroup.static.name = 'bar';
10973
10974 /**
10975 * PopupToolGroup is an abstract base class used by both {@link OO.ui.MenuToolGroup MenuToolGroup}
10976 * and {@link OO.ui.ListToolGroup ListToolGroup} to provide a popup--an overlaid menu or list of tools with an
10977 * optional icon and label. This class can be used for other base classes that also use this functionality.
10978 *
10979 * @abstract
10980 * @class
10981 * @extends OO.ui.ToolGroup
10982 * @mixins OO.ui.mixin.IconElement
10983 * @mixins OO.ui.mixin.IndicatorElement
10984 * @mixins OO.ui.mixin.LabelElement
10985 * @mixins OO.ui.mixin.TitledElement
10986 * @mixins OO.ui.mixin.ClippableElement
10987 * @mixins OO.ui.mixin.TabIndexedElement
10988 *
10989 * @constructor
10990 * @param {OO.ui.Toolbar} toolbar
10991 * @param {Object} [config] Configuration options
10992 * @cfg {string} [header] Text to display at the top of the popup
10993 */
10994 OO.ui.PopupToolGroup = function OoUiPopupToolGroup( toolbar, config ) {
10995 // Allow passing positional parameters inside the config object
10996 if ( OO.isPlainObject( toolbar ) && config === undefined ) {
10997 config = toolbar;
10998 toolbar = config.toolbar;
10999 }
11000
11001 // Configuration initialization
11002 config = config || {};
11003
11004 // Parent constructor
11005 OO.ui.PopupToolGroup.parent.call( this, toolbar, config );
11006
11007 // Properties
11008 this.active = false;
11009 this.dragging = false;
11010 this.onBlurHandler = this.onBlur.bind( this );
11011 this.$handle = $( '<span>' );
11012
11013 // Mixin constructors
11014 OO.ui.mixin.IconElement.call( this, config );
11015 OO.ui.mixin.IndicatorElement.call( this, config );
11016 OO.ui.mixin.LabelElement.call( this, config );
11017 OO.ui.mixin.TitledElement.call( this, config );
11018 OO.ui.mixin.ClippableElement.call( this, $.extend( {}, config, { $clippable: this.$group } ) );
11019 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$handle } ) );
11020
11021 // Events
11022 this.$handle.on( {
11023 keydown: this.onHandleMouseKeyDown.bind( this ),
11024 keyup: this.onHandleMouseKeyUp.bind( this ),
11025 mousedown: this.onHandleMouseKeyDown.bind( this ),
11026 mouseup: this.onHandleMouseKeyUp.bind( this )
11027 } );
11028
11029 // Initialization
11030 this.$handle
11031 .addClass( 'oo-ui-popupToolGroup-handle' )
11032 .append( this.$icon, this.$label, this.$indicator );
11033 // If the pop-up should have a header, add it to the top of the toolGroup.
11034 // Note: If this feature is useful for other widgets, we could abstract it into an
11035 // OO.ui.HeaderedElement mixin constructor.
11036 if ( config.header !== undefined ) {
11037 this.$group
11038 .prepend( $( '<span>' )
11039 .addClass( 'oo-ui-popupToolGroup-header' )
11040 .text( config.header )
11041 );
11042 }
11043 this.$element
11044 .addClass( 'oo-ui-popupToolGroup' )
11045 .prepend( this.$handle );
11046 };
11047
11048 /* Setup */
11049
11050 OO.inheritClass( OO.ui.PopupToolGroup, OO.ui.ToolGroup );
11051 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.mixin.IconElement );
11052 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.mixin.IndicatorElement );
11053 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.mixin.LabelElement );
11054 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.mixin.TitledElement );
11055 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.mixin.ClippableElement );
11056 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.mixin.TabIndexedElement );
11057
11058 /* Methods */
11059
11060 /**
11061 * @inheritdoc
11062 */
11063 OO.ui.PopupToolGroup.prototype.setDisabled = function () {
11064 // Parent method
11065 OO.ui.PopupToolGroup.parent.prototype.setDisabled.apply( this, arguments );
11066
11067 if ( this.isDisabled() && this.isElementAttached() ) {
11068 this.setActive( false );
11069 }
11070 };
11071
11072 /**
11073 * Handle focus being lost.
11074 *
11075 * The event is actually generated from a mouseup/keyup, so it is not a normal blur event object.
11076 *
11077 * @protected
11078 * @param {jQuery.Event} e Mouse up or key up event
11079 */
11080 OO.ui.PopupToolGroup.prototype.onBlur = function ( e ) {
11081 // Only deactivate when clicking outside the dropdown element
11082 if ( $( e.target ).closest( '.oo-ui-popupToolGroup' )[ 0 ] !== this.$element[ 0 ] ) {
11083 this.setActive( false );
11084 }
11085 };
11086
11087 /**
11088 * @inheritdoc
11089 */
11090 OO.ui.PopupToolGroup.prototype.onMouseKeyUp = function ( e ) {
11091 // Only close toolgroup when a tool was actually selected
11092 if (
11093 !this.isDisabled() && this.pressed && this.pressed === this.getTargetTool( e ) &&
11094 ( e.which === 1 || e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
11095 ) {
11096 this.setActive( false );
11097 }
11098 return OO.ui.PopupToolGroup.parent.prototype.onMouseKeyUp.call( this, e );
11099 };
11100
11101 /**
11102 * Handle mouse up and key up events.
11103 *
11104 * @protected
11105 * @param {jQuery.Event} e Mouse up or key up event
11106 */
11107 OO.ui.PopupToolGroup.prototype.onHandleMouseKeyUp = function ( e ) {
11108 if (
11109 !this.isDisabled() &&
11110 ( e.which === 1 || e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
11111 ) {
11112 return false;
11113 }
11114 };
11115
11116 /**
11117 * Handle mouse down and key down events.
11118 *
11119 * @protected
11120 * @param {jQuery.Event} e Mouse down or key down event
11121 */
11122 OO.ui.PopupToolGroup.prototype.onHandleMouseKeyDown = function ( e ) {
11123 if (
11124 !this.isDisabled() &&
11125 ( e.which === 1 || e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
11126 ) {
11127 this.setActive( !this.active );
11128 return false;
11129 }
11130 };
11131
11132 /**
11133 * Switch into 'active' mode.
11134 *
11135 * When active, the popup is visible. A mouseup event anywhere in the document will trigger
11136 * deactivation.
11137 */
11138 OO.ui.PopupToolGroup.prototype.setActive = function ( value ) {
11139 var containerWidth, containerLeft;
11140 value = !!value;
11141 if ( this.active !== value ) {
11142 this.active = value;
11143 if ( value ) {
11144 OO.ui.addCaptureEventListener( this.getElementDocument(), 'mouseup', this.onBlurHandler );
11145 OO.ui.addCaptureEventListener( this.getElementDocument(), 'keyup', this.onBlurHandler );
11146
11147 this.$clippable.css( 'left', '' );
11148 // Try anchoring the popup to the left first
11149 this.$element.addClass( 'oo-ui-popupToolGroup-active oo-ui-popupToolGroup-left' );
11150 this.toggleClipping( true );
11151 if ( this.isClippedHorizontally() ) {
11152 // Anchoring to the left caused the popup to clip, so anchor it to the right instead
11153 this.toggleClipping( false );
11154 this.$element
11155 .removeClass( 'oo-ui-popupToolGroup-left' )
11156 .addClass( 'oo-ui-popupToolGroup-right' );
11157 this.toggleClipping( true );
11158 }
11159 if ( this.isClippedHorizontally() ) {
11160 // Anchoring to the right also caused the popup to clip, so just make it fill the container
11161 containerWidth = this.$clippableContainer.width();
11162 containerLeft = this.$clippableContainer.offset().left;
11163
11164 this.toggleClipping( false );
11165 this.$element.removeClass( 'oo-ui-popupToolGroup-right' );
11166
11167 this.$clippable.css( {
11168 left: -( this.$element.offset().left - containerLeft ),
11169 width: containerWidth
11170 } );
11171 }
11172 } else {
11173 OO.ui.removeCaptureEventListener( this.getElementDocument(), 'mouseup', this.onBlurHandler );
11174 OO.ui.removeCaptureEventListener( this.getElementDocument(), 'keyup', this.onBlurHandler );
11175 this.$element.removeClass(
11176 'oo-ui-popupToolGroup-active oo-ui-popupToolGroup-left oo-ui-popupToolGroup-right'
11177 );
11178 this.toggleClipping( false );
11179 }
11180 }
11181 };
11182
11183 /**
11184 * ListToolGroups are one of three types of {@link OO.ui.ToolGroup toolgroups} that are used to
11185 * create {@link OO.ui.Toolbar toolbars} (the other types of groups are {@link OO.ui.MenuToolGroup MenuToolGroup}
11186 * and {@link OO.ui.BarToolGroup BarToolGroup}). The {@link OO.ui.Tool tools} in a ListToolGroup are displayed
11187 * by label in a dropdown menu. The title of the tool is used as the label text. The menu itself can be configured
11188 * with a label, icon, indicator, header, and title.
11189 *
11190 * ListToolGroups can be configured to be expanded and collapsed. Collapsed lists will have a ‘More’ option that
11191 * users can select to see the full list of tools. If a collapsed toolgroup is expanded, a ‘Fewer’ option permits
11192 * users to collapse the list again.
11193 *
11194 * ListToolGroups are created by a {@link OO.ui.ToolGroupFactory toolgroup factory} when the toolbar is set up. The factory
11195 * requires the ListToolGroup's symbolic name, 'list', which is specified along with the other configurations. For more
11196 * information about how to add tools to a ListToolGroup, please see {@link OO.ui.ToolGroup toolgroup}.
11197 *
11198 * @example
11199 * // Example of a ListToolGroup
11200 * var toolFactory = new OO.ui.ToolFactory();
11201 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
11202 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
11203 *
11204 * // Configure and register two tools
11205 * function SettingsTool() {
11206 * SettingsTool.parent.apply( this, arguments );
11207 * }
11208 * OO.inheritClass( SettingsTool, OO.ui.Tool );
11209 * SettingsTool.static.name = 'settings';
11210 * SettingsTool.static.icon = 'settings';
11211 * SettingsTool.static.title = 'Change settings';
11212 * SettingsTool.prototype.onSelect = function () {
11213 * this.setActive( false );
11214 * };
11215 * toolFactory.register( SettingsTool );
11216 * // Register two more tools, nothing interesting here
11217 * function StuffTool() {
11218 * StuffTool.parent.apply( this, arguments );
11219 * }
11220 * OO.inheritClass( StuffTool, OO.ui.Tool );
11221 * StuffTool.static.name = 'stuff';
11222 * StuffTool.static.icon = 'ellipsis';
11223 * StuffTool.static.title = 'Change the world';
11224 * StuffTool.prototype.onSelect = function () {
11225 * this.setActive( false );
11226 * };
11227 * toolFactory.register( StuffTool );
11228 * toolbar.setup( [
11229 * {
11230 * // Configurations for list toolgroup.
11231 * type: 'list',
11232 * label: 'ListToolGroup',
11233 * indicator: 'down',
11234 * icon: 'picture',
11235 * title: 'This is the title, displayed when user moves the mouse over the list toolgroup',
11236 * header: 'This is the header',
11237 * include: [ 'settings', 'stuff' ],
11238 * allowCollapse: ['stuff']
11239 * }
11240 * ] );
11241 *
11242 * // Create some UI around the toolbar and place it in the document
11243 * var frame = new OO.ui.PanelLayout( {
11244 * expanded: false,
11245 * framed: true
11246 * } );
11247 * frame.$element.append(
11248 * toolbar.$element
11249 * );
11250 * $( 'body' ).append( frame.$element );
11251 * // Build the toolbar. This must be done after the toolbar has been appended to the document.
11252 * toolbar.initialize();
11253 *
11254 * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki][1].
11255 *
11256 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
11257 *
11258 * @class
11259 * @extends OO.ui.PopupToolGroup
11260 *
11261 * @constructor
11262 * @param {OO.ui.Toolbar} toolbar
11263 * @param {Object} [config] Configuration options
11264 * @cfg {Array} [allowCollapse] Allow the specified tools to be collapsed. By default, collapsible tools
11265 * will only be displayed if users click the ‘More’ option displayed at the bottom of the list. If
11266 * the list is expanded, a ‘Fewer’ option permits users to collapse the list again. Any tools that
11267 * are included in the toolgroup, but are not designated as collapsible, will always be displayed.
11268 * To open a collapsible list in its expanded state, set #expanded to 'true'.
11269 * @cfg {Array} [forceExpand] Expand the specified tools. All other tools will be designated as collapsible.
11270 * Unless #expanded is set to true, the collapsible tools will be collapsed when the list is first opened.
11271 * @cfg {boolean} [expanded=false] Expand collapsible tools. This config is only relevant if tools have
11272 * been designated as collapsible. When expanded is set to true, all tools in the group will be displayed
11273 * when the list is first opened. Users can collapse the list with a ‘Fewer’ option at the bottom.
11274 */
11275 OO.ui.ListToolGroup = function OoUiListToolGroup( toolbar, config ) {
11276 // Allow passing positional parameters inside the config object
11277 if ( OO.isPlainObject( toolbar ) && config === undefined ) {
11278 config = toolbar;
11279 toolbar = config.toolbar;
11280 }
11281
11282 // Configuration initialization
11283 config = config || {};
11284
11285 // Properties (must be set before parent constructor, which calls #populate)
11286 this.allowCollapse = config.allowCollapse;
11287 this.forceExpand = config.forceExpand;
11288 this.expanded = config.expanded !== undefined ? config.expanded : false;
11289 this.collapsibleTools = [];
11290
11291 // Parent constructor
11292 OO.ui.ListToolGroup.parent.call( this, toolbar, config );
11293
11294 // Initialization
11295 this.$element.addClass( 'oo-ui-listToolGroup' );
11296 };
11297
11298 /* Setup */
11299
11300 OO.inheritClass( OO.ui.ListToolGroup, OO.ui.PopupToolGroup );
11301
11302 /* Static Properties */
11303
11304 OO.ui.ListToolGroup.static.name = 'list';
11305
11306 /* Methods */
11307
11308 /**
11309 * @inheritdoc
11310 */
11311 OO.ui.ListToolGroup.prototype.populate = function () {
11312 var i, len, allowCollapse = [];
11313
11314 OO.ui.ListToolGroup.parent.prototype.populate.call( this );
11315
11316 // Update the list of collapsible tools
11317 if ( this.allowCollapse !== undefined ) {
11318 allowCollapse = this.allowCollapse;
11319 } else if ( this.forceExpand !== undefined ) {
11320 allowCollapse = OO.simpleArrayDifference( Object.keys( this.tools ), this.forceExpand );
11321 }
11322
11323 this.collapsibleTools = [];
11324 for ( i = 0, len = allowCollapse.length; i < len; i++ ) {
11325 if ( this.tools[ allowCollapse[ i ] ] !== undefined ) {
11326 this.collapsibleTools.push( this.tools[ allowCollapse[ i ] ] );
11327 }
11328 }
11329
11330 // Keep at the end, even when tools are added
11331 this.$group.append( this.getExpandCollapseTool().$element );
11332
11333 this.getExpandCollapseTool().toggle( this.collapsibleTools.length !== 0 );
11334 this.updateCollapsibleState();
11335 };
11336
11337 OO.ui.ListToolGroup.prototype.getExpandCollapseTool = function () {
11338 if ( this.expandCollapseTool === undefined ) {
11339 var ExpandCollapseTool = function () {
11340 ExpandCollapseTool.parent.apply( this, arguments );
11341 };
11342
11343 OO.inheritClass( ExpandCollapseTool, OO.ui.Tool );
11344
11345 ExpandCollapseTool.prototype.onSelect = function () {
11346 this.toolGroup.expanded = !this.toolGroup.expanded;
11347 this.toolGroup.updateCollapsibleState();
11348 this.setActive( false );
11349 };
11350 ExpandCollapseTool.prototype.onUpdateState = function () {
11351 // Do nothing. Tool interface requires an implementation of this function.
11352 };
11353
11354 ExpandCollapseTool.static.name = 'more-fewer';
11355
11356 this.expandCollapseTool = new ExpandCollapseTool( this );
11357 }
11358 return this.expandCollapseTool;
11359 };
11360
11361 /**
11362 * @inheritdoc
11363 */
11364 OO.ui.ListToolGroup.prototype.onMouseKeyUp = function ( e ) {
11365 // Do not close the popup when the user wants to show more/fewer tools
11366 if (
11367 $( e.target ).closest( '.oo-ui-tool-name-more-fewer' ).length &&
11368 ( e.which === 1 || e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
11369 ) {
11370 // HACK: Prevent the popup list from being hidden. Skip the PopupToolGroup implementation (which
11371 // hides the popup list when a tool is selected) and call ToolGroup's implementation directly.
11372 return OO.ui.ListToolGroup.parent.parent.prototype.onMouseKeyUp.call( this, e );
11373 } else {
11374 return OO.ui.ListToolGroup.parent.prototype.onMouseKeyUp.call( this, e );
11375 }
11376 };
11377
11378 OO.ui.ListToolGroup.prototype.updateCollapsibleState = function () {
11379 var i, len;
11380
11381 this.getExpandCollapseTool()
11382 .setIcon( this.expanded ? 'collapse' : 'expand' )
11383 .setTitle( OO.ui.msg( this.expanded ? 'ooui-toolgroup-collapse' : 'ooui-toolgroup-expand' ) );
11384
11385 for ( i = 0, len = this.collapsibleTools.length; i < len; i++ ) {
11386 this.collapsibleTools[ i ].toggle( this.expanded );
11387 }
11388 };
11389
11390 /**
11391 * MenuToolGroups are one of three types of {@link OO.ui.ToolGroup toolgroups} that are used to
11392 * create {@link OO.ui.Toolbar toolbars} (the other types of groups are {@link OO.ui.BarToolGroup BarToolGroup}
11393 * and {@link OO.ui.ListToolGroup ListToolGroup}). MenuToolGroups contain selectable {@link OO.ui.Tool tools},
11394 * which are displayed by label in a dropdown menu. The tool's title is used as the label text, and the
11395 * menu label is updated to reflect which tool or tools are currently selected. If no tools are selected,
11396 * the menu label is empty. The menu can be configured with an indicator, icon, title, and/or header.
11397 *
11398 * MenuToolGroups are created by a {@link OO.ui.ToolGroupFactory tool group factory} when the toolbar
11399 * is set up. Note that all tools must define an {@link OO.ui.Tool#onUpdateState onUpdateState} method if
11400 * a MenuToolGroup is used.
11401 *
11402 * @example
11403 * // Example of a MenuToolGroup
11404 * var toolFactory = new OO.ui.ToolFactory();
11405 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
11406 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
11407 *
11408 * // We will be placing status text in this element when tools are used
11409 * var $area = $( '<p>' ).text( 'An example of a MenuToolGroup. Select a tool from the dropdown menu.' );
11410 *
11411 * // Define the tools that we're going to place in our toolbar
11412 *
11413 * function SettingsTool() {
11414 * SettingsTool.parent.apply( this, arguments );
11415 * this.reallyActive = false;
11416 * }
11417 * OO.inheritClass( SettingsTool, OO.ui.Tool );
11418 * SettingsTool.static.name = 'settings';
11419 * SettingsTool.static.icon = 'settings';
11420 * SettingsTool.static.title = 'Change settings';
11421 * SettingsTool.prototype.onSelect = function () {
11422 * $area.text( 'Settings tool clicked!' );
11423 * // Toggle the active state on each click
11424 * this.reallyActive = !this.reallyActive;
11425 * this.setActive( this.reallyActive );
11426 * // To update the menu label
11427 * this.toolbar.emit( 'updateState' );
11428 * };
11429 * SettingsTool.prototype.onUpdateState = function () {
11430 * };
11431 * toolFactory.register( SettingsTool );
11432 *
11433 * function StuffTool() {
11434 * StuffTool.parent.apply( this, arguments );
11435 * this.reallyActive = false;
11436 * }
11437 * OO.inheritClass( StuffTool, OO.ui.Tool );
11438 * StuffTool.static.name = 'stuff';
11439 * StuffTool.static.icon = 'ellipsis';
11440 * StuffTool.static.title = 'More stuff';
11441 * StuffTool.prototype.onSelect = function () {
11442 * $area.text( 'More stuff tool clicked!' );
11443 * // Toggle the active state on each click
11444 * this.reallyActive = !this.reallyActive;
11445 * this.setActive( this.reallyActive );
11446 * // To update the menu label
11447 * this.toolbar.emit( 'updateState' );
11448 * };
11449 * StuffTool.prototype.onUpdateState = function () {
11450 * };
11451 * toolFactory.register( StuffTool );
11452 *
11453 * // Finally define which tools and in what order appear in the toolbar. Each tool may only be
11454 * // used once (but not all defined tools must be used).
11455 * toolbar.setup( [
11456 * {
11457 * type: 'menu',
11458 * header: 'This is the (optional) header',
11459 * title: 'This is the (optional) title',
11460 * indicator: 'down',
11461 * include: [ 'settings', 'stuff' ]
11462 * }
11463 * ] );
11464 *
11465 * // Create some UI around the toolbar and place it in the document
11466 * var frame = new OO.ui.PanelLayout( {
11467 * expanded: false,
11468 * framed: true
11469 * } );
11470 * var contentFrame = new OO.ui.PanelLayout( {
11471 * expanded: false,
11472 * padded: true
11473 * } );
11474 * frame.$element.append(
11475 * toolbar.$element,
11476 * contentFrame.$element.append( $area )
11477 * );
11478 * $( 'body' ).append( frame.$element );
11479 *
11480 * // Here is where the toolbar is actually built. This must be done after inserting it into the
11481 * // document.
11482 * toolbar.initialize();
11483 * toolbar.emit( 'updateState' );
11484 *
11485 * For more information about how to add tools to a MenuToolGroup, please see {@link OO.ui.ToolGroup toolgroup}.
11486 * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki] [1].
11487 *
11488 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
11489 *
11490 * @class
11491 * @extends OO.ui.PopupToolGroup
11492 *
11493 * @constructor
11494 * @param {OO.ui.Toolbar} toolbar
11495 * @param {Object} [config] Configuration options
11496 */
11497 OO.ui.MenuToolGroup = function OoUiMenuToolGroup( toolbar, config ) {
11498 // Allow passing positional parameters inside the config object
11499 if ( OO.isPlainObject( toolbar ) && config === undefined ) {
11500 config = toolbar;
11501 toolbar = config.toolbar;
11502 }
11503
11504 // Configuration initialization
11505 config = config || {};
11506
11507 // Parent constructor
11508 OO.ui.MenuToolGroup.parent.call( this, toolbar, config );
11509
11510 // Events
11511 this.toolbar.connect( this, { updateState: 'onUpdateState' } );
11512
11513 // Initialization
11514 this.$element.addClass( 'oo-ui-menuToolGroup' );
11515 };
11516
11517 /* Setup */
11518
11519 OO.inheritClass( OO.ui.MenuToolGroup, OO.ui.PopupToolGroup );
11520
11521 /* Static Properties */
11522
11523 OO.ui.MenuToolGroup.static.name = 'menu';
11524
11525 /* Methods */
11526
11527 /**
11528 * Handle the toolbar state being updated.
11529 *
11530 * When the state changes, the title of each active item in the menu will be joined together and
11531 * used as a label for the group. The label will be empty if none of the items are active.
11532 *
11533 * @private
11534 */
11535 OO.ui.MenuToolGroup.prototype.onUpdateState = function () {
11536 var name,
11537 labelTexts = [];
11538
11539 for ( name in this.tools ) {
11540 if ( this.tools[ name ].isActive() ) {
11541 labelTexts.push( this.tools[ name ].getTitle() );
11542 }
11543 }
11544
11545 this.setLabel( labelTexts.join( ', ' ) || ' ' );
11546 };
11547
11548 /**
11549 * Popup tools open a popup window when they are selected from the {@link OO.ui.Toolbar toolbar}. Each popup tool is configured
11550 * 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
11551 * an #onSelect or #onUpdateState method, as these methods have been implemented already.
11552 *
11553 * // Example of a popup tool. When selected, a popup tool displays
11554 * // a popup window.
11555 * function HelpTool( toolGroup, config ) {
11556 * OO.ui.PopupTool.call( this, toolGroup, $.extend( { popup: {
11557 * padded: true,
11558 * label: 'Help',
11559 * head: true
11560 * } }, config ) );
11561 * this.popup.$body.append( '<p>I am helpful!</p>' );
11562 * };
11563 * OO.inheritClass( HelpTool, OO.ui.PopupTool );
11564 * HelpTool.static.name = 'help';
11565 * HelpTool.static.icon = 'help';
11566 * HelpTool.static.title = 'Help';
11567 * toolFactory.register( HelpTool );
11568 *
11569 * For an example of a toolbar that contains a popup tool, see {@link OO.ui.Toolbar toolbars}. For more information about
11570 * toolbars in genreral, please see the [OOjs UI documentation on MediaWiki][1].
11571 *
11572 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
11573 *
11574 * @abstract
11575 * @class
11576 * @extends OO.ui.Tool
11577 * @mixins OO.ui.mixin.PopupElement
11578 *
11579 * @constructor
11580 * @param {OO.ui.ToolGroup} toolGroup
11581 * @param {Object} [config] Configuration options
11582 */
11583 OO.ui.PopupTool = function OoUiPopupTool( toolGroup, config ) {
11584 // Allow passing positional parameters inside the config object
11585 if ( OO.isPlainObject( toolGroup ) && config === undefined ) {
11586 config = toolGroup;
11587 toolGroup = config.toolGroup;
11588 }
11589
11590 // Parent constructor
11591 OO.ui.PopupTool.parent.call( this, toolGroup, config );
11592
11593 // Mixin constructors
11594 OO.ui.mixin.PopupElement.call( this, config );
11595
11596 // Initialization
11597 this.$element
11598 .addClass( 'oo-ui-popupTool' )
11599 .append( this.popup.$element );
11600 };
11601
11602 /* Setup */
11603
11604 OO.inheritClass( OO.ui.PopupTool, OO.ui.Tool );
11605 OO.mixinClass( OO.ui.PopupTool, OO.ui.mixin.PopupElement );
11606
11607 /* Methods */
11608
11609 /**
11610 * Handle the tool being selected.
11611 *
11612 * @inheritdoc
11613 */
11614 OO.ui.PopupTool.prototype.onSelect = function () {
11615 if ( !this.isDisabled() ) {
11616 this.popup.toggle();
11617 }
11618 this.setActive( false );
11619 return false;
11620 };
11621
11622 /**
11623 * Handle the toolbar state being updated.
11624 *
11625 * @inheritdoc
11626 */
11627 OO.ui.PopupTool.prototype.onUpdateState = function () {
11628 this.setActive( false );
11629 };
11630
11631 /**
11632 * A ToolGroupTool is a special sort of tool that can contain other {@link OO.ui.Tool tools}
11633 * and {@link OO.ui.ToolGroup toolgroups}. The ToolGroupTool was specifically designed to be used
11634 * inside a {@link OO.ui.BarToolGroup bar} toolgroup to provide access to additional tools from
11635 * the bar item. Included tools will be displayed in a dropdown {@link OO.ui.ListToolGroup list}
11636 * when the ToolGroupTool is selected.
11637 *
11638 * // Example: ToolGroupTool with two nested tools, 'setting1' and 'setting2', defined elsewhere.
11639 *
11640 * function SettingsTool() {
11641 * SettingsTool.parent.apply( this, arguments );
11642 * };
11643 * OO.inheritClass( SettingsTool, OO.ui.ToolGroupTool );
11644 * SettingsTool.static.name = 'settings';
11645 * SettingsTool.static.title = 'Change settings';
11646 * SettingsTool.static.groupConfig = {
11647 * icon: 'settings',
11648 * label: 'ToolGroupTool',
11649 * include: [ 'setting1', 'setting2' ]
11650 * };
11651 * toolFactory.register( SettingsTool );
11652 *
11653 * For more information, please see the [OOjs UI documentation on MediaWiki][1].
11654 *
11655 * Please note that this implementation is subject to change per [T74159] [2].
11656 *
11657 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars#ToolGroupTool
11658 * [2]: https://phabricator.wikimedia.org/T74159
11659 *
11660 * @abstract
11661 * @class
11662 * @extends OO.ui.Tool
11663 *
11664 * @constructor
11665 * @param {OO.ui.ToolGroup} toolGroup
11666 * @param {Object} [config] Configuration options
11667 */
11668 OO.ui.ToolGroupTool = function OoUiToolGroupTool( toolGroup, config ) {
11669 // Allow passing positional parameters inside the config object
11670 if ( OO.isPlainObject( toolGroup ) && config === undefined ) {
11671 config = toolGroup;
11672 toolGroup = config.toolGroup;
11673 }
11674
11675 // Parent constructor
11676 OO.ui.ToolGroupTool.parent.call( this, toolGroup, config );
11677
11678 // Properties
11679 this.innerToolGroup = this.createGroup( this.constructor.static.groupConfig );
11680
11681 // Events
11682 this.innerToolGroup.connect( this, { disable: 'onToolGroupDisable' } );
11683
11684 // Initialization
11685 this.$link.remove();
11686 this.$element
11687 .addClass( 'oo-ui-toolGroupTool' )
11688 .append( this.innerToolGroup.$element );
11689 };
11690
11691 /* Setup */
11692
11693 OO.inheritClass( OO.ui.ToolGroupTool, OO.ui.Tool );
11694
11695 /* Static Properties */
11696
11697 /**
11698 * Toolgroup configuration.
11699 *
11700 * The toolgroup configuration consists of the tools to include, as well as an icon and label
11701 * to use for the bar item. Tools can be included by symbolic name, group, or with the
11702 * wildcard selector. Please see {@link OO.ui.ToolGroup toolgroup} for more information.
11703 *
11704 * @property {Object.<string,Array>}
11705 */
11706 OO.ui.ToolGroupTool.static.groupConfig = {};
11707
11708 /* Methods */
11709
11710 /**
11711 * Handle the tool being selected.
11712 *
11713 * @inheritdoc
11714 */
11715 OO.ui.ToolGroupTool.prototype.onSelect = function () {
11716 this.innerToolGroup.setActive( !this.innerToolGroup.active );
11717 return false;
11718 };
11719
11720 /**
11721 * Synchronize disabledness state of the tool with the inner toolgroup.
11722 *
11723 * @private
11724 * @param {boolean} disabled Element is disabled
11725 */
11726 OO.ui.ToolGroupTool.prototype.onToolGroupDisable = function ( disabled ) {
11727 this.setDisabled( disabled );
11728 };
11729
11730 /**
11731 * Handle the toolbar state being updated.
11732 *
11733 * @inheritdoc
11734 */
11735 OO.ui.ToolGroupTool.prototype.onUpdateState = function () {
11736 this.setActive( false );
11737 };
11738
11739 /**
11740 * Build a {@link OO.ui.ToolGroup toolgroup} from the specified configuration.
11741 *
11742 * @param {Object.<string,Array>} group Toolgroup configuration. Please see {@link OO.ui.ToolGroup toolgroup} for
11743 * more information.
11744 * @return {OO.ui.ListToolGroup}
11745 */
11746 OO.ui.ToolGroupTool.prototype.createGroup = function ( group ) {
11747 if ( group.include === '*' ) {
11748 // Apply defaults to catch-all groups
11749 if ( group.label === undefined ) {
11750 group.label = OO.ui.msg( 'ooui-toolbar-more' );
11751 }
11752 }
11753
11754 return this.toolbar.getToolGroupFactory().create( 'list', this.toolbar, group );
11755 };
11756
11757 /**
11758 * Mixin for OO.ui.Widget subclasses to provide OO.ui.mixin.GroupElement.
11759 *
11760 * Use together with OO.ui.mixin.ItemWidget to make disabled state inheritable.
11761 *
11762 * @private
11763 * @abstract
11764 * @class
11765 * @extends OO.ui.mixin.GroupElement
11766 *
11767 * @constructor
11768 * @param {Object} [config] Configuration options
11769 */
11770 OO.ui.mixin.GroupWidget = function OoUiMixinGroupWidget( config ) {
11771 // Parent constructor
11772 OO.ui.mixin.GroupWidget.parent.call( this, config );
11773 };
11774
11775 /* Setup */
11776
11777 OO.inheritClass( OO.ui.mixin.GroupWidget, OO.ui.mixin.GroupElement );
11778
11779 /* Methods */
11780
11781 /**
11782 * Set the disabled state of the widget.
11783 *
11784 * This will also update the disabled state of child widgets.
11785 *
11786 * @param {boolean} disabled Disable widget
11787 * @chainable
11788 */
11789 OO.ui.mixin.GroupWidget.prototype.setDisabled = function ( disabled ) {
11790 var i, len;
11791
11792 // Parent method
11793 // Note: Calling #setDisabled this way assumes this is mixed into an OO.ui.Widget
11794 OO.ui.Widget.prototype.setDisabled.call( this, disabled );
11795
11796 // During construction, #setDisabled is called before the OO.ui.mixin.GroupElement constructor
11797 if ( this.items ) {
11798 for ( i = 0, len = this.items.length; i < len; i++ ) {
11799 this.items[ i ].updateDisabled();
11800 }
11801 }
11802
11803 return this;
11804 };
11805
11806 /**
11807 * Mixin for widgets used as items in widgets that mix in OO.ui.mixin.GroupWidget.
11808 *
11809 * Item widgets have a reference to a OO.ui.mixin.GroupWidget while they are attached to the group. This
11810 * allows bidirectional communication.
11811 *
11812 * Use together with OO.ui.mixin.GroupWidget to make disabled state inheritable.
11813 *
11814 * @private
11815 * @abstract
11816 * @class
11817 *
11818 * @constructor
11819 */
11820 OO.ui.mixin.ItemWidget = function OoUiMixinItemWidget() {
11821 //
11822 };
11823
11824 /* Methods */
11825
11826 /**
11827 * Check if widget is disabled.
11828 *
11829 * Checks parent if present, making disabled state inheritable.
11830 *
11831 * @return {boolean} Widget is disabled
11832 */
11833 OO.ui.mixin.ItemWidget.prototype.isDisabled = function () {
11834 return this.disabled ||
11835 ( this.elementGroup instanceof OO.ui.Widget && this.elementGroup.isDisabled() );
11836 };
11837
11838 /**
11839 * Set group element is in.
11840 *
11841 * @param {OO.ui.mixin.GroupElement|null} group Group element, null if none
11842 * @chainable
11843 */
11844 OO.ui.mixin.ItemWidget.prototype.setElementGroup = function ( group ) {
11845 // Parent method
11846 // Note: Calling #setElementGroup this way assumes this is mixed into an OO.ui.Element
11847 OO.ui.Element.prototype.setElementGroup.call( this, group );
11848
11849 // Initialize item disabled states
11850 this.updateDisabled();
11851
11852 return this;
11853 };
11854
11855 /**
11856 * OutlineControlsWidget is a set of controls for an {@link OO.ui.OutlineSelectWidget outline select widget}.
11857 * Controls include moving items up and down, removing items, and adding different kinds of items.
11858 *
11859 * **Currently, this class is only used by {@link OO.ui.BookletLayout booklet layouts}.**
11860 *
11861 * @class
11862 * @extends OO.ui.Widget
11863 * @mixins OO.ui.mixin.GroupElement
11864 * @mixins OO.ui.mixin.IconElement
11865 *
11866 * @constructor
11867 * @param {OO.ui.OutlineSelectWidget} outline Outline to control
11868 * @param {Object} [config] Configuration options
11869 * @cfg {Object} [abilities] List of abilties
11870 * @cfg {boolean} [abilities.move=true] Allow moving movable items
11871 * @cfg {boolean} [abilities.remove=true] Allow removing removable items
11872 */
11873 OO.ui.OutlineControlsWidget = function OoUiOutlineControlsWidget( outline, config ) {
11874 // Allow passing positional parameters inside the config object
11875 if ( OO.isPlainObject( outline ) && config === undefined ) {
11876 config = outline;
11877 outline = config.outline;
11878 }
11879
11880 // Configuration initialization
11881 config = $.extend( { icon: 'add' }, config );
11882
11883 // Parent constructor
11884 OO.ui.OutlineControlsWidget.parent.call( this, config );
11885
11886 // Mixin constructors
11887 OO.ui.mixin.GroupElement.call( this, config );
11888 OO.ui.mixin.IconElement.call( this, config );
11889
11890 // Properties
11891 this.outline = outline;
11892 this.$movers = $( '<div>' );
11893 this.upButton = new OO.ui.ButtonWidget( {
11894 framed: false,
11895 icon: 'collapse',
11896 title: OO.ui.msg( 'ooui-outline-control-move-up' )
11897 } );
11898 this.downButton = new OO.ui.ButtonWidget( {
11899 framed: false,
11900 icon: 'expand',
11901 title: OO.ui.msg( 'ooui-outline-control-move-down' )
11902 } );
11903 this.removeButton = new OO.ui.ButtonWidget( {
11904 framed: false,
11905 icon: 'remove',
11906 title: OO.ui.msg( 'ooui-outline-control-remove' )
11907 } );
11908 this.abilities = { move: true, remove: true };
11909
11910 // Events
11911 outline.connect( this, {
11912 select: 'onOutlineChange',
11913 add: 'onOutlineChange',
11914 remove: 'onOutlineChange'
11915 } );
11916 this.upButton.connect( this, { click: [ 'emit', 'move', -1 ] } );
11917 this.downButton.connect( this, { click: [ 'emit', 'move', 1 ] } );
11918 this.removeButton.connect( this, { click: [ 'emit', 'remove' ] } );
11919
11920 // Initialization
11921 this.$element.addClass( 'oo-ui-outlineControlsWidget' );
11922 this.$group.addClass( 'oo-ui-outlineControlsWidget-items' );
11923 this.$movers
11924 .addClass( 'oo-ui-outlineControlsWidget-movers' )
11925 .append( this.removeButton.$element, this.upButton.$element, this.downButton.$element );
11926 this.$element.append( this.$icon, this.$group, this.$movers );
11927 this.setAbilities( config.abilities || {} );
11928 };
11929
11930 /* Setup */
11931
11932 OO.inheritClass( OO.ui.OutlineControlsWidget, OO.ui.Widget );
11933 OO.mixinClass( OO.ui.OutlineControlsWidget, OO.ui.mixin.GroupElement );
11934 OO.mixinClass( OO.ui.OutlineControlsWidget, OO.ui.mixin.IconElement );
11935
11936 /* Events */
11937
11938 /**
11939 * @event move
11940 * @param {number} places Number of places to move
11941 */
11942
11943 /**
11944 * @event remove
11945 */
11946
11947 /* Methods */
11948
11949 /**
11950 * Set abilities.
11951 *
11952 * @param {Object} abilities List of abilties
11953 * @param {boolean} [abilities.move] Allow moving movable items
11954 * @param {boolean} [abilities.remove] Allow removing removable items
11955 */
11956 OO.ui.OutlineControlsWidget.prototype.setAbilities = function ( abilities ) {
11957 var ability;
11958
11959 for ( ability in this.abilities ) {
11960 if ( abilities[ability] !== undefined ) {
11961 this.abilities[ability] = !!abilities[ability];
11962 }
11963 }
11964
11965 this.onOutlineChange();
11966 };
11967
11968 /**
11969 *
11970 * @private
11971 * Handle outline change events.
11972 */
11973 OO.ui.OutlineControlsWidget.prototype.onOutlineChange = function () {
11974 var i, len, firstMovable, lastMovable,
11975 items = this.outline.getItems(),
11976 selectedItem = this.outline.getSelectedItem(),
11977 movable = this.abilities.move && selectedItem && selectedItem.isMovable(),
11978 removable = this.abilities.remove && selectedItem && selectedItem.isRemovable();
11979
11980 if ( movable ) {
11981 i = -1;
11982 len = items.length;
11983 while ( ++i < len ) {
11984 if ( items[ i ].isMovable() ) {
11985 firstMovable = items[ i ];
11986 break;
11987 }
11988 }
11989 i = len;
11990 while ( i-- ) {
11991 if ( items[ i ].isMovable() ) {
11992 lastMovable = items[ i ];
11993 break;
11994 }
11995 }
11996 }
11997 this.upButton.setDisabled( !movable || selectedItem === firstMovable );
11998 this.downButton.setDisabled( !movable || selectedItem === lastMovable );
11999 this.removeButton.setDisabled( !removable );
12000 };
12001
12002 /**
12003 * ToggleWidget implements basic behavior of widgets with an on/off state.
12004 * Please see OO.ui.ToggleButtonWidget and OO.ui.ToggleSwitchWidget for examples.
12005 *
12006 * @abstract
12007 * @class
12008 * @extends OO.ui.Widget
12009 *
12010 * @constructor
12011 * @param {Object} [config] Configuration options
12012 * @cfg {boolean} [value=false] The toggle’s initial on/off state.
12013 * By default, the toggle is in the 'off' state.
12014 */
12015 OO.ui.ToggleWidget = function OoUiToggleWidget( config ) {
12016 // Configuration initialization
12017 config = config || {};
12018
12019 // Parent constructor
12020 OO.ui.ToggleWidget.parent.call( this, config );
12021
12022 // Properties
12023 this.value = null;
12024
12025 // Initialization
12026 this.$element.addClass( 'oo-ui-toggleWidget' );
12027 this.setValue( !!config.value );
12028 };
12029
12030 /* Setup */
12031
12032 OO.inheritClass( OO.ui.ToggleWidget, OO.ui.Widget );
12033
12034 /* Events */
12035
12036 /**
12037 * @event change
12038 *
12039 * A change event is emitted when the on/off state of the toggle changes.
12040 *
12041 * @param {boolean} value Value representing the new state of the toggle
12042 */
12043
12044 /* Methods */
12045
12046 /**
12047 * Get the value representing the toggle’s state.
12048 *
12049 * @return {boolean} The on/off state of the toggle
12050 */
12051 OO.ui.ToggleWidget.prototype.getValue = function () {
12052 return this.value;
12053 };
12054
12055 /**
12056 * Set the state of the toggle: `true` for 'on', `false' for 'off'.
12057 *
12058 * @param {boolean} value The state of the toggle
12059 * @fires change
12060 * @chainable
12061 */
12062 OO.ui.ToggleWidget.prototype.setValue = function ( value ) {
12063 value = !!value;
12064 if ( this.value !== value ) {
12065 this.value = value;
12066 this.emit( 'change', value );
12067 this.$element.toggleClass( 'oo-ui-toggleWidget-on', value );
12068 this.$element.toggleClass( 'oo-ui-toggleWidget-off', !value );
12069 this.$element.attr( 'aria-checked', value.toString() );
12070 }
12071 return this;
12072 };
12073
12074 /**
12075 * A ButtonGroupWidget groups related buttons and is used together with OO.ui.ButtonWidget and
12076 * its subclasses. Each button in a group is addressed by a unique reference. Buttons can be added,
12077 * removed, and cleared from the group.
12078 *
12079 * @example
12080 * // Example: A ButtonGroupWidget with two buttons
12081 * var button1 = new OO.ui.PopupButtonWidget( {
12082 * label: 'Select a category',
12083 * icon: 'menu',
12084 * popup: {
12085 * $content: $( '<p>List of categories...</p>' ),
12086 * padded: true,
12087 * align: 'left'
12088 * }
12089 * } );
12090 * var button2 = new OO.ui.ButtonWidget( {
12091 * label: 'Add item'
12092 * });
12093 * var buttonGroup = new OO.ui.ButtonGroupWidget( {
12094 * items: [button1, button2]
12095 * } );
12096 * $( 'body' ).append( buttonGroup.$element );
12097 *
12098 * @class
12099 * @extends OO.ui.Widget
12100 * @mixins OO.ui.mixin.GroupElement
12101 *
12102 * @constructor
12103 * @param {Object} [config] Configuration options
12104 * @cfg {OO.ui.ButtonWidget[]} [items] Buttons to add
12105 */
12106 OO.ui.ButtonGroupWidget = function OoUiButtonGroupWidget( config ) {
12107 // Configuration initialization
12108 config = config || {};
12109
12110 // Parent constructor
12111 OO.ui.ButtonGroupWidget.parent.call( this, config );
12112
12113 // Mixin constructors
12114 OO.ui.mixin.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) );
12115
12116 // Initialization
12117 this.$element.addClass( 'oo-ui-buttonGroupWidget' );
12118 if ( Array.isArray( config.items ) ) {
12119 this.addItems( config.items );
12120 }
12121 };
12122
12123 /* Setup */
12124
12125 OO.inheritClass( OO.ui.ButtonGroupWidget, OO.ui.Widget );
12126 OO.mixinClass( OO.ui.ButtonGroupWidget, OO.ui.mixin.GroupElement );
12127
12128 /**
12129 * ButtonWidget is a generic widget for buttons. A wide variety of looks,
12130 * feels, and functionality can be customized via the class’s configuration options
12131 * and methods. Please see the [OOjs UI documentation on MediaWiki] [1] for more information
12132 * and examples.
12133 *
12134 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches
12135 *
12136 * @example
12137 * // A button widget
12138 * var button = new OO.ui.ButtonWidget( {
12139 * label: 'Button with Icon',
12140 * icon: 'remove',
12141 * iconTitle: 'Remove'
12142 * } );
12143 * $( 'body' ).append( button.$element );
12144 *
12145 * NOTE: HTML form buttons should use the OO.ui.ButtonInputWidget class.
12146 *
12147 * @class
12148 * @extends OO.ui.Widget
12149 * @mixins OO.ui.mixin.ButtonElement
12150 * @mixins OO.ui.mixin.IconElement
12151 * @mixins OO.ui.mixin.IndicatorElement
12152 * @mixins OO.ui.mixin.LabelElement
12153 * @mixins OO.ui.mixin.TitledElement
12154 * @mixins OO.ui.mixin.FlaggedElement
12155 * @mixins OO.ui.mixin.TabIndexedElement
12156 *
12157 * @constructor
12158 * @param {Object} [config] Configuration options
12159 * @cfg {string} [href] Hyperlink to visit when the button is clicked.
12160 * @cfg {string} [target] The frame or window in which to open the hyperlink.
12161 * @cfg {boolean} [noFollow] Search engine traversal hint (default: true)
12162 */
12163 OO.ui.ButtonWidget = function OoUiButtonWidget( config ) {
12164 // Configuration initialization
12165 config = config || {};
12166
12167 // Parent constructor
12168 OO.ui.ButtonWidget.parent.call( this, config );
12169
12170 // Mixin constructors
12171 OO.ui.mixin.ButtonElement.call( this, config );
12172 OO.ui.mixin.IconElement.call( this, config );
12173 OO.ui.mixin.IndicatorElement.call( this, config );
12174 OO.ui.mixin.LabelElement.call( this, config );
12175 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$button } ) );
12176 OO.ui.mixin.FlaggedElement.call( this, config );
12177 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$button } ) );
12178
12179 // Properties
12180 this.href = null;
12181 this.target = null;
12182 this.noFollow = false;
12183
12184 // Events
12185 this.connect( this, { disable: 'onDisable' } );
12186
12187 // Initialization
12188 this.$button.append( this.$icon, this.$label, this.$indicator );
12189 this.$element
12190 .addClass( 'oo-ui-buttonWidget' )
12191 .append( this.$button );
12192 this.setHref( config.href );
12193 this.setTarget( config.target );
12194 this.setNoFollow( config.noFollow );
12195 };
12196
12197 /* Setup */
12198
12199 OO.inheritClass( OO.ui.ButtonWidget, OO.ui.Widget );
12200 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.ButtonElement );
12201 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.IconElement );
12202 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.IndicatorElement );
12203 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.LabelElement );
12204 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.TitledElement );
12205 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.FlaggedElement );
12206 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.TabIndexedElement );
12207
12208 /* Methods */
12209
12210 /**
12211 * @inheritdoc
12212 */
12213 OO.ui.ButtonWidget.prototype.onMouseDown = function ( e ) {
12214 if ( !this.isDisabled() ) {
12215 // Remove the tab-index while the button is down to prevent the button from stealing focus
12216 this.$button.removeAttr( 'tabindex' );
12217 }
12218
12219 return OO.ui.mixin.ButtonElement.prototype.onMouseDown.call( this, e );
12220 };
12221
12222 /**
12223 * @inheritdoc
12224 */
12225 OO.ui.ButtonWidget.prototype.onMouseUp = function ( e ) {
12226 if ( !this.isDisabled() ) {
12227 // Restore the tab-index after the button is up to restore the button's accessibility
12228 this.$button.attr( 'tabindex', this.tabIndex );
12229 }
12230
12231 return OO.ui.mixin.ButtonElement.prototype.onMouseUp.call( this, e );
12232 };
12233
12234 /**
12235 * Get hyperlink location.
12236 *
12237 * @return {string} Hyperlink location
12238 */
12239 OO.ui.ButtonWidget.prototype.getHref = function () {
12240 return this.href;
12241 };
12242
12243 /**
12244 * Get hyperlink target.
12245 *
12246 * @return {string} Hyperlink target
12247 */
12248 OO.ui.ButtonWidget.prototype.getTarget = function () {
12249 return this.target;
12250 };
12251
12252 /**
12253 * Get search engine traversal hint.
12254 *
12255 * @return {boolean} Whether search engines should avoid traversing this hyperlink
12256 */
12257 OO.ui.ButtonWidget.prototype.getNoFollow = function () {
12258 return this.noFollow;
12259 };
12260
12261 /**
12262 * Set hyperlink location.
12263 *
12264 * @param {string|null} href Hyperlink location, null to remove
12265 */
12266 OO.ui.ButtonWidget.prototype.setHref = function ( href ) {
12267 href = typeof href === 'string' ? href : null;
12268 if ( href !== null ) {
12269 if ( !OO.ui.isSafeUrl( href ) ) {
12270 throw new Error( 'Potentially unsafe href provided: ' + href );
12271 }
12272
12273 }
12274
12275 if ( href !== this.href ) {
12276 this.href = href;
12277 this.updateHref();
12278 }
12279
12280 return this;
12281 };
12282
12283 /**
12284 * Update the `href` attribute, in case of changes to href or
12285 * disabled state.
12286 *
12287 * @private
12288 * @chainable
12289 */
12290 OO.ui.ButtonWidget.prototype.updateHref = function () {
12291 if ( this.href !== null && !this.isDisabled() ) {
12292 this.$button.attr( 'href', this.href );
12293 } else {
12294 this.$button.removeAttr( 'href' );
12295 }
12296
12297 return this;
12298 };
12299
12300 /**
12301 * Handle disable events.
12302 *
12303 * @private
12304 * @param {boolean} disabled Element is disabled
12305 */
12306 OO.ui.ButtonWidget.prototype.onDisable = function () {
12307 this.updateHref();
12308 };
12309
12310 /**
12311 * Set hyperlink target.
12312 *
12313 * @param {string|null} target Hyperlink target, null to remove
12314 */
12315 OO.ui.ButtonWidget.prototype.setTarget = function ( target ) {
12316 target = typeof target === 'string' ? target : null;
12317
12318 if ( target !== this.target ) {
12319 this.target = target;
12320 if ( target !== null ) {
12321 this.$button.attr( 'target', target );
12322 } else {
12323 this.$button.removeAttr( 'target' );
12324 }
12325 }
12326
12327 return this;
12328 };
12329
12330 /**
12331 * Set search engine traversal hint.
12332 *
12333 * @param {boolean} noFollow True if search engines should avoid traversing this hyperlink
12334 */
12335 OO.ui.ButtonWidget.prototype.setNoFollow = function ( noFollow ) {
12336 noFollow = typeof noFollow === 'boolean' ? noFollow : true;
12337
12338 if ( noFollow !== this.noFollow ) {
12339 this.noFollow = noFollow;
12340 if ( noFollow ) {
12341 this.$button.attr( 'rel', 'nofollow' );
12342 } else {
12343 this.$button.removeAttr( 'rel' );
12344 }
12345 }
12346
12347 return this;
12348 };
12349
12350 /**
12351 * An ActionWidget is a {@link OO.ui.ButtonWidget button widget} that executes an action.
12352 * Action widgets are used with OO.ui.ActionSet, which manages the behavior and availability
12353 * of the actions.
12354 *
12355 * Both actions and action sets are primarily used with {@link OO.ui.Dialog Dialogs}.
12356 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information
12357 * and examples.
12358 *
12359 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Action_sets
12360 *
12361 * @class
12362 * @extends OO.ui.ButtonWidget
12363 * @mixins OO.ui.mixin.PendingElement
12364 *
12365 * @constructor
12366 * @param {Object} [config] Configuration options
12367 * @cfg {string} [action] Symbolic name of the action (e.g., ‘continue’ or ‘cancel’).
12368 * @cfg {string[]} [modes] Symbolic names of the modes (e.g., ‘edit’ or ‘read’) in which the action
12369 * should be made available. See the action set's {@link OO.ui.ActionSet#setMode setMode} method
12370 * for more information about setting modes.
12371 * @cfg {boolean} [framed=false] Render the action button with a frame
12372 */
12373 OO.ui.ActionWidget = function OoUiActionWidget( config ) {
12374 // Configuration initialization
12375 config = $.extend( { framed: false }, config );
12376
12377 // Parent constructor
12378 OO.ui.ActionWidget.parent.call( this, config );
12379
12380 // Mixin constructors
12381 OO.ui.mixin.PendingElement.call( this, config );
12382
12383 // Properties
12384 this.action = config.action || '';
12385 this.modes = config.modes || [];
12386 this.width = 0;
12387 this.height = 0;
12388
12389 // Initialization
12390 this.$element.addClass( 'oo-ui-actionWidget' );
12391 };
12392
12393 /* Setup */
12394
12395 OO.inheritClass( OO.ui.ActionWidget, OO.ui.ButtonWidget );
12396 OO.mixinClass( OO.ui.ActionWidget, OO.ui.mixin.PendingElement );
12397
12398 /* Events */
12399
12400 /**
12401 * A resize event is emitted when the size of the widget changes.
12402 *
12403 * @event resize
12404 */
12405
12406 /* Methods */
12407
12408 /**
12409 * Check if the action is configured to be available in the specified `mode`.
12410 *
12411 * @param {string} mode Name of mode
12412 * @return {boolean} The action is configured with the mode
12413 */
12414 OO.ui.ActionWidget.prototype.hasMode = function ( mode ) {
12415 return this.modes.indexOf( mode ) !== -1;
12416 };
12417
12418 /**
12419 * Get the symbolic name of the action (e.g., ‘continue’ or ‘cancel’).
12420 *
12421 * @return {string}
12422 */
12423 OO.ui.ActionWidget.prototype.getAction = function () {
12424 return this.action;
12425 };
12426
12427 /**
12428 * Get the symbolic name of the mode or modes for which the action is configured to be available.
12429 *
12430 * The current mode is set with the action set's {@link OO.ui.ActionSet#setMode setMode} method.
12431 * Only actions that are configured to be avaiable in the current mode will be visible. All other actions
12432 * are hidden.
12433 *
12434 * @return {string[]}
12435 */
12436 OO.ui.ActionWidget.prototype.getModes = function () {
12437 return this.modes.slice();
12438 };
12439
12440 /**
12441 * Emit a resize event if the size has changed.
12442 *
12443 * @private
12444 * @chainable
12445 */
12446 OO.ui.ActionWidget.prototype.propagateResize = function () {
12447 var width, height;
12448
12449 if ( this.isElementAttached() ) {
12450 width = this.$element.width();
12451 height = this.$element.height();
12452
12453 if ( width !== this.width || height !== this.height ) {
12454 this.width = width;
12455 this.height = height;
12456 this.emit( 'resize' );
12457 }
12458 }
12459
12460 return this;
12461 };
12462
12463 /**
12464 * @inheritdoc
12465 */
12466 OO.ui.ActionWidget.prototype.setIcon = function () {
12467 // Mixin method
12468 OO.ui.mixin.IconElement.prototype.setIcon.apply( this, arguments );
12469 this.propagateResize();
12470
12471 return this;
12472 };
12473
12474 /**
12475 * @inheritdoc
12476 */
12477 OO.ui.ActionWidget.prototype.setLabel = function () {
12478 // Mixin method
12479 OO.ui.mixin.LabelElement.prototype.setLabel.apply( this, arguments );
12480 this.propagateResize();
12481
12482 return this;
12483 };
12484
12485 /**
12486 * @inheritdoc
12487 */
12488 OO.ui.ActionWidget.prototype.setFlags = function () {
12489 // Mixin method
12490 OO.ui.mixin.FlaggedElement.prototype.setFlags.apply( this, arguments );
12491 this.propagateResize();
12492
12493 return this;
12494 };
12495
12496 /**
12497 * @inheritdoc
12498 */
12499 OO.ui.ActionWidget.prototype.clearFlags = function () {
12500 // Mixin method
12501 OO.ui.mixin.FlaggedElement.prototype.clearFlags.apply( this, arguments );
12502 this.propagateResize();
12503
12504 return this;
12505 };
12506
12507 /**
12508 * Toggle the visibility of the action button.
12509 *
12510 * @param {boolean} [show] Show button, omit to toggle visibility
12511 * @chainable
12512 */
12513 OO.ui.ActionWidget.prototype.toggle = function () {
12514 // Parent method
12515 OO.ui.ActionWidget.parent.prototype.toggle.apply( this, arguments );
12516 this.propagateResize();
12517
12518 return this;
12519 };
12520
12521 /**
12522 * PopupButtonWidgets toggle the visibility of a contained {@link OO.ui.PopupWidget PopupWidget},
12523 * which is used to display additional information or options.
12524 *
12525 * @example
12526 * // Example of a popup button.
12527 * var popupButton = new OO.ui.PopupButtonWidget( {
12528 * label: 'Popup button with options',
12529 * icon: 'menu',
12530 * popup: {
12531 * $content: $( '<p>Additional options here.</p>' ),
12532 * padded: true,
12533 * align: 'force-left'
12534 * }
12535 * } );
12536 * // Append the button to the DOM.
12537 * $( 'body' ).append( popupButton.$element );
12538 *
12539 * @class
12540 * @extends OO.ui.ButtonWidget
12541 * @mixins OO.ui.mixin.PopupElement
12542 *
12543 * @constructor
12544 * @param {Object} [config] Configuration options
12545 */
12546 OO.ui.PopupButtonWidget = function OoUiPopupButtonWidget( config ) {
12547 // Parent constructor
12548 OO.ui.PopupButtonWidget.parent.call( this, config );
12549
12550 // Mixin constructors
12551 OO.ui.mixin.PopupElement.call( this, config );
12552
12553 // Events
12554 this.connect( this, { click: 'onAction' } );
12555
12556 // Initialization
12557 this.$element
12558 .addClass( 'oo-ui-popupButtonWidget' )
12559 .attr( 'aria-haspopup', 'true' )
12560 .append( this.popup.$element );
12561 };
12562
12563 /* Setup */
12564
12565 OO.inheritClass( OO.ui.PopupButtonWidget, OO.ui.ButtonWidget );
12566 OO.mixinClass( OO.ui.PopupButtonWidget, OO.ui.mixin.PopupElement );
12567
12568 /* Methods */
12569
12570 /**
12571 * Handle the button action being triggered.
12572 *
12573 * @private
12574 */
12575 OO.ui.PopupButtonWidget.prototype.onAction = function () {
12576 this.popup.toggle();
12577 };
12578
12579 /**
12580 * ToggleButtons are buttons that have a state (‘on’ or ‘off’) that is represented by a
12581 * Boolean value. Like other {@link OO.ui.ButtonWidget buttons}, toggle buttons can be
12582 * configured with {@link OO.ui.mixin.IconElement icons}, {@link OO.ui.mixin.IndicatorElement indicators},
12583 * {@link OO.ui.mixin.TitledElement titles}, {@link OO.ui.mixin.FlaggedElement styling flags},
12584 * and {@link OO.ui.mixin.LabelElement labels}. Please see
12585 * the [OOjs UI documentation][1] on MediaWiki for more information.
12586 *
12587 * @example
12588 * // Toggle buttons in the 'off' and 'on' state.
12589 * var toggleButton1 = new OO.ui.ToggleButtonWidget( {
12590 * label: 'Toggle Button off'
12591 * } );
12592 * var toggleButton2 = new OO.ui.ToggleButtonWidget( {
12593 * label: 'Toggle Button on',
12594 * value: true
12595 * } );
12596 * // Append the buttons to the DOM.
12597 * $( 'body' ).append( toggleButton1.$element, toggleButton2.$element );
12598 *
12599 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#Toggle_buttons
12600 *
12601 * @class
12602 * @extends OO.ui.ToggleWidget
12603 * @mixins OO.ui.mixin.ButtonElement
12604 * @mixins OO.ui.mixin.IconElement
12605 * @mixins OO.ui.mixin.IndicatorElement
12606 * @mixins OO.ui.mixin.LabelElement
12607 * @mixins OO.ui.mixin.TitledElement
12608 * @mixins OO.ui.mixin.FlaggedElement
12609 * @mixins OO.ui.mixin.TabIndexedElement
12610 *
12611 * @constructor
12612 * @param {Object} [config] Configuration options
12613 * @cfg {boolean} [value=false] The toggle button’s initial on/off
12614 * state. By default, the button is in the 'off' state.
12615 */
12616 OO.ui.ToggleButtonWidget = function OoUiToggleButtonWidget( config ) {
12617 // Configuration initialization
12618 config = config || {};
12619
12620 // Parent constructor
12621 OO.ui.ToggleButtonWidget.parent.call( this, config );
12622
12623 // Mixin constructors
12624 OO.ui.mixin.ButtonElement.call( this, config );
12625 OO.ui.mixin.IconElement.call( this, config );
12626 OO.ui.mixin.IndicatorElement.call( this, config );
12627 OO.ui.mixin.LabelElement.call( this, config );
12628 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$button } ) );
12629 OO.ui.mixin.FlaggedElement.call( this, config );
12630 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$button } ) );
12631
12632 // Events
12633 this.connect( this, { click: 'onAction' } );
12634
12635 // Initialization
12636 this.$button.append( this.$icon, this.$label, this.$indicator );
12637 this.$element
12638 .addClass( 'oo-ui-toggleButtonWidget' )
12639 .append( this.$button );
12640 };
12641
12642 /* Setup */
12643
12644 OO.inheritClass( OO.ui.ToggleButtonWidget, OO.ui.ToggleWidget );
12645 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.ButtonElement );
12646 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.IconElement );
12647 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.IndicatorElement );
12648 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.LabelElement );
12649 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.TitledElement );
12650 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.FlaggedElement );
12651 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.TabIndexedElement );
12652
12653 /* Methods */
12654
12655 /**
12656 * Handle the button action being triggered.
12657 *
12658 * @private
12659 */
12660 OO.ui.ToggleButtonWidget.prototype.onAction = function () {
12661 this.setValue( !this.value );
12662 };
12663
12664 /**
12665 * @inheritdoc
12666 */
12667 OO.ui.ToggleButtonWidget.prototype.setValue = function ( value ) {
12668 value = !!value;
12669 if ( value !== this.value ) {
12670 // Might be called from parent constructor before ButtonElement constructor
12671 if ( this.$button ) {
12672 this.$button.attr( 'aria-pressed', value.toString() );
12673 }
12674 this.setActive( value );
12675 }
12676
12677 // Parent method
12678 OO.ui.ToggleButtonWidget.parent.prototype.setValue.call( this, value );
12679
12680 return this;
12681 };
12682
12683 /**
12684 * @inheritdoc
12685 */
12686 OO.ui.ToggleButtonWidget.prototype.setButtonElement = function ( $button ) {
12687 if ( this.$button ) {
12688 this.$button.removeAttr( 'aria-pressed' );
12689 }
12690 OO.ui.mixin.ButtonElement.prototype.setButtonElement.call( this, $button );
12691 this.$button.attr( 'aria-pressed', this.value.toString() );
12692 };
12693
12694 /**
12695 * CapsuleMultiSelectWidgets are something like a {@link OO.ui.ComboBoxWidget combo box widget}
12696 * that allows for selecting multiple values.
12697 *
12698 * For more information about menus and options, please see the [OOjs UI documentation on MediaWiki][1].
12699 *
12700 * @example
12701 * // Example: A CapsuleMultiSelectWidget.
12702 * var capsule = new OO.ui.CapsuleMultiSelectWidget( {
12703 * label: 'CapsuleMultiSelectWidget',
12704 * selected: [ 'Option 1', 'Option 3' ],
12705 * menu: {
12706 * items: [
12707 * new OO.ui.MenuOptionWidget( {
12708 * data: 'Option 1',
12709 * label: 'Option One'
12710 * } ),
12711 * new OO.ui.MenuOptionWidget( {
12712 * data: 'Option 2',
12713 * label: 'Option Two'
12714 * } ),
12715 * new OO.ui.MenuOptionWidget( {
12716 * data: 'Option 3',
12717 * label: 'Option Three'
12718 * } ),
12719 * new OO.ui.MenuOptionWidget( {
12720 * data: 'Option 4',
12721 * label: 'Option Four'
12722 * } ),
12723 * new OO.ui.MenuOptionWidget( {
12724 * data: 'Option 5',
12725 * label: 'Option Five'
12726 * } )
12727 * ]
12728 * }
12729 * } );
12730 * $( 'body' ).append( capsule.$element );
12731 *
12732 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
12733 *
12734 * @class
12735 * @extends OO.ui.Widget
12736 * @mixins OO.ui.mixin.TabIndexedElement
12737 * @mixins OO.ui.mixin.GroupElement
12738 *
12739 * @constructor
12740 * @param {Object} [config] Configuration options
12741 * @cfg {boolean} [allowArbitrary=false] Allow data items to be added even if not present in the menu.
12742 * @cfg {Object} [menu] Configuration options to pass to the {@link OO.ui.MenuSelectWidget menu select widget}.
12743 * @cfg {Object} [popup] Configuration options to pass to the {@link OO.ui.PopupWidget popup widget}.
12744 * If specified, this popup will be shown instead of the menu (but the menu
12745 * will still be used for item labels and allowArbitrary=false). The widgets
12746 * in the popup should use this.addItemsFromData() or this.addItems() as necessary.
12747 * @cfg {jQuery} [$overlay] Render the menu or popup into a separate layer.
12748 * This configuration is useful in cases where the expanded menu is larger than
12749 * its containing `<div>`. The specified overlay layer is usually on top of
12750 * the containing `<div>` and has a larger area. By default, the menu uses
12751 * relative positioning.
12752 */
12753 OO.ui.CapsuleMultiSelectWidget = function OoUiCapsuleMultiSelectWidget( config ) {
12754 var $tabFocus;
12755
12756 // Configuration initialization
12757 config = config || {};
12758
12759 // Parent constructor
12760 OO.ui.CapsuleMultiSelectWidget.parent.call( this, config );
12761
12762 // Properties (must be set before mixin constructor calls)
12763 this.$input = config.popup ? null : $( '<input>' );
12764 this.$handle = $( '<div>' );
12765
12766 // Mixin constructors
12767 OO.ui.mixin.GroupElement.call( this, config );
12768 if ( config.popup ) {
12769 config.popup = $.extend( {}, config.popup, {
12770 align: 'forwards',
12771 anchor: false
12772 } );
12773 OO.ui.mixin.PopupElement.call( this, config );
12774 $tabFocus = $( '<span>' );
12775 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: $tabFocus } ) );
12776 } else {
12777 this.popup = null;
12778 $tabFocus = null;
12779 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$input } ) );
12780 }
12781 OO.ui.mixin.IndicatorElement.call( this, config );
12782 OO.ui.mixin.IconElement.call( this, config );
12783
12784 // Properties
12785 this.allowArbitrary = !!config.allowArbitrary;
12786 this.$overlay = config.$overlay || this.$element;
12787 this.menu = new OO.ui.FloatingMenuSelectWidget( $.extend(
12788 {
12789 widget: this,
12790 $input: this.$input,
12791 $container: this.$element,
12792 filterFromInput: true,
12793 disabled: this.isDisabled()
12794 },
12795 config.menu
12796 ) );
12797
12798 // Events
12799 if ( this.popup ) {
12800 $tabFocus.on( {
12801 focus: this.onFocusForPopup.bind( this )
12802 } );
12803 this.popup.$element.on( 'focusout', this.onPopupFocusOut.bind( this ) );
12804 if ( this.popup.$autoCloseIgnore ) {
12805 this.popup.$autoCloseIgnore.on( 'focusout', this.onPopupFocusOut.bind( this ) );
12806 }
12807 this.popup.connect( this, {
12808 toggle: function ( visible ) {
12809 $tabFocus.toggle( !visible );
12810 }
12811 } );
12812 } else {
12813 this.$input.on( {
12814 focus: this.onInputFocus.bind( this ),
12815 blur: this.onInputBlur.bind( this ),
12816 'propertychange change click mouseup keydown keyup input cut paste select': this.onInputChange.bind( this ),
12817 keydown: this.onKeyDown.bind( this ),
12818 keypress: this.onKeyPress.bind( this )
12819 } );
12820 }
12821 this.menu.connect( this, {
12822 choose: 'onMenuChoose',
12823 add: 'onMenuItemsChange',
12824 remove: 'onMenuItemsChange'
12825 } );
12826 this.$handle.on( {
12827 click: this.onClick.bind( this )
12828 } );
12829
12830 // Initialization
12831 if ( this.$input ) {
12832 this.$input.prop( 'disabled', this.isDisabled() );
12833 this.$input.attr( {
12834 role: 'combobox',
12835 'aria-autocomplete': 'list'
12836 } );
12837 this.$input.width( '1em' );
12838 }
12839 if ( config.data ) {
12840 this.setItemsFromData( config.data );
12841 }
12842 this.$group.addClass( 'oo-ui-capsuleMultiSelectWidget-group' );
12843 this.$handle.addClass( 'oo-ui-capsuleMultiSelectWidget-handle' )
12844 .append( this.$indicator, this.$icon, this.$group );
12845 this.$element.addClass( 'oo-ui-capsuleMultiSelectWidget' )
12846 .append( this.$handle );
12847 if ( this.popup ) {
12848 this.$handle.append( $tabFocus );
12849 this.$overlay.append( this.popup.$element );
12850 } else {
12851 this.$handle.append( this.$input );
12852 this.$overlay.append( this.menu.$element );
12853 }
12854 this.onMenuItemsChange();
12855 };
12856
12857 /* Setup */
12858
12859 OO.inheritClass( OO.ui.CapsuleMultiSelectWidget, OO.ui.Widget );
12860 OO.mixinClass( OO.ui.CapsuleMultiSelectWidget, OO.ui.mixin.GroupElement );
12861 OO.mixinClass( OO.ui.CapsuleMultiSelectWidget, OO.ui.mixin.PopupElement );
12862 OO.mixinClass( OO.ui.CapsuleMultiSelectWidget, OO.ui.mixin.TabIndexedElement );
12863 OO.mixinClass( OO.ui.CapsuleMultiSelectWidget, OO.ui.mixin.IndicatorElement );
12864 OO.mixinClass( OO.ui.CapsuleMultiSelectWidget, OO.ui.mixin.IconElement );
12865
12866 /* Events */
12867
12868 /**
12869 * @event change
12870 *
12871 * A change event is emitted when the set of selected items changes.
12872 *
12873 * @param {Mixed[]} datas Data of the now-selected items
12874 */
12875
12876 /* Methods */
12877
12878 /**
12879 * Get the data of the items in the capsule
12880 * @return {Mixed[]}
12881 */
12882 OO.ui.CapsuleMultiSelectWidget.prototype.getItemsData = function () {
12883 return $.map( this.getItems(), function ( e ) { return e.data; } );
12884 };
12885
12886 /**
12887 * Set the items in the capsule by providing data
12888 * @chainable
12889 * @param {Mixed[]} datas
12890 * @return {OO.ui.CapsuleMultiSelectWidget}
12891 */
12892 OO.ui.CapsuleMultiSelectWidget.prototype.setItemsFromData = function ( datas ) {
12893 var widget = this,
12894 menu = this.menu,
12895 items = this.getItems();
12896
12897 $.each( datas, function ( i, data ) {
12898 var j, label,
12899 item = menu.getItemFromData( data );
12900
12901 if ( item ) {
12902 label = item.label;
12903 } else if ( widget.allowArbitrary ) {
12904 label = String( data );
12905 } else {
12906 return;
12907 }
12908
12909 item = null;
12910 for ( j = 0; j < items.length; j++ ) {
12911 if ( items[j].data === data && items[j].label === label ) {
12912 item = items[j];
12913 items.splice( j, 1 );
12914 break;
12915 }
12916 }
12917 if ( !item ) {
12918 item = new OO.ui.CapsuleItemWidget( { data: data, label: label } );
12919 }
12920 widget.addItems( [ item ], i );
12921 } );
12922
12923 if ( items.length ) {
12924 widget.removeItems( items );
12925 }
12926
12927 return this;
12928 };
12929
12930 /**
12931 * Add items to the capsule by providing their data
12932 * @chainable
12933 * @param {Mixed[]} datas
12934 * @return {OO.ui.CapsuleMultiSelectWidget}
12935 */
12936 OO.ui.CapsuleMultiSelectWidget.prototype.addItemsFromData = function ( datas ) {
12937 var widget = this,
12938 menu = this.menu,
12939 items = [];
12940
12941 $.each( datas, function ( i, data ) {
12942 var item;
12943
12944 if ( !widget.getItemFromData( data ) ) {
12945 item = menu.getItemFromData( data );
12946 if ( item ) {
12947 items.push( new OO.ui.CapsuleItemWidget( { data: data, label: item.label } ) );
12948 } else if ( widget.allowArbitrary ) {
12949 items.push( new OO.ui.CapsuleItemWidget( { data: data, label: String( data ) } ) );
12950 }
12951 }
12952 } );
12953
12954 if ( items.length ) {
12955 this.addItems( items );
12956 }
12957
12958 return this;
12959 };
12960
12961 /**
12962 * Remove items by data
12963 * @chainable
12964 * @param {Mixed[]} datas
12965 * @return {OO.ui.CapsuleMultiSelectWidget}
12966 */
12967 OO.ui.CapsuleMultiSelectWidget.prototype.removeItemsFromData = function ( datas ) {
12968 var widget = this,
12969 items = [];
12970
12971 $.each( datas, function ( i, data ) {
12972 var item = widget.getItemFromData( data );
12973 if ( item ) {
12974 items.push( item );
12975 }
12976 } );
12977
12978 if ( items.length ) {
12979 this.removeItems( items );
12980 }
12981
12982 return this;
12983 };
12984
12985 /**
12986 * @inheritdoc
12987 */
12988 OO.ui.CapsuleMultiSelectWidget.prototype.addItems = function ( items ) {
12989 var same, i, l,
12990 oldItems = this.items.slice();
12991
12992 OO.ui.mixin.GroupElement.prototype.addItems.call( this, items );
12993
12994 if ( this.items.length !== oldItems.length ) {
12995 same = false;
12996 } else {
12997 same = true;
12998 for ( i = 0, l = oldItems.length; same && i < l; i++ ) {
12999 same = same && this.items[i] === oldItems[i];
13000 }
13001 }
13002 if ( !same ) {
13003 this.emit( 'change', this.getItemsData() );
13004 }
13005
13006 return this;
13007 };
13008
13009 /**
13010 * @inheritdoc
13011 */
13012 OO.ui.CapsuleMultiSelectWidget.prototype.removeItems = function ( items ) {
13013 var same, i, l,
13014 oldItems = this.items.slice();
13015
13016 OO.ui.mixin.GroupElement.prototype.removeItems.call( this, items );
13017
13018 if ( this.items.length !== oldItems.length ) {
13019 same = false;
13020 } else {
13021 same = true;
13022 for ( i = 0, l = oldItems.length; same && i < l; i++ ) {
13023 same = same && this.items[i] === oldItems[i];
13024 }
13025 }
13026 if ( !same ) {
13027 this.emit( 'change', this.getItemsData() );
13028 }
13029
13030 return this;
13031 };
13032
13033 /**
13034 * @inheritdoc
13035 */
13036 OO.ui.CapsuleMultiSelectWidget.prototype.clearItems = function () {
13037 if ( this.items.length ) {
13038 OO.ui.mixin.GroupElement.prototype.clearItems.call( this );
13039 this.emit( 'change', this.getItemsData() );
13040 }
13041 return this;
13042 };
13043
13044 /**
13045 * Get the capsule widget's menu.
13046 * @return {OO.ui.MenuSelectWidget} Menu widget
13047 */
13048 OO.ui.CapsuleMultiSelectWidget.prototype.getMenu = function () {
13049 return this.menu;
13050 };
13051
13052 /**
13053 * Handle focus events
13054 *
13055 * @private
13056 * @param {jQuery.Event} event
13057 */
13058 OO.ui.CapsuleMultiSelectWidget.prototype.onInputFocus = function () {
13059 if ( !this.isDisabled() ) {
13060 this.menu.toggle( true );
13061 }
13062 };
13063
13064 /**
13065 * Handle blur events
13066 *
13067 * @private
13068 * @param {jQuery.Event} event
13069 */
13070 OO.ui.CapsuleMultiSelectWidget.prototype.onInputBlur = function () {
13071 this.clearInput();
13072 };
13073
13074 /**
13075 * Handle focus events
13076 *
13077 * @private
13078 * @param {jQuery.Event} event
13079 */
13080 OO.ui.CapsuleMultiSelectWidget.prototype.onFocusForPopup = function () {
13081 if ( !this.isDisabled() ) {
13082 this.popup.setSize( this.$handle.width() );
13083 this.popup.toggle( true );
13084 this.popup.$element.find( '*' )
13085 .filter( function () { return OO.ui.isFocusableElement( $( this ), true ); } )
13086 .first()
13087 .focus();
13088 }
13089 };
13090
13091 /**
13092 * Handles popup focus out events.
13093 *
13094 * @private
13095 * @param {Event} e Focus out event
13096 */
13097 OO.ui.CapsuleMultiSelectWidget.prototype.onPopupFocusOut = function () {
13098 var widget = this.popup;
13099
13100 setTimeout( function () {
13101 if (
13102 widget.isVisible() &&
13103 !OO.ui.contains( widget.$element[0], document.activeElement, true ) &&
13104 ( !widget.$autoCloseIgnore || !widget.$autoCloseIgnore.has( document.activeElement ).length )
13105 ) {
13106 widget.toggle( false );
13107 }
13108 } );
13109 };
13110
13111 /**
13112 * Handle mouse click events.
13113 *
13114 * @private
13115 * @param {jQuery.Event} e Mouse click event
13116 */
13117 OO.ui.CapsuleMultiSelectWidget.prototype.onClick = function ( e ) {
13118 if ( e.which === 1 ) {
13119 this.focus();
13120 return false;
13121 }
13122 };
13123
13124 /**
13125 * Handle key press events.
13126 *
13127 * @private
13128 * @param {jQuery.Event} e Key press event
13129 */
13130 OO.ui.CapsuleMultiSelectWidget.prototype.onKeyPress = function ( e ) {
13131 var item;
13132
13133 if ( !this.isDisabled() ) {
13134 if ( e.which === OO.ui.Keys.ESCAPE ) {
13135 this.clearInput();
13136 return false;
13137 }
13138
13139 if ( !this.popup ) {
13140 this.menu.toggle( true );
13141 if ( e.which === OO.ui.Keys.ENTER ) {
13142 item = this.menu.getItemFromLabel( this.$input.val(), true );
13143 if ( item ) {
13144 this.addItemsFromData( [ item.data ] );
13145 this.clearInput();
13146 } else if ( this.allowArbitrary && this.$input.val().trim() !== '' ) {
13147 this.addItemsFromData( [ this.$input.val() ] );
13148 this.clearInput();
13149 }
13150 return false;
13151 }
13152
13153 // Make sure the input gets resized.
13154 setTimeout( this.onInputChange.bind( this ), 0 );
13155 }
13156 }
13157 };
13158
13159 /**
13160 * Handle key down events.
13161 *
13162 * @private
13163 * @param {jQuery.Event} e Key down event
13164 */
13165 OO.ui.CapsuleMultiSelectWidget.prototype.onKeyDown = function ( e ) {
13166 if ( !this.isDisabled() ) {
13167 // 'keypress' event is not triggered for Backspace
13168 if ( e.keyCode === OO.ui.Keys.BACKSPACE && this.$input.val() === '' ) {
13169 if ( this.items.length ) {
13170 this.removeItems( this.items.slice( -1 ) );
13171 }
13172 return false;
13173 }
13174 }
13175 };
13176
13177 /**
13178 * Handle input change events.
13179 *
13180 * @private
13181 * @param {jQuery.Event} e Event of some sort
13182 */
13183 OO.ui.CapsuleMultiSelectWidget.prototype.onInputChange = function () {
13184 if ( !this.isDisabled() ) {
13185 this.$input.width( this.$input.val().length + 'em' );
13186 }
13187 };
13188
13189 /**
13190 * Handle menu choose events.
13191 *
13192 * @private
13193 * @param {OO.ui.OptionWidget} item Chosen item
13194 */
13195 OO.ui.CapsuleMultiSelectWidget.prototype.onMenuChoose = function ( item ) {
13196 if ( item && item.isVisible() ) {
13197 this.addItemsFromData( [ item.getData() ] );
13198 this.clearInput();
13199 }
13200 };
13201
13202 /**
13203 * Handle menu item change events.
13204 *
13205 * @private
13206 */
13207 OO.ui.CapsuleMultiSelectWidget.prototype.onMenuItemsChange = function () {
13208 this.setItemsFromData( this.getItemsData() );
13209 this.$element.toggleClass( 'oo-ui-capsuleMultiSelectWidget-empty', this.menu.isEmpty() );
13210 };
13211
13212 /**
13213 * Clear the input field
13214 * @private
13215 */
13216 OO.ui.CapsuleMultiSelectWidget.prototype.clearInput = function () {
13217 if ( this.$input ) {
13218 this.$input.val( '' );
13219 this.$input.width( '1em' );
13220 }
13221 if ( this.popup ) {
13222 this.popup.toggle( false );
13223 }
13224 this.menu.toggle( false );
13225 this.menu.selectItem();
13226 this.menu.highlightItem();
13227 };
13228
13229 /**
13230 * @inheritdoc
13231 */
13232 OO.ui.CapsuleMultiSelectWidget.prototype.setDisabled = function ( disabled ) {
13233 var i, len;
13234
13235 // Parent method
13236 OO.ui.CapsuleMultiSelectWidget.parent.prototype.setDisabled.call( this, disabled );
13237
13238 if ( this.$input ) {
13239 this.$input.prop( 'disabled', this.isDisabled() );
13240 }
13241 if ( this.menu ) {
13242 this.menu.setDisabled( this.isDisabled() );
13243 }
13244 if ( this.popup ) {
13245 this.popup.setDisabled( this.isDisabled() );
13246 }
13247
13248 if ( this.items ) {
13249 for ( i = 0, len = this.items.length; i < len; i++ ) {
13250 this.items[i].updateDisabled();
13251 }
13252 }
13253
13254 return this;
13255 };
13256
13257 /**
13258 * Focus the widget
13259 * @chainable
13260 * @return {OO.ui.CapsuleMultiSelectWidget}
13261 */
13262 OO.ui.CapsuleMultiSelectWidget.prototype.focus = function () {
13263 if ( !this.isDisabled() ) {
13264 if ( this.popup ) {
13265 this.popup.setSize( this.$handle.width() );
13266 this.popup.toggle( true );
13267 this.popup.$element.find( '*' )
13268 .filter( function () { return OO.ui.isFocusableElement( $( this ), true ); } )
13269 .first()
13270 .focus();
13271 } else {
13272 this.menu.toggle( true );
13273 this.$input.focus();
13274 }
13275 }
13276 return this;
13277 };
13278
13279 /**
13280 * CapsuleItemWidgets are used within a {@link OO.ui.CapsuleMultiSelectWidget
13281 * CapsuleMultiSelectWidget} to display the selected items.
13282 *
13283 * @class
13284 * @extends OO.ui.Widget
13285 * @mixins OO.ui.mixin.ItemWidget
13286 * @mixins OO.ui.mixin.IndicatorElement
13287 * @mixins OO.ui.mixin.LabelElement
13288 * @mixins OO.ui.mixin.FlaggedElement
13289 * @mixins OO.ui.mixin.TabIndexedElement
13290 *
13291 * @constructor
13292 * @param {Object} [config] Configuration options
13293 */
13294 OO.ui.CapsuleItemWidget = function OoUiCapsuleItemWidget( config ) {
13295 // Configuration initialization
13296 config = config || {};
13297
13298 // Parent constructor
13299 OO.ui.CapsuleItemWidget.parent.call( this, config );
13300
13301 // Properties (must be set before mixin constructor calls)
13302 this.$indicator = $( '<span>' );
13303
13304 // Mixin constructors
13305 OO.ui.mixin.ItemWidget.call( this );
13306 OO.ui.mixin.IndicatorElement.call( this, $.extend( {}, config, { $indicator: this.$indicator, indicator: 'clear' } ) );
13307 OO.ui.mixin.LabelElement.call( this, config );
13308 OO.ui.mixin.FlaggedElement.call( this, config );
13309 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$indicator } ) );
13310
13311 // Events
13312 this.$indicator.on( {
13313 keydown: this.onCloseKeyDown.bind( this ),
13314 click: this.onCloseClick.bind( this )
13315 } );
13316 this.$element.on( 'click', false );
13317
13318 // Initialization
13319 this.$element
13320 .addClass( 'oo-ui-capsuleItemWidget' )
13321 .append( this.$indicator, this.$label );
13322 };
13323
13324 /* Setup */
13325
13326 OO.inheritClass( OO.ui.CapsuleItemWidget, OO.ui.Widget );
13327 OO.mixinClass( OO.ui.CapsuleItemWidget, OO.ui.mixin.ItemWidget );
13328 OO.mixinClass( OO.ui.CapsuleItemWidget, OO.ui.mixin.IndicatorElement );
13329 OO.mixinClass( OO.ui.CapsuleItemWidget, OO.ui.mixin.LabelElement );
13330 OO.mixinClass( OO.ui.CapsuleItemWidget, OO.ui.mixin.FlaggedElement );
13331 OO.mixinClass( OO.ui.CapsuleItemWidget, OO.ui.mixin.TabIndexedElement );
13332
13333 /* Methods */
13334
13335 /**
13336 * Handle close icon clicks
13337 * @param {jQuery.Event} event
13338 */
13339 OO.ui.CapsuleItemWidget.prototype.onCloseClick = function () {
13340 var element = this.getElementGroup();
13341
13342 if ( !this.isDisabled() && element && $.isFunction( element.removeItems ) ) {
13343 element.removeItems( [ this ] );
13344 element.focus();
13345 }
13346 };
13347
13348 /**
13349 * Handle close keyboard events
13350 * @param {jQuery.Event} event Key down event
13351 */
13352 OO.ui.CapsuleItemWidget.prototype.onCloseKeyDown = function ( e ) {
13353 if ( !this.isDisabled() && $.isFunction( this.getElementGroup().removeItems ) ) {
13354 switch ( e.which ) {
13355 case OO.ui.Keys.ENTER:
13356 case OO.ui.Keys.BACKSPACE:
13357 case OO.ui.Keys.SPACE:
13358 this.getElementGroup().removeItems( [ this ] );
13359 return false;
13360 }
13361 }
13362 };
13363
13364 /**
13365 * DropdownWidgets are not menus themselves, rather they contain a menu of options created with
13366 * OO.ui.MenuOptionWidget. The DropdownWidget takes care of opening and displaying the menu so that
13367 * users can interact with it.
13368 *
13369 * If you want to use this within a HTML form, such as a OO.ui.FormLayout, use
13370 * OO.ui.DropdownInputWidget instead.
13371 *
13372 * @example
13373 * // Example: A DropdownWidget with a menu that contains three options
13374 * var dropDown = new OO.ui.DropdownWidget( {
13375 * label: 'Dropdown menu: Select a menu option',
13376 * menu: {
13377 * items: [
13378 * new OO.ui.MenuOptionWidget( {
13379 * data: 'a',
13380 * label: 'First'
13381 * } ),
13382 * new OO.ui.MenuOptionWidget( {
13383 * data: 'b',
13384 * label: 'Second'
13385 * } ),
13386 * new OO.ui.MenuOptionWidget( {
13387 * data: 'c',
13388 * label: 'Third'
13389 * } )
13390 * ]
13391 * }
13392 * } );
13393 *
13394 * $( 'body' ).append( dropDown.$element );
13395 *
13396 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
13397 *
13398 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
13399 *
13400 * @class
13401 * @extends OO.ui.Widget
13402 * @mixins OO.ui.mixin.IconElement
13403 * @mixins OO.ui.mixin.IndicatorElement
13404 * @mixins OO.ui.mixin.LabelElement
13405 * @mixins OO.ui.mixin.TitledElement
13406 * @mixins OO.ui.mixin.TabIndexedElement
13407 *
13408 * @constructor
13409 * @param {Object} [config] Configuration options
13410 * @cfg {Object} [menu] Configuration options to pass to {@link OO.ui.FloatingMenuSelectWidget menu select widget}
13411 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
13412 * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
13413 * containing `<div>` and has a larger area. By default, the menu uses relative positioning.
13414 */
13415 OO.ui.DropdownWidget = function OoUiDropdownWidget( config ) {
13416 // Configuration initialization
13417 config = $.extend( { indicator: 'down' }, config );
13418
13419 // Parent constructor
13420 OO.ui.DropdownWidget.parent.call( this, config );
13421
13422 // Properties (must be set before TabIndexedElement constructor call)
13423 this.$handle = this.$( '<span>' );
13424 this.$overlay = config.$overlay || this.$element;
13425
13426 // Mixin constructors
13427 OO.ui.mixin.IconElement.call( this, config );
13428 OO.ui.mixin.IndicatorElement.call( this, config );
13429 OO.ui.mixin.LabelElement.call( this, config );
13430 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$label } ) );
13431 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$handle } ) );
13432
13433 // Properties
13434 this.menu = new OO.ui.FloatingMenuSelectWidget( $.extend( {
13435 widget: this,
13436 $container: this.$element
13437 }, config.menu ) );
13438
13439 // Events
13440 this.$handle.on( {
13441 click: this.onClick.bind( this ),
13442 keypress: this.onKeyPress.bind( this )
13443 } );
13444 this.menu.connect( this, { select: 'onMenuSelect' } );
13445
13446 // Initialization
13447 this.$handle
13448 .addClass( 'oo-ui-dropdownWidget-handle' )
13449 .append( this.$icon, this.$label, this.$indicator );
13450 this.$element
13451 .addClass( 'oo-ui-dropdownWidget' )
13452 .append( this.$handle );
13453 this.$overlay.append( this.menu.$element );
13454 };
13455
13456 /* Setup */
13457
13458 OO.inheritClass( OO.ui.DropdownWidget, OO.ui.Widget );
13459 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.IconElement );
13460 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.IndicatorElement );
13461 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.LabelElement );
13462 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.TitledElement );
13463 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.TabIndexedElement );
13464
13465 /* Methods */
13466
13467 /**
13468 * Get the menu.
13469 *
13470 * @return {OO.ui.MenuSelectWidget} Menu of widget
13471 */
13472 OO.ui.DropdownWidget.prototype.getMenu = function () {
13473 return this.menu;
13474 };
13475
13476 /**
13477 * Handles menu select events.
13478 *
13479 * @private
13480 * @param {OO.ui.MenuOptionWidget} item Selected menu item
13481 */
13482 OO.ui.DropdownWidget.prototype.onMenuSelect = function ( item ) {
13483 var selectedLabel;
13484
13485 if ( !item ) {
13486 this.setLabel( null );
13487 return;
13488 }
13489
13490 selectedLabel = item.getLabel();
13491
13492 // If the label is a DOM element, clone it, because setLabel will append() it
13493 if ( selectedLabel instanceof jQuery ) {
13494 selectedLabel = selectedLabel.clone();
13495 }
13496
13497 this.setLabel( selectedLabel );
13498 };
13499
13500 /**
13501 * Handle mouse click events.
13502 *
13503 * @private
13504 * @param {jQuery.Event} e Mouse click event
13505 */
13506 OO.ui.DropdownWidget.prototype.onClick = function ( e ) {
13507 if ( !this.isDisabled() && e.which === 1 ) {
13508 this.menu.toggle();
13509 }
13510 return false;
13511 };
13512
13513 /**
13514 * Handle key press events.
13515 *
13516 * @private
13517 * @param {jQuery.Event} e Key press event
13518 */
13519 OO.ui.DropdownWidget.prototype.onKeyPress = function ( e ) {
13520 if ( !this.isDisabled() &&
13521 ( ( e.which === OO.ui.Keys.SPACE && !this.menu.isVisible() ) || e.which === OO.ui.Keys.ENTER )
13522 ) {
13523 this.menu.toggle();
13524 return false;
13525 }
13526 };
13527
13528 /**
13529 * SelectFileWidgets allow for selecting files, using the HTML5 File API. These
13530 * widgets can be configured with {@link OO.ui.mixin.IconElement icons} and {@link
13531 * OO.ui.mixin.IndicatorElement indicators}.
13532 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
13533 *
13534 * @example
13535 * // Example of a file select widget
13536 * var selectFile = new OO.ui.SelectFileWidget();
13537 * $( 'body' ).append( selectFile.$element );
13538 *
13539 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets
13540 *
13541 * @class
13542 * @extends OO.ui.Widget
13543 * @mixins OO.ui.mixin.IconElement
13544 * @mixins OO.ui.mixin.IndicatorElement
13545 * @mixins OO.ui.mixin.PendingElement
13546 * @mixins OO.ui.mixin.LabelElement
13547 * @mixins OO.ui.mixin.TabIndexedElement
13548 *
13549 * @constructor
13550 * @param {Object} [config] Configuration options
13551 * @cfg {string[]|null} [accept=null] MIME types to accept. null accepts all types.
13552 * @cfg {string} [placeholder] Text to display when no file is selected.
13553 * @cfg {string} [notsupported] Text to display when file support is missing in the browser.
13554 * @cfg {boolean} [droppable=true] Whether to accept files by drag and drop.
13555 */
13556 OO.ui.SelectFileWidget = function OoUiSelectFileWidget( config ) {
13557 var dragHandler;
13558
13559 // Configuration initialization
13560 config = $.extend( {
13561 accept: null,
13562 placeholder: OO.ui.msg( 'ooui-selectfile-placeholder' ),
13563 notsupported: OO.ui.msg( 'ooui-selectfile-not-supported' ),
13564 droppable: true
13565 }, config );
13566
13567 // Parent constructor
13568 OO.ui.SelectFileWidget.parent.call( this, config );
13569
13570 // Properties (must be set before TabIndexedElement constructor call)
13571 this.$handle = $( '<span>' );
13572
13573 // Mixin constructors
13574 OO.ui.mixin.IconElement.call( this, config );
13575 OO.ui.mixin.IndicatorElement.call( this, config );
13576 OO.ui.mixin.PendingElement.call( this, $.extend( {}, config, { $pending: this.$handle } ) );
13577 OO.ui.mixin.LabelElement.call( this, $.extend( {}, config, { autoFitLabel: true } ) );
13578 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$handle } ) );
13579
13580 // Properties
13581 this.isSupported = this.constructor.static.isSupported();
13582 this.currentFile = null;
13583 if ( Array.isArray( config.accept ) ) {
13584 this.accept = config.accept;
13585 } else {
13586 this.accept = null;
13587 }
13588 this.placeholder = config.placeholder;
13589 this.notsupported = config.notsupported;
13590 this.onFileSelectedHandler = this.onFileSelected.bind( this );
13591
13592 this.clearButton = new OO.ui.ButtonWidget( {
13593 classes: [ 'oo-ui-selectFileWidget-clearButton' ],
13594 framed: false,
13595 icon: 'remove',
13596 disabled: this.disabled
13597 } );
13598
13599 // Events
13600 this.$handle.on( {
13601 keypress: this.onKeyPress.bind( this )
13602 } );
13603 this.clearButton.connect( this, {
13604 click: 'onClearClick'
13605 } );
13606 if ( config.droppable ) {
13607 dragHandler = this.onDragEnterOrOver.bind( this );
13608 this.$handle.on( {
13609 dragenter: dragHandler,
13610 dragover: dragHandler,
13611 dragleave: this.onDragLeave.bind( this ),
13612 drop: this.onDrop.bind( this )
13613 } );
13614 }
13615
13616 // Initialization
13617 this.addInput();
13618 this.updateUI();
13619 this.$label.addClass( 'oo-ui-selectFileWidget-label' );
13620 this.$handle
13621 .addClass( 'oo-ui-selectFileWidget-handle' )
13622 .append( this.$icon, this.$label, this.clearButton.$element, this.$indicator );
13623 this.$element
13624 .addClass( 'oo-ui-selectFileWidget' )
13625 .append( this.$handle );
13626 if ( config.droppable ) {
13627 this.$element.addClass( 'oo-ui-selectFileWidget-droppable' );
13628 }
13629 };
13630
13631 /* Setup */
13632
13633 OO.inheritClass( OO.ui.SelectFileWidget, OO.ui.Widget );
13634 OO.mixinClass( OO.ui.SelectFileWidget, OO.ui.mixin.IconElement );
13635 OO.mixinClass( OO.ui.SelectFileWidget, OO.ui.mixin.IndicatorElement );
13636 OO.mixinClass( OO.ui.SelectFileWidget, OO.ui.mixin.PendingElement );
13637 OO.mixinClass( OO.ui.SelectFileWidget, OO.ui.mixin.LabelElement );
13638 OO.mixinClass( OO.ui.SelectFileWidget, OO.ui.mixin.TabIndexedElement );
13639
13640 /* Static Properties */
13641
13642 /**
13643 * Check if this widget is supported
13644 *
13645 * @static
13646 * @return {boolean}
13647 */
13648 OO.ui.SelectFileWidget.static.isSupported = function () {
13649 var $input;
13650 if ( OO.ui.SelectFileWidget.static.isSupportedCache === null ) {
13651 $input = $( '<input type="file">' );
13652 OO.ui.SelectFileWidget.static.isSupportedCache = $input[0].files !== undefined;
13653 }
13654 return OO.ui.SelectFileWidget.static.isSupportedCache;
13655 };
13656
13657 OO.ui.SelectFileWidget.static.isSupportedCache = null;
13658
13659 /* Events */
13660
13661 /**
13662 * @event change
13663 *
13664 * A change event is emitted when the on/off state of the toggle changes.
13665 *
13666 * @param {File|null} value New value
13667 */
13668
13669 /* Methods */
13670
13671 /**
13672 * Get the current value of the field
13673 *
13674 * @return {File|null}
13675 */
13676 OO.ui.SelectFileWidget.prototype.getValue = function () {
13677 return this.currentFile;
13678 };
13679
13680 /**
13681 * Set the current value of the field
13682 *
13683 * @param {File|null} file File to select
13684 */
13685 OO.ui.SelectFileWidget.prototype.setValue = function ( file ) {
13686 if ( this.currentFile !== file ) {
13687 this.currentFile = file;
13688 this.updateUI();
13689 this.emit( 'change', this.currentFile );
13690 }
13691 };
13692
13693 /**
13694 * Update the user interface when a file is selected or unselected
13695 *
13696 * @protected
13697 */
13698 OO.ui.SelectFileWidget.prototype.updateUI = function () {
13699 if ( !this.isSupported ) {
13700 this.$element.addClass( 'oo-ui-selectFileWidget-notsupported' );
13701 this.$element.removeClass( 'oo-ui-selectFileWidget-empty' );
13702 this.setLabel( this.notsupported );
13703 } else if ( this.currentFile ) {
13704 this.$element.removeClass( 'oo-ui-selectFileWidget-empty' );
13705 this.setLabel( this.currentFile.name +
13706 ( this.currentFile.type !== '' ? OO.ui.msg( 'ooui-semicolon-separator' ) + this.currentFile.type : '' )
13707 );
13708 } else {
13709 this.$element.addClass( 'oo-ui-selectFileWidget-empty' );
13710 this.setLabel( this.placeholder );
13711 }
13712
13713 if ( this.$input ) {
13714 this.$input.attr( 'title', this.getLabel() );
13715 }
13716 };
13717
13718 /**
13719 * Add the input to the handle
13720 *
13721 * @private
13722 */
13723 OO.ui.SelectFileWidget.prototype.addInput = function () {
13724 if ( this.$input ) {
13725 this.$input.remove();
13726 }
13727
13728 if ( !this.isSupported ) {
13729 this.$input = null;
13730 return;
13731 }
13732
13733 this.$input = $( '<input type="file">' );
13734 this.$input.on( 'change', this.onFileSelectedHandler );
13735 this.$input.attr( {
13736 tabindex: -1,
13737 title: this.getLabel()
13738 } );
13739 if ( this.accept ) {
13740 this.$input.attr( 'accept', this.accept.join( ', ' ) );
13741 }
13742 this.$handle.append( this.$input );
13743 };
13744
13745 /**
13746 * Determine if we should accept this file
13747 *
13748 * @private
13749 * @param {File} file
13750 * @return {boolean}
13751 */
13752 OO.ui.SelectFileWidget.prototype.isFileAcceptable = function ( file ) {
13753 var i, mime, mimeTest;
13754
13755 if ( !this.accept || file.type === '' ) {
13756 return true;
13757 }
13758
13759 mime = file.type;
13760 for ( i = 0; i < this.accept.length; i++ ) {
13761 mimeTest = this.accept[i];
13762 if ( mimeTest === mime ) {
13763 return true;
13764 } else if ( mimeTest.substr( -2 ) === '/*' ) {
13765 mimeTest = mimeTest.substr( 0, mimeTest.length - 1 );
13766 if ( mime.substr( 0, mimeTest.length ) === mimeTest ) {
13767 return true;
13768 }
13769 }
13770 }
13771
13772 return false;
13773 };
13774
13775 /**
13776 * Handle file selection from the input
13777 *
13778 * @private
13779 * @param {jQuery.Event} e
13780 */
13781 OO.ui.SelectFileWidget.prototype.onFileSelected = function ( e ) {
13782 var file = null;
13783
13784 if ( e.target.files && e.target.files[0] ) {
13785 file = e.target.files[0];
13786 if ( !this.isFileAcceptable( file ) ) {
13787 file = null;
13788 }
13789 }
13790
13791 this.setValue( file );
13792 this.addInput();
13793 };
13794
13795 /**
13796 * Handle clear button click events.
13797 *
13798 * @private
13799 */
13800 OO.ui.SelectFileWidget.prototype.onClearClick = function () {
13801 this.setValue( null );
13802 return false;
13803 };
13804
13805 /**
13806 * Handle key press events.
13807 *
13808 * @private
13809 * @param {jQuery.Event} e Key press event
13810 */
13811 OO.ui.SelectFileWidget.prototype.onKeyPress = function ( e ) {
13812 if ( this.isSupported && !this.isDisabled() && this.$input &&
13813 ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
13814 ) {
13815 this.$input.click();
13816 return false;
13817 }
13818 };
13819
13820 /**
13821 * Handle drag enter and over events
13822 *
13823 * @private
13824 * @param {jQuery.Event} e Drag event
13825 */
13826 OO.ui.SelectFileWidget.prototype.onDragEnterOrOver = function ( e ) {
13827 var file = null,
13828 dt = e.originalEvent.dataTransfer;
13829
13830 e.preventDefault();
13831 e.stopPropagation();
13832
13833 if ( this.isDisabled() || !this.isSupported ) {
13834 this.$element.removeClass( 'oo-ui-selectFileWidget-canDrop' );
13835 dt.dropEffect = 'none';
13836 return false;
13837 }
13838
13839 if ( dt && dt.files && dt.files[0] ) {
13840 file = dt.files[0];
13841 if ( !this.isFileAcceptable( file ) ) {
13842 file = null;
13843 }
13844 } else if ( dt && dt.types && $.inArray( 'Files', dt.types ) ) {
13845 // We know we have files so set 'file' to something truthy, we just
13846 // can't know any details about them.
13847 // * https://bugzilla.mozilla.org/show_bug.cgi?id=640534
13848 file = 'Files exist, but details are unknown';
13849 }
13850 if ( file ) {
13851 this.$element.addClass( 'oo-ui-selectFileWidget-canDrop' );
13852 } else {
13853 this.$element.removeClass( 'oo-ui-selectFileWidget-canDrop' );
13854 dt.dropEffect = 'none';
13855 }
13856
13857 return false;
13858 };
13859
13860 /**
13861 * Handle drag leave events
13862 *
13863 * @private
13864 * @param {jQuery.Event} e Drag event
13865 */
13866 OO.ui.SelectFileWidget.prototype.onDragLeave = function () {
13867 this.$element.removeClass( 'oo-ui-selectFileWidget-canDrop' );
13868 };
13869
13870 /**
13871 * Handle drop events
13872 *
13873 * @private
13874 * @param {jQuery.Event} e Drop event
13875 */
13876 OO.ui.SelectFileWidget.prototype.onDrop = function ( e ) {
13877 var file = null,
13878 dt = e.originalEvent.dataTransfer;
13879
13880 e.preventDefault();
13881 e.stopPropagation();
13882 this.$element.removeClass( 'oo-ui-selectFileWidget-canDrop' );
13883
13884 if ( this.isDisabled() || !this.isSupported ) {
13885 return false;
13886 }
13887
13888 if ( dt && dt.files && dt.files[0] ) {
13889 file = dt.files[0];
13890 if ( !this.isFileAcceptable( file ) ) {
13891 file = null;
13892 }
13893 }
13894 if ( file ) {
13895 this.setValue( file );
13896 }
13897
13898 return false;
13899 };
13900
13901 /**
13902 * @inheritdoc
13903 */
13904 OO.ui.SelectFileWidget.prototype.setDisabled = function ( state ) {
13905 OO.ui.SelectFileWidget.parent.prototype.setDisabled.call( this, state );
13906 if ( this.clearButton ) {
13907 this.clearButton.setDisabled( state );
13908 }
13909 return this;
13910 };
13911
13912 /**
13913 * IconWidget is a generic widget for {@link OO.ui.mixin.IconElement icons}. In general, IconWidgets should be used with OO.ui.LabelWidget,
13914 * which creates a label that identifies the icon’s function. See the [OOjs UI documentation on MediaWiki] [1]
13915 * for a list of icons included in the library.
13916 *
13917 * @example
13918 * // An icon widget with a label
13919 * var myIcon = new OO.ui.IconWidget( {
13920 * icon: 'help',
13921 * iconTitle: 'Help'
13922 * } );
13923 * // Create a label.
13924 * var iconLabel = new OO.ui.LabelWidget( {
13925 * label: 'Help'
13926 * } );
13927 * $( 'body' ).append( myIcon.$element, iconLabel.$element );
13928 *
13929 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
13930 *
13931 * @class
13932 * @extends OO.ui.Widget
13933 * @mixins OO.ui.mixin.IconElement
13934 * @mixins OO.ui.mixin.TitledElement
13935 * @mixins OO.ui.mixin.FlaggedElement
13936 *
13937 * @constructor
13938 * @param {Object} [config] Configuration options
13939 */
13940 OO.ui.IconWidget = function OoUiIconWidget( config ) {
13941 // Configuration initialization
13942 config = config || {};
13943
13944 // Parent constructor
13945 OO.ui.IconWidget.parent.call( this, config );
13946
13947 // Mixin constructors
13948 OO.ui.mixin.IconElement.call( this, $.extend( {}, config, { $icon: this.$element } ) );
13949 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$element } ) );
13950 OO.ui.mixin.FlaggedElement.call( this, $.extend( {}, config, { $flagged: this.$element } ) );
13951
13952 // Initialization
13953 this.$element.addClass( 'oo-ui-iconWidget' );
13954 };
13955
13956 /* Setup */
13957
13958 OO.inheritClass( OO.ui.IconWidget, OO.ui.Widget );
13959 OO.mixinClass( OO.ui.IconWidget, OO.ui.mixin.IconElement );
13960 OO.mixinClass( OO.ui.IconWidget, OO.ui.mixin.TitledElement );
13961 OO.mixinClass( OO.ui.IconWidget, OO.ui.mixin.FlaggedElement );
13962
13963 /* Static Properties */
13964
13965 OO.ui.IconWidget.static.tagName = 'span';
13966
13967 /**
13968 * IndicatorWidgets create indicators, which are small graphics that are generally used to draw
13969 * attention to the status of an item or to clarify the function of a control. For a list of
13970 * indicators included in the library, please see the [OOjs UI documentation on MediaWiki][1].
13971 *
13972 * @example
13973 * // Example of an indicator widget
13974 * var indicator1 = new OO.ui.IndicatorWidget( {
13975 * indicator: 'alert'
13976 * } );
13977 *
13978 * // Create a fieldset layout to add a label
13979 * var fieldset = new OO.ui.FieldsetLayout();
13980 * fieldset.addItems( [
13981 * new OO.ui.FieldLayout( indicator1, { label: 'An alert indicator:' } )
13982 * ] );
13983 * $( 'body' ).append( fieldset.$element );
13984 *
13985 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
13986 *
13987 * @class
13988 * @extends OO.ui.Widget
13989 * @mixins OO.ui.mixin.IndicatorElement
13990 * @mixins OO.ui.mixin.TitledElement
13991 *
13992 * @constructor
13993 * @param {Object} [config] Configuration options
13994 */
13995 OO.ui.IndicatorWidget = function OoUiIndicatorWidget( config ) {
13996 // Configuration initialization
13997 config = config || {};
13998
13999 // Parent constructor
14000 OO.ui.IndicatorWidget.parent.call( this, config );
14001
14002 // Mixin constructors
14003 OO.ui.mixin.IndicatorElement.call( this, $.extend( {}, config, { $indicator: this.$element } ) );
14004 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$element } ) );
14005
14006 // Initialization
14007 this.$element.addClass( 'oo-ui-indicatorWidget' );
14008 };
14009
14010 /* Setup */
14011
14012 OO.inheritClass( OO.ui.IndicatorWidget, OO.ui.Widget );
14013 OO.mixinClass( OO.ui.IndicatorWidget, OO.ui.mixin.IndicatorElement );
14014 OO.mixinClass( OO.ui.IndicatorWidget, OO.ui.mixin.TitledElement );
14015
14016 /* Static Properties */
14017
14018 OO.ui.IndicatorWidget.static.tagName = 'span';
14019
14020 /**
14021 * InputWidget is the base class for all input widgets, which
14022 * include {@link OO.ui.TextInputWidget text inputs}, {@link OO.ui.CheckboxInputWidget checkbox inputs},
14023 * {@link OO.ui.RadioInputWidget radio inputs}, and {@link OO.ui.ButtonInputWidget button inputs}.
14024 * See the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
14025 *
14026 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
14027 *
14028 * @abstract
14029 * @class
14030 * @extends OO.ui.Widget
14031 * @mixins OO.ui.mixin.FlaggedElement
14032 * @mixins OO.ui.mixin.TabIndexedElement
14033 *
14034 * @constructor
14035 * @param {Object} [config] Configuration options
14036 * @cfg {string} [name=''] The value of the input’s HTML `name` attribute.
14037 * @cfg {string} [value=''] The value of the input.
14038 * @cfg {Function} [inputFilter] The name of an input filter function. Input filters modify the value of an input
14039 * before it is accepted.
14040 */
14041 OO.ui.InputWidget = function OoUiInputWidget( config ) {
14042 // Configuration initialization
14043 config = config || {};
14044
14045 // Parent constructor
14046 OO.ui.InputWidget.parent.call( this, config );
14047
14048 // Properties
14049 this.$input = this.getInputElement( config );
14050 this.value = '';
14051 this.inputFilter = config.inputFilter;
14052
14053 // Mixin constructors
14054 OO.ui.mixin.FlaggedElement.call( this, config );
14055 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$input } ) );
14056
14057 // Events
14058 this.$input.on( 'keydown mouseup cut paste change input select', this.onEdit.bind( this ) );
14059
14060 // Initialization
14061 this.$input
14062 .addClass( 'oo-ui-inputWidget-input' )
14063 .attr( 'name', config.name )
14064 .prop( 'disabled', this.isDisabled() );
14065 this.$element
14066 .addClass( 'oo-ui-inputWidget' )
14067 .append( this.$input );
14068 this.setValue( config.value );
14069 };
14070
14071 /* Setup */
14072
14073 OO.inheritClass( OO.ui.InputWidget, OO.ui.Widget );
14074 OO.mixinClass( OO.ui.InputWidget, OO.ui.mixin.FlaggedElement );
14075 OO.mixinClass( OO.ui.InputWidget, OO.ui.mixin.TabIndexedElement );
14076
14077 /* Static Properties */
14078
14079 OO.ui.InputWidget.static.supportsSimpleLabel = true;
14080
14081 /* Events */
14082
14083 /**
14084 * @event change
14085 *
14086 * A change event is emitted when the value of the input changes.
14087 *
14088 * @param {string} value
14089 */
14090
14091 /* Methods */
14092
14093 /**
14094 * Get input element.
14095 *
14096 * Subclasses of OO.ui.InputWidget use the `config` parameter to produce different elements in
14097 * different circumstances. The element must have a `value` property (like form elements).
14098 *
14099 * @protected
14100 * @param {Object} config Configuration options
14101 * @return {jQuery} Input element
14102 */
14103 OO.ui.InputWidget.prototype.getInputElement = function () {
14104 return $( '<input>' );
14105 };
14106
14107 /**
14108 * Handle potentially value-changing events.
14109 *
14110 * @private
14111 * @param {jQuery.Event} e Key down, mouse up, cut, paste, change, input, or select event
14112 */
14113 OO.ui.InputWidget.prototype.onEdit = function () {
14114 var widget = this;
14115 if ( !this.isDisabled() ) {
14116 // Allow the stack to clear so the value will be updated
14117 setTimeout( function () {
14118 widget.setValue( widget.$input.val() );
14119 } );
14120 }
14121 };
14122
14123 /**
14124 * Get the value of the input.
14125 *
14126 * @return {string} Input value
14127 */
14128 OO.ui.InputWidget.prototype.getValue = function () {
14129 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
14130 // it, and we won't know unless they're kind enough to trigger a 'change' event.
14131 var value = this.$input.val();
14132 if ( this.value !== value ) {
14133 this.setValue( value );
14134 }
14135 return this.value;
14136 };
14137
14138 /**
14139 * Set the direction of the input, either RTL (right-to-left) or LTR (left-to-right).
14140 *
14141 * @param {boolean} isRTL
14142 * Direction is right-to-left
14143 */
14144 OO.ui.InputWidget.prototype.setRTL = function ( isRTL ) {
14145 this.$input.prop( 'dir', isRTL ? 'rtl' : 'ltr' );
14146 };
14147
14148 /**
14149 * Set the value of the input.
14150 *
14151 * @param {string} value New value
14152 * @fires change
14153 * @chainable
14154 */
14155 OO.ui.InputWidget.prototype.setValue = function ( value ) {
14156 value = this.cleanUpValue( value );
14157 // Update the DOM if it has changed. Note that with cleanUpValue, it
14158 // is possible for the DOM value to change without this.value changing.
14159 if ( this.$input.val() !== value ) {
14160 this.$input.val( value );
14161 }
14162 if ( this.value !== value ) {
14163 this.value = value;
14164 this.emit( 'change', this.value );
14165 }
14166 return this;
14167 };
14168
14169 /**
14170 * Clean up incoming value.
14171 *
14172 * Ensures value is a string, and converts undefined and null to empty string.
14173 *
14174 * @private
14175 * @param {string} value Original value
14176 * @return {string} Cleaned up value
14177 */
14178 OO.ui.InputWidget.prototype.cleanUpValue = function ( value ) {
14179 if ( value === undefined || value === null ) {
14180 return '';
14181 } else if ( this.inputFilter ) {
14182 return this.inputFilter( String( value ) );
14183 } else {
14184 return String( value );
14185 }
14186 };
14187
14188 /**
14189 * Simulate the behavior of clicking on a label bound to this input. This method is only called by
14190 * {@link OO.ui.LabelWidget LabelWidget} and {@link OO.ui.FieldLayout FieldLayout}. It should not be
14191 * called directly.
14192 */
14193 OO.ui.InputWidget.prototype.simulateLabelClick = function () {
14194 if ( !this.isDisabled() ) {
14195 if ( this.$input.is( ':checkbox, :radio' ) ) {
14196 this.$input.click();
14197 }
14198 if ( this.$input.is( ':input' ) ) {
14199 this.$input[ 0 ].focus();
14200 }
14201 }
14202 };
14203
14204 /**
14205 * @inheritdoc
14206 */
14207 OO.ui.InputWidget.prototype.setDisabled = function ( state ) {
14208 OO.ui.InputWidget.parent.prototype.setDisabled.call( this, state );
14209 if ( this.$input ) {
14210 this.$input.prop( 'disabled', this.isDisabled() );
14211 }
14212 return this;
14213 };
14214
14215 /**
14216 * Focus the input.
14217 *
14218 * @chainable
14219 */
14220 OO.ui.InputWidget.prototype.focus = function () {
14221 this.$input[ 0 ].focus();
14222 return this;
14223 };
14224
14225 /**
14226 * Blur the input.
14227 *
14228 * @chainable
14229 */
14230 OO.ui.InputWidget.prototype.blur = function () {
14231 this.$input[ 0 ].blur();
14232 return this;
14233 };
14234
14235 /**
14236 * @inheritdoc
14237 */
14238 OO.ui.InputWidget.prototype.gatherPreInfuseState = function ( node ) {
14239 var
14240 state = OO.ui.InputWidget.parent.prototype.gatherPreInfuseState.call( this, node ),
14241 $input = state.$input || $( node ).find( '.oo-ui-inputWidget-input' );
14242 state.value = $input.val();
14243 // Might be better in TabIndexedElement, but it's awkward to do there because mixins are awkward
14244 state.focus = $input.is( ':focus' );
14245 return state;
14246 };
14247
14248 /**
14249 * @inheritdoc
14250 */
14251 OO.ui.InputWidget.prototype.restorePreInfuseState = function ( state ) {
14252 OO.ui.InputWidget.parent.prototype.restorePreInfuseState.call( this, state );
14253 if ( state.value !== undefined && state.value !== this.getValue() ) {
14254 this.setValue( state.value );
14255 }
14256 if ( state.focus ) {
14257 this.focus();
14258 }
14259 };
14260
14261 /**
14262 * ButtonInputWidget is used to submit HTML forms and is intended to be used within
14263 * a OO.ui.FormLayout. If you do not need the button to work with HTML forms, you probably
14264 * want to use OO.ui.ButtonWidget instead. Button input widgets can be rendered as either an
14265 * HTML `<button/>` (the default) or an HTML `<input/>` tags. See the
14266 * [OOjs UI documentation on MediaWiki] [1] for more information.
14267 *
14268 * @example
14269 * // A ButtonInputWidget rendered as an HTML button, the default.
14270 * var button = new OO.ui.ButtonInputWidget( {
14271 * label: 'Input button',
14272 * icon: 'check',
14273 * value: 'check'
14274 * } );
14275 * $( 'body' ).append( button.$element );
14276 *
14277 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs#Button_inputs
14278 *
14279 * @class
14280 * @extends OO.ui.InputWidget
14281 * @mixins OO.ui.mixin.ButtonElement
14282 * @mixins OO.ui.mixin.IconElement
14283 * @mixins OO.ui.mixin.IndicatorElement
14284 * @mixins OO.ui.mixin.LabelElement
14285 * @mixins OO.ui.mixin.TitledElement
14286 *
14287 * @constructor
14288 * @param {Object} [config] Configuration options
14289 * @cfg {string} [type='button'] The value of the HTML `'type'` attribute: 'button', 'submit' or 'reset'.
14290 * @cfg {boolean} [useInputTag=false] Use an `<input/>` tag instead of a `<button/>` tag, the default.
14291 * Widgets configured to be an `<input/>` do not support {@link #icon icons} and {@link #indicator indicators},
14292 * non-plaintext {@link #label labels}, or {@link #value values}. In general, useInputTag should only
14293 * be set to `true` when there’s need to support IE6 in a form with multiple buttons.
14294 */
14295 OO.ui.ButtonInputWidget = function OoUiButtonInputWidget( config ) {
14296 // Configuration initialization
14297 config = $.extend( { type: 'button', useInputTag: false }, config );
14298
14299 // Properties (must be set before parent constructor, which calls #setValue)
14300 this.useInputTag = config.useInputTag;
14301
14302 // Parent constructor
14303 OO.ui.ButtonInputWidget.parent.call( this, config );
14304
14305 // Mixin constructors
14306 OO.ui.mixin.ButtonElement.call( this, $.extend( {}, config, { $button: this.$input } ) );
14307 OO.ui.mixin.IconElement.call( this, config );
14308 OO.ui.mixin.IndicatorElement.call( this, config );
14309 OO.ui.mixin.LabelElement.call( this, config );
14310 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$input } ) );
14311
14312 // Initialization
14313 if ( !config.useInputTag ) {
14314 this.$input.append( this.$icon, this.$label, this.$indicator );
14315 }
14316 this.$element.addClass( 'oo-ui-buttonInputWidget' );
14317 };
14318
14319 /* Setup */
14320
14321 OO.inheritClass( OO.ui.ButtonInputWidget, OO.ui.InputWidget );
14322 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.ButtonElement );
14323 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.IconElement );
14324 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.IndicatorElement );
14325 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.LabelElement );
14326 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.TitledElement );
14327
14328 /* Static Properties */
14329
14330 /**
14331 * Disable generating `<label>` elements for buttons. One would very rarely need additional label
14332 * for a button, and it's already a big clickable target, and it causes unexpected rendering.
14333 */
14334 OO.ui.ButtonInputWidget.static.supportsSimpleLabel = false;
14335
14336 /* Methods */
14337
14338 /**
14339 * @inheritdoc
14340 * @protected
14341 */
14342 OO.ui.ButtonInputWidget.prototype.getInputElement = function ( config ) {
14343 var type = [ 'button', 'submit', 'reset' ].indexOf( config.type ) !== -1 ?
14344 config.type :
14345 'button';
14346 return $( '<' + ( config.useInputTag ? 'input' : 'button' ) + ' type="' + type + '">' );
14347 };
14348
14349 /**
14350 * Set label value.
14351 *
14352 * If #useInputTag is `true`, the label is set as the `value` of the `<input/>` tag.
14353 *
14354 * @param {jQuery|string|Function|null} label Label nodes, text, a function that returns nodes or
14355 * text, or `null` for no label
14356 * @chainable
14357 */
14358 OO.ui.ButtonInputWidget.prototype.setLabel = function ( label ) {
14359 OO.ui.mixin.LabelElement.prototype.setLabel.call( this, label );
14360
14361 if ( this.useInputTag ) {
14362 if ( typeof label === 'function' ) {
14363 label = OO.ui.resolveMsg( label );
14364 }
14365 if ( label instanceof jQuery ) {
14366 label = label.text();
14367 }
14368 if ( !label ) {
14369 label = '';
14370 }
14371 this.$input.val( label );
14372 }
14373
14374 return this;
14375 };
14376
14377 /**
14378 * Set the value of the input.
14379 *
14380 * This method is disabled for button inputs configured as {@link #useInputTag <input/> tags}, as
14381 * they do not support {@link #value values}.
14382 *
14383 * @param {string} value New value
14384 * @chainable
14385 */
14386 OO.ui.ButtonInputWidget.prototype.setValue = function ( value ) {
14387 if ( !this.useInputTag ) {
14388 OO.ui.ButtonInputWidget.parent.prototype.setValue.call( this, value );
14389 }
14390 return this;
14391 };
14392
14393 /**
14394 * CheckboxInputWidgets, like HTML checkboxes, can be selected and/or configured with a value.
14395 * Note that these {@link OO.ui.InputWidget input widgets} are best laid out
14396 * in {@link OO.ui.FieldLayout field layouts} that use the {@link OO.ui.FieldLayout#align inline}
14397 * alignment. For more information, please see the [OOjs UI documentation on MediaWiki][1].
14398 *
14399 * This widget can be used inside a HTML form, such as a OO.ui.FormLayout.
14400 *
14401 * @example
14402 * // An example of selected, unselected, and disabled checkbox inputs
14403 * var checkbox1=new OO.ui.CheckboxInputWidget( {
14404 * value: 'a',
14405 * selected: true
14406 * } );
14407 * var checkbox2=new OO.ui.CheckboxInputWidget( {
14408 * value: 'b'
14409 * } );
14410 * var checkbox3=new OO.ui.CheckboxInputWidget( {
14411 * value:'c',
14412 * disabled: true
14413 * } );
14414 * // Create a fieldset layout with fields for each checkbox.
14415 * var fieldset = new OO.ui.FieldsetLayout( {
14416 * label: 'Checkboxes'
14417 * } );
14418 * fieldset.addItems( [
14419 * new OO.ui.FieldLayout( checkbox1, { label: 'Selected checkbox', align: 'inline' } ),
14420 * new OO.ui.FieldLayout( checkbox2, { label: 'Unselected checkbox', align: 'inline' } ),
14421 * new OO.ui.FieldLayout( checkbox3, { label: 'Disabled checkbox', align: 'inline' } ),
14422 * ] );
14423 * $( 'body' ).append( fieldset.$element );
14424 *
14425 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
14426 *
14427 * @class
14428 * @extends OO.ui.InputWidget
14429 *
14430 * @constructor
14431 * @param {Object} [config] Configuration options
14432 * @cfg {boolean} [selected=false] Select the checkbox initially. By default, the checkbox is not selected.
14433 */
14434 OO.ui.CheckboxInputWidget = function OoUiCheckboxInputWidget( config ) {
14435 // Configuration initialization
14436 config = config || {};
14437
14438 // Parent constructor
14439 OO.ui.CheckboxInputWidget.parent.call( this, config );
14440
14441 // Initialization
14442 this.$element
14443 .addClass( 'oo-ui-checkboxInputWidget' )
14444 // Required for pretty styling in MediaWiki theme
14445 .append( $( '<span>' ) );
14446 this.setSelected( config.selected !== undefined ? config.selected : false );
14447 };
14448
14449 /* Setup */
14450
14451 OO.inheritClass( OO.ui.CheckboxInputWidget, OO.ui.InputWidget );
14452
14453 /* Methods */
14454
14455 /**
14456 * @inheritdoc
14457 * @protected
14458 */
14459 OO.ui.CheckboxInputWidget.prototype.getInputElement = function () {
14460 return $( '<input type="checkbox" />' );
14461 };
14462
14463 /**
14464 * @inheritdoc
14465 */
14466 OO.ui.CheckboxInputWidget.prototype.onEdit = function () {
14467 var widget = this;
14468 if ( !this.isDisabled() ) {
14469 // Allow the stack to clear so the value will be updated
14470 setTimeout( function () {
14471 widget.setSelected( widget.$input.prop( 'checked' ) );
14472 } );
14473 }
14474 };
14475
14476 /**
14477 * Set selection state of this checkbox.
14478 *
14479 * @param {boolean} state `true` for selected
14480 * @chainable
14481 */
14482 OO.ui.CheckboxInputWidget.prototype.setSelected = function ( state ) {
14483 state = !!state;
14484 if ( this.selected !== state ) {
14485 this.selected = state;
14486 this.$input.prop( 'checked', this.selected );
14487 this.emit( 'change', this.selected );
14488 }
14489 return this;
14490 };
14491
14492 /**
14493 * Check if this checkbox is selected.
14494 *
14495 * @return {boolean} Checkbox is selected
14496 */
14497 OO.ui.CheckboxInputWidget.prototype.isSelected = function () {
14498 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
14499 // it, and we won't know unless they're kind enough to trigger a 'change' event.
14500 var selected = this.$input.prop( 'checked' );
14501 if ( this.selected !== selected ) {
14502 this.setSelected( selected );
14503 }
14504 return this.selected;
14505 };
14506
14507 /**
14508 * @inheritdoc
14509 */
14510 OO.ui.CheckboxInputWidget.prototype.gatherPreInfuseState = function ( node ) {
14511 var
14512 state = OO.ui.CheckboxInputWidget.parent.prototype.gatherPreInfuseState.call( this, node ),
14513 $input = $( node ).find( '.oo-ui-inputWidget-input' );
14514 state.$input = $input; // shortcut for performance, used in InputWidget
14515 state.checked = $input.prop( 'checked' );
14516 return state;
14517 };
14518
14519 /**
14520 * @inheritdoc
14521 */
14522 OO.ui.CheckboxInputWidget.prototype.restorePreInfuseState = function ( state ) {
14523 OO.ui.CheckboxInputWidget.parent.prototype.restorePreInfuseState.call( this, state );
14524 if ( state.checked !== undefined && state.checked !== this.isSelected() ) {
14525 this.setSelected( state.checked );
14526 }
14527 };
14528
14529 /**
14530 * DropdownInputWidget is a {@link OO.ui.DropdownWidget DropdownWidget} intended to be used
14531 * within a HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with the value
14532 * of a hidden HTML `input` tag. Please see the [OOjs UI documentation on MediaWiki][1] for
14533 * more information about input widgets.
14534 *
14535 * A DropdownInputWidget always has a value (one of the options is always selected), unless there
14536 * are no options. If no `value` configuration option is provided, the first option is selected.
14537 * If you need a state representing no value (no option being selected), use a DropdownWidget.
14538 *
14539 * This and OO.ui.RadioSelectInputWidget support the same configuration options.
14540 *
14541 * @example
14542 * // Example: A DropdownInputWidget with three options
14543 * var dropdownInput = new OO.ui.DropdownInputWidget( {
14544 * options: [
14545 * { data: 'a', label: 'First' },
14546 * { data: 'b', label: 'Second'},
14547 * { data: 'c', label: 'Third' }
14548 * ]
14549 * } );
14550 * $( 'body' ).append( dropdownInput.$element );
14551 *
14552 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
14553 *
14554 * @class
14555 * @extends OO.ui.InputWidget
14556 * @mixins OO.ui.mixin.TitledElement
14557 *
14558 * @constructor
14559 * @param {Object} [config] Configuration options
14560 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
14561 */
14562 OO.ui.DropdownInputWidget = function OoUiDropdownInputWidget( config ) {
14563 // Configuration initialization
14564 config = config || {};
14565
14566 // Properties (must be done before parent constructor which calls #setDisabled)
14567 this.dropdownWidget = new OO.ui.DropdownWidget();
14568
14569 // Parent constructor
14570 OO.ui.DropdownInputWidget.parent.call( this, config );
14571
14572 // Mixin constructors
14573 OO.ui.mixin.TitledElement.call( this, config );
14574
14575 // Events
14576 this.dropdownWidget.getMenu().connect( this, { select: 'onMenuSelect' } );
14577
14578 // Initialization
14579 this.setOptions( config.options || [] );
14580 this.$element
14581 .addClass( 'oo-ui-dropdownInputWidget' )
14582 .append( this.dropdownWidget.$element );
14583 };
14584
14585 /* Setup */
14586
14587 OO.inheritClass( OO.ui.DropdownInputWidget, OO.ui.InputWidget );
14588 OO.mixinClass( OO.ui.DropdownInputWidget, OO.ui.mixin.TitledElement );
14589
14590 /* Methods */
14591
14592 /**
14593 * @inheritdoc
14594 * @protected
14595 */
14596 OO.ui.DropdownInputWidget.prototype.getInputElement = function () {
14597 return $( '<input type="hidden">' );
14598 };
14599
14600 /**
14601 * Handles menu select events.
14602 *
14603 * @private
14604 * @param {OO.ui.MenuOptionWidget} item Selected menu item
14605 */
14606 OO.ui.DropdownInputWidget.prototype.onMenuSelect = function ( item ) {
14607 this.setValue( item.getData() );
14608 };
14609
14610 /**
14611 * @inheritdoc
14612 */
14613 OO.ui.DropdownInputWidget.prototype.setValue = function ( value ) {
14614 value = this.cleanUpValue( value );
14615 this.dropdownWidget.getMenu().selectItemByData( value );
14616 OO.ui.DropdownInputWidget.parent.prototype.setValue.call( this, value );
14617 return this;
14618 };
14619
14620 /**
14621 * @inheritdoc
14622 */
14623 OO.ui.DropdownInputWidget.prototype.setDisabled = function ( state ) {
14624 this.dropdownWidget.setDisabled( state );
14625 OO.ui.DropdownInputWidget.parent.prototype.setDisabled.call( this, state );
14626 return this;
14627 };
14628
14629 /**
14630 * Set the options available for this input.
14631 *
14632 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
14633 * @chainable
14634 */
14635 OO.ui.DropdownInputWidget.prototype.setOptions = function ( options ) {
14636 var
14637 value = this.getValue(),
14638 widget = this;
14639
14640 // Rebuild the dropdown menu
14641 this.dropdownWidget.getMenu()
14642 .clearItems()
14643 .addItems( options.map( function ( opt ) {
14644 var optValue = widget.cleanUpValue( opt.data );
14645 return new OO.ui.MenuOptionWidget( {
14646 data: optValue,
14647 label: opt.label !== undefined ? opt.label : optValue
14648 } );
14649 } ) );
14650
14651 // Restore the previous value, or reset to something sensible
14652 if ( this.dropdownWidget.getMenu().getItemFromData( value ) ) {
14653 // Previous value is still available, ensure consistency with the dropdown
14654 this.setValue( value );
14655 } else {
14656 // No longer valid, reset
14657 if ( options.length ) {
14658 this.setValue( options[ 0 ].data );
14659 }
14660 }
14661
14662 return this;
14663 };
14664
14665 /**
14666 * @inheritdoc
14667 */
14668 OO.ui.DropdownInputWidget.prototype.focus = function () {
14669 this.dropdownWidget.getMenu().toggle( true );
14670 return this;
14671 };
14672
14673 /**
14674 * @inheritdoc
14675 */
14676 OO.ui.DropdownInputWidget.prototype.blur = function () {
14677 this.dropdownWidget.getMenu().toggle( false );
14678 return this;
14679 };
14680
14681 /**
14682 * RadioInputWidget creates a single radio button. Because radio buttons are usually used as a set,
14683 * in most cases you will want to use a {@link OO.ui.RadioSelectWidget radio select}
14684 * with {@link OO.ui.RadioOptionWidget radio options} instead of this class. For more information,
14685 * please see the [OOjs UI documentation on MediaWiki][1].
14686 *
14687 * This widget can be used inside a HTML form, such as a OO.ui.FormLayout.
14688 *
14689 * @example
14690 * // An example of selected, unselected, and disabled radio inputs
14691 * var radio1 = new OO.ui.RadioInputWidget( {
14692 * value: 'a',
14693 * selected: true
14694 * } );
14695 * var radio2 = new OO.ui.RadioInputWidget( {
14696 * value: 'b'
14697 * } );
14698 * var radio3 = new OO.ui.RadioInputWidget( {
14699 * value: 'c',
14700 * disabled: true
14701 * } );
14702 * // Create a fieldset layout with fields for each radio button.
14703 * var fieldset = new OO.ui.FieldsetLayout( {
14704 * label: 'Radio inputs'
14705 * } );
14706 * fieldset.addItems( [
14707 * new OO.ui.FieldLayout( radio1, { label: 'Selected', align: 'inline' } ),
14708 * new OO.ui.FieldLayout( radio2, { label: 'Unselected', align: 'inline' } ),
14709 * new OO.ui.FieldLayout( radio3, { label: 'Disabled', align: 'inline' } ),
14710 * ] );
14711 * $( 'body' ).append( fieldset.$element );
14712 *
14713 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
14714 *
14715 * @class
14716 * @extends OO.ui.InputWidget
14717 *
14718 * @constructor
14719 * @param {Object} [config] Configuration options
14720 * @cfg {boolean} [selected=false] Select the radio button initially. By default, the radio button is not selected.
14721 */
14722 OO.ui.RadioInputWidget = function OoUiRadioInputWidget( config ) {
14723 // Configuration initialization
14724 config = config || {};
14725
14726 // Parent constructor
14727 OO.ui.RadioInputWidget.parent.call( this, config );
14728
14729 // Initialization
14730 this.$element
14731 .addClass( 'oo-ui-radioInputWidget' )
14732 // Required for pretty styling in MediaWiki theme
14733 .append( $( '<span>' ) );
14734 this.setSelected( config.selected !== undefined ? config.selected : false );
14735 };
14736
14737 /* Setup */
14738
14739 OO.inheritClass( OO.ui.RadioInputWidget, OO.ui.InputWidget );
14740
14741 /* Methods */
14742
14743 /**
14744 * @inheritdoc
14745 * @protected
14746 */
14747 OO.ui.RadioInputWidget.prototype.getInputElement = function () {
14748 return $( '<input type="radio" />' );
14749 };
14750
14751 /**
14752 * @inheritdoc
14753 */
14754 OO.ui.RadioInputWidget.prototype.onEdit = function () {
14755 // RadioInputWidget doesn't track its state.
14756 };
14757
14758 /**
14759 * Set selection state of this radio button.
14760 *
14761 * @param {boolean} state `true` for selected
14762 * @chainable
14763 */
14764 OO.ui.RadioInputWidget.prototype.setSelected = function ( state ) {
14765 // RadioInputWidget doesn't track its state.
14766 this.$input.prop( 'checked', state );
14767 return this;
14768 };
14769
14770 /**
14771 * Check if this radio button is selected.
14772 *
14773 * @return {boolean} Radio is selected
14774 */
14775 OO.ui.RadioInputWidget.prototype.isSelected = function () {
14776 return this.$input.prop( 'checked' );
14777 };
14778
14779 /**
14780 * @inheritdoc
14781 */
14782 OO.ui.RadioInputWidget.prototype.gatherPreInfuseState = function ( node ) {
14783 var
14784 state = OO.ui.RadioInputWidget.parent.prototype.gatherPreInfuseState.call( this, node ),
14785 $input = $( node ).find( '.oo-ui-inputWidget-input' );
14786 state.$input = $input; // shortcut for performance, used in InputWidget
14787 state.checked = $input.prop( 'checked' );
14788 return state;
14789 };
14790
14791 /**
14792 * @inheritdoc
14793 */
14794 OO.ui.RadioInputWidget.prototype.restorePreInfuseState = function ( state ) {
14795 OO.ui.RadioInputWidget.parent.prototype.restorePreInfuseState.call( this, state );
14796 if ( state.checked !== undefined && state.checked !== this.isSelected() ) {
14797 this.setSelected( state.checked );
14798 }
14799 };
14800
14801 /**
14802 * RadioSelectInputWidget is a {@link OO.ui.RadioSelectWidget RadioSelectWidget} intended to be used
14803 * within a HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with the value
14804 * of a hidden HTML `input` tag. Please see the [OOjs UI documentation on MediaWiki][1] for
14805 * more information about input widgets.
14806 *
14807 * This and OO.ui.DropdownInputWidget support the same configuration options.
14808 *
14809 * @example
14810 * // Example: A RadioSelectInputWidget with three options
14811 * var radioSelectInput = new OO.ui.RadioSelectInputWidget( {
14812 * options: [
14813 * { data: 'a', label: 'First' },
14814 * { data: 'b', label: 'Second'},
14815 * { data: 'c', label: 'Third' }
14816 * ]
14817 * } );
14818 * $( 'body' ).append( radioSelectInput.$element );
14819 *
14820 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
14821 *
14822 * @class
14823 * @extends OO.ui.InputWidget
14824 *
14825 * @constructor
14826 * @param {Object} [config] Configuration options
14827 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
14828 */
14829 OO.ui.RadioSelectInputWidget = function OoUiRadioSelectInputWidget( config ) {
14830 // Configuration initialization
14831 config = config || {};
14832
14833 // Properties (must be done before parent constructor which calls #setDisabled)
14834 this.radioSelectWidget = new OO.ui.RadioSelectWidget();
14835
14836 // Parent constructor
14837 OO.ui.RadioSelectInputWidget.parent.call( this, config );
14838
14839 // Events
14840 this.radioSelectWidget.connect( this, { select: 'onMenuSelect' } );
14841
14842 // Initialization
14843 this.setOptions( config.options || [] );
14844 this.$element
14845 .addClass( 'oo-ui-radioSelectInputWidget' )
14846 .append( this.radioSelectWidget.$element );
14847 };
14848
14849 /* Setup */
14850
14851 OO.inheritClass( OO.ui.RadioSelectInputWidget, OO.ui.InputWidget );
14852
14853 /* Static Properties */
14854
14855 OO.ui.RadioSelectInputWidget.static.supportsSimpleLabel = false;
14856
14857 /* Methods */
14858
14859 /**
14860 * @inheritdoc
14861 * @protected
14862 */
14863 OO.ui.RadioSelectInputWidget.prototype.getInputElement = function () {
14864 return $( '<input type="hidden">' );
14865 };
14866
14867 /**
14868 * Handles menu select events.
14869 *
14870 * @private
14871 * @param {OO.ui.RadioOptionWidget} item Selected menu item
14872 */
14873 OO.ui.RadioSelectInputWidget.prototype.onMenuSelect = function ( item ) {
14874 this.setValue( item.getData() );
14875 };
14876
14877 /**
14878 * @inheritdoc
14879 */
14880 OO.ui.RadioSelectInputWidget.prototype.setValue = function ( value ) {
14881 value = this.cleanUpValue( value );
14882 this.radioSelectWidget.selectItemByData( value );
14883 OO.ui.RadioSelectInputWidget.parent.prototype.setValue.call( this, value );
14884 return this;
14885 };
14886
14887 /**
14888 * @inheritdoc
14889 */
14890 OO.ui.RadioSelectInputWidget.prototype.setDisabled = function ( state ) {
14891 this.radioSelectWidget.setDisabled( state );
14892 OO.ui.RadioSelectInputWidget.parent.prototype.setDisabled.call( this, state );
14893 return this;
14894 };
14895
14896 /**
14897 * Set the options available for this input.
14898 *
14899 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
14900 * @chainable
14901 */
14902 OO.ui.RadioSelectInputWidget.prototype.setOptions = function ( options ) {
14903 var
14904 value = this.getValue(),
14905 widget = this;
14906
14907 // Rebuild the radioSelect menu
14908 this.radioSelectWidget
14909 .clearItems()
14910 .addItems( options.map( function ( opt ) {
14911 var optValue = widget.cleanUpValue( opt.data );
14912 return new OO.ui.RadioOptionWidget( {
14913 data: optValue,
14914 label: opt.label !== undefined ? opt.label : optValue
14915 } );
14916 } ) );
14917
14918 // Restore the previous value, or reset to something sensible
14919 if ( this.radioSelectWidget.getItemFromData( value ) ) {
14920 // Previous value is still available, ensure consistency with the radioSelect
14921 this.setValue( value );
14922 } else {
14923 // No longer valid, reset
14924 if ( options.length ) {
14925 this.setValue( options[ 0 ].data );
14926 }
14927 }
14928
14929 return this;
14930 };
14931
14932 /**
14933 * @inheritdoc
14934 */
14935 OO.ui.RadioSelectInputWidget.prototype.gatherPreInfuseState = function ( node ) {
14936 var state = OO.ui.RadioSelectInputWidget.parent.prototype.gatherPreInfuseState.call( this, node );
14937 state.value = $( node ).find( '.oo-ui-radioInputWidget .oo-ui-inputWidget-input:checked' ).val();
14938 return state;
14939 };
14940
14941 /**
14942 * TextInputWidgets, like HTML text inputs, can be configured with options that customize the
14943 * size of the field as well as its presentation. In addition, these widgets can be configured
14944 * with {@link OO.ui.mixin.IconElement icons}, {@link OO.ui.mixin.IndicatorElement indicators}, an optional
14945 * validation-pattern (used to determine if an input value is valid or not) and an input filter,
14946 * which modifies incoming values rather than validating them.
14947 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
14948 *
14949 * This widget can be used inside a HTML form, such as a OO.ui.FormLayout.
14950 *
14951 * @example
14952 * // Example of a text input widget
14953 * var textInput = new OO.ui.TextInputWidget( {
14954 * value: 'Text input'
14955 * } )
14956 * $( 'body' ).append( textInput.$element );
14957 *
14958 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
14959 *
14960 * @class
14961 * @extends OO.ui.InputWidget
14962 * @mixins OO.ui.mixin.IconElement
14963 * @mixins OO.ui.mixin.IndicatorElement
14964 * @mixins OO.ui.mixin.PendingElement
14965 * @mixins OO.ui.mixin.LabelElement
14966 *
14967 * @constructor
14968 * @param {Object} [config] Configuration options
14969 * @cfg {string} [type='text'] The value of the HTML `type` attribute: 'text', 'password', 'search',
14970 * 'email' or 'url'. Ignored if `multiline` is true.
14971 *
14972 * Some values of `type` result in additional behaviors:
14973 *
14974 * - `search`: implies `icon: 'search'` and `indicator: 'clear'`; when clicked, the indicator
14975 * empties the text field
14976 * @cfg {string} [placeholder] Placeholder text
14977 * @cfg {boolean} [autofocus=false] Use an HTML `autofocus` attribute to
14978 * instruct the browser to focus this widget.
14979 * @cfg {boolean} [readOnly=false] Prevent changes to the value of the text input.
14980 * @cfg {number} [maxLength] Maximum number of characters allowed in the input.
14981 * @cfg {boolean} [multiline=false] Allow multiple lines of text
14982 * @cfg {number} [rows] If multiline, number of visible lines in textarea. If used with `autosize`,
14983 * specifies minimum number of rows to display.
14984 * @cfg {boolean} [autosize=false] Automatically resize the text input to fit its content.
14985 * Use the #maxRows config to specify a maximum number of displayed rows.
14986 * @cfg {boolean} [maxRows] Maximum number of rows to display when #autosize is set to true.
14987 * Defaults to the maximum of `10` and `2 * rows`, or `10` if `rows` isn't provided.
14988 * @cfg {string} [labelPosition='after'] The position of the inline label relative to that of
14989 * the value or placeholder text: `'before'` or `'after'`
14990 * @cfg {boolean} [required=false] Mark the field as required. Implies `indicator: 'required'`.
14991 * @cfg {boolean} [autocomplete=true] Should the browser support autocomplete for this field
14992 * @cfg {RegExp|Function|string} [validate] Validation pattern: when string, a symbolic name of a
14993 * pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer'
14994 * (the value must contain only numbers); when RegExp, a regular expression that must match the
14995 * value for it to be considered valid; when Function, a function receiving the value as parameter
14996 * that must return true, or promise resolving to true, for it to be considered valid.
14997 */
14998 OO.ui.TextInputWidget = function OoUiTextInputWidget( config ) {
14999 // Configuration initialization
15000 config = $.extend( {
15001 type: 'text',
15002 labelPosition: 'after'
15003 }, config );
15004 if ( config.type === 'search' ) {
15005 if ( config.icon === undefined ) {
15006 config.icon = 'search';
15007 }
15008 // indicator: 'clear' is set dynamically later, depending on value
15009 }
15010 if ( config.required ) {
15011 if ( config.indicator === undefined ) {
15012 config.indicator = 'required';
15013 }
15014 }
15015
15016 // Parent constructor
15017 OO.ui.TextInputWidget.parent.call( this, config );
15018
15019 // Mixin constructors
15020 OO.ui.mixin.IconElement.call( this, config );
15021 OO.ui.mixin.IndicatorElement.call( this, config );
15022 OO.ui.mixin.PendingElement.call( this, $.extend( {}, config, { $pending: this.$input } ) );
15023 OO.ui.mixin.LabelElement.call( this, config );
15024
15025 // Properties
15026 this.type = this.getSaneType( config );
15027 this.readOnly = false;
15028 this.multiline = !!config.multiline;
15029 this.autosize = !!config.autosize;
15030 this.minRows = config.rows !== undefined ? config.rows : '';
15031 this.maxRows = config.maxRows || Math.max( 2 * ( this.minRows || 0 ), 10 );
15032 this.validate = null;
15033
15034 // Clone for resizing
15035 if ( this.autosize ) {
15036 this.$clone = this.$input
15037 .clone()
15038 .insertAfter( this.$input )
15039 .attr( 'aria-hidden', 'true' )
15040 .addClass( 'oo-ui-element-hidden' );
15041 }
15042
15043 this.setValidation( config.validate );
15044 this.setLabelPosition( config.labelPosition );
15045
15046 // Events
15047 this.$input.on( {
15048 keypress: this.onKeyPress.bind( this ),
15049 blur: this.onBlur.bind( this )
15050 } );
15051 this.$input.one( {
15052 focus: this.onElementAttach.bind( this )
15053 } );
15054 this.$icon.on( 'mousedown', this.onIconMouseDown.bind( this ) );
15055 this.$indicator.on( 'mousedown', this.onIndicatorMouseDown.bind( this ) );
15056 this.on( 'labelChange', this.updatePosition.bind( this ) );
15057 this.connect( this, {
15058 change: 'onChange',
15059 disable: 'onDisable'
15060 } );
15061
15062 // Initialization
15063 this.$element
15064 .addClass( 'oo-ui-textInputWidget oo-ui-textInputWidget-type-' + this.type )
15065 .append( this.$icon, this.$indicator );
15066 this.setReadOnly( !!config.readOnly );
15067 this.updateSearchIndicator();
15068 if ( config.placeholder ) {
15069 this.$input.attr( 'placeholder', config.placeholder );
15070 }
15071 if ( config.maxLength !== undefined ) {
15072 this.$input.attr( 'maxlength', config.maxLength );
15073 }
15074 if ( config.autofocus ) {
15075 this.$input.attr( 'autofocus', 'autofocus' );
15076 }
15077 if ( config.required ) {
15078 this.$input.attr( 'required', 'required' );
15079 this.$input.attr( 'aria-required', 'true' );
15080 }
15081 if ( config.autocomplete === false ) {
15082 this.$input.attr( 'autocomplete', 'off' );
15083 }
15084 if ( this.multiline && config.rows ) {
15085 this.$input.attr( 'rows', config.rows );
15086 }
15087 if ( this.label || config.autosize ) {
15088 this.installParentChangeDetector();
15089 }
15090 };
15091
15092 /* Setup */
15093
15094 OO.inheritClass( OO.ui.TextInputWidget, OO.ui.InputWidget );
15095 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.mixin.IconElement );
15096 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.mixin.IndicatorElement );
15097 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.mixin.PendingElement );
15098 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.mixin.LabelElement );
15099
15100 /* Static Properties */
15101
15102 OO.ui.TextInputWidget.static.validationPatterns = {
15103 'non-empty': /.+/,
15104 integer: /^\d+$/
15105 };
15106
15107 /* Events */
15108
15109 /**
15110 * An `enter` event is emitted when the user presses 'enter' inside the text box.
15111 *
15112 * Not emitted if the input is multiline.
15113 *
15114 * @event enter
15115 */
15116
15117 /* Methods */
15118
15119 /**
15120 * Handle icon mouse down events.
15121 *
15122 * @private
15123 * @param {jQuery.Event} e Mouse down event
15124 * @fires icon
15125 */
15126 OO.ui.TextInputWidget.prototype.onIconMouseDown = function ( e ) {
15127 if ( e.which === 1 ) {
15128 this.$input[ 0 ].focus();
15129 return false;
15130 }
15131 };
15132
15133 /**
15134 * Handle indicator mouse down events.
15135 *
15136 * @private
15137 * @param {jQuery.Event} e Mouse down event
15138 * @fires indicator
15139 */
15140 OO.ui.TextInputWidget.prototype.onIndicatorMouseDown = function ( e ) {
15141 if ( e.which === 1 ) {
15142 if ( this.type === 'search' ) {
15143 // Clear the text field
15144 this.setValue( '' );
15145 }
15146 this.$input[ 0 ].focus();
15147 return false;
15148 }
15149 };
15150
15151 /**
15152 * Handle key press events.
15153 *
15154 * @private
15155 * @param {jQuery.Event} e Key press event
15156 * @fires enter If enter key is pressed and input is not multiline
15157 */
15158 OO.ui.TextInputWidget.prototype.onKeyPress = function ( e ) {
15159 if ( e.which === OO.ui.Keys.ENTER && !this.multiline ) {
15160 this.emit( 'enter', e );
15161 }
15162 };
15163
15164 /**
15165 * Handle blur events.
15166 *
15167 * @private
15168 * @param {jQuery.Event} e Blur event
15169 */
15170 OO.ui.TextInputWidget.prototype.onBlur = function () {
15171 this.setValidityFlag();
15172 };
15173
15174 /**
15175 * Handle element attach events.
15176 *
15177 * @private
15178 * @param {jQuery.Event} e Element attach event
15179 */
15180 OO.ui.TextInputWidget.prototype.onElementAttach = function () {
15181 // Any previously calculated size is now probably invalid if we reattached elsewhere
15182 this.valCache = null;
15183 this.adjustSize();
15184 this.positionLabel();
15185 };
15186
15187 /**
15188 * Handle change events.
15189 *
15190 * @param {string} value
15191 * @private
15192 */
15193 OO.ui.TextInputWidget.prototype.onChange = function () {
15194 this.updateSearchIndicator();
15195 this.setValidityFlag();
15196 this.adjustSize();
15197 };
15198
15199 /**
15200 * Handle disable events.
15201 *
15202 * @param {boolean} disabled Element is disabled
15203 * @private
15204 */
15205 OO.ui.TextInputWidget.prototype.onDisable = function () {
15206 this.updateSearchIndicator();
15207 };
15208
15209 /**
15210 * Check if the input is {@link #readOnly read-only}.
15211 *
15212 * @return {boolean}
15213 */
15214 OO.ui.TextInputWidget.prototype.isReadOnly = function () {
15215 return this.readOnly;
15216 };
15217
15218 /**
15219 * Set the {@link #readOnly read-only} state of the input.
15220 *
15221 * @param {boolean} state Make input read-only
15222 * @chainable
15223 */
15224 OO.ui.TextInputWidget.prototype.setReadOnly = function ( state ) {
15225 this.readOnly = !!state;
15226 this.$input.prop( 'readOnly', this.readOnly );
15227 this.updateSearchIndicator();
15228 return this;
15229 };
15230
15231 /**
15232 * Support function for making #onElementAttach work across browsers.
15233 *
15234 * This whole function could be replaced with one line of code using the DOMNodeInsertedIntoDocument
15235 * event, but it's not supported by Firefox and allegedly deprecated, so we only use it as fallback.
15236 *
15237 * Due to MutationObserver performance woes, #onElementAttach is only somewhat reliably called the
15238 * first time that the element gets attached to the documented.
15239 */
15240 OO.ui.TextInputWidget.prototype.installParentChangeDetector = function () {
15241 var mutationObserver, onRemove, topmostNode, fakeParentNode,
15242 MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver,
15243 widget = this;
15244
15245 if ( MutationObserver ) {
15246 // The new way. If only it wasn't so ugly.
15247
15248 if ( this.$element.closest( 'html' ).length ) {
15249 // Widget is attached already, do nothing. This breaks the functionality of this function when
15250 // the widget is detached and reattached. Alas, doing this correctly with MutationObserver
15251 // would require observation of the whole document, which would hurt performance of other,
15252 // more important code.
15253 return;
15254 }
15255
15256 // Find topmost node in the tree
15257 topmostNode = this.$element[0];
15258 while ( topmostNode.parentNode ) {
15259 topmostNode = topmostNode.parentNode;
15260 }
15261
15262 // We have no way to detect the $element being attached somewhere without observing the entire
15263 // DOM with subtree modifications, which would hurt performance. So we cheat: we hook to the
15264 // parent node of $element, and instead detect when $element is removed from it (and thus
15265 // probably attached somewhere else). If there is no parent, we create a "fake" one. If it
15266 // doesn't get attached, we end up back here and create the parent.
15267
15268 mutationObserver = new MutationObserver( function ( mutations ) {
15269 var i, j, removedNodes;
15270 for ( i = 0; i < mutations.length; i++ ) {
15271 removedNodes = mutations[ i ].removedNodes;
15272 for ( j = 0; j < removedNodes.length; j++ ) {
15273 if ( removedNodes[ j ] === topmostNode ) {
15274 setTimeout( onRemove, 0 );
15275 return;
15276 }
15277 }
15278 }
15279 } );
15280
15281 onRemove = function () {
15282 // If the node was attached somewhere else, report it
15283 if ( widget.$element.closest( 'html' ).length ) {
15284 widget.onElementAttach();
15285 }
15286 mutationObserver.disconnect();
15287 widget.installParentChangeDetector();
15288 };
15289
15290 // Create a fake parent and observe it
15291 fakeParentNode = $( '<div>' ).append( topmostNode )[0];
15292 mutationObserver.observe( fakeParentNode, { childList: true } );
15293 } else {
15294 // Using the DOMNodeInsertedIntoDocument event is much nicer and less magical, and works for
15295 // detachment and reattachment, but it's not supported by Firefox and allegedly deprecated.
15296 this.$element.on( 'DOMNodeInsertedIntoDocument', this.onElementAttach.bind( this ) );
15297 }
15298 };
15299
15300 /**
15301 * Automatically adjust the size of the text input.
15302 *
15303 * This only affects #multiline inputs that are {@link #autosize autosized}.
15304 *
15305 * @chainable
15306 */
15307 OO.ui.TextInputWidget.prototype.adjustSize = function () {
15308 var scrollHeight, innerHeight, outerHeight, maxInnerHeight, measurementError, idealHeight;
15309
15310 if ( this.multiline && this.autosize && this.$input.val() !== this.valCache ) {
15311 this.$clone
15312 .val( this.$input.val() )
15313 .attr( 'rows', this.minRows )
15314 // Set inline height property to 0 to measure scroll height
15315 .css( 'height', 0 );
15316
15317 this.$clone.removeClass( 'oo-ui-element-hidden' );
15318
15319 this.valCache = this.$input.val();
15320
15321 scrollHeight = this.$clone[ 0 ].scrollHeight;
15322
15323 // Remove inline height property to measure natural heights
15324 this.$clone.css( 'height', '' );
15325 innerHeight = this.$clone.innerHeight();
15326 outerHeight = this.$clone.outerHeight();
15327
15328 // Measure max rows height
15329 this.$clone
15330 .attr( 'rows', this.maxRows )
15331 .css( 'height', 'auto' )
15332 .val( '' );
15333 maxInnerHeight = this.$clone.innerHeight();
15334
15335 // Difference between reported innerHeight and scrollHeight with no scrollbars present
15336 // Equals 1 on Blink-based browsers and 0 everywhere else
15337 measurementError = maxInnerHeight - this.$clone[ 0 ].scrollHeight;
15338 idealHeight = Math.min( maxInnerHeight, scrollHeight + measurementError );
15339
15340 this.$clone.addClass( 'oo-ui-element-hidden' );
15341
15342 // Only apply inline height when expansion beyond natural height is needed
15343 if ( idealHeight > innerHeight ) {
15344 // Use the difference between the inner and outer height as a buffer
15345 this.$input.css( 'height', idealHeight + ( outerHeight - innerHeight ) );
15346 } else {
15347 this.$input.css( 'height', '' );
15348 }
15349 }
15350 return this;
15351 };
15352
15353 /**
15354 * @inheritdoc
15355 * @protected
15356 */
15357 OO.ui.TextInputWidget.prototype.getInputElement = function ( config ) {
15358 return config.multiline ?
15359 $( '<textarea>' ) :
15360 $( '<input type="' + this.getSaneType( config ) + '" />' );
15361 };
15362
15363 /**
15364 * Get sanitized value for 'type' for given config.
15365 *
15366 * @param {Object} config Configuration options
15367 * @return {string|null}
15368 * @private
15369 */
15370 OO.ui.TextInputWidget.prototype.getSaneType = function ( config ) {
15371 var type = [ 'text', 'password', 'search', 'email', 'url' ].indexOf( config.type ) !== -1 ?
15372 config.type :
15373 'text';
15374 return config.multiline ? 'multiline' : type;
15375 };
15376
15377 /**
15378 * Check if the input supports multiple lines.
15379 *
15380 * @return {boolean}
15381 */
15382 OO.ui.TextInputWidget.prototype.isMultiline = function () {
15383 return !!this.multiline;
15384 };
15385
15386 /**
15387 * Check if the input automatically adjusts its size.
15388 *
15389 * @return {boolean}
15390 */
15391 OO.ui.TextInputWidget.prototype.isAutosizing = function () {
15392 return !!this.autosize;
15393 };
15394
15395 /**
15396 * Select the entire text of the input.
15397 *
15398 * @chainable
15399 */
15400 OO.ui.TextInputWidget.prototype.select = function () {
15401 this.$input.select();
15402 return this;
15403 };
15404
15405 /**
15406 * Set the validation pattern.
15407 *
15408 * The validation pattern is either a regular expression, a function, or the symbolic name of a
15409 * pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer' (the
15410 * value must contain only numbers).
15411 *
15412 * @param {RegExp|Function|string|null} validate Regular expression, function, or the symbolic name
15413 * of a pattern (either ‘integer’ or ‘non-empty’) defined by the class.
15414 */
15415 OO.ui.TextInputWidget.prototype.setValidation = function ( validate ) {
15416 if ( validate instanceof RegExp || validate instanceof Function ) {
15417 this.validate = validate;
15418 } else {
15419 this.validate = this.constructor.static.validationPatterns[ validate ] || /.*/;
15420 }
15421 };
15422
15423 /**
15424 * Sets the 'invalid' flag appropriately.
15425 *
15426 * @param {boolean} [isValid] Optionally override validation result
15427 */
15428 OO.ui.TextInputWidget.prototype.setValidityFlag = function ( isValid ) {
15429 var widget = this,
15430 setFlag = function ( valid ) {
15431 if ( !valid ) {
15432 widget.$input.attr( 'aria-invalid', 'true' );
15433 } else {
15434 widget.$input.removeAttr( 'aria-invalid' );
15435 }
15436 widget.setFlags( { invalid: !valid } );
15437 };
15438
15439 if ( isValid !== undefined ) {
15440 setFlag( isValid );
15441 } else {
15442 this.getValidity().then( function () {
15443 setFlag( true );
15444 }, function () {
15445 setFlag( false );
15446 } );
15447 }
15448 };
15449
15450 /**
15451 * Check if a value is valid.
15452 *
15453 * This method returns a promise that resolves with a boolean `true` if the current value is
15454 * considered valid according to the supplied {@link #validate validation pattern}.
15455 *
15456 * @deprecated
15457 * @return {jQuery.Promise} A promise that resolves to a boolean `true` if the value is valid.
15458 */
15459 OO.ui.TextInputWidget.prototype.isValid = function () {
15460 if ( this.validate instanceof Function ) {
15461 var result = this.validate( this.getValue() );
15462 if ( $.isFunction( result.promise ) ) {
15463 return result.promise();
15464 } else {
15465 return $.Deferred().resolve( !!result ).promise();
15466 }
15467 } else {
15468 return $.Deferred().resolve( !!this.getValue().match( this.validate ) ).promise();
15469 }
15470 };
15471
15472 /**
15473 * Get the validity of current value.
15474 *
15475 * This method returns a promise that resolves if the value is valid and rejects if
15476 * it isn't. Uses the {@link #validate validation pattern} to check for validity.
15477 *
15478 * @return {jQuery.Promise} A promise that resolves if the value is valid, rejects if not.
15479 */
15480 OO.ui.TextInputWidget.prototype.getValidity = function () {
15481 var result, promise;
15482
15483 function rejectOrResolve( valid ) {
15484 if ( valid ) {
15485 return $.Deferred().resolve().promise();
15486 } else {
15487 return $.Deferred().reject().promise();
15488 }
15489 }
15490
15491 if ( this.validate instanceof Function ) {
15492 result = this.validate( this.getValue() );
15493
15494 if ( $.isFunction( result.promise ) ) {
15495 promise = $.Deferred();
15496
15497 result.then( function ( valid ) {
15498 if ( valid ) {
15499 promise.resolve();
15500 } else {
15501 promise.reject();
15502 }
15503 }, function () {
15504 promise.reject();
15505 } );
15506
15507 return promise.promise();
15508 } else {
15509 return rejectOrResolve( result );
15510 }
15511 } else {
15512 return rejectOrResolve( this.getValue().match( this.validate ) );
15513 }
15514 };
15515
15516 /**
15517 * Set the position of the inline label relative to that of the value: `‘before’` or `‘after’`.
15518 *
15519 * @param {string} labelPosition Label position, 'before' or 'after'
15520 * @chainable
15521 */
15522 OO.ui.TextInputWidget.prototype.setLabelPosition = function ( labelPosition ) {
15523 this.labelPosition = labelPosition;
15524 this.updatePosition();
15525 return this;
15526 };
15527
15528 /**
15529 * Deprecated alias of #setLabelPosition
15530 *
15531 * @deprecated Use setLabelPosition instead.
15532 */
15533 OO.ui.TextInputWidget.prototype.setPosition =
15534 OO.ui.TextInputWidget.prototype.setLabelPosition;
15535
15536 /**
15537 * Update the position of the inline label.
15538 *
15539 * This method is called by #setLabelPosition, and can also be called on its own if
15540 * something causes the label to be mispositioned.
15541 *
15542 * @chainable
15543 */
15544 OO.ui.TextInputWidget.prototype.updatePosition = function () {
15545 var after = this.labelPosition === 'after';
15546
15547 this.$element
15548 .toggleClass( 'oo-ui-textInputWidget-labelPosition-after', !!this.label && after )
15549 .toggleClass( 'oo-ui-textInputWidget-labelPosition-before', !!this.label && !after );
15550
15551 this.positionLabel();
15552
15553 return this;
15554 };
15555
15556 /**
15557 * Update the 'clear' indicator displayed on type: 'search' text fields, hiding it when the field is
15558 * already empty or when it's not editable.
15559 */
15560 OO.ui.TextInputWidget.prototype.updateSearchIndicator = function () {
15561 if ( this.type === 'search' ) {
15562 if ( this.getValue() === '' || this.isDisabled() || this.isReadOnly() ) {
15563 this.setIndicator( null );
15564 } else {
15565 this.setIndicator( 'clear' );
15566 }
15567 }
15568 };
15569
15570 /**
15571 * Position the label by setting the correct padding on the input.
15572 *
15573 * @private
15574 * @chainable
15575 */
15576 OO.ui.TextInputWidget.prototype.positionLabel = function () {
15577 // Clear old values
15578 this.$input
15579 // Clear old values if present
15580 .css( {
15581 'padding-right': '',
15582 'padding-left': ''
15583 } );
15584
15585 if ( this.label ) {
15586 this.$element.append( this.$label );
15587 } else {
15588 this.$label.detach();
15589 return;
15590 }
15591
15592 var after = this.labelPosition === 'after',
15593 rtl = this.$element.css( 'direction' ) === 'rtl',
15594 property = after === rtl ? 'padding-left' : 'padding-right';
15595
15596 this.$input.css( property, this.$label.outerWidth( true ) );
15597
15598 return this;
15599 };
15600
15601 /**
15602 * @inheritdoc
15603 */
15604 OO.ui.TextInputWidget.prototype.gatherPreInfuseState = function ( node ) {
15605 var
15606 state = OO.ui.TextInputWidget.parent.prototype.gatherPreInfuseState.call( this, node ),
15607 $input = $( node ).find( '.oo-ui-inputWidget-input' );
15608 state.$input = $input; // shortcut for performance, used in InputWidget
15609 if ( this.multiline ) {
15610 state.scrollTop = $input.scrollTop();
15611 }
15612 return state;
15613 };
15614
15615 /**
15616 * @inheritdoc
15617 */
15618 OO.ui.TextInputWidget.prototype.restorePreInfuseState = function ( state ) {
15619 OO.ui.TextInputWidget.parent.prototype.restorePreInfuseState.call( this, state );
15620 if ( state.scrollTop !== undefined ) {
15621 this.$input.scrollTop( state.scrollTop );
15622 }
15623 };
15624
15625 /**
15626 * ComboBoxWidgets combine a {@link OO.ui.TextInputWidget text input} (where a value
15627 * can be entered manually) and a {@link OO.ui.MenuSelectWidget menu of options} (from which
15628 * a value can be chosen instead). Users can choose options from the combo box in one of two ways:
15629 *
15630 * - by typing a value in the text input field. If the value exactly matches the value of a menu
15631 * option, that option will appear to be selected.
15632 * - by choosing a value from the menu. The value of the chosen option will then appear in the text
15633 * input field.
15634 *
15635 * For more information about menus and options, please see the [OOjs UI documentation on MediaWiki][1].
15636 *
15637 * @example
15638 * // Example: A ComboBoxWidget.
15639 * var comboBox = new OO.ui.ComboBoxWidget( {
15640 * label: 'ComboBoxWidget',
15641 * input: { value: 'Option One' },
15642 * menu: {
15643 * items: [
15644 * new OO.ui.MenuOptionWidget( {
15645 * data: 'Option 1',
15646 * label: 'Option One'
15647 * } ),
15648 * new OO.ui.MenuOptionWidget( {
15649 * data: 'Option 2',
15650 * label: 'Option Two'
15651 * } ),
15652 * new OO.ui.MenuOptionWidget( {
15653 * data: 'Option 3',
15654 * label: 'Option Three'
15655 * } ),
15656 * new OO.ui.MenuOptionWidget( {
15657 * data: 'Option 4',
15658 * label: 'Option Four'
15659 * } ),
15660 * new OO.ui.MenuOptionWidget( {
15661 * data: 'Option 5',
15662 * label: 'Option Five'
15663 * } )
15664 * ]
15665 * }
15666 * } );
15667 * $( 'body' ).append( comboBox.$element );
15668 *
15669 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
15670 *
15671 * @class
15672 * @extends OO.ui.Widget
15673 * @mixins OO.ui.mixin.TabIndexedElement
15674 *
15675 * @constructor
15676 * @param {Object} [config] Configuration options
15677 * @cfg {Object} [menu] Configuration options to pass to the {@link OO.ui.FloatingMenuSelectWidget menu select widget}.
15678 * @cfg {Object} [input] Configuration options to pass to the {@link OO.ui.TextInputWidget text input widget}.
15679 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
15680 * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
15681 * containing `<div>` and has a larger area. By default, the menu uses relative positioning.
15682 */
15683 OO.ui.ComboBoxWidget = function OoUiComboBoxWidget( config ) {
15684 // Configuration initialization
15685 config = config || {};
15686
15687 // Parent constructor
15688 OO.ui.ComboBoxWidget.parent.call( this, config );
15689
15690 // Properties (must be set before TabIndexedElement constructor call)
15691 this.$indicator = this.$( '<span>' );
15692
15693 // Mixin constructors
15694 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$indicator } ) );
15695
15696 // Properties
15697 this.$overlay = config.$overlay || this.$element;
15698 this.input = new OO.ui.TextInputWidget( $.extend(
15699 {
15700 indicator: 'down',
15701 $indicator: this.$indicator,
15702 disabled: this.isDisabled()
15703 },
15704 config.input
15705 ) );
15706 this.input.$input.eq( 0 ).attr( {
15707 role: 'combobox',
15708 'aria-autocomplete': 'list'
15709 } );
15710 this.menu = new OO.ui.FloatingMenuSelectWidget( $.extend(
15711 {
15712 widget: this,
15713 input: this.input,
15714 $container: this.input.$element,
15715 disabled: this.isDisabled()
15716 },
15717 config.menu
15718 ) );
15719
15720 // Events
15721 this.$indicator.on( {
15722 click: this.onClick.bind( this ),
15723 keypress: this.onKeyPress.bind( this )
15724 } );
15725 this.input.connect( this, {
15726 change: 'onInputChange',
15727 enter: 'onInputEnter'
15728 } );
15729 this.menu.connect( this, {
15730 choose: 'onMenuChoose',
15731 add: 'onMenuItemsChange',
15732 remove: 'onMenuItemsChange'
15733 } );
15734
15735 // Initialization
15736 this.$element.addClass( 'oo-ui-comboBoxWidget' ).append( this.input.$element );
15737 this.$overlay.append( this.menu.$element );
15738 this.onMenuItemsChange();
15739 };
15740
15741 /* Setup */
15742
15743 OO.inheritClass( OO.ui.ComboBoxWidget, OO.ui.Widget );
15744 OO.mixinClass( OO.ui.ComboBoxWidget, OO.ui.mixin.TabIndexedElement );
15745
15746 /* Methods */
15747
15748 /**
15749 * Get the combobox's menu.
15750 * @return {OO.ui.FloatingMenuSelectWidget} Menu widget
15751 */
15752 OO.ui.ComboBoxWidget.prototype.getMenu = function () {
15753 return this.menu;
15754 };
15755
15756 /**
15757 * Get the combobox's text input widget.
15758 * @return {OO.ui.TextInputWidget} Text input widget
15759 */
15760 OO.ui.ComboBoxWidget.prototype.getInput = function () {
15761 return this.input;
15762 };
15763
15764 /**
15765 * Handle input change events.
15766 *
15767 * @private
15768 * @param {string} value New value
15769 */
15770 OO.ui.ComboBoxWidget.prototype.onInputChange = function ( value ) {
15771 var match = this.menu.getItemFromData( value );
15772
15773 this.menu.selectItem( match );
15774 if ( this.menu.getHighlightedItem() ) {
15775 this.menu.highlightItem( match );
15776 }
15777
15778 if ( !this.isDisabled() ) {
15779 this.menu.toggle( true );
15780 }
15781 };
15782
15783 /**
15784 * Handle mouse click events.
15785 *
15786 *
15787 * @private
15788 * @param {jQuery.Event} e Mouse click event
15789 */
15790 OO.ui.ComboBoxWidget.prototype.onClick = function ( e ) {
15791 if ( !this.isDisabled() && e.which === 1 ) {
15792 this.menu.toggle();
15793 this.input.$input[ 0 ].focus();
15794 }
15795 return false;
15796 };
15797
15798 /**
15799 * Handle key press events.
15800 *
15801 *
15802 * @private
15803 * @param {jQuery.Event} e Key press event
15804 */
15805 OO.ui.ComboBoxWidget.prototype.onKeyPress = function ( e ) {
15806 if ( !this.isDisabled() && ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER ) ) {
15807 this.menu.toggle();
15808 this.input.$input[ 0 ].focus();
15809 return false;
15810 }
15811 };
15812
15813 /**
15814 * Handle input enter events.
15815 *
15816 * @private
15817 */
15818 OO.ui.ComboBoxWidget.prototype.onInputEnter = function () {
15819 if ( !this.isDisabled() ) {
15820 this.menu.toggle( false );
15821 }
15822 };
15823
15824 /**
15825 * Handle menu choose events.
15826 *
15827 * @private
15828 * @param {OO.ui.OptionWidget} item Chosen item
15829 */
15830 OO.ui.ComboBoxWidget.prototype.onMenuChoose = function ( item ) {
15831 this.input.setValue( item.getData() );
15832 };
15833
15834 /**
15835 * Handle menu item change events.
15836 *
15837 * @private
15838 */
15839 OO.ui.ComboBoxWidget.prototype.onMenuItemsChange = function () {
15840 var match = this.menu.getItemFromData( this.input.getValue() );
15841 this.menu.selectItem( match );
15842 if ( this.menu.getHighlightedItem() ) {
15843 this.menu.highlightItem( match );
15844 }
15845 this.$element.toggleClass( 'oo-ui-comboBoxWidget-empty', this.menu.isEmpty() );
15846 };
15847
15848 /**
15849 * @inheritdoc
15850 */
15851 OO.ui.ComboBoxWidget.prototype.setDisabled = function ( disabled ) {
15852 // Parent method
15853 OO.ui.ComboBoxWidget.parent.prototype.setDisabled.call( this, disabled );
15854
15855 if ( this.input ) {
15856 this.input.setDisabled( this.isDisabled() );
15857 }
15858 if ( this.menu ) {
15859 this.menu.setDisabled( this.isDisabled() );
15860 }
15861
15862 return this;
15863 };
15864
15865 /**
15866 * LabelWidgets help identify the function of interface elements. Each LabelWidget can
15867 * be configured with a `label` option that is set to a string, a label node, or a function:
15868 *
15869 * - String: a plaintext string
15870 * - jQuery selection: a jQuery selection, used for anything other than a plaintext label, e.g., a
15871 * label that includes a link or special styling, such as a gray color or additional graphical elements.
15872 * - Function: a function that will produce a string in the future. Functions are used
15873 * in cases where the value of the label is not currently defined.
15874 *
15875 * In addition, the LabelWidget can be associated with an {@link OO.ui.InputWidget input widget}, which
15876 * will come into focus when the label is clicked.
15877 *
15878 * @example
15879 * // Examples of LabelWidgets
15880 * var label1 = new OO.ui.LabelWidget( {
15881 * label: 'plaintext label'
15882 * } );
15883 * var label2 = new OO.ui.LabelWidget( {
15884 * label: $( '<a href="default.html">jQuery label</a>' )
15885 * } );
15886 * // Create a fieldset layout with fields for each example
15887 * var fieldset = new OO.ui.FieldsetLayout();
15888 * fieldset.addItems( [
15889 * new OO.ui.FieldLayout( label1 ),
15890 * new OO.ui.FieldLayout( label2 )
15891 * ] );
15892 * $( 'body' ).append( fieldset.$element );
15893 *
15894 *
15895 * @class
15896 * @extends OO.ui.Widget
15897 * @mixins OO.ui.mixin.LabelElement
15898 *
15899 * @constructor
15900 * @param {Object} [config] Configuration options
15901 * @cfg {OO.ui.InputWidget} [input] {@link OO.ui.InputWidget Input widget} that uses the label.
15902 * Clicking the label will focus the specified input field.
15903 */
15904 OO.ui.LabelWidget = function OoUiLabelWidget( config ) {
15905 // Configuration initialization
15906 config = config || {};
15907
15908 // Parent constructor
15909 OO.ui.LabelWidget.parent.call( this, config );
15910
15911 // Mixin constructors
15912 OO.ui.mixin.LabelElement.call( this, $.extend( {}, config, { $label: this.$element } ) );
15913 OO.ui.mixin.TitledElement.call( this, config );
15914
15915 // Properties
15916 this.input = config.input;
15917
15918 // Events
15919 if ( this.input instanceof OO.ui.InputWidget ) {
15920 this.$element.on( 'click', this.onClick.bind( this ) );
15921 }
15922
15923 // Initialization
15924 this.$element.addClass( 'oo-ui-labelWidget' );
15925 };
15926
15927 /* Setup */
15928
15929 OO.inheritClass( OO.ui.LabelWidget, OO.ui.Widget );
15930 OO.mixinClass( OO.ui.LabelWidget, OO.ui.mixin.LabelElement );
15931 OO.mixinClass( OO.ui.LabelWidget, OO.ui.mixin.TitledElement );
15932
15933 /* Static Properties */
15934
15935 OO.ui.LabelWidget.static.tagName = 'span';
15936
15937 /* Methods */
15938
15939 /**
15940 * Handles label mouse click events.
15941 *
15942 * @private
15943 * @param {jQuery.Event} e Mouse click event
15944 */
15945 OO.ui.LabelWidget.prototype.onClick = function () {
15946 this.input.simulateLabelClick();
15947 return false;
15948 };
15949
15950 /**
15951 * OptionWidgets are special elements that can be selected and configured with data. The
15952 * data is often unique for each option, but it does not have to be. OptionWidgets are used
15953 * with OO.ui.SelectWidget to create a selection of mutually exclusive options. For more information
15954 * and examples, please see the [OOjs UI documentation on MediaWiki][1].
15955 *
15956 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
15957 *
15958 * @class
15959 * @extends OO.ui.Widget
15960 * @mixins OO.ui.mixin.LabelElement
15961 * @mixins OO.ui.mixin.FlaggedElement
15962 *
15963 * @constructor
15964 * @param {Object} [config] Configuration options
15965 */
15966 OO.ui.OptionWidget = function OoUiOptionWidget( config ) {
15967 // Configuration initialization
15968 config = config || {};
15969
15970 // Parent constructor
15971 OO.ui.OptionWidget.parent.call( this, config );
15972
15973 // Mixin constructors
15974 OO.ui.mixin.ItemWidget.call( this );
15975 OO.ui.mixin.LabelElement.call( this, config );
15976 OO.ui.mixin.FlaggedElement.call( this, config );
15977
15978 // Properties
15979 this.selected = false;
15980 this.highlighted = false;
15981 this.pressed = false;
15982
15983 // Initialization
15984 this.$element
15985 .data( 'oo-ui-optionWidget', this )
15986 .attr( 'role', 'option' )
15987 .attr( 'aria-selected', 'false' )
15988 .addClass( 'oo-ui-optionWidget' )
15989 .append( this.$label );
15990 };
15991
15992 /* Setup */
15993
15994 OO.inheritClass( OO.ui.OptionWidget, OO.ui.Widget );
15995 OO.mixinClass( OO.ui.OptionWidget, OO.ui.mixin.ItemWidget );
15996 OO.mixinClass( OO.ui.OptionWidget, OO.ui.mixin.LabelElement );
15997 OO.mixinClass( OO.ui.OptionWidget, OO.ui.mixin.FlaggedElement );
15998
15999 /* Static Properties */
16000
16001 OO.ui.OptionWidget.static.selectable = true;
16002
16003 OO.ui.OptionWidget.static.highlightable = true;
16004
16005 OO.ui.OptionWidget.static.pressable = true;
16006
16007 OO.ui.OptionWidget.static.scrollIntoViewOnSelect = false;
16008
16009 /* Methods */
16010
16011 /**
16012 * Check if the option can be selected.
16013 *
16014 * @return {boolean} Item is selectable
16015 */
16016 OO.ui.OptionWidget.prototype.isSelectable = function () {
16017 return this.constructor.static.selectable && !this.isDisabled() && this.isVisible();
16018 };
16019
16020 /**
16021 * Check if the option can be highlighted. A highlight indicates that the option
16022 * may be selected when a user presses enter or clicks. Disabled items cannot
16023 * be highlighted.
16024 *
16025 * @return {boolean} Item is highlightable
16026 */
16027 OO.ui.OptionWidget.prototype.isHighlightable = function () {
16028 return this.constructor.static.highlightable && !this.isDisabled() && this.isVisible();
16029 };
16030
16031 /**
16032 * Check if the option can be pressed. The pressed state occurs when a user mouses
16033 * down on an item, but has not yet let go of the mouse.
16034 *
16035 * @return {boolean} Item is pressable
16036 */
16037 OO.ui.OptionWidget.prototype.isPressable = function () {
16038 return this.constructor.static.pressable && !this.isDisabled() && this.isVisible();
16039 };
16040
16041 /**
16042 * Check if the option is selected.
16043 *
16044 * @return {boolean} Item is selected
16045 */
16046 OO.ui.OptionWidget.prototype.isSelected = function () {
16047 return this.selected;
16048 };
16049
16050 /**
16051 * Check if the option is highlighted. A highlight indicates that the
16052 * item may be selected when a user presses enter or clicks.
16053 *
16054 * @return {boolean} Item is highlighted
16055 */
16056 OO.ui.OptionWidget.prototype.isHighlighted = function () {
16057 return this.highlighted;
16058 };
16059
16060 /**
16061 * Check if the option is pressed. The pressed state occurs when a user mouses
16062 * down on an item, but has not yet let go of the mouse. The item may appear
16063 * selected, but it will not be selected until the user releases the mouse.
16064 *
16065 * @return {boolean} Item is pressed
16066 */
16067 OO.ui.OptionWidget.prototype.isPressed = function () {
16068 return this.pressed;
16069 };
16070
16071 /**
16072 * Set the option’s selected state. In general, all modifications to the selection
16073 * should be handled by the SelectWidget’s {@link OO.ui.SelectWidget#selectItem selectItem( [item] )}
16074 * method instead of this method.
16075 *
16076 * @param {boolean} [state=false] Select option
16077 * @chainable
16078 */
16079 OO.ui.OptionWidget.prototype.setSelected = function ( state ) {
16080 if ( this.constructor.static.selectable ) {
16081 this.selected = !!state;
16082 this.$element
16083 .toggleClass( 'oo-ui-optionWidget-selected', state )
16084 .attr( 'aria-selected', state.toString() );
16085 if ( state && this.constructor.static.scrollIntoViewOnSelect ) {
16086 this.scrollElementIntoView();
16087 }
16088 this.updateThemeClasses();
16089 }
16090 return this;
16091 };
16092
16093 /**
16094 * Set the option’s highlighted state. In general, all programmatic
16095 * modifications to the highlight should be handled by the
16096 * SelectWidget’s {@link OO.ui.SelectWidget#highlightItem highlightItem( [item] )}
16097 * method instead of this method.
16098 *
16099 * @param {boolean} [state=false] Highlight option
16100 * @chainable
16101 */
16102 OO.ui.OptionWidget.prototype.setHighlighted = function ( state ) {
16103 if ( this.constructor.static.highlightable ) {
16104 this.highlighted = !!state;
16105 this.$element.toggleClass( 'oo-ui-optionWidget-highlighted', state );
16106 this.updateThemeClasses();
16107 }
16108 return this;
16109 };
16110
16111 /**
16112 * Set the option’s pressed state. In general, all
16113 * programmatic modifications to the pressed state should be handled by the
16114 * SelectWidget’s {@link OO.ui.SelectWidget#pressItem pressItem( [item] )}
16115 * method instead of this method.
16116 *
16117 * @param {boolean} [state=false] Press option
16118 * @chainable
16119 */
16120 OO.ui.OptionWidget.prototype.setPressed = function ( state ) {
16121 if ( this.constructor.static.pressable ) {
16122 this.pressed = !!state;
16123 this.$element.toggleClass( 'oo-ui-optionWidget-pressed', state );
16124 this.updateThemeClasses();
16125 }
16126 return this;
16127 };
16128
16129 /**
16130 * DecoratedOptionWidgets are {@link OO.ui.OptionWidget options} that can be configured
16131 * with an {@link OO.ui.mixin.IconElement icon} and/or {@link OO.ui.mixin.IndicatorElement indicator}.
16132 * This class is used with OO.ui.SelectWidget to create a selection of mutually exclusive
16133 * options. For more information about options and selects, please see the
16134 * [OOjs UI documentation on MediaWiki][1].
16135 *
16136 * @example
16137 * // Decorated options in a select widget
16138 * var select = new OO.ui.SelectWidget( {
16139 * items: [
16140 * new OO.ui.DecoratedOptionWidget( {
16141 * data: 'a',
16142 * label: 'Option with icon',
16143 * icon: 'help'
16144 * } ),
16145 * new OO.ui.DecoratedOptionWidget( {
16146 * data: 'b',
16147 * label: 'Option with indicator',
16148 * indicator: 'next'
16149 * } )
16150 * ]
16151 * } );
16152 * $( 'body' ).append( select.$element );
16153 *
16154 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
16155 *
16156 * @class
16157 * @extends OO.ui.OptionWidget
16158 * @mixins OO.ui.mixin.IconElement
16159 * @mixins OO.ui.mixin.IndicatorElement
16160 *
16161 * @constructor
16162 * @param {Object} [config] Configuration options
16163 */
16164 OO.ui.DecoratedOptionWidget = function OoUiDecoratedOptionWidget( config ) {
16165 // Parent constructor
16166 OO.ui.DecoratedOptionWidget.parent.call( this, config );
16167
16168 // Mixin constructors
16169 OO.ui.mixin.IconElement.call( this, config );
16170 OO.ui.mixin.IndicatorElement.call( this, config );
16171
16172 // Initialization
16173 this.$element
16174 .addClass( 'oo-ui-decoratedOptionWidget' )
16175 .prepend( this.$icon )
16176 .append( this.$indicator );
16177 };
16178
16179 /* Setup */
16180
16181 OO.inheritClass( OO.ui.DecoratedOptionWidget, OO.ui.OptionWidget );
16182 OO.mixinClass( OO.ui.DecoratedOptionWidget, OO.ui.mixin.IconElement );
16183 OO.mixinClass( OO.ui.DecoratedOptionWidget, OO.ui.mixin.IndicatorElement );
16184
16185 /**
16186 * ButtonOptionWidget is a special type of {@link OO.ui.mixin.ButtonElement button element} that
16187 * can be selected and configured with data. The class is
16188 * used with OO.ui.ButtonSelectWidget to create a selection of button options. Please see the
16189 * [OOjs UI documentation on MediaWiki] [1] for more information.
16190 *
16191 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Button_selects_and_options
16192 *
16193 * @class
16194 * @extends OO.ui.DecoratedOptionWidget
16195 * @mixins OO.ui.mixin.ButtonElement
16196 * @mixins OO.ui.mixin.TabIndexedElement
16197 *
16198 * @constructor
16199 * @param {Object} [config] Configuration options
16200 */
16201 OO.ui.ButtonOptionWidget = function OoUiButtonOptionWidget( config ) {
16202 // Configuration initialization
16203 config = config || {};
16204
16205 // Parent constructor
16206 OO.ui.ButtonOptionWidget.parent.call( this, config );
16207
16208 // Mixin constructors
16209 OO.ui.mixin.ButtonElement.call( this, config );
16210 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, {
16211 $tabIndexed: this.$button,
16212 tabIndex: -1
16213 } ) );
16214
16215 // Initialization
16216 this.$element.addClass( 'oo-ui-buttonOptionWidget' );
16217 this.$button.append( this.$element.contents() );
16218 this.$element.append( this.$button );
16219 };
16220
16221 /* Setup */
16222
16223 OO.inheritClass( OO.ui.ButtonOptionWidget, OO.ui.DecoratedOptionWidget );
16224 OO.mixinClass( OO.ui.ButtonOptionWidget, OO.ui.mixin.ButtonElement );
16225 OO.mixinClass( OO.ui.ButtonOptionWidget, OO.ui.mixin.TabIndexedElement );
16226
16227 /* Static Properties */
16228
16229 // Allow button mouse down events to pass through so they can be handled by the parent select widget
16230 OO.ui.ButtonOptionWidget.static.cancelButtonMouseDownEvents = false;
16231
16232 OO.ui.ButtonOptionWidget.static.highlightable = false;
16233
16234 /* Methods */
16235
16236 /**
16237 * @inheritdoc
16238 */
16239 OO.ui.ButtonOptionWidget.prototype.setSelected = function ( state ) {
16240 OO.ui.ButtonOptionWidget.parent.prototype.setSelected.call( this, state );
16241
16242 if ( this.constructor.static.selectable ) {
16243 this.setActive( state );
16244 }
16245
16246 return this;
16247 };
16248
16249 /**
16250 * RadioOptionWidget is an option widget that looks like a radio button.
16251 * The class is used with OO.ui.RadioSelectWidget to create a selection of radio options.
16252 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information.
16253 *
16254 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Button_selects_and_option
16255 *
16256 * @class
16257 * @extends OO.ui.OptionWidget
16258 *
16259 * @constructor
16260 * @param {Object} [config] Configuration options
16261 */
16262 OO.ui.RadioOptionWidget = function OoUiRadioOptionWidget( config ) {
16263 // Configuration initialization
16264 config = config || {};
16265
16266 // Properties (must be done before parent constructor which calls #setDisabled)
16267 this.radio = new OO.ui.RadioInputWidget( { value: config.data, tabIndex: -1 } );
16268
16269 // Parent constructor
16270 OO.ui.RadioOptionWidget.parent.call( this, config );
16271
16272 // Events
16273 this.radio.$input.on( 'focus', this.onInputFocus.bind( this ) );
16274
16275 // Initialization
16276 // Remove implicit role, we're handling it ourselves
16277 this.radio.$input.attr( 'role', 'presentation' );
16278 this.$element
16279 .addClass( 'oo-ui-radioOptionWidget' )
16280 .attr( 'role', 'radio' )
16281 .attr( 'aria-checked', 'false' )
16282 .removeAttr( 'aria-selected' )
16283 .prepend( this.radio.$element );
16284 };
16285
16286 /* Setup */
16287
16288 OO.inheritClass( OO.ui.RadioOptionWidget, OO.ui.OptionWidget );
16289
16290 /* Static Properties */
16291
16292 OO.ui.RadioOptionWidget.static.highlightable = false;
16293
16294 OO.ui.RadioOptionWidget.static.scrollIntoViewOnSelect = true;
16295
16296 OO.ui.RadioOptionWidget.static.pressable = false;
16297
16298 OO.ui.RadioOptionWidget.static.tagName = 'label';
16299
16300 /* Methods */
16301
16302 /**
16303 * @param {jQuery.Event} e Focus event
16304 * @private
16305 */
16306 OO.ui.RadioOptionWidget.prototype.onInputFocus = function () {
16307 this.radio.$input.blur();
16308 this.$element.parent().focus();
16309 };
16310
16311 /**
16312 * @inheritdoc
16313 */
16314 OO.ui.RadioOptionWidget.prototype.setSelected = function ( state ) {
16315 OO.ui.RadioOptionWidget.parent.prototype.setSelected.call( this, state );
16316
16317 this.radio.setSelected( state );
16318 this.$element
16319 .attr( 'aria-checked', state.toString() )
16320 .removeAttr( 'aria-selected' );
16321
16322 return this;
16323 };
16324
16325 /**
16326 * @inheritdoc
16327 */
16328 OO.ui.RadioOptionWidget.prototype.setDisabled = function ( disabled ) {
16329 OO.ui.RadioOptionWidget.parent.prototype.setDisabled.call( this, disabled );
16330
16331 this.radio.setDisabled( this.isDisabled() );
16332
16333 return this;
16334 };
16335
16336 /**
16337 * MenuOptionWidget is an option widget that looks like a menu item. The class is used with
16338 * OO.ui.MenuSelectWidget to create a menu of mutually exclusive options. Please see
16339 * the [OOjs UI documentation on MediaWiki] [1] for more information.
16340 *
16341 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
16342 *
16343 * @class
16344 * @extends OO.ui.DecoratedOptionWidget
16345 *
16346 * @constructor
16347 * @param {Object} [config] Configuration options
16348 */
16349 OO.ui.MenuOptionWidget = function OoUiMenuOptionWidget( config ) {
16350 // Configuration initialization
16351 config = $.extend( { icon: 'check' }, config );
16352
16353 // Parent constructor
16354 OO.ui.MenuOptionWidget.parent.call( this, config );
16355
16356 // Initialization
16357 this.$element
16358 .attr( 'role', 'menuitem' )
16359 .addClass( 'oo-ui-menuOptionWidget' );
16360 };
16361
16362 /* Setup */
16363
16364 OO.inheritClass( OO.ui.MenuOptionWidget, OO.ui.DecoratedOptionWidget );
16365
16366 /* Static Properties */
16367
16368 OO.ui.MenuOptionWidget.static.scrollIntoViewOnSelect = true;
16369
16370 /**
16371 * MenuSectionOptionWidgets are used inside {@link OO.ui.MenuSelectWidget menu select widgets} to group one or more related
16372 * {@link OO.ui.MenuOptionWidget menu options}. MenuSectionOptionWidgets cannot be highlighted or selected.
16373 *
16374 * @example
16375 * var myDropdown = new OO.ui.DropdownWidget( {
16376 * menu: {
16377 * items: [
16378 * new OO.ui.MenuSectionOptionWidget( {
16379 * label: 'Dogs'
16380 * } ),
16381 * new OO.ui.MenuOptionWidget( {
16382 * data: 'corgi',
16383 * label: 'Welsh Corgi'
16384 * } ),
16385 * new OO.ui.MenuOptionWidget( {
16386 * data: 'poodle',
16387 * label: 'Standard Poodle'
16388 * } ),
16389 * new OO.ui.MenuSectionOptionWidget( {
16390 * label: 'Cats'
16391 * } ),
16392 * new OO.ui.MenuOptionWidget( {
16393 * data: 'lion',
16394 * label: 'Lion'
16395 * } )
16396 * ]
16397 * }
16398 * } );
16399 * $( 'body' ).append( myDropdown.$element );
16400 *
16401 *
16402 * @class
16403 * @extends OO.ui.DecoratedOptionWidget
16404 *
16405 * @constructor
16406 * @param {Object} [config] Configuration options
16407 */
16408 OO.ui.MenuSectionOptionWidget = function OoUiMenuSectionOptionWidget( config ) {
16409 // Parent constructor
16410 OO.ui.MenuSectionOptionWidget.parent.call( this, config );
16411
16412 // Initialization
16413 this.$element.addClass( 'oo-ui-menuSectionOptionWidget' );
16414 };
16415
16416 /* Setup */
16417
16418 OO.inheritClass( OO.ui.MenuSectionOptionWidget, OO.ui.DecoratedOptionWidget );
16419
16420 /* Static Properties */
16421
16422 OO.ui.MenuSectionOptionWidget.static.selectable = false;
16423
16424 OO.ui.MenuSectionOptionWidget.static.highlightable = false;
16425
16426 /**
16427 * OutlineOptionWidget is an item in an {@link OO.ui.OutlineSelectWidget OutlineSelectWidget}.
16428 *
16429 * Currently, this class is only used by {@link OO.ui.BookletLayout booklet layouts}, which contain
16430 * {@link OO.ui.PageLayout page layouts}. See {@link OO.ui.BookletLayout BookletLayout}
16431 * for an example.
16432 *
16433 * @class
16434 * @extends OO.ui.DecoratedOptionWidget
16435 *
16436 * @constructor
16437 * @param {Object} [config] Configuration options
16438 * @cfg {number} [level] Indentation level
16439 * @cfg {boolean} [movable] Allow modification from {@link OO.ui.OutlineControlsWidget outline controls}.
16440 */
16441 OO.ui.OutlineOptionWidget = function OoUiOutlineOptionWidget( config ) {
16442 // Configuration initialization
16443 config = config || {};
16444
16445 // Parent constructor
16446 OO.ui.OutlineOptionWidget.parent.call( this, config );
16447
16448 // Properties
16449 this.level = 0;
16450 this.movable = !!config.movable;
16451 this.removable = !!config.removable;
16452
16453 // Initialization
16454 this.$element.addClass( 'oo-ui-outlineOptionWidget' );
16455 this.setLevel( config.level );
16456 };
16457
16458 /* Setup */
16459
16460 OO.inheritClass( OO.ui.OutlineOptionWidget, OO.ui.DecoratedOptionWidget );
16461
16462 /* Static Properties */
16463
16464 OO.ui.OutlineOptionWidget.static.highlightable = false;
16465
16466 OO.ui.OutlineOptionWidget.static.scrollIntoViewOnSelect = true;
16467
16468 OO.ui.OutlineOptionWidget.static.levelClass = 'oo-ui-outlineOptionWidget-level-';
16469
16470 OO.ui.OutlineOptionWidget.static.levels = 3;
16471
16472 /* Methods */
16473
16474 /**
16475 * Check if item is movable.
16476 *
16477 * Movability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
16478 *
16479 * @return {boolean} Item is movable
16480 */
16481 OO.ui.OutlineOptionWidget.prototype.isMovable = function () {
16482 return this.movable;
16483 };
16484
16485 /**
16486 * Check if item is removable.
16487 *
16488 * Removability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
16489 *
16490 * @return {boolean} Item is removable
16491 */
16492 OO.ui.OutlineOptionWidget.prototype.isRemovable = function () {
16493 return this.removable;
16494 };
16495
16496 /**
16497 * Get indentation level.
16498 *
16499 * @return {number} Indentation level
16500 */
16501 OO.ui.OutlineOptionWidget.prototype.getLevel = function () {
16502 return this.level;
16503 };
16504
16505 /**
16506 * Set movability.
16507 *
16508 * Movability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
16509 *
16510 * @param {boolean} movable Item is movable
16511 * @chainable
16512 */
16513 OO.ui.OutlineOptionWidget.prototype.setMovable = function ( movable ) {
16514 this.movable = !!movable;
16515 this.updateThemeClasses();
16516 return this;
16517 };
16518
16519 /**
16520 * Set removability.
16521 *
16522 * Removability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
16523 *
16524 * @param {boolean} movable Item is removable
16525 * @chainable
16526 */
16527 OO.ui.OutlineOptionWidget.prototype.setRemovable = function ( removable ) {
16528 this.removable = !!removable;
16529 this.updateThemeClasses();
16530 return this;
16531 };
16532
16533 /**
16534 * Set indentation level.
16535 *
16536 * @param {number} [level=0] Indentation level, in the range of [0,#maxLevel]
16537 * @chainable
16538 */
16539 OO.ui.OutlineOptionWidget.prototype.setLevel = function ( level ) {
16540 var levels = this.constructor.static.levels,
16541 levelClass = this.constructor.static.levelClass,
16542 i = levels;
16543
16544 this.level = level ? Math.max( 0, Math.min( levels - 1, level ) ) : 0;
16545 while ( i-- ) {
16546 if ( this.level === i ) {
16547 this.$element.addClass( levelClass + i );
16548 } else {
16549 this.$element.removeClass( levelClass + i );
16550 }
16551 }
16552 this.updateThemeClasses();
16553
16554 return this;
16555 };
16556
16557 /**
16558 * TabOptionWidget is an item in a {@link OO.ui.TabSelectWidget TabSelectWidget}.
16559 *
16560 * Currently, this class is only used by {@link OO.ui.IndexLayout index layouts}, which contain
16561 * {@link OO.ui.CardLayout card layouts}. See {@link OO.ui.IndexLayout IndexLayout}
16562 * for an example.
16563 *
16564 * @class
16565 * @extends OO.ui.OptionWidget
16566 *
16567 * @constructor
16568 * @param {Object} [config] Configuration options
16569 */
16570 OO.ui.TabOptionWidget = function OoUiTabOptionWidget( config ) {
16571 // Configuration initialization
16572 config = config || {};
16573
16574 // Parent constructor
16575 OO.ui.TabOptionWidget.parent.call( this, config );
16576
16577 // Initialization
16578 this.$element.addClass( 'oo-ui-tabOptionWidget' );
16579 };
16580
16581 /* Setup */
16582
16583 OO.inheritClass( OO.ui.TabOptionWidget, OO.ui.OptionWidget );
16584
16585 /* Static Properties */
16586
16587 OO.ui.TabOptionWidget.static.highlightable = false;
16588
16589 /**
16590 * PopupWidget is a container for content. The popup is overlaid and positioned absolutely.
16591 * By default, each popup has an anchor that points toward its origin.
16592 * Please see the [OOjs UI documentation on Mediawiki] [1] for more information and examples.
16593 *
16594 * @example
16595 * // A popup widget.
16596 * var popup = new OO.ui.PopupWidget( {
16597 * $content: $( '<p>Hi there!</p>' ),
16598 * padded: true,
16599 * width: 300
16600 * } );
16601 *
16602 * $( 'body' ).append( popup.$element );
16603 * // To display the popup, toggle the visibility to 'true'.
16604 * popup.toggle( true );
16605 *
16606 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups
16607 *
16608 * @class
16609 * @extends OO.ui.Widget
16610 * @mixins OO.ui.mixin.LabelElement
16611 *
16612 * @constructor
16613 * @param {Object} [config] Configuration options
16614 * @cfg {number} [width=320] Width of popup in pixels
16615 * @cfg {number} [height] Height of popup in pixels. Omit to use the automatic height.
16616 * @cfg {boolean} [anchor=true] Show anchor pointing to origin of popup
16617 * @cfg {string} [align='center'] Alignment of the popup: `center`, `force-left`, `force-right`, `backwards` or `forwards`.
16618 * If the popup is forced-left the popup body is leaning towards the left. For force-right alignment, the body of the
16619 * popup is leaning towards the right of the screen.
16620 * Using 'backwards' is a logical direction which will result in the popup leaning towards the beginning of the sentence
16621 * in the given language, which means it will flip to the correct positioning in right-to-left languages.
16622 * Using 'forward' will also result in a logical alignment where the body of the popup leans towards the end of the
16623 * sentence in the given language.
16624 * @cfg {jQuery} [$container] Constrain the popup to the boundaries of the specified container.
16625 * See the [OOjs UI docs on MediaWiki][3] for an example.
16626 * [3]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups#containerExample
16627 * @cfg {number} [containerPadding=10] Padding between the popup and its container, specified as a number of pixels.
16628 * @cfg {jQuery} [$content] Content to append to the popup's body
16629 * @cfg {boolean} [autoClose=false] Automatically close the popup when it loses focus.
16630 * @cfg {jQuery} [$autoCloseIgnore] Elements that will not close the popup when clicked.
16631 * This config option is only relevant if #autoClose is set to `true`. See the [OOjs UI docs on MediaWiki][2]
16632 * for an example.
16633 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups#autocloseExample
16634 * @cfg {boolean} [head] Show a popup header that contains a #label (if specified) and close
16635 * button.
16636 * @cfg {boolean} [padded] Add padding to the popup's body
16637 */
16638 OO.ui.PopupWidget = function OoUiPopupWidget( config ) {
16639 // Configuration initialization
16640 config = config || {};
16641
16642 // Parent constructor
16643 OO.ui.PopupWidget.parent.call( this, config );
16644
16645 // Properties (must be set before ClippableElement constructor call)
16646 this.$body = $( '<div>' );
16647
16648 // Mixin constructors
16649 OO.ui.mixin.LabelElement.call( this, config );
16650 OO.ui.mixin.ClippableElement.call( this, $.extend( {}, config, { $clippable: this.$body } ) );
16651
16652 // Properties
16653 this.$popup = $( '<div>' );
16654 this.$head = $( '<div>' );
16655 this.$anchor = $( '<div>' );
16656 // If undefined, will be computed lazily in updateDimensions()
16657 this.$container = config.$container;
16658 this.containerPadding = config.containerPadding !== undefined ? config.containerPadding : 10;
16659 this.autoClose = !!config.autoClose;
16660 this.$autoCloseIgnore = config.$autoCloseIgnore;
16661 this.transitionTimeout = null;
16662 this.anchor = null;
16663 this.width = config.width !== undefined ? config.width : 320;
16664 this.height = config.height !== undefined ? config.height : null;
16665 this.setAlignment( config.align );
16666 this.closeButton = new OO.ui.ButtonWidget( { framed: false, icon: 'close' } );
16667 this.onMouseDownHandler = this.onMouseDown.bind( this );
16668 this.onDocumentKeyDownHandler = this.onDocumentKeyDown.bind( this );
16669
16670 // Events
16671 this.closeButton.connect( this, { click: 'onCloseButtonClick' } );
16672
16673 // Initialization
16674 this.toggleAnchor( config.anchor === undefined || config.anchor );
16675 this.$body.addClass( 'oo-ui-popupWidget-body' );
16676 this.$anchor.addClass( 'oo-ui-popupWidget-anchor' );
16677 this.$head
16678 .addClass( 'oo-ui-popupWidget-head' )
16679 .append( this.$label, this.closeButton.$element );
16680 if ( !config.head ) {
16681 this.$head.addClass( 'oo-ui-element-hidden' );
16682 }
16683 this.$popup
16684 .addClass( 'oo-ui-popupWidget-popup' )
16685 .append( this.$head, this.$body );
16686 this.$element
16687 .addClass( 'oo-ui-popupWidget' )
16688 .append( this.$popup, this.$anchor );
16689 // Move content, which was added to #$element by OO.ui.Widget, to the body
16690 if ( config.$content instanceof jQuery ) {
16691 this.$body.append( config.$content );
16692 }
16693 if ( config.padded ) {
16694 this.$body.addClass( 'oo-ui-popupWidget-body-padded' );
16695 }
16696
16697 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
16698 // that reference properties not initialized at that time of parent class construction
16699 // TODO: Find a better way to handle post-constructor setup
16700 this.visible = false;
16701 this.$element.addClass( 'oo-ui-element-hidden' );
16702 };
16703
16704 /* Setup */
16705
16706 OO.inheritClass( OO.ui.PopupWidget, OO.ui.Widget );
16707 OO.mixinClass( OO.ui.PopupWidget, OO.ui.mixin.LabelElement );
16708 OO.mixinClass( OO.ui.PopupWidget, OO.ui.mixin.ClippableElement );
16709
16710 /* Methods */
16711
16712 /**
16713 * Handles mouse down events.
16714 *
16715 * @private
16716 * @param {MouseEvent} e Mouse down event
16717 */
16718 OO.ui.PopupWidget.prototype.onMouseDown = function ( e ) {
16719 if (
16720 this.isVisible() &&
16721 !$.contains( this.$element[ 0 ], e.target ) &&
16722 ( !this.$autoCloseIgnore || !this.$autoCloseIgnore.has( e.target ).length )
16723 ) {
16724 this.toggle( false );
16725 }
16726 };
16727
16728 /**
16729 * Bind mouse down listener.
16730 *
16731 * @private
16732 */
16733 OO.ui.PopupWidget.prototype.bindMouseDownListener = function () {
16734 // Capture clicks outside popup
16735 OO.ui.addCaptureEventListener( this.getElementWindow(), 'mousedown', this.onMouseDownHandler );
16736 };
16737
16738 /**
16739 * Handles close button click events.
16740 *
16741 * @private
16742 */
16743 OO.ui.PopupWidget.prototype.onCloseButtonClick = function () {
16744 if ( this.isVisible() ) {
16745 this.toggle( false );
16746 }
16747 };
16748
16749 /**
16750 * Unbind mouse down listener.
16751 *
16752 * @private
16753 */
16754 OO.ui.PopupWidget.prototype.unbindMouseDownListener = function () {
16755 OO.ui.removeCaptureEventListener( this.getElementWindow(), 'mousedown', this.onMouseDownHandler );
16756 };
16757
16758 /**
16759 * Handles key down events.
16760 *
16761 * @private
16762 * @param {KeyboardEvent} e Key down event
16763 */
16764 OO.ui.PopupWidget.prototype.onDocumentKeyDown = function ( e ) {
16765 if (
16766 e.which === OO.ui.Keys.ESCAPE &&
16767 this.isVisible()
16768 ) {
16769 this.toggle( false );
16770 e.preventDefault();
16771 e.stopPropagation();
16772 }
16773 };
16774
16775 /**
16776 * Bind key down listener.
16777 *
16778 * @private
16779 */
16780 OO.ui.PopupWidget.prototype.bindKeyDownListener = function () {
16781 OO.ui.addCaptureEventListener( this.getElementWindow(), 'keydown', this.onDocumentKeyDownHandler );
16782 };
16783
16784 /**
16785 * Unbind key down listener.
16786 *
16787 * @private
16788 */
16789 OO.ui.PopupWidget.prototype.unbindKeyDownListener = function () {
16790 OO.ui.removeCaptureEventListener( this.getElementWindow(), 'keydown', this.onDocumentKeyDownHandler );
16791 };
16792
16793 /**
16794 * Show, hide, or toggle the visibility of the anchor.
16795 *
16796 * @param {boolean} [show] Show anchor, omit to toggle
16797 */
16798 OO.ui.PopupWidget.prototype.toggleAnchor = function ( show ) {
16799 show = show === undefined ? !this.anchored : !!show;
16800
16801 if ( this.anchored !== show ) {
16802 if ( show ) {
16803 this.$element.addClass( 'oo-ui-popupWidget-anchored' );
16804 } else {
16805 this.$element.removeClass( 'oo-ui-popupWidget-anchored' );
16806 }
16807 this.anchored = show;
16808 }
16809 };
16810
16811 /**
16812 * Check if the anchor is visible.
16813 *
16814 * @return {boolean} Anchor is visible
16815 */
16816 OO.ui.PopupWidget.prototype.hasAnchor = function () {
16817 return this.anchor;
16818 };
16819
16820 /**
16821 * @inheritdoc
16822 */
16823 OO.ui.PopupWidget.prototype.toggle = function ( show ) {
16824 show = show === undefined ? !this.isVisible() : !!show;
16825
16826 var change = show !== this.isVisible();
16827
16828 // Parent method
16829 OO.ui.PopupWidget.parent.prototype.toggle.call( this, show );
16830
16831 if ( change ) {
16832 if ( show ) {
16833 if ( this.autoClose ) {
16834 this.bindMouseDownListener();
16835 this.bindKeyDownListener();
16836 }
16837 this.updateDimensions();
16838 this.toggleClipping( true );
16839 } else {
16840 this.toggleClipping( false );
16841 if ( this.autoClose ) {
16842 this.unbindMouseDownListener();
16843 this.unbindKeyDownListener();
16844 }
16845 }
16846 }
16847
16848 return this;
16849 };
16850
16851 /**
16852 * Set the size of the popup.
16853 *
16854 * Changing the size may also change the popup's position depending on the alignment.
16855 *
16856 * @param {number} width Width in pixels
16857 * @param {number} height Height in pixels
16858 * @param {boolean} [transition=false] Use a smooth transition
16859 * @chainable
16860 */
16861 OO.ui.PopupWidget.prototype.setSize = function ( width, height, transition ) {
16862 this.width = width;
16863 this.height = height !== undefined ? height : null;
16864 if ( this.isVisible() ) {
16865 this.updateDimensions( transition );
16866 }
16867 };
16868
16869 /**
16870 * Update the size and position.
16871 *
16872 * Only use this to keep the popup properly anchored. Use #setSize to change the size, and this will
16873 * be called automatically.
16874 *
16875 * @param {boolean} [transition=false] Use a smooth transition
16876 * @chainable
16877 */
16878 OO.ui.PopupWidget.prototype.updateDimensions = function ( transition ) {
16879 var popupOffset, originOffset, containerLeft, containerWidth, containerRight,
16880 popupLeft, popupRight, overlapLeft, overlapRight, anchorWidth,
16881 align = this.align,
16882 widget = this;
16883
16884 if ( !this.$container ) {
16885 // Lazy-initialize $container if not specified in constructor
16886 this.$container = $( this.getClosestScrollableElementContainer() );
16887 }
16888
16889 // Set height and width before measuring things, since it might cause our measurements
16890 // to change (e.g. due to scrollbars appearing or disappearing)
16891 this.$popup.css( {
16892 width: this.width,
16893 height: this.height !== null ? this.height : 'auto'
16894 } );
16895
16896 // If we are in RTL, we need to flip the alignment, unless it is center
16897 if ( align === 'forwards' || align === 'backwards' ) {
16898 if ( this.$container.css( 'direction' ) === 'rtl' ) {
16899 align = ( { forwards: 'force-left', backwards: 'force-right' } )[ this.align ];
16900 } else {
16901 align = ( { forwards: 'force-right', backwards: 'force-left' } )[ this.align ];
16902 }
16903
16904 }
16905
16906 // Compute initial popupOffset based on alignment
16907 popupOffset = this.width * ( { 'force-left': -1, center: -0.5, 'force-right': 0 } )[ align ];
16908
16909 // Figure out if this will cause the popup to go beyond the edge of the container
16910 originOffset = this.$element.offset().left;
16911 containerLeft = this.$container.offset().left;
16912 containerWidth = this.$container.innerWidth();
16913 containerRight = containerLeft + containerWidth;
16914 popupLeft = popupOffset - this.containerPadding;
16915 popupRight = popupOffset + this.containerPadding + this.width + this.containerPadding;
16916 overlapLeft = ( originOffset + popupLeft ) - containerLeft;
16917 overlapRight = containerRight - ( originOffset + popupRight );
16918
16919 // Adjust offset to make the popup not go beyond the edge, if needed
16920 if ( overlapRight < 0 ) {
16921 popupOffset += overlapRight;
16922 } else if ( overlapLeft < 0 ) {
16923 popupOffset -= overlapLeft;
16924 }
16925
16926 // Adjust offset to avoid anchor being rendered too close to the edge
16927 // $anchor.width() doesn't work with the pure CSS anchor (returns 0)
16928 // TODO: Find a measurement that works for CSS anchors and image anchors
16929 anchorWidth = this.$anchor[ 0 ].scrollWidth * 2;
16930 if ( popupOffset + this.width < anchorWidth ) {
16931 popupOffset = anchorWidth - this.width;
16932 } else if ( -popupOffset < anchorWidth ) {
16933 popupOffset = -anchorWidth;
16934 }
16935
16936 // Prevent transition from being interrupted
16937 clearTimeout( this.transitionTimeout );
16938 if ( transition ) {
16939 // Enable transition
16940 this.$element.addClass( 'oo-ui-popupWidget-transitioning' );
16941 }
16942
16943 // Position body relative to anchor
16944 this.$popup.css( 'margin-left', popupOffset );
16945
16946 if ( transition ) {
16947 // Prevent transitioning after transition is complete
16948 this.transitionTimeout = setTimeout( function () {
16949 widget.$element.removeClass( 'oo-ui-popupWidget-transitioning' );
16950 }, 200 );
16951 } else {
16952 // Prevent transitioning immediately
16953 this.$element.removeClass( 'oo-ui-popupWidget-transitioning' );
16954 }
16955
16956 // Reevaluate clipping state since we've relocated and resized the popup
16957 this.clip();
16958
16959 return this;
16960 };
16961
16962 /**
16963 * Set popup alignment
16964 * @param {string} align Alignment of the popup, `center`, `force-left`, `force-right`,
16965 * `backwards` or `forwards`.
16966 */
16967 OO.ui.PopupWidget.prototype.setAlignment = function ( align ) {
16968 // Validate alignment and transform deprecated values
16969 if ( [ 'left', 'right', 'force-left', 'force-right', 'backwards', 'forwards', 'center' ].indexOf( align ) > -1 ) {
16970 this.align = { left: 'force-right', right: 'force-left' }[ align ] || align;
16971 } else {
16972 this.align = 'center';
16973 }
16974 };
16975
16976 /**
16977 * Get popup alignment
16978 * @return {string} align Alignment of the popup, `center`, `force-left`, `force-right`,
16979 * `backwards` or `forwards`.
16980 */
16981 OO.ui.PopupWidget.prototype.getAlignment = function () {
16982 return this.align;
16983 };
16984
16985 /**
16986 * Progress bars visually display the status of an operation, such as a download,
16987 * and can be either determinate or indeterminate:
16988 *
16989 * - **determinate** process bars show the percent of an operation that is complete.
16990 *
16991 * - **indeterminate** process bars use a visual display of motion to indicate that an operation
16992 * is taking place. Because the extent of an indeterminate operation is unknown, the bar does
16993 * not use percentages.
16994 *
16995 * The value of the `progress` configuration determines whether the bar is determinate or indeterminate.
16996 *
16997 * @example
16998 * // Examples of determinate and indeterminate progress bars.
16999 * var progressBar1 = new OO.ui.ProgressBarWidget( {
17000 * progress: 33
17001 * } );
17002 * var progressBar2 = new OO.ui.ProgressBarWidget();
17003 *
17004 * // Create a FieldsetLayout to layout progress bars
17005 * var fieldset = new OO.ui.FieldsetLayout;
17006 * fieldset.addItems( [
17007 * new OO.ui.FieldLayout( progressBar1, {label: 'Determinate', align: 'top'}),
17008 * new OO.ui.FieldLayout( progressBar2, {label: 'Indeterminate', align: 'top'})
17009 * ] );
17010 * $( 'body' ).append( fieldset.$element );
17011 *
17012 * @class
17013 * @extends OO.ui.Widget
17014 *
17015 * @constructor
17016 * @param {Object} [config] Configuration options
17017 * @cfg {number|boolean} [progress=false] The type of progress bar (determinate or indeterminate).
17018 * To create a determinate progress bar, specify a number that reflects the initial percent complete.
17019 * By default, the progress bar is indeterminate.
17020 */
17021 OO.ui.ProgressBarWidget = function OoUiProgressBarWidget( config ) {
17022 // Configuration initialization
17023 config = config || {};
17024
17025 // Parent constructor
17026 OO.ui.ProgressBarWidget.parent.call( this, config );
17027
17028 // Properties
17029 this.$bar = $( '<div>' );
17030 this.progress = null;
17031
17032 // Initialization
17033 this.setProgress( config.progress !== undefined ? config.progress : false );
17034 this.$bar.addClass( 'oo-ui-progressBarWidget-bar' );
17035 this.$element
17036 .attr( {
17037 role: 'progressbar',
17038 'aria-valuemin': 0,
17039 'aria-valuemax': 100
17040 } )
17041 .addClass( 'oo-ui-progressBarWidget' )
17042 .append( this.$bar );
17043 };
17044
17045 /* Setup */
17046
17047 OO.inheritClass( OO.ui.ProgressBarWidget, OO.ui.Widget );
17048
17049 /* Static Properties */
17050
17051 OO.ui.ProgressBarWidget.static.tagName = 'div';
17052
17053 /* Methods */
17054
17055 /**
17056 * Get the percent of the progress that has been completed. Indeterminate progresses will return `false`.
17057 *
17058 * @return {number|boolean} Progress percent
17059 */
17060 OO.ui.ProgressBarWidget.prototype.getProgress = function () {
17061 return this.progress;
17062 };
17063
17064 /**
17065 * Set the percent of the process completed or `false` for an indeterminate process.
17066 *
17067 * @param {number|boolean} progress Progress percent or `false` for indeterminate
17068 */
17069 OO.ui.ProgressBarWidget.prototype.setProgress = function ( progress ) {
17070 this.progress = progress;
17071
17072 if ( progress !== false ) {
17073 this.$bar.css( 'width', this.progress + '%' );
17074 this.$element.attr( 'aria-valuenow', this.progress );
17075 } else {
17076 this.$bar.css( 'width', '' );
17077 this.$element.removeAttr( 'aria-valuenow' );
17078 }
17079 this.$element.toggleClass( 'oo-ui-progressBarWidget-indeterminate', !progress );
17080 };
17081
17082 /**
17083 * SearchWidgets combine a {@link OO.ui.TextInputWidget text input field}, where users can type a search query,
17084 * and a menu of search results, which is displayed beneath the query
17085 * field. Unlike {@link OO.ui.mixin.LookupElement lookup menus}, search result menus are always visible to the user.
17086 * Users can choose an item from the menu or type a query into the text field to search for a matching result item.
17087 * In general, search widgets are used inside a separate {@link OO.ui.Dialog dialog} window.
17088 *
17089 * Each time the query is changed, the search result menu is cleared and repopulated. Please see
17090 * the [OOjs UI demos][1] for an example.
17091 *
17092 * [1]: https://tools.wmflabs.org/oojs-ui/oojs-ui/demos/#dialogs-mediawiki-vector-ltr
17093 *
17094 * @class
17095 * @extends OO.ui.Widget
17096 *
17097 * @constructor
17098 * @param {Object} [config] Configuration options
17099 * @cfg {string|jQuery} [placeholder] Placeholder text for query input
17100 * @cfg {string} [value] Initial query value
17101 */
17102 OO.ui.SearchWidget = function OoUiSearchWidget( config ) {
17103 // Configuration initialization
17104 config = config || {};
17105
17106 // Parent constructor
17107 OO.ui.SearchWidget.parent.call( this, config );
17108
17109 // Properties
17110 this.query = new OO.ui.TextInputWidget( {
17111 icon: 'search',
17112 placeholder: config.placeholder,
17113 value: config.value
17114 } );
17115 this.results = new OO.ui.SelectWidget();
17116 this.$query = $( '<div>' );
17117 this.$results = $( '<div>' );
17118
17119 // Events
17120 this.query.connect( this, {
17121 change: 'onQueryChange',
17122 enter: 'onQueryEnter'
17123 } );
17124 this.query.$input.on( 'keydown', this.onQueryKeydown.bind( this ) );
17125
17126 // Initialization
17127 this.$query
17128 .addClass( 'oo-ui-searchWidget-query' )
17129 .append( this.query.$element );
17130 this.$results
17131 .addClass( 'oo-ui-searchWidget-results' )
17132 .append( this.results.$element );
17133 this.$element
17134 .addClass( 'oo-ui-searchWidget' )
17135 .append( this.$results, this.$query );
17136 };
17137
17138 /* Setup */
17139
17140 OO.inheritClass( OO.ui.SearchWidget, OO.ui.Widget );
17141
17142 /* Methods */
17143
17144 /**
17145 * Handle query key down events.
17146 *
17147 * @private
17148 * @param {jQuery.Event} e Key down event
17149 */
17150 OO.ui.SearchWidget.prototype.onQueryKeydown = function ( e ) {
17151 var highlightedItem, nextItem,
17152 dir = e.which === OO.ui.Keys.DOWN ? 1 : ( e.which === OO.ui.Keys.UP ? -1 : 0 );
17153
17154 if ( dir ) {
17155 highlightedItem = this.results.getHighlightedItem();
17156 if ( !highlightedItem ) {
17157 highlightedItem = this.results.getSelectedItem();
17158 }
17159 nextItem = this.results.getRelativeSelectableItem( highlightedItem, dir );
17160 this.results.highlightItem( nextItem );
17161 nextItem.scrollElementIntoView();
17162 }
17163 };
17164
17165 /**
17166 * Handle select widget select events.
17167 *
17168 * Clears existing results. Subclasses should repopulate items according to new query.
17169 *
17170 * @private
17171 * @param {string} value New value
17172 */
17173 OO.ui.SearchWidget.prototype.onQueryChange = function () {
17174 // Reset
17175 this.results.clearItems();
17176 };
17177
17178 /**
17179 * Handle select widget enter key events.
17180 *
17181 * Chooses highlighted item.
17182 *
17183 * @private
17184 * @param {string} value New value
17185 */
17186 OO.ui.SearchWidget.prototype.onQueryEnter = function () {
17187 // Reset
17188 this.results.chooseItem( this.results.getHighlightedItem() );
17189 };
17190
17191 /**
17192 * Get the query input.
17193 *
17194 * @return {OO.ui.TextInputWidget} Query input
17195 */
17196 OO.ui.SearchWidget.prototype.getQuery = function () {
17197 return this.query;
17198 };
17199
17200 /**
17201 * Get the search results menu.
17202 *
17203 * @return {OO.ui.SelectWidget} Menu of search results
17204 */
17205 OO.ui.SearchWidget.prototype.getResults = function () {
17206 return this.results;
17207 };
17208
17209 /**
17210 * A SelectWidget is of a generic selection of options. The OOjs UI library contains several types of
17211 * select widgets, including {@link OO.ui.ButtonSelectWidget button selects},
17212 * {@link OO.ui.RadioSelectWidget radio selects}, and {@link OO.ui.MenuSelectWidget
17213 * menu selects}.
17214 *
17215 * This class should be used together with OO.ui.OptionWidget or OO.ui.DecoratedOptionWidget. For more
17216 * information, please see the [OOjs UI documentation on MediaWiki][1].
17217 *
17218 * @example
17219 * // Example of a select widget with three options
17220 * var select = new OO.ui.SelectWidget( {
17221 * items: [
17222 * new OO.ui.OptionWidget( {
17223 * data: 'a',
17224 * label: 'Option One',
17225 * } ),
17226 * new OO.ui.OptionWidget( {
17227 * data: 'b',
17228 * label: 'Option Two',
17229 * } ),
17230 * new OO.ui.OptionWidget( {
17231 * data: 'c',
17232 * label: 'Option Three',
17233 * } )
17234 * ]
17235 * } );
17236 * $( 'body' ).append( select.$element );
17237 *
17238 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
17239 *
17240 * @abstract
17241 * @class
17242 * @extends OO.ui.Widget
17243 * @mixins OO.ui.mixin.GroupWidget
17244 *
17245 * @constructor
17246 * @param {Object} [config] Configuration options
17247 * @cfg {OO.ui.OptionWidget[]} [items] An array of options to add to the select.
17248 * Options are created with {@link OO.ui.OptionWidget OptionWidget} classes. See
17249 * the [OOjs UI documentation on MediaWiki] [2] for examples.
17250 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
17251 */
17252 OO.ui.SelectWidget = function OoUiSelectWidget( config ) {
17253 // Configuration initialization
17254 config = config || {};
17255
17256 // Parent constructor
17257 OO.ui.SelectWidget.parent.call( this, config );
17258
17259 // Mixin constructors
17260 OO.ui.mixin.GroupWidget.call( this, $.extend( {}, config, { $group: this.$element } ) );
17261
17262 // Properties
17263 this.pressed = false;
17264 this.selecting = null;
17265 this.onMouseUpHandler = this.onMouseUp.bind( this );
17266 this.onMouseMoveHandler = this.onMouseMove.bind( this );
17267 this.onKeyDownHandler = this.onKeyDown.bind( this );
17268 this.onKeyPressHandler = this.onKeyPress.bind( this );
17269 this.keyPressBuffer = '';
17270 this.keyPressBufferTimer = null;
17271
17272 // Events
17273 this.connect( this, {
17274 toggle: 'onToggle'
17275 } );
17276 this.$element.on( {
17277 mousedown: this.onMouseDown.bind( this ),
17278 mouseover: this.onMouseOver.bind( this ),
17279 mouseleave: this.onMouseLeave.bind( this )
17280 } );
17281
17282 // Initialization
17283 this.$element
17284 .addClass( 'oo-ui-selectWidget oo-ui-selectWidget-depressed' )
17285 .attr( 'role', 'listbox' );
17286 if ( Array.isArray( config.items ) ) {
17287 this.addItems( config.items );
17288 }
17289 };
17290
17291 /* Setup */
17292
17293 OO.inheritClass( OO.ui.SelectWidget, OO.ui.Widget );
17294
17295 // Need to mixin base class as well
17296 OO.mixinClass( OO.ui.SelectWidget, OO.ui.mixin.GroupElement );
17297 OO.mixinClass( OO.ui.SelectWidget, OO.ui.mixin.GroupWidget );
17298
17299 /* Static */
17300 OO.ui.SelectWidget.static.passAllFilter = function () {
17301 return true;
17302 };
17303
17304 /* Events */
17305
17306 /**
17307 * @event highlight
17308 *
17309 * A `highlight` event is emitted when the highlight is changed with the #highlightItem method.
17310 *
17311 * @param {OO.ui.OptionWidget|null} item Highlighted item
17312 */
17313
17314 /**
17315 * @event press
17316 *
17317 * A `press` event is emitted when the #pressItem method is used to programmatically modify the
17318 * pressed state of an option.
17319 *
17320 * @param {OO.ui.OptionWidget|null} item Pressed item
17321 */
17322
17323 /**
17324 * @event select
17325 *
17326 * A `select` event is emitted when the selection is modified programmatically with the #selectItem method.
17327 *
17328 * @param {OO.ui.OptionWidget|null} item Selected item
17329 */
17330
17331 /**
17332 * @event choose
17333 * A `choose` event is emitted when an item is chosen with the #chooseItem method.
17334 * @param {OO.ui.OptionWidget} item Chosen item
17335 */
17336
17337 /**
17338 * @event add
17339 *
17340 * An `add` event is emitted when options are added to the select with the #addItems method.
17341 *
17342 * @param {OO.ui.OptionWidget[]} items Added items
17343 * @param {number} index Index of insertion point
17344 */
17345
17346 /**
17347 * @event remove
17348 *
17349 * A `remove` event is emitted when options are removed from the select with the #clearItems
17350 * or #removeItems methods.
17351 *
17352 * @param {OO.ui.OptionWidget[]} items Removed items
17353 */
17354
17355 /* Methods */
17356
17357 /**
17358 * Handle mouse down events.
17359 *
17360 * @private
17361 * @param {jQuery.Event} e Mouse down event
17362 */
17363 OO.ui.SelectWidget.prototype.onMouseDown = function ( e ) {
17364 var item;
17365
17366 if ( !this.isDisabled() && e.which === 1 ) {
17367 this.togglePressed( true );
17368 item = this.getTargetItem( e );
17369 if ( item && item.isSelectable() ) {
17370 this.pressItem( item );
17371 this.selecting = item;
17372 OO.ui.addCaptureEventListener(
17373 this.getElementDocument(),
17374 'mouseup',
17375 this.onMouseUpHandler
17376 );
17377 OO.ui.addCaptureEventListener(
17378 this.getElementDocument(),
17379 'mousemove',
17380 this.onMouseMoveHandler
17381 );
17382 }
17383 }
17384 return false;
17385 };
17386
17387 /**
17388 * Handle mouse up events.
17389 *
17390 * @private
17391 * @param {jQuery.Event} e Mouse up event
17392 */
17393 OO.ui.SelectWidget.prototype.onMouseUp = function ( e ) {
17394 var item;
17395
17396 this.togglePressed( false );
17397 if ( !this.selecting ) {
17398 item = this.getTargetItem( e );
17399 if ( item && item.isSelectable() ) {
17400 this.selecting = item;
17401 }
17402 }
17403 if ( !this.isDisabled() && e.which === 1 && this.selecting ) {
17404 this.pressItem( null );
17405 this.chooseItem( this.selecting );
17406 this.selecting = null;
17407 }
17408
17409 OO.ui.removeCaptureEventListener( this.getElementDocument(), 'mouseup',
17410 this.onMouseUpHandler );
17411 OO.ui.removeCaptureEventListener( this.getElementDocument(), 'mousemove',
17412 this.onMouseMoveHandler );
17413
17414 return false;
17415 };
17416
17417 /**
17418 * Handle mouse move events.
17419 *
17420 * @private
17421 * @param {jQuery.Event} e Mouse move event
17422 */
17423 OO.ui.SelectWidget.prototype.onMouseMove = function ( e ) {
17424 var item;
17425
17426 if ( !this.isDisabled() && this.pressed ) {
17427 item = this.getTargetItem( e );
17428 if ( item && item !== this.selecting && item.isSelectable() ) {
17429 this.pressItem( item );
17430 this.selecting = item;
17431 }
17432 }
17433 return false;
17434 };
17435
17436 /**
17437 * Handle mouse over events.
17438 *
17439 * @private
17440 * @param {jQuery.Event} e Mouse over event
17441 */
17442 OO.ui.SelectWidget.prototype.onMouseOver = function ( e ) {
17443 var item;
17444
17445 if ( !this.isDisabled() ) {
17446 item = this.getTargetItem( e );
17447 this.highlightItem( item && item.isHighlightable() ? item : null );
17448 }
17449 return false;
17450 };
17451
17452 /**
17453 * Handle mouse leave events.
17454 *
17455 * @private
17456 * @param {jQuery.Event} e Mouse over event
17457 */
17458 OO.ui.SelectWidget.prototype.onMouseLeave = function () {
17459 if ( !this.isDisabled() ) {
17460 this.highlightItem( null );
17461 }
17462 return false;
17463 };
17464
17465 /**
17466 * Handle key down events.
17467 *
17468 * @protected
17469 * @param {jQuery.Event} e Key down event
17470 */
17471 OO.ui.SelectWidget.prototype.onKeyDown = function ( e ) {
17472 var nextItem,
17473 handled = false,
17474 currentItem = this.getHighlightedItem() || this.getSelectedItem();
17475
17476 if ( !this.isDisabled() && this.isVisible() ) {
17477 switch ( e.keyCode ) {
17478 case OO.ui.Keys.ENTER:
17479 if ( currentItem && currentItem.constructor.static.highlightable ) {
17480 // Was only highlighted, now let's select it. No-op if already selected.
17481 this.chooseItem( currentItem );
17482 handled = true;
17483 }
17484 break;
17485 case OO.ui.Keys.UP:
17486 case OO.ui.Keys.LEFT:
17487 this.clearKeyPressBuffer();
17488 nextItem = this.getRelativeSelectableItem( currentItem, -1 );
17489 handled = true;
17490 break;
17491 case OO.ui.Keys.DOWN:
17492 case OO.ui.Keys.RIGHT:
17493 this.clearKeyPressBuffer();
17494 nextItem = this.getRelativeSelectableItem( currentItem, 1 );
17495 handled = true;
17496 break;
17497 case OO.ui.Keys.ESCAPE:
17498 case OO.ui.Keys.TAB:
17499 if ( currentItem && currentItem.constructor.static.highlightable ) {
17500 currentItem.setHighlighted( false );
17501 }
17502 this.unbindKeyDownListener();
17503 this.unbindKeyPressListener();
17504 // Don't prevent tabbing away / defocusing
17505 handled = false;
17506 break;
17507 }
17508
17509 if ( nextItem ) {
17510 if ( nextItem.constructor.static.highlightable ) {
17511 this.highlightItem( nextItem );
17512 } else {
17513 this.chooseItem( nextItem );
17514 }
17515 nextItem.scrollElementIntoView();
17516 }
17517
17518 if ( handled ) {
17519 // Can't just return false, because e is not always a jQuery event
17520 e.preventDefault();
17521 e.stopPropagation();
17522 }
17523 }
17524 };
17525
17526 /**
17527 * Bind key down listener.
17528 *
17529 * @protected
17530 */
17531 OO.ui.SelectWidget.prototype.bindKeyDownListener = function () {
17532 OO.ui.addCaptureEventListener( this.getElementWindow(), 'keydown', this.onKeyDownHandler );
17533 };
17534
17535 /**
17536 * Unbind key down listener.
17537 *
17538 * @protected
17539 */
17540 OO.ui.SelectWidget.prototype.unbindKeyDownListener = function () {
17541 OO.ui.removeCaptureEventListener( this.getElementWindow(), 'keydown', this.onKeyDownHandler );
17542 };
17543
17544 /**
17545 * Clear the key-press buffer
17546 *
17547 * @protected
17548 */
17549 OO.ui.SelectWidget.prototype.clearKeyPressBuffer = function () {
17550 if ( this.keyPressBufferTimer ) {
17551 clearTimeout( this.keyPressBufferTimer );
17552 this.keyPressBufferTimer = null;
17553 }
17554 this.keyPressBuffer = '';
17555 };
17556
17557 /**
17558 * Handle key press events.
17559 *
17560 * @protected
17561 * @param {jQuery.Event} e Key press event
17562 */
17563 OO.ui.SelectWidget.prototype.onKeyPress = function ( e ) {
17564 var c, filter, item;
17565
17566 if ( !e.charCode ) {
17567 if ( e.keyCode === OO.ui.Keys.BACKSPACE && this.keyPressBuffer !== '' ) {
17568 this.keyPressBuffer = this.keyPressBuffer.substr( 0, this.keyPressBuffer.length - 1 );
17569 return false;
17570 }
17571 return;
17572 }
17573 if ( String.fromCodePoint ) {
17574 c = String.fromCodePoint( e.charCode );
17575 } else {
17576 c = String.fromCharCode( e.charCode );
17577 }
17578
17579 if ( this.keyPressBufferTimer ) {
17580 clearTimeout( this.keyPressBufferTimer );
17581 }
17582 this.keyPressBufferTimer = setTimeout( this.clearKeyPressBuffer.bind( this ), 1500 );
17583
17584 item = this.getHighlightedItem() || this.getSelectedItem();
17585
17586 if ( this.keyPressBuffer === c ) {
17587 // Common (if weird) special case: typing "xxxx" will cycle through all
17588 // the items beginning with "x".
17589 if ( item ) {
17590 item = this.getRelativeSelectableItem( item, 1 );
17591 }
17592 } else {
17593 this.keyPressBuffer += c;
17594 }
17595
17596 filter = this.getItemMatcher( this.keyPressBuffer, false );
17597 if ( !item || !filter( item ) ) {
17598 item = this.getRelativeSelectableItem( item, 1, filter );
17599 }
17600 if ( item ) {
17601 if ( item.constructor.static.highlightable ) {
17602 this.highlightItem( item );
17603 } else {
17604 this.chooseItem( item );
17605 }
17606 item.scrollElementIntoView();
17607 }
17608
17609 return false;
17610 };
17611
17612 /**
17613 * Get a matcher for the specific string
17614 *
17615 * @protected
17616 * @param {string} s String to match against items
17617 * @param {boolean} [exact=false] Only accept exact matches
17618 * @return {Function} function ( OO.ui.OptionItem ) => boolean
17619 */
17620 OO.ui.SelectWidget.prototype.getItemMatcher = function ( s, exact ) {
17621 var re;
17622
17623 if ( s.normalize ) {
17624 s = s.normalize();
17625 }
17626 s = exact ? s.trim() : s.replace( /^\s+/, '' );
17627 re = '^\\s*' + s.replace( /([\\{}()|.?*+\-\^$\[\]])/g, '\\$1' ).replace( /\s+/g, '\\s+' );
17628 if ( exact ) {
17629 re += '\\s*$';
17630 }
17631 re = new RegExp( re, 'i' );
17632 return function ( item ) {
17633 var l = item.getLabel();
17634 if ( typeof l !== 'string' ) {
17635 l = item.$label.text();
17636 }
17637 if ( l.normalize ) {
17638 l = l.normalize();
17639 }
17640 return re.test( l );
17641 };
17642 };
17643
17644 /**
17645 * Bind key press listener.
17646 *
17647 * @protected
17648 */
17649 OO.ui.SelectWidget.prototype.bindKeyPressListener = function () {
17650 OO.ui.addCaptureEventListener( this.getElementWindow(), 'keypress', this.onKeyPressHandler );
17651 };
17652
17653 /**
17654 * Unbind key down listener.
17655 *
17656 * If you override this, be sure to call this.clearKeyPressBuffer() from your
17657 * implementation.
17658 *
17659 * @protected
17660 */
17661 OO.ui.SelectWidget.prototype.unbindKeyPressListener = function () {
17662 OO.ui.removeCaptureEventListener( this.getElementWindow(), 'keypress', this.onKeyPressHandler );
17663 this.clearKeyPressBuffer();
17664 };
17665
17666 /**
17667 * Visibility change handler
17668 *
17669 * @protected
17670 * @param {boolean} visible
17671 */
17672 OO.ui.SelectWidget.prototype.onToggle = function ( visible ) {
17673 if ( !visible ) {
17674 this.clearKeyPressBuffer();
17675 }
17676 };
17677
17678 /**
17679 * Get the closest item to a jQuery.Event.
17680 *
17681 * @private
17682 * @param {jQuery.Event} e
17683 * @return {OO.ui.OptionWidget|null} Outline item widget, `null` if none was found
17684 */
17685 OO.ui.SelectWidget.prototype.getTargetItem = function ( e ) {
17686 return $( e.target ).closest( '.oo-ui-optionWidget' ).data( 'oo-ui-optionWidget' ) || null;
17687 };
17688
17689 /**
17690 * Get selected item.
17691 *
17692 * @return {OO.ui.OptionWidget|null} Selected item, `null` if no item is selected
17693 */
17694 OO.ui.SelectWidget.prototype.getSelectedItem = function () {
17695 var i, len;
17696
17697 for ( i = 0, len = this.items.length; i < len; i++ ) {
17698 if ( this.items[ i ].isSelected() ) {
17699 return this.items[ i ];
17700 }
17701 }
17702 return null;
17703 };
17704
17705 /**
17706 * Get highlighted item.
17707 *
17708 * @return {OO.ui.OptionWidget|null} Highlighted item, `null` if no item is highlighted
17709 */
17710 OO.ui.SelectWidget.prototype.getHighlightedItem = function () {
17711 var i, len;
17712
17713 for ( i = 0, len = this.items.length; i < len; i++ ) {
17714 if ( this.items[ i ].isHighlighted() ) {
17715 return this.items[ i ];
17716 }
17717 }
17718 return null;
17719 };
17720
17721 /**
17722 * Toggle pressed state.
17723 *
17724 * Press is a state that occurs when a user mouses down on an item, but
17725 * has not yet let go of the mouse. The item may appear selected, but it will not be selected
17726 * until the user releases the mouse.
17727 *
17728 * @param {boolean} pressed An option is being pressed
17729 */
17730 OO.ui.SelectWidget.prototype.togglePressed = function ( pressed ) {
17731 if ( pressed === undefined ) {
17732 pressed = !this.pressed;
17733 }
17734 if ( pressed !== this.pressed ) {
17735 this.$element
17736 .toggleClass( 'oo-ui-selectWidget-pressed', pressed )
17737 .toggleClass( 'oo-ui-selectWidget-depressed', !pressed );
17738 this.pressed = pressed;
17739 }
17740 };
17741
17742 /**
17743 * Highlight an option. If the `item` param is omitted, no options will be highlighted
17744 * and any existing highlight will be removed. The highlight is mutually exclusive.
17745 *
17746 * @param {OO.ui.OptionWidget} [item] Item to highlight, omit for no highlight
17747 * @fires highlight
17748 * @chainable
17749 */
17750 OO.ui.SelectWidget.prototype.highlightItem = function ( item ) {
17751 var i, len, highlighted,
17752 changed = false;
17753
17754 for ( i = 0, len = this.items.length; i < len; i++ ) {
17755 highlighted = this.items[ i ] === item;
17756 if ( this.items[ i ].isHighlighted() !== highlighted ) {
17757 this.items[ i ].setHighlighted( highlighted );
17758 changed = true;
17759 }
17760 }
17761 if ( changed ) {
17762 this.emit( 'highlight', item );
17763 }
17764
17765 return this;
17766 };
17767
17768 /**
17769 * Fetch an item by its label.
17770 *
17771 * @param {string} label Label of the item to select.
17772 * @param {boolean} [prefix=false] Allow a prefix match, if only a single item matches
17773 * @return {OO.ui.Element|null} Item with equivalent label, `null` if none exists
17774 */
17775 OO.ui.SelectWidget.prototype.getItemFromLabel = function ( label, prefix ) {
17776 var i, item, found,
17777 len = this.items.length,
17778 filter = this.getItemMatcher( label, true );
17779
17780 for ( i = 0; i < len; i++ ) {
17781 item = this.items[i];
17782 if ( item instanceof OO.ui.OptionWidget && item.isSelectable() && filter( item ) ) {
17783 return item;
17784 }
17785 }
17786
17787 if ( prefix ) {
17788 found = null;
17789 filter = this.getItemMatcher( label, false );
17790 for ( i = 0; i < len; i++ ) {
17791 item = this.items[i];
17792 if ( item instanceof OO.ui.OptionWidget && item.isSelectable() && filter( item ) ) {
17793 if ( found ) {
17794 return null;
17795 }
17796 found = item;
17797 }
17798 }
17799 if ( found ) {
17800 return found;
17801 }
17802 }
17803
17804 return null;
17805 };
17806
17807 /**
17808 * Programmatically select an option by its label. If the item does not exist,
17809 * all options will be deselected.
17810 *
17811 * @param {string} [label] Label of the item to select.
17812 * @param {boolean} [prefix=false] Allow a prefix match, if only a single item matches
17813 * @fires select
17814 * @chainable
17815 */
17816 OO.ui.SelectWidget.prototype.selectItemByLabel = function ( label, prefix ) {
17817 var itemFromLabel = this.getItemFromLabel( label, !!prefix );
17818 if ( label === undefined || !itemFromLabel ) {
17819 return this.selectItem();
17820 }
17821 return this.selectItem( itemFromLabel );
17822 };
17823
17824 /**
17825 * Programmatically select an option by its data. If the `data` parameter is omitted,
17826 * or if the item does not exist, all options will be deselected.
17827 *
17828 * @param {Object|string} [data] Value of the item to select, omit to deselect all
17829 * @fires select
17830 * @chainable
17831 */
17832 OO.ui.SelectWidget.prototype.selectItemByData = function ( data ) {
17833 var itemFromData = this.getItemFromData( data );
17834 if ( data === undefined || !itemFromData ) {
17835 return this.selectItem();
17836 }
17837 return this.selectItem( itemFromData );
17838 };
17839
17840 /**
17841 * Programmatically select an option by its reference. If the `item` parameter is omitted,
17842 * all options will be deselected.
17843 *
17844 * @param {OO.ui.OptionWidget} [item] Item to select, omit to deselect all
17845 * @fires select
17846 * @chainable
17847 */
17848 OO.ui.SelectWidget.prototype.selectItem = function ( item ) {
17849 var i, len, selected,
17850 changed = false;
17851
17852 for ( i = 0, len = this.items.length; i < len; i++ ) {
17853 selected = this.items[ i ] === item;
17854 if ( this.items[ i ].isSelected() !== selected ) {
17855 this.items[ i ].setSelected( selected );
17856 changed = true;
17857 }
17858 }
17859 if ( changed ) {
17860 this.emit( 'select', item );
17861 }
17862
17863 return this;
17864 };
17865
17866 /**
17867 * Press an item.
17868 *
17869 * Press is a state that occurs when a user mouses down on an item, but has not
17870 * yet let go of the mouse. The item may appear selected, but it will not be selected until the user
17871 * releases the mouse.
17872 *
17873 * @param {OO.ui.OptionWidget} [item] Item to press, omit to depress all
17874 * @fires press
17875 * @chainable
17876 */
17877 OO.ui.SelectWidget.prototype.pressItem = function ( item ) {
17878 var i, len, pressed,
17879 changed = false;
17880
17881 for ( i = 0, len = this.items.length; i < len; i++ ) {
17882 pressed = this.items[ i ] === item;
17883 if ( this.items[ i ].isPressed() !== pressed ) {
17884 this.items[ i ].setPressed( pressed );
17885 changed = true;
17886 }
17887 }
17888 if ( changed ) {
17889 this.emit( 'press', item );
17890 }
17891
17892 return this;
17893 };
17894
17895 /**
17896 * Choose an item.
17897 *
17898 * Note that ‘choose’ should never be modified programmatically. A user can choose
17899 * an option with the keyboard or mouse and it becomes selected. To select an item programmatically,
17900 * use the #selectItem method.
17901 *
17902 * This method is identical to #selectItem, but may vary in subclasses that take additional action
17903 * when users choose an item with the keyboard or mouse.
17904 *
17905 * @param {OO.ui.OptionWidget} item Item to choose
17906 * @fires choose
17907 * @chainable
17908 */
17909 OO.ui.SelectWidget.prototype.chooseItem = function ( item ) {
17910 this.selectItem( item );
17911 this.emit( 'choose', item );
17912
17913 return this;
17914 };
17915
17916 /**
17917 * Get an option by its position relative to the specified item (or to the start of the option array,
17918 * if item is `null`). The direction in which to search through the option array is specified with a
17919 * number: -1 for reverse (the default) or 1 for forward. The method will return an option, or
17920 * `null` if there are no options in the array.
17921 *
17922 * @param {OO.ui.OptionWidget|null} item Item to describe the start position, or `null` to start at the beginning of the array.
17923 * @param {number} direction Direction to move in: -1 to move backward, 1 to move forward
17924 * @param {Function} filter Only consider items for which this function returns
17925 * true. Function takes an OO.ui.OptionWidget and returns a boolean.
17926 * @return {OO.ui.OptionWidget|null} Item at position, `null` if there are no items in the select
17927 */
17928 OO.ui.SelectWidget.prototype.getRelativeSelectableItem = function ( item, direction, filter ) {
17929 var currentIndex, nextIndex, i,
17930 increase = direction > 0 ? 1 : -1,
17931 len = this.items.length;
17932
17933 if ( !$.isFunction( filter ) ) {
17934 filter = OO.ui.SelectWidget.static.passAllFilter;
17935 }
17936
17937 if ( item instanceof OO.ui.OptionWidget ) {
17938 currentIndex = $.inArray( item, this.items );
17939 nextIndex = ( currentIndex + increase + len ) % len;
17940 } else {
17941 // If no item is selected and moving forward, start at the beginning.
17942 // If moving backward, start at the end.
17943 nextIndex = direction > 0 ? 0 : len - 1;
17944 }
17945
17946 for ( i = 0; i < len; i++ ) {
17947 item = this.items[ nextIndex ];
17948 if ( item instanceof OO.ui.OptionWidget && item.isSelectable() && filter( item ) ) {
17949 return item;
17950 }
17951 nextIndex = ( nextIndex + increase + len ) % len;
17952 }
17953 return null;
17954 };
17955
17956 /**
17957 * Get the next selectable item or `null` if there are no selectable items.
17958 * Disabled options and menu-section markers and breaks are not selectable.
17959 *
17960 * @return {OO.ui.OptionWidget|null} Item, `null` if there aren't any selectable items
17961 */
17962 OO.ui.SelectWidget.prototype.getFirstSelectableItem = function () {
17963 var i, len, item;
17964
17965 for ( i = 0, len = this.items.length; i < len; i++ ) {
17966 item = this.items[ i ];
17967 if ( item instanceof OO.ui.OptionWidget && item.isSelectable() ) {
17968 return item;
17969 }
17970 }
17971
17972 return null;
17973 };
17974
17975 /**
17976 * Add an array of options to the select. Optionally, an index number can be used to
17977 * specify an insertion point.
17978 *
17979 * @param {OO.ui.OptionWidget[]} items Items to add
17980 * @param {number} [index] Index to insert items after
17981 * @fires add
17982 * @chainable
17983 */
17984 OO.ui.SelectWidget.prototype.addItems = function ( items, index ) {
17985 // Mixin method
17986 OO.ui.mixin.GroupWidget.prototype.addItems.call( this, items, index );
17987
17988 // Always provide an index, even if it was omitted
17989 this.emit( 'add', items, index === undefined ? this.items.length - items.length - 1 : index );
17990
17991 return this;
17992 };
17993
17994 /**
17995 * Remove the specified array of options from the select. Options will be detached
17996 * from the DOM, not removed, so they can be reused later. To remove all options from
17997 * the select, you may wish to use the #clearItems method instead.
17998 *
17999 * @param {OO.ui.OptionWidget[]} items Items to remove
18000 * @fires remove
18001 * @chainable
18002 */
18003 OO.ui.SelectWidget.prototype.removeItems = function ( items ) {
18004 var i, len, item;
18005
18006 // Deselect items being removed
18007 for ( i = 0, len = items.length; i < len; i++ ) {
18008 item = items[ i ];
18009 if ( item.isSelected() ) {
18010 this.selectItem( null );
18011 }
18012 }
18013
18014 // Mixin method
18015 OO.ui.mixin.GroupWidget.prototype.removeItems.call( this, items );
18016
18017 this.emit( 'remove', items );
18018
18019 return this;
18020 };
18021
18022 /**
18023 * Clear all options from the select. Options will be detached from the DOM, not removed,
18024 * so that they can be reused later. To remove a subset of options from the select, use
18025 * the #removeItems method.
18026 *
18027 * @fires remove
18028 * @chainable
18029 */
18030 OO.ui.SelectWidget.prototype.clearItems = function () {
18031 var items = this.items.slice();
18032
18033 // Mixin method
18034 OO.ui.mixin.GroupWidget.prototype.clearItems.call( this );
18035
18036 // Clear selection
18037 this.selectItem( null );
18038
18039 this.emit( 'remove', items );
18040
18041 return this;
18042 };
18043
18044 /**
18045 * ButtonSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains
18046 * button options and is used together with
18047 * OO.ui.ButtonOptionWidget. The ButtonSelectWidget provides an interface for
18048 * highlighting, choosing, and selecting mutually exclusive options. Please see
18049 * the [OOjs UI documentation on MediaWiki] [1] for more information.
18050 *
18051 * @example
18052 * // Example: A ButtonSelectWidget that contains three ButtonOptionWidgets
18053 * var option1 = new OO.ui.ButtonOptionWidget( {
18054 * data: 1,
18055 * label: 'Option 1',
18056 * title: 'Button option 1'
18057 * } );
18058 *
18059 * var option2 = new OO.ui.ButtonOptionWidget( {
18060 * data: 2,
18061 * label: 'Option 2',
18062 * title: 'Button option 2'
18063 * } );
18064 *
18065 * var option3 = new OO.ui.ButtonOptionWidget( {
18066 * data: 3,
18067 * label: 'Option 3',
18068 * title: 'Button option 3'
18069 * } );
18070 *
18071 * var buttonSelect=new OO.ui.ButtonSelectWidget( {
18072 * items: [ option1, option2, option3 ]
18073 * } );
18074 * $( 'body' ).append( buttonSelect.$element );
18075 *
18076 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
18077 *
18078 * @class
18079 * @extends OO.ui.SelectWidget
18080 * @mixins OO.ui.mixin.TabIndexedElement
18081 *
18082 * @constructor
18083 * @param {Object} [config] Configuration options
18084 */
18085 OO.ui.ButtonSelectWidget = function OoUiButtonSelectWidget( config ) {
18086 // Parent constructor
18087 OO.ui.ButtonSelectWidget.parent.call( this, config );
18088
18089 // Mixin constructors
18090 OO.ui.mixin.TabIndexedElement.call( this, config );
18091
18092 // Events
18093 this.$element.on( {
18094 focus: this.bindKeyDownListener.bind( this ),
18095 blur: this.unbindKeyDownListener.bind( this )
18096 } );
18097
18098 // Initialization
18099 this.$element.addClass( 'oo-ui-buttonSelectWidget' );
18100 };
18101
18102 /* Setup */
18103
18104 OO.inheritClass( OO.ui.ButtonSelectWidget, OO.ui.SelectWidget );
18105 OO.mixinClass( OO.ui.ButtonSelectWidget, OO.ui.mixin.TabIndexedElement );
18106
18107 /**
18108 * RadioSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains radio
18109 * options and is used together with OO.ui.RadioOptionWidget. The RadioSelectWidget provides
18110 * an interface for adding, removing and selecting options.
18111 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
18112 *
18113 * If you want to use this within a HTML form, such as a OO.ui.FormLayout, use
18114 * OO.ui.RadioSelectInputWidget instead.
18115 *
18116 * @example
18117 * // A RadioSelectWidget with RadioOptions.
18118 * var option1 = new OO.ui.RadioOptionWidget( {
18119 * data: 'a',
18120 * label: 'Selected radio option'
18121 * } );
18122 *
18123 * var option2 = new OO.ui.RadioOptionWidget( {
18124 * data: 'b',
18125 * label: 'Unselected radio option'
18126 * } );
18127 *
18128 * var radioSelect=new OO.ui.RadioSelectWidget( {
18129 * items: [ option1, option2 ]
18130 * } );
18131 *
18132 * // Select 'option 1' using the RadioSelectWidget's selectItem() method.
18133 * radioSelect.selectItem( option1 );
18134 *
18135 * $( 'body' ).append( radioSelect.$element );
18136 *
18137 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
18138
18139 *
18140 * @class
18141 * @extends OO.ui.SelectWidget
18142 * @mixins OO.ui.mixin.TabIndexedElement
18143 *
18144 * @constructor
18145 * @param {Object} [config] Configuration options
18146 */
18147 OO.ui.RadioSelectWidget = function OoUiRadioSelectWidget( config ) {
18148 // Parent constructor
18149 OO.ui.RadioSelectWidget.parent.call( this, config );
18150
18151 // Mixin constructors
18152 OO.ui.mixin.TabIndexedElement.call( this, config );
18153
18154 // Events
18155 this.$element.on( {
18156 focus: this.bindKeyDownListener.bind( this ),
18157 blur: this.unbindKeyDownListener.bind( this )
18158 } );
18159
18160 // Initialization
18161 this.$element
18162 .addClass( 'oo-ui-radioSelectWidget' )
18163 .attr( 'role', 'radiogroup' );
18164 };
18165
18166 /* Setup */
18167
18168 OO.inheritClass( OO.ui.RadioSelectWidget, OO.ui.SelectWidget );
18169 OO.mixinClass( OO.ui.RadioSelectWidget, OO.ui.mixin.TabIndexedElement );
18170
18171 /**
18172 * MenuSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains options and
18173 * is used together with OO.ui.MenuOptionWidget. It is designed be used as part of another widget.
18174 * See {@link OO.ui.DropdownWidget DropdownWidget}, {@link OO.ui.ComboBoxWidget ComboBoxWidget},
18175 * and {@link OO.ui.mixin.LookupElement LookupElement} for examples of widgets that contain menus.
18176 * MenuSelectWidgets themselves are not instantiated directly, rather subclassed
18177 * and customized to be opened, closed, and displayed as needed.
18178 *
18179 * By default, menus are clipped to the visible viewport and are not visible when a user presses the
18180 * mouse outside the menu.
18181 *
18182 * Menus also have support for keyboard interaction:
18183 *
18184 * - Enter/Return key: choose and select a menu option
18185 * - Up-arrow key: highlight the previous menu option
18186 * - Down-arrow key: highlight the next menu option
18187 * - Esc key: hide the menu
18188 *
18189 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
18190 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
18191 *
18192 * @class
18193 * @extends OO.ui.SelectWidget
18194 * @mixins OO.ui.mixin.ClippableElement
18195 *
18196 * @constructor
18197 * @param {Object} [config] Configuration options
18198 * @cfg {OO.ui.TextInputWidget} [input] Text input used to implement option highlighting for menu items that match
18199 * the text the user types. This config is used by {@link OO.ui.ComboBoxWidget ComboBoxWidget}
18200 * and {@link OO.ui.mixin.LookupElement LookupElement}
18201 * @cfg {jQuery} [$input] Text input used to implement option highlighting for menu items that match
18202 * the text the user types. This config is used by {@link OO.ui.CapsuleMultiSelectWidget CapsuleMultiSelectWidget}
18203 * @cfg {OO.ui.Widget} [widget] Widget associated with the menu's active state. If the user clicks the mouse
18204 * anywhere on the page outside of this widget, the menu is hidden. For example, if there is a button
18205 * that toggles the menu's visibility on click, the menu will be hidden then re-shown when the user clicks
18206 * that button, unless the button (or its parent widget) is passed in here.
18207 * @cfg {boolean} [autoHide=true] Hide the menu when the mouse is pressed outside the menu.
18208 * @cfg {boolean} [filterFromInput=false] Filter the displayed options from the input
18209 */
18210 OO.ui.MenuSelectWidget = function OoUiMenuSelectWidget( config ) {
18211 // Configuration initialization
18212 config = config || {};
18213
18214 // Parent constructor
18215 OO.ui.MenuSelectWidget.parent.call( this, config );
18216
18217 // Mixin constructors
18218 OO.ui.mixin.ClippableElement.call( this, $.extend( {}, config, { $clippable: this.$group } ) );
18219
18220 // Properties
18221 this.newItems = null;
18222 this.autoHide = config.autoHide === undefined || !!config.autoHide;
18223 this.filterFromInput = !!config.filterFromInput;
18224 this.$input = config.$input ? config.$input : config.input ? config.input.$input : null;
18225 this.$widget = config.widget ? config.widget.$element : null;
18226 this.onDocumentMouseDownHandler = this.onDocumentMouseDown.bind( this );
18227 this.onInputEditHandler = OO.ui.debounce( this.updateItemVisibility.bind( this ), 100 );
18228
18229 // Initialization
18230 this.$element
18231 .addClass( 'oo-ui-menuSelectWidget' )
18232 .attr( 'role', 'menu' );
18233
18234 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
18235 // that reference properties not initialized at that time of parent class construction
18236 // TODO: Find a better way to handle post-constructor setup
18237 this.visible = false;
18238 this.$element.addClass( 'oo-ui-element-hidden' );
18239 };
18240
18241 /* Setup */
18242
18243 OO.inheritClass( OO.ui.MenuSelectWidget, OO.ui.SelectWidget );
18244 OO.mixinClass( OO.ui.MenuSelectWidget, OO.ui.mixin.ClippableElement );
18245
18246 /* Methods */
18247
18248 /**
18249 * Handles document mouse down events.
18250 *
18251 * @protected
18252 * @param {jQuery.Event} e Key down event
18253 */
18254 OO.ui.MenuSelectWidget.prototype.onDocumentMouseDown = function ( e ) {
18255 if (
18256 !OO.ui.contains( this.$element[ 0 ], e.target, true ) &&
18257 ( !this.$widget || !OO.ui.contains( this.$widget[ 0 ], e.target, true ) )
18258 ) {
18259 this.toggle( false );
18260 }
18261 };
18262
18263 /**
18264 * @inheritdoc
18265 */
18266 OO.ui.MenuSelectWidget.prototype.onKeyDown = function ( e ) {
18267 var currentItem = this.getHighlightedItem() || this.getSelectedItem();
18268
18269 if ( !this.isDisabled() && this.isVisible() ) {
18270 switch ( e.keyCode ) {
18271 case OO.ui.Keys.LEFT:
18272 case OO.ui.Keys.RIGHT:
18273 // Do nothing if a text field is associated, arrow keys will be handled natively
18274 if ( !this.$input ) {
18275 OO.ui.MenuSelectWidget.parent.prototype.onKeyDown.call( this, e );
18276 }
18277 break;
18278 case OO.ui.Keys.ESCAPE:
18279 case OO.ui.Keys.TAB:
18280 if ( currentItem ) {
18281 currentItem.setHighlighted( false );
18282 }
18283 this.toggle( false );
18284 // Don't prevent tabbing away, prevent defocusing
18285 if ( e.keyCode === OO.ui.Keys.ESCAPE ) {
18286 e.preventDefault();
18287 e.stopPropagation();
18288 }
18289 break;
18290 default:
18291 OO.ui.MenuSelectWidget.parent.prototype.onKeyDown.call( this, e );
18292 return;
18293 }
18294 }
18295 };
18296
18297 /**
18298 * Update menu item visibility after input changes.
18299 * @protected
18300 */
18301 OO.ui.MenuSelectWidget.prototype.updateItemVisibility = function () {
18302 var i, item,
18303 len = this.items.length,
18304 showAll = !this.isVisible(),
18305 filter = showAll ? null : this.getItemMatcher( this.$input.val() );
18306
18307 for ( i = 0; i < len; i++ ) {
18308 item = this.items[i];
18309 if ( item instanceof OO.ui.OptionWidget ) {
18310 item.toggle( showAll || filter( item ) );
18311 }
18312 }
18313
18314 // Reevaluate clipping
18315 this.clip();
18316 };
18317
18318 /**
18319 * @inheritdoc
18320 */
18321 OO.ui.MenuSelectWidget.prototype.bindKeyDownListener = function () {
18322 if ( this.$input ) {
18323 this.$input.on( 'keydown', this.onKeyDownHandler );
18324 } else {
18325 OO.ui.MenuSelectWidget.parent.prototype.bindKeyDownListener.call( this );
18326 }
18327 };
18328
18329 /**
18330 * @inheritdoc
18331 */
18332 OO.ui.MenuSelectWidget.prototype.unbindKeyDownListener = function () {
18333 if ( this.$input ) {
18334 this.$input.off( 'keydown', this.onKeyDownHandler );
18335 } else {
18336 OO.ui.MenuSelectWidget.parent.prototype.unbindKeyDownListener.call( this );
18337 }
18338 };
18339
18340 /**
18341 * @inheritdoc
18342 */
18343 OO.ui.MenuSelectWidget.prototype.bindKeyPressListener = function () {
18344 if ( this.$input ) {
18345 if ( this.filterFromInput ) {
18346 this.$input.on( 'keydown mouseup cut paste change input select', this.onInputEditHandler );
18347 }
18348 } else {
18349 OO.ui.MenuSelectWidget.parent.prototype.bindKeyPressListener.call( this );
18350 }
18351 };
18352
18353 /**
18354 * @inheritdoc
18355 */
18356 OO.ui.MenuSelectWidget.prototype.unbindKeyPressListener = function () {
18357 if ( this.$input ) {
18358 if ( this.filterFromInput ) {
18359 this.$input.off( 'keydown mouseup cut paste change input select', this.onInputEditHandler );
18360 this.updateItemVisibility();
18361 }
18362 } else {
18363 OO.ui.MenuSelectWidget.parent.prototype.unbindKeyPressListener.call( this );
18364 }
18365 };
18366
18367 /**
18368 * Choose an item.
18369 *
18370 * When a user chooses an item, the menu is closed.
18371 *
18372 * Note that ‘choose’ should never be modified programmatically. A user can choose an option with the keyboard
18373 * or mouse and it becomes selected. To select an item programmatically, use the #selectItem method.
18374 * @param {OO.ui.OptionWidget} item Item to choose
18375 * @chainable
18376 */
18377 OO.ui.MenuSelectWidget.prototype.chooseItem = function ( item ) {
18378 OO.ui.MenuSelectWidget.parent.prototype.chooseItem.call( this, item );
18379 this.toggle( false );
18380 return this;
18381 };
18382
18383 /**
18384 * @inheritdoc
18385 */
18386 OO.ui.MenuSelectWidget.prototype.addItems = function ( items, index ) {
18387 var i, len, item;
18388
18389 // Parent method
18390 OO.ui.MenuSelectWidget.parent.prototype.addItems.call( this, items, index );
18391
18392 // Auto-initialize
18393 if ( !this.newItems ) {
18394 this.newItems = [];
18395 }
18396
18397 for ( i = 0, len = items.length; i < len; i++ ) {
18398 item = items[ i ];
18399 if ( this.isVisible() ) {
18400 // Defer fitting label until item has been attached
18401 item.fitLabel();
18402 } else {
18403 this.newItems.push( item );
18404 }
18405 }
18406
18407 // Reevaluate clipping
18408 this.clip();
18409
18410 return this;
18411 };
18412
18413 /**
18414 * @inheritdoc
18415 */
18416 OO.ui.MenuSelectWidget.prototype.removeItems = function ( items ) {
18417 // Parent method
18418 OO.ui.MenuSelectWidget.parent.prototype.removeItems.call( this, items );
18419
18420 // Reevaluate clipping
18421 this.clip();
18422
18423 return this;
18424 };
18425
18426 /**
18427 * @inheritdoc
18428 */
18429 OO.ui.MenuSelectWidget.prototype.clearItems = function () {
18430 // Parent method
18431 OO.ui.MenuSelectWidget.parent.prototype.clearItems.call( this );
18432
18433 // Reevaluate clipping
18434 this.clip();
18435
18436 return this;
18437 };
18438
18439 /**
18440 * @inheritdoc
18441 */
18442 OO.ui.MenuSelectWidget.prototype.toggle = function ( visible ) {
18443 visible = ( visible === undefined ? !this.visible : !!visible ) && !!this.items.length;
18444
18445 var i, len,
18446 change = visible !== this.isVisible();
18447
18448 // Parent method
18449 OO.ui.MenuSelectWidget.parent.prototype.toggle.call( this, visible );
18450
18451 if ( change ) {
18452 if ( visible ) {
18453 this.bindKeyDownListener();
18454 this.bindKeyPressListener();
18455
18456 if ( this.newItems && this.newItems.length ) {
18457 for ( i = 0, len = this.newItems.length; i < len; i++ ) {
18458 this.newItems[ i ].fitLabel();
18459 }
18460 this.newItems = null;
18461 }
18462 this.toggleClipping( true );
18463
18464 // Auto-hide
18465 if ( this.autoHide ) {
18466 OO.ui.addCaptureEventListener( this.getElementDocument(), 'mousedown', this.onDocumentMouseDownHandler );
18467 }
18468 } else {
18469 this.unbindKeyDownListener();
18470 this.unbindKeyPressListener();
18471 OO.ui.removeCaptureEventListener( this.getElementDocument(), 'mousedown', this.onDocumentMouseDownHandler );
18472 this.toggleClipping( false );
18473 }
18474 }
18475
18476 return this;
18477 };
18478
18479 /**
18480 * FloatingMenuSelectWidget is a menu that will stick under a specified
18481 * container, even when it is inserted elsewhere in the document (for example,
18482 * in a OO.ui.Window's $overlay). This is sometimes necessary to prevent the
18483 * menu from being clipped too aggresively.
18484 *
18485 * The menu's position is automatically calculated and maintained when the menu
18486 * is toggled or the window is resized.
18487 *
18488 * See OO.ui.ComboBoxWidget for an example of a widget that uses this class.
18489 *
18490 * @class
18491 * @extends OO.ui.MenuSelectWidget
18492 *
18493 * @constructor
18494 * @param {OO.ui.Widget} [inputWidget] Widget to provide the menu for.
18495 * Deprecated, omit this parameter and specify `$container` instead.
18496 * @param {Object} [config] Configuration options
18497 * @cfg {jQuery} [$container=inputWidget.$element] Element to render menu under
18498 */
18499 OO.ui.FloatingMenuSelectWidget = function OoUiFloatingMenuSelectWidget( inputWidget, config ) {
18500 // Allow 'inputWidget' parameter and config for backwards compatibility
18501 if ( OO.isPlainObject( inputWidget ) && config === undefined ) {
18502 config = inputWidget;
18503 inputWidget = config.inputWidget;
18504 }
18505
18506 // Configuration initialization
18507 config = config || {};
18508
18509 // Parent constructor
18510 OO.ui.FloatingMenuSelectWidget.parent.call( this, config );
18511
18512 // Properties
18513 this.inputWidget = inputWidget; // For backwards compatibility
18514 this.$container = config.$container || this.inputWidget.$element;
18515 this.onWindowResizeHandler = this.onWindowResize.bind( this );
18516
18517 // Initialization
18518 this.$element.addClass( 'oo-ui-floatingMenuSelectWidget' );
18519 // For backwards compatibility
18520 this.$element.addClass( 'oo-ui-textInputMenuSelectWidget' );
18521 };
18522
18523 /* Setup */
18524
18525 OO.inheritClass( OO.ui.FloatingMenuSelectWidget, OO.ui.MenuSelectWidget );
18526
18527 // For backwards compatibility
18528 OO.ui.TextInputMenuSelectWidget = OO.ui.FloatingMenuSelectWidget;
18529
18530 /* Methods */
18531
18532 /**
18533 * Handle window resize event.
18534 *
18535 * @private
18536 * @param {jQuery.Event} e Window resize event
18537 */
18538 OO.ui.FloatingMenuSelectWidget.prototype.onWindowResize = function () {
18539 this.position();
18540 };
18541
18542 /**
18543 * @inheritdoc
18544 */
18545 OO.ui.FloatingMenuSelectWidget.prototype.toggle = function ( visible ) {
18546 visible = visible === undefined ? !this.isVisible() : !!visible;
18547
18548 var change = visible !== this.isVisible();
18549
18550 if ( change && visible ) {
18551 // Make sure the width is set before the parent method runs.
18552 // After this we have to call this.position(); again to actually
18553 // position ourselves correctly.
18554 this.position();
18555 }
18556
18557 // Parent method
18558 OO.ui.FloatingMenuSelectWidget.parent.prototype.toggle.call( this, visible );
18559
18560 if ( change ) {
18561 if ( this.isVisible() ) {
18562 this.position();
18563 $( this.getElementWindow() ).on( 'resize', this.onWindowResizeHandler );
18564 } else {
18565 $( this.getElementWindow() ).off( 'resize', this.onWindowResizeHandler );
18566 }
18567 }
18568
18569 return this;
18570 };
18571
18572 /**
18573 * Position the menu.
18574 *
18575 * @private
18576 * @chainable
18577 */
18578 OO.ui.FloatingMenuSelectWidget.prototype.position = function () {
18579 var $container = this.$container,
18580 pos = OO.ui.Element.static.getRelativePosition( $container, this.$element.offsetParent() );
18581
18582 // Position under input
18583 pos.top += $container.height();
18584 this.$element.css( pos );
18585
18586 // Set width
18587 this.setIdealSize( $container.width() );
18588 // We updated the position, so re-evaluate the clipping state
18589 this.clip();
18590
18591 return this;
18592 };
18593
18594 /**
18595 * OutlineSelectWidget is a structured list that contains {@link OO.ui.OutlineOptionWidget outline options}
18596 * A set of controls can be provided with an {@link OO.ui.OutlineControlsWidget outline controls} widget.
18597 *
18598 * **Currently, this class is only used by {@link OO.ui.BookletLayout booklet layouts}.**
18599 *
18600 * @class
18601 * @extends OO.ui.SelectWidget
18602 * @mixins OO.ui.mixin.TabIndexedElement
18603 *
18604 * @constructor
18605 * @param {Object} [config] Configuration options
18606 */
18607 OO.ui.OutlineSelectWidget = function OoUiOutlineSelectWidget( config ) {
18608 // Parent constructor
18609 OO.ui.OutlineSelectWidget.parent.call( this, config );
18610
18611 // Mixin constructors
18612 OO.ui.mixin.TabIndexedElement.call( this, config );
18613
18614 // Events
18615 this.$element.on( {
18616 focus: this.bindKeyDownListener.bind( this ),
18617 blur: this.unbindKeyDownListener.bind( this )
18618 } );
18619
18620 // Initialization
18621 this.$element.addClass( 'oo-ui-outlineSelectWidget' );
18622 };
18623
18624 /* Setup */
18625
18626 OO.inheritClass( OO.ui.OutlineSelectWidget, OO.ui.SelectWidget );
18627 OO.mixinClass( OO.ui.OutlineSelectWidget, OO.ui.mixin.TabIndexedElement );
18628
18629 /**
18630 * TabSelectWidget is a list that contains {@link OO.ui.TabOptionWidget tab options}
18631 *
18632 * **Currently, this class is only used by {@link OO.ui.IndexLayout index layouts}.**
18633 *
18634 * @class
18635 * @extends OO.ui.SelectWidget
18636 * @mixins OO.ui.mixin.TabIndexedElement
18637 *
18638 * @constructor
18639 * @param {Object} [config] Configuration options
18640 */
18641 OO.ui.TabSelectWidget = function OoUiTabSelectWidget( config ) {
18642 // Parent constructor
18643 OO.ui.TabSelectWidget.parent.call( this, config );
18644
18645 // Mixin constructors
18646 OO.ui.mixin.TabIndexedElement.call( this, config );
18647
18648 // Events
18649 this.$element.on( {
18650 focus: this.bindKeyDownListener.bind( this ),
18651 blur: this.unbindKeyDownListener.bind( this )
18652 } );
18653
18654 // Initialization
18655 this.$element.addClass( 'oo-ui-tabSelectWidget' );
18656 };
18657
18658 /* Setup */
18659
18660 OO.inheritClass( OO.ui.TabSelectWidget, OO.ui.SelectWidget );
18661 OO.mixinClass( OO.ui.TabSelectWidget, OO.ui.mixin.TabIndexedElement );
18662
18663 /**
18664 * NumberInputWidgets combine a {@link OO.ui.TextInputWidget text input} (where a value
18665 * can be entered manually) and two {@link OO.ui.ButtonWidget button widgets}
18666 * (to adjust the value in increments) to allow the user to enter a number.
18667 *
18668 * @example
18669 * // Example: A NumberInputWidget.
18670 * var numberInput = new OO.ui.NumberInputWidget( {
18671 * label: 'NumberInputWidget',
18672 * input: { value: 5, min: 1, max: 10 }
18673 * } );
18674 * $( 'body' ).append( numberInput.$element );
18675 *
18676 * @class
18677 * @extends OO.ui.Widget
18678 *
18679 * @constructor
18680 * @param {Object} [config] Configuration options
18681 * @cfg {Object} [input] Configuration options to pass to the {@link OO.ui.TextInputWidget text input widget}.
18682 * @cfg {Object} [minusButton] Configuration options to pass to the {@link OO.ui.ButtonWidget decrementing button widget}.
18683 * @cfg {Object} [plusButton] Configuration options to pass to the {@link OO.ui.ButtonWidget incrementing button widget}.
18684 * @cfg {boolean} [isInteger=false] Whether the field accepts only integer values.
18685 * @cfg {number} [min=-Infinity] Minimum allowed value
18686 * @cfg {number} [max=Infinity] Maximum allowed value
18687 * @cfg {number} [step=1] Delta when using the buttons or up/down arrow keys
18688 * @cfg {number|null} [pageStep] Delta when using the page-up/page-down keys. Defaults to 10 times #step.
18689 */
18690 OO.ui.NumberInputWidget = function OoUiNumberInputWidget( config ) {
18691 // Configuration initialization
18692 config = $.extend( {
18693 isInteger: false,
18694 min: -Infinity,
18695 max: Infinity,
18696 step: 1,
18697 pageStep: null
18698 }, config );
18699
18700 // Parent constructor
18701 OO.ui.NumberInputWidget.parent.call( this, config );
18702
18703 // Properties
18704 this.input = new OO.ui.TextInputWidget( $.extend(
18705 {
18706 disabled: this.isDisabled()
18707 },
18708 config.input
18709 ) );
18710 this.minusButton = new OO.ui.ButtonWidget( $.extend(
18711 {
18712 disabled: this.isDisabled(),
18713 tabIndex: -1
18714 },
18715 config.minusButton,
18716 {
18717 classes: [ 'oo-ui-numberInputWidget-minusButton' ],
18718 label: '−'
18719 }
18720 ) );
18721 this.plusButton = new OO.ui.ButtonWidget( $.extend(
18722 {
18723 disabled: this.isDisabled(),
18724 tabIndex: -1
18725 },
18726 config.plusButton,
18727 {
18728 classes: [ 'oo-ui-numberInputWidget-plusButton' ],
18729 label: '+'
18730 }
18731 ) );
18732
18733 // Events
18734 this.input.connect( this, {
18735 change: this.emit.bind( this, 'change' ),
18736 enter: this.emit.bind( this, 'enter' )
18737 } );
18738 this.input.$input.on( {
18739 keydown: this.onKeyDown.bind( this ),
18740 'wheel mousewheel DOMMouseScroll': this.onWheel.bind( this )
18741 } );
18742 this.plusButton.connect( this, {
18743 click: [ 'onButtonClick', +1 ]
18744 } );
18745 this.minusButton.connect( this, {
18746 click: [ 'onButtonClick', -1 ]
18747 } );
18748
18749 // Initialization
18750 this.setIsInteger( !!config.isInteger );
18751 this.setRange( config.min, config.max );
18752 this.setStep( config.step, config.pageStep );
18753
18754 this.$field = $( '<div>' ).addClass( 'oo-ui-numberInputWidget-field' )
18755 .append(
18756 this.minusButton.$element,
18757 this.input.$element,
18758 this.plusButton.$element
18759 );
18760 this.$element.addClass( 'oo-ui-numberInputWidget' ).append( this.$field );
18761 this.input.setValidation( this.validateNumber.bind( this ) );
18762 };
18763
18764 /* Setup */
18765
18766 OO.inheritClass( OO.ui.NumberInputWidget, OO.ui.Widget );
18767
18768 /* Events */
18769
18770 /**
18771 * A `change` event is emitted when the value of the input changes.
18772 *
18773 * @event change
18774 */
18775
18776 /**
18777 * An `enter` event is emitted when the user presses 'enter' inside the text box.
18778 *
18779 * @event enter
18780 */
18781
18782 /* Methods */
18783
18784 /**
18785 * Set whether only integers are allowed
18786 * @param {boolean} flag
18787 */
18788 OO.ui.NumberInputWidget.prototype.setIsInteger = function ( flag ) {
18789 this.isInteger = !!flag;
18790 this.input.setValidityFlag();
18791 };
18792
18793 /**
18794 * Get whether only integers are allowed
18795 * @return {boolean} Flag value
18796 */
18797 OO.ui.NumberInputWidget.prototype.getIsInteger = function () {
18798 return this.isInteger;
18799 };
18800
18801 /**
18802 * Set the range of allowed values
18803 * @param {number} min Minimum allowed value
18804 * @param {number} max Maximum allowed value
18805 */
18806 OO.ui.NumberInputWidget.prototype.setRange = function ( min, max ) {
18807 if ( min > max ) {
18808 throw new Error( 'Minimum (' + min + ') must not be greater than maximum (' + max + ')' );
18809 }
18810 this.min = min;
18811 this.max = max;
18812 this.input.setValidityFlag();
18813 };
18814
18815 /**
18816 * Get the current range
18817 * @return {number[]} Minimum and maximum values
18818 */
18819 OO.ui.NumberInputWidget.prototype.getRange = function () {
18820 return [ this.min, this.max ];
18821 };
18822
18823 /**
18824 * Set the stepping deltas
18825 * @param {number} step Normal step
18826 * @param {number|null} pageStep Page step. If null, 10 * step will be used.
18827 */
18828 OO.ui.NumberInputWidget.prototype.setStep = function ( step, pageStep ) {
18829 if ( step <= 0 ) {
18830 throw new Error( 'Step value must be positive' );
18831 }
18832 if ( pageStep === null ) {
18833 pageStep = step * 10;
18834 } else if ( pageStep <= 0 ) {
18835 throw new Error( 'Page step value must be positive' );
18836 }
18837 this.step = step;
18838 this.pageStep = pageStep;
18839 };
18840
18841 /**
18842 * Get the current stepping values
18843 * @return {number[]} Step and page step
18844 */
18845 OO.ui.NumberInputWidget.prototype.getStep = function () {
18846 return [ this.step, this.pageStep ];
18847 };
18848
18849 /**
18850 * Get the current value of the widget
18851 * @return {string}
18852 */
18853 OO.ui.NumberInputWidget.prototype.getValue = function () {
18854 return this.input.getValue();
18855 };
18856
18857 /**
18858 * Get the current value of the widget as a number
18859 * @return {number} May be NaN, or an invalid number
18860 */
18861 OO.ui.NumberInputWidget.prototype.getNumericValue = function () {
18862 return +this.input.getValue();
18863 };
18864
18865 /**
18866 * Set the value of the widget
18867 * @param {string} value Invalid values are allowed
18868 */
18869 OO.ui.NumberInputWidget.prototype.setValue = function ( value ) {
18870 this.input.setValue( value );
18871 };
18872
18873 /**
18874 * Adjust the value of the widget
18875 * @param {number} delta Adjustment amount
18876 */
18877 OO.ui.NumberInputWidget.prototype.adjustValue = function ( delta ) {
18878 var n, v = this.getNumericValue();
18879
18880 delta = +delta;
18881 if ( isNaN( delta ) || !isFinite( delta ) ) {
18882 throw new Error( 'Delta must be a finite number' );
18883 }
18884
18885 if ( isNaN( v ) ) {
18886 n = 0;
18887 } else {
18888 n = v + delta;
18889 n = Math.max( Math.min( n, this.max ), this.min );
18890 if ( this.isInteger ) {
18891 n = Math.round( n );
18892 }
18893 }
18894
18895 if ( n !== v ) {
18896 this.setValue( n );
18897 }
18898 };
18899
18900 /**
18901 * Validate input
18902 * @private
18903 * @param {string} value Field value
18904 * @return {boolean}
18905 */
18906 OO.ui.NumberInputWidget.prototype.validateNumber = function ( value ) {
18907 var n = +value;
18908 if ( isNaN( n ) || !isFinite( n ) ) {
18909 return false;
18910 }
18911
18912 /*jshint bitwise: false */
18913 if ( this.isInteger && ( n | 0 ) !== n ) {
18914 return false;
18915 }
18916 /*jshint bitwise: true */
18917
18918 if ( n < this.min || n > this.max ) {
18919 return false;
18920 }
18921
18922 return true;
18923 };
18924
18925 /**
18926 * Handle mouse click events.
18927 *
18928 * @private
18929 * @param {number} dir +1 or -1
18930 */
18931 OO.ui.NumberInputWidget.prototype.onButtonClick = function ( dir ) {
18932 this.adjustValue( dir * this.step );
18933 };
18934
18935 /**
18936 * Handle mouse wheel events.
18937 *
18938 * @private
18939 * @param {jQuery.Event} event
18940 */
18941 OO.ui.NumberInputWidget.prototype.onWheel = function ( event ) {
18942 var delta = 0;
18943
18944 // Standard 'wheel' event
18945 if ( event.originalEvent.deltaMode !== undefined ) {
18946 this.sawWheelEvent = true;
18947 }
18948 if ( event.originalEvent.deltaY ) {
18949 delta = -event.originalEvent.deltaY;
18950 } else if ( event.originalEvent.deltaX ) {
18951 delta = event.originalEvent.deltaX;
18952 }
18953
18954 // Non-standard events
18955 if ( !this.sawWheelEvent ) {
18956 if ( event.originalEvent.wheelDeltaX ) {
18957 delta = -event.originalEvent.wheelDeltaX;
18958 } else if ( event.originalEvent.wheelDeltaY ) {
18959 delta = event.originalEvent.wheelDeltaY;
18960 } else if ( event.originalEvent.wheelDelta ) {
18961 delta = event.originalEvent.wheelDelta;
18962 } else if ( event.originalEvent.detail ) {
18963 delta = -event.originalEvent.detail;
18964 }
18965 }
18966
18967 if ( delta ) {
18968 delta = delta < 0 ? -1 : 1;
18969 this.adjustValue( delta * this.step );
18970 }
18971
18972 return false;
18973 };
18974
18975 /**
18976 * Handle key down events.
18977 *
18978 *
18979 * @private
18980 * @param {jQuery.Event} e Key down event
18981 */
18982 OO.ui.NumberInputWidget.prototype.onKeyDown = function ( e ) {
18983 if ( !this.isDisabled() ) {
18984 switch ( e.which ) {
18985 case OO.ui.Keys.UP:
18986 this.adjustValue( this.step );
18987 return false;
18988 case OO.ui.Keys.DOWN:
18989 this.adjustValue( -this.step );
18990 return false;
18991 case OO.ui.Keys.PAGEUP:
18992 this.adjustValue( this.pageStep );
18993 return false;
18994 case OO.ui.Keys.PAGEDOWN:
18995 this.adjustValue( -this.pageStep );
18996 return false;
18997 }
18998 }
18999 };
19000
19001 /**
19002 * @inheritdoc
19003 */
19004 OO.ui.NumberInputWidget.prototype.setDisabled = function ( disabled ) {
19005 // Parent method
19006 OO.ui.NumberInputWidget.parent.prototype.setDisabled.call( this, disabled );
19007
19008 if ( this.input ) {
19009 this.input.setDisabled( this.isDisabled() );
19010 }
19011 if ( this.minusButton ) {
19012 this.minusButton.setDisabled( this.isDisabled() );
19013 }
19014 if ( this.plusButton ) {
19015 this.plusButton.setDisabled( this.isDisabled() );
19016 }
19017
19018 return this;
19019 };
19020
19021 /**
19022 * ToggleSwitches are switches that slide on and off. Their state is represented by a Boolean
19023 * value (`true` for ‘on’, and `false` otherwise, the default). The ‘off’ state is represented
19024 * visually by a slider in the leftmost position.
19025 *
19026 * @example
19027 * // Toggle switches in the 'off' and 'on' position.
19028 * var toggleSwitch1 = new OO.ui.ToggleSwitchWidget();
19029 * var toggleSwitch2 = new OO.ui.ToggleSwitchWidget( {
19030 * value: true
19031 * } );
19032 *
19033 * // Create a FieldsetLayout to layout and label switches
19034 * var fieldset = new OO.ui.FieldsetLayout( {
19035 * label: 'Toggle switches'
19036 * } );
19037 * fieldset.addItems( [
19038 * new OO.ui.FieldLayout( toggleSwitch1, { label: 'Off', align: 'top' } ),
19039 * new OO.ui.FieldLayout( toggleSwitch2, { label: 'On', align: 'top' } )
19040 * ] );
19041 * $( 'body' ).append( fieldset.$element );
19042 *
19043 * @class
19044 * @extends OO.ui.ToggleWidget
19045 * @mixins OO.ui.mixin.TabIndexedElement
19046 *
19047 * @constructor
19048 * @param {Object} [config] Configuration options
19049 * @cfg {boolean} [value=false] The toggle switch’s initial on/off state.
19050 * By default, the toggle switch is in the 'off' position.
19051 */
19052 OO.ui.ToggleSwitchWidget = function OoUiToggleSwitchWidget( config ) {
19053 // Parent constructor
19054 OO.ui.ToggleSwitchWidget.parent.call( this, config );
19055
19056 // Mixin constructors
19057 OO.ui.mixin.TabIndexedElement.call( this, config );
19058
19059 // Properties
19060 this.dragging = false;
19061 this.dragStart = null;
19062 this.sliding = false;
19063 this.$glow = $( '<span>' );
19064 this.$grip = $( '<span>' );
19065
19066 // Events
19067 this.$element.on( {
19068 click: this.onClick.bind( this ),
19069 keypress: this.onKeyPress.bind( this )
19070 } );
19071
19072 // Initialization
19073 this.$glow.addClass( 'oo-ui-toggleSwitchWidget-glow' );
19074 this.$grip.addClass( 'oo-ui-toggleSwitchWidget-grip' );
19075 this.$element
19076 .addClass( 'oo-ui-toggleSwitchWidget' )
19077 .attr( 'role', 'checkbox' )
19078 .append( this.$glow, this.$grip );
19079 };
19080
19081 /* Setup */
19082
19083 OO.inheritClass( OO.ui.ToggleSwitchWidget, OO.ui.ToggleWidget );
19084 OO.mixinClass( OO.ui.ToggleSwitchWidget, OO.ui.mixin.TabIndexedElement );
19085
19086 /* Methods */
19087
19088 /**
19089 * Handle mouse click events.
19090 *
19091 * @private
19092 * @param {jQuery.Event} e Mouse click event
19093 */
19094 OO.ui.ToggleSwitchWidget.prototype.onClick = function ( e ) {
19095 if ( !this.isDisabled() && e.which === 1 ) {
19096 this.setValue( !this.value );
19097 }
19098 return false;
19099 };
19100
19101 /**
19102 * Handle key press events.
19103 *
19104 * @private
19105 * @param {jQuery.Event} e Key press event
19106 */
19107 OO.ui.ToggleSwitchWidget.prototype.onKeyPress = function ( e ) {
19108 if ( !this.isDisabled() && ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER ) ) {
19109 this.setValue( !this.value );
19110 return false;
19111 }
19112 };
19113
19114 /*!
19115 * Deprecated aliases for classes in the `OO.ui.mixin` namespace.
19116 */
19117
19118 /**
19119 * @inheritdoc OO.ui.mixin.ButtonElement
19120 * @deprecated Use {@link OO.ui.mixin.ButtonElement} instead.
19121 */
19122 OO.ui.ButtonElement = OO.ui.mixin.ButtonElement;
19123
19124 /**
19125 * @inheritdoc OO.ui.mixin.ClippableElement
19126 * @deprecated Use {@link OO.ui.mixin.ClippableElement} instead.
19127 */
19128 OO.ui.ClippableElement = OO.ui.mixin.ClippableElement;
19129
19130 /**
19131 * @inheritdoc OO.ui.mixin.DraggableElement
19132 * @deprecated Use {@link OO.ui.mixin.DraggableElement} instead.
19133 */
19134 OO.ui.DraggableElement = OO.ui.mixin.DraggableElement;
19135
19136 /**
19137 * @inheritdoc OO.ui.mixin.DraggableGroupElement
19138 * @deprecated Use {@link OO.ui.mixin.DraggableGroupElement} instead.
19139 */
19140 OO.ui.DraggableGroupElement = OO.ui.mixin.DraggableGroupElement;
19141
19142 /**
19143 * @inheritdoc OO.ui.mixin.FlaggedElement
19144 * @deprecated Use {@link OO.ui.mixin.FlaggedElement} instead.
19145 */
19146 OO.ui.FlaggedElement = OO.ui.mixin.FlaggedElement;
19147
19148 /**
19149 * @inheritdoc OO.ui.mixin.GroupElement
19150 * @deprecated Use {@link OO.ui.mixin.GroupElement} instead.
19151 */
19152 OO.ui.GroupElement = OO.ui.mixin.GroupElement;
19153
19154 /**
19155 * @inheritdoc OO.ui.mixin.GroupWidget
19156 * @deprecated Use {@link OO.ui.mixin.GroupWidget} instead.
19157 */
19158 OO.ui.GroupWidget = OO.ui.mixin.GroupWidget;
19159
19160 /**
19161 * @inheritdoc OO.ui.mixin.IconElement
19162 * @deprecated Use {@link OO.ui.mixin.IconElement} instead.
19163 */
19164 OO.ui.IconElement = OO.ui.mixin.IconElement;
19165
19166 /**
19167 * @inheritdoc OO.ui.mixin.IndicatorElement
19168 * @deprecated Use {@link OO.ui.mixin.IndicatorElement} instead.
19169 */
19170 OO.ui.IndicatorElement = OO.ui.mixin.IndicatorElement;
19171
19172 /**
19173 * @inheritdoc OO.ui.mixin.ItemWidget
19174 * @deprecated Use {@link OO.ui.mixin.ItemWidget} instead.
19175 */
19176 OO.ui.ItemWidget = OO.ui.mixin.ItemWidget;
19177
19178 /**
19179 * @inheritdoc OO.ui.mixin.LabelElement
19180 * @deprecated Use {@link OO.ui.mixin.LabelElement} instead.
19181 */
19182 OO.ui.LabelElement = OO.ui.mixin.LabelElement;
19183
19184 /**
19185 * @inheritdoc OO.ui.mixin.LookupElement
19186 * @deprecated Use {@link OO.ui.mixin.LookupElement} instead.
19187 */
19188 OO.ui.LookupElement = OO.ui.mixin.LookupElement;
19189
19190 /**
19191 * @inheritdoc OO.ui.mixin.PendingElement
19192 * @deprecated Use {@link OO.ui.mixin.PendingElement} instead.
19193 */
19194 OO.ui.PendingElement = OO.ui.mixin.PendingElement;
19195
19196 /**
19197 * @inheritdoc OO.ui.mixin.PopupElement
19198 * @deprecated Use {@link OO.ui.mixin.PopupElement} instead.
19199 */
19200 OO.ui.PopupElement = OO.ui.mixin.PopupElement;
19201
19202 /**
19203 * @inheritdoc OO.ui.mixin.TabIndexedElement
19204 * @deprecated Use {@link OO.ui.mixin.TabIndexedElement} instead.
19205 */
19206 OO.ui.TabIndexedElement = OO.ui.mixin.TabIndexedElement;
19207
19208 /**
19209 * @inheritdoc OO.ui.mixin.TitledElement
19210 * @deprecated Use {@link OO.ui.mixin.TitledElement} instead.
19211 */
19212 OO.ui.TitledElement = OO.ui.mixin.TitledElement;
19213
19214 }( OO ) );