Merge "Enable users to watch category membership changes #2"
[lhc/web/wiklou.git] / resources / lib / oojs-ui / oojs-ui.js
1 /*!
2 * OOjs UI v0.12.12
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-10-13T20:38:18Z
10 */
11 ( function ( OO ) {
12
13 'use strict';
14
15 /**
16 * Namespace for all classes, static methods and static properties.
17 *
18 * @class
19 * @singleton
20 */
21 OO.ui = {};
22
23 OO.ui.bind = $.proxy;
24
25 /**
26 * @property {Object}
27 */
28 OO.ui.Keys = {
29 UNDEFINED: 0,
30 BACKSPACE: 8,
31 DELETE: 46,
32 LEFT: 37,
33 RIGHT: 39,
34 UP: 38,
35 DOWN: 40,
36 ENTER: 13,
37 END: 35,
38 HOME: 36,
39 TAB: 9,
40 PAGEUP: 33,
41 PAGEDOWN: 34,
42 ESCAPE: 27,
43 SHIFT: 16,
44 SPACE: 32
45 };
46
47 /**
48 * @property {Number}
49 */
50 OO.ui.elementId = 0;
51
52 /**
53 * Generate a unique ID for element
54 *
55 * @return {String} [id]
56 */
57 OO.ui.generateElementId = function () {
58 OO.ui.elementId += 1;
59 return 'oojsui-' + OO.ui.elementId;
60 };
61
62 /**
63 * Check if an element is focusable.
64 * Inspired from :focusable in jQueryUI v1.11.4 - 2015-04-14
65 *
66 * @param {jQuery} element Element to test
67 * @return {boolean}
68 */
69 OO.ui.isFocusableElement = function ( $element ) {
70 var nodeName,
71 element = $element[ 0 ];
72
73 // Anything disabled is not focusable
74 if ( element.disabled ) {
75 return false;
76 }
77
78 // Check if the element is visible
79 if ( !(
80 // This is quicker than calling $element.is( ':visible' )
81 $.expr.filters.visible( element ) &&
82 // Check that all parents are visible
83 !$element.parents().addBack().filter( function () {
84 return $.css( this, 'visibility' ) === 'hidden';
85 } ).length
86 ) ) {
87 return false;
88 }
89
90 // Check if the element is ContentEditable, which is the string 'true'
91 if ( element.contentEditable === 'true' ) {
92 return true;
93 }
94
95 // Anything with a non-negative numeric tabIndex is focusable.
96 // Use .prop to avoid browser bugs
97 if ( $element.prop( 'tabIndex' ) >= 0 ) {
98 return true;
99 }
100
101 // Some element types are naturally focusable
102 // (indexOf is much faster than regex in Chrome and about the
103 // same in FF: https://jsperf.com/regex-vs-indexof-array2)
104 nodeName = element.nodeName.toLowerCase();
105 if ( [ 'input', 'select', 'textarea', 'button', 'object' ].indexOf( nodeName ) !== -1 ) {
106 return true;
107 }
108
109 // Links and areas are focusable if they have an href
110 if ( ( nodeName === 'a' || nodeName === 'area' ) && $element.attr( 'href' ) !== undefined ) {
111 return true;
112 }
113
114 return false;
115 };
116
117 /**
118 * Find a focusable child
119 *
120 * @param {jQuery} $container Container to search in
121 * @param {boolean} [backwards] Search backwards
122 * @return {jQuery} Focusable child, an empty jQuery object if none found
123 */
124 OO.ui.findFocusable = function ( $container, backwards ) {
125 var $focusable = $( [] ),
126 // $focusableCandidates is a superset of things that
127 // could get matched by isFocusableElement
128 $focusableCandidates = $container
129 .find( 'input, select, textarea, button, object, a, area, [contenteditable], [tabindex]' );
130
131 if ( backwards ) {
132 $focusableCandidates = Array.prototype.reverse.call( $focusableCandidates );
133 }
134
135 $focusableCandidates.each( function () {
136 var $this = $( this );
137 if ( OO.ui.isFocusableElement( $this ) ) {
138 $focusable = $this;
139 return false;
140 }
141 } );
142 return $focusable;
143 };
144
145 /**
146 * Get the user's language and any fallback languages.
147 *
148 * These language codes are used to localize user interface elements in the user's language.
149 *
150 * In environments that provide a localization system, this function should be overridden to
151 * return the user's language(s). The default implementation returns English (en) only.
152 *
153 * @return {string[]} Language codes, in descending order of priority
154 */
155 OO.ui.getUserLanguages = function () {
156 return [ 'en' ];
157 };
158
159 /**
160 * Get a value in an object keyed by language code.
161 *
162 * @param {Object.<string,Mixed>} obj Object keyed by language code
163 * @param {string|null} [lang] Language code, if omitted or null defaults to any user language
164 * @param {string} [fallback] Fallback code, used if no matching language can be found
165 * @return {Mixed} Local value
166 */
167 OO.ui.getLocalValue = function ( obj, lang, fallback ) {
168 var i, len, langs;
169
170 // Requested language
171 if ( obj[ lang ] ) {
172 return obj[ lang ];
173 }
174 // Known user language
175 langs = OO.ui.getUserLanguages();
176 for ( i = 0, len = langs.length; i < len; i++ ) {
177 lang = langs[ i ];
178 if ( obj[ lang ] ) {
179 return obj[ lang ];
180 }
181 }
182 // Fallback language
183 if ( obj[ fallback ] ) {
184 return obj[ fallback ];
185 }
186 // First existing language
187 for ( lang in obj ) {
188 return obj[ lang ];
189 }
190
191 return undefined;
192 };
193
194 /**
195 * Check if a node is contained within another node
196 *
197 * Similar to jQuery#contains except a list of containers can be supplied
198 * and a boolean argument allows you to include the container in the match list
199 *
200 * @param {HTMLElement|HTMLElement[]} containers Container node(s) to search in
201 * @param {HTMLElement} contained Node to find
202 * @param {boolean} [matchContainers] Include the container(s) in the list of nodes to match, otherwise only match descendants
203 * @return {boolean} The node is in the list of target nodes
204 */
205 OO.ui.contains = function ( containers, contained, matchContainers ) {
206 var i;
207 if ( !Array.isArray( containers ) ) {
208 containers = [ containers ];
209 }
210 for ( i = containers.length - 1; i >= 0; i-- ) {
211 if ( ( matchContainers && contained === containers[ i ] ) || $.contains( containers[ i ], contained ) ) {
212 return true;
213 }
214 }
215 return false;
216 };
217
218 /**
219 * Return a function, that, as long as it continues to be invoked, will not
220 * be triggered. The function will be called after it stops being called for
221 * N milliseconds. If `immediate` is passed, trigger the function on the
222 * leading edge, instead of the trailing.
223 *
224 * Ported from: http://underscorejs.org/underscore.js
225 *
226 * @param {Function} func
227 * @param {number} wait
228 * @param {boolean} immediate
229 * @return {Function}
230 */
231 OO.ui.debounce = function ( func, wait, immediate ) {
232 var timeout;
233 return function () {
234 var context = this,
235 args = arguments,
236 later = function () {
237 timeout = null;
238 if ( !immediate ) {
239 func.apply( context, args );
240 }
241 };
242 if ( immediate && !timeout ) {
243 func.apply( context, args );
244 }
245 clearTimeout( timeout );
246 timeout = setTimeout( later, wait );
247 };
248 };
249
250 /**
251 * Proxy for `node.addEventListener( eventName, handler, true )`, if the browser supports it.
252 * Otherwise falls back to non-capturing event listeners.
253 *
254 * @param {HTMLElement} node
255 * @param {string} eventName
256 * @param {Function} handler
257 */
258 OO.ui.addCaptureEventListener = function ( node, eventName, handler ) {
259 if ( node.addEventListener ) {
260 node.addEventListener( eventName, handler, true );
261 } else {
262 node.attachEvent( 'on' + eventName, handler );
263 }
264 };
265
266 /**
267 * Proxy for `node.removeEventListener( eventName, handler, true )`, if the browser supports it.
268 * Otherwise falls back to non-capturing event listeners.
269 *
270 * @param {HTMLElement} node
271 * @param {string} eventName
272 * @param {Function} handler
273 */
274 OO.ui.removeCaptureEventListener = function ( node, eventName, handler ) {
275 if ( node.addEventListener ) {
276 node.removeEventListener( eventName, handler, true );
277 } else {
278 node.detachEvent( 'on' + eventName, handler );
279 }
280 };
281
282 /**
283 * Reconstitute a JavaScript object corresponding to a widget created by
284 * the PHP implementation.
285 *
286 * This is an alias for `OO.ui.Element.static.infuse()`.
287 *
288 * @param {string|HTMLElement|jQuery} idOrNode
289 * A DOM id (if a string) or node for the widget to infuse.
290 * @return {OO.ui.Element}
291 * The `OO.ui.Element` corresponding to this (infusable) document node.
292 */
293 OO.ui.infuse = function ( idOrNode ) {
294 return OO.ui.Element.static.infuse( idOrNode );
295 };
296
297 ( function () {
298 /**
299 * Message store for the default implementation of OO.ui.msg
300 *
301 * Environments that provide a localization system should not use this, but should override
302 * OO.ui.msg altogether.
303 *
304 * @private
305 */
306 var messages = {
307 // Tool tip for a button that moves items in a list down one place
308 'ooui-outline-control-move-down': 'Move item down',
309 // Tool tip for a button that moves items in a list up one place
310 'ooui-outline-control-move-up': 'Move item up',
311 // Tool tip for a button that removes items from a list
312 'ooui-outline-control-remove': 'Remove item',
313 // Label for the toolbar group that contains a list of all other available tools
314 'ooui-toolbar-more': 'More',
315 // Label for the fake tool that expands the full list of tools in a toolbar group
316 'ooui-toolgroup-expand': 'More',
317 // Label for the fake tool that collapses the full list of tools in a toolbar group
318 'ooui-toolgroup-collapse': 'Fewer',
319 // Default label for the accept button of a confirmation dialog
320 'ooui-dialog-message-accept': 'OK',
321 // Default label for the reject button of a confirmation dialog
322 'ooui-dialog-message-reject': 'Cancel',
323 // Title for process dialog error description
324 'ooui-dialog-process-error': 'Something went wrong',
325 // Label for process dialog dismiss error button, visible when describing errors
326 'ooui-dialog-process-dismiss': 'Dismiss',
327 // Label for process dialog retry action button, visible when describing only recoverable errors
328 'ooui-dialog-process-retry': 'Try again',
329 // Label for process dialog retry action button, visible when describing only warnings
330 'ooui-dialog-process-continue': 'Continue',
331 // Label for the file selection widget's select file button
332 'ooui-selectfile-button-select': 'Select a file',
333 // Label for the file selection widget if file selection is not supported
334 'ooui-selectfile-not-supported': 'File selection is not supported',
335 // Label for the file selection widget when no file is currently selected
336 'ooui-selectfile-placeholder': 'No file is selected',
337 // Label for the file selection widget's drop target
338 'ooui-selectfile-dragdrop-placeholder': 'Drop file here'
339 };
340
341 /**
342 * Get a localized message.
343 *
344 * In environments that provide a localization system, this function should be overridden to
345 * return the message translated in the user's language. The default implementation always returns
346 * English messages.
347 *
348 * After the message key, message parameters may optionally be passed. In the default implementation,
349 * any occurrences of $1 are replaced with the first parameter, $2 with the second parameter, etc.
350 * Alternative implementations of OO.ui.msg may use any substitution system they like, as long as
351 * they support unnamed, ordered message parameters.
352 *
353 * @abstract
354 * @param {string} key Message key
355 * @param {Mixed...} [params] Message parameters
356 * @return {string} Translated message with parameters substituted
357 */
358 OO.ui.msg = function ( key ) {
359 var message = messages[ key ],
360 params = Array.prototype.slice.call( arguments, 1 );
361 if ( typeof message === 'string' ) {
362 // Perform $1 substitution
363 message = message.replace( /\$(\d+)/g, function ( unused, n ) {
364 var i = parseInt( n, 10 );
365 return params[ i - 1 ] !== undefined ? params[ i - 1 ] : '$' + n;
366 } );
367 } else {
368 // Return placeholder if message not found
369 message = '[' + key + ']';
370 }
371 return message;
372 };
373
374 /**
375 * Package a message and arguments for deferred resolution.
376 *
377 * Use this when you are statically specifying a message and the message may not yet be present.
378 *
379 * @param {string} key Message key
380 * @param {Mixed...} [params] Message parameters
381 * @return {Function} Function that returns the resolved message when executed
382 */
383 OO.ui.deferMsg = function () {
384 var args = arguments;
385 return function () {
386 return OO.ui.msg.apply( OO.ui, args );
387 };
388 };
389
390 /**
391 * Resolve a message.
392 *
393 * If the message is a function it will be executed, otherwise it will pass through directly.
394 *
395 * @param {Function|string} msg Deferred message, or message text
396 * @return {string} Resolved message
397 */
398 OO.ui.resolveMsg = function ( msg ) {
399 if ( $.isFunction( msg ) ) {
400 return msg();
401 }
402 return msg;
403 };
404
405 /**
406 * @param {string} url
407 * @return {boolean}
408 */
409 OO.ui.isSafeUrl = function ( url ) {
410 var protocol,
411 // Keep in sync with php/Tag.php
412 whitelist = [
413 'bitcoin:', 'ftp:', 'ftps:', 'geo:', 'git:', 'gopher:', 'http:', 'https:', 'irc:', 'ircs:',
414 'magnet:', 'mailto:', 'mms:', 'news:', 'nntp:', 'redis:', 'sftp:', 'sip:', 'sips:', 'sms:', 'ssh:',
415 'svn:', 'tel:', 'telnet:', 'urn:', 'worldwind:', 'xmpp:'
416 ];
417
418 if ( url.indexOf( ':' ) === -1 ) {
419 // No protocol, safe
420 return true;
421 }
422
423 protocol = url.split( ':', 1 )[ 0 ] + ':';
424 if ( !protocol.match( /^([A-za-z0-9\+\.\-])+:/ ) ) {
425 // Not a valid protocol, safe
426 return true;
427 }
428
429 // Safe if in the whitelist
430 return whitelist.indexOf( protocol ) !== -1;
431 };
432
433 } )();
434
435 /*!
436 * Mixin namespace.
437 */
438
439 /**
440 * Namespace for OOjs UI mixins.
441 *
442 * Mixins are named according to the type of object they are intended to
443 * be mixed in to. For example, OO.ui.mixin.GroupElement is intended to be
444 * mixed in to an instance of OO.ui.Element, and OO.ui.mixin.GroupWidget
445 * is intended to be mixed in to an instance of OO.ui.Widget.
446 *
447 * @class
448 * @singleton
449 */
450 OO.ui.mixin = {};
451
452 /**
453 * PendingElement is a mixin that is used to create elements that notify users that something is happening
454 * and that they should wait before proceeding. The pending state is visually represented with a pending
455 * texture that appears in the head of a pending {@link OO.ui.ProcessDialog process dialog} or in the input
456 * field of a {@link OO.ui.TextInputWidget text input widget}.
457 *
458 * Currently, {@link OO.ui.ActionWidget Action widgets}, which mix in this class, can also be marked as pending, but only when
459 * used in {@link OO.ui.MessageDialog message dialogs}. The behavior is not currently supported for action widgets used
460 * in process dialogs.
461 *
462 * @example
463 * function MessageDialog( config ) {
464 * MessageDialog.parent.call( this, config );
465 * }
466 * OO.inheritClass( MessageDialog, OO.ui.MessageDialog );
467 *
468 * MessageDialog.static.actions = [
469 * { action: 'save', label: 'Done', flags: 'primary' },
470 * { label: 'Cancel', flags: 'safe' }
471 * ];
472 *
473 * MessageDialog.prototype.initialize = function () {
474 * MessageDialog.parent.prototype.initialize.apply( this, arguments );
475 * this.content = new OO.ui.PanelLayout( { $: this.$, padded: true } );
476 * this.content.$element.append( '<p>Click the \'Done\' action widget to see its pending state. Note that action widgets can be marked pending in message dialogs but not process dialogs.</p>' );
477 * this.$body.append( this.content.$element );
478 * };
479 * MessageDialog.prototype.getBodyHeight = function () {
480 * return 100;
481 * }
482 * MessageDialog.prototype.getActionProcess = function ( action ) {
483 * var dialog = this;
484 * if ( action === 'save' ) {
485 * dialog.getActions().get({actions: 'save'})[0].pushPending();
486 * return new OO.ui.Process()
487 * .next( 1000 )
488 * .next( function () {
489 * dialog.getActions().get({actions: 'save'})[0].popPending();
490 * } );
491 * }
492 * return MessageDialog.parent.prototype.getActionProcess.call( this, action );
493 * };
494 *
495 * var windowManager = new OO.ui.WindowManager();
496 * $( 'body' ).append( windowManager.$element );
497 *
498 * var dialog = new MessageDialog();
499 * windowManager.addWindows( [ dialog ] );
500 * windowManager.openWindow( dialog );
501 *
502 * @abstract
503 * @class
504 *
505 * @constructor
506 * @param {Object} [config] Configuration options
507 * @cfg {jQuery} [$pending] Element to mark as pending, defaults to this.$element
508 */
509 OO.ui.mixin.PendingElement = function OoUiMixinPendingElement( config ) {
510 // Configuration initialization
511 config = config || {};
512
513 // Properties
514 this.pending = 0;
515 this.$pending = null;
516
517 // Initialisation
518 this.setPendingElement( config.$pending || this.$element );
519 };
520
521 /* Setup */
522
523 OO.initClass( OO.ui.mixin.PendingElement );
524
525 /* Methods */
526
527 /**
528 * Set the pending element (and clean up any existing one).
529 *
530 * @param {jQuery} $pending The element to set to pending.
531 */
532 OO.ui.mixin.PendingElement.prototype.setPendingElement = function ( $pending ) {
533 if ( this.$pending ) {
534 this.$pending.removeClass( 'oo-ui-pendingElement-pending' );
535 }
536
537 this.$pending = $pending;
538 if ( this.pending > 0 ) {
539 this.$pending.addClass( 'oo-ui-pendingElement-pending' );
540 }
541 };
542
543 /**
544 * Check if an element is pending.
545 *
546 * @return {boolean} Element is pending
547 */
548 OO.ui.mixin.PendingElement.prototype.isPending = function () {
549 return !!this.pending;
550 };
551
552 /**
553 * Increase the pending counter. The pending state will remain active until the counter is zero
554 * (i.e., the number of calls to #pushPending and #popPending is the same).
555 *
556 * @chainable
557 */
558 OO.ui.mixin.PendingElement.prototype.pushPending = function () {
559 if ( this.pending === 0 ) {
560 this.$pending.addClass( 'oo-ui-pendingElement-pending' );
561 this.updateThemeClasses();
562 }
563 this.pending++;
564
565 return this;
566 };
567
568 /**
569 * Decrease the pending counter. The pending state will remain active until the counter is zero
570 * (i.e., the number of calls to #pushPending and #popPending is the same).
571 *
572 * @chainable
573 */
574 OO.ui.mixin.PendingElement.prototype.popPending = function () {
575 if ( this.pending === 1 ) {
576 this.$pending.removeClass( 'oo-ui-pendingElement-pending' );
577 this.updateThemeClasses();
578 }
579 this.pending = Math.max( 0, this.pending - 1 );
580
581 return this;
582 };
583
584 /**
585 * ActionSets manage the behavior of the {@link OO.ui.ActionWidget action widgets} that comprise them.
586 * Actions can be made available for specific contexts (modes) and circumstances
587 * (abilities). Action sets are primarily used with {@link OO.ui.Dialog Dialogs}.
588 *
589 * ActionSets contain two types of actions:
590 *
591 * - Special: Special actions are the first visible actions with special flags, such as 'safe' and 'primary', the default special flags. Additional special flags can be configured in subclasses with the static #specialFlags property.
592 * - Other: Other actions include all non-special visible actions.
593 *
594 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
595 *
596 * @example
597 * // Example: An action set used in a process dialog
598 * function MyProcessDialog( config ) {
599 * MyProcessDialog.parent.call( this, config );
600 * }
601 * OO.inheritClass( MyProcessDialog, OO.ui.ProcessDialog );
602 * MyProcessDialog.static.title = 'An action set in a process dialog';
603 * // An action set that uses modes ('edit' and 'help' mode, in this example).
604 * MyProcessDialog.static.actions = [
605 * { action: 'continue', modes: 'edit', label: 'Continue', flags: [ 'primary', 'constructive' ] },
606 * { action: 'help', modes: 'edit', label: 'Help' },
607 * { modes: 'edit', label: 'Cancel', flags: 'safe' },
608 * { action: 'back', modes: 'help', label: 'Back', flags: 'safe' }
609 * ];
610 *
611 * MyProcessDialog.prototype.initialize = function () {
612 * MyProcessDialog.parent.prototype.initialize.apply( this, arguments );
613 * this.panel1 = new OO.ui.PanelLayout( { padded: true, expanded: false } );
614 * this.panel1.$element.append( '<p>This dialog uses an action set (continue, help, cancel, back) configured with modes. This is edit mode. Click \'help\' to see help mode.</p>' );
615 * this.panel2 = new OO.ui.PanelLayout( { padded: true, expanded: false } );
616 * this.panel2.$element.append( '<p>This is help mode. Only the \'back\' action widget is configured to be visible here. Click \'back\' to return to \'edit\' mode.</p>' );
617 * this.stackLayout = new OO.ui.StackLayout( {
618 * items: [ this.panel1, this.panel2 ]
619 * } );
620 * this.$body.append( this.stackLayout.$element );
621 * };
622 * MyProcessDialog.prototype.getSetupProcess = function ( data ) {
623 * return MyProcessDialog.parent.prototype.getSetupProcess.call( this, data )
624 * .next( function () {
625 * this.actions.setMode( 'edit' );
626 * }, this );
627 * };
628 * MyProcessDialog.prototype.getActionProcess = function ( action ) {
629 * if ( action === 'help' ) {
630 * this.actions.setMode( 'help' );
631 * this.stackLayout.setItem( this.panel2 );
632 * } else if ( action === 'back' ) {
633 * this.actions.setMode( 'edit' );
634 * this.stackLayout.setItem( this.panel1 );
635 * } else if ( action === 'continue' ) {
636 * var dialog = this;
637 * return new OO.ui.Process( function () {
638 * dialog.close();
639 * } );
640 * }
641 * return MyProcessDialog.parent.prototype.getActionProcess.call( this, action );
642 * };
643 * MyProcessDialog.prototype.getBodyHeight = function () {
644 * return this.panel1.$element.outerHeight( true );
645 * };
646 * var windowManager = new OO.ui.WindowManager();
647 * $( 'body' ).append( windowManager.$element );
648 * var dialog = new MyProcessDialog( {
649 * size: 'medium'
650 * } );
651 * windowManager.addWindows( [ dialog ] );
652 * windowManager.openWindow( dialog );
653 *
654 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Action_sets
655 *
656 * @abstract
657 * @class
658 * @mixins OO.EventEmitter
659 *
660 * @constructor
661 * @param {Object} [config] Configuration options
662 */
663 OO.ui.ActionSet = function OoUiActionSet( config ) {
664 // Configuration initialization
665 config = config || {};
666
667 // Mixin constructors
668 OO.EventEmitter.call( this );
669
670 // Properties
671 this.list = [];
672 this.categories = {
673 actions: 'getAction',
674 flags: 'getFlags',
675 modes: 'getModes'
676 };
677 this.categorized = {};
678 this.special = {};
679 this.others = [];
680 this.organized = false;
681 this.changing = false;
682 this.changed = false;
683 };
684
685 /* Setup */
686
687 OO.mixinClass( OO.ui.ActionSet, OO.EventEmitter );
688
689 /* Static Properties */
690
691 /**
692 * Symbolic name of the flags used to identify special actions. Special actions are displayed in the
693 * header of a {@link OO.ui.ProcessDialog process dialog}.
694 * See the [OOjs UI documentation on MediaWiki][2] for more information and examples.
695 *
696 * [2]:https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs
697 *
698 * @abstract
699 * @static
700 * @inheritable
701 * @property {string}
702 */
703 OO.ui.ActionSet.static.specialFlags = [ 'safe', 'primary' ];
704
705 /* Events */
706
707 /**
708 * @event click
709 *
710 * A 'click' event is emitted when an action is clicked.
711 *
712 * @param {OO.ui.ActionWidget} action Action that was clicked
713 */
714
715 /**
716 * @event resize
717 *
718 * A 'resize' event is emitted when an action widget is resized.
719 *
720 * @param {OO.ui.ActionWidget} action Action that was resized
721 */
722
723 /**
724 * @event add
725 *
726 * An 'add' event is emitted when actions are {@link #method-add added} to the action set.
727 *
728 * @param {OO.ui.ActionWidget[]} added Actions added
729 */
730
731 /**
732 * @event remove
733 *
734 * A 'remove' event is emitted when actions are {@link #method-remove removed}
735 * or {@link #clear cleared}.
736 *
737 * @param {OO.ui.ActionWidget[]} added Actions removed
738 */
739
740 /**
741 * @event change
742 *
743 * A 'change' event is emitted when actions are {@link #method-add added}, {@link #clear cleared},
744 * or {@link #method-remove removed} from the action set or when the {@link #setMode mode} is changed.
745 *
746 */
747
748 /* Methods */
749
750 /**
751 * Handle action change events.
752 *
753 * @private
754 * @fires change
755 */
756 OO.ui.ActionSet.prototype.onActionChange = function () {
757 this.organized = false;
758 if ( this.changing ) {
759 this.changed = true;
760 } else {
761 this.emit( 'change' );
762 }
763 };
764
765 /**
766 * Check if an action is one of the special actions.
767 *
768 * @param {OO.ui.ActionWidget} action Action to check
769 * @return {boolean} Action is special
770 */
771 OO.ui.ActionSet.prototype.isSpecial = function ( action ) {
772 var flag;
773
774 for ( flag in this.special ) {
775 if ( action === this.special[ flag ] ) {
776 return true;
777 }
778 }
779
780 return false;
781 };
782
783 /**
784 * Get action widgets based on the specified filter: ‘actions’, ‘flags’, ‘modes’, ‘visible’,
785 * or ‘disabled’.
786 *
787 * @param {Object} [filters] Filters to use, omit to get all actions
788 * @param {string|string[]} [filters.actions] Actions that action widgets must have
789 * @param {string|string[]} [filters.flags] Flags that action widgets must have (e.g., 'safe')
790 * @param {string|string[]} [filters.modes] Modes that action widgets must have
791 * @param {boolean} [filters.visible] Action widgets must be visible
792 * @param {boolean} [filters.disabled] Action widgets must be disabled
793 * @return {OO.ui.ActionWidget[]} Action widgets matching all criteria
794 */
795 OO.ui.ActionSet.prototype.get = function ( filters ) {
796 var i, len, list, category, actions, index, match, matches;
797
798 if ( filters ) {
799 this.organize();
800
801 // Collect category candidates
802 matches = [];
803 for ( category in this.categorized ) {
804 list = filters[ category ];
805 if ( list ) {
806 if ( !Array.isArray( list ) ) {
807 list = [ list ];
808 }
809 for ( i = 0, len = list.length; i < len; i++ ) {
810 actions = this.categorized[ category ][ list[ i ] ];
811 if ( Array.isArray( actions ) ) {
812 matches.push.apply( matches, actions );
813 }
814 }
815 }
816 }
817 // Remove by boolean filters
818 for ( i = 0, len = matches.length; i < len; i++ ) {
819 match = matches[ i ];
820 if (
821 ( filters.visible !== undefined && match.isVisible() !== filters.visible ) ||
822 ( filters.disabled !== undefined && match.isDisabled() !== filters.disabled )
823 ) {
824 matches.splice( i, 1 );
825 len--;
826 i--;
827 }
828 }
829 // Remove duplicates
830 for ( i = 0, len = matches.length; i < len; i++ ) {
831 match = matches[ i ];
832 index = matches.lastIndexOf( match );
833 while ( index !== i ) {
834 matches.splice( index, 1 );
835 len--;
836 index = matches.lastIndexOf( match );
837 }
838 }
839 return matches;
840 }
841 return this.list.slice();
842 };
843
844 /**
845 * Get 'special' actions.
846 *
847 * Special actions are the first visible action widgets with special flags, such as 'safe' and 'primary'.
848 * Special flags can be configured in subclasses by changing the static #specialFlags property.
849 *
850 * @return {OO.ui.ActionWidget[]|null} 'Special' action widgets.
851 */
852 OO.ui.ActionSet.prototype.getSpecial = function () {
853 this.organize();
854 return $.extend( {}, this.special );
855 };
856
857 /**
858 * Get 'other' actions.
859 *
860 * Other actions include all non-special visible action widgets.
861 *
862 * @return {OO.ui.ActionWidget[]} 'Other' action widgets
863 */
864 OO.ui.ActionSet.prototype.getOthers = function () {
865 this.organize();
866 return this.others.slice();
867 };
868
869 /**
870 * Set the mode (e.g., ‘edit’ or ‘view’). Only {@link OO.ui.ActionWidget#modes actions} configured
871 * to be available in the specified mode will be made visible. All other actions will be hidden.
872 *
873 * @param {string} mode The mode. Only actions configured to be available in the specified
874 * mode will be made visible.
875 * @chainable
876 * @fires toggle
877 * @fires change
878 */
879 OO.ui.ActionSet.prototype.setMode = function ( mode ) {
880 var i, len, action;
881
882 this.changing = true;
883 for ( i = 0, len = this.list.length; i < len; i++ ) {
884 action = this.list[ i ];
885 action.toggle( action.hasMode( mode ) );
886 }
887
888 this.organized = false;
889 this.changing = false;
890 this.emit( 'change' );
891
892 return this;
893 };
894
895 /**
896 * Set the abilities of the specified actions.
897 *
898 * Action widgets that are configured with the specified actions will be enabled
899 * or disabled based on the boolean values specified in the `actions`
900 * parameter.
901 *
902 * @param {Object.<string,boolean>} actions A list keyed by action name with boolean
903 * values that indicate whether or not the action should be enabled.
904 * @chainable
905 */
906 OO.ui.ActionSet.prototype.setAbilities = function ( actions ) {
907 var i, len, action, item;
908
909 for ( i = 0, len = this.list.length; i < len; i++ ) {
910 item = this.list[ i ];
911 action = item.getAction();
912 if ( actions[ action ] !== undefined ) {
913 item.setDisabled( !actions[ action ] );
914 }
915 }
916
917 return this;
918 };
919
920 /**
921 * Executes a function once per action.
922 *
923 * When making changes to multiple actions, use this method instead of iterating over the actions
924 * manually to defer emitting a #change event until after all actions have been changed.
925 *
926 * @param {Object|null} actions Filters to use to determine which actions to iterate over; see #get
927 * @param {Function} callback Callback to run for each action; callback is invoked with three
928 * arguments: the action, the action's index, the list of actions being iterated over
929 * @chainable
930 */
931 OO.ui.ActionSet.prototype.forEach = function ( filter, callback ) {
932 this.changed = false;
933 this.changing = true;
934 this.get( filter ).forEach( callback );
935 this.changing = false;
936 if ( this.changed ) {
937 this.emit( 'change' );
938 }
939
940 return this;
941 };
942
943 /**
944 * Add action widgets to the action set.
945 *
946 * @param {OO.ui.ActionWidget[]} actions Action widgets to add
947 * @chainable
948 * @fires add
949 * @fires change
950 */
951 OO.ui.ActionSet.prototype.add = function ( actions ) {
952 var i, len, action;
953
954 this.changing = true;
955 for ( i = 0, len = actions.length; i < len; i++ ) {
956 action = actions[ i ];
957 action.connect( this, {
958 click: [ 'emit', 'click', action ],
959 resize: [ 'emit', 'resize', action ],
960 toggle: [ 'onActionChange' ]
961 } );
962 this.list.push( action );
963 }
964 this.organized = false;
965 this.emit( 'add', actions );
966 this.changing = false;
967 this.emit( 'change' );
968
969 return this;
970 };
971
972 /**
973 * Remove action widgets from the set.
974 *
975 * To remove all actions, you may wish to use the #clear method instead.
976 *
977 * @param {OO.ui.ActionWidget[]} actions Action widgets to remove
978 * @chainable
979 * @fires remove
980 * @fires change
981 */
982 OO.ui.ActionSet.prototype.remove = function ( actions ) {
983 var i, len, index, action;
984
985 this.changing = true;
986 for ( i = 0, len = actions.length; i < len; i++ ) {
987 action = actions[ i ];
988 index = this.list.indexOf( action );
989 if ( index !== -1 ) {
990 action.disconnect( this );
991 this.list.splice( index, 1 );
992 }
993 }
994 this.organized = false;
995 this.emit( 'remove', actions );
996 this.changing = false;
997 this.emit( 'change' );
998
999 return this;
1000 };
1001
1002 /**
1003 * Remove all action widets from the set.
1004 *
1005 * To remove only specified actions, use the {@link #method-remove remove} method instead.
1006 *
1007 * @chainable
1008 * @fires remove
1009 * @fires change
1010 */
1011 OO.ui.ActionSet.prototype.clear = function () {
1012 var i, len, action,
1013 removed = this.list.slice();
1014
1015 this.changing = true;
1016 for ( i = 0, len = this.list.length; i < len; i++ ) {
1017 action = this.list[ i ];
1018 action.disconnect( this );
1019 }
1020
1021 this.list = [];
1022
1023 this.organized = false;
1024 this.emit( 'remove', removed );
1025 this.changing = false;
1026 this.emit( 'change' );
1027
1028 return this;
1029 };
1030
1031 /**
1032 * Organize actions.
1033 *
1034 * This is called whenever organized information is requested. It will only reorganize the actions
1035 * if something has changed since the last time it ran.
1036 *
1037 * @private
1038 * @chainable
1039 */
1040 OO.ui.ActionSet.prototype.organize = function () {
1041 var i, iLen, j, jLen, flag, action, category, list, item, special,
1042 specialFlags = this.constructor.static.specialFlags;
1043
1044 if ( !this.organized ) {
1045 this.categorized = {};
1046 this.special = {};
1047 this.others = [];
1048 for ( i = 0, iLen = this.list.length; i < iLen; i++ ) {
1049 action = this.list[ i ];
1050 if ( action.isVisible() ) {
1051 // Populate categories
1052 for ( category in this.categories ) {
1053 if ( !this.categorized[ category ] ) {
1054 this.categorized[ category ] = {};
1055 }
1056 list = action[ this.categories[ category ] ]();
1057 if ( !Array.isArray( list ) ) {
1058 list = [ list ];
1059 }
1060 for ( j = 0, jLen = list.length; j < jLen; j++ ) {
1061 item = list[ j ];
1062 if ( !this.categorized[ category ][ item ] ) {
1063 this.categorized[ category ][ item ] = [];
1064 }
1065 this.categorized[ category ][ item ].push( action );
1066 }
1067 }
1068 // Populate special/others
1069 special = false;
1070 for ( j = 0, jLen = specialFlags.length; j < jLen; j++ ) {
1071 flag = specialFlags[ j ];
1072 if ( !this.special[ flag ] && action.hasFlag( flag ) ) {
1073 this.special[ flag ] = action;
1074 special = true;
1075 break;
1076 }
1077 }
1078 if ( !special ) {
1079 this.others.push( action );
1080 }
1081 }
1082 }
1083 this.organized = true;
1084 }
1085
1086 return this;
1087 };
1088
1089 /**
1090 * Each Element represents a rendering in the DOM—a button or an icon, for example, or anything
1091 * that is visible to a user. Unlike {@link OO.ui.Widget widgets}, plain elements usually do not have events
1092 * connected to them and can't be interacted with.
1093 *
1094 * @abstract
1095 * @class
1096 *
1097 * @constructor
1098 * @param {Object} [config] Configuration options
1099 * @cfg {string[]} [classes] The names of the CSS classes to apply to the element. CSS styles are added
1100 * to the top level (e.g., the outermost div) of the element. See the [OOjs UI documentation on MediaWiki][2]
1101 * for an example.
1102 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#cssExample
1103 * @cfg {string} [id] The HTML id attribute used in the rendered tag.
1104 * @cfg {string} [text] Text to insert
1105 * @cfg {Array} [content] An array of content elements to append (after #text).
1106 * Strings will be html-escaped; use an OO.ui.HtmlSnippet to append raw HTML.
1107 * Instances of OO.ui.Element will have their $element appended.
1108 * @cfg {jQuery} [$content] Content elements to append (after #text).
1109 * @cfg {jQuery} [$element] Wrapper element. Defaults to a new element with #getTagName.
1110 * @cfg {Mixed} [data] Custom data of any type or combination of types (e.g., string, number, array, object).
1111 * Data can also be specified with the #setData method.
1112 */
1113 OO.ui.Element = function OoUiElement( config ) {
1114 // Configuration initialization
1115 config = config || {};
1116
1117 // Properties
1118 this.$ = $;
1119 this.visible = true;
1120 this.data = config.data;
1121 this.$element = config.$element ||
1122 $( document.createElement( this.getTagName() ) );
1123 this.elementGroup = null;
1124 this.debouncedUpdateThemeClassesHandler = OO.ui.debounce( this.debouncedUpdateThemeClasses );
1125
1126 // Initialization
1127 if ( Array.isArray( config.classes ) ) {
1128 this.$element.addClass( config.classes.join( ' ' ) );
1129 }
1130 if ( config.id ) {
1131 this.$element.attr( 'id', config.id );
1132 }
1133 if ( config.text ) {
1134 this.$element.text( config.text );
1135 }
1136 if ( config.content ) {
1137 // The `content` property treats plain strings as text; use an
1138 // HtmlSnippet to append HTML content. `OO.ui.Element`s get their
1139 // appropriate $element appended.
1140 this.$element.append( config.content.map( function ( v ) {
1141 if ( typeof v === 'string' ) {
1142 // Escape string so it is properly represented in HTML.
1143 return document.createTextNode( v );
1144 } else if ( v instanceof OO.ui.HtmlSnippet ) {
1145 // Bypass escaping.
1146 return v.toString();
1147 } else if ( v instanceof OO.ui.Element ) {
1148 return v.$element;
1149 }
1150 return v;
1151 } ) );
1152 }
1153 if ( config.$content ) {
1154 // The `$content` property treats plain strings as HTML.
1155 this.$element.append( config.$content );
1156 }
1157 };
1158
1159 /* Setup */
1160
1161 OO.initClass( OO.ui.Element );
1162
1163 /* Static Properties */
1164
1165 /**
1166 * The name of the HTML tag used by the element.
1167 *
1168 * The static value may be ignored if the #getTagName method is overridden.
1169 *
1170 * @static
1171 * @inheritable
1172 * @property {string}
1173 */
1174 OO.ui.Element.static.tagName = 'div';
1175
1176 /* Static Methods */
1177
1178 /**
1179 * Reconstitute a JavaScript object corresponding to a widget created
1180 * by the PHP implementation.
1181 *
1182 * @param {string|HTMLElement|jQuery} idOrNode
1183 * A DOM id (if a string) or node for the widget to infuse.
1184 * @return {OO.ui.Element}
1185 * The `OO.ui.Element` corresponding to this (infusable) document node.
1186 * For `Tag` objects emitted on the HTML side (used occasionally for content)
1187 * the value returned is a newly-created Element wrapping around the existing
1188 * DOM node.
1189 */
1190 OO.ui.Element.static.infuse = function ( idOrNode ) {
1191 var obj = OO.ui.Element.static.unsafeInfuse( idOrNode, false );
1192 // Verify that the type matches up.
1193 // FIXME: uncomment after T89721 is fixed (see T90929)
1194 /*
1195 if ( !( obj instanceof this['class'] ) ) {
1196 throw new Error( 'Infusion type mismatch!' );
1197 }
1198 */
1199 return obj;
1200 };
1201
1202 /**
1203 * Implementation helper for `infuse`; skips the type check and has an
1204 * extra property so that only the top-level invocation touches the DOM.
1205 * @private
1206 * @param {string|HTMLElement|jQuery} idOrNode
1207 * @param {jQuery.Promise|boolean} domPromise A promise that will be resolved
1208 * when the top-level widget of this infusion is inserted into DOM,
1209 * replacing the original node; or false for top-level invocation.
1210 * @return {OO.ui.Element}
1211 */
1212 OO.ui.Element.static.unsafeInfuse = function ( idOrNode, domPromise ) {
1213 // look for a cached result of a previous infusion.
1214 var id, $elem, data, cls, parts, parent, obj, top, state;
1215 if ( typeof idOrNode === 'string' ) {
1216 id = idOrNode;
1217 $elem = $( document.getElementById( id ) );
1218 } else {
1219 $elem = $( idOrNode );
1220 id = $elem.attr( 'id' );
1221 }
1222 if ( !$elem.length ) {
1223 throw new Error( 'Widget not found: ' + id );
1224 }
1225 data = $elem.data( 'ooui-infused' ) || $elem[ 0 ].oouiInfused;
1226 if ( data ) {
1227 // cached!
1228 if ( data === true ) {
1229 throw new Error( 'Circular dependency! ' + id );
1230 }
1231 return data;
1232 }
1233 data = $elem.attr( 'data-ooui' );
1234 if ( !data ) {
1235 throw new Error( 'No infusion data found: ' + id );
1236 }
1237 try {
1238 data = $.parseJSON( data );
1239 } catch ( _ ) {
1240 data = null;
1241 }
1242 if ( !( data && data._ ) ) {
1243 throw new Error( 'No valid infusion data found: ' + id );
1244 }
1245 if ( data._ === 'Tag' ) {
1246 // Special case: this is a raw Tag; wrap existing node, don't rebuild.
1247 return new OO.ui.Element( { $element: $elem } );
1248 }
1249 parts = data._.split( '.' );
1250 cls = OO.getProp.apply( OO, [ window ].concat( parts ) );
1251 if ( cls === undefined ) {
1252 // The PHP output might be old and not including the "OO.ui" prefix
1253 // TODO: Remove this back-compat after next major release
1254 cls = OO.getProp.apply( OO, [ OO.ui ].concat( parts ) );
1255 if ( cls === undefined ) {
1256 throw new Error( 'Unknown widget type: id: ' + id + ', class: ' + data._ );
1257 }
1258 }
1259
1260 // Verify that we're creating an OO.ui.Element instance
1261 parent = cls.parent;
1262
1263 while ( parent !== undefined ) {
1264 if ( parent === OO.ui.Element ) {
1265 // Safe
1266 break;
1267 }
1268
1269 parent = parent.parent;
1270 }
1271
1272 if ( parent !== OO.ui.Element ) {
1273 throw new Error( 'Unknown widget type: id: ' + id + ', class: ' + data._ );
1274 }
1275
1276 if ( domPromise === false ) {
1277 top = $.Deferred();
1278 domPromise = top.promise();
1279 }
1280 $elem.data( 'ooui-infused', true ); // prevent loops
1281 data.id = id; // implicit
1282 data = OO.copy( data, null, function deserialize( value ) {
1283 if ( OO.isPlainObject( value ) ) {
1284 if ( value.tag ) {
1285 return OO.ui.Element.static.unsafeInfuse( value.tag, domPromise );
1286 }
1287 if ( value.html ) {
1288 return new OO.ui.HtmlSnippet( value.html );
1289 }
1290 }
1291 } );
1292 // jscs:disable requireCapitalizedConstructors
1293 obj = new cls( data ); // rebuild widget
1294 // pick up dynamic state, like focus, value of form inputs, scroll position, etc.
1295 state = obj.gatherPreInfuseState( $elem );
1296 // now replace old DOM with this new DOM.
1297 if ( top ) {
1298 $elem.replaceWith( obj.$element );
1299 // This element is now gone from the DOM, but if anyone is holding a reference to it,
1300 // let's allow them to OO.ui.infuse() it and do what they expect (T105828).
1301 // Do not use jQuery.data(), as using it on detached nodes leaks memory in 1.x line by design.
1302 $elem[ 0 ].oouiInfused = obj;
1303 top.resolve();
1304 }
1305 obj.$element.data( 'ooui-infused', obj );
1306 // set the 'data-ooui' attribute so we can identify infused widgets
1307 obj.$element.attr( 'data-ooui', '' );
1308 // restore dynamic state after the new element is inserted into DOM
1309 domPromise.done( obj.restorePreInfuseState.bind( obj, state ) );
1310 return obj;
1311 };
1312
1313 /**
1314 * Get a jQuery function within a specific document.
1315 *
1316 * @static
1317 * @param {jQuery|HTMLElement|HTMLDocument|Window} context Context to bind the function to
1318 * @param {jQuery} [$iframe] HTML iframe element that contains the document, omit if document is
1319 * not in an iframe
1320 * @return {Function} Bound jQuery function
1321 */
1322 OO.ui.Element.static.getJQuery = function ( context, $iframe ) {
1323 function wrapper( selector ) {
1324 return $( selector, wrapper.context );
1325 }
1326
1327 wrapper.context = this.getDocument( context );
1328
1329 if ( $iframe ) {
1330 wrapper.$iframe = $iframe;
1331 }
1332
1333 return wrapper;
1334 };
1335
1336 /**
1337 * Get the document of an element.
1338 *
1339 * @static
1340 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Object to get the document for
1341 * @return {HTMLDocument|null} Document object
1342 */
1343 OO.ui.Element.static.getDocument = function ( obj ) {
1344 // jQuery - selections created "offscreen" won't have a context, so .context isn't reliable
1345 return ( obj[ 0 ] && obj[ 0 ].ownerDocument ) ||
1346 // Empty jQuery selections might have a context
1347 obj.context ||
1348 // HTMLElement
1349 obj.ownerDocument ||
1350 // Window
1351 obj.document ||
1352 // HTMLDocument
1353 ( obj.nodeType === 9 && obj ) ||
1354 null;
1355 };
1356
1357 /**
1358 * Get the window of an element or document.
1359 *
1360 * @static
1361 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the window for
1362 * @return {Window} Window object
1363 */
1364 OO.ui.Element.static.getWindow = function ( obj ) {
1365 var doc = this.getDocument( obj );
1366 // Support: IE 8
1367 // Standard Document.defaultView is IE9+
1368 return doc.parentWindow || doc.defaultView;
1369 };
1370
1371 /**
1372 * Get the direction of an element or document.
1373 *
1374 * @static
1375 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the direction for
1376 * @return {string} Text direction, either 'ltr' or 'rtl'
1377 */
1378 OO.ui.Element.static.getDir = function ( obj ) {
1379 var isDoc, isWin;
1380
1381 if ( obj instanceof jQuery ) {
1382 obj = obj[ 0 ];
1383 }
1384 isDoc = obj.nodeType === 9;
1385 isWin = obj.document !== undefined;
1386 if ( isDoc || isWin ) {
1387 if ( isWin ) {
1388 obj = obj.document;
1389 }
1390 obj = obj.body;
1391 }
1392 return $( obj ).css( 'direction' );
1393 };
1394
1395 /**
1396 * Get the offset between two frames.
1397 *
1398 * TODO: Make this function not use recursion.
1399 *
1400 * @static
1401 * @param {Window} from Window of the child frame
1402 * @param {Window} [to=window] Window of the parent frame
1403 * @param {Object} [offset] Offset to start with, used internally
1404 * @return {Object} Offset object, containing left and top properties
1405 */
1406 OO.ui.Element.static.getFrameOffset = function ( from, to, offset ) {
1407 var i, len, frames, frame, rect;
1408
1409 if ( !to ) {
1410 to = window;
1411 }
1412 if ( !offset ) {
1413 offset = { top: 0, left: 0 };
1414 }
1415 if ( from.parent === from ) {
1416 return offset;
1417 }
1418
1419 // Get iframe element
1420 frames = from.parent.document.getElementsByTagName( 'iframe' );
1421 for ( i = 0, len = frames.length; i < len; i++ ) {
1422 if ( frames[ i ].contentWindow === from ) {
1423 frame = frames[ i ];
1424 break;
1425 }
1426 }
1427
1428 // Recursively accumulate offset values
1429 if ( frame ) {
1430 rect = frame.getBoundingClientRect();
1431 offset.left += rect.left;
1432 offset.top += rect.top;
1433 if ( from !== to ) {
1434 this.getFrameOffset( from.parent, offset );
1435 }
1436 }
1437 return offset;
1438 };
1439
1440 /**
1441 * Get the offset between two elements.
1442 *
1443 * The two elements may be in a different frame, but in that case the frame $element is in must
1444 * be contained in the frame $anchor is in.
1445 *
1446 * @static
1447 * @param {jQuery} $element Element whose position to get
1448 * @param {jQuery} $anchor Element to get $element's position relative to
1449 * @return {Object} Translated position coordinates, containing top and left properties
1450 */
1451 OO.ui.Element.static.getRelativePosition = function ( $element, $anchor ) {
1452 var iframe, iframePos,
1453 pos = $element.offset(),
1454 anchorPos = $anchor.offset(),
1455 elementDocument = this.getDocument( $element ),
1456 anchorDocument = this.getDocument( $anchor );
1457
1458 // If $element isn't in the same document as $anchor, traverse up
1459 while ( elementDocument !== anchorDocument ) {
1460 iframe = elementDocument.defaultView.frameElement;
1461 if ( !iframe ) {
1462 throw new Error( '$element frame is not contained in $anchor frame' );
1463 }
1464 iframePos = $( iframe ).offset();
1465 pos.left += iframePos.left;
1466 pos.top += iframePos.top;
1467 elementDocument = iframe.ownerDocument;
1468 }
1469 pos.left -= anchorPos.left;
1470 pos.top -= anchorPos.top;
1471 return pos;
1472 };
1473
1474 /**
1475 * Get element border sizes.
1476 *
1477 * @static
1478 * @param {HTMLElement} el Element to measure
1479 * @return {Object} Dimensions object with `top`, `left`, `bottom` and `right` properties
1480 */
1481 OO.ui.Element.static.getBorders = function ( el ) {
1482 var doc = el.ownerDocument,
1483 // Support: IE 8
1484 // Standard Document.defaultView is IE9+
1485 win = doc.parentWindow || doc.defaultView,
1486 style = win && win.getComputedStyle ?
1487 win.getComputedStyle( el, null ) :
1488 // Support: IE 8
1489 // Standard getComputedStyle() is IE9+
1490 el.currentStyle,
1491 $el = $( el ),
1492 top = parseFloat( style ? style.borderTopWidth : $el.css( 'borderTopWidth' ) ) || 0,
1493 left = parseFloat( style ? style.borderLeftWidth : $el.css( 'borderLeftWidth' ) ) || 0,
1494 bottom = parseFloat( style ? style.borderBottomWidth : $el.css( 'borderBottomWidth' ) ) || 0,
1495 right = parseFloat( style ? style.borderRightWidth : $el.css( 'borderRightWidth' ) ) || 0;
1496
1497 return {
1498 top: top,
1499 left: left,
1500 bottom: bottom,
1501 right: right
1502 };
1503 };
1504
1505 /**
1506 * Get dimensions of an element or window.
1507 *
1508 * @static
1509 * @param {HTMLElement|Window} el Element to measure
1510 * @return {Object} Dimensions object with `borders`, `scroll`, `scrollbar` and `rect` properties
1511 */
1512 OO.ui.Element.static.getDimensions = function ( el ) {
1513 var $el, $win,
1514 doc = el.ownerDocument || el.document,
1515 // Support: IE 8
1516 // Standard Document.defaultView is IE9+
1517 win = doc.parentWindow || doc.defaultView;
1518
1519 if ( win === el || el === doc.documentElement ) {
1520 $win = $( win );
1521 return {
1522 borders: { top: 0, left: 0, bottom: 0, right: 0 },
1523 scroll: {
1524 top: $win.scrollTop(),
1525 left: $win.scrollLeft()
1526 },
1527 scrollbar: { right: 0, bottom: 0 },
1528 rect: {
1529 top: 0,
1530 left: 0,
1531 bottom: $win.innerHeight(),
1532 right: $win.innerWidth()
1533 }
1534 };
1535 } else {
1536 $el = $( el );
1537 return {
1538 borders: this.getBorders( el ),
1539 scroll: {
1540 top: $el.scrollTop(),
1541 left: $el.scrollLeft()
1542 },
1543 scrollbar: {
1544 right: $el.innerWidth() - el.clientWidth,
1545 bottom: $el.innerHeight() - el.clientHeight
1546 },
1547 rect: el.getBoundingClientRect()
1548 };
1549 }
1550 };
1551
1552 /**
1553 * Get scrollable object parent
1554 *
1555 * documentElement can't be used to get or set the scrollTop
1556 * property on Blink. Changing and testing its value lets us
1557 * use 'body' or 'documentElement' based on what is working.
1558 *
1559 * https://code.google.com/p/chromium/issues/detail?id=303131
1560 *
1561 * @static
1562 * @param {HTMLElement} el Element to find scrollable parent for
1563 * @return {HTMLElement} Scrollable parent
1564 */
1565 OO.ui.Element.static.getRootScrollableElement = function ( el ) {
1566 var scrollTop, body;
1567
1568 if ( OO.ui.scrollableElement === undefined ) {
1569 body = el.ownerDocument.body;
1570 scrollTop = body.scrollTop;
1571 body.scrollTop = 1;
1572
1573 if ( body.scrollTop === 1 ) {
1574 body.scrollTop = scrollTop;
1575 OO.ui.scrollableElement = 'body';
1576 } else {
1577 OO.ui.scrollableElement = 'documentElement';
1578 }
1579 }
1580
1581 return el.ownerDocument[ OO.ui.scrollableElement ];
1582 };
1583
1584 /**
1585 * Get closest scrollable container.
1586 *
1587 * Traverses up until either a scrollable element or the root is reached, in which case the window
1588 * will be returned.
1589 *
1590 * @static
1591 * @param {HTMLElement} el Element to find scrollable container for
1592 * @param {string} [dimension] Dimension of scrolling to look for; `x`, `y` or omit for either
1593 * @return {HTMLElement} Closest scrollable container
1594 */
1595 OO.ui.Element.static.getClosestScrollableContainer = function ( el, dimension ) {
1596 var i, val,
1597 // props = [ 'overflow' ] doesn't work due to https://bugzilla.mozilla.org/show_bug.cgi?id=889091
1598 props = [ 'overflow-x', 'overflow-y' ],
1599 $parent = $( el ).parent();
1600
1601 if ( dimension === 'x' || dimension === 'y' ) {
1602 props = [ 'overflow-' + dimension ];
1603 }
1604
1605 while ( $parent.length ) {
1606 if ( $parent[ 0 ] === this.getRootScrollableElement( el ) ) {
1607 return $parent[ 0 ];
1608 }
1609 i = props.length;
1610 while ( i-- ) {
1611 val = $parent.css( props[ i ] );
1612 if ( val === 'auto' || val === 'scroll' ) {
1613 return $parent[ 0 ];
1614 }
1615 }
1616 $parent = $parent.parent();
1617 }
1618 return this.getDocument( el ).body;
1619 };
1620
1621 /**
1622 * Scroll element into view.
1623 *
1624 * @static
1625 * @param {HTMLElement} el Element to scroll into view
1626 * @param {Object} [config] Configuration options
1627 * @param {string} [config.duration] jQuery animation duration value
1628 * @param {string} [config.direction] Scroll in only one direction, e.g. 'x' or 'y', omit
1629 * to scroll in both directions
1630 * @param {Function} [config.complete] Function to call when scrolling completes
1631 */
1632 OO.ui.Element.static.scrollIntoView = function ( el, config ) {
1633 var rel, anim, callback, sc, $sc, eld, scd, $win;
1634
1635 // Configuration initialization
1636 config = config || {};
1637
1638 anim = {};
1639 callback = typeof config.complete === 'function' && config.complete;
1640 sc = this.getClosestScrollableContainer( el, config.direction );
1641 $sc = $( sc );
1642 eld = this.getDimensions( el );
1643 scd = this.getDimensions( sc );
1644 $win = $( this.getWindow( el ) );
1645
1646 // Compute the distances between the edges of el and the edges of the scroll viewport
1647 if ( $sc.is( 'html, body' ) ) {
1648 // If the scrollable container is the root, this is easy
1649 rel = {
1650 top: eld.rect.top,
1651 bottom: $win.innerHeight() - eld.rect.bottom,
1652 left: eld.rect.left,
1653 right: $win.innerWidth() - eld.rect.right
1654 };
1655 } else {
1656 // Otherwise, we have to subtract el's coordinates from sc's coordinates
1657 rel = {
1658 top: eld.rect.top - ( scd.rect.top + scd.borders.top ),
1659 bottom: scd.rect.bottom - scd.borders.bottom - scd.scrollbar.bottom - eld.rect.bottom,
1660 left: eld.rect.left - ( scd.rect.left + scd.borders.left ),
1661 right: scd.rect.right - scd.borders.right - scd.scrollbar.right - eld.rect.right
1662 };
1663 }
1664
1665 if ( !config.direction || config.direction === 'y' ) {
1666 if ( rel.top < 0 ) {
1667 anim.scrollTop = scd.scroll.top + rel.top;
1668 } else if ( rel.top > 0 && rel.bottom < 0 ) {
1669 anim.scrollTop = scd.scroll.top + Math.min( rel.top, -rel.bottom );
1670 }
1671 }
1672 if ( !config.direction || config.direction === 'x' ) {
1673 if ( rel.left < 0 ) {
1674 anim.scrollLeft = scd.scroll.left + rel.left;
1675 } else if ( rel.left > 0 && rel.right < 0 ) {
1676 anim.scrollLeft = scd.scroll.left + Math.min( rel.left, -rel.right );
1677 }
1678 }
1679 if ( !$.isEmptyObject( anim ) ) {
1680 $sc.stop( true ).animate( anim, config.duration || 'fast' );
1681 if ( callback ) {
1682 $sc.queue( function ( next ) {
1683 callback();
1684 next();
1685 } );
1686 }
1687 } else {
1688 if ( callback ) {
1689 callback();
1690 }
1691 }
1692 };
1693
1694 /**
1695 * Force the browser to reconsider whether it really needs to render scrollbars inside the element
1696 * and reserve space for them, because it probably doesn't.
1697 *
1698 * Workaround primarily for <https://code.google.com/p/chromium/issues/detail?id=387290>, but also
1699 * similar bugs in other browsers. "Just" forcing a reflow is not sufficient in all cases, we need
1700 * to first actually detach (or hide, but detaching is simpler) all children, *then* force a reflow,
1701 * and then reattach (or show) them back.
1702 *
1703 * @static
1704 * @param {HTMLElement} el Element to reconsider the scrollbars on
1705 */
1706 OO.ui.Element.static.reconsiderScrollbars = function ( el ) {
1707 var i, len, scrollLeft, scrollTop, nodes = [];
1708 // Save scroll position
1709 scrollLeft = el.scrollLeft;
1710 scrollTop = el.scrollTop;
1711 // Detach all children
1712 while ( el.firstChild ) {
1713 nodes.push( el.firstChild );
1714 el.removeChild( el.firstChild );
1715 }
1716 // Force reflow
1717 void el.offsetHeight;
1718 // Reattach all children
1719 for ( i = 0, len = nodes.length; i < len; i++ ) {
1720 el.appendChild( nodes[ i ] );
1721 }
1722 // Restore scroll position (no-op if scrollbars disappeared)
1723 el.scrollLeft = scrollLeft;
1724 el.scrollTop = scrollTop;
1725 };
1726
1727 /* Methods */
1728
1729 /**
1730 * Toggle visibility of an element.
1731 *
1732 * @param {boolean} [show] Make element visible, omit to toggle visibility
1733 * @fires visible
1734 * @chainable
1735 */
1736 OO.ui.Element.prototype.toggle = function ( show ) {
1737 show = show === undefined ? !this.visible : !!show;
1738
1739 if ( show !== this.isVisible() ) {
1740 this.visible = show;
1741 this.$element.toggleClass( 'oo-ui-element-hidden', !this.visible );
1742 this.emit( 'toggle', show );
1743 }
1744
1745 return this;
1746 };
1747
1748 /**
1749 * Check if element is visible.
1750 *
1751 * @return {boolean} element is visible
1752 */
1753 OO.ui.Element.prototype.isVisible = function () {
1754 return this.visible;
1755 };
1756
1757 /**
1758 * Get element data.
1759 *
1760 * @return {Mixed} Element data
1761 */
1762 OO.ui.Element.prototype.getData = function () {
1763 return this.data;
1764 };
1765
1766 /**
1767 * Set element data.
1768 *
1769 * @param {Mixed} Element data
1770 * @chainable
1771 */
1772 OO.ui.Element.prototype.setData = function ( data ) {
1773 this.data = data;
1774 return this;
1775 };
1776
1777 /**
1778 * Check if element supports one or more methods.
1779 *
1780 * @param {string|string[]} methods Method or list of methods to check
1781 * @return {boolean} All methods are supported
1782 */
1783 OO.ui.Element.prototype.supports = function ( methods ) {
1784 var i, len,
1785 support = 0;
1786
1787 methods = Array.isArray( methods ) ? methods : [ methods ];
1788 for ( i = 0, len = methods.length; i < len; i++ ) {
1789 if ( $.isFunction( this[ methods[ i ] ] ) ) {
1790 support++;
1791 }
1792 }
1793
1794 return methods.length === support;
1795 };
1796
1797 /**
1798 * Update the theme-provided classes.
1799 *
1800 * @localdoc This is called in element mixins and widget classes any time state changes.
1801 * Updating is debounced, minimizing overhead of changing multiple attributes and
1802 * guaranteeing that theme updates do not occur within an element's constructor
1803 */
1804 OO.ui.Element.prototype.updateThemeClasses = function () {
1805 this.debouncedUpdateThemeClassesHandler();
1806 };
1807
1808 /**
1809 * @private
1810 * @localdoc This method is called directly from the QUnit tests instead of #updateThemeClasses, to
1811 * make them synchronous.
1812 */
1813 OO.ui.Element.prototype.debouncedUpdateThemeClasses = function () {
1814 OO.ui.theme.updateElementClasses( this );
1815 };
1816
1817 /**
1818 * Get the HTML tag name.
1819 *
1820 * Override this method to base the result on instance information.
1821 *
1822 * @return {string} HTML tag name
1823 */
1824 OO.ui.Element.prototype.getTagName = function () {
1825 return this.constructor.static.tagName;
1826 };
1827
1828 /**
1829 * Check if the element is attached to the DOM
1830 * @return {boolean} The element is attached to the DOM
1831 */
1832 OO.ui.Element.prototype.isElementAttached = function () {
1833 return $.contains( this.getElementDocument(), this.$element[ 0 ] );
1834 };
1835
1836 /**
1837 * Get the DOM document.
1838 *
1839 * @return {HTMLDocument} Document object
1840 */
1841 OO.ui.Element.prototype.getElementDocument = function () {
1842 // Don't cache this in other ways either because subclasses could can change this.$element
1843 return OO.ui.Element.static.getDocument( this.$element );
1844 };
1845
1846 /**
1847 * Get the DOM window.
1848 *
1849 * @return {Window} Window object
1850 */
1851 OO.ui.Element.prototype.getElementWindow = function () {
1852 return OO.ui.Element.static.getWindow( this.$element );
1853 };
1854
1855 /**
1856 * Get closest scrollable container.
1857 */
1858 OO.ui.Element.prototype.getClosestScrollableElementContainer = function () {
1859 return OO.ui.Element.static.getClosestScrollableContainer( this.$element[ 0 ] );
1860 };
1861
1862 /**
1863 * Get group element is in.
1864 *
1865 * @return {OO.ui.mixin.GroupElement|null} Group element, null if none
1866 */
1867 OO.ui.Element.prototype.getElementGroup = function () {
1868 return this.elementGroup;
1869 };
1870
1871 /**
1872 * Set group element is in.
1873 *
1874 * @param {OO.ui.mixin.GroupElement|null} group Group element, null if none
1875 * @chainable
1876 */
1877 OO.ui.Element.prototype.setElementGroup = function ( group ) {
1878 this.elementGroup = group;
1879 return this;
1880 };
1881
1882 /**
1883 * Scroll element into view.
1884 *
1885 * @param {Object} [config] Configuration options
1886 */
1887 OO.ui.Element.prototype.scrollElementIntoView = function ( config ) {
1888 return OO.ui.Element.static.scrollIntoView( this.$element[ 0 ], config );
1889 };
1890
1891 /**
1892 * Gather the dynamic state (focus, value of form inputs, scroll position, etc.) of a HTML DOM node
1893 * (and its children) that represent an Element of the same type and configuration as the current
1894 * one, generated by the PHP implementation.
1895 *
1896 * This method is called just before `node` is detached from the DOM. The return value of this
1897 * function will be passed to #restorePreInfuseState after this widget's #$element is inserted into
1898 * DOM to replace `node`.
1899 *
1900 * @protected
1901 * @param {HTMLElement} node
1902 * @return {Object}
1903 */
1904 OO.ui.Element.prototype.gatherPreInfuseState = function () {
1905 return {};
1906 };
1907
1908 /**
1909 * Restore the pre-infusion dynamic state for this widget.
1910 *
1911 * This method is called after #$element has been inserted into DOM. The parameter is the return
1912 * value of #gatherPreInfuseState.
1913 *
1914 * @protected
1915 * @param {Object} state
1916 */
1917 OO.ui.Element.prototype.restorePreInfuseState = function () {
1918 };
1919
1920 /**
1921 * Layouts are containers for elements and are used to arrange other widgets of arbitrary type in a way
1922 * that is centrally controlled and can be updated dynamically. Layouts can be, and usually are, combined.
1923 * See {@link OO.ui.FieldsetLayout FieldsetLayout}, {@link OO.ui.FieldLayout FieldLayout}, {@link OO.ui.FormLayout FormLayout},
1924 * {@link OO.ui.PanelLayout PanelLayout}, {@link OO.ui.StackLayout StackLayout}, {@link OO.ui.PageLayout PageLayout},
1925 * {@link OO.ui.HorizontalLayout HorizontalLayout}, and {@link OO.ui.BookletLayout BookletLayout} for more information and examples.
1926 *
1927 * @abstract
1928 * @class
1929 * @extends OO.ui.Element
1930 * @mixins OO.EventEmitter
1931 *
1932 * @constructor
1933 * @param {Object} [config] Configuration options
1934 */
1935 OO.ui.Layout = function OoUiLayout( config ) {
1936 // Configuration initialization
1937 config = config || {};
1938
1939 // Parent constructor
1940 OO.ui.Layout.parent.call( this, config );
1941
1942 // Mixin constructors
1943 OO.EventEmitter.call( this );
1944
1945 // Initialization
1946 this.$element.addClass( 'oo-ui-layout' );
1947 };
1948
1949 /* Setup */
1950
1951 OO.inheritClass( OO.ui.Layout, OO.ui.Element );
1952 OO.mixinClass( OO.ui.Layout, OO.EventEmitter );
1953
1954 /**
1955 * Widgets are compositions of one or more OOjs UI elements that users can both view
1956 * and interact with. All widgets can be configured and modified via a standard API,
1957 * and their state can change dynamically according to a model.
1958 *
1959 * @abstract
1960 * @class
1961 * @extends OO.ui.Element
1962 * @mixins OO.EventEmitter
1963 *
1964 * @constructor
1965 * @param {Object} [config] Configuration options
1966 * @cfg {boolean} [disabled=false] Disable the widget. Disabled widgets cannot be used and their
1967 * appearance reflects this state.
1968 */
1969 OO.ui.Widget = function OoUiWidget( config ) {
1970 // Initialize config
1971 config = $.extend( { disabled: false }, config );
1972
1973 // Parent constructor
1974 OO.ui.Widget.parent.call( this, config );
1975
1976 // Mixin constructors
1977 OO.EventEmitter.call( this );
1978
1979 // Properties
1980 this.disabled = null;
1981 this.wasDisabled = null;
1982
1983 // Initialization
1984 this.$element.addClass( 'oo-ui-widget' );
1985 this.setDisabled( !!config.disabled );
1986 };
1987
1988 /* Setup */
1989
1990 OO.inheritClass( OO.ui.Widget, OO.ui.Element );
1991 OO.mixinClass( OO.ui.Widget, OO.EventEmitter );
1992
1993 /* Static Properties */
1994
1995 /**
1996 * Whether this widget will behave reasonably when wrapped in a HTML `<label>`. If this is true,
1997 * wrappers such as OO.ui.FieldLayout may use a `<label>` instead of implementing own label click
1998 * handling.
1999 *
2000 * @static
2001 * @inheritable
2002 * @property {boolean}
2003 */
2004 OO.ui.Widget.static.supportsSimpleLabel = false;
2005
2006 /* Events */
2007
2008 /**
2009 * @event disable
2010 *
2011 * A 'disable' event is emitted when the disabled state of the widget changes
2012 * (i.e. on disable **and** enable).
2013 *
2014 * @param {boolean} disabled Widget is disabled
2015 */
2016
2017 /**
2018 * @event toggle
2019 *
2020 * A 'toggle' event is emitted when the visibility of the widget changes.
2021 *
2022 * @param {boolean} visible Widget is visible
2023 */
2024
2025 /* Methods */
2026
2027 /**
2028 * Check if the widget is disabled.
2029 *
2030 * @return {boolean} Widget is disabled
2031 */
2032 OO.ui.Widget.prototype.isDisabled = function () {
2033 return this.disabled;
2034 };
2035
2036 /**
2037 * Set the 'disabled' state of the widget.
2038 *
2039 * When a widget is disabled, it cannot be used and its appearance is updated to reflect this state.
2040 *
2041 * @param {boolean} disabled Disable widget
2042 * @chainable
2043 */
2044 OO.ui.Widget.prototype.setDisabled = function ( disabled ) {
2045 var isDisabled;
2046
2047 this.disabled = !!disabled;
2048 isDisabled = this.isDisabled();
2049 if ( isDisabled !== this.wasDisabled ) {
2050 this.$element.toggleClass( 'oo-ui-widget-disabled', isDisabled );
2051 this.$element.toggleClass( 'oo-ui-widget-enabled', !isDisabled );
2052 this.$element.attr( 'aria-disabled', isDisabled.toString() );
2053 this.emit( 'disable', isDisabled );
2054 this.updateThemeClasses();
2055 }
2056 this.wasDisabled = isDisabled;
2057
2058 return this;
2059 };
2060
2061 /**
2062 * Update the disabled state, in case of changes in parent widget.
2063 *
2064 * @chainable
2065 */
2066 OO.ui.Widget.prototype.updateDisabled = function () {
2067 this.setDisabled( this.disabled );
2068 return this;
2069 };
2070
2071 /**
2072 * A window is a container for elements that are in a child frame. They are used with
2073 * a window manager (OO.ui.WindowManager), which is used to open and close the window and control
2074 * its presentation. The size of a window is specified using a symbolic name (e.g., ‘small’, ‘medium’,
2075 * ‘large’), which is interpreted by the window manager. If the requested size is not recognized,
2076 * the window manager will choose a sensible fallback.
2077 *
2078 * The lifecycle of a window has three primary stages (opening, opened, and closing) in which
2079 * different processes are executed:
2080 *
2081 * **opening**: The opening stage begins when the window manager's {@link OO.ui.WindowManager#openWindow
2082 * openWindow} or the window's {@link #open open} methods are used, and the window manager begins to open
2083 * the window.
2084 *
2085 * - {@link #getSetupProcess} method is called and its result executed
2086 * - {@link #getReadyProcess} method is called and its result executed
2087 *
2088 * **opened**: The window is now open
2089 *
2090 * **closing**: The closing stage begins when the window manager's
2091 * {@link OO.ui.WindowManager#closeWindow closeWindow}
2092 * or the window's {@link #close} methods are used, and the window manager begins to close the window.
2093 *
2094 * - {@link #getHoldProcess} method is called and its result executed
2095 * - {@link #getTeardownProcess} method is called and its result executed. The window is now closed
2096 *
2097 * Each of the window's processes (setup, ready, hold, and teardown) can be extended in subclasses
2098 * by overriding the window's #getSetupProcess, #getReadyProcess, #getHoldProcess and #getTeardownProcess
2099 * methods. Note that each {@link OO.ui.Process process} is executed in series, so asynchronous
2100 * processing can complete. Always assume window processes are executed asynchronously.
2101 *
2102 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
2103 *
2104 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows
2105 *
2106 * @abstract
2107 * @class
2108 * @extends OO.ui.Element
2109 * @mixins OO.EventEmitter
2110 *
2111 * @constructor
2112 * @param {Object} [config] Configuration options
2113 * @cfg {string} [size] Symbolic name of the dialog size: `small`, `medium`, `large`, `larger` or
2114 * `full`. If omitted, the value of the {@link #static-size static size} property will be used.
2115 */
2116 OO.ui.Window = function OoUiWindow( config ) {
2117 // Configuration initialization
2118 config = config || {};
2119
2120 // Parent constructor
2121 OO.ui.Window.parent.call( this, config );
2122
2123 // Mixin constructors
2124 OO.EventEmitter.call( this );
2125
2126 // Properties
2127 this.manager = null;
2128 this.size = config.size || this.constructor.static.size;
2129 this.$frame = $( '<div>' );
2130 this.$overlay = $( '<div>' );
2131 this.$content = $( '<div>' );
2132
2133 this.$focusTrapBefore = $( '<div>' ).prop( 'tabIndex', 0 );
2134 this.$focusTrapAfter = $( '<div>' ).prop( 'tabIndex', 0 );
2135 this.$focusTraps = this.$focusTrapBefore.add( this.$focusTrapAfter );
2136
2137 // Initialization
2138 this.$overlay.addClass( 'oo-ui-window-overlay' );
2139 this.$content
2140 .addClass( 'oo-ui-window-content' )
2141 .attr( 'tabindex', 0 );
2142 this.$frame
2143 .addClass( 'oo-ui-window-frame' )
2144 .append( this.$focusTrapBefore, this.$content, this.$focusTrapAfter );
2145
2146 this.$element
2147 .addClass( 'oo-ui-window' )
2148 .append( this.$frame, this.$overlay );
2149
2150 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
2151 // that reference properties not initialized at that time of parent class construction
2152 // TODO: Find a better way to handle post-constructor setup
2153 this.visible = false;
2154 this.$element.addClass( 'oo-ui-element-hidden' );
2155 };
2156
2157 /* Setup */
2158
2159 OO.inheritClass( OO.ui.Window, OO.ui.Element );
2160 OO.mixinClass( OO.ui.Window, OO.EventEmitter );
2161
2162 /* Static Properties */
2163
2164 /**
2165 * Symbolic name of the window size: `small`, `medium`, `large`, `larger` or `full`.
2166 *
2167 * The static size is used if no #size is configured during construction.
2168 *
2169 * @static
2170 * @inheritable
2171 * @property {string}
2172 */
2173 OO.ui.Window.static.size = 'medium';
2174
2175 /* Methods */
2176
2177 /**
2178 * Handle mouse down events.
2179 *
2180 * @private
2181 * @param {jQuery.Event} e Mouse down event
2182 */
2183 OO.ui.Window.prototype.onMouseDown = function ( e ) {
2184 // Prevent clicking on the click-block from stealing focus
2185 if ( e.target === this.$element[ 0 ] ) {
2186 return false;
2187 }
2188 };
2189
2190 /**
2191 * Check if the window has been initialized.
2192 *
2193 * Initialization occurs when a window is added to a manager.
2194 *
2195 * @return {boolean} Window has been initialized
2196 */
2197 OO.ui.Window.prototype.isInitialized = function () {
2198 return !!this.manager;
2199 };
2200
2201 /**
2202 * Check if the window is visible.
2203 *
2204 * @return {boolean} Window is visible
2205 */
2206 OO.ui.Window.prototype.isVisible = function () {
2207 return this.visible;
2208 };
2209
2210 /**
2211 * Check if the window is opening.
2212 *
2213 * This method is a wrapper around the window manager's {@link OO.ui.WindowManager#isOpening isOpening}
2214 * method.
2215 *
2216 * @return {boolean} Window is opening
2217 */
2218 OO.ui.Window.prototype.isOpening = function () {
2219 return this.manager.isOpening( this );
2220 };
2221
2222 /**
2223 * Check if the window is closing.
2224 *
2225 * This method is a wrapper around the window manager's {@link OO.ui.WindowManager#isClosing isClosing} method.
2226 *
2227 * @return {boolean} Window is closing
2228 */
2229 OO.ui.Window.prototype.isClosing = function () {
2230 return this.manager.isClosing( this );
2231 };
2232
2233 /**
2234 * Check if the window is opened.
2235 *
2236 * This method is a wrapper around the window manager's {@link OO.ui.WindowManager#isOpened isOpened} method.
2237 *
2238 * @return {boolean} Window is opened
2239 */
2240 OO.ui.Window.prototype.isOpened = function () {
2241 return this.manager.isOpened( this );
2242 };
2243
2244 /**
2245 * Get the window manager.
2246 *
2247 * All windows must be attached to a window manager, which is used to open
2248 * and close the window and control its presentation.
2249 *
2250 * @return {OO.ui.WindowManager} Manager of window
2251 */
2252 OO.ui.Window.prototype.getManager = function () {
2253 return this.manager;
2254 };
2255
2256 /**
2257 * Get the symbolic name of the window size (e.g., `small` or `medium`).
2258 *
2259 * @return {string} Symbolic name of the size: `small`, `medium`, `large`, `larger`, `full`
2260 */
2261 OO.ui.Window.prototype.getSize = function () {
2262 var viewport = OO.ui.Element.static.getDimensions( this.getElementWindow() ),
2263 sizes = this.manager.constructor.static.sizes,
2264 size = this.size;
2265
2266 if ( !sizes[ size ] ) {
2267 size = this.manager.constructor.static.defaultSize;
2268 }
2269 if ( size !== 'full' && viewport.rect.right - viewport.rect.left < sizes[ size ].width ) {
2270 size = 'full';
2271 }
2272
2273 return size;
2274 };
2275
2276 /**
2277 * Get the size properties associated with the current window size
2278 *
2279 * @return {Object} Size properties
2280 */
2281 OO.ui.Window.prototype.getSizeProperties = function () {
2282 return this.manager.constructor.static.sizes[ this.getSize() ];
2283 };
2284
2285 /**
2286 * Disable transitions on window's frame for the duration of the callback function, then enable them
2287 * back.
2288 *
2289 * @private
2290 * @param {Function} callback Function to call while transitions are disabled
2291 */
2292 OO.ui.Window.prototype.withoutSizeTransitions = function ( callback ) {
2293 // Temporarily resize the frame so getBodyHeight() can use scrollHeight measurements.
2294 // Disable transitions first, otherwise we'll get values from when the window was animating.
2295 var oldTransition,
2296 styleObj = this.$frame[ 0 ].style;
2297 oldTransition = styleObj.transition || styleObj.OTransition || styleObj.MsTransition ||
2298 styleObj.MozTransition || styleObj.WebkitTransition;
2299 styleObj.transition = styleObj.OTransition = styleObj.MsTransition =
2300 styleObj.MozTransition = styleObj.WebkitTransition = 'none';
2301 callback();
2302 // Force reflow to make sure the style changes done inside callback really are not transitioned
2303 this.$frame.height();
2304 styleObj.transition = styleObj.OTransition = styleObj.MsTransition =
2305 styleObj.MozTransition = styleObj.WebkitTransition = oldTransition;
2306 };
2307
2308 /**
2309 * Get the height of the full window contents (i.e., the window head, body and foot together).
2310 *
2311 * What consistitutes the head, body, and foot varies depending on the window type.
2312 * A {@link OO.ui.MessageDialog message dialog} displays a title and message in its body,
2313 * and any actions in the foot. A {@link OO.ui.ProcessDialog process dialog} displays a title
2314 * and special actions in the head, and dialog content in the body.
2315 *
2316 * To get just the height of the dialog body, use the #getBodyHeight method.
2317 *
2318 * @return {number} The height of the window contents (the dialog head, body and foot) in pixels
2319 */
2320 OO.ui.Window.prototype.getContentHeight = function () {
2321 var bodyHeight,
2322 win = this,
2323 bodyStyleObj = this.$body[ 0 ].style,
2324 frameStyleObj = this.$frame[ 0 ].style;
2325
2326 // Temporarily resize the frame so getBodyHeight() can use scrollHeight measurements.
2327 // Disable transitions first, otherwise we'll get values from when the window was animating.
2328 this.withoutSizeTransitions( function () {
2329 var oldHeight = frameStyleObj.height,
2330 oldPosition = bodyStyleObj.position;
2331 frameStyleObj.height = '1px';
2332 // Force body to resize to new width
2333 bodyStyleObj.position = 'relative';
2334 bodyHeight = win.getBodyHeight();
2335 frameStyleObj.height = oldHeight;
2336 bodyStyleObj.position = oldPosition;
2337 } );
2338
2339 return (
2340 // Add buffer for border
2341 ( this.$frame.outerHeight() - this.$frame.innerHeight() ) +
2342 // Use combined heights of children
2343 ( this.$head.outerHeight( true ) + bodyHeight + this.$foot.outerHeight( true ) )
2344 );
2345 };
2346
2347 /**
2348 * Get the height of the window body.
2349 *
2350 * To get the height of the full window contents (the window body, head, and foot together),
2351 * use #getContentHeight.
2352 *
2353 * When this function is called, the window will temporarily have been resized
2354 * to height=1px, so .scrollHeight measurements can be taken accurately.
2355 *
2356 * @return {number} Height of the window body in pixels
2357 */
2358 OO.ui.Window.prototype.getBodyHeight = function () {
2359 return this.$body[ 0 ].scrollHeight;
2360 };
2361
2362 /**
2363 * Get the directionality of the frame (right-to-left or left-to-right).
2364 *
2365 * @return {string} Directionality: `'ltr'` or `'rtl'`
2366 */
2367 OO.ui.Window.prototype.getDir = function () {
2368 return OO.ui.Element.static.getDir( this.$content ) || 'ltr';
2369 };
2370
2371 /**
2372 * Get the 'setup' process.
2373 *
2374 * The setup process is used to set up a window for use in a particular context,
2375 * based on the `data` argument. This method is called during the opening phase of the window’s
2376 * lifecycle.
2377 *
2378 * Override this method to add additional steps to the ‘setup’ process the parent method provides
2379 * using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next} methods
2380 * of OO.ui.Process.
2381 *
2382 * To add window content that persists between openings, you may wish to use the #initialize method
2383 * instead.
2384 *
2385 * @abstract
2386 * @param {Object} [data] Window opening data
2387 * @return {OO.ui.Process} Setup process
2388 */
2389 OO.ui.Window.prototype.getSetupProcess = function () {
2390 return new OO.ui.Process();
2391 };
2392
2393 /**
2394 * Get the ‘ready’ process.
2395 *
2396 * The ready process is used to ready a window for use in a particular
2397 * context, based on the `data` argument. This method is called during the opening phase of
2398 * the window’s lifecycle, after the window has been {@link #getSetupProcess setup}.
2399 *
2400 * Override this method to add additional steps to the ‘ready’ process the parent method
2401 * provides using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next}
2402 * methods of OO.ui.Process.
2403 *
2404 * @abstract
2405 * @param {Object} [data] Window opening data
2406 * @return {OO.ui.Process} Ready process
2407 */
2408 OO.ui.Window.prototype.getReadyProcess = function () {
2409 return new OO.ui.Process();
2410 };
2411
2412 /**
2413 * Get the 'hold' process.
2414 *
2415 * The hold proccess is used to keep a window from being used in a particular context,
2416 * based on the `data` argument. This method is called during the closing phase of the window’s
2417 * lifecycle.
2418 *
2419 * Override this method to add additional steps to the 'hold' process the parent method provides
2420 * using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next} methods
2421 * of OO.ui.Process.
2422 *
2423 * @abstract
2424 * @param {Object} [data] Window closing data
2425 * @return {OO.ui.Process} Hold process
2426 */
2427 OO.ui.Window.prototype.getHoldProcess = function () {
2428 return new OO.ui.Process();
2429 };
2430
2431 /**
2432 * Get the ‘teardown’ process.
2433 *
2434 * The teardown process is used to teardown a window after use. During teardown,
2435 * user interactions within the window are conveyed and the window is closed, based on the `data`
2436 * argument. This method is called during the closing phase of the window’s lifecycle.
2437 *
2438 * Override this method to add additional steps to the ‘teardown’ process the parent method provides
2439 * using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next} methods
2440 * of OO.ui.Process.
2441 *
2442 * @abstract
2443 * @param {Object} [data] Window closing data
2444 * @return {OO.ui.Process} Teardown process
2445 */
2446 OO.ui.Window.prototype.getTeardownProcess = function () {
2447 return new OO.ui.Process();
2448 };
2449
2450 /**
2451 * Set the window manager.
2452 *
2453 * This will cause the window to initialize. Calling it more than once will cause an error.
2454 *
2455 * @param {OO.ui.WindowManager} manager Manager for this window
2456 * @throws {Error} An error is thrown if the method is called more than once
2457 * @chainable
2458 */
2459 OO.ui.Window.prototype.setManager = function ( manager ) {
2460 if ( this.manager ) {
2461 throw new Error( 'Cannot set window manager, window already has a manager' );
2462 }
2463
2464 this.manager = manager;
2465 this.initialize();
2466
2467 return this;
2468 };
2469
2470 /**
2471 * Set the window size by symbolic name (e.g., 'small' or 'medium')
2472 *
2473 * @param {string} size Symbolic name of size: `small`, `medium`, `large`, `larger` or
2474 * `full`
2475 * @chainable
2476 */
2477 OO.ui.Window.prototype.setSize = function ( size ) {
2478 this.size = size;
2479 this.updateSize();
2480 return this;
2481 };
2482
2483 /**
2484 * Update the window size.
2485 *
2486 * @throws {Error} An error is thrown if the window is not attached to a window manager
2487 * @chainable
2488 */
2489 OO.ui.Window.prototype.updateSize = function () {
2490 if ( !this.manager ) {
2491 throw new Error( 'Cannot update window size, must be attached to a manager' );
2492 }
2493
2494 this.manager.updateWindowSize( this );
2495
2496 return this;
2497 };
2498
2499 /**
2500 * Set window dimensions. This method is called by the {@link OO.ui.WindowManager window manager}
2501 * when the window is opening. In general, setDimensions should not be called directly.
2502 *
2503 * To set the size of the window, use the #setSize method.
2504 *
2505 * @param {Object} dim CSS dimension properties
2506 * @param {string|number} [dim.width] Width
2507 * @param {string|number} [dim.minWidth] Minimum width
2508 * @param {string|number} [dim.maxWidth] Maximum width
2509 * @param {string|number} [dim.width] Height, omit to set based on height of contents
2510 * @param {string|number} [dim.minWidth] Minimum height
2511 * @param {string|number} [dim.maxWidth] Maximum height
2512 * @chainable
2513 */
2514 OO.ui.Window.prototype.setDimensions = function ( dim ) {
2515 var height,
2516 win = this,
2517 styleObj = this.$frame[ 0 ].style;
2518
2519 // Calculate the height we need to set using the correct width
2520 if ( dim.height === undefined ) {
2521 this.withoutSizeTransitions( function () {
2522 var oldWidth = styleObj.width;
2523 win.$frame.css( 'width', dim.width || '' );
2524 height = win.getContentHeight();
2525 styleObj.width = oldWidth;
2526 } );
2527 } else {
2528 height = dim.height;
2529 }
2530
2531 this.$frame.css( {
2532 width: dim.width || '',
2533 minWidth: dim.minWidth || '',
2534 maxWidth: dim.maxWidth || '',
2535 height: height || '',
2536 minHeight: dim.minHeight || '',
2537 maxHeight: dim.maxHeight || ''
2538 } );
2539
2540 return this;
2541 };
2542
2543 /**
2544 * Initialize window contents.
2545 *
2546 * Before the window is opened for the first time, #initialize is called so that content that
2547 * persists between openings can be added to the window.
2548 *
2549 * To set up a window with new content each time the window opens, use #getSetupProcess.
2550 *
2551 * @throws {Error} An error is thrown if the window is not attached to a window manager
2552 * @chainable
2553 */
2554 OO.ui.Window.prototype.initialize = function () {
2555 if ( !this.manager ) {
2556 throw new Error( 'Cannot initialize window, must be attached to a manager' );
2557 }
2558
2559 // Properties
2560 this.$head = $( '<div>' );
2561 this.$body = $( '<div>' );
2562 this.$foot = $( '<div>' );
2563 this.$document = $( this.getElementDocument() );
2564
2565 // Events
2566 this.$element.on( 'mousedown', this.onMouseDown.bind( this ) );
2567
2568 // Initialization
2569 this.$head.addClass( 'oo-ui-window-head' );
2570 this.$body.addClass( 'oo-ui-window-body' );
2571 this.$foot.addClass( 'oo-ui-window-foot' );
2572 this.$content.append( this.$head, this.$body, this.$foot );
2573
2574 return this;
2575 };
2576
2577 /**
2578 * Called when someone tries to focus the hidden element at the end of the dialog.
2579 * Sends focus back to the start of the dialog.
2580 *
2581 * @param {jQuery.Event} event Focus event
2582 */
2583 OO.ui.Window.prototype.onFocusTrapFocused = function ( event ) {
2584 if ( this.$focusTrapBefore.is( event.target ) ) {
2585 OO.ui.findFocusable( this.$content, true ).focus();
2586 } else {
2587 // this.$content is the part of the focus cycle, and is the first focusable element
2588 this.$content.focus();
2589 }
2590 };
2591
2592 /**
2593 * Open the window.
2594 *
2595 * This method is a wrapper around a call to the window manager’s {@link OO.ui.WindowManager#openWindow openWindow}
2596 * method, which returns a promise resolved when the window is done opening.
2597 *
2598 * To customize the window each time it opens, use #getSetupProcess or #getReadyProcess.
2599 *
2600 * @param {Object} [data] Window opening data
2601 * @return {jQuery.Promise} Promise resolved with a value when the window is opened, or rejected
2602 * if the window fails to open. When the promise is resolved successfully, the first argument of the
2603 * value is a new promise, which is resolved when the window begins closing.
2604 * @throws {Error} An error is thrown if the window is not attached to a window manager
2605 */
2606 OO.ui.Window.prototype.open = function ( data ) {
2607 if ( !this.manager ) {
2608 throw new Error( 'Cannot open window, must be attached to a manager' );
2609 }
2610
2611 return this.manager.openWindow( this, data );
2612 };
2613
2614 /**
2615 * Close the window.
2616 *
2617 * This method is a wrapper around a call to the window
2618 * manager’s {@link OO.ui.WindowManager#closeWindow closeWindow} method,
2619 * which returns a closing promise resolved when the window is done closing.
2620 *
2621 * The window's #getHoldProcess and #getTeardownProcess methods are called during the closing
2622 * phase of the window’s lifecycle and can be used to specify closing behavior each time
2623 * the window closes.
2624 *
2625 * @param {Object} [data] Window closing data
2626 * @return {jQuery.Promise} Promise resolved when window is closed
2627 * @throws {Error} An error is thrown if the window is not attached to a window manager
2628 */
2629 OO.ui.Window.prototype.close = function ( data ) {
2630 if ( !this.manager ) {
2631 throw new Error( 'Cannot close window, must be attached to a manager' );
2632 }
2633
2634 return this.manager.closeWindow( this, data );
2635 };
2636
2637 /**
2638 * Setup window.
2639 *
2640 * This is called by OO.ui.WindowManager during window opening, and should not be called directly
2641 * by other systems.
2642 *
2643 * @param {Object} [data] Window opening data
2644 * @return {jQuery.Promise} Promise resolved when window is setup
2645 */
2646 OO.ui.Window.prototype.setup = function ( data ) {
2647 var win = this,
2648 deferred = $.Deferred();
2649
2650 this.toggle( true );
2651
2652 this.focusTrapHandler = OO.ui.bind( this.onFocusTrapFocused, this );
2653 this.$focusTraps.on( 'focus', this.focusTrapHandler );
2654
2655 this.getSetupProcess( data ).execute().done( function () {
2656 // Force redraw by asking the browser to measure the elements' widths
2657 win.$element.addClass( 'oo-ui-window-active oo-ui-window-setup' ).width();
2658 win.$content.addClass( 'oo-ui-window-content-setup' ).width();
2659 deferred.resolve();
2660 } );
2661
2662 return deferred.promise();
2663 };
2664
2665 /**
2666 * Ready window.
2667 *
2668 * This is called by OO.ui.WindowManager during window opening, and should not be called directly
2669 * by other systems.
2670 *
2671 * @param {Object} [data] Window opening data
2672 * @return {jQuery.Promise} Promise resolved when window is ready
2673 */
2674 OO.ui.Window.prototype.ready = function ( data ) {
2675 var win = this,
2676 deferred = $.Deferred();
2677
2678 this.$content.focus();
2679 this.getReadyProcess( data ).execute().done( function () {
2680 // Force redraw by asking the browser to measure the elements' widths
2681 win.$element.addClass( 'oo-ui-window-ready' ).width();
2682 win.$content.addClass( 'oo-ui-window-content-ready' ).width();
2683 deferred.resolve();
2684 } );
2685
2686 return deferred.promise();
2687 };
2688
2689 /**
2690 * Hold window.
2691 *
2692 * This is called by OO.ui.WindowManager during window closing, and should not be called directly
2693 * by other systems.
2694 *
2695 * @param {Object} [data] Window closing data
2696 * @return {jQuery.Promise} Promise resolved when window is held
2697 */
2698 OO.ui.Window.prototype.hold = function ( data ) {
2699 var win = this,
2700 deferred = $.Deferred();
2701
2702 this.getHoldProcess( data ).execute().done( function () {
2703 // Get the focused element within the window's content
2704 var $focus = win.$content.find( OO.ui.Element.static.getDocument( win.$content ).activeElement );
2705
2706 // Blur the focused element
2707 if ( $focus.length ) {
2708 $focus[ 0 ].blur();
2709 }
2710
2711 // Force redraw by asking the browser to measure the elements' widths
2712 win.$element.removeClass( 'oo-ui-window-ready' ).width();
2713 win.$content.removeClass( 'oo-ui-window-content-ready' ).width();
2714 deferred.resolve();
2715 } );
2716
2717 return deferred.promise();
2718 };
2719
2720 /**
2721 * Teardown window.
2722 *
2723 * This is called by OO.ui.WindowManager during window closing, and should not be called directly
2724 * by other systems.
2725 *
2726 * @param {Object} [data] Window closing data
2727 * @return {jQuery.Promise} Promise resolved when window is torn down
2728 */
2729 OO.ui.Window.prototype.teardown = function ( data ) {
2730 var win = this;
2731
2732 return this.getTeardownProcess( data ).execute()
2733 .done( function () {
2734 // Force redraw by asking the browser to measure the elements' widths
2735 win.$element.removeClass( 'oo-ui-window-active oo-ui-window-setup' ).width();
2736 win.$content.removeClass( 'oo-ui-window-content-setup' ).width();
2737 win.$focusTraps.off( 'focus', win.focusTrapHandler );
2738 win.toggle( false );
2739 } );
2740 };
2741
2742 /**
2743 * The Dialog class serves as the base class for the other types of dialogs.
2744 * Unless extended to include controls, the rendered dialog box is a simple window
2745 * that users can close by hitting the ‘Esc’ key. Dialog windows are used with OO.ui.WindowManager,
2746 * which opens, closes, and controls the presentation of the window. See the
2747 * [OOjs UI documentation on MediaWiki] [1] for more information.
2748 *
2749 * @example
2750 * // A simple dialog window.
2751 * function MyDialog( config ) {
2752 * MyDialog.parent.call( this, config );
2753 * }
2754 * OO.inheritClass( MyDialog, OO.ui.Dialog );
2755 * MyDialog.prototype.initialize = function () {
2756 * MyDialog.parent.prototype.initialize.call( this );
2757 * this.content = new OO.ui.PanelLayout( { padded: true, expanded: false } );
2758 * this.content.$element.append( '<p>A simple dialog window. Press \'Esc\' to close.</p>' );
2759 * this.$body.append( this.content.$element );
2760 * };
2761 * MyDialog.prototype.getBodyHeight = function () {
2762 * return this.content.$element.outerHeight( true );
2763 * };
2764 * var myDialog = new MyDialog( {
2765 * size: 'medium'
2766 * } );
2767 * // Create and append a window manager, which opens and closes the window.
2768 * var windowManager = new OO.ui.WindowManager();
2769 * $( 'body' ).append( windowManager.$element );
2770 * windowManager.addWindows( [ myDialog ] );
2771 * // Open the window!
2772 * windowManager.openWindow( myDialog );
2773 *
2774 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Dialogs
2775 *
2776 * @abstract
2777 * @class
2778 * @extends OO.ui.Window
2779 * @mixins OO.ui.mixin.PendingElement
2780 *
2781 * @constructor
2782 * @param {Object} [config] Configuration options
2783 */
2784 OO.ui.Dialog = function OoUiDialog( config ) {
2785 // Parent constructor
2786 OO.ui.Dialog.parent.call( this, config );
2787
2788 // Mixin constructors
2789 OO.ui.mixin.PendingElement.call( this );
2790
2791 // Properties
2792 this.actions = new OO.ui.ActionSet();
2793 this.attachedActions = [];
2794 this.currentAction = null;
2795 this.onDialogKeyDownHandler = this.onDialogKeyDown.bind( this );
2796
2797 // Events
2798 this.actions.connect( this, {
2799 click: 'onActionClick',
2800 resize: 'onActionResize',
2801 change: 'onActionsChange'
2802 } );
2803
2804 // Initialization
2805 this.$element
2806 .addClass( 'oo-ui-dialog' )
2807 .attr( 'role', 'dialog' );
2808 };
2809
2810 /* Setup */
2811
2812 OO.inheritClass( OO.ui.Dialog, OO.ui.Window );
2813 OO.mixinClass( OO.ui.Dialog, OO.ui.mixin.PendingElement );
2814
2815 /* Static Properties */
2816
2817 /**
2818 * Symbolic name of dialog.
2819 *
2820 * The dialog class must have a symbolic name in order to be registered with OO.Factory.
2821 * Please see the [OOjs UI documentation on MediaWiki] [3] for more information.
2822 *
2823 * [3]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
2824 *
2825 * @abstract
2826 * @static
2827 * @inheritable
2828 * @property {string}
2829 */
2830 OO.ui.Dialog.static.name = '';
2831
2832 /**
2833 * The dialog title.
2834 *
2835 * The title can be specified as a plaintext string, a {@link OO.ui.mixin.LabelElement Label} node, or a function
2836 * that will produce a Label node or string. The title can also be specified with data passed to the
2837 * constructor (see #getSetupProcess). In this case, the static value will be overriden.
2838 *
2839 * @abstract
2840 * @static
2841 * @inheritable
2842 * @property {jQuery|string|Function}
2843 */
2844 OO.ui.Dialog.static.title = '';
2845
2846 /**
2847 * An array of configured {@link OO.ui.ActionWidget action widgets}.
2848 *
2849 * Actions can also be specified with data passed to the constructor (see #getSetupProcess). In this case, the static
2850 * value will be overriden.
2851 *
2852 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Action_sets
2853 *
2854 * @static
2855 * @inheritable
2856 * @property {Object[]}
2857 */
2858 OO.ui.Dialog.static.actions = [];
2859
2860 /**
2861 * Close the dialog when the 'Esc' key is pressed.
2862 *
2863 * @static
2864 * @abstract
2865 * @inheritable
2866 * @property {boolean}
2867 */
2868 OO.ui.Dialog.static.escapable = true;
2869
2870 /* Methods */
2871
2872 /**
2873 * Handle frame document key down events.
2874 *
2875 * @private
2876 * @param {jQuery.Event} e Key down event
2877 */
2878 OO.ui.Dialog.prototype.onDialogKeyDown = function ( e ) {
2879 if ( e.which === OO.ui.Keys.ESCAPE ) {
2880 this.close();
2881 e.preventDefault();
2882 e.stopPropagation();
2883 }
2884 };
2885
2886 /**
2887 * Handle action resized events.
2888 *
2889 * @private
2890 * @param {OO.ui.ActionWidget} action Action that was resized
2891 */
2892 OO.ui.Dialog.prototype.onActionResize = function () {
2893 // Override in subclass
2894 };
2895
2896 /**
2897 * Handle action click events.
2898 *
2899 * @private
2900 * @param {OO.ui.ActionWidget} action Action that was clicked
2901 */
2902 OO.ui.Dialog.prototype.onActionClick = function ( action ) {
2903 if ( !this.isPending() ) {
2904 this.executeAction( action.getAction() );
2905 }
2906 };
2907
2908 /**
2909 * Handle actions change event.
2910 *
2911 * @private
2912 */
2913 OO.ui.Dialog.prototype.onActionsChange = function () {
2914 this.detachActions();
2915 if ( !this.isClosing() ) {
2916 this.attachActions();
2917 }
2918 };
2919
2920 /**
2921 * Get the set of actions used by the dialog.
2922 *
2923 * @return {OO.ui.ActionSet}
2924 */
2925 OO.ui.Dialog.prototype.getActions = function () {
2926 return this.actions;
2927 };
2928
2929 /**
2930 * Get a process for taking action.
2931 *
2932 * When you override this method, you can create a new OO.ui.Process and return it, or add additional
2933 * accept steps to the process the parent method provides using the {@link OO.ui.Process#first 'first'}
2934 * and {@link OO.ui.Process#next 'next'} methods of OO.ui.Process.
2935 *
2936 * @abstract
2937 * @param {string} [action] Symbolic name of action
2938 * @return {OO.ui.Process} Action process
2939 */
2940 OO.ui.Dialog.prototype.getActionProcess = function ( action ) {
2941 return new OO.ui.Process()
2942 .next( function () {
2943 if ( !action ) {
2944 // An empty action always closes the dialog without data, which should always be
2945 // safe and make no changes
2946 this.close();
2947 }
2948 }, this );
2949 };
2950
2951 /**
2952 * @inheritdoc
2953 *
2954 * @param {Object} [data] Dialog opening data
2955 * @param {jQuery|string|Function|null} [data.title] Dialog title, omit to use
2956 * the {@link #static-title static title}
2957 * @param {Object[]} [data.actions] List of configuration options for each
2958 * {@link OO.ui.ActionWidget action widget}, omit to use {@link #static-actions static actions}.
2959 */
2960 OO.ui.Dialog.prototype.getSetupProcess = function ( data ) {
2961 data = data || {};
2962
2963 // Parent method
2964 return OO.ui.Dialog.parent.prototype.getSetupProcess.call( this, data )
2965 .next( function () {
2966 var config = this.constructor.static,
2967 actions = data.actions !== undefined ? data.actions : config.actions;
2968
2969 this.title.setLabel(
2970 data.title !== undefined ? data.title : this.constructor.static.title
2971 );
2972 this.actions.add( this.getActionWidgets( actions ) );
2973
2974 if ( this.constructor.static.escapable ) {
2975 this.$element.on( 'keydown', this.onDialogKeyDownHandler );
2976 }
2977 }, this );
2978 };
2979
2980 /**
2981 * @inheritdoc
2982 */
2983 OO.ui.Dialog.prototype.getTeardownProcess = function ( data ) {
2984 // Parent method
2985 return OO.ui.Dialog.parent.prototype.getTeardownProcess.call( this, data )
2986 .first( function () {
2987 if ( this.constructor.static.escapable ) {
2988 this.$element.off( 'keydown', this.onDialogKeyDownHandler );
2989 }
2990
2991 this.actions.clear();
2992 this.currentAction = null;
2993 }, this );
2994 };
2995
2996 /**
2997 * @inheritdoc
2998 */
2999 OO.ui.Dialog.prototype.initialize = function () {
3000 var titleId;
3001
3002 // Parent method
3003 OO.ui.Dialog.parent.prototype.initialize.call( this );
3004
3005 titleId = OO.ui.generateElementId();
3006
3007 // Properties
3008 this.title = new OO.ui.LabelWidget( {
3009 id: titleId
3010 } );
3011
3012 // Initialization
3013 this.$content.addClass( 'oo-ui-dialog-content' );
3014 this.$element.attr( 'aria-labelledby', titleId );
3015 this.setPendingElement( this.$head );
3016 };
3017
3018 /**
3019 * Get action widgets from a list of configs
3020 *
3021 * @param {Object[]} actions Action widget configs
3022 * @return {OO.ui.ActionWidget[]} Action widgets
3023 */
3024 OO.ui.Dialog.prototype.getActionWidgets = function ( actions ) {
3025 var i, len, widgets = [];
3026 for ( i = 0, len = actions.length; i < len; i++ ) {
3027 widgets.push(
3028 new OO.ui.ActionWidget( actions[ i ] )
3029 );
3030 }
3031 return widgets;
3032 };
3033
3034 /**
3035 * Attach action actions.
3036 *
3037 * @protected
3038 */
3039 OO.ui.Dialog.prototype.attachActions = function () {
3040 // Remember the list of potentially attached actions
3041 this.attachedActions = this.actions.get();
3042 };
3043
3044 /**
3045 * Detach action actions.
3046 *
3047 * @protected
3048 * @chainable
3049 */
3050 OO.ui.Dialog.prototype.detachActions = function () {
3051 var i, len;
3052
3053 // Detach all actions that may have been previously attached
3054 for ( i = 0, len = this.attachedActions.length; i < len; i++ ) {
3055 this.attachedActions[ i ].$element.detach();
3056 }
3057 this.attachedActions = [];
3058 };
3059
3060 /**
3061 * Execute an action.
3062 *
3063 * @param {string} action Symbolic name of action to execute
3064 * @return {jQuery.Promise} Promise resolved when action completes, rejected if it fails
3065 */
3066 OO.ui.Dialog.prototype.executeAction = function ( action ) {
3067 this.pushPending();
3068 this.currentAction = action;
3069 return this.getActionProcess( action ).execute()
3070 .always( this.popPending.bind( this ) );
3071 };
3072
3073 /**
3074 * Window managers are used to open and close {@link OO.ui.Window windows} and control their presentation.
3075 * Managed windows are mutually exclusive. If a new window is opened while a current window is opening
3076 * or is opened, the current window will be closed and any ongoing {@link OO.ui.Process process} will be cancelled. Windows
3077 * themselves are persistent and—rather than being torn down when closed—can be repopulated with the
3078 * pertinent data and reused.
3079 *
3080 * Over the lifecycle of a window, the window manager makes available three promises: `opening`,
3081 * `opened`, and `closing`, which represent the primary stages of the cycle:
3082 *
3083 * **Opening**: the opening stage begins when the window manager’s #openWindow or a window’s
3084 * {@link OO.ui.Window#open open} method is used, and the window manager begins to open the window.
3085 *
3086 * - an `opening` event is emitted with an `opening` promise
3087 * - the #getSetupDelay method is called and the returned value is used to time a pause in execution before
3088 * the window’s {@link OO.ui.Window#getSetupProcess getSetupProcess} method is called on the
3089 * window and its result executed
3090 * - a `setup` progress notification is emitted from the `opening` promise
3091 * - the #getReadyDelay method is called the returned value is used to time a pause in execution before
3092 * the window’s {@link OO.ui.Window#getReadyProcess getReadyProcess} method is called on the
3093 * window and its result executed
3094 * - a `ready` progress notification is emitted from the `opening` promise
3095 * - the `opening` promise is resolved with an `opened` promise
3096 *
3097 * **Opened**: the window is now open.
3098 *
3099 * **Closing**: the closing stage begins when the window manager's #closeWindow or the
3100 * window's {@link OO.ui.Window#close close} methods is used, and the window manager begins
3101 * to close the window.
3102 *
3103 * - the `opened` promise is resolved with `closing` promise and a `closing` event is emitted
3104 * - the #getHoldDelay method is called and the returned value is used to time a pause in execution before
3105 * the window's {@link OO.ui.Window#getHoldProcess getHoldProces} method is called on the
3106 * window and its result executed
3107 * - a `hold` progress notification is emitted from the `closing` promise
3108 * - the #getTeardownDelay() method is called and the returned value is used to time a pause in execution before
3109 * the window's {@link OO.ui.Window#getTeardownProcess getTeardownProcess} method is called on the
3110 * window and its result executed
3111 * - a `teardown` progress notification is emitted from the `closing` promise
3112 * - the `closing` promise is resolved. The window is now closed
3113 *
3114 * See the [OOjs UI documentation on MediaWiki][1] for more information.
3115 *
3116 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
3117 *
3118 * @class
3119 * @extends OO.ui.Element
3120 * @mixins OO.EventEmitter
3121 *
3122 * @constructor
3123 * @param {Object} [config] Configuration options
3124 * @cfg {OO.Factory} [factory] Window factory to use for automatic instantiation
3125 * Note that window classes that are instantiated with a factory must have
3126 * a {@link OO.ui.Dialog#static-name static name} property that specifies a symbolic name.
3127 * @cfg {boolean} [modal=true] Prevent interaction outside the dialog
3128 */
3129 OO.ui.WindowManager = function OoUiWindowManager( config ) {
3130 // Configuration initialization
3131 config = config || {};
3132
3133 // Parent constructor
3134 OO.ui.WindowManager.parent.call( this, config );
3135
3136 // Mixin constructors
3137 OO.EventEmitter.call( this );
3138
3139 // Properties
3140 this.factory = config.factory;
3141 this.modal = config.modal === undefined || !!config.modal;
3142 this.windows = {};
3143 this.opening = null;
3144 this.opened = null;
3145 this.closing = null;
3146 this.preparingToOpen = null;
3147 this.preparingToClose = null;
3148 this.currentWindow = null;
3149 this.globalEvents = false;
3150 this.$ariaHidden = null;
3151 this.onWindowResizeTimeout = null;
3152 this.onWindowResizeHandler = this.onWindowResize.bind( this );
3153 this.afterWindowResizeHandler = this.afterWindowResize.bind( this );
3154
3155 // Initialization
3156 this.$element
3157 .addClass( 'oo-ui-windowManager' )
3158 .toggleClass( 'oo-ui-windowManager-modal', this.modal );
3159 };
3160
3161 /* Setup */
3162
3163 OO.inheritClass( OO.ui.WindowManager, OO.ui.Element );
3164 OO.mixinClass( OO.ui.WindowManager, OO.EventEmitter );
3165
3166 /* Events */
3167
3168 /**
3169 * An 'opening' event is emitted when the window begins to be opened.
3170 *
3171 * @event opening
3172 * @param {OO.ui.Window} win Window that's being opened
3173 * @param {jQuery.Promise} opening An `opening` promise resolved with a value when the window is opened successfully.
3174 * When the `opening` promise is resolved, the first argument of the value is an 'opened' promise, the second argument
3175 * is the opening data. The `opening` promise emits `setup` and `ready` notifications when those processes are complete.
3176 * @param {Object} data Window opening data
3177 */
3178
3179 /**
3180 * A 'closing' event is emitted when the window begins to be closed.
3181 *
3182 * @event closing
3183 * @param {OO.ui.Window} win Window that's being closed
3184 * @param {jQuery.Promise} closing A `closing` promise is resolved with a value when the window
3185 * is closed successfully. The promise emits `hold` and `teardown` notifications when those
3186 * processes are complete. When the `closing` promise is resolved, the first argument of its value
3187 * is the closing data.
3188 * @param {Object} data Window closing data
3189 */
3190
3191 /**
3192 * A 'resize' event is emitted when a window is resized.
3193 *
3194 * @event resize
3195 * @param {OO.ui.Window} win Window that was resized
3196 */
3197
3198 /* Static Properties */
3199
3200 /**
3201 * Map of the symbolic name of each window size and its CSS properties.
3202 *
3203 * @static
3204 * @inheritable
3205 * @property {Object}
3206 */
3207 OO.ui.WindowManager.static.sizes = {
3208 small: {
3209 width: 300
3210 },
3211 medium: {
3212 width: 500
3213 },
3214 large: {
3215 width: 700
3216 },
3217 larger: {
3218 width: 900
3219 },
3220 full: {
3221 // These can be non-numeric because they are never used in calculations
3222 width: '100%',
3223 height: '100%'
3224 }
3225 };
3226
3227 /**
3228 * Symbolic name of the default window size.
3229 *
3230 * The default size is used if the window's requested size is not recognized.
3231 *
3232 * @static
3233 * @inheritable
3234 * @property {string}
3235 */
3236 OO.ui.WindowManager.static.defaultSize = 'medium';
3237
3238 /* Methods */
3239
3240 /**
3241 * Handle window resize events.
3242 *
3243 * @private
3244 * @param {jQuery.Event} e Window resize event
3245 */
3246 OO.ui.WindowManager.prototype.onWindowResize = function () {
3247 clearTimeout( this.onWindowResizeTimeout );
3248 this.onWindowResizeTimeout = setTimeout( this.afterWindowResizeHandler, 200 );
3249 };
3250
3251 /**
3252 * Handle window resize events.
3253 *
3254 * @private
3255 * @param {jQuery.Event} e Window resize event
3256 */
3257 OO.ui.WindowManager.prototype.afterWindowResize = function () {
3258 if ( this.currentWindow ) {
3259 this.updateWindowSize( this.currentWindow );
3260 }
3261 };
3262
3263 /**
3264 * Check if window is opening.
3265 *
3266 * @return {boolean} Window is opening
3267 */
3268 OO.ui.WindowManager.prototype.isOpening = function ( win ) {
3269 return win === this.currentWindow && !!this.opening && this.opening.state() === 'pending';
3270 };
3271
3272 /**
3273 * Check if window is closing.
3274 *
3275 * @return {boolean} Window is closing
3276 */
3277 OO.ui.WindowManager.prototype.isClosing = function ( win ) {
3278 return win === this.currentWindow && !!this.closing && this.closing.state() === 'pending';
3279 };
3280
3281 /**
3282 * Check if window is opened.
3283 *
3284 * @return {boolean} Window is opened
3285 */
3286 OO.ui.WindowManager.prototype.isOpened = function ( win ) {
3287 return win === this.currentWindow && !!this.opened && this.opened.state() === 'pending';
3288 };
3289
3290 /**
3291 * Check if a window is being managed.
3292 *
3293 * @param {OO.ui.Window} win Window to check
3294 * @return {boolean} Window is being managed
3295 */
3296 OO.ui.WindowManager.prototype.hasWindow = function ( win ) {
3297 var name;
3298
3299 for ( name in this.windows ) {
3300 if ( this.windows[ name ] === win ) {
3301 return true;
3302 }
3303 }
3304
3305 return false;
3306 };
3307
3308 /**
3309 * Get the number of milliseconds to wait after opening begins before executing the ‘setup’ process.
3310 *
3311 * @param {OO.ui.Window} win Window being opened
3312 * @param {Object} [data] Window opening data
3313 * @return {number} Milliseconds to wait
3314 */
3315 OO.ui.WindowManager.prototype.getSetupDelay = function () {
3316 return 0;
3317 };
3318
3319 /**
3320 * Get the number of milliseconds to wait after setup has finished before executing the ‘ready’ process.
3321 *
3322 * @param {OO.ui.Window} win Window being opened
3323 * @param {Object} [data] Window opening data
3324 * @return {number} Milliseconds to wait
3325 */
3326 OO.ui.WindowManager.prototype.getReadyDelay = function () {
3327 return 0;
3328 };
3329
3330 /**
3331 * Get the number of milliseconds to wait after closing has begun before executing the 'hold' process.
3332 *
3333 * @param {OO.ui.Window} win Window being closed
3334 * @param {Object} [data] Window closing data
3335 * @return {number} Milliseconds to wait
3336 */
3337 OO.ui.WindowManager.prototype.getHoldDelay = function () {
3338 return 0;
3339 };
3340
3341 /**
3342 * Get the number of milliseconds to wait after the ‘hold’ process has finished before
3343 * executing the ‘teardown’ process.
3344 *
3345 * @param {OO.ui.Window} win Window being closed
3346 * @param {Object} [data] Window closing data
3347 * @return {number} Milliseconds to wait
3348 */
3349 OO.ui.WindowManager.prototype.getTeardownDelay = function () {
3350 return this.modal ? 250 : 0;
3351 };
3352
3353 /**
3354 * Get a window by its symbolic name.
3355 *
3356 * If the window is not yet instantiated and its symbolic name is recognized by a factory, it will be
3357 * instantiated and added to the window manager automatically. Please see the [OOjs UI documentation on MediaWiki][3]
3358 * for more information about using factories.
3359 * [3]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
3360 *
3361 * @param {string} name Symbolic name of the window
3362 * @return {jQuery.Promise} Promise resolved with matching window, or rejected with an OO.ui.Error
3363 * @throws {Error} An error is thrown if the symbolic name is not recognized by the factory.
3364 * @throws {Error} An error is thrown if the named window is not recognized as a managed window.
3365 */
3366 OO.ui.WindowManager.prototype.getWindow = function ( name ) {
3367 var deferred = $.Deferred(),
3368 win = this.windows[ name ];
3369
3370 if ( !( win instanceof OO.ui.Window ) ) {
3371 if ( this.factory ) {
3372 if ( !this.factory.lookup( name ) ) {
3373 deferred.reject( new OO.ui.Error(
3374 'Cannot auto-instantiate window: symbolic name is unrecognized by the factory'
3375 ) );
3376 } else {
3377 win = this.factory.create( name );
3378 this.addWindows( [ win ] );
3379 deferred.resolve( win );
3380 }
3381 } else {
3382 deferred.reject( new OO.ui.Error(
3383 'Cannot get unmanaged window: symbolic name unrecognized as a managed window'
3384 ) );
3385 }
3386 } else {
3387 deferred.resolve( win );
3388 }
3389
3390 return deferred.promise();
3391 };
3392
3393 /**
3394 * Get current window.
3395 *
3396 * @return {OO.ui.Window|null} Currently opening/opened/closing window
3397 */
3398 OO.ui.WindowManager.prototype.getCurrentWindow = function () {
3399 return this.currentWindow;
3400 };
3401
3402 /**
3403 * Open a window.
3404 *
3405 * @param {OO.ui.Window|string} win Window object or symbolic name of window to open
3406 * @param {Object} [data] Window opening data
3407 * @return {jQuery.Promise} An `opening` promise resolved when the window is done opening.
3408 * See {@link #event-opening 'opening' event} for more information about `opening` promises.
3409 * @fires opening
3410 */
3411 OO.ui.WindowManager.prototype.openWindow = function ( win, data ) {
3412 var manager = this,
3413 opening = $.Deferred();
3414
3415 // Argument handling
3416 if ( typeof win === 'string' ) {
3417 return this.getWindow( win ).then( function ( win ) {
3418 return manager.openWindow( win, data );
3419 } );
3420 }
3421
3422 // Error handling
3423 if ( !this.hasWindow( win ) ) {
3424 opening.reject( new OO.ui.Error(
3425 'Cannot open window: window is not attached to manager'
3426 ) );
3427 } else if ( this.preparingToOpen || this.opening || this.opened ) {
3428 opening.reject( new OO.ui.Error(
3429 'Cannot open window: another window is opening or open'
3430 ) );
3431 }
3432
3433 // Window opening
3434 if ( opening.state() !== 'rejected' ) {
3435 // If a window is currently closing, wait for it to complete
3436 this.preparingToOpen = $.when( this.closing );
3437 // Ensure handlers get called after preparingToOpen is set
3438 this.preparingToOpen.done( function () {
3439 if ( manager.modal ) {
3440 manager.toggleGlobalEvents( true );
3441 manager.toggleAriaIsolation( true );
3442 }
3443 manager.currentWindow = win;
3444 manager.opening = opening;
3445 manager.preparingToOpen = null;
3446 manager.emit( 'opening', win, opening, data );
3447 setTimeout( function () {
3448 win.setup( data ).then( function () {
3449 manager.updateWindowSize( win );
3450 manager.opening.notify( { state: 'setup' } );
3451 setTimeout( function () {
3452 win.ready( data ).then( function () {
3453 manager.opening.notify( { state: 'ready' } );
3454 manager.opening = null;
3455 manager.opened = $.Deferred();
3456 opening.resolve( manager.opened.promise(), data );
3457 } );
3458 }, manager.getReadyDelay() );
3459 } );
3460 }, manager.getSetupDelay() );
3461 } );
3462 }
3463
3464 return opening.promise();
3465 };
3466
3467 /**
3468 * Close a window.
3469 *
3470 * @param {OO.ui.Window|string} win Window object or symbolic name of window to close
3471 * @param {Object} [data] Window closing data
3472 * @return {jQuery.Promise} A `closing` promise resolved when the window is done closing.
3473 * See {@link #event-closing 'closing' event} for more information about closing promises.
3474 * @throws {Error} An error is thrown if the window is not managed by the window manager.
3475 * @fires closing
3476 */
3477 OO.ui.WindowManager.prototype.closeWindow = function ( win, data ) {
3478 var manager = this,
3479 closing = $.Deferred(),
3480 opened;
3481
3482 // Argument handling
3483 if ( typeof win === 'string' ) {
3484 win = this.windows[ win ];
3485 } else if ( !this.hasWindow( win ) ) {
3486 win = null;
3487 }
3488
3489 // Error handling
3490 if ( !win ) {
3491 closing.reject( new OO.ui.Error(
3492 'Cannot close window: window is not attached to manager'
3493 ) );
3494 } else if ( win !== this.currentWindow ) {
3495 closing.reject( new OO.ui.Error(
3496 'Cannot close window: window already closed with different data'
3497 ) );
3498 } else if ( this.preparingToClose || this.closing ) {
3499 closing.reject( new OO.ui.Error(
3500 'Cannot close window: window already closing with different data'
3501 ) );
3502 }
3503
3504 // Window closing
3505 if ( closing.state() !== 'rejected' ) {
3506 // If the window is currently opening, close it when it's done
3507 this.preparingToClose = $.when( this.opening );
3508 // Ensure handlers get called after preparingToClose is set
3509 this.preparingToClose.done( function () {
3510 manager.closing = closing;
3511 manager.preparingToClose = null;
3512 manager.emit( 'closing', win, closing, data );
3513 opened = manager.opened;
3514 manager.opened = null;
3515 opened.resolve( closing.promise(), data );
3516 setTimeout( function () {
3517 win.hold( data ).then( function () {
3518 closing.notify( { state: 'hold' } );
3519 setTimeout( function () {
3520 win.teardown( data ).then( function () {
3521 closing.notify( { state: 'teardown' } );
3522 if ( manager.modal ) {
3523 manager.toggleGlobalEvents( false );
3524 manager.toggleAriaIsolation( false );
3525 }
3526 manager.closing = null;
3527 manager.currentWindow = null;
3528 closing.resolve( data );
3529 } );
3530 }, manager.getTeardownDelay() );
3531 } );
3532 }, manager.getHoldDelay() );
3533 } );
3534 }
3535
3536 return closing.promise();
3537 };
3538
3539 /**
3540 * Add windows to the window manager.
3541 *
3542 * Windows can be added by reference, symbolic name, or explicitly defined symbolic names.
3543 * See the [OOjs ui documentation on MediaWiki] [2] for examples.
3544 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
3545 *
3546 * @param {Object.<string,OO.ui.Window>|OO.ui.Window[]} windows An array of window objects specified
3547 * by reference, symbolic name, or explicitly defined symbolic names.
3548 * @throws {Error} An error is thrown if a window is added by symbolic name, but has neither an
3549 * explicit nor a statically configured symbolic name.
3550 */
3551 OO.ui.WindowManager.prototype.addWindows = function ( windows ) {
3552 var i, len, win, name, list;
3553
3554 if ( Array.isArray( windows ) ) {
3555 // Convert to map of windows by looking up symbolic names from static configuration
3556 list = {};
3557 for ( i = 0, len = windows.length; i < len; i++ ) {
3558 name = windows[ i ].constructor.static.name;
3559 if ( typeof name !== 'string' ) {
3560 throw new Error( 'Cannot add window' );
3561 }
3562 list[ name ] = windows[ i ];
3563 }
3564 } else if ( OO.isPlainObject( windows ) ) {
3565 list = windows;
3566 }
3567
3568 // Add windows
3569 for ( name in list ) {
3570 win = list[ name ];
3571 this.windows[ name ] = win.toggle( false );
3572 this.$element.append( win.$element );
3573 win.setManager( this );
3574 }
3575 };
3576
3577 /**
3578 * Remove the specified windows from the windows manager.
3579 *
3580 * Windows will be closed before they are removed. If you wish to remove all windows, you may wish to use
3581 * the #clearWindows method instead. If you no longer need the window manager and want to ensure that it no
3582 * longer listens to events, use the #destroy method.
3583 *
3584 * @param {string[]} names Symbolic names of windows to remove
3585 * @return {jQuery.Promise} Promise resolved when window is closed and removed
3586 * @throws {Error} An error is thrown if the named windows are not managed by the window manager.
3587 */
3588 OO.ui.WindowManager.prototype.removeWindows = function ( names ) {
3589 var i, len, win, name, cleanupWindow,
3590 manager = this,
3591 promises = [],
3592 cleanup = function ( name, win ) {
3593 delete manager.windows[ name ];
3594 win.$element.detach();
3595 };
3596
3597 for ( i = 0, len = names.length; i < len; i++ ) {
3598 name = names[ i ];
3599 win = this.windows[ name ];
3600 if ( !win ) {
3601 throw new Error( 'Cannot remove window' );
3602 }
3603 cleanupWindow = cleanup.bind( null, name, win );
3604 promises.push( this.closeWindow( name ).then( cleanupWindow, cleanupWindow ) );
3605 }
3606
3607 return $.when.apply( $, promises );
3608 };
3609
3610 /**
3611 * Remove all windows from the window manager.
3612 *
3613 * Windows will be closed before they are removed. Note that the window manager, though not in use, will still
3614 * listen to events. If the window manager will not be used again, you may wish to use the #destroy method instead.
3615 * To remove just a subset of windows, use the #removeWindows method.
3616 *
3617 * @return {jQuery.Promise} Promise resolved when all windows are closed and removed
3618 */
3619 OO.ui.WindowManager.prototype.clearWindows = function () {
3620 return this.removeWindows( Object.keys( this.windows ) );
3621 };
3622
3623 /**
3624 * Set dialog size. In general, this method should not be called directly.
3625 *
3626 * Fullscreen mode will be used if the dialog is too wide to fit in the screen.
3627 *
3628 * @chainable
3629 */
3630 OO.ui.WindowManager.prototype.updateWindowSize = function ( win ) {
3631 var isFullscreen;
3632
3633 // Bypass for non-current, and thus invisible, windows
3634 if ( win !== this.currentWindow ) {
3635 return;
3636 }
3637
3638 isFullscreen = win.getSize() === 'full';
3639
3640 this.$element.toggleClass( 'oo-ui-windowManager-fullscreen', isFullscreen );
3641 this.$element.toggleClass( 'oo-ui-windowManager-floating', !isFullscreen );
3642 win.setDimensions( win.getSizeProperties() );
3643
3644 this.emit( 'resize', win );
3645
3646 return this;
3647 };
3648
3649 /**
3650 * Bind or unbind global events for scrolling.
3651 *
3652 * @private
3653 * @param {boolean} [on] Bind global events
3654 * @chainable
3655 */
3656 OO.ui.WindowManager.prototype.toggleGlobalEvents = function ( on ) {
3657 var scrollWidth, bodyMargin,
3658 $body = $( this.getElementDocument().body ),
3659 // We could have multiple window managers open so only modify
3660 // the body css at the bottom of the stack
3661 stackDepth = $body.data( 'windowManagerGlobalEvents' ) || 0 ;
3662
3663 on = on === undefined ? !!this.globalEvents : !!on;
3664
3665 if ( on ) {
3666 if ( !this.globalEvents ) {
3667 $( this.getElementWindow() ).on( {
3668 // Start listening for top-level window dimension changes
3669 'orientationchange resize': this.onWindowResizeHandler
3670 } );
3671 if ( stackDepth === 0 ) {
3672 scrollWidth = window.innerWidth - document.documentElement.clientWidth;
3673 bodyMargin = parseFloat( $body.css( 'margin-right' ) ) || 0;
3674 $body.css( {
3675 overflow: 'hidden',
3676 'margin-right': bodyMargin + scrollWidth
3677 } );
3678 }
3679 stackDepth++;
3680 this.globalEvents = true;
3681 }
3682 } else if ( this.globalEvents ) {
3683 $( this.getElementWindow() ).off( {
3684 // Stop listening for top-level window dimension changes
3685 'orientationchange resize': this.onWindowResizeHandler
3686 } );
3687 stackDepth--;
3688 if ( stackDepth === 0 ) {
3689 $body.css( {
3690 overflow: '',
3691 'margin-right': ''
3692 } );
3693 }
3694 this.globalEvents = false;
3695 }
3696 $body.data( 'windowManagerGlobalEvents', stackDepth );
3697
3698 return this;
3699 };
3700
3701 /**
3702 * Toggle screen reader visibility of content other than the window manager.
3703 *
3704 * @private
3705 * @param {boolean} [isolate] Make only the window manager visible to screen readers
3706 * @chainable
3707 */
3708 OO.ui.WindowManager.prototype.toggleAriaIsolation = function ( isolate ) {
3709 isolate = isolate === undefined ? !this.$ariaHidden : !!isolate;
3710
3711 if ( isolate ) {
3712 if ( !this.$ariaHidden ) {
3713 // Hide everything other than the window manager from screen readers
3714 this.$ariaHidden = $( 'body' )
3715 .children()
3716 .not( this.$element.parentsUntil( 'body' ).last() )
3717 .attr( 'aria-hidden', '' );
3718 }
3719 } else if ( this.$ariaHidden ) {
3720 // Restore screen reader visibility
3721 this.$ariaHidden.removeAttr( 'aria-hidden' );
3722 this.$ariaHidden = null;
3723 }
3724
3725 return this;
3726 };
3727
3728 /**
3729 * Destroy the window manager.
3730 *
3731 * Destroying the window manager ensures that it will no longer listen to events. If you would like to
3732 * continue using the window manager, but wish to remove all windows from it, use the #clearWindows method
3733 * instead.
3734 */
3735 OO.ui.WindowManager.prototype.destroy = function () {
3736 this.toggleGlobalEvents( false );
3737 this.toggleAriaIsolation( false );
3738 this.clearWindows();
3739 this.$element.remove();
3740 };
3741
3742 /**
3743 * Errors contain a required message (either a string or jQuery selection) that is used to describe what went wrong
3744 * in a {@link OO.ui.Process process}. The error's #recoverable and #warning configurations are used to customize the
3745 * appearance and functionality of the error interface.
3746 *
3747 * The basic error interface contains a formatted error message as well as two buttons: 'Dismiss' and 'Try again' (i.e., the error
3748 * is 'recoverable' by default). If the error is not recoverable, the 'Try again' button will not be rendered and the widget
3749 * that initiated the failed process will be disabled.
3750 *
3751 * If the error is a warning, the error interface will include a 'Dismiss' and a 'Continue' button, which will try the
3752 * process again.
3753 *
3754 * For an example of error interfaces, please see the [OOjs UI documentation on MediaWiki][1].
3755 *
3756 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Processes_and_errors
3757 *
3758 * @class
3759 *
3760 * @constructor
3761 * @param {string|jQuery} message Description of error
3762 * @param {Object} [config] Configuration options
3763 * @cfg {boolean} [recoverable=true] Error is recoverable.
3764 * By default, errors are recoverable, and users can try the process again.
3765 * @cfg {boolean} [warning=false] Error is a warning.
3766 * If the error is a warning, the error interface will include a
3767 * 'Dismiss' and a 'Continue' button. It is the responsibility of the developer to ensure that the warning
3768 * is not triggered a second time if the user chooses to continue.
3769 */
3770 OO.ui.Error = function OoUiError( message, config ) {
3771 // Allow passing positional parameters inside the config object
3772 if ( OO.isPlainObject( message ) && config === undefined ) {
3773 config = message;
3774 message = config.message;
3775 }
3776
3777 // Configuration initialization
3778 config = config || {};
3779
3780 // Properties
3781 this.message = message instanceof jQuery ? message : String( message );
3782 this.recoverable = config.recoverable === undefined || !!config.recoverable;
3783 this.warning = !!config.warning;
3784 };
3785
3786 /* Setup */
3787
3788 OO.initClass( OO.ui.Error );
3789
3790 /* Methods */
3791
3792 /**
3793 * Check if the error is recoverable.
3794 *
3795 * If the error is recoverable, users are able to try the process again.
3796 *
3797 * @return {boolean} Error is recoverable
3798 */
3799 OO.ui.Error.prototype.isRecoverable = function () {
3800 return this.recoverable;
3801 };
3802
3803 /**
3804 * Check if the error is a warning.
3805 *
3806 * If the error is a warning, the error interface will include a 'Dismiss' and a 'Continue' button.
3807 *
3808 * @return {boolean} Error is warning
3809 */
3810 OO.ui.Error.prototype.isWarning = function () {
3811 return this.warning;
3812 };
3813
3814 /**
3815 * Get error message as DOM nodes.
3816 *
3817 * @return {jQuery} Error message in DOM nodes
3818 */
3819 OO.ui.Error.prototype.getMessage = function () {
3820 return this.message instanceof jQuery ?
3821 this.message.clone() :
3822 $( '<div>' ).text( this.message ).contents();
3823 };
3824
3825 /**
3826 * Get the error message text.
3827 *
3828 * @return {string} Error message
3829 */
3830 OO.ui.Error.prototype.getMessageText = function () {
3831 return this.message instanceof jQuery ? this.message.text() : this.message;
3832 };
3833
3834 /**
3835 * Wraps an HTML snippet for use with configuration values which default
3836 * to strings. This bypasses the default html-escaping done to string
3837 * values.
3838 *
3839 * @class
3840 *
3841 * @constructor
3842 * @param {string} [content] HTML content
3843 */
3844 OO.ui.HtmlSnippet = function OoUiHtmlSnippet( content ) {
3845 // Properties
3846 this.content = content;
3847 };
3848
3849 /* Setup */
3850
3851 OO.initClass( OO.ui.HtmlSnippet );
3852
3853 /* Methods */
3854
3855 /**
3856 * Render into HTML.
3857 *
3858 * @return {string} Unchanged HTML snippet.
3859 */
3860 OO.ui.HtmlSnippet.prototype.toString = function () {
3861 return this.content;
3862 };
3863
3864 /**
3865 * A Process is a list of steps that are called in sequence. The step can be a number, a jQuery promise,
3866 * or a function:
3867 *
3868 * - **number**: the process will wait for the specified number of milliseconds before proceeding.
3869 * - **promise**: the process will continue to the next step when the promise is successfully resolved
3870 * or stop if the promise is rejected.
3871 * - **function**: the process will execute the function. The process will stop if the function returns
3872 * either a boolean `false` or a promise that is rejected; if the function returns a number, the process
3873 * will wait for that number of milliseconds before proceeding.
3874 *
3875 * If the process fails, an {@link OO.ui.Error error} is generated. Depending on how the error is
3876 * configured, users can dismiss the error and try the process again, or not. If a process is stopped,
3877 * its remaining steps will not be performed.
3878 *
3879 * @class
3880 *
3881 * @constructor
3882 * @param {number|jQuery.Promise|Function} step Number of miliseconds to wait before proceeding, promise
3883 * that must be resolved before proceeding, or a function to execute. See #createStep for more information. see #createStep for more information
3884 * @param {Object} [context=null] Execution context of the function. The context is ignored if the step is
3885 * a number or promise.
3886 * @return {Object} Step object, with `callback` and `context` properties
3887 */
3888 OO.ui.Process = function ( step, context ) {
3889 // Properties
3890 this.steps = [];
3891
3892 // Initialization
3893 if ( step !== undefined ) {
3894 this.next( step, context );
3895 }
3896 };
3897
3898 /* Setup */
3899
3900 OO.initClass( OO.ui.Process );
3901
3902 /* Methods */
3903
3904 /**
3905 * Start the process.
3906 *
3907 * @return {jQuery.Promise} Promise that is resolved when all steps have successfully completed.
3908 * If any of the steps return a promise that is rejected or a boolean false, this promise is rejected
3909 * and any remaining steps are not performed.
3910 */
3911 OO.ui.Process.prototype.execute = function () {
3912 var i, len, promise;
3913
3914 /**
3915 * Continue execution.
3916 *
3917 * @ignore
3918 * @param {Array} step A function and the context it should be called in
3919 * @return {Function} Function that continues the process
3920 */
3921 function proceed( step ) {
3922 return function () {
3923 // Execute step in the correct context
3924 var deferred,
3925 result = step.callback.call( step.context );
3926
3927 if ( result === false ) {
3928 // Use rejected promise for boolean false results
3929 return $.Deferred().reject( [] ).promise();
3930 }
3931 if ( typeof result === 'number' ) {
3932 if ( result < 0 ) {
3933 throw new Error( 'Cannot go back in time: flux capacitor is out of service' );
3934 }
3935 // Use a delayed promise for numbers, expecting them to be in milliseconds
3936 deferred = $.Deferred();
3937 setTimeout( deferred.resolve, result );
3938 return deferred.promise();
3939 }
3940 if ( result instanceof OO.ui.Error ) {
3941 // Use rejected promise for error
3942 return $.Deferred().reject( [ result ] ).promise();
3943 }
3944 if ( Array.isArray( result ) && result.length && result[ 0 ] instanceof OO.ui.Error ) {
3945 // Use rejected promise for list of errors
3946 return $.Deferred().reject( result ).promise();
3947 }
3948 // Duck-type the object to see if it can produce a promise
3949 if ( result && $.isFunction( result.promise ) ) {
3950 // Use a promise generated from the result
3951 return result.promise();
3952 }
3953 // Use resolved promise for other results
3954 return $.Deferred().resolve().promise();
3955 };
3956 }
3957
3958 if ( this.steps.length ) {
3959 // Generate a chain reaction of promises
3960 promise = proceed( this.steps[ 0 ] )();
3961 for ( i = 1, len = this.steps.length; i < len; i++ ) {
3962 promise = promise.then( proceed( this.steps[ i ] ) );
3963 }
3964 } else {
3965 promise = $.Deferred().resolve().promise();
3966 }
3967
3968 return promise;
3969 };
3970
3971 /**
3972 * Create a process step.
3973 *
3974 * @private
3975 * @param {number|jQuery.Promise|Function} step
3976 *
3977 * - Number of milliseconds to wait before proceeding
3978 * - Promise that must be resolved before proceeding
3979 * - Function to execute
3980 * - If the function returns a boolean false the process will stop
3981 * - If the function returns a promise, the process will continue to the next
3982 * step when the promise is resolved or stop if the promise is rejected
3983 * - If the function returns a number, the process will wait for that number of
3984 * milliseconds before proceeding
3985 * @param {Object} [context=null] Execution context of the function. The context is
3986 * ignored if the step is a number or promise.
3987 * @return {Object} Step object, with `callback` and `context` properties
3988 */
3989 OO.ui.Process.prototype.createStep = function ( step, context ) {
3990 if ( typeof step === 'number' || $.isFunction( step.promise ) ) {
3991 return {
3992 callback: function () {
3993 return step;
3994 },
3995 context: null
3996 };
3997 }
3998 if ( $.isFunction( step ) ) {
3999 return {
4000 callback: step,
4001 context: context
4002 };
4003 }
4004 throw new Error( 'Cannot create process step: number, promise or function expected' );
4005 };
4006
4007 /**
4008 * Add step to the beginning of the process.
4009 *
4010 * @inheritdoc #createStep
4011 * @return {OO.ui.Process} this
4012 * @chainable
4013 */
4014 OO.ui.Process.prototype.first = function ( step, context ) {
4015 this.steps.unshift( this.createStep( step, context ) );
4016 return this;
4017 };
4018
4019 /**
4020 * Add step to the end of the process.
4021 *
4022 * @inheritdoc #createStep
4023 * @return {OO.ui.Process} this
4024 * @chainable
4025 */
4026 OO.ui.Process.prototype.next = function ( step, context ) {
4027 this.steps.push( this.createStep( step, context ) );
4028 return this;
4029 };
4030
4031 /**
4032 * A ToolFactory creates tools on demand. All tools ({@link OO.ui.Tool Tools}, {@link OO.ui.PopupTool PopupTools},
4033 * and {@link OO.ui.ToolGroupTool ToolGroupTools}) must be registered with a tool factory. Tools are
4034 * registered by their symbolic name. See {@link OO.ui.Toolbar toolbars} for an example.
4035 *
4036 * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki][1].
4037 *
4038 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
4039 *
4040 * @class
4041 * @extends OO.Factory
4042 * @constructor
4043 */
4044 OO.ui.ToolFactory = function OoUiToolFactory() {
4045 // Parent constructor
4046 OO.ui.ToolFactory.parent.call( this );
4047 };
4048
4049 /* Setup */
4050
4051 OO.inheritClass( OO.ui.ToolFactory, OO.Factory );
4052
4053 /* Methods */
4054
4055 /**
4056 * Get tools from the factory
4057 *
4058 * @param {Array} include Included tools
4059 * @param {Array} exclude Excluded tools
4060 * @param {Array} promote Promoted tools
4061 * @param {Array} demote Demoted tools
4062 * @return {string[]} List of tools
4063 */
4064 OO.ui.ToolFactory.prototype.getTools = function ( include, exclude, promote, demote ) {
4065 var i, len, included, promoted, demoted,
4066 auto = [],
4067 used = {};
4068
4069 // Collect included and not excluded tools
4070 included = OO.simpleArrayDifference( this.extract( include ), this.extract( exclude ) );
4071
4072 // Promotion
4073 promoted = this.extract( promote, used );
4074 demoted = this.extract( demote, used );
4075
4076 // Auto
4077 for ( i = 0, len = included.length; i < len; i++ ) {
4078 if ( !used[ included[ i ] ] ) {
4079 auto.push( included[ i ] );
4080 }
4081 }
4082
4083 return promoted.concat( auto ).concat( demoted );
4084 };
4085
4086 /**
4087 * Get a flat list of names from a list of names or groups.
4088 *
4089 * Tools can be specified in the following ways:
4090 *
4091 * - A specific tool: `{ name: 'tool-name' }` or `'tool-name'`
4092 * - All tools in a group: `{ group: 'group-name' }`
4093 * - All tools: `'*'`
4094 *
4095 * @private
4096 * @param {Array|string} collection List of tools
4097 * @param {Object} [used] Object with names that should be skipped as properties; extracted
4098 * names will be added as properties
4099 * @return {string[]} List of extracted names
4100 */
4101 OO.ui.ToolFactory.prototype.extract = function ( collection, used ) {
4102 var i, len, item, name, tool,
4103 names = [];
4104
4105 if ( collection === '*' ) {
4106 for ( name in this.registry ) {
4107 tool = this.registry[ name ];
4108 if (
4109 // Only add tools by group name when auto-add is enabled
4110 tool.static.autoAddToCatchall &&
4111 // Exclude already used tools
4112 ( !used || !used[ name ] )
4113 ) {
4114 names.push( name );
4115 if ( used ) {
4116 used[ name ] = true;
4117 }
4118 }
4119 }
4120 } else if ( Array.isArray( collection ) ) {
4121 for ( i = 0, len = collection.length; i < len; i++ ) {
4122 item = collection[ i ];
4123 // Allow plain strings as shorthand for named tools
4124 if ( typeof item === 'string' ) {
4125 item = { name: item };
4126 }
4127 if ( OO.isPlainObject( item ) ) {
4128 if ( item.group ) {
4129 for ( name in this.registry ) {
4130 tool = this.registry[ name ];
4131 if (
4132 // Include tools with matching group
4133 tool.static.group === item.group &&
4134 // Only add tools by group name when auto-add is enabled
4135 tool.static.autoAddToGroup &&
4136 // Exclude already used tools
4137 ( !used || !used[ name ] )
4138 ) {
4139 names.push( name );
4140 if ( used ) {
4141 used[ name ] = true;
4142 }
4143 }
4144 }
4145 // Include tools with matching name and exclude already used tools
4146 } else if ( item.name && ( !used || !used[ item.name ] ) ) {
4147 names.push( item.name );
4148 if ( used ) {
4149 used[ item.name ] = true;
4150 }
4151 }
4152 }
4153 }
4154 }
4155 return names;
4156 };
4157
4158 /**
4159 * ToolGroupFactories create {@link OO.ui.ToolGroup toolgroups} on demand. The toolgroup classes must
4160 * specify a symbolic name and be registered with the factory. The following classes are registered by
4161 * default:
4162 *
4163 * - {@link OO.ui.BarToolGroup BarToolGroups} (‘bar’)
4164 * - {@link OO.ui.MenuToolGroup MenuToolGroups} (‘menu’)
4165 * - {@link OO.ui.ListToolGroup ListToolGroups} (‘list’)
4166 *
4167 * See {@link OO.ui.Toolbar toolbars} for an example.
4168 *
4169 * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki][1].
4170 *
4171 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
4172 * @class
4173 * @extends OO.Factory
4174 * @constructor
4175 */
4176 OO.ui.ToolGroupFactory = function OoUiToolGroupFactory() {
4177 var i, l, defaultClasses;
4178 // Parent constructor
4179 OO.Factory.call( this );
4180
4181 defaultClasses = this.constructor.static.getDefaultClasses();
4182
4183 // Register default toolgroups
4184 for ( i = 0, l = defaultClasses.length; i < l; i++ ) {
4185 this.register( defaultClasses[ i ] );
4186 }
4187 };
4188
4189 /* Setup */
4190
4191 OO.inheritClass( OO.ui.ToolGroupFactory, OO.Factory );
4192
4193 /* Static Methods */
4194
4195 /**
4196 * Get a default set of classes to be registered on construction.
4197 *
4198 * @return {Function[]} Default classes
4199 */
4200 OO.ui.ToolGroupFactory.static.getDefaultClasses = function () {
4201 return [
4202 OO.ui.BarToolGroup,
4203 OO.ui.ListToolGroup,
4204 OO.ui.MenuToolGroup
4205 ];
4206 };
4207
4208 /**
4209 * Theme logic.
4210 *
4211 * @abstract
4212 * @class
4213 *
4214 * @constructor
4215 * @param {Object} [config] Configuration options
4216 */
4217 OO.ui.Theme = function OoUiTheme( config ) {
4218 // Configuration initialization
4219 config = config || {};
4220 };
4221
4222 /* Setup */
4223
4224 OO.initClass( OO.ui.Theme );
4225
4226 /* Methods */
4227
4228 /**
4229 * Get a list of classes to be applied to a widget.
4230 *
4231 * The 'on' and 'off' lists combined MUST contain keys for all classes the theme adds or removes,
4232 * otherwise state transitions will not work properly.
4233 *
4234 * @param {OO.ui.Element} element Element for which to get classes
4235 * @return {Object.<string,string[]>} Categorized class names with `on` and `off` lists
4236 */
4237 OO.ui.Theme.prototype.getElementClasses = function () {
4238 return { on: [], off: [] };
4239 };
4240
4241 /**
4242 * Update CSS classes provided by the theme.
4243 *
4244 * For elements with theme logic hooks, this should be called any time there's a state change.
4245 *
4246 * @param {OO.ui.Element} element Element for which to update classes
4247 * @return {Object.<string,string[]>} Categorized class names with `on` and `off` lists
4248 */
4249 OO.ui.Theme.prototype.updateElementClasses = function ( element ) {
4250 var $elements = $( [] ),
4251 classes = this.getElementClasses( element );
4252
4253 if ( element.$icon ) {
4254 $elements = $elements.add( element.$icon );
4255 }
4256 if ( element.$indicator ) {
4257 $elements = $elements.add( element.$indicator );
4258 }
4259
4260 $elements
4261 .removeClass( classes.off.join( ' ' ) )
4262 .addClass( classes.on.join( ' ' ) );
4263 };
4264
4265 /**
4266 * The TabIndexedElement class is an attribute mixin used to add additional functionality to an
4267 * element created by another class. The mixin provides a ‘tabIndex’ property, which specifies the
4268 * order in which users will navigate through the focusable elements via the "tab" key.
4269 *
4270 * @example
4271 * // TabIndexedElement is mixed into the ButtonWidget class
4272 * // to provide a tabIndex property.
4273 * var button1 = new OO.ui.ButtonWidget( {
4274 * label: 'fourth',
4275 * tabIndex: 4
4276 * } );
4277 * var button2 = new OO.ui.ButtonWidget( {
4278 * label: 'second',
4279 * tabIndex: 2
4280 * } );
4281 * var button3 = new OO.ui.ButtonWidget( {
4282 * label: 'third',
4283 * tabIndex: 3
4284 * } );
4285 * var button4 = new OO.ui.ButtonWidget( {
4286 * label: 'first',
4287 * tabIndex: 1
4288 * } );
4289 * $( 'body' ).append( button1.$element, button2.$element, button3.$element, button4.$element );
4290 *
4291 * @abstract
4292 * @class
4293 *
4294 * @constructor
4295 * @param {Object} [config] Configuration options
4296 * @cfg {jQuery} [$tabIndexed] The element that should use the tabindex functionality. By default,
4297 * the functionality is applied to the element created by the class ($element). If a different element is specified, the tabindex
4298 * functionality will be applied to it instead.
4299 * @cfg {number|null} [tabIndex=0] Number that specifies the element’s position in the tab-navigation
4300 * order (e.g., 1 for the first focusable element). Use 0 to use the default navigation order; use -1
4301 * to remove the element from the tab-navigation flow.
4302 */
4303 OO.ui.mixin.TabIndexedElement = function OoUiMixinTabIndexedElement( config ) {
4304 // Configuration initialization
4305 config = $.extend( { tabIndex: 0 }, config );
4306
4307 // Properties
4308 this.$tabIndexed = null;
4309 this.tabIndex = null;
4310
4311 // Events
4312 this.connect( this, { disable: 'onTabIndexedElementDisable' } );
4313
4314 // Initialization
4315 this.setTabIndex( config.tabIndex );
4316 this.setTabIndexedElement( config.$tabIndexed || this.$element );
4317 };
4318
4319 /* Setup */
4320
4321 OO.initClass( OO.ui.mixin.TabIndexedElement );
4322
4323 /* Methods */
4324
4325 /**
4326 * Set the element that should use the tabindex functionality.
4327 *
4328 * This method is used to retarget a tabindex mixin so that its functionality applies
4329 * to the specified element. If an element is currently using the functionality, the mixin’s
4330 * effect on that element is removed before the new element is set up.
4331 *
4332 * @param {jQuery} $tabIndexed Element that should use the tabindex functionality
4333 * @chainable
4334 */
4335 OO.ui.mixin.TabIndexedElement.prototype.setTabIndexedElement = function ( $tabIndexed ) {
4336 var tabIndex = this.tabIndex;
4337 // Remove attributes from old $tabIndexed
4338 this.setTabIndex( null );
4339 // Force update of new $tabIndexed
4340 this.$tabIndexed = $tabIndexed;
4341 this.tabIndex = tabIndex;
4342 return this.updateTabIndex();
4343 };
4344
4345 /**
4346 * Set the value of the tabindex.
4347 *
4348 * @param {number|null} tabIndex Tabindex value, or `null` for no tabindex
4349 * @chainable
4350 */
4351 OO.ui.mixin.TabIndexedElement.prototype.setTabIndex = function ( tabIndex ) {
4352 tabIndex = typeof tabIndex === 'number' ? tabIndex : null;
4353
4354 if ( this.tabIndex !== tabIndex ) {
4355 this.tabIndex = tabIndex;
4356 this.updateTabIndex();
4357 }
4358
4359 return this;
4360 };
4361
4362 /**
4363 * Update the `tabindex` attribute, in case of changes to tab index or
4364 * disabled state.
4365 *
4366 * @private
4367 * @chainable
4368 */
4369 OO.ui.mixin.TabIndexedElement.prototype.updateTabIndex = function () {
4370 if ( this.$tabIndexed ) {
4371 if ( this.tabIndex !== null ) {
4372 // Do not index over disabled elements
4373 this.$tabIndexed.attr( {
4374 tabindex: this.isDisabled() ? -1 : this.tabIndex,
4375 // Support: ChromeVox and NVDA
4376 // These do not seem to inherit aria-disabled from parent elements
4377 'aria-disabled': this.isDisabled().toString()
4378 } );
4379 } else {
4380 this.$tabIndexed.removeAttr( 'tabindex aria-disabled' );
4381 }
4382 }
4383 return this;
4384 };
4385
4386 /**
4387 * Handle disable events.
4388 *
4389 * @private
4390 * @param {boolean} disabled Element is disabled
4391 */
4392 OO.ui.mixin.TabIndexedElement.prototype.onTabIndexedElementDisable = function () {
4393 this.updateTabIndex();
4394 };
4395
4396 /**
4397 * Get the value of the tabindex.
4398 *
4399 * @return {number|null} Tabindex value
4400 */
4401 OO.ui.mixin.TabIndexedElement.prototype.getTabIndex = function () {
4402 return this.tabIndex;
4403 };
4404
4405 /**
4406 * ButtonElement is often mixed into other classes to generate a button, which is a clickable
4407 * interface element that can be configured with access keys for accessibility.
4408 * See the [OOjs UI documentation on MediaWiki] [1] for examples.
4409 *
4410 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#Buttons
4411 * @abstract
4412 * @class
4413 *
4414 * @constructor
4415 * @param {Object} [config] Configuration options
4416 * @cfg {jQuery} [$button] The button element created by the class.
4417 * If this configuration is omitted, the button element will use a generated `<a>`.
4418 * @cfg {boolean} [framed=true] Render the button with a frame
4419 */
4420 OO.ui.mixin.ButtonElement = function OoUiMixinButtonElement( config ) {
4421 // Configuration initialization
4422 config = config || {};
4423
4424 // Properties
4425 this.$button = null;
4426 this.framed = null;
4427 this.active = false;
4428 this.onMouseUpHandler = this.onMouseUp.bind( this );
4429 this.onMouseDownHandler = this.onMouseDown.bind( this );
4430 this.onKeyDownHandler = this.onKeyDown.bind( this );
4431 this.onKeyUpHandler = this.onKeyUp.bind( this );
4432 this.onClickHandler = this.onClick.bind( this );
4433 this.onKeyPressHandler = this.onKeyPress.bind( this );
4434
4435 // Initialization
4436 this.$element.addClass( 'oo-ui-buttonElement' );
4437 this.toggleFramed( config.framed === undefined || config.framed );
4438 this.setButtonElement( config.$button || $( '<a>' ) );
4439 };
4440
4441 /* Setup */
4442
4443 OO.initClass( OO.ui.mixin.ButtonElement );
4444
4445 /* Static Properties */
4446
4447 /**
4448 * Cancel mouse down events.
4449 *
4450 * This property is usually set to `true` to prevent the focus from changing when the button is clicked.
4451 * Classes such as {@link OO.ui.mixin.DraggableElement DraggableElement} and {@link OO.ui.ButtonOptionWidget ButtonOptionWidget}
4452 * use a value of `false` so that dragging behavior is possible and mousedown events can be handled by a
4453 * parent widget.
4454 *
4455 * @static
4456 * @inheritable
4457 * @property {boolean}
4458 */
4459 OO.ui.mixin.ButtonElement.static.cancelButtonMouseDownEvents = true;
4460
4461 /* Events */
4462
4463 /**
4464 * A 'click' event is emitted when the button element is clicked.
4465 *
4466 * @event click
4467 */
4468
4469 /* Methods */
4470
4471 /**
4472 * Set the button element.
4473 *
4474 * This method is used to retarget a button mixin so that its functionality applies to
4475 * the specified button element instead of the one created by the class. If a button element
4476 * is already set, the method will remove the mixin’s effect on that element.
4477 *
4478 * @param {jQuery} $button Element to use as button
4479 */
4480 OO.ui.mixin.ButtonElement.prototype.setButtonElement = function ( $button ) {
4481 if ( this.$button ) {
4482 this.$button
4483 .removeClass( 'oo-ui-buttonElement-button' )
4484 .removeAttr( 'role accesskey' )
4485 .off( {
4486 mousedown: this.onMouseDownHandler,
4487 keydown: this.onKeyDownHandler,
4488 click: this.onClickHandler,
4489 keypress: this.onKeyPressHandler
4490 } );
4491 }
4492
4493 this.$button = $button
4494 .addClass( 'oo-ui-buttonElement-button' )
4495 .attr( { role: 'button' } )
4496 .on( {
4497 mousedown: this.onMouseDownHandler,
4498 keydown: this.onKeyDownHandler,
4499 click: this.onClickHandler,
4500 keypress: this.onKeyPressHandler
4501 } );
4502 };
4503
4504 /**
4505 * Handles mouse down events.
4506 *
4507 * @protected
4508 * @param {jQuery.Event} e Mouse down event
4509 */
4510 OO.ui.mixin.ButtonElement.prototype.onMouseDown = function ( e ) {
4511 if ( this.isDisabled() || e.which !== 1 ) {
4512 return;
4513 }
4514 this.$element.addClass( 'oo-ui-buttonElement-pressed' );
4515 // Run the mouseup handler no matter where the mouse is when the button is let go, so we can
4516 // reliably remove the pressed class
4517 OO.ui.addCaptureEventListener( this.getElementDocument(), 'mouseup', this.onMouseUpHandler );
4518 // Prevent change of focus unless specifically configured otherwise
4519 if ( this.constructor.static.cancelButtonMouseDownEvents ) {
4520 return false;
4521 }
4522 };
4523
4524 /**
4525 * Handles mouse up events.
4526 *
4527 * @protected
4528 * @param {jQuery.Event} e Mouse up event
4529 */
4530 OO.ui.mixin.ButtonElement.prototype.onMouseUp = function ( e ) {
4531 if ( this.isDisabled() || e.which !== 1 ) {
4532 return;
4533 }
4534 this.$element.removeClass( 'oo-ui-buttonElement-pressed' );
4535 // Stop listening for mouseup, since we only needed this once
4536 OO.ui.removeCaptureEventListener( this.getElementDocument(), 'mouseup', this.onMouseUpHandler );
4537 };
4538
4539 /**
4540 * Handles mouse click events.
4541 *
4542 * @protected
4543 * @param {jQuery.Event} e Mouse click event
4544 * @fires click
4545 */
4546 OO.ui.mixin.ButtonElement.prototype.onClick = function ( e ) {
4547 if ( !this.isDisabled() && e.which === 1 ) {
4548 if ( this.emit( 'click' ) ) {
4549 return false;
4550 }
4551 }
4552 };
4553
4554 /**
4555 * Handles key down events.
4556 *
4557 * @protected
4558 * @param {jQuery.Event} e Key down event
4559 */
4560 OO.ui.mixin.ButtonElement.prototype.onKeyDown = function ( e ) {
4561 if ( this.isDisabled() || ( e.which !== OO.ui.Keys.SPACE && e.which !== OO.ui.Keys.ENTER ) ) {
4562 return;
4563 }
4564 this.$element.addClass( 'oo-ui-buttonElement-pressed' );
4565 // Run the keyup handler no matter where the key is when the button is let go, so we can
4566 // reliably remove the pressed class
4567 OO.ui.addCaptureEventListener( this.getElementDocument(), 'keyup', this.onKeyUpHandler );
4568 };
4569
4570 /**
4571 * Handles key up events.
4572 *
4573 * @protected
4574 * @param {jQuery.Event} e Key up event
4575 */
4576 OO.ui.mixin.ButtonElement.prototype.onKeyUp = function ( e ) {
4577 if ( this.isDisabled() || ( e.which !== OO.ui.Keys.SPACE && e.which !== OO.ui.Keys.ENTER ) ) {
4578 return;
4579 }
4580 this.$element.removeClass( 'oo-ui-buttonElement-pressed' );
4581 // Stop listening for keyup, since we only needed this once
4582 OO.ui.removeCaptureEventListener( this.getElementDocument(), 'keyup', this.onKeyUpHandler );
4583 };
4584
4585 /**
4586 * Handles key press events.
4587 *
4588 * @protected
4589 * @param {jQuery.Event} e Key press event
4590 * @fires click
4591 */
4592 OO.ui.mixin.ButtonElement.prototype.onKeyPress = function ( e ) {
4593 if ( !this.isDisabled() && ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER ) ) {
4594 if ( this.emit( 'click' ) ) {
4595 return false;
4596 }
4597 }
4598 };
4599
4600 /**
4601 * Check if button has a frame.
4602 *
4603 * @return {boolean} Button is framed
4604 */
4605 OO.ui.mixin.ButtonElement.prototype.isFramed = function () {
4606 return this.framed;
4607 };
4608
4609 /**
4610 * Render the button with or without a frame. Omit the `framed` parameter to toggle the button frame on and off.
4611 *
4612 * @param {boolean} [framed] Make button framed, omit to toggle
4613 * @chainable
4614 */
4615 OO.ui.mixin.ButtonElement.prototype.toggleFramed = function ( framed ) {
4616 framed = framed === undefined ? !this.framed : !!framed;
4617 if ( framed !== this.framed ) {
4618 this.framed = framed;
4619 this.$element
4620 .toggleClass( 'oo-ui-buttonElement-frameless', !framed )
4621 .toggleClass( 'oo-ui-buttonElement-framed', framed );
4622 this.updateThemeClasses();
4623 }
4624
4625 return this;
4626 };
4627
4628 /**
4629 * Set the button's active state.
4630 *
4631 * The active state occurs when a {@link OO.ui.ButtonOptionWidget ButtonOptionWidget} or
4632 * a {@link OO.ui.ToggleButtonWidget ToggleButtonWidget} is pressed. This method does nothing
4633 * for other button types.
4634 *
4635 * @param {boolean} value Make button active
4636 * @chainable
4637 */
4638 OO.ui.mixin.ButtonElement.prototype.setActive = function ( value ) {
4639 this.active = !!value;
4640 this.$element.toggleClass( 'oo-ui-buttonElement-active', this.active );
4641 return this;
4642 };
4643
4644 /**
4645 * Check if the button is active
4646 *
4647 * @return {boolean} The button is active
4648 */
4649 OO.ui.mixin.ButtonElement.prototype.isActive = function () {
4650 return this.active;
4651 };
4652
4653 /**
4654 * Any OOjs UI widget that contains other widgets (such as {@link OO.ui.ButtonWidget buttons} or
4655 * {@link OO.ui.OptionWidget options}) mixes in GroupElement. Adding, removing, and clearing
4656 * items from the group is done through the interface the class provides.
4657 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
4658 *
4659 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Groups
4660 *
4661 * @abstract
4662 * @class
4663 *
4664 * @constructor
4665 * @param {Object} [config] Configuration options
4666 * @cfg {jQuery} [$group] The container element created by the class. If this configuration
4667 * is omitted, the group element will use a generated `<div>`.
4668 */
4669 OO.ui.mixin.GroupElement = function OoUiMixinGroupElement( config ) {
4670 // Configuration initialization
4671 config = config || {};
4672
4673 // Properties
4674 this.$group = null;
4675 this.items = [];
4676 this.aggregateItemEvents = {};
4677
4678 // Initialization
4679 this.setGroupElement( config.$group || $( '<div>' ) );
4680 };
4681
4682 /* Methods */
4683
4684 /**
4685 * Set the group element.
4686 *
4687 * If an element is already set, items will be moved to the new element.
4688 *
4689 * @param {jQuery} $group Element to use as group
4690 */
4691 OO.ui.mixin.GroupElement.prototype.setGroupElement = function ( $group ) {
4692 var i, len;
4693
4694 this.$group = $group;
4695 for ( i = 0, len = this.items.length; i < len; i++ ) {
4696 this.$group.append( this.items[ i ].$element );
4697 }
4698 };
4699
4700 /**
4701 * Check if a group contains no items.
4702 *
4703 * @return {boolean} Group is empty
4704 */
4705 OO.ui.mixin.GroupElement.prototype.isEmpty = function () {
4706 return !this.items.length;
4707 };
4708
4709 /**
4710 * Get all items in the group.
4711 *
4712 * The method returns an array of item references (e.g., [button1, button2, button3]) and is useful
4713 * when synchronizing groups of items, or whenever the references are required (e.g., when removing items
4714 * from a group).
4715 *
4716 * @return {OO.ui.Element[]} An array of items.
4717 */
4718 OO.ui.mixin.GroupElement.prototype.getItems = function () {
4719 return this.items.slice( 0 );
4720 };
4721
4722 /**
4723 * Get an item by its data.
4724 *
4725 * Only the first item with matching data will be returned. To return all matching items,
4726 * use the #getItemsFromData method.
4727 *
4728 * @param {Object} data Item data to search for
4729 * @return {OO.ui.Element|null} Item with equivalent data, `null` if none exists
4730 */
4731 OO.ui.mixin.GroupElement.prototype.getItemFromData = function ( data ) {
4732 var i, len, item,
4733 hash = OO.getHash( data );
4734
4735 for ( i = 0, len = this.items.length; i < len; i++ ) {
4736 item = this.items[ i ];
4737 if ( hash === OO.getHash( item.getData() ) ) {
4738 return item;
4739 }
4740 }
4741
4742 return null;
4743 };
4744
4745 /**
4746 * Get items by their data.
4747 *
4748 * All items with matching data will be returned. To return only the first match, use the #getItemFromData method instead.
4749 *
4750 * @param {Object} data Item data to search for
4751 * @return {OO.ui.Element[]} Items with equivalent data
4752 */
4753 OO.ui.mixin.GroupElement.prototype.getItemsFromData = function ( data ) {
4754 var i, len, item,
4755 hash = OO.getHash( data ),
4756 items = [];
4757
4758 for ( i = 0, len = this.items.length; i < len; i++ ) {
4759 item = this.items[ i ];
4760 if ( hash === OO.getHash( item.getData() ) ) {
4761 items.push( item );
4762 }
4763 }
4764
4765 return items;
4766 };
4767
4768 /**
4769 * Aggregate the events emitted by the group.
4770 *
4771 * When events are aggregated, the group will listen to all contained items for the event,
4772 * and then emit the event under a new name. The new event will contain an additional leading
4773 * parameter containing the item that emitted the original event. Other arguments emitted from
4774 * the original event are passed through.
4775 *
4776 * @param {Object.<string,string|null>} events An object keyed by the name of the event that should be
4777 * aggregated (e.g., ‘click’) and the value of the new name to use (e.g., ‘groupClick’).
4778 * A `null` value will remove aggregated events.
4779
4780 * @throws {Error} An error is thrown if aggregation already exists.
4781 */
4782 OO.ui.mixin.GroupElement.prototype.aggregate = function ( events ) {
4783 var i, len, item, add, remove, itemEvent, groupEvent;
4784
4785 for ( itemEvent in events ) {
4786 groupEvent = events[ itemEvent ];
4787
4788 // Remove existing aggregated event
4789 if ( Object.prototype.hasOwnProperty.call( this.aggregateItemEvents, itemEvent ) ) {
4790 // Don't allow duplicate aggregations
4791 if ( groupEvent ) {
4792 throw new Error( 'Duplicate item event aggregation for ' + itemEvent );
4793 }
4794 // Remove event aggregation from existing items
4795 for ( i = 0, len = this.items.length; i < len; i++ ) {
4796 item = this.items[ i ];
4797 if ( item.connect && item.disconnect ) {
4798 remove = {};
4799 remove[ itemEvent ] = [ 'emit', this.aggregateItemEvents[ itemEvent ], item ];
4800 item.disconnect( this, remove );
4801 }
4802 }
4803 // Prevent future items from aggregating event
4804 delete this.aggregateItemEvents[ itemEvent ];
4805 }
4806
4807 // Add new aggregate event
4808 if ( groupEvent ) {
4809 // Make future items aggregate event
4810 this.aggregateItemEvents[ itemEvent ] = groupEvent;
4811 // Add event aggregation to existing items
4812 for ( i = 0, len = this.items.length; i < len; i++ ) {
4813 item = this.items[ i ];
4814 if ( item.connect && item.disconnect ) {
4815 add = {};
4816 add[ itemEvent ] = [ 'emit', groupEvent, item ];
4817 item.connect( this, add );
4818 }
4819 }
4820 }
4821 }
4822 };
4823
4824 /**
4825 * Add items to the group.
4826 *
4827 * Items will be added to the end of the group array unless the optional `index` parameter specifies
4828 * a different insertion point. Adding an existing item will move it to the end of the array or the point specified by the `index`.
4829 *
4830 * @param {OO.ui.Element[]} items An array of items to add to the group
4831 * @param {number} [index] Index of the insertion point
4832 * @chainable
4833 */
4834 OO.ui.mixin.GroupElement.prototype.addItems = function ( items, index ) {
4835 var i, len, item, event, events, currentIndex,
4836 itemElements = [];
4837
4838 for ( i = 0, len = items.length; i < len; i++ ) {
4839 item = items[ i ];
4840
4841 // Check if item exists then remove it first, effectively "moving" it
4842 currentIndex = this.items.indexOf( item );
4843 if ( currentIndex >= 0 ) {
4844 this.removeItems( [ item ] );
4845 // Adjust index to compensate for removal
4846 if ( currentIndex < index ) {
4847 index--;
4848 }
4849 }
4850 // Add the item
4851 if ( item.connect && item.disconnect && !$.isEmptyObject( this.aggregateItemEvents ) ) {
4852 events = {};
4853 for ( event in this.aggregateItemEvents ) {
4854 events[ event ] = [ 'emit', this.aggregateItemEvents[ event ], item ];
4855 }
4856 item.connect( this, events );
4857 }
4858 item.setElementGroup( this );
4859 itemElements.push( item.$element.get( 0 ) );
4860 }
4861
4862 if ( index === undefined || index < 0 || index >= this.items.length ) {
4863 this.$group.append( itemElements );
4864 this.items.push.apply( this.items, items );
4865 } else if ( index === 0 ) {
4866 this.$group.prepend( itemElements );
4867 this.items.unshift.apply( this.items, items );
4868 } else {
4869 this.items[ index ].$element.before( itemElements );
4870 this.items.splice.apply( this.items, [ index, 0 ].concat( items ) );
4871 }
4872
4873 return this;
4874 };
4875
4876 /**
4877 * Remove the specified items from a group.
4878 *
4879 * Removed items are detached (not removed) from the DOM so that they may be reused.
4880 * To remove all items from a group, you may wish to use the #clearItems method instead.
4881 *
4882 * @param {OO.ui.Element[]} items An array of items to remove
4883 * @chainable
4884 */
4885 OO.ui.mixin.GroupElement.prototype.removeItems = function ( items ) {
4886 var i, len, item, index, remove, itemEvent;
4887
4888 // Remove specific items
4889 for ( i = 0, len = items.length; i < len; i++ ) {
4890 item = items[ i ];
4891 index = this.items.indexOf( item );
4892 if ( index !== -1 ) {
4893 if (
4894 item.connect && item.disconnect &&
4895 !$.isEmptyObject( this.aggregateItemEvents )
4896 ) {
4897 remove = {};
4898 if ( Object.prototype.hasOwnProperty.call( this.aggregateItemEvents, itemEvent ) ) {
4899 remove[ itemEvent ] = [ 'emit', this.aggregateItemEvents[ itemEvent ], item ];
4900 }
4901 item.disconnect( this, remove );
4902 }
4903 item.setElementGroup( null );
4904 this.items.splice( index, 1 );
4905 item.$element.detach();
4906 }
4907 }
4908
4909 return this;
4910 };
4911
4912 /**
4913 * Clear all items from the group.
4914 *
4915 * Cleared items are detached from the DOM, not removed, so that they may be reused.
4916 * To remove only a subset of items from a group, use the #removeItems method.
4917 *
4918 * @chainable
4919 */
4920 OO.ui.mixin.GroupElement.prototype.clearItems = function () {
4921 var i, len, item, remove, itemEvent;
4922
4923 // Remove all items
4924 for ( i = 0, len = this.items.length; i < len; i++ ) {
4925 item = this.items[ i ];
4926 if (
4927 item.connect && item.disconnect &&
4928 !$.isEmptyObject( this.aggregateItemEvents )
4929 ) {
4930 remove = {};
4931 if ( Object.prototype.hasOwnProperty.call( this.aggregateItemEvents, itemEvent ) ) {
4932 remove[ itemEvent ] = [ 'emit', this.aggregateItemEvents[ itemEvent ], item ];
4933 }
4934 item.disconnect( this, remove );
4935 }
4936 item.setElementGroup( null );
4937 item.$element.detach();
4938 }
4939
4940 this.items = [];
4941 return this;
4942 };
4943
4944 /**
4945 * DraggableElement is a mixin class used to create elements that can be clicked
4946 * and dragged by a mouse to a new position within a group. This class must be used
4947 * in conjunction with OO.ui.mixin.DraggableGroupElement, which provides a container for
4948 * the draggable elements.
4949 *
4950 * @abstract
4951 * @class
4952 *
4953 * @constructor
4954 */
4955 OO.ui.mixin.DraggableElement = function OoUiMixinDraggableElement() {
4956 // Properties
4957 this.index = null;
4958
4959 // Initialize and events
4960 this.$element
4961 .attr( 'draggable', true )
4962 .addClass( 'oo-ui-draggableElement' )
4963 .on( {
4964 dragstart: this.onDragStart.bind( this ),
4965 dragover: this.onDragOver.bind( this ),
4966 dragend: this.onDragEnd.bind( this ),
4967 drop: this.onDrop.bind( this )
4968 } );
4969 };
4970
4971 OO.initClass( OO.ui.mixin.DraggableElement );
4972
4973 /* Events */
4974
4975 /**
4976 * @event dragstart
4977 *
4978 * A dragstart event is emitted when the user clicks and begins dragging an item.
4979 * @param {OO.ui.mixin.DraggableElement} item The item the user has clicked and is dragging with the mouse.
4980 */
4981
4982 /**
4983 * @event dragend
4984 * A dragend event is emitted when the user drags an item and releases the mouse,
4985 * thus terminating the drag operation.
4986 */
4987
4988 /**
4989 * @event drop
4990 * A drop event is emitted when the user drags an item and then releases the mouse button
4991 * over a valid target.
4992 */
4993
4994 /* Static Properties */
4995
4996 /**
4997 * @inheritdoc OO.ui.mixin.ButtonElement
4998 */
4999 OO.ui.mixin.DraggableElement.static.cancelButtonMouseDownEvents = false;
5000
5001 /* Methods */
5002
5003 /**
5004 * Respond to dragstart event.
5005 *
5006 * @private
5007 * @param {jQuery.Event} event jQuery event
5008 * @fires dragstart
5009 */
5010 OO.ui.mixin.DraggableElement.prototype.onDragStart = function ( e ) {
5011 var dataTransfer = e.originalEvent.dataTransfer;
5012 // Define drop effect
5013 dataTransfer.dropEffect = 'none';
5014 dataTransfer.effectAllowed = 'move';
5015 // Support: Firefox
5016 // We must set up a dataTransfer data property or Firefox seems to
5017 // ignore the fact the element is draggable.
5018 try {
5019 dataTransfer.setData( 'application-x/OOjs-UI-draggable', this.getIndex() );
5020 } catch ( err ) {
5021 // The above is only for Firefox. Move on if it fails.
5022 }
5023 // Add dragging class
5024 this.$element.addClass( 'oo-ui-draggableElement-dragging' );
5025 // Emit event
5026 this.emit( 'dragstart', this );
5027 return true;
5028 };
5029
5030 /**
5031 * Respond to dragend event.
5032 *
5033 * @private
5034 * @fires dragend
5035 */
5036 OO.ui.mixin.DraggableElement.prototype.onDragEnd = function () {
5037 this.$element.removeClass( 'oo-ui-draggableElement-dragging' );
5038 this.emit( 'dragend' );
5039 };
5040
5041 /**
5042 * Handle drop event.
5043 *
5044 * @private
5045 * @param {jQuery.Event} event jQuery event
5046 * @fires drop
5047 */
5048 OO.ui.mixin.DraggableElement.prototype.onDrop = function ( e ) {
5049 e.preventDefault();
5050 this.emit( 'drop', e );
5051 };
5052
5053 /**
5054 * In order for drag/drop to work, the dragover event must
5055 * return false and stop propogation.
5056 *
5057 * @private
5058 */
5059 OO.ui.mixin.DraggableElement.prototype.onDragOver = function ( e ) {
5060 e.preventDefault();
5061 };
5062
5063 /**
5064 * Set item index.
5065 * Store it in the DOM so we can access from the widget drag event
5066 *
5067 * @private
5068 * @param {number} Item index
5069 */
5070 OO.ui.mixin.DraggableElement.prototype.setIndex = function ( index ) {
5071 if ( this.index !== index ) {
5072 this.index = index;
5073 this.$element.data( 'index', index );
5074 }
5075 };
5076
5077 /**
5078 * Get item index
5079 *
5080 * @private
5081 * @return {number} Item index
5082 */
5083 OO.ui.mixin.DraggableElement.prototype.getIndex = function () {
5084 return this.index;
5085 };
5086
5087 /**
5088 * DraggableGroupElement is a mixin class used to create a group element to
5089 * contain draggable elements, which are items that can be clicked and dragged by a mouse.
5090 * The class is used with OO.ui.mixin.DraggableElement.
5091 *
5092 * @abstract
5093 * @class
5094 * @mixins OO.ui.mixin.GroupElement
5095 *
5096 * @constructor
5097 * @param {Object} [config] Configuration options
5098 * @cfg {string} [orientation] Item orientation: 'horizontal' or 'vertical'. The orientation
5099 * should match the layout of the items. Items displayed in a single row
5100 * or in several rows should use horizontal orientation. The vertical orientation should only be
5101 * used when the items are displayed in a single column. Defaults to 'vertical'
5102 */
5103 OO.ui.mixin.DraggableGroupElement = function OoUiMixinDraggableGroupElement( config ) {
5104 // Configuration initialization
5105 config = config || {};
5106
5107 // Parent constructor
5108 OO.ui.mixin.GroupElement.call( this, config );
5109
5110 // Properties
5111 this.orientation = config.orientation || 'vertical';
5112 this.dragItem = null;
5113 this.itemDragOver = null;
5114 this.itemKeys = {};
5115 this.sideInsertion = '';
5116
5117 // Events
5118 this.aggregate( {
5119 dragstart: 'itemDragStart',
5120 dragend: 'itemDragEnd',
5121 drop: 'itemDrop'
5122 } );
5123 this.connect( this, {
5124 itemDragStart: 'onItemDragStart',
5125 itemDrop: 'onItemDrop',
5126 itemDragEnd: 'onItemDragEnd'
5127 } );
5128 this.$element.on( {
5129 dragover: this.onDragOver.bind( this ),
5130 dragleave: this.onDragLeave.bind( this )
5131 } );
5132
5133 // Initialize
5134 if ( Array.isArray( config.items ) ) {
5135 this.addItems( config.items );
5136 }
5137 this.$placeholder = $( '<div>' )
5138 .addClass( 'oo-ui-draggableGroupElement-placeholder' );
5139 this.$element
5140 .addClass( 'oo-ui-draggableGroupElement' )
5141 .append( this.$status )
5142 .toggleClass( 'oo-ui-draggableGroupElement-horizontal', this.orientation === 'horizontal' )
5143 .prepend( this.$placeholder );
5144 };
5145
5146 /* Setup */
5147 OO.mixinClass( OO.ui.mixin.DraggableGroupElement, OO.ui.mixin.GroupElement );
5148
5149 /* Events */
5150
5151 /**
5152 * A 'reorder' event is emitted when the order of items in the group changes.
5153 *
5154 * @event reorder
5155 * @param {OO.ui.mixin.DraggableElement} item Reordered item
5156 * @param {number} [newIndex] New index for the item
5157 */
5158
5159 /* Methods */
5160
5161 /**
5162 * Respond to item drag start event
5163 *
5164 * @private
5165 * @param {OO.ui.mixin.DraggableElement} item Dragged item
5166 */
5167 OO.ui.mixin.DraggableGroupElement.prototype.onItemDragStart = function ( item ) {
5168 var i, len;
5169
5170 // Map the index of each object
5171 for ( i = 0, len = this.items.length; i < len; i++ ) {
5172 this.items[ i ].setIndex( i );
5173 }
5174
5175 if ( this.orientation === 'horizontal' ) {
5176 // Set the height of the indicator
5177 this.$placeholder.css( {
5178 height: item.$element.outerHeight(),
5179 width: 2
5180 } );
5181 } else {
5182 // Set the width of the indicator
5183 this.$placeholder.css( {
5184 height: 2,
5185 width: item.$element.outerWidth()
5186 } );
5187 }
5188 this.setDragItem( item );
5189 };
5190
5191 /**
5192 * Respond to item drag end event
5193 *
5194 * @private
5195 */
5196 OO.ui.mixin.DraggableGroupElement.prototype.onItemDragEnd = function () {
5197 this.unsetDragItem();
5198 return false;
5199 };
5200
5201 /**
5202 * Handle drop event and switch the order of the items accordingly
5203 *
5204 * @private
5205 * @param {OO.ui.mixin.DraggableElement} item Dropped item
5206 * @fires reorder
5207 */
5208 OO.ui.mixin.DraggableGroupElement.prototype.onItemDrop = function ( item ) {
5209 var toIndex = item.getIndex();
5210 // Check if the dropped item is from the current group
5211 // TODO: Figure out a way to configure a list of legally droppable
5212 // elements even if they are not yet in the list
5213 if ( this.getDragItem() ) {
5214 // If the insertion point is 'after', the insertion index
5215 // is shifted to the right (or to the left in RTL, hence 'after')
5216 if ( this.sideInsertion === 'after' ) {
5217 toIndex++;
5218 }
5219 // Emit change event
5220 this.emit( 'reorder', this.getDragItem(), toIndex );
5221 }
5222 this.unsetDragItem();
5223 // Return false to prevent propogation
5224 return false;
5225 };
5226
5227 /**
5228 * Handle dragleave event.
5229 *
5230 * @private
5231 */
5232 OO.ui.mixin.DraggableGroupElement.prototype.onDragLeave = function () {
5233 // This means the item was dragged outside the widget
5234 this.$placeholder
5235 .css( 'left', 0 )
5236 .addClass( 'oo-ui-element-hidden' );
5237 };
5238
5239 /**
5240 * Respond to dragover event
5241 *
5242 * @private
5243 * @param {jQuery.Event} event Event details
5244 */
5245 OO.ui.mixin.DraggableGroupElement.prototype.onDragOver = function ( e ) {
5246 var dragOverObj, $optionWidget, itemOffset, itemMidpoint, itemBoundingRect,
5247 itemSize, cssOutput, dragPosition, itemIndex, itemPosition,
5248 clientX = e.originalEvent.clientX,
5249 clientY = e.originalEvent.clientY;
5250
5251 // Get the OptionWidget item we are dragging over
5252 dragOverObj = this.getElementDocument().elementFromPoint( clientX, clientY );
5253 $optionWidget = $( dragOverObj ).closest( '.oo-ui-draggableElement' );
5254 if ( $optionWidget[ 0 ] ) {
5255 itemOffset = $optionWidget.offset();
5256 itemBoundingRect = $optionWidget[ 0 ].getBoundingClientRect();
5257 itemPosition = $optionWidget.position();
5258 itemIndex = $optionWidget.data( 'index' );
5259 }
5260
5261 if (
5262 itemOffset &&
5263 this.isDragging() &&
5264 itemIndex !== this.getDragItem().getIndex()
5265 ) {
5266 if ( this.orientation === 'horizontal' ) {
5267 // Calculate where the mouse is relative to the item width
5268 itemSize = itemBoundingRect.width;
5269 itemMidpoint = itemBoundingRect.left + itemSize / 2;
5270 dragPosition = clientX;
5271 // Which side of the item we hover over will dictate
5272 // where the placeholder will appear, on the left or
5273 // on the right
5274 cssOutput = {
5275 left: dragPosition < itemMidpoint ? itemPosition.left : itemPosition.left + itemSize,
5276 top: itemPosition.top
5277 };
5278 } else {
5279 // Calculate where the mouse is relative to the item height
5280 itemSize = itemBoundingRect.height;
5281 itemMidpoint = itemBoundingRect.top + itemSize / 2;
5282 dragPosition = clientY;
5283 // Which side of the item we hover over will dictate
5284 // where the placeholder will appear, on the top or
5285 // on the bottom
5286 cssOutput = {
5287 top: dragPosition < itemMidpoint ? itemPosition.top : itemPosition.top + itemSize,
5288 left: itemPosition.left
5289 };
5290 }
5291 // Store whether we are before or after an item to rearrange
5292 // For horizontal layout, we need to account for RTL, as this is flipped
5293 if ( this.orientation === 'horizontal' && this.$element.css( 'direction' ) === 'rtl' ) {
5294 this.sideInsertion = dragPosition < itemMidpoint ? 'after' : 'before';
5295 } else {
5296 this.sideInsertion = dragPosition < itemMidpoint ? 'before' : 'after';
5297 }
5298 // Add drop indicator between objects
5299 this.$placeholder
5300 .css( cssOutput )
5301 .removeClass( 'oo-ui-element-hidden' );
5302 } else {
5303 // This means the item was dragged outside the widget
5304 this.$placeholder
5305 .css( 'left', 0 )
5306 .addClass( 'oo-ui-element-hidden' );
5307 }
5308 // Prevent default
5309 e.preventDefault();
5310 };
5311
5312 /**
5313 * Set a dragged item
5314 *
5315 * @param {OO.ui.mixin.DraggableElement} item Dragged item
5316 */
5317 OO.ui.mixin.DraggableGroupElement.prototype.setDragItem = function ( item ) {
5318 this.dragItem = item;
5319 };
5320
5321 /**
5322 * Unset the current dragged item
5323 */
5324 OO.ui.mixin.DraggableGroupElement.prototype.unsetDragItem = function () {
5325 this.dragItem = null;
5326 this.itemDragOver = null;
5327 this.$placeholder.addClass( 'oo-ui-element-hidden' );
5328 this.sideInsertion = '';
5329 };
5330
5331 /**
5332 * Get the item that is currently being dragged.
5333 *
5334 * @return {OO.ui.mixin.DraggableElement|null} The currently dragged item, or `null` if no item is being dragged
5335 */
5336 OO.ui.mixin.DraggableGroupElement.prototype.getDragItem = function () {
5337 return this.dragItem;
5338 };
5339
5340 /**
5341 * Check if an item in the group is currently being dragged.
5342 *
5343 * @return {Boolean} Item is being dragged
5344 */
5345 OO.ui.mixin.DraggableGroupElement.prototype.isDragging = function () {
5346 return this.getDragItem() !== null;
5347 };
5348
5349 /**
5350 * IconElement is often mixed into other classes to generate an icon.
5351 * Icons are graphics, about the size of normal text. They are used to aid the user
5352 * in locating a control or to convey information in a space-efficient way. See the
5353 * [OOjs UI documentation on MediaWiki] [1] for a list of icons
5354 * included in the library.
5355 *
5356 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
5357 *
5358 * @abstract
5359 * @class
5360 *
5361 * @constructor
5362 * @param {Object} [config] Configuration options
5363 * @cfg {jQuery} [$icon] The icon element created by the class. If this configuration is omitted,
5364 * the icon element will use a generated `<span>`. To use a different HTML tag, or to specify that
5365 * the icon element be set to an existing icon instead of the one generated by this class, set a
5366 * value using a jQuery selection. For example:
5367 *
5368 * // Use a <div> tag instead of a <span>
5369 * $icon: $("<div>")
5370 * // Use an existing icon element instead of the one generated by the class
5371 * $icon: this.$element
5372 * // Use an icon element from a child widget
5373 * $icon: this.childwidget.$element
5374 * @cfg {Object|string} [icon=''] The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of
5375 * symbolic names. A map is used for i18n purposes and contains a `default` icon
5376 * name and additional names keyed by language code. The `default` name is used when no icon is keyed
5377 * by the user's language.
5378 *
5379 * Example of an i18n map:
5380 *
5381 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
5382 * See the [OOjs UI documentation on MediaWiki] [2] for a list of icons included in the library.
5383 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
5384 * @cfg {string|Function} [iconTitle] A text string used as the icon title, or a function that returns title
5385 * text. The icon title is displayed when users move the mouse over the icon.
5386 */
5387 OO.ui.mixin.IconElement = function OoUiMixinIconElement( config ) {
5388 // Configuration initialization
5389 config = config || {};
5390
5391 // Properties
5392 this.$icon = null;
5393 this.icon = null;
5394 this.iconTitle = null;
5395
5396 // Initialization
5397 this.setIcon( config.icon || this.constructor.static.icon );
5398 this.setIconTitle( config.iconTitle || this.constructor.static.iconTitle );
5399 this.setIconElement( config.$icon || $( '<span>' ) );
5400 };
5401
5402 /* Setup */
5403
5404 OO.initClass( OO.ui.mixin.IconElement );
5405
5406 /* Static Properties */
5407
5408 /**
5409 * The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of symbolic names. A map is used
5410 * for i18n purposes and contains a `default` icon name and additional names keyed by
5411 * language code. The `default` name is used when no icon is keyed by the user's language.
5412 *
5413 * Example of an i18n map:
5414 *
5415 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
5416 *
5417 * Note: the static property will be overridden if the #icon configuration is used.
5418 *
5419 * @static
5420 * @inheritable
5421 * @property {Object|string}
5422 */
5423 OO.ui.mixin.IconElement.static.icon = null;
5424
5425 /**
5426 * The icon title, displayed when users move the mouse over the icon. The value can be text, a
5427 * function that returns title text, or `null` for no title.
5428 *
5429 * The static property will be overridden if the #iconTitle configuration is used.
5430 *
5431 * @static
5432 * @inheritable
5433 * @property {string|Function|null}
5434 */
5435 OO.ui.mixin.IconElement.static.iconTitle = null;
5436
5437 /* Methods */
5438
5439 /**
5440 * Set the icon element. This method is used to retarget an icon mixin so that its functionality
5441 * applies to the specified icon element instead of the one created by the class. If an icon
5442 * element is already set, the mixin’s effect on that element is removed. Generated CSS classes
5443 * and mixin methods will no longer affect the element.
5444 *
5445 * @param {jQuery} $icon Element to use as icon
5446 */
5447 OO.ui.mixin.IconElement.prototype.setIconElement = function ( $icon ) {
5448 if ( this.$icon ) {
5449 this.$icon
5450 .removeClass( 'oo-ui-iconElement-icon oo-ui-icon-' + this.icon )
5451 .removeAttr( 'title' );
5452 }
5453
5454 this.$icon = $icon
5455 .addClass( 'oo-ui-iconElement-icon' )
5456 .toggleClass( 'oo-ui-icon-' + this.icon, !!this.icon );
5457 if ( this.iconTitle !== null ) {
5458 this.$icon.attr( 'title', this.iconTitle );
5459 }
5460
5461 this.updateThemeClasses();
5462 };
5463
5464 /**
5465 * Set icon by symbolic name (e.g., ‘remove’ or ‘menu’). Use `null` to remove an icon.
5466 * The icon parameter can also be set to a map of icon names. See the #icon config setting
5467 * for an example.
5468 *
5469 * @param {Object|string|null} icon A symbolic icon name, a {@link #icon map of icon names} keyed
5470 * by language code, or `null` to remove the icon.
5471 * @chainable
5472 */
5473 OO.ui.mixin.IconElement.prototype.setIcon = function ( icon ) {
5474 icon = OO.isPlainObject( icon ) ? OO.ui.getLocalValue( icon, null, 'default' ) : icon;
5475 icon = typeof icon === 'string' && icon.trim().length ? icon.trim() : null;
5476
5477 if ( this.icon !== icon ) {
5478 if ( this.$icon ) {
5479 if ( this.icon !== null ) {
5480 this.$icon.removeClass( 'oo-ui-icon-' + this.icon );
5481 }
5482 if ( icon !== null ) {
5483 this.$icon.addClass( 'oo-ui-icon-' + icon );
5484 }
5485 }
5486 this.icon = icon;
5487 }
5488
5489 this.$element.toggleClass( 'oo-ui-iconElement', !!this.icon );
5490 this.updateThemeClasses();
5491
5492 return this;
5493 };
5494
5495 /**
5496 * Set the icon title. Use `null` to remove the title.
5497 *
5498 * @param {string|Function|null} iconTitle A text string used as the icon title,
5499 * a function that returns title text, or `null` for no title.
5500 * @chainable
5501 */
5502 OO.ui.mixin.IconElement.prototype.setIconTitle = function ( iconTitle ) {
5503 iconTitle = typeof iconTitle === 'function' ||
5504 ( typeof iconTitle === 'string' && iconTitle.length ) ?
5505 OO.ui.resolveMsg( iconTitle ) : null;
5506
5507 if ( this.iconTitle !== iconTitle ) {
5508 this.iconTitle = iconTitle;
5509 if ( this.$icon ) {
5510 if ( this.iconTitle !== null ) {
5511 this.$icon.attr( 'title', iconTitle );
5512 } else {
5513 this.$icon.removeAttr( 'title' );
5514 }
5515 }
5516 }
5517
5518 return this;
5519 };
5520
5521 /**
5522 * Get the symbolic name of the icon.
5523 *
5524 * @return {string} Icon name
5525 */
5526 OO.ui.mixin.IconElement.prototype.getIcon = function () {
5527 return this.icon;
5528 };
5529
5530 /**
5531 * Get the icon title. The title text is displayed when a user moves the mouse over the icon.
5532 *
5533 * @return {string} Icon title text
5534 */
5535 OO.ui.mixin.IconElement.prototype.getIconTitle = function () {
5536 return this.iconTitle;
5537 };
5538
5539 /**
5540 * IndicatorElement is often mixed into other classes to generate an indicator.
5541 * Indicators are small graphics that are generally used in two ways:
5542 *
5543 * - To draw attention to the status of an item. For example, an indicator might be
5544 * used to show that an item in a list has errors that need to be resolved.
5545 * - To clarify the function of a control that acts in an exceptional way (a button
5546 * that opens a menu instead of performing an action directly, for example).
5547 *
5548 * For a list of indicators included in the library, please see the
5549 * [OOjs UI documentation on MediaWiki] [1].
5550 *
5551 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
5552 *
5553 * @abstract
5554 * @class
5555 *
5556 * @constructor
5557 * @param {Object} [config] Configuration options
5558 * @cfg {jQuery} [$indicator] The indicator element created by the class. If this
5559 * configuration is omitted, the indicator element will use a generated `<span>`.
5560 * @cfg {string} [indicator] Symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
5561 * See the [OOjs UI documentation on MediaWiki][2] for a list of indicators included
5562 * in the library.
5563 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
5564 * @cfg {string|Function} [indicatorTitle] A text string used as the indicator title,
5565 * or a function that returns title text. The indicator title is displayed when users move
5566 * the mouse over the indicator.
5567 */
5568 OO.ui.mixin.IndicatorElement = function OoUiMixinIndicatorElement( config ) {
5569 // Configuration initialization
5570 config = config || {};
5571
5572 // Properties
5573 this.$indicator = null;
5574 this.indicator = null;
5575 this.indicatorTitle = null;
5576
5577 // Initialization
5578 this.setIndicator( config.indicator || this.constructor.static.indicator );
5579 this.setIndicatorTitle( config.indicatorTitle || this.constructor.static.indicatorTitle );
5580 this.setIndicatorElement( config.$indicator || $( '<span>' ) );
5581 };
5582
5583 /* Setup */
5584
5585 OO.initClass( OO.ui.mixin.IndicatorElement );
5586
5587 /* Static Properties */
5588
5589 /**
5590 * Symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
5591 * The static property will be overridden if the #indicator configuration is used.
5592 *
5593 * @static
5594 * @inheritable
5595 * @property {string|null}
5596 */
5597 OO.ui.mixin.IndicatorElement.static.indicator = null;
5598
5599 /**
5600 * A text string used as the indicator title, a function that returns title text, or `null`
5601 * for no title. The static property will be overridden if the #indicatorTitle configuration is used.
5602 *
5603 * @static
5604 * @inheritable
5605 * @property {string|Function|null}
5606 */
5607 OO.ui.mixin.IndicatorElement.static.indicatorTitle = null;
5608
5609 /* Methods */
5610
5611 /**
5612 * Set the indicator element.
5613 *
5614 * If an element is already set, it will be cleaned up before setting up the new element.
5615 *
5616 * @param {jQuery} $indicator Element to use as indicator
5617 */
5618 OO.ui.mixin.IndicatorElement.prototype.setIndicatorElement = function ( $indicator ) {
5619 if ( this.$indicator ) {
5620 this.$indicator
5621 .removeClass( 'oo-ui-indicatorElement-indicator oo-ui-indicator-' + this.indicator )
5622 .removeAttr( 'title' );
5623 }
5624
5625 this.$indicator = $indicator
5626 .addClass( 'oo-ui-indicatorElement-indicator' )
5627 .toggleClass( 'oo-ui-indicator-' + this.indicator, !!this.indicator );
5628 if ( this.indicatorTitle !== null ) {
5629 this.$indicator.attr( 'title', this.indicatorTitle );
5630 }
5631
5632 this.updateThemeClasses();
5633 };
5634
5635 /**
5636 * Set the indicator by its symbolic name: ‘alert’, ‘down’, ‘next’, ‘previous’, ‘required’, ‘up’. Use `null` to remove the indicator.
5637 *
5638 * @param {string|null} indicator Symbolic name of indicator, or `null` for no indicator
5639 * @chainable
5640 */
5641 OO.ui.mixin.IndicatorElement.prototype.setIndicator = function ( indicator ) {
5642 indicator = typeof indicator === 'string' && indicator.length ? indicator.trim() : null;
5643
5644 if ( this.indicator !== indicator ) {
5645 if ( this.$indicator ) {
5646 if ( this.indicator !== null ) {
5647 this.$indicator.removeClass( 'oo-ui-indicator-' + this.indicator );
5648 }
5649 if ( indicator !== null ) {
5650 this.$indicator.addClass( 'oo-ui-indicator-' + indicator );
5651 }
5652 }
5653 this.indicator = indicator;
5654 }
5655
5656 this.$element.toggleClass( 'oo-ui-indicatorElement', !!this.indicator );
5657 this.updateThemeClasses();
5658
5659 return this;
5660 };
5661
5662 /**
5663 * Set the indicator title.
5664 *
5665 * The title is displayed when a user moves the mouse over the indicator.
5666 *
5667 * @param {string|Function|null} indicator Indicator title text, a function that returns text, or
5668 * `null` for no indicator title
5669 * @chainable
5670 */
5671 OO.ui.mixin.IndicatorElement.prototype.setIndicatorTitle = function ( indicatorTitle ) {
5672 indicatorTitle = typeof indicatorTitle === 'function' ||
5673 ( typeof indicatorTitle === 'string' && indicatorTitle.length ) ?
5674 OO.ui.resolveMsg( indicatorTitle ) : null;
5675
5676 if ( this.indicatorTitle !== indicatorTitle ) {
5677 this.indicatorTitle = indicatorTitle;
5678 if ( this.$indicator ) {
5679 if ( this.indicatorTitle !== null ) {
5680 this.$indicator.attr( 'title', indicatorTitle );
5681 } else {
5682 this.$indicator.removeAttr( 'title' );
5683 }
5684 }
5685 }
5686
5687 return this;
5688 };
5689
5690 /**
5691 * Get the symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
5692 *
5693 * @return {string} Symbolic name of indicator
5694 */
5695 OO.ui.mixin.IndicatorElement.prototype.getIndicator = function () {
5696 return this.indicator;
5697 };
5698
5699 /**
5700 * Get the indicator title.
5701 *
5702 * The title is displayed when a user moves the mouse over the indicator.
5703 *
5704 * @return {string} Indicator title text
5705 */
5706 OO.ui.mixin.IndicatorElement.prototype.getIndicatorTitle = function () {
5707 return this.indicatorTitle;
5708 };
5709
5710 /**
5711 * LabelElement is often mixed into other classes to generate a label, which
5712 * helps identify the function of an interface element.
5713 * See the [OOjs UI documentation on MediaWiki] [1] for more information.
5714 *
5715 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Labels
5716 *
5717 * @abstract
5718 * @class
5719 *
5720 * @constructor
5721 * @param {Object} [config] Configuration options
5722 * @cfg {jQuery} [$label] The label element created by the class. If this
5723 * configuration is omitted, the label element will use a generated `<span>`.
5724 * @cfg {jQuery|string|Function|OO.ui.HtmlSnippet} [label] The label text. The label can be specified
5725 * as a plaintext string, a jQuery selection of elements, or a function that will produce a string
5726 * in the future. See the [OOjs UI documentation on MediaWiki] [2] for examples.
5727 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Labels
5728 * @cfg {boolean} [autoFitLabel=true] Fit the label to the width of the parent element.
5729 * The label will be truncated to fit if necessary.
5730 */
5731 OO.ui.mixin.LabelElement = function OoUiMixinLabelElement( config ) {
5732 // Configuration initialization
5733 config = config || {};
5734
5735 // Properties
5736 this.$label = null;
5737 this.label = null;
5738 this.autoFitLabel = config.autoFitLabel === undefined || !!config.autoFitLabel;
5739
5740 // Initialization
5741 this.setLabel( config.label || this.constructor.static.label );
5742 this.setLabelElement( config.$label || $( '<span>' ) );
5743 };
5744
5745 /* Setup */
5746
5747 OO.initClass( OO.ui.mixin.LabelElement );
5748
5749 /* Events */
5750
5751 /**
5752 * @event labelChange
5753 * @param {string} value
5754 */
5755
5756 /* Static Properties */
5757
5758 /**
5759 * The label text. The label can be specified as a plaintext string, a function that will
5760 * produce a string in the future, or `null` for no label. The static value will
5761 * be overridden if a label is specified with the #label config option.
5762 *
5763 * @static
5764 * @inheritable
5765 * @property {string|Function|null}
5766 */
5767 OO.ui.mixin.LabelElement.static.label = null;
5768
5769 /* Methods */
5770
5771 /**
5772 * Set the label element.
5773 *
5774 * If an element is already set, it will be cleaned up before setting up the new element.
5775 *
5776 * @param {jQuery} $label Element to use as label
5777 */
5778 OO.ui.mixin.LabelElement.prototype.setLabelElement = function ( $label ) {
5779 if ( this.$label ) {
5780 this.$label.removeClass( 'oo-ui-labelElement-label' ).empty();
5781 }
5782
5783 this.$label = $label.addClass( 'oo-ui-labelElement-label' );
5784 this.setLabelContent( this.label );
5785 };
5786
5787 /**
5788 * Set the label.
5789 *
5790 * An empty string will result in the label being hidden. A string containing only whitespace will
5791 * be converted to a single `&nbsp;`.
5792 *
5793 * @param {jQuery|string|OO.ui.HtmlSnippet|Function|null} label Label nodes; text; a function that returns nodes or
5794 * text; or null for no label
5795 * @chainable
5796 */
5797 OO.ui.mixin.LabelElement.prototype.setLabel = function ( label ) {
5798 label = typeof label === 'function' ? OO.ui.resolveMsg( label ) : label;
5799 label = ( ( typeof label === 'string' && label.length ) || label instanceof jQuery || label instanceof OO.ui.HtmlSnippet ) ? label : null;
5800
5801 this.$element.toggleClass( 'oo-ui-labelElement', !!label );
5802
5803 if ( this.label !== label ) {
5804 if ( this.$label ) {
5805 this.setLabelContent( label );
5806 }
5807 this.label = label;
5808 this.emit( 'labelChange' );
5809 }
5810
5811 return this;
5812 };
5813
5814 /**
5815 * Get the label.
5816 *
5817 * @return {jQuery|string|Function|null} Label nodes; text; a function that returns nodes or
5818 * text; or null for no label
5819 */
5820 OO.ui.mixin.LabelElement.prototype.getLabel = function () {
5821 return this.label;
5822 };
5823
5824 /**
5825 * Fit the label.
5826 *
5827 * @chainable
5828 */
5829 OO.ui.mixin.LabelElement.prototype.fitLabel = function () {
5830 if ( this.$label && this.$label.autoEllipsis && this.autoFitLabel ) {
5831 this.$label.autoEllipsis( { hasSpan: false, tooltip: true } );
5832 }
5833
5834 return this;
5835 };
5836
5837 /**
5838 * Set the content of the label.
5839 *
5840 * Do not call this method until after the label element has been set by #setLabelElement.
5841 *
5842 * @private
5843 * @param {jQuery|string|Function|null} label Label nodes; text; a function that returns nodes or
5844 * text; or null for no label
5845 */
5846 OO.ui.mixin.LabelElement.prototype.setLabelContent = function ( label ) {
5847 if ( typeof label === 'string' ) {
5848 if ( label.match( /^\s*$/ ) ) {
5849 // Convert whitespace only string to a single non-breaking space
5850 this.$label.html( '&nbsp;' );
5851 } else {
5852 this.$label.text( label );
5853 }
5854 } else if ( label instanceof OO.ui.HtmlSnippet ) {
5855 this.$label.html( label.toString() );
5856 } else if ( label instanceof jQuery ) {
5857 this.$label.empty().append( label );
5858 } else {
5859 this.$label.empty();
5860 }
5861 };
5862
5863 /**
5864 * LookupElement is a mixin that creates a {@link OO.ui.FloatingMenuSelectWidget menu} of suggested values for
5865 * a {@link OO.ui.TextInputWidget text input widget}. Suggested values are based on the characters the user types
5866 * into the text input field and, in general, the menu is only displayed when the user types. If a suggested value is chosen
5867 * from the lookup menu, that value becomes the value of the input field.
5868 *
5869 * Note that a new menu of suggested items is displayed when a value is chosen from the lookup menu. If this is
5870 * not the desired behavior, disable lookup menus with the #setLookupsDisabled method, then set the value, then
5871 * re-enable lookups.
5872 *
5873 * See the [OOjs UI demos][1] for an example.
5874 *
5875 * [1]: https://tools.wmflabs.org/oojs-ui/oojs-ui/demos/index.html#widgets-apex-vector-ltr
5876 *
5877 * @class
5878 * @abstract
5879 *
5880 * @constructor
5881 * @param {Object} [config] Configuration options
5882 * @cfg {jQuery} [$overlay] Overlay for the lookup menu; defaults to relative positioning
5883 * @cfg {jQuery} [$container=this.$element] The container element. The lookup menu is rendered beneath the specified element.
5884 * @cfg {boolean} [allowSuggestionsWhenEmpty=false] Request and display a lookup menu when the text input is empty.
5885 * By default, the lookup menu is not generated and displayed until the user begins to type.
5886 */
5887 OO.ui.mixin.LookupElement = function OoUiMixinLookupElement( config ) {
5888 // Configuration initialization
5889 config = config || {};
5890
5891 // Properties
5892 this.$overlay = config.$overlay || this.$element;
5893 this.lookupMenu = new OO.ui.FloatingMenuSelectWidget( {
5894 widget: this,
5895 input: this,
5896 $container: config.$container || this.$element
5897 } );
5898
5899 this.allowSuggestionsWhenEmpty = config.allowSuggestionsWhenEmpty || false;
5900
5901 this.lookupCache = {};
5902 this.lookupQuery = null;
5903 this.lookupRequest = null;
5904 this.lookupsDisabled = false;
5905 this.lookupInputFocused = false;
5906
5907 // Events
5908 this.$input.on( {
5909 focus: this.onLookupInputFocus.bind( this ),
5910 blur: this.onLookupInputBlur.bind( this ),
5911 mousedown: this.onLookupInputMouseDown.bind( this )
5912 } );
5913 this.connect( this, { change: 'onLookupInputChange' } );
5914 this.lookupMenu.connect( this, {
5915 toggle: 'onLookupMenuToggle',
5916 choose: 'onLookupMenuItemChoose'
5917 } );
5918
5919 // Initialization
5920 this.$element.addClass( 'oo-ui-lookupElement' );
5921 this.lookupMenu.$element.addClass( 'oo-ui-lookupElement-menu' );
5922 this.$overlay.append( this.lookupMenu.$element );
5923 };
5924
5925 /* Methods */
5926
5927 /**
5928 * Handle input focus event.
5929 *
5930 * @protected
5931 * @param {jQuery.Event} e Input focus event
5932 */
5933 OO.ui.mixin.LookupElement.prototype.onLookupInputFocus = function () {
5934 this.lookupInputFocused = true;
5935 this.populateLookupMenu();
5936 };
5937
5938 /**
5939 * Handle input blur event.
5940 *
5941 * @protected
5942 * @param {jQuery.Event} e Input blur event
5943 */
5944 OO.ui.mixin.LookupElement.prototype.onLookupInputBlur = function () {
5945 this.closeLookupMenu();
5946 this.lookupInputFocused = false;
5947 };
5948
5949 /**
5950 * Handle input mouse down event.
5951 *
5952 * @protected
5953 * @param {jQuery.Event} e Input mouse down event
5954 */
5955 OO.ui.mixin.LookupElement.prototype.onLookupInputMouseDown = function () {
5956 // Only open the menu if the input was already focused.
5957 // This way we allow the user to open the menu again after closing it with Esc
5958 // by clicking in the input. Opening (and populating) the menu when initially
5959 // clicking into the input is handled by the focus handler.
5960 if ( this.lookupInputFocused && !this.lookupMenu.isVisible() ) {
5961 this.populateLookupMenu();
5962 }
5963 };
5964
5965 /**
5966 * Handle input change event.
5967 *
5968 * @protected
5969 * @param {string} value New input value
5970 */
5971 OO.ui.mixin.LookupElement.prototype.onLookupInputChange = function () {
5972 if ( this.lookupInputFocused ) {
5973 this.populateLookupMenu();
5974 }
5975 };
5976
5977 /**
5978 * Handle the lookup menu being shown/hidden.
5979 *
5980 * @protected
5981 * @param {boolean} visible Whether the lookup menu is now visible.
5982 */
5983 OO.ui.mixin.LookupElement.prototype.onLookupMenuToggle = function ( visible ) {
5984 if ( !visible ) {
5985 // When the menu is hidden, abort any active request and clear the menu.
5986 // This has to be done here in addition to closeLookupMenu(), because
5987 // MenuSelectWidget will close itself when the user presses Esc.
5988 this.abortLookupRequest();
5989 this.lookupMenu.clearItems();
5990 }
5991 };
5992
5993 /**
5994 * Handle menu item 'choose' event, updating the text input value to the value of the clicked item.
5995 *
5996 * @protected
5997 * @param {OO.ui.MenuOptionWidget} item Selected item
5998 */
5999 OO.ui.mixin.LookupElement.prototype.onLookupMenuItemChoose = function ( item ) {
6000 this.setValue( item.getData() );
6001 };
6002
6003 /**
6004 * Get lookup menu.
6005 *
6006 * @private
6007 * @return {OO.ui.FloatingMenuSelectWidget}
6008 */
6009 OO.ui.mixin.LookupElement.prototype.getLookupMenu = function () {
6010 return this.lookupMenu;
6011 };
6012
6013 /**
6014 * Disable or re-enable lookups.
6015 *
6016 * When lookups are disabled, calls to #populateLookupMenu will be ignored.
6017 *
6018 * @param {boolean} disabled Disable lookups
6019 */
6020 OO.ui.mixin.LookupElement.prototype.setLookupsDisabled = function ( disabled ) {
6021 this.lookupsDisabled = !!disabled;
6022 };
6023
6024 /**
6025 * Open the menu. If there are no entries in the menu, this does nothing.
6026 *
6027 * @private
6028 * @chainable
6029 */
6030 OO.ui.mixin.LookupElement.prototype.openLookupMenu = function () {
6031 if ( !this.lookupMenu.isEmpty() ) {
6032 this.lookupMenu.toggle( true );
6033 }
6034 return this;
6035 };
6036
6037 /**
6038 * Close the menu, empty it, and abort any pending request.
6039 *
6040 * @private
6041 * @chainable
6042 */
6043 OO.ui.mixin.LookupElement.prototype.closeLookupMenu = function () {
6044 this.lookupMenu.toggle( false );
6045 this.abortLookupRequest();
6046 this.lookupMenu.clearItems();
6047 return this;
6048 };
6049
6050 /**
6051 * Request menu items based on the input's current value, and when they arrive,
6052 * populate the menu with these items and show the menu.
6053 *
6054 * If lookups have been disabled with #setLookupsDisabled, this function does nothing.
6055 *
6056 * @private
6057 * @chainable
6058 */
6059 OO.ui.mixin.LookupElement.prototype.populateLookupMenu = function () {
6060 var widget = this,
6061 value = this.getValue();
6062
6063 if ( this.lookupsDisabled || this.isReadOnly() ) {
6064 return;
6065 }
6066
6067 // If the input is empty, clear the menu, unless suggestions when empty are allowed.
6068 if ( !this.allowSuggestionsWhenEmpty && value === '' ) {
6069 this.closeLookupMenu();
6070 // Skip population if there is already a request pending for the current value
6071 } else if ( value !== this.lookupQuery ) {
6072 this.getLookupMenuItems()
6073 .done( function ( items ) {
6074 widget.lookupMenu.clearItems();
6075 if ( items.length ) {
6076 widget.lookupMenu
6077 .addItems( items )
6078 .toggle( true );
6079 widget.initializeLookupMenuSelection();
6080 } else {
6081 widget.lookupMenu.toggle( false );
6082 }
6083 } )
6084 .fail( function () {
6085 widget.lookupMenu.clearItems();
6086 } );
6087 }
6088
6089 return this;
6090 };
6091
6092 /**
6093 * Highlight the first selectable item in the menu.
6094 *
6095 * @private
6096 * @chainable
6097 */
6098 OO.ui.mixin.LookupElement.prototype.initializeLookupMenuSelection = function () {
6099 if ( !this.lookupMenu.getSelectedItem() ) {
6100 this.lookupMenu.highlightItem( this.lookupMenu.getFirstSelectableItem() );
6101 }
6102 };
6103
6104 /**
6105 * Get lookup menu items for the current query.
6106 *
6107 * @private
6108 * @return {jQuery.Promise} Promise object which will be passed menu items as the first argument of
6109 * the done event. If the request was aborted to make way for a subsequent request, this promise
6110 * will not be rejected: it will remain pending forever.
6111 */
6112 OO.ui.mixin.LookupElement.prototype.getLookupMenuItems = function () {
6113 var widget = this,
6114 value = this.getValue(),
6115 deferred = $.Deferred(),
6116 ourRequest;
6117
6118 this.abortLookupRequest();
6119 if ( Object.prototype.hasOwnProperty.call( this.lookupCache, value ) ) {
6120 deferred.resolve( this.getLookupMenuOptionsFromData( this.lookupCache[ value ] ) );
6121 } else {
6122 this.pushPending();
6123 this.lookupQuery = value;
6124 ourRequest = this.lookupRequest = this.getLookupRequest();
6125 ourRequest
6126 .always( function () {
6127 // We need to pop pending even if this is an old request, otherwise
6128 // the widget will remain pending forever.
6129 // TODO: this assumes that an aborted request will fail or succeed soon after
6130 // being aborted, or at least eventually. It would be nice if we could popPending()
6131 // at abort time, but only if we knew that we hadn't already called popPending()
6132 // for that request.
6133 widget.popPending();
6134 } )
6135 .done( function ( response ) {
6136 // If this is an old request (and aborting it somehow caused it to still succeed),
6137 // ignore its success completely
6138 if ( ourRequest === widget.lookupRequest ) {
6139 widget.lookupQuery = null;
6140 widget.lookupRequest = null;
6141 widget.lookupCache[ value ] = widget.getLookupCacheDataFromResponse( response );
6142 deferred.resolve( widget.getLookupMenuOptionsFromData( widget.lookupCache[ value ] ) );
6143 }
6144 } )
6145 .fail( function () {
6146 // If this is an old request (or a request failing because it's being aborted),
6147 // ignore its failure completely
6148 if ( ourRequest === widget.lookupRequest ) {
6149 widget.lookupQuery = null;
6150 widget.lookupRequest = null;
6151 deferred.reject();
6152 }
6153 } );
6154 }
6155 return deferred.promise();
6156 };
6157
6158 /**
6159 * Abort the currently pending lookup request, if any.
6160 *
6161 * @private
6162 */
6163 OO.ui.mixin.LookupElement.prototype.abortLookupRequest = function () {
6164 var oldRequest = this.lookupRequest;
6165 if ( oldRequest ) {
6166 // First unset this.lookupRequest to the fail handler will notice
6167 // that the request is no longer current
6168 this.lookupRequest = null;
6169 this.lookupQuery = null;
6170 oldRequest.abort();
6171 }
6172 };
6173
6174 /**
6175 * Get a new request object of the current lookup query value.
6176 *
6177 * @protected
6178 * @abstract
6179 * @return {jQuery.Promise} jQuery AJAX object, or promise object with an .abort() method
6180 */
6181 OO.ui.mixin.LookupElement.prototype.getLookupRequest = function () {
6182 // Stub, implemented in subclass
6183 return null;
6184 };
6185
6186 /**
6187 * Pre-process data returned by the request from #getLookupRequest.
6188 *
6189 * The return value of this function will be cached, and any further queries for the given value
6190 * will use the cache rather than doing API requests.
6191 *
6192 * @protected
6193 * @abstract
6194 * @param {Mixed} response Response from server
6195 * @return {Mixed} Cached result data
6196 */
6197 OO.ui.mixin.LookupElement.prototype.getLookupCacheDataFromResponse = function () {
6198 // Stub, implemented in subclass
6199 return [];
6200 };
6201
6202 /**
6203 * Get a list of menu option widgets from the (possibly cached) data returned by
6204 * #getLookupCacheDataFromResponse.
6205 *
6206 * @protected
6207 * @abstract
6208 * @param {Mixed} data Cached result data, usually an array
6209 * @return {OO.ui.MenuOptionWidget[]} Menu items
6210 */
6211 OO.ui.mixin.LookupElement.prototype.getLookupMenuOptionsFromData = function () {
6212 // Stub, implemented in subclass
6213 return [];
6214 };
6215
6216 /**
6217 * Set the read-only state of the widget.
6218 *
6219 * This will also disable/enable the lookups functionality.
6220 *
6221 * @param {boolean} readOnly Make input read-only
6222 * @chainable
6223 */
6224 OO.ui.mixin.LookupElement.prototype.setReadOnly = function ( readOnly ) {
6225 // Parent method
6226 // Note: Calling #setReadOnly this way assumes this is mixed into an OO.ui.TextInputWidget
6227 OO.ui.TextInputWidget.prototype.setReadOnly.call( this, readOnly );
6228
6229 // During construction, #setReadOnly is called before the OO.ui.mixin.LookupElement constructor
6230 if ( this.isReadOnly() && this.lookupMenu ) {
6231 this.closeLookupMenu();
6232 }
6233
6234 return this;
6235 };
6236
6237 /**
6238 * PopupElement is mixed into other classes to generate a {@link OO.ui.PopupWidget popup widget}.
6239 * A popup is a container for content. It is overlaid and positioned absolutely. By default, each
6240 * popup has an anchor, which is an arrow-like protrusion that points toward the popup’s origin.
6241 * See {@link OO.ui.PopupWidget PopupWidget} for an example.
6242 *
6243 * @abstract
6244 * @class
6245 *
6246 * @constructor
6247 * @param {Object} [config] Configuration options
6248 * @cfg {Object} [popup] Configuration to pass to popup
6249 * @cfg {boolean} [popup.autoClose=true] Popup auto-closes when it loses focus
6250 */
6251 OO.ui.mixin.PopupElement = function OoUiMixinPopupElement( config ) {
6252 // Configuration initialization
6253 config = config || {};
6254
6255 // Properties
6256 this.popup = new OO.ui.PopupWidget( $.extend(
6257 { autoClose: true },
6258 config.popup,
6259 { $autoCloseIgnore: this.$element }
6260 ) );
6261 };
6262
6263 /* Methods */
6264
6265 /**
6266 * Get popup.
6267 *
6268 * @return {OO.ui.PopupWidget} Popup widget
6269 */
6270 OO.ui.mixin.PopupElement.prototype.getPopup = function () {
6271 return this.popup;
6272 };
6273
6274 /**
6275 * The FlaggedElement class is an attribute mixin, meaning that it is used to add
6276 * additional functionality to an element created by another class. The class provides
6277 * a ‘flags’ property assigned the name (or an array of names) of styling flags,
6278 * which are used to customize the look and feel of a widget to better describe its
6279 * importance and functionality.
6280 *
6281 * The library currently contains the following styling flags for general use:
6282 *
6283 * - **progressive**: Progressive styling is applied to convey that the widget will move the user forward in a process.
6284 * - **destructive**: Destructive styling is applied to convey that the widget will remove something.
6285 * - **constructive**: Constructive styling is applied to convey that the widget will create something.
6286 *
6287 * The flags affect the appearance of the buttons:
6288 *
6289 * @example
6290 * // FlaggedElement is mixed into ButtonWidget to provide styling flags
6291 * var button1 = new OO.ui.ButtonWidget( {
6292 * label: 'Constructive',
6293 * flags: 'constructive'
6294 * } );
6295 * var button2 = new OO.ui.ButtonWidget( {
6296 * label: 'Destructive',
6297 * flags: 'destructive'
6298 * } );
6299 * var button3 = new OO.ui.ButtonWidget( {
6300 * label: 'Progressive',
6301 * flags: 'progressive'
6302 * } );
6303 * $( 'body' ).append( button1.$element, button2.$element, button3.$element );
6304 *
6305 * {@link OO.ui.ActionWidget ActionWidgets}, which are a special kind of button that execute an action, use these flags: **primary** and **safe**.
6306 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information.
6307 *
6308 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Flagged
6309 *
6310 * @abstract
6311 * @class
6312 *
6313 * @constructor
6314 * @param {Object} [config] Configuration options
6315 * @cfg {string|string[]} [flags] The name or names of the flags (e.g., 'constructive' or 'primary') to apply.
6316 * Please see the [OOjs UI documentation on MediaWiki] [2] for more information about available flags.
6317 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Flagged
6318 * @cfg {jQuery} [$flagged] The flagged element. By default,
6319 * the flagged functionality is applied to the element created by the class ($element).
6320 * If a different element is specified, the flagged functionality will be applied to it instead.
6321 */
6322 OO.ui.mixin.FlaggedElement = function OoUiMixinFlaggedElement( config ) {
6323 // Configuration initialization
6324 config = config || {};
6325
6326 // Properties
6327 this.flags = {};
6328 this.$flagged = null;
6329
6330 // Initialization
6331 this.setFlags( config.flags );
6332 this.setFlaggedElement( config.$flagged || this.$element );
6333 };
6334
6335 /* Events */
6336
6337 /**
6338 * @event flag
6339 * A flag event is emitted when the #clearFlags or #setFlags methods are used. The `changes`
6340 * parameter contains the name of each modified flag and indicates whether it was
6341 * added or removed.
6342 *
6343 * @param {Object.<string,boolean>} changes Object keyed by flag name. A Boolean `true` indicates
6344 * that the flag was added, `false` that the flag was removed.
6345 */
6346
6347 /* Methods */
6348
6349 /**
6350 * Set the flagged element.
6351 *
6352 * This method is used to retarget a flagged mixin so that its functionality applies to the specified element.
6353 * If an element is already set, the method will remove the mixin’s effect on that element.
6354 *
6355 * @param {jQuery} $flagged Element that should be flagged
6356 */
6357 OO.ui.mixin.FlaggedElement.prototype.setFlaggedElement = function ( $flagged ) {
6358 var classNames = Object.keys( this.flags ).map( function ( flag ) {
6359 return 'oo-ui-flaggedElement-' + flag;
6360 } ).join( ' ' );
6361
6362 if ( this.$flagged ) {
6363 this.$flagged.removeClass( classNames );
6364 }
6365
6366 this.$flagged = $flagged.addClass( classNames );
6367 };
6368
6369 /**
6370 * Check if the specified flag is set.
6371 *
6372 * @param {string} flag Name of flag
6373 * @return {boolean} The flag is set
6374 */
6375 OO.ui.mixin.FlaggedElement.prototype.hasFlag = function ( flag ) {
6376 // This may be called before the constructor, thus before this.flags is set
6377 return this.flags && ( flag in this.flags );
6378 };
6379
6380 /**
6381 * Get the names of all flags set.
6382 *
6383 * @return {string[]} Flag names
6384 */
6385 OO.ui.mixin.FlaggedElement.prototype.getFlags = function () {
6386 // This may be called before the constructor, thus before this.flags is set
6387 return Object.keys( this.flags || {} );
6388 };
6389
6390 /**
6391 * Clear all flags.
6392 *
6393 * @chainable
6394 * @fires flag
6395 */
6396 OO.ui.mixin.FlaggedElement.prototype.clearFlags = function () {
6397 var flag, className,
6398 changes = {},
6399 remove = [],
6400 classPrefix = 'oo-ui-flaggedElement-';
6401
6402 for ( flag in this.flags ) {
6403 className = classPrefix + flag;
6404 changes[ flag ] = false;
6405 delete this.flags[ flag ];
6406 remove.push( className );
6407 }
6408
6409 if ( this.$flagged ) {
6410 this.$flagged.removeClass( remove.join( ' ' ) );
6411 }
6412
6413 this.updateThemeClasses();
6414 this.emit( 'flag', changes );
6415
6416 return this;
6417 };
6418
6419 /**
6420 * Add one or more flags.
6421 *
6422 * @param {string|string[]|Object.<string, boolean>} flags A flag name, an array of flag names,
6423 * or an object keyed by flag name with a boolean value that indicates whether the flag should
6424 * be added (`true`) or removed (`false`).
6425 * @chainable
6426 * @fires flag
6427 */
6428 OO.ui.mixin.FlaggedElement.prototype.setFlags = function ( flags ) {
6429 var i, len, flag, className,
6430 changes = {},
6431 add = [],
6432 remove = [],
6433 classPrefix = 'oo-ui-flaggedElement-';
6434
6435 if ( typeof flags === 'string' ) {
6436 className = classPrefix + flags;
6437 // Set
6438 if ( !this.flags[ flags ] ) {
6439 this.flags[ flags ] = true;
6440 add.push( className );
6441 }
6442 } else if ( Array.isArray( flags ) ) {
6443 for ( i = 0, len = flags.length; i < len; i++ ) {
6444 flag = flags[ i ];
6445 className = classPrefix + flag;
6446 // Set
6447 if ( !this.flags[ flag ] ) {
6448 changes[ flag ] = true;
6449 this.flags[ flag ] = true;
6450 add.push( className );
6451 }
6452 }
6453 } else if ( OO.isPlainObject( flags ) ) {
6454 for ( flag in flags ) {
6455 className = classPrefix + flag;
6456 if ( flags[ flag ] ) {
6457 // Set
6458 if ( !this.flags[ flag ] ) {
6459 changes[ flag ] = true;
6460 this.flags[ flag ] = true;
6461 add.push( className );
6462 }
6463 } else {
6464 // Remove
6465 if ( this.flags[ flag ] ) {
6466 changes[ flag ] = false;
6467 delete this.flags[ flag ];
6468 remove.push( className );
6469 }
6470 }
6471 }
6472 }
6473
6474 if ( this.$flagged ) {
6475 this.$flagged
6476 .addClass( add.join( ' ' ) )
6477 .removeClass( remove.join( ' ' ) );
6478 }
6479
6480 this.updateThemeClasses();
6481 this.emit( 'flag', changes );
6482
6483 return this;
6484 };
6485
6486 /**
6487 * TitledElement is mixed into other classes to provide a `title` attribute.
6488 * Titles are rendered by the browser and are made visible when the user moves
6489 * the mouse over the element. Titles are not visible on touch devices.
6490 *
6491 * @example
6492 * // TitledElement provides a 'title' attribute to the
6493 * // ButtonWidget class
6494 * var button = new OO.ui.ButtonWidget( {
6495 * label: 'Button with Title',
6496 * title: 'I am a button'
6497 * } );
6498 * $( 'body' ).append( button.$element );
6499 *
6500 * @abstract
6501 * @class
6502 *
6503 * @constructor
6504 * @param {Object} [config] Configuration options
6505 * @cfg {jQuery} [$titled] The element to which the `title` attribute is applied.
6506 * If this config is omitted, the title functionality is applied to $element, the
6507 * element created by the class.
6508 * @cfg {string|Function} [title] The title text or a function that returns text. If
6509 * this config is omitted, the value of the {@link #static-title static title} property is used.
6510 */
6511 OO.ui.mixin.TitledElement = function OoUiMixinTitledElement( config ) {
6512 // Configuration initialization
6513 config = config || {};
6514
6515 // Properties
6516 this.$titled = null;
6517 this.title = null;
6518
6519 // Initialization
6520 this.setTitle( config.title || this.constructor.static.title );
6521 this.setTitledElement( config.$titled || this.$element );
6522 };
6523
6524 /* Setup */
6525
6526 OO.initClass( OO.ui.mixin.TitledElement );
6527
6528 /* Static Properties */
6529
6530 /**
6531 * The title text, a function that returns text, or `null` for no title. The value of the static property
6532 * is overridden if the #title config option is used.
6533 *
6534 * @static
6535 * @inheritable
6536 * @property {string|Function|null}
6537 */
6538 OO.ui.mixin.TitledElement.static.title = null;
6539
6540 /* Methods */
6541
6542 /**
6543 * Set the titled element.
6544 *
6545 * This method is used to retarget a titledElement mixin so that its functionality applies to the specified element.
6546 * If an element is already set, the mixin’s effect on that element is removed before the new element is set up.
6547 *
6548 * @param {jQuery} $titled Element that should use the 'titled' functionality
6549 */
6550 OO.ui.mixin.TitledElement.prototype.setTitledElement = function ( $titled ) {
6551 if ( this.$titled ) {
6552 this.$titled.removeAttr( 'title' );
6553 }
6554
6555 this.$titled = $titled;
6556 if ( this.title ) {
6557 this.$titled.attr( 'title', this.title );
6558 }
6559 };
6560
6561 /**
6562 * Set title.
6563 *
6564 * @param {string|Function|null} title Title text, a function that returns text, or `null` for no title
6565 * @chainable
6566 */
6567 OO.ui.mixin.TitledElement.prototype.setTitle = function ( title ) {
6568 title = typeof title === 'string' ? OO.ui.resolveMsg( title ) : null;
6569
6570 if ( this.title !== title ) {
6571 if ( this.$titled ) {
6572 if ( title !== null ) {
6573 this.$titled.attr( 'title', title );
6574 } else {
6575 this.$titled.removeAttr( 'title' );
6576 }
6577 }
6578 this.title = title;
6579 }
6580
6581 return this;
6582 };
6583
6584 /**
6585 * Get title.
6586 *
6587 * @return {string} Title string
6588 */
6589 OO.ui.mixin.TitledElement.prototype.getTitle = function () {
6590 return this.title;
6591 };
6592
6593 /**
6594 * Element that can be automatically clipped to visible boundaries.
6595 *
6596 * Whenever the element's natural height changes, you have to call
6597 * {@link OO.ui.mixin.ClippableElement#clip} to make sure it's still
6598 * clipping correctly.
6599 *
6600 * The dimensions of #$clippableContainer will be compared to the boundaries of the
6601 * nearest scrollable container. If #$clippableContainer is too tall and/or too wide,
6602 * then #$clippable will be given a fixed reduced height and/or width and will be made
6603 * scrollable. By default, #$clippable and #$clippableContainer are the same element,
6604 * but you can build a static footer by setting #$clippableContainer to an element that contains
6605 * #$clippable and the footer.
6606 *
6607 * @abstract
6608 * @class
6609 *
6610 * @constructor
6611 * @param {Object} [config] Configuration options
6612 * @cfg {jQuery} [$clippable] Node to clip, assigned to #$clippable, omit to use #$element
6613 * @cfg {jQuery} [$clippableContainer] Node to keep visible, assigned to #$clippableContainer,
6614 * omit to use #$clippable
6615 */
6616 OO.ui.mixin.ClippableElement = function OoUiMixinClippableElement( config ) {
6617 // Configuration initialization
6618 config = config || {};
6619
6620 // Properties
6621 this.$clippable = null;
6622 this.$clippableContainer = null;
6623 this.clipping = false;
6624 this.clippedHorizontally = false;
6625 this.clippedVertically = false;
6626 this.$clippableScrollableContainer = null;
6627 this.$clippableScroller = null;
6628 this.$clippableWindow = null;
6629 this.idealWidth = null;
6630 this.idealHeight = null;
6631 this.onClippableScrollHandler = this.clip.bind( this );
6632 this.onClippableWindowResizeHandler = this.clip.bind( this );
6633
6634 // Initialization
6635 if ( config.$clippableContainer ) {
6636 this.setClippableContainer( config.$clippableContainer );
6637 }
6638 this.setClippableElement( config.$clippable || this.$element );
6639 };
6640
6641 /* Methods */
6642
6643 /**
6644 * Set clippable element.
6645 *
6646 * If an element is already set, it will be cleaned up before setting up the new element.
6647 *
6648 * @param {jQuery} $clippable Element to make clippable
6649 */
6650 OO.ui.mixin.ClippableElement.prototype.setClippableElement = function ( $clippable ) {
6651 if ( this.$clippable ) {
6652 this.$clippable.removeClass( 'oo-ui-clippableElement-clippable' );
6653 this.$clippable.css( { width: '', height: '', overflowX: '', overflowY: '' } );
6654 OO.ui.Element.static.reconsiderScrollbars( this.$clippable[ 0 ] );
6655 }
6656
6657 this.$clippable = $clippable.addClass( 'oo-ui-clippableElement-clippable' );
6658 this.clip();
6659 };
6660
6661 /**
6662 * Set clippable container.
6663 *
6664 * This is the container that will be measured when deciding whether to clip. When clipping,
6665 * #$clippable will be resized in order to keep the clippable container fully visible.
6666 *
6667 * If the clippable container is unset, #$clippable will be used.
6668 *
6669 * @param {jQuery|null} $clippableContainer Container to keep visible, or null to unset
6670 */
6671 OO.ui.mixin.ClippableElement.prototype.setClippableContainer = function ( $clippableContainer ) {
6672 this.$clippableContainer = $clippableContainer;
6673 if ( this.$clippable ) {
6674 this.clip();
6675 }
6676 };
6677
6678 /**
6679 * Toggle clipping.
6680 *
6681 * Do not turn clipping on until after the element is attached to the DOM and visible.
6682 *
6683 * @param {boolean} [clipping] Enable clipping, omit to toggle
6684 * @chainable
6685 */
6686 OO.ui.mixin.ClippableElement.prototype.toggleClipping = function ( clipping ) {
6687 clipping = clipping === undefined ? !this.clipping : !!clipping;
6688
6689 if ( this.clipping !== clipping ) {
6690 this.clipping = clipping;
6691 if ( clipping ) {
6692 this.$clippableScrollableContainer = $( this.getClosestScrollableElementContainer() );
6693 // If the clippable container is the root, we have to listen to scroll events and check
6694 // jQuery.scrollTop on the window because of browser inconsistencies
6695 this.$clippableScroller = this.$clippableScrollableContainer.is( 'html, body' ) ?
6696 $( OO.ui.Element.static.getWindow( this.$clippableScrollableContainer ) ) :
6697 this.$clippableScrollableContainer;
6698 this.$clippableScroller.on( 'scroll', this.onClippableScrollHandler );
6699 this.$clippableWindow = $( this.getElementWindow() )
6700 .on( 'resize', this.onClippableWindowResizeHandler );
6701 // Initial clip after visible
6702 this.clip();
6703 } else {
6704 this.$clippable.css( { width: '', height: '', overflowX: '', overflowY: '' } );
6705 OO.ui.Element.static.reconsiderScrollbars( this.$clippable[ 0 ] );
6706
6707 this.$clippableScrollableContainer = null;
6708 this.$clippableScroller.off( 'scroll', this.onClippableScrollHandler );
6709 this.$clippableScroller = null;
6710 this.$clippableWindow.off( 'resize', this.onClippableWindowResizeHandler );
6711 this.$clippableWindow = null;
6712 }
6713 }
6714
6715 return this;
6716 };
6717
6718 /**
6719 * Check if the element will be clipped to fit the visible area of the nearest scrollable container.
6720 *
6721 * @return {boolean} Element will be clipped to the visible area
6722 */
6723 OO.ui.mixin.ClippableElement.prototype.isClipping = function () {
6724 return this.clipping;
6725 };
6726
6727 /**
6728 * Check if the bottom or right of the element is being clipped by the nearest scrollable container.
6729 *
6730 * @return {boolean} Part of the element is being clipped
6731 */
6732 OO.ui.mixin.ClippableElement.prototype.isClipped = function () {
6733 return this.clippedHorizontally || this.clippedVertically;
6734 };
6735
6736 /**
6737 * Check if the right of the element is being clipped by the nearest scrollable container.
6738 *
6739 * @return {boolean} Part of the element is being clipped
6740 */
6741 OO.ui.mixin.ClippableElement.prototype.isClippedHorizontally = function () {
6742 return this.clippedHorizontally;
6743 };
6744
6745 /**
6746 * Check if the bottom of the element is being clipped by the nearest scrollable container.
6747 *
6748 * @return {boolean} Part of the element is being clipped
6749 */
6750 OO.ui.mixin.ClippableElement.prototype.isClippedVertically = function () {
6751 return this.clippedVertically;
6752 };
6753
6754 /**
6755 * Set the ideal size. These are the dimensions the element will have when it's not being clipped.
6756 *
6757 * @param {number|string} [width] Width as a number of pixels or CSS string with unit suffix
6758 * @param {number|string} [height] Height as a number of pixels or CSS string with unit suffix
6759 */
6760 OO.ui.mixin.ClippableElement.prototype.setIdealSize = function ( width, height ) {
6761 this.idealWidth = width;
6762 this.idealHeight = height;
6763
6764 if ( !this.clipping ) {
6765 // Update dimensions
6766 this.$clippable.css( { width: width, height: height } );
6767 }
6768 // While clipping, idealWidth and idealHeight are not considered
6769 };
6770
6771 /**
6772 * Clip element to visible boundaries and allow scrolling when needed. Call this method when
6773 * the element's natural height changes.
6774 *
6775 * Element will be clipped the bottom or right of the element is within 10px of the edge of, or
6776 * overlapped by, the visible area of the nearest scrollable container.
6777 *
6778 * @chainable
6779 */
6780 OO.ui.mixin.ClippableElement.prototype.clip = function () {
6781 var $container, extraHeight, extraWidth, ccOffset,
6782 $scrollableContainer, scOffset, scHeight, scWidth,
6783 ccWidth, scrollerIsWindow, scrollTop, scrollLeft,
6784 desiredWidth, desiredHeight, allotedWidth, allotedHeight,
6785 naturalWidth, naturalHeight, clipWidth, clipHeight,
6786 buffer = 7; // Chosen by fair dice roll
6787
6788 if ( !this.clipping ) {
6789 // this.$clippableScrollableContainer and this.$clippableWindow are null, so the below will fail
6790 return this;
6791 }
6792
6793 $container = this.$clippableContainer || this.$clippable;
6794 extraHeight = $container.outerHeight() - this.$clippable.outerHeight();
6795 extraWidth = $container.outerWidth() - this.$clippable.outerWidth();
6796 ccOffset = $container.offset();
6797 $scrollableContainer = this.$clippableScrollableContainer.is( 'html, body' ) ?
6798 this.$clippableWindow : this.$clippableScrollableContainer;
6799 scOffset = $scrollableContainer.offset() || { top: 0, left: 0 };
6800 scHeight = $scrollableContainer.innerHeight() - buffer;
6801 scWidth = $scrollableContainer.innerWidth() - buffer;
6802 ccWidth = $container.outerWidth() + buffer;
6803 scrollerIsWindow = this.$clippableScroller[ 0 ] === this.$clippableWindow[ 0 ];
6804 scrollTop = scrollerIsWindow ? this.$clippableScroller.scrollTop() : 0;
6805 scrollLeft = scrollerIsWindow ? this.$clippableScroller.scrollLeft() : 0;
6806 desiredWidth = ccOffset.left < 0 ?
6807 ccWidth + ccOffset.left :
6808 ( scOffset.left + scrollLeft + scWidth ) - ccOffset.left;
6809 desiredHeight = ( scOffset.top + scrollTop + scHeight ) - ccOffset.top;
6810 allotedWidth = desiredWidth - extraWidth;
6811 allotedHeight = desiredHeight - extraHeight;
6812 naturalWidth = this.$clippable.prop( 'scrollWidth' );
6813 naturalHeight = this.$clippable.prop( 'scrollHeight' );
6814 clipWidth = allotedWidth < naturalWidth;
6815 clipHeight = allotedHeight < naturalHeight;
6816
6817 if ( clipWidth ) {
6818 this.$clippable.css( { overflowX: 'scroll', width: Math.max( 0, allotedWidth ) } );
6819 } else {
6820 this.$clippable.css( { width: this.idealWidth ? this.idealWidth - extraWidth : '', overflowX: '' } );
6821 }
6822 if ( clipHeight ) {
6823 this.$clippable.css( { overflowY: 'scroll', height: Math.max( 0, allotedHeight ) } );
6824 } else {
6825 this.$clippable.css( { height: this.idealHeight ? this.idealHeight - extraHeight : '', overflowY: '' } );
6826 }
6827
6828 // If we stopped clipping in at least one of the dimensions
6829 if ( ( this.clippedHorizontally && !clipWidth ) || ( this.clippedVertically && !clipHeight ) ) {
6830 OO.ui.Element.static.reconsiderScrollbars( this.$clippable[ 0 ] );
6831 }
6832
6833 this.clippedHorizontally = clipWidth;
6834 this.clippedVertically = clipHeight;
6835
6836 return this;
6837 };
6838
6839 /**
6840 * Element that will stick under a specified container, even when it is inserted elsewhere in the
6841 * document (for example, in a OO.ui.Window's $overlay).
6842 *
6843 * The elements's position is automatically calculated and maintained when window is resized or the
6844 * page is scrolled. If you reposition the container manually, you have to call #position to make
6845 * sure the element is still placed correctly.
6846 *
6847 * As positioning is only possible when both the element and the container are attached to the DOM
6848 * and visible, it's only done after you call #togglePositioning. You might want to do this inside
6849 * the #toggle method to display a floating popup, for example.
6850 *
6851 * @abstract
6852 * @class
6853 *
6854 * @constructor
6855 * @param {Object} [config] Configuration options
6856 * @cfg {jQuery} [$floatable] Node to position, assigned to #$floatable, omit to use #$element
6857 * @cfg {jQuery} [$floatableContainer] Node to position below
6858 */
6859 OO.ui.mixin.FloatableElement = function OoUiMixinFloatableElement( config ) {
6860 // Configuration initialization
6861 config = config || {};
6862
6863 // Properties
6864 this.$floatable = null;
6865 this.$floatableContainer = null;
6866 this.$floatableWindow = null;
6867 this.$floatableClosestScrollable = null;
6868 this.onFloatableScrollHandler = this.position.bind( this );
6869 this.onFloatableWindowResizeHandler = this.position.bind( this );
6870
6871 // Initialization
6872 this.setFloatableContainer( config.$floatableContainer );
6873 this.setFloatableElement( config.$floatable || this.$element );
6874 };
6875
6876 /* Methods */
6877
6878 /**
6879 * Set floatable element.
6880 *
6881 * If an element is already set, it will be cleaned up before setting up the new element.
6882 *
6883 * @param {jQuery} $floatable Element to make floatable
6884 */
6885 OO.ui.mixin.FloatableElement.prototype.setFloatableElement = function ( $floatable ) {
6886 if ( this.$floatable ) {
6887 this.$floatable.removeClass( 'oo-ui-floatableElement-floatable' );
6888 this.$floatable.css( { left: '', top: '' } );
6889 }
6890
6891 this.$floatable = $floatable.addClass( 'oo-ui-floatableElement-floatable' );
6892 this.position();
6893 };
6894
6895 /**
6896 * Set floatable container.
6897 *
6898 * The element will be always positioned under the specified container.
6899 *
6900 * @param {jQuery|null} $floatableContainer Container to keep visible, or null to unset
6901 */
6902 OO.ui.mixin.FloatableElement.prototype.setFloatableContainer = function ( $floatableContainer ) {
6903 this.$floatableContainer = $floatableContainer;
6904 if ( this.$floatable ) {
6905 this.position();
6906 }
6907 };
6908
6909 /**
6910 * Toggle positioning.
6911 *
6912 * Do not turn positioning on until after the element is attached to the DOM and visible.
6913 *
6914 * @param {boolean} [positioning] Enable positioning, omit to toggle
6915 * @chainable
6916 */
6917 OO.ui.mixin.FloatableElement.prototype.togglePositioning = function ( positioning ) {
6918 var closestScrollableOfContainer, closestScrollableOfFloatable;
6919
6920 positioning = positioning === undefined ? !this.positioning : !!positioning;
6921
6922 if ( this.positioning !== positioning ) {
6923 this.positioning = positioning;
6924
6925 closestScrollableOfContainer = OO.ui.Element.static.getClosestScrollableContainer( this.$floatableContainer[ 0 ] );
6926 closestScrollableOfFloatable = OO.ui.Element.static.getClosestScrollableContainer( this.$floatable[ 0 ] );
6927 if ( closestScrollableOfContainer !== closestScrollableOfFloatable ) {
6928 // If the scrollable is the root, we have to listen to scroll events
6929 // on the window because of browser inconsistencies (or do we? someone should verify this)
6930 if ( $( closestScrollableOfContainer ).is( 'html, body' ) ) {
6931 closestScrollableOfContainer = OO.ui.Element.static.getWindow( closestScrollableOfContainer );
6932 }
6933 }
6934
6935 if ( positioning ) {
6936 this.$floatableWindow = $( this.getElementWindow() );
6937 this.$floatableWindow.on( 'resize', this.onFloatableWindowResizeHandler );
6938
6939 if ( closestScrollableOfContainer !== closestScrollableOfFloatable ) {
6940 this.$floatableClosestScrollable = $( closestScrollableOfContainer );
6941 this.$floatableClosestScrollable.on( 'scroll', this.onFloatableScrollHandler );
6942 }
6943
6944 // Initial position after visible
6945 this.position();
6946 } else {
6947 if ( this.$floatableWindow ) {
6948 this.$floatableWindow.off( 'resize', this.onFloatableWindowResizeHandler );
6949 this.$floatableWindow = null;
6950 }
6951
6952 if ( this.$floatableClosestScrollable ) {
6953 this.$floatableClosestScrollable.off( 'scroll', this.onFloatableScrollHandler );
6954 this.$floatableClosestScrollable = null;
6955 }
6956
6957 this.$floatable.css( { left: '', top: '' } );
6958 }
6959 }
6960
6961 return this;
6962 };
6963
6964 /**
6965 * Position the floatable below its container.
6966 *
6967 * This should only be done when both of them are attached to the DOM and visible.
6968 *
6969 * @chainable
6970 */
6971 OO.ui.mixin.FloatableElement.prototype.position = function () {
6972 var pos;
6973
6974 if ( !this.positioning ) {
6975 return this;
6976 }
6977
6978 pos = OO.ui.Element.static.getRelativePosition( this.$floatableContainer, this.$floatable.offsetParent() );
6979
6980 // Position under container
6981 pos.top += this.$floatableContainer.height();
6982 this.$floatable.css( pos );
6983
6984 // We updated the position, so re-evaluate the clipping state.
6985 // (ClippableElement does not listen to 'scroll' events on $floatableContainer's parent, and so
6986 // will not notice the need to update itself.)
6987 // TODO: This is terrible, we shouldn't need to know about ClippableElement at all here. Why does
6988 // it not listen to the right events in the right places?
6989 if ( this.clip ) {
6990 this.clip();
6991 }
6992
6993 return this;
6994 };
6995
6996 /**
6997 * AccessKeyedElement is mixed into other classes to provide an `accesskey` attribute.
6998 * Accesskeys allow an user to go to a specific element by using
6999 * a shortcut combination of a browser specific keys + the key
7000 * set to the field.
7001 *
7002 * @example
7003 * // AccessKeyedElement provides an 'accesskey' attribute to the
7004 * // ButtonWidget class
7005 * var button = new OO.ui.ButtonWidget( {
7006 * label: 'Button with Accesskey',
7007 * accessKey: 'k'
7008 * } );
7009 * $( 'body' ).append( button.$element );
7010 *
7011 * @abstract
7012 * @class
7013 *
7014 * @constructor
7015 * @param {Object} [config] Configuration options
7016 * @cfg {jQuery} [$accessKeyed] The element to which the `accesskey` attribute is applied.
7017 * If this config is omitted, the accesskey functionality is applied to $element, the
7018 * element created by the class.
7019 * @cfg {string|Function} [accessKey] The key or a function that returns the key. If
7020 * this config is omitted, no accesskey will be added.
7021 */
7022 OO.ui.mixin.AccessKeyedElement = function OoUiMixinAccessKeyedElement( config ) {
7023 // Configuration initialization
7024 config = config || {};
7025
7026 // Properties
7027 this.$accessKeyed = null;
7028 this.accessKey = null;
7029
7030 // Initialization
7031 this.setAccessKey( config.accessKey || null );
7032 this.setAccessKeyedElement( config.$accessKeyed || this.$element );
7033 };
7034
7035 /* Setup */
7036
7037 OO.initClass( OO.ui.mixin.AccessKeyedElement );
7038
7039 /* Static Properties */
7040
7041 /**
7042 * The access key, a function that returns a key, or `null` for no accesskey.
7043 *
7044 * @static
7045 * @inheritable
7046 * @property {string|Function|null}
7047 */
7048 OO.ui.mixin.AccessKeyedElement.static.accessKey = null;
7049
7050 /* Methods */
7051
7052 /**
7053 * Set the accesskeyed element.
7054 *
7055 * This method is used to retarget a AccessKeyedElement mixin so that its functionality applies to the specified element.
7056 * If an element is already set, the mixin's effect on that element is removed before the new element is set up.
7057 *
7058 * @param {jQuery} $accessKeyed Element that should use the 'accesskeyes' functionality
7059 */
7060 OO.ui.mixin.AccessKeyedElement.prototype.setAccessKeyedElement = function ( $accessKeyed ) {
7061 if ( this.$accessKeyed ) {
7062 this.$accessKeyed.removeAttr( 'accesskey' );
7063 }
7064
7065 this.$accessKeyed = $accessKeyed;
7066 if ( this.accessKey ) {
7067 this.$accessKeyed.attr( 'accesskey', this.accessKey );
7068 }
7069 };
7070
7071 /**
7072 * Set accesskey.
7073 *
7074 * @param {string|Function|null} accesskey Key, a function that returns a key, or `null` for no accesskey
7075 * @chainable
7076 */
7077 OO.ui.mixin.AccessKeyedElement.prototype.setAccessKey = function ( accessKey ) {
7078 accessKey = typeof accessKey === 'string' ? OO.ui.resolveMsg( accessKey ) : null;
7079
7080 if ( this.accessKey !== accessKey ) {
7081 if ( this.$accessKeyed ) {
7082 if ( accessKey !== null ) {
7083 this.$accessKeyed.attr( 'accesskey', accessKey );
7084 } else {
7085 this.$accessKeyed.removeAttr( 'accesskey' );
7086 }
7087 }
7088 this.accessKey = accessKey;
7089 }
7090
7091 return this;
7092 };
7093
7094 /**
7095 * Get accesskey.
7096 *
7097 * @return {string} accessKey string
7098 */
7099 OO.ui.mixin.AccessKeyedElement.prototype.getAccessKey = function () {
7100 return this.accessKey;
7101 };
7102
7103 /**
7104 * Tools, together with {@link OO.ui.ToolGroup toolgroups}, constitute {@link OO.ui.Toolbar toolbars}.
7105 * Each tool is configured with a static name, title, and icon and is customized with the command to carry
7106 * out when the tool is selected. Tools must also be registered with a {@link OO.ui.ToolFactory tool factory},
7107 * which creates the tools on demand.
7108 *
7109 * Tools are added to toolgroups ({@link OO.ui.ListToolGroup ListToolGroup},
7110 * {@link OO.ui.BarToolGroup BarToolGroup}, or {@link OO.ui.MenuToolGroup MenuToolGroup}), which determine how
7111 * the tool is displayed in the toolbar. See {@link OO.ui.Toolbar toolbars} for an example.
7112 *
7113 * For more information, please see the [OOjs UI documentation on MediaWiki][1].
7114 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
7115 *
7116 * @abstract
7117 * @class
7118 * @extends OO.ui.Widget
7119 * @mixins OO.ui.mixin.IconElement
7120 * @mixins OO.ui.mixin.FlaggedElement
7121 * @mixins OO.ui.mixin.TabIndexedElement
7122 *
7123 * @constructor
7124 * @param {OO.ui.ToolGroup} toolGroup
7125 * @param {Object} [config] Configuration options
7126 * @cfg {string|Function} [title] Title text or a function that returns text. If this config is omitted, the value of
7127 * the {@link #static-title static title} property is used.
7128 *
7129 * The title is used in different ways depending on the type of toolgroup that contains the tool. The
7130 * 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
7131 * part of a {@link OO.ui.ListToolGroup list} or {@link OO.ui.MenuToolGroup menu} toolgroup.
7132 *
7133 * For bar toolgroups, a description of the accelerator key is appended to the title if an accelerator key
7134 * is associated with an action by the same name as the tool and accelerator functionality has been added to the application.
7135 * To add accelerator key functionality, you must subclass OO.ui.Toolbar and override the {@link OO.ui.Toolbar#getToolAccelerator getToolAccelerator} method.
7136 */
7137 OO.ui.Tool = function OoUiTool( toolGroup, config ) {
7138 // Allow passing positional parameters inside the config object
7139 if ( OO.isPlainObject( toolGroup ) && config === undefined ) {
7140 config = toolGroup;
7141 toolGroup = config.toolGroup;
7142 }
7143
7144 // Configuration initialization
7145 config = config || {};
7146
7147 // Parent constructor
7148 OO.ui.Tool.parent.call( this, config );
7149
7150 // Properties
7151 this.toolGroup = toolGroup;
7152 this.toolbar = this.toolGroup.getToolbar();
7153 this.active = false;
7154 this.$title = $( '<span>' );
7155 this.$accel = $( '<span>' );
7156 this.$link = $( '<a>' );
7157 this.title = null;
7158
7159 // Mixin constructors
7160 OO.ui.mixin.IconElement.call( this, config );
7161 OO.ui.mixin.FlaggedElement.call( this, config );
7162 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$link } ) );
7163
7164 // Events
7165 this.toolbar.connect( this, { updateState: 'onUpdateState' } );
7166
7167 // Initialization
7168 this.$title.addClass( 'oo-ui-tool-title' );
7169 this.$accel
7170 .addClass( 'oo-ui-tool-accel' )
7171 .prop( {
7172 // This may need to be changed if the key names are ever localized,
7173 // but for now they are essentially written in English
7174 dir: 'ltr',
7175 lang: 'en'
7176 } );
7177 this.$link
7178 .addClass( 'oo-ui-tool-link' )
7179 .append( this.$icon, this.$title, this.$accel )
7180 .attr( 'role', 'button' );
7181 this.$element
7182 .data( 'oo-ui-tool', this )
7183 .addClass(
7184 'oo-ui-tool ' + 'oo-ui-tool-name-' +
7185 this.constructor.static.name.replace( /^([^\/]+)\/([^\/]+).*$/, '$1-$2' )
7186 )
7187 .toggleClass( 'oo-ui-tool-with-label', this.constructor.static.displayBothIconAndLabel )
7188 .append( this.$link );
7189 this.setTitle( config.title || this.constructor.static.title );
7190 };
7191
7192 /* Setup */
7193
7194 OO.inheritClass( OO.ui.Tool, OO.ui.Widget );
7195 OO.mixinClass( OO.ui.Tool, OO.ui.mixin.IconElement );
7196 OO.mixinClass( OO.ui.Tool, OO.ui.mixin.FlaggedElement );
7197 OO.mixinClass( OO.ui.Tool, OO.ui.mixin.TabIndexedElement );
7198
7199 /* Static Properties */
7200
7201 /**
7202 * @static
7203 * @inheritdoc
7204 */
7205 OO.ui.Tool.static.tagName = 'span';
7206
7207 /**
7208 * Symbolic name of tool.
7209 *
7210 * The symbolic name is used internally to register the tool with a {@link OO.ui.ToolFactory ToolFactory}. It can
7211 * also be used when adding tools to toolgroups.
7212 *
7213 * @abstract
7214 * @static
7215 * @inheritable
7216 * @property {string}
7217 */
7218 OO.ui.Tool.static.name = '';
7219
7220 /**
7221 * Symbolic name of the group.
7222 *
7223 * The group name is used to associate tools with each other so that they can be selected later by
7224 * a {@link OO.ui.ToolGroup toolgroup}.
7225 *
7226 * @abstract
7227 * @static
7228 * @inheritable
7229 * @property {string}
7230 */
7231 OO.ui.Tool.static.group = '';
7232
7233 /**
7234 * 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.
7235 *
7236 * @abstract
7237 * @static
7238 * @inheritable
7239 * @property {string|Function}
7240 */
7241 OO.ui.Tool.static.title = '';
7242
7243 /**
7244 * Display both icon and label when the tool is used in a {@link OO.ui.BarToolGroup bar} toolgroup.
7245 * Normally only the icon is displayed, or only the label if no icon is given.
7246 *
7247 * @static
7248 * @inheritable
7249 * @property {boolean}
7250 */
7251 OO.ui.Tool.static.displayBothIconAndLabel = false;
7252
7253 /**
7254 * Add tool to catch-all groups automatically.
7255 *
7256 * A catch-all group, which contains all tools that do not currently belong to a toolgroup,
7257 * can be included in a toolgroup using the wildcard selector, an asterisk (*).
7258 *
7259 * @static
7260 * @inheritable
7261 * @property {boolean}
7262 */
7263 OO.ui.Tool.static.autoAddToCatchall = true;
7264
7265 /**
7266 * Add tool to named groups automatically.
7267 *
7268 * By default, tools that are configured with a static ‘group’ property are added
7269 * to that group and will be selected when the symbolic name of the group is specified (e.g., when
7270 * toolgroups include tools by group name).
7271 *
7272 * @static
7273 * @property {boolean}
7274 * @inheritable
7275 */
7276 OO.ui.Tool.static.autoAddToGroup = true;
7277
7278 /**
7279 * Check if this tool is compatible with given data.
7280 *
7281 * This is a stub that can be overriden to provide support for filtering tools based on an
7282 * arbitrary piece of information (e.g., where the cursor is in a document). The implementation
7283 * must also call this method so that the compatibility check can be performed.
7284 *
7285 * @static
7286 * @inheritable
7287 * @param {Mixed} data Data to check
7288 * @return {boolean} Tool can be used with data
7289 */
7290 OO.ui.Tool.static.isCompatibleWith = function () {
7291 return false;
7292 };
7293
7294 /* Methods */
7295
7296 /**
7297 * Handle the toolbar state being updated.
7298 *
7299 * This is an abstract method that must be overridden in a concrete subclass.
7300 *
7301 * @protected
7302 * @abstract
7303 */
7304 OO.ui.Tool.prototype.onUpdateState = function () {
7305 throw new Error(
7306 'OO.ui.Tool.onUpdateState not implemented in this subclass:' + this.constructor
7307 );
7308 };
7309
7310 /**
7311 * Handle the tool being selected.
7312 *
7313 * This is an abstract method that must be overridden in a concrete subclass.
7314 *
7315 * @protected
7316 * @abstract
7317 */
7318 OO.ui.Tool.prototype.onSelect = function () {
7319 throw new Error(
7320 'OO.ui.Tool.onSelect not implemented in this subclass:' + this.constructor
7321 );
7322 };
7323
7324 /**
7325 * Check if the tool is active.
7326 *
7327 * Tools become active when their #onSelect or #onUpdateState handlers change them to appear pressed
7328 * with the #setActive method. Additional CSS is applied to the tool to reflect the active state.
7329 *
7330 * @return {boolean} Tool is active
7331 */
7332 OO.ui.Tool.prototype.isActive = function () {
7333 return this.active;
7334 };
7335
7336 /**
7337 * Make the tool appear active or inactive.
7338 *
7339 * This method should be called within #onSelect or #onUpdateState event handlers to make the tool
7340 * appear pressed or not.
7341 *
7342 * @param {boolean} state Make tool appear active
7343 */
7344 OO.ui.Tool.prototype.setActive = function ( state ) {
7345 this.active = !!state;
7346 if ( this.active ) {
7347 this.$element.addClass( 'oo-ui-tool-active' );
7348 } else {
7349 this.$element.removeClass( 'oo-ui-tool-active' );
7350 }
7351 };
7352
7353 /**
7354 * Set the tool #title.
7355 *
7356 * @param {string|Function} title Title text or a function that returns text
7357 * @chainable
7358 */
7359 OO.ui.Tool.prototype.setTitle = function ( title ) {
7360 this.title = OO.ui.resolveMsg( title );
7361 this.updateTitle();
7362 return this;
7363 };
7364
7365 /**
7366 * Get the tool #title.
7367 *
7368 * @return {string} Title text
7369 */
7370 OO.ui.Tool.prototype.getTitle = function () {
7371 return this.title;
7372 };
7373
7374 /**
7375 * Get the tool's symbolic name.
7376 *
7377 * @return {string} Symbolic name of tool
7378 */
7379 OO.ui.Tool.prototype.getName = function () {
7380 return this.constructor.static.name;
7381 };
7382
7383 /**
7384 * Update the title.
7385 */
7386 OO.ui.Tool.prototype.updateTitle = function () {
7387 var titleTooltips = this.toolGroup.constructor.static.titleTooltips,
7388 accelTooltips = this.toolGroup.constructor.static.accelTooltips,
7389 accel = this.toolbar.getToolAccelerator( this.constructor.static.name ),
7390 tooltipParts = [];
7391
7392 this.$title.text( this.title );
7393 this.$accel.text( accel );
7394
7395 if ( titleTooltips && typeof this.title === 'string' && this.title.length ) {
7396 tooltipParts.push( this.title );
7397 }
7398 if ( accelTooltips && typeof accel === 'string' && accel.length ) {
7399 tooltipParts.push( accel );
7400 }
7401 if ( tooltipParts.length ) {
7402 this.$link.attr( 'title', tooltipParts.join( ' ' ) );
7403 } else {
7404 this.$link.removeAttr( 'title' );
7405 }
7406 };
7407
7408 /**
7409 * Destroy tool.
7410 *
7411 * Destroying the tool removes all event handlers and the tool’s DOM elements.
7412 * Call this method whenever you are done using a tool.
7413 */
7414 OO.ui.Tool.prototype.destroy = function () {
7415 this.toolbar.disconnect( this );
7416 this.$element.remove();
7417 };
7418
7419 /**
7420 * Toolbars are complex interface components that permit users to easily access a variety
7421 * of {@link OO.ui.Tool tools} (e.g., formatting commands) and actions, which are additional commands that are
7422 * part of the toolbar, but not configured as tools.
7423 *
7424 * Individual tools are customized and then registered with a {@link OO.ui.ToolFactory tool factory}, which creates
7425 * the tools on demand. Each tool has a symbolic name (used when registering the tool), a title (e.g., ‘Insert
7426 * picture’), and an icon.
7427 *
7428 * Individual tools are organized in {@link OO.ui.ToolGroup toolgroups}, which can be {@link OO.ui.MenuToolGroup menus}
7429 * of tools, {@link OO.ui.ListToolGroup lists} of tools, or a single {@link OO.ui.BarToolGroup bar} of tools.
7430 * The arrangement and order of the toolgroups is customized when the toolbar is set up. Tools can be presented in
7431 * any order, but each can only appear once in the toolbar.
7432 *
7433 * The following is an example of a basic toolbar.
7434 *
7435 * @example
7436 * // Example of a toolbar
7437 * // Create the toolbar
7438 * var toolFactory = new OO.ui.ToolFactory();
7439 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
7440 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
7441 *
7442 * // We will be placing status text in this element when tools are used
7443 * var $area = $( '<p>' ).text( 'Toolbar example' );
7444 *
7445 * // Define the tools that we're going to place in our toolbar
7446 *
7447 * // Create a class inheriting from OO.ui.Tool
7448 * function PictureTool() {
7449 * PictureTool.parent.apply( this, arguments );
7450 * }
7451 * OO.inheritClass( PictureTool, OO.ui.Tool );
7452 * // Each tool must have a 'name' (used as an internal identifier, see later) and at least one
7453 * // of 'icon' and 'title' (displayed icon and text).
7454 * PictureTool.static.name = 'picture';
7455 * PictureTool.static.icon = 'picture';
7456 * PictureTool.static.title = 'Insert picture';
7457 * // Defines the action that will happen when this tool is selected (clicked).
7458 * PictureTool.prototype.onSelect = function () {
7459 * $area.text( 'Picture tool clicked!' );
7460 * // Never display this tool as "active" (selected).
7461 * this.setActive( false );
7462 * };
7463 * // Make this tool available in our toolFactory and thus our toolbar
7464 * toolFactory.register( PictureTool );
7465 *
7466 * // Register two more tools, nothing interesting here
7467 * function SettingsTool() {
7468 * SettingsTool.parent.apply( this, arguments );
7469 * }
7470 * OO.inheritClass( SettingsTool, OO.ui.Tool );
7471 * SettingsTool.static.name = 'settings';
7472 * SettingsTool.static.icon = 'settings';
7473 * SettingsTool.static.title = 'Change settings';
7474 * SettingsTool.prototype.onSelect = function () {
7475 * $area.text( 'Settings tool clicked!' );
7476 * this.setActive( false );
7477 * };
7478 * toolFactory.register( SettingsTool );
7479 *
7480 * // Register two more tools, nothing interesting here
7481 * function StuffTool() {
7482 * StuffTool.parent.apply( this, arguments );
7483 * }
7484 * OO.inheritClass( StuffTool, OO.ui.Tool );
7485 * StuffTool.static.name = 'stuff';
7486 * StuffTool.static.icon = 'ellipsis';
7487 * StuffTool.static.title = 'More stuff';
7488 * StuffTool.prototype.onSelect = function () {
7489 * $area.text( 'More stuff tool clicked!' );
7490 * this.setActive( false );
7491 * };
7492 * toolFactory.register( StuffTool );
7493 *
7494 * // This is a PopupTool. Rather than having a custom 'onSelect' action, it will display a
7495 * // little popup window (a PopupWidget).
7496 * function HelpTool( toolGroup, config ) {
7497 * OO.ui.PopupTool.call( this, toolGroup, $.extend( { popup: {
7498 * padded: true,
7499 * label: 'Help',
7500 * head: true
7501 * } }, config ) );
7502 * this.popup.$body.append( '<p>I am helpful!</p>' );
7503 * }
7504 * OO.inheritClass( HelpTool, OO.ui.PopupTool );
7505 * HelpTool.static.name = 'help';
7506 * HelpTool.static.icon = 'help';
7507 * HelpTool.static.title = 'Help';
7508 * toolFactory.register( HelpTool );
7509 *
7510 * // Finally define which tools and in what order appear in the toolbar. Each tool may only be
7511 * // used once (but not all defined tools must be used).
7512 * toolbar.setup( [
7513 * {
7514 * // 'bar' tool groups display tools' icons only, side-by-side.
7515 * type: 'bar',
7516 * include: [ 'picture', 'help' ]
7517 * },
7518 * {
7519 * // 'list' tool groups display both the titles and icons, in a dropdown list.
7520 * type: 'list',
7521 * indicator: 'down',
7522 * label: 'More',
7523 * include: [ 'settings', 'stuff' ]
7524 * }
7525 * // Note how the tools themselves are toolgroup-agnostic - the same tool can be displayed
7526 * // either in a 'list' or a 'bar'. There is a 'menu' tool group too, not showcased here,
7527 * // since it's more complicated to use. (See the next example snippet on this page.)
7528 * ] );
7529 *
7530 * // Create some UI around the toolbar and place it in the document
7531 * var frame = new OO.ui.PanelLayout( {
7532 * expanded: false,
7533 * framed: true
7534 * } );
7535 * var contentFrame = new OO.ui.PanelLayout( {
7536 * expanded: false,
7537 * padded: true
7538 * } );
7539 * frame.$element.append(
7540 * toolbar.$element,
7541 * contentFrame.$element.append( $area )
7542 * );
7543 * $( 'body' ).append( frame.$element );
7544 *
7545 * // Here is where the toolbar is actually built. This must be done after inserting it into the
7546 * // document.
7547 * toolbar.initialize();
7548 *
7549 * The following example extends the previous one to illustrate 'menu' toolgroups and the usage of
7550 * 'updateState' event.
7551 *
7552 * @example
7553 * // Create the toolbar
7554 * var toolFactory = new OO.ui.ToolFactory();
7555 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
7556 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
7557 *
7558 * // We will be placing status text in this element when tools are used
7559 * var $area = $( '<p>' ).text( 'Toolbar example' );
7560 *
7561 * // Define the tools that we're going to place in our toolbar
7562 *
7563 * // Create a class inheriting from OO.ui.Tool
7564 * function PictureTool() {
7565 * PictureTool.parent.apply( this, arguments );
7566 * }
7567 * OO.inheritClass( PictureTool, OO.ui.Tool );
7568 * // Each tool must have a 'name' (used as an internal identifier, see later) and at least one
7569 * // of 'icon' and 'title' (displayed icon and text).
7570 * PictureTool.static.name = 'picture';
7571 * PictureTool.static.icon = 'picture';
7572 * PictureTool.static.title = 'Insert picture';
7573 * // Defines the action that will happen when this tool is selected (clicked).
7574 * PictureTool.prototype.onSelect = function () {
7575 * $area.text( 'Picture tool clicked!' );
7576 * // Never display this tool as "active" (selected).
7577 * this.setActive( false );
7578 * };
7579 * // The toolbar can be synchronized with the state of some external stuff, like a text
7580 * // editor's editing area, highlighting the tools (e.g. a 'bold' tool would be shown as active
7581 * // when the text cursor was inside bolded text). Here we simply disable this feature.
7582 * PictureTool.prototype.onUpdateState = function () {
7583 * };
7584 * // Make this tool available in our toolFactory and thus our toolbar
7585 * toolFactory.register( PictureTool );
7586 *
7587 * // Register two more tools, nothing interesting here
7588 * function SettingsTool() {
7589 * SettingsTool.parent.apply( this, arguments );
7590 * this.reallyActive = false;
7591 * }
7592 * OO.inheritClass( SettingsTool, OO.ui.Tool );
7593 * SettingsTool.static.name = 'settings';
7594 * SettingsTool.static.icon = 'settings';
7595 * SettingsTool.static.title = 'Change settings';
7596 * SettingsTool.prototype.onSelect = function () {
7597 * $area.text( 'Settings tool clicked!' );
7598 * // Toggle the active state on each click
7599 * this.reallyActive = !this.reallyActive;
7600 * this.setActive( this.reallyActive );
7601 * // To update the menu label
7602 * this.toolbar.emit( 'updateState' );
7603 * };
7604 * SettingsTool.prototype.onUpdateState = function () {
7605 * };
7606 * toolFactory.register( SettingsTool );
7607 *
7608 * // Register two more tools, nothing interesting here
7609 * function StuffTool() {
7610 * StuffTool.parent.apply( this, arguments );
7611 * this.reallyActive = false;
7612 * }
7613 * OO.inheritClass( StuffTool, OO.ui.Tool );
7614 * StuffTool.static.name = 'stuff';
7615 * StuffTool.static.icon = 'ellipsis';
7616 * StuffTool.static.title = 'More stuff';
7617 * StuffTool.prototype.onSelect = function () {
7618 * $area.text( 'More stuff tool clicked!' );
7619 * // Toggle the active state on each click
7620 * this.reallyActive = !this.reallyActive;
7621 * this.setActive( this.reallyActive );
7622 * // To update the menu label
7623 * this.toolbar.emit( 'updateState' );
7624 * };
7625 * StuffTool.prototype.onUpdateState = function () {
7626 * };
7627 * toolFactory.register( StuffTool );
7628 *
7629 * // This is a PopupTool. Rather than having a custom 'onSelect' action, it will display a
7630 * // little popup window (a PopupWidget). 'onUpdateState' is also already implemented.
7631 * function HelpTool( toolGroup, config ) {
7632 * OO.ui.PopupTool.call( this, toolGroup, $.extend( { popup: {
7633 * padded: true,
7634 * label: 'Help',
7635 * head: true
7636 * } }, config ) );
7637 * this.popup.$body.append( '<p>I am helpful!</p>' );
7638 * }
7639 * OO.inheritClass( HelpTool, OO.ui.PopupTool );
7640 * HelpTool.static.name = 'help';
7641 * HelpTool.static.icon = 'help';
7642 * HelpTool.static.title = 'Help';
7643 * toolFactory.register( HelpTool );
7644 *
7645 * // Finally define which tools and in what order appear in the toolbar. Each tool may only be
7646 * // used once (but not all defined tools must be used).
7647 * toolbar.setup( [
7648 * {
7649 * // 'bar' tool groups display tools' icons only, side-by-side.
7650 * type: 'bar',
7651 * include: [ 'picture', 'help' ]
7652 * },
7653 * {
7654 * // 'menu' tool groups display both the titles and icons, in a dropdown menu.
7655 * // Menu label indicates which items are selected.
7656 * type: 'menu',
7657 * indicator: 'down',
7658 * include: [ 'settings', 'stuff' ]
7659 * }
7660 * ] );
7661 *
7662 * // Create some UI around the toolbar and place it in the document
7663 * var frame = new OO.ui.PanelLayout( {
7664 * expanded: false,
7665 * framed: true
7666 * } );
7667 * var contentFrame = new OO.ui.PanelLayout( {
7668 * expanded: false,
7669 * padded: true
7670 * } );
7671 * frame.$element.append(
7672 * toolbar.$element,
7673 * contentFrame.$element.append( $area )
7674 * );
7675 * $( 'body' ).append( frame.$element );
7676 *
7677 * // Here is where the toolbar is actually built. This must be done after inserting it into the
7678 * // document.
7679 * toolbar.initialize();
7680 * toolbar.emit( 'updateState' );
7681 *
7682 * @class
7683 * @extends OO.ui.Element
7684 * @mixins OO.EventEmitter
7685 * @mixins OO.ui.mixin.GroupElement
7686 *
7687 * @constructor
7688 * @param {OO.ui.ToolFactory} toolFactory Factory for creating tools
7689 * @param {OO.ui.ToolGroupFactory} toolGroupFactory Factory for creating toolgroups
7690 * @param {Object} [config] Configuration options
7691 * @cfg {boolean} [actions] Add an actions section to the toolbar. Actions are commands that are included
7692 * in the toolbar, but are not configured as tools. By default, actions are displayed on the right side of
7693 * the toolbar.
7694 * @cfg {boolean} [shadow] Add a shadow below the toolbar.
7695 */
7696 OO.ui.Toolbar = function OoUiToolbar( toolFactory, toolGroupFactory, config ) {
7697 // Allow passing positional parameters inside the config object
7698 if ( OO.isPlainObject( toolFactory ) && config === undefined ) {
7699 config = toolFactory;
7700 toolFactory = config.toolFactory;
7701 toolGroupFactory = config.toolGroupFactory;
7702 }
7703
7704 // Configuration initialization
7705 config = config || {};
7706
7707 // Parent constructor
7708 OO.ui.Toolbar.parent.call( this, config );
7709
7710 // Mixin constructors
7711 OO.EventEmitter.call( this );
7712 OO.ui.mixin.GroupElement.call( this, config );
7713
7714 // Properties
7715 this.toolFactory = toolFactory;
7716 this.toolGroupFactory = toolGroupFactory;
7717 this.groups = [];
7718 this.tools = {};
7719 this.$bar = $( '<div>' );
7720 this.$actions = $( '<div>' );
7721 this.initialized = false;
7722 this.onWindowResizeHandler = this.onWindowResize.bind( this );
7723
7724 // Events
7725 this.$element
7726 .add( this.$bar ).add( this.$group ).add( this.$actions )
7727 .on( 'mousedown keydown', this.onPointerDown.bind( this ) );
7728
7729 // Initialization
7730 this.$group.addClass( 'oo-ui-toolbar-tools' );
7731 if ( config.actions ) {
7732 this.$bar.append( this.$actions.addClass( 'oo-ui-toolbar-actions' ) );
7733 }
7734 this.$bar
7735 .addClass( 'oo-ui-toolbar-bar' )
7736 .append( this.$group, '<div style="clear:both"></div>' );
7737 if ( config.shadow ) {
7738 this.$bar.append( '<div class="oo-ui-toolbar-shadow"></div>' );
7739 }
7740 this.$element.addClass( 'oo-ui-toolbar' ).append( this.$bar );
7741 };
7742
7743 /* Setup */
7744
7745 OO.inheritClass( OO.ui.Toolbar, OO.ui.Element );
7746 OO.mixinClass( OO.ui.Toolbar, OO.EventEmitter );
7747 OO.mixinClass( OO.ui.Toolbar, OO.ui.mixin.GroupElement );
7748
7749 /* Methods */
7750
7751 /**
7752 * Get the tool factory.
7753 *
7754 * @return {OO.ui.ToolFactory} Tool factory
7755 */
7756 OO.ui.Toolbar.prototype.getToolFactory = function () {
7757 return this.toolFactory;
7758 };
7759
7760 /**
7761 * Get the toolgroup factory.
7762 *
7763 * @return {OO.Factory} Toolgroup factory
7764 */
7765 OO.ui.Toolbar.prototype.getToolGroupFactory = function () {
7766 return this.toolGroupFactory;
7767 };
7768
7769 /**
7770 * Handles mouse down events.
7771 *
7772 * @private
7773 * @param {jQuery.Event} e Mouse down event
7774 */
7775 OO.ui.Toolbar.prototype.onPointerDown = function ( e ) {
7776 var $closestWidgetToEvent = $( e.target ).closest( '.oo-ui-widget' ),
7777 $closestWidgetToToolbar = this.$element.closest( '.oo-ui-widget' );
7778 if ( !$closestWidgetToEvent.length || $closestWidgetToEvent[ 0 ] === $closestWidgetToToolbar[ 0 ] ) {
7779 return false;
7780 }
7781 };
7782
7783 /**
7784 * Handle window resize event.
7785 *
7786 * @private
7787 * @param {jQuery.Event} e Window resize event
7788 */
7789 OO.ui.Toolbar.prototype.onWindowResize = function () {
7790 this.$element.toggleClass(
7791 'oo-ui-toolbar-narrow',
7792 this.$bar.width() <= this.narrowThreshold
7793 );
7794 };
7795
7796 /**
7797 * Sets up handles and preloads required information for the toolbar to work.
7798 * This must be called after it is attached to a visible document and before doing anything else.
7799 */
7800 OO.ui.Toolbar.prototype.initialize = function () {
7801 if ( !this.initialized ) {
7802 this.initialized = true;
7803 this.narrowThreshold = this.$group.width() + this.$actions.width();
7804 $( this.getElementWindow() ).on( 'resize', this.onWindowResizeHandler );
7805 this.onWindowResize();
7806 }
7807 };
7808
7809 /**
7810 * Set up the toolbar.
7811 *
7812 * The toolbar is set up with a list of toolgroup configurations that specify the type of
7813 * toolgroup ({@link OO.ui.BarToolGroup bar}, {@link OO.ui.MenuToolGroup menu}, or {@link OO.ui.ListToolGroup list})
7814 * to add and which tools to include, exclude, promote, or demote within that toolgroup. Please
7815 * see {@link OO.ui.ToolGroup toolgroups} for more information about including tools in toolgroups.
7816 *
7817 * @param {Object.<string,Array>} groups List of toolgroup configurations
7818 * @param {Array|string} [groups.include] Tools to include in the toolgroup
7819 * @param {Array|string} [groups.exclude] Tools to exclude from the toolgroup
7820 * @param {Array|string} [groups.promote] Tools to promote to the beginning of the toolgroup
7821 * @param {Array|string} [groups.demote] Tools to demote to the end of the toolgroup
7822 */
7823 OO.ui.Toolbar.prototype.setup = function ( groups ) {
7824 var i, len, type, group,
7825 items = [],
7826 defaultType = 'bar';
7827
7828 // Cleanup previous groups
7829 this.reset();
7830
7831 // Build out new groups
7832 for ( i = 0, len = groups.length; i < len; i++ ) {
7833 group = groups[ i ];
7834 if ( group.include === '*' ) {
7835 // Apply defaults to catch-all groups
7836 if ( group.type === undefined ) {
7837 group.type = 'list';
7838 }
7839 if ( group.label === undefined ) {
7840 group.label = OO.ui.msg( 'ooui-toolbar-more' );
7841 }
7842 }
7843 // Check type has been registered
7844 type = this.getToolGroupFactory().lookup( group.type ) ? group.type : defaultType;
7845 items.push(
7846 this.getToolGroupFactory().create( type, this, group )
7847 );
7848 }
7849 this.addItems( items );
7850 };
7851
7852 /**
7853 * Remove all tools and toolgroups from the toolbar.
7854 */
7855 OO.ui.Toolbar.prototype.reset = function () {
7856 var i, len;
7857
7858 this.groups = [];
7859 this.tools = {};
7860 for ( i = 0, len = this.items.length; i < len; i++ ) {
7861 this.items[ i ].destroy();
7862 }
7863 this.clearItems();
7864 };
7865
7866 /**
7867 * Destroy the toolbar.
7868 *
7869 * Destroying the toolbar removes all event handlers and DOM elements that constitute the toolbar. Call
7870 * this method whenever you are done using a toolbar.
7871 */
7872 OO.ui.Toolbar.prototype.destroy = function () {
7873 $( this.getElementWindow() ).off( 'resize', this.onWindowResizeHandler );
7874 this.reset();
7875 this.$element.remove();
7876 };
7877
7878 /**
7879 * Check if the tool is available.
7880 *
7881 * Available tools are ones that have not yet been added to the toolbar.
7882 *
7883 * @param {string} name Symbolic name of tool
7884 * @return {boolean} Tool is available
7885 */
7886 OO.ui.Toolbar.prototype.isToolAvailable = function ( name ) {
7887 return !this.tools[ name ];
7888 };
7889
7890 /**
7891 * Prevent tool from being used again.
7892 *
7893 * @param {OO.ui.Tool} tool Tool to reserve
7894 */
7895 OO.ui.Toolbar.prototype.reserveTool = function ( tool ) {
7896 this.tools[ tool.getName() ] = tool;
7897 };
7898
7899 /**
7900 * Allow tool to be used again.
7901 *
7902 * @param {OO.ui.Tool} tool Tool to release
7903 */
7904 OO.ui.Toolbar.prototype.releaseTool = function ( tool ) {
7905 delete this.tools[ tool.getName() ];
7906 };
7907
7908 /**
7909 * Get accelerator label for tool.
7910 *
7911 * The OOjs UI library does not contain an accelerator system, but this is the hook for one. To
7912 * use an accelerator system, subclass the toolbar and override this method, which is meant to return a label
7913 * that describes the accelerator keys for the tool passed (by symbolic name) to the method.
7914 *
7915 * @param {string} name Symbolic name of tool
7916 * @return {string|undefined} Tool accelerator label if available
7917 */
7918 OO.ui.Toolbar.prototype.getToolAccelerator = function () {
7919 return undefined;
7920 };
7921
7922 /**
7923 * ToolGroups are collections of {@link OO.ui.Tool tools} that are used in a {@link OO.ui.Toolbar toolbar}.
7924 * The type of toolgroup ({@link OO.ui.ListToolGroup list}, {@link OO.ui.BarToolGroup bar}, or {@link OO.ui.MenuToolGroup menu})
7925 * to which a tool belongs determines how the tool is arranged and displayed in the toolbar. Toolgroups
7926 * themselves are created on demand with a {@link OO.ui.ToolGroupFactory toolgroup factory}.
7927 *
7928 * Toolgroups can contain individual tools, groups of tools, or all available tools:
7929 *
7930 * To include an individual tool (or array of individual tools), specify tools by symbolic name:
7931 *
7932 * include: [ 'tool-name' ] or [ { name: 'tool-name' }]
7933 *
7934 * 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.)
7935 *
7936 * include: [ { group: 'group-name' } ]
7937 *
7938 * To include all tools that are not yet assigned to a toolgroup, use the catch-all selector, an asterisk (*):
7939 *
7940 * include: '*'
7941 *
7942 * See {@link OO.ui.Toolbar toolbars} for a full example. For more information about toolbars in general,
7943 * please see the [OOjs UI documentation on MediaWiki][1].
7944 *
7945 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
7946 *
7947 * @abstract
7948 * @class
7949 * @extends OO.ui.Widget
7950 * @mixins OO.ui.mixin.GroupElement
7951 *
7952 * @constructor
7953 * @param {OO.ui.Toolbar} toolbar
7954 * @param {Object} [config] Configuration options
7955 * @cfg {Array|string} [include=[]] List of tools to include in the toolgroup.
7956 * @cfg {Array|string} [exclude=[]] List of tools to exclude from the toolgroup.
7957 * @cfg {Array|string} [promote=[]] List of tools to promote to the beginning of the toolgroup.
7958 * @cfg {Array|string} [demote=[]] List of tools to demote to the end of the toolgroup.
7959 * This setting is particularly useful when tools have been added to the toolgroup
7960 * en masse (e.g., via the catch-all selector).
7961 */
7962 OO.ui.ToolGroup = function OoUiToolGroup( toolbar, config ) {
7963 // Allow passing positional parameters inside the config object
7964 if ( OO.isPlainObject( toolbar ) && config === undefined ) {
7965 config = toolbar;
7966 toolbar = config.toolbar;
7967 }
7968
7969 // Configuration initialization
7970 config = config || {};
7971
7972 // Parent constructor
7973 OO.ui.ToolGroup.parent.call( this, config );
7974
7975 // Mixin constructors
7976 OO.ui.mixin.GroupElement.call( this, config );
7977
7978 // Properties
7979 this.toolbar = toolbar;
7980 this.tools = {};
7981 this.pressed = null;
7982 this.autoDisabled = false;
7983 this.include = config.include || [];
7984 this.exclude = config.exclude || [];
7985 this.promote = config.promote || [];
7986 this.demote = config.demote || [];
7987 this.onCapturedMouseKeyUpHandler = this.onCapturedMouseKeyUp.bind( this );
7988
7989 // Events
7990 this.$element.on( {
7991 mousedown: this.onMouseKeyDown.bind( this ),
7992 mouseup: this.onMouseKeyUp.bind( this ),
7993 keydown: this.onMouseKeyDown.bind( this ),
7994 keyup: this.onMouseKeyUp.bind( this ),
7995 focus: this.onMouseOverFocus.bind( this ),
7996 blur: this.onMouseOutBlur.bind( this ),
7997 mouseover: this.onMouseOverFocus.bind( this ),
7998 mouseout: this.onMouseOutBlur.bind( this )
7999 } );
8000 this.toolbar.getToolFactory().connect( this, { register: 'onToolFactoryRegister' } );
8001 this.aggregate( { disable: 'itemDisable' } );
8002 this.connect( this, { itemDisable: 'updateDisabled' } );
8003
8004 // Initialization
8005 this.$group.addClass( 'oo-ui-toolGroup-tools' );
8006 this.$element
8007 .addClass( 'oo-ui-toolGroup' )
8008 .append( this.$group );
8009 this.populate();
8010 };
8011
8012 /* Setup */
8013
8014 OO.inheritClass( OO.ui.ToolGroup, OO.ui.Widget );
8015 OO.mixinClass( OO.ui.ToolGroup, OO.ui.mixin.GroupElement );
8016
8017 /* Events */
8018
8019 /**
8020 * @event update
8021 */
8022
8023 /* Static Properties */
8024
8025 /**
8026 * Show labels in tooltips.
8027 *
8028 * @static
8029 * @inheritable
8030 * @property {boolean}
8031 */
8032 OO.ui.ToolGroup.static.titleTooltips = false;
8033
8034 /**
8035 * Show acceleration labels in tooltips.
8036 *
8037 * Note: The OOjs UI library does not include an accelerator system, but does contain
8038 * a hook for one. To use an accelerator system, subclass the {@link OO.ui.Toolbar toolbar} and
8039 * override the {@link OO.ui.Toolbar#getToolAccelerator getToolAccelerator} method, which is
8040 * meant to return a label that describes the accelerator keys for a given tool (e.g., 'Ctrl + M').
8041 *
8042 * @static
8043 * @inheritable
8044 * @property {boolean}
8045 */
8046 OO.ui.ToolGroup.static.accelTooltips = false;
8047
8048 /**
8049 * Automatically disable the toolgroup when all tools are disabled
8050 *
8051 * @static
8052 * @inheritable
8053 * @property {boolean}
8054 */
8055 OO.ui.ToolGroup.static.autoDisable = true;
8056
8057 /* Methods */
8058
8059 /**
8060 * @inheritdoc
8061 */
8062 OO.ui.ToolGroup.prototype.isDisabled = function () {
8063 return this.autoDisabled || OO.ui.ToolGroup.parent.prototype.isDisabled.apply( this, arguments );
8064 };
8065
8066 /**
8067 * @inheritdoc
8068 */
8069 OO.ui.ToolGroup.prototype.updateDisabled = function () {
8070 var i, item, allDisabled = true;
8071
8072 if ( this.constructor.static.autoDisable ) {
8073 for ( i = this.items.length - 1; i >= 0; i-- ) {
8074 item = this.items[ i ];
8075 if ( !item.isDisabled() ) {
8076 allDisabled = false;
8077 break;
8078 }
8079 }
8080 this.autoDisabled = allDisabled;
8081 }
8082 OO.ui.ToolGroup.parent.prototype.updateDisabled.apply( this, arguments );
8083 };
8084
8085 /**
8086 * Handle mouse down and key down events.
8087 *
8088 * @protected
8089 * @param {jQuery.Event} e Mouse down or key down event
8090 */
8091 OO.ui.ToolGroup.prototype.onMouseKeyDown = function ( e ) {
8092 if (
8093 !this.isDisabled() &&
8094 ( e.which === 1 || e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
8095 ) {
8096 this.pressed = this.getTargetTool( e );
8097 if ( this.pressed ) {
8098 this.pressed.setActive( true );
8099 OO.ui.addCaptureEventListener( this.getElementDocument(), 'mouseup', this.onCapturedMouseKeyUpHandler );
8100 OO.ui.addCaptureEventListener( this.getElementDocument(), 'keyup', this.onCapturedMouseKeyUpHandler );
8101 }
8102 return false;
8103 }
8104 };
8105
8106 /**
8107 * Handle captured mouse up and key up events.
8108 *
8109 * @protected
8110 * @param {Event} e Mouse up or key up event
8111 */
8112 OO.ui.ToolGroup.prototype.onCapturedMouseKeyUp = function ( e ) {
8113 OO.ui.removeCaptureEventListener( this.getElementDocument(), 'mouseup', this.onCapturedMouseKeyUpHandler );
8114 OO.ui.removeCaptureEventListener( this.getElementDocument(), 'keyup', this.onCapturedMouseKeyUpHandler );
8115 // onMouseKeyUp may be called a second time, depending on where the mouse is when the button is
8116 // released, but since `this.pressed` will no longer be true, the second call will be ignored.
8117 this.onMouseKeyUp( e );
8118 };
8119
8120 /**
8121 * Handle mouse up and key up events.
8122 *
8123 * @protected
8124 * @param {jQuery.Event} e Mouse up or key up event
8125 */
8126 OO.ui.ToolGroup.prototype.onMouseKeyUp = function ( e ) {
8127 var tool = this.getTargetTool( e );
8128
8129 if (
8130 !this.isDisabled() && this.pressed && this.pressed === tool &&
8131 ( e.which === 1 || e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
8132 ) {
8133 this.pressed.onSelect();
8134 this.pressed = null;
8135 return false;
8136 }
8137
8138 this.pressed = null;
8139 };
8140
8141 /**
8142 * Handle mouse over and focus events.
8143 *
8144 * @protected
8145 * @param {jQuery.Event} e Mouse over or focus event
8146 */
8147 OO.ui.ToolGroup.prototype.onMouseOverFocus = function ( e ) {
8148 var tool = this.getTargetTool( e );
8149
8150 if ( this.pressed && this.pressed === tool ) {
8151 this.pressed.setActive( true );
8152 }
8153 };
8154
8155 /**
8156 * Handle mouse out and blur events.
8157 *
8158 * @protected
8159 * @param {jQuery.Event} e Mouse out or blur event
8160 */
8161 OO.ui.ToolGroup.prototype.onMouseOutBlur = function ( e ) {
8162 var tool = this.getTargetTool( e );
8163
8164 if ( this.pressed && this.pressed === tool ) {
8165 this.pressed.setActive( false );
8166 }
8167 };
8168
8169 /**
8170 * Get the closest tool to a jQuery.Event.
8171 *
8172 * Only tool links are considered, which prevents other elements in the tool such as popups from
8173 * triggering tool group interactions.
8174 *
8175 * @private
8176 * @param {jQuery.Event} e
8177 * @return {OO.ui.Tool|null} Tool, `null` if none was found
8178 */
8179 OO.ui.ToolGroup.prototype.getTargetTool = function ( e ) {
8180 var tool,
8181 $item = $( e.target ).closest( '.oo-ui-tool-link' );
8182
8183 if ( $item.length ) {
8184 tool = $item.parent().data( 'oo-ui-tool' );
8185 }
8186
8187 return tool && !tool.isDisabled() ? tool : null;
8188 };
8189
8190 /**
8191 * Handle tool registry register events.
8192 *
8193 * If a tool is registered after the group is created, we must repopulate the list to account for:
8194 *
8195 * - a tool being added that may be included
8196 * - a tool already included being overridden
8197 *
8198 * @protected
8199 * @param {string} name Symbolic name of tool
8200 */
8201 OO.ui.ToolGroup.prototype.onToolFactoryRegister = function () {
8202 this.populate();
8203 };
8204
8205 /**
8206 * Get the toolbar that contains the toolgroup.
8207 *
8208 * @return {OO.ui.Toolbar} Toolbar that contains the toolgroup
8209 */
8210 OO.ui.ToolGroup.prototype.getToolbar = function () {
8211 return this.toolbar;
8212 };
8213
8214 /**
8215 * Add and remove tools based on configuration.
8216 */
8217 OO.ui.ToolGroup.prototype.populate = function () {
8218 var i, len, name, tool,
8219 toolFactory = this.toolbar.getToolFactory(),
8220 names = {},
8221 add = [],
8222 remove = [],
8223 list = this.toolbar.getToolFactory().getTools(
8224 this.include, this.exclude, this.promote, this.demote
8225 );
8226
8227 // Build a list of needed tools
8228 for ( i = 0, len = list.length; i < len; i++ ) {
8229 name = list[ i ];
8230 if (
8231 // Tool exists
8232 toolFactory.lookup( name ) &&
8233 // Tool is available or is already in this group
8234 ( this.toolbar.isToolAvailable( name ) || this.tools[ name ] )
8235 ) {
8236 // Hack to prevent infinite recursion via ToolGroupTool. We need to reserve the tool before
8237 // creating it, but we can't call reserveTool() yet because we haven't created the tool.
8238 this.toolbar.tools[ name ] = true;
8239 tool = this.tools[ name ];
8240 if ( !tool ) {
8241 // Auto-initialize tools on first use
8242 this.tools[ name ] = tool = toolFactory.create( name, this );
8243 tool.updateTitle();
8244 }
8245 this.toolbar.reserveTool( tool );
8246 add.push( tool );
8247 names[ name ] = true;
8248 }
8249 }
8250 // Remove tools that are no longer needed
8251 for ( name in this.tools ) {
8252 if ( !names[ name ] ) {
8253 this.tools[ name ].destroy();
8254 this.toolbar.releaseTool( this.tools[ name ] );
8255 remove.push( this.tools[ name ] );
8256 delete this.tools[ name ];
8257 }
8258 }
8259 if ( remove.length ) {
8260 this.removeItems( remove );
8261 }
8262 // Update emptiness state
8263 if ( add.length ) {
8264 this.$element.removeClass( 'oo-ui-toolGroup-empty' );
8265 } else {
8266 this.$element.addClass( 'oo-ui-toolGroup-empty' );
8267 }
8268 // Re-add tools (moving existing ones to new locations)
8269 this.addItems( add );
8270 // Disabled state may depend on items
8271 this.updateDisabled();
8272 };
8273
8274 /**
8275 * Destroy toolgroup.
8276 */
8277 OO.ui.ToolGroup.prototype.destroy = function () {
8278 var name;
8279
8280 this.clearItems();
8281 this.toolbar.getToolFactory().disconnect( this );
8282 for ( name in this.tools ) {
8283 this.toolbar.releaseTool( this.tools[ name ] );
8284 this.tools[ name ].disconnect( this ).destroy();
8285 delete this.tools[ name ];
8286 }
8287 this.$element.remove();
8288 };
8289
8290 /**
8291 * MessageDialogs display a confirmation or alert message. By default, the rendered dialog box
8292 * consists of a header that contains the dialog title, a body with the message, and a footer that
8293 * contains any {@link OO.ui.ActionWidget action widgets}. The MessageDialog class is the only type
8294 * of {@link OO.ui.Dialog dialog} that is usually instantiated directly.
8295 *
8296 * There are two basic types of message dialogs, confirmation and alert:
8297 *
8298 * - **confirmation**: the dialog title describes what a progressive action will do and the message provides
8299 * more details about the consequences.
8300 * - **alert**: the dialog title describes which event occurred and the message provides more information
8301 * about why the event occurred.
8302 *
8303 * The MessageDialog class specifies two actions: ‘accept’, the primary
8304 * action (e.g., ‘ok’) and ‘reject,’ the safe action (e.g., ‘cancel’). Both will close the window,
8305 * passing along the selected action.
8306 *
8307 * For more information and examples, please see the [OOjs UI documentation on MediaWiki][1].
8308 *
8309 * @example
8310 * // Example: Creating and opening a message dialog window.
8311 * var messageDialog = new OO.ui.MessageDialog();
8312 *
8313 * // Create and append a window manager.
8314 * var windowManager = new OO.ui.WindowManager();
8315 * $( 'body' ).append( windowManager.$element );
8316 * windowManager.addWindows( [ messageDialog ] );
8317 * // Open the window.
8318 * windowManager.openWindow( messageDialog, {
8319 * title: 'Basic message dialog',
8320 * message: 'This is the message'
8321 * } );
8322 *
8323 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Message_Dialogs
8324 *
8325 * @class
8326 * @extends OO.ui.Dialog
8327 *
8328 * @constructor
8329 * @param {Object} [config] Configuration options
8330 */
8331 OO.ui.MessageDialog = function OoUiMessageDialog( config ) {
8332 // Parent constructor
8333 OO.ui.MessageDialog.parent.call( this, config );
8334
8335 // Properties
8336 this.verticalActionLayout = null;
8337
8338 // Initialization
8339 this.$element.addClass( 'oo-ui-messageDialog' );
8340 };
8341
8342 /* Setup */
8343
8344 OO.inheritClass( OO.ui.MessageDialog, OO.ui.Dialog );
8345
8346 /* Static Properties */
8347
8348 OO.ui.MessageDialog.static.name = 'message';
8349
8350 OO.ui.MessageDialog.static.size = 'small';
8351
8352 OO.ui.MessageDialog.static.verbose = false;
8353
8354 /**
8355 * Dialog title.
8356 *
8357 * The title of a confirmation dialog describes what a progressive action will do. The
8358 * title of an alert dialog describes which event occurred.
8359 *
8360 * @static
8361 * @inheritable
8362 * @property {jQuery|string|Function|null}
8363 */
8364 OO.ui.MessageDialog.static.title = null;
8365
8366 /**
8367 * The message displayed in the dialog body.
8368 *
8369 * A confirmation message describes the consequences of a progressive action. An alert
8370 * message describes why an event occurred.
8371 *
8372 * @static
8373 * @inheritable
8374 * @property {jQuery|string|Function|null}
8375 */
8376 OO.ui.MessageDialog.static.message = null;
8377
8378 OO.ui.MessageDialog.static.actions = [
8379 { action: 'accept', label: OO.ui.deferMsg( 'ooui-dialog-message-accept' ), flags: 'primary' },
8380 { action: 'reject', label: OO.ui.deferMsg( 'ooui-dialog-message-reject' ), flags: 'safe' }
8381 ];
8382
8383 /* Methods */
8384
8385 /**
8386 * @inheritdoc
8387 */
8388 OO.ui.MessageDialog.prototype.setManager = function ( manager ) {
8389 OO.ui.MessageDialog.parent.prototype.setManager.call( this, manager );
8390
8391 // Events
8392 this.manager.connect( this, {
8393 resize: 'onResize'
8394 } );
8395
8396 return this;
8397 };
8398
8399 /**
8400 * @inheritdoc
8401 */
8402 OO.ui.MessageDialog.prototype.onActionResize = function ( action ) {
8403 this.fitActions();
8404 return OO.ui.MessageDialog.parent.prototype.onActionResize.call( this, action );
8405 };
8406
8407 /**
8408 * Handle window resized events.
8409 *
8410 * @private
8411 */
8412 OO.ui.MessageDialog.prototype.onResize = function () {
8413 var dialog = this;
8414 dialog.fitActions();
8415 // Wait for CSS transition to finish and do it again :(
8416 setTimeout( function () {
8417 dialog.fitActions();
8418 }, 300 );
8419 };
8420
8421 /**
8422 * Toggle action layout between vertical and horizontal.
8423 *
8424 * @private
8425 * @param {boolean} [value] Layout actions vertically, omit to toggle
8426 * @chainable
8427 */
8428 OO.ui.MessageDialog.prototype.toggleVerticalActionLayout = function ( value ) {
8429 value = value === undefined ? !this.verticalActionLayout : !!value;
8430
8431 if ( value !== this.verticalActionLayout ) {
8432 this.verticalActionLayout = value;
8433 this.$actions
8434 .toggleClass( 'oo-ui-messageDialog-actions-vertical', value )
8435 .toggleClass( 'oo-ui-messageDialog-actions-horizontal', !value );
8436 }
8437
8438 return this;
8439 };
8440
8441 /**
8442 * @inheritdoc
8443 */
8444 OO.ui.MessageDialog.prototype.getActionProcess = function ( action ) {
8445 if ( action ) {
8446 return new OO.ui.Process( function () {
8447 this.close( { action: action } );
8448 }, this );
8449 }
8450 return OO.ui.MessageDialog.parent.prototype.getActionProcess.call( this, action );
8451 };
8452
8453 /**
8454 * @inheritdoc
8455 *
8456 * @param {Object} [data] Dialog opening data
8457 * @param {jQuery|string|Function|null} [data.title] Description of the action being confirmed
8458 * @param {jQuery|string|Function|null} [data.message] Description of the action's consequence
8459 * @param {boolean} [data.verbose] Message is verbose and should be styled as a long message
8460 * @param {Object[]} [data.actions] List of OO.ui.ActionOptionWidget configuration options for each
8461 * action item
8462 */
8463 OO.ui.MessageDialog.prototype.getSetupProcess = function ( data ) {
8464 data = data || {};
8465
8466 // Parent method
8467 return OO.ui.MessageDialog.parent.prototype.getSetupProcess.call( this, data )
8468 .next( function () {
8469 this.title.setLabel(
8470 data.title !== undefined ? data.title : this.constructor.static.title
8471 );
8472 this.message.setLabel(
8473 data.message !== undefined ? data.message : this.constructor.static.message
8474 );
8475 this.message.$element.toggleClass(
8476 'oo-ui-messageDialog-message-verbose',
8477 data.verbose !== undefined ? data.verbose : this.constructor.static.verbose
8478 );
8479 }, this );
8480 };
8481
8482 /**
8483 * @inheritdoc
8484 */
8485 OO.ui.MessageDialog.prototype.getReadyProcess = function ( data ) {
8486 data = data || {};
8487
8488 // Parent method
8489 return OO.ui.MessageDialog.parent.prototype.getReadyProcess.call( this, data )
8490 .next( function () {
8491 // Focus the primary action button
8492 var actions = this.actions.get();
8493 actions = actions.filter( function ( action ) {
8494 return action.getFlags().indexOf( 'primary' ) > -1;
8495 } );
8496 if ( actions.length > 0 ) {
8497 actions[ 0 ].$button.focus();
8498 }
8499 }, this );
8500 };
8501
8502 /**
8503 * @inheritdoc
8504 */
8505 OO.ui.MessageDialog.prototype.getBodyHeight = function () {
8506 var bodyHeight, oldOverflow,
8507 $scrollable = this.container.$element;
8508
8509 oldOverflow = $scrollable[ 0 ].style.overflow;
8510 $scrollable[ 0 ].style.overflow = 'hidden';
8511
8512 OO.ui.Element.static.reconsiderScrollbars( $scrollable[ 0 ] );
8513
8514 bodyHeight = this.text.$element.outerHeight( true );
8515 $scrollable[ 0 ].style.overflow = oldOverflow;
8516
8517 return bodyHeight;
8518 };
8519
8520 /**
8521 * @inheritdoc
8522 */
8523 OO.ui.MessageDialog.prototype.setDimensions = function ( dim ) {
8524 var $scrollable = this.container.$element;
8525 OO.ui.MessageDialog.parent.prototype.setDimensions.call( this, dim );
8526
8527 // Twiddle the overflow property, otherwise an unnecessary scrollbar will be produced.
8528 // Need to do it after transition completes (250ms), add 50ms just in case.
8529 setTimeout( function () {
8530 var oldOverflow = $scrollable[ 0 ].style.overflow;
8531 $scrollable[ 0 ].style.overflow = 'hidden';
8532
8533 OO.ui.Element.static.reconsiderScrollbars( $scrollable[ 0 ] );
8534
8535 $scrollable[ 0 ].style.overflow = oldOverflow;
8536 }, 300 );
8537
8538 return this;
8539 };
8540
8541 /**
8542 * @inheritdoc
8543 */
8544 OO.ui.MessageDialog.prototype.initialize = function () {
8545 // Parent method
8546 OO.ui.MessageDialog.parent.prototype.initialize.call( this );
8547
8548 // Properties
8549 this.$actions = $( '<div>' );
8550 this.container = new OO.ui.PanelLayout( {
8551 scrollable: true, classes: [ 'oo-ui-messageDialog-container' ]
8552 } );
8553 this.text = new OO.ui.PanelLayout( {
8554 padded: true, expanded: false, classes: [ 'oo-ui-messageDialog-text' ]
8555 } );
8556 this.message = new OO.ui.LabelWidget( {
8557 classes: [ 'oo-ui-messageDialog-message' ]
8558 } );
8559
8560 // Initialization
8561 this.title.$element.addClass( 'oo-ui-messageDialog-title' );
8562 this.$content.addClass( 'oo-ui-messageDialog-content' );
8563 this.container.$element.append( this.text.$element );
8564 this.text.$element.append( this.title.$element, this.message.$element );
8565 this.$body.append( this.container.$element );
8566 this.$actions.addClass( 'oo-ui-messageDialog-actions' );
8567 this.$foot.append( this.$actions );
8568 };
8569
8570 /**
8571 * @inheritdoc
8572 */
8573 OO.ui.MessageDialog.prototype.attachActions = function () {
8574 var i, len, other, special, others;
8575
8576 // Parent method
8577 OO.ui.MessageDialog.parent.prototype.attachActions.call( this );
8578
8579 special = this.actions.getSpecial();
8580 others = this.actions.getOthers();
8581
8582 if ( special.safe ) {
8583 this.$actions.append( special.safe.$element );
8584 special.safe.toggleFramed( false );
8585 }
8586 if ( others.length ) {
8587 for ( i = 0, len = others.length; i < len; i++ ) {
8588 other = others[ i ];
8589 this.$actions.append( other.$element );
8590 other.toggleFramed( false );
8591 }
8592 }
8593 if ( special.primary ) {
8594 this.$actions.append( special.primary.$element );
8595 special.primary.toggleFramed( false );
8596 }
8597
8598 if ( !this.isOpening() ) {
8599 // If the dialog is currently opening, this will be called automatically soon.
8600 // This also calls #fitActions.
8601 this.updateSize();
8602 }
8603 };
8604
8605 /**
8606 * Fit action actions into columns or rows.
8607 *
8608 * Columns will be used if all labels can fit without overflow, otherwise rows will be used.
8609 *
8610 * @private
8611 */
8612 OO.ui.MessageDialog.prototype.fitActions = function () {
8613 var i, len, action,
8614 previous = this.verticalActionLayout,
8615 actions = this.actions.get();
8616
8617 // Detect clipping
8618 this.toggleVerticalActionLayout( false );
8619 for ( i = 0, len = actions.length; i < len; i++ ) {
8620 action = actions[ i ];
8621 if ( action.$element.innerWidth() < action.$label.outerWidth( true ) ) {
8622 this.toggleVerticalActionLayout( true );
8623 break;
8624 }
8625 }
8626
8627 // Move the body out of the way of the foot
8628 this.$body.css( 'bottom', this.$foot.outerHeight( true ) );
8629
8630 if ( this.verticalActionLayout !== previous ) {
8631 // We changed the layout, window height might need to be updated.
8632 this.updateSize();
8633 }
8634 };
8635
8636 /**
8637 * ProcessDialog windows encapsulate a {@link OO.ui.Process process} and all of the code necessary
8638 * to complete it. If the process terminates with an error, a customizable {@link OO.ui.Error error
8639 * interface} alerts users to the trouble, permitting the user to dismiss the error and try again when
8640 * relevant. The ProcessDialog class is always extended and customized with the actions and content
8641 * required for each process.
8642 *
8643 * The process dialog box consists of a header that visually represents the ‘working’ state of long
8644 * processes with an animation. The header contains the dialog title as well as
8645 * two {@link OO.ui.ActionWidget action widgets}: a ‘safe’ action on the left (e.g., ‘Cancel’) and
8646 * a ‘primary’ action on the right (e.g., ‘Done’).
8647 *
8648 * Like other windows, the process dialog is managed by a {@link OO.ui.WindowManager window manager}.
8649 * Please see the [OOjs UI documentation on MediaWiki][1] for more information and examples.
8650 *
8651 * @example
8652 * // Example: Creating and opening a process dialog window.
8653 * function MyProcessDialog( config ) {
8654 * MyProcessDialog.parent.call( this, config );
8655 * }
8656 * OO.inheritClass( MyProcessDialog, OO.ui.ProcessDialog );
8657 *
8658 * MyProcessDialog.static.title = 'Process dialog';
8659 * MyProcessDialog.static.actions = [
8660 * { action: 'save', label: 'Done', flags: 'primary' },
8661 * { label: 'Cancel', flags: 'safe' }
8662 * ];
8663 *
8664 * MyProcessDialog.prototype.initialize = function () {
8665 * MyProcessDialog.parent.prototype.initialize.apply( this, arguments );
8666 * this.content = new OO.ui.PanelLayout( { padded: true, expanded: false } );
8667 * 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>' );
8668 * this.$body.append( this.content.$element );
8669 * };
8670 * MyProcessDialog.prototype.getActionProcess = function ( action ) {
8671 * var dialog = this;
8672 * if ( action ) {
8673 * return new OO.ui.Process( function () {
8674 * dialog.close( { action: action } );
8675 * } );
8676 * }
8677 * return MyProcessDialog.parent.prototype.getActionProcess.call( this, action );
8678 * };
8679 *
8680 * var windowManager = new OO.ui.WindowManager();
8681 * $( 'body' ).append( windowManager.$element );
8682 *
8683 * var dialog = new MyProcessDialog();
8684 * windowManager.addWindows( [ dialog ] );
8685 * windowManager.openWindow( dialog );
8686 *
8687 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs
8688 *
8689 * @abstract
8690 * @class
8691 * @extends OO.ui.Dialog
8692 *
8693 * @constructor
8694 * @param {Object} [config] Configuration options
8695 */
8696 OO.ui.ProcessDialog = function OoUiProcessDialog( config ) {
8697 // Parent constructor
8698 OO.ui.ProcessDialog.parent.call( this, config );
8699
8700 // Properties
8701 this.fitOnOpen = false;
8702
8703 // Initialization
8704 this.$element.addClass( 'oo-ui-processDialog' );
8705 };
8706
8707 /* Setup */
8708
8709 OO.inheritClass( OO.ui.ProcessDialog, OO.ui.Dialog );
8710
8711 /* Methods */
8712
8713 /**
8714 * Handle dismiss button click events.
8715 *
8716 * Hides errors.
8717 *
8718 * @private
8719 */
8720 OO.ui.ProcessDialog.prototype.onDismissErrorButtonClick = function () {
8721 this.hideErrors();
8722 };
8723
8724 /**
8725 * Handle retry button click events.
8726 *
8727 * Hides errors and then tries again.
8728 *
8729 * @private
8730 */
8731 OO.ui.ProcessDialog.prototype.onRetryButtonClick = function () {
8732 this.hideErrors();
8733 this.executeAction( this.currentAction );
8734 };
8735
8736 /**
8737 * @inheritdoc
8738 */
8739 OO.ui.ProcessDialog.prototype.onActionResize = function ( action ) {
8740 if ( this.actions.isSpecial( action ) ) {
8741 this.fitLabel();
8742 }
8743 return OO.ui.ProcessDialog.parent.prototype.onActionResize.call( this, action );
8744 };
8745
8746 /**
8747 * @inheritdoc
8748 */
8749 OO.ui.ProcessDialog.prototype.initialize = function () {
8750 // Parent method
8751 OO.ui.ProcessDialog.parent.prototype.initialize.call( this );
8752
8753 // Properties
8754 this.$navigation = $( '<div>' );
8755 this.$location = $( '<div>' );
8756 this.$safeActions = $( '<div>' );
8757 this.$primaryActions = $( '<div>' );
8758 this.$otherActions = $( '<div>' );
8759 this.dismissButton = new OO.ui.ButtonWidget( {
8760 label: OO.ui.msg( 'ooui-dialog-process-dismiss' )
8761 } );
8762 this.retryButton = new OO.ui.ButtonWidget();
8763 this.$errors = $( '<div>' );
8764 this.$errorsTitle = $( '<div>' );
8765
8766 // Events
8767 this.dismissButton.connect( this, { click: 'onDismissErrorButtonClick' } );
8768 this.retryButton.connect( this, { click: 'onRetryButtonClick' } );
8769
8770 // Initialization
8771 this.title.$element.addClass( 'oo-ui-processDialog-title' );
8772 this.$location
8773 .append( this.title.$element )
8774 .addClass( 'oo-ui-processDialog-location' );
8775 this.$safeActions.addClass( 'oo-ui-processDialog-actions-safe' );
8776 this.$primaryActions.addClass( 'oo-ui-processDialog-actions-primary' );
8777 this.$otherActions.addClass( 'oo-ui-processDialog-actions-other' );
8778 this.$errorsTitle
8779 .addClass( 'oo-ui-processDialog-errors-title' )
8780 .text( OO.ui.msg( 'ooui-dialog-process-error' ) );
8781 this.$errors
8782 .addClass( 'oo-ui-processDialog-errors oo-ui-element-hidden' )
8783 .append( this.$errorsTitle, this.dismissButton.$element, this.retryButton.$element );
8784 this.$content
8785 .addClass( 'oo-ui-processDialog-content' )
8786 .append( this.$errors );
8787 this.$navigation
8788 .addClass( 'oo-ui-processDialog-navigation' )
8789 .append( this.$safeActions, this.$location, this.$primaryActions );
8790 this.$head.append( this.$navigation );
8791 this.$foot.append( this.$otherActions );
8792 };
8793
8794 /**
8795 * @inheritdoc
8796 */
8797 OO.ui.ProcessDialog.prototype.getActionWidgets = function ( actions ) {
8798 var i, len, widgets = [];
8799 for ( i = 0, len = actions.length; i < len; i++ ) {
8800 widgets.push(
8801 new OO.ui.ActionWidget( $.extend( { framed: true }, actions[ i ] ) )
8802 );
8803 }
8804 return widgets;
8805 };
8806
8807 /**
8808 * @inheritdoc
8809 */
8810 OO.ui.ProcessDialog.prototype.attachActions = function () {
8811 var i, len, other, special, others;
8812
8813 // Parent method
8814 OO.ui.ProcessDialog.parent.prototype.attachActions.call( this );
8815
8816 special = this.actions.getSpecial();
8817 others = this.actions.getOthers();
8818 if ( special.primary ) {
8819 this.$primaryActions.append( special.primary.$element );
8820 }
8821 for ( i = 0, len = others.length; i < len; i++ ) {
8822 other = others[ i ];
8823 this.$otherActions.append( other.$element );
8824 }
8825 if ( special.safe ) {
8826 this.$safeActions.append( special.safe.$element );
8827 }
8828
8829 this.fitLabel();
8830 this.$body.css( 'bottom', this.$foot.outerHeight( true ) );
8831 };
8832
8833 /**
8834 * @inheritdoc
8835 */
8836 OO.ui.ProcessDialog.prototype.executeAction = function ( action ) {
8837 var process = this;
8838 return OO.ui.ProcessDialog.parent.prototype.executeAction.call( this, action )
8839 .fail( function ( errors ) {
8840 process.showErrors( errors || [] );
8841 } );
8842 };
8843
8844 /**
8845 * @inheritdoc
8846 */
8847 OO.ui.ProcessDialog.prototype.setDimensions = function () {
8848 // Parent method
8849 OO.ui.ProcessDialog.parent.prototype.setDimensions.apply( this, arguments );
8850
8851 this.fitLabel();
8852 };
8853
8854 /**
8855 * Fit label between actions.
8856 *
8857 * @private
8858 * @chainable
8859 */
8860 OO.ui.ProcessDialog.prototype.fitLabel = function () {
8861 var safeWidth, primaryWidth, biggerWidth, labelWidth, navigationWidth, leftWidth, rightWidth,
8862 size = this.getSizeProperties();
8863
8864 if ( typeof size.width !== 'number' ) {
8865 if ( this.isOpened() ) {
8866 navigationWidth = this.$head.width() - 20;
8867 } else if ( this.isOpening() ) {
8868 if ( !this.fitOnOpen ) {
8869 // Size is relative and the dialog isn't open yet, so wait.
8870 this.manager.opening.done( this.fitLabel.bind( this ) );
8871 this.fitOnOpen = true;
8872 }
8873 return;
8874 } else {
8875 return;
8876 }
8877 } else {
8878 navigationWidth = size.width - 20;
8879 }
8880
8881 safeWidth = this.$safeActions.is( ':visible' ) ? this.$safeActions.width() : 0;
8882 primaryWidth = this.$primaryActions.is( ':visible' ) ? this.$primaryActions.width() : 0;
8883 biggerWidth = Math.max( safeWidth, primaryWidth );
8884
8885 labelWidth = this.title.$element.width();
8886
8887 if ( 2 * biggerWidth + labelWidth < navigationWidth ) {
8888 // We have enough space to center the label
8889 leftWidth = rightWidth = biggerWidth;
8890 } else {
8891 // Let's hope we at least have enough space not to overlap, because we can't wrap the label…
8892 if ( this.getDir() === 'ltr' ) {
8893 leftWidth = safeWidth;
8894 rightWidth = primaryWidth;
8895 } else {
8896 leftWidth = primaryWidth;
8897 rightWidth = safeWidth;
8898 }
8899 }
8900
8901 this.$location.css( { paddingLeft: leftWidth, paddingRight: rightWidth } );
8902
8903 return this;
8904 };
8905
8906 /**
8907 * Handle errors that occurred during accept or reject processes.
8908 *
8909 * @private
8910 * @param {OO.ui.Error[]|OO.ui.Error} errors Errors to be handled
8911 */
8912 OO.ui.ProcessDialog.prototype.showErrors = function ( errors ) {
8913 var i, len, $item, actions,
8914 items = [],
8915 abilities = {},
8916 recoverable = true,
8917 warning = false;
8918
8919 if ( errors instanceof OO.ui.Error ) {
8920 errors = [ errors ];
8921 }
8922
8923 for ( i = 0, len = errors.length; i < len; i++ ) {
8924 if ( !errors[ i ].isRecoverable() ) {
8925 recoverable = false;
8926 }
8927 if ( errors[ i ].isWarning() ) {
8928 warning = true;
8929 }
8930 $item = $( '<div>' )
8931 .addClass( 'oo-ui-processDialog-error' )
8932 .append( errors[ i ].getMessage() );
8933 items.push( $item[ 0 ] );
8934 }
8935 this.$errorItems = $( items );
8936 if ( recoverable ) {
8937 abilities[ this.currentAction ] = true;
8938 // Copy the flags from the first matching action
8939 actions = this.actions.get( { actions: this.currentAction } );
8940 if ( actions.length ) {
8941 this.retryButton.clearFlags().setFlags( actions[ 0 ].getFlags() );
8942 }
8943 } else {
8944 abilities[ this.currentAction ] = false;
8945 this.actions.setAbilities( abilities );
8946 }
8947 if ( warning ) {
8948 this.retryButton.setLabel( OO.ui.msg( 'ooui-dialog-process-continue' ) );
8949 } else {
8950 this.retryButton.setLabel( OO.ui.msg( 'ooui-dialog-process-retry' ) );
8951 }
8952 this.retryButton.toggle( recoverable );
8953 this.$errorsTitle.after( this.$errorItems );
8954 this.$errors.removeClass( 'oo-ui-element-hidden' ).scrollTop( 0 );
8955 };
8956
8957 /**
8958 * Hide errors.
8959 *
8960 * @private
8961 */
8962 OO.ui.ProcessDialog.prototype.hideErrors = function () {
8963 this.$errors.addClass( 'oo-ui-element-hidden' );
8964 if ( this.$errorItems ) {
8965 this.$errorItems.remove();
8966 this.$errorItems = null;
8967 }
8968 };
8969
8970 /**
8971 * @inheritdoc
8972 */
8973 OO.ui.ProcessDialog.prototype.getTeardownProcess = function ( data ) {
8974 // Parent method
8975 return OO.ui.ProcessDialog.parent.prototype.getTeardownProcess.call( this, data )
8976 .first( function () {
8977 // Make sure to hide errors
8978 this.hideErrors();
8979 this.fitOnOpen = false;
8980 }, this );
8981 };
8982
8983 /**
8984 * FieldLayouts are used with OO.ui.FieldsetLayout. Each FieldLayout requires a field-widget,
8985 * which is a widget that is specified by reference before any optional configuration settings.
8986 *
8987 * Field layouts can be configured with help text and/or labels. Labels are aligned in one of four ways:
8988 *
8989 * - **left**: The label is placed before the field-widget and aligned with the left margin.
8990 * A left-alignment is used for forms with many fields.
8991 * - **right**: The label is placed before the field-widget and aligned to the right margin.
8992 * A right-alignment is used for long but familiar forms which users tab through,
8993 * verifying the current field with a quick glance at the label.
8994 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
8995 * that users fill out from top to bottom.
8996 * - **inline**: The label is placed after the field-widget and aligned to the left.
8997 * An inline-alignment is best used with checkboxes or radio buttons.
8998 *
8999 * Help text is accessed via a help icon that appears in the upper right corner of the rendered field layout.
9000 * Please see the [OOjs UI documentation on MediaWiki] [1] for examples and more information.
9001 *
9002 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Fields_and_Fieldsets
9003 * @class
9004 * @extends OO.ui.Layout
9005 * @mixins OO.ui.mixin.LabelElement
9006 * @mixins OO.ui.mixin.TitledElement
9007 *
9008 * @constructor
9009 * @param {OO.ui.Widget} fieldWidget Field widget
9010 * @param {Object} [config] Configuration options
9011 * @cfg {string} [align='left'] Alignment of the label: 'left', 'right', 'top' or 'inline'
9012 * @cfg {Array} [errors] Error messages about the widget, which will be displayed below the widget.
9013 * The array may contain strings or OO.ui.HtmlSnippet instances.
9014 * @cfg {Array} [notices] Notices about the widget, which will be displayed below the widget.
9015 * The array may contain strings or OO.ui.HtmlSnippet instances.
9016 * @cfg {string|OO.ui.HtmlSnippet} [help] Help text. When help text is specified, a "help" icon will appear
9017 * in the upper-right corner of the rendered field; clicking it will display the text in a popup.
9018 * For important messages, you are advised to use `notices`, as they are always shown.
9019 *
9020 * @throws {Error} An error is thrown if no widget is specified
9021 */
9022 OO.ui.FieldLayout = function OoUiFieldLayout( fieldWidget, config ) {
9023 var hasInputWidget, div, i;
9024
9025 // Allow passing positional parameters inside the config object
9026 if ( OO.isPlainObject( fieldWidget ) && config === undefined ) {
9027 config = fieldWidget;
9028 fieldWidget = config.fieldWidget;
9029 }
9030
9031 // Make sure we have required constructor arguments
9032 if ( fieldWidget === undefined ) {
9033 throw new Error( 'Widget not found' );
9034 }
9035
9036 hasInputWidget = fieldWidget.constructor.static.supportsSimpleLabel;
9037
9038 // Configuration initialization
9039 config = $.extend( { align: 'left' }, config );
9040
9041 // Parent constructor
9042 OO.ui.FieldLayout.parent.call( this, config );
9043
9044 // Mixin constructors
9045 OO.ui.mixin.LabelElement.call( this, config );
9046 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$label } ) );
9047
9048 // Properties
9049 this.fieldWidget = fieldWidget;
9050 this.errors = config.errors || [];
9051 this.notices = config.notices || [];
9052 this.$field = $( '<div>' );
9053 this.$messages = $( '<ul>' );
9054 this.$body = $( '<' + ( hasInputWidget ? 'label' : 'div' ) + '>' );
9055 this.align = null;
9056 if ( config.help ) {
9057 this.popupButtonWidget = new OO.ui.PopupButtonWidget( {
9058 classes: [ 'oo-ui-fieldLayout-help' ],
9059 framed: false,
9060 icon: 'info'
9061 } );
9062
9063 div = $( '<div>' );
9064 if ( config.help instanceof OO.ui.HtmlSnippet ) {
9065 div.html( config.help.toString() );
9066 } else {
9067 div.text( config.help );
9068 }
9069 this.popupButtonWidget.getPopup().$body.append(
9070 div.addClass( 'oo-ui-fieldLayout-help-content' )
9071 );
9072 this.$help = this.popupButtonWidget.$element;
9073 } else {
9074 this.$help = $( [] );
9075 }
9076
9077 // Events
9078 if ( hasInputWidget ) {
9079 this.$label.on( 'click', this.onLabelClick.bind( this ) );
9080 }
9081 this.fieldWidget.connect( this, { disable: 'onFieldDisable' } );
9082
9083 // Initialization
9084 this.$element
9085 .addClass( 'oo-ui-fieldLayout' )
9086 .append( this.$help, this.$body );
9087 if ( this.errors.length || this.notices.length ) {
9088 this.$element.append( this.$messages );
9089 }
9090 this.$body.addClass( 'oo-ui-fieldLayout-body' );
9091 this.$messages.addClass( 'oo-ui-fieldLayout-messages' );
9092 this.$field
9093 .addClass( 'oo-ui-fieldLayout-field' )
9094 .toggleClass( 'oo-ui-fieldLayout-disable', this.fieldWidget.isDisabled() )
9095 .append( this.fieldWidget.$element );
9096
9097 for ( i = 0; i < this.notices.length; i++ ) {
9098 this.$messages.append( this.makeMessage( 'notice', this.notices[ i ] ) );
9099 }
9100 for ( i = 0; i < this.errors.length; i++ ) {
9101 this.$messages.append( this.makeMessage( 'error', this.errors[ i ] ) );
9102 }
9103
9104 this.setAlignment( config.align );
9105 };
9106
9107 /* Setup */
9108
9109 OO.inheritClass( OO.ui.FieldLayout, OO.ui.Layout );
9110 OO.mixinClass( OO.ui.FieldLayout, OO.ui.mixin.LabelElement );
9111 OO.mixinClass( OO.ui.FieldLayout, OO.ui.mixin.TitledElement );
9112
9113 /* Methods */
9114
9115 /**
9116 * Handle field disable events.
9117 *
9118 * @private
9119 * @param {boolean} value Field is disabled
9120 */
9121 OO.ui.FieldLayout.prototype.onFieldDisable = function ( value ) {
9122 this.$element.toggleClass( 'oo-ui-fieldLayout-disabled', value );
9123 };
9124
9125 /**
9126 * Handle label mouse click events.
9127 *
9128 * @private
9129 * @param {jQuery.Event} e Mouse click event
9130 */
9131 OO.ui.FieldLayout.prototype.onLabelClick = function () {
9132 this.fieldWidget.simulateLabelClick();
9133 return false;
9134 };
9135
9136 /**
9137 * Get the widget contained by the field.
9138 *
9139 * @return {OO.ui.Widget} Field widget
9140 */
9141 OO.ui.FieldLayout.prototype.getField = function () {
9142 return this.fieldWidget;
9143 };
9144
9145 /**
9146 * @param {string} kind 'error' or 'notice'
9147 * @param {string|OO.ui.HtmlSnippet} text
9148 * @return {jQuery}
9149 */
9150 OO.ui.FieldLayout.prototype.makeMessage = function ( kind, text ) {
9151 var $listItem, $icon, message;
9152 $listItem = $( '<li>' );
9153 if ( kind === 'error' ) {
9154 $icon = new OO.ui.IconWidget( { icon: 'alert', flags: [ 'warning' ] } ).$element;
9155 } else if ( kind === 'notice' ) {
9156 $icon = new OO.ui.IconWidget( { icon: 'info' } ).$element;
9157 } else {
9158 $icon = '';
9159 }
9160 message = new OO.ui.LabelWidget( { label: text } );
9161 $listItem
9162 .append( $icon, message.$element )
9163 .addClass( 'oo-ui-fieldLayout-messages-' + kind );
9164 return $listItem;
9165 };
9166
9167 /**
9168 * Set the field alignment mode.
9169 *
9170 * @private
9171 * @param {string} value Alignment mode, either 'left', 'right', 'top' or 'inline'
9172 * @chainable
9173 */
9174 OO.ui.FieldLayout.prototype.setAlignment = function ( value ) {
9175 if ( value !== this.align ) {
9176 // Default to 'left'
9177 if ( [ 'left', 'right', 'top', 'inline' ].indexOf( value ) === -1 ) {
9178 value = 'left';
9179 }
9180 // Reorder elements
9181 if ( value === 'inline' ) {
9182 this.$body.append( this.$field, this.$label );
9183 } else {
9184 this.$body.append( this.$label, this.$field );
9185 }
9186 // Set classes. The following classes can be used here:
9187 // * oo-ui-fieldLayout-align-left
9188 // * oo-ui-fieldLayout-align-right
9189 // * oo-ui-fieldLayout-align-top
9190 // * oo-ui-fieldLayout-align-inline
9191 if ( this.align ) {
9192 this.$element.removeClass( 'oo-ui-fieldLayout-align-' + this.align );
9193 }
9194 this.$element.addClass( 'oo-ui-fieldLayout-align-' + value );
9195 this.align = value;
9196 }
9197
9198 return this;
9199 };
9200
9201 /**
9202 * ActionFieldLayouts are used with OO.ui.FieldsetLayout. The layout consists of a field-widget, a button,
9203 * and an optional label and/or help text. The field-widget (e.g., a {@link OO.ui.TextInputWidget TextInputWidget}),
9204 * is required and is specified before any optional configuration settings.
9205 *
9206 * Labels can be aligned in one of four ways:
9207 *
9208 * - **left**: The label is placed before the field-widget and aligned with the left margin.
9209 * A left-alignment is used for forms with many fields.
9210 * - **right**: The label is placed before the field-widget and aligned to the right margin.
9211 * A right-alignment is used for long but familiar forms which users tab through,
9212 * verifying the current field with a quick glance at the label.
9213 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
9214 * that users fill out from top to bottom.
9215 * - **inline**: The label is placed after the field-widget and aligned to the left.
9216 * An inline-alignment is best used with checkboxes or radio buttons.
9217 *
9218 * Help text is accessed via a help icon that appears in the upper right corner of the rendered field layout when help
9219 * text is specified.
9220 *
9221 * @example
9222 * // Example of an ActionFieldLayout
9223 * var actionFieldLayout = new OO.ui.ActionFieldLayout(
9224 * new OO.ui.TextInputWidget( {
9225 * placeholder: 'Field widget'
9226 * } ),
9227 * new OO.ui.ButtonWidget( {
9228 * label: 'Button'
9229 * } ),
9230 * {
9231 * label: 'An ActionFieldLayout. This label is aligned top',
9232 * align: 'top',
9233 * help: 'This is help text'
9234 * }
9235 * );
9236 *
9237 * $( 'body' ).append( actionFieldLayout.$element );
9238 *
9239 * @class
9240 * @extends OO.ui.FieldLayout
9241 *
9242 * @constructor
9243 * @param {OO.ui.Widget} fieldWidget Field widget
9244 * @param {OO.ui.ButtonWidget} buttonWidget Button widget
9245 */
9246 OO.ui.ActionFieldLayout = function OoUiActionFieldLayout( fieldWidget, buttonWidget, config ) {
9247 // Allow passing positional parameters inside the config object
9248 if ( OO.isPlainObject( fieldWidget ) && config === undefined ) {
9249 config = fieldWidget;
9250 fieldWidget = config.fieldWidget;
9251 buttonWidget = config.buttonWidget;
9252 }
9253
9254 // Parent constructor
9255 OO.ui.ActionFieldLayout.parent.call( this, fieldWidget, config );
9256
9257 // Properties
9258 this.buttonWidget = buttonWidget;
9259 this.$button = $( '<div>' );
9260 this.$input = $( '<div>' );
9261
9262 // Initialization
9263 this.$element
9264 .addClass( 'oo-ui-actionFieldLayout' );
9265 this.$button
9266 .addClass( 'oo-ui-actionFieldLayout-button' )
9267 .append( this.buttonWidget.$element );
9268 this.$input
9269 .addClass( 'oo-ui-actionFieldLayout-input' )
9270 .append( this.fieldWidget.$element );
9271 this.$field
9272 .append( this.$input, this.$button );
9273 };
9274
9275 /* Setup */
9276
9277 OO.inheritClass( OO.ui.ActionFieldLayout, OO.ui.FieldLayout );
9278
9279 /**
9280 * FieldsetLayouts are composed of one or more {@link OO.ui.FieldLayout FieldLayouts},
9281 * which each contain an individual widget and, optionally, a label. Each Fieldset can be
9282 * configured with a label as well. For more information and examples,
9283 * please see the [OOjs UI documentation on MediaWiki][1].
9284 *
9285 * @example
9286 * // Example of a fieldset layout
9287 * var input1 = new OO.ui.TextInputWidget( {
9288 * placeholder: 'A text input field'
9289 * } );
9290 *
9291 * var input2 = new OO.ui.TextInputWidget( {
9292 * placeholder: 'A text input field'
9293 * } );
9294 *
9295 * var fieldset = new OO.ui.FieldsetLayout( {
9296 * label: 'Example of a fieldset layout'
9297 * } );
9298 *
9299 * fieldset.addItems( [
9300 * new OO.ui.FieldLayout( input1, {
9301 * label: 'Field One'
9302 * } ),
9303 * new OO.ui.FieldLayout( input2, {
9304 * label: 'Field Two'
9305 * } )
9306 * ] );
9307 * $( 'body' ).append( fieldset.$element );
9308 *
9309 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Fields_and_Fieldsets
9310 *
9311 * @class
9312 * @extends OO.ui.Layout
9313 * @mixins OO.ui.mixin.IconElement
9314 * @mixins OO.ui.mixin.LabelElement
9315 * @mixins OO.ui.mixin.GroupElement
9316 *
9317 * @constructor
9318 * @param {Object} [config] Configuration options
9319 * @cfg {OO.ui.FieldLayout[]} [items] An array of fields to add to the fieldset. See OO.ui.FieldLayout for more information about fields.
9320 */
9321 OO.ui.FieldsetLayout = function OoUiFieldsetLayout( config ) {
9322 // Configuration initialization
9323 config = config || {};
9324
9325 // Parent constructor
9326 OO.ui.FieldsetLayout.parent.call( this, config );
9327
9328 // Mixin constructors
9329 OO.ui.mixin.IconElement.call( this, config );
9330 OO.ui.mixin.LabelElement.call( this, config );
9331 OO.ui.mixin.GroupElement.call( this, config );
9332
9333 if ( config.help ) {
9334 this.popupButtonWidget = new OO.ui.PopupButtonWidget( {
9335 classes: [ 'oo-ui-fieldsetLayout-help' ],
9336 framed: false,
9337 icon: 'info'
9338 } );
9339
9340 this.popupButtonWidget.getPopup().$body.append(
9341 $( '<div>' )
9342 .text( config.help )
9343 .addClass( 'oo-ui-fieldsetLayout-help-content' )
9344 );
9345 this.$help = this.popupButtonWidget.$element;
9346 } else {
9347 this.$help = $( [] );
9348 }
9349
9350 // Initialization
9351 this.$element
9352 .addClass( 'oo-ui-fieldsetLayout' )
9353 .prepend( this.$help, this.$icon, this.$label, this.$group );
9354 if ( Array.isArray( config.items ) ) {
9355 this.addItems( config.items );
9356 }
9357 };
9358
9359 /* Setup */
9360
9361 OO.inheritClass( OO.ui.FieldsetLayout, OO.ui.Layout );
9362 OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.mixin.IconElement );
9363 OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.mixin.LabelElement );
9364 OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.mixin.GroupElement );
9365
9366 /**
9367 * FormLayouts are used to wrap {@link OO.ui.FieldsetLayout FieldsetLayouts} when you intend to use browser-based
9368 * form submission for the fields instead of handling them in JavaScript. Form layouts can be configured with an
9369 * HTML form action, an encoding type, and a method using the #action, #enctype, and #method configs, respectively.
9370 * See the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
9371 *
9372 * Only widgets from the {@link OO.ui.InputWidget InputWidget} family support form submission. It
9373 * includes standard form elements like {@link OO.ui.CheckboxInputWidget checkboxes}, {@link
9374 * OO.ui.RadioInputWidget radio buttons} and {@link OO.ui.TextInputWidget text fields}, as well as
9375 * some fancier controls. Some controls have both regular and InputWidget variants, for example
9376 * OO.ui.DropdownWidget and OO.ui.DropdownInputWidget – only the latter support form submission and
9377 * often have simplified APIs to match the capabilities of HTML forms.
9378 * See the [OOjs UI Inputs documentation on MediaWiki] [2] for more information about InputWidgets.
9379 *
9380 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Forms
9381 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
9382 *
9383 * @example
9384 * // Example of a form layout that wraps a fieldset layout
9385 * var input1 = new OO.ui.TextInputWidget( {
9386 * placeholder: 'Username'
9387 * } );
9388 * var input2 = new OO.ui.TextInputWidget( {
9389 * placeholder: 'Password',
9390 * type: 'password'
9391 * } );
9392 * var submit = new OO.ui.ButtonInputWidget( {
9393 * label: 'Submit'
9394 * } );
9395 *
9396 * var fieldset = new OO.ui.FieldsetLayout( {
9397 * label: 'A form layout'
9398 * } );
9399 * fieldset.addItems( [
9400 * new OO.ui.FieldLayout( input1, {
9401 * label: 'Username',
9402 * align: 'top'
9403 * } ),
9404 * new OO.ui.FieldLayout( input2, {
9405 * label: 'Password',
9406 * align: 'top'
9407 * } ),
9408 * new OO.ui.FieldLayout( submit )
9409 * ] );
9410 * var form = new OO.ui.FormLayout( {
9411 * items: [ fieldset ],
9412 * action: '/api/formhandler',
9413 * method: 'get'
9414 * } )
9415 * $( 'body' ).append( form.$element );
9416 *
9417 * @class
9418 * @extends OO.ui.Layout
9419 * @mixins OO.ui.mixin.GroupElement
9420 *
9421 * @constructor
9422 * @param {Object} [config] Configuration options
9423 * @cfg {string} [method] HTML form `method` attribute
9424 * @cfg {string} [action] HTML form `action` attribute
9425 * @cfg {string} [enctype] HTML form `enctype` attribute
9426 * @cfg {OO.ui.FieldsetLayout[]} [items] Fieldset layouts to add to the form layout.
9427 */
9428 OO.ui.FormLayout = function OoUiFormLayout( config ) {
9429 // Configuration initialization
9430 config = config || {};
9431
9432 // Parent constructor
9433 OO.ui.FormLayout.parent.call( this, config );
9434
9435 // Mixin constructors
9436 OO.ui.mixin.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) );
9437
9438 // Events
9439 this.$element.on( 'submit', this.onFormSubmit.bind( this ) );
9440
9441 // Make sure the action is safe
9442 if ( config.action !== undefined && !OO.ui.isSafeUrl( config.action ) ) {
9443 throw new Error( 'Potentially unsafe action provided: ' + config.action );
9444 }
9445
9446 // Initialization
9447 this.$element
9448 .addClass( 'oo-ui-formLayout' )
9449 .attr( {
9450 method: config.method,
9451 action: config.action,
9452 enctype: config.enctype
9453 } );
9454 if ( Array.isArray( config.items ) ) {
9455 this.addItems( config.items );
9456 }
9457 };
9458
9459 /* Setup */
9460
9461 OO.inheritClass( OO.ui.FormLayout, OO.ui.Layout );
9462 OO.mixinClass( OO.ui.FormLayout, OO.ui.mixin.GroupElement );
9463
9464 /* Events */
9465
9466 /**
9467 * A 'submit' event is emitted when the form is submitted.
9468 *
9469 * @event submit
9470 */
9471
9472 /* Static Properties */
9473
9474 OO.ui.FormLayout.static.tagName = 'form';
9475
9476 /* Methods */
9477
9478 /**
9479 * Handle form submit events.
9480 *
9481 * @private
9482 * @param {jQuery.Event} e Submit event
9483 * @fires submit
9484 */
9485 OO.ui.FormLayout.prototype.onFormSubmit = function () {
9486 if ( this.emit( 'submit' ) ) {
9487 return false;
9488 }
9489 };
9490
9491 /**
9492 * 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)
9493 * and its size is customized with the #menuSize config. The content area will fill all remaining space.
9494 *
9495 * @example
9496 * var menuLayout = new OO.ui.MenuLayout( {
9497 * position: 'top'
9498 * } ),
9499 * menuPanel = new OO.ui.PanelLayout( { padded: true, expanded: true, scrollable: true } ),
9500 * contentPanel = new OO.ui.PanelLayout( { padded: true, expanded: true, scrollable: true } ),
9501 * select = new OO.ui.SelectWidget( {
9502 * items: [
9503 * new OO.ui.OptionWidget( {
9504 * data: 'before',
9505 * label: 'Before',
9506 * } ),
9507 * new OO.ui.OptionWidget( {
9508 * data: 'after',
9509 * label: 'After',
9510 * } ),
9511 * new OO.ui.OptionWidget( {
9512 * data: 'top',
9513 * label: 'Top',
9514 * } ),
9515 * new OO.ui.OptionWidget( {
9516 * data: 'bottom',
9517 * label: 'Bottom',
9518 * } )
9519 * ]
9520 * } ).on( 'select', function ( item ) {
9521 * menuLayout.setMenuPosition( item.getData() );
9522 * } );
9523 *
9524 * menuLayout.$menu.append(
9525 * menuPanel.$element.append( '<b>Menu panel</b>', select.$element )
9526 * );
9527 * menuLayout.$content.append(
9528 * contentPanel.$element.append( '<b>Content panel</b>', '<p>Note that the menu is positioned relative to the content panel: top, bottom, after, before.</p>')
9529 * );
9530 * $( 'body' ).append( menuLayout.$element );
9531 *
9532 * If menu size needs to be overridden, it can be accomplished using CSS similar to the snippet
9533 * below. MenuLayout's CSS will override the appropriate values with 'auto' or '0' to display the
9534 * menu correctly. If `menuPosition` is known beforehand, CSS rules corresponding to other positions
9535 * may be omitted.
9536 *
9537 * .oo-ui-menuLayout-menu {
9538 * height: 200px;
9539 * width: 200px;
9540 * }
9541 * .oo-ui-menuLayout-content {
9542 * top: 200px;
9543 * left: 200px;
9544 * right: 200px;
9545 * bottom: 200px;
9546 * }
9547 *
9548 * @class
9549 * @extends OO.ui.Layout
9550 *
9551 * @constructor
9552 * @param {Object} [config] Configuration options
9553 * @cfg {boolean} [showMenu=true] Show menu
9554 * @cfg {string} [menuPosition='before'] Position of menu: `top`, `after`, `bottom` or `before`
9555 */
9556 OO.ui.MenuLayout = function OoUiMenuLayout( config ) {
9557 // Configuration initialization
9558 config = $.extend( {
9559 showMenu: true,
9560 menuPosition: 'before'
9561 }, config );
9562
9563 // Parent constructor
9564 OO.ui.MenuLayout.parent.call( this, config );
9565
9566 /**
9567 * Menu DOM node
9568 *
9569 * @property {jQuery}
9570 */
9571 this.$menu = $( '<div>' );
9572 /**
9573 * Content DOM node
9574 *
9575 * @property {jQuery}
9576 */
9577 this.$content = $( '<div>' );
9578
9579 // Initialization
9580 this.$menu
9581 .addClass( 'oo-ui-menuLayout-menu' );
9582 this.$content.addClass( 'oo-ui-menuLayout-content' );
9583 this.$element
9584 .addClass( 'oo-ui-menuLayout' )
9585 .append( this.$content, this.$menu );
9586 this.setMenuPosition( config.menuPosition );
9587 this.toggleMenu( config.showMenu );
9588 };
9589
9590 /* Setup */
9591
9592 OO.inheritClass( OO.ui.MenuLayout, OO.ui.Layout );
9593
9594 /* Methods */
9595
9596 /**
9597 * Toggle menu.
9598 *
9599 * @param {boolean} showMenu Show menu, omit to toggle
9600 * @chainable
9601 */
9602 OO.ui.MenuLayout.prototype.toggleMenu = function ( showMenu ) {
9603 showMenu = showMenu === undefined ? !this.showMenu : !!showMenu;
9604
9605 if ( this.showMenu !== showMenu ) {
9606 this.showMenu = showMenu;
9607 this.$element
9608 .toggleClass( 'oo-ui-menuLayout-showMenu', this.showMenu )
9609 .toggleClass( 'oo-ui-menuLayout-hideMenu', !this.showMenu );
9610 }
9611
9612 return this;
9613 };
9614
9615 /**
9616 * Check if menu is visible
9617 *
9618 * @return {boolean} Menu is visible
9619 */
9620 OO.ui.MenuLayout.prototype.isMenuVisible = function () {
9621 return this.showMenu;
9622 };
9623
9624 /**
9625 * Set menu position.
9626 *
9627 * @param {string} position Position of menu, either `top`, `after`, `bottom` or `before`
9628 * @throws {Error} If position value is not supported
9629 * @chainable
9630 */
9631 OO.ui.MenuLayout.prototype.setMenuPosition = function ( position ) {
9632 this.$element.removeClass( 'oo-ui-menuLayout-' + this.menuPosition );
9633 this.menuPosition = position;
9634 this.$element.addClass( 'oo-ui-menuLayout-' + position );
9635
9636 return this;
9637 };
9638
9639 /**
9640 * Get menu position.
9641 *
9642 * @return {string} Menu position
9643 */
9644 OO.ui.MenuLayout.prototype.getMenuPosition = function () {
9645 return this.menuPosition;
9646 };
9647
9648 /**
9649 * BookletLayouts contain {@link OO.ui.PageLayout page layouts} as well as
9650 * an {@link OO.ui.OutlineSelectWidget outline} that allows users to easily navigate
9651 * through the pages and select which one to display. By default, only one page is
9652 * displayed at a time and the outline is hidden. When a user navigates to a new page,
9653 * the booklet layout automatically focuses on the first focusable element, unless the
9654 * default setting is changed. Optionally, booklets can be configured to show
9655 * {@link OO.ui.OutlineControlsWidget controls} for adding, moving, and removing items.
9656 *
9657 * @example
9658 * // Example of a BookletLayout that contains two PageLayouts.
9659 *
9660 * function PageOneLayout( name, config ) {
9661 * PageOneLayout.parent.call( this, name, config );
9662 * this.$element.append( '<p>First page</p><p>(This booklet has an outline, displayed on the left)</p>' );
9663 * }
9664 * OO.inheritClass( PageOneLayout, OO.ui.PageLayout );
9665 * PageOneLayout.prototype.setupOutlineItem = function () {
9666 * this.outlineItem.setLabel( 'Page One' );
9667 * };
9668 *
9669 * function PageTwoLayout( name, config ) {
9670 * PageTwoLayout.parent.call( this, name, config );
9671 * this.$element.append( '<p>Second page</p>' );
9672 * }
9673 * OO.inheritClass( PageTwoLayout, OO.ui.PageLayout );
9674 * PageTwoLayout.prototype.setupOutlineItem = function () {
9675 * this.outlineItem.setLabel( 'Page Two' );
9676 * };
9677 *
9678 * var page1 = new PageOneLayout( 'one' ),
9679 * page2 = new PageTwoLayout( 'two' );
9680 *
9681 * var booklet = new OO.ui.BookletLayout( {
9682 * outlined: true
9683 * } );
9684 *
9685 * booklet.addPages ( [ page1, page2 ] );
9686 * $( 'body' ).append( booklet.$element );
9687 *
9688 * @class
9689 * @extends OO.ui.MenuLayout
9690 *
9691 * @constructor
9692 * @param {Object} [config] Configuration options
9693 * @cfg {boolean} [continuous=false] Show all pages, one after another
9694 * @cfg {boolean} [autoFocus=true] Focus on the first focusable element when a new page is displayed.
9695 * @cfg {boolean} [outlined=false] Show the outline. The outline is used to navigate through the pages of the booklet.
9696 * @cfg {boolean} [editable=false] Show controls for adding, removing and reordering pages
9697 */
9698 OO.ui.BookletLayout = function OoUiBookletLayout( config ) {
9699 // Configuration initialization
9700 config = config || {};
9701
9702 // Parent constructor
9703 OO.ui.BookletLayout.parent.call( this, config );
9704
9705 // Properties
9706 this.currentPageName = null;
9707 this.pages = {};
9708 this.ignoreFocus = false;
9709 this.stackLayout = new OO.ui.StackLayout( { continuous: !!config.continuous } );
9710 this.$content.append( this.stackLayout.$element );
9711 this.autoFocus = config.autoFocus === undefined || !!config.autoFocus;
9712 this.outlineVisible = false;
9713 this.outlined = !!config.outlined;
9714 if ( this.outlined ) {
9715 this.editable = !!config.editable;
9716 this.outlineControlsWidget = null;
9717 this.outlineSelectWidget = new OO.ui.OutlineSelectWidget();
9718 this.outlinePanel = new OO.ui.PanelLayout( { scrollable: true } );
9719 this.$menu.append( this.outlinePanel.$element );
9720 this.outlineVisible = true;
9721 if ( this.editable ) {
9722 this.outlineControlsWidget = new OO.ui.OutlineControlsWidget(
9723 this.outlineSelectWidget
9724 );
9725 }
9726 }
9727 this.toggleMenu( this.outlined );
9728
9729 // Events
9730 this.stackLayout.connect( this, { set: 'onStackLayoutSet' } );
9731 if ( this.outlined ) {
9732 this.outlineSelectWidget.connect( this, { select: 'onOutlineSelectWidgetSelect' } );
9733 }
9734 if ( this.autoFocus ) {
9735 // Event 'focus' does not bubble, but 'focusin' does
9736 this.stackLayout.$element.on( 'focusin', this.onStackLayoutFocus.bind( this ) );
9737 }
9738
9739 // Initialization
9740 this.$element.addClass( 'oo-ui-bookletLayout' );
9741 this.stackLayout.$element.addClass( 'oo-ui-bookletLayout-stackLayout' );
9742 if ( this.outlined ) {
9743 this.outlinePanel.$element
9744 .addClass( 'oo-ui-bookletLayout-outlinePanel' )
9745 .append( this.outlineSelectWidget.$element );
9746 if ( this.editable ) {
9747 this.outlinePanel.$element
9748 .addClass( 'oo-ui-bookletLayout-outlinePanel-editable' )
9749 .append( this.outlineControlsWidget.$element );
9750 }
9751 }
9752 };
9753
9754 /* Setup */
9755
9756 OO.inheritClass( OO.ui.BookletLayout, OO.ui.MenuLayout );
9757
9758 /* Events */
9759
9760 /**
9761 * A 'set' event is emitted when a page is {@link #setPage set} to be displayed by the booklet layout.
9762 * @event set
9763 * @param {OO.ui.PageLayout} page Current page
9764 */
9765
9766 /**
9767 * An 'add' event is emitted when pages are {@link #addPages added} to the booklet layout.
9768 *
9769 * @event add
9770 * @param {OO.ui.PageLayout[]} page Added pages
9771 * @param {number} index Index pages were added at
9772 */
9773
9774 /**
9775 * A 'remove' event is emitted when pages are {@link #clearPages cleared} or
9776 * {@link #removePages removed} from the booklet.
9777 *
9778 * @event remove
9779 * @param {OO.ui.PageLayout[]} pages Removed pages
9780 */
9781
9782 /* Methods */
9783
9784 /**
9785 * Handle stack layout focus.
9786 *
9787 * @private
9788 * @param {jQuery.Event} e Focusin event
9789 */
9790 OO.ui.BookletLayout.prototype.onStackLayoutFocus = function ( e ) {
9791 var name, $target;
9792
9793 // Find the page that an element was focused within
9794 $target = $( e.target ).closest( '.oo-ui-pageLayout' );
9795 for ( name in this.pages ) {
9796 // Check for page match, exclude current page to find only page changes
9797 if ( this.pages[ name ].$element[ 0 ] === $target[ 0 ] && name !== this.currentPageName ) {
9798 this.setPage( name );
9799 break;
9800 }
9801 }
9802 };
9803
9804 /**
9805 * Handle stack layout set events.
9806 *
9807 * @private
9808 * @param {OO.ui.PanelLayout|null} page The page panel that is now the current panel
9809 */
9810 OO.ui.BookletLayout.prototype.onStackLayoutSet = function ( page ) {
9811 var layout = this;
9812 if ( page ) {
9813 page.scrollElementIntoView( { complete: function () {
9814 if ( layout.autoFocus ) {
9815 layout.focus();
9816 }
9817 } } );
9818 }
9819 };
9820
9821 /**
9822 * Focus the first input in the current page.
9823 *
9824 * If no page is selected, the first selectable page will be selected.
9825 * If the focus is already in an element on the current page, nothing will happen.
9826 * @param {number} [itemIndex] A specific item to focus on
9827 */
9828 OO.ui.BookletLayout.prototype.focus = function ( itemIndex ) {
9829 var page,
9830 items = this.stackLayout.getItems();
9831
9832 if ( itemIndex !== undefined && items[ itemIndex ] ) {
9833 page = items[ itemIndex ];
9834 } else {
9835 page = this.stackLayout.getCurrentItem();
9836 }
9837
9838 if ( !page && this.outlined ) {
9839 this.selectFirstSelectablePage();
9840 page = this.stackLayout.getCurrentItem();
9841 }
9842 if ( !page ) {
9843 return;
9844 }
9845 // Only change the focus if is not already in the current page
9846 if ( !OO.ui.contains( page.$element[ 0 ], this.getElementDocument().activeElement, true ) ) {
9847 page.focus();
9848 }
9849 };
9850
9851 /**
9852 * Find the first focusable input in the booklet layout and focus
9853 * on it.
9854 */
9855 OO.ui.BookletLayout.prototype.focusFirstFocusable = function () {
9856 OO.ui.findFocusable( this.stackLayout.$element ).focus();
9857 };
9858
9859 /**
9860 * Handle outline widget select events.
9861 *
9862 * @private
9863 * @param {OO.ui.OptionWidget|null} item Selected item
9864 */
9865 OO.ui.BookletLayout.prototype.onOutlineSelectWidgetSelect = function ( item ) {
9866 if ( item ) {
9867 this.setPage( item.getData() );
9868 }
9869 };
9870
9871 /**
9872 * Check if booklet has an outline.
9873 *
9874 * @return {boolean} Booklet has an outline
9875 */
9876 OO.ui.BookletLayout.prototype.isOutlined = function () {
9877 return this.outlined;
9878 };
9879
9880 /**
9881 * Check if booklet has editing controls.
9882 *
9883 * @return {boolean} Booklet is editable
9884 */
9885 OO.ui.BookletLayout.prototype.isEditable = function () {
9886 return this.editable;
9887 };
9888
9889 /**
9890 * Check if booklet has a visible outline.
9891 *
9892 * @return {boolean} Outline is visible
9893 */
9894 OO.ui.BookletLayout.prototype.isOutlineVisible = function () {
9895 return this.outlined && this.outlineVisible;
9896 };
9897
9898 /**
9899 * Hide or show the outline.
9900 *
9901 * @param {boolean} [show] Show outline, omit to invert current state
9902 * @chainable
9903 */
9904 OO.ui.BookletLayout.prototype.toggleOutline = function ( show ) {
9905 if ( this.outlined ) {
9906 show = show === undefined ? !this.outlineVisible : !!show;
9907 this.outlineVisible = show;
9908 this.toggleMenu( show );
9909 }
9910
9911 return this;
9912 };
9913
9914 /**
9915 * Get the page closest to the specified page.
9916 *
9917 * @param {OO.ui.PageLayout} page Page to use as a reference point
9918 * @return {OO.ui.PageLayout|null} Page closest to the specified page
9919 */
9920 OO.ui.BookletLayout.prototype.getClosestPage = function ( page ) {
9921 var next, prev, level,
9922 pages = this.stackLayout.getItems(),
9923 index = pages.indexOf( page );
9924
9925 if ( index !== -1 ) {
9926 next = pages[ index + 1 ];
9927 prev = pages[ index - 1 ];
9928 // Prefer adjacent pages at the same level
9929 if ( this.outlined ) {
9930 level = this.outlineSelectWidget.getItemFromData( page.getName() ).getLevel();
9931 if (
9932 prev &&
9933 level === this.outlineSelectWidget.getItemFromData( prev.getName() ).getLevel()
9934 ) {
9935 return prev;
9936 }
9937 if (
9938 next &&
9939 level === this.outlineSelectWidget.getItemFromData( next.getName() ).getLevel()
9940 ) {
9941 return next;
9942 }
9943 }
9944 }
9945 return prev || next || null;
9946 };
9947
9948 /**
9949 * Get the outline widget.
9950 *
9951 * If the booklet is not outlined, the method will return `null`.
9952 *
9953 * @return {OO.ui.OutlineSelectWidget|null} Outline widget, or null if the booklet is not outlined
9954 */
9955 OO.ui.BookletLayout.prototype.getOutline = function () {
9956 return this.outlineSelectWidget;
9957 };
9958
9959 /**
9960 * Get the outline controls widget.
9961 *
9962 * If the outline is not editable, the method will return `null`.
9963 *
9964 * @return {OO.ui.OutlineControlsWidget|null} The outline controls widget.
9965 */
9966 OO.ui.BookletLayout.prototype.getOutlineControls = function () {
9967 return this.outlineControlsWidget;
9968 };
9969
9970 /**
9971 * Get a page by its symbolic name.
9972 *
9973 * @param {string} name Symbolic name of page
9974 * @return {OO.ui.PageLayout|undefined} Page, if found
9975 */
9976 OO.ui.BookletLayout.prototype.getPage = function ( name ) {
9977 return this.pages[ name ];
9978 };
9979
9980 /**
9981 * Get the current page.
9982 *
9983 * @return {OO.ui.PageLayout|undefined} Current page, if found
9984 */
9985 OO.ui.BookletLayout.prototype.getCurrentPage = function () {
9986 var name = this.getCurrentPageName();
9987 return name ? this.getPage( name ) : undefined;
9988 };
9989
9990 /**
9991 * Get the symbolic name of the current page.
9992 *
9993 * @return {string|null} Symbolic name of the current page
9994 */
9995 OO.ui.BookletLayout.prototype.getCurrentPageName = function () {
9996 return this.currentPageName;
9997 };
9998
9999 /**
10000 * Add pages to the booklet layout
10001 *
10002 * When pages are added with the same names as existing pages, the existing pages will be
10003 * automatically removed before the new pages are added.
10004 *
10005 * @param {OO.ui.PageLayout[]} pages Pages to add
10006 * @param {number} index Index of the insertion point
10007 * @fires add
10008 * @chainable
10009 */
10010 OO.ui.BookletLayout.prototype.addPages = function ( pages, index ) {
10011 var i, len, name, page, item, currentIndex,
10012 stackLayoutPages = this.stackLayout.getItems(),
10013 remove = [],
10014 items = [];
10015
10016 // Remove pages with same names
10017 for ( i = 0, len = pages.length; i < len; i++ ) {
10018 page = pages[ i ];
10019 name = page.getName();
10020
10021 if ( Object.prototype.hasOwnProperty.call( this.pages, name ) ) {
10022 // Correct the insertion index
10023 currentIndex = stackLayoutPages.indexOf( this.pages[ name ] );
10024 if ( currentIndex !== -1 && currentIndex + 1 < index ) {
10025 index--;
10026 }
10027 remove.push( this.pages[ name ] );
10028 }
10029 }
10030 if ( remove.length ) {
10031 this.removePages( remove );
10032 }
10033
10034 // Add new pages
10035 for ( i = 0, len = pages.length; i < len; i++ ) {
10036 page = pages[ i ];
10037 name = page.getName();
10038 this.pages[ page.getName() ] = page;
10039 if ( this.outlined ) {
10040 item = new OO.ui.OutlineOptionWidget( { data: name } );
10041 page.setOutlineItem( item );
10042 items.push( item );
10043 }
10044 }
10045
10046 if ( this.outlined && items.length ) {
10047 this.outlineSelectWidget.addItems( items, index );
10048 this.selectFirstSelectablePage();
10049 }
10050 this.stackLayout.addItems( pages, index );
10051 this.emit( 'add', pages, index );
10052
10053 return this;
10054 };
10055
10056 /**
10057 * Remove the specified pages from the booklet layout.
10058 *
10059 * To remove all pages from the booklet, you may wish to use the #clearPages method instead.
10060 *
10061 * @param {OO.ui.PageLayout[]} pages An array of pages to remove
10062 * @fires remove
10063 * @chainable
10064 */
10065 OO.ui.BookletLayout.prototype.removePages = function ( pages ) {
10066 var i, len, name, page,
10067 items = [];
10068
10069 for ( i = 0, len = pages.length; i < len; i++ ) {
10070 page = pages[ i ];
10071 name = page.getName();
10072 delete this.pages[ name ];
10073 if ( this.outlined ) {
10074 items.push( this.outlineSelectWidget.getItemFromData( name ) );
10075 page.setOutlineItem( null );
10076 }
10077 }
10078 if ( this.outlined && items.length ) {
10079 this.outlineSelectWidget.removeItems( items );
10080 this.selectFirstSelectablePage();
10081 }
10082 this.stackLayout.removeItems( pages );
10083 this.emit( 'remove', pages );
10084
10085 return this;
10086 };
10087
10088 /**
10089 * Clear all pages from the booklet layout.
10090 *
10091 * To remove only a subset of pages from the booklet, use the #removePages method.
10092 *
10093 * @fires remove
10094 * @chainable
10095 */
10096 OO.ui.BookletLayout.prototype.clearPages = function () {
10097 var i, len,
10098 pages = this.stackLayout.getItems();
10099
10100 this.pages = {};
10101 this.currentPageName = null;
10102 if ( this.outlined ) {
10103 this.outlineSelectWidget.clearItems();
10104 for ( i = 0, len = pages.length; i < len; i++ ) {
10105 pages[ i ].setOutlineItem( null );
10106 }
10107 }
10108 this.stackLayout.clearItems();
10109
10110 this.emit( 'remove', pages );
10111
10112 return this;
10113 };
10114
10115 /**
10116 * Set the current page by symbolic name.
10117 *
10118 * @fires set
10119 * @param {string} name Symbolic name of page
10120 */
10121 OO.ui.BookletLayout.prototype.setPage = function ( name ) {
10122 var selectedItem,
10123 $focused,
10124 page = this.pages[ name ],
10125 previousPage = this.currentPageName && this.pages[ this.currentPageName ];
10126
10127 if ( name !== this.currentPageName ) {
10128 if ( this.outlined ) {
10129 selectedItem = this.outlineSelectWidget.getSelectedItem();
10130 if ( selectedItem && selectedItem.getData() !== name ) {
10131 this.outlineSelectWidget.selectItemByData( name );
10132 }
10133 }
10134 if ( page ) {
10135 if ( previousPage ) {
10136 previousPage.setActive( false );
10137 // Blur anything focused if the next page doesn't have anything focusable.
10138 // This is not needed if the next page has something focusable (because once it is focused
10139 // this blur happens automatically). If the layout is non-continuous, this check is
10140 // meaningless because the next page is not visible yet and thus can't hold focus.
10141 if (
10142 this.autoFocus &&
10143 this.stackLayout.continuous &&
10144 OO.ui.findFocusable( page.$element ).length !== 0
10145 ) {
10146 $focused = previousPage.$element.find( ':focus' );
10147 if ( $focused.length ) {
10148 $focused[ 0 ].blur();
10149 }
10150 }
10151 }
10152 this.currentPageName = name;
10153 page.setActive( true );
10154 this.stackLayout.setItem( page );
10155 if ( !this.stackLayout.continuous && previousPage ) {
10156 // This should not be necessary, since any inputs on the previous page should have been
10157 // blurred when it was hidden, but browsers are not very consistent about this.
10158 $focused = previousPage.$element.find( ':focus' );
10159 if ( $focused.length ) {
10160 $focused[ 0 ].blur();
10161 }
10162 }
10163 this.emit( 'set', page );
10164 }
10165 }
10166 };
10167
10168 /**
10169 * Select the first selectable page.
10170 *
10171 * @chainable
10172 */
10173 OO.ui.BookletLayout.prototype.selectFirstSelectablePage = function () {
10174 if ( !this.outlineSelectWidget.getSelectedItem() ) {
10175 this.outlineSelectWidget.selectItem( this.outlineSelectWidget.getFirstSelectableItem() );
10176 }
10177
10178 return this;
10179 };
10180
10181 /**
10182 * IndexLayouts contain {@link OO.ui.CardLayout card layouts} as well as
10183 * {@link OO.ui.TabSelectWidget tabs} that allow users to easily navigate through the cards and
10184 * select which one to display. By default, only one card is displayed at a time. When a user
10185 * navigates to a new card, the index layout automatically focuses on the first focusable element,
10186 * unless the default setting is changed.
10187 *
10188 * TODO: This class is similar to BookletLayout, we may want to refactor to reduce duplication
10189 *
10190 * @example
10191 * // Example of a IndexLayout that contains two CardLayouts.
10192 *
10193 * function CardOneLayout( name, config ) {
10194 * CardOneLayout.parent.call( this, name, config );
10195 * this.$element.append( '<p>First card</p>' );
10196 * }
10197 * OO.inheritClass( CardOneLayout, OO.ui.CardLayout );
10198 * CardOneLayout.prototype.setupTabItem = function () {
10199 * this.tabItem.setLabel( 'Card one' );
10200 * };
10201 *
10202 * var card1 = new CardOneLayout( 'one' ),
10203 * card2 = new CardLayout( 'two', { label: 'Card two' } );
10204 *
10205 * card2.$element.append( '<p>Second card</p>' );
10206 *
10207 * var index = new OO.ui.IndexLayout();
10208 *
10209 * index.addCards ( [ card1, card2 ] );
10210 * $( 'body' ).append( index.$element );
10211 *
10212 * @class
10213 * @extends OO.ui.MenuLayout
10214 *
10215 * @constructor
10216 * @param {Object} [config] Configuration options
10217 * @cfg {boolean} [continuous=false] Show all cards, one after another
10218 * @cfg {boolean} [expanded=true] Expand the content panel to fill the entire parent element.
10219 * @cfg {boolean} [autoFocus=true] Focus on the first focusable element when a new card is displayed.
10220 */
10221 OO.ui.IndexLayout = function OoUiIndexLayout( config ) {
10222 // Configuration initialization
10223 config = $.extend( {}, config, { menuPosition: 'top' } );
10224
10225 // Parent constructor
10226 OO.ui.IndexLayout.parent.call( this, config );
10227
10228 // Properties
10229 this.currentCardName = null;
10230 this.cards = {};
10231 this.ignoreFocus = false;
10232 this.stackLayout = new OO.ui.StackLayout( {
10233 continuous: !!config.continuous,
10234 expanded: config.expanded
10235 } );
10236 this.$content.append( this.stackLayout.$element );
10237 this.autoFocus = config.autoFocus === undefined || !!config.autoFocus;
10238
10239 this.tabSelectWidget = new OO.ui.TabSelectWidget();
10240 this.tabPanel = new OO.ui.PanelLayout();
10241 this.$menu.append( this.tabPanel.$element );
10242
10243 this.toggleMenu( true );
10244
10245 // Events
10246 this.stackLayout.connect( this, { set: 'onStackLayoutSet' } );
10247 this.tabSelectWidget.connect( this, { select: 'onTabSelectWidgetSelect' } );
10248 if ( this.autoFocus ) {
10249 // Event 'focus' does not bubble, but 'focusin' does
10250 this.stackLayout.$element.on( 'focusin', this.onStackLayoutFocus.bind( this ) );
10251 }
10252
10253 // Initialization
10254 this.$element.addClass( 'oo-ui-indexLayout' );
10255 this.stackLayout.$element.addClass( 'oo-ui-indexLayout-stackLayout' );
10256 this.tabPanel.$element
10257 .addClass( 'oo-ui-indexLayout-tabPanel' )
10258 .append( this.tabSelectWidget.$element );
10259 };
10260
10261 /* Setup */
10262
10263 OO.inheritClass( OO.ui.IndexLayout, OO.ui.MenuLayout );
10264
10265 /* Events */
10266
10267 /**
10268 * A 'set' event is emitted when a card is {@link #setCard set} to be displayed by the index layout.
10269 * @event set
10270 * @param {OO.ui.CardLayout} card Current card
10271 */
10272
10273 /**
10274 * An 'add' event is emitted when cards are {@link #addCards added} to the index layout.
10275 *
10276 * @event add
10277 * @param {OO.ui.CardLayout[]} card Added cards
10278 * @param {number} index Index cards were added at
10279 */
10280
10281 /**
10282 * A 'remove' event is emitted when cards are {@link #clearCards cleared} or
10283 * {@link #removeCards removed} from the index.
10284 *
10285 * @event remove
10286 * @param {OO.ui.CardLayout[]} cards Removed cards
10287 */
10288
10289 /* Methods */
10290
10291 /**
10292 * Handle stack layout focus.
10293 *
10294 * @private
10295 * @param {jQuery.Event} e Focusin event
10296 */
10297 OO.ui.IndexLayout.prototype.onStackLayoutFocus = function ( e ) {
10298 var name, $target;
10299
10300 // Find the card that an element was focused within
10301 $target = $( e.target ).closest( '.oo-ui-cardLayout' );
10302 for ( name in this.cards ) {
10303 // Check for card match, exclude current card to find only card changes
10304 if ( this.cards[ name ].$element[ 0 ] === $target[ 0 ] && name !== this.currentCardName ) {
10305 this.setCard( name );
10306 break;
10307 }
10308 }
10309 };
10310
10311 /**
10312 * Handle stack layout set events.
10313 *
10314 * @private
10315 * @param {OO.ui.PanelLayout|null} card The card panel that is now the current panel
10316 */
10317 OO.ui.IndexLayout.prototype.onStackLayoutSet = function ( card ) {
10318 var layout = this;
10319 if ( card ) {
10320 card.scrollElementIntoView( { complete: function () {
10321 if ( layout.autoFocus ) {
10322 layout.focus();
10323 }
10324 } } );
10325 }
10326 };
10327
10328 /**
10329 * Focus the first input in the current card.
10330 *
10331 * If no card is selected, the first selectable card will be selected.
10332 * If the focus is already in an element on the current card, nothing will happen.
10333 * @param {number} [itemIndex] A specific item to focus on
10334 */
10335 OO.ui.IndexLayout.prototype.focus = function ( itemIndex ) {
10336 var card,
10337 items = this.stackLayout.getItems();
10338
10339 if ( itemIndex !== undefined && items[ itemIndex ] ) {
10340 card = items[ itemIndex ];
10341 } else {
10342 card = this.stackLayout.getCurrentItem();
10343 }
10344
10345 if ( !card ) {
10346 this.selectFirstSelectableCard();
10347 card = this.stackLayout.getCurrentItem();
10348 }
10349 if ( !card ) {
10350 return;
10351 }
10352 // Only change the focus if is not already in the current page
10353 if ( !OO.ui.contains( card.$element[ 0 ], this.getElementDocument().activeElement, true ) ) {
10354 card.focus();
10355 }
10356 };
10357
10358 /**
10359 * Find the first focusable input in the index layout and focus
10360 * on it.
10361 */
10362 OO.ui.IndexLayout.prototype.focusFirstFocusable = function () {
10363 OO.ui.findFocusable( this.stackLayout.$element ).focus();
10364 };
10365
10366 /**
10367 * Handle tab widget select events.
10368 *
10369 * @private
10370 * @param {OO.ui.OptionWidget|null} item Selected item
10371 */
10372 OO.ui.IndexLayout.prototype.onTabSelectWidgetSelect = function ( item ) {
10373 if ( item ) {
10374 this.setCard( item.getData() );
10375 }
10376 };
10377
10378 /**
10379 * Get the card closest to the specified card.
10380 *
10381 * @param {OO.ui.CardLayout} card Card to use as a reference point
10382 * @return {OO.ui.CardLayout|null} Card closest to the specified card
10383 */
10384 OO.ui.IndexLayout.prototype.getClosestCard = function ( card ) {
10385 var next, prev, level,
10386 cards = this.stackLayout.getItems(),
10387 index = cards.indexOf( card );
10388
10389 if ( index !== -1 ) {
10390 next = cards[ index + 1 ];
10391 prev = cards[ index - 1 ];
10392 // Prefer adjacent cards at the same level
10393 level = this.tabSelectWidget.getItemFromData( card.getName() ).getLevel();
10394 if (
10395 prev &&
10396 level === this.tabSelectWidget.getItemFromData( prev.getName() ).getLevel()
10397 ) {
10398 return prev;
10399 }
10400 if (
10401 next &&
10402 level === this.tabSelectWidget.getItemFromData( next.getName() ).getLevel()
10403 ) {
10404 return next;
10405 }
10406 }
10407 return prev || next || null;
10408 };
10409
10410 /**
10411 * Get the tabs widget.
10412 *
10413 * @return {OO.ui.TabSelectWidget} Tabs widget
10414 */
10415 OO.ui.IndexLayout.prototype.getTabs = function () {
10416 return this.tabSelectWidget;
10417 };
10418
10419 /**
10420 * Get a card by its symbolic name.
10421 *
10422 * @param {string} name Symbolic name of card
10423 * @return {OO.ui.CardLayout|undefined} Card, if found
10424 */
10425 OO.ui.IndexLayout.prototype.getCard = function ( name ) {
10426 return this.cards[ name ];
10427 };
10428
10429 /**
10430 * Get the current card.
10431 *
10432 * @return {OO.ui.CardLayout|undefined} Current card, if found
10433 */
10434 OO.ui.IndexLayout.prototype.getCurrentCard = function () {
10435 var name = this.getCurrentCardName();
10436 return name ? this.getCard( name ) : undefined;
10437 };
10438
10439 /**
10440 * Get the symbolic name of the current card.
10441 *
10442 * @return {string|null} Symbolic name of the current card
10443 */
10444 OO.ui.IndexLayout.prototype.getCurrentCardName = function () {
10445 return this.currentCardName;
10446 };
10447
10448 /**
10449 * Add cards to the index layout
10450 *
10451 * When cards are added with the same names as existing cards, the existing cards will be
10452 * automatically removed before the new cards are added.
10453 *
10454 * @param {OO.ui.CardLayout[]} cards Cards to add
10455 * @param {number} index Index of the insertion point
10456 * @fires add
10457 * @chainable
10458 */
10459 OO.ui.IndexLayout.prototype.addCards = function ( cards, index ) {
10460 var i, len, name, card, item, currentIndex,
10461 stackLayoutCards = this.stackLayout.getItems(),
10462 remove = [],
10463 items = [];
10464
10465 // Remove cards with same names
10466 for ( i = 0, len = cards.length; i < len; i++ ) {
10467 card = cards[ i ];
10468 name = card.getName();
10469
10470 if ( Object.prototype.hasOwnProperty.call( this.cards, name ) ) {
10471 // Correct the insertion index
10472 currentIndex = stackLayoutCards.indexOf( this.cards[ name ] );
10473 if ( currentIndex !== -1 && currentIndex + 1 < index ) {
10474 index--;
10475 }
10476 remove.push( this.cards[ name ] );
10477 }
10478 }
10479 if ( remove.length ) {
10480 this.removeCards( remove );
10481 }
10482
10483 // Add new cards
10484 for ( i = 0, len = cards.length; i < len; i++ ) {
10485 card = cards[ i ];
10486 name = card.getName();
10487 this.cards[ card.getName() ] = card;
10488 item = new OO.ui.TabOptionWidget( { data: name } );
10489 card.setTabItem( item );
10490 items.push( item );
10491 }
10492
10493 if ( items.length ) {
10494 this.tabSelectWidget.addItems( items, index );
10495 this.selectFirstSelectableCard();
10496 }
10497 this.stackLayout.addItems( cards, index );
10498 this.emit( 'add', cards, index );
10499
10500 return this;
10501 };
10502
10503 /**
10504 * Remove the specified cards from the index layout.
10505 *
10506 * To remove all cards from the index, you may wish to use the #clearCards method instead.
10507 *
10508 * @param {OO.ui.CardLayout[]} cards An array of cards to remove
10509 * @fires remove
10510 * @chainable
10511 */
10512 OO.ui.IndexLayout.prototype.removeCards = function ( cards ) {
10513 var i, len, name, card,
10514 items = [];
10515
10516 for ( i = 0, len = cards.length; i < len; i++ ) {
10517 card = cards[ i ];
10518 name = card.getName();
10519 delete this.cards[ name ];
10520 items.push( this.tabSelectWidget.getItemFromData( name ) );
10521 card.setTabItem( null );
10522 }
10523 if ( items.length ) {
10524 this.tabSelectWidget.removeItems( items );
10525 this.selectFirstSelectableCard();
10526 }
10527 this.stackLayout.removeItems( cards );
10528 this.emit( 'remove', cards );
10529
10530 return this;
10531 };
10532
10533 /**
10534 * Clear all cards from the index layout.
10535 *
10536 * To remove only a subset of cards from the index, use the #removeCards method.
10537 *
10538 * @fires remove
10539 * @chainable
10540 */
10541 OO.ui.IndexLayout.prototype.clearCards = function () {
10542 var i, len,
10543 cards = this.stackLayout.getItems();
10544
10545 this.cards = {};
10546 this.currentCardName = null;
10547 this.tabSelectWidget.clearItems();
10548 for ( i = 0, len = cards.length; i < len; i++ ) {
10549 cards[ i ].setTabItem( null );
10550 }
10551 this.stackLayout.clearItems();
10552
10553 this.emit( 'remove', cards );
10554
10555 return this;
10556 };
10557
10558 /**
10559 * Set the current card by symbolic name.
10560 *
10561 * @fires set
10562 * @param {string} name Symbolic name of card
10563 */
10564 OO.ui.IndexLayout.prototype.setCard = function ( name ) {
10565 var selectedItem,
10566 $focused,
10567 card = this.cards[ name ],
10568 previousCard = this.currentCardName && this.cards[ this.currentCardName ];
10569
10570 if ( name !== this.currentCardName ) {
10571 selectedItem = this.tabSelectWidget.getSelectedItem();
10572 if ( selectedItem && selectedItem.getData() !== name ) {
10573 this.tabSelectWidget.selectItemByData( name );
10574 }
10575 if ( card ) {
10576 if ( previousCard ) {
10577 previousCard.setActive( false );
10578 // Blur anything focused if the next card doesn't have anything focusable.
10579 // This is not needed if the next card has something focusable (because once it is focused
10580 // this blur happens automatically). If the layout is non-continuous, this check is
10581 // meaningless because the next card is not visible yet and thus can't hold focus.
10582 if (
10583 this.autoFocus &&
10584 this.stackLayout.continuous &&
10585 OO.ui.findFocusable( card.$element ).length !== 0
10586 ) {
10587 $focused = previousCard.$element.find( ':focus' );
10588 if ( $focused.length ) {
10589 $focused[ 0 ].blur();
10590 }
10591 }
10592 }
10593 this.currentCardName = name;
10594 card.setActive( true );
10595 this.stackLayout.setItem( card );
10596 if ( !this.stackLayout.continuous && previousCard ) {
10597 // This should not be necessary, since any inputs on the previous card should have been
10598 // blurred when it was hidden, but browsers are not very consistent about this.
10599 $focused = previousCard.$element.find( ':focus' );
10600 if ( $focused.length ) {
10601 $focused[ 0 ].blur();
10602 }
10603 }
10604 this.emit( 'set', card );
10605 }
10606 }
10607 };
10608
10609 /**
10610 * Select the first selectable card.
10611 *
10612 * @chainable
10613 */
10614 OO.ui.IndexLayout.prototype.selectFirstSelectableCard = function () {
10615 if ( !this.tabSelectWidget.getSelectedItem() ) {
10616 this.tabSelectWidget.selectItem( this.tabSelectWidget.getFirstSelectableItem() );
10617 }
10618
10619 return this;
10620 };
10621
10622 /**
10623 * PanelLayouts expand to cover the entire area of their parent. They can be configured with scrolling, padding,
10624 * and a frame, and are often used together with {@link OO.ui.StackLayout StackLayouts}.
10625 *
10626 * @example
10627 * // Example of a panel layout
10628 * var panel = new OO.ui.PanelLayout( {
10629 * expanded: false,
10630 * framed: true,
10631 * padded: true,
10632 * $content: $( '<p>A panel layout with padding and a frame.</p>' )
10633 * } );
10634 * $( 'body' ).append( panel.$element );
10635 *
10636 * @class
10637 * @extends OO.ui.Layout
10638 *
10639 * @constructor
10640 * @param {Object} [config] Configuration options
10641 * @cfg {boolean} [scrollable=false] Allow vertical scrolling
10642 * @cfg {boolean} [padded=false] Add padding between the content and the edges of the panel.
10643 * @cfg {boolean} [expanded=true] Expand the panel to fill the entire parent element.
10644 * @cfg {boolean} [framed=false] Render the panel with a frame to visually separate it from outside content.
10645 */
10646 OO.ui.PanelLayout = function OoUiPanelLayout( config ) {
10647 // Configuration initialization
10648 config = $.extend( {
10649 scrollable: false,
10650 padded: false,
10651 expanded: true,
10652 framed: false
10653 }, config );
10654
10655 // Parent constructor
10656 OO.ui.PanelLayout.parent.call( this, config );
10657
10658 // Initialization
10659 this.$element.addClass( 'oo-ui-panelLayout' );
10660 if ( config.scrollable ) {
10661 this.$element.addClass( 'oo-ui-panelLayout-scrollable' );
10662 }
10663 if ( config.padded ) {
10664 this.$element.addClass( 'oo-ui-panelLayout-padded' );
10665 }
10666 if ( config.expanded ) {
10667 this.$element.addClass( 'oo-ui-panelLayout-expanded' );
10668 }
10669 if ( config.framed ) {
10670 this.$element.addClass( 'oo-ui-panelLayout-framed' );
10671 }
10672 };
10673
10674 /* Setup */
10675
10676 OO.inheritClass( OO.ui.PanelLayout, OO.ui.Layout );
10677
10678 /* Methods */
10679
10680 /**
10681 * Focus the panel layout
10682 *
10683 * The default implementation just focuses the first focusable element in the panel
10684 */
10685 OO.ui.PanelLayout.prototype.focus = function () {
10686 OO.ui.findFocusable( this.$element ).focus();
10687 };
10688
10689 /**
10690 * CardLayouts are used within {@link OO.ui.IndexLayout index layouts} to create cards that users can select and display
10691 * from the index's optional {@link OO.ui.TabSelectWidget tab} navigation. Cards are usually not instantiated directly,
10692 * rather extended to include the required content and functionality.
10693 *
10694 * Each card must have a unique symbolic name, which is passed to the constructor. In addition, the card's tab
10695 * item is customized (with a label) using the #setupTabItem method. See
10696 * {@link OO.ui.IndexLayout IndexLayout} for an example.
10697 *
10698 * @class
10699 * @extends OO.ui.PanelLayout
10700 *
10701 * @constructor
10702 * @param {string} name Unique symbolic name of card
10703 * @param {Object} [config] Configuration options
10704 * @cfg {jQuery|string|Function|OO.ui.HtmlSnippet} [label] Label for card's tab
10705 */
10706 OO.ui.CardLayout = function OoUiCardLayout( name, config ) {
10707 // Allow passing positional parameters inside the config object
10708 if ( OO.isPlainObject( name ) && config === undefined ) {
10709 config = name;
10710 name = config.name;
10711 }
10712
10713 // Configuration initialization
10714 config = $.extend( { scrollable: true }, config );
10715
10716 // Parent constructor
10717 OO.ui.CardLayout.parent.call( this, config );
10718
10719 // Properties
10720 this.name = name;
10721 this.label = config.label;
10722 this.tabItem = null;
10723 this.active = false;
10724
10725 // Initialization
10726 this.$element.addClass( 'oo-ui-cardLayout' );
10727 };
10728
10729 /* Setup */
10730
10731 OO.inheritClass( OO.ui.CardLayout, OO.ui.PanelLayout );
10732
10733 /* Events */
10734
10735 /**
10736 * An 'active' event is emitted when the card becomes active. Cards become active when they are
10737 * shown in a index layout that is configured to display only one card at a time.
10738 *
10739 * @event active
10740 * @param {boolean} active Card is active
10741 */
10742
10743 /* Methods */
10744
10745 /**
10746 * Get the symbolic name of the card.
10747 *
10748 * @return {string} Symbolic name of card
10749 */
10750 OO.ui.CardLayout.prototype.getName = function () {
10751 return this.name;
10752 };
10753
10754 /**
10755 * Check if card is active.
10756 *
10757 * Cards become active when they are shown in a {@link OO.ui.IndexLayout index layout} that is configured to display
10758 * only one card at a time. Additional CSS is applied to the card's tab item to reflect the active state.
10759 *
10760 * @return {boolean} Card is active
10761 */
10762 OO.ui.CardLayout.prototype.isActive = function () {
10763 return this.active;
10764 };
10765
10766 /**
10767 * Get tab item.
10768 *
10769 * The tab item allows users to access the card from the index's tab
10770 * navigation. The tab item itself can be customized (with a label, level, etc.) using the #setupTabItem method.
10771 *
10772 * @return {OO.ui.TabOptionWidget|null} Tab option widget
10773 */
10774 OO.ui.CardLayout.prototype.getTabItem = function () {
10775 return this.tabItem;
10776 };
10777
10778 /**
10779 * Set or unset the tab item.
10780 *
10781 * Specify a {@link OO.ui.TabOptionWidget tab option} to set it,
10782 * or `null` to clear the tab item. To customize the tab item itself (e.g., to set a label or tab
10783 * level), use #setupTabItem instead of this method.
10784 *
10785 * @param {OO.ui.TabOptionWidget|null} tabItem Tab option widget, null to clear
10786 * @chainable
10787 */
10788 OO.ui.CardLayout.prototype.setTabItem = function ( tabItem ) {
10789 this.tabItem = tabItem || null;
10790 if ( tabItem ) {
10791 this.setupTabItem();
10792 }
10793 return this;
10794 };
10795
10796 /**
10797 * Set up the tab item.
10798 *
10799 * Use this method to customize the tab item (e.g., to add a label or tab level). To set or unset
10800 * the tab item itself (with a {@link OO.ui.TabOptionWidget tab option} or `null`), use
10801 * the #setTabItem method instead.
10802 *
10803 * @param {OO.ui.TabOptionWidget} tabItem Tab option widget to set up
10804 * @chainable
10805 */
10806 OO.ui.CardLayout.prototype.setupTabItem = function () {
10807 if ( this.label ) {
10808 this.tabItem.setLabel( this.label );
10809 }
10810 return this;
10811 };
10812
10813 /**
10814 * Set the card to its 'active' state.
10815 *
10816 * Cards become active when they are shown in a index layout that is configured to display only one card at a time. Additional
10817 * CSS is applied to the tab item to reflect the card's active state. Outside of the index
10818 * context, setting the active state on a card does nothing.
10819 *
10820 * @param {boolean} value Card is active
10821 * @fires active
10822 */
10823 OO.ui.CardLayout.prototype.setActive = function ( active ) {
10824 active = !!active;
10825
10826 if ( active !== this.active ) {
10827 this.active = active;
10828 this.$element.toggleClass( 'oo-ui-cardLayout-active', this.active );
10829 this.emit( 'active', this.active );
10830 }
10831 };
10832
10833 /**
10834 * PageLayouts are used within {@link OO.ui.BookletLayout booklet layouts} to create pages that users can select and display
10835 * from the booklet's optional {@link OO.ui.OutlineSelectWidget outline} navigation. Pages are usually not instantiated directly,
10836 * rather extended to include the required content and functionality.
10837 *
10838 * Each page must have a unique symbolic name, which is passed to the constructor. In addition, the page's outline
10839 * item is customized (with a label, outline level, etc.) using the #setupOutlineItem method. See
10840 * {@link OO.ui.BookletLayout BookletLayout} for an example.
10841 *
10842 * @class
10843 * @extends OO.ui.PanelLayout
10844 *
10845 * @constructor
10846 * @param {string} name Unique symbolic name of page
10847 * @param {Object} [config] Configuration options
10848 */
10849 OO.ui.PageLayout = function OoUiPageLayout( name, config ) {
10850 // Allow passing positional parameters inside the config object
10851 if ( OO.isPlainObject( name ) && config === undefined ) {
10852 config = name;
10853 name = config.name;
10854 }
10855
10856 // Configuration initialization
10857 config = $.extend( { scrollable: true }, config );
10858
10859 // Parent constructor
10860 OO.ui.PageLayout.parent.call( this, config );
10861
10862 // Properties
10863 this.name = name;
10864 this.outlineItem = null;
10865 this.active = false;
10866
10867 // Initialization
10868 this.$element.addClass( 'oo-ui-pageLayout' );
10869 };
10870
10871 /* Setup */
10872
10873 OO.inheritClass( OO.ui.PageLayout, OO.ui.PanelLayout );
10874
10875 /* Events */
10876
10877 /**
10878 * An 'active' event is emitted when the page becomes active. Pages become active when they are
10879 * shown in a booklet layout that is configured to display only one page at a time.
10880 *
10881 * @event active
10882 * @param {boolean} active Page is active
10883 */
10884
10885 /* Methods */
10886
10887 /**
10888 * Get the symbolic name of the page.
10889 *
10890 * @return {string} Symbolic name of page
10891 */
10892 OO.ui.PageLayout.prototype.getName = function () {
10893 return this.name;
10894 };
10895
10896 /**
10897 * Check if page is active.
10898 *
10899 * Pages become active when they are shown in a {@link OO.ui.BookletLayout booklet layout} that is configured to display
10900 * only one page at a time. Additional CSS is applied to the page's outline item to reflect the active state.
10901 *
10902 * @return {boolean} Page is active
10903 */
10904 OO.ui.PageLayout.prototype.isActive = function () {
10905 return this.active;
10906 };
10907
10908 /**
10909 * Get outline item.
10910 *
10911 * The outline item allows users to access the page from the booklet's outline
10912 * navigation. The outline item itself can be customized (with a label, level, etc.) using the #setupOutlineItem method.
10913 *
10914 * @return {OO.ui.OutlineOptionWidget|null} Outline option widget
10915 */
10916 OO.ui.PageLayout.prototype.getOutlineItem = function () {
10917 return this.outlineItem;
10918 };
10919
10920 /**
10921 * Set or unset the outline item.
10922 *
10923 * Specify an {@link OO.ui.OutlineOptionWidget outline option} to set it,
10924 * or `null` to clear the outline item. To customize the outline item itself (e.g., to set a label or outline
10925 * level), use #setupOutlineItem instead of this method.
10926 *
10927 * @param {OO.ui.OutlineOptionWidget|null} outlineItem Outline option widget, null to clear
10928 * @chainable
10929 */
10930 OO.ui.PageLayout.prototype.setOutlineItem = function ( outlineItem ) {
10931 this.outlineItem = outlineItem || null;
10932 if ( outlineItem ) {
10933 this.setupOutlineItem();
10934 }
10935 return this;
10936 };
10937
10938 /**
10939 * Set up the outline item.
10940 *
10941 * Use this method to customize the outline item (e.g., to add a label or outline level). To set or unset
10942 * the outline item itself (with an {@link OO.ui.OutlineOptionWidget outline option} or `null`), use
10943 * the #setOutlineItem method instead.
10944 *
10945 * @param {OO.ui.OutlineOptionWidget} outlineItem Outline option widget to set up
10946 * @chainable
10947 */
10948 OO.ui.PageLayout.prototype.setupOutlineItem = function () {
10949 return this;
10950 };
10951
10952 /**
10953 * Set the page to its 'active' state.
10954 *
10955 * Pages become active when they are shown in a booklet layout that is configured to display only one page at a time. Additional
10956 * CSS is applied to the outline item to reflect the page's active state. Outside of the booklet
10957 * context, setting the active state on a page does nothing.
10958 *
10959 * @param {boolean} value Page is active
10960 * @fires active
10961 */
10962 OO.ui.PageLayout.prototype.setActive = function ( active ) {
10963 active = !!active;
10964
10965 if ( active !== this.active ) {
10966 this.active = active;
10967 this.$element.toggleClass( 'oo-ui-pageLayout-active', active );
10968 this.emit( 'active', this.active );
10969 }
10970 };
10971
10972 /**
10973 * StackLayouts contain a series of {@link OO.ui.PanelLayout panel layouts}. By default, only one panel is displayed
10974 * at a time, though the stack layout can also be configured to show all contained panels, one after another,
10975 * by setting the #continuous option to 'true'.
10976 *
10977 * @example
10978 * // A stack layout with two panels, configured to be displayed continously
10979 * var myStack = new OO.ui.StackLayout( {
10980 * items: [
10981 * new OO.ui.PanelLayout( {
10982 * $content: $( '<p>Panel One</p>' ),
10983 * padded: true,
10984 * framed: true
10985 * } ),
10986 * new OO.ui.PanelLayout( {
10987 * $content: $( '<p>Panel Two</p>' ),
10988 * padded: true,
10989 * framed: true
10990 * } )
10991 * ],
10992 * continuous: true
10993 * } );
10994 * $( 'body' ).append( myStack.$element );
10995 *
10996 * @class
10997 * @extends OO.ui.PanelLayout
10998 * @mixins OO.ui.mixin.GroupElement
10999 *
11000 * @constructor
11001 * @param {Object} [config] Configuration options
11002 * @cfg {boolean} [continuous=false] Show all panels, one after another. By default, only one panel is displayed at a time.
11003 * @cfg {OO.ui.Layout[]} [items] Panel layouts to add to the stack layout.
11004 */
11005 OO.ui.StackLayout = function OoUiStackLayout( config ) {
11006 // Configuration initialization
11007 config = $.extend( { scrollable: true }, config );
11008
11009 // Parent constructor
11010 OO.ui.StackLayout.parent.call( this, config );
11011
11012 // Mixin constructors
11013 OO.ui.mixin.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) );
11014
11015 // Properties
11016 this.currentItem = null;
11017 this.continuous = !!config.continuous;
11018
11019 // Initialization
11020 this.$element.addClass( 'oo-ui-stackLayout' );
11021 if ( this.continuous ) {
11022 this.$element.addClass( 'oo-ui-stackLayout-continuous' );
11023 }
11024 if ( Array.isArray( config.items ) ) {
11025 this.addItems( config.items );
11026 }
11027 };
11028
11029 /* Setup */
11030
11031 OO.inheritClass( OO.ui.StackLayout, OO.ui.PanelLayout );
11032 OO.mixinClass( OO.ui.StackLayout, OO.ui.mixin.GroupElement );
11033
11034 /* Events */
11035
11036 /**
11037 * A 'set' event is emitted when panels are {@link #addItems added}, {@link #removeItems removed},
11038 * {@link #clearItems cleared} or {@link #setItem displayed}.
11039 *
11040 * @event set
11041 * @param {OO.ui.Layout|null} item Current panel or `null` if no panel is shown
11042 */
11043
11044 /* Methods */
11045
11046 /**
11047 * Get the current panel.
11048 *
11049 * @return {OO.ui.Layout|null}
11050 */
11051 OO.ui.StackLayout.prototype.getCurrentItem = function () {
11052 return this.currentItem;
11053 };
11054
11055 /**
11056 * Unset the current item.
11057 *
11058 * @private
11059 * @param {OO.ui.StackLayout} layout
11060 * @fires set
11061 */
11062 OO.ui.StackLayout.prototype.unsetCurrentItem = function () {
11063 var prevItem = this.currentItem;
11064 if ( prevItem === null ) {
11065 return;
11066 }
11067
11068 this.currentItem = null;
11069 this.emit( 'set', null );
11070 };
11071
11072 /**
11073 * Add panel layouts to the stack layout.
11074 *
11075 * Panels will be added to the end of the stack layout array unless the optional index parameter specifies a different
11076 * insertion point. Adding a panel that is already in the stack will move it to the end of the array or the point specified
11077 * by the index.
11078 *
11079 * @param {OO.ui.Layout[]} items Panels to add
11080 * @param {number} [index] Index of the insertion point
11081 * @chainable
11082 */
11083 OO.ui.StackLayout.prototype.addItems = function ( items, index ) {
11084 // Update the visibility
11085 this.updateHiddenState( items, this.currentItem );
11086
11087 // Mixin method
11088 OO.ui.mixin.GroupElement.prototype.addItems.call( this, items, index );
11089
11090 if ( !this.currentItem && items.length ) {
11091 this.setItem( items[ 0 ] );
11092 }
11093
11094 return this;
11095 };
11096
11097 /**
11098 * Remove the specified panels from the stack layout.
11099 *
11100 * Removed panels are detached from the DOM, not removed, so that they may be reused. To remove all panels,
11101 * you may wish to use the #clearItems method instead.
11102 *
11103 * @param {OO.ui.Layout[]} items Panels to remove
11104 * @chainable
11105 * @fires set
11106 */
11107 OO.ui.StackLayout.prototype.removeItems = function ( items ) {
11108 // Mixin method
11109 OO.ui.mixin.GroupElement.prototype.removeItems.call( this, items );
11110
11111 if ( items.indexOf( this.currentItem ) !== -1 ) {
11112 if ( this.items.length ) {
11113 this.setItem( this.items[ 0 ] );
11114 } else {
11115 this.unsetCurrentItem();
11116 }
11117 }
11118
11119 return this;
11120 };
11121
11122 /**
11123 * Clear all panels from the stack layout.
11124 *
11125 * Cleared panels are detached from the DOM, not removed, so that they may be reused. To remove only
11126 * a subset of panels, use the #removeItems method.
11127 *
11128 * @chainable
11129 * @fires set
11130 */
11131 OO.ui.StackLayout.prototype.clearItems = function () {
11132 this.unsetCurrentItem();
11133 OO.ui.mixin.GroupElement.prototype.clearItems.call( this );
11134
11135 return this;
11136 };
11137
11138 /**
11139 * Show the specified panel.
11140 *
11141 * If another panel is currently displayed, it will be hidden.
11142 *
11143 * @param {OO.ui.Layout} item Panel to show
11144 * @chainable
11145 * @fires set
11146 */
11147 OO.ui.StackLayout.prototype.setItem = function ( item ) {
11148 if ( item !== this.currentItem ) {
11149 this.updateHiddenState( this.items, item );
11150
11151 if ( this.items.indexOf( item ) !== -1 ) {
11152 this.currentItem = item;
11153 this.emit( 'set', item );
11154 } else {
11155 this.unsetCurrentItem();
11156 }
11157 }
11158
11159 return this;
11160 };
11161
11162 /**
11163 * Update the visibility of all items in case of non-continuous view.
11164 *
11165 * Ensure all items are hidden except for the selected one.
11166 * This method does nothing when the stack is continuous.
11167 *
11168 * @private
11169 * @param {OO.ui.Layout[]} items Item list iterate over
11170 * @param {OO.ui.Layout} [selectedItem] Selected item to show
11171 */
11172 OO.ui.StackLayout.prototype.updateHiddenState = function ( items, selectedItem ) {
11173 var i, len;
11174
11175 if ( !this.continuous ) {
11176 for ( i = 0, len = items.length; i < len; i++ ) {
11177 if ( !selectedItem || selectedItem !== items[ i ] ) {
11178 items[ i ].$element.addClass( 'oo-ui-element-hidden' );
11179 }
11180 }
11181 if ( selectedItem ) {
11182 selectedItem.$element.removeClass( 'oo-ui-element-hidden' );
11183 }
11184 }
11185 };
11186
11187 /**
11188 * HorizontalLayout arranges its contents in a single line (using `display: inline-block` for its
11189 * items), with small margins between them. Convenient when you need to put a number of block-level
11190 * widgets on a single line next to each other.
11191 *
11192 * Note that inline elements, such as OO.ui.ButtonWidgets, do not need this wrapper.
11193 *
11194 * @example
11195 * // HorizontalLayout with a text input and a label
11196 * var layout = new OO.ui.HorizontalLayout( {
11197 * items: [
11198 * new OO.ui.LabelWidget( { label: 'Label' } ),
11199 * new OO.ui.TextInputWidget( { value: 'Text' } )
11200 * ]
11201 * } );
11202 * $( 'body' ).append( layout.$element );
11203 *
11204 * @class
11205 * @extends OO.ui.Layout
11206 * @mixins OO.ui.mixin.GroupElement
11207 *
11208 * @constructor
11209 * @param {Object} [config] Configuration options
11210 * @cfg {OO.ui.Widget[]|OO.ui.Layout[]} [items] Widgets or other layouts to add to the layout.
11211 */
11212 OO.ui.HorizontalLayout = function OoUiHorizontalLayout( config ) {
11213 // Configuration initialization
11214 config = config || {};
11215
11216 // Parent constructor
11217 OO.ui.HorizontalLayout.parent.call( this, config );
11218
11219 // Mixin constructors
11220 OO.ui.mixin.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) );
11221
11222 // Initialization
11223 this.$element.addClass( 'oo-ui-horizontalLayout' );
11224 if ( Array.isArray( config.items ) ) {
11225 this.addItems( config.items );
11226 }
11227 };
11228
11229 /* Setup */
11230
11231 OO.inheritClass( OO.ui.HorizontalLayout, OO.ui.Layout );
11232 OO.mixinClass( OO.ui.HorizontalLayout, OO.ui.mixin.GroupElement );
11233
11234 /**
11235 * BarToolGroups are one of three types of {@link OO.ui.ToolGroup toolgroups} that are used to
11236 * create {@link OO.ui.Toolbar toolbars} (the other types of groups are {@link OO.ui.MenuToolGroup MenuToolGroup}
11237 * and {@link OO.ui.ListToolGroup ListToolGroup}). The {@link OO.ui.Tool tools} in a BarToolGroup are
11238 * displayed by icon in a single row. The title of the tool is displayed when users move the mouse over
11239 * the tool.
11240 *
11241 * BarToolGroups are created by a {@link OO.ui.ToolGroupFactory tool group factory} when the toolbar is
11242 * set up.
11243 *
11244 * @example
11245 * // Example of a BarToolGroup with two tools
11246 * var toolFactory = new OO.ui.ToolFactory();
11247 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
11248 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
11249 *
11250 * // We will be placing status text in this element when tools are used
11251 * var $area = $( '<p>' ).text( 'Example of a BarToolGroup with two tools.' );
11252 *
11253 * // Define the tools that we're going to place in our toolbar
11254 *
11255 * // Create a class inheriting from OO.ui.Tool
11256 * function PictureTool() {
11257 * PictureTool.parent.apply( this, arguments );
11258 * }
11259 * OO.inheritClass( PictureTool, OO.ui.Tool );
11260 * // Each tool must have a 'name' (used as an internal identifier, see later) and at least one
11261 * // of 'icon' and 'title' (displayed icon and text).
11262 * PictureTool.static.name = 'picture';
11263 * PictureTool.static.icon = 'picture';
11264 * PictureTool.static.title = 'Insert picture';
11265 * // Defines the action that will happen when this tool is selected (clicked).
11266 * PictureTool.prototype.onSelect = function () {
11267 * $area.text( 'Picture tool clicked!' );
11268 * // Never display this tool as "active" (selected).
11269 * this.setActive( false );
11270 * };
11271 * // Make this tool available in our toolFactory and thus our toolbar
11272 * toolFactory.register( PictureTool );
11273 *
11274 * // This is a PopupTool. Rather than having a custom 'onSelect' action, it will display a
11275 * // little popup window (a PopupWidget).
11276 * function HelpTool( toolGroup, config ) {
11277 * OO.ui.PopupTool.call( this, toolGroup, $.extend( { popup: {
11278 * padded: true,
11279 * label: 'Help',
11280 * head: true
11281 * } }, config ) );
11282 * this.popup.$body.append( '<p>I am helpful!</p>' );
11283 * }
11284 * OO.inheritClass( HelpTool, OO.ui.PopupTool );
11285 * HelpTool.static.name = 'help';
11286 * HelpTool.static.icon = 'help';
11287 * HelpTool.static.title = 'Help';
11288 * toolFactory.register( HelpTool );
11289 *
11290 * // Finally define which tools and in what order appear in the toolbar. Each tool may only be
11291 * // used once (but not all defined tools must be used).
11292 * toolbar.setup( [
11293 * {
11294 * // 'bar' tool groups display tools by icon only
11295 * type: 'bar',
11296 * include: [ 'picture', 'help' ]
11297 * }
11298 * ] );
11299 *
11300 * // Create some UI around the toolbar and place it in the document
11301 * var frame = new OO.ui.PanelLayout( {
11302 * expanded: false,
11303 * framed: true
11304 * } );
11305 * var contentFrame = new OO.ui.PanelLayout( {
11306 * expanded: false,
11307 * padded: true
11308 * } );
11309 * frame.$element.append(
11310 * toolbar.$element,
11311 * contentFrame.$element.append( $area )
11312 * );
11313 * $( 'body' ).append( frame.$element );
11314 *
11315 * // Here is where the toolbar is actually built. This must be done after inserting it into the
11316 * // document.
11317 * toolbar.initialize();
11318 *
11319 * For more information about how to add tools to a bar tool group, please see {@link OO.ui.ToolGroup toolgroup}.
11320 * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki][1].
11321 *
11322 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
11323 *
11324 * @class
11325 * @extends OO.ui.ToolGroup
11326 *
11327 * @constructor
11328 * @param {OO.ui.Toolbar} toolbar
11329 * @param {Object} [config] Configuration options
11330 */
11331 OO.ui.BarToolGroup = function OoUiBarToolGroup( toolbar, config ) {
11332 // Allow passing positional parameters inside the config object
11333 if ( OO.isPlainObject( toolbar ) && config === undefined ) {
11334 config = toolbar;
11335 toolbar = config.toolbar;
11336 }
11337
11338 // Parent constructor
11339 OO.ui.BarToolGroup.parent.call( this, toolbar, config );
11340
11341 // Initialization
11342 this.$element.addClass( 'oo-ui-barToolGroup' );
11343 };
11344
11345 /* Setup */
11346
11347 OO.inheritClass( OO.ui.BarToolGroup, OO.ui.ToolGroup );
11348
11349 /* Static Properties */
11350
11351 OO.ui.BarToolGroup.static.titleTooltips = true;
11352
11353 OO.ui.BarToolGroup.static.accelTooltips = true;
11354
11355 OO.ui.BarToolGroup.static.name = 'bar';
11356
11357 /**
11358 * PopupToolGroup is an abstract base class used by both {@link OO.ui.MenuToolGroup MenuToolGroup}
11359 * and {@link OO.ui.ListToolGroup ListToolGroup} to provide a popup--an overlaid menu or list of tools with an
11360 * optional icon and label. This class can be used for other base classes that also use this functionality.
11361 *
11362 * @abstract
11363 * @class
11364 * @extends OO.ui.ToolGroup
11365 * @mixins OO.ui.mixin.IconElement
11366 * @mixins OO.ui.mixin.IndicatorElement
11367 * @mixins OO.ui.mixin.LabelElement
11368 * @mixins OO.ui.mixin.TitledElement
11369 * @mixins OO.ui.mixin.ClippableElement
11370 * @mixins OO.ui.mixin.TabIndexedElement
11371 *
11372 * @constructor
11373 * @param {OO.ui.Toolbar} toolbar
11374 * @param {Object} [config] Configuration options
11375 * @cfg {string} [header] Text to display at the top of the popup
11376 */
11377 OO.ui.PopupToolGroup = function OoUiPopupToolGroup( toolbar, config ) {
11378 // Allow passing positional parameters inside the config object
11379 if ( OO.isPlainObject( toolbar ) && config === undefined ) {
11380 config = toolbar;
11381 toolbar = config.toolbar;
11382 }
11383
11384 // Configuration initialization
11385 config = config || {};
11386
11387 // Parent constructor
11388 OO.ui.PopupToolGroup.parent.call( this, toolbar, config );
11389
11390 // Properties
11391 this.active = false;
11392 this.dragging = false;
11393 this.onBlurHandler = this.onBlur.bind( this );
11394 this.$handle = $( '<span>' );
11395
11396 // Mixin constructors
11397 OO.ui.mixin.IconElement.call( this, config );
11398 OO.ui.mixin.IndicatorElement.call( this, config );
11399 OO.ui.mixin.LabelElement.call( this, config );
11400 OO.ui.mixin.TitledElement.call( this, config );
11401 OO.ui.mixin.ClippableElement.call( this, $.extend( {}, config, { $clippable: this.$group } ) );
11402 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$handle } ) );
11403
11404 // Events
11405 this.$handle.on( {
11406 keydown: this.onHandleMouseKeyDown.bind( this ),
11407 keyup: this.onHandleMouseKeyUp.bind( this ),
11408 mousedown: this.onHandleMouseKeyDown.bind( this ),
11409 mouseup: this.onHandleMouseKeyUp.bind( this )
11410 } );
11411
11412 // Initialization
11413 this.$handle
11414 .addClass( 'oo-ui-popupToolGroup-handle' )
11415 .append( this.$icon, this.$label, this.$indicator );
11416 // If the pop-up should have a header, add it to the top of the toolGroup.
11417 // Note: If this feature is useful for other widgets, we could abstract it into an
11418 // OO.ui.HeaderedElement mixin constructor.
11419 if ( config.header !== undefined ) {
11420 this.$group
11421 .prepend( $( '<span>' )
11422 .addClass( 'oo-ui-popupToolGroup-header' )
11423 .text( config.header )
11424 );
11425 }
11426 this.$element
11427 .addClass( 'oo-ui-popupToolGroup' )
11428 .prepend( this.$handle );
11429 };
11430
11431 /* Setup */
11432
11433 OO.inheritClass( OO.ui.PopupToolGroup, OO.ui.ToolGroup );
11434 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.mixin.IconElement );
11435 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.mixin.IndicatorElement );
11436 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.mixin.LabelElement );
11437 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.mixin.TitledElement );
11438 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.mixin.ClippableElement );
11439 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.mixin.TabIndexedElement );
11440
11441 /* Methods */
11442
11443 /**
11444 * @inheritdoc
11445 */
11446 OO.ui.PopupToolGroup.prototype.setDisabled = function () {
11447 // Parent method
11448 OO.ui.PopupToolGroup.parent.prototype.setDisabled.apply( this, arguments );
11449
11450 if ( this.isDisabled() && this.isElementAttached() ) {
11451 this.setActive( false );
11452 }
11453 };
11454
11455 /**
11456 * Handle focus being lost.
11457 *
11458 * The event is actually generated from a mouseup/keyup, so it is not a normal blur event object.
11459 *
11460 * @protected
11461 * @param {jQuery.Event} e Mouse up or key up event
11462 */
11463 OO.ui.PopupToolGroup.prototype.onBlur = function ( e ) {
11464 // Only deactivate when clicking outside the dropdown element
11465 if ( $( e.target ).closest( '.oo-ui-popupToolGroup' )[ 0 ] !== this.$element[ 0 ] ) {
11466 this.setActive( false );
11467 }
11468 };
11469
11470 /**
11471 * @inheritdoc
11472 */
11473 OO.ui.PopupToolGroup.prototype.onMouseKeyUp = function ( e ) {
11474 // Only close toolgroup when a tool was actually selected
11475 if (
11476 !this.isDisabled() && this.pressed && this.pressed === this.getTargetTool( e ) &&
11477 ( e.which === 1 || e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
11478 ) {
11479 this.setActive( false );
11480 }
11481 return OO.ui.PopupToolGroup.parent.prototype.onMouseKeyUp.call( this, e );
11482 };
11483
11484 /**
11485 * Handle mouse up and key up events.
11486 *
11487 * @protected
11488 * @param {jQuery.Event} e Mouse up or key up event
11489 */
11490 OO.ui.PopupToolGroup.prototype.onHandleMouseKeyUp = function ( e ) {
11491 if (
11492 !this.isDisabled() &&
11493 ( e.which === 1 || e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
11494 ) {
11495 return false;
11496 }
11497 };
11498
11499 /**
11500 * Handle mouse down and key down events.
11501 *
11502 * @protected
11503 * @param {jQuery.Event} e Mouse down or key down event
11504 */
11505 OO.ui.PopupToolGroup.prototype.onHandleMouseKeyDown = function ( e ) {
11506 if (
11507 !this.isDisabled() &&
11508 ( e.which === 1 || e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
11509 ) {
11510 this.setActive( !this.active );
11511 return false;
11512 }
11513 };
11514
11515 /**
11516 * Switch into 'active' mode.
11517 *
11518 * When active, the popup is visible. A mouseup event anywhere in the document will trigger
11519 * deactivation.
11520 */
11521 OO.ui.PopupToolGroup.prototype.setActive = function ( value ) {
11522 var containerWidth, containerLeft;
11523 value = !!value;
11524 if ( this.active !== value ) {
11525 this.active = value;
11526 if ( value ) {
11527 OO.ui.addCaptureEventListener( this.getElementDocument(), 'mouseup', this.onBlurHandler );
11528 OO.ui.addCaptureEventListener( this.getElementDocument(), 'keyup', this.onBlurHandler );
11529
11530 this.$clippable.css( 'left', '' );
11531 // Try anchoring the popup to the left first
11532 this.$element.addClass( 'oo-ui-popupToolGroup-active oo-ui-popupToolGroup-left' );
11533 this.toggleClipping( true );
11534 if ( this.isClippedHorizontally() ) {
11535 // Anchoring to the left caused the popup to clip, so anchor it to the right instead
11536 this.toggleClipping( false );
11537 this.$element
11538 .removeClass( 'oo-ui-popupToolGroup-left' )
11539 .addClass( 'oo-ui-popupToolGroup-right' );
11540 this.toggleClipping( true );
11541 }
11542 if ( this.isClippedHorizontally() ) {
11543 // Anchoring to the right also caused the popup to clip, so just make it fill the container
11544 containerWidth = this.$clippableScrollableContainer.width();
11545 containerLeft = this.$clippableScrollableContainer.offset().left;
11546
11547 this.toggleClipping( false );
11548 this.$element.removeClass( 'oo-ui-popupToolGroup-right' );
11549
11550 this.$clippable.css( {
11551 left: -( this.$element.offset().left - containerLeft ),
11552 width: containerWidth
11553 } );
11554 }
11555 } else {
11556 OO.ui.removeCaptureEventListener( this.getElementDocument(), 'mouseup', this.onBlurHandler );
11557 OO.ui.removeCaptureEventListener( this.getElementDocument(), 'keyup', this.onBlurHandler );
11558 this.$element.removeClass(
11559 'oo-ui-popupToolGroup-active oo-ui-popupToolGroup-left oo-ui-popupToolGroup-right'
11560 );
11561 this.toggleClipping( false );
11562 }
11563 }
11564 };
11565
11566 /**
11567 * ListToolGroups are one of three types of {@link OO.ui.ToolGroup toolgroups} that are used to
11568 * create {@link OO.ui.Toolbar toolbars} (the other types of groups are {@link OO.ui.MenuToolGroup MenuToolGroup}
11569 * and {@link OO.ui.BarToolGroup BarToolGroup}). The {@link OO.ui.Tool tools} in a ListToolGroup are displayed
11570 * by label in a dropdown menu. The title of the tool is used as the label text. The menu itself can be configured
11571 * with a label, icon, indicator, header, and title.
11572 *
11573 * ListToolGroups can be configured to be expanded and collapsed. Collapsed lists will have a ‘More’ option that
11574 * users can select to see the full list of tools. If a collapsed toolgroup is expanded, a ‘Fewer’ option permits
11575 * users to collapse the list again.
11576 *
11577 * ListToolGroups are created by a {@link OO.ui.ToolGroupFactory toolgroup factory} when the toolbar is set up. The factory
11578 * requires the ListToolGroup's symbolic name, 'list', which is specified along with the other configurations. For more
11579 * information about how to add tools to a ListToolGroup, please see {@link OO.ui.ToolGroup toolgroup}.
11580 *
11581 * @example
11582 * // Example of a ListToolGroup
11583 * var toolFactory = new OO.ui.ToolFactory();
11584 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
11585 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
11586 *
11587 * // Configure and register two tools
11588 * function SettingsTool() {
11589 * SettingsTool.parent.apply( this, arguments );
11590 * }
11591 * OO.inheritClass( SettingsTool, OO.ui.Tool );
11592 * SettingsTool.static.name = 'settings';
11593 * SettingsTool.static.icon = 'settings';
11594 * SettingsTool.static.title = 'Change settings';
11595 * SettingsTool.prototype.onSelect = function () {
11596 * this.setActive( false );
11597 * };
11598 * toolFactory.register( SettingsTool );
11599 * // Register two more tools, nothing interesting here
11600 * function StuffTool() {
11601 * StuffTool.parent.apply( this, arguments );
11602 * }
11603 * OO.inheritClass( StuffTool, OO.ui.Tool );
11604 * StuffTool.static.name = 'stuff';
11605 * StuffTool.static.icon = 'ellipsis';
11606 * StuffTool.static.title = 'Change the world';
11607 * StuffTool.prototype.onSelect = function () {
11608 * this.setActive( false );
11609 * };
11610 * toolFactory.register( StuffTool );
11611 * toolbar.setup( [
11612 * {
11613 * // Configurations for list toolgroup.
11614 * type: 'list',
11615 * label: 'ListToolGroup',
11616 * indicator: 'down',
11617 * icon: 'picture',
11618 * title: 'This is the title, displayed when user moves the mouse over the list toolgroup',
11619 * header: 'This is the header',
11620 * include: [ 'settings', 'stuff' ],
11621 * allowCollapse: ['stuff']
11622 * }
11623 * ] );
11624 *
11625 * // Create some UI around the toolbar and place it in the document
11626 * var frame = new OO.ui.PanelLayout( {
11627 * expanded: false,
11628 * framed: true
11629 * } );
11630 * frame.$element.append(
11631 * toolbar.$element
11632 * );
11633 * $( 'body' ).append( frame.$element );
11634 * // Build the toolbar. This must be done after the toolbar has been appended to the document.
11635 * toolbar.initialize();
11636 *
11637 * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki][1].
11638 *
11639 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
11640 *
11641 * @class
11642 * @extends OO.ui.PopupToolGroup
11643 *
11644 * @constructor
11645 * @param {OO.ui.Toolbar} toolbar
11646 * @param {Object} [config] Configuration options
11647 * @cfg {Array} [allowCollapse] Allow the specified tools to be collapsed. By default, collapsible tools
11648 * will only be displayed if users click the ‘More’ option displayed at the bottom of the list. If
11649 * the list is expanded, a ‘Fewer’ option permits users to collapse the list again. Any tools that
11650 * are included in the toolgroup, but are not designated as collapsible, will always be displayed.
11651 * To open a collapsible list in its expanded state, set #expanded to 'true'.
11652 * @cfg {Array} [forceExpand] Expand the specified tools. All other tools will be designated as collapsible.
11653 * Unless #expanded is set to true, the collapsible tools will be collapsed when the list is first opened.
11654 * @cfg {boolean} [expanded=false] Expand collapsible tools. This config is only relevant if tools have
11655 * been designated as collapsible. When expanded is set to true, all tools in the group will be displayed
11656 * when the list is first opened. Users can collapse the list with a ‘Fewer’ option at the bottom.
11657 */
11658 OO.ui.ListToolGroup = function OoUiListToolGroup( toolbar, config ) {
11659 // Allow passing positional parameters inside the config object
11660 if ( OO.isPlainObject( toolbar ) && config === undefined ) {
11661 config = toolbar;
11662 toolbar = config.toolbar;
11663 }
11664
11665 // Configuration initialization
11666 config = config || {};
11667
11668 // Properties (must be set before parent constructor, which calls #populate)
11669 this.allowCollapse = config.allowCollapse;
11670 this.forceExpand = config.forceExpand;
11671 this.expanded = config.expanded !== undefined ? config.expanded : false;
11672 this.collapsibleTools = [];
11673
11674 // Parent constructor
11675 OO.ui.ListToolGroup.parent.call( this, toolbar, config );
11676
11677 // Initialization
11678 this.$element.addClass( 'oo-ui-listToolGroup' );
11679 };
11680
11681 /* Setup */
11682
11683 OO.inheritClass( OO.ui.ListToolGroup, OO.ui.PopupToolGroup );
11684
11685 /* Static Properties */
11686
11687 OO.ui.ListToolGroup.static.name = 'list';
11688
11689 /* Methods */
11690
11691 /**
11692 * @inheritdoc
11693 */
11694 OO.ui.ListToolGroup.prototype.populate = function () {
11695 var i, len, allowCollapse = [];
11696
11697 OO.ui.ListToolGroup.parent.prototype.populate.call( this );
11698
11699 // Update the list of collapsible tools
11700 if ( this.allowCollapse !== undefined ) {
11701 allowCollapse = this.allowCollapse;
11702 } else if ( this.forceExpand !== undefined ) {
11703 allowCollapse = OO.simpleArrayDifference( Object.keys( this.tools ), this.forceExpand );
11704 }
11705
11706 this.collapsibleTools = [];
11707 for ( i = 0, len = allowCollapse.length; i < len; i++ ) {
11708 if ( this.tools[ allowCollapse[ i ] ] !== undefined ) {
11709 this.collapsibleTools.push( this.tools[ allowCollapse[ i ] ] );
11710 }
11711 }
11712
11713 // Keep at the end, even when tools are added
11714 this.$group.append( this.getExpandCollapseTool().$element );
11715
11716 this.getExpandCollapseTool().toggle( this.collapsibleTools.length !== 0 );
11717 this.updateCollapsibleState();
11718 };
11719
11720 OO.ui.ListToolGroup.prototype.getExpandCollapseTool = function () {
11721 var ExpandCollapseTool;
11722 if ( this.expandCollapseTool === undefined ) {
11723 ExpandCollapseTool = function () {
11724 ExpandCollapseTool.parent.apply( this, arguments );
11725 };
11726
11727 OO.inheritClass( ExpandCollapseTool, OO.ui.Tool );
11728
11729 ExpandCollapseTool.prototype.onSelect = function () {
11730 this.toolGroup.expanded = !this.toolGroup.expanded;
11731 this.toolGroup.updateCollapsibleState();
11732 this.setActive( false );
11733 };
11734 ExpandCollapseTool.prototype.onUpdateState = function () {
11735 // Do nothing. Tool interface requires an implementation of this function.
11736 };
11737
11738 ExpandCollapseTool.static.name = 'more-fewer';
11739
11740 this.expandCollapseTool = new ExpandCollapseTool( this );
11741 }
11742 return this.expandCollapseTool;
11743 };
11744
11745 /**
11746 * @inheritdoc
11747 */
11748 OO.ui.ListToolGroup.prototype.onMouseKeyUp = function ( e ) {
11749 // Do not close the popup when the user wants to show more/fewer tools
11750 if (
11751 $( e.target ).closest( '.oo-ui-tool-name-more-fewer' ).length &&
11752 ( e.which === 1 || e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
11753 ) {
11754 // HACK: Prevent the popup list from being hidden. Skip the PopupToolGroup implementation (which
11755 // hides the popup list when a tool is selected) and call ToolGroup's implementation directly.
11756 return OO.ui.ListToolGroup.parent.parent.prototype.onMouseKeyUp.call( this, e );
11757 } else {
11758 return OO.ui.ListToolGroup.parent.prototype.onMouseKeyUp.call( this, e );
11759 }
11760 };
11761
11762 OO.ui.ListToolGroup.prototype.updateCollapsibleState = function () {
11763 var i, len;
11764
11765 this.getExpandCollapseTool()
11766 .setIcon( this.expanded ? 'collapse' : 'expand' )
11767 .setTitle( OO.ui.msg( this.expanded ? 'ooui-toolgroup-collapse' : 'ooui-toolgroup-expand' ) );
11768
11769 for ( i = 0, len = this.collapsibleTools.length; i < len; i++ ) {
11770 this.collapsibleTools[ i ].toggle( this.expanded );
11771 }
11772 };
11773
11774 /**
11775 * MenuToolGroups are one of three types of {@link OO.ui.ToolGroup toolgroups} that are used to
11776 * create {@link OO.ui.Toolbar toolbars} (the other types of groups are {@link OO.ui.BarToolGroup BarToolGroup}
11777 * and {@link OO.ui.ListToolGroup ListToolGroup}). MenuToolGroups contain selectable {@link OO.ui.Tool tools},
11778 * which are displayed by label in a dropdown menu. The tool's title is used as the label text, and the
11779 * menu label is updated to reflect which tool or tools are currently selected. If no tools are selected,
11780 * the menu label is empty. The menu can be configured with an indicator, icon, title, and/or header.
11781 *
11782 * MenuToolGroups are created by a {@link OO.ui.ToolGroupFactory tool group factory} when the toolbar
11783 * is set up. Note that all tools must define an {@link OO.ui.Tool#onUpdateState onUpdateState} method if
11784 * a MenuToolGroup is used.
11785 *
11786 * @example
11787 * // Example of a MenuToolGroup
11788 * var toolFactory = new OO.ui.ToolFactory();
11789 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
11790 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
11791 *
11792 * // We will be placing status text in this element when tools are used
11793 * var $area = $( '<p>' ).text( 'An example of a MenuToolGroup. Select a tool from the dropdown menu.' );
11794 *
11795 * // Define the tools that we're going to place in our toolbar
11796 *
11797 * function SettingsTool() {
11798 * SettingsTool.parent.apply( this, arguments );
11799 * this.reallyActive = false;
11800 * }
11801 * OO.inheritClass( SettingsTool, OO.ui.Tool );
11802 * SettingsTool.static.name = 'settings';
11803 * SettingsTool.static.icon = 'settings';
11804 * SettingsTool.static.title = 'Change settings';
11805 * SettingsTool.prototype.onSelect = function () {
11806 * $area.text( 'Settings tool clicked!' );
11807 * // Toggle the active state on each click
11808 * this.reallyActive = !this.reallyActive;
11809 * this.setActive( this.reallyActive );
11810 * // To update the menu label
11811 * this.toolbar.emit( 'updateState' );
11812 * };
11813 * SettingsTool.prototype.onUpdateState = function () {
11814 * };
11815 * toolFactory.register( SettingsTool );
11816 *
11817 * function StuffTool() {
11818 * StuffTool.parent.apply( this, arguments );
11819 * this.reallyActive = false;
11820 * }
11821 * OO.inheritClass( StuffTool, OO.ui.Tool );
11822 * StuffTool.static.name = 'stuff';
11823 * StuffTool.static.icon = 'ellipsis';
11824 * StuffTool.static.title = 'More stuff';
11825 * StuffTool.prototype.onSelect = function () {
11826 * $area.text( 'More stuff tool clicked!' );
11827 * // Toggle the active state on each click
11828 * this.reallyActive = !this.reallyActive;
11829 * this.setActive( this.reallyActive );
11830 * // To update the menu label
11831 * this.toolbar.emit( 'updateState' );
11832 * };
11833 * StuffTool.prototype.onUpdateState = function () {
11834 * };
11835 * toolFactory.register( StuffTool );
11836 *
11837 * // Finally define which tools and in what order appear in the toolbar. Each tool may only be
11838 * // used once (but not all defined tools must be used).
11839 * toolbar.setup( [
11840 * {
11841 * type: 'menu',
11842 * header: 'This is the (optional) header',
11843 * title: 'This is the (optional) title',
11844 * indicator: 'down',
11845 * include: [ 'settings', 'stuff' ]
11846 * }
11847 * ] );
11848 *
11849 * // Create some UI around the toolbar and place it in the document
11850 * var frame = new OO.ui.PanelLayout( {
11851 * expanded: false,
11852 * framed: true
11853 * } );
11854 * var contentFrame = new OO.ui.PanelLayout( {
11855 * expanded: false,
11856 * padded: true
11857 * } );
11858 * frame.$element.append(
11859 * toolbar.$element,
11860 * contentFrame.$element.append( $area )
11861 * );
11862 * $( 'body' ).append( frame.$element );
11863 *
11864 * // Here is where the toolbar is actually built. This must be done after inserting it into the
11865 * // document.
11866 * toolbar.initialize();
11867 * toolbar.emit( 'updateState' );
11868 *
11869 * For more information about how to add tools to a MenuToolGroup, please see {@link OO.ui.ToolGroup toolgroup}.
11870 * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki] [1].
11871 *
11872 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
11873 *
11874 * @class
11875 * @extends OO.ui.PopupToolGroup
11876 *
11877 * @constructor
11878 * @param {OO.ui.Toolbar} toolbar
11879 * @param {Object} [config] Configuration options
11880 */
11881 OO.ui.MenuToolGroup = function OoUiMenuToolGroup( toolbar, config ) {
11882 // Allow passing positional parameters inside the config object
11883 if ( OO.isPlainObject( toolbar ) && config === undefined ) {
11884 config = toolbar;
11885 toolbar = config.toolbar;
11886 }
11887
11888 // Configuration initialization
11889 config = config || {};
11890
11891 // Parent constructor
11892 OO.ui.MenuToolGroup.parent.call( this, toolbar, config );
11893
11894 // Events
11895 this.toolbar.connect( this, { updateState: 'onUpdateState' } );
11896
11897 // Initialization
11898 this.$element.addClass( 'oo-ui-menuToolGroup' );
11899 };
11900
11901 /* Setup */
11902
11903 OO.inheritClass( OO.ui.MenuToolGroup, OO.ui.PopupToolGroup );
11904
11905 /* Static Properties */
11906
11907 OO.ui.MenuToolGroup.static.name = 'menu';
11908
11909 /* Methods */
11910
11911 /**
11912 * Handle the toolbar state being updated.
11913 *
11914 * When the state changes, the title of each active item in the menu will be joined together and
11915 * used as a label for the group. The label will be empty if none of the items are active.
11916 *
11917 * @private
11918 */
11919 OO.ui.MenuToolGroup.prototype.onUpdateState = function () {
11920 var name,
11921 labelTexts = [];
11922
11923 for ( name in this.tools ) {
11924 if ( this.tools[ name ].isActive() ) {
11925 labelTexts.push( this.tools[ name ].getTitle() );
11926 }
11927 }
11928
11929 this.setLabel( labelTexts.join( ', ' ) || ' ' );
11930 };
11931
11932 /**
11933 * Popup tools open a popup window when they are selected from the {@link OO.ui.Toolbar toolbar}. Each popup tool is configured
11934 * 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
11935 * an #onSelect or #onUpdateState method, as these methods have been implemented already.
11936 *
11937 * // Example of a popup tool. When selected, a popup tool displays
11938 * // a popup window.
11939 * function HelpTool( toolGroup, config ) {
11940 * OO.ui.PopupTool.call( this, toolGroup, $.extend( { popup: {
11941 * padded: true,
11942 * label: 'Help',
11943 * head: true
11944 * } }, config ) );
11945 * this.popup.$body.append( '<p>I am helpful!</p>' );
11946 * };
11947 * OO.inheritClass( HelpTool, OO.ui.PopupTool );
11948 * HelpTool.static.name = 'help';
11949 * HelpTool.static.icon = 'help';
11950 * HelpTool.static.title = 'Help';
11951 * toolFactory.register( HelpTool );
11952 *
11953 * For an example of a toolbar that contains a popup tool, see {@link OO.ui.Toolbar toolbars}. For more information about
11954 * toolbars in genreral, please see the [OOjs UI documentation on MediaWiki][1].
11955 *
11956 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
11957 *
11958 * @abstract
11959 * @class
11960 * @extends OO.ui.Tool
11961 * @mixins OO.ui.mixin.PopupElement
11962 *
11963 * @constructor
11964 * @param {OO.ui.ToolGroup} toolGroup
11965 * @param {Object} [config] Configuration options
11966 */
11967 OO.ui.PopupTool = function OoUiPopupTool( toolGroup, config ) {
11968 // Allow passing positional parameters inside the config object
11969 if ( OO.isPlainObject( toolGroup ) && config === undefined ) {
11970 config = toolGroup;
11971 toolGroup = config.toolGroup;
11972 }
11973
11974 // Parent constructor
11975 OO.ui.PopupTool.parent.call( this, toolGroup, config );
11976
11977 // Mixin constructors
11978 OO.ui.mixin.PopupElement.call( this, config );
11979
11980 // Initialization
11981 this.$element
11982 .addClass( 'oo-ui-popupTool' )
11983 .append( this.popup.$element );
11984 };
11985
11986 /* Setup */
11987
11988 OO.inheritClass( OO.ui.PopupTool, OO.ui.Tool );
11989 OO.mixinClass( OO.ui.PopupTool, OO.ui.mixin.PopupElement );
11990
11991 /* Methods */
11992
11993 /**
11994 * Handle the tool being selected.
11995 *
11996 * @inheritdoc
11997 */
11998 OO.ui.PopupTool.prototype.onSelect = function () {
11999 if ( !this.isDisabled() ) {
12000 this.popup.toggle();
12001 }
12002 this.setActive( false );
12003 return false;
12004 };
12005
12006 /**
12007 * Handle the toolbar state being updated.
12008 *
12009 * @inheritdoc
12010 */
12011 OO.ui.PopupTool.prototype.onUpdateState = function () {
12012 this.setActive( false );
12013 };
12014
12015 /**
12016 * A ToolGroupTool is a special sort of tool that can contain other {@link OO.ui.Tool tools}
12017 * and {@link OO.ui.ToolGroup toolgroups}. The ToolGroupTool was specifically designed to be used
12018 * inside a {@link OO.ui.BarToolGroup bar} toolgroup to provide access to additional tools from
12019 * the bar item. Included tools will be displayed in a dropdown {@link OO.ui.ListToolGroup list}
12020 * when the ToolGroupTool is selected.
12021 *
12022 * // Example: ToolGroupTool with two nested tools, 'setting1' and 'setting2', defined elsewhere.
12023 *
12024 * function SettingsTool() {
12025 * SettingsTool.parent.apply( this, arguments );
12026 * };
12027 * OO.inheritClass( SettingsTool, OO.ui.ToolGroupTool );
12028 * SettingsTool.static.name = 'settings';
12029 * SettingsTool.static.title = 'Change settings';
12030 * SettingsTool.static.groupConfig = {
12031 * icon: 'settings',
12032 * label: 'ToolGroupTool',
12033 * include: [ 'setting1', 'setting2' ]
12034 * };
12035 * toolFactory.register( SettingsTool );
12036 *
12037 * For more information, please see the [OOjs UI documentation on MediaWiki][1].
12038 *
12039 * Please note that this implementation is subject to change per [T74159] [2].
12040 *
12041 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars#ToolGroupTool
12042 * [2]: https://phabricator.wikimedia.org/T74159
12043 *
12044 * @abstract
12045 * @class
12046 * @extends OO.ui.Tool
12047 *
12048 * @constructor
12049 * @param {OO.ui.ToolGroup} toolGroup
12050 * @param {Object} [config] Configuration options
12051 */
12052 OO.ui.ToolGroupTool = function OoUiToolGroupTool( toolGroup, config ) {
12053 // Allow passing positional parameters inside the config object
12054 if ( OO.isPlainObject( toolGroup ) && config === undefined ) {
12055 config = toolGroup;
12056 toolGroup = config.toolGroup;
12057 }
12058
12059 // Parent constructor
12060 OO.ui.ToolGroupTool.parent.call( this, toolGroup, config );
12061
12062 // Properties
12063 this.innerToolGroup = this.createGroup( this.constructor.static.groupConfig );
12064
12065 // Events
12066 this.innerToolGroup.connect( this, { disable: 'onToolGroupDisable' } );
12067
12068 // Initialization
12069 this.$link.remove();
12070 this.$element
12071 .addClass( 'oo-ui-toolGroupTool' )
12072 .append( this.innerToolGroup.$element );
12073 };
12074
12075 /* Setup */
12076
12077 OO.inheritClass( OO.ui.ToolGroupTool, OO.ui.Tool );
12078
12079 /* Static Properties */
12080
12081 /**
12082 * Toolgroup configuration.
12083 *
12084 * The toolgroup configuration consists of the tools to include, as well as an icon and label
12085 * to use for the bar item. Tools can be included by symbolic name, group, or with the
12086 * wildcard selector. Please see {@link OO.ui.ToolGroup toolgroup} for more information.
12087 *
12088 * @property {Object.<string,Array>}
12089 */
12090 OO.ui.ToolGroupTool.static.groupConfig = {};
12091
12092 /* Methods */
12093
12094 /**
12095 * Handle the tool being selected.
12096 *
12097 * @inheritdoc
12098 */
12099 OO.ui.ToolGroupTool.prototype.onSelect = function () {
12100 this.innerToolGroup.setActive( !this.innerToolGroup.active );
12101 return false;
12102 };
12103
12104 /**
12105 * Synchronize disabledness state of the tool with the inner toolgroup.
12106 *
12107 * @private
12108 * @param {boolean} disabled Element is disabled
12109 */
12110 OO.ui.ToolGroupTool.prototype.onToolGroupDisable = function ( disabled ) {
12111 this.setDisabled( disabled );
12112 };
12113
12114 /**
12115 * Handle the toolbar state being updated.
12116 *
12117 * @inheritdoc
12118 */
12119 OO.ui.ToolGroupTool.prototype.onUpdateState = function () {
12120 this.setActive( false );
12121 };
12122
12123 /**
12124 * Build a {@link OO.ui.ToolGroup toolgroup} from the specified configuration.
12125 *
12126 * @param {Object.<string,Array>} group Toolgroup configuration. Please see {@link OO.ui.ToolGroup toolgroup} for
12127 * more information.
12128 * @return {OO.ui.ListToolGroup}
12129 */
12130 OO.ui.ToolGroupTool.prototype.createGroup = function ( group ) {
12131 if ( group.include === '*' ) {
12132 // Apply defaults to catch-all groups
12133 if ( group.label === undefined ) {
12134 group.label = OO.ui.msg( 'ooui-toolbar-more' );
12135 }
12136 }
12137
12138 return this.toolbar.getToolGroupFactory().create( 'list', this.toolbar, group );
12139 };
12140
12141 /**
12142 * Mixin for OO.ui.Widget subclasses to provide OO.ui.mixin.GroupElement.
12143 *
12144 * Use together with OO.ui.mixin.ItemWidget to make disabled state inheritable.
12145 *
12146 * @private
12147 * @abstract
12148 * @class
12149 * @extends OO.ui.mixin.GroupElement
12150 *
12151 * @constructor
12152 * @param {Object} [config] Configuration options
12153 */
12154 OO.ui.mixin.GroupWidget = function OoUiMixinGroupWidget( config ) {
12155 // Parent constructor
12156 OO.ui.mixin.GroupWidget.parent.call( this, config );
12157 };
12158
12159 /* Setup */
12160
12161 OO.inheritClass( OO.ui.mixin.GroupWidget, OO.ui.mixin.GroupElement );
12162
12163 /* Methods */
12164
12165 /**
12166 * Set the disabled state of the widget.
12167 *
12168 * This will also update the disabled state of child widgets.
12169 *
12170 * @param {boolean} disabled Disable widget
12171 * @chainable
12172 */
12173 OO.ui.mixin.GroupWidget.prototype.setDisabled = function ( disabled ) {
12174 var i, len;
12175
12176 // Parent method
12177 // Note: Calling #setDisabled this way assumes this is mixed into an OO.ui.Widget
12178 OO.ui.Widget.prototype.setDisabled.call( this, disabled );
12179
12180 // During construction, #setDisabled is called before the OO.ui.mixin.GroupElement constructor
12181 if ( this.items ) {
12182 for ( i = 0, len = this.items.length; i < len; i++ ) {
12183 this.items[ i ].updateDisabled();
12184 }
12185 }
12186
12187 return this;
12188 };
12189
12190 /**
12191 * Mixin for widgets used as items in widgets that mix in OO.ui.mixin.GroupWidget.
12192 *
12193 * Item widgets have a reference to a OO.ui.mixin.GroupWidget while they are attached to the group. This
12194 * allows bidirectional communication.
12195 *
12196 * Use together with OO.ui.mixin.GroupWidget to make disabled state inheritable.
12197 *
12198 * @private
12199 * @abstract
12200 * @class
12201 *
12202 * @constructor
12203 */
12204 OO.ui.mixin.ItemWidget = function OoUiMixinItemWidget() {
12205 //
12206 };
12207
12208 /* Methods */
12209
12210 /**
12211 * Check if widget is disabled.
12212 *
12213 * Checks parent if present, making disabled state inheritable.
12214 *
12215 * @return {boolean} Widget is disabled
12216 */
12217 OO.ui.mixin.ItemWidget.prototype.isDisabled = function () {
12218 return this.disabled ||
12219 ( this.elementGroup instanceof OO.ui.Widget && this.elementGroup.isDisabled() );
12220 };
12221
12222 /**
12223 * Set group element is in.
12224 *
12225 * @param {OO.ui.mixin.GroupElement|null} group Group element, null if none
12226 * @chainable
12227 */
12228 OO.ui.mixin.ItemWidget.prototype.setElementGroup = function ( group ) {
12229 // Parent method
12230 // Note: Calling #setElementGroup this way assumes this is mixed into an OO.ui.Element
12231 OO.ui.Element.prototype.setElementGroup.call( this, group );
12232
12233 // Initialize item disabled states
12234 this.updateDisabled();
12235
12236 return this;
12237 };
12238
12239 /**
12240 * OutlineControlsWidget is a set of controls for an {@link OO.ui.OutlineSelectWidget outline select widget}.
12241 * Controls include moving items up and down, removing items, and adding different kinds of items.
12242 *
12243 * **Currently, this class is only used by {@link OO.ui.BookletLayout booklet layouts}.**
12244 *
12245 * @class
12246 * @extends OO.ui.Widget
12247 * @mixins OO.ui.mixin.GroupElement
12248 * @mixins OO.ui.mixin.IconElement
12249 *
12250 * @constructor
12251 * @param {OO.ui.OutlineSelectWidget} outline Outline to control
12252 * @param {Object} [config] Configuration options
12253 * @cfg {Object} [abilities] List of abilties
12254 * @cfg {boolean} [abilities.move=true] Allow moving movable items
12255 * @cfg {boolean} [abilities.remove=true] Allow removing removable items
12256 */
12257 OO.ui.OutlineControlsWidget = function OoUiOutlineControlsWidget( outline, config ) {
12258 // Allow passing positional parameters inside the config object
12259 if ( OO.isPlainObject( outline ) && config === undefined ) {
12260 config = outline;
12261 outline = config.outline;
12262 }
12263
12264 // Configuration initialization
12265 config = $.extend( { icon: 'add' }, config );
12266
12267 // Parent constructor
12268 OO.ui.OutlineControlsWidget.parent.call( this, config );
12269
12270 // Mixin constructors
12271 OO.ui.mixin.GroupElement.call( this, config );
12272 OO.ui.mixin.IconElement.call( this, config );
12273
12274 // Properties
12275 this.outline = outline;
12276 this.$movers = $( '<div>' );
12277 this.upButton = new OO.ui.ButtonWidget( {
12278 framed: false,
12279 icon: 'collapse',
12280 title: OO.ui.msg( 'ooui-outline-control-move-up' )
12281 } );
12282 this.downButton = new OO.ui.ButtonWidget( {
12283 framed: false,
12284 icon: 'expand',
12285 title: OO.ui.msg( 'ooui-outline-control-move-down' )
12286 } );
12287 this.removeButton = new OO.ui.ButtonWidget( {
12288 framed: false,
12289 icon: 'remove',
12290 title: OO.ui.msg( 'ooui-outline-control-remove' )
12291 } );
12292 this.abilities = { move: true, remove: true };
12293
12294 // Events
12295 outline.connect( this, {
12296 select: 'onOutlineChange',
12297 add: 'onOutlineChange',
12298 remove: 'onOutlineChange'
12299 } );
12300 this.upButton.connect( this, { click: [ 'emit', 'move', -1 ] } );
12301 this.downButton.connect( this, { click: [ 'emit', 'move', 1 ] } );
12302 this.removeButton.connect( this, { click: [ 'emit', 'remove' ] } );
12303
12304 // Initialization
12305 this.$element.addClass( 'oo-ui-outlineControlsWidget' );
12306 this.$group.addClass( 'oo-ui-outlineControlsWidget-items' );
12307 this.$movers
12308 .addClass( 'oo-ui-outlineControlsWidget-movers' )
12309 .append( this.removeButton.$element, this.upButton.$element, this.downButton.$element );
12310 this.$element.append( this.$icon, this.$group, this.$movers );
12311 this.setAbilities( config.abilities || {} );
12312 };
12313
12314 /* Setup */
12315
12316 OO.inheritClass( OO.ui.OutlineControlsWidget, OO.ui.Widget );
12317 OO.mixinClass( OO.ui.OutlineControlsWidget, OO.ui.mixin.GroupElement );
12318 OO.mixinClass( OO.ui.OutlineControlsWidget, OO.ui.mixin.IconElement );
12319
12320 /* Events */
12321
12322 /**
12323 * @event move
12324 * @param {number} places Number of places to move
12325 */
12326
12327 /**
12328 * @event remove
12329 */
12330
12331 /* Methods */
12332
12333 /**
12334 * Set abilities.
12335 *
12336 * @param {Object} abilities List of abilties
12337 * @param {boolean} [abilities.move] Allow moving movable items
12338 * @param {boolean} [abilities.remove] Allow removing removable items
12339 */
12340 OO.ui.OutlineControlsWidget.prototype.setAbilities = function ( abilities ) {
12341 var ability;
12342
12343 for ( ability in this.abilities ) {
12344 if ( abilities[ ability ] !== undefined ) {
12345 this.abilities[ ability ] = !!abilities[ ability ];
12346 }
12347 }
12348
12349 this.onOutlineChange();
12350 };
12351
12352 /**
12353 * @private
12354 * Handle outline change events.
12355 */
12356 OO.ui.OutlineControlsWidget.prototype.onOutlineChange = function () {
12357 var i, len, firstMovable, lastMovable,
12358 items = this.outline.getItems(),
12359 selectedItem = this.outline.getSelectedItem(),
12360 movable = this.abilities.move && selectedItem && selectedItem.isMovable(),
12361 removable = this.abilities.remove && selectedItem && selectedItem.isRemovable();
12362
12363 if ( movable ) {
12364 i = -1;
12365 len = items.length;
12366 while ( ++i < len ) {
12367 if ( items[ i ].isMovable() ) {
12368 firstMovable = items[ i ];
12369 break;
12370 }
12371 }
12372 i = len;
12373 while ( i-- ) {
12374 if ( items[ i ].isMovable() ) {
12375 lastMovable = items[ i ];
12376 break;
12377 }
12378 }
12379 }
12380 this.upButton.setDisabled( !movable || selectedItem === firstMovable );
12381 this.downButton.setDisabled( !movable || selectedItem === lastMovable );
12382 this.removeButton.setDisabled( !removable );
12383 };
12384
12385 /**
12386 * ToggleWidget implements basic behavior of widgets with an on/off state.
12387 * Please see OO.ui.ToggleButtonWidget and OO.ui.ToggleSwitchWidget for examples.
12388 *
12389 * @abstract
12390 * @class
12391 * @extends OO.ui.Widget
12392 *
12393 * @constructor
12394 * @param {Object} [config] Configuration options
12395 * @cfg {boolean} [value=false] The toggle’s initial on/off state.
12396 * By default, the toggle is in the 'off' state.
12397 */
12398 OO.ui.ToggleWidget = function OoUiToggleWidget( config ) {
12399 // Configuration initialization
12400 config = config || {};
12401
12402 // Parent constructor
12403 OO.ui.ToggleWidget.parent.call( this, config );
12404
12405 // Properties
12406 this.value = null;
12407
12408 // Initialization
12409 this.$element.addClass( 'oo-ui-toggleWidget' );
12410 this.setValue( !!config.value );
12411 };
12412
12413 /* Setup */
12414
12415 OO.inheritClass( OO.ui.ToggleWidget, OO.ui.Widget );
12416
12417 /* Events */
12418
12419 /**
12420 * @event change
12421 *
12422 * A change event is emitted when the on/off state of the toggle changes.
12423 *
12424 * @param {boolean} value Value representing the new state of the toggle
12425 */
12426
12427 /* Methods */
12428
12429 /**
12430 * Get the value representing the toggle’s state.
12431 *
12432 * @return {boolean} The on/off state of the toggle
12433 */
12434 OO.ui.ToggleWidget.prototype.getValue = function () {
12435 return this.value;
12436 };
12437
12438 /**
12439 * Set the state of the toggle: `true` for 'on', `false' for 'off'.
12440 *
12441 * @param {boolean} value The state of the toggle
12442 * @fires change
12443 * @chainable
12444 */
12445 OO.ui.ToggleWidget.prototype.setValue = function ( value ) {
12446 value = !!value;
12447 if ( this.value !== value ) {
12448 this.value = value;
12449 this.emit( 'change', value );
12450 this.$element.toggleClass( 'oo-ui-toggleWidget-on', value );
12451 this.$element.toggleClass( 'oo-ui-toggleWidget-off', !value );
12452 this.$element.attr( 'aria-checked', value.toString() );
12453 }
12454 return this;
12455 };
12456
12457 /**
12458 * A ButtonGroupWidget groups related buttons and is used together with OO.ui.ButtonWidget and
12459 * its subclasses. Each button in a group is addressed by a unique reference. Buttons can be added,
12460 * removed, and cleared from the group.
12461 *
12462 * @example
12463 * // Example: A ButtonGroupWidget with two buttons
12464 * var button1 = new OO.ui.PopupButtonWidget( {
12465 * label: 'Select a category',
12466 * icon: 'menu',
12467 * popup: {
12468 * $content: $( '<p>List of categories...</p>' ),
12469 * padded: true,
12470 * align: 'left'
12471 * }
12472 * } );
12473 * var button2 = new OO.ui.ButtonWidget( {
12474 * label: 'Add item'
12475 * });
12476 * var buttonGroup = new OO.ui.ButtonGroupWidget( {
12477 * items: [button1, button2]
12478 * } );
12479 * $( 'body' ).append( buttonGroup.$element );
12480 *
12481 * @class
12482 * @extends OO.ui.Widget
12483 * @mixins OO.ui.mixin.GroupElement
12484 *
12485 * @constructor
12486 * @param {Object} [config] Configuration options
12487 * @cfg {OO.ui.ButtonWidget[]} [items] Buttons to add
12488 */
12489 OO.ui.ButtonGroupWidget = function OoUiButtonGroupWidget( config ) {
12490 // Configuration initialization
12491 config = config || {};
12492
12493 // Parent constructor
12494 OO.ui.ButtonGroupWidget.parent.call( this, config );
12495
12496 // Mixin constructors
12497 OO.ui.mixin.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) );
12498
12499 // Initialization
12500 this.$element.addClass( 'oo-ui-buttonGroupWidget' );
12501 if ( Array.isArray( config.items ) ) {
12502 this.addItems( config.items );
12503 }
12504 };
12505
12506 /* Setup */
12507
12508 OO.inheritClass( OO.ui.ButtonGroupWidget, OO.ui.Widget );
12509 OO.mixinClass( OO.ui.ButtonGroupWidget, OO.ui.mixin.GroupElement );
12510
12511 /**
12512 * ButtonWidget is a generic widget for buttons. A wide variety of looks,
12513 * feels, and functionality can be customized via the class’s configuration options
12514 * and methods. Please see the [OOjs UI documentation on MediaWiki] [1] for more information
12515 * and examples.
12516 *
12517 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches
12518 *
12519 * @example
12520 * // A button widget
12521 * var button = new OO.ui.ButtonWidget( {
12522 * label: 'Button with Icon',
12523 * icon: 'remove',
12524 * iconTitle: 'Remove'
12525 * } );
12526 * $( 'body' ).append( button.$element );
12527 *
12528 * NOTE: HTML form buttons should use the OO.ui.ButtonInputWidget class.
12529 *
12530 * @class
12531 * @extends OO.ui.Widget
12532 * @mixins OO.ui.mixin.ButtonElement
12533 * @mixins OO.ui.mixin.IconElement
12534 * @mixins OO.ui.mixin.IndicatorElement
12535 * @mixins OO.ui.mixin.LabelElement
12536 * @mixins OO.ui.mixin.TitledElement
12537 * @mixins OO.ui.mixin.FlaggedElement
12538 * @mixins OO.ui.mixin.TabIndexedElement
12539 * @mixins OO.ui.mixin.AccessKeyedElement
12540 *
12541 * @constructor
12542 * @param {Object} [config] Configuration options
12543 * @cfg {string} [href] Hyperlink to visit when the button is clicked.
12544 * @cfg {string} [target] The frame or window in which to open the hyperlink.
12545 * @cfg {boolean} [noFollow] Search engine traversal hint (default: true)
12546 */
12547 OO.ui.ButtonWidget = function OoUiButtonWidget( config ) {
12548 // Configuration initialization
12549 config = config || {};
12550
12551 // Parent constructor
12552 OO.ui.ButtonWidget.parent.call( this, config );
12553
12554 // Mixin constructors
12555 OO.ui.mixin.ButtonElement.call( this, config );
12556 OO.ui.mixin.IconElement.call( this, config );
12557 OO.ui.mixin.IndicatorElement.call( this, config );
12558 OO.ui.mixin.LabelElement.call( this, config );
12559 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$button } ) );
12560 OO.ui.mixin.FlaggedElement.call( this, config );
12561 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$button } ) );
12562 OO.ui.mixin.AccessKeyedElement.call( this, $.extend( {}, config, { $accessKeyed: this.$button } ) );
12563
12564 // Properties
12565 this.href = null;
12566 this.target = null;
12567 this.noFollow = false;
12568
12569 // Events
12570 this.connect( this, { disable: 'onDisable' } );
12571
12572 // Initialization
12573 this.$button.append( this.$icon, this.$label, this.$indicator );
12574 this.$element
12575 .addClass( 'oo-ui-buttonWidget' )
12576 .append( this.$button );
12577 this.setHref( config.href );
12578 this.setTarget( config.target );
12579 this.setNoFollow( config.noFollow );
12580 };
12581
12582 /* Setup */
12583
12584 OO.inheritClass( OO.ui.ButtonWidget, OO.ui.Widget );
12585 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.ButtonElement );
12586 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.IconElement );
12587 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.IndicatorElement );
12588 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.LabelElement );
12589 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.TitledElement );
12590 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.FlaggedElement );
12591 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.TabIndexedElement );
12592 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.AccessKeyedElement );
12593
12594 /* Methods */
12595
12596 /**
12597 * @inheritdoc
12598 */
12599 OO.ui.ButtonWidget.prototype.onMouseDown = function ( e ) {
12600 if ( !this.isDisabled() ) {
12601 // Remove the tab-index while the button is down to prevent the button from stealing focus
12602 this.$button.removeAttr( 'tabindex' );
12603 }
12604
12605 return OO.ui.mixin.ButtonElement.prototype.onMouseDown.call( this, e );
12606 };
12607
12608 /**
12609 * @inheritdoc
12610 */
12611 OO.ui.ButtonWidget.prototype.onMouseUp = function ( e ) {
12612 if ( !this.isDisabled() ) {
12613 // Restore the tab-index after the button is up to restore the button's accessibility
12614 this.$button.attr( 'tabindex', this.tabIndex );
12615 }
12616
12617 return OO.ui.mixin.ButtonElement.prototype.onMouseUp.call( this, e );
12618 };
12619
12620 /**
12621 * Get hyperlink location.
12622 *
12623 * @return {string} Hyperlink location
12624 */
12625 OO.ui.ButtonWidget.prototype.getHref = function () {
12626 return this.href;
12627 };
12628
12629 /**
12630 * Get hyperlink target.
12631 *
12632 * @return {string} Hyperlink target
12633 */
12634 OO.ui.ButtonWidget.prototype.getTarget = function () {
12635 return this.target;
12636 };
12637
12638 /**
12639 * Get search engine traversal hint.
12640 *
12641 * @return {boolean} Whether search engines should avoid traversing this hyperlink
12642 */
12643 OO.ui.ButtonWidget.prototype.getNoFollow = function () {
12644 return this.noFollow;
12645 };
12646
12647 /**
12648 * Set hyperlink location.
12649 *
12650 * @param {string|null} href Hyperlink location, null to remove
12651 */
12652 OO.ui.ButtonWidget.prototype.setHref = function ( href ) {
12653 href = typeof href === 'string' ? href : null;
12654 if ( href !== null ) {
12655 if ( !OO.ui.isSafeUrl( href ) ) {
12656 throw new Error( 'Potentially unsafe href provided: ' + href );
12657 }
12658
12659 }
12660
12661 if ( href !== this.href ) {
12662 this.href = href;
12663 this.updateHref();
12664 }
12665
12666 return this;
12667 };
12668
12669 /**
12670 * Update the `href` attribute, in case of changes to href or
12671 * disabled state.
12672 *
12673 * @private
12674 * @chainable
12675 */
12676 OO.ui.ButtonWidget.prototype.updateHref = function () {
12677 if ( this.href !== null && !this.isDisabled() ) {
12678 this.$button.attr( 'href', this.href );
12679 } else {
12680 this.$button.removeAttr( 'href' );
12681 }
12682
12683 return this;
12684 };
12685
12686 /**
12687 * Handle disable events.
12688 *
12689 * @private
12690 * @param {boolean} disabled Element is disabled
12691 */
12692 OO.ui.ButtonWidget.prototype.onDisable = function () {
12693 this.updateHref();
12694 };
12695
12696 /**
12697 * Set hyperlink target.
12698 *
12699 * @param {string|null} target Hyperlink target, null to remove
12700 */
12701 OO.ui.ButtonWidget.prototype.setTarget = function ( target ) {
12702 target = typeof target === 'string' ? target : null;
12703
12704 if ( target !== this.target ) {
12705 this.target = target;
12706 if ( target !== null ) {
12707 this.$button.attr( 'target', target );
12708 } else {
12709 this.$button.removeAttr( 'target' );
12710 }
12711 }
12712
12713 return this;
12714 };
12715
12716 /**
12717 * Set search engine traversal hint.
12718 *
12719 * @param {boolean} noFollow True if search engines should avoid traversing this hyperlink
12720 */
12721 OO.ui.ButtonWidget.prototype.setNoFollow = function ( noFollow ) {
12722 noFollow = typeof noFollow === 'boolean' ? noFollow : true;
12723
12724 if ( noFollow !== this.noFollow ) {
12725 this.noFollow = noFollow;
12726 if ( noFollow ) {
12727 this.$button.attr( 'rel', 'nofollow' );
12728 } else {
12729 this.$button.removeAttr( 'rel' );
12730 }
12731 }
12732
12733 return this;
12734 };
12735
12736 /**
12737 * An ActionWidget is a {@link OO.ui.ButtonWidget button widget} that executes an action.
12738 * Action widgets are used with OO.ui.ActionSet, which manages the behavior and availability
12739 * of the actions.
12740 *
12741 * Both actions and action sets are primarily used with {@link OO.ui.Dialog Dialogs}.
12742 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information
12743 * and examples.
12744 *
12745 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Action_sets
12746 *
12747 * @class
12748 * @extends OO.ui.ButtonWidget
12749 * @mixins OO.ui.mixin.PendingElement
12750 *
12751 * @constructor
12752 * @param {Object} [config] Configuration options
12753 * @cfg {string} [action] Symbolic name of the action (e.g., ‘continue’ or ‘cancel’).
12754 * @cfg {string[]} [modes] Symbolic names of the modes (e.g., ‘edit’ or ‘read’) in which the action
12755 * should be made available. See the action set's {@link OO.ui.ActionSet#setMode setMode} method
12756 * for more information about setting modes.
12757 * @cfg {boolean} [framed=false] Render the action button with a frame
12758 */
12759 OO.ui.ActionWidget = function OoUiActionWidget( config ) {
12760 // Configuration initialization
12761 config = $.extend( { framed: false }, config );
12762
12763 // Parent constructor
12764 OO.ui.ActionWidget.parent.call( this, config );
12765
12766 // Mixin constructors
12767 OO.ui.mixin.PendingElement.call( this, config );
12768
12769 // Properties
12770 this.action = config.action || '';
12771 this.modes = config.modes || [];
12772 this.width = 0;
12773 this.height = 0;
12774
12775 // Initialization
12776 this.$element.addClass( 'oo-ui-actionWidget' );
12777 };
12778
12779 /* Setup */
12780
12781 OO.inheritClass( OO.ui.ActionWidget, OO.ui.ButtonWidget );
12782 OO.mixinClass( OO.ui.ActionWidget, OO.ui.mixin.PendingElement );
12783
12784 /* Events */
12785
12786 /**
12787 * A resize event is emitted when the size of the widget changes.
12788 *
12789 * @event resize
12790 */
12791
12792 /* Methods */
12793
12794 /**
12795 * Check if the action is configured to be available in the specified `mode`.
12796 *
12797 * @param {string} mode Name of mode
12798 * @return {boolean} The action is configured with the mode
12799 */
12800 OO.ui.ActionWidget.prototype.hasMode = function ( mode ) {
12801 return this.modes.indexOf( mode ) !== -1;
12802 };
12803
12804 /**
12805 * Get the symbolic name of the action (e.g., ‘continue’ or ‘cancel’).
12806 *
12807 * @return {string}
12808 */
12809 OO.ui.ActionWidget.prototype.getAction = function () {
12810 return this.action;
12811 };
12812
12813 /**
12814 * Get the symbolic name of the mode or modes for which the action is configured to be available.
12815 *
12816 * The current mode is set with the action set's {@link OO.ui.ActionSet#setMode setMode} method.
12817 * Only actions that are configured to be avaiable in the current mode will be visible. All other actions
12818 * are hidden.
12819 *
12820 * @return {string[]}
12821 */
12822 OO.ui.ActionWidget.prototype.getModes = function () {
12823 return this.modes.slice();
12824 };
12825
12826 /**
12827 * Emit a resize event if the size has changed.
12828 *
12829 * @private
12830 * @chainable
12831 */
12832 OO.ui.ActionWidget.prototype.propagateResize = function () {
12833 var width, height;
12834
12835 if ( this.isElementAttached() ) {
12836 width = this.$element.width();
12837 height = this.$element.height();
12838
12839 if ( width !== this.width || height !== this.height ) {
12840 this.width = width;
12841 this.height = height;
12842 this.emit( 'resize' );
12843 }
12844 }
12845
12846 return this;
12847 };
12848
12849 /**
12850 * @inheritdoc
12851 */
12852 OO.ui.ActionWidget.prototype.setIcon = function () {
12853 // Mixin method
12854 OO.ui.mixin.IconElement.prototype.setIcon.apply( this, arguments );
12855 this.propagateResize();
12856
12857 return this;
12858 };
12859
12860 /**
12861 * @inheritdoc
12862 */
12863 OO.ui.ActionWidget.prototype.setLabel = function () {
12864 // Mixin method
12865 OO.ui.mixin.LabelElement.prototype.setLabel.apply( this, arguments );
12866 this.propagateResize();
12867
12868 return this;
12869 };
12870
12871 /**
12872 * @inheritdoc
12873 */
12874 OO.ui.ActionWidget.prototype.setFlags = function () {
12875 // Mixin method
12876 OO.ui.mixin.FlaggedElement.prototype.setFlags.apply( this, arguments );
12877 this.propagateResize();
12878
12879 return this;
12880 };
12881
12882 /**
12883 * @inheritdoc
12884 */
12885 OO.ui.ActionWidget.prototype.clearFlags = function () {
12886 // Mixin method
12887 OO.ui.mixin.FlaggedElement.prototype.clearFlags.apply( this, arguments );
12888 this.propagateResize();
12889
12890 return this;
12891 };
12892
12893 /**
12894 * Toggle the visibility of the action button.
12895 *
12896 * @param {boolean} [show] Show button, omit to toggle visibility
12897 * @chainable
12898 */
12899 OO.ui.ActionWidget.prototype.toggle = function () {
12900 // Parent method
12901 OO.ui.ActionWidget.parent.prototype.toggle.apply( this, arguments );
12902 this.propagateResize();
12903
12904 return this;
12905 };
12906
12907 /**
12908 * PopupButtonWidgets toggle the visibility of a contained {@link OO.ui.PopupWidget PopupWidget},
12909 * which is used to display additional information or options.
12910 *
12911 * @example
12912 * // Example of a popup button.
12913 * var popupButton = new OO.ui.PopupButtonWidget( {
12914 * label: 'Popup button with options',
12915 * icon: 'menu',
12916 * popup: {
12917 * $content: $( '<p>Additional options here.</p>' ),
12918 * padded: true,
12919 * align: 'force-left'
12920 * }
12921 * } );
12922 * // Append the button to the DOM.
12923 * $( 'body' ).append( popupButton.$element );
12924 *
12925 * @class
12926 * @extends OO.ui.ButtonWidget
12927 * @mixins OO.ui.mixin.PopupElement
12928 *
12929 * @constructor
12930 * @param {Object} [config] Configuration options
12931 */
12932 OO.ui.PopupButtonWidget = function OoUiPopupButtonWidget( config ) {
12933 // Parent constructor
12934 OO.ui.PopupButtonWidget.parent.call( this, config );
12935
12936 // Mixin constructors
12937 OO.ui.mixin.PopupElement.call( this, config );
12938
12939 // Events
12940 this.connect( this, { click: 'onAction' } );
12941
12942 // Initialization
12943 this.$element
12944 .addClass( 'oo-ui-popupButtonWidget' )
12945 .attr( 'aria-haspopup', 'true' )
12946 .append( this.popup.$element );
12947 };
12948
12949 /* Setup */
12950
12951 OO.inheritClass( OO.ui.PopupButtonWidget, OO.ui.ButtonWidget );
12952 OO.mixinClass( OO.ui.PopupButtonWidget, OO.ui.mixin.PopupElement );
12953
12954 /* Methods */
12955
12956 /**
12957 * Handle the button action being triggered.
12958 *
12959 * @private
12960 */
12961 OO.ui.PopupButtonWidget.prototype.onAction = function () {
12962 this.popup.toggle();
12963 };
12964
12965 /**
12966 * ToggleButtons are buttons that have a state (‘on’ or ‘off’) that is represented by a
12967 * Boolean value. Like other {@link OO.ui.ButtonWidget buttons}, toggle buttons can be
12968 * configured with {@link OO.ui.mixin.IconElement icons}, {@link OO.ui.mixin.IndicatorElement indicators},
12969 * {@link OO.ui.mixin.TitledElement titles}, {@link OO.ui.mixin.FlaggedElement styling flags},
12970 * and {@link OO.ui.mixin.LabelElement labels}. Please see
12971 * the [OOjs UI documentation][1] on MediaWiki for more information.
12972 *
12973 * @example
12974 * // Toggle buttons in the 'off' and 'on' state.
12975 * var toggleButton1 = new OO.ui.ToggleButtonWidget( {
12976 * label: 'Toggle Button off'
12977 * } );
12978 * var toggleButton2 = new OO.ui.ToggleButtonWidget( {
12979 * label: 'Toggle Button on',
12980 * value: true
12981 * } );
12982 * // Append the buttons to the DOM.
12983 * $( 'body' ).append( toggleButton1.$element, toggleButton2.$element );
12984 *
12985 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#Toggle_buttons
12986 *
12987 * @class
12988 * @extends OO.ui.ToggleWidget
12989 * @mixins OO.ui.mixin.ButtonElement
12990 * @mixins OO.ui.mixin.IconElement
12991 * @mixins OO.ui.mixin.IndicatorElement
12992 * @mixins OO.ui.mixin.LabelElement
12993 * @mixins OO.ui.mixin.TitledElement
12994 * @mixins OO.ui.mixin.FlaggedElement
12995 * @mixins OO.ui.mixin.TabIndexedElement
12996 *
12997 * @constructor
12998 * @param {Object} [config] Configuration options
12999 * @cfg {boolean} [value=false] The toggle button’s initial on/off
13000 * state. By default, the button is in the 'off' state.
13001 */
13002 OO.ui.ToggleButtonWidget = function OoUiToggleButtonWidget( config ) {
13003 // Configuration initialization
13004 config = config || {};
13005
13006 // Parent constructor
13007 OO.ui.ToggleButtonWidget.parent.call( this, config );
13008
13009 // Mixin constructors
13010 OO.ui.mixin.ButtonElement.call( this, config );
13011 OO.ui.mixin.IconElement.call( this, config );
13012 OO.ui.mixin.IndicatorElement.call( this, config );
13013 OO.ui.mixin.LabelElement.call( this, config );
13014 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$button } ) );
13015 OO.ui.mixin.FlaggedElement.call( this, config );
13016 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$button } ) );
13017
13018 // Events
13019 this.connect( this, { click: 'onAction' } );
13020
13021 // Initialization
13022 this.$button.append( this.$icon, this.$label, this.$indicator );
13023 this.$element
13024 .addClass( 'oo-ui-toggleButtonWidget' )
13025 .append( this.$button );
13026 };
13027
13028 /* Setup */
13029
13030 OO.inheritClass( OO.ui.ToggleButtonWidget, OO.ui.ToggleWidget );
13031 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.ButtonElement );
13032 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.IconElement );
13033 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.IndicatorElement );
13034 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.LabelElement );
13035 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.TitledElement );
13036 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.FlaggedElement );
13037 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.TabIndexedElement );
13038
13039 /* Methods */
13040
13041 /**
13042 * Handle the button action being triggered.
13043 *
13044 * @private
13045 */
13046 OO.ui.ToggleButtonWidget.prototype.onAction = function () {
13047 this.setValue( !this.value );
13048 };
13049
13050 /**
13051 * @inheritdoc
13052 */
13053 OO.ui.ToggleButtonWidget.prototype.setValue = function ( value ) {
13054 value = !!value;
13055 if ( value !== this.value ) {
13056 // Might be called from parent constructor before ButtonElement constructor
13057 if ( this.$button ) {
13058 this.$button.attr( 'aria-pressed', value.toString() );
13059 }
13060 this.setActive( value );
13061 }
13062
13063 // Parent method
13064 OO.ui.ToggleButtonWidget.parent.prototype.setValue.call( this, value );
13065
13066 return this;
13067 };
13068
13069 /**
13070 * @inheritdoc
13071 */
13072 OO.ui.ToggleButtonWidget.prototype.setButtonElement = function ( $button ) {
13073 if ( this.$button ) {
13074 this.$button.removeAttr( 'aria-pressed' );
13075 }
13076 OO.ui.mixin.ButtonElement.prototype.setButtonElement.call( this, $button );
13077 this.$button.attr( 'aria-pressed', this.value.toString() );
13078 };
13079
13080 /**
13081 * CapsuleMultiSelectWidgets are something like a {@link OO.ui.ComboBoxWidget combo box widget}
13082 * that allows for selecting multiple values.
13083 *
13084 * For more information about menus and options, please see the [OOjs UI documentation on MediaWiki][1].
13085 *
13086 * @example
13087 * // Example: A CapsuleMultiSelectWidget.
13088 * var capsule = new OO.ui.CapsuleMultiSelectWidget( {
13089 * label: 'CapsuleMultiSelectWidget',
13090 * selected: [ 'Option 1', 'Option 3' ],
13091 * menu: {
13092 * items: [
13093 * new OO.ui.MenuOptionWidget( {
13094 * data: 'Option 1',
13095 * label: 'Option One'
13096 * } ),
13097 * new OO.ui.MenuOptionWidget( {
13098 * data: 'Option 2',
13099 * label: 'Option Two'
13100 * } ),
13101 * new OO.ui.MenuOptionWidget( {
13102 * data: 'Option 3',
13103 * label: 'Option Three'
13104 * } ),
13105 * new OO.ui.MenuOptionWidget( {
13106 * data: 'Option 4',
13107 * label: 'Option Four'
13108 * } ),
13109 * new OO.ui.MenuOptionWidget( {
13110 * data: 'Option 5',
13111 * label: 'Option Five'
13112 * } )
13113 * ]
13114 * }
13115 * } );
13116 * $( 'body' ).append( capsule.$element );
13117 *
13118 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
13119 *
13120 * @class
13121 * @extends OO.ui.Widget
13122 * @mixins OO.ui.mixin.TabIndexedElement
13123 * @mixins OO.ui.mixin.GroupElement
13124 *
13125 * @constructor
13126 * @param {Object} [config] Configuration options
13127 * @cfg {boolean} [allowArbitrary=false] Allow data items to be added even if not present in the menu.
13128 * @cfg {Object} [menu] Configuration options to pass to the {@link OO.ui.MenuSelectWidget menu select widget}.
13129 * @cfg {Object} [popup] Configuration options to pass to the {@link OO.ui.PopupWidget popup widget}.
13130 * If specified, this popup will be shown instead of the menu (but the menu
13131 * will still be used for item labels and allowArbitrary=false). The widgets
13132 * in the popup should use this.addItemsFromData() or this.addItems() as necessary.
13133 * @cfg {jQuery} [$overlay] Render the menu or popup into a separate layer.
13134 * This configuration is useful in cases where the expanded menu is larger than
13135 * its containing `<div>`. The specified overlay layer is usually on top of
13136 * the containing `<div>` and has a larger area. By default, the menu uses
13137 * relative positioning.
13138 */
13139 OO.ui.CapsuleMultiSelectWidget = function OoUiCapsuleMultiSelectWidget( config ) {
13140 var $tabFocus;
13141
13142 // Configuration initialization
13143 config = config || {};
13144
13145 // Parent constructor
13146 OO.ui.CapsuleMultiSelectWidget.parent.call( this, config );
13147
13148 // Properties (must be set before mixin constructor calls)
13149 this.$input = config.popup ? null : $( '<input>' );
13150 this.$handle = $( '<div>' );
13151
13152 // Mixin constructors
13153 OO.ui.mixin.GroupElement.call( this, config );
13154 if ( config.popup ) {
13155 config.popup = $.extend( {}, config.popup, {
13156 align: 'forwards',
13157 anchor: false
13158 } );
13159 OO.ui.mixin.PopupElement.call( this, config );
13160 $tabFocus = $( '<span>' );
13161 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: $tabFocus } ) );
13162 } else {
13163 this.popup = null;
13164 $tabFocus = null;
13165 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$input } ) );
13166 }
13167 OO.ui.mixin.IndicatorElement.call( this, config );
13168 OO.ui.mixin.IconElement.call( this, config );
13169
13170 // Properties
13171 this.allowArbitrary = !!config.allowArbitrary;
13172 this.$overlay = config.$overlay || this.$element;
13173 this.menu = new OO.ui.FloatingMenuSelectWidget( $.extend(
13174 {
13175 widget: this,
13176 $input: this.$input,
13177 $container: this.$element,
13178 filterFromInput: true,
13179 disabled: this.isDisabled()
13180 },
13181 config.menu
13182 ) );
13183
13184 // Events
13185 if ( this.popup ) {
13186 $tabFocus.on( {
13187 focus: this.onFocusForPopup.bind( this )
13188 } );
13189 this.popup.$element.on( 'focusout', this.onPopupFocusOut.bind( this ) );
13190 if ( this.popup.$autoCloseIgnore ) {
13191 this.popup.$autoCloseIgnore.on( 'focusout', this.onPopupFocusOut.bind( this ) );
13192 }
13193 this.popup.connect( this, {
13194 toggle: function ( visible ) {
13195 $tabFocus.toggle( !visible );
13196 }
13197 } );
13198 } else {
13199 this.$input.on( {
13200 focus: this.onInputFocus.bind( this ),
13201 blur: this.onInputBlur.bind( this ),
13202 'propertychange change click mouseup keydown keyup input cut paste select': this.onInputChange.bind( this ),
13203 keydown: this.onKeyDown.bind( this ),
13204 keypress: this.onKeyPress.bind( this )
13205 } );
13206 }
13207 this.menu.connect( this, {
13208 choose: 'onMenuChoose',
13209 add: 'onMenuItemsChange',
13210 remove: 'onMenuItemsChange'
13211 } );
13212 this.$handle.on( {
13213 click: this.onClick.bind( this )
13214 } );
13215
13216 // Initialization
13217 if ( this.$input ) {
13218 this.$input.prop( 'disabled', this.isDisabled() );
13219 this.$input.attr( {
13220 role: 'combobox',
13221 'aria-autocomplete': 'list'
13222 } );
13223 this.$input.width( '1em' );
13224 }
13225 if ( config.data ) {
13226 this.setItemsFromData( config.data );
13227 }
13228 this.$group.addClass( 'oo-ui-capsuleMultiSelectWidget-group' );
13229 this.$handle.addClass( 'oo-ui-capsuleMultiSelectWidget-handle' )
13230 .append( this.$indicator, this.$icon, this.$group );
13231 this.$element.addClass( 'oo-ui-capsuleMultiSelectWidget' )
13232 .append( this.$handle );
13233 if ( this.popup ) {
13234 this.$handle.append( $tabFocus );
13235 this.$overlay.append( this.popup.$element );
13236 } else {
13237 this.$handle.append( this.$input );
13238 this.$overlay.append( this.menu.$element );
13239 }
13240 this.onMenuItemsChange();
13241 };
13242
13243 /* Setup */
13244
13245 OO.inheritClass( OO.ui.CapsuleMultiSelectWidget, OO.ui.Widget );
13246 OO.mixinClass( OO.ui.CapsuleMultiSelectWidget, OO.ui.mixin.GroupElement );
13247 OO.mixinClass( OO.ui.CapsuleMultiSelectWidget, OO.ui.mixin.PopupElement );
13248 OO.mixinClass( OO.ui.CapsuleMultiSelectWidget, OO.ui.mixin.TabIndexedElement );
13249 OO.mixinClass( OO.ui.CapsuleMultiSelectWidget, OO.ui.mixin.IndicatorElement );
13250 OO.mixinClass( OO.ui.CapsuleMultiSelectWidget, OO.ui.mixin.IconElement );
13251
13252 /* Events */
13253
13254 /**
13255 * @event change
13256 *
13257 * A change event is emitted when the set of selected items changes.
13258 *
13259 * @param {Mixed[]} datas Data of the now-selected items
13260 */
13261
13262 /* Methods */
13263
13264 /**
13265 * Construct a OO.ui.CapsuleItemWidget (or a subclass thereof) from given label and data.
13266 *
13267 * @protected
13268 * @param {Mixed} data Custom data of any type.
13269 * @param {string} label The label text.
13270 * @return {OO.ui.CapsuleItemWidget}
13271 */
13272 OO.ui.CapsuleMultiSelectWidget.prototype.createItemWidget = function ( data, label ) {
13273 return new OO.ui.CapsuleItemWidget( { data: data, label: label } );
13274 };
13275
13276 /**
13277 * Get the data of the items in the capsule
13278 * @return {Mixed[]}
13279 */
13280 OO.ui.CapsuleMultiSelectWidget.prototype.getItemsData = function () {
13281 return $.map( this.getItems(), function ( e ) { return e.data; } );
13282 };
13283
13284 /**
13285 * Set the items in the capsule by providing data
13286 * @chainable
13287 * @param {Mixed[]} datas
13288 * @return {OO.ui.CapsuleMultiSelectWidget}
13289 */
13290 OO.ui.CapsuleMultiSelectWidget.prototype.setItemsFromData = function ( datas ) {
13291 var widget = this,
13292 menu = this.menu,
13293 items = this.getItems();
13294
13295 $.each( datas, function ( i, data ) {
13296 var j, label,
13297 item = menu.getItemFromData( data );
13298
13299 if ( item ) {
13300 label = item.label;
13301 } else if ( widget.allowArbitrary ) {
13302 label = String( data );
13303 } else {
13304 return;
13305 }
13306
13307 item = null;
13308 for ( j = 0; j < items.length; j++ ) {
13309 if ( items[ j ].data === data && items[ j ].label === label ) {
13310 item = items[ j ];
13311 items.splice( j, 1 );
13312 break;
13313 }
13314 }
13315 if ( !item ) {
13316 item = widget.createItemWidget( data, label );
13317 }
13318 widget.addItems( [ item ], i );
13319 } );
13320
13321 if ( items.length ) {
13322 widget.removeItems( items );
13323 }
13324
13325 return this;
13326 };
13327
13328 /**
13329 * Add items to the capsule by providing their data
13330 * @chainable
13331 * @param {Mixed[]} datas
13332 * @return {OO.ui.CapsuleMultiSelectWidget}
13333 */
13334 OO.ui.CapsuleMultiSelectWidget.prototype.addItemsFromData = function ( datas ) {
13335 var widget = this,
13336 menu = this.menu,
13337 items = [];
13338
13339 $.each( datas, function ( i, data ) {
13340 var item;
13341
13342 if ( !widget.getItemFromData( data ) ) {
13343 item = menu.getItemFromData( data );
13344 if ( item ) {
13345 items.push( widget.createItemWidget( data, item.label ) );
13346 } else if ( widget.allowArbitrary ) {
13347 items.push( widget.createItemWidget( data, String( data ) ) );
13348 }
13349 }
13350 } );
13351
13352 if ( items.length ) {
13353 this.addItems( items );
13354 }
13355
13356 return this;
13357 };
13358
13359 /**
13360 * Remove items by data
13361 * @chainable
13362 * @param {Mixed[]} datas
13363 * @return {OO.ui.CapsuleMultiSelectWidget}
13364 */
13365 OO.ui.CapsuleMultiSelectWidget.prototype.removeItemsFromData = function ( datas ) {
13366 var widget = this,
13367 items = [];
13368
13369 $.each( datas, function ( i, data ) {
13370 var item = widget.getItemFromData( data );
13371 if ( item ) {
13372 items.push( item );
13373 }
13374 } );
13375
13376 if ( items.length ) {
13377 this.removeItems( items );
13378 }
13379
13380 return this;
13381 };
13382
13383 /**
13384 * @inheritdoc
13385 */
13386 OO.ui.CapsuleMultiSelectWidget.prototype.addItems = function ( items ) {
13387 var same, i, l,
13388 oldItems = this.items.slice();
13389
13390 OO.ui.mixin.GroupElement.prototype.addItems.call( this, items );
13391
13392 if ( this.items.length !== oldItems.length ) {
13393 same = false;
13394 } else {
13395 same = true;
13396 for ( i = 0, l = oldItems.length; same && i < l; i++ ) {
13397 same = same && this.items[ i ] === oldItems[ i ];
13398 }
13399 }
13400 if ( !same ) {
13401 this.emit( 'change', this.getItemsData() );
13402 }
13403
13404 return this;
13405 };
13406
13407 /**
13408 * @inheritdoc
13409 */
13410 OO.ui.CapsuleMultiSelectWidget.prototype.removeItems = function ( items ) {
13411 var same, i, l,
13412 oldItems = this.items.slice();
13413
13414 OO.ui.mixin.GroupElement.prototype.removeItems.call( this, items );
13415
13416 if ( this.items.length !== oldItems.length ) {
13417 same = false;
13418 } else {
13419 same = true;
13420 for ( i = 0, l = oldItems.length; same && i < l; i++ ) {
13421 same = same && this.items[ i ] === oldItems[ i ];
13422 }
13423 }
13424 if ( !same ) {
13425 this.emit( 'change', this.getItemsData() );
13426 }
13427
13428 return this;
13429 };
13430
13431 /**
13432 * @inheritdoc
13433 */
13434 OO.ui.CapsuleMultiSelectWidget.prototype.clearItems = function () {
13435 if ( this.items.length ) {
13436 OO.ui.mixin.GroupElement.prototype.clearItems.call( this );
13437 this.emit( 'change', this.getItemsData() );
13438 }
13439 return this;
13440 };
13441
13442 /**
13443 * Get the capsule widget's menu.
13444 * @return {OO.ui.MenuSelectWidget} Menu widget
13445 */
13446 OO.ui.CapsuleMultiSelectWidget.prototype.getMenu = function () {
13447 return this.menu;
13448 };
13449
13450 /**
13451 * Handle focus events
13452 *
13453 * @private
13454 * @param {jQuery.Event} event
13455 */
13456 OO.ui.CapsuleMultiSelectWidget.prototype.onInputFocus = function () {
13457 if ( !this.isDisabled() ) {
13458 this.menu.toggle( true );
13459 }
13460 };
13461
13462 /**
13463 * Handle blur events
13464 *
13465 * @private
13466 * @param {jQuery.Event} event
13467 */
13468 OO.ui.CapsuleMultiSelectWidget.prototype.onInputBlur = function () {
13469 if ( this.allowArbitrary && this.$input.val().trim() !== '' ) {
13470 this.addItemsFromData( [ this.$input.val() ] );
13471 }
13472 this.clearInput();
13473 };
13474
13475 /**
13476 * Handle focus events
13477 *
13478 * @private
13479 * @param {jQuery.Event} event
13480 */
13481 OO.ui.CapsuleMultiSelectWidget.prototype.onFocusForPopup = function () {
13482 if ( !this.isDisabled() ) {
13483 this.popup.setSize( this.$handle.width() );
13484 this.popup.toggle( true );
13485 this.popup.$element.find( '*' )
13486 .filter( function () { return OO.ui.isFocusableElement( $( this ), true ); } )
13487 .first()
13488 .focus();
13489 }
13490 };
13491
13492 /**
13493 * Handles popup focus out events.
13494 *
13495 * @private
13496 * @param {Event} e Focus out event
13497 */
13498 OO.ui.CapsuleMultiSelectWidget.prototype.onPopupFocusOut = function () {
13499 var widget = this.popup;
13500
13501 setTimeout( function () {
13502 if (
13503 widget.isVisible() &&
13504 !OO.ui.contains( widget.$element[ 0 ], document.activeElement, true ) &&
13505 ( !widget.$autoCloseIgnore || !widget.$autoCloseIgnore.has( document.activeElement ).length )
13506 ) {
13507 widget.toggle( false );
13508 }
13509 } );
13510 };
13511
13512 /**
13513 * Handle mouse click events.
13514 *
13515 * @private
13516 * @param {jQuery.Event} e Mouse click event
13517 */
13518 OO.ui.CapsuleMultiSelectWidget.prototype.onClick = function ( e ) {
13519 if ( e.which === 1 ) {
13520 this.focus();
13521 return false;
13522 }
13523 };
13524
13525 /**
13526 * Handle key press events.
13527 *
13528 * @private
13529 * @param {jQuery.Event} e Key press event
13530 */
13531 OO.ui.CapsuleMultiSelectWidget.prototype.onKeyPress = function ( e ) {
13532 var item;
13533
13534 if ( !this.isDisabled() ) {
13535 if ( e.which === OO.ui.Keys.ESCAPE ) {
13536 this.clearInput();
13537 return false;
13538 }
13539
13540 if ( !this.popup ) {
13541 this.menu.toggle( true );
13542 if ( e.which === OO.ui.Keys.ENTER ) {
13543 item = this.menu.getItemFromLabel( this.$input.val(), true );
13544 if ( item ) {
13545 this.addItemsFromData( [ item.data ] );
13546 this.clearInput();
13547 } else if ( this.allowArbitrary && this.$input.val().trim() !== '' ) {
13548 this.addItemsFromData( [ this.$input.val() ] );
13549 this.clearInput();
13550 }
13551 return false;
13552 }
13553
13554 // Make sure the input gets resized.
13555 setTimeout( this.onInputChange.bind( this ), 0 );
13556 }
13557 }
13558 };
13559
13560 /**
13561 * Handle key down events.
13562 *
13563 * @private
13564 * @param {jQuery.Event} e Key down event
13565 */
13566 OO.ui.CapsuleMultiSelectWidget.prototype.onKeyDown = function ( e ) {
13567 if ( !this.isDisabled() ) {
13568 // 'keypress' event is not triggered for Backspace
13569 if ( e.keyCode === OO.ui.Keys.BACKSPACE && this.$input.val() === '' ) {
13570 if ( this.items.length ) {
13571 this.removeItems( this.items.slice( -1 ) );
13572 }
13573 return false;
13574 }
13575 }
13576 };
13577
13578 /**
13579 * Handle input change events.
13580 *
13581 * @private
13582 * @param {jQuery.Event} e Event of some sort
13583 */
13584 OO.ui.CapsuleMultiSelectWidget.prototype.onInputChange = function () {
13585 if ( !this.isDisabled() ) {
13586 this.$input.width( this.$input.val().length + 'em' );
13587 }
13588 };
13589
13590 /**
13591 * Handle menu choose events.
13592 *
13593 * @private
13594 * @param {OO.ui.OptionWidget} item Chosen item
13595 */
13596 OO.ui.CapsuleMultiSelectWidget.prototype.onMenuChoose = function ( item ) {
13597 if ( item && item.isVisible() ) {
13598 this.addItemsFromData( [ item.getData() ] );
13599 this.clearInput();
13600 }
13601 };
13602
13603 /**
13604 * Handle menu item change events.
13605 *
13606 * @private
13607 */
13608 OO.ui.CapsuleMultiSelectWidget.prototype.onMenuItemsChange = function () {
13609 this.setItemsFromData( this.getItemsData() );
13610 this.$element.toggleClass( 'oo-ui-capsuleMultiSelectWidget-empty', this.menu.isEmpty() );
13611 };
13612
13613 /**
13614 * Clear the input field
13615 * @private
13616 */
13617 OO.ui.CapsuleMultiSelectWidget.prototype.clearInput = function () {
13618 if ( this.$input ) {
13619 this.$input.val( '' );
13620 this.$input.width( '1em' );
13621 }
13622 if ( this.popup ) {
13623 this.popup.toggle( false );
13624 }
13625 this.menu.toggle( false );
13626 this.menu.selectItem();
13627 this.menu.highlightItem();
13628 };
13629
13630 /**
13631 * @inheritdoc
13632 */
13633 OO.ui.CapsuleMultiSelectWidget.prototype.setDisabled = function ( disabled ) {
13634 var i, len;
13635
13636 // Parent method
13637 OO.ui.CapsuleMultiSelectWidget.parent.prototype.setDisabled.call( this, disabled );
13638
13639 if ( this.$input ) {
13640 this.$input.prop( 'disabled', this.isDisabled() );
13641 }
13642 if ( this.menu ) {
13643 this.menu.setDisabled( this.isDisabled() );
13644 }
13645 if ( this.popup ) {
13646 this.popup.setDisabled( this.isDisabled() );
13647 }
13648
13649 if ( this.items ) {
13650 for ( i = 0, len = this.items.length; i < len; i++ ) {
13651 this.items[ i ].updateDisabled();
13652 }
13653 }
13654
13655 return this;
13656 };
13657
13658 /**
13659 * Focus the widget
13660 * @chainable
13661 * @return {OO.ui.CapsuleMultiSelectWidget}
13662 */
13663 OO.ui.CapsuleMultiSelectWidget.prototype.focus = function () {
13664 if ( !this.isDisabled() ) {
13665 if ( this.popup ) {
13666 this.popup.setSize( this.$handle.width() );
13667 this.popup.toggle( true );
13668 this.popup.$element.find( '*' )
13669 .filter( function () { return OO.ui.isFocusableElement( $( this ), true ); } )
13670 .first()
13671 .focus();
13672 } else {
13673 this.menu.toggle( true );
13674 this.$input.focus();
13675 }
13676 }
13677 return this;
13678 };
13679
13680 /**
13681 * CapsuleItemWidgets are used within a {@link OO.ui.CapsuleMultiSelectWidget
13682 * CapsuleMultiSelectWidget} to display the selected items.
13683 *
13684 * @class
13685 * @extends OO.ui.Widget
13686 * @mixins OO.ui.mixin.ItemWidget
13687 * @mixins OO.ui.mixin.IndicatorElement
13688 * @mixins OO.ui.mixin.LabelElement
13689 * @mixins OO.ui.mixin.FlaggedElement
13690 * @mixins OO.ui.mixin.TabIndexedElement
13691 *
13692 * @constructor
13693 * @param {Object} [config] Configuration options
13694 */
13695 OO.ui.CapsuleItemWidget = function OoUiCapsuleItemWidget( config ) {
13696 // Configuration initialization
13697 config = config || {};
13698
13699 // Parent constructor
13700 OO.ui.CapsuleItemWidget.parent.call( this, config );
13701
13702 // Properties (must be set before mixin constructor calls)
13703 this.$indicator = $( '<span>' );
13704
13705 // Mixin constructors
13706 OO.ui.mixin.ItemWidget.call( this );
13707 OO.ui.mixin.IndicatorElement.call( this, $.extend( {}, config, { $indicator: this.$indicator, indicator: 'clear' } ) );
13708 OO.ui.mixin.LabelElement.call( this, config );
13709 OO.ui.mixin.FlaggedElement.call( this, config );
13710 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$indicator } ) );
13711
13712 // Events
13713 this.$indicator.on( {
13714 keydown: this.onCloseKeyDown.bind( this ),
13715 click: this.onCloseClick.bind( this )
13716 } );
13717
13718 // Initialization
13719 this.$element
13720 .addClass( 'oo-ui-capsuleItemWidget' )
13721 .append( this.$indicator, this.$label );
13722 };
13723
13724 /* Setup */
13725
13726 OO.inheritClass( OO.ui.CapsuleItemWidget, OO.ui.Widget );
13727 OO.mixinClass( OO.ui.CapsuleItemWidget, OO.ui.mixin.ItemWidget );
13728 OO.mixinClass( OO.ui.CapsuleItemWidget, OO.ui.mixin.IndicatorElement );
13729 OO.mixinClass( OO.ui.CapsuleItemWidget, OO.ui.mixin.LabelElement );
13730 OO.mixinClass( OO.ui.CapsuleItemWidget, OO.ui.mixin.FlaggedElement );
13731 OO.mixinClass( OO.ui.CapsuleItemWidget, OO.ui.mixin.TabIndexedElement );
13732
13733 /* Methods */
13734
13735 /**
13736 * Handle close icon clicks
13737 * @param {jQuery.Event} event
13738 */
13739 OO.ui.CapsuleItemWidget.prototype.onCloseClick = function () {
13740 var element = this.getElementGroup();
13741
13742 if ( !this.isDisabled() && element && $.isFunction( element.removeItems ) ) {
13743 element.removeItems( [ this ] );
13744 element.focus();
13745 }
13746 };
13747
13748 /**
13749 * Handle close keyboard events
13750 * @param {jQuery.Event} event Key down event
13751 */
13752 OO.ui.CapsuleItemWidget.prototype.onCloseKeyDown = function ( e ) {
13753 if ( !this.isDisabled() && $.isFunction( this.getElementGroup().removeItems ) ) {
13754 switch ( e.which ) {
13755 case OO.ui.Keys.ENTER:
13756 case OO.ui.Keys.BACKSPACE:
13757 case OO.ui.Keys.SPACE:
13758 this.getElementGroup().removeItems( [ this ] );
13759 return false;
13760 }
13761 }
13762 };
13763
13764 /**
13765 * DropdownWidgets are not menus themselves, rather they contain a menu of options created with
13766 * OO.ui.MenuOptionWidget. The DropdownWidget takes care of opening and displaying the menu so that
13767 * users can interact with it.
13768 *
13769 * If you want to use this within a HTML form, such as a OO.ui.FormLayout, use
13770 * OO.ui.DropdownInputWidget instead.
13771 *
13772 * @example
13773 * // Example: A DropdownWidget with a menu that contains three options
13774 * var dropDown = new OO.ui.DropdownWidget( {
13775 * label: 'Dropdown menu: Select a menu option',
13776 * menu: {
13777 * items: [
13778 * new OO.ui.MenuOptionWidget( {
13779 * data: 'a',
13780 * label: 'First'
13781 * } ),
13782 * new OO.ui.MenuOptionWidget( {
13783 * data: 'b',
13784 * label: 'Second'
13785 * } ),
13786 * new OO.ui.MenuOptionWidget( {
13787 * data: 'c',
13788 * label: 'Third'
13789 * } )
13790 * ]
13791 * }
13792 * } );
13793 *
13794 * $( 'body' ).append( dropDown.$element );
13795 *
13796 * dropDown.getMenu().selectItemByData( 'b' );
13797 *
13798 * dropDown.getMenu().getSelectedItem().getData(); // returns 'b'
13799 *
13800 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
13801 *
13802 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
13803 *
13804 * @class
13805 * @extends OO.ui.Widget
13806 * @mixins OO.ui.mixin.IconElement
13807 * @mixins OO.ui.mixin.IndicatorElement
13808 * @mixins OO.ui.mixin.LabelElement
13809 * @mixins OO.ui.mixin.TitledElement
13810 * @mixins OO.ui.mixin.TabIndexedElement
13811 *
13812 * @constructor
13813 * @param {Object} [config] Configuration options
13814 * @cfg {Object} [menu] Configuration options to pass to {@link OO.ui.FloatingMenuSelectWidget menu select widget}
13815 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
13816 * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
13817 * containing `<div>` and has a larger area. By default, the menu uses relative positioning.
13818 */
13819 OO.ui.DropdownWidget = function OoUiDropdownWidget( config ) {
13820 // Configuration initialization
13821 config = $.extend( { indicator: 'down' }, config );
13822
13823 // Parent constructor
13824 OO.ui.DropdownWidget.parent.call( this, config );
13825
13826 // Properties (must be set before TabIndexedElement constructor call)
13827 this.$handle = this.$( '<span>' );
13828 this.$overlay = config.$overlay || this.$element;
13829
13830 // Mixin constructors
13831 OO.ui.mixin.IconElement.call( this, config );
13832 OO.ui.mixin.IndicatorElement.call( this, config );
13833 OO.ui.mixin.LabelElement.call( this, config );
13834 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$label } ) );
13835 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$handle } ) );
13836
13837 // Properties
13838 this.menu = new OO.ui.FloatingMenuSelectWidget( $.extend( {
13839 widget: this,
13840 $container: this.$element
13841 }, config.menu ) );
13842
13843 // Events
13844 this.$handle.on( {
13845 click: this.onClick.bind( this ),
13846 keypress: this.onKeyPress.bind( this )
13847 } );
13848 this.menu.connect( this, { select: 'onMenuSelect' } );
13849
13850 // Initialization
13851 this.$handle
13852 .addClass( 'oo-ui-dropdownWidget-handle' )
13853 .append( this.$icon, this.$label, this.$indicator );
13854 this.$element
13855 .addClass( 'oo-ui-dropdownWidget' )
13856 .append( this.$handle );
13857 this.$overlay.append( this.menu.$element );
13858 };
13859
13860 /* Setup */
13861
13862 OO.inheritClass( OO.ui.DropdownWidget, OO.ui.Widget );
13863 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.IconElement );
13864 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.IndicatorElement );
13865 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.LabelElement );
13866 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.TitledElement );
13867 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.TabIndexedElement );
13868
13869 /* Methods */
13870
13871 /**
13872 * Get the menu.
13873 *
13874 * @return {OO.ui.MenuSelectWidget} Menu of widget
13875 */
13876 OO.ui.DropdownWidget.prototype.getMenu = function () {
13877 return this.menu;
13878 };
13879
13880 /**
13881 * Handles menu select events.
13882 *
13883 * @private
13884 * @param {OO.ui.MenuOptionWidget} item Selected menu item
13885 */
13886 OO.ui.DropdownWidget.prototype.onMenuSelect = function ( item ) {
13887 var selectedLabel;
13888
13889 if ( !item ) {
13890 this.setLabel( null );
13891 return;
13892 }
13893
13894 selectedLabel = item.getLabel();
13895
13896 // If the label is a DOM element, clone it, because setLabel will append() it
13897 if ( selectedLabel instanceof jQuery ) {
13898 selectedLabel = selectedLabel.clone();
13899 }
13900
13901 this.setLabel( selectedLabel );
13902 };
13903
13904 /**
13905 * Handle mouse click events.
13906 *
13907 * @private
13908 * @param {jQuery.Event} e Mouse click event
13909 */
13910 OO.ui.DropdownWidget.prototype.onClick = function ( e ) {
13911 if ( !this.isDisabled() && e.which === 1 ) {
13912 this.menu.toggle();
13913 }
13914 return false;
13915 };
13916
13917 /**
13918 * Handle key press events.
13919 *
13920 * @private
13921 * @param {jQuery.Event} e Key press event
13922 */
13923 OO.ui.DropdownWidget.prototype.onKeyPress = function ( e ) {
13924 if ( !this.isDisabled() &&
13925 ( ( e.which === OO.ui.Keys.SPACE && !this.menu.isVisible() ) || e.which === OO.ui.Keys.ENTER )
13926 ) {
13927 this.menu.toggle();
13928 return false;
13929 }
13930 };
13931
13932 /**
13933 * SelectFileWidgets allow for selecting files, using the HTML5 File API. These
13934 * widgets can be configured with {@link OO.ui.mixin.IconElement icons} and {@link
13935 * OO.ui.mixin.IndicatorElement indicators}.
13936 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
13937 *
13938 * @example
13939 * // Example of a file select widget
13940 * var selectFile = new OO.ui.SelectFileWidget();
13941 * $( 'body' ).append( selectFile.$element );
13942 *
13943 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets
13944 *
13945 * @class
13946 * @extends OO.ui.Widget
13947 * @mixins OO.ui.mixin.IconElement
13948 * @mixins OO.ui.mixin.IndicatorElement
13949 * @mixins OO.ui.mixin.PendingElement
13950 * @mixins OO.ui.mixin.LabelElement
13951 *
13952 * @constructor
13953 * @param {Object} [config] Configuration options
13954 * @cfg {string[]|null} [accept=null] MIME types to accept. null accepts all types.
13955 * @cfg {string} [placeholder] Text to display when no file is selected.
13956 * @cfg {string} [notsupported] Text to display when file support is missing in the browser.
13957 * @cfg {boolean} [droppable=true] Whether to accept files by drag and drop.
13958 * @cfg {boolean} [showDropTarget=false] Whether to show a drop target. Requires droppable to be true.
13959 * @cfg {boolean} [dragDropUI=false] Deprecated alias for showDropTarget
13960 */
13961 OO.ui.SelectFileWidget = function OoUiSelectFileWidget( config ) {
13962 var dragHandler;
13963
13964 // TODO: Remove in next release
13965 if ( config && config.dragDropUI ) {
13966 config.showDropTarget = true;
13967 }
13968
13969 // Configuration initialization
13970 config = $.extend( {
13971 accept: null,
13972 placeholder: OO.ui.msg( 'ooui-selectfile-placeholder' ),
13973 notsupported: OO.ui.msg( 'ooui-selectfile-not-supported' ),
13974 droppable: true,
13975 showDropTarget: false
13976 }, config );
13977
13978 // Parent constructor
13979 OO.ui.SelectFileWidget.parent.call( this, config );
13980
13981 // Mixin constructors
13982 OO.ui.mixin.IconElement.call( this, config );
13983 OO.ui.mixin.IndicatorElement.call( this, config );
13984 OO.ui.mixin.PendingElement.call( this, $.extend( {}, config, { $pending: this.$info } ) );
13985 OO.ui.mixin.LabelElement.call( this, $.extend( {}, config, { autoFitLabel: true } ) );
13986
13987 // Properties
13988 this.$info = $( '<span>' );
13989
13990 // Properties
13991 this.showDropTarget = config.showDropTarget;
13992 this.isSupported = this.constructor.static.isSupported();
13993 this.currentFile = null;
13994 if ( Array.isArray( config.accept ) ) {
13995 this.accept = config.accept;
13996 } else {
13997 this.accept = null;
13998 }
13999 this.placeholder = config.placeholder;
14000 this.notsupported = config.notsupported;
14001 this.onFileSelectedHandler = this.onFileSelected.bind( this );
14002
14003 this.selectButton = new OO.ui.ButtonWidget( {
14004 classes: [ 'oo-ui-selectFileWidget-selectButton' ],
14005 label: 'Select a file',
14006 disabled: this.disabled || !this.isSupported
14007 } );
14008
14009 this.clearButton = new OO.ui.ButtonWidget( {
14010 classes: [ 'oo-ui-selectFileWidget-clearButton' ],
14011 framed: false,
14012 icon: 'remove',
14013 disabled: this.disabled
14014 } );
14015
14016 // Events
14017 this.selectButton.$button.on( {
14018 keypress: this.onKeyPress.bind( this )
14019 } );
14020 this.clearButton.connect( this, {
14021 click: 'onClearClick'
14022 } );
14023 if ( config.droppable ) {
14024 dragHandler = this.onDragEnterOrOver.bind( this );
14025 this.$element.on( {
14026 dragenter: dragHandler,
14027 dragover: dragHandler,
14028 dragleave: this.onDragLeave.bind( this ),
14029 drop: this.onDrop.bind( this )
14030 } );
14031 }
14032
14033 // Initialization
14034 this.addInput();
14035 this.updateUI();
14036 this.$label.addClass( 'oo-ui-selectFileWidget-label' );
14037 this.$info
14038 .addClass( 'oo-ui-selectFileWidget-info' )
14039 .append( this.$icon, this.$label, this.clearButton.$element, this.$indicator );
14040 this.$element
14041 .addClass( 'oo-ui-selectFileWidget' )
14042 .append( this.$info, this.selectButton.$element );
14043 if ( config.droppable && config.showDropTarget ) {
14044 this.$dropTarget = $( '<div>' )
14045 .addClass( 'oo-ui-selectFileWidget-dropTarget' )
14046 .text( OO.ui.msg( 'ooui-selectfile-dragdrop-placeholder' ) )
14047 .on( {
14048 click: this.onDropTargetClick.bind( this )
14049 } );
14050 this.$element.prepend( this.$dropTarget );
14051 }
14052 };
14053
14054 /* Setup */
14055
14056 OO.inheritClass( OO.ui.SelectFileWidget, OO.ui.Widget );
14057 OO.mixinClass( OO.ui.SelectFileWidget, OO.ui.mixin.IconElement );
14058 OO.mixinClass( OO.ui.SelectFileWidget, OO.ui.mixin.IndicatorElement );
14059 OO.mixinClass( OO.ui.SelectFileWidget, OO.ui.mixin.PendingElement );
14060 OO.mixinClass( OO.ui.SelectFileWidget, OO.ui.mixin.LabelElement );
14061
14062 /* Static Properties */
14063
14064 /**
14065 * Check if this widget is supported
14066 *
14067 * @static
14068 * @return {boolean}
14069 */
14070 OO.ui.SelectFileWidget.static.isSupported = function () {
14071 var $input;
14072 if ( OO.ui.SelectFileWidget.static.isSupportedCache === null ) {
14073 $input = $( '<input type="file">' );
14074 OO.ui.SelectFileWidget.static.isSupportedCache = $input[ 0 ].files !== undefined;
14075 }
14076 return OO.ui.SelectFileWidget.static.isSupportedCache;
14077 };
14078
14079 OO.ui.SelectFileWidget.static.isSupportedCache = null;
14080
14081 /* Events */
14082
14083 /**
14084 * @event change
14085 *
14086 * A change event is emitted when the on/off state of the toggle changes.
14087 *
14088 * @param {File|null} value New value
14089 */
14090
14091 /* Methods */
14092
14093 /**
14094 * Get the current value of the field
14095 *
14096 * @return {File|null}
14097 */
14098 OO.ui.SelectFileWidget.prototype.getValue = function () {
14099 return this.currentFile;
14100 };
14101
14102 /**
14103 * Set the current value of the field
14104 *
14105 * @param {File|null} file File to select
14106 */
14107 OO.ui.SelectFileWidget.prototype.setValue = function ( file ) {
14108 if ( this.currentFile !== file ) {
14109 this.currentFile = file;
14110 this.updateUI();
14111 this.emit( 'change', this.currentFile );
14112 }
14113 };
14114
14115 /**
14116 * Focus the widget.
14117 *
14118 * Focusses the select file button.
14119 *
14120 * @chainable
14121 */
14122 OO.ui.SelectFileWidget.prototype.focus = function () {
14123 this.selectButton.$button[ 0 ].focus();
14124 return this;
14125 };
14126
14127 /**
14128 * Update the user interface when a file is selected or unselected
14129 *
14130 * @protected
14131 */
14132 OO.ui.SelectFileWidget.prototype.updateUI = function () {
14133 var $label;
14134 if ( !this.isSupported ) {
14135 this.$element.addClass( 'oo-ui-selectFileWidget-notsupported' );
14136 this.$element.removeClass( 'oo-ui-selectFileWidget-empty' );
14137 this.setLabel( this.notsupported );
14138 } else {
14139 this.$element.addClass( 'oo-ui-selectFileWidget-supported' );
14140 if ( this.currentFile ) {
14141 this.$element.removeClass( 'oo-ui-selectFileWidget-empty' );
14142 $label = $( [] );
14143 if ( this.currentFile.type !== '' ) {
14144 $label = $label.add( $( '<span>' ).addClass( 'oo-ui-selectFileWidget-fileType' ).text( this.currentFile.type ) );
14145 }
14146 $label = $label.add( $( '<span>' ).text( this.currentFile.name ) );
14147 this.setLabel( $label );
14148 } else {
14149 this.$element.addClass( 'oo-ui-selectFileWidget-empty' );
14150 this.setLabel( this.placeholder );
14151 }
14152 }
14153
14154 if ( this.$input ) {
14155 this.$input.attr( 'title', this.getLabel() );
14156 }
14157 };
14158
14159 /**
14160 * Add the input to the widget
14161 *
14162 * @private
14163 */
14164 OO.ui.SelectFileWidget.prototype.addInput = function () {
14165 if ( this.$input ) {
14166 this.$input.remove();
14167 }
14168
14169 if ( !this.isSupported ) {
14170 this.$input = null;
14171 return;
14172 }
14173
14174 this.$input = $( '<input type="file">' );
14175 this.$input.on( 'change', this.onFileSelectedHandler );
14176 this.$input.attr( {
14177 tabindex: -1,
14178 title: this.getLabel()
14179 } );
14180 if ( this.accept ) {
14181 this.$input.attr( 'accept', this.accept.join( ', ' ) );
14182 }
14183 this.selectButton.$button.append( this.$input );
14184 };
14185
14186 /**
14187 * Determine if we should accept this file
14188 *
14189 * @private
14190 * @param {string} File MIME type
14191 * @return {boolean}
14192 */
14193 OO.ui.SelectFileWidget.prototype.isAllowedType = function ( mimeType ) {
14194 var i, mimeTest;
14195
14196 if ( !this.accept || !mimeType ) {
14197 return true;
14198 }
14199
14200 for ( i = 0; i < this.accept.length; i++ ) {
14201 mimeTest = this.accept[ i ];
14202 if ( mimeTest === mimeType ) {
14203 return true;
14204 } else if ( mimeTest.substr( -2 ) === '/*' ) {
14205 mimeTest = mimeTest.substr( 0, mimeTest.length - 1 );
14206 if ( mimeType.substr( 0, mimeTest.length ) === mimeTest ) {
14207 return true;
14208 }
14209 }
14210 }
14211
14212 return false;
14213 };
14214
14215 /**
14216 * Handle file selection from the input
14217 *
14218 * @private
14219 * @param {jQuery.Event} e
14220 */
14221 OO.ui.SelectFileWidget.prototype.onFileSelected = function ( e ) {
14222 var file = OO.getProp( e.target, 'files', 0 ) || null;
14223
14224 if ( file && !this.isAllowedType( file.type ) ) {
14225 file = null;
14226 }
14227
14228 this.setValue( file );
14229 this.addInput();
14230 };
14231
14232 /**
14233 * Handle clear button click events.
14234 *
14235 * @private
14236 */
14237 OO.ui.SelectFileWidget.prototype.onClearClick = function () {
14238 this.setValue( null );
14239 return false;
14240 };
14241
14242 /**
14243 * Handle key press events.
14244 *
14245 * @private
14246 * @param {jQuery.Event} e Key press event
14247 */
14248 OO.ui.SelectFileWidget.prototype.onKeyPress = function ( e ) {
14249 if ( this.isSupported && !this.isDisabled() && this.$input &&
14250 ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
14251 ) {
14252 this.$input.click();
14253 return false;
14254 }
14255 };
14256
14257 /**
14258 * Handle drop target click events.
14259 *
14260 * @private
14261 * @param {jQuery.Event} e Key press event
14262 */
14263 OO.ui.SelectFileWidget.prototype.onDropTargetClick = function () {
14264 if ( this.isSupported && !this.isDisabled() && this.$input ) {
14265 this.$input.click();
14266 return false;
14267 }
14268 };
14269
14270 /**
14271 * Handle drag enter and over events
14272 *
14273 * @private
14274 * @param {jQuery.Event} e Drag event
14275 */
14276 OO.ui.SelectFileWidget.prototype.onDragEnterOrOver = function ( e ) {
14277 var itemOrFile,
14278 droppableFile = false,
14279 dt = e.originalEvent.dataTransfer;
14280
14281 e.preventDefault();
14282 e.stopPropagation();
14283
14284 if ( this.isDisabled() || !this.isSupported ) {
14285 this.$element.removeClass( 'oo-ui-selectFileWidget-canDrop' );
14286 dt.dropEffect = 'none';
14287 return false;
14288 }
14289
14290 // DataTransferItem and File both have a type property, but in Chrome files
14291 // have no information at this point.
14292 itemOrFile = OO.getProp( dt, 'items', 0 ) || OO.getProp( dt, 'files', 0 );
14293 if ( itemOrFile ) {
14294 if ( this.isAllowedType( itemOrFile.type ) ) {
14295 droppableFile = true;
14296 }
14297 // dt.types is Array-like, but not an Array
14298 } else if ( Array.prototype.indexOf.call( OO.getProp( dt, 'types' ) || [], 'Files' ) !== -1 ) {
14299 // File information is not available at this point for security so just assume
14300 // it is acceptable for now.
14301 // https://bugzilla.mozilla.org/show_bug.cgi?id=640534
14302 droppableFile = true;
14303 }
14304
14305 this.$element.toggleClass( 'oo-ui-selectFileWidget-canDrop', droppableFile );
14306 if ( !droppableFile ) {
14307 dt.dropEffect = 'none';
14308 }
14309
14310 return false;
14311 };
14312
14313 /**
14314 * Handle drag leave events
14315 *
14316 * @private
14317 * @param {jQuery.Event} e Drag event
14318 */
14319 OO.ui.SelectFileWidget.prototype.onDragLeave = function () {
14320 this.$element.removeClass( 'oo-ui-selectFileWidget-canDrop' );
14321 };
14322
14323 /**
14324 * Handle drop events
14325 *
14326 * @private
14327 * @param {jQuery.Event} e Drop event
14328 */
14329 OO.ui.SelectFileWidget.prototype.onDrop = function ( e ) {
14330 var file = null,
14331 dt = e.originalEvent.dataTransfer;
14332
14333 e.preventDefault();
14334 e.stopPropagation();
14335 this.$element.removeClass( 'oo-ui-selectFileWidget-canDrop' );
14336
14337 if ( this.isDisabled() || !this.isSupported ) {
14338 return false;
14339 }
14340
14341 file = OO.getProp( dt, 'files', 0 );
14342 if ( file && !this.isAllowedType( file.type ) ) {
14343 file = null;
14344 }
14345 if ( file ) {
14346 this.setValue( file );
14347 }
14348
14349 return false;
14350 };
14351
14352 /**
14353 * @inheritdoc
14354 */
14355 OO.ui.SelectFileWidget.prototype.setDisabled = function ( disabled ) {
14356 OO.ui.SelectFileWidget.parent.prototype.setDisabled.call( this, disabled );
14357 if ( this.selectButton ) {
14358 this.selectButton.setDisabled( disabled );
14359 }
14360 if ( this.clearButton ) {
14361 this.clearButton.setDisabled( disabled );
14362 }
14363 return this;
14364 };
14365
14366 /**
14367 * IconWidget is a generic widget for {@link OO.ui.mixin.IconElement icons}. In general, IconWidgets should be used with OO.ui.LabelWidget,
14368 * which creates a label that identifies the icon’s function. See the [OOjs UI documentation on MediaWiki] [1]
14369 * for a list of icons included in the library.
14370 *
14371 * @example
14372 * // An icon widget with a label
14373 * var myIcon = new OO.ui.IconWidget( {
14374 * icon: 'help',
14375 * iconTitle: 'Help'
14376 * } );
14377 * // Create a label.
14378 * var iconLabel = new OO.ui.LabelWidget( {
14379 * label: 'Help'
14380 * } );
14381 * $( 'body' ).append( myIcon.$element, iconLabel.$element );
14382 *
14383 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
14384 *
14385 * @class
14386 * @extends OO.ui.Widget
14387 * @mixins OO.ui.mixin.IconElement
14388 * @mixins OO.ui.mixin.TitledElement
14389 * @mixins OO.ui.mixin.FlaggedElement
14390 *
14391 * @constructor
14392 * @param {Object} [config] Configuration options
14393 */
14394 OO.ui.IconWidget = function OoUiIconWidget( config ) {
14395 // Configuration initialization
14396 config = config || {};
14397
14398 // Parent constructor
14399 OO.ui.IconWidget.parent.call( this, config );
14400
14401 // Mixin constructors
14402 OO.ui.mixin.IconElement.call( this, $.extend( {}, config, { $icon: this.$element } ) );
14403 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$element } ) );
14404 OO.ui.mixin.FlaggedElement.call( this, $.extend( {}, config, { $flagged: this.$element } ) );
14405
14406 // Initialization
14407 this.$element.addClass( 'oo-ui-iconWidget' );
14408 };
14409
14410 /* Setup */
14411
14412 OO.inheritClass( OO.ui.IconWidget, OO.ui.Widget );
14413 OO.mixinClass( OO.ui.IconWidget, OO.ui.mixin.IconElement );
14414 OO.mixinClass( OO.ui.IconWidget, OO.ui.mixin.TitledElement );
14415 OO.mixinClass( OO.ui.IconWidget, OO.ui.mixin.FlaggedElement );
14416
14417 /* Static Properties */
14418
14419 OO.ui.IconWidget.static.tagName = 'span';
14420
14421 /**
14422 * IndicatorWidgets create indicators, which are small graphics that are generally used to draw
14423 * attention to the status of an item or to clarify the function of a control. For a list of
14424 * indicators included in the library, please see the [OOjs UI documentation on MediaWiki][1].
14425 *
14426 * @example
14427 * // Example of an indicator widget
14428 * var indicator1 = new OO.ui.IndicatorWidget( {
14429 * indicator: 'alert'
14430 * } );
14431 *
14432 * // Create a fieldset layout to add a label
14433 * var fieldset = new OO.ui.FieldsetLayout();
14434 * fieldset.addItems( [
14435 * new OO.ui.FieldLayout( indicator1, { label: 'An alert indicator:' } )
14436 * ] );
14437 * $( 'body' ).append( fieldset.$element );
14438 *
14439 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
14440 *
14441 * @class
14442 * @extends OO.ui.Widget
14443 * @mixins OO.ui.mixin.IndicatorElement
14444 * @mixins OO.ui.mixin.TitledElement
14445 *
14446 * @constructor
14447 * @param {Object} [config] Configuration options
14448 */
14449 OO.ui.IndicatorWidget = function OoUiIndicatorWidget( config ) {
14450 // Configuration initialization
14451 config = config || {};
14452
14453 // Parent constructor
14454 OO.ui.IndicatorWidget.parent.call( this, config );
14455
14456 // Mixin constructors
14457 OO.ui.mixin.IndicatorElement.call( this, $.extend( {}, config, { $indicator: this.$element } ) );
14458 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$element } ) );
14459
14460 // Initialization
14461 this.$element.addClass( 'oo-ui-indicatorWidget' );
14462 };
14463
14464 /* Setup */
14465
14466 OO.inheritClass( OO.ui.IndicatorWidget, OO.ui.Widget );
14467 OO.mixinClass( OO.ui.IndicatorWidget, OO.ui.mixin.IndicatorElement );
14468 OO.mixinClass( OO.ui.IndicatorWidget, OO.ui.mixin.TitledElement );
14469
14470 /* Static Properties */
14471
14472 OO.ui.IndicatorWidget.static.tagName = 'span';
14473
14474 /**
14475 * InputWidget is the base class for all input widgets, which
14476 * include {@link OO.ui.TextInputWidget text inputs}, {@link OO.ui.CheckboxInputWidget checkbox inputs},
14477 * {@link OO.ui.RadioInputWidget radio inputs}, and {@link OO.ui.ButtonInputWidget button inputs}.
14478 * See the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
14479 *
14480 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
14481 *
14482 * @abstract
14483 * @class
14484 * @extends OO.ui.Widget
14485 * @mixins OO.ui.mixin.FlaggedElement
14486 * @mixins OO.ui.mixin.TabIndexedElement
14487 * @mixins OO.ui.mixin.TitledElement
14488 * @mixins OO.ui.mixin.AccessKeyedElement
14489 *
14490 * @constructor
14491 * @param {Object} [config] Configuration options
14492 * @cfg {string} [name=''] The value of the input’s HTML `name` attribute.
14493 * @cfg {string} [value=''] The value of the input.
14494 * @cfg {string} [accessKey=''] The access key of the input.
14495 * @cfg {Function} [inputFilter] The name of an input filter function. Input filters modify the value of an input
14496 * before it is accepted.
14497 */
14498 OO.ui.InputWidget = function OoUiInputWidget( config ) {
14499 // Configuration initialization
14500 config = config || {};
14501
14502 // Parent constructor
14503 OO.ui.InputWidget.parent.call( this, config );
14504
14505 // Properties
14506 this.$input = this.getInputElement( config );
14507 this.value = '';
14508 this.inputFilter = config.inputFilter;
14509
14510 // Mixin constructors
14511 OO.ui.mixin.FlaggedElement.call( this, config );
14512 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$input } ) );
14513 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$input } ) );
14514 OO.ui.mixin.AccessKeyedElement.call( this, $.extend( {}, config, { $accessKeyed: this.$input } ) );
14515
14516 // Events
14517 this.$input.on( 'keydown mouseup cut paste change input select', this.onEdit.bind( this ) );
14518
14519 // Initialization
14520 this.$input
14521 .addClass( 'oo-ui-inputWidget-input' )
14522 .attr( 'name', config.name )
14523 .prop( 'disabled', this.isDisabled() );
14524 this.$element
14525 .addClass( 'oo-ui-inputWidget' )
14526 .append( this.$input );
14527 this.setValue( config.value );
14528 this.setAccessKey( config.accessKey );
14529 };
14530
14531 /* Setup */
14532
14533 OO.inheritClass( OO.ui.InputWidget, OO.ui.Widget );
14534 OO.mixinClass( OO.ui.InputWidget, OO.ui.mixin.FlaggedElement );
14535 OO.mixinClass( OO.ui.InputWidget, OO.ui.mixin.TabIndexedElement );
14536 OO.mixinClass( OO.ui.InputWidget, OO.ui.mixin.TitledElement );
14537 OO.mixinClass( OO.ui.InputWidget, OO.ui.mixin.AccessKeyedElement );
14538
14539 /* Static Properties */
14540
14541 OO.ui.InputWidget.static.supportsSimpleLabel = true;
14542
14543 /* Events */
14544
14545 /**
14546 * @event change
14547 *
14548 * A change event is emitted when the value of the input changes.
14549 *
14550 * @param {string} value
14551 */
14552
14553 /* Methods */
14554
14555 /**
14556 * Get input element.
14557 *
14558 * Subclasses of OO.ui.InputWidget use the `config` parameter to produce different elements in
14559 * different circumstances. The element must have a `value` property (like form elements).
14560 *
14561 * @protected
14562 * @param {Object} config Configuration options
14563 * @return {jQuery} Input element
14564 */
14565 OO.ui.InputWidget.prototype.getInputElement = function () {
14566 return $( '<input>' );
14567 };
14568
14569 /**
14570 * Handle potentially value-changing events.
14571 *
14572 * @private
14573 * @param {jQuery.Event} e Key down, mouse up, cut, paste, change, input, or select event
14574 */
14575 OO.ui.InputWidget.prototype.onEdit = function () {
14576 var widget = this;
14577 if ( !this.isDisabled() ) {
14578 // Allow the stack to clear so the value will be updated
14579 setTimeout( function () {
14580 widget.setValue( widget.$input.val() );
14581 } );
14582 }
14583 };
14584
14585 /**
14586 * Get the value of the input.
14587 *
14588 * @return {string} Input value
14589 */
14590 OO.ui.InputWidget.prototype.getValue = function () {
14591 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
14592 // it, and we won't know unless they're kind enough to trigger a 'change' event.
14593 var value = this.$input.val();
14594 if ( this.value !== value ) {
14595 this.setValue( value );
14596 }
14597 return this.value;
14598 };
14599
14600 /**
14601 * Set the direction of the input, either RTL (right-to-left) or LTR (left-to-right).
14602 *
14603 * @param {boolean} isRTL
14604 * Direction is right-to-left
14605 */
14606 OO.ui.InputWidget.prototype.setRTL = function ( isRTL ) {
14607 this.$input.prop( 'dir', isRTL ? 'rtl' : 'ltr' );
14608 };
14609
14610 /**
14611 * Set the value of the input.
14612 *
14613 * @param {string} value New value
14614 * @fires change
14615 * @chainable
14616 */
14617 OO.ui.InputWidget.prototype.setValue = function ( value ) {
14618 value = this.cleanUpValue( value );
14619 // Update the DOM if it has changed. Note that with cleanUpValue, it
14620 // is possible for the DOM value to change without this.value changing.
14621 if ( this.$input.val() !== value ) {
14622 this.$input.val( value );
14623 }
14624 if ( this.value !== value ) {
14625 this.value = value;
14626 this.emit( 'change', this.value );
14627 }
14628 return this;
14629 };
14630
14631 /**
14632 * Set the input's access key.
14633 * FIXME: This is the same code as in OO.ui.mixin.ButtonElement, maybe find a better place for it?
14634 *
14635 * @param {string} accessKey Input's access key, use empty string to remove
14636 * @chainable
14637 */
14638 OO.ui.InputWidget.prototype.setAccessKey = function ( accessKey ) {
14639 accessKey = typeof accessKey === 'string' && accessKey.length ? accessKey : null;
14640
14641 if ( this.accessKey !== accessKey ) {
14642 if ( this.$input ) {
14643 if ( accessKey !== null ) {
14644 this.$input.attr( 'accesskey', accessKey );
14645 } else {
14646 this.$input.removeAttr( 'accesskey' );
14647 }
14648 }
14649 this.accessKey = accessKey;
14650 }
14651
14652 return this;
14653 };
14654
14655 /**
14656 * Clean up incoming value.
14657 *
14658 * Ensures value is a string, and converts undefined and null to empty string.
14659 *
14660 * @private
14661 * @param {string} value Original value
14662 * @return {string} Cleaned up value
14663 */
14664 OO.ui.InputWidget.prototype.cleanUpValue = function ( value ) {
14665 if ( value === undefined || value === null ) {
14666 return '';
14667 } else if ( this.inputFilter ) {
14668 return this.inputFilter( String( value ) );
14669 } else {
14670 return String( value );
14671 }
14672 };
14673
14674 /**
14675 * Simulate the behavior of clicking on a label bound to this input. This method is only called by
14676 * {@link OO.ui.LabelWidget LabelWidget} and {@link OO.ui.FieldLayout FieldLayout}. It should not be
14677 * called directly.
14678 */
14679 OO.ui.InputWidget.prototype.simulateLabelClick = function () {
14680 if ( !this.isDisabled() ) {
14681 if ( this.$input.is( ':checkbox, :radio' ) ) {
14682 this.$input.click();
14683 }
14684 if ( this.$input.is( ':input' ) ) {
14685 this.$input[ 0 ].focus();
14686 }
14687 }
14688 };
14689
14690 /**
14691 * @inheritdoc
14692 */
14693 OO.ui.InputWidget.prototype.setDisabled = function ( state ) {
14694 OO.ui.InputWidget.parent.prototype.setDisabled.call( this, state );
14695 if ( this.$input ) {
14696 this.$input.prop( 'disabled', this.isDisabled() );
14697 }
14698 return this;
14699 };
14700
14701 /**
14702 * Focus the input.
14703 *
14704 * @chainable
14705 */
14706 OO.ui.InputWidget.prototype.focus = function () {
14707 this.$input[ 0 ].focus();
14708 return this;
14709 };
14710
14711 /**
14712 * Blur the input.
14713 *
14714 * @chainable
14715 */
14716 OO.ui.InputWidget.prototype.blur = function () {
14717 this.$input[ 0 ].blur();
14718 return this;
14719 };
14720
14721 /**
14722 * @inheritdoc
14723 */
14724 OO.ui.InputWidget.prototype.gatherPreInfuseState = function ( node ) {
14725 var
14726 state = OO.ui.InputWidget.parent.prototype.gatherPreInfuseState.call( this, node ),
14727 $input = state.$input || $( node ).find( '.oo-ui-inputWidget-input' );
14728 state.value = $input.val();
14729 // Might be better in TabIndexedElement, but it's awkward to do there because mixins are awkward
14730 state.focus = $input.is( ':focus' );
14731 return state;
14732 };
14733
14734 /**
14735 * @inheritdoc
14736 */
14737 OO.ui.InputWidget.prototype.restorePreInfuseState = function ( state ) {
14738 OO.ui.InputWidget.parent.prototype.restorePreInfuseState.call( this, state );
14739 if ( state.value !== undefined && state.value !== this.getValue() ) {
14740 this.setValue( state.value );
14741 }
14742 if ( state.focus ) {
14743 this.focus();
14744 }
14745 };
14746
14747 /**
14748 * ButtonInputWidget is used to submit HTML forms and is intended to be used within
14749 * a OO.ui.FormLayout. If you do not need the button to work with HTML forms, you probably
14750 * want to use OO.ui.ButtonWidget instead. Button input widgets can be rendered as either an
14751 * HTML `<button/>` (the default) or an HTML `<input/>` tags. See the
14752 * [OOjs UI documentation on MediaWiki] [1] for more information.
14753 *
14754 * @example
14755 * // A ButtonInputWidget rendered as an HTML button, the default.
14756 * var button = new OO.ui.ButtonInputWidget( {
14757 * label: 'Input button',
14758 * icon: 'check',
14759 * value: 'check'
14760 * } );
14761 * $( 'body' ).append( button.$element );
14762 *
14763 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs#Button_inputs
14764 *
14765 * @class
14766 * @extends OO.ui.InputWidget
14767 * @mixins OO.ui.mixin.ButtonElement
14768 * @mixins OO.ui.mixin.IconElement
14769 * @mixins OO.ui.mixin.IndicatorElement
14770 * @mixins OO.ui.mixin.LabelElement
14771 * @mixins OO.ui.mixin.TitledElement
14772 *
14773 * @constructor
14774 * @param {Object} [config] Configuration options
14775 * @cfg {string} [type='button'] The value of the HTML `'type'` attribute: 'button', 'submit' or 'reset'.
14776 * @cfg {boolean} [useInputTag=false] Use an `<input/>` tag instead of a `<button/>` tag, the default.
14777 * Widgets configured to be an `<input/>` do not support {@link #icon icons} and {@link #indicator indicators},
14778 * non-plaintext {@link #label labels}, or {@link #value values}. In general, useInputTag should only
14779 * be set to `true` when there’s need to support IE6 in a form with multiple buttons.
14780 */
14781 OO.ui.ButtonInputWidget = function OoUiButtonInputWidget( config ) {
14782 // Configuration initialization
14783 config = $.extend( { type: 'button', useInputTag: false }, config );
14784
14785 // Properties (must be set before parent constructor, which calls #setValue)
14786 this.useInputTag = config.useInputTag;
14787
14788 // Parent constructor
14789 OO.ui.ButtonInputWidget.parent.call( this, config );
14790
14791 // Mixin constructors
14792 OO.ui.mixin.ButtonElement.call( this, $.extend( {}, config, { $button: this.$input } ) );
14793 OO.ui.mixin.IconElement.call( this, config );
14794 OO.ui.mixin.IndicatorElement.call( this, config );
14795 OO.ui.mixin.LabelElement.call( this, config );
14796 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$input } ) );
14797
14798 // Initialization
14799 if ( !config.useInputTag ) {
14800 this.$input.append( this.$icon, this.$label, this.$indicator );
14801 }
14802 this.$element.addClass( 'oo-ui-buttonInputWidget' );
14803 };
14804
14805 /* Setup */
14806
14807 OO.inheritClass( OO.ui.ButtonInputWidget, OO.ui.InputWidget );
14808 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.ButtonElement );
14809 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.IconElement );
14810 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.IndicatorElement );
14811 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.LabelElement );
14812 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.TitledElement );
14813
14814 /* Static Properties */
14815
14816 /**
14817 * Disable generating `<label>` elements for buttons. One would very rarely need additional label
14818 * for a button, and it's already a big clickable target, and it causes unexpected rendering.
14819 */
14820 OO.ui.ButtonInputWidget.static.supportsSimpleLabel = false;
14821
14822 /* Methods */
14823
14824 /**
14825 * @inheritdoc
14826 * @protected
14827 */
14828 OO.ui.ButtonInputWidget.prototype.getInputElement = function ( config ) {
14829 var type = [ 'button', 'submit', 'reset' ].indexOf( config.type ) !== -1 ?
14830 config.type :
14831 'button';
14832 return $( '<' + ( config.useInputTag ? 'input' : 'button' ) + ' type="' + type + '">' );
14833 };
14834
14835 /**
14836 * Set label value.
14837 *
14838 * If #useInputTag is `true`, the label is set as the `value` of the `<input/>` tag.
14839 *
14840 * @param {jQuery|string|Function|null} label Label nodes, text, a function that returns nodes or
14841 * text, or `null` for no label
14842 * @chainable
14843 */
14844 OO.ui.ButtonInputWidget.prototype.setLabel = function ( label ) {
14845 OO.ui.mixin.LabelElement.prototype.setLabel.call( this, label );
14846
14847 if ( this.useInputTag ) {
14848 if ( typeof label === 'function' ) {
14849 label = OO.ui.resolveMsg( label );
14850 }
14851 if ( label instanceof jQuery ) {
14852 label = label.text();
14853 }
14854 if ( !label ) {
14855 label = '';
14856 }
14857 this.$input.val( label );
14858 }
14859
14860 return this;
14861 };
14862
14863 /**
14864 * Set the value of the input.
14865 *
14866 * This method is disabled for button inputs configured as {@link #useInputTag <input/> tags}, as
14867 * they do not support {@link #value values}.
14868 *
14869 * @param {string} value New value
14870 * @chainable
14871 */
14872 OO.ui.ButtonInputWidget.prototype.setValue = function ( value ) {
14873 if ( !this.useInputTag ) {
14874 OO.ui.ButtonInputWidget.parent.prototype.setValue.call( this, value );
14875 }
14876 return this;
14877 };
14878
14879 /**
14880 * CheckboxInputWidgets, like HTML checkboxes, can be selected and/or configured with a value.
14881 * Note that these {@link OO.ui.InputWidget input widgets} are best laid out
14882 * in {@link OO.ui.FieldLayout field layouts} that use the {@link OO.ui.FieldLayout#align inline}
14883 * alignment. For more information, please see the [OOjs UI documentation on MediaWiki][1].
14884 *
14885 * This widget can be used inside a HTML form, such as a OO.ui.FormLayout.
14886 *
14887 * @example
14888 * // An example of selected, unselected, and disabled checkbox inputs
14889 * var checkbox1=new OO.ui.CheckboxInputWidget( {
14890 * value: 'a',
14891 * selected: true
14892 * } );
14893 * var checkbox2=new OO.ui.CheckboxInputWidget( {
14894 * value: 'b'
14895 * } );
14896 * var checkbox3=new OO.ui.CheckboxInputWidget( {
14897 * value:'c',
14898 * disabled: true
14899 * } );
14900 * // Create a fieldset layout with fields for each checkbox.
14901 * var fieldset = new OO.ui.FieldsetLayout( {
14902 * label: 'Checkboxes'
14903 * } );
14904 * fieldset.addItems( [
14905 * new OO.ui.FieldLayout( checkbox1, { label: 'Selected checkbox', align: 'inline' } ),
14906 * new OO.ui.FieldLayout( checkbox2, { label: 'Unselected checkbox', align: 'inline' } ),
14907 * new OO.ui.FieldLayout( checkbox3, { label: 'Disabled checkbox', align: 'inline' } ),
14908 * ] );
14909 * $( 'body' ).append( fieldset.$element );
14910 *
14911 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
14912 *
14913 * @class
14914 * @extends OO.ui.InputWidget
14915 *
14916 * @constructor
14917 * @param {Object} [config] Configuration options
14918 * @cfg {boolean} [selected=false] Select the checkbox initially. By default, the checkbox is not selected.
14919 */
14920 OO.ui.CheckboxInputWidget = function OoUiCheckboxInputWidget( config ) {
14921 // Configuration initialization
14922 config = config || {};
14923
14924 // Parent constructor
14925 OO.ui.CheckboxInputWidget.parent.call( this, config );
14926
14927 // Initialization
14928 this.$element
14929 .addClass( 'oo-ui-checkboxInputWidget' )
14930 // Required for pretty styling in MediaWiki theme
14931 .append( $( '<span>' ) );
14932 this.setSelected( config.selected !== undefined ? config.selected : false );
14933 };
14934
14935 /* Setup */
14936
14937 OO.inheritClass( OO.ui.CheckboxInputWidget, OO.ui.InputWidget );
14938
14939 /* Methods */
14940
14941 /**
14942 * @inheritdoc
14943 * @protected
14944 */
14945 OO.ui.CheckboxInputWidget.prototype.getInputElement = function () {
14946 return $( '<input type="checkbox" />' );
14947 };
14948
14949 /**
14950 * @inheritdoc
14951 */
14952 OO.ui.CheckboxInputWidget.prototype.onEdit = function () {
14953 var widget = this;
14954 if ( !this.isDisabled() ) {
14955 // Allow the stack to clear so the value will be updated
14956 setTimeout( function () {
14957 widget.setSelected( widget.$input.prop( 'checked' ) );
14958 } );
14959 }
14960 };
14961
14962 /**
14963 * Set selection state of this checkbox.
14964 *
14965 * @param {boolean} state `true` for selected
14966 * @chainable
14967 */
14968 OO.ui.CheckboxInputWidget.prototype.setSelected = function ( state ) {
14969 state = !!state;
14970 if ( this.selected !== state ) {
14971 this.selected = state;
14972 this.$input.prop( 'checked', this.selected );
14973 this.emit( 'change', this.selected );
14974 }
14975 return this;
14976 };
14977
14978 /**
14979 * Check if this checkbox is selected.
14980 *
14981 * @return {boolean} Checkbox is selected
14982 */
14983 OO.ui.CheckboxInputWidget.prototype.isSelected = function () {
14984 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
14985 // it, and we won't know unless they're kind enough to trigger a 'change' event.
14986 var selected = this.$input.prop( 'checked' );
14987 if ( this.selected !== selected ) {
14988 this.setSelected( selected );
14989 }
14990 return this.selected;
14991 };
14992
14993 /**
14994 * @inheritdoc
14995 */
14996 OO.ui.CheckboxInputWidget.prototype.gatherPreInfuseState = function ( node ) {
14997 var
14998 state = OO.ui.CheckboxInputWidget.parent.prototype.gatherPreInfuseState.call( this, node ),
14999 $input = $( node ).find( '.oo-ui-inputWidget-input' );
15000 state.$input = $input; // shortcut for performance, used in InputWidget
15001 state.checked = $input.prop( 'checked' );
15002 return state;
15003 };
15004
15005 /**
15006 * @inheritdoc
15007 */
15008 OO.ui.CheckboxInputWidget.prototype.restorePreInfuseState = function ( state ) {
15009 OO.ui.CheckboxInputWidget.parent.prototype.restorePreInfuseState.call( this, state );
15010 if ( state.checked !== undefined && state.checked !== this.isSelected() ) {
15011 this.setSelected( state.checked );
15012 }
15013 };
15014
15015 /**
15016 * DropdownInputWidget is a {@link OO.ui.DropdownWidget DropdownWidget} intended to be used
15017 * within a HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with the value
15018 * of a hidden HTML `input` tag. Please see the [OOjs UI documentation on MediaWiki][1] for
15019 * more information about input widgets.
15020 *
15021 * A DropdownInputWidget always has a value (one of the options is always selected), unless there
15022 * are no options. If no `value` configuration option is provided, the first option is selected.
15023 * If you need a state representing no value (no option being selected), use a DropdownWidget.
15024 *
15025 * This and OO.ui.RadioSelectInputWidget support the same configuration options.
15026 *
15027 * @example
15028 * // Example: A DropdownInputWidget with three options
15029 * var dropdownInput = new OO.ui.DropdownInputWidget( {
15030 * options: [
15031 * { data: 'a', label: 'First' },
15032 * { data: 'b', label: 'Second'},
15033 * { data: 'c', label: 'Third' }
15034 * ]
15035 * } );
15036 * $( 'body' ).append( dropdownInput.$element );
15037 *
15038 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
15039 *
15040 * @class
15041 * @extends OO.ui.InputWidget
15042 * @mixins OO.ui.mixin.TitledElement
15043 *
15044 * @constructor
15045 * @param {Object} [config] Configuration options
15046 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
15047 * @cfg {Object} [dropdown] Configuration options for {@link OO.ui.DropdownWidget DropdownWidget}
15048 */
15049 OO.ui.DropdownInputWidget = function OoUiDropdownInputWidget( config ) {
15050 // Configuration initialization
15051 config = config || {};
15052
15053 // Properties (must be done before parent constructor which calls #setDisabled)
15054 this.dropdownWidget = new OO.ui.DropdownWidget( config.dropdown );
15055
15056 // Parent constructor
15057 OO.ui.DropdownInputWidget.parent.call( this, config );
15058
15059 // Mixin constructors
15060 OO.ui.mixin.TitledElement.call( this, config );
15061
15062 // Events
15063 this.dropdownWidget.getMenu().connect( this, { select: 'onMenuSelect' } );
15064
15065 // Initialization
15066 this.setOptions( config.options || [] );
15067 this.$element
15068 .addClass( 'oo-ui-dropdownInputWidget' )
15069 .append( this.dropdownWidget.$element );
15070 };
15071
15072 /* Setup */
15073
15074 OO.inheritClass( OO.ui.DropdownInputWidget, OO.ui.InputWidget );
15075 OO.mixinClass( OO.ui.DropdownInputWidget, OO.ui.mixin.TitledElement );
15076
15077 /* Methods */
15078
15079 /**
15080 * @inheritdoc
15081 * @protected
15082 */
15083 OO.ui.DropdownInputWidget.prototype.getInputElement = function () {
15084 return $( '<input type="hidden">' );
15085 };
15086
15087 /**
15088 * Handles menu select events.
15089 *
15090 * @private
15091 * @param {OO.ui.MenuOptionWidget} item Selected menu item
15092 */
15093 OO.ui.DropdownInputWidget.prototype.onMenuSelect = function ( item ) {
15094 this.setValue( item.getData() );
15095 };
15096
15097 /**
15098 * @inheritdoc
15099 */
15100 OO.ui.DropdownInputWidget.prototype.setValue = function ( value ) {
15101 value = this.cleanUpValue( value );
15102 this.dropdownWidget.getMenu().selectItemByData( value );
15103 OO.ui.DropdownInputWidget.parent.prototype.setValue.call( this, value );
15104 return this;
15105 };
15106
15107 /**
15108 * @inheritdoc
15109 */
15110 OO.ui.DropdownInputWidget.prototype.setDisabled = function ( state ) {
15111 this.dropdownWidget.setDisabled( state );
15112 OO.ui.DropdownInputWidget.parent.prototype.setDisabled.call( this, state );
15113 return this;
15114 };
15115
15116 /**
15117 * Set the options available for this input.
15118 *
15119 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
15120 * @chainable
15121 */
15122 OO.ui.DropdownInputWidget.prototype.setOptions = function ( options ) {
15123 var
15124 value = this.getValue(),
15125 widget = this;
15126
15127 // Rebuild the dropdown menu
15128 this.dropdownWidget.getMenu()
15129 .clearItems()
15130 .addItems( options.map( function ( opt ) {
15131 var optValue = widget.cleanUpValue( opt.data );
15132 return new OO.ui.MenuOptionWidget( {
15133 data: optValue,
15134 label: opt.label !== undefined ? opt.label : optValue
15135 } );
15136 } ) );
15137
15138 // Restore the previous value, or reset to something sensible
15139 if ( this.dropdownWidget.getMenu().getItemFromData( value ) ) {
15140 // Previous value is still available, ensure consistency with the dropdown
15141 this.setValue( value );
15142 } else {
15143 // No longer valid, reset
15144 if ( options.length ) {
15145 this.setValue( options[ 0 ].data );
15146 }
15147 }
15148
15149 return this;
15150 };
15151
15152 /**
15153 * @inheritdoc
15154 */
15155 OO.ui.DropdownInputWidget.prototype.focus = function () {
15156 this.dropdownWidget.getMenu().toggle( true );
15157 return this;
15158 };
15159
15160 /**
15161 * @inheritdoc
15162 */
15163 OO.ui.DropdownInputWidget.prototype.blur = function () {
15164 this.dropdownWidget.getMenu().toggle( false );
15165 return this;
15166 };
15167
15168 /**
15169 * RadioInputWidget creates a single radio button. Because radio buttons are usually used as a set,
15170 * in most cases you will want to use a {@link OO.ui.RadioSelectWidget radio select}
15171 * with {@link OO.ui.RadioOptionWidget radio options} instead of this class. For more information,
15172 * please see the [OOjs UI documentation on MediaWiki][1].
15173 *
15174 * This widget can be used inside a HTML form, such as a OO.ui.FormLayout.
15175 *
15176 * @example
15177 * // An example of selected, unselected, and disabled radio inputs
15178 * var radio1 = new OO.ui.RadioInputWidget( {
15179 * value: 'a',
15180 * selected: true
15181 * } );
15182 * var radio2 = new OO.ui.RadioInputWidget( {
15183 * value: 'b'
15184 * } );
15185 * var radio3 = new OO.ui.RadioInputWidget( {
15186 * value: 'c',
15187 * disabled: true
15188 * } );
15189 * // Create a fieldset layout with fields for each radio button.
15190 * var fieldset = new OO.ui.FieldsetLayout( {
15191 * label: 'Radio inputs'
15192 * } );
15193 * fieldset.addItems( [
15194 * new OO.ui.FieldLayout( radio1, { label: 'Selected', align: 'inline' } ),
15195 * new OO.ui.FieldLayout( radio2, { label: 'Unselected', align: 'inline' } ),
15196 * new OO.ui.FieldLayout( radio3, { label: 'Disabled', align: 'inline' } ),
15197 * ] );
15198 * $( 'body' ).append( fieldset.$element );
15199 *
15200 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
15201 *
15202 * @class
15203 * @extends OO.ui.InputWidget
15204 *
15205 * @constructor
15206 * @param {Object} [config] Configuration options
15207 * @cfg {boolean} [selected=false] Select the radio button initially. By default, the radio button is not selected.
15208 */
15209 OO.ui.RadioInputWidget = function OoUiRadioInputWidget( config ) {
15210 // Configuration initialization
15211 config = config || {};
15212
15213 // Parent constructor
15214 OO.ui.RadioInputWidget.parent.call( this, config );
15215
15216 // Initialization
15217 this.$element
15218 .addClass( 'oo-ui-radioInputWidget' )
15219 // Required for pretty styling in MediaWiki theme
15220 .append( $( '<span>' ) );
15221 this.setSelected( config.selected !== undefined ? config.selected : false );
15222 };
15223
15224 /* Setup */
15225
15226 OO.inheritClass( OO.ui.RadioInputWidget, OO.ui.InputWidget );
15227
15228 /* Methods */
15229
15230 /**
15231 * @inheritdoc
15232 * @protected
15233 */
15234 OO.ui.RadioInputWidget.prototype.getInputElement = function () {
15235 return $( '<input type="radio" />' );
15236 };
15237
15238 /**
15239 * @inheritdoc
15240 */
15241 OO.ui.RadioInputWidget.prototype.onEdit = function () {
15242 // RadioInputWidget doesn't track its state.
15243 };
15244
15245 /**
15246 * Set selection state of this radio button.
15247 *
15248 * @param {boolean} state `true` for selected
15249 * @chainable
15250 */
15251 OO.ui.RadioInputWidget.prototype.setSelected = function ( state ) {
15252 // RadioInputWidget doesn't track its state.
15253 this.$input.prop( 'checked', state );
15254 return this;
15255 };
15256
15257 /**
15258 * Check if this radio button is selected.
15259 *
15260 * @return {boolean} Radio is selected
15261 */
15262 OO.ui.RadioInputWidget.prototype.isSelected = function () {
15263 return this.$input.prop( 'checked' );
15264 };
15265
15266 /**
15267 * @inheritdoc
15268 */
15269 OO.ui.RadioInputWidget.prototype.gatherPreInfuseState = function ( node ) {
15270 var
15271 state = OO.ui.RadioInputWidget.parent.prototype.gatherPreInfuseState.call( this, node ),
15272 $input = $( node ).find( '.oo-ui-inputWidget-input' );
15273 state.$input = $input; // shortcut for performance, used in InputWidget
15274 state.checked = $input.prop( 'checked' );
15275 return state;
15276 };
15277
15278 /**
15279 * @inheritdoc
15280 */
15281 OO.ui.RadioInputWidget.prototype.restorePreInfuseState = function ( state ) {
15282 OO.ui.RadioInputWidget.parent.prototype.restorePreInfuseState.call( this, state );
15283 if ( state.checked !== undefined && state.checked !== this.isSelected() ) {
15284 this.setSelected( state.checked );
15285 }
15286 };
15287
15288 /**
15289 * RadioSelectInputWidget is a {@link OO.ui.RadioSelectWidget RadioSelectWidget} intended to be used
15290 * within a HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with the value
15291 * of a hidden HTML `input` tag. Please see the [OOjs UI documentation on MediaWiki][1] for
15292 * more information about input widgets.
15293 *
15294 * This and OO.ui.DropdownInputWidget support the same configuration options.
15295 *
15296 * @example
15297 * // Example: A RadioSelectInputWidget with three options
15298 * var radioSelectInput = new OO.ui.RadioSelectInputWidget( {
15299 * options: [
15300 * { data: 'a', label: 'First' },
15301 * { data: 'b', label: 'Second'},
15302 * { data: 'c', label: 'Third' }
15303 * ]
15304 * } );
15305 * $( 'body' ).append( radioSelectInput.$element );
15306 *
15307 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
15308 *
15309 * @class
15310 * @extends OO.ui.InputWidget
15311 *
15312 * @constructor
15313 * @param {Object} [config] Configuration options
15314 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
15315 */
15316 OO.ui.RadioSelectInputWidget = function OoUiRadioSelectInputWidget( config ) {
15317 // Configuration initialization
15318 config = config || {};
15319
15320 // Properties (must be done before parent constructor which calls #setDisabled)
15321 this.radioSelectWidget = new OO.ui.RadioSelectWidget();
15322
15323 // Parent constructor
15324 OO.ui.RadioSelectInputWidget.parent.call( this, config );
15325
15326 // Events
15327 this.radioSelectWidget.connect( this, { select: 'onMenuSelect' } );
15328
15329 // Initialization
15330 this.setOptions( config.options || [] );
15331 this.$element
15332 .addClass( 'oo-ui-radioSelectInputWidget' )
15333 .append( this.radioSelectWidget.$element );
15334 };
15335
15336 /* Setup */
15337
15338 OO.inheritClass( OO.ui.RadioSelectInputWidget, OO.ui.InputWidget );
15339
15340 /* Static Properties */
15341
15342 OO.ui.RadioSelectInputWidget.static.supportsSimpleLabel = false;
15343
15344 /* Methods */
15345
15346 /**
15347 * @inheritdoc
15348 * @protected
15349 */
15350 OO.ui.RadioSelectInputWidget.prototype.getInputElement = function () {
15351 return $( '<input type="hidden">' );
15352 };
15353
15354 /**
15355 * Handles menu select events.
15356 *
15357 * @private
15358 * @param {OO.ui.RadioOptionWidget} item Selected menu item
15359 */
15360 OO.ui.RadioSelectInputWidget.prototype.onMenuSelect = function ( item ) {
15361 this.setValue( item.getData() );
15362 };
15363
15364 /**
15365 * @inheritdoc
15366 */
15367 OO.ui.RadioSelectInputWidget.prototype.setValue = function ( value ) {
15368 value = this.cleanUpValue( value );
15369 this.radioSelectWidget.selectItemByData( value );
15370 OO.ui.RadioSelectInputWidget.parent.prototype.setValue.call( this, value );
15371 return this;
15372 };
15373
15374 /**
15375 * @inheritdoc
15376 */
15377 OO.ui.RadioSelectInputWidget.prototype.setDisabled = function ( state ) {
15378 this.radioSelectWidget.setDisabled( state );
15379 OO.ui.RadioSelectInputWidget.parent.prototype.setDisabled.call( this, state );
15380 return this;
15381 };
15382
15383 /**
15384 * Set the options available for this input.
15385 *
15386 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
15387 * @chainable
15388 */
15389 OO.ui.RadioSelectInputWidget.prototype.setOptions = function ( options ) {
15390 var
15391 value = this.getValue(),
15392 widget = this;
15393
15394 // Rebuild the radioSelect menu
15395 this.radioSelectWidget
15396 .clearItems()
15397 .addItems( options.map( function ( opt ) {
15398 var optValue = widget.cleanUpValue( opt.data );
15399 return new OO.ui.RadioOptionWidget( {
15400 data: optValue,
15401 label: opt.label !== undefined ? opt.label : optValue
15402 } );
15403 } ) );
15404
15405 // Restore the previous value, or reset to something sensible
15406 if ( this.radioSelectWidget.getItemFromData( value ) ) {
15407 // Previous value is still available, ensure consistency with the radioSelect
15408 this.setValue( value );
15409 } else {
15410 // No longer valid, reset
15411 if ( options.length ) {
15412 this.setValue( options[ 0 ].data );
15413 }
15414 }
15415
15416 return this;
15417 };
15418
15419 /**
15420 * @inheritdoc
15421 */
15422 OO.ui.RadioSelectInputWidget.prototype.gatherPreInfuseState = function ( node ) {
15423 var state = OO.ui.RadioSelectInputWidget.parent.prototype.gatherPreInfuseState.call( this, node );
15424 state.value = $( node ).find( '.oo-ui-radioInputWidget .oo-ui-inputWidget-input:checked' ).val();
15425 return state;
15426 };
15427
15428 /**
15429 * TextInputWidgets, like HTML text inputs, can be configured with options that customize the
15430 * size of the field as well as its presentation. In addition, these widgets can be configured
15431 * with {@link OO.ui.mixin.IconElement icons}, {@link OO.ui.mixin.IndicatorElement indicators}, an optional
15432 * validation-pattern (used to determine if an input value is valid or not) and an input filter,
15433 * which modifies incoming values rather than validating them.
15434 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
15435 *
15436 * This widget can be used inside a HTML form, such as a OO.ui.FormLayout.
15437 *
15438 * @example
15439 * // Example of a text input widget
15440 * var textInput = new OO.ui.TextInputWidget( {
15441 * value: 'Text input'
15442 * } )
15443 * $( 'body' ).append( textInput.$element );
15444 *
15445 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
15446 *
15447 * @class
15448 * @extends OO.ui.InputWidget
15449 * @mixins OO.ui.mixin.IconElement
15450 * @mixins OO.ui.mixin.IndicatorElement
15451 * @mixins OO.ui.mixin.PendingElement
15452 * @mixins OO.ui.mixin.LabelElement
15453 *
15454 * @constructor
15455 * @param {Object} [config] Configuration options
15456 * @cfg {string} [type='text'] The value of the HTML `type` attribute: 'text', 'password', 'search',
15457 * 'email' or 'url'. Ignored if `multiline` is true.
15458 *
15459 * Some values of `type` result in additional behaviors:
15460 *
15461 * - `search`: implies `icon: 'search'` and `indicator: 'clear'`; when clicked, the indicator
15462 * empties the text field
15463 * @cfg {string} [placeholder] Placeholder text
15464 * @cfg {boolean} [autofocus=false] Use an HTML `autofocus` attribute to
15465 * instruct the browser to focus this widget.
15466 * @cfg {boolean} [readOnly=false] Prevent changes to the value of the text input.
15467 * @cfg {number} [maxLength] Maximum number of characters allowed in the input.
15468 * @cfg {boolean} [multiline=false] Allow multiple lines of text
15469 * @cfg {number} [rows] If multiline, number of visible lines in textarea. If used with `autosize`,
15470 * specifies minimum number of rows to display.
15471 * @cfg {boolean} [autosize=false] Automatically resize the text input to fit its content.
15472 * Use the #maxRows config to specify a maximum number of displayed rows.
15473 * @cfg {boolean} [maxRows] Maximum number of rows to display when #autosize is set to true.
15474 * Defaults to the maximum of `10` and `2 * rows`, or `10` if `rows` isn't provided.
15475 * @cfg {string} [labelPosition='after'] The position of the inline label relative to that of
15476 * the value or placeholder text: `'before'` or `'after'`
15477 * @cfg {boolean} [required=false] Mark the field as required. Implies `indicator: 'required'`.
15478 * @cfg {boolean} [autocomplete=true] Should the browser support autocomplete for this field
15479 * @cfg {RegExp|Function|string} [validate] Validation pattern: when string, a symbolic name of a
15480 * pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer'
15481 * (the value must contain only numbers); when RegExp, a regular expression that must match the
15482 * value for it to be considered valid; when Function, a function receiving the value as parameter
15483 * that must return true, or promise resolving to true, for it to be considered valid.
15484 */
15485 OO.ui.TextInputWidget = function OoUiTextInputWidget( config ) {
15486 // Configuration initialization
15487 config = $.extend( {
15488 type: 'text',
15489 labelPosition: 'after'
15490 }, config );
15491 if ( config.type === 'search' ) {
15492 if ( config.icon === undefined ) {
15493 config.icon = 'search';
15494 }
15495 // indicator: 'clear' is set dynamically later, depending on value
15496 }
15497 if ( config.required ) {
15498 if ( config.indicator === undefined ) {
15499 config.indicator = 'required';
15500 }
15501 }
15502
15503 // Parent constructor
15504 OO.ui.TextInputWidget.parent.call( this, config );
15505
15506 // Mixin constructors
15507 OO.ui.mixin.IconElement.call( this, config );
15508 OO.ui.mixin.IndicatorElement.call( this, config );
15509 OO.ui.mixin.PendingElement.call( this, $.extend( {}, config, { $pending: this.$input } ) );
15510 OO.ui.mixin.LabelElement.call( this, config );
15511
15512 // Properties
15513 this.type = this.getSaneType( config );
15514 this.readOnly = false;
15515 this.multiline = !!config.multiline;
15516 this.autosize = !!config.autosize;
15517 this.minRows = config.rows !== undefined ? config.rows : '';
15518 this.maxRows = config.maxRows || Math.max( 2 * ( this.minRows || 0 ), 10 );
15519 this.validate = null;
15520
15521 // Clone for resizing
15522 if ( this.autosize ) {
15523 this.$clone = this.$input
15524 .clone()
15525 .insertAfter( this.$input )
15526 .attr( 'aria-hidden', 'true' )
15527 .addClass( 'oo-ui-element-hidden' );
15528 }
15529
15530 this.setValidation( config.validate );
15531 this.setLabelPosition( config.labelPosition );
15532
15533 // Events
15534 this.$input.on( {
15535 keypress: this.onKeyPress.bind( this ),
15536 blur: this.onBlur.bind( this )
15537 } );
15538 this.$input.one( {
15539 focus: this.onElementAttach.bind( this )
15540 } );
15541 this.$icon.on( 'mousedown', this.onIconMouseDown.bind( this ) );
15542 this.$indicator.on( 'mousedown', this.onIndicatorMouseDown.bind( this ) );
15543 this.on( 'labelChange', this.updatePosition.bind( this ) );
15544 this.connect( this, {
15545 change: 'onChange',
15546 disable: 'onDisable'
15547 } );
15548
15549 // Initialization
15550 this.$element
15551 .addClass( 'oo-ui-textInputWidget oo-ui-textInputWidget-type-' + this.type )
15552 .append( this.$icon, this.$indicator );
15553 this.setReadOnly( !!config.readOnly );
15554 this.updateSearchIndicator();
15555 if ( config.placeholder ) {
15556 this.$input.attr( 'placeholder', config.placeholder );
15557 }
15558 if ( config.maxLength !== undefined ) {
15559 this.$input.attr( 'maxlength', config.maxLength );
15560 }
15561 if ( config.autofocus ) {
15562 this.$input.attr( 'autofocus', 'autofocus' );
15563 }
15564 if ( config.required ) {
15565 this.$input.attr( 'required', 'required' );
15566 this.$input.attr( 'aria-required', 'true' );
15567 }
15568 if ( config.autocomplete === false ) {
15569 this.$input.attr( 'autocomplete', 'off' );
15570 // Turning off autocompletion also disables "form caching" when the user navigates to a
15571 // different page and then clicks "Back". Re-enable it when leaving. Borrowed from jQuery UI.
15572 $( window ).on( {
15573 beforeunload: function () {
15574 this.$input.removeAttr( 'autocomplete' );
15575 }.bind( this ),
15576 pageshow: function () {
15577 // Browsers don't seem to actually fire this event on "Back", they instead just reload the
15578 // whole page... it shouldn't hurt, though.
15579 this.$input.attr( 'autocomplete', 'off' );
15580 }.bind( this )
15581 } );
15582 }
15583 if ( this.multiline && config.rows ) {
15584 this.$input.attr( 'rows', config.rows );
15585 }
15586 if ( this.label || config.autosize ) {
15587 this.installParentChangeDetector();
15588 }
15589 };
15590
15591 /* Setup */
15592
15593 OO.inheritClass( OO.ui.TextInputWidget, OO.ui.InputWidget );
15594 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.mixin.IconElement );
15595 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.mixin.IndicatorElement );
15596 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.mixin.PendingElement );
15597 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.mixin.LabelElement );
15598
15599 /* Static Properties */
15600
15601 OO.ui.TextInputWidget.static.validationPatterns = {
15602 'non-empty': /.+/,
15603 integer: /^\d+$/
15604 };
15605
15606 /* Events */
15607
15608 /**
15609 * An `enter` event is emitted when the user presses 'enter' inside the text box.
15610 *
15611 * Not emitted if the input is multiline.
15612 *
15613 * @event enter
15614 */
15615
15616 /* Methods */
15617
15618 /**
15619 * Handle icon mouse down events.
15620 *
15621 * @private
15622 * @param {jQuery.Event} e Mouse down event
15623 * @fires icon
15624 */
15625 OO.ui.TextInputWidget.prototype.onIconMouseDown = function ( e ) {
15626 if ( e.which === 1 ) {
15627 this.$input[ 0 ].focus();
15628 return false;
15629 }
15630 };
15631
15632 /**
15633 * Handle indicator mouse down events.
15634 *
15635 * @private
15636 * @param {jQuery.Event} e Mouse down event
15637 * @fires indicator
15638 */
15639 OO.ui.TextInputWidget.prototype.onIndicatorMouseDown = function ( e ) {
15640 if ( e.which === 1 ) {
15641 if ( this.type === 'search' ) {
15642 // Clear the text field
15643 this.setValue( '' );
15644 }
15645 this.$input[ 0 ].focus();
15646 return false;
15647 }
15648 };
15649
15650 /**
15651 * Handle key press events.
15652 *
15653 * @private
15654 * @param {jQuery.Event} e Key press event
15655 * @fires enter If enter key is pressed and input is not multiline
15656 */
15657 OO.ui.TextInputWidget.prototype.onKeyPress = function ( e ) {
15658 if ( e.which === OO.ui.Keys.ENTER && !this.multiline ) {
15659 this.emit( 'enter', e );
15660 }
15661 };
15662
15663 /**
15664 * Handle blur events.
15665 *
15666 * @private
15667 * @param {jQuery.Event} e Blur event
15668 */
15669 OO.ui.TextInputWidget.prototype.onBlur = function () {
15670 this.setValidityFlag();
15671 };
15672
15673 /**
15674 * Handle element attach events.
15675 *
15676 * @private
15677 * @param {jQuery.Event} e Element attach event
15678 */
15679 OO.ui.TextInputWidget.prototype.onElementAttach = function () {
15680 // Any previously calculated size is now probably invalid if we reattached elsewhere
15681 this.valCache = null;
15682 this.adjustSize();
15683 this.positionLabel();
15684 };
15685
15686 /**
15687 * Handle change events.
15688 *
15689 * @param {string} value
15690 * @private
15691 */
15692 OO.ui.TextInputWidget.prototype.onChange = function () {
15693 this.updateSearchIndicator();
15694 this.setValidityFlag();
15695 this.adjustSize();
15696 };
15697
15698 /**
15699 * Handle disable events.
15700 *
15701 * @param {boolean} disabled Element is disabled
15702 * @private
15703 */
15704 OO.ui.TextInputWidget.prototype.onDisable = function () {
15705 this.updateSearchIndicator();
15706 };
15707
15708 /**
15709 * Check if the input is {@link #readOnly read-only}.
15710 *
15711 * @return {boolean}
15712 */
15713 OO.ui.TextInputWidget.prototype.isReadOnly = function () {
15714 return this.readOnly;
15715 };
15716
15717 /**
15718 * Set the {@link #readOnly read-only} state of the input.
15719 *
15720 * @param {boolean} state Make input read-only
15721 * @chainable
15722 */
15723 OO.ui.TextInputWidget.prototype.setReadOnly = function ( state ) {
15724 this.readOnly = !!state;
15725 this.$input.prop( 'readOnly', this.readOnly );
15726 this.updateSearchIndicator();
15727 return this;
15728 };
15729
15730 /**
15731 * Support function for making #onElementAttach work across browsers.
15732 *
15733 * This whole function could be replaced with one line of code using the DOMNodeInsertedIntoDocument
15734 * event, but it's not supported by Firefox and allegedly deprecated, so we only use it as fallback.
15735 *
15736 * Due to MutationObserver performance woes, #onElementAttach is only somewhat reliably called the
15737 * first time that the element gets attached to the documented.
15738 */
15739 OO.ui.TextInputWidget.prototype.installParentChangeDetector = function () {
15740 var mutationObserver, onRemove, topmostNode, fakeParentNode,
15741 MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver,
15742 widget = this;
15743
15744 if ( MutationObserver ) {
15745 // The new way. If only it wasn't so ugly.
15746
15747 if ( this.$element.closest( 'html' ).length ) {
15748 // Widget is attached already, do nothing. This breaks the functionality of this function when
15749 // the widget is detached and reattached. Alas, doing this correctly with MutationObserver
15750 // would require observation of the whole document, which would hurt performance of other,
15751 // more important code.
15752 return;
15753 }
15754
15755 // Find topmost node in the tree
15756 topmostNode = this.$element[ 0 ];
15757 while ( topmostNode.parentNode ) {
15758 topmostNode = topmostNode.parentNode;
15759 }
15760
15761 // We have no way to detect the $element being attached somewhere without observing the entire
15762 // DOM with subtree modifications, which would hurt performance. So we cheat: we hook to the
15763 // parent node of $element, and instead detect when $element is removed from it (and thus
15764 // probably attached somewhere else). If there is no parent, we create a "fake" one. If it
15765 // doesn't get attached, we end up back here and create the parent.
15766
15767 mutationObserver = new MutationObserver( function ( mutations ) {
15768 var i, j, removedNodes;
15769 for ( i = 0; i < mutations.length; i++ ) {
15770 removedNodes = mutations[ i ].removedNodes;
15771 for ( j = 0; j < removedNodes.length; j++ ) {
15772 if ( removedNodes[ j ] === topmostNode ) {
15773 setTimeout( onRemove, 0 );
15774 return;
15775 }
15776 }
15777 }
15778 } );
15779
15780 onRemove = function () {
15781 // If the node was attached somewhere else, report it
15782 if ( widget.$element.closest( 'html' ).length ) {
15783 widget.onElementAttach();
15784 }
15785 mutationObserver.disconnect();
15786 widget.installParentChangeDetector();
15787 };
15788
15789 // Create a fake parent and observe it
15790 fakeParentNode = $( '<div>' ).append( topmostNode )[ 0 ];
15791 mutationObserver.observe( fakeParentNode, { childList: true } );
15792 } else {
15793 // Using the DOMNodeInsertedIntoDocument event is much nicer and less magical, and works for
15794 // detachment and reattachment, but it's not supported by Firefox and allegedly deprecated.
15795 this.$element.on( 'DOMNodeInsertedIntoDocument', this.onElementAttach.bind( this ) );
15796 }
15797 };
15798
15799 /**
15800 * Automatically adjust the size of the text input.
15801 *
15802 * This only affects #multiline inputs that are {@link #autosize autosized}.
15803 *
15804 * @chainable
15805 */
15806 OO.ui.TextInputWidget.prototype.adjustSize = function () {
15807 var scrollHeight, innerHeight, outerHeight, maxInnerHeight, measurementError, idealHeight;
15808
15809 if ( this.multiline && this.autosize && this.$input.val() !== this.valCache ) {
15810 this.$clone
15811 .val( this.$input.val() )
15812 .attr( 'rows', this.minRows )
15813 // Set inline height property to 0 to measure scroll height
15814 .css( 'height', 0 );
15815
15816 this.$clone.removeClass( 'oo-ui-element-hidden' );
15817
15818 this.valCache = this.$input.val();
15819
15820 scrollHeight = this.$clone[ 0 ].scrollHeight;
15821
15822 // Remove inline height property to measure natural heights
15823 this.$clone.css( 'height', '' );
15824 innerHeight = this.$clone.innerHeight();
15825 outerHeight = this.$clone.outerHeight();
15826
15827 // Measure max rows height
15828 this.$clone
15829 .attr( 'rows', this.maxRows )
15830 .css( 'height', 'auto' )
15831 .val( '' );
15832 maxInnerHeight = this.$clone.innerHeight();
15833
15834 // Difference between reported innerHeight and scrollHeight with no scrollbars present
15835 // Equals 1 on Blink-based browsers and 0 everywhere else
15836 measurementError = maxInnerHeight - this.$clone[ 0 ].scrollHeight;
15837 idealHeight = Math.min( maxInnerHeight, scrollHeight + measurementError );
15838
15839 this.$clone.addClass( 'oo-ui-element-hidden' );
15840
15841 // Only apply inline height when expansion beyond natural height is needed
15842 if ( idealHeight > innerHeight ) {
15843 // Use the difference between the inner and outer height as a buffer
15844 this.$input.css( 'height', idealHeight + ( outerHeight - innerHeight ) );
15845 } else {
15846 this.$input.css( 'height', '' );
15847 }
15848 }
15849 return this;
15850 };
15851
15852 /**
15853 * @inheritdoc
15854 * @protected
15855 */
15856 OO.ui.TextInputWidget.prototype.getInputElement = function ( config ) {
15857 return config.multiline ?
15858 $( '<textarea>' ) :
15859 $( '<input type="' + this.getSaneType( config ) + '" />' );
15860 };
15861
15862 /**
15863 * Get sanitized value for 'type' for given config.
15864 *
15865 * @param {Object} config Configuration options
15866 * @return {string|null}
15867 * @private
15868 */
15869 OO.ui.TextInputWidget.prototype.getSaneType = function ( config ) {
15870 var type = [ 'text', 'password', 'search', 'email', 'url' ].indexOf( config.type ) !== -1 ?
15871 config.type :
15872 'text';
15873 return config.multiline ? 'multiline' : type;
15874 };
15875
15876 /**
15877 * Check if the input supports multiple lines.
15878 *
15879 * @return {boolean}
15880 */
15881 OO.ui.TextInputWidget.prototype.isMultiline = function () {
15882 return !!this.multiline;
15883 };
15884
15885 /**
15886 * Check if the input automatically adjusts its size.
15887 *
15888 * @return {boolean}
15889 */
15890 OO.ui.TextInputWidget.prototype.isAutosizing = function () {
15891 return !!this.autosize;
15892 };
15893
15894 /**
15895 * Select the entire text of the input.
15896 *
15897 * @chainable
15898 */
15899 OO.ui.TextInputWidget.prototype.select = function () {
15900 this.$input.select();
15901 return this;
15902 };
15903
15904 /**
15905 * Focus the input and move the cursor to the end.
15906 */
15907 OO.ui.TextInputWidget.prototype.moveCursorToEnd = function () {
15908 var textRange,
15909 element = this.$input[ 0 ];
15910 this.focus();
15911 if ( element.selectionStart !== undefined ) {
15912 element.selectionStart = element.selectionEnd = element.value.length;
15913 } else if ( element.createTextRange ) {
15914 // IE 8 and below
15915 textRange = element.createTextRange();
15916 textRange.collapse( false );
15917 textRange.select();
15918 }
15919 };
15920
15921 /**
15922 * Set the validation pattern.
15923 *
15924 * The validation pattern is either a regular expression, a function, or the symbolic name of a
15925 * pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer' (the
15926 * value must contain only numbers).
15927 *
15928 * @param {RegExp|Function|string|null} validate Regular expression, function, or the symbolic name
15929 * of a pattern (either ‘integer’ or ‘non-empty’) defined by the class.
15930 */
15931 OO.ui.TextInputWidget.prototype.setValidation = function ( validate ) {
15932 if ( validate instanceof RegExp || validate instanceof Function ) {
15933 this.validate = validate;
15934 } else {
15935 this.validate = this.constructor.static.validationPatterns[ validate ] || /.*/;
15936 }
15937 };
15938
15939 /**
15940 * Sets the 'invalid' flag appropriately.
15941 *
15942 * @param {boolean} [isValid] Optionally override validation result
15943 */
15944 OO.ui.TextInputWidget.prototype.setValidityFlag = function ( isValid ) {
15945 var widget = this,
15946 setFlag = function ( valid ) {
15947 if ( !valid ) {
15948 widget.$input.attr( 'aria-invalid', 'true' );
15949 } else {
15950 widget.$input.removeAttr( 'aria-invalid' );
15951 }
15952 widget.setFlags( { invalid: !valid } );
15953 };
15954
15955 if ( isValid !== undefined ) {
15956 setFlag( isValid );
15957 } else {
15958 this.getValidity().then( function () {
15959 setFlag( true );
15960 }, function () {
15961 setFlag( false );
15962 } );
15963 }
15964 };
15965
15966 /**
15967 * Check if a value is valid.
15968 *
15969 * This method returns a promise that resolves with a boolean `true` if the current value is
15970 * considered valid according to the supplied {@link #validate validation pattern}.
15971 *
15972 * @deprecated
15973 * @return {jQuery.Promise} A promise that resolves to a boolean `true` if the value is valid.
15974 */
15975 OO.ui.TextInputWidget.prototype.isValid = function () {
15976 var result;
15977
15978 if ( this.validate instanceof Function ) {
15979 result = this.validate( this.getValue() );
15980 if ( $.isFunction( result.promise ) ) {
15981 return result.promise();
15982 } else {
15983 return $.Deferred().resolve( !!result ).promise();
15984 }
15985 } else {
15986 return $.Deferred().resolve( !!this.getValue().match( this.validate ) ).promise();
15987 }
15988 };
15989
15990 /**
15991 * Get the validity of current value.
15992 *
15993 * This method returns a promise that resolves if the value is valid and rejects if
15994 * it isn't. Uses the {@link #validate validation pattern} to check for validity.
15995 *
15996 * @return {jQuery.Promise} A promise that resolves if the value is valid, rejects if not.
15997 */
15998 OO.ui.TextInputWidget.prototype.getValidity = function () {
15999 var result, promise;
16000
16001 function rejectOrResolve( valid ) {
16002 if ( valid ) {
16003 return $.Deferred().resolve().promise();
16004 } else {
16005 return $.Deferred().reject().promise();
16006 }
16007 }
16008
16009 if ( this.validate instanceof Function ) {
16010 result = this.validate( this.getValue() );
16011
16012 if ( $.isFunction( result.promise ) ) {
16013 promise = $.Deferred();
16014
16015 result.then( function ( valid ) {
16016 if ( valid ) {
16017 promise.resolve();
16018 } else {
16019 promise.reject();
16020 }
16021 }, function () {
16022 promise.reject();
16023 } );
16024
16025 return promise.promise();
16026 } else {
16027 return rejectOrResolve( result );
16028 }
16029 } else {
16030 return rejectOrResolve( this.getValue().match( this.validate ) );
16031 }
16032 };
16033
16034 /**
16035 * Set the position of the inline label relative to that of the value: `‘before’` or `‘after’`.
16036 *
16037 * @param {string} labelPosition Label position, 'before' or 'after'
16038 * @chainable
16039 */
16040 OO.ui.TextInputWidget.prototype.setLabelPosition = function ( labelPosition ) {
16041 this.labelPosition = labelPosition;
16042 this.updatePosition();
16043 return this;
16044 };
16045
16046 /**
16047 * Deprecated alias of #setLabelPosition
16048 *
16049 * @deprecated Use setLabelPosition instead.
16050 */
16051 OO.ui.TextInputWidget.prototype.setPosition =
16052 OO.ui.TextInputWidget.prototype.setLabelPosition;
16053
16054 /**
16055 * Update the position of the inline label.
16056 *
16057 * This method is called by #setLabelPosition, and can also be called on its own if
16058 * something causes the label to be mispositioned.
16059 *
16060 * @chainable
16061 */
16062 OO.ui.TextInputWidget.prototype.updatePosition = function () {
16063 var after = this.labelPosition === 'after';
16064
16065 this.$element
16066 .toggleClass( 'oo-ui-textInputWidget-labelPosition-after', !!this.label && after )
16067 .toggleClass( 'oo-ui-textInputWidget-labelPosition-before', !!this.label && !after );
16068
16069 this.positionLabel();
16070
16071 return this;
16072 };
16073
16074 /**
16075 * Update the 'clear' indicator displayed on type: 'search' text fields, hiding it when the field is
16076 * already empty or when it's not editable.
16077 */
16078 OO.ui.TextInputWidget.prototype.updateSearchIndicator = function () {
16079 if ( this.type === 'search' ) {
16080 if ( this.getValue() === '' || this.isDisabled() || this.isReadOnly() ) {
16081 this.setIndicator( null );
16082 } else {
16083 this.setIndicator( 'clear' );
16084 }
16085 }
16086 };
16087
16088 /**
16089 * Position the label by setting the correct padding on the input.
16090 *
16091 * @private
16092 * @chainable
16093 */
16094 OO.ui.TextInputWidget.prototype.positionLabel = function () {
16095 var after, rtl, property;
16096 // Clear old values
16097 this.$input
16098 // Clear old values if present
16099 .css( {
16100 'padding-right': '',
16101 'padding-left': ''
16102 } );
16103
16104 if ( this.label ) {
16105 this.$element.append( this.$label );
16106 } else {
16107 this.$label.detach();
16108 return;
16109 }
16110
16111 after = this.labelPosition === 'after';
16112 rtl = this.$element.css( 'direction' ) === 'rtl';
16113 property = after === rtl ? 'padding-left' : 'padding-right';
16114
16115 this.$input.css( property, this.$label.outerWidth( true ) );
16116
16117 return this;
16118 };
16119
16120 /**
16121 * @inheritdoc
16122 */
16123 OO.ui.TextInputWidget.prototype.gatherPreInfuseState = function ( node ) {
16124 var
16125 state = OO.ui.TextInputWidget.parent.prototype.gatherPreInfuseState.call( this, node ),
16126 $input = $( node ).find( '.oo-ui-inputWidget-input' );
16127 state.$input = $input; // shortcut for performance, used in InputWidget
16128 if ( this.multiline ) {
16129 state.scrollTop = $input.scrollTop();
16130 }
16131 return state;
16132 };
16133
16134 /**
16135 * @inheritdoc
16136 */
16137 OO.ui.TextInputWidget.prototype.restorePreInfuseState = function ( state ) {
16138 OO.ui.TextInputWidget.parent.prototype.restorePreInfuseState.call( this, state );
16139 if ( state.scrollTop !== undefined ) {
16140 this.$input.scrollTop( state.scrollTop );
16141 }
16142 };
16143
16144 /**
16145 * ComboBoxWidgets combine a {@link OO.ui.TextInputWidget text input} (where a value
16146 * can be entered manually) and a {@link OO.ui.MenuSelectWidget menu of options} (from which
16147 * a value can be chosen instead). Users can choose options from the combo box in one of two ways:
16148 *
16149 * - by typing a value in the text input field. If the value exactly matches the value of a menu
16150 * option, that option will appear to be selected.
16151 * - by choosing a value from the menu. The value of the chosen option will then appear in the text
16152 * input field.
16153 *
16154 * For more information about menus and options, please see the [OOjs UI documentation on MediaWiki][1].
16155 *
16156 * @example
16157 * // Example: A ComboBoxWidget.
16158 * var comboBox = new OO.ui.ComboBoxWidget( {
16159 * label: 'ComboBoxWidget',
16160 * input: { value: 'Option One' },
16161 * menu: {
16162 * items: [
16163 * new OO.ui.MenuOptionWidget( {
16164 * data: 'Option 1',
16165 * label: 'Option One'
16166 * } ),
16167 * new OO.ui.MenuOptionWidget( {
16168 * data: 'Option 2',
16169 * label: 'Option Two'
16170 * } ),
16171 * new OO.ui.MenuOptionWidget( {
16172 * data: 'Option 3',
16173 * label: 'Option Three'
16174 * } ),
16175 * new OO.ui.MenuOptionWidget( {
16176 * data: 'Option 4',
16177 * label: 'Option Four'
16178 * } ),
16179 * new OO.ui.MenuOptionWidget( {
16180 * data: 'Option 5',
16181 * label: 'Option Five'
16182 * } )
16183 * ]
16184 * }
16185 * } );
16186 * $( 'body' ).append( comboBox.$element );
16187 *
16188 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
16189 *
16190 * @class
16191 * @extends OO.ui.Widget
16192 * @mixins OO.ui.mixin.TabIndexedElement
16193 *
16194 * @constructor
16195 * @param {Object} [config] Configuration options
16196 * @cfg {Object} [menu] Configuration options to pass to the {@link OO.ui.FloatingMenuSelectWidget menu select widget}.
16197 * @cfg {Object} [input] Configuration options to pass to the {@link OO.ui.TextInputWidget text input widget}.
16198 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
16199 * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
16200 * containing `<div>` and has a larger area. By default, the menu uses relative positioning.
16201 */
16202 OO.ui.ComboBoxWidget = function OoUiComboBoxWidget( config ) {
16203 // Configuration initialization
16204 config = config || {};
16205
16206 // Parent constructor
16207 OO.ui.ComboBoxWidget.parent.call( this, config );
16208
16209 // Properties (must be set before TabIndexedElement constructor call)
16210 this.$indicator = this.$( '<span>' );
16211
16212 // Mixin constructors
16213 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$indicator } ) );
16214
16215 // Properties
16216 this.$overlay = config.$overlay || this.$element;
16217 this.input = new OO.ui.TextInputWidget( $.extend(
16218 {
16219 indicator: 'down',
16220 $indicator: this.$indicator,
16221 disabled: this.isDisabled()
16222 },
16223 config.input
16224 ) );
16225 this.input.$input.eq( 0 ).attr( {
16226 role: 'combobox',
16227 'aria-autocomplete': 'list'
16228 } );
16229 this.menu = new OO.ui.FloatingMenuSelectWidget( $.extend(
16230 {
16231 widget: this,
16232 input: this.input,
16233 $container: this.input.$element,
16234 disabled: this.isDisabled()
16235 },
16236 config.menu
16237 ) );
16238
16239 // Events
16240 this.$indicator.on( {
16241 click: this.onClick.bind( this ),
16242 keypress: this.onKeyPress.bind( this )
16243 } );
16244 this.input.connect( this, {
16245 change: 'onInputChange',
16246 enter: 'onInputEnter'
16247 } );
16248 this.menu.connect( this, {
16249 choose: 'onMenuChoose',
16250 add: 'onMenuItemsChange',
16251 remove: 'onMenuItemsChange'
16252 } );
16253
16254 // Initialization
16255 this.$element.addClass( 'oo-ui-comboBoxWidget' ).append( this.input.$element );
16256 this.$overlay.append( this.menu.$element );
16257 this.onMenuItemsChange();
16258 };
16259
16260 /* Setup */
16261
16262 OO.inheritClass( OO.ui.ComboBoxWidget, OO.ui.Widget );
16263 OO.mixinClass( OO.ui.ComboBoxWidget, OO.ui.mixin.TabIndexedElement );
16264
16265 /* Methods */
16266
16267 /**
16268 * Get the combobox's menu.
16269 * @return {OO.ui.FloatingMenuSelectWidget} Menu widget
16270 */
16271 OO.ui.ComboBoxWidget.prototype.getMenu = function () {
16272 return this.menu;
16273 };
16274
16275 /**
16276 * Get the combobox's text input widget.
16277 * @return {OO.ui.TextInputWidget} Text input widget
16278 */
16279 OO.ui.ComboBoxWidget.prototype.getInput = function () {
16280 return this.input;
16281 };
16282
16283 /**
16284 * Handle input change events.
16285 *
16286 * @private
16287 * @param {string} value New value
16288 */
16289 OO.ui.ComboBoxWidget.prototype.onInputChange = function ( value ) {
16290 var match = this.menu.getItemFromData( value );
16291
16292 this.menu.selectItem( match );
16293 if ( this.menu.getHighlightedItem() ) {
16294 this.menu.highlightItem( match );
16295 }
16296
16297 if ( !this.isDisabled() ) {
16298 this.menu.toggle( true );
16299 }
16300 };
16301
16302 /**
16303 * Handle mouse click events.
16304 *
16305 * @private
16306 * @param {jQuery.Event} e Mouse click event
16307 */
16308 OO.ui.ComboBoxWidget.prototype.onClick = function ( e ) {
16309 if ( !this.isDisabled() && e.which === 1 ) {
16310 this.menu.toggle();
16311 this.input.$input[ 0 ].focus();
16312 }
16313 return false;
16314 };
16315
16316 /**
16317 * Handle key press events.
16318 *
16319 * @private
16320 * @param {jQuery.Event} e Key press event
16321 */
16322 OO.ui.ComboBoxWidget.prototype.onKeyPress = function ( e ) {
16323 if ( !this.isDisabled() && ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER ) ) {
16324 this.menu.toggle();
16325 this.input.$input[ 0 ].focus();
16326 return false;
16327 }
16328 };
16329
16330 /**
16331 * Handle input enter events.
16332 *
16333 * @private
16334 */
16335 OO.ui.ComboBoxWidget.prototype.onInputEnter = function () {
16336 if ( !this.isDisabled() ) {
16337 this.menu.toggle( false );
16338 }
16339 };
16340
16341 /**
16342 * Handle menu choose events.
16343 *
16344 * @private
16345 * @param {OO.ui.OptionWidget} item Chosen item
16346 */
16347 OO.ui.ComboBoxWidget.prototype.onMenuChoose = function ( item ) {
16348 this.input.setValue( item.getData() );
16349 };
16350
16351 /**
16352 * Handle menu item change events.
16353 *
16354 * @private
16355 */
16356 OO.ui.ComboBoxWidget.prototype.onMenuItemsChange = function () {
16357 var match = this.menu.getItemFromData( this.input.getValue() );
16358 this.menu.selectItem( match );
16359 if ( this.menu.getHighlightedItem() ) {
16360 this.menu.highlightItem( match );
16361 }
16362 this.$element.toggleClass( 'oo-ui-comboBoxWidget-empty', this.menu.isEmpty() );
16363 };
16364
16365 /**
16366 * @inheritdoc
16367 */
16368 OO.ui.ComboBoxWidget.prototype.setDisabled = function ( disabled ) {
16369 // Parent method
16370 OO.ui.ComboBoxWidget.parent.prototype.setDisabled.call( this, disabled );
16371
16372 if ( this.input ) {
16373 this.input.setDisabled( this.isDisabled() );
16374 }
16375 if ( this.menu ) {
16376 this.menu.setDisabled( this.isDisabled() );
16377 }
16378
16379 return this;
16380 };
16381
16382 /**
16383 * LabelWidgets help identify the function of interface elements. Each LabelWidget can
16384 * be configured with a `label` option that is set to a string, a label node, or a function:
16385 *
16386 * - String: a plaintext string
16387 * - jQuery selection: a jQuery selection, used for anything other than a plaintext label, e.g., a
16388 * label that includes a link or special styling, such as a gray color or additional graphical elements.
16389 * - Function: a function that will produce a string in the future. Functions are used
16390 * in cases where the value of the label is not currently defined.
16391 *
16392 * In addition, the LabelWidget can be associated with an {@link OO.ui.InputWidget input widget}, which
16393 * will come into focus when the label is clicked.
16394 *
16395 * @example
16396 * // Examples of LabelWidgets
16397 * var label1 = new OO.ui.LabelWidget( {
16398 * label: 'plaintext label'
16399 * } );
16400 * var label2 = new OO.ui.LabelWidget( {
16401 * label: $( '<a href="default.html">jQuery label</a>' )
16402 * } );
16403 * // Create a fieldset layout with fields for each example
16404 * var fieldset = new OO.ui.FieldsetLayout();
16405 * fieldset.addItems( [
16406 * new OO.ui.FieldLayout( label1 ),
16407 * new OO.ui.FieldLayout( label2 )
16408 * ] );
16409 * $( 'body' ).append( fieldset.$element );
16410 *
16411 * @class
16412 * @extends OO.ui.Widget
16413 * @mixins OO.ui.mixin.LabelElement
16414 *
16415 * @constructor
16416 * @param {Object} [config] Configuration options
16417 * @cfg {OO.ui.InputWidget} [input] {@link OO.ui.InputWidget Input widget} that uses the label.
16418 * Clicking the label will focus the specified input field.
16419 */
16420 OO.ui.LabelWidget = function OoUiLabelWidget( config ) {
16421 // Configuration initialization
16422 config = config || {};
16423
16424 // Parent constructor
16425 OO.ui.LabelWidget.parent.call( this, config );
16426
16427 // Mixin constructors
16428 OO.ui.mixin.LabelElement.call( this, $.extend( {}, config, { $label: this.$element } ) );
16429 OO.ui.mixin.TitledElement.call( this, config );
16430
16431 // Properties
16432 this.input = config.input;
16433
16434 // Events
16435 if ( this.input instanceof OO.ui.InputWidget ) {
16436 this.$element.on( 'click', this.onClick.bind( this ) );
16437 }
16438
16439 // Initialization
16440 this.$element.addClass( 'oo-ui-labelWidget' );
16441 };
16442
16443 /* Setup */
16444
16445 OO.inheritClass( OO.ui.LabelWidget, OO.ui.Widget );
16446 OO.mixinClass( OO.ui.LabelWidget, OO.ui.mixin.LabelElement );
16447 OO.mixinClass( OO.ui.LabelWidget, OO.ui.mixin.TitledElement );
16448
16449 /* Static Properties */
16450
16451 OO.ui.LabelWidget.static.tagName = 'span';
16452
16453 /* Methods */
16454
16455 /**
16456 * Handles label mouse click events.
16457 *
16458 * @private
16459 * @param {jQuery.Event} e Mouse click event
16460 */
16461 OO.ui.LabelWidget.prototype.onClick = function () {
16462 this.input.simulateLabelClick();
16463 return false;
16464 };
16465
16466 /**
16467 * OptionWidgets are special elements that can be selected and configured with data. The
16468 * data is often unique for each option, but it does not have to be. OptionWidgets are used
16469 * with OO.ui.SelectWidget to create a selection of mutually exclusive options. For more information
16470 * and examples, please see the [OOjs UI documentation on MediaWiki][1].
16471 *
16472 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
16473 *
16474 * @class
16475 * @extends OO.ui.Widget
16476 * @mixins OO.ui.mixin.LabelElement
16477 * @mixins OO.ui.mixin.FlaggedElement
16478 *
16479 * @constructor
16480 * @param {Object} [config] Configuration options
16481 */
16482 OO.ui.OptionWidget = function OoUiOptionWidget( config ) {
16483 // Configuration initialization
16484 config = config || {};
16485
16486 // Parent constructor
16487 OO.ui.OptionWidget.parent.call( this, config );
16488
16489 // Mixin constructors
16490 OO.ui.mixin.ItemWidget.call( this );
16491 OO.ui.mixin.LabelElement.call( this, config );
16492 OO.ui.mixin.FlaggedElement.call( this, config );
16493
16494 // Properties
16495 this.selected = false;
16496 this.highlighted = false;
16497 this.pressed = false;
16498
16499 // Initialization
16500 this.$element
16501 .data( 'oo-ui-optionWidget', this )
16502 .attr( 'role', 'option' )
16503 .attr( 'aria-selected', 'false' )
16504 .addClass( 'oo-ui-optionWidget' )
16505 .append( this.$label );
16506 };
16507
16508 /* Setup */
16509
16510 OO.inheritClass( OO.ui.OptionWidget, OO.ui.Widget );
16511 OO.mixinClass( OO.ui.OptionWidget, OO.ui.mixin.ItemWidget );
16512 OO.mixinClass( OO.ui.OptionWidget, OO.ui.mixin.LabelElement );
16513 OO.mixinClass( OO.ui.OptionWidget, OO.ui.mixin.FlaggedElement );
16514
16515 /* Static Properties */
16516
16517 OO.ui.OptionWidget.static.selectable = true;
16518
16519 OO.ui.OptionWidget.static.highlightable = true;
16520
16521 OO.ui.OptionWidget.static.pressable = true;
16522
16523 OO.ui.OptionWidget.static.scrollIntoViewOnSelect = false;
16524
16525 /* Methods */
16526
16527 /**
16528 * Check if the option can be selected.
16529 *
16530 * @return {boolean} Item is selectable
16531 */
16532 OO.ui.OptionWidget.prototype.isSelectable = function () {
16533 return this.constructor.static.selectable && !this.isDisabled() && this.isVisible();
16534 };
16535
16536 /**
16537 * Check if the option can be highlighted. A highlight indicates that the option
16538 * may be selected when a user presses enter or clicks. Disabled items cannot
16539 * be highlighted.
16540 *
16541 * @return {boolean} Item is highlightable
16542 */
16543 OO.ui.OptionWidget.prototype.isHighlightable = function () {
16544 return this.constructor.static.highlightable && !this.isDisabled() && this.isVisible();
16545 };
16546
16547 /**
16548 * Check if the option can be pressed. The pressed state occurs when a user mouses
16549 * down on an item, but has not yet let go of the mouse.
16550 *
16551 * @return {boolean} Item is pressable
16552 */
16553 OO.ui.OptionWidget.prototype.isPressable = function () {
16554 return this.constructor.static.pressable && !this.isDisabled() && this.isVisible();
16555 };
16556
16557 /**
16558 * Check if the option is selected.
16559 *
16560 * @return {boolean} Item is selected
16561 */
16562 OO.ui.OptionWidget.prototype.isSelected = function () {
16563 return this.selected;
16564 };
16565
16566 /**
16567 * Check if the option is highlighted. A highlight indicates that the
16568 * item may be selected when a user presses enter or clicks.
16569 *
16570 * @return {boolean} Item is highlighted
16571 */
16572 OO.ui.OptionWidget.prototype.isHighlighted = function () {
16573 return this.highlighted;
16574 };
16575
16576 /**
16577 * Check if the option is pressed. The pressed state occurs when a user mouses
16578 * down on an item, but has not yet let go of the mouse. The item may appear
16579 * selected, but it will not be selected until the user releases the mouse.
16580 *
16581 * @return {boolean} Item is pressed
16582 */
16583 OO.ui.OptionWidget.prototype.isPressed = function () {
16584 return this.pressed;
16585 };
16586
16587 /**
16588 * Set the option’s selected state. In general, all modifications to the selection
16589 * should be handled by the SelectWidget’s {@link OO.ui.SelectWidget#selectItem selectItem( [item] )}
16590 * method instead of this method.
16591 *
16592 * @param {boolean} [state=false] Select option
16593 * @chainable
16594 */
16595 OO.ui.OptionWidget.prototype.setSelected = function ( state ) {
16596 if ( this.constructor.static.selectable ) {
16597 this.selected = !!state;
16598 this.$element
16599 .toggleClass( 'oo-ui-optionWidget-selected', state )
16600 .attr( 'aria-selected', state.toString() );
16601 if ( state && this.constructor.static.scrollIntoViewOnSelect ) {
16602 this.scrollElementIntoView();
16603 }
16604 this.updateThemeClasses();
16605 }
16606 return this;
16607 };
16608
16609 /**
16610 * Set the option’s highlighted state. In general, all programmatic
16611 * modifications to the highlight should be handled by the
16612 * SelectWidget’s {@link OO.ui.SelectWidget#highlightItem highlightItem( [item] )}
16613 * method instead of this method.
16614 *
16615 * @param {boolean} [state=false] Highlight option
16616 * @chainable
16617 */
16618 OO.ui.OptionWidget.prototype.setHighlighted = function ( state ) {
16619 if ( this.constructor.static.highlightable ) {
16620 this.highlighted = !!state;
16621 this.$element.toggleClass( 'oo-ui-optionWidget-highlighted', state );
16622 this.updateThemeClasses();
16623 }
16624 return this;
16625 };
16626
16627 /**
16628 * Set the option’s pressed state. In general, all
16629 * programmatic modifications to the pressed state should be handled by the
16630 * SelectWidget’s {@link OO.ui.SelectWidget#pressItem pressItem( [item] )}
16631 * method instead of this method.
16632 *
16633 * @param {boolean} [state=false] Press option
16634 * @chainable
16635 */
16636 OO.ui.OptionWidget.prototype.setPressed = function ( state ) {
16637 if ( this.constructor.static.pressable ) {
16638 this.pressed = !!state;
16639 this.$element.toggleClass( 'oo-ui-optionWidget-pressed', state );
16640 this.updateThemeClasses();
16641 }
16642 return this;
16643 };
16644
16645 /**
16646 * DecoratedOptionWidgets are {@link OO.ui.OptionWidget options} that can be configured
16647 * with an {@link OO.ui.mixin.IconElement icon} and/or {@link OO.ui.mixin.IndicatorElement indicator}.
16648 * This class is used with OO.ui.SelectWidget to create a selection of mutually exclusive
16649 * options. For more information about options and selects, please see the
16650 * [OOjs UI documentation on MediaWiki][1].
16651 *
16652 * @example
16653 * // Decorated options in a select widget
16654 * var select = new OO.ui.SelectWidget( {
16655 * items: [
16656 * new OO.ui.DecoratedOptionWidget( {
16657 * data: 'a',
16658 * label: 'Option with icon',
16659 * icon: 'help'
16660 * } ),
16661 * new OO.ui.DecoratedOptionWidget( {
16662 * data: 'b',
16663 * label: 'Option with indicator',
16664 * indicator: 'next'
16665 * } )
16666 * ]
16667 * } );
16668 * $( 'body' ).append( select.$element );
16669 *
16670 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
16671 *
16672 * @class
16673 * @extends OO.ui.OptionWidget
16674 * @mixins OO.ui.mixin.IconElement
16675 * @mixins OO.ui.mixin.IndicatorElement
16676 *
16677 * @constructor
16678 * @param {Object} [config] Configuration options
16679 */
16680 OO.ui.DecoratedOptionWidget = function OoUiDecoratedOptionWidget( config ) {
16681 // Parent constructor
16682 OO.ui.DecoratedOptionWidget.parent.call( this, config );
16683
16684 // Mixin constructors
16685 OO.ui.mixin.IconElement.call( this, config );
16686 OO.ui.mixin.IndicatorElement.call( this, config );
16687
16688 // Initialization
16689 this.$element
16690 .addClass( 'oo-ui-decoratedOptionWidget' )
16691 .prepend( this.$icon )
16692 .append( this.$indicator );
16693 };
16694
16695 /* Setup */
16696
16697 OO.inheritClass( OO.ui.DecoratedOptionWidget, OO.ui.OptionWidget );
16698 OO.mixinClass( OO.ui.DecoratedOptionWidget, OO.ui.mixin.IconElement );
16699 OO.mixinClass( OO.ui.DecoratedOptionWidget, OO.ui.mixin.IndicatorElement );
16700
16701 /**
16702 * ButtonOptionWidget is a special type of {@link OO.ui.mixin.ButtonElement button element} that
16703 * can be selected and configured with data. The class is
16704 * used with OO.ui.ButtonSelectWidget to create a selection of button options. Please see the
16705 * [OOjs UI documentation on MediaWiki] [1] for more information.
16706 *
16707 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Button_selects_and_options
16708 *
16709 * @class
16710 * @extends OO.ui.DecoratedOptionWidget
16711 * @mixins OO.ui.mixin.ButtonElement
16712 * @mixins OO.ui.mixin.TabIndexedElement
16713 * @mixins OO.ui.mixin.TitledElement
16714 *
16715 * @constructor
16716 * @param {Object} [config] Configuration options
16717 */
16718 OO.ui.ButtonOptionWidget = function OoUiButtonOptionWidget( config ) {
16719 // Configuration initialization
16720 config = config || {};
16721
16722 // Parent constructor
16723 OO.ui.ButtonOptionWidget.parent.call( this, config );
16724
16725 // Mixin constructors
16726 OO.ui.mixin.ButtonElement.call( this, config );
16727 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$button } ) );
16728 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, {
16729 $tabIndexed: this.$button,
16730 tabIndex: -1
16731 } ) );
16732
16733 // Initialization
16734 this.$element.addClass( 'oo-ui-buttonOptionWidget' );
16735 this.$button.append( this.$element.contents() );
16736 this.$element.append( this.$button );
16737 };
16738
16739 /* Setup */
16740
16741 OO.inheritClass( OO.ui.ButtonOptionWidget, OO.ui.DecoratedOptionWidget );
16742 OO.mixinClass( OO.ui.ButtonOptionWidget, OO.ui.mixin.ButtonElement );
16743 OO.mixinClass( OO.ui.ButtonOptionWidget, OO.ui.mixin.TitledElement );
16744 OO.mixinClass( OO.ui.ButtonOptionWidget, OO.ui.mixin.TabIndexedElement );
16745
16746 /* Static Properties */
16747
16748 // Allow button mouse down events to pass through so they can be handled by the parent select widget
16749 OO.ui.ButtonOptionWidget.static.cancelButtonMouseDownEvents = false;
16750
16751 OO.ui.ButtonOptionWidget.static.highlightable = false;
16752
16753 /* Methods */
16754
16755 /**
16756 * @inheritdoc
16757 */
16758 OO.ui.ButtonOptionWidget.prototype.setSelected = function ( state ) {
16759 OO.ui.ButtonOptionWidget.parent.prototype.setSelected.call( this, state );
16760
16761 if ( this.constructor.static.selectable ) {
16762 this.setActive( state );
16763 }
16764
16765 return this;
16766 };
16767
16768 /**
16769 * RadioOptionWidget is an option widget that looks like a radio button.
16770 * The class is used with OO.ui.RadioSelectWidget to create a selection of radio options.
16771 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information.
16772 *
16773 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Button_selects_and_option
16774 *
16775 * @class
16776 * @extends OO.ui.OptionWidget
16777 *
16778 * @constructor
16779 * @param {Object} [config] Configuration options
16780 */
16781 OO.ui.RadioOptionWidget = function OoUiRadioOptionWidget( config ) {
16782 // Configuration initialization
16783 config = config || {};
16784
16785 // Properties (must be done before parent constructor which calls #setDisabled)
16786 this.radio = new OO.ui.RadioInputWidget( { value: config.data, tabIndex: -1 } );
16787
16788 // Parent constructor
16789 OO.ui.RadioOptionWidget.parent.call( this, config );
16790
16791 // Events
16792 this.radio.$input.on( 'focus', this.onInputFocus.bind( this ) );
16793
16794 // Initialization
16795 // Remove implicit role, we're handling it ourselves
16796 this.radio.$input.attr( 'role', 'presentation' );
16797 this.$element
16798 .addClass( 'oo-ui-radioOptionWidget' )
16799 .attr( 'role', 'radio' )
16800 .attr( 'aria-checked', 'false' )
16801 .removeAttr( 'aria-selected' )
16802 .prepend( this.radio.$element );
16803 };
16804
16805 /* Setup */
16806
16807 OO.inheritClass( OO.ui.RadioOptionWidget, OO.ui.OptionWidget );
16808
16809 /* Static Properties */
16810
16811 OO.ui.RadioOptionWidget.static.highlightable = false;
16812
16813 OO.ui.RadioOptionWidget.static.scrollIntoViewOnSelect = true;
16814
16815 OO.ui.RadioOptionWidget.static.pressable = false;
16816
16817 OO.ui.RadioOptionWidget.static.tagName = 'label';
16818
16819 /* Methods */
16820
16821 /**
16822 * @param {jQuery.Event} e Focus event
16823 * @private
16824 */
16825 OO.ui.RadioOptionWidget.prototype.onInputFocus = function () {
16826 this.radio.$input.blur();
16827 this.$element.parent().focus();
16828 };
16829
16830 /**
16831 * @inheritdoc
16832 */
16833 OO.ui.RadioOptionWidget.prototype.setSelected = function ( state ) {
16834 OO.ui.RadioOptionWidget.parent.prototype.setSelected.call( this, state );
16835
16836 this.radio.setSelected( state );
16837 this.$element
16838 .attr( 'aria-checked', state.toString() )
16839 .removeAttr( 'aria-selected' );
16840
16841 return this;
16842 };
16843
16844 /**
16845 * @inheritdoc
16846 */
16847 OO.ui.RadioOptionWidget.prototype.setDisabled = function ( disabled ) {
16848 OO.ui.RadioOptionWidget.parent.prototype.setDisabled.call( this, disabled );
16849
16850 this.radio.setDisabled( this.isDisabled() );
16851
16852 return this;
16853 };
16854
16855 /**
16856 * MenuOptionWidget is an option widget that looks like a menu item. The class is used with
16857 * OO.ui.MenuSelectWidget to create a menu of mutually exclusive options. Please see
16858 * the [OOjs UI documentation on MediaWiki] [1] for more information.
16859 *
16860 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
16861 *
16862 * @class
16863 * @extends OO.ui.DecoratedOptionWidget
16864 *
16865 * @constructor
16866 * @param {Object} [config] Configuration options
16867 */
16868 OO.ui.MenuOptionWidget = function OoUiMenuOptionWidget( config ) {
16869 // Configuration initialization
16870 config = $.extend( { icon: 'check' }, config );
16871
16872 // Parent constructor
16873 OO.ui.MenuOptionWidget.parent.call( this, config );
16874
16875 // Initialization
16876 this.$element
16877 .attr( 'role', 'menuitem' )
16878 .addClass( 'oo-ui-menuOptionWidget' );
16879 };
16880
16881 /* Setup */
16882
16883 OO.inheritClass( OO.ui.MenuOptionWidget, OO.ui.DecoratedOptionWidget );
16884
16885 /* Static Properties */
16886
16887 OO.ui.MenuOptionWidget.static.scrollIntoViewOnSelect = true;
16888
16889 /**
16890 * MenuSectionOptionWidgets are used inside {@link OO.ui.MenuSelectWidget menu select widgets} to group one or more related
16891 * {@link OO.ui.MenuOptionWidget menu options}. MenuSectionOptionWidgets cannot be highlighted or selected.
16892 *
16893 * @example
16894 * var myDropdown = new OO.ui.DropdownWidget( {
16895 * menu: {
16896 * items: [
16897 * new OO.ui.MenuSectionOptionWidget( {
16898 * label: 'Dogs'
16899 * } ),
16900 * new OO.ui.MenuOptionWidget( {
16901 * data: 'corgi',
16902 * label: 'Welsh Corgi'
16903 * } ),
16904 * new OO.ui.MenuOptionWidget( {
16905 * data: 'poodle',
16906 * label: 'Standard Poodle'
16907 * } ),
16908 * new OO.ui.MenuSectionOptionWidget( {
16909 * label: 'Cats'
16910 * } ),
16911 * new OO.ui.MenuOptionWidget( {
16912 * data: 'lion',
16913 * label: 'Lion'
16914 * } )
16915 * ]
16916 * }
16917 * } );
16918 * $( 'body' ).append( myDropdown.$element );
16919 *
16920 * @class
16921 * @extends OO.ui.DecoratedOptionWidget
16922 *
16923 * @constructor
16924 * @param {Object} [config] Configuration options
16925 */
16926 OO.ui.MenuSectionOptionWidget = function OoUiMenuSectionOptionWidget( config ) {
16927 // Parent constructor
16928 OO.ui.MenuSectionOptionWidget.parent.call( this, config );
16929
16930 // Initialization
16931 this.$element.addClass( 'oo-ui-menuSectionOptionWidget' );
16932 };
16933
16934 /* Setup */
16935
16936 OO.inheritClass( OO.ui.MenuSectionOptionWidget, OO.ui.DecoratedOptionWidget );
16937
16938 /* Static Properties */
16939
16940 OO.ui.MenuSectionOptionWidget.static.selectable = false;
16941
16942 OO.ui.MenuSectionOptionWidget.static.highlightable = false;
16943
16944 /**
16945 * OutlineOptionWidget is an item in an {@link OO.ui.OutlineSelectWidget OutlineSelectWidget}.
16946 *
16947 * Currently, this class is only used by {@link OO.ui.BookletLayout booklet layouts}, which contain
16948 * {@link OO.ui.PageLayout page layouts}. See {@link OO.ui.BookletLayout BookletLayout}
16949 * for an example.
16950 *
16951 * @class
16952 * @extends OO.ui.DecoratedOptionWidget
16953 *
16954 * @constructor
16955 * @param {Object} [config] Configuration options
16956 * @cfg {number} [level] Indentation level
16957 * @cfg {boolean} [movable] Allow modification from {@link OO.ui.OutlineControlsWidget outline controls}.
16958 */
16959 OO.ui.OutlineOptionWidget = function OoUiOutlineOptionWidget( config ) {
16960 // Configuration initialization
16961 config = config || {};
16962
16963 // Parent constructor
16964 OO.ui.OutlineOptionWidget.parent.call( this, config );
16965
16966 // Properties
16967 this.level = 0;
16968 this.movable = !!config.movable;
16969 this.removable = !!config.removable;
16970
16971 // Initialization
16972 this.$element.addClass( 'oo-ui-outlineOptionWidget' );
16973 this.setLevel( config.level );
16974 };
16975
16976 /* Setup */
16977
16978 OO.inheritClass( OO.ui.OutlineOptionWidget, OO.ui.DecoratedOptionWidget );
16979
16980 /* Static Properties */
16981
16982 OO.ui.OutlineOptionWidget.static.highlightable = false;
16983
16984 OO.ui.OutlineOptionWidget.static.scrollIntoViewOnSelect = true;
16985
16986 OO.ui.OutlineOptionWidget.static.levelClass = 'oo-ui-outlineOptionWidget-level-';
16987
16988 OO.ui.OutlineOptionWidget.static.levels = 3;
16989
16990 /* Methods */
16991
16992 /**
16993 * Check if item is movable.
16994 *
16995 * Movability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
16996 *
16997 * @return {boolean} Item is movable
16998 */
16999 OO.ui.OutlineOptionWidget.prototype.isMovable = function () {
17000 return this.movable;
17001 };
17002
17003 /**
17004 * Check if item is removable.
17005 *
17006 * Removability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
17007 *
17008 * @return {boolean} Item is removable
17009 */
17010 OO.ui.OutlineOptionWidget.prototype.isRemovable = function () {
17011 return this.removable;
17012 };
17013
17014 /**
17015 * Get indentation level.
17016 *
17017 * @return {number} Indentation level
17018 */
17019 OO.ui.OutlineOptionWidget.prototype.getLevel = function () {
17020 return this.level;
17021 };
17022
17023 /**
17024 * Set movability.
17025 *
17026 * Movability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
17027 *
17028 * @param {boolean} movable Item is movable
17029 * @chainable
17030 */
17031 OO.ui.OutlineOptionWidget.prototype.setMovable = function ( movable ) {
17032 this.movable = !!movable;
17033 this.updateThemeClasses();
17034 return this;
17035 };
17036
17037 /**
17038 * Set removability.
17039 *
17040 * Removability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
17041 *
17042 * @param {boolean} movable Item is removable
17043 * @chainable
17044 */
17045 OO.ui.OutlineOptionWidget.prototype.setRemovable = function ( removable ) {
17046 this.removable = !!removable;
17047 this.updateThemeClasses();
17048 return this;
17049 };
17050
17051 /**
17052 * Set indentation level.
17053 *
17054 * @param {number} [level=0] Indentation level, in the range of [0,#maxLevel]
17055 * @chainable
17056 */
17057 OO.ui.OutlineOptionWidget.prototype.setLevel = function ( level ) {
17058 var levels = this.constructor.static.levels,
17059 levelClass = this.constructor.static.levelClass,
17060 i = levels;
17061
17062 this.level = level ? Math.max( 0, Math.min( levels - 1, level ) ) : 0;
17063 while ( i-- ) {
17064 if ( this.level === i ) {
17065 this.$element.addClass( levelClass + i );
17066 } else {
17067 this.$element.removeClass( levelClass + i );
17068 }
17069 }
17070 this.updateThemeClasses();
17071
17072 return this;
17073 };
17074
17075 /**
17076 * TabOptionWidget is an item in a {@link OO.ui.TabSelectWidget TabSelectWidget}.
17077 *
17078 * Currently, this class is only used by {@link OO.ui.IndexLayout index layouts}, which contain
17079 * {@link OO.ui.CardLayout card layouts}. See {@link OO.ui.IndexLayout IndexLayout}
17080 * for an example.
17081 *
17082 * @class
17083 * @extends OO.ui.OptionWidget
17084 *
17085 * @constructor
17086 * @param {Object} [config] Configuration options
17087 */
17088 OO.ui.TabOptionWidget = function OoUiTabOptionWidget( config ) {
17089 // Configuration initialization
17090 config = config || {};
17091
17092 // Parent constructor
17093 OO.ui.TabOptionWidget.parent.call( this, config );
17094
17095 // Initialization
17096 this.$element.addClass( 'oo-ui-tabOptionWidget' );
17097 };
17098
17099 /* Setup */
17100
17101 OO.inheritClass( OO.ui.TabOptionWidget, OO.ui.OptionWidget );
17102
17103 /* Static Properties */
17104
17105 OO.ui.TabOptionWidget.static.highlightable = false;
17106
17107 /**
17108 * PopupWidget is a container for content. The popup is overlaid and positioned absolutely.
17109 * By default, each popup has an anchor that points toward its origin.
17110 * Please see the [OOjs UI documentation on Mediawiki] [1] for more information and examples.
17111 *
17112 * @example
17113 * // A popup widget.
17114 * var popup = new OO.ui.PopupWidget( {
17115 * $content: $( '<p>Hi there!</p>' ),
17116 * padded: true,
17117 * width: 300
17118 * } );
17119 *
17120 * $( 'body' ).append( popup.$element );
17121 * // To display the popup, toggle the visibility to 'true'.
17122 * popup.toggle( true );
17123 *
17124 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups
17125 *
17126 * @class
17127 * @extends OO.ui.Widget
17128 * @mixins OO.ui.mixin.LabelElement
17129 * @mixins OO.ui.mixin.ClippableElement
17130 *
17131 * @constructor
17132 * @param {Object} [config] Configuration options
17133 * @cfg {number} [width=320] Width of popup in pixels
17134 * @cfg {number} [height] Height of popup in pixels. Omit to use the automatic height.
17135 * @cfg {boolean} [anchor=true] Show anchor pointing to origin of popup
17136 * @cfg {string} [align='center'] Alignment of the popup: `center`, `force-left`, `force-right`, `backwards` or `forwards`.
17137 * If the popup is forced-left the popup body is leaning towards the left. For force-right alignment, the body of the
17138 * popup is leaning towards the right of the screen.
17139 * Using 'backwards' is a logical direction which will result in the popup leaning towards the beginning of the sentence
17140 * in the given language, which means it will flip to the correct positioning in right-to-left languages.
17141 * Using 'forward' will also result in a logical alignment where the body of the popup leans towards the end of the
17142 * sentence in the given language.
17143 * @cfg {jQuery} [$container] Constrain the popup to the boundaries of the specified container.
17144 * See the [OOjs UI docs on MediaWiki][3] for an example.
17145 * [3]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups#containerExample
17146 * @cfg {number} [containerPadding=10] Padding between the popup and its container, specified as a number of pixels.
17147 * @cfg {jQuery} [$content] Content to append to the popup's body
17148 * @cfg {jQuery} [$footer] Content to append to the popup's footer
17149 * @cfg {boolean} [autoClose=false] Automatically close the popup when it loses focus.
17150 * @cfg {jQuery} [$autoCloseIgnore] Elements that will not close the popup when clicked.
17151 * This config option is only relevant if #autoClose is set to `true`. See the [OOjs UI docs on MediaWiki][2]
17152 * for an example.
17153 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups#autocloseExample
17154 * @cfg {boolean} [head] Show a popup header that contains a #label (if specified) and close
17155 * button.
17156 * @cfg {boolean} [padded] Add padding to the popup's body
17157 */
17158 OO.ui.PopupWidget = function OoUiPopupWidget( config ) {
17159 // Configuration initialization
17160 config = config || {};
17161
17162 // Parent constructor
17163 OO.ui.PopupWidget.parent.call( this, config );
17164
17165 // Properties (must be set before ClippableElement constructor call)
17166 this.$body = $( '<div>' );
17167 this.$popup = $( '<div>' );
17168
17169 // Mixin constructors
17170 OO.ui.mixin.LabelElement.call( this, config );
17171 OO.ui.mixin.ClippableElement.call( this, $.extend( {}, config, {
17172 $clippable: this.$body,
17173 $clippableContainer: this.$popup
17174 } ) );
17175
17176 // Properties
17177 this.$head = $( '<div>' );
17178 this.$footer = $( '<div>' );
17179 this.$anchor = $( '<div>' );
17180 // If undefined, will be computed lazily in updateDimensions()
17181 this.$container = config.$container;
17182 this.containerPadding = config.containerPadding !== undefined ? config.containerPadding : 10;
17183 this.autoClose = !!config.autoClose;
17184 this.$autoCloseIgnore = config.$autoCloseIgnore;
17185 this.transitionTimeout = null;
17186 this.anchor = null;
17187 this.width = config.width !== undefined ? config.width : 320;
17188 this.height = config.height !== undefined ? config.height : null;
17189 this.setAlignment( config.align );
17190 this.closeButton = new OO.ui.ButtonWidget( { framed: false, icon: 'close' } );
17191 this.onMouseDownHandler = this.onMouseDown.bind( this );
17192 this.onDocumentKeyDownHandler = this.onDocumentKeyDown.bind( this );
17193
17194 // Events
17195 this.closeButton.connect( this, { click: 'onCloseButtonClick' } );
17196
17197 // Initialization
17198 this.toggleAnchor( config.anchor === undefined || config.anchor );
17199 this.$body.addClass( 'oo-ui-popupWidget-body' );
17200 this.$anchor.addClass( 'oo-ui-popupWidget-anchor' );
17201 this.$head
17202 .addClass( 'oo-ui-popupWidget-head' )
17203 .append( this.$label, this.closeButton.$element );
17204 this.$footer.addClass( 'oo-ui-popupWidget-footer' );
17205 if ( !config.head ) {
17206 this.$head.addClass( 'oo-ui-element-hidden' );
17207 }
17208 if ( !config.$footer ) {
17209 this.$footer.addClass( 'oo-ui-element-hidden' );
17210 }
17211 this.$popup
17212 .addClass( 'oo-ui-popupWidget-popup' )
17213 .append( this.$head, this.$body, this.$footer );
17214 this.$element
17215 .addClass( 'oo-ui-popupWidget' )
17216 .append( this.$popup, this.$anchor );
17217 // Move content, which was added to #$element by OO.ui.Widget, to the body
17218 if ( config.$content instanceof jQuery ) {
17219 this.$body.append( config.$content );
17220 }
17221 if ( config.$footer instanceof jQuery ) {
17222 this.$footer.append( config.$footer );
17223 }
17224 if ( config.padded ) {
17225 this.$body.addClass( 'oo-ui-popupWidget-body-padded' );
17226 }
17227
17228 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
17229 // that reference properties not initialized at that time of parent class construction
17230 // TODO: Find a better way to handle post-constructor setup
17231 this.visible = false;
17232 this.$element.addClass( 'oo-ui-element-hidden' );
17233 };
17234
17235 /* Setup */
17236
17237 OO.inheritClass( OO.ui.PopupWidget, OO.ui.Widget );
17238 OO.mixinClass( OO.ui.PopupWidget, OO.ui.mixin.LabelElement );
17239 OO.mixinClass( OO.ui.PopupWidget, OO.ui.mixin.ClippableElement );
17240
17241 /* Methods */
17242
17243 /**
17244 * Handles mouse down events.
17245 *
17246 * @private
17247 * @param {MouseEvent} e Mouse down event
17248 */
17249 OO.ui.PopupWidget.prototype.onMouseDown = function ( e ) {
17250 if (
17251 this.isVisible() &&
17252 !$.contains( this.$element[ 0 ], e.target ) &&
17253 ( !this.$autoCloseIgnore || !this.$autoCloseIgnore.has( e.target ).length )
17254 ) {
17255 this.toggle( false );
17256 }
17257 };
17258
17259 /**
17260 * Bind mouse down listener.
17261 *
17262 * @private
17263 */
17264 OO.ui.PopupWidget.prototype.bindMouseDownListener = function () {
17265 // Capture clicks outside popup
17266 OO.ui.addCaptureEventListener( this.getElementWindow(), 'mousedown', this.onMouseDownHandler );
17267 };
17268
17269 /**
17270 * Handles close button click events.
17271 *
17272 * @private
17273 */
17274 OO.ui.PopupWidget.prototype.onCloseButtonClick = function () {
17275 if ( this.isVisible() ) {
17276 this.toggle( false );
17277 }
17278 };
17279
17280 /**
17281 * Unbind mouse down listener.
17282 *
17283 * @private
17284 */
17285 OO.ui.PopupWidget.prototype.unbindMouseDownListener = function () {
17286 OO.ui.removeCaptureEventListener( this.getElementWindow(), 'mousedown', this.onMouseDownHandler );
17287 };
17288
17289 /**
17290 * Handles key down events.
17291 *
17292 * @private
17293 * @param {KeyboardEvent} e Key down event
17294 */
17295 OO.ui.PopupWidget.prototype.onDocumentKeyDown = function ( e ) {
17296 if (
17297 e.which === OO.ui.Keys.ESCAPE &&
17298 this.isVisible()
17299 ) {
17300 this.toggle( false );
17301 e.preventDefault();
17302 e.stopPropagation();
17303 }
17304 };
17305
17306 /**
17307 * Bind key down listener.
17308 *
17309 * @private
17310 */
17311 OO.ui.PopupWidget.prototype.bindKeyDownListener = function () {
17312 OO.ui.addCaptureEventListener( this.getElementWindow(), 'keydown', this.onDocumentKeyDownHandler );
17313 };
17314
17315 /**
17316 * Unbind key down listener.
17317 *
17318 * @private
17319 */
17320 OO.ui.PopupWidget.prototype.unbindKeyDownListener = function () {
17321 OO.ui.removeCaptureEventListener( this.getElementWindow(), 'keydown', this.onDocumentKeyDownHandler );
17322 };
17323
17324 /**
17325 * Show, hide, or toggle the visibility of the anchor.
17326 *
17327 * @param {boolean} [show] Show anchor, omit to toggle
17328 */
17329 OO.ui.PopupWidget.prototype.toggleAnchor = function ( show ) {
17330 show = show === undefined ? !this.anchored : !!show;
17331
17332 if ( this.anchored !== show ) {
17333 if ( show ) {
17334 this.$element.addClass( 'oo-ui-popupWidget-anchored' );
17335 } else {
17336 this.$element.removeClass( 'oo-ui-popupWidget-anchored' );
17337 }
17338 this.anchored = show;
17339 }
17340 };
17341
17342 /**
17343 * Check if the anchor is visible.
17344 *
17345 * @return {boolean} Anchor is visible
17346 */
17347 OO.ui.PopupWidget.prototype.hasAnchor = function () {
17348 return this.anchor;
17349 };
17350
17351 /**
17352 * @inheritdoc
17353 */
17354 OO.ui.PopupWidget.prototype.toggle = function ( show ) {
17355 var change;
17356 show = show === undefined ? !this.isVisible() : !!show;
17357
17358 change = show !== this.isVisible();
17359
17360 // Parent method
17361 OO.ui.PopupWidget.parent.prototype.toggle.call( this, show );
17362
17363 if ( change ) {
17364 if ( show ) {
17365 if ( this.autoClose ) {
17366 this.bindMouseDownListener();
17367 this.bindKeyDownListener();
17368 }
17369 this.updateDimensions();
17370 this.toggleClipping( true );
17371 } else {
17372 this.toggleClipping( false );
17373 if ( this.autoClose ) {
17374 this.unbindMouseDownListener();
17375 this.unbindKeyDownListener();
17376 }
17377 }
17378 }
17379
17380 return this;
17381 };
17382
17383 /**
17384 * Set the size of the popup.
17385 *
17386 * Changing the size may also change the popup's position depending on the alignment.
17387 *
17388 * @param {number} width Width in pixels
17389 * @param {number} height Height in pixels
17390 * @param {boolean} [transition=false] Use a smooth transition
17391 * @chainable
17392 */
17393 OO.ui.PopupWidget.prototype.setSize = function ( width, height, transition ) {
17394 this.width = width;
17395 this.height = height !== undefined ? height : null;
17396 if ( this.isVisible() ) {
17397 this.updateDimensions( transition );
17398 }
17399 };
17400
17401 /**
17402 * Update the size and position.
17403 *
17404 * Only use this to keep the popup properly anchored. Use #setSize to change the size, and this will
17405 * be called automatically.
17406 *
17407 * @param {boolean} [transition=false] Use a smooth transition
17408 * @chainable
17409 */
17410 OO.ui.PopupWidget.prototype.updateDimensions = function ( transition ) {
17411 var popupOffset, originOffset, containerLeft, containerWidth, containerRight,
17412 popupLeft, popupRight, overlapLeft, overlapRight, anchorWidth,
17413 align = this.align,
17414 widget = this;
17415
17416 if ( !this.$container ) {
17417 // Lazy-initialize $container if not specified in constructor
17418 this.$container = $( this.getClosestScrollableElementContainer() );
17419 }
17420
17421 // Set height and width before measuring things, since it might cause our measurements
17422 // to change (e.g. due to scrollbars appearing or disappearing)
17423 this.$popup.css( {
17424 width: this.width,
17425 height: this.height !== null ? this.height : 'auto'
17426 } );
17427
17428 // If we are in RTL, we need to flip the alignment, unless it is center
17429 if ( align === 'forwards' || align === 'backwards' ) {
17430 if ( this.$container.css( 'direction' ) === 'rtl' ) {
17431 align = ( { forwards: 'force-left', backwards: 'force-right' } )[ this.align ];
17432 } else {
17433 align = ( { forwards: 'force-right', backwards: 'force-left' } )[ this.align ];
17434 }
17435
17436 }
17437
17438 // Compute initial popupOffset based on alignment
17439 popupOffset = this.width * ( { 'force-left': -1, center: -0.5, 'force-right': 0 } )[ align ];
17440
17441 // Figure out if this will cause the popup to go beyond the edge of the container
17442 originOffset = this.$element.offset().left;
17443 containerLeft = this.$container.offset().left;
17444 containerWidth = this.$container.innerWidth();
17445 containerRight = containerLeft + containerWidth;
17446 popupLeft = popupOffset - this.containerPadding;
17447 popupRight = popupOffset + this.containerPadding + this.width + this.containerPadding;
17448 overlapLeft = ( originOffset + popupLeft ) - containerLeft;
17449 overlapRight = containerRight - ( originOffset + popupRight );
17450
17451 // Adjust offset to make the popup not go beyond the edge, if needed
17452 if ( overlapRight < 0 ) {
17453 popupOffset += overlapRight;
17454 } else if ( overlapLeft < 0 ) {
17455 popupOffset -= overlapLeft;
17456 }
17457
17458 // Adjust offset to avoid anchor being rendered too close to the edge
17459 // $anchor.width() doesn't work with the pure CSS anchor (returns 0)
17460 // TODO: Find a measurement that works for CSS anchors and image anchors
17461 anchorWidth = this.$anchor[ 0 ].scrollWidth * 2;
17462 if ( popupOffset + this.width < anchorWidth ) {
17463 popupOffset = anchorWidth - this.width;
17464 } else if ( -popupOffset < anchorWidth ) {
17465 popupOffset = -anchorWidth;
17466 }
17467
17468 // Prevent transition from being interrupted
17469 clearTimeout( this.transitionTimeout );
17470 if ( transition ) {
17471 // Enable transition
17472 this.$element.addClass( 'oo-ui-popupWidget-transitioning' );
17473 }
17474
17475 // Position body relative to anchor
17476 this.$popup.css( 'margin-left', popupOffset );
17477
17478 if ( transition ) {
17479 // Prevent transitioning after transition is complete
17480 this.transitionTimeout = setTimeout( function () {
17481 widget.$element.removeClass( 'oo-ui-popupWidget-transitioning' );
17482 }, 200 );
17483 } else {
17484 // Prevent transitioning immediately
17485 this.$element.removeClass( 'oo-ui-popupWidget-transitioning' );
17486 }
17487
17488 // Reevaluate clipping state since we've relocated and resized the popup
17489 this.clip();
17490
17491 return this;
17492 };
17493
17494 /**
17495 * Set popup alignment
17496 * @param {string} align Alignment of the popup, `center`, `force-left`, `force-right`,
17497 * `backwards` or `forwards`.
17498 */
17499 OO.ui.PopupWidget.prototype.setAlignment = function ( align ) {
17500 // Validate alignment and transform deprecated values
17501 if ( [ 'left', 'right', 'force-left', 'force-right', 'backwards', 'forwards', 'center' ].indexOf( align ) > -1 ) {
17502 this.align = { left: 'force-right', right: 'force-left' }[ align ] || align;
17503 } else {
17504 this.align = 'center';
17505 }
17506 };
17507
17508 /**
17509 * Get popup alignment
17510 * @return {string} align Alignment of the popup, `center`, `force-left`, `force-right`,
17511 * `backwards` or `forwards`.
17512 */
17513 OO.ui.PopupWidget.prototype.getAlignment = function () {
17514 return this.align;
17515 };
17516
17517 /**
17518 * Progress bars visually display the status of an operation, such as a download,
17519 * and can be either determinate or indeterminate:
17520 *
17521 * - **determinate** process bars show the percent of an operation that is complete.
17522 *
17523 * - **indeterminate** process bars use a visual display of motion to indicate that an operation
17524 * is taking place. Because the extent of an indeterminate operation is unknown, the bar does
17525 * not use percentages.
17526 *
17527 * The value of the `progress` configuration determines whether the bar is determinate or indeterminate.
17528 *
17529 * @example
17530 * // Examples of determinate and indeterminate progress bars.
17531 * var progressBar1 = new OO.ui.ProgressBarWidget( {
17532 * progress: 33
17533 * } );
17534 * var progressBar2 = new OO.ui.ProgressBarWidget();
17535 *
17536 * // Create a FieldsetLayout to layout progress bars
17537 * var fieldset = new OO.ui.FieldsetLayout;
17538 * fieldset.addItems( [
17539 * new OO.ui.FieldLayout( progressBar1, {label: 'Determinate', align: 'top'}),
17540 * new OO.ui.FieldLayout( progressBar2, {label: 'Indeterminate', align: 'top'})
17541 * ] );
17542 * $( 'body' ).append( fieldset.$element );
17543 *
17544 * @class
17545 * @extends OO.ui.Widget
17546 *
17547 * @constructor
17548 * @param {Object} [config] Configuration options
17549 * @cfg {number|boolean} [progress=false] The type of progress bar (determinate or indeterminate).
17550 * To create a determinate progress bar, specify a number that reflects the initial percent complete.
17551 * By default, the progress bar is indeterminate.
17552 */
17553 OO.ui.ProgressBarWidget = function OoUiProgressBarWidget( config ) {
17554 // Configuration initialization
17555 config = config || {};
17556
17557 // Parent constructor
17558 OO.ui.ProgressBarWidget.parent.call( this, config );
17559
17560 // Properties
17561 this.$bar = $( '<div>' );
17562 this.progress = null;
17563
17564 // Initialization
17565 this.setProgress( config.progress !== undefined ? config.progress : false );
17566 this.$bar.addClass( 'oo-ui-progressBarWidget-bar' );
17567 this.$element
17568 .attr( {
17569 role: 'progressbar',
17570 'aria-valuemin': 0,
17571 'aria-valuemax': 100
17572 } )
17573 .addClass( 'oo-ui-progressBarWidget' )
17574 .append( this.$bar );
17575 };
17576
17577 /* Setup */
17578
17579 OO.inheritClass( OO.ui.ProgressBarWidget, OO.ui.Widget );
17580
17581 /* Static Properties */
17582
17583 OO.ui.ProgressBarWidget.static.tagName = 'div';
17584
17585 /* Methods */
17586
17587 /**
17588 * Get the percent of the progress that has been completed. Indeterminate progresses will return `false`.
17589 *
17590 * @return {number|boolean} Progress percent
17591 */
17592 OO.ui.ProgressBarWidget.prototype.getProgress = function () {
17593 return this.progress;
17594 };
17595
17596 /**
17597 * Set the percent of the process completed or `false` for an indeterminate process.
17598 *
17599 * @param {number|boolean} progress Progress percent or `false` for indeterminate
17600 */
17601 OO.ui.ProgressBarWidget.prototype.setProgress = function ( progress ) {
17602 this.progress = progress;
17603
17604 if ( progress !== false ) {
17605 this.$bar.css( 'width', this.progress + '%' );
17606 this.$element.attr( 'aria-valuenow', this.progress );
17607 } else {
17608 this.$bar.css( 'width', '' );
17609 this.$element.removeAttr( 'aria-valuenow' );
17610 }
17611 this.$element.toggleClass( 'oo-ui-progressBarWidget-indeterminate', !progress );
17612 };
17613
17614 /**
17615 * SearchWidgets combine a {@link OO.ui.TextInputWidget text input field}, where users can type a search query,
17616 * and a menu of search results, which is displayed beneath the query
17617 * field. Unlike {@link OO.ui.mixin.LookupElement lookup menus}, search result menus are always visible to the user.
17618 * Users can choose an item from the menu or type a query into the text field to search for a matching result item.
17619 * In general, search widgets are used inside a separate {@link OO.ui.Dialog dialog} window.
17620 *
17621 * Each time the query is changed, the search result menu is cleared and repopulated. Please see
17622 * the [OOjs UI demos][1] for an example.
17623 *
17624 * [1]: https://tools.wmflabs.org/oojs-ui/oojs-ui/demos/#dialogs-mediawiki-vector-ltr
17625 *
17626 * @class
17627 * @extends OO.ui.Widget
17628 *
17629 * @constructor
17630 * @param {Object} [config] Configuration options
17631 * @cfg {string|jQuery} [placeholder] Placeholder text for query input
17632 * @cfg {string} [value] Initial query value
17633 */
17634 OO.ui.SearchWidget = function OoUiSearchWidget( config ) {
17635 // Configuration initialization
17636 config = config || {};
17637
17638 // Parent constructor
17639 OO.ui.SearchWidget.parent.call( this, config );
17640
17641 // Properties
17642 this.query = new OO.ui.TextInputWidget( {
17643 icon: 'search',
17644 placeholder: config.placeholder,
17645 value: config.value
17646 } );
17647 this.results = new OO.ui.SelectWidget();
17648 this.$query = $( '<div>' );
17649 this.$results = $( '<div>' );
17650
17651 // Events
17652 this.query.connect( this, {
17653 change: 'onQueryChange',
17654 enter: 'onQueryEnter'
17655 } );
17656 this.query.$input.on( 'keydown', this.onQueryKeydown.bind( this ) );
17657
17658 // Initialization
17659 this.$query
17660 .addClass( 'oo-ui-searchWidget-query' )
17661 .append( this.query.$element );
17662 this.$results
17663 .addClass( 'oo-ui-searchWidget-results' )
17664 .append( this.results.$element );
17665 this.$element
17666 .addClass( 'oo-ui-searchWidget' )
17667 .append( this.$results, this.$query );
17668 };
17669
17670 /* Setup */
17671
17672 OO.inheritClass( OO.ui.SearchWidget, OO.ui.Widget );
17673
17674 /* Methods */
17675
17676 /**
17677 * Handle query key down events.
17678 *
17679 * @private
17680 * @param {jQuery.Event} e Key down event
17681 */
17682 OO.ui.SearchWidget.prototype.onQueryKeydown = function ( e ) {
17683 var highlightedItem, nextItem,
17684 dir = e.which === OO.ui.Keys.DOWN ? 1 : ( e.which === OO.ui.Keys.UP ? -1 : 0 );
17685
17686 if ( dir ) {
17687 highlightedItem = this.results.getHighlightedItem();
17688 if ( !highlightedItem ) {
17689 highlightedItem = this.results.getSelectedItem();
17690 }
17691 nextItem = this.results.getRelativeSelectableItem( highlightedItem, dir );
17692 this.results.highlightItem( nextItem );
17693 nextItem.scrollElementIntoView();
17694 }
17695 };
17696
17697 /**
17698 * Handle select widget select events.
17699 *
17700 * Clears existing results. Subclasses should repopulate items according to new query.
17701 *
17702 * @private
17703 * @param {string} value New value
17704 */
17705 OO.ui.SearchWidget.prototype.onQueryChange = function () {
17706 // Reset
17707 this.results.clearItems();
17708 };
17709
17710 /**
17711 * Handle select widget enter key events.
17712 *
17713 * Chooses highlighted item.
17714 *
17715 * @private
17716 * @param {string} value New value
17717 */
17718 OO.ui.SearchWidget.prototype.onQueryEnter = function () {
17719 var highlightedItem = this.results.getHighlightedItem();
17720 if ( highlightedItem ) {
17721 this.results.chooseItem( highlightedItem );
17722 }
17723 };
17724
17725 /**
17726 * Get the query input.
17727 *
17728 * @return {OO.ui.TextInputWidget} Query input
17729 */
17730 OO.ui.SearchWidget.prototype.getQuery = function () {
17731 return this.query;
17732 };
17733
17734 /**
17735 * Get the search results menu.
17736 *
17737 * @return {OO.ui.SelectWidget} Menu of search results
17738 */
17739 OO.ui.SearchWidget.prototype.getResults = function () {
17740 return this.results;
17741 };
17742
17743 /**
17744 * A SelectWidget is of a generic selection of options. The OOjs UI library contains several types of
17745 * select widgets, including {@link OO.ui.ButtonSelectWidget button selects},
17746 * {@link OO.ui.RadioSelectWidget radio selects}, and {@link OO.ui.MenuSelectWidget
17747 * menu selects}.
17748 *
17749 * This class should be used together with OO.ui.OptionWidget or OO.ui.DecoratedOptionWidget. For more
17750 * information, please see the [OOjs UI documentation on MediaWiki][1].
17751 *
17752 * @example
17753 * // Example of a select widget with three options
17754 * var select = new OO.ui.SelectWidget( {
17755 * items: [
17756 * new OO.ui.OptionWidget( {
17757 * data: 'a',
17758 * label: 'Option One',
17759 * } ),
17760 * new OO.ui.OptionWidget( {
17761 * data: 'b',
17762 * label: 'Option Two',
17763 * } ),
17764 * new OO.ui.OptionWidget( {
17765 * data: 'c',
17766 * label: 'Option Three',
17767 * } )
17768 * ]
17769 * } );
17770 * $( 'body' ).append( select.$element );
17771 *
17772 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
17773 *
17774 * @abstract
17775 * @class
17776 * @extends OO.ui.Widget
17777 * @mixins OO.ui.mixin.GroupWidget
17778 *
17779 * @constructor
17780 * @param {Object} [config] Configuration options
17781 * @cfg {OO.ui.OptionWidget[]} [items] An array of options to add to the select.
17782 * Options are created with {@link OO.ui.OptionWidget OptionWidget} classes. See
17783 * the [OOjs UI documentation on MediaWiki] [2] for examples.
17784 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
17785 */
17786 OO.ui.SelectWidget = function OoUiSelectWidget( config ) {
17787 // Configuration initialization
17788 config = config || {};
17789
17790 // Parent constructor
17791 OO.ui.SelectWidget.parent.call( this, config );
17792
17793 // Mixin constructors
17794 OO.ui.mixin.GroupWidget.call( this, $.extend( {}, config, { $group: this.$element } ) );
17795
17796 // Properties
17797 this.pressed = false;
17798 this.selecting = null;
17799 this.onMouseUpHandler = this.onMouseUp.bind( this );
17800 this.onMouseMoveHandler = this.onMouseMove.bind( this );
17801 this.onKeyDownHandler = this.onKeyDown.bind( this );
17802 this.onKeyPressHandler = this.onKeyPress.bind( this );
17803 this.keyPressBuffer = '';
17804 this.keyPressBufferTimer = null;
17805
17806 // Events
17807 this.connect( this, {
17808 toggle: 'onToggle'
17809 } );
17810 this.$element.on( {
17811 mousedown: this.onMouseDown.bind( this ),
17812 mouseover: this.onMouseOver.bind( this ),
17813 mouseleave: this.onMouseLeave.bind( this )
17814 } );
17815
17816 // Initialization
17817 this.$element
17818 .addClass( 'oo-ui-selectWidget oo-ui-selectWidget-depressed' )
17819 .attr( 'role', 'listbox' );
17820 if ( Array.isArray( config.items ) ) {
17821 this.addItems( config.items );
17822 }
17823 };
17824
17825 /* Setup */
17826
17827 OO.inheritClass( OO.ui.SelectWidget, OO.ui.Widget );
17828
17829 // Need to mixin base class as well
17830 OO.mixinClass( OO.ui.SelectWidget, OO.ui.mixin.GroupElement );
17831 OO.mixinClass( OO.ui.SelectWidget, OO.ui.mixin.GroupWidget );
17832
17833 /* Static */
17834 OO.ui.SelectWidget.static.passAllFilter = function () {
17835 return true;
17836 };
17837
17838 /* Events */
17839
17840 /**
17841 * @event highlight
17842 *
17843 * A `highlight` event is emitted when the highlight is changed with the #highlightItem method.
17844 *
17845 * @param {OO.ui.OptionWidget|null} item Highlighted item
17846 */
17847
17848 /**
17849 * @event press
17850 *
17851 * A `press` event is emitted when the #pressItem method is used to programmatically modify the
17852 * pressed state of an option.
17853 *
17854 * @param {OO.ui.OptionWidget|null} item Pressed item
17855 */
17856
17857 /**
17858 * @event select
17859 *
17860 * A `select` event is emitted when the selection is modified programmatically with the #selectItem method.
17861 *
17862 * @param {OO.ui.OptionWidget|null} item Selected item
17863 */
17864
17865 /**
17866 * @event choose
17867 * A `choose` event is emitted when an item is chosen with the #chooseItem method.
17868 * @param {OO.ui.OptionWidget} item Chosen item
17869 */
17870
17871 /**
17872 * @event add
17873 *
17874 * An `add` event is emitted when options are added to the select with the #addItems method.
17875 *
17876 * @param {OO.ui.OptionWidget[]} items Added items
17877 * @param {number} index Index of insertion point
17878 */
17879
17880 /**
17881 * @event remove
17882 *
17883 * A `remove` event is emitted when options are removed from the select with the #clearItems
17884 * or #removeItems methods.
17885 *
17886 * @param {OO.ui.OptionWidget[]} items Removed items
17887 */
17888
17889 /* Methods */
17890
17891 /**
17892 * Handle mouse down events.
17893 *
17894 * @private
17895 * @param {jQuery.Event} e Mouse down event
17896 */
17897 OO.ui.SelectWidget.prototype.onMouseDown = function ( e ) {
17898 var item;
17899
17900 if ( !this.isDisabled() && e.which === 1 ) {
17901 this.togglePressed( true );
17902 item = this.getTargetItem( e );
17903 if ( item && item.isSelectable() ) {
17904 this.pressItem( item );
17905 this.selecting = item;
17906 OO.ui.addCaptureEventListener(
17907 this.getElementDocument(),
17908 'mouseup',
17909 this.onMouseUpHandler
17910 );
17911 OO.ui.addCaptureEventListener(
17912 this.getElementDocument(),
17913 'mousemove',
17914 this.onMouseMoveHandler
17915 );
17916 }
17917 }
17918 return false;
17919 };
17920
17921 /**
17922 * Handle mouse up events.
17923 *
17924 * @private
17925 * @param {jQuery.Event} e Mouse up event
17926 */
17927 OO.ui.SelectWidget.prototype.onMouseUp = function ( e ) {
17928 var item;
17929
17930 this.togglePressed( false );
17931 if ( !this.selecting ) {
17932 item = this.getTargetItem( e );
17933 if ( item && item.isSelectable() ) {
17934 this.selecting = item;
17935 }
17936 }
17937 if ( !this.isDisabled() && e.which === 1 && this.selecting ) {
17938 this.pressItem( null );
17939 this.chooseItem( this.selecting );
17940 this.selecting = null;
17941 }
17942
17943 OO.ui.removeCaptureEventListener( this.getElementDocument(), 'mouseup',
17944 this.onMouseUpHandler );
17945 OO.ui.removeCaptureEventListener( this.getElementDocument(), 'mousemove',
17946 this.onMouseMoveHandler );
17947
17948 return false;
17949 };
17950
17951 /**
17952 * Handle mouse move events.
17953 *
17954 * @private
17955 * @param {jQuery.Event} e Mouse move event
17956 */
17957 OO.ui.SelectWidget.prototype.onMouseMove = function ( e ) {
17958 var item;
17959
17960 if ( !this.isDisabled() && this.pressed ) {
17961 item = this.getTargetItem( e );
17962 if ( item && item !== this.selecting && item.isSelectable() ) {
17963 this.pressItem( item );
17964 this.selecting = item;
17965 }
17966 }
17967 return false;
17968 };
17969
17970 /**
17971 * Handle mouse over events.
17972 *
17973 * @private
17974 * @param {jQuery.Event} e Mouse over event
17975 */
17976 OO.ui.SelectWidget.prototype.onMouseOver = function ( e ) {
17977 var item;
17978
17979 if ( !this.isDisabled() ) {
17980 item = this.getTargetItem( e );
17981 this.highlightItem( item && item.isHighlightable() ? item : null );
17982 }
17983 return false;
17984 };
17985
17986 /**
17987 * Handle mouse leave events.
17988 *
17989 * @private
17990 * @param {jQuery.Event} e Mouse over event
17991 */
17992 OO.ui.SelectWidget.prototype.onMouseLeave = function () {
17993 if ( !this.isDisabled() ) {
17994 this.highlightItem( null );
17995 }
17996 return false;
17997 };
17998
17999 /**
18000 * Handle key down events.
18001 *
18002 * @protected
18003 * @param {jQuery.Event} e Key down event
18004 */
18005 OO.ui.SelectWidget.prototype.onKeyDown = function ( e ) {
18006 var nextItem,
18007 handled = false,
18008 currentItem = this.getHighlightedItem() || this.getSelectedItem();
18009
18010 if ( !this.isDisabled() && this.isVisible() ) {
18011 switch ( e.keyCode ) {
18012 case OO.ui.Keys.ENTER:
18013 if ( currentItem && currentItem.constructor.static.highlightable ) {
18014 // Was only highlighted, now let's select it. No-op if already selected.
18015 this.chooseItem( currentItem );
18016 handled = true;
18017 }
18018 break;
18019 case OO.ui.Keys.UP:
18020 case OO.ui.Keys.LEFT:
18021 this.clearKeyPressBuffer();
18022 nextItem = this.getRelativeSelectableItem( currentItem, -1 );
18023 handled = true;
18024 break;
18025 case OO.ui.Keys.DOWN:
18026 case OO.ui.Keys.RIGHT:
18027 this.clearKeyPressBuffer();
18028 nextItem = this.getRelativeSelectableItem( currentItem, 1 );
18029 handled = true;
18030 break;
18031 case OO.ui.Keys.ESCAPE:
18032 case OO.ui.Keys.TAB:
18033 if ( currentItem && currentItem.constructor.static.highlightable ) {
18034 currentItem.setHighlighted( false );
18035 }
18036 this.unbindKeyDownListener();
18037 this.unbindKeyPressListener();
18038 // Don't prevent tabbing away / defocusing
18039 handled = false;
18040 break;
18041 }
18042
18043 if ( nextItem ) {
18044 if ( nextItem.constructor.static.highlightable ) {
18045 this.highlightItem( nextItem );
18046 } else {
18047 this.chooseItem( nextItem );
18048 }
18049 nextItem.scrollElementIntoView();
18050 }
18051
18052 if ( handled ) {
18053 // Can't just return false, because e is not always a jQuery event
18054 e.preventDefault();
18055 e.stopPropagation();
18056 }
18057 }
18058 };
18059
18060 /**
18061 * Bind key down listener.
18062 *
18063 * @protected
18064 */
18065 OO.ui.SelectWidget.prototype.bindKeyDownListener = function () {
18066 OO.ui.addCaptureEventListener( this.getElementWindow(), 'keydown', this.onKeyDownHandler );
18067 };
18068
18069 /**
18070 * Unbind key down listener.
18071 *
18072 * @protected
18073 */
18074 OO.ui.SelectWidget.prototype.unbindKeyDownListener = function () {
18075 OO.ui.removeCaptureEventListener( this.getElementWindow(), 'keydown', this.onKeyDownHandler );
18076 };
18077
18078 /**
18079 * Clear the key-press buffer
18080 *
18081 * @protected
18082 */
18083 OO.ui.SelectWidget.prototype.clearKeyPressBuffer = function () {
18084 if ( this.keyPressBufferTimer ) {
18085 clearTimeout( this.keyPressBufferTimer );
18086 this.keyPressBufferTimer = null;
18087 }
18088 this.keyPressBuffer = '';
18089 };
18090
18091 /**
18092 * Handle key press events.
18093 *
18094 * @protected
18095 * @param {jQuery.Event} e Key press event
18096 */
18097 OO.ui.SelectWidget.prototype.onKeyPress = function ( e ) {
18098 var c, filter, item;
18099
18100 if ( !e.charCode ) {
18101 if ( e.keyCode === OO.ui.Keys.BACKSPACE && this.keyPressBuffer !== '' ) {
18102 this.keyPressBuffer = this.keyPressBuffer.substr( 0, this.keyPressBuffer.length - 1 );
18103 return false;
18104 }
18105 return;
18106 }
18107 if ( String.fromCodePoint ) {
18108 c = String.fromCodePoint( e.charCode );
18109 } else {
18110 c = String.fromCharCode( e.charCode );
18111 }
18112
18113 if ( this.keyPressBufferTimer ) {
18114 clearTimeout( this.keyPressBufferTimer );
18115 }
18116 this.keyPressBufferTimer = setTimeout( this.clearKeyPressBuffer.bind( this ), 1500 );
18117
18118 item = this.getHighlightedItem() || this.getSelectedItem();
18119
18120 if ( this.keyPressBuffer === c ) {
18121 // Common (if weird) special case: typing "xxxx" will cycle through all
18122 // the items beginning with "x".
18123 if ( item ) {
18124 item = this.getRelativeSelectableItem( item, 1 );
18125 }
18126 } else {
18127 this.keyPressBuffer += c;
18128 }
18129
18130 filter = this.getItemMatcher( this.keyPressBuffer, false );
18131 if ( !item || !filter( item ) ) {
18132 item = this.getRelativeSelectableItem( item, 1, filter );
18133 }
18134 if ( item ) {
18135 if ( item.constructor.static.highlightable ) {
18136 this.highlightItem( item );
18137 } else {
18138 this.chooseItem( item );
18139 }
18140 item.scrollElementIntoView();
18141 }
18142
18143 return false;
18144 };
18145
18146 /**
18147 * Get a matcher for the specific string
18148 *
18149 * @protected
18150 * @param {string} s String to match against items
18151 * @param {boolean} [exact=false] Only accept exact matches
18152 * @return {Function} function ( OO.ui.OptionItem ) => boolean
18153 */
18154 OO.ui.SelectWidget.prototype.getItemMatcher = function ( s, exact ) {
18155 var re;
18156
18157 if ( s.normalize ) {
18158 s = s.normalize();
18159 }
18160 s = exact ? s.trim() : s.replace( /^\s+/, '' );
18161 re = '^\\s*' + s.replace( /([\\{}()|.?*+\-\^$\[\]])/g, '\\$1' ).replace( /\s+/g, '\\s+' );
18162 if ( exact ) {
18163 re += '\\s*$';
18164 }
18165 re = new RegExp( re, 'i' );
18166 return function ( item ) {
18167 var l = item.getLabel();
18168 if ( typeof l !== 'string' ) {
18169 l = item.$label.text();
18170 }
18171 if ( l.normalize ) {
18172 l = l.normalize();
18173 }
18174 return re.test( l );
18175 };
18176 };
18177
18178 /**
18179 * Bind key press listener.
18180 *
18181 * @protected
18182 */
18183 OO.ui.SelectWidget.prototype.bindKeyPressListener = function () {
18184 OO.ui.addCaptureEventListener( this.getElementWindow(), 'keypress', this.onKeyPressHandler );
18185 };
18186
18187 /**
18188 * Unbind key down listener.
18189 *
18190 * If you override this, be sure to call this.clearKeyPressBuffer() from your
18191 * implementation.
18192 *
18193 * @protected
18194 */
18195 OO.ui.SelectWidget.prototype.unbindKeyPressListener = function () {
18196 OO.ui.removeCaptureEventListener( this.getElementWindow(), 'keypress', this.onKeyPressHandler );
18197 this.clearKeyPressBuffer();
18198 };
18199
18200 /**
18201 * Visibility change handler
18202 *
18203 * @protected
18204 * @param {boolean} visible
18205 */
18206 OO.ui.SelectWidget.prototype.onToggle = function ( visible ) {
18207 if ( !visible ) {
18208 this.clearKeyPressBuffer();
18209 }
18210 };
18211
18212 /**
18213 * Get the closest item to a jQuery.Event.
18214 *
18215 * @private
18216 * @param {jQuery.Event} e
18217 * @return {OO.ui.OptionWidget|null} Outline item widget, `null` if none was found
18218 */
18219 OO.ui.SelectWidget.prototype.getTargetItem = function ( e ) {
18220 return $( e.target ).closest( '.oo-ui-optionWidget' ).data( 'oo-ui-optionWidget' ) || null;
18221 };
18222
18223 /**
18224 * Get selected item.
18225 *
18226 * @return {OO.ui.OptionWidget|null} Selected item, `null` if no item is selected
18227 */
18228 OO.ui.SelectWidget.prototype.getSelectedItem = function () {
18229 var i, len;
18230
18231 for ( i = 0, len = this.items.length; i < len; i++ ) {
18232 if ( this.items[ i ].isSelected() ) {
18233 return this.items[ i ];
18234 }
18235 }
18236 return null;
18237 };
18238
18239 /**
18240 * Get highlighted item.
18241 *
18242 * @return {OO.ui.OptionWidget|null} Highlighted item, `null` if no item is highlighted
18243 */
18244 OO.ui.SelectWidget.prototype.getHighlightedItem = function () {
18245 var i, len;
18246
18247 for ( i = 0, len = this.items.length; i < len; i++ ) {
18248 if ( this.items[ i ].isHighlighted() ) {
18249 return this.items[ i ];
18250 }
18251 }
18252 return null;
18253 };
18254
18255 /**
18256 * Toggle pressed state.
18257 *
18258 * Press is a state that occurs when a user mouses down on an item, but
18259 * has not yet let go of the mouse. The item may appear selected, but it will not be selected
18260 * until the user releases the mouse.
18261 *
18262 * @param {boolean} pressed An option is being pressed
18263 */
18264 OO.ui.SelectWidget.prototype.togglePressed = function ( pressed ) {
18265 if ( pressed === undefined ) {
18266 pressed = !this.pressed;
18267 }
18268 if ( pressed !== this.pressed ) {
18269 this.$element
18270 .toggleClass( 'oo-ui-selectWidget-pressed', pressed )
18271 .toggleClass( 'oo-ui-selectWidget-depressed', !pressed );
18272 this.pressed = pressed;
18273 }
18274 };
18275
18276 /**
18277 * Highlight an option. If the `item` param is omitted, no options will be highlighted
18278 * and any existing highlight will be removed. The highlight is mutually exclusive.
18279 *
18280 * @param {OO.ui.OptionWidget} [item] Item to highlight, omit for no highlight
18281 * @fires highlight
18282 * @chainable
18283 */
18284 OO.ui.SelectWidget.prototype.highlightItem = function ( item ) {
18285 var i, len, highlighted,
18286 changed = false;
18287
18288 for ( i = 0, len = this.items.length; i < len; i++ ) {
18289 highlighted = this.items[ i ] === item;
18290 if ( this.items[ i ].isHighlighted() !== highlighted ) {
18291 this.items[ i ].setHighlighted( highlighted );
18292 changed = true;
18293 }
18294 }
18295 if ( changed ) {
18296 this.emit( 'highlight', item );
18297 }
18298
18299 return this;
18300 };
18301
18302 /**
18303 * Fetch an item by its label.
18304 *
18305 * @param {string} label Label of the item to select.
18306 * @param {boolean} [prefix=false] Allow a prefix match, if only a single item matches
18307 * @return {OO.ui.Element|null} Item with equivalent label, `null` if none exists
18308 */
18309 OO.ui.SelectWidget.prototype.getItemFromLabel = function ( label, prefix ) {
18310 var i, item, found,
18311 len = this.items.length,
18312 filter = this.getItemMatcher( label, true );
18313
18314 for ( i = 0; i < len; i++ ) {
18315 item = this.items[ i ];
18316 if ( item instanceof OO.ui.OptionWidget && item.isSelectable() && filter( item ) ) {
18317 return item;
18318 }
18319 }
18320
18321 if ( prefix ) {
18322 found = null;
18323 filter = this.getItemMatcher( label, false );
18324 for ( i = 0; i < len; i++ ) {
18325 item = this.items[ i ];
18326 if ( item instanceof OO.ui.OptionWidget && item.isSelectable() && filter( item ) ) {
18327 if ( found ) {
18328 return null;
18329 }
18330 found = item;
18331 }
18332 }
18333 if ( found ) {
18334 return found;
18335 }
18336 }
18337
18338 return null;
18339 };
18340
18341 /**
18342 * Programmatically select an option by its label. If the item does not exist,
18343 * all options will be deselected.
18344 *
18345 * @param {string} [label] Label of the item to select.
18346 * @param {boolean} [prefix=false] Allow a prefix match, if only a single item matches
18347 * @fires select
18348 * @chainable
18349 */
18350 OO.ui.SelectWidget.prototype.selectItemByLabel = function ( label, prefix ) {
18351 var itemFromLabel = this.getItemFromLabel( label, !!prefix );
18352 if ( label === undefined || !itemFromLabel ) {
18353 return this.selectItem();
18354 }
18355 return this.selectItem( itemFromLabel );
18356 };
18357
18358 /**
18359 * Programmatically select an option by its data. If the `data` parameter is omitted,
18360 * or if the item does not exist, all options will be deselected.
18361 *
18362 * @param {Object|string} [data] Value of the item to select, omit to deselect all
18363 * @fires select
18364 * @chainable
18365 */
18366 OO.ui.SelectWidget.prototype.selectItemByData = function ( data ) {
18367 var itemFromData = this.getItemFromData( data );
18368 if ( data === undefined || !itemFromData ) {
18369 return this.selectItem();
18370 }
18371 return this.selectItem( itemFromData );
18372 };
18373
18374 /**
18375 * Programmatically select an option by its reference. If the `item` parameter is omitted,
18376 * all options will be deselected.
18377 *
18378 * @param {OO.ui.OptionWidget} [item] Item to select, omit to deselect all
18379 * @fires select
18380 * @chainable
18381 */
18382 OO.ui.SelectWidget.prototype.selectItem = function ( item ) {
18383 var i, len, selected,
18384 changed = false;
18385
18386 for ( i = 0, len = this.items.length; i < len; i++ ) {
18387 selected = this.items[ i ] === item;
18388 if ( this.items[ i ].isSelected() !== selected ) {
18389 this.items[ i ].setSelected( selected );
18390 changed = true;
18391 }
18392 }
18393 if ( changed ) {
18394 this.emit( 'select', item );
18395 }
18396
18397 return this;
18398 };
18399
18400 /**
18401 * Press an item.
18402 *
18403 * Press is a state that occurs when a user mouses down on an item, but has not
18404 * yet let go of the mouse. The item may appear selected, but it will not be selected until the user
18405 * releases the mouse.
18406 *
18407 * @param {OO.ui.OptionWidget} [item] Item to press, omit to depress all
18408 * @fires press
18409 * @chainable
18410 */
18411 OO.ui.SelectWidget.prototype.pressItem = function ( item ) {
18412 var i, len, pressed,
18413 changed = false;
18414
18415 for ( i = 0, len = this.items.length; i < len; i++ ) {
18416 pressed = this.items[ i ] === item;
18417 if ( this.items[ i ].isPressed() !== pressed ) {
18418 this.items[ i ].setPressed( pressed );
18419 changed = true;
18420 }
18421 }
18422 if ( changed ) {
18423 this.emit( 'press', item );
18424 }
18425
18426 return this;
18427 };
18428
18429 /**
18430 * Choose an item.
18431 *
18432 * Note that ‘choose’ should never be modified programmatically. A user can choose
18433 * an option with the keyboard or mouse and it becomes selected. To select an item programmatically,
18434 * use the #selectItem method.
18435 *
18436 * This method is identical to #selectItem, but may vary in subclasses that take additional action
18437 * when users choose an item with the keyboard or mouse.
18438 *
18439 * @param {OO.ui.OptionWidget} item Item to choose
18440 * @fires choose
18441 * @chainable
18442 */
18443 OO.ui.SelectWidget.prototype.chooseItem = function ( item ) {
18444 if ( item ) {
18445 this.selectItem( item );
18446 this.emit( 'choose', item );
18447 }
18448
18449 return this;
18450 };
18451
18452 /**
18453 * Get an option by its position relative to the specified item (or to the start of the option array,
18454 * if item is `null`). The direction in which to search through the option array is specified with a
18455 * number: -1 for reverse (the default) or 1 for forward. The method will return an option, or
18456 * `null` if there are no options in the array.
18457 *
18458 * @param {OO.ui.OptionWidget|null} item Item to describe the start position, or `null` to start at the beginning of the array.
18459 * @param {number} direction Direction to move in: -1 to move backward, 1 to move forward
18460 * @param {Function} filter Only consider items for which this function returns
18461 * true. Function takes an OO.ui.OptionWidget and returns a boolean.
18462 * @return {OO.ui.OptionWidget|null} Item at position, `null` if there are no items in the select
18463 */
18464 OO.ui.SelectWidget.prototype.getRelativeSelectableItem = function ( item, direction, filter ) {
18465 var currentIndex, nextIndex, i,
18466 increase = direction > 0 ? 1 : -1,
18467 len = this.items.length;
18468
18469 if ( !$.isFunction( filter ) ) {
18470 filter = OO.ui.SelectWidget.static.passAllFilter;
18471 }
18472
18473 if ( item instanceof OO.ui.OptionWidget ) {
18474 currentIndex = this.items.indexOf( item );
18475 nextIndex = ( currentIndex + increase + len ) % len;
18476 } else {
18477 // If no item is selected and moving forward, start at the beginning.
18478 // If moving backward, start at the end.
18479 nextIndex = direction > 0 ? 0 : len - 1;
18480 }
18481
18482 for ( i = 0; i < len; i++ ) {
18483 item = this.items[ nextIndex ];
18484 if ( item instanceof OO.ui.OptionWidget && item.isSelectable() && filter( item ) ) {
18485 return item;
18486 }
18487 nextIndex = ( nextIndex + increase + len ) % len;
18488 }
18489 return null;
18490 };
18491
18492 /**
18493 * Get the next selectable item or `null` if there are no selectable items.
18494 * Disabled options and menu-section markers and breaks are not selectable.
18495 *
18496 * @return {OO.ui.OptionWidget|null} Item, `null` if there aren't any selectable items
18497 */
18498 OO.ui.SelectWidget.prototype.getFirstSelectableItem = function () {
18499 var i, len, item;
18500
18501 for ( i = 0, len = this.items.length; i < len; i++ ) {
18502 item = this.items[ i ];
18503 if ( item instanceof OO.ui.OptionWidget && item.isSelectable() ) {
18504 return item;
18505 }
18506 }
18507
18508 return null;
18509 };
18510
18511 /**
18512 * Add an array of options to the select. Optionally, an index number can be used to
18513 * specify an insertion point.
18514 *
18515 * @param {OO.ui.OptionWidget[]} items Items to add
18516 * @param {number} [index] Index to insert items after
18517 * @fires add
18518 * @chainable
18519 */
18520 OO.ui.SelectWidget.prototype.addItems = function ( items, index ) {
18521 // Mixin method
18522 OO.ui.mixin.GroupWidget.prototype.addItems.call( this, items, index );
18523
18524 // Always provide an index, even if it was omitted
18525 this.emit( 'add', items, index === undefined ? this.items.length - items.length - 1 : index );
18526
18527 return this;
18528 };
18529
18530 /**
18531 * Remove the specified array of options from the select. Options will be detached
18532 * from the DOM, not removed, so they can be reused later. To remove all options from
18533 * the select, you may wish to use the #clearItems method instead.
18534 *
18535 * @param {OO.ui.OptionWidget[]} items Items to remove
18536 * @fires remove
18537 * @chainable
18538 */
18539 OO.ui.SelectWidget.prototype.removeItems = function ( items ) {
18540 var i, len, item;
18541
18542 // Deselect items being removed
18543 for ( i = 0, len = items.length; i < len; i++ ) {
18544 item = items[ i ];
18545 if ( item.isSelected() ) {
18546 this.selectItem( null );
18547 }
18548 }
18549
18550 // Mixin method
18551 OO.ui.mixin.GroupWidget.prototype.removeItems.call( this, items );
18552
18553 this.emit( 'remove', items );
18554
18555 return this;
18556 };
18557
18558 /**
18559 * Clear all options from the select. Options will be detached from the DOM, not removed,
18560 * so that they can be reused later. To remove a subset of options from the select, use
18561 * the #removeItems method.
18562 *
18563 * @fires remove
18564 * @chainable
18565 */
18566 OO.ui.SelectWidget.prototype.clearItems = function () {
18567 var items = this.items.slice();
18568
18569 // Mixin method
18570 OO.ui.mixin.GroupWidget.prototype.clearItems.call( this );
18571
18572 // Clear selection
18573 this.selectItem( null );
18574
18575 this.emit( 'remove', items );
18576
18577 return this;
18578 };
18579
18580 /**
18581 * ButtonSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains
18582 * button options and is used together with
18583 * OO.ui.ButtonOptionWidget. The ButtonSelectWidget provides an interface for
18584 * highlighting, choosing, and selecting mutually exclusive options. Please see
18585 * the [OOjs UI documentation on MediaWiki] [1] for more information.
18586 *
18587 * @example
18588 * // Example: A ButtonSelectWidget that contains three ButtonOptionWidgets
18589 * var option1 = new OO.ui.ButtonOptionWidget( {
18590 * data: 1,
18591 * label: 'Option 1',
18592 * title: 'Button option 1'
18593 * } );
18594 *
18595 * var option2 = new OO.ui.ButtonOptionWidget( {
18596 * data: 2,
18597 * label: 'Option 2',
18598 * title: 'Button option 2'
18599 * } );
18600 *
18601 * var option3 = new OO.ui.ButtonOptionWidget( {
18602 * data: 3,
18603 * label: 'Option 3',
18604 * title: 'Button option 3'
18605 * } );
18606 *
18607 * var buttonSelect=new OO.ui.ButtonSelectWidget( {
18608 * items: [ option1, option2, option3 ]
18609 * } );
18610 * $( 'body' ).append( buttonSelect.$element );
18611 *
18612 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
18613 *
18614 * @class
18615 * @extends OO.ui.SelectWidget
18616 * @mixins OO.ui.mixin.TabIndexedElement
18617 *
18618 * @constructor
18619 * @param {Object} [config] Configuration options
18620 */
18621 OO.ui.ButtonSelectWidget = function OoUiButtonSelectWidget( config ) {
18622 // Parent constructor
18623 OO.ui.ButtonSelectWidget.parent.call( this, config );
18624
18625 // Mixin constructors
18626 OO.ui.mixin.TabIndexedElement.call( this, config );
18627
18628 // Events
18629 this.$element.on( {
18630 focus: this.bindKeyDownListener.bind( this ),
18631 blur: this.unbindKeyDownListener.bind( this )
18632 } );
18633
18634 // Initialization
18635 this.$element.addClass( 'oo-ui-buttonSelectWidget' );
18636 };
18637
18638 /* Setup */
18639
18640 OO.inheritClass( OO.ui.ButtonSelectWidget, OO.ui.SelectWidget );
18641 OO.mixinClass( OO.ui.ButtonSelectWidget, OO.ui.mixin.TabIndexedElement );
18642
18643 /**
18644 * RadioSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains radio
18645 * options and is used together with OO.ui.RadioOptionWidget. The RadioSelectWidget provides
18646 * an interface for adding, removing and selecting options.
18647 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
18648 *
18649 * If you want to use this within a HTML form, such as a OO.ui.FormLayout, use
18650 * OO.ui.RadioSelectInputWidget instead.
18651 *
18652 * @example
18653 * // A RadioSelectWidget with RadioOptions.
18654 * var option1 = new OO.ui.RadioOptionWidget( {
18655 * data: 'a',
18656 * label: 'Selected radio option'
18657 * } );
18658 *
18659 * var option2 = new OO.ui.RadioOptionWidget( {
18660 * data: 'b',
18661 * label: 'Unselected radio option'
18662 * } );
18663 *
18664 * var radioSelect=new OO.ui.RadioSelectWidget( {
18665 * items: [ option1, option2 ]
18666 * } );
18667 *
18668 * // Select 'option 1' using the RadioSelectWidget's selectItem() method.
18669 * radioSelect.selectItem( option1 );
18670 *
18671 * $( 'body' ).append( radioSelect.$element );
18672 *
18673 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
18674
18675 *
18676 * @class
18677 * @extends OO.ui.SelectWidget
18678 * @mixins OO.ui.mixin.TabIndexedElement
18679 *
18680 * @constructor
18681 * @param {Object} [config] Configuration options
18682 */
18683 OO.ui.RadioSelectWidget = function OoUiRadioSelectWidget( config ) {
18684 // Parent constructor
18685 OO.ui.RadioSelectWidget.parent.call( this, config );
18686
18687 // Mixin constructors
18688 OO.ui.mixin.TabIndexedElement.call( this, config );
18689
18690 // Events
18691 this.$element.on( {
18692 focus: this.bindKeyDownListener.bind( this ),
18693 blur: this.unbindKeyDownListener.bind( this )
18694 } );
18695
18696 // Initialization
18697 this.$element
18698 .addClass( 'oo-ui-radioSelectWidget' )
18699 .attr( 'role', 'radiogroup' );
18700 };
18701
18702 /* Setup */
18703
18704 OO.inheritClass( OO.ui.RadioSelectWidget, OO.ui.SelectWidget );
18705 OO.mixinClass( OO.ui.RadioSelectWidget, OO.ui.mixin.TabIndexedElement );
18706
18707 /**
18708 * MenuSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains options and
18709 * is used together with OO.ui.MenuOptionWidget. It is designed be used as part of another widget.
18710 * See {@link OO.ui.DropdownWidget DropdownWidget}, {@link OO.ui.ComboBoxWidget ComboBoxWidget},
18711 * and {@link OO.ui.mixin.LookupElement LookupElement} for examples of widgets that contain menus.
18712 * MenuSelectWidgets themselves are not instantiated directly, rather subclassed
18713 * and customized to be opened, closed, and displayed as needed.
18714 *
18715 * By default, menus are clipped to the visible viewport and are not visible when a user presses the
18716 * mouse outside the menu.
18717 *
18718 * Menus also have support for keyboard interaction:
18719 *
18720 * - Enter/Return key: choose and select a menu option
18721 * - Up-arrow key: highlight the previous menu option
18722 * - Down-arrow key: highlight the next menu option
18723 * - Esc key: hide the menu
18724 *
18725 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
18726 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
18727 *
18728 * @class
18729 * @extends OO.ui.SelectWidget
18730 * @mixins OO.ui.mixin.ClippableElement
18731 *
18732 * @constructor
18733 * @param {Object} [config] Configuration options
18734 * @cfg {OO.ui.TextInputWidget} [input] Text input used to implement option highlighting for menu items that match
18735 * the text the user types. This config is used by {@link OO.ui.ComboBoxWidget ComboBoxWidget}
18736 * and {@link OO.ui.mixin.LookupElement LookupElement}
18737 * @cfg {jQuery} [$input] Text input used to implement option highlighting for menu items that match
18738 * the text the user types. This config is used by {@link OO.ui.CapsuleMultiSelectWidget CapsuleMultiSelectWidget}
18739 * @cfg {OO.ui.Widget} [widget] Widget associated with the menu's active state. If the user clicks the mouse
18740 * anywhere on the page outside of this widget, the menu is hidden. For example, if there is a button
18741 * that toggles the menu's visibility on click, the menu will be hidden then re-shown when the user clicks
18742 * that button, unless the button (or its parent widget) is passed in here.
18743 * @cfg {boolean} [autoHide=true] Hide the menu when the mouse is pressed outside the menu.
18744 * @cfg {boolean} [filterFromInput=false] Filter the displayed options from the input
18745 */
18746 OO.ui.MenuSelectWidget = function OoUiMenuSelectWidget( config ) {
18747 // Configuration initialization
18748 config = config || {};
18749
18750 // Parent constructor
18751 OO.ui.MenuSelectWidget.parent.call( this, config );
18752
18753 // Mixin constructors
18754 OO.ui.mixin.ClippableElement.call( this, $.extend( {}, config, { $clippable: this.$group } ) );
18755
18756 // Properties
18757 this.newItems = null;
18758 this.autoHide = config.autoHide === undefined || !!config.autoHide;
18759 this.filterFromInput = !!config.filterFromInput;
18760 this.$input = config.$input ? config.$input : config.input ? config.input.$input : null;
18761 this.$widget = config.widget ? config.widget.$element : null;
18762 this.onDocumentMouseDownHandler = this.onDocumentMouseDown.bind( this );
18763 this.onInputEditHandler = OO.ui.debounce( this.updateItemVisibility.bind( this ), 100 );
18764
18765 // Initialization
18766 this.$element
18767 .addClass( 'oo-ui-menuSelectWidget' )
18768 .attr( 'role', 'menu' );
18769
18770 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
18771 // that reference properties not initialized at that time of parent class construction
18772 // TODO: Find a better way to handle post-constructor setup
18773 this.visible = false;
18774 this.$element.addClass( 'oo-ui-element-hidden' );
18775 };
18776
18777 /* Setup */
18778
18779 OO.inheritClass( OO.ui.MenuSelectWidget, OO.ui.SelectWidget );
18780 OO.mixinClass( OO.ui.MenuSelectWidget, OO.ui.mixin.ClippableElement );
18781
18782 /* Methods */
18783
18784 /**
18785 * Handles document mouse down events.
18786 *
18787 * @protected
18788 * @param {jQuery.Event} e Key down event
18789 */
18790 OO.ui.MenuSelectWidget.prototype.onDocumentMouseDown = function ( e ) {
18791 if (
18792 !OO.ui.contains( this.$element[ 0 ], e.target, true ) &&
18793 ( !this.$widget || !OO.ui.contains( this.$widget[ 0 ], e.target, true ) )
18794 ) {
18795 this.toggle( false );
18796 }
18797 };
18798
18799 /**
18800 * @inheritdoc
18801 */
18802 OO.ui.MenuSelectWidget.prototype.onKeyDown = function ( e ) {
18803 var currentItem = this.getHighlightedItem() || this.getSelectedItem();
18804
18805 if ( !this.isDisabled() && this.isVisible() ) {
18806 switch ( e.keyCode ) {
18807 case OO.ui.Keys.LEFT:
18808 case OO.ui.Keys.RIGHT:
18809 // Do nothing if a text field is associated, arrow keys will be handled natively
18810 if ( !this.$input ) {
18811 OO.ui.MenuSelectWidget.parent.prototype.onKeyDown.call( this, e );
18812 }
18813 break;
18814 case OO.ui.Keys.ESCAPE:
18815 case OO.ui.Keys.TAB:
18816 if ( currentItem ) {
18817 currentItem.setHighlighted( false );
18818 }
18819 this.toggle( false );
18820 // Don't prevent tabbing away, prevent defocusing
18821 if ( e.keyCode === OO.ui.Keys.ESCAPE ) {
18822 e.preventDefault();
18823 e.stopPropagation();
18824 }
18825 break;
18826 default:
18827 OO.ui.MenuSelectWidget.parent.prototype.onKeyDown.call( this, e );
18828 return;
18829 }
18830 }
18831 };
18832
18833 /**
18834 * Update menu item visibility after input changes.
18835 * @protected
18836 */
18837 OO.ui.MenuSelectWidget.prototype.updateItemVisibility = function () {
18838 var i, item,
18839 len = this.items.length,
18840 showAll = !this.isVisible(),
18841 filter = showAll ? null : this.getItemMatcher( this.$input.val() );
18842
18843 for ( i = 0; i < len; i++ ) {
18844 item = this.items[ i ];
18845 if ( item instanceof OO.ui.OptionWidget ) {
18846 item.toggle( showAll || filter( item ) );
18847 }
18848 }
18849
18850 // Reevaluate clipping
18851 this.clip();
18852 };
18853
18854 /**
18855 * @inheritdoc
18856 */
18857 OO.ui.MenuSelectWidget.prototype.bindKeyDownListener = function () {
18858 if ( this.$input ) {
18859 this.$input.on( 'keydown', this.onKeyDownHandler );
18860 } else {
18861 OO.ui.MenuSelectWidget.parent.prototype.bindKeyDownListener.call( this );
18862 }
18863 };
18864
18865 /**
18866 * @inheritdoc
18867 */
18868 OO.ui.MenuSelectWidget.prototype.unbindKeyDownListener = function () {
18869 if ( this.$input ) {
18870 this.$input.off( 'keydown', this.onKeyDownHandler );
18871 } else {
18872 OO.ui.MenuSelectWidget.parent.prototype.unbindKeyDownListener.call( this );
18873 }
18874 };
18875
18876 /**
18877 * @inheritdoc
18878 */
18879 OO.ui.MenuSelectWidget.prototype.bindKeyPressListener = function () {
18880 if ( this.$input ) {
18881 if ( this.filterFromInput ) {
18882 this.$input.on( 'keydown mouseup cut paste change input select', this.onInputEditHandler );
18883 }
18884 } else {
18885 OO.ui.MenuSelectWidget.parent.prototype.bindKeyPressListener.call( this );
18886 }
18887 };
18888
18889 /**
18890 * @inheritdoc
18891 */
18892 OO.ui.MenuSelectWidget.prototype.unbindKeyPressListener = function () {
18893 if ( this.$input ) {
18894 if ( this.filterFromInput ) {
18895 this.$input.off( 'keydown mouseup cut paste change input select', this.onInputEditHandler );
18896 this.updateItemVisibility();
18897 }
18898 } else {
18899 OO.ui.MenuSelectWidget.parent.prototype.unbindKeyPressListener.call( this );
18900 }
18901 };
18902
18903 /**
18904 * Choose an item.
18905 *
18906 * When a user chooses an item, the menu is closed.
18907 *
18908 * Note that ‘choose’ should never be modified programmatically. A user can choose an option with the keyboard
18909 * or mouse and it becomes selected. To select an item programmatically, use the #selectItem method.
18910 * @param {OO.ui.OptionWidget} item Item to choose
18911 * @chainable
18912 */
18913 OO.ui.MenuSelectWidget.prototype.chooseItem = function ( item ) {
18914 OO.ui.MenuSelectWidget.parent.prototype.chooseItem.call( this, item );
18915 this.toggle( false );
18916 return this;
18917 };
18918
18919 /**
18920 * @inheritdoc
18921 */
18922 OO.ui.MenuSelectWidget.prototype.addItems = function ( items, index ) {
18923 var i, len, item;
18924
18925 // Parent method
18926 OO.ui.MenuSelectWidget.parent.prototype.addItems.call( this, items, index );
18927
18928 // Auto-initialize
18929 if ( !this.newItems ) {
18930 this.newItems = [];
18931 }
18932
18933 for ( i = 0, len = items.length; i < len; i++ ) {
18934 item = items[ i ];
18935 if ( this.isVisible() ) {
18936 // Defer fitting label until item has been attached
18937 item.fitLabel();
18938 } else {
18939 this.newItems.push( item );
18940 }
18941 }
18942
18943 // Reevaluate clipping
18944 this.clip();
18945
18946 return this;
18947 };
18948
18949 /**
18950 * @inheritdoc
18951 */
18952 OO.ui.MenuSelectWidget.prototype.removeItems = function ( items ) {
18953 // Parent method
18954 OO.ui.MenuSelectWidget.parent.prototype.removeItems.call( this, items );
18955
18956 // Reevaluate clipping
18957 this.clip();
18958
18959 return this;
18960 };
18961
18962 /**
18963 * @inheritdoc
18964 */
18965 OO.ui.MenuSelectWidget.prototype.clearItems = function () {
18966 // Parent method
18967 OO.ui.MenuSelectWidget.parent.prototype.clearItems.call( this );
18968
18969 // Reevaluate clipping
18970 this.clip();
18971
18972 return this;
18973 };
18974
18975 /**
18976 * @inheritdoc
18977 */
18978 OO.ui.MenuSelectWidget.prototype.toggle = function ( visible ) {
18979 var i, len, change;
18980
18981 visible = ( visible === undefined ? !this.visible : !!visible ) && !!this.items.length;
18982 change = visible !== this.isVisible();
18983
18984 // Parent method
18985 OO.ui.MenuSelectWidget.parent.prototype.toggle.call( this, visible );
18986
18987 if ( change ) {
18988 if ( visible ) {
18989 this.bindKeyDownListener();
18990 this.bindKeyPressListener();
18991
18992 if ( this.newItems && this.newItems.length ) {
18993 for ( i = 0, len = this.newItems.length; i < len; i++ ) {
18994 this.newItems[ i ].fitLabel();
18995 }
18996 this.newItems = null;
18997 }
18998 this.toggleClipping( true );
18999
19000 // Auto-hide
19001 if ( this.autoHide ) {
19002 OO.ui.addCaptureEventListener( this.getElementDocument(), 'mousedown', this.onDocumentMouseDownHandler );
19003 }
19004 } else {
19005 this.unbindKeyDownListener();
19006 this.unbindKeyPressListener();
19007 OO.ui.removeCaptureEventListener( this.getElementDocument(), 'mousedown', this.onDocumentMouseDownHandler );
19008 this.toggleClipping( false );
19009 }
19010 }
19011
19012 return this;
19013 };
19014
19015 /**
19016 * FloatingMenuSelectWidget is a menu that will stick under a specified
19017 * container, even when it is inserted elsewhere in the document (for example,
19018 * in a OO.ui.Window's $overlay). This is sometimes necessary to prevent the
19019 * menu from being clipped too aggresively.
19020 *
19021 * The menu's position is automatically calculated and maintained when the menu
19022 * is toggled or the window is resized.
19023 *
19024 * See OO.ui.ComboBoxWidget for an example of a widget that uses this class.
19025 *
19026 * @class
19027 * @extends OO.ui.MenuSelectWidget
19028 * @mixins OO.ui.mixin.FloatableElement
19029 *
19030 * @constructor
19031 * @param {OO.ui.Widget} [inputWidget] Widget to provide the menu for.
19032 * Deprecated, omit this parameter and specify `$container` instead.
19033 * @param {Object} [config] Configuration options
19034 * @cfg {jQuery} [$container=inputWidget.$element] Element to render menu under
19035 */
19036 OO.ui.FloatingMenuSelectWidget = function OoUiFloatingMenuSelectWidget( inputWidget, config ) {
19037 // Allow 'inputWidget' parameter and config for backwards compatibility
19038 if ( OO.isPlainObject( inputWidget ) && config === undefined ) {
19039 config = inputWidget;
19040 inputWidget = config.inputWidget;
19041 }
19042
19043 // Configuration initialization
19044 config = config || {};
19045
19046 // Parent constructor
19047 OO.ui.FloatingMenuSelectWidget.parent.call( this, config );
19048
19049 // Properties (must be set before mixin constructors)
19050 this.inputWidget = inputWidget; // For backwards compatibility
19051 this.$container = config.$container || this.inputWidget.$element;
19052
19053 // Mixins constructors
19054 OO.ui.mixin.FloatableElement.call( this, $.extend( {}, config, { $floatableContainer: this.$container } ) );
19055
19056 // Initialization
19057 this.$element.addClass( 'oo-ui-floatingMenuSelectWidget' );
19058 // For backwards compatibility
19059 this.$element.addClass( 'oo-ui-textInputMenuSelectWidget' );
19060 };
19061
19062 /* Setup */
19063
19064 OO.inheritClass( OO.ui.FloatingMenuSelectWidget, OO.ui.MenuSelectWidget );
19065 OO.mixinClass( OO.ui.FloatingMenuSelectWidget, OO.ui.mixin.FloatableElement );
19066
19067 // For backwards compatibility
19068 OO.ui.TextInputMenuSelectWidget = OO.ui.FloatingMenuSelectWidget;
19069
19070 /* Methods */
19071
19072 /**
19073 * @inheritdoc
19074 */
19075 OO.ui.FloatingMenuSelectWidget.prototype.toggle = function ( visible ) {
19076 var change;
19077 visible = visible === undefined ? !this.isVisible() : !!visible;
19078 change = visible !== this.isVisible();
19079
19080 if ( change && visible ) {
19081 // Make sure the width is set before the parent method runs.
19082 this.setIdealSize( this.$container.width() );
19083 }
19084
19085 // Parent method
19086 // This will call this.clip(), which is nonsensical since we're not positioned yet...
19087 OO.ui.FloatingMenuSelectWidget.parent.prototype.toggle.call( this, visible );
19088
19089 if ( change ) {
19090 this.togglePositioning( this.isVisible() );
19091 }
19092
19093 return this;
19094 };
19095
19096 /**
19097 * OutlineSelectWidget is a structured list that contains {@link OO.ui.OutlineOptionWidget outline options}
19098 * A set of controls can be provided with an {@link OO.ui.OutlineControlsWidget outline controls} widget.
19099 *
19100 * **Currently, this class is only used by {@link OO.ui.BookletLayout booklet layouts}.**
19101 *
19102 * @class
19103 * @extends OO.ui.SelectWidget
19104 * @mixins OO.ui.mixin.TabIndexedElement
19105 *
19106 * @constructor
19107 * @param {Object} [config] Configuration options
19108 */
19109 OO.ui.OutlineSelectWidget = function OoUiOutlineSelectWidget( config ) {
19110 // Parent constructor
19111 OO.ui.OutlineSelectWidget.parent.call( this, config );
19112
19113 // Mixin constructors
19114 OO.ui.mixin.TabIndexedElement.call( this, config );
19115
19116 // Events
19117 this.$element.on( {
19118 focus: this.bindKeyDownListener.bind( this ),
19119 blur: this.unbindKeyDownListener.bind( this )
19120 } );
19121
19122 // Initialization
19123 this.$element.addClass( 'oo-ui-outlineSelectWidget' );
19124 };
19125
19126 /* Setup */
19127
19128 OO.inheritClass( OO.ui.OutlineSelectWidget, OO.ui.SelectWidget );
19129 OO.mixinClass( OO.ui.OutlineSelectWidget, OO.ui.mixin.TabIndexedElement );
19130
19131 /**
19132 * TabSelectWidget is a list that contains {@link OO.ui.TabOptionWidget tab options}
19133 *
19134 * **Currently, this class is only used by {@link OO.ui.IndexLayout index layouts}.**
19135 *
19136 * @class
19137 * @extends OO.ui.SelectWidget
19138 * @mixins OO.ui.mixin.TabIndexedElement
19139 *
19140 * @constructor
19141 * @param {Object} [config] Configuration options
19142 */
19143 OO.ui.TabSelectWidget = function OoUiTabSelectWidget( config ) {
19144 // Parent constructor
19145 OO.ui.TabSelectWidget.parent.call( this, config );
19146
19147 // Mixin constructors
19148 OO.ui.mixin.TabIndexedElement.call( this, config );
19149
19150 // Events
19151 this.$element.on( {
19152 focus: this.bindKeyDownListener.bind( this ),
19153 blur: this.unbindKeyDownListener.bind( this )
19154 } );
19155
19156 // Initialization
19157 this.$element.addClass( 'oo-ui-tabSelectWidget' );
19158 };
19159
19160 /* Setup */
19161
19162 OO.inheritClass( OO.ui.TabSelectWidget, OO.ui.SelectWidget );
19163 OO.mixinClass( OO.ui.TabSelectWidget, OO.ui.mixin.TabIndexedElement );
19164
19165 /**
19166 * NumberInputWidgets combine a {@link OO.ui.TextInputWidget text input} (where a value
19167 * can be entered manually) and two {@link OO.ui.ButtonWidget button widgets}
19168 * (to adjust the value in increments) to allow the user to enter a number.
19169 *
19170 * @example
19171 * // Example: A NumberInputWidget.
19172 * var numberInput = new OO.ui.NumberInputWidget( {
19173 * label: 'NumberInputWidget',
19174 * input: { value: 5, min: 1, max: 10 }
19175 * } );
19176 * $( 'body' ).append( numberInput.$element );
19177 *
19178 * @class
19179 * @extends OO.ui.Widget
19180 *
19181 * @constructor
19182 * @param {Object} [config] Configuration options
19183 * @cfg {Object} [input] Configuration options to pass to the {@link OO.ui.TextInputWidget text input widget}.
19184 * @cfg {Object} [minusButton] Configuration options to pass to the {@link OO.ui.ButtonWidget decrementing button widget}.
19185 * @cfg {Object} [plusButton] Configuration options to pass to the {@link OO.ui.ButtonWidget incrementing button widget}.
19186 * @cfg {boolean} [isInteger=false] Whether the field accepts only integer values.
19187 * @cfg {number} [min=-Infinity] Minimum allowed value
19188 * @cfg {number} [max=Infinity] Maximum allowed value
19189 * @cfg {number} [step=1] Delta when using the buttons or up/down arrow keys
19190 * @cfg {number|null} [pageStep] Delta when using the page-up/page-down keys. Defaults to 10 times #step.
19191 */
19192 OO.ui.NumberInputWidget = function OoUiNumberInputWidget( config ) {
19193 // Configuration initialization
19194 config = $.extend( {
19195 isInteger: false,
19196 min: -Infinity,
19197 max: Infinity,
19198 step: 1,
19199 pageStep: null
19200 }, config );
19201
19202 // Parent constructor
19203 OO.ui.NumberInputWidget.parent.call( this, config );
19204
19205 // Properties
19206 this.input = new OO.ui.TextInputWidget( $.extend(
19207 {
19208 disabled: this.isDisabled()
19209 },
19210 config.input
19211 ) );
19212 this.minusButton = new OO.ui.ButtonWidget( $.extend(
19213 {
19214 disabled: this.isDisabled(),
19215 tabIndex: -1
19216 },
19217 config.minusButton,
19218 {
19219 classes: [ 'oo-ui-numberInputWidget-minusButton' ],
19220 label: '−'
19221 }
19222 ) );
19223 this.plusButton = new OO.ui.ButtonWidget( $.extend(
19224 {
19225 disabled: this.isDisabled(),
19226 tabIndex: -1
19227 },
19228 config.plusButton,
19229 {
19230 classes: [ 'oo-ui-numberInputWidget-plusButton' ],
19231 label: '+'
19232 }
19233 ) );
19234
19235 // Events
19236 this.input.connect( this, {
19237 change: this.emit.bind( this, 'change' ),
19238 enter: this.emit.bind( this, 'enter' )
19239 } );
19240 this.input.$input.on( {
19241 keydown: this.onKeyDown.bind( this ),
19242 'wheel mousewheel DOMMouseScroll': this.onWheel.bind( this )
19243 } );
19244 this.plusButton.connect( this, {
19245 click: [ 'onButtonClick', +1 ]
19246 } );
19247 this.minusButton.connect( this, {
19248 click: [ 'onButtonClick', -1 ]
19249 } );
19250
19251 // Initialization
19252 this.setIsInteger( !!config.isInteger );
19253 this.setRange( config.min, config.max );
19254 this.setStep( config.step, config.pageStep );
19255
19256 this.$field = $( '<div>' ).addClass( 'oo-ui-numberInputWidget-field' )
19257 .append(
19258 this.minusButton.$element,
19259 this.input.$element,
19260 this.plusButton.$element
19261 );
19262 this.$element.addClass( 'oo-ui-numberInputWidget' ).append( this.$field );
19263 this.input.setValidation( this.validateNumber.bind( this ) );
19264 };
19265
19266 /* Setup */
19267
19268 OO.inheritClass( OO.ui.NumberInputWidget, OO.ui.Widget );
19269
19270 /* Events */
19271
19272 /**
19273 * A `change` event is emitted when the value of the input changes.
19274 *
19275 * @event change
19276 */
19277
19278 /**
19279 * An `enter` event is emitted when the user presses 'enter' inside the text box.
19280 *
19281 * @event enter
19282 */
19283
19284 /* Methods */
19285
19286 /**
19287 * Set whether only integers are allowed
19288 * @param {boolean} flag
19289 */
19290 OO.ui.NumberInputWidget.prototype.setIsInteger = function ( flag ) {
19291 this.isInteger = !!flag;
19292 this.input.setValidityFlag();
19293 };
19294
19295 /**
19296 * Get whether only integers are allowed
19297 * @return {boolean} Flag value
19298 */
19299 OO.ui.NumberInputWidget.prototype.getIsInteger = function () {
19300 return this.isInteger;
19301 };
19302
19303 /**
19304 * Set the range of allowed values
19305 * @param {number} min Minimum allowed value
19306 * @param {number} max Maximum allowed value
19307 */
19308 OO.ui.NumberInputWidget.prototype.setRange = function ( min, max ) {
19309 if ( min > max ) {
19310 throw new Error( 'Minimum (' + min + ') must not be greater than maximum (' + max + ')' );
19311 }
19312 this.min = min;
19313 this.max = max;
19314 this.input.setValidityFlag();
19315 };
19316
19317 /**
19318 * Get the current range
19319 * @return {number[]} Minimum and maximum values
19320 */
19321 OO.ui.NumberInputWidget.prototype.getRange = function () {
19322 return [ this.min, this.max ];
19323 };
19324
19325 /**
19326 * Set the stepping deltas
19327 * @param {number} step Normal step
19328 * @param {number|null} pageStep Page step. If null, 10 * step will be used.
19329 */
19330 OO.ui.NumberInputWidget.prototype.setStep = function ( step, pageStep ) {
19331 if ( step <= 0 ) {
19332 throw new Error( 'Step value must be positive' );
19333 }
19334 if ( pageStep === null ) {
19335 pageStep = step * 10;
19336 } else if ( pageStep <= 0 ) {
19337 throw new Error( 'Page step value must be positive' );
19338 }
19339 this.step = step;
19340 this.pageStep = pageStep;
19341 };
19342
19343 /**
19344 * Get the current stepping values
19345 * @return {number[]} Step and page step
19346 */
19347 OO.ui.NumberInputWidget.prototype.getStep = function () {
19348 return [ this.step, this.pageStep ];
19349 };
19350
19351 /**
19352 * Get the current value of the widget
19353 * @return {string}
19354 */
19355 OO.ui.NumberInputWidget.prototype.getValue = function () {
19356 return this.input.getValue();
19357 };
19358
19359 /**
19360 * Get the current value of the widget as a number
19361 * @return {number} May be NaN, or an invalid number
19362 */
19363 OO.ui.NumberInputWidget.prototype.getNumericValue = function () {
19364 return +this.input.getValue();
19365 };
19366
19367 /**
19368 * Set the value of the widget
19369 * @param {string} value Invalid values are allowed
19370 */
19371 OO.ui.NumberInputWidget.prototype.setValue = function ( value ) {
19372 this.input.setValue( value );
19373 };
19374
19375 /**
19376 * Adjust the value of the widget
19377 * @param {number} delta Adjustment amount
19378 */
19379 OO.ui.NumberInputWidget.prototype.adjustValue = function ( delta ) {
19380 var n, v = this.getNumericValue();
19381
19382 delta = +delta;
19383 if ( isNaN( delta ) || !isFinite( delta ) ) {
19384 throw new Error( 'Delta must be a finite number' );
19385 }
19386
19387 if ( isNaN( v ) ) {
19388 n = 0;
19389 } else {
19390 n = v + delta;
19391 n = Math.max( Math.min( n, this.max ), this.min );
19392 if ( this.isInteger ) {
19393 n = Math.round( n );
19394 }
19395 }
19396
19397 if ( n !== v ) {
19398 this.setValue( n );
19399 }
19400 };
19401
19402 /**
19403 * Validate input
19404 * @private
19405 * @param {string} value Field value
19406 * @return {boolean}
19407 */
19408 OO.ui.NumberInputWidget.prototype.validateNumber = function ( value ) {
19409 var n = +value;
19410 if ( isNaN( n ) || !isFinite( n ) ) {
19411 return false;
19412 }
19413
19414 /*jshint bitwise: false */
19415 if ( this.isInteger && ( n | 0 ) !== n ) {
19416 return false;
19417 }
19418 /*jshint bitwise: true */
19419
19420 if ( n < this.min || n > this.max ) {
19421 return false;
19422 }
19423
19424 return true;
19425 };
19426
19427 /**
19428 * Handle mouse click events.
19429 *
19430 * @private
19431 * @param {number} dir +1 or -1
19432 */
19433 OO.ui.NumberInputWidget.prototype.onButtonClick = function ( dir ) {
19434 this.adjustValue( dir * this.step );
19435 };
19436
19437 /**
19438 * Handle mouse wheel events.
19439 *
19440 * @private
19441 * @param {jQuery.Event} event
19442 */
19443 OO.ui.NumberInputWidget.prototype.onWheel = function ( event ) {
19444 var delta = 0;
19445
19446 // Standard 'wheel' event
19447 if ( event.originalEvent.deltaMode !== undefined ) {
19448 this.sawWheelEvent = true;
19449 }
19450 if ( event.originalEvent.deltaY ) {
19451 delta = -event.originalEvent.deltaY;
19452 } else if ( event.originalEvent.deltaX ) {
19453 delta = event.originalEvent.deltaX;
19454 }
19455
19456 // Non-standard events
19457 if ( !this.sawWheelEvent ) {
19458 if ( event.originalEvent.wheelDeltaX ) {
19459 delta = -event.originalEvent.wheelDeltaX;
19460 } else if ( event.originalEvent.wheelDeltaY ) {
19461 delta = event.originalEvent.wheelDeltaY;
19462 } else if ( event.originalEvent.wheelDelta ) {
19463 delta = event.originalEvent.wheelDelta;
19464 } else if ( event.originalEvent.detail ) {
19465 delta = -event.originalEvent.detail;
19466 }
19467 }
19468
19469 if ( delta ) {
19470 delta = delta < 0 ? -1 : 1;
19471 this.adjustValue( delta * this.step );
19472 }
19473
19474 return false;
19475 };
19476
19477 /**
19478 * Handle key down events.
19479 *
19480 * @private
19481 * @param {jQuery.Event} e Key down event
19482 */
19483 OO.ui.NumberInputWidget.prototype.onKeyDown = function ( e ) {
19484 if ( !this.isDisabled() ) {
19485 switch ( e.which ) {
19486 case OO.ui.Keys.UP:
19487 this.adjustValue( this.step );
19488 return false;
19489 case OO.ui.Keys.DOWN:
19490 this.adjustValue( -this.step );
19491 return false;
19492 case OO.ui.Keys.PAGEUP:
19493 this.adjustValue( this.pageStep );
19494 return false;
19495 case OO.ui.Keys.PAGEDOWN:
19496 this.adjustValue( -this.pageStep );
19497 return false;
19498 }
19499 }
19500 };
19501
19502 /**
19503 * @inheritdoc
19504 */
19505 OO.ui.NumberInputWidget.prototype.setDisabled = function ( disabled ) {
19506 // Parent method
19507 OO.ui.NumberInputWidget.parent.prototype.setDisabled.call( this, disabled );
19508
19509 if ( this.input ) {
19510 this.input.setDisabled( this.isDisabled() );
19511 }
19512 if ( this.minusButton ) {
19513 this.minusButton.setDisabled( this.isDisabled() );
19514 }
19515 if ( this.plusButton ) {
19516 this.plusButton.setDisabled( this.isDisabled() );
19517 }
19518
19519 return this;
19520 };
19521
19522 /**
19523 * ToggleSwitches are switches that slide on and off. Their state is represented by a Boolean
19524 * value (`true` for ‘on’, and `false` otherwise, the default). The ‘off’ state is represented
19525 * visually by a slider in the leftmost position.
19526 *
19527 * @example
19528 * // Toggle switches in the 'off' and 'on' position.
19529 * var toggleSwitch1 = new OO.ui.ToggleSwitchWidget();
19530 * var toggleSwitch2 = new OO.ui.ToggleSwitchWidget( {
19531 * value: true
19532 * } );
19533 *
19534 * // Create a FieldsetLayout to layout and label switches
19535 * var fieldset = new OO.ui.FieldsetLayout( {
19536 * label: 'Toggle switches'
19537 * } );
19538 * fieldset.addItems( [
19539 * new OO.ui.FieldLayout( toggleSwitch1, { label: 'Off', align: 'top' } ),
19540 * new OO.ui.FieldLayout( toggleSwitch2, { label: 'On', align: 'top' } )
19541 * ] );
19542 * $( 'body' ).append( fieldset.$element );
19543 *
19544 * @class
19545 * @extends OO.ui.ToggleWidget
19546 * @mixins OO.ui.mixin.TabIndexedElement
19547 *
19548 * @constructor
19549 * @param {Object} [config] Configuration options
19550 * @cfg {boolean} [value=false] The toggle switch’s initial on/off state.
19551 * By default, the toggle switch is in the 'off' position.
19552 */
19553 OO.ui.ToggleSwitchWidget = function OoUiToggleSwitchWidget( config ) {
19554 // Parent constructor
19555 OO.ui.ToggleSwitchWidget.parent.call( this, config );
19556
19557 // Mixin constructors
19558 OO.ui.mixin.TabIndexedElement.call( this, config );
19559
19560 // Properties
19561 this.dragging = false;
19562 this.dragStart = null;
19563 this.sliding = false;
19564 this.$glow = $( '<span>' );
19565 this.$grip = $( '<span>' );
19566
19567 // Events
19568 this.$element.on( {
19569 click: this.onClick.bind( this ),
19570 keypress: this.onKeyPress.bind( this )
19571 } );
19572
19573 // Initialization
19574 this.$glow.addClass( 'oo-ui-toggleSwitchWidget-glow' );
19575 this.$grip.addClass( 'oo-ui-toggleSwitchWidget-grip' );
19576 this.$element
19577 .addClass( 'oo-ui-toggleSwitchWidget' )
19578 .attr( 'role', 'checkbox' )
19579 .append( this.$glow, this.$grip );
19580 };
19581
19582 /* Setup */
19583
19584 OO.inheritClass( OO.ui.ToggleSwitchWidget, OO.ui.ToggleWidget );
19585 OO.mixinClass( OO.ui.ToggleSwitchWidget, OO.ui.mixin.TabIndexedElement );
19586
19587 /* Methods */
19588
19589 /**
19590 * Handle mouse click events.
19591 *
19592 * @private
19593 * @param {jQuery.Event} e Mouse click event
19594 */
19595 OO.ui.ToggleSwitchWidget.prototype.onClick = function ( e ) {
19596 if ( !this.isDisabled() && e.which === 1 ) {
19597 this.setValue( !this.value );
19598 }
19599 return false;
19600 };
19601
19602 /**
19603 * Handle key press events.
19604 *
19605 * @private
19606 * @param {jQuery.Event} e Key press event
19607 */
19608 OO.ui.ToggleSwitchWidget.prototype.onKeyPress = function ( e ) {
19609 if ( !this.isDisabled() && ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER ) ) {
19610 this.setValue( !this.value );
19611 return false;
19612 }
19613 };
19614
19615 /*!
19616 * Deprecated aliases for classes in the `OO.ui.mixin` namespace.
19617 */
19618
19619 /**
19620 * @inheritdoc OO.ui.mixin.ButtonElement
19621 * @deprecated Use {@link OO.ui.mixin.ButtonElement} instead.
19622 */
19623 OO.ui.ButtonElement = OO.ui.mixin.ButtonElement;
19624
19625 /**
19626 * @inheritdoc OO.ui.mixin.ClippableElement
19627 * @deprecated Use {@link OO.ui.mixin.ClippableElement} instead.
19628 */
19629 OO.ui.ClippableElement = OO.ui.mixin.ClippableElement;
19630
19631 /**
19632 * @inheritdoc OO.ui.mixin.DraggableElement
19633 * @deprecated Use {@link OO.ui.mixin.DraggableElement} instead.
19634 */
19635 OO.ui.DraggableElement = OO.ui.mixin.DraggableElement;
19636
19637 /**
19638 * @inheritdoc OO.ui.mixin.DraggableGroupElement
19639 * @deprecated Use {@link OO.ui.mixin.DraggableGroupElement} instead.
19640 */
19641 OO.ui.DraggableGroupElement = OO.ui.mixin.DraggableGroupElement;
19642
19643 /**
19644 * @inheritdoc OO.ui.mixin.FlaggedElement
19645 * @deprecated Use {@link OO.ui.mixin.FlaggedElement} instead.
19646 */
19647 OO.ui.FlaggedElement = OO.ui.mixin.FlaggedElement;
19648
19649 /**
19650 * @inheritdoc OO.ui.mixin.GroupElement
19651 * @deprecated Use {@link OO.ui.mixin.GroupElement} instead.
19652 */
19653 OO.ui.GroupElement = OO.ui.mixin.GroupElement;
19654
19655 /**
19656 * @inheritdoc OO.ui.mixin.GroupWidget
19657 * @deprecated Use {@link OO.ui.mixin.GroupWidget} instead.
19658 */
19659 OO.ui.GroupWidget = OO.ui.mixin.GroupWidget;
19660
19661 /**
19662 * @inheritdoc OO.ui.mixin.IconElement
19663 * @deprecated Use {@link OO.ui.mixin.IconElement} instead.
19664 */
19665 OO.ui.IconElement = OO.ui.mixin.IconElement;
19666
19667 /**
19668 * @inheritdoc OO.ui.mixin.IndicatorElement
19669 * @deprecated Use {@link OO.ui.mixin.IndicatorElement} instead.
19670 */
19671 OO.ui.IndicatorElement = OO.ui.mixin.IndicatorElement;
19672
19673 /**
19674 * @inheritdoc OO.ui.mixin.ItemWidget
19675 * @deprecated Use {@link OO.ui.mixin.ItemWidget} instead.
19676 */
19677 OO.ui.ItemWidget = OO.ui.mixin.ItemWidget;
19678
19679 /**
19680 * @inheritdoc OO.ui.mixin.LabelElement
19681 * @deprecated Use {@link OO.ui.mixin.LabelElement} instead.
19682 */
19683 OO.ui.LabelElement = OO.ui.mixin.LabelElement;
19684
19685 /**
19686 * @inheritdoc OO.ui.mixin.LookupElement
19687 * @deprecated Use {@link OO.ui.mixin.LookupElement} instead.
19688 */
19689 OO.ui.LookupElement = OO.ui.mixin.LookupElement;
19690
19691 /**
19692 * @inheritdoc OO.ui.mixin.PendingElement
19693 * @deprecated Use {@link OO.ui.mixin.PendingElement} instead.
19694 */
19695 OO.ui.PendingElement = OO.ui.mixin.PendingElement;
19696
19697 /**
19698 * @inheritdoc OO.ui.mixin.PopupElement
19699 * @deprecated Use {@link OO.ui.mixin.PopupElement} instead.
19700 */
19701 OO.ui.PopupElement = OO.ui.mixin.PopupElement;
19702
19703 /**
19704 * @inheritdoc OO.ui.mixin.TabIndexedElement
19705 * @deprecated Use {@link OO.ui.mixin.TabIndexedElement} instead.
19706 */
19707 OO.ui.TabIndexedElement = OO.ui.mixin.TabIndexedElement;
19708
19709 /**
19710 * @inheritdoc OO.ui.mixin.TitledElement
19711 * @deprecated Use {@link OO.ui.mixin.TitledElement} instead.
19712 */
19713 OO.ui.TitledElement = OO.ui.mixin.TitledElement;
19714
19715 }( OO ) );